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): make a mid-turn steer interrupt the running turn (#82481)

Alessandro Pogliaghib8e2cd894912
diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts
index 6d3a3a98e8ec..a21fd3027f3a 100644
--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts
@@ -527,7 +527,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {
const isSteer = isSteerMeta(params._meta);
if (hasInFlightTurns && isSteer) {
- // Fold into the running turn (promptToClaude tagged it priority:"next");
+ // Fold into the running turn (promptToClaude tagged it priority:"now");
// the benign end_turn is ignored by clients, which key off _meta.steer.
const owner =
this.session.activeTurn ??
diff --git a/products/desktop/packages/agent/src/adapters/claude/conversion/acp-to-sdk.test.ts b/products/desktop/packages/agent/src/adapters/claude/conversion/acp-to-sdk.test.ts
index 9585a4f4805d..950254dc03b3 100644
--- a/products/desktop/packages/agent/src/adapters/claude/conversion/acp-to-sdk.test.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/conversion/acp-to-sdk.test.ts
@@ -70,13 +70,13 @@ describe("promptToClaude", () => {
expect(text).toContain("pages");
});
- it("tags a steer message with priority 'next' for tool-boundary delivery", () => {
+ it("tags a steer message with priority 'now' so it interrupts the turn", () => {
const result = promptToClaude({
sessionId: "session-1",
prompt: [{ type: "text", text: "use a different approach" }],
_meta: { steer: true },
});
- expect(result.priority).toBe("next");
+ expect(result.priority).toBe("now");
});
it("adds local skill context before the visible slash command", () => {
diff --git a/products/desktop/packages/agent/src/adapters/claude/conversion/acp-to-sdk.ts b/products/desktop/packages/agent/src/adapters/claude/conversion/acp-to-sdk.ts
index d4a8cbf42123..3a7eb4be5494 100644
--- a/products/desktop/packages/agent/src/adapters/claude/conversion/acp-to-sdk.ts
+++ b/products/desktop/packages/agent/src/adapters/claude/conversion/acp-to-sdk.ts
@@ -213,10 +213,8 @@ export function promptToClaude(prompt: PromptRequest): SDKUserMessage {
parent_tool_use_id: null,
};
- // A steer is folded into the turn already running: priority "next" tells the
- // SDK to deliver it at the next tool-call boundary rather than as a new turn.
if (isSteerMeta(meta)) {
- message.priority = "next";
+ message.priority = "now";
}
return message;
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.ts
index 2938a770f48f..71136b5d8370 100644
--- a/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.ts
+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.ts
@@ -1,5 +1,6 @@
import type {
AgentSideConnection,
+ CancelNotification,
InitializeRequest,
NewSessionRequest,
PromptRequest,
@@ -101,6 +102,10 @@ function makeFakeClient(
const init = { protocolVersion: 1 } as unknown as InitializeRequest;
describe("CodexAppServerAgent", () => {
+ const tokenUsage = (last: Record<string, number>) => ({
+ tokenUsage: { total: last, last, modelContextWindow: 200_000 },
+ });
+
it("logs session initialization diagnostics when thread setup fails", async () => {
const stub = makeStubRpc({
"thread/start": new Error("thread setup failed"),
@@ -2514,11 +2519,10 @@ describe("CodexAppServerAgent", () => {
);
});
- it("rejects a failed turn/steer without echoing or acknowledging it", async () => {
+ it("interrupts the running turn and continues it with the steered message", async () => {
const stub = makeStubRpc({
"thread/start": { thread: { id: "t" } },
"turn/start": { turn: { id: "turn_1" } },
- "turn/steer": new Error("steer transport failed"),
});
const { client, sessionUpdates } = makeFakeClient();
const agent = new CodexAppServerAgent(client, {
@@ -2529,39 +2533,251 @@ describe("CodexAppServerAgent", () => {
await agent.newSession({ cwd: "/r" } as unknown as NewSessionRequest);
const first = agent.prompt({
sessionId: "t",
- prompt: [{ type: "text", text: "one" }],
+ prompt: [{ type: "text", text: "write a long poem" }],
} as unknown as PromptRequest);
stub.emit("turn/started", { threadId: "t", turn: { id: "turn_1" } });
await expect(
agent.prompt({
sessionId: "t",
- prompt: [{ type: "text", text: "lost steer" }],
+ prompt: [{ type: "text", text: "stop, do this instead" }],
_meta: { steer: true },
} as unknown as PromptRequest),
- ).rejects.toThrow("steer transport failed");
- expect(sessionUpdates).not.toContainEqual(
+ ).resolves.toMatchObject({
+ stopReason: "end_turn",
+ _meta: { steer: true },
+ });
+
+ expect(
+ stub.requests.find((r) => r.method === "turn/interrupt")?.params,
+ ).toMatchObject({ threadId: "t", turnId: "turn_1" });
+ const starts = stub.requests.filter((r) => r.method === "turn/start");
+ expect(starts).toHaveLength(2);
+ expect(starts[1].params).toMatchObject({
+ input: [{ type: "text", text: "stop, do this instead" }],
+ });
+ expect(stub.requests.some((r) => r.method === "turn/steer")).toBe(false);
+ expect(sessionUpdates).toContainEqual(
expect.objectContaining({
update: expect.objectContaining({
sessionUpdate: "user_message_chunk",
- content: { type: "text", text: "lost steer" },
+ content: { type: "text", text: "stop, do this instead" },
}),
}),
);
- stub.emit("turn/completed", { turn: { status: "completed" } });
- await first;
+ stub.emit("turn/completed", {
+ turn: { id: "turn_1", status: "interrupted" },
+ });
+ stub.emit("turn/started", { threadId: "t", turn: { id: "turn_2" } });
+ await Promise.race([
+ first.then(() => "settled"),
+ new Promise((r) => setTimeout(() => r("pending"), 10)),
+ ]).then((state) => expect(state).toBe("pending"));
+
+ stub.emit("turn/completed", {
+ turn: { id: "turn_2", status: "completed" },
+ });
+ await expect(first).resolves.toMatchObject({ stopReason: "end_turn" });
+ });
+
+ it("interrupts the continuation when a cancel wins the race to start it", async () => {
+ let starts = 0;
+ const stub = makeStubRpc({
+ "thread/start": { thread: { id: "t" } },
+ "turn/start": () => {
+ starts += 1;
+ return { turn: { id: `turn_${starts}` } };
+ },
+ });
+ const { client } = makeFakeClient();
+ const agent = new CodexAppServerAgent(client, {
+ processOptions: { binaryPath: "/x/codex" },
+ rpcFactory: stub.factory,
+ });
+
+ await agent.newSession({ cwd: "/r" } as unknown as NewSessionRequest);
+ const first = agent.prompt({
+ sessionId: "t",
+ prompt: [{ type: "text", text: "write a long poem" }],
+ } as unknown as PromptRequest);
+ stub.emit("turn/started", { threadId: "t", turn: { id: "turn_1" } });
+
+ const steer = agent.prompt({
+ sessionId: "t",
+ prompt: [{ type: "text", text: "do this instead" }],
+ _meta: { steer: true },
+ } as unknown as PromptRequest);
+ await agent.cancel({ sessionId: "t" } as unknown as CancelNotification);
+ await expect(first).resolves.toMatchObject({ stopReason: "cancelled" });
+ await expect(steer).resolves.toMatchObject({ _meta: { steer: false } });
+
+ const interrupted = stub.requests
+ .filter((r) => r.method === "turn/interrupt")
+ .map((r) => (r.params as { turnId?: string }).turnId);
+ expect(interrupted).toContain("turn_2");
+ });
+
+ it("declines a second steer that overlaps the first's interrupt window", async () => {
+ const stub = makeStubRpc({
+ "thread/start": { thread: { id: "t" } },
+ "turn/start": { turn: { id: "turn_1" } },
+ });
+ const { client } = makeFakeClient();
+ const agent = new CodexAppServerAgent(client, {
+ processOptions: { binaryPath: "/x/codex" },
+ rpcFactory: stub.factory,
+ });
+
+ await agent.newSession({ cwd: "/r" } as unknown as NewSessionRequest);
+ const first = agent.prompt({
+ sessionId: "t",
+ prompt: [{ type: "text", text: "write a long poem" }],
+ } as unknown as PromptRequest);
+ stub.emit("turn/started", { threadId: "t", turn: { id: "turn_1" } });
+
+ const steerA = agent.prompt({
+ sessionId: "t",
+ prompt: [{ type: "text", text: "do A instead" }],
+ _meta: { steer: true },
+ } as unknown as PromptRequest);
+ const steerB = agent.prompt({
+ sessionId: "t",
+ prompt: [{ type: "text", text: "do B instead" }],
+ _meta: { steer: true },
+ } as unknown as PromptRequest);
+
+ await expect(steerA).resolves.toMatchObject({ _meta: { steer: true } });
+ await expect(steerB).resolves.toMatchObject({ _meta: { steer: false } });
+ expect(stub.requests.filter((r) => r.method === "turn/start")).toHaveLength(
+ 2,
+ );
+
+ stub.emit("turn/completed", {
+ turn: { id: "turn_1", status: "interrupted" },
+ });
+ stub.emit("turn/started", { threadId: "t", turn: { id: "turn_2" } });
+ stub.emit("turn/completed", {
+ turn: { id: "turn_2", status: "completed" },
+ });
+ await expect(first).resolves.toMatchObject({ stopReason: "end_turn" });
+ });
+
+ it("sums both native turns' usage when a steer splits the host turn", async () => {
+ const stub = makeStubRpc({
+ "thread/start": { thread: { id: "t" } },
+ "turn/start": { turn: { id: "turn_1" } },
+ });
+ const { client } = makeFakeClient();
+ const agent = new CodexAppServerAgent(client, {
+ processOptions: { binaryPath: "/x/codex" },
+ rpcFactory: stub.factory,
+ });
+ await agent.newSession({ cwd: "/r" } as unknown as NewSessionRequest);
+ const first = agent.prompt({
+ sessionId: "t",
+ prompt: [{ type: "text", text: "write a long poem" }],
+ } as unknown as PromptRequest);
+ stub.emit("turn/started", { threadId: "t", turn: { id: "turn_1" } });
+ stub.emit(
+ "thread/tokenUsage/updated",
+ tokenUsage({
+ inputTokens: 400,
+ cachedInputTokens: 50,
+ outputTokens: 80,
+ reasoningOutputTokens: 20,
+ totalTokens: 500,
+ }),
+ );
+
+ await expect(
+ agent.prompt({
+ sessionId: "t",
+ prompt: [{ type: "text", text: "stop, do this instead" }],
+ _meta: { steer: true },
+ } as unknown as PromptRequest),
+ ).resolves.toMatchObject({ _meta: { steer: true } });
+
+ stub.emit("turn/completed", {
+ turn: { id: "turn_1", status: "interrupted" },
+ });
+ stub.emit("turn/started", { threadId: "t", turn: { id: "turn_2" } });
+ stub.emit(
+ "thread/tokenUsage/updated",
+ tokenUsage({
+ inputTokens: 100,
+ cachedInputTokens: 10,
+ outputTokens: 20,
+ reasoningOutputTokens: 5,
+ totalTokens: 130,
+ }),
+ );
+ stub.emit("turn/completed", {
+ turn: { id: "turn_2", status: "completed" },
+ });
+
+ await expect(first).resolves.toMatchObject({
+ stopReason: "end_turn",
+ usage: {
+ inputTokens: 500,
+ outputTokens: 100,
+ cachedReadTokens: 60,
+ thoughtTokens: 25,
+ totalTokens: 630,
+ },
+ });
});
- it("declines a stale turn/steer so the caller can queue it normally", async () => {
+ it("still delivers the steer when the interrupt loses the race to the turn's end", async () => {
const stub = makeStubRpc({
"thread/start": { thread: { id: "t" } },
"turn/start": { turn: { id: "turn_1" } },
- "turn/steer": new AppServerRequestError(
+ "turn/interrupt": new AppServerRequestError(
-32600,
- "expected active turn id `turn_1` but found `turn_2`",
+ "no active turn to interrupt",
),
});
+ const { client } = makeFakeClient();
+ const agent = new CodexAppServerAgent(client, {
+ processOptions: { binaryPath: "/x/codex" },
+ rpcFactory: stub.factory,
+ });
+
+ await agent.newSession({ cwd: "/r" } as unknown as NewSessionRequest);
+ const first = agent.prompt({
+ sessionId: "t",
+ prompt: [{ type: "text", text: "one" }],
+ } as unknown as PromptRequest);
+ stub.emit("turn/started", { threadId: "t", turn: { id: "turn_1" } });
+
+ await expect(
+ agent.prompt({
+ sessionId: "t",
+ prompt: [{ type: "text", text: "steer me" }],
+ _meta: { steer: true },
+ } as unknown as PromptRequest),
+ ).resolves.toMatchObject({ _meta: { steer: true } });
+ expect(stub.requests.filter((r) => r.method === "turn/start")).toHaveLength(
+ 2,
+ );
+
+ stub.emit("turn/started", { threadId: "t", turn: { id: "turn_2" } });
+ stub.emit("turn/completed", {
+ turn: { id: "turn_2", status: "completed" },
+ });
+ await expect(first).resolves.toMatchObject({ stopReason: "end_turn" });
+ });
+
+ it("declines a steer whose continuation turn cannot start, and ends the turn", async () => {
+ let starts = 0;
+ const stub = makeStubRpc({
+ "thread/start": { thread: { id: "t" } },
+ "turn/start": () => {
+ starts += 1;
+ if (starts > 1) throw new Error("turn/start transport failed");
+ return { turn: { id: "turn_1" } };
+ },
+ });
const { client, sessionUpdates } = makeFakeClient();
const agent = new CodexAppServerAgent(client, {
processOptions: { binaryPath: "/x/codex" },
@@ -2578,7 +2794,7 @@ describe("CodexAppServerAgent", () => {
await expect(
agent.prompt({
sessionId: "t",
- prompt: [{ type: "text", text: "queue me" }],
+ prompt: [{ type: "text", text: "lost steer" }],
_meta: { steer: true },
} as unknown as PromptRequest),
).resolves.toMatchObject({ _meta: { steer: false } });
@@ -2586,13 +2802,85 @@ describe("CodexAppServerAgent", () => {
expect.objectContaining({
update: expect.objectContaining({
sessionUpdate: "user_message_chunk",
- content: { type: "text", text: "queue me" },
+ content: { type: "text", text: "lost steer" },
}),
}),
);
- stub.emit("turn/completed", { turn: { status: "completed" } });
- await first;
+ stub.emit("turn/completed", {
+ turn: { id: "turn_1", status: "interrupted" },
+ });
+ await expect(first).resolves.toMatchObject({ stopReason: "cancelled" });
+ });
+
+ it("does not double-count usage when a failed steer leaves the original turn running", async () => {
+ let starts = 0;
+ const stub = makeStubRpc({
+ "thread/start": { thread: { id: "t" } },
+ "turn/start": () => {
+ starts += 1;
+ if (starts > 1) throw new Error("turn/start transport failed");
+ return { turn: { id: "turn_1" } };
+ },
+ "turn/interrupt": new AppServerRequestError(
+ -32600,
+ "no active turn to interrupt",
+ ),
+ });
+ const { client } = makeFakeClient();
+ const agent = new CodexAppServerAgent(client, {
+ processOptions: { binaryPath: "/x/codex" },
+ rpcFactory: stub.factory,
+ });
+ await agent.newSession({ cwd: "/r" } as unknown as NewSessionRequest);
+ const first = agent.prompt({
+ sessionId: "t",
+ prompt: [{ type: "text", text: "one" }],
+ } as unknown as PromptRequest);
+ stub.emit("turn/started", { threadId: "t", turn: { id: "turn_1" } });
+ stub.emit(
+ "thread/tokenUsage/updated",
+ tokenUsage({
+ inputTokens: 400,
+ cachedInputTokens: 50,
+ outputTokens: 80,
+ reasoningOutputTokens: 20,
+ totalTokens: 500,
+ }),
+ );
+
+ await expect(
+ agent.prompt({
+ sessionId: "t",
+ prompt: [{ type: "text", text: "lost steer" }],
+ _meta: { steer: true },
+ } as unknown as PromptRequest),
+ ).resolves.toMatchObject({ _meta: { steer: false } });
+
+ stub.emit(
+ "thread/tokenUsage/updated",
+ tokenUsage({
+ inputTokens: 600,
+ cachedInputTokens: 70,
+ outputTokens: 120,
+ reasoningOutputTokens: 30,
+ totalTokens: 750,
+ }),
+ );
+ stub.emit("turn/completed", {
+ turn: { id: "turn_1", status: "completed" },
+ });
+
+ await expect(first).resolves.toMatchObject({
+ stopReason: "end_turn",
+ usage: {
+ inputTokens: 600,
+ outputTokens: 120,
+ cachedReadTokens: 70,
+ thoughtTokens: 30,
+ totalTokens: 750,
+ },
+ });
});
it("declines an explicit steer after the active turn has ended", async () => {
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts
index b9fefdbc1f71..e16d6e3f2016 100644
--- a/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts
+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts
@@ -58,7 +58,6 @@ import { resolveSpokenNarration } from "../session-meta";
import {
AppServerClient,
type AppServerClientHandlers,
- AppServerRequestError,
type AppServerRpc,
} from "./app-server-client";
import { handleServerRequest } from "./approvals";
@@ -95,17 +94,7 @@ import {
} from "./spawn";
import { parseStructuredOutput } from "./structured-output";
import { TurnController } from "./turn-controller";
-import { UsageTracker } from "./usage-tracker";
-
-function isStaleTurnSteerError(error: unknown): boolean {
- if (!(error instanceof AppServerRequestError) || error.code !== -32600) {
- return false;
- }
- return (
- error.message === "no active turn to steer" ||
- /^expected active turn id `.*` but found `.*`$/.test(error.message)
- );
-}
+import { mergeUsage, UsageTracker } from "./usage-tracker";
type AppServerSessionMeta = {
// The host sends either a plain string or the Claude-style `{ append }` form.
@@ -189,29 +178,18 @@ function parseGoalCommand(prompt: PromptRequest["prompt"]): GoalCommand | null {
}
}
-function mergePromptUsage(
- left: PromptResponse["usage"],
- right: PromptResponse["usage"],
-): PromptResponse["usage"] {
- if (!left) return right;
- if (!right) return left;
- return {
- inputTokens: left.inputTokens + right.inputTokens,
- outputTokens: left.outputTokens + right.outputTokens,
- cachedReadTokens:
- (left.cachedReadTokens ?? 0) + (right.cachedReadTokens ?? 0),
- cachedWriteTokens:
- (left.cachedWriteTokens ?? 0) + (right.cachedWriteTokens ?? 0),
- thoughtTokens: (left.thoughtTokens ?? 0) + (right.thoughtTokens ?? 0),
- totalTokens: left.totalTokens + right.totalTokens,
- };
+function steerDeclined(): PromptResponse {
+ return { stopReason: "end_turn", _meta: { steer: false } };
}
function mergePromptResponses(
left: PromptResponse,
right: PromptResponse,
): PromptResponse {
- return { ...right, usage: mergePromptUsage(left.usage, right.usage) };
+ return {
+ ...right,
+ usage: mergeUsage(left.usage ?? undefined, right.usage ?? undefined),
+ };
}
// The native app-server owns its config; BaseAcpAgent only calls dispose() on this.
@@ -293,6 +271,7 @@ export class CodexAppServerAgent extends BaseAcpAgent {
private cancelNextGoalTurn = false;
/** Native goal ticks start outside prompt(), so TurnController does not own them. */
private nativeGoalTurnId?: string;
+ private steering = false;
constructor(
client: AgentSideConnection,
@@ -808,35 +787,26 @@ export class CodexAppServerAgent extends BaseAcpAgent {
if (dropped > 0) {
this.logger.warn("Dropped non-text/non-image prompt blocks", { dropped });
}
+ const isSteer =
+ (params._meta as { steer?: unknown } | undefined)?.steer === true;
if (this.turns.isRunning) {
- // A turn is already running: fold the message in via turn/steer (precondition: the
- // active turnId). Refresh from the response's rotated turnId so a later steer/interrupt
- // still targets the live turn (no turn/started is re-emitted for a steer).
- let steerRes: { turnId?: string };
- try {
- steerRes = await this.rpc.request<{ turnId?: string }>(
- APP_SERVER_METHODS.TURN_STEER,
- {
- threadId: this.threadId,
- input,
- expectedTurnId: this.turns.activeTurnId,
- },
- );
- } catch (error) {
- if (
- (params._meta as { steer?: unknown } | undefined)?.steer === true &&
- isStaleTurnSteerError(error)
- ) {
- return { stopReason: "end_turn", _meta: { steer: false } };
- }
- throw error;
+ if (isSteer) {
+ return await this.steerRunningTurn(input, params.prompt);
}
+ const steerRes = await this.rpc.request<{ turnId?: string }>(
+ APP_SERVER_METHODS.TURN_STEER,
+ {
+ threadId: this.threadId,
+ input,
+ expectedTurnId: this.turns.activeTurnId,
+ },
+ );
this.turns.onSteered(steerRes?.turnId);
this.broadcastUserInput(params.prompt);
return { stopReason: "end_turn", _meta: { steer: true } };
}
- if ((params._meta as { steer?: unknown } | undefined)?.steer === true) {
- return { stopReason: "end_turn", _meta: { steer: false } };
+ if (isSteer) {
+ return steerDeclined();
}
if (this.turns.isPending) {
// A turn is pending but has no turnId yet, so we can't steer; fail fast.
@@ -960,6 +930,96 @@ export class CodexAppServerAgent extends BaseAcpAgent {
);
}
+ private turnStartParams(input: CodexUserInput[]): Record<string, unknown> {
+ const approvalPolicy = this.config.approvalPolicy();
+ const sandboxPolicy = this.sandboxPolicyForTurn();
+ return {
+ threadId: this.threadId,
+ input,
+ model: this.config.model,
+ ...(this.config.effort ? { effort: this.config.effort } : {}),
+ // Always request a reasoning summary; the default "auto" can skip it on trivial turns.
+ summary: "detailed",
+ // Picker preset applied per-turn. codex keeps turn overrides for subsequent turns,
+ // so every mode sends its full policy — omitting a field would leave the previous
+ // mode's value active (e.g. plan's readOnly sandbox bleeding into auto).
+ ...(approvalPolicy ? { approvalPolicy } : {}),
+ // Pushed every turn — codex remembers the last mode, so switching back from plan must be explicit.
+ collaborationMode: this.config.collaborationModeForTurn(),
+ // Skipped on cloud, where a non-danger sandbox re-engages the unavailable
+ // linux-sandbox and panics; the enclosing docker/Modal sandbox isolates instead.
+ ...(this.environment !== "cloud" && sandboxPolicy
+ ? { sandboxPolicy }
+ : {}),
+ // Constrain the final message to the task schema for parseable structured output.
+ ...(this.jsonSchema ? { outputSchema: this.jsonSchema } : {}),
+ };
+ }
+
+ private async interruptTurn(turnId: string, label: string): Promise<void> {
+ await this.rpc
+ .request(APP_SERVER_METHODS.TURN_INTERRUPT, {
+ threadId: this.threadId,
+ turnId,
+ })
+ .catch((err) => this.logger.warn(label, err));
+ }
+
+ private async steerRunningTurn(
+ input: CodexUserInput[],
+ prompt: PromptRequest["prompt"],
+ ): Promise<PromptResponse> {
+ if (this.steering) {
+ return steerDeclined();
+ }
+ this.steering = true;
+ try {
+ const turnId = this.session.cancelled
+ ? undefined
+ : this.turns.markInterrupted();
+ if (!turnId) {
+ return steerDeclined();
+ }
+ await this.interruptTurn(turnId, "steer turn/interrupt failed");
+ this.planProposal = undefined;
+ this.streamedPlanToolCallId = undefined;
+ let started: { turn?: { id?: string } };
+ try {
+ started = await this.rpc.request<{ turn?: { id?: string } }>(
+ APP_SERVER_METHODS.TURN_START,
+ this.turnStartParams(input),
+ );
+ } catch (err) {
+ this.logger.warn("steer continuation turn/start failed", err);
+ if (!this.turns.clearInterrupted(turnId)) {
+ await this.finalizeTurn("cancelled");
+ }
+ return steerDeclined();
+ }
+ this.usage.carryForNativeTurn();
+ if (this.session.cancelled) {
+ const orphanId = this.turns.markInterrupted(started?.turn?.id);
+ this.logger.warn(
+ "cancel raced the steer continuation; interrupting it",
+ {
+ turnId: orphanId,
+ },
+ );
+ if (orphanId) {
+ await this.interruptTurn(
+ orphanId,
+ "orphan continuation interrupt failed",
+ );
+ }
+ return steerDeclined();
+ }
+ this.broadcastUserInput(prompt);
+ return { stopReason: "end_turn", _meta: { steer: true } };
+ } finally {
+ this.steering = false;
+ }
+ }
+
/** Start one codex turn and await its completion. */
private async runTurn(input: CodexUserInput[]): Promise<PromptResponse> {
this.lastAgentMessage = "";
@@ -970,29 +1030,10 @@ export class CodexAppServerAgent extends BaseAcpAgent {
this.deferredTurnComplete = undefined;
const { completion, turn } = this.turns.begin();
try {
- const approvalPolicy = this.config.approvalPolicy();
- const sandboxPolicy = this.sandboxPolicyForTurn();
- await this.rpc.request(APP_SERVER_METHODS.TURN_START, {
- threadId: this.threadId,
- input,
- model: this.config.model,
- ...(this.config.effort ? { effort: this.config.effort } : {}),
- // Always request a reasoning summary; the default "auto" can skip it on trivial turns.
- summary: "detailed",
- // Picker preset applied per-turn. codex keeps turn overrides for subsequent turns,
- // so every mode sends its full policy — omitting a field would leave the previous
- // mode's value active (e.g. plan's readOnly sandbox bleeding into auto).
- ...(approvalPolicy ? { approvalPolicy } : {}),
- // Pushed every turn — codex remembers the last mode, so switching back from plan must be explicit.
- collaborationMode: this.config.collaborationModeForTurn(),
- // Skipped on cloud, where a non-danger sandbox re-engages the unavailable
- // linux-sandbox and panics; the enclosing docker/Modal sandbox isolates instead.
- ...(this.environment !== "cloud" && sandboxPolicy
- ? { sandboxPolicy }
- : {}),
- // Constrain the final message to the task schema for parseable structured output.
- ...(this.jsonSchema ? { outputSchema: this.jsonSchema } : {}),
- });
+ await this.rpc.request(
+ APP_SERVER_METHODS.TURN_START,
+ this.turnStartParams(input),
+ );
return await completion;
} finally {
this.turns.finishPrompt(turn);
@@ -1354,12 +1395,7 @@ export class CodexAppServerAgent extends BaseAcpAgent {
// threadId and turnId (else -32600); skip the RPC when no turn started.
const turnId = this.turns.markInterrupted();
if (this.threadId && turnId) {
- await this.rpc
- .request(APP_SERVER_METHODS.TURN_INTERRUPT, {
- threadId: this.threadId,
- turnId,
- })
- .catch((err) => this.logger.warn("turn/interrupt failed", err));
+ await this.interruptTurn(turnId, "turn/interrupt failed");
}
await this.finalizeTurn("cancelled");
}
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/turn-controller.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/turn-controller.ts
index 90e7bcb21bdd..2edf7fac0d6d 100644
--- a/products/desktop/packages/agent/src/adapters/codex-app-server/turn-controller.ts
+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/turn-controller.ts
@@ -58,10 +58,10 @@ export class TurnController {
}
/** Mark the live turn interrupted (so its late completion is dropped) and return its id, or undefined. */
- markInterrupted(): string | undefined {
- if (!this.turnId) return undefined;
- this.cancelled.add(this.turnId);
- return this.turnId;
+ markInterrupted(id: string | undefined = this.turnId): string | undefined {
+ if (!id) return undefined;
+ this.cancelled.add(id);
+ return id;
}
/** True (once) if this completion is for an interrupted turn we should drop. */
@@ -69,6 +69,10 @@ export class TurnController {
return id ? this.cancelled.delete(id) : false;
}
+ clearInterrupted(id: string | undefined): boolean {
+ return this.shouldDropCompletion(id);
+ }
+
/**
* Clear the pending slot after prompt() returns (covers a turn/start throw). Guarded by
* the caller's turn token: finalizeTurn claims before it awaits, so a new prompt() can
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/usage-tracker.test.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/usage-tracker.test.ts
index d8c579bd18a5..6366ba8ae719 100644
--- a/products/desktop/packages/agent/src/adapters/codex-app-server/usage-tracker.test.ts
+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/usage-tracker.test.ts
@@ -80,10 +80,55 @@ describe("UsageTracker", () => {
expect(tracker.contextTokens()).toBe(500);
});
- it("resetForTurn clears stale per-turn usage", () => {
+ it("carryForNativeTurn sums the interrupted turn's usage into the continuation", () => {
const tracker = new UsageTracker();
tracker.ingest(payload());
+ tracker.carryForNativeTurn();
+ tracker.ingest(
+ payload({
+ last: {
+ inputTokens: 100,
+ cachedInputTokens: 10,
+ outputTokens: 20,
+ reasoningOutputTokens: 5,
+ totalTokens: 130,
+ },
+ }),
+ );
+
+ expect(tracker.perTurnUsage()).toEqual({
+ inputTokens: 500,
+ outputTokens: 100,
+ cachedReadTokens: 60,
+ cachedWriteTokens: 0,
+ thoughtTokens: 25,
+ totalTokens: 630,
+ });
+ expect(tracker.contextTokens()).toBe(130);
+ });
+
+ it("carryForNativeTurn keeps the interrupted usage when the continuation reports none", () => {
+ const tracker = new UsageTracker();
+ tracker.ingest(payload());
+
+ tracker.carryForNativeTurn();
+
+ expect(tracker.perTurnUsage()).toEqual({
+ inputTokens: 400,
+ outputTokens: 80,
+ cachedReadTokens: 50,
+ cachedWriteTokens: 0,
+ thoughtTokens: 20,
+ totalTokens: 500,
+ });
+ });
+
+ it("resetForTurn clears stale per-turn and carried usage", () => {
+ const tracker = new UsageTracker();
+ tracker.ingest(payload());
+ tracker.carryForNativeTurn();
+
tracker.resetForTurn();
expect(tracker.contextTokens()).toBeUndefined();
expect(tracker.perTurnUsage()).toBeUndefined();
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/usage-tracker.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/usage-tracker.ts
index fd107a7c13af..4fc7d46610f8 100644
--- a/products/desktop/packages/agent/src/adapters/codex-app-server/usage-tracker.ts
+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/usage-tracker.ts
@@ -5,6 +5,24 @@ import {
} from "../claude/context-breakdown";
import { readTokenUsage } from "./token-usage";
+export function mergeUsage(
+ left: Usage | undefined,
+ right: Usage | undefined,
+): Usage | undefined {
+ if (!left) return right;
+ if (!right) return left;
+ return {
+ inputTokens: left.inputTokens + right.inputTokens,
+ outputTokens: left.outputTokens + right.outputTokens,
+ cachedReadTokens:
+ (left.cachedReadTokens ?? 0) + (right.cachedReadTokens ?? 0),
+ cachedWriteTokens:
+ (left.cachedWriteTokens ?? 0) + (right.cachedWriteTokens ?? 0),
+ thoughtTokens: (left.thoughtTokens ?? 0) + (right.thoughtTokens ?? 0),
+ totalTokens: left.totalTokens + right.totalTokens,
+ };
+}
+
/** The live `_posthog/usage_update` fields (context-window occupancy). */
export interface UsageUpdate {
used: number;
@@ -26,6 +44,7 @@ export interface UsageUpdate {
export class UsageTracker {
private baseline: ContextBreakdownBaseline = emptyBaseline();
private lastTurn?: Usage;
+ private carried?: Usage;
private contextUsed?: number;
setBaseline(baseline: ContextBreakdownBaseline): void {
@@ -38,9 +57,15 @@ export class UsageTracker {
resetForTurn(): void {
this.lastTurn = undefined;
+ this.carried = undefined;
this.contextUsed = undefined;
}
+ carryForNativeTurn(): void {
+ this.carried = mergeUsage(this.carried, this.lastTurn);
+ this.lastTurn = undefined;
+ }
+
/** Ingest a `thread/tokenUsage/updated` payload; returns the live usage_update, or null if unusable. */
ingest(params: unknown): UsageUpdate | null {
const reading = readTokenUsage(params);
@@ -74,7 +99,8 @@ export class UsageTracker {
}
perTurnUsage(): Usage | undefined {
- return this.lastTurn ? { ...this.lastTurn } : undefined;
+ const merged = mergeUsage(this.carried, this.lastTurn);
+ return merged ? { ...merged } : undefined;
}
/** Live context occupancy (same derivation as the renderer gauge), or undefined pre-usage. */
diff --git a/products/desktop/packages/agent/src/server/pi-agent-server.test.ts b/products/desktop/packages/agent/src/server/pi-agent-server.test.ts
index 3d4fa92f6dd0..ad68a77f922d 100644
--- a/products/desktop/packages/agent/src/server/pi-agent-server.test.ts
+++ b/products/desktop/packages/agent/src/server/pi-agent-server.test.ts
@@ -397,6 +397,172 @@ describe("PiAgentServer", () => {
await rm(repositoryPath, { recursive: true });
});
+ it("aborts the streaming run and re-prompts when a steer arrives", async () => {
+ const sendCommand = vi.fn(async (_command: Record<string, unknown>) => ({
+ success: true,
+ }));
+ const order: string[] = [];
+ const abort = vi.fn(async () => {
+ order.push("abort");
+ });
+ const server = new PiAgentServer(config()) as unknown as {
+ session: unknown;
+ executeCommand(
+ method: string,
+ params: Record<string, unknown>,
+ ): Promise<unknown>;
+ };
+ server.session = {
+ runtime: {
+ client: {
+ getState: vi.fn(async () => ({ isStreaming: true })),
+ abort,
+ },
+ sendCommand: vi.fn(async (command: Record<string, unknown>) => {
+ order.push("sendCommand");
+ return sendCommand(command);
+ }),
+ },
+ };
+
+ await server.executeCommand("user_message", {
+ content: "stop, do this instead",
+ messageId: "message-1",
+ steer: true,
+ });
+
+ expect(order).toEqual(["abort", "sendCommand"]);
+ expect(sendCommand).toHaveBeenCalledTimes(1);
+ expect(sendCommand).toHaveBeenCalledWith({
+ id: "message-1",
+ type: "prompt",
+ message: "stop, do this instead",
+ images: [],
+ });
+ });
+
+ it("queues a steer that pi rejects because another run took the idle slot", async () => {
+ const sendCommand = vi.fn(async (command: Record<string, unknown>) => {
+ if (command.type === "prompt") {
+ return { success: false, error: "Agent is already processing." };
+ }
+ return { success: true };
+ });
+ const server = new PiAgentServer(config()) as unknown as {
+ session: unknown;
+ executeCommand(
+ method: string,
+ params: Record<string, unknown>,
+ ): Promise<unknown>;
+ };
+ server.session = {
+ runtime: {
+ client: {
+ getState: vi.fn(async () => ({ isStreaming: true })),
+ abort: vi.fn(async () => {}),
+ },
+ sendCommand,
+ },
+ };
+
+ const result = await server.executeCommand("user_message", {
+ content: "stop, do this instead",
+ messageId: "message-3",
+ steer: true,
+ });
+
+ expect(sendCommand).toHaveBeenLastCalledWith({
+ id: "message-3",
+ type: "follow_up",
+ message: "stop, do this instead",
+ images: [],
+ });
+ expect(result).toMatchObject({ success: true });
+ });
+
+ it("declines a steer whose re-prompt fails while pi stays idle so the host redelivers", async () => {
+ const sendCommand = vi.fn(async (command: Record<string, unknown>) => {
+ if (command.type === "prompt") {
+ return {
+ success: false,
+ error: "Cannot submit a prompt while compaction is in progress.",
+ };
+ }
+ return { success: true };
+ });
+ const getState = vi
+ .fn()
+ .mockResolvedValueOnce({ isStreaming: true })
+ .mockResolvedValueOnce({ isStreaming: false });
+ const server = new PiAgentServer(config()) as unknown as {
+ session: unknown;
+ executeCommand(
+ method: string,
+ params: Record<string, unknown>,
+ ): Promise<unknown>;
+ };
+ server.session = {
+ runtime: {
+ client: {
+ getState,
+ abort: vi.fn(async () => {}),
+ },
+ sendCommand,
+ },
+ };
+
+ const result = await server.executeCommand("user_message", {
+ content: "stop, do this instead",
+ messageId: "message-4",
+ steer: true,
+ });
+
+ expect(sendCommand).toHaveBeenCalledTimes(1);
+ expect(sendCommand).toHaveBeenCalledWith({
+ id: "message-4",
+ type: "prompt",
+ message: "stop, do this instead",
+ images: [],
+ });
+ expect(result).toMatchObject({ success: false });
+ });
+
+ it("queues a mid-turn message that is not a steer instead of aborting", async () => {
+ const sendCommand = vi.fn(
+ async (_command: Record<string, unknown>) => ({}),
+ );
+ const abort = vi.fn(async () => {});
+ const server = new PiAgentServer(config()) as unknown as {
+ session: unknown;
+ executeCommand(
+ method: string,
+ params: Record<string, unknown>,
+ ): Promise<unknown>;
+ };
+ server.session = {
+ runtime: {
+ client: {
+ getState: vi.fn(async () => ({ isStreaming: true })),
+ abort,
+ },
+ sendCommand,
+ },
+ };
+
+ await server.executeCommand("user_message", {
+ content: "when you are done, also update the docs",
+ messageId: "message-2",
+ });
+
+ expect(abort).not.toHaveBeenCalled();
+ expect(sendCommand).toHaveBeenCalledWith({
+ id: "message-2",
+ type: "follow_up",
+ message: "when you are done, also update the docs",
+ images: [],
+ });
+ });
+
it("allows a failed user-message delivery to be retried", async () => {
const sendCommand = vi
.fn()
diff --git a/products/desktop/packages/agent/src/server/pi-agent-server.ts b/products/desktop/packages/agent/src/server/pi-agent-server.ts
index de109655c6a6..f34b90705502 100644
--- a/products/desktop/packages/agent/src/server/pi-agent-server.ts
+++ b/products/desktop/packages/agent/src/server/pi-agent-server.ts
@@ -784,29 +784,22 @@ export class PiAgentServer {
id: string,
steer: boolean,
): Promise<unknown> {
+ const send = (type: "prompt" | "follow_up") =>
+ runtime.sendCommand({ id, type, message: content, images });
const state = await runtime.client.getState();
- if (state.isStreaming && steer) {
- return runtime.sendCommand({
- id,
- type: "steer",
- message: content,
- images,
- });
+ if (!state.isStreaming) {
+ return send("prompt");
}
- if (state.isStreaming) {
- return runtime.sendCommand({
- id,
- type: "follow_up",
- message: content,
- images,
- });
+ if (!steer) {
+ return send("follow_up");
}
- return runtime.sendCommand({
- id,
- type: "prompt",
- message: content,
- images,
- });
+ await runtime.client.abort();
+ const prompted = await send("prompt");
+ if (prompted.success) {
+ return prompted;
+ }
+ const afterPrompt = await runtime.client.getState();
+ return afterPrompt.isStreaming ? send("follow_up") : prompted;
}
private installSseController(sseController: SseController | null): void {