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(posthog_ai): stop an open SSE stream from wedging local hot reload (#77348)

Georgiy Tarasov2ed1f1017317
diff --git a/bin/start-backend b/bin/start-backend
index 4f37459f70ef..f21b4820a2dd 100755
--- a/bin/start-backend
+++ b/bin/start-backend
@@ -23,6 +23,11 @@ fi
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+# --workers-kill-timeout bounds the reload. Granian defaults it to disabled, which means it joins
+# the old worker with no timeout and only escalates to a hard kill when the flag is set. An open SSE
+# stream (an agent run log held by a browser tab) never finishes on its own, so without this the
+# worker never exits, the replacement is never spawned, and port 8000 stays dead until it is killed
+# by hand. A worker with nothing in flight still exits immediately, so normal reloads are unaffected.
python ${DEBUG:+ -m debugpy --listen 127.0.0.1:5678} -m granian \
--interface asgi \
posthog.asgi:application \
@@ -33,4 +38,5 @@ python ${DEBUG:+ -m debugpy --listen 127.0.0.1:5678} -m granian \
--reload-paths ./frontend/src/products.json \
--host $HOST_BIND \
--log-level debug \
- --workers 1
+ --workers 1 \
+ --workers-kill-timeout 5
diff --git a/frontend/jest.config.ts b/frontend/jest.config.ts
index d79c5091a607..cca37ae16f8c 100644
--- a/frontend/jest.config.ts
+++ b/frontend/jest.config.ts
@@ -183,6 +183,10 @@ const config: Config = {
// `new URL("./x.png", import.meta.url)` — import.meta is unavailable under Sucrase/CJS,
// so mock them to the styleMock string instead of executing them.
'^@posthog/brand/.*/png/.*$': '<rootDir>/src/test/mocks/styleMock.js',
+ // devHmrStreamAbort subscribes to Vite HMR events via import.meta, which Sucrase passes
+ // through into CJS and Jest then cannot compile ("Cannot use 'import.meta' outside a module").
+ // It is dev-server-only behavior, so stub it out rather than transform it.
+ devHmrStreamAbort$: '<rootDir>/src/test/mocks/emptyMock.js',
'^.+\\.sql\\?raw$': '<rootDir>/src/test/mocks/rawFileMock.js',
'^(.+)\\.yaml\\?raw$': '$1.yaml',
'^~/(.*)$': '<rootDir>/src/$1',
diff --git a/products/posthog_ai/frontend/logics/devHmrStreamAbort.ts b/products/posthog_ai/frontend/logics/devHmrStreamAbort.ts
new file mode 100644
index 000000000000..33f681bd0fef
--- /dev/null
+++ b/products/posthog_ai/frontend/logics/devHmrStreamAbort.ts
@@ -0,0 +1,79 @@
+import type { LiveStreamEntry } from './runStreamLogic'
+
+interface LiveStreamRegistryHost {
+ __posthogAiLiveStreamControllers?: Set<LiveStreamEntry>
+}
+
+// Vite injects `import.meta.hot` in dev and replaces it with undefined in production builds. Typed
+// locally because `vite/client` only resolves from the frontend workspace, not from this product.
+interface ViteHotContext {
+ on: (event: 'vite:afterUpdate' | 'vite:beforeFullReload' | 'vite:beforeUpdate', cb: () => void) => void
+}
+
+let registered = false
+
+/**
+ * Closes live SSE readers before Vite applies an HMR update, so a dev reload never waits on them.
+ *
+ * An open SSE response keeps a granian dev worker alive, and granian's reload joins the old worker
+ * before spawning its replacement, so a stream nobody closes stalls the whole backend until the kill
+ * timeout in bin/start-backend fires. Vite awaits `vite:beforeUpdate` listeners before applying an
+ * update, which makes it the one hook early enough to release the worker rather than race it.
+ *
+ * Every update fires this, including updates that leave `runStreamLogic` itself untouched. Those
+ * logics survive the swap with a live thread still on screen, and an aborted signal is the silent
+ * teardown path that schedules no reconnect, so aborting alone would stall the run with no way back.
+ * They are reopened on `vite:afterUpdate` instead.
+ *
+ * Registry membership is what decides who gets reopened, because an entry is removed only when its
+ * 'event-source' disposable tears down. An entry still present after the swap therefore has a logic
+ * that is mounted and still wants a stream. Entries that vanished belong either to a logic that
+ * unmounted mid-swap or to a build the swap discarded (re-evaluating `runStreamLogic` installs a
+ * fresh registry), and both must stay closed.
+ *
+ * This lives outside `runStreamLogic` because `import.meta` cannot appear in any module Jest
+ * compiles: Sucrase passes it through into CJS and the script then fails to compile with "Cannot use
+ * 'import.meta' outside a module", which no runtime environment check can prevent. Jest maps this
+ * path to an empty module (see `moduleNameMapper` in frontend/jest.config.ts), so the caller must
+ * keep the call itself behind a development check.
+ */
+export function registerHmrStreamAbort(): void {
+ const hot = (import.meta as ImportMeta & { hot?: ViteHotContext }).hot
+ // An HMR swap that re-evaluates only the caller would otherwise stack a second set of listeners
+ // on this module's still-live hot context.
+ if (!hot || registered) {
+ return
+ }
+ registered = true
+
+ const registryHost = globalThis as LiveStreamRegistryHost
+ let pendingReopen: LiveStreamEntry[] = []
+
+ const abortAll = (): LiveStreamEntry[] => {
+ const entries = [...(registryHost.__posthogAiLiveStreamControllers ?? [])]
+ entries.forEach((entry) => entry.controller.abort())
+ return entries
+ }
+
+ hot.on('vite:beforeUpdate', () => {
+ pendingReopen = abortAll()
+ })
+
+ hot.on('vite:afterUpdate', () => {
+ const entries = pendingReopen
+ pendingReopen = []
+ const current = registryHost.__posthogAiLiveStreamControllers
+ entries.forEach((entry) => {
+ if (current?.has(entry)) {
+ entry.reopen()
+ }
+ })
+ })
+
+ // A full reload discards the page anyway, but releasing the worker before it starts means the new
+ // page's first requests aren't queued behind a backend still waiting on the old connection.
+ hot.on('vite:beforeFullReload', () => {
+ pendingReopen = []
+ abortAll()
+ })
+}
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.ts
index 44fc0a85b06f..69bcdb668b21 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts
@@ -72,27 +72,38 @@ import { extractContextBlockLines } from '../utils/posthogContextBlock'
import { getClaudeCodeMeta, resolveToolCall } from '../utils/toolResolver'
import { attachedContextLogic } from './attachedContextLogic'
import { debugLogsLogic } from './debugLogsLogic'
+import { registerHmrStreamAbort } from './devHmrStreamAbort'
import { foregroundStreamLogic } from './foregroundStreamLogic'
import { hasReplayListener, toolStreamEventsLogic } from './toolStreamEventsLogic'
import type { ToolStreamSubscription } from './toolStreamEventsLogic'
+export interface LiveStreamEntry {
+ controller: AbortController
+ /** Reopens this stream after an HMR swap its logic survived. See `devHmrStreamAbort`. */
+ reopen: () => void
+}
+
interface LiveStreamRegistryHost {
- __posthogAiLiveStreamControllers?: Set<AbortController>
+ __posthogAiLiveStreamControllers?: Set<LiveStreamEntry>
}
// Dev-only guard against orphaned SSE readers: an HMR swap re-evaluates this module in the same page,
-// and the old build's logic gets discarded with a fresh kea `cache` — its 'event-source' disposable
-// never runs teardown, so its reader keeps the connection open (pinning a granian dev worker) until
-// the tab closes. A fresh evaluation finding controllers in the page-global registry therefore means
-// an HMR swap just replaced their build — abort them (an aborted signal is the silent teardown path,
-// so the old logic won't schedule a reconnect). On first load the registry is empty, and a full page
-// load needs none of this: the browser aborts in-flight fetches itself. `import.meta.hot.dispose`
-// would be the idiomatic hook, but `import.meta` is a parse error in Jest's CJS transform.
-const liveStreamControllers = new Set<AbortController>()
+// and the old build's logic gets discarded with a fresh kea `cache`, so its 'event-source' disposable
+// never runs teardown and its reader keeps the connection open (pinning a granian dev worker) until
+// the tab closes. A fresh evaluation finding entries in the page-global registry therefore means
+// an HMR swap just replaced their build, so abort them (an aborted signal is the silent teardown path,
+// which is why the old logic won't schedule a reconnect). On first load the registry is empty, and a
+// full page load needs none of this because the browser aborts in-flight fetches itself.
+//
+// This only covers swaps that re-evaluate this module. `devHmrStreamAbort` covers the rest, where the
+// logic survives and its stream has to be reopened rather than left closed.
+const liveStreamControllers = new Set<LiveStreamEntry>()
if (process.env.NODE_ENV === 'development') {
const registryHost = globalThis as LiveStreamRegistryHost
- registryHost.__posthogAiLiveStreamControllers?.forEach((controller) => controller.abort())
+ registryHost.__posthogAiLiveStreamControllers?.forEach((entry) => entry.controller.abort())
registryHost.__posthogAiLiveStreamControllers = liveStreamControllers
+ // Jest maps this module to an empty stub, so the call has to stay inside this check.
+ registerHmrStreamAbort()
}
export type RunSseStatus = 'idle' | 'connecting' | 'open' | 'reconnecting' | 'closed' | 'error'
@@ -2626,10 +2637,17 @@ export const runStreamLogic = kea<runStreamLogicType>([
cache.disposables.add(
(): (() => void) => {
const controller = new AbortController()
- liveStreamControllers.add(controller)
+ // `startLatest: true` mirrors the reconnect path below: the resume actually happens
+ // off `cache.lastEventId` via Last-Event-ID, so this only matters if no frame has
+ // arrived yet.
+ const entry: LiveStreamEntry = {
+ controller,
+ reopen: () => actions.openSseForRun({ taskId, runId, startLatest: true }),
+ }
+ liveStreamControllers.add(entry)
void streamRun(controller.signal)
return () => {
- liveStreamControllers.delete(controller)
+ liveStreamControllers.delete(entry)
controller.abort()
}
},