: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): notify on video export completion and link kickoff toast (#72948)
Arno Hillenb4734de4ba3f
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/exports/SidePanelExports.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/exports/SidePanelExports.tsxindex f1e248deeefc..132688b6ecb7 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/exports/SidePanelExports.tsx+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/exports/SidePanelExports.tsx@@ -4,7 +4,7 @@ import { IconDownload, IconPencil, IconRefresh, IconWarning } from '@posthog/icoimport { LemonButton, LemonSelect, LemonSkeleton, Spinner, lemonToast } from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'-import { downloadExportedAsset, exportedAssetBlob } from 'lib/components/ExportButton/exporter'+import { exportedAssetBlob } from 'lib/components/ExportButton/exporter'import { getExportDisabledReason, getExportPendingLabel } from 'lib/components/ExportButton/exportStatus'import { ScreenShotEditor } from 'lib/components/TakeScreenshot/ScreenShotEditor'import { takeScreenshotLogic } from 'lib/components/TakeScreenshot/takeScreenshotLogic'@@ -66,7 +66,7 @@ function ExportPanelHeader(): JSX.Element {function ExportRow({ asset }: { asset: ExportedAssetType }): JSX.Element {const { freshUndownloadedExports } = useValues(sidePanelExportsLogic)- const { removeFresh } = useActions(sidePanelExportsLogic)+ const { downloadExport } = useActions(sidePanelExportsLogic)const { setBlob } = useActions(takeScreenshotLogic({ screenshotKey: 'exports' }))const handleEdit = async (asset: ExportedAssetType): Promise<void> => {@@ -144,10 +144,7 @@ function ExportRow({ asset }: { asset: ExportedAssetType }): JSX.Element {key={asset.id}data-attr="export-download"disabledReason={disabledReason}- onClick={() => {- removeFresh(asset)- void downloadExportedAsset(asset)- }}+ onClick={() => downloadExport(asset)}sideIcon={stillCalculating ? (<Spinner />diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/exports/sidePanelExportsLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/exports/sidePanelExportsLogic.tsindex 0f569ceb4fa1..b219d28e6b34 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/exports/sidePanelExportsLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/exports/sidePanelExportsLogic.ts@@ -15,6 +15,9 @@ export interface sidePanelExportsLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface sidePanelExportsLogicActions {+ downloadExport: (exportedAsset: ExportedAssetType) => {+ exportedAsset: ExportedAssetType+ } // exportsLogicloadExports: () => {value: true} // exportsLogic@@ -43,7 +46,7 @@ export const sidePanelExportsLogic = kea<sidePanelExportsLogicType>([sidePanelStateLogic,['openSidePanel'],exportsLogic,- ['loadExports', 'removeFresh', 'setAssetFormat'],+ ['loadExports', 'removeFresh', 'downloadExport', 'setAssetFormat'],],})),afterMount(({ actions }) => {diff --git a/frontend/src/lib/components/ExportButton/exportsLogic.test.ts b/frontend/src/lib/components/ExportButton/exportsLogic.test.tsindex 8d6e3f27a758..1ae9e9b2c6fb 100644--- a/frontend/src/lib/components/ExportButton/exportsLogic.test.ts+++ b/frontend/src/lib/components/ExportButton/exportsLogic.test.ts@@ -1,8 +1,9 @@import api from 'lib/api'import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { initKeaTests } from '~/test/init'-import { ExportedAssetType, ExporterFormat } from '~/types'+import { ExportedAssetType, ExporterFormat, SidePanelTab } from '~/types'import { downloadExportedAsset } from './exporter'import { exportsLogic, pickPollDelayMs } from './exportsLogic'@@ -118,6 +119,8 @@ describe('exportsLogic', () => {settles: { resolved: string } | { rejected: string }expectsDownload: booleanfreshIds: number[]+ expectsViewExportsButton: boolean+ expectsPanelOpen: boolean}[] = [{label: 'async export resolves to "Export started" and is tracked as undownloaded',@@ -126,6 +129,8 @@ describe('exportsLogic', () => {settles: { resolved: 'Export started' },expectsDownload: false,freshIds: [11],+ expectsViewExportsButton: true,+ expectsPanelOpen: true,},{label: 'blocking export with content is downloaded and resolves to "Export complete!"',@@ -134,6 +139,8 @@ describe('exportsLogic', () => {settles: { resolved: 'Export complete!' },expectsDownload: true,freshIds: [],+ expectsViewExportsButton: false,+ expectsPanelOpen: false,},{label: 'export that failed in the request rejects with the error',@@ -142,6 +149,8 @@ describe('exportsLogic', () => {settles: { rejected: 'Export failed: boom' },expectsDownload: false,freshIds: [],+ expectsViewExportsButton: true,+ expectsPanelOpen: false,},{label: 'create request that throws rejects with the error',@@ -150,35 +159,57 @@ describe('exportsLogic', () => {settles: { rejected: 'Export failed: network down' },expectsDownload: false,freshIds: [],+ expectsViewExportsButton: true,+ expectsPanelOpen: false,},]- it.each(createCases)('$label', async ({ response, rejectWith, format, settles, expectsDownload, freshIds }) => {- const createSpy = jest.spyOn(api.exports, 'create')- if (rejectWith) {- createSpy.mockRejectedValue(rejectWith)- } else {- createSpy.mockResolvedValue(response!)- }+ it.each(createCases)(+ '$label',+ async ({+ response,+ rejectWith,+ format,+ settles,+ expectsDownload,+ freshIds,+ expectsViewExportsButton,+ expectsPanelOpen,+ }) => {+ const createSpy = jest.spyOn(api.exports, 'create')+ if (rejectWith) {+ createSpy.mockRejectedValue(rejectWith)+ } else {+ createSpy.mockResolvedValue(response!)+ }- logic.actions.createExport({ exportData: { export_format: format } })- await flush()+ logic.actions.createExport({ exportData: { export_format: format } })+ await flush()- // 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)+ // 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) })+ )+ // Video renders finish out of band, so their kickoff toast must link to the exports panel.+ const toastOptions = jest.mocked(lemonToast.promise).mock.calls[0][2]+ expect(toastOptions?.button?.label).toEqual(expectsViewExportsButton ? 'View exports' : undefined)+ 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)+ // selectedTab is persisted across kea contexts, so assert the open+tab combination.+ expect(+ sidePanelStateLogic.values.sidePanelOpen &&+ sidePanelStateLogic.values.selectedTab === SidePanelTab.Exports+ ).toBe(expectsPanelOpen)}- expect(jest.mocked(downloadExportedAsset).mock.calls).toEqual(expectsDownload ? [[response]] : [])- expect(logic.values.freshUndownloadedExports.map((a) => a.id)).toEqual(freshIds)- })+ )it('does not confirm completion when the content download fails', async () => {// The export toast must not settle as "Export complete!" if retrieval failed — otherwise@@ -199,6 +230,91 @@ describe('exportsLogic', () => {expect(lemonToast.dismiss).toHaveBeenCalled()})+ it('notifies once with a Download button that routes through downloadExport', async () => {+ const pending = asset({ id: 21, export_format: ExporterFormat.MP4, has_content: false })+ const finished = asset({ id: 21, export_format: ExporterFormat.MP4, has_content: true })+ // An unrelated completed export in the list must not trigger a toast of its own.+ const unrelated = asset({ id: 99, export_format: ExporterFormat.CSV, has_content: true })+ const downloadExportSpy = jest.spyOn(logic.actions, 'downloadExport')++ logic.actions.addFresh(pending)+ logic.actions.loadExportsSuccess([finished, unrelated])+ await flush()+ // A second poll of the same finished export must not re-toast it.+ logic.actions.loadExportsSuccess([finished, unrelated])+ await flush()++ expect(jest.mocked(lemonToast.success).mock.calls).toEqual([+ [+ 'Export complete!',+ expect.objectContaining({ button: expect.objectContaining({ label: 'Download' }) }),+ ],+ ])+ // The export keeps its "not downloaded" highlight until the user actually downloads it.+ expect(logic.values.freshUndownloadedExports.map((a) => a.id)).toEqual([21])++ jest.mocked(lemonToast.success).mock.calls[0][1]!.button!.action()+ expect(downloadExportSpy).toHaveBeenCalledWith(finished)+ })++ it.each([+ {+ label: 'clears the highlight when the download succeeds',+ downloadOk: true,+ remainingIds: [] as number[],+ },+ { label: 'keeps the highlight when the download fails', downloadOk: false, remainingIds: [41] },+ ])('downloadExport $label', async ({ downloadOk, remainingIds }) => {+ 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)+ })++ it('surfaces the failure and stops tracking when a tracked async export fails', async () => {+ const pending = asset({ id: 22, export_format: ExporterFormat.MP4, has_content: false })+ const failed = asset({ id: 22, export_format: ExporterFormat.MP4, exception: 'render crashed' })++ logic.actions.addFresh(pending)+ logic.actions.loadExportsSuccess([failed])+ await flush()++ expect(lemonToast.error).toHaveBeenCalledWith('Export failed: render crashed')+ expect(logic.values.freshUndownloadedExports).toEqual([])+ })++ it('keeps polling a tracked export when its individual fetch fails', async () => {+ // A tracked export can be missing from a format-filtered list, so it is fetched directly.+ // A transient fetch failure must not stop the poll loop and orphan the export.+ jest.useFakeTimers()+ try {+ const pending = asset({ id: 31, export_format: ExporterFormat.MP4, has_content: false })+ // The list omits id 31 and its only entry is already complete, so a re-poll can+ // only come from the failed export being kept in the pending set.+ const unrelatedDone = asset({ id: 88, export_format: ExporterFormat.CSV, has_content: true })+ jest.spyOn(api.exports, 'get').mockRejectedValue(new Error('transient'))+ const loadExportsSpy = jest.spyOn(logic.actions, 'loadExports')++ logic.actions.addFresh(pending)+ logic.actions.loadExportsSuccess([unrelatedDone])+ await jest.advanceTimersByTimeAsync(30000)++ expect(api.exports.get).toHaveBeenCalledWith(31)+ expect(loadExportsSpy).toHaveBeenCalled()+ // The export is neither dropped nor prematurely notified as complete/failed.+ expect(logic.values.freshUndownloadedExports.map((a) => a.id)).toContain(31)+ expect(lemonToast.success).not.toHaveBeenCalled()+ expect(lemonToast.error).not.toHaveBeenCalled()+ } finally {+ jest.useRealTimers()+ }+ })+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' },diff --git a/frontend/src/lib/components/ExportButton/exportsLogic.ts b/frontend/src/lib/components/ExportButton/exportsLogic.tsindex 1c970216a0fa..add95c9ee2d9 100644--- a/frontend/src/lib/components/ExportButton/exportsLogic.ts+++ b/frontend/src/lib/components/ExportButton/exportsLogic.ts@@ -1,20 +1,28 @@-import { MakeLogicType, actions, kea, listeners, path, reducers } from 'kea'+import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'import { loaders } from 'kea-loaders'import { router } from 'kea-router'import api from 'lib/api'import { TriggerExportProps, downloadBlob, downloadExportedAsset } from 'lib/components/ExportButton/exporter'import { isLongRunningExportFormat } from 'lib/components/ExportButton/exportStatus'-import { dayjs } from 'lib/dayjs'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { delay } from 'lib/utils/async'import { uuid } from 'lib/utils/dom'import type { SessionRecordingPlayerMode } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'import { urls } from 'scenes/urls'+import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { cohortsModel } from '~/models/cohortsModel'import { AnyDataNode } from '~/queries/schema/schema-general'-import { APIErrorType, CohortType, ExportContext, ExportedAssetType, ExporterFormat, LocalExportContext } from '~/types'+import {+ APIErrorType,+ CohortType,+ ExportContext,+ ExportedAssetType,+ ExporterFormat,+ LocalExportContext,+ 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.@@ -26,8 +34,19 @@ const POLL_DELAY_MS = 10000// pending queue is dominated by long-running formats.const LONG_RUNNING_POLL_DELAY_MS = 30000+// An export is still rendering while it has neither produced content nor failed.+const isRendering = (asset: ExportedAssetType): boolean => !asset.has_content && !asset.exception++const fetchExportOrNull = async (id: number): Promise<ExportedAssetType | null> => {+ try {+ return await api.exports.get(id)+ } catch {+ return null+ }+}+export const pickPollDelayMs = (pendingAssets: ExportedAssetType[]): number => {- const pending = pendingAssets.filter((asset) => !asset.has_content && !asset.exception)+ const pending = pendingAssets.filter(isRendering)if (pending.length === 0) {return POLL_DELAY_MS}@@ -52,12 +71,16 @@ export interface exportsLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface exportsLogicActions {+ openSidePanel: (+ tab: SidePanelTab,+ options?: string | undefined+ ) => {+ options: string | undefined+ tab: SidePanelTab+ } // sidePanelStateLogicaddFresh: (exportedAsset: ExportedAssetType) => {exportedAsset: ExportedAssetType}- checkExportStatus: (exportedAsset: ExportedAssetType) => {- exportedAsset: ExportedAssetType- }createExport: ({ exportData }: any) => anycreateExportFailure: (error: string,@@ -80,6 +103,9 @@ export interface exportsLogicActions {name: stringquery: AnyDataNode}+ downloadExport: (exportedAsset: ExportedAssetType) => {+ exportedAsset: ExportedAssetType+ }loadExports: () => {value: true}@@ -101,9 +127,6 @@ export interface exportsLogicActions {value: true}}- pollExportStatus: (exportedAsset: ExportedAssetType) => {- exportedAsset: ExportedAssetType- }removeFresh: (exportedAsset: ExportedAssetType) => {exportedAsset: ExportedAssetType}@@ -154,14 +177,16 @@ export type exportsLogicType = MakeLogicType<exportsLogicValues, exportsLogicActexport const exportsLogic = kea<exportsLogicType>([path(['scenes', 'navigation', 'sidepanel', 'exportsLogic']),+ connect(() => ({+ actions: [sidePanelStateLogic, ['openSidePanel']],+ })),actions({loadExports: true,startExport: (exportData: TriggerExportProps) => ({ exportData }),- checkExportStatus: (exportedAsset: ExportedAssetType) => ({ exportedAsset }),- pollExportStatus: (exportedAsset: ExportedAssetType) => ({ exportedAsset }),addFresh: (exportedAsset: ExportedAssetType) => ({ exportedAsset }),removeFresh: (exportedAsset: ExportedAssetType) => ({ exportedAsset }),+ downloadExport: (exportedAsset: ExportedAssetType) => ({ exportedAsset }),createStaticCohort: (name: string, query: AnyDataNode) => ({ query, name }),setAssetFormat: (format: ExporterFormat | null) => ({ format }),setHasReachedExportFullVideoLimit: (hasReached: boolean) => ({ hasReached }),@@ -211,7 +236,7 @@ export const exportsLogic = kea<exportsLogicType>([],}),- listeners(({ actions }) => ({+ listeners(({ actions, values, cache }) => ({startExport: async ({ exportData }) => {if (isLocalExport(exportData.export_context)) {try {@@ -231,10 +256,46 @@ export const exportsLogic = kea<exportsLogicType>([createExportSuccess: () => {actions.loadExports()},+ downloadExport: async ({ exportedAsset }) => {+ // 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)) {+ actions.removeFresh(exportedAsset)+ }+ },loadExportsSuccess: async ({ exports: exportsList }, breakpoint) => {- // Keep the list fresh while any export is still rendering, so the panel reflects completion.- if (exportsList.some((asset) => !asset.has_content && !asset.exception)) {- await breakpoint(pickPollDelayMs(exportsList))+ // Surface async exports we kicked off that have now finished: the render completes long+ // after the kickoff toast, so this poll is the only completion signal the user gets.+ cache.notifiedExportIds ??= new Set<number>()+ const pending = exportsList.filter(isRendering)+ for (const fresh of values.freshUndownloadedExports) {+ // The list can be format-filtered (assetFormat), so fetch directly if it's not in it.+ const listed = exportsList.find((asset) => asset.id === fresh.id)+ const latest = listed ?? (await fetchExportOrNull(fresh.id))+ if (!latest || isRendering(latest)) {+ // Still rendering, or a transient fetch miss: keep an out-of-list export polling.+ if (!listed) {+ pending.push(latest ?? fresh)+ }+ continue+ }+ if (cache.notifiedExportIds.has(fresh.id)) {+ continue+ }+ if (latest.has_content) {+ cache.notifiedExportIds.add(fresh.id)+ const finished = latest+ lemonToast.success('Export complete!', {+ button: { label: 'Download', action: () => actions.downloadExport(finished) },+ })+ } else {+ actions.removeFresh(fresh)+ lemonToast.error('Export failed: ' + latest.exception)+ }+ }++ if (pending.length) {+ await breakpoint(pickPollDelayMs(pending))actions.loadExports()}},@@ -334,7 +395,6 @@ export const exportsLogic = kea<exportsLogicType>([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;@@ -363,8 +423,9 @@ export const exportsLogic = kea<exportsLogicType>([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.+ // kickoff and open the exports panel, where it lands once the render finishes.actions.addFresh(response)+ actions.openSidePanel(SidePanelTab.Exports)return 'Export started'}@@ -378,7 +439,19 @@ export const exportsLogic = kea<exportsLogicType>([success: 'Export complete!',error: 'Export failed',},- { toastId: exportToastId }+ {+ toastId: exportToastId,+ // Video renders finish minutes later in the exports panel, so the+ // kickoff toast must point somewhere instead of dead-ending.+ ...(isLongRunningExportFormat(exportData.export_format)+ ? {+ button: {+ label: 'View exports',+ action: () => actions.openSidePanel(SidePanelTab.Exports),+ },+ }+ : {}),+ })} catch (error) {const apiError = error as { data?: APIErrorType }diff --git a/frontend/src/scenes/exports/ExportsScene.tsx b/frontend/src/scenes/exports/ExportsScene.tsxindex 4c6d3d9d9ab8..637b6c7e98a3 100644--- a/frontend/src/scenes/exports/ExportsScene.tsx+++ b/frontend/src/scenes/exports/ExportsScene.tsx@@ -5,7 +5,7 @@ import { LemonButton, LemonSelect, LemonTable, LemonTag, Spinner, lemonToast } fimport { LemonTableColumns } from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'-import { downloadExportedAsset, exportedAssetBlob } from 'lib/components/ExportButton/exporter'+import { exportedAssetBlob } from 'lib/components/ExportButton/exporter'import { exportsLogic } from 'lib/components/ExportButton/exportsLogic'import { getExportDisabledReason, getExportPendingLabel } from 'lib/components/ExportButton/exportStatus'import { takeScreenshotLogic } from 'lib/components/TakeScreenshot/takeScreenshotLogic'@@ -29,7 +29,7 @@ export const scene: SceneExport = {function ExportActions({ asset }: { asset: ExportedAssetType }): JSX.Element {const { freshUndownloadedExports } = useValues(exportsLogic)- const { removeFresh } = useActions(exportsLogic)+ const { downloadExport } = useActions(exportsLogic)const { setBlob } = useActions(takeScreenshotLogic({ screenshotKey: 'exports' }))const isNotDownloaded = freshUndownloadedExports.some((fresh) => fresh.id === asset.id)@@ -83,10 +83,7 @@ function ExportActions({ asset }: { asset: ExportedAssetType }): JSX.Element {type={isNotDownloaded ? 'primary' : 'secondary'}data-attr="export-download"disabledReason={disabledReason}- onClick={() => {- removeFresh(asset)- void downloadExportedAsset(asset)- }}+ onClick={() => downloadExport(asset)}sideIcon={stillCalculating ? (<Spinner />