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(desktop): keep a streamed message whole across server diagnostics (#98205)

Vojta Bartoš7b9ea5b263dc
diff --git a/products/desktop/packages/agent/src/session-log-writer.test.ts b/products/desktop/packages/agent/src/session-log-writer.test.ts
index 0e5364575889..57549f5fbffb 100644
--- a/products/desktop/packages/agent/src/session-log-writer.test.ts
+++ b/products/desktop/packages/agent/src/session-log-writer.test.ts
@@ -254,6 +254,43 @@ 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 });
+
+ 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" }),
+ );
+
+ await logWriter.flush(sessionId);
+
+ // A split here would reach the Slack relay as only the second half.
+ expect(logWriter.getAgentResponseParts(sessionId)).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.ts
index f148ae40c3ac..ad1402ec1140 100644
--- a/products/desktop/packages/agent/src/session-log-writer.ts
+++ b/products/desktop/packages/agent/src/session-log-writer.ts
@@ -1,7 +1,10 @@
import fs from "node:fs";
import fsp from "node:fs/promises";
import path from "node:path";
-import { serializeError } from "@posthog/shared";
+import {
+ isTranscriptNeutralNotificationMethod,
+ serializeError,
+} from "@posthog/shared";
import type { PostHogAPIClient } from "./posthog-api";
import type { StoredNotification } from "./types";
import { isEmptyContentBlock } from "./utils/acp-content";
@@ -240,7 +243,11 @@ export class SessionLogWriter {
if (this.isDirectAgentMessage(message) && session.chunkBuffer) {
supersededChunks = session.chunkBuffer;
session.chunkBuffer = undefined;
- } else {
+ } else if (
+ !isTranscriptNeutralNotificationMethod(
+ message.method as string | undefined,
+ )
+ ) {
this.emitCoalescedMessage(sessionId, session);
}
diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.ts
index 0047e0fe9e04..ef202cef97ce 100644
--- a/products/desktop/packages/core/src/sessions/sessionService.ts
+++ b/products/desktop/packages/core/src/sessions/sessionService.ts
@@ -38,6 +38,7 @@ import {
isJsonRpcResponse,
isPersistedOptionSupported,
isRateLimitError,
+ isTranscriptNeutralNotificationMethod,
isTransientUpstreamError,
isTurnEndedWithoutResponseError,
leadingSlashCommand,
@@ -1494,6 +1495,14 @@ 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;
@@ -1512,6 +1521,7 @@ function discardChunksSupersededByHydratedMessages(
};
for (const event of hydratedTurn.events) {
if (isSessionPromptEvent(event)) continue;
+ if (isTranscriptNeutralEvent(event)) continue;
const updateKind = agentMessageUpdateKind(event);
if (updateKind === "ignored") continue;
if (updateKind === "chunk") {
@@ -1548,6 +1558,9 @@ function discardChunksSupersededByHydratedMessages(
let keep = true;
if (isSessionPromptEvent(event)) {
discardChunkRun = false;
+ } else if (isTranscriptNeutralEvent(event)) {
+ // The writer's chunk buffer stays open across these, so the live
+ // position must not advance either.
} else {
const updateKind = agentMessageUpdateKind(event);
if (updateKind === "chunk") {
diff --git a/products/desktop/packages/core/src/sessions/sessionServiceHydration.test.ts b/products/desktop/packages/core/src/sessions/sessionServiceHydration.test.ts
index 27dfda38ceea..2d2df2e3f699 100644
--- a/products/desktop/packages/core/src/sessions/sessionServiceHydration.test.ts
+++ b/products/desktop/packages/core/src/sessions/sessionServiceHydration.test.ts
@@ -82,6 +82,18 @@ function turnComplete(ts: number): AcpMessage {
};
}
+function consoleLog(ts: number): AcpMessage {
+ return {
+ type: "acp_message",
+ ts,
+ message: {
+ jsonrpc: "2.0",
+ method: "_posthog/console",
+ params: { level: "debug", message: "diagnostic" },
+ },
+ };
+}
+
function storedEntry(event: AcpMessage): StoredLogEntry {
return {
type: "notification",
@@ -112,6 +124,31 @@ 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("preserves a new assistant response after an overlapping tool boundary", () => {
const boundary = toolCall("tool-1", 30);
const nextResponse = agentMessageChunk("after tool", 40);
diff --git a/products/desktop/packages/shared/src/index.ts b/products/desktop/packages/shared/src/index.ts
index f55bcc7ab438..757eefedba8f 100644
--- a/products/desktop/packages/shared/src/index.ts
+++ b/products/desktop/packages/shared/src/index.ts
@@ -373,6 +373,7 @@ export {
readMcpToolName,
readParentToolCallId,
} from "./tool-meta";
+export { isTranscriptNeutralNotificationMethod } from "./transcript-neutral-notifications";
export { TypedEventEmitter } from "./typed-event-emitter";
export { isSafeExternalUrl, isSafePostHogUrl } from "./url";
export { getCloudUrlFromRegion } from "./urls";
diff --git a/products/desktop/packages/shared/src/transcript-neutral-notifications.ts b/products/desktop/packages/shared/src/transcript-neutral-notifications.ts
new file mode 100644
index 000000000000..850563d46e3c
--- /dev/null
+++ b/products/desktop/packages/shared/src/transcript-neutral-notifications.ts
@@ -0,0 +1,31 @@
+/**
+ * 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/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}`,
+ );
+}