: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(desktop): keep a streamed message whole across every wire line (#102864)
Vojta Bartoš91c27cb44517
diff --git a/products/desktop/packages/agent/src/session-log-writer.test.ts b/products/desktop/packages/agent/src/session-log-writer.test.tsindex 50683569b095..8792b1fe1ca1 100644--- a/products/desktop/packages/agent/src/session-log-writer.test.ts+++ b/products/desktop/packages/agent/src/session-log-writer.test.ts@@ -381,43 +381,107 @@ describe("SessionLogWriter", () => {},);- // The double-prefixed form is what extNotification puts on the wire.- it.each(["_posthog/console", "__posthog/usage_update"])(- "keeps a streamed message whole across an interleaved %s",- async (method) => {- const sessionId = "s1";- logWriter.register(sessionId, { taskId: "t1", runId: sessionId });+ async function partsAroundInterleavedLines(+ ...wireMessages: Record<string, unknown>[]+ ): Promise<string[] | undefined> {+ const sessionId = "s1";+ logWriter.register(sessionId, { taskId: "t1", runId: sessionId });+ logWriter.appendRawLine(+ sessionId,+ makeSessionUpdate("agent_message_chunk", {+ content: { type: "text", text: "dashboards still" },+ }),+ );+ for (const wireMessage of wireMessages) {logWriter.appendRawLine(sessionId,- makeSessionUpdate("agent_message_chunk", {- content: { type: "text", text: "dashboards still" },- }),- );- logWriter.appendRawLine(- sessionId,- JSON.stringify({ jsonrpc: "2.0", method, params: {} }),- );- logWriter.appendRawLine(- sessionId,- makeSessionUpdate("agent_message_chunk", {- content: { type: "text", text: " use that field filter" },- }),- );- logWriter.appendRawLine(- sessionId,- makeSessionUpdate("tool_call", { toolCallId: "tc1" }),+ JSON.stringify({ jsonrpc: "2.0", ...wireMessage }),);+ }+ logWriter.appendRawLine(+ sessionId,+ makeSessionUpdate("agent_message_chunk", {+ content: { type: "text", text: " use that field filter" },+ }),+ );+ logWriter.appendRawLine(+ sessionId,+ makeSessionUpdate("tool_call", { toolCallId: "tc1" }),+ );- await logWriter.flush(sessionId);+ await logWriter.flush(sessionId);+ return logWriter.getAgentResponseParts(sessionId);+ }+ // Every line of both directions of the tapped wire reaches the writer: the+ // server's own notifications, the control calls the host makes mid-run, and+ // the bare responses to them. The double-prefixed form is what+ // extNotification puts on the wire.+ it.each([+ {+ label: "a console notification",+ wireMessages: [{ method: "_posthog/console", params: {} }],+ },+ {+ label: "a double-prefixed usage update",+ wireMessages: [{ method: "__posthog/usage_update", params: {} }],+ },+ {+ label: "a session refresh call and its response",+ wireMessages: [+ { id: 7, method: "_posthog/refresh_session", params: {} },+ { id: 7, result: { refreshed: true } },+ ],+ },+ {+ label: "an unrecognized server diagnostic",+ wireMessages: [{ method: "_posthog/some_new_diagnostic", params: {} }],+ },+ ])(+ "keeps a streamed message whole across an interleaved $label",+ async ({ wireMessages }) => {// A split here would reach the Slack relay as only the second half.- expect(logWriter.getAgentResponseParts(sessionId)).toEqual([+ expect(await partsAroundInterleavedLines(...wireMessages)).toEqual(["dashboards still use that field filter",]);},);+ it.each([+ {+ // The client renders progress as a card, so the reader sees the split.+ label: "a conversation event",+ wireMessages: [+ { method: "_posthog/progress", params: { label: "Cloning" } },+ ],+ },+ {+ // A local session gets no `_posthog/turn_complete`, so this response is+ // the only signal that closes the last message of the turn.+ label: "the response to session/prompt",+ wireMessages: [+ { id: 4, method: "session/prompt", params: { prompt: [] } },+ { id: 4, result: { stopReason: "end_turn" } },+ ],+ },+ {+ // The id spaces of the two directions overlap, so a control call can+ // hold the id a later prompt reuses.+ label: "a prompt response reusing an answered control call's id",+ wireMessages: [+ { id: 4, method: "_posthog/refresh_session", params: {} },+ { id: 4, method: "session/prompt", params: { prompt: [] } },+ { id: 4, result: { stopReason: "end_turn" } },+ ],+ },+ ])("ends the message on $label", async ({ wireMessages }) => {+ expect(await partsAroundInterleavedLines(...wireMessages)).toEqual([+ "dashboards still",+ " use that field filter",+ ]);+ });+it("stamps the coalesced entry with the covered chunk id range", async () => {const sessionId = "s1";logWriter.register(sessionId, { taskId: "t1", runId: sessionId });diff --git a/products/desktop/packages/agent/src/session-log-writer.ts b/products/desktop/packages/agent/src/session-log-writer.tsindex e072391f7655..81ed39b9ebe4 100644--- a/products/desktop/packages/agent/src/session-log-writer.ts+++ b/products/desktop/packages/agent/src/session-log-writer.ts@@ -1,10 +1,7 @@import fs from "node:fs";import fsp from "node:fs/promises";import path from "node:path";-import {- isTranscriptNeutralNotificationMethod,- serializeError,-} from "@posthog/shared";+import { serializeError, TranscriptBoundaries } from "@posthog/shared";import { type PostHogAPIClient, PostHogAPIError } from "./posthog-api";import type { StoredNotification } from "./types";import { isEmptyContentBlock } from "./utils/acp-content";@@ -72,6 +69,7 @@ interface BufferedToolUpdate {interface SessionState {context: SessionContext;+ transcriptBoundaries: TranscriptBoundaries;chunkBuffer?: ChunkBuffer;lastAgentMessage?: string;currentTurnMessages: string[];@@ -176,6 +174,7 @@ export class SessionLogWriter {this.sessions.set(sessionId, {context,+ transcriptBoundaries: new TranscriptBoundaries(),currentTurnMessages: [],toolUpdateCache: new Map(),pendingRawInputSnapshots: new Map(),@@ -280,11 +279,7 @@ export class SessionLogWriter {if (this.isDirectAgentMessage(message) && session.chunkBuffer) {supersededChunks = session.chunkBuffer;session.chunkBuffer = undefined;- } else if (- !isTranscriptNeutralNotificationMethod(- message.method as string | undefined,- )- ) {+ } else if (!session.transcriptBoundaries.isNeutral(message)) {this.emitCoalescedMessage(sessionId, session);}diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.tsindex f4cd6b96e02f..c5c6a59d03ab 100644--- a/products/desktop/packages/core/src/sessions/sessionService.ts+++ b/products/desktop/packages/core/src/sessions/sessionService.ts@@ -38,7 +38,6 @@ import {isJsonRpcResponse,isPersistedOptionSupported,isRateLimitError,- isTranscriptNeutralNotificationMethod,isTransientUpstreamError,isTurnEndedWithoutResponseError,leadingSlashCommand,@@ -55,6 +54,7 @@ import {type TaskRunArtifact,type TaskRunStatus,TRANSCRIPT_TAIL_WINDOW,+ TranscriptBoundaries,} from "@posthog/shared";import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";import {@@ -1500,14 +1500,6 @@ function isSessionPromptEvent(event: AcpMessage): boolean {);}-/** Matches SessionLogWriter, which keeps one chunk buffer across these. */-function isTranscriptNeutralEvent(event: AcpMessage): boolean {- return (- isJsonRpcNotification(event.message) &&- isTranscriptNeutralNotificationMethod(event.message.method)- );-}-function finishAgentMessageChunkRun(position: AgentMessagePosition): void {if (!position.chunkRunActive) return;position.messageIndex += 1;@@ -1524,9 +1516,13 @@ function discardChunksSupersededByHydratedMessages(messageIndex: 0,chunkRunActive: false,};+ // Every line goes through the tracker in arrival order, the way the writer+ // feeds it, so the two agree on which responses answer a control call.+ const hydratedBoundaries = new TranscriptBoundaries();for (const event of hydratedTurn.events) {+ const neutral = hydratedBoundaries.isNeutral(event.message);if (isSessionPromptEvent(event)) continue;- if (isTranscriptNeutralEvent(event)) continue;+ if (neutral) continue;const updateKind = agentMessageUpdateKind(event);if (updateKind === "ignored") continue;if (updateKind === "chunk") {@@ -1552,6 +1548,7 @@ function discardChunksSupersededByHydratedMessages(chunkRunActive: false,};let discardChunkRun = false;+ const liveBoundaries = new TranscriptBoundaries();const events: AcpMessage[] = [];const eventHashes: number[] = [];for (@@ -1560,10 +1557,11 @@ function discardChunksSupersededByHydratedMessages(eventIndex += 1) {const event = liveTurn.events[eventIndex];+ const neutral = liveBoundaries.isNeutral(event.message);let keep = true;if (isSessionPromptEvent(event)) {discardChunkRun = false;- } else if (isTranscriptNeutralEvent(event)) {+ } else if (neutral) {// The writer's chunk buffer stays open across these, so the live// position must not advance either.} else {diff --git a/products/desktop/packages/core/src/sessions/sessionServiceHydration.test.ts b/products/desktop/packages/core/src/sessions/sessionServiceHydration.test.tsindex 2d2df2e3f699..646f18755df0 100644--- a/products/desktop/packages/core/src/sessions/sessionServiceHydration.test.ts+++ b/products/desktop/packages/core/src/sessions/sessionServiceHydration.test.ts@@ -94,6 +94,19 @@ function consoleLog(ts: number): AcpMessage {};}+function refreshSessionCall(ts: number): AcpMessage {+ return {+ type: "acp_message",+ ts,+ message: {+ jsonrpc: "2.0",+ id: 7,+ method: "_posthog/refresh_session",+ params: { mcpServers: [] },+ },+ };+}+function storedEntry(event: AcpMessage): StoredLogEntry {return {type: "notification",@@ -124,30 +137,35 @@ describe("resume hydration reconciliation", () => {).toEqual([]);});- it("discards both halves of a chunk run split by a server-internal notification", () => {- // The writer keeps one chunk buffer across a diagnostic, so the durable- // log holds one message where the live tail holds two chunk runs.- const diagnostic = consoleLog(20);- const completion = turnComplete(40);- const hydratedEvents = [- prompt(1, "ask", 10),- diagnostic,- agentMessage("dashboards still use that filter", 30),- completion,- ];-- expect(- reconcileLiveEventsWithHydratedEvents(- [- agentMessageChunk("dashboards still", 21),- { ...diagnostic, ts: 22 },- agentMessageChunk(" use that filter", 23),- { ...completion, ts: 41 },- ],- hydratedEvents,- ),- ).toEqual([]);- });+ it.each([+ { label: "a server-internal notification", interloper: consoleLog(20) },+ { label: "a host control call", interloper: refreshSessionCall(20) },+ ])(+ "discards both halves of a chunk run split by $label",+ ({ interloper }) => {+ // The writer keeps one chunk buffer across these, so the durable log holds+ // one message where the live tail holds two chunk runs.+ const completion = turnComplete(40);+ const hydratedEvents = [+ prompt(1, "ask", 10),+ interloper,+ agentMessage("dashboards still use that filter", 30),+ completion,+ ];++ expect(+ reconcileLiveEventsWithHydratedEvents(+ [+ agentMessageChunk("dashboards still", 21),+ { ...interloper, ts: 22 },+ agentMessageChunk(" use that filter", 23),+ { ...completion, ts: 41 },+ ],+ hydratedEvents,+ ),+ ).toEqual([]);+ },+ );it("preserves a new assistant response after an overlapping tool boundary", () => {const boundary = toolCall("tool-1", 30);diff --git a/products/desktop/packages/shared/src/index.ts b/products/desktop/packages/shared/src/index.tsindex 9d2d77c8701d..6ec04e07b5d6 100644--- a/products/desktop/packages/shared/src/index.ts+++ b/products/desktop/packages/shared/src/index.ts@@ -398,7 +398,7 @@ export {readMcpToolName,readParentToolCallId,} from "./tool-meta";-export { isTranscriptNeutralNotificationMethod } from "./transcript-neutral-notifications";+export { TranscriptBoundaries } from "./transcript-neutral-messages";export { TypedEventEmitter } from "./typed-event-emitter";export {isSafeExternalUrl,diff --git a/products/desktop/packages/shared/src/transcript-neutral-messages.ts b/products/desktop/packages/shared/src/transcript-neutral-messages.tsnew file mode 100644index 000000000000..62b1d8b60ff6--- /dev/null+++ b/products/desktop/packages/shared/src/transcript-neutral-messages.ts@@ -0,0 +1,74 @@+/**+ * Whether a line on the ACP wire may close a streamed assistant message.+ *+ * Both directions of the wire are tapped into the session log writer, which+ * groups a run of `agent_message_chunk` updates into one message and closes that+ * group when any other line arrives. Closing a message the model is still+ * streaming splits one answer into two parts, and the Slack relay posts only the+ * last part, so the reply starts mid-sentence at whatever point the stream delta+ * ended. ACP's own `session/…` requests keep their boundary meaning, because a+ * prompt and a permission request do belong in the transcript.+ *+ * A response carries no method, so its own line cannot say what it answers.+ * Tracking the outstanding `_posthog/` control calls is what separates the+ * answer to a session refresh, which must not close anything, from the+ * `session/prompt` response, which is the only turn-done signal a local session+ * gets: the Claude adapter emits `_posthog/turn_complete` from the cloud server+ * alone, so a local turn ends with chunks and that response and nothing else.+ *+ * Hydration reconciliation runs its own tracker over the same lines. If the two+ * disagree, a resumed transcript duplicates part of the answer.+ */++/**+ * An unlisted `_posthog/` notification is neutral, which is the safe side of the+ * trade: a missed boundary joins two messages, a false one loses the first.+ */+const TRANSCRIPT_EVENT_NOTIFICATION_METHODS = new Set([+ "_posthog/background_turn_complete",+ "_posthog/background_turn_started",+ "_posthog/compact_boundary",+ "_posthog/conversation_cleared",+ "_posthog/error",+ "_posthog/initialization_failed",+ "_posthog/permission_request",+ "_posthog/progress",+ "_posthog/task_complete",+ "_posthog/turn_complete",+ "_posthog/user_message",+]);++/** `extNotification` puts the double-prefixed `__posthog/…` form on the wire. */+function canonicalMethod(method: string): string {+ return method.startsWith("__posthog/") ? method.slice(1) : method;+}++export class TranscriptBoundaries {+ /**+ * Ids of `_posthog/` calls still awaiting an answer. Each side of the wire+ * numbers its own requests, so an id can name a control call and a prompt at+ * the same time; a request that is not a control call therefore drops the id+ * it reuses, and an answered call consumes its own.+ */+ private neutralCallIds = new Set<unknown>();++ isNeutral(message: { id?: unknown; method?: unknown }): boolean {+ const isCall = message.id !== undefined;+ if (typeof message.method !== "string") {+ return isCall && this.neutralCallIds.delete(message.id);+ }+ const method = canonicalMethod(message.method);+ const isPosthogMethod = method.startsWith("_posthog/");+ if (isCall) {+ if (isPosthogMethod) {+ this.neutralCallIds.add(message.id);+ } else {+ this.neutralCallIds.delete(message.id);+ }+ return isPosthogMethod;+ }+ return (+ isPosthogMethod && !TRANSCRIPT_EVENT_NOTIFICATION_METHODS.has(method)+ );+ }+}diff --git a/products/desktop/packages/shared/src/transcript-neutral-notifications.ts b/products/desktop/packages/shared/src/transcript-neutral-notifications.tsdeleted file mode 100644index 514289b81fb3..000000000000--- a/products/desktop/packages/shared/src/transcript-neutral-notifications.ts+++ /dev/null@@ -1,32 +0,0 @@-/**- * Notifications the agent server emits about itself rather than about the- * conversation. They arrive at arbitrary moments, including between two- * chunks of a message the model is still streaming, so no consumer that- * groups chunks into messages may treat one as a message boundary. The- * session log writer and hydration reconciliation share this predicate;- * if they disagree, a resumed transcript duplicates part of the answer.- *- * `_posthog/progress` is deliberately absent: the client renders it as a- * card in the transcript, so it is a visible boundary.- */-const TRANSCRIPT_NEUTRAL_NOTIFICATION_METHODS = [- "_posthog/console",- "_posthog/mode_change",- "_posthog/status",- "_posthog/task_notification",- "_posthog/usage_update",- "_posthog/resources_used",- "_posthog/rtk_savings",- "_posthog/budget_steer",- "_posthog/codex_goal",-];--/** Accepts the double-prefixed `__posthog/…` form extNotification puts on the wire. */-export function isTranscriptNeutralNotificationMethod(- method: string | undefined,-): boolean {- if (!method) return false;- return TRANSCRIPT_NEUTRAL_NOTIFICATION_METHODS.some(- (neutral) => method === neutral || method === `_${neutral}`,- );-}