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): reopen the turn on a user message from the wire (#91793)

Georgiy Tarasovabbe7d7a46a7
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
index bfa8826fe474..88ae645ee278 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
@@ -1624,16 +1624,68 @@ describe('runStreamLogic', () => {
expect(logic.values.isThinking).toEqual(false)
})
- it('re-raises on a follow-up turn opened by a human message, with no new run_started', () => {
+ // A follow-up on the same run starts a new turn with no second run_started frame. It reaches
+ // the thread as this composer's optimistic echo, as a wire user turn in one of its two forms,
+ // or — for a follow-up sent from Slack, where the live stream carries no user turn at all —
+ // only as the agent's first output.
+ it.each([
+ ['this composer', (): void => logic.actions.pushHumanMessage('and the mobile funnel?')],
+ [
+ 'a wire _posthog/user_message',
+ (): void =>
+ logic.actions.ingestAcpFrame(
+ notification('_posthog/user_message', { content: 'and the mobile funnel?' })
+ ),
+ ],
+ [
+ 'a wire session/update user_message',
+ (): void =>
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({ sessionUpdate: 'user_message', content: { text: 'and the mobile funnel?' } })
+ ),
+ ],
+ [
+ 'the agent producing output',
+ (): void =>
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({
+ sessionUpdate: 'agent_message_chunk',
+ messageId: 'm2',
+ content: { text: 'On' },
+ })
+ ),
+ ],
+ ])('re-raises on a follow-up turn opened by %s, with no new run_started', (_case, sendFollowUp) => {
logic.actions.ingestAcpFrame(notification('_posthog/run_started', {}))
logic.actions.ingestAcpFrame(notification('_posthog/turn_complete', {}))
expect(logic.values.isThinking).toEqual(false)
- // A follow-up on the same run starts a new turn — no second run_started frame arrives.
- logic.actions.pushHumanMessage('and the mobile funnel?')
+ sendFollowUp()
expect(logic.values.isThinking).toEqual(true)
})
+ it('re-raises for a queued follow-up whose user turn precedes the prior turn_complete', () => {
+ logic.actions.ingestAcpFrame(notification('_posthog/run_started', {}))
+ // A follow-up sent while the first turn is still running is persisted when it is received,
+ // so the replayed log carries it before that turn's completion.
+ logic.actions.ingestAcpFrame(notification('_posthog/user_message', { content: 'and mobile?' }))
+ logic.actions.ingestAcpFrame(notification('_posthog/turn_complete', {}))
+ expect(logic.values.isThinking).toEqual(false)
+
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', messageId: 'm2', content: { text: 'On' } })
+ )
+ expect(logic.values.isThinking).toEqual(true)
+ })
+
+ it('stays off after turn_complete on an update that does not mean the agent is generating', () => {
+ logic.actions.ingestAcpFrame(notification('_posthog/run_started', {}))
+ logic.actions.ingestAcpFrame(notification('_posthog/turn_complete', {}))
+
+ logic.actions.ingestAcpFrame(sessionUpdate({ sessionUpdate: 'current_mode_update', currentModeId: 'auto' }))
+ expect(logic.values.isThinking).toEqual(false)
+ })
+
it('is on during the cold-boot queued window before the first run_started', async () => {
await expectLogic(logic, () => {
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.ts
index 6526af44d767..58d7fb1c8c63 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts
@@ -153,6 +153,20 @@ export const INITIAL_PERMISSION_MODE: TaskRunBootstrapCreateRequestInitialPermis
/** The crash-error string the in-sandbox agent server writes on a fatal exception. */
const AGENT_CRASH_PREFIX = 'Agent server crashed'
+/**
+ * `session/update` sub-types that mean the agent is producing output for a turn, and so that a turn is
+ * open. An allowlist, so an unknown or malformed sub-type fails safe to "not generating" rather than
+ * reopening a turn that finished. `tool_call_update` is deliberately absent: it updates a call the turn
+ * already started, and can trail the end of that turn.
+ */
+const AGENT_GENERATING_SESSION_UPDATES: ReadonlySet<string> = new Set([
+ 'agent_message',
+ 'agent_message_chunk',
+ 'agent_thought_chunk',
+ 'tool_call',
+ 'plan',
+])
+
/**
* In-band durable end-of-run sentinel emitted by both the Django stream view and the agent-proxy
* (`event: stream-end`, `data: {"status":"complete"}`). Distinct from the rotation `end` event (a
@@ -1504,6 +1518,9 @@ export interface runStreamLogicActions {
markTurnComplete: () => {
value: true
}
+ markTurnStarted: () => {
+ value: true
+ }
mergeResourcesUsed: (
products: {
id?: string
@@ -1807,6 +1824,12 @@ export const runStreamLogic = kea<runStreamLogicType>([
/** Records the agent's `/clear` capability, read off each `_posthog/run_started` frame. */
setConversationClearSupported: (supported: boolean) => ({ supported }),
markTurnComplete: true,
+ /**
+ * Reopens the turn for a follow-up that started outside this composer, such as one sent from Slack
+ * or from another tab. Dispatched from a user turn seen on the wire, and from the agent's first
+ * output of a turn, which is the only marker the live stream carries.
+ */
+ markTurnStarted: true,
/** Echoes the user's own message into the thread as a `client`-sourced log entry (the wire never replays a live turn). */
pushHumanMessage: (content: string) => ({ content }),
/**
@@ -2102,8 +2125,11 @@ export const runStreamLogic = kea<runStreamLogicType>([
// A run emits `_posthog/run_started` once; a follow-up message on the same run starts
// a fresh turn with no new run_started frame, so a human message also reopens the
// turn — otherwise the thinking indicator would stay off for the whole follow-up.
+ // `pushHumanMessage` covers a send from this composer, `markTurnStarted` a turn that
+ // started some other way (Slack, another tab, a replayed history tail).
markRunStarted: () => false,
pushHumanMessage: () => false,
+ markTurnStarted: () => false,
reset: () => false,
},
],
@@ -3251,6 +3277,7 @@ export const runStreamLogic = kea<runStreamLogicType>([
// unattached optimistic stream has no task id and records nothing — its send path marks
// sent keys directly.
if (isPosthogNotification(notification, '_posthog/user_message')) {
+ actions.markTurnStarted()
if (values.bootstrappedTaskId) {
const lines = contextBlockLinesFromUserMessage(extractUserMessageText(notification.params?.content))
if (lines.length > 0) {
@@ -3294,6 +3321,7 @@ export const runStreamLogic = kea<runStreamLogicType>([
// chains persist a turn in both wire forms, and the seen-lines reducer dedupes the overlap.
// Chunked frames are skipped: a partial text could truncate a block mid-line.
if (isSessionUpdateUserMessage(update)) {
+ actions.markTurnStarted()
if (values.bootstrappedTaskId && update.sessionUpdate === 'user_message') {
const lines = contextBlockLinesFromUserMessage(String(update.content?.text ?? update.text ?? ''))
if (lines.length > 0) {
@@ -3305,6 +3333,15 @@ export const runStreamLogic = kea<runStreamLogicType>([
if (!isKnownSessionUpdate(update)) {
return
}
+ // The agent producing output is the only marker of a new turn this client can rely on when the
+ // turn was started from outside its own composer. Such a follow-up is queued on the run, which
+ // emits no second `run_started`, and neither wire form of the user turn fills the gap: the live
+ // stream never carries one, and the persisted one is written when the message is received, so a
+ // message sent mid-turn is replayed *before* the previous turn's `turn_complete`. Guarded on
+ // `turnComplete` so this costs one dispatch per turn rather than one per streamed chunk.
+ if (values.turnComplete && AGENT_GENERATING_SESSION_UPDATES.has(update.sessionUpdate)) {
+ actions.markTurnStarted()
+ }
if (update.sessionUpdate === 'current_mode_update') {
actions.setCurrentMode(String(update.currentModeId ?? update.mode ?? ''))
return