: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(posthog-ai): reuse the retained stream after a run continuation (#120752)
Shy Altereda5615b8110
diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsxindex 4407aea0b418..d2caf5f0da88 100644--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx@@ -6,8 +6,8 @@ import { LemonBanner, LemonButton, LemonDivider } from '@posthog/lemon-ui'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { useThreadSkin } from '../hooks/useThreadSkin'-import { retainMountedLogic } from '../logics/retainedLogics'-import { isTerminalRunStatus, runStreamLogic } from '../logics/runStreamLogic'+import { isLogicRetained, RETAINED_RUN_STREAMS, retainMountedLogic } from '../logics/retainedLogics'+import { findLiveRunStreamKey, isTerminalRunStatus, runStreamLogic } from '../logics/runStreamLogic'import { taskLogic } from '../logics/taskLogic'import { isPiTaskRuntime, OriginProduct } from '../types/taskTypes'import { type TurnTrailer } from '../utils/turnTrailers'@@ -107,9 +107,16 @@ function RunSurfaceRoot({const [floatingInputsHeight, setFloatingInputsHeight] = useState(0)const { hasThreadItems } = useValues(runStreamLogic({ streamKey: logicKey, conversationId, replayOnly }))useEffect(() => {- if (retainAfterUnmount && !replayOnly && runId && logicKey === runId) {+ if (+ retainAfterUnmount &&+ !replayOnly &&+ runId &&+ (logicKey === runId ||+ isLogicRetained(RETAINED_RUN_STREAMS, logicKey) ||+ findLiveRunStreamKey(runId) === logicKey)+ ) {retainMountedLogic(- 'run-stream',+ RETAINED_RUN_STREAMS,logicKey,runStreamLogic({ streamKey: logicKey, conversationId, replayOnly }),MAX_RETAINED_RUN_STREAMSdiff --git a/products/posthog_ai/frontend/logics/retainedLogics.test.ts b/products/posthog_ai/frontend/logics/retainedLogics.test.tsindex 142885080112..c51390933ebc 100644--- a/products/posthog_ai/frontend/logics/retainedLogics.test.ts+++ b/products/posthog_ai/frontend/logics/retainedLogics.test.ts@@ -1,8 +1,23 @@import { actions, kea, key, path, props, reducers } from 'kea'+import { expectLogic } from 'kea-test-utils'++import api from 'lib/api'+import { projectLogic } from 'scenes/projectLogic'import { initKeaTests } from '~/test/init'-import { retainMountedLogic } from './retainedLogics'+import { tasksRunsRetrieve } from 'products/tasks/frontend/generated/api'++import { turnSuggestionsStateRetrieve } from '../generated/api'+import { RETAINED_RUN_STREAMS, resolveRunStreamKey, retainMountedLogic } from './retainedLogics'+import { runStreamLogic } from './runStreamLogic'++jest.mock('../generated/api', () => ({ turnSuggestionsStateRetrieve: jest.fn() }))+jest.mock('products/tasks/frontend/generated/api', () => ({+ tasksRunsRetrieve: jest.fn(),+ tasksRunsCommandCreate: jest.fn(),+ tasksRunsStreamTokenRetrieve: jest.fn(),+}))const counterLogic = kea([props({} as { id: string }),@@ -12,9 +27,20 @@ const counterLogic = kea([reducers({ count: [0, { increment: (state: number) => state + 1 }] }),])-describe('retainMountedLogic', () => {+describe('retainedLogics', () => {beforeEach(() => {initKeaTests()+ projectLogic.mount()+ projectLogic.actions.loadCurrentProjectSuccess({ id: 997 } as any)+ jest.mocked(tasksRunsRetrieve)+ .mockReset()+ .mockResolvedValue({ status: 'completed', state: {} } as any)+ jest.mocked(turnSuggestionsStateRetrieve).mockResolvedValue({ muted: false, resolved_turns: [] })+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([])+ })++ afterEach(() => {+ jest.restoreAllMocks()})it('keeps the logic and its state after its holder unmounts, and evicts the oldest past the limit', () => {@@ -34,4 +60,41 @@ describe('retainMountedLogic', () => {expect(counterLogic.findMounted({ id: 'a' })?.values.count).toBe(1)expect(counterLogic.findMounted({ id: 'c' })).not.toBeNull()})++ async function streamServing(streamKey: string, runId: string): Promise<() => void> {+ const logic = runStreamLogic({ streamKey })+ const unmount = logic.mount()+ logic.actions.bootstrapRun({ taskId: 'task-1', runId })+ await expectLogic(logic).toFinishAllListeners()+ return unmount+ }++ it.each([+ { name: 'no key resolves to the continuation alias', streamKey: undefined, expected: 'run-a' },+ { name: 'the run id resolves to the continuation alias', streamKey: 'run-b', expected: 'run-a' },+ { name: 'an explicit other key is kept', streamKey: 'client-key', expected: 'client-key' },+ ])('$name', async ({ streamKey, expected }) => {+ await streamServing('run-a', 'run-b')++ expect(resolveRunStreamKey('run-b', streamKey)).toBe(expected)+ })++ it('finds an alias that retention evicted while another surface keeps it mounted', async () => {+ const panelUnmount = await streamServing('run-a', 'run-b')+ retainMountedLogic(RETAINED_RUN_STREAMS, 'run-a', runStreamLogic({ streamKey: 'run-a' }), 1)+ retainMountedLogic(RETAINED_RUN_STREAMS, 'run-c', counterLogic({ id: 'run-c' }), 1)++ expect(resolveRunStreamKey('run-b', undefined)).toBe('run-a')++ panelUnmount()+ expect(resolveRunStreamKey('run-b', undefined)).toBeUndefined()+ })++ it('drops an instance from the registry when it streams a run it did not bootstrap', async () => {+ await streamServing('conversation-1', 'run-a')+ runStreamLogic({ streamKey: 'conversation-1' }).actions.openSseForRun({ taskId: 'task-1', runId: 'run-b' })++ expect(resolveRunStreamKey('run-a', undefined)).toBeUndefined()+ expect(resolveRunStreamKey('run-b', undefined)).toBeUndefined()+ })})diff --git a/products/posthog_ai/frontend/logics/retainedLogics.ts b/products/posthog_ai/frontend/logics/retainedLogics.tsindex bfd4dae087cd..3af6b0765a24 100644--- a/products/posthog_ai/frontend/logics/retainedLogics.ts+++ b/products/posthog_ai/frontend/logics/retainedLogics.ts@@ -1,5 +1,9 @@import { BuiltLogic, getContext } from 'kea'+import { findLiveRunStreamKey } from './runStreamLogic'++export const RETAINED_RUN_STREAMS = 'run-stream'+const retainedByContext = new WeakMap<object, Map<string, Map<string, () => void>>>()function retainedGroup(group: string): Map<string, () => void> {@@ -35,3 +39,14 @@ export function retainMountedLogic(group: string, key: string, logic: BuiltLogic}return false}++export function isLogicRetained(group: string, key: string): boolean {+ return retainedGroup(group).has(key)+}++export function resolveRunStreamKey(runId: string, streamKey: string | undefined): string | undefined {+ if (streamKey && streamKey !== runId) {+ return streamKey+ }+ return findLiveRunStreamKey(runId) ?? streamKey+}diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.tsindex 7b71a7889116..c994ce000eac 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts@@ -1,5 +1,18 @@import { type EventSourceMessage, createParser } from 'eventsource-parser'-import { MakeLogicType, getContext, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import {+ MakeLogicType,+ getContext,+ actions,+ beforeUnmount,+ connect,+ kea,+ key,+ listeners,+ path,+ props,+ reducers,+ selectors,+} from 'kea'import posthog from 'posthog-js'import { agentConversationEventToAcpNotification } from '@posthog/agent-contracts/acp-conversation'@@ -120,6 +133,27 @@ interface LiveStreamRegistryHost {// 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>()++const liveRunStreamsByContext = new WeakMap<object, Map<string, string>>()++function liveRunStreams(): Map<string, string> {+ const context = getContext()+ let streams = liveRunStreamsByContext.get(context)+ if (!streams) {+ streams = new Map()+ liveRunStreamsByContext.set(context, streams)+ }+ return streams+}++export function findLiveRunStreamKey(runId: string): string | null {+ for (const [streamKey, servedRunId] of liveRunStreams()) {+ if (servedRunId === runId) {+ return streamKey+ }+ }+ return null+}if (process.env.NODE_ENV === 'development') {const registryHost = globalThis as LiveStreamRegistryHostregistryHost.__posthogAiLiveStreamControllers?.forEach((entry) => entry.controller.abort())@@ -4051,6 +4085,9 @@ export const runStreamLogic = kea<runStreamLogicType>([}},bootstrapRun: async ({ taskId, runId, justCreatedRun, retainedMessage }) => {+ if (!props.replayOnly) {+ liveRunStreams().set(props.streamKey, runId)+ }const previous = sessionNow()if (previous?.paused &&@@ -4150,6 +4187,9 @@ export const runStreamLogic = kea<runStreamLogicType>([if (props.replayOnly) {return}+ if (liveRunStreams().get(props.streamKey) !== runId) {+ liveRunStreams().delete(props.streamKey)+ }const previous = sessionNow()if ((previous?.paused &&@@ -4802,6 +4842,9 @@ export const runStreamLogic = kea<runStreamLogicType>([cache.disposables.dispose('event-source')},reset: () => {+ if (!props.replayOnly) {+ liveRunStreams().delete(props.streamKey)+ }cache.disposables.dispose('stream-session')cache.bootstrapStartedAt = undefinedcache.recoverySession = undefined@@ -5289,4 +5332,9 @@ export const runStreamLogic = kea<runStreamLogicType>([},}}),+ beforeUnmount(({ props }) => {+ if (!props.replayOnly) {+ liveRunStreams().delete(props.streamKey)+ }+ }),])diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.test.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.test.tsxindex 4db824071bdb..ddb963498215 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.test.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.test.tsx@@ -3,6 +3,7 @@ import '@testing-library/jest-dom'import { cleanup, render, screen } from '@testing-library/react'import { useActions, useValues } from 'kea'+import { useForegroundStream } from '../../../hooks/useForegroundStream'import type { ActiveCreation } from '../../../logics/runnerPanelLogic'import { SidePanelRunnerImpl } from './SidePanelRunnerImpl'@@ -60,4 +61,19 @@ describe('SidePanelRunnerImpl', () => {expect(screen.getByTestId('task-history-list')).toBeInTheDocument()})++ it.each([+ { name: 'a startup stream', creation: { streamKey: 'draft-1' }, registered: 'draft-1' },+ {+ name: 'a run, which TaskRunChat registers',+ creation: { streamKey: 'run-b', taskId: 'task-1', runId: 'run-b' },+ registered: null,+ },+ ])('registers the foreground stream for $name', ({ creation, registered }) => {+ setValues(creation as ActiveCreation, false)++ render(<SidePanelRunnerImpl panelId="panel" />)++ expect(useForegroundStream).toHaveBeenLastCalledWith(registered)+ })})diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsxindex 5ec8ec863d56..311eb2deae38 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx@@ -74,10 +74,12 @@ function SidePanelRunnerContent({const lemonChrome = useThreadSkin() === 'lemon'// This compact surface renders only in Max's side panel, so the run it shows is a foreground- // stream. Register its `streamKey` (cleared when the panel drops back to the composer/history, and- // re-pointed when it switches runs). The `/tasks` full-page run view registers its own entry via- // `TaskRunChat`; registrations are provider-keyed, so co-mounted surfaces don't clobber each other.- useForegroundStream(activeCreation?.streamKey ?? null)+ // stream. Register the startup stream here; once a run exists, `TaskRunChat` registers the key it+ // resolves, which can be a retained alias. Registrations are provider-keyed, so co-mounted surfaces+ // don't clobber each other.+ useForegroundStream(+ activeCreation && !(activeCreation.taskId && activeCreation.runId) ? activeCreation.streamKey : null+ )// Edit-capable hosts attach this before the first send, before a run exists. Question-only// hosts provide their own instructions instead of advertising edits to the open page.diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsxindex 57f5df9dd53d..1cb1d6375abc 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx@@ -1,5 +1,5 @@import { BindLogic, useActions, useValues } from 'kea'-import { type MutableRefObject, useEffect, useRef } from 'react'+import { type MutableRefObject, useEffect, useMemo, useRef } from 'react'import { cn } from 'lib/utils/css-classes'import { userLogic } from 'scenes/userLogic'@@ -13,6 +13,7 @@ import { RunSurface } from 'products/posthog_ai/frontend/api/runSurface'import { RunEscapeBoundary, type RunEscapeBoundaryProps } from '../../../components/RunEscapeBoundary'import { useForegroundStream } from '../../../hooks/useForegroundStream'import { useThreadSkin } from '../../../hooks/useThreadSkin'+import { resolveRunStreamKey } from '../../../logics/retainedLogics'import { runCancellationLogic } from '../../../logics/runCancellationLogic'import type { RunContinuationHandoff } from '../../../logics/runInteractionLogic'import type { AttachedContextItem } from '../../../types/contextTypes'@@ -71,10 +72,11 @@ export function TaskRunChat({// the run's setup only when the two agree; a mismatch would launch the successor on another run's config.const runConfig = selectedRun?.id === runId ? selectedRun : undefinedconst pendingInteraction = interactionKey ? runInteractionLogic.findMounted(interactionKey) : undefined+ const resolvedStreamKey = useMemo(() => resolveRunStreamKey(runId, streamKey), [runId, streamKey])const logicProps: RunInteractionLogicProps = {taskId,runId,- streamKey,+ streamKey: resolvedStreamKey,interactionKey,initialDraft,onDraftAdopted,