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(agent-proxy): Preserve first events after stream wait (#67231)

Charles Vien954d1a077235
diff --git a/services/agent-proxy/src/hono/sse-handler.ts b/services/agent-proxy/src/hono/sse-handler.ts
index 114ee79451c7..d7f80c0350b0 100644
--- a/services/agent-proxy/src/hono/sse-handler.ts
+++ b/services/agent-proxy/src/hono/sse-handler.ts
@@ -125,13 +125,12 @@ export async function* streamTaskRunEvents(
let delay = WAIT_INITIAL_DELAY_MS
const waitStartedAt = Date.now()
let lastKeepaliveAt = waitStartedAt
- let waited = false
-
+ let waitedForStream = false
while (!(await redisStream.exists())) {
const now = Date.now()
- if (!waited) {
- waited = true
+ if (!waitedForStream) {
+ waitedForStream = true
logger.debug('stream:waiting', { streamKey })
}
@@ -153,7 +152,7 @@ export async function* streamTaskRunEvents(
delay = Math.min(delay + WAIT_DELAY_INCREMENT_MS, WAIT_MAX_DELAY_MS)
}
- if (waited) {
+ if (waitedForStream) {
logger.debug('stream:available', { streamKey, waitedMs: Date.now() - waitStartedAt })
}
@@ -161,7 +160,7 @@ export async function* streamTaskRunEvents(
let startId: string
if (lastEventId) {
startId = lastEventId
- } else if (startLatest) {
+ } else if (startLatest && !waitedForStream) {
startId = (await redisStream.getLatestStreamId()) ?? '0'
} else {
startId = '0'
diff --git a/services/agent-proxy/tests/hono/ingest-handler.test.ts b/services/agent-proxy/tests/hono/ingest-handler.test.ts
index 4e658532e1a3..68272901b0c6 100644
--- a/services/agent-proxy/tests/hono/ingest-handler.test.ts
+++ b/services/agent-proxy/tests/hono/ingest-handler.test.ts
@@ -462,6 +462,35 @@ describe('ingest-handler', () => {
expect(body).toMatchObject({ accepted: 1, duplicate: 0, last_accepted_seq: 1 })
})
+ it('writes complete NDJSON lines before the request body closes', async () => {
+ const config = makeConfig()
+ const encoder = new TextEncoder()
+ let controller!: ReadableStreamDefaultController<Uint8Array>
+ const body = new ReadableStream<Uint8Array>({
+ start(c) {
+ controller = c
+ },
+ })
+
+ const resPromise = handleIngest(makeContext({ body }), fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+
+ controller.enqueue(encoder.encode(`${JSON.stringify({ seq: 1, event: { type: 'first-live' } })}\n`))
+
+ await vi.waitFor(async () => {
+ const entries = await fakeRedis.xrange(getStreamKey(RUN_ID))
+ expect(entries).toHaveLength(1)
+ expect(entries[0]?.[1].data).toContain('"first-live"')
+ })
+
+ controller.enqueue(encoder.encode(`${JSON.stringify({ seq: 2, event: { type: 'second-live' } })}\n`))
+ controller.close()
+
+ const res = await resPromise
+ expect(res.status).toBe(200)
+ const responseBody = await decodeJson(res)
+ expect(responseBody).toMatchObject({ accepted: 2, duplicate: 0, last_accepted_seq: 2 })
+ })
+
it('accepts multiple sequential events', async () => {
const config = makeConfig()
const lines =
diff --git a/services/agent-proxy/tests/hono/sse-handler.test.ts b/services/agent-proxy/tests/hono/sse-handler.test.ts
index 41576b38726f..9fb6367b0687 100644
--- a/services/agent-proxy/tests/hono/sse-handler.test.ts
+++ b/services/agent-proxy/tests/hono/sse-handler.test.ts
@@ -633,6 +633,28 @@ describe('sse-handler', () => {
expect(body).toContain('"new"')
expect(body).toContain(SSE_EVENT_STREAM_END)
})
+
+ it('with startLatest=true reads from the beginning when the stream appears after connect', async () => {
+ vi.useFakeTimers()
+
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+
+ const bodyPromise = collect(
+ streamTaskRunEvents(streamKey, redis as unknown as Redis, { startLatest: true })
+ )
+
+ await Promise.resolve()
+ await Promise.resolve()
+ xaddData(redis, streamKey, { type: 'notification', msg: 'first-after-wait' })
+ xaddComplete(redis, streamKey)
+ await vi.advanceTimersByTimeAsync(100)
+
+ const body = await bodyPromise
+
+ expect(body).toContain('"first-after-wait"')
+ expect(body).toContain(SSE_EVENT_STREAM_END)
+ })
})
// -------------------------------------------------------------------------