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 the thread live when a user steers mid-turn (#88263)

Alessandro Pogliaghiad7753cec04b
diff --git a/products/desktop/packages/core/src/sessions/sessionEvents.test.ts b/products/desktop/packages/core/src/sessions/sessionEvents.test.ts
index 917c26370189..b939f82538a6 100644
--- a/products/desktop/packages/core/src/sessions/sessionEvents.test.ts
+++ b/products/desktop/packages/core/src/sessions/sessionEvents.test.ts
@@ -1,5 +1,9 @@
import type { ContentBlock } from "@agentclientprotocol/sdk";
-import type { AcpMessage, StoredLogEntry } from "@posthog/shared";
+import type {
+ AcpMessage,
+ OptimisticItem,
+ StoredLogEntry,
+} from "@posthog/shared";
import { describe, expect, it } from "vitest";
import { makeAttachmentUri } from "./promptContent";
@@ -13,6 +17,7 @@ import {
isAbsoluteFolderPath,
isFatalSessionError,
promptReferencesAbsoluteFolder,
+ selectEchoedOptimisticItemIds,
} from "./sessionEvents";
describe("isFatalSessionError", () => {
@@ -231,6 +236,97 @@ describe("hasSessionPromptEvent", () => {
});
});
+describe("selectEchoedOptimisticItemIds", () => {
+ // The floor is compared against stored-log positions, so the events have to
+ // be built the way a cloud commit builds them rather than by hand.
+ const promptLog = (...texts: string[]): AcpMessage[] =>
+ convertStoredEntriesToEvents(
+ texts.map((text) => ({
+ type: "notification",
+ notification: {
+ id: 1,
+ method: "session/prompt",
+ params: { prompt: [{ type: "text", text }] },
+ },
+ })) as StoredLogEntry[],
+ undefined,
+ { taskRunId: "run-1", startEntryIndex: 0 },
+ );
+ const tailItem = (id: string, content: string): OptimisticItem => ({
+ type: "user_message",
+ id,
+ content,
+ timestamp: 1,
+ pinToTop: false,
+ });
+
+ it("keeps a bubble the events carry no echo for", () => {
+ expect(
+ selectEchoedOptimisticItemIds(
+ [tailItem("o1", "steer me")],
+ promptLog("the original task"),
+ 0,
+ ),
+ ).toEqual([]);
+ });
+
+ it("drops a bubble once its echo lands", () => {
+ expect(
+ selectEchoedOptimisticItemIds(
+ [tailItem("o1", "steer me")],
+ promptLog("the original task", "steer me"),
+ 0,
+ ),
+ ).toEqual(["o1"]);
+ });
+
+ it("matches an echo that omits the bubble's attachment summary", () => {
+ expect(
+ selectEchoedOptimisticItemIds(
+ [tailItem("o1", "look at this\n\nAttached files: notes.txt")],
+ promptLog("look at this"),
+ 0,
+ ),
+ ).toEqual(["o1"]);
+ });
+
+ it("leaves a pinned bubble for the merge layer to dedupe", () => {
+ const pinned: OptimisticItem = {
+ type: "user_message",
+ id: "o1",
+ content: "the original task",
+ timestamp: 1,
+ };
+ expect(
+ selectEchoedOptimisticItemIds(
+ [pinned],
+ promptLog("the original task"),
+ 0,
+ ),
+ ).toEqual([]);
+ });
+
+ it("keeps a bubble whose repeated text only matches an already-committed prompt", () => {
+ expect(
+ selectEchoedOptimisticItemIds(
+ [tailItem("o1", "yes")],
+ promptLog("yes", "carry on"),
+ 2,
+ ),
+ ).toEqual([]);
+ });
+
+ it("retires one bubble per echo when several share the same text", () => {
+ expect(
+ selectEchoedOptimisticItemIds(
+ [tailItem("o1", "yes"), tailItem("o2", "yes")],
+ promptLog("yes"),
+ 0,
+ ),
+ ).toEqual(["o1"]);
+ });
+});
+
describe("dropEventsCoveredByTail", () => {
const noteEntry = (method: string): StoredLogEntry =>
({
diff --git a/products/desktop/packages/core/src/sessions/sessionEvents.ts b/products/desktop/packages/core/src/sessions/sessionEvents.ts
index 1af709fadd02..5bd13c449a16 100644
--- a/products/desktop/packages/core/src/sessions/sessionEvents.ts
+++ b/products/desktop/packages/core/src/sessions/sessionEvents.ts
@@ -11,6 +11,7 @@ import type {
AcpMessage,
JsonRpcMessage,
JsonRpcRequest,
+ OptimisticItem,
StoredLogEntry,
UserShellExecuteParams,
} from "@posthog/shared";
@@ -19,6 +20,7 @@ import {
isJsonRpcNotification,
isJsonRpcRequest,
} from "@posthog/shared";
+import { stripTrailingAttachmentSummary } from "../editor/cloud-prompt";
import { skillTagsToSlashCommands } from "../message-editor/skillTags";
import { isNotification, POSTHOG_NOTIFICATIONS } from "./acpNotifications";
import { extractPromptDisplayContent } from "./promptContent";
@@ -484,6 +486,60 @@ export function hasSessionPromptEventForTaskRun(
);
}
+export function isSteerPromptParams(params: unknown): boolean {
+ return (
+ (params as { _meta?: { steer?: boolean } } | undefined)?._meta?.steer ===
+ true
+ );
+}
+
+/**
+ * Ids of the tail optimistic bubbles that `events` now carries an echo for.
+ *
+ * `firstUnseenEntryIndex` is the log cursor the store had before this commit.
+ * Only entries at or beyond it can be an echo, because a rebuilt log replays
+ * the whole run: without the floor, a prompt the user sent earlier would
+ * retire a bubble whose own echo has not arrived, and a repeated "yes" would
+ * do it every time.
+ *
+ * One echo retires one bubble, so two pending bubbles sharing text need two
+ * echoes. Pinned bubbles are left alone: the initial prompt is deduped against
+ * its echo by the merge layer, which upgrades it with the server's timestamp.
+ */
+export function selectEchoedOptimisticItemIds(
+ optimisticItems: OptimisticItem[],
+ events: AcpMessage[],
+ firstUnseenEntryIndex: number,
+): string[] {
+ const echoCounts = new Map<string, number>();
+ for (const event of events) {
+ const msg = event.message;
+ if (!isJsonRpcRequest(msg) || msg.method !== "session/prompt") continue;
+ const entryIndex = getStoredLogEventPosition(event)?.entryIndex;
+ if (entryIndex === undefined || entryIndex < firstUnseenEntryIndex)
+ continue;
+ const blocks = (msg.params as { prompt?: ContentBlock[] } | undefined)
+ ?.prompt;
+ if (!blocks?.length) continue;
+ const text = extractPromptDisplayContent(blocks, {
+ filterHidden: true,
+ }).text.trim();
+ echoCounts.set(text, (echoCounts.get(text) ?? 0) + 1);
+ }
+ if (echoCounts.size === 0) return [];
+
+ const echoed: string[] = [];
+ for (const item of optimisticItems) {
+ if (item.type !== "user_message" || item.pinToTop !== false) continue;
+ const text = stripTrailingAttachmentSummary(item.content);
+ const remaining = echoCounts.get(text) ?? 0;
+ if (remaining === 0) continue;
+ echoCounts.set(text, remaining - 1);
+ echoed.push(item.id);
+ }
+ return echoed;
+}
+
/**
* Whether an event is a turn-complete notification.
*/
diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.ts
index 7790b15e8470..5ad1252903c5 100644
--- a/products/desktop/packages/core/src/sessions/sessionService.ts
+++ b/products/desktop/packages/core/src/sessions/sessionService.ts
@@ -117,9 +117,11 @@ import {
getUserShellExecutesSinceLastPrompt,
hasSessionPromptEvent,
hasSessionPromptEventForTaskRun,
+ isSteerPromptParams,
isTurnCompleteEvent,
normalizePromptToBlocks,
promptReferencesAbsoluteFolder,
+ selectEchoedOptimisticItemIds,
shellExecutesToContextBlocks,
} from "./sessionEvents";
import { selectSessionsToEvict } from "./sessionEviction";
@@ -426,6 +428,7 @@ export interface ISessionStore {
): void;
clearOptimisticItems(taskRunId: string): void;
clearTailOptimisticItems(taskRunId: string): void;
+ removeOptimisticItems(taskRunId: string, ids: string[]): void;
replaceOptimisticWithEvent(taskRunId: string, event: AcpMessage): void;
getSessionByTaskId(taskId: string): AgentSession | undefined;
getSessions(): Record<string, AgentSession>;
@@ -3255,11 +3258,11 @@ export class SessionService {
* guard ignores it without needing a marker here.
*/
private isSteerMessage(msg: AcpMessage["message"]): boolean {
- if (isJsonRpcRequest(msg) && msg.method === "session/prompt") {
- const params = msg.params as { _meta?: { steer?: boolean } } | undefined;
- return params?._meta?.steer === true;
- }
- return false;
+ return (
+ isJsonRpcRequest(msg) &&
+ msg.method === "session/prompt" &&
+ isSteerPromptParams(msg.params)
+ );
}
private finalizeTurnContent(
@@ -4970,7 +4973,7 @@ export class SessionService {
}
const commandResult = result.result as
- | { queued?: boolean; steered?: boolean; stopReason?: string }
+ | { queued?: boolean; stopReason?: string }
| undefined;
const stopReason = commandResult?.queued
? "queued"
@@ -9119,6 +9122,22 @@ export class SessionService {
}
}
+ private clearEchoedTailOptimisticItems(
+ taskRunId: string,
+ events: AcpMessage[],
+ ): void {
+ const session = this.getSessionByRunId(taskRunId);
+ if (!session?.optimisticItems.length) return;
+ const echoed = selectEchoedOptimisticItemIds(
+ session.optimisticItems,
+ events,
+ session.processedLineCount ?? 0,
+ );
+ if (echoed.length > 0) {
+ this.d.store.removeOptimisticItems(taskRunId, echoed);
+ }
+ }
+
private appendCloudTailEvents(
taskRunId: string,
entries: StoredLogEntry[],
@@ -9131,9 +9150,7 @@ export class SessionService {
startEntryIndex,
});
if (events.length === 0) return;
- if (hasSessionPromptEvent(events)) {
- this.d.store.clearTailOptimisticItems(taskRunId);
- }
+ this.clearEchoedTailOptimisticItems(taskRunId, events);
const existingEvents = this.getSessionByRunId(taskRunId)?.events;
const keptEvents = existingEvents
? dropEventsCoveredByTail(existingEvents, taskRunId, startEntryIndex)
@@ -9179,9 +9196,7 @@ export class SessionService {
? reconcileLiveEventsWithHydratedEvents(liveRunEvents, events)
: []),
];
- if (hasSessionPromptEvent(events)) {
- this.d.store.clearTailOptimisticItems(taskRunId);
- }
+ this.clearEchoedTailOptimisticItems(taskRunId, events);
this.cloudRunIdleTracker.delete(taskRunId);
// The reconciled log is the complete chain, so any hydration window is
// gone; resetting the window start also trips loadOlderCloudTranscript's
@@ -9206,9 +9221,7 @@ export class SessionService {
taskRunId,
startEntryIndex: windowStart,
});
- if (hasSessionPromptEvent(events)) {
- this.d.store.clearTailOptimisticItems(taskRunId);
- }
+ this.clearEchoedTailOptimisticItems(taskRunId, events);
this.cloudRunIdleTracker.delete(taskRunId);
// Moving the window start also trips loadOlderCloudTranscript's
// stale-window guard if a prepend was in flight, instead of duplicating
diff --git a/products/desktop/packages/core/src/sessions/sessionStore.ts b/products/desktop/packages/core/src/sessions/sessionStore.ts
index 90bbda9957de..469681044b6d 100644
--- a/products/desktop/packages/core/src/sessions/sessionStore.ts
+++ b/products/desktop/packages/core/src/sessions/sessionStore.ts
@@ -410,6 +410,18 @@ export const sessionStoreSetters = {
});
},
+ removeOptimisticItems: (taskRunId: string, ids: string[]): void => {
+ const removed = new Set(ids);
+ sessionStore.setState((state) => {
+ const session = state.sessions[taskRunId];
+ if (session) {
+ session.optimisticItems = session.optimisticItems.filter(
+ (item) => !removed.has(item.id),
+ );
+ }
+ });
+ },
+
replaceOptimisticWithEvent: (taskRunId: string, event: AcpMessage): void => {
sessionStore.setState((state) => {
const session = state.sessions[taskRunId];
diff --git a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.test.ts b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.test.ts
index 175d4b4db8aa..8c2d8ecc4a1f 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.test.ts
@@ -957,6 +957,37 @@ describe("buildConversationItems", () => {
3,
);
});
+
+ it("still settles a tool call started before a mid-turn steer", () => {
+ const steerMsg: AcpMessage = {
+ type: "acp_message",
+ ts: 3,
+ message: {
+ jsonrpc: "2.0",
+ id: 99,
+ method: "session/prompt",
+ params: {
+ _meta: { steer: true },
+ prompt: [{ type: "text", text: "change course" }],
+ },
+ },
+ };
+ const events = [
+ userPromptMsg(1, 1, "go"),
+ toolCallMsg(2, "t1"),
+ steerMsg,
+ toolUpdateMsg(4, "t1", { status: "completed" }),
+ ];
+ const result = buildConversationItems(events, true);
+
+ expect(result.completedToolCallCount).toBe(1);
+ expect(
+ result.items.filter((item) => item.type === "session_update"),
+ ).toHaveLength(1);
+ expect(
+ result.items.filter((item) => item.type === "user_message"),
+ ).toHaveLength(2);
+ });
});
describe("lastActivityAt", () => {
diff --git a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts
index 73199a0ef44e..fc0ef3a27ce7 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts
@@ -7,6 +7,7 @@ import {
POSTHOG_NOTIFICATIONS,
} from "@posthog/agent/acp-extensions";
import { extractPromptDisplayContent } from "@posthog/core/sessions/promptContent";
+import { isSteerPromptParams } from "@posthog/core/sessions/sessionEvents";
import {
type AcpMessage,
type AgentConversationEvent,
@@ -359,7 +360,11 @@ export function processEvent(
}
if (isJsonRpcRequest(msg) && msg.method === "session/prompt") {
- handlePromptRequest(b, msg, event.ts);
+ if (isSteerPromptParams(msg.params)) {
+ handleSteerPromptRequest(b, msg, event.ts);
+ } else {
+ handlePromptRequest(b, msg, event.ts);
+ }
return;
}
@@ -540,6 +545,29 @@ export function readLastTurnInfo(b: ItemBuilder): LastTurnInfo | null {
: null;
}
+function handleSteerPromptRequest(
+ b: ItemBuilder,
+ msg: { id: number | string; params?: unknown },
+ ts: number,
+) {
+ const userPrompt = extractUserPrompt(msg.params);
+
+ if (
+ userPrompt.content.trim().length === 0 &&
+ userPrompt.attachments.length === 0
+ ) {
+ return;
+ }
+
+ b.items.push({
+ type: "user_message",
+ id: `steer-${ts}-${msg.id}`,
+ content: userPrompt.content,
+ timestamp: ts,
+ attachments: userPrompt.attachments,
+ });
+}
+
function handlePromptRequest(
b: ItemBuilder,
msg: { id: number | string; params?: unknown },
diff --git a/products/desktop/packages/ui/src/features/sessions/components/incrementalConversationItems.test.ts b/products/desktop/packages/ui/src/features/sessions/components/incrementalConversationItems.test.ts
index a93814b7ac8a..e2e6e94e4e21 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/incrementalConversationItems.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/incrementalConversationItems.test.ts
@@ -31,6 +31,19 @@ function userPromptMsg(ts: number, id: number, text: string): AcpMessage {
};
}
+function steerPromptMsg(ts: number, id: number, text: string): AcpMessage {
+ return {
+ type: "acp_message",
+ ts,
+ message: {
+ jsonrpc: "2.0",
+ id,
+ method: "session/prompt",
+ params: { _meta: { steer: true }, prompt: [{ type: "text", text }] },
+ },
+ };
+}
+
function promptResponseMsg(
ts: number,
id: number,
@@ -289,6 +302,18 @@ const SCENARIOS: Record<string, AcpMessage[]> = {
agentChunk(3, " — done"),
promptResponseMsg(4, 1),
],
+ "mid-turn steer folded into the running turn": [
+ userPromptMsg(1, 1, "do a thing"),
+ toolCallMsg(2, "t1"),
+ steerPromptMsg(3, 99, "actually do it differently"),
+ promptResponseMsg(4, 99, "steered"),
+ toolUpdateMsg(5, "t1", {
+ status: "completed",
+ content: [{ type: "content", content: { type: "text", text: "ok" } }],
+ }),
+ agentChunk(6, "adjusting"),
+ promptResponseMsg(7, 1),
+ ],
};
const EQUIVALENCE_CASES = Object.entries(SCENARIOS).flatMap(([name, events]) =>
diff --git a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
index a44c350da84e..72aa5657c92f 100644
--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
@@ -433,11 +433,13 @@ vi.mock("@posthog/core/sessions/sessionEvents", async () => {
isAbsoluteFolderPath: actual.isAbsoluteFolderPath,
isFatalSessionError: actual.isFatalSessionError,
isRateLimitError: actual.isRateLimitError,
+ isSteerPromptParams: actual.isSteerPromptParams,
isTurnCompleteEvent: actual.isTurnCompleteEvent,
normalizePromptToBlocks: vi.fn((p) =>
typeof p === "string" ? [{ type: "text", text: p }] : p,
),
promptReferencesAbsoluteFolder: actual.promptReferencesAbsoluteFolder,
+ selectEchoedOptimisticItemIds: actual.selectEchoedOptimisticItemIds,
shellExecutesToContextBlocks: vi.fn(() => []),
};
});