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): keep follow-up turns streaming after the first one (#91387)

Georgiy Tarasovb054eb1dc1f3
diff --git a/products/posthog_ai/frontend/AGENTS.md b/products/posthog_ai/frontend/AGENTS.md
index 3d483ceae0e3..d3e2bd80d2c9 100644
--- a/products/posthog_ai/frontend/AGENTS.md
+++ b/products/posthog_ai/frontend/AGENTS.md
@@ -117,7 +117,16 @@ It must stay **free of the Max scene and conversation orchestration**. Do not im
The heart of the surface:
- **SSE connection** — a `fetch` body reader pumped through `eventsource-parser`; a reconnect resumes after
- the last Redis stream id via `Last-Event-ID` (capped exponential backoff + cumulative cap).
+ the last Redis stream id via `Last-Event-ID` (capped exponential backoff + cumulative cap). Connection
+ state (the `stream-end` sentinel, the resume cursor, the proxy token budget) belongs to one connection:
+ every `openSseForRun` starts it fresh, and the cursor is dropped when the run being opened differs from
+ the one it came from. A send never revives a dead stream, and three things make that harder than it
+ looks: after the `stream-end` sentinel the run's Redis stream holds a completion entry the server stops
+ at and refuses to write past, so only a successor run can carry the next turn; `sseStatus: 'error'`
+ covers a failed history bootstrap as well as an exhausted reconnect budget, and the bootstrap case has
+ already dropped buffered frames whose ids advanced the resume cursor; and a reopen inherits the spent
+ reconnect budgets, so its first drop gives up at once. A user-initiated recovery needs its own action,
+ its own budgets, and a log-completeness precondition.
- **Ordered, append-only `log` is the single source of truth** — every wire frame (plus a few synthetic
client entries) is appended, never keyed or per-entry deduped — with one exception: superseded
`tool_call_update` frames are field-wise merged per `toolCallId` (`appendToRunLog`). Each update carries
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
index 62ff44960afd..bfa8826fe474 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
@@ -1911,6 +1911,45 @@ describe('runStreamLogic', () => {
})
})
+ describe('connection state across runs', () => {
+ // A follow-up on a finished run opens a successor with a stream of its own. The finished
+ // run's sentinel flag and resume cursor must not carry into it: the flag gates the drop
+ // handler, and the cursor addresses a different Redis stream.
+ it("opens a successor run on fresh connection state, not the finished run's", async () => {
+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)
+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })
+ await MockStream.latest().emitMessage(notification('_posthog/run_started', {}), '100-0')
+ await MockStream.latest().emitStreamEnd()
+
+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-2', startLatest: false })
+
+ expect(MockStream.latest().options.lastEventId).toBeUndefined()
+ await MockStream.latest().emitOpen()
+
+ const opened = MockStream.connections.length
+ jest.useFakeTimers()
+ await MockStream.latest().emitClose()
+ await flushPromises()
+ expect(logic.values.sseStatus).toEqual('reconnecting')
+ jest.advanceTimersByTime(2000)
+ expect(MockStream.connections.length).toEqual(opened + 1)
+ jest.useRealTimers()
+ })
+
+ it('leaves a dead stream closed when a follow-up starts a turn', async () => {
+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)
+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })
+ await MockStream.latest().emitMessage(notification('_posthog/run_started', {}), '100-0')
+ await MockStream.latest().emitStreamEnd()
+ expect(logic.values.sseStatus).toEqual('closed')
+ const opened = MockStream.connections.length
+
+ logic.actions.pushHumanMessage('and one more thing')
+
+ expect(MockStream.connections.length).toEqual(opened)
+ })
+ })
+
describe('connection teardown', () => {
// The keyed log store makes duplicate ingestion idempotent, so correctness no longer depends
// on closing the exact connection a hot reload orphaned (the old EventSource registry is
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.ts
index 867e998fe5b2..6526af44d767 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts
@@ -1855,6 +1855,9 @@ export const runStreamLogic = kea<runStreamLogicType>([
sseOpened: () => 'open',
sseReconnecting: () => 'reconnecting',
closeSse: () => 'closed',
+ // The sentinel tears the connection down without reconnecting, so the stream is no
+ // longer open — say so, rather than leaving a dead connection reading as healthy.
+ streamEnded: () => 'closed',
handleStreamError: () => 'error',
reset: () => 'idle',
},
@@ -2481,6 +2484,19 @@ export const runStreamLogic = kea<runStreamLogicType>([
return
}
+ // Every open starts a fresh connection. The end sentinel and the proxy re-mint budget
+ // belong to the connection that saw them, so a stale `streamEnded` must not leak into
+ // this one — it suppresses the drop handler, which leaves a dropped stream dead with no
+ // reconnect and no terminal refetch (the thread then waits on a turn nothing delivers).
+ // A stream that really is finished re-delivers the sentinel on this connection.
+ cache.streamEnded = false
+ cache.streamTokenRefreshes = 0
+ const previousRun = cache.activeRun as { taskId: string; runId: string } | undefined
+ if (previousRun && previousRun.runId !== runId) {
+ // The cursor is a Redis id from the previous run's stream — it addresses nothing in
+ // this one, so resuming from it can skip this run's opening frames.
+ cache.lastEventId = undefined
+ }
// Track the active run so the reconnect loop can refetch it on a drop.
cache.activeRun = { taskId, runId }
@@ -3061,6 +3077,13 @@ export const runStreamLogic = kea<runStreamLogicType>([
// stamp the turn start for per-turn duration metrics and append it as a `client`-sourced
// log entry the projection renders in order.
cache.turnStartedAtMs = Date.now()
+ // A send does NOT revive a dead stream, and reviving one is harder than it looks:
+ // `sseStatus: 'error'` covers a failed history bootstrap as well as an exhausted
+ // reconnect budget, and the bootstrap case has already dropped buffered frames whose
+ // ids advanced the resume cursor, so reopening from it silently skips them; a reopen
+ // also inherits the spent reconnect budgets, so the next drop gives up at once. A
+ // stream the durable sentinel closed cannot be revived at all — its Redis stream holds
+ // a completion entry the server stops at and refuses to write past.
actions.appendEntries([
{
entry: {