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 re-rendering old messages when a run resumes (#107249)

Vojta Bartoš908b101429d7
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index a44b476894f6..4029096b59b2 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9501,9 +9501,9 @@ snapshots:
scenes-app-inbox-scene--installing-self-driving--light:
hash: v1.k794b7964.fc1d6c0f35936c2a9a59fe89dbc9fdd8bae321ef4a4cba09af26626522d606eb.Ben1AjqSzgVvRph3ykOT3OusF-gZBfMIiFyONV4k6hA
scenes-app-inbox-scene--legacy--dark:
- hash: v1.k794b7964.143169747c1f614f8df808dc3cc5bee08e637eefe22c2609b562e3c38e857c62.-M69zyhY1NmS4SFgByyoWbqmHcv-1Hkogv8xCWFXT5U
+ hash: v1.k794b7964.cf7ea7c47bba3a13402d4ffca0936c08040dee5c57ddf01bf8cee89892eb2664.dShBZ3vzzVmp5DadPnsR_vMHw11m5cA6LVA9A2eFOzE
scenes-app-inbox-scene--legacy--light:
- hash: v1.k794b7964.0b27dcd61502751b4b090ad9f6dcf6f315fd00ce591c335edfe70e36aa121b7b.Hup-oWqMacI4OKYN2II-QZC-rY3zaxL2XjP699WEjEw
+ hash: v1.k794b7964.f503449990502057e4a2bf6d41dd2c94efad321503856eb11d338084507ed4fb.USiZ5UnWiaNkNJ1ci9aMi6h82TyPLJ1ASTwGfBmidj4
scenes-app-inbox-scene--legacy-report--dark:
hash: v1.k794b7964.73179e203433187821ff41208f41221b082f1ca19865fb7b26a751cffffdb633.cNaIyo_D196C9nTyUTVcxfSgwTM5ku-1KroxfCH34_s
scenes-app-inbox-scene--legacy-report--light:
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
index a992f5e8d8c7..d69da73021cc 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
@@ -1145,12 +1145,15 @@ describe('runStreamLogic', () => {
it('appends a human_message item ordered before subsequently ingested assistant frames', async () => {
await expectLogic(logic, () => {
logic.actions.pushHumanMessage('hello agent')
+ // The agent takes the send up and echoes it, which is what places the message.
+ logic.actions.ingestAcpFrame(notification('_posthog/user_message', { content: 'hello agent' }))
logic.actions.ingestAcpFrame(
sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'Hi!' } })
)
}).toFinishAllListeners()
expect(logic.values.threadItems).toHaveLength(2)
+ // The echo keeps the row the placeholder drew, rather than minting a second id.
expect(logic.values.threadItems[0]).toEqual({
id: 'human-0',
type: 'human_message',
@@ -1159,6 +1162,73 @@ describe('runStreamLogic', () => {
})
expect(logic.values.threadItems[1].type).toEqual('assistant_message')
})
+
+ it('sinks a waiting send that later frames landed on top of', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.pushHumanMessage('first')
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'chatter' } })
+ )
+ logic.actions.pushHumanMessage('second')
+ }).toFinishAllListeners()
+
+ expect(
+ logic.values.threadItems
+ .filter((item) => item.type === 'human_message' || item.type === 'assistant_message')
+ .map((item) => item.text)
+ ).toEqual(['chatter', 'first', 'second'])
+ })
+
+ it('keeps sends the agent has not taken up yet at the foot of the thread, in send order', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'still here' } })
+ )
+ logic.actions.pushHumanMessage('10')
+ logic.actions.pushHumanMessage('11')
+ // The agent takes up only the first, so the second keeps waiting below its answer.
+ logic.actions.ingestAcpFrame(notification('_posthog/turn_complete', {}))
+ logic.actions.ingestAcpFrame(notification('_posthog/user_message', { content: '10' }))
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({
+ sessionUpdate: 'agent_message',
+ messageId: 'm2',
+ content: { text: 'answer to 10' },
+ })
+ )
+ }).toFinishAllListeners()
+
+ expect(
+ logic.values.threadItems
+ .filter((item) => item.type === 'human_message' || item.type === 'assistant_message')
+ .map((item) => item.text)
+ ).toEqual(['still here', '10', 'answer to 10', '11'])
+ })
+
+ it('leaves a send typed mid-answer below the text already streaming', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.ingestAcpFrame(notification('_posthog/turn_complete', {}))
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({
+ sessionUpdate: 'agent_message',
+ messageId: 'm1',
+ content: { text: 'answering the message before' },
+ })
+ )
+ logic.actions.pushHumanMessage('typed while it worked')
+ // Taken up inside the same turn, so only the draw placed it — the foot-of-thread
+ // sink no longer covers for a message drawn in the wrong spot.
+ logic.actions.ingestAcpFrame(
+ notification('_posthog/user_message', { content: 'typed while it worked' })
+ )
+ }).toFinishAllListeners()
+
+ expect(
+ logic.values.threadItems
+ .filter((item) => item.type === 'human_message' || item.type === 'assistant_message')
+ .map((item) => item.text)
+ ).toEqual(['answering the message before', 'typed while it worked'])
+ })
})
describe('history-derived context dedupe', () => {
@@ -1631,6 +1701,123 @@ describe('runStreamLogic', () => {
expect(logic.values.threadItems.filter((item) => item.type === 'human_message')).toHaveLength(1)
})
+ it('renders a send typed while the agent was busy in the turn that answers it', async () => {
+ const answer = (messageId: string, text: string): void => {
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({ sessionUpdate: 'agent_message', messageId, content: { text } })
+ )
+ }
+ await expectLogic(logic, () => {
+ // Two sends typed over an answer to an earlier message; the agent takes them one turn each.
+ logic.actions.pushHumanMessage('first ahead')
+ answer('m1', 'answer to the message before')
+ logic.actions.ingestAcpFrame(notification('_posthog/turn_complete', {}))
+ logic.actions.pushHumanMessage('second ahead')
+ logic.actions.ingestAcpFrame(notification('_posthog/user_message', { content: 'first ahead' }))
+ answer('m2', 'answer to first')
+ logic.actions.ingestAcpFrame(notification('_posthog/turn_complete', {}))
+ logic.actions.ingestAcpFrame(notification('_posthog/user_message', { content: 'second ahead' }))
+ answer('m3', 'answer to second')
+ }).toFinishAllListeners()
+
+ expect(
+ logic.values.threadItems
+ .filter((item) => item.type === 'human_message' || item.type === 'assistant_message')
+ .map((item) => item.text)
+ ).toEqual([
+ 'answer to the message before',
+ 'first ahead',
+ 'answer to first',
+ 'second ahead',
+ 'answer to second',
+ ])
+ })
+
+ it('takes up the older of two waiting sends that read the same, and leaves the other waiting', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.pushHumanMessage('same words')
+ logic.actions.pushHumanMessage('same words')
+ logic.actions.ingestAcpFrame(notification('_posthog/turn_complete', {}))
+ // One send, echoed in both wire forms — the second form must not take the other send.
+ logic.actions.ingestAcpFrame(notification('_posthog/user_message', { content: 'same words' }))
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({
+ sessionUpdate: 'user_message_chunk',
+ content: { type: 'text', text: 'same words' },
+ })
+ )
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'answer' } })
+ )
+ }).toFinishAllListeners()
+
+ expect(
+ logic.values.threadItems
+ .filter((item) => item.type === 'human_message' || item.type === 'assistant_message')
+ .map((item) => item.text)
+ ).toEqual(['same words', 'answer', 'same words'])
+ })
+
+ it('takes up both sends that read the same when one turn answers them in sequence', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm0', content: { text: 'busy' } })
+ )
+ logic.actions.pushHumanMessage('same words')
+ logic.actions.pushHumanMessage('same words')
+ logic.actions.ingestAcpFrame(notification('_posthog/turn_complete', {}))
+ // Both sends are steered into one turn, each echoed in both wire forms.
+ for (const messageId of ['m1', 'm2']) {
+ logic.actions.ingestAcpFrame(notification('_posthog/user_message', { content: 'same words' }))
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({
+ sessionUpdate: 'user_message_chunk',
+ content: { type: 'text', text: 'same words' },
+ })
+ )
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({
+ sessionUpdate: 'agent_message',
+ messageId,
+ content: { text: `answer ${messageId}` },
+ })
+ )
+ }
+ }).toFinishAllListeners()
+
+ expect(
+ logic.values.threadItems
+ .filter((item) => item.type === 'human_message' || item.type === 'assistant_message')
+ .map((item) => item.text)
+ ).toEqual(['busy', 'same words', 'answer m1', 'same words', 'answer m2'])
+ })
+
+ it.each(['posthog', 'chunk', 'both'])(
+ 'does not double a send the agent echoes as %s a turn after the composer drew it',
+ async (format) => {
+ const persisted = notification('_posthog/user_message', { content: 'steer me' })
+ const wire = sessionUpdate({
+ sessionUpdate: 'user_message_chunk',
+ content: { type: 'text', text: 'steer me' },
+ })
+ await expectLogic(logic, () => {
+ logic.actions.pushHumanMessage('steer me')
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'busy' } })
+ )
+ // A steered or queued send is picked up in the next turn, so its echo lands past here.
+ logic.actions.ingestAcpFrame(notification('_posthog/turn_complete', {}))
+ for (const frame of format === 'both'
+ ? [persisted, wire]
+ : [format === 'chunk' ? wire : persisted]) {
+ logic.actions.ingestAcpFrame(frame)
+ }
+ }).toFinishAllListeners()
+
+ expect(logic.values.threadItems.filter((item) => item.type === 'human_message')).toHaveLength(1)
+ }
+ )
+
it.each([false, true])(
'displays a pending first message before logs arrive (readOnly=%s)',
async (readOnly) => {
@@ -2048,6 +2235,54 @@ describe('runStreamLogic', () => {
})
describe('chunk folding', () => {
+ it('keeps an answer in one bubble when a send waits between its chunks', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', messageId: 'm1', content: { text: 'Hel' } })
+ )
+ // The placeholder sinks below the whole answer before it renders, so it must not end
+ // the buffer and leave the half-written 'Hel' beside the finished text.
+ logic.actions.pushHumanMessage('typed while it wrote')
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', messageId: 'm1', content: { text: 'lo' } })
+ )
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'Hello' } })
+ )
+ }).toFinishAllListeners()
+
+ expect(logic.values.threadItems.map((item) => [item.type, item.text])).toEqual([
+ ['assistant_message', 'Hello'],
+ ['human_message', 'typed while it wrote'],
+ ])
+ })
+
+ it('keeps an answer in one bubble when the send between its chunks is echoed in the same turn', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({
+ sessionUpdate: 'agent_message_chunk',
+ messageId: 'm1',
+ content: { text: 'part one ' },
+ })
+ )
+ logic.actions.pushHumanMessage('steer')
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({
+ sessionUpdate: 'agent_message_chunk',
+ messageId: 'm1',
+ content: { text: 'part two' },
+ })
+ )
+ logic.actions.ingestAcpFrame(notification('_posthog/user_message', { content: 'steer' }))
+ }).toFinishAllListeners()
+
+ expect(logic.values.threadItems.map((item) => [item.type, item.text])).toEqual([
+ ['assistant_message', 'part one part two'],
+ ['human_message', 'steer'],
+ ])
+ })
+
it('folds distinct chunks of the same message into one growing buffer', async () => {
await expectLogic(logic, () => {
logic.actions.ingestAcpFrame(
@@ -2871,6 +3106,76 @@ describe('runStreamLogic', () => {
}
)
+ it('keeps an unconfirmed resume echo that repeats more than one saved message', () => {
+ const saved = ['Retry', 'Retry'].flatMap((content) => [
+ notification('_posthog/user_message', { content }),
+ notification('_posthog/turn_complete', {}),
+ ])
+ const unconfirmed = {
+ entry: notification('_client/human_message', { content: 'Retry' }),
+ source: 'client' as const,
+ }
+
+ const log = reconcileRunLog(saved, [unconfirmed], [], unconfirmed)
+
+ expect(
+ foldLogToThread(log.entries, { isResumeRun: false })
+ .threadItems.filter((item) => item.type === 'human_message')
+ .map((item) => item.text)
+ ).toEqual(['Retry', 'Retry', 'Retry'])
+ })
+
+ it('renders a follow-up sent to the previous run once after the successor bootstraps', async () => {
+ const run = {
+ id: 'run-2',
+ task: 'task-1',
+ stage: null,
+ branch: null,
+ status: TaskRunStatus.QUEUED,
+ environment: TaskRunEnvironment.CLOUD,
+ error_message: null,
+ output: null,
+ task_summary: null,
+ artifacts: [],
+ state: { resume_from_run_id: 'run-1' },
+ } satisfies TaskRunDetailDTOApi
+ const firstTurn = [
+ notification('_posthog/run_started', { runId: 'run-1' }),
+ notification('_posthog/user_message', { content: 'First question' }),
+ notification('_posthog/turn_complete', {}),
+ ]
+ jest.mocked(tasksRunsRetrieve).mockResolvedValue(run)
+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue(firstTurn)
+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })
+ await flushPromises()
+
+ // A follow-up typed into the still-running run-1: an optimistic echo, then the server's.
+ const wireEcho = sessionUpdate({
+ sessionUpdate: 'user_message_chunk',
+ content: { type: 'text', text: 'Follow-up' },
+ })
+ logic.actions.pushHumanMessage('Follow-up')
+ await MockStream.latest().emitMessage(wireEcho)
+ await MockStream.latest().emitMessage(notification('_posthog/turn_complete', {}))
+ logic.actions.handleTerminalStatus({ status: 'completed' })
+
+ // run-1 has since persisted the follow-up, and the next send opens run-2 over that chain.
+ jest.mocked(api.tasks.runs.getLogEntries).mockResolvedValue([
+ ...firstTurn,
+ notification('_posthog/user_message', { content: 'Follow-up' }),
+ wireEcho,
+ notification('_posthog/turn_complete', {}),
+ notification('_posthog/run_started', { runId: 'run-2' }),
+ notification('_posthog/user_message', { content: 'Next question' }),
+ ])
+ logic.actions.startOptimisticResume('Next question')
+ await expectLogic(logic, () => logic.actions.attachOptimisticResume('task-1', run)).toFinishAllListeners()
+
+ expect(
+ logic.values.threadItems.filter((item) => item.type === 'human_message').map((item) => item.text)
+ ).toEqual(['First question', 'Follow-up', 'Next question'])
+ })
+
it.each(['history', 'retained', 'buffered'])(
'preserves neutral notifications inside a coalesced range from %s',
(source) => {
@@ -4258,6 +4563,62 @@ describe('runStreamLogic', () => {
})
describe('_posthog/progress handling', () => {
+ const undeliveredFollowup = notification('_posthog/progress', {
+ step: 'followup_delivery',
+ status: 'failed',
+ label: "Couldn't deliver your message",
+ group: 'followup-delivery:m1',
+ detail: 'send_followup failed',
+ })
+
+ it('leaves an undelivered send where it was drawn instead of below the turns that follow', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.ingestAcpFrame(notification('_posthog/turn_complete', {}))
+ logic.actions.pushHumanMessage('never arrived')
+ logic.actions.ingestAcpFrame(undeliveredFollowup)
+ logic.actions.pushHumanMessage('arrived')
+ logic.actions.ingestAcpFrame(notification('_posthog/user_message', { content: 'arrived' }))
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm9', content: { text: 'answer' } })
+ )
+ }).toFinishAllListeners()
+
+ expect(
+ logic.values.threadItems
+ .filter((item) => item.type !== 'turn_separator')
+ .map((item) => [item.type, item.text ?? item.errorMessage])
+ ).toEqual([
+ ['human_message', 'never arrived'],
+ ['error', 'send_followup failed'],
+ ['human_message', 'arrived'],
+ ['assistant_message', 'answer'],
+ ])
+ })
+
+ it('gives a retry of an undelivered send its own bubble above the answer', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.ingestAcpFrame(notification('_posthog/turn_complete', {}))
+ logic.actions.pushHumanMessage('try again')
+ logic.actions.ingestAcpFrame(undeliveredFollowup)
+ logic.actions.pushHumanMessage('try again')
+ logic.actions.ingestAcpFrame(notification('_posthog/user_message', { content: 'try again' }))
+ logic.actions.ingestAcpFrame(
+ sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm9', content: { text: 'answer' } })
+ )
+ }).toFinishAllListeners()
+
+ expect(
+ logic.values.threadItems
+ .filter((item) => item.type !== 'turn_separator')
+ .map((item) => [item.type, item.text ?? item.errorMessage])
+ ).toEqual([
+ ['human_message', 'try again'],
+ ['error', 'send_followup failed'],
+ ['human_message', 'try again'],
+ ['assistant_message', 'answer'],
+ ])
+ })
+
it('folds a failed follow-up delivery into the preceding error card', async () => {
await expectLogic(logic, () => {
logic.actions.ingestAcpFrame(
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.ts
index 2cf40bfc8f74..c686dba7e35f 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts
@@ -669,11 +669,13 @@ function findLastBufferIndex(state: ThreadItem[], id: string, type: ThreadItemTy
/**
* A debug row carries a `_posthog/console` line from the agent server, and `threadItems` gates it on
* `showDebugLogs`, so for most viewers it renders nothing. Ending a streamed message on one splits
- * the answer wherever the delta happened to end, with nothing between the halves to explain it.
+ * the answer wherever the delta happened to end, with nothing between the halves to explain it. A
+ * send the agent has not taken up yet sinks below the whole answer before it renders, so it splits
+ * the halves the same way and is passed over too.
*/
-function onlyDebugRowsFollow(state: ThreadItem[], idx: number): boolean {
+function onlyDebugRowsFollow(state: ThreadItem[], idx: number, waitingIds: ReadonlySet<string>): boolean {
for (let i = idx + 1; i < state.length; i++) {
- if (state[i].type !== 'debug') {
+ if (state[i].type !== 'debug' && !waitingIds.has(state[i].id)) {
return false
}
}
@@ -1277,11 +1279,17 @@ function retainedFramesWithoutOptimisticEchoes(retained: StoredEntry[]): StoredL
})
}
+/**
+ * A follow-up persists under the run it was sent to, not the successor that bootstraps next, so a
+ * persisted turn cancels its local echo whichever run of the chain it belongs to. `unconfirmedEcho`
+ * is the one echo no persisted copy covers yet, matched by identity because the same words can
+ * arrive several times.
+ */
export function reconcileRunLog(
history: StoredLogEntry[],
retained: StoredEntry[],
buffered: StoredLogEntry[],
- optimisticRunId?: string
+ unconfirmedEcho?: StoredEntry
): RunLog {
let entries: StoredEntry[] = history.map((entry) => ({ entry, source: 'replay' }))
const coverage = new RunEventCoverage(history)
@@ -1289,7 +1297,7 @@ export function reconcileRunLog(
const rememberedHumanTexts = new Map<string, number>()
for (const entry of dedupeBufferedAgainstHistory(history, retainedFramesWithoutOptimisticEchoes(retained))) {
const text = persistedHumanText(entry)
- if (!text || (optimisticRunId && entry.source_run_id !== optimisticRunId)) {
+ if (!text) {
continue
}
if (entry.notification.method === '_posthog/user_message') {
@@ -1315,7 +1323,7 @@ export function reconcileRunLog(
survivors.forEach((entry) => survivorCounts.set(entry, (survivorCounts.get(entry) ?? 0) + 1))
for (const stored of tail) {
const { entry } = stored
- if (entry.notification.method === '_client/human_message') {
+ if (entry.notification.method === '_client/human_message' && stored !== unconfirmedEcho) {
const text = String(entry.notification.params?.content ?? '')
const saved = savedHumanCounts.get(text) ?? 0
if (saved > 0) {
@@ -1490,6 +1498,14 @@ export function foldLogToThread(
// Texts already rendered by a `_posthog/user_message`, so a later identical `user_message_chunk`
// (resume chains persist the same turn in both forms) is consumed once rather than doubled.
const rememberedHumanTexts = new Map<string, number>()
+ // Placeholders the composer drew for sends the agent has not taken up, in send order. A queued or
+ // steering send is echoed only when the agent takes it up, which is a turn later than the bubble,
+ // so the pairing outlives that turn. Text is what an echo matches on, because a client echo
+ // carries no id, and send order keeps repeated sends of one text apart.
+ const waitingSends: { id: string; text: string }[] = []
+ // Sends this turn already paired, counted per text so the same send's second wire form takes no
+ // further placeholder while a second send of that text still takes its own.
+ const pairedSends = new Map<string, number>()
let humanCount = 0
let bubbleSeq = 0
let separatorSeq = 0
@@ -1507,20 +1523,35 @@ export function foldLogToThread(
let pendingInsertionIndex: number | undefined
let bufferedAttachments: ThreadAttachment[] = []
- const pushHuman = (text: string, attachments: ThreadAttachment[] = []): void => {
+ /**
+ * A wire turn opens with its message, so that is where a message goes by default. A send the
+ * agent has not taken up opens nothing and waits `atFoot` instead. `reuseId` keeps the row React
+ * already rendered when an echo takes a placeholder's place.
+ */
+ const pushHuman = (
+ text: string,
+ attachments: ThreadAttachment[] = [],
+ placement: { atFoot?: boolean; reuseId?: string } = {}
+ ): string => {
if (options.pendingMessage?.text === text && entryRunId === options.pendingMessage.runId) {
pendingMessageSeen = true
}
const carried = [...attachments, ...bufferedAttachments]
- items = insertHumanMessageAtTurnStart(items, {
- id: `human-${humanCount++}`,
+ const item: ThreadItem = {
+ id: placement.reuseId ?? `human-${humanCount++}`,
type: 'human_message',
text,
complete: true,
...(carried.length > 0 && { attachments: carried }),
...(timestamp !== undefined && { startedAt: timestamp }),
- })
+ }
+ if (placement.atFoot) {
+ items.push(item)
+ } else {
+ items = insertHumanMessageAtTurnStart(items, item)
+ }
bufferedAttachments = []
+ return item.id
}
/**
@@ -1553,6 +1584,8 @@ export function foldLogToThread(
}
}
+ const waitingSendIds = (): ReadonlySet<string> => new Set(waitingSends.map((send) => send.id))
+
const appendChunk = (id: string, type: ThreadItemType, delta: string): void => {
const idx = findLastBufferIndex(items, id, type, false)
// Continue the matched buffer only while it's incomplete and only debug rows followed it;
@@ -1562,7 +1595,7 @@ export function foldLogToThread(
// the S3 replay always does, since the backend drops chunks), so the bare fallback id would
// collide as a React key across messages. The continuation lookup matches the `${id}@`
// prefix, so it still works.
- if (idx === -1 || items[idx].complete || !onlyDebugRowsFollow(items, idx)) {
+ if (idx === -1 || items[idx].complete || !onlyDebugRowsFollow(items, idx, waitingSendIds())) {
items.push({
id: `${id}@${bubbleSeq++}`,
type,
@@ -1647,7 +1680,13 @@ export function foldLogToThread(
}
}
- const renderLiveHuman = (rawText: string): void => {
+ /** The oldest send of this text the agent has not taken up, which is the one it takes up next. */
+ const takeWaitingPlaceholder = (text: string): string | undefined => {
+ const index = waitingSends.findIndex((send) => send.text === text)
+ return index === -1 ? undefined : waitingSends.splice(index, 1)[0].id
+ }
+
+ const renderLiveHuman = (rawText: string, remember: boolean): void => {
const { text, contextBlocks } = splitUserMessageContent(rawText)
if (!text) {
return
@@ -1655,10 +1694,40 @@ export function foldLogToThread(
// The blocks ride only the server echo (the optimistic `_client/human_message` carries the raw
// text), so push them even when the human text below dedupes against the optimistic render.
pushContextBlocks(contextBlocks)
- // The server echoes every user send live. An idle send already rendered it optimistically via
- // `_client/human_message`; a queue-drained send (dispatched with `addToThread: false`) did not,
- // so its echo is what surfaces it. Render unless the current turn already shows this message —
- // which both drops the optimistic-paired echo and dedupes a send echoed in two wire forms.
+ // A send echoed in two wire forms is one send: the `_posthog/user_message` form places it and
+ // leaves a credit the `user_message_chunk` form spends. Counting rather than flagging the text
+ // keeps a second send of the same text in one turn from reading as the first send's echo.
+ if (!remember) {
+ const paired = pairedSends.get(text) ?? 0
+ if (paired > 0) {
+ pairedSends.set(text, paired - 1)
+ return
+ }
+ }
+ // The echo says the agent took the send up, so it is what places the message: the placeholder
+ // leaves the foot of the thread and the message renders at the head of the turn it opens,
+ // keeping the attachment previews the placeholder carried. A placeholder already inside this
+ // turn is where it belongs, so it stays put.
+ const waitingId = takeWaitingPlaceholder(text)
+ if (waitingId !== undefined) {
+ if (remember) {
+ pairedSends.set(text, (pairedSends.get(text) ?? 0) + 1)
+ }
+ const index = items.findIndex((item) => item.id === waitingId)
+ if (index >= items.findLastIndex((item) => item.type === 'turn_separator') + 1) {
+ // The placeholder already sits in this turn, which is where the echo would put it.
+ return
+ }
+ if (index === -1) {
+ pushHuman(text)
+ return
+ }
+ const [placeholder] = items.splice(index, 1)
+ pushHuman(text, placeholder.attachments ?? [], { reuseId: placeholder.id })
+ return
+ }
+ // No send of ours is waiting — a drained queue from another tab, or a replayed turn the
+ // current turn already shows.
if (currentTurnHasHumanText(items, text)) {
return
}
@@ -1735,7 +1804,9 @@ export function foldLogToThread(
timestamp = !importedRun && !updateMeta?.imported && Number.isFinite(recordedAt) ? recordedAt : undefined
if (method === '_client/human_message') {
- pushHuman(String(params.content ?? ''), optimisticAttachments(params.attachments))
+ const optimisticText = String(params.content ?? '')
+ const id = pushHuman(optimisticText, optimisticAttachments(params.attachments), { atFoot: true })
+ waitingSends.push({ id, text: optimisticText })
continue
}
if (method === '_client/error') {
@@ -1763,6 +1834,7 @@ export function foldLogToThread(
...(traceId && { traceId }),
...(timestamp !== undefined && { startedAt: timestamp }),
})
+ pairedSends.clear()
continue
}
if (method === '_posthog/progress') {
@@ -1773,6 +1845,11 @@ export function foldLogToThread(
// The undelivered follow-up is a consequence of the run's error, so it rides the error
// card instead of a second failed row. Without a preceding error it becomes the card.
items = items.filter((item) => !(item.type === 'progress' && item.progressGroup === group))
+ // The notice follows the send that failed, which is the last one drawn. Retiring it
+ // stops a retry of the same text from taking its placeholder, and keeps a send that
+ // was never delivered where the composer drew it instead of sinking it below the
+ // answers that came after.
+ waitingSends.pop()
const last = items[items.length - 1]
if (last?.type === 'error' && last.variant !== 'crash') {
items[items.length - 1] = { ...last, undeliveredMessage: true }
@@ -1872,7 +1949,7 @@ export function foldLogToThread(
if (source === 'replay') {
renderReplayHuman(userText, true)
} else {
- renderLiveHuman(userText)
+ renderLiveHuman(userText, true)
}
if (Array.isArray(params.content)) {
for (const block of params.content) {
@@ -1928,7 +2005,7 @@ export function foldLogToThread(
if (source === 'replay') {
renderReplayHuman(userText, false)
} else {
- renderLiveHuman(userText)
+ renderLiveHuman(userText, false)
}
continue
}
@@ -1980,6 +2057,13 @@ export function foldLogToThread(
}
}
+ // A send the agent has not taken up sits below everything that has landed, in send order, however
+ // much arrived after the composer drew it.
+ const waiting = waitingSendIds()
+ if (waiting.size > 0) {
+ items = [...items.filter((item) => !waiting.has(item.id)), ...items.filter((item) => waiting.has(item.id))]
+ }
+
if (options.pendingMessage && !pendingMessageSeen) {
// This is a display fallback, not an optimistic send; bootstrap must still read the full log.
items.splice(pendingInsertionIndex ?? items.length, 0, {
@@ -3405,22 +3489,21 @@ export const runStreamLogic = kea<runStreamLogicType>([
}
})
const history = normalizeHistory(entries, session.runId, values.isBootstrapResumeRun)
- let retained = values.log.entries
- if (
- cache.retainedMessage &&
+ const echo = cache.retainedMessage
+ ? values.log.entries.findLast(
+ ({ entry }) =>
+ entry.notification.method === '_client/human_message' &&
+ entry.notification.params?.content === cache.retainedMessage
+ )
+ : undefined
+ const echoPersisted =
+ !!echo &&
history.some(
(entry) =>
entry.source_run_id === session.runId && persistedHumanText(entry) === cache.retainedMessage
)
- ) {
- const optimisticIndex = retained.findLastIndex(
- ({ entry }) =>
- entry.notification.method === '_client/human_message' &&
- entry.notification.params?.content === cache.retainedMessage
- )
- retained = retained.filter((_, index) => index !== optimisticIndex)
- }
- const log = reconcileRunLog(history, retained, session.buffer, session.runId)
+ const retained = echoPersisted ? values.log.entries.filter((stored) => stored !== echo) : values.log.entries
+ const log = reconcileRunLog(history, retained, session.buffer, echoPersisted ? undefined : echo)
const bufferedEntries = new Set(session.buffer)
const bufferedIds = new Set(session.buffer.flatMap((entry) => (entry.event_id ? [entry.event_id] : [])))
// Rebuild state without publishing a partial transcript or repeating live reactions.