: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 the upstream cause on a fatal codex error (#93104)
posthog[bot]e4cc366bd14d
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.tsindex 0f2b9f0571ab..575838a68696 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@@ -2262,7 +2262,7 @@ describe("CodexAppServerAgent", () => {stub.emit("error", { willRetry: false, error: { message: "boom" } });await expect(done).rejects.toThrow(- "The agent stopped before completing this request. Please try again.",+ "The agent stopped before completing this request: boom",);});@@ -2510,6 +2510,183 @@ describe("CodexAppServerAgent", () => {vi.useRealTimers();});+ it("keeps the retried cause when the retries run out", async () => {+ vi.useFakeTimers();+ const stub = makeStubRpc({ "thread/start": { thread: { id: "t" } } });+ const { client, sessionUpdates } = makeFakeClient();+ const agent = new CodexAppServerAgent(client, {+ processOptions: { binaryPath: "/x/codex" },+ rpcFactory: stub.factory,+ });++ await agent.newSession({ cwd: "/r" } as unknown as NewSessionRequest);+ const done = agent.prompt({+ sessionId: "t",+ prompt: [{ type: "text", text: "go" }],+ } as unknown as PromptRequest);+ stub.emit("turn/started", { turn: { id: "turn_1" } });+ // A retried error carries the only text; turn/completed has none of its own.+ stub.emit("error", {+ turnId: "turn_1",+ willRetry: true,+ error: { message: "API Error: 503 Service Unavailable" },+ });+ stub.emit("turn/completed", {+ turn: { id: "turn_1", status: "failed" },+ });++ await vi.advanceTimersByTimeAsync(250);+ await expect(done).resolves.toMatchObject({ stopReason: "refusal" });+ expect(sessionUpdates).toContainEqual({+ sessionId: "t",+ update: {+ sessionUpdate: "agent_message_chunk",+ content: {+ type: "text",+ text: "The agent stopped before completing this request: API Error: 503 Service Unavailable",+ },+ },+ });+ vi.useRealTimers();+ });++ it("surfaces the completion's own fatal cause when it is the only one", async () => {+ vi.useFakeTimers();+ const stub = makeStubRpc({ "thread/start": { thread: { id: "t" } } });+ const { client, sessionUpdates } = makeFakeClient();+ const agent = new CodexAppServerAgent(client, {+ processOptions: { binaryPath: "/x/codex" },+ rpcFactory: stub.factory,+ });++ await agent.newSession({ cwd: "/r" } as unknown as NewSessionRequest);+ const done = agent.prompt({+ sessionId: "t",+ prompt: [{ type: "text", text: "go" }],+ } as unknown as PromptRequest);+ stub.emit("turn/started", { turn: { id: "turn_1" } });+ // codex reports the cause only on the completion — no error notification arrived.+ stub.emit("turn/completed", {+ turn: {+ id: "turn_1",+ status: "failed",+ error: { message: "API Error: 502 Bad Gateway" },+ },+ });++ await vi.advanceTimersByTimeAsync(250);+ await expect(done).resolves.toMatchObject({ stopReason: "refusal" });+ expect(sessionUpdates).toContainEqual({+ sessionId: "t",+ update: {+ sessionUpdate: "agent_message_chunk",+ content: {+ type: "text",+ text: "The agent stopped before completing this request: API Error: 502 Bad Gateway",+ },+ },+ });+ vi.useRealTimers();+ });++ it("prefers the completion's terminal cause over a stale retry message", async () => {+ vi.useFakeTimers();+ const stub = makeStubRpc({ "thread/start": { thread: { id: "t" } } });+ const { client, sessionUpdates } = makeFakeClient();+ const agent = new CodexAppServerAgent(client, {+ processOptions: { binaryPath: "/x/codex" },+ rpcFactory: stub.factory,+ });++ await agent.newSession({ cwd: "/r" } as unknown as NewSessionRequest);+ const done = agent.prompt({+ sessionId: "t",+ prompt: [{ type: "text", text: "go" }],+ } as unknown as PromptRequest);+ stub.emit("turn/started", { turn: { id: "turn_1" } });+ // A retry reports one cause; the turn then dies for a different terminal reason.+ stub.emit("error", {+ turnId: "turn_1",+ willRetry: true,+ error: { message: "API Error: 503 Service Unavailable" },+ });+ stub.emit("turn/completed", {+ turn: {+ id: "turn_1",+ status: "failed",+ error: { message: "API Error: 500 Internal Server Error" },+ },+ });++ await vi.advanceTimersByTimeAsync(250);+ await expect(done).resolves.toMatchObject({ stopReason: "refusal" });+ expect(sessionUpdates).toContainEqual({+ sessionId: "t",+ update: {+ sessionUpdate: "agent_message_chunk",+ content: {+ type: "text",+ text: "The agent stopped before completing this request: API Error: 500 Internal Server Error",+ },+ },+ });+ vi.useRealTimers();+ });++ it("does not attribute a pre-steer retry cause to a steered turn", async () => {+ vi.useFakeTimers();+ const stub = makeStubRpc({ "thread/start": { thread: { id: "t" } } });+ const { client, sessionUpdates } = makeFakeClient();+ const agent = new CodexAppServerAgent(client, {+ processOptions: { binaryPath: "/x/codex" },+ rpcFactory: stub.factory,+ });++ await agent.newSession({ cwd: "/r" } as unknown as NewSessionRequest);+ const done = agent.prompt({+ sessionId: "t",+ prompt: [{ type: "text", text: "go" }],+ } as unknown as PromptRequest);+ stub.emit("turn/started", { turn: { id: "turn_1" } });+ // turn_1 hits a transient provider error that codex will retry.+ stub.emit("error", {+ turnId: "turn_1",+ willRetry: true,+ error: { message: "API Error: 503 Service Unavailable" },+ });+ // A steer rotates the active turn id to turn_2 (the continuation turn).+ stub.emit("turn/started", { turn: { id: "turn_2" } });+ // turn_2 then fails through a bare completion with no cause of its own.+ stub.emit("turn/completed", {+ turn: { id: "turn_2", status: "failed" },+ });++ await vi.advanceTimersByTimeAsync(250);+ await expect(done).resolves.toMatchObject({ stopReason: "refusal" });+ // turn_1's transient cause must not be reported as turn_2's failure.+ expect(sessionUpdates).toContainEqual({+ sessionId: "t",+ update: {+ sessionUpdate: "agent_message_chunk",+ content: {+ type: "text",+ text: "The agent stopped before completing this request. Please try again.",+ },+ },+ });+ expect(sessionUpdates).not.toContainEqual({+ sessionId: "t",+ update: {+ sessionUpdate: "agent_message_chunk",+ content: {+ type: "text",+ text: "The agent stopped before completing this request: API Error: 503 Service Unavailable",+ },+ },+ });+ vi.useRealTimers();+ });+it("does not let an ID-less failed completion refuse a later prompt", async () => {vi.useFakeTimers();const stub = makeStubRpc({ "thread/start": { thread: { id: "t" } } });@@ -2529,7 +2706,7 @@ describe("CodexAppServerAgent", () => {});stub.emit("error", { willRetry: false, error: { message: "boom" } });await expect(first).rejects.toThrow(- "The agent stopped before completing this request. Please try again.",+ "The agent stopped before completing this request: boom",);const second = agent.prompt({@@ -2681,7 +2858,7 @@ describe("CodexAppServerAgent", () => {stub.emit("error", { willRetry: false, error: { message: "boom" } });stub.emit("turn/completed", { turn: { status: "failed" } });await expect(done).rejects.toThrow(- "The agent stopped before completing this request. Please try again.",+ "The agent stopped before completing this request: boom",);// Structured output is gated on a clean end_turn: a failed turn records nothing.@@ -3822,7 +3999,7 @@ describe("CodexAppServerAgent", () => {});stub.emit("error", { willRetry: false, error: { message: "boom" } });await expect(done).rejects.toThrow(- "The agent stopped before completing this request. Please try again.",+ "The agent stopped before completing this request: boom",);expect(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.tsindex 866a326a9494..c39a3c7ea920 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@@ -113,6 +113,24 @@ const POLICY_ERROR_MESSAGE ="This request was blocked by a safety policy. Revise the request and try again.";const GENERIC_FATAL_ERROR_MESSAGE ="The agent stopped before completing this request. Please try again.";+/** Keeps a verbose upstream payload out of the chat bubble and the run's error field. */+const MAX_FATAL_CAUSE_LENGTH = 400;++/**+ * Frame an unclassified fatal error for the reader, keeping the upstream cause.+ *+ * Without the cause every unclassified failure reads the same, so a burst of them+ * cannot be told apart in the run's error field or in analytics.+ */+function describeFatalError(upstream: string): string {+ const cause = upstream.trim();+ if (!cause) return GENERIC_FATAL_ERROR_MESSAGE;+ const shown =+ cause.length > MAX_FATAL_CAUSE_LENGTH+ ? `${cause.slice(0, MAX_FATAL_CAUSE_LENGTH)}...`+ : cause;+ return `The agent stopped before completing this request: ${shown}`;+}type ApprovalRequestDetail = {itemId?: string;@@ -286,6 +304,11 @@ export class CodexAppServerAgent extends BaseAcpAgent {private jsonSchema?: Record<string, unknown>;/** Final assistant message text for the in-flight turn (structured output). */private lastAgentMessage = "";+ /**+ * Newest upstream error for the in-flight turn, retried ones included, bound to+ * its turn id so a steer that rotates the id cannot borrow the wrong cause.+ */+ private lastTurnError?: { turnId?: string; message: string };/** True between a contextCompaction item's start and its boundary (dedupes the boundary). */private compactionActive = false;/** Maps the host's taskRunId to this session, replayed for cloud notifications. */@@ -1160,6 +1183,7 @@ export class CodexAppServerAgent extends BaseAcpAgent {/** Start one codex turn and await its completion. */private async runTurn(input: CodexUserInput[]): Promise<PromptResponse> {this.lastAgentMessage = "";+ this.lastTurnError = undefined;this.resetUsage();this.planProposal = undefined;this.streamedPlanToolCallId = undefined;@@ -1661,8 +1685,15 @@ export class CodexAppServerAgent extends BaseAcpAgent {if (method === APP_SERVER_NOTIFICATIONS.TURN_COMPLETED) {this.commandOutputs.clear();- const turn = (params as { turn?: { id?: string; status?: string } })- ?.turn;+ const turn = (+ params as {+ turn?: {+ id?: string;+ status?: string;+ error?: { message?: unknown };+ };+ }+ )?.turn;const completedNativeGoalTurn = turn?.id === this.nativeGoalTurnId;if (completedNativeGoalTurn) {this.nativeGoalTurnId = undefined;@@ -1681,9 +1712,14 @@ export class CodexAppServerAgent extends BaseAcpAgent {// Drop the late completion of an already-interrupted turn (else it cancels the follow-up).if (this.turns.shouldDropCompletion(turn?.id)) return;if (turn?.status === "failed") {+ // codex reports the terminal cause on the completion itself. Prefer it+ // over the last retry message, which can be stale or never arrived.+ const terminalCause =+ typeof turn.error?.message === "string" ? turn.error.message : "";this.deferFailedTurnFinalization(turn?.id,this.turns.currentGeneration,+ terminalCause,);return;}@@ -1705,20 +1741,30 @@ export class CodexAppServerAgent extends BaseAcpAgent {}if (method === APP_SERVER_NOTIFICATIONS.ERROR) {- // A non-retried fatal error: resolve the turn so prompt() returns rather than hangs.+ // Every error carries a cause worth keeping. A non-retried one also resolves+ // the turn, so prompt() returns rather than hangs.const { willRetry, turnId, error } = (params ?? {}) as {willRetry?: boolean;turnId?: string;error?: { message?: unknown; codexErrorInfo?: unknown };};+ if (turnId && turnId !== this.turns.activeTurnId) {+ return;+ }+ const message = typeof error?.message === "string" ? error.message : "";+ // Keep the newest cause even while codex retries: when the retries run out the+ // turn dies through `turn/completed`, which carries no error text of its own.+ // Bind it to the turn so a later steered turn cannot inherit this cause.+ if (message) {+ this.lastTurnError = {+ turnId: turnId ?? this.turns.activeTurnId,+ message,+ };+ }if (willRetry === false) {- if (turnId && turnId !== this.turns.activeTurnId) {- return;- }this.logger.warn("codex app-server fatal error notification", {params,});- const message = typeof error?.message === "string" ? error.message : "";const codexErrorInfo =typeof error?.codexErrorInfo === "string"? error.codexErrorInfo@@ -1763,7 +1809,7 @@ export class CodexAppServerAgent extends BaseAcpAgent {void this.failTurn(new RequestError(ACP_INTERNAL_ERROR_CODE,- GENERIC_FATAL_ERROR_MESSAGE,+ describeFatalError(message),),);}@@ -2099,6 +2145,7 @@ export class CodexAppServerAgent extends BaseAcpAgent {private deferFailedTurnFinalization(turnId: string | undefined,generation: number,+ terminalCause: string,): void {setTimeout(() => {if (generation !== this.turns.currentGeneration) return;@@ -2110,7 +2157,17 @@ export class CodexAppServerAgent extends BaseAcpAgent {return;}if (!this.turns.isPending) return;- this.refuseTurnWithMessage(GENERIC_FATAL_ERROR_MESSAGE);+ const saved = this.lastTurnError;+ // A saved cause bound to a different turn (e.g. a retry before a steer+ // rotated the id) is not this turn's cause; ignore it.+ const mismatched =+ saved?.turnId !== undefined &&+ turnId !== undefined &&+ saved.turnId !== turnId;+ const savedCause = saved && !mismatched ? saved.message : "";+ this.refuseTurnWithMessage(+ describeFatalError(terminalCause || savedCause),+ );}, 250);}