: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(notebooks): auto-reconnect collab SSE and show warning (#59406)
Alex Lider534b5e259ec4
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 460a3ef419bd..fcd7c9ab13f5 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -4756,15 +4756,31 @@ const api = {{onMessage,onError,+ onOpen,+ onClose,signal,+ lastEventId,}: {onMessage: (data: EventSourceMessage) => voidonError: (error: any) => void+ onOpen?: () => void+ onClose?: () => voidsignal?: AbortSignal+ /** Stream id of the last received event; sent as `Last-Event-ID` so the+ * server resumes from there instead of restarting at the stream tip. */+ lastEventId?: string}): Promise<void> {const url = new ApiRequest().notebook(notebookId).withAction('collab/stream').assembleFullUrl(true)- await api.stream(url, { method: 'GET', onMessage, onError, signal })+ await api.stream(url, {+ method: 'GET',+ onMessage,+ onError,+ onOpen,+ onClose,+ signal,+ headers: lastEventId ? { 'Last-Event-ID': lastEventId } : undefined,+ })},},@@ -6812,6 +6828,8 @@ const api = {data,onMessage,onError,+ onOpen,+ onClose,headers,signal,}:@@ -6821,6 +6839,12 @@ const api = {data?: neveronMessage: (data: EventSourceMessage) => voidonError: (error: any) => void+ /** Fires every time the underlying fetch returns a healthy response — i.e.+ * on initial open *and* on each successful internal reconnect by fetch-event-source. */+ onOpen?: () => void+ /** Fires when the server cleanly closes the response body (not on errors,+ * not on abort). Use this to react to server-initiated stream rotation. */+ onClose?: () => voidheaders?: Record<string, string>signal?: AbortSignal}@@ -6830,6 +6854,8 @@ const api = {data: anyonMessage: (data: EventSourceMessage) => voidonError: (error: any) => void+ onOpen?: () => void+ onClose?: () => voidheaders?: Record<string, string>signal?: AbortSignal}@@ -6888,15 +6914,19 @@ const api = {))abortController.abort()- } else if (isLivestreamUrl) {- posthog.capture('livestream_sse_opened', {- url,- status: response.status,- })+ } else {+ onOpen?.()+ if (isLivestreamUrl) {+ posthog.capture('livestream_sse_opened', {+ url,+ status: response.status,+ })+ }}},onmessage: onMessage,onerror: onError,+ onclose: onClose,// By default fetch-event-source stops connection when document is no longer focused, but that is not how// EventSource works normally, hence reverting (https://github.com/Azure/fetch-event-source/issues/36)openWhenHidden: true,diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookMeta.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookMeta.tsxindex 61ddfbc61baa..ec48aa395720 100644--- a/frontend/src/scenes/notebooks/Notebook/NotebookMeta.tsx+++ b/frontend/src/scenes/notebooks/Notebook/NotebookMeta.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'import { useCallback, useEffect, useState } from 'react'-import { IconBook, IconTerminal } from '@posthog/icons'+import { IconBook, IconTerminal, IconWarning } from '@posthog/icons'import { LemonButton, LemonButtonProps, LemonTag } from '@posthog/lemon-ui'import { FEATURE_FLAGS } from 'lib/constants'@@ -12,6 +12,7 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'import { NotebookSyncStatus } from '../types'+import { notebookCollabLogic } from './notebookCollabLogic'import { NotebookLogicProps, notebookLogic } from './notebookLogic'import { notebookSettingsLogic } from './notebookSettingsLogic'@@ -88,6 +89,28 @@ export const NotebookSyncInfo = (props: NotebookLogicProps): JSX.Element | null) : null}+/**+ * Surfaces when the collab SSE is disconnected *and* no reconnect attempt is in flight,+ * so the user only sees the warning when something is actually wrong — not during the+ * initial connect or the brief gap on a normal reconnect.+ */+export const NotebookCollabStatus = (props: NotebookLogicProps): JSX.Element | null => {+ const { collabEnabled } = useValues(notebookLogic(props))+ const { streamConnected, isConnecting, streamError } = useValues(notebookCollabLogic({ shortId: props.shortId }))++ if (!collabEnabled || streamConnected || isConnecting) {+ return null+ }++ const tooltip = streamError ? `Live updates paused. Last error: ${streamError}` : 'Live updates paused.'++ return (+ <Tooltip title={tooltip} placement="left">+ <LemonButton size="small" icon={<IconWarning className="text-warning" />} type="tertiary" />+ </Tooltip>+ )+}+interface NotebookExpandButtonProps extends Pick<LemonButtonProps, 'size' | 'type'> {inPanel: boolean}diff --git a/frontend/src/scenes/notebooks/Notebook/notebookCollabLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookCollabLogic.tsindex 6b98850f856c..be37a5587239 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookCollabLogic.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookCollabLogic.ts@@ -92,6 +92,8 @@ export const notebookCollabLogic = kea<notebookCollabLogicType>([rebaseFailed: (params: { localContent: JSONContent; localText: string }) => params,connectStream: true,disconnectStream: true,+ streamOpened: true,+ streamClosed: (error: string | null = null) => ({ error }),}),reducers({@@ -104,6 +106,31 @@ export const notebookCollabLogic = kea<notebookCollabLogicType>([],// Stable per-logic clientID; shared with the PM collab plugin for self-event filtering.clientID: [uuid() as string, {}],+ streamConnected: [+ false,+ {+ streamOpened: () => true,+ streamClosed: () => false,+ disconnectStream: () => false,+ },+ ],+ isConnecting: [+ false,+ {+ connectStream: () => true,+ streamOpened: () => false,+ streamClosed: () => false,+ disconnectStream: () => false,+ },+ ],+ streamError: [+ null as string | null,+ {+ streamOpened: () => null,+ streamClosed: (_, { error }) => error,+ disconnectStream: () => null,+ },+ ],}),listeners(({ actions, values, props, cache }) => ({@@ -168,6 +195,7 @@ export const notebookCollabLogic = kea<notebookCollabLogicType>([}// SSE id is the Redis stream id `N-0` and N is the prosemirror version.// We use it for both reconnection (Last-Event-ID) and idempotency.+ cache.lastEventId = msg.idconst version = parseInt(msg.id.split('-', 1)[0], 10)if (!Number.isFinite(version)) {return@@ -209,22 +237,48 @@ export const notebookCollabLogic = kea<notebookCollabLogicType>([if (controller.signal.aborted) {return}- posthog.captureException(error instanceof Error ? error : new Error(String(error)), {+ const message = error instanceof Error ? error.message : String(error)+ actions.streamClosed(message)+ posthog.captureException(error instanceof Error ? error : new Error(message), {action: 'notebook collab stream',})}- // fetchEventSource handles reconnection via Last-Event-ID; this awaits for the connection's lifetime.+ // onOpen fires on every successful fetch — including fetch-event-source's own+ // internal retries — so the UI flips back to "live" the moment a connection+ // opens, whether it's the initial one or a recovery after a transient error.+ const onOpen = (): void => {+ if (controller.signal.aborted) {+ return+ }+ actions.streamOpened()+ }++ // onClose fires when the server cleanly ends the body — the backend does this+ // every STREAM_LIFETIME_SECONDS (5 min) by design. Errors and abort don't trigger+ // this hook, so it cleanly isolates the "rotation" case from the failure case.+ const onClose = (): void => {+ if (controller.signal.aborted) {+ return+ }+ actions.streamClosed()+ actions.connectStream()+ }+try {await api.notebooks.collabStream(props.shortId, {onMessage,onError,+ onOpen,+ onClose,signal: controller.signal,+ lastEventId: cache.lastEventId,})} catch (e) {if (controller.signal.aborted) {return}+ actions.streamClosed(e instanceof Error ? e.message : String(e))posthog.captureException(e as Error, { action: 'notebook collab stream open' })}},@@ -232,6 +286,7 @@ export const notebookCollabLogic = kea<notebookCollabLogicType>([disconnectStream: () => {cache.abortController?.abort()cache.abortController = null+ cache.lastEventId = undefined},})),diff --git a/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsx b/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsxindex 59ce426d948d..29ee1156117a 100644--- a/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsx+++ b/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsx@@ -16,7 +16,7 @@ import { SidePanelContentContainer } from '~/layout/navigation-3000/sidepanel/Siimport { Notebook } from '../Notebook/Notebook'import { NotebookListMini } from '../Notebook/NotebookListMini'import { notebookLogic } from '../Notebook/notebookLogic'-import { NotebookExpandButton, NotebookSyncInfo } from '../Notebook/NotebookMeta'+import { NotebookCollabStatus, NotebookExpandButton, NotebookSyncInfo } from '../Notebook/NotebookMeta'import { NotebookMenu } from '../NotebookMenu'import { NotebookTarget } from '../types'import { NotebookPanelDropzone } from './NotebookPanelDropzone'@@ -49,7 +49,12 @@ export function NotebookPanel(): JSX.Element | null {buttonProps={{ className: 'max-w-[120px]', truncate: true }}/>- {selectedNotebook && <NotebookSyncInfo shortId={selectedNotebook} />}+ {selectedNotebook && (+ <>+ <NotebookCollabStatus shortId={selectedNotebook} />+ <NotebookSyncInfo shortId={selectedNotebook} />+ </>+ )}</div><div className="flex-1" />diff --git a/frontend/src/scenes/notebooks/NotebookScene.tsx b/frontend/src/scenes/notebooks/NotebookScene.tsxindex 2284061c1275..15d1bbaba36f 100644--- a/frontend/src/scenes/notebooks/NotebookScene.tsx+++ b/frontend/src/scenes/notebooks/NotebookScene.tsx@@ -18,6 +18,7 @@ import { Notebook } from './Notebook/Notebook'import { NotebookLoadingState } from './Notebook/NotebookLoadingState'import { notebookLogic } from './Notebook/notebookLogic'import {+ NotebookCollabStatus,NotebookExpandButton,NotebookKernelInfoButton,NotebookSyncInfo,@@ -124,6 +125,7 @@ export function NotebookScene(): JSX.Element {</div><div className="flex gap-2 items-center">+ <NotebookCollabStatus shortId={notebookId} /><NotebookSyncInfo shortId={notebookId} /><NotebookMenu shortId={notebookId} />