: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): prevent steering during resume startup (#83092)
Alessandro Pogliaghi72f7bde06241
diff --git a/products/desktop/packages/agent/src/server/agent-server.test.ts b/products/desktop/packages/agent/src/server/agent-server.test.tsindex b56be4e4f640..93b1b37c7448 100644--- a/products/desktop/packages/agent/src/server/agent-server.test.ts+++ b/products/desktop/packages/agent/src/server/agent-server.test.ts@@ -2778,6 +2778,90 @@ describe("AgentServer HTTP Mode", () => {expect(resetTurnMessages).not.toHaveBeenCalled();}, 20000);+ it("declines steering while an initial or resume turn is starting", async () => {+ const s = createServer();+ await s.start();+ const prompt = vi.fn();+ const serverInternals = s as unknown as {+ activeOwnedTurnCount: number;+ activeStartupTurnCount: number;+ session: { clientConnection: { prompt: typeof prompt } };+ };+ serverInternals.activeOwnedTurnCount = 1;+ serverInternals.activeStartupTurnCount = 1;+ serverInternals.session.clientConnection.prompt = prompt;++ const response = await fetch(`http://localhost:${port}/command`, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${createToken()}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ jsonrpc: "2.0",+ id: "steer-during-resume",+ method: "user_message",+ params: {+ content: "status?",+ messageId: "steer-during-resume",+ steer: true,+ },+ }),+ });++ expect(response.status).toBe(200);+ await expect(response.json()).resolves.toMatchObject({+ result: { stopReason: "steer_declined", steered: false },+ });+ expect(prompt).not.toHaveBeenCalled();+ }, 20000);++ it("declines steering while a prewarmed first turn is starting", async () => {+ const s = createServer();+ await s.start();+ let finishTurn!: (result: { stopReason: "end_turn" }) => void;+ const prompt = vi.fn(+ () =>+ new Promise<{ stopReason: "end_turn" }>((resolve) => {+ finishTurn = resolve;+ }),+ );+ const serverInternals = s as unknown as {+ prewarmedStartupTurnPending: boolean;+ session: { clientConnection: { prompt: typeof prompt } };+ };+ serverInternals.prewarmedStartupTurnPending = true;+ serverInternals.session.clientConnection.prompt = prompt;++ const token = createToken();+ const send = (id: string, steer = false) =>+ fetch(`http://localhost:${port}/command`, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${token}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ jsonrpc: "2.0",+ id,+ method: "user_message",+ params: { content: id, messageId: id, ...(steer && { steer }) },+ }),+ });++ const firstTurn = send("first-turn");+ await vi.waitFor(() => expect(prompt).toHaveBeenCalledOnce());++ const steerResponse = await send("steer-during-first-turn", true);+ await expect(steerResponse.json()).resolves.toMatchObject({+ result: { stopReason: "steer_declined", steered: false },+ });+ expect(prompt).toHaveBeenCalledOnce();++ finishTurn({ stopReason: "end_turn" });+ await firstTurn;+ }, 20000);+it("does not queue steering behind an active non-steering turn", async () => {const s = createServer();await s.start();diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.tsindex 5ce099fc21c6..d1c179d7a1a3 100644--- a/products/desktop/packages/agent/src/server/agent-server.ts+++ b/products/desktop/packages/agent/src/server/agent-server.ts@@ -447,6 +447,7 @@ export class AgentServer {// --autoPublish flag can't carry the user's choice; it is resolved from run// state when the first message arrives (see resolveWarmActivationSettings).private prewarmedRun = false;+ private prewarmedStartupTurnPending = false;private warmAutoPublishResolved = false;private warmReasoningEffortResolved = false;private installedSkillBundles = new Set<string>();@@ -465,6 +466,7 @@ export class AgentServer {private pendingCompactContinuationMessageIds = new Set<string>();private inFlightMessageDeliveries = new Map<string, Promise<unknown>>();private activeOwnedTurnCount = 0;+ private activeStartupTurnCount = 0;// Normal follow-ups own turns in arrival order. Explicit steering bypasses// this tail so it can still reach the active adapter turn immediately.private nonSteerDeliveryTail: Promise<void> = Promise.resolve();@@ -1221,7 +1223,10 @@ export class AgentServer {};if (params.steer === true) {- if (this.activeOwnedTurnCount > 0) {+ if (+ this.activeOwnedTurnCount > 0 &&+ this.activeStartupTurnCount === 0+ ) {const result = await commandSession.clientConnection.prompt({sessionId: commandSession.acpSessionId,prompt,@@ -1271,7 +1276,7 @@ export class AgentServer {this.pendingCompactContinuationMessageIds.delete(messageId);}} else {- result = await this.runOwnedTurn(() => {+ const runPrompt = () => {const promptResult = commandSession.clientConnection.prompt({sessionId: commandSession.acpSessionId,prompt,@@ -1283,7 +1288,13 @@ export class AgentServer {throw new Error("Agent connection did not accept the prompt");}return promptResult;- });+ };+ if (this.prewarmedStartupTurnPending) {+ this.prewarmedStartupTurnPending = false;+ result = await this.runStartupTurn(runPrompt);+ } else {+ result = await this.runOwnedTurn(runPrompt);+ }if (result.stopReason === "end_turn" && manualCompactPrompt) {commitDelivery();@@ -1602,6 +1613,7 @@ export class AgentServer {this.nativeResume = null;this.preSessionEvents = [];this.prewarmedRun = false;+ this.prewarmedStartupTurnPending = false;this.warmAutoPublishResolved = false;this.warmReasoningEffortResolved = false;@@ -1641,6 +1653,7 @@ export class AgentServer {this.prewarmedRun =(preTaskRun?.state as Record<string, unknown> | undefined)?.prewarmed ===true;+ this.prewarmedStartupTurnPending = this.prewarmedRun;const gatewayEnv = this.configureEnvironment({isInternal: preTask?.internal === true,@@ -2064,6 +2077,15 @@ export class AgentServer {}}+ private async runStartupTurn<T>(operation: () => Promise<T>): Promise<T> {+ this.activeStartupTurnCount += 1;+ try {+ return await this.runOwnedTurn(operation);+ } finally {+ this.activeStartupTurnCount -= 1;+ }+ }+private async acquireNonSteerDeliveryTurn(): Promise<() => void> {const previous = this.nonSteerDeliveryTail;let release!: () => void;@@ -2295,7 +2317,7 @@ export class AgentServer {throw new Error("Agent session is missing its ACP session ID");}- const result = await this.runOwnedTurn(() =>+ const result = await this.runStartupTurn(() =>this.promptWithUpstreamRetry({sessionId: acpSessionId,prompt: initialPrompt,@@ -2533,7 +2555,7 @@ export class AgentServer {throw new Error("Agent session is missing its ACP session ID");}- const result = await this.runOwnedTurn(() =>+ const result = await this.runStartupTurn(() =>this.promptWithUpstreamRetry({sessionId: acpSessionId,prompt: builtPrompt.prompt,