: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 mid-turn messages in the right place (#81065)
Adam Leithf96311f03fc3
diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.tsindex feb6e2a19ca4..502e3225ccaa 100644--- a/products/desktop/packages/core/src/sessions/sessionService.ts+++ b/products/desktop/packages/core/src/sessions/sessionService.ts@@ -134,6 +134,24 @@ const MAX_RESPONDED_PERMISSION_REQUEST_IDS = 500;* imperceptible for streamed text.*/const SESSION_EVENT_FLUSH_MS = 16;+/**+ * Steering an adapter that can't fold a message into a running turn leaves only+ * one way in: interrupt it. Cancelling the instant the user hits send cuts off+ * whatever sentence was streaming, so wait for the agent's output to go quiet+ * this long first. Several flush ticks of silence, not a pause between tokens.+ */+const STEER_INTERRUPT_QUIET_MS = 250;+/**+ * Ceiling on that wait, so an agent that streams without pausing still gets+ * interrupted instead of holding the user's message indefinitely.+ */+const STEER_INTERRUPT_MAX_WAIT_MS = 1_500;++/** The turn a steer was aimed at, so the interrupt cannot land on a later one. */+interface SteeredTurn {+ taskRunId: string;+ promptId: number | null;+}/*** A backgrounded session's transcript is freed this long after it stops being* viewed, and reloaded from disk on return. Only disconnected (idle, no live@@ -1283,6 +1301,25 @@ function discardExactHydratedEvents(return liveTurn.events.filter((_event, index) => keep[index]);}+/**+ * Whether the event is the agent emitting text — what a user watches arrive+ * token by token. Tool calls, progress and status updates are not: nothing is+ * mid-sentence, so there is nothing to wait out before interrupting.+ */+function isAgentTextStreamEvent(event: AcpMessage): boolean {+ const message = event.message;+ if (!isJsonRpcNotification(message) || message.method !== "session/update") {+ return false;+ }+ const sessionUpdate = (+ message.params as { update?: { sessionUpdate?: string } } | undefined+ )?.update?.sessionUpdate;+ return (+ sessionUpdate === "agent_message_chunk" ||+ sessionUpdate === "agent_thought_chunk"+ );+}+function agentMessageUpdateKind(event: AcpMessage,): "final" | "chunk" | "ignored" | undefined {@@ -2586,8 +2623,15 @@ export class SessionService {* within a taskRunId is preserved; taskRunIds are independent. */private pendingSessionEvents = new Map<string, AcpMessage[]>();private sessionEventFlushHandle: ReturnType<typeof setTimeout> | null = null;+ /** When each run last streamed agent text. Read by the steer fallback so its+ * interrupt lands between sentences rather than mid-token. Recorded on+ * arrival, not on flush, so the buffering delay doesn't read as silence. */+ private lastAgentTextAt = new Map<string, number>();private enqueueSessionEvent(taskRunId: string, acpMsg: AcpMessage): void {+ if (isAgentTextStreamEvent(acpMsg)) {+ this.lastAgentTextAt.set(taskRunId, Date.now());+ }const buffered = this.pendingSessionEvents.get(taskRunId);if (buffered) {buffered.push(acpMsg);@@ -2787,6 +2831,7 @@ export class SessionService {this.subscriptions.delete(taskRunId);this.liveTurnContent.delete(taskRunId);this.agentSpokeAt.delete(taskRunId);+ this.lastAgentTextAt.delete(taskRunId);// Drop any speak calls still mid-stream for this run (never reached a// terminal status, so they were never enqueued or deleted above).this.speakCalls.delete(taskRunId);@@ -3575,7 +3620,27 @@ export class SessionService {}}if (!session.isCloud) {- await this.cancelPrompt(taskId);+ // Nothing folds the message into the running turn here, so the turn has+ // to end for it to land. Let the output in flight finish first —+ // cancelling on the keystroke truncates the sentence being read.+ const steeredTurn: SteeredTurn = {+ taskRunId: session.taskRunId,+ promptId: session.currentPromptId ?? null,+ };+ await this.waitForAgentTextToSettle(taskId, steeredTurn);+ // Only the turn the user steered against may be interrupted. If it+ // ended while we waited, a queued message can already have started the+ // next one, and cancelling that would cut off a message the user never+ // steered. Falling through queues this message behind it instead.+ //+ // A snapshot is enough even though the cancel is async: it is+ // dispatched in this same synchronous step, while a replacement turn+ // can only be dispatched once a later event flush reports this one+ // ended. Ordered transport then puts `session/cancel` at the agent+ // first, so a cancel can never overtake the turn that replaces this.+ if (this.isSteeredTurnStillRunning(taskId, steeredTurn)) {+ await this.cancelPrompt(taskId);+ }const refreshed = this.d.store.getSessionByTaskId(taskId);if (refreshed) {session = refreshed;@@ -3667,6 +3732,52 @@ export class SessionService {});}+ /**+ * Whether the turn a steer was aimed at is still the one running. `taskId`+ * outlives any single turn, so it cannot answer this on its own: a turn that+ * ends lets a queued message start a new one under the same task, and+ * `currentPromptId` is what tells the two apart.+ */+ private isSteeredTurnStillRunning(+ taskId: string,+ turn: SteeredTurn,+ ): boolean {+ const session = this.d.store.getSessionByTaskId(taskId);+ return (+ session?.isPromptPending === true &&+ session.taskRunId === turn.taskRunId &&+ (session.currentPromptId ?? null) === turn.promptId+ );+ }++ /**+ * Resolve once the agent's streamed text has been quiet for+ * {@link STEER_INTERRUPT_QUIET_MS}, the steered turn has stopped running, or+ * {@link STEER_INTERRUPT_MAX_WAIT_MS} has elapsed. Returns straight away when+ * nothing is streaming — the common case, since a steer usually arrives while+ * the agent is inside a tool call rather than mid-sentence.+ */+ private async waitForAgentTextToSettle(+ taskId: string,+ turn: SteeredTurn,+ ): Promise<void> {+ const deadline = Date.now() + STEER_INTERRUPT_MAX_WAIT_MS;+ for (;;) {+ if (!this.isSteeredTurnStillRunning(taskId, turn)) return;+ // A run that has never streamed text is quiet by definition, whatever the+ // clock reads.+ const quietFor =+ Date.now() -+ (this.lastAgentTextAt.get(turn.taskRunId) ?? Number.NEGATIVE_INFINITY);+ const wait = Math.min(+ STEER_INTERRUPT_QUIET_MS - quietFor,+ deadline - Date.now(),+ );+ if (wait <= 0) return;+ await new Promise((resolve) => setTimeout(resolve, wait));+ }+ }+/*** Send a steer message: folded into the turn already running rather than* queued. It renders when its `session/prompt` echo arrives and is injecteddiff --git a/products/desktop/packages/core/src/sessions/sessionServiceSteerInterrupt.test.ts b/products/desktop/packages/core/src/sessions/sessionServiceSteerInterrupt.test.tsnew file mode 100644index 000000000000..970f102d4f0b--- /dev/null+++ b/products/desktop/packages/core/src/sessions/sessionServiceSteerInterrupt.test.ts@@ -0,0 +1,243 @@+import type { AcpMessage, AgentSession } from "@posthog/shared";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { SessionService, type SessionServiceDeps } from "./sessionService";++const TASK_ID = "task-1";+const RUN_ID = "run-1";+const QUIET_MS = 250;+const MAX_WAIT_MS = 1_500;++function agentTextChunk(text: string): AcpMessage {+ return {+ ts: 1,+ message: {+ jsonrpc: "2.0",+ method: "session/update",+ params: {+ sessionId: RUN_ID,+ update: {+ sessionUpdate: "agent_message_chunk",+ content: { type: "text", text },+ },+ },+ },+ } as unknown as AcpMessage;+}++function toolCallUpdate(): AcpMessage {+ return {+ ts: 1,+ message: {+ jsonrpc: "2.0",+ method: "session/update",+ params: {+ sessionId: RUN_ID,+ update: {+ sessionUpdate: "tool_call",+ toolCallId: "t1",+ status: "in_progress",+ title: "Bash",+ },+ },+ },+ } as unknown as AcpMessage;+}++function createHarness() {+ const sessions: Record<string, AgentSession> = {+ [RUN_ID]: {+ taskRunId: RUN_ID,+ taskId: TASK_ID,+ taskTitle: "Local Task",+ events: [],+ messageQueue: [],+ pendingPermissions: new Map(),+ status: "connected",+ startedAt: 0,+ currentPromptId: 1,+ // No native steering, so a mid-turn message can only land by interrupting.+ steering: "interrupt-resend",+ adapter: "codex",+ isCloud: false,+ isPromptPending: true,+ isCompacting: false,+ } as unknown as AgentSession,+ };++ const store = {+ getSessions: () => sessions,+ getSessionByTaskId: (taskId: string) =>+ Object.values(sessions).find((s) => s.taskId === taskId),+ setSession: (session: AgentSession) => {+ sessions[session.taskRunId] = session;+ },+ updateSession: (taskRunId: string, updates: Partial<AgentSession>) => {+ const session = sessions[taskRunId];+ if (session) sessions[taskRunId] = { ...session, ...updates };+ },+ appendEvents: vi.fn(),+ replaceOptimisticWithEvent: vi.fn(),+ setPendingPermissions: vi.fn(),+ clearMessageQueue: vi.fn(),+ clearTailOptimisticItems: vi.fn(),+ clearOptimisticItems: vi.fn(),+ appendOptimisticItem: vi.fn(),+ enqueueMessage: vi.fn(),+ };++ const cancelPrompt = vi.fn(async () => true);+ const prompt = vi.fn(async () => ({ stopReason: "end_turn" }));+ let onEvent: ((payload: unknown) => void) | undefined;++ const deps = {+ store,+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },+ track: vi.fn(),+ getIsOnline: () => true,+ addDirectoryDialog: { open: false },+ notifyPromptComplete: vi.fn(),+ notifyPermissionRequest: vi.fn(),+ enqueueSpeech: vi.fn(),+ toast: { error: vi.fn(), success: vi.fn() },+ usageLimit: { show: vi.fn() },+ taskViewedApi: { markActivity: vi.fn() },+ h: { extractSkillButtonId: () => undefined },+ getPersistedConfigOptions: () => undefined,+ setPersistedConfigOptions: vi.fn(),+ trpc: {+ agent: {+ prompt: { mutate: prompt },+ cancelPrompt: { mutate: cancelPrompt },+ onSessionEvent: {+ subscribe: (+ _input: unknown,+ handlers: { onData: (payload: unknown) => void },+ ) => {+ onEvent = handlers.onData;+ return { unsubscribe: vi.fn() };+ },+ },+ onPermissionRequest: { subscribe: () => ({ unsubscribe: vi.fn() }) },+ onSessionIdleKilled: { subscribe: () => ({ unsubscribe: vi.fn() }) },+ },+ },+ } as unknown as SessionServiceDeps;++ const service = new SessionService(deps);+ (+ service as unknown as { subscribeToChannel(id: string): void }+ ).subscribeToChannel(RUN_ID);+ if (!onEvent) throw new Error("subscribeToChannel did not subscribe");++ return {+ service,+ cancelPrompt,+ prompt,+ emit: (event: AcpMessage) => onEvent?.(event),+ endTurn: () =>+ store.updateSession(RUN_ID, {+ isPromptPending: false,+ currentPromptId: null,+ }),+ // The turn ends and a message queued earlier immediately starts the next+ // one, which is what the turn-end drain does via its zero-delay timer.+ endTurnAndStartQueued: () => {+ store.updateSession(RUN_ID, {+ isPromptPending: false,+ currentPromptId: null,+ });+ setTimeout(() => {+ store.updateSession(RUN_ID, { isPromptPending: true });+ }, 0);+ },+ isPromptPending: () => sessions[RUN_ID].isPromptPending,+ steer: () =>+ service.sendPrompt(TASK_ID, "actually, do it the other way", {+ steer: true,+ }),+ };+}++describe("steering an adapter without native steering", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ it("waits for streamed text to go quiet before interrupting", async () => {+ const h = createHarness();+ h.emit(agentTextChunk("Let me explain"));++ const sent = h.steer();++ await vi.advanceTimersByTimeAsync(QUIET_MS - 50);+ expect(h.cancelPrompt).not.toHaveBeenCalled();++ // More text arrives, so the quiet window restarts rather than elapsing.+ h.emit(agentTextChunk(" the approach"));+ await vi.advanceTimersByTimeAsync(QUIET_MS - 50);+ expect(h.cancelPrompt).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(QUIET_MS);+ await sent;+ expect(h.cancelPrompt).toHaveBeenCalledTimes(1);+ expect(h.prompt).toHaveBeenCalledTimes(1);+ });++ it("interrupts without waiting when no text is streaming", async () => {+ const h = createHarness();+ // A tool call is running: nothing is mid-sentence to cut off.+ h.emit(toolCallUpdate());++ await h.steer();++ expect(h.cancelPrompt).toHaveBeenCalledTimes(1);+ expect(h.prompt).toHaveBeenCalledTimes(1);+ });++ it("interrupts at the ceiling when text never stops", async () => {+ const h = createHarness();+ h.emit(agentTextChunk("..."));+ const streaming = setInterval(() => h.emit(agentTextChunk("...")), 50);++ const sent = h.steer();+ await vi.advanceTimersByTimeAsync(MAX_WAIT_MS - 100);+ expect(h.cancelPrompt).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(200);+ clearInterval(streaming);+ await sent;+ expect(h.cancelPrompt).toHaveBeenCalledTimes(1);+ });++ // The steered turn ending hands the session to a message queued earlier.+ // Both flips land inside one sleep, so the wait never sees the idle gap and+ // only the turn's identity distinguishes the new turn from the steered one.+ it("does not interrupt a queued turn that starts while waiting", async () => {+ const h = createHarness();+ h.emit(agentTextChunk("wrapping up"));++ const sent = h.steer();+ h.endTurnAndStartQueued();++ await vi.advanceTimersByTimeAsync(QUIET_MS * 2);+ await sent;+ expect(h.isPromptPending()).toBe(true);+ expect(h.cancelPrompt).not.toHaveBeenCalled();+ });++ it("skips the interrupt when the turn ends while waiting", async () => {+ const h = createHarness();+ h.emit(agentTextChunk("wrapping up"));++ const sent = h.steer();+ h.endTurn();++ await vi.advanceTimersByTimeAsync(QUIET_MS * 2);+ await sent;+ expect(h.cancelPrompt).not.toHaveBeenCalled();+ expect(h.prompt).toHaveBeenCalledTimes(1);+ });+});diff --git a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.tsindex 44042029b485..c361163a0435 100644--- a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts+++ b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts@@ -227,6 +227,30 @@ export interface BuildConversationOptions {showDebugLogs?: boolean;}+/**+ * The single ordering policy every conversation builder reads events in:+ * ascending timestamp, ties keeping arrival order (`Array.sort` is stable).+ * Returns `events` untouched when it already ascends — the normal streaming+ * case — so the common path costs a scan rather than a copy and a sort.+ *+ * Both full builders and the incremental one must agree here, or the same+ * transcript renders in one order while a turn streams and another once it+ * settles.+ */+export function orderEventsByTimestamp<T>(+ events: T[],+ timestampOf: (event: T) => number,+): T[] {+ for (let i = 1; i < events.length; i++) {+ if (timestampOf(events[i]) < timestampOf(events[i - 1])) {+ return events.toSorted(+ (left, right) => timestampOf(left) - timestampOf(right),+ );+ }+ }+ return events;+}+export function buildConversationItems(events: AcpMessage[],isPromptPending: boolean | null,@@ -234,13 +258,7 @@ export function buildConversationItems(): BuildResult {const b = createItemBuilder();- let ordered = events;- for (let i = 1; i < events.length; i++) {- if (events[i].ts < events[i - 1].ts) {- ordered = [...events].sort((a, b) => a.ts - b.ts);- break;- }- }+ const ordered = orderEventsByTimestamp(events, (event) => event.ts);for (const event of ordered) {processEvent(b, event, options);}@@ -295,9 +313,7 @@ export function buildAgentConversationItems(isPromptPending: boolean | null,): BuildResult {const b = createItemBuilder();- const ordered = [...events].sort(- (left, right) => left.timestamp - right.timestamp,- );+ const ordered = orderEventsByTimestamp(events, (event) => event.timestamp);for (const event of ordered) {processAgentConversationEvent(b, event);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.tsindex d74626172a99..330830ff7bb8 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@@ -279,6 +279,15 @@ const SCENARIOS: Record<string, AcpMessage[]> = {agentChunk(5, "out"),promptResponseMsg(6, 1),],+ // The prompt echo reaches the client after the reply it prompted. Rendering+ // in arrival order would put the agent above the user's own message until the+ // turn ended and the thread re-sorted.+ "prompt echo arriving after the reply": [+ agentChunk(2, "on it"),+ userPromptMsg(1, 1, "hello"),+ agentChunk(3, " — done"),+ promptResponseMsg(4, 1),+ ],};const EQUIVALENCE_CASES = Object.entries(SCENARIOS).flatMap(([name, events]) =>@@ -345,9 +354,9 @@ describe("createIncrementalConversationBuilder", () => {);});- // A full rebuild sorts by ts while the incremental builder processed arrival- // order, so out-of-order events must reject finalize-in-place and fall back.- it("falls back to a full rebuild on out-of-order timestamps at idle", () => {+ // Both builders read events in ts-order, so a late arrival mid-stream must+ // leave the streamed transcript and the finalized one in the same order.+ it("stays equivalent when a timestamp arrives out of order", () => {const events = [userPromptMsg(1, 1, "hello"),agentChunk(5, "later "),diff --git a/products/desktop/packages/ui/src/features/sessions/components/incrementalConversationItems.ts b/products/desktop/packages/ui/src/features/sessions/components/incrementalConversationItems.tsindex b4bb784120a8..ecc91b919a68 100644--- a/products/desktop/packages/ui/src/features/sessions/components/incrementalConversationItems.ts+++ b/products/desktop/packages/ui/src/features/sessions/components/incrementalConversationItems.ts@@ -8,11 +8,31 @@ import {finalizeBuilder,type ItemBuilder,markThoughtCompletion,+ orderEventsByTimestamp,processEvent,readLastTurnInfo,type TurnContext,} from "./buildConversationItems";+/**+ * Whether feeding `events[from..]` to the builder keeps the sequence it has+ * already consumed in ascending timestamp order. `lastTs` is the timestamp of+ * the last event fed, so a late arrival that belongs earlier in the transcript+ * fails here and forces a re-read of the whole array in sorted order.+ */+function extendsTimestampOrder(+ events: AcpMessage[],+ from: number,+ lastTs: number,+): boolean {+ let previous = lastTs;+ for (let i = from; i < events.length; i++) {+ if (events[i].ts < previous) return false;+ previous = events[i].ts;+ }+ return true;+}+/*** Incremental front end for `buildConversationItems`.*@@ -35,12 +55,15 @@ export function createIncrementalConversationBuilder() {let firstEventRef: AcpMessage | null = null;let boundaryEventRef: AcpMessage | null = null;let showDebugLogs: boolean | undefined;+ /** Timestamp of the last event fed to `b`, so a late arrival is detectable. */+ let lastProcessedTs = Number.NEGATIVE_INFINITY;function reset() {b = null;processedCount = 0;firstEventRef = null;boundaryEventRef = null;+ lastProcessedTs = Number.NEGATIVE_INFINITY;}function update(@@ -52,25 +75,18 @@ export function createIncrementalConversationBuilder() {// Idle (not streaming): finalize the persistent builder in place instead of// re-parsing every event, but only when the append-only prefix is still- // valid AND events are already in ts-order — a full rebuild sorts, while the- // incremental builder processed in arrival order, so out-of-order events- // must fall back to keep output identical.+ // valid AND the events arriving with the idle flip carry on in ts-order.+ // Whatever the builder already consumed is in ts-order by construction, so+ // only the catch-up tail needs checking.if (isPromptPending === false) {- let inOrder = true;- for (let i = 1; i < events.length; i++) {- if (events[i].ts < events[i - 1].ts) {- inOrder = false;- break;- }- }const canFinalizeInPlace =- inOrder &&b !== null &&debug === showDebugLogs &&events.length >= processedCount &&(processedCount === 0 || events[0] === firstEventRef) &&(processedCount === 0 ||- events[processedCount - 1] === boundaryEventRef);+ events[processedCount - 1] === boundaryEventRef) &&+ extendsTimestampOrder(events, processedCount, lastProcessedTs);if (canFinalizeInPlace) {const builder = b as ItemBuilder;@@ -96,26 +112,41 @@ export function createIncrementalConversationBuilder() {// The fast path is valid only when this call appends to the exact prefix we// already processed (events is append-only during streaming, immer hands us- // a new array each push but keeps element identity).+ // a new array each push but keeps element identity) and the new events carry+ // on in ts-order. An event that lands behind what we already consumed would+ // otherwise render where it arrived rather than where it belongs — a user's+ // own message sitting under the reply it prompted, until the turn ended and+ // the thread re-sorted underneath them.const canAppend =b !== null &&debug === showDebugLogs &&events.length >= processedCount &&(processedCount === 0 || events[0] === firstEventRef) &&- (processedCount === 0 || events[processedCount - 1] === boundaryEventRef);+ (processedCount === 0 ||+ events[processedCount - 1] === boundaryEventRef) &&+ extendsTimestampOrder(events, processedCount, lastProcessedTs);if (!canAppend) {b = createItemBuilder();processedCount = 0;+ lastProcessedTs = Number.NEGATIVE_INFINITY;showDebugLogs = debug;}const builder = b as ItemBuilder;builder.lowestTouchedProgressIndex = Number.POSITIVE_INFINITY;- for (let i = processedCount; i < events.length; i++) {- processEvent(builder, events[i], options);+ // A rebuild re-reads the whole array, so order it first. An append continues+ // a sequence already in ts-order and takes the new events as they came.+ const ordered =+ processedCount === 0+ ? orderEventsByTimestamp(events, (event) => event.ts)+ : events;+ for (let i = processedCount; i < ordered.length; i++) {+ processEvent(builder, ordered[i], options);}processedCount = events.length;+ lastProcessedTs =+ ordered[ordered.length - 1]?.ts ?? Number.NEGATIVE_INFINITY;firstEventRef = events[0] ?? null;boundaryEventRef = events[processedCount - 1] ?? null;