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(dashboards): recover the dashboard after a lost connection (#107836)

posthog[bot]60a9ccc47159
diff --git a/frontend/src/lib/api.test.ts b/frontend/src/lib/api.test.ts
index b9239b45d6e2..89a272abba3d 100644
--- a/frontend/src/lib/api.test.ts
+++ b/frontend/src/lib/api.test.ts
@@ -145,7 +145,7 @@ describe('API helper', () => {
const connectionError = new TypeError('Failed to fetch')
streamOptions.onerror?.(connectionError)
expect(onApiResponse).toHaveBeenCalledWith(undefined, connectionError)
- expect(onError).toHaveBeenCalledWith(connectionError)
+ expect(onError).toHaveBeenCalledWith(connectionError, true)
const abortError = new DOMException('The operation was aborted', 'AbortError')
streamOptions.onerror?.(abortError)
@@ -156,6 +156,19 @@ describe('API helper', () => {
apiStatusLogicSpy.mockRestore()
})
+ it('ends a stream with an unreadable message so a new load can recover', async () => {
+ const fetchEventSourceSpy = jest
+ .spyOn(fetchEventSourceModule, 'fetchEventSource')
+ .mockReturnValueOnce(new Promise<void>(() => {}))
+ const onError = jest.fn()
+ await api.dashboards.streamTiles(5, {}, jest.fn(), jest.fn(), onError)
+ const options = fetchEventSourceSpy.mock.calls[0][1]
+ options.onmessage?.({ data: 'invalid json', event: '', id: '' })
+ expect(onError).toHaveBeenCalledWith(expect.any(SyntaxError))
+ expect(options.signal?.aborted).toBe(true)
+ fetchEventSourceSpy.mockRestore()
+ })
+
it('reports a stream that closes before completion', async () => {
const fetchEventSourceSpy = jest.spyOn(fetchEventSourceModule, 'fetchEventSource').mockResolvedValueOnce()
const onError = jest.fn()
@@ -166,7 +179,8 @@ describe('API helper', () => {
expect(onError).toHaveBeenCalledWith(
expect.objectContaining({
message: 'Dashboard stream ended before loading finished. Refresh the page.',
- })
+ }),
+ false
)
fetchEventSourceSpy.mockRestore()
})
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 08891c82f200..c07739ba404f 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -3431,7 +3431,7 @@ const api = {
} = {},
onMessage: (data: any) => void,
onComplete: () => void,
- onError: (error: any) => void
+ onError: (error: any, willRetry?: boolean) => void
): Promise<() => void> {
const url = new ApiRequest()
.dashboardsDetail(id)
@@ -3447,12 +3447,12 @@ const api = {
const abortController = new AbortController()
let streamFinished = false
- const handleConnectionError = (error: any): void => {
- if (isAbortError(error)) {
+ const handleConnectionError = (error: any, willRetry = false): void => {
+ if (abortController.signal.aborted || isAbortError(error)) {
return
}
apiStatusLogic.findMounted()?.actions.onApiResponse(undefined, error)
- onError(error)
+ onError(error, willRetry)
}
fetchEventSource(url, {
@@ -3477,16 +3477,18 @@ const api = {
onComplete()
} else if (data.type === 'error') {
streamFinished = true
+ abortController.abort()
onError(new Error(data.error || 'Streaming error'))
} else {
onMessage(data)
}
} catch (error) {
+ abortController.abort()
onError(error)
}
},
onerror: (error) => {
- handleConnectionError(error)
+ handleConnectionError(error, true)
},
}).then(() => {
if (!abortController.signal.aborted && !streamFinished) {
diff --git a/frontend/src/scenes/dashboard/Dashboard.tsx b/frontend/src/scenes/dashboard/Dashboard.tsx
index cb1b2eb09730..572251bbc1a9 100644
--- a/frontend/src/scenes/dashboard/Dashboard.tsx
+++ b/frontend/src/scenes/dashboard/Dashboard.tsx
@@ -10,12 +10,13 @@ import { NotFound } from 'lib/components/NotFound'
import { ScreenShotEditor } from 'lib/components/TakeScreenshot/ScreenShotEditor'
import { useFileSystemLogView } from 'lib/hooks/useFileSystemLogView'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { Link } from 'lib/lemon-ui/Link'
import { cn } from 'lib/utils/css-classes'
import { lazyWithRetry } from 'lib/utils/retryImport'
import { DashboardFilterBar } from 'scenes/dashboard/DashboardFilters'
import { DashboardItems } from 'scenes/dashboard/DashboardItems'
-import { DashboardLoadAction, DashboardLogicProps, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
+import { DashboardLogicProps, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { dataThemeLogic } from 'scenes/dataThemeLogic'
import { InsightErrorState } from 'scenes/insights/EmptyStates'
import { SceneExport } from 'scenes/sceneTypes'
@@ -115,15 +116,18 @@ function DashboardScene({
tiles,
itemsLoading,
dashboardLoading,
+ dashboardStreaming,
layoutEditMode,
dashboardFailedToLoad,
+ internetConnectionIssue,
accessDeniedToDashboard,
error404,
hasInvalidDashboardId,
} = useValues(dashboardLogic)
const { layoutZoom } = useValues(dashboardLogic)
const { currentTeamId } = useValues(teamLogic)
- const { reportDashboardViewed, abortAnyRunningQuery, loadDashboard, setLayoutZoom } = useActions(dashboardLogic)
+ const { reportDashboardViewed, abortAnyRunningQuery, retryDashboardLoad, setLayoutZoom } =
+ useActions(dashboardLogic)
const { addInsightToDashboardModalVisible } = useValues(addInsightToDashboardLogic)
const { hideAddInsightToDashboardModal } = useActions(addInsightToDashboardLogic)
const closeAddInsightToDashboardModal = (): void => {
@@ -198,15 +202,15 @@ function DashboardScene({
)}
<DashboardEmbeddedShareButton dashboard={dashboard} placement={placement} />
- {dashboardFailedToLoad ? (
+ {dashboardFailedToLoad && !tiles?.length ? (
<InsightErrorState
- title="There was an error loading this dashboard"
- onRetry={
- placement === DashboardPlacement.Export
- ? undefined
- : () => loadDashboard({ action: DashboardLoadAction.Update })
+ title={
+ internetConnectionIssue
+ ? "We couldn't connect to PostHog. Check your connection and try again."
+ : 'There was an error loading this dashboard'
}
- retryLoading={dashboardLoading}
+ onRetry={placement === DashboardPlacement.Export ? undefined : retryDashboardLoad}
+ retryLoading={dashboardLoading || dashboardStreaming}
placement={placement}
/>
) : !tiles || tiles.length === 0 ? (
@@ -217,6 +221,24 @@ function DashboardScene({
'-mt-4': placement == DashboardPlacement.ProjectHomepage,
})}
>
+ {dashboardFailedToLoad && (
+ <LemonBanner
+ type="warning"
+ className="mb-4"
+ action={
+ placement === DashboardPlacement.Export
+ ? undefined
+ : {
+ children: 'Try again',
+ onClick: retryDashboardLoad,
+ loading: dashboardLoading || dashboardStreaming,
+ 'data-attr': 'dashboard-load-retry',
+ }
+ }
+ >
+ This dashboard couldn't finish loading.
+ </LemonBanner>
+ )}
<DashboardRetentionBanner />
<DashboardQueryScanBanner />
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
index ad3594df38eb..1ac0c159a8a4 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
@@ -13,6 +13,7 @@ import api from 'lib/api'
import { ApiError } from 'lib/api-error'
import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs, now } from 'lib/dayjs'
+import { apiStatusLogic } from 'lib/logic/apiStatusLogic'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { DashboardEventSource, eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { addInsightToDashboardLogic } from 'scenes/dashboard/addInsightToDashboardModalLogic'
@@ -2309,6 +2310,62 @@ describe('dashboardLogic', () => {
})
})
+ it.each([
+ {
+ trigger: 'a request succeeds again',
+ recover: () => apiStatusLogic.actions.setInternetConnectionIssue(false),
+ },
+ {
+ trigger: 'the browser goes back online',
+ recover: () => window.dispatchEvent(new Event('online')),
+ },
+ ])('keeps the error state during a retry and retries when $trigger', async ({ recover }) => {
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.dashboardFailedToLoad).toBe(true)
+
+ await expectLogic(logic, recover)
+ .toDispatchActions(['retryDashboardLoad', 'loadDashboard'])
+ .toMatchValues({ dashboardFailedToLoad: true, dashboardLoading: true })
+ .toDispatchActions(['loadDashboardFailure'])
+ .toMatchValues({ dashboardFailedToLoad: true, dashboardLoading: false })
+
+ await expectLogic(logic, () => {
+ apiStatusLogic.actions.setInternetConnectionIssue(true)
+ }).toNotHaveDispatchedActions(['retryDashboardLoad'])
+ })
+
+ it.each(
+ ['request', 'online'].flatMap((trigger) => [true, false].map((initialLoad) => ({ trigger, initialLoad })))
+ )(
+ 'retries once when $trigger signals recovery during a failed load (initial=$initialLoad)',
+ async ({ trigger, initialLoad }) => {
+ if (!initialLoad) {
+ await expectLogic(logic).toFinishAllListeners()
+ }
+ apiStatusLogic.actions.setInternetConnectionIssue(true)
+
+ await expectLogic(logic, () => {
+ if (!initialLoad) {
+ logic.actions.loadDashboard({ action: DashboardLoadAction.Update })
+ }
+ if (trigger === 'online') {
+ window.dispatchEvent(new Event('online'))
+ apiStatusLogic.actions.setInternetConnectionIssue(true)
+ } else {
+ apiStatusLogic.actions.setInternetConnectionIssue(false)
+ }
+ })
+ .toDispatchActions([
+ 'loadDashboardFailure',
+ 'retryDashboardLoad',
+ 'loadDashboard',
+ 'loadDashboardFailure',
+ ])
+ .toFinishAllListeners()
+ .toNotHaveDispatchedActions(['retryDashboardLoad'])
+ }
+ )
+
it.each([
{ id: 14, accessDenied: false },
{ id: 15, accessDenied: true },
@@ -2405,7 +2462,7 @@ describe('dashboardLogic', () => {
await expectLogic(logic).toFinishAllListeners()
await expectLogic(logic, () => {
- logic.actions.tileStreamingFailure({ message: 'Query failed with code 404 upstream' })
+ logic.actions.tileStreamingFailure({ message: 'Query failed with code 404 upstream' }, true)
}).toFinishAllListeners()
expect(logic.values.error404).toBe(false)
expect(logic.values.dashboardFailedToLoad).toBe(false)
@@ -2549,6 +2606,111 @@ describe('dashboardLogic', () => {
expect(logic.values.dashboardFailedToLoad).toBe(false)
expect(logic.values.dashboard).not.toBeNull()
})
+
+ it.each(['request', 'online'].flatMap((trigger) => [false, true].map((metadata) => ({ trigger, metadata }))))(
+ 'keeps an auto-retrying stream on $trigger recovery but replaces an ended one (metadata=$metadata)',
+ async ({ trigger, metadata }) => {
+ const globals = globalThis as { EventSource?: unknown }
+ const originalEventSource = globals.EventSource
+ globals.EventSource = class {}
+ try {
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.dashboardNotFound()
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.SSE_DASHBOARDS], {
+ [FEATURE_FLAGS.SSE_DASHBOARDS]: true,
+ })
+ const disposeStream = jest.fn()
+ const streamTilesSpy = jest.spyOn(api.dashboards, 'streamTiles').mockResolvedValue(disposeStream)
+ await expectLogic(logic, () => {
+ logic.actions.loadDashboardStreaming({ action: DashboardLoadAction.InitialLoad })
+ }).toFinishAllListeners()
+ const recover = (): void => {
+ if (trigger === 'online') {
+ window.dispatchEvent(new Event('online'))
+ } else {
+ apiStatusLogic.actions.setInternetConnectionIssue(false)
+ }
+ }
+ if (metadata) {
+ streamTilesSpy.mock.calls[0][2]({ type: 'metadata', dashboard: dashboardResult(5, []) })
+ streamTilesSpy.mock.calls[0][2]({ type: 'tile', tile: TEXT_TILE })
+ streamTilesSpy.mock.calls[0][2]({ type: 'tile', tile: { ...TEXT_TILE, id: 99 } })
+ }
+ const onError = streamTilesSpy.mock.calls[0][4]
+ await expectLogic(logic, () =>
+ onError(new TypeError('Failed to fetch'), true)
+ ).toFinishAllListeners()
+ expect(logic.values.dashboardFailedToLoad).toBe(!metadata)
+
+ await expectLogic(logic, recover).toFinishAllListeners()
+ expect(streamTilesSpy).toHaveBeenCalledTimes(1)
+ expect(disposeStream).not.toHaveBeenCalled()
+
+ await expectLogic(logic, () =>
+ onError(new SyntaxError('Unreadable dashboard message'))
+ ).toFinishAllListeners()
+ expect(logic.values.dashboardFailedToLoad).toBe(true)
+ await expectLogic(logic, recover).toFinishAllListeners()
+ expect(streamTilesSpy).toHaveBeenCalledTimes(2)
+ expect(disposeStream).toHaveBeenCalledTimes(1)
+ if (metadata) {
+ expect(logic.values.tiles?.map((tile) => tile.id)).toEqual([TEXT_TILE.id, 99])
+ }
+
+ await expectLogic(logic, () => {
+ streamTilesSpy.mock.calls[1][2]({ type: 'metadata', dashboard: dashboardResult(5, []) })
+ streamTilesSpy.mock.calls[1][2]({ type: 'tile', tile: TEXT_TILE })
+ }).toFinishAllListeners()
+ if (metadata) {
+ expect(logic.values.tiles?.map((tile) => tile.id)).toEqual([TEXT_TILE.id, 99])
+ expect(logic.values.dashboardFailedToLoad).toBe(true)
+ }
+
+ await expectLogic(logic, () => {
+ streamTilesSpy.mock.calls[1][2]({ type: 'tile', tile: { ...TEXT_TILE, id: 6 } })
+ streamTilesSpy.mock.calls[1][3]()
+ }).toFinishAllListeners()
+ expect(logic.values.dashboard?.id).toBe(5)
+ expect(logic.values.tiles?.map((tile) => tile.id)).toEqual([TEXT_TILE.id, 6])
+ expect(logic.values.dashboardFailedToLoad).toBe(false)
+ } finally {
+ globals.EventSource = originalEventSource
+ }
+ }
+ )
+
+ it('keeps the stream that recovered while a connection retry waited', async () => {
+ const globals = globalThis as { EventSource?: unknown }
+ const originalEventSource = globals.EventSource
+ globals.EventSource = class {}
+ try {
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.dashboardNotFound()
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.SSE_DASHBOARDS], {
+ [FEATURE_FLAGS.SSE_DASHBOARDS]: true,
+ })
+ logic.actions.tileStreamingFailure({ message: 'network dropped mid-connect' })
+ expect(logic.values.dashboardFailedToLoad).toBe(true)
+ const streamTilesSpy = jest.spyOn(api.dashboards, 'streamTiles').mockResolvedValue(jest.fn())
+
+ await expectLogic(logic, () => {
+ apiStatusLogic.actions.setInternetConnectionIssue(false)
+ logic.actions.loadDashboardMetadataSuccess(dashboardResult(5, []))
+ })
+ .toDispatchActions([
+ 'retryDashboardLoad',
+ 'loadDashboardStreaming',
+ 'loadDashboardStreamingSuccess',
+ ])
+ .toFinishAllListeners()
+
+ expect(streamTilesSpy).not.toHaveBeenCalled()
+ expect(logic.values.dashboard).not.toBeNull()
+ expect(logic.values.dashboardFailedToLoad).toBe(false)
+ } finally {
+ globals.EventSource = originalEventSource
+ }
+ })
})
describe('when a dashboard item API errors', () => {
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsx
index d31a2cb604df..001c1914d2b6 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx
+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx
@@ -41,6 +41,7 @@ import { OrganizationMembershipLevel } from 'lib/constants'
import { FEATURE_FLAGS } from 'lib/constants'
import { Dayjs, dayjs, now } from 'lib/dayjs'
import { Link } from 'lib/lemon-ui/Link'
+import { apiStatusLogic } from 'lib/logic/apiStatusLogic'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'
import { deleteInsightWithUndo } from 'lib/utils/deleteWithUndo'
@@ -295,6 +296,7 @@ function mergeUpdatedWidgetTileIntoDashboard(
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardLogicValues {
+ internetConnectionIssue: boolean // apiStatusLogic
retentionMonths: number | null // dataRetentionBannerLogic
retentionPeriodLabel: string | null // dataRetentionBannerLogic
warningEligible: boolean // dataRetentionBannerLogic
@@ -591,9 +593,14 @@ export interface dashboardLogicActions {
loadDashboardMetadataSuccess: (dashboard: DashboardType | null) => {
dashboard: DashboardType | null
}
- loadDashboardStreaming: (payload: { action: DashboardLoadAction; manualDashboardRefresh?: boolean }) => {
+ loadDashboardStreaming: (payload: {
+ action: DashboardLoadAction
+ manualDashboardRefresh?: boolean
+ retry?: boolean
+ }) => {
action: DashboardLoadAction
manualDashboardRefresh?: boolean | undefined
+ retry?: boolean | undefined
}
loadDashboardStreamingFailure: (
error: string,
@@ -603,16 +610,18 @@ export interface dashboardLogicActions {
errorObject?: any
}
loadDashboardStreamingSuccess: (
- dashboard: null,
+ dashboard: DashboardType | null,
payload?: {
action: DashboardLoadAction
manualDashboardRefresh?: boolean | undefined
+ retry?: boolean | undefined
}
) => {
- dashboard: null
+ dashboard: DashboardType | null
payload?: {
action: DashboardLoadAction
manualDashboardRefresh?: boolean | undefined
+ retry?: boolean | undefined
}
}
loadDashboardSuccess: (
@@ -775,6 +784,9 @@ export interface dashboardLogicActions {
themeId: number | null
} | null
}
+ retryDashboardLoad: () => {
+ value: true
+ }
saveDashboardChanges: () => {
value: true
}
@@ -1018,8 +1030,12 @@ export interface dashboardLogicActions {
tileStreamingComplete: () => {
value: true
}
- tileStreamingFailure: (error: any) => {
+ tileStreamingFailure: (
+ error: any,
+ willRetry?: boolean
+ ) => {
error: any
+ willRetry: boolean
}
toggleAddWidgetCollapsedGroup: (groupId: string) => {
groupId: string
@@ -1390,6 +1406,8 @@ export const dashboardLogic = kea<dashboardLogicType>([
['getTheme'],
dataRetentionBannerLogic,
['warningEligible', 'retentionMonths', 'retentionPeriodLabel'],
+ apiStatusLogic,
+ ['internetConnectionIssue'],
],
logic: [dashboardsModel, insightsModel, eventUsageLogic, addInsightToDashboardLogic],
})),
@@ -1409,7 +1427,11 @@ export const dashboardLogic = kea<dashboardLogicType>([
*/
loadDashboard: (payload: { action: DashboardLoadAction }) => payload,
/** Load dashboard with streaming tiles approach. */
- loadDashboardStreaming: (payload: { action: DashboardLoadAction; manualDashboardRefresh?: boolean }) => payload,
+ loadDashboardStreaming: (payload: {
+ action: DashboardLoadAction
+ manualDashboardRefresh?: boolean
+ retry?: boolean
+ }) => payload,
/** Dashboard metadata loaded successfully. */
loadDashboardMetadataSuccess: (dashboard: DashboardType | null) => ({ dashboard }),
/** Single tile received from stream. */
@@ -1417,9 +1439,11 @@ export const dashboardLogic = kea<dashboardLogicType>([
/** Tile streaming completed. */
tileStreamingComplete: true,
/** Tile streaming failed. */
- tileStreamingFailure: (error: any) => ({ error }),
- /** A non-404 stream failure left no dashboard to render — show a load error, not "not found". */
+ tileStreamingFailure: (error: any, willRetry: boolean = false) => ({ error, willRetry }),
+ /** A failed dashboard stream needs a load error with a retry action. */
setDashboardStreamFailed: true,
+ /** Retry a failed load through the same load path as the initial load. */
+ retryDashboardLoad: true,
/** Expose additional information about the current dashboard load in dashboardLoadData. */
loadingDashboardItemsStarted: (action: DashboardLoadAction) => ({ action }),
/** Expose response size information about the current dashboard load in dashboardLoadData. */
@@ -1669,11 +1693,21 @@ export const dashboardLogic = kea<dashboardLogicType>([
throw error
}
},
- loadDashboardStreaming: async ({ action }, breakpoint) => {
+ loadDashboardStreaming: async ({ action, retry }, breakpoint) => {
actions.loadingDashboardItemsStarted(action)
await breakpoint(200)
+ // fetchEventSource retries the failed stream on its own. If that stream delivered metadata during
+ // the wait, a new stream would abort it and replace the loaded dashboard with null.
+ if (retry && !values.dashboardFailedToLoad) {
+ return values.dashboard
+ }
let metadataReceived = false
+ const preserveTiles = retry && !!values.dashboard?.tiles?.length
+ let retriedDashboard: DashboardType | null = null
+ cache.disposables.dispose('dashboardStream')
+ cache.dashboardStreamActive = true
+ // nosemgrep: prefer-codegen-api-namespaced-dashboards -- The generated void client cannot handle SSE messages, retries, and cancellation.
const disposeStream = await api.dashboards.streamTiles(
props.id,
{
@@ -1685,16 +1719,29 @@ export const dashboardLogic = kea<dashboardLogicType>([
(data) => {
if (data.type === 'metadata') {
metadataReceived = true
- actions.loadDashboardMetadataSuccess(
- getQueryBasedDashboard(data.dashboard as DashboardType)
- )
+ if (preserveTiles) {
+ // Keep readable tiles until a complete replacement is available, even if retry fails.
+ retriedDashboard = { ...data.dashboard, tiles: [...(data.dashboard.tiles ?? [])] }
+ } else {
+ actions.loadDashboardMetadataSuccess(
+ getQueryBasedDashboard(data.dashboard as DashboardType)
+ )
+ }
} else if (data.type === 'tile') {
- actions.receiveTileFromStream(data)
+ if (retriedDashboard) {
+ retriedDashboard.tiles.push(data.tile)
+ } else {
+ actions.receiveTileFromStream(data)
+ }
}
},
// onComplete callback
() => {
+ cache.dashboardStreamActive = false
if (metadataReceived) {
+ if (retriedDashboard) {
+ actions.loadDashboardMetadataSuccess(getQueryBasedDashboard(retriedDashboard))
+ }
actions.tileStreamingComplete()
} else {
actions.tileStreamingFailure(
@@ -1703,15 +1750,22 @@ export const dashboardLogic = kea<dashboardLogicType>([
}
},
// onError callback
- (error) => {
+ (error, willRetry = false) => {
+ cache.dashboardStreamActive = willRetry
console.error('❌ Tile streaming error:', error)
- actions.tileStreamingFailure(error)
+ actions.tileStreamingFailure(error, willRetry)
}
)
- cache.disposables.add(() => disposeStream, 'dashboardStream', { pauseOnPageHidden: false })
+ cache.disposables.add(
+ () => () => {
+ cache.dashboardStreamActive = false
+ disposeStream()
+ },
+ 'dashboardStream',
+ { pauseOnPageHidden: false }
+ )
- // Return null - metadata will update the dashboard
- return null
+ return preserveTiles ? values.dashboard : null
},
saveEditModeChanges: async ({ scope }, breakpoint) => {
cache.dashboardChangesPersisted = false
@@ -2100,8 +2154,8 @@ export const dashboardLogic = kea<dashboardLogicType>([
dashboardFailedToLoad: [
false,
{
- loadDashboard: () => false,
- loadDashboardStreaming: () => false,
+ // A new load keeps the error state mounted, so a retry shows its loading state
+ // and a failed retry does not flash the error state off and on.
loadDashboardSuccess: () => false,
// The stream auto-retries after transient errors; delivered metadata means it recovered,
// so clear the load-error state instead of leaving it latched over a loaded dashboard.
@@ -3543,6 +3597,28 @@ export const dashboardLogic = kea<dashboardLogicType>([
actions.dashboardNotFound()
return
}
+ // apiStatusLogic clears internetConnectionIssue only after a successful request, and a failed
+ // dashboard sends no more requests. So the browser's online event must also start the retry.
+ cache.disposables.add(
+ () => {
+ const onOnline = (): void => {
+ if (cache.dashboardStreamActive) {
+ return
+ }
+ if (values.dashboardLoading || values.dashboardStreaming) {
+ cache.onlineRecoveryPending = true
+ return
+ }
+ if (values.dashboardFailedToLoad) {
+ actions.retryDashboardLoad()
+ }
+ }
+ window.addEventListener('online', onOnline)
+ return () => window.removeEventListener('online', onOnline)
+ },
+ 'connectionRecoveryOnline',
+ { pauseOnPageHidden: false }
+ )
if (props.id) {
if (props.dashboard) {
// If we already have dashboard data, use it. Should the data turn out to be stale,
@@ -3704,8 +3780,44 @@ export const dashboardLogic = kea<dashboardLogicType>([
primary_interaction_id: dashboardQueryId,
time_to_see_data_ms: Math.floor(performance.now() - startTime),
})
+ if (cache.onlineRecoveryPending || (cache.connectionRecoveryPending && !values.internetConnectionIssue)) {
+ cache.onlineRecoveryPending = false
+ cache.connectionRecoveryPending = false
+ actions.retryDashboardLoad()
+ }
+ },
+ setDashboardStreamFailed: () => {
+ if (cache.dashboardStreamActive) {
+ return
+ }
+ if (cache.onlineRecoveryPending || (cache.connectionRecoveryPending && !values.internetConnectionIssue)) {
+ cache.onlineRecoveryPending = false
+ cache.connectionRecoveryPending = false
+ actions.retryDashboardLoad()
+ }
},
- tileStreamingFailure: ({ error }) => {
+ retryDashboardLoad: () => {
+ if (values.shouldUseStreaming) {
+ actions.loadDashboardStreaming({ action: DashboardLoadAction.InitialLoad, retry: true })
+ } else {
+ actions.loadDashboard({ action: DashboardLoadAction.InitialLoad })
+ }
+ },
+ [apiStatusLogic.actionTypes.setInternetConnectionIssue]: ({ issue }: { issue: boolean }) => {
+ cache.connectionRecoveryPending = false
+ if (issue || cache.dashboardStreamActive) {
+ return
+ }
+ if (values.dashboardLoading || values.dashboardStreaming) {
+ // The connection came back during a load. If that load fails, retry it once.
+ cache.connectionRecoveryPending = true
+ return
+ }
+ if (values.dashboardFailedToLoad) {
+ actions.retryDashboardLoad()
+ }
+ },
+ tileStreamingFailure: ({ error, willRetry }) => {
// Only a genuine 404 response means the dashboard is missing. Stream errors can contain
// "404" in their message even when the dashboard still exists.
if (error?.status === 404) {
@@ -3716,10 +3828,9 @@ export const dashboardLogic = kea<dashboardLogicType>([
// Show error toast for other errors (500s, network issues, etc.)
const errorMessage = error?.message || 'Dashboard streaming failed'
lemonToast.error(`Failed to load dashboard: ${errorMessage}`)
- // If the stream died before any metadata arrived there is no dashboard to render.
- // The empty-state gate would otherwise fall through to the "Dashboard not found" screen,
- // so mark the load as failed to show a load-error state instead.
- if (!values.dashboard) {
+ // A stopped stream can leave missing tiles even after metadata arrived. Keep recovery
+ // available for terminal errors, and show a load error when there is nothing to render.
+ if (!willRetry || !values.dashboard) {
actions.setDashboardStreamFailed()
}
}
@@ -4772,6 +4883,8 @@ export const dashboardLogic = kea<dashboardLogicType>([
loadDashboardSuccess: [
sharedListeners.reportLoadTiming,
() => {
+ cache.onlineRecoveryPending = false
+ cache.connectionRecoveryPending = false
if (!values.dashboard) {
actions.dashboardNotFound()
return // We hit a 404
@@ -4780,6 +4893,8 @@ export const dashboardLogic = kea<dashboardLogicType>([
sharedListeners.handleDashboardLoadComplete,
],
loadDashboardMetadataSuccess: ({ dashboard }) => {
+ cache.onlineRecoveryPending = false
+ cache.connectionRecoveryPending = false
if (!dashboard) {
actions.dashboardNotFound()
return // We hit a 404