: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(tasks): let a codex turn failure keep its cause and retry (#93125)
posthog[bot]6d8295bdce28
diff --git a/products/desktop/packages/agent/README.md b/products/desktop/packages/agent/README.mdindex 3a46fb1bae1f..e51db4e3d38e 100644--- a/products/desktop/packages/agent/README.md+++ b/products/desktop/packages/agent/README.md@@ -248,7 +248,7 @@ ACP defines standard methods like `session/prompt`, `session/update`, and `sessi- `_posthog/run_started` — `{ sessionId, runId, taskId?, agentVersion }` — session initialized and ready. `agentVersion` is the agent's semver, used by clients to gate UI features against agent capabilities- `_posthog/task_complete` — `{ sessionId, taskId }` — agent finished (success or end-turn)-- `_posthog/error` — `{ sessionId, message, error? }` — unrecoverable error+- `_posthog/error` — `{ sessionId, message, error?, errorCategory? }` — unrecoverable error. `errorCategory` is the `classifyAgentError()` classification, which the Django log drain reports as the run's cause- `_posthog/status` — `{ sessionId, status, message? }` — progress updates- `_posthog/sdk_session` — `{ taskRunId, sessionId, adapter }` — maps the ACP session to a task run and adapter type (emitted once per session, used by clients to know which adapter is active)diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.tsindex 050039b14ffa..04797370e17d 100644--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts@@ -1393,7 +1393,10 @@ export class ClaudeAcpAgent extends BaseAcpAgent {break;}- const result = handleResultMessage(message);+ const result = handleResultMessage(+ message,+ session.activeTurn?.madeProgress === true,+ );if (result.error) {if (!isTaskNotification) {failActive(result.error);@@ -1621,6 +1624,18 @@ export class ClaudeAcpAgent extends BaseAcpAgent {}}+ if (+ session.activeTurn &&+ message.parent_tool_use_id === null &&+ Array.isArray(message.message.content) &&+ message.message.content.some(+ (block) =>+ block.type === "tool_use" || block.type === "tool_result",+ )+ ) {+ session.activeTurn.madeProgress = true;+ }+const result = await handleUserAssistantMessage(message, context);if (result.error) {failActive(result.error);diff --git a/products/desktop/packages/agent/src/adapters/claude/conversion/sdk-to-acp.test.ts b/products/desktop/packages/agent/src/adapters/claude/conversion/sdk-to-acp.test.tsindex 41321566ec2a..d5c029afe118 100644--- a/products/desktop/packages/agent/src/adapters/claude/conversion/sdk-to-acp.test.ts+++ b/products/desktop/packages/agent/src/adapters/claude/conversion/sdk-to-acp.test.ts@@ -49,6 +49,38 @@ describe("handleResultMessage error text", () => {"Internal error: API Error: 500 something broke",);});++ it("keeps tool progress on a provider error", () => {+ const message = {+ subtype: "success",+ is_error: true,+ result: "API Error: 500 something broke",+ } as unknown as SDKResultMessage;++ const { error } = handleResultMessage(message, true);++ expect(+ (error as unknown as { data?: { madeProgress?: boolean } }).data+ ?.madeProgress,+ ).toBe(true);+ });++ it("keeps tool progress on an execution error", () => {+ const message = {+ subtype: "error_during_execution",+ is_error: true,+ errors: ["API Error: 500 something broke"],+ } as unknown as SDKResultMessage;++ const { error } = handleResultMessage(message, true);++ expect(error).toMatchObject({+ data: expect.objectContaining({+ classification: "upstream_provider_failure",+ madeProgress: true,+ }),+ });+ });});describe("stripMarkerTags", () => {diff --git a/products/desktop/packages/agent/src/adapters/claude/conversion/sdk-to-acp.ts b/products/desktop/packages/agent/src/adapters/claude/conversion/sdk-to-acp.tsindex c17b6bc7acbb..3ebc82f347dd 100644--- a/products/desktop/packages/agent/src/adapters/claude/conversion/sdk-to-acp.ts+++ b/products/desktop/packages/agent/src/adapters/claude/conversion/sdk-to-acp.ts@@ -921,6 +921,7 @@ export type ResultMessageHandlerResult = {export function handleResultMessage(message: SDKResultMessage,+ madeProgress = false,): ResultMessageHandlerResult {const usage = extractUsageFromResult(message);@@ -945,9 +946,10 @@ export function handleResultMessage(classification === "subscription_usage_limit"? new RequestError(ACP_INTERNAL_ERROR_CODE, message.result, {classification,+ madeProgress,}): RequestError.internalError(- { classification, result: message.result },+ { classification, result: message.result, madeProgress },message.result,);return { shouldStop: true, error, usage };@@ -959,11 +961,13 @@ export function handleResultMessage(return { shouldStop: true, stopReason: "max_tokens", usage };}if (message.is_error) {+ const result = message.errors.join(", ") || message.subtype;+ const classification = classifyAgentError(result);return {shouldStop: true,error: RequestError.internalError(- undefined,- message.errors.join(", ") || message.subtype,+ { classification, result, madeProgress },+ result,),usage,};diff --git a/products/desktop/packages/agent/src/adapters/claude/types.ts b/products/desktop/packages/agent/src/adapters/claude/types.tsindex 389ffdfd640a..3693da4d7435 100644--- a/products/desktop/packages/agent/src/adapters/claude/types.ts+++ b/products/desktop/packages/agent/src/adapters/claude/types.ts@@ -71,6 +71,8 @@ export type Turn = {firstMessageTimed?: boolean;/** Set once the first assistant message for this turn has been timed. */firstOutputTimed?: boolean;+ /** A top-level tool call or result was observed during this turn. */+ madeProgress?: boolean;settled: boolean;resolve: (response: PromptResponse) => void;reject: (error: unknown) => void;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 575838a68696..9c53c4eecea8 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@@ -709,6 +709,40 @@ describe("CodexAppServerAgent", () => {});});+ it("does not echo hidden retry blocks into conversation history", async () => {+ 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: "visible" },+ {+ type: "text",+ text: "hidden retry",+ _meta: { ui: { hidden: true } },+ },+ ],+ } as unknown as PromptRequest);+ stub.emit("turn/completed", { turn: { status: "completed" } });+ await done;++ const userMessages = (+ sessionUpdates as Array<{+ update?: { sessionUpdate?: string; content?: unknown };+ }>+ ).filter((update) => update.update?.sessionUpdate === "user_message_chunk");+ expect(userMessages).toHaveLength(1);+ expect(userMessages[0]?.update).toMatchObject({+ content: { type: "text", text: "visible" },+ });+ });+it("reports a steered goal command as accepted so the host does not redeliver it", async () => {const stub = makeStubRpc({"thread/start": { thread: { id: "thr_1" } },@@ -2524,6 +2558,12 @@ describe("CodexAppServerAgent", () => {sessionId: "t",prompt: [{ type: "text", text: "go" }],} as unknown as PromptRequest);+ const rejection = expect(done).rejects.toMatchObject({+ data: expect.objectContaining({+ classification: "upstream_provider_failure",+ result: "API Error: 503",+ }),+ });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", {@@ -2536,17 +2576,16 @@ describe("CodexAppServerAgent", () => {});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",- },- },- });+ await rejection;+ expect(sessionUpdates).not.toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ update: expect.objectContaining({+ sessionUpdate: "agent_message_chunk",+ }),+ }),+ ]),+ );vi.useRealTimers();});@@ -2564,6 +2603,12 @@ describe("CodexAppServerAgent", () => {sessionId: "t",prompt: [{ type: "text", text: "go" }],} as unknown as PromptRequest);+ const rejection = expect(done).rejects.toMatchObject({+ data: expect.objectContaining({+ classification: "upstream_provider_failure",+ result: "API Error: 502",+ }),+ });stub.emit("turn/started", { turn: { id: "turn_1" } });// codex reports the cause only on the completion — no error notification arrived.stub.emit("turn/completed", {@@ -2575,17 +2620,16 @@ describe("CodexAppServerAgent", () => {});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",- },- },- });+ await rejection;+ expect(sessionUpdates).not.toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ update: expect.objectContaining({+ sessionUpdate: "agent_message_chunk",+ }),+ }),+ ]),+ );vi.useRealTimers();});@@ -2603,6 +2647,12 @@ describe("CodexAppServerAgent", () => {sessionId: "t",prompt: [{ type: "text", text: "go" }],} as unknown as PromptRequest);+ const rejection = expect(done).rejects.toMatchObject({+ data: expect.objectContaining({+ classification: "upstream_provider_failure",+ result: "API Error: 500",+ }),+ });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", {@@ -2619,17 +2669,16 @@ describe("CodexAppServerAgent", () => {});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",- },- },- });+ await rejection;+ expect(sessionUpdates).not.toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ update: expect.objectContaining({+ sessionUpdate: "agent_message_chunk",+ }),+ }),+ ]),+ );vi.useRealTimers();});@@ -2742,6 +2791,67 @@ describe("CodexAppServerAgent", () => {);});+ it("carries the app-server cause and its classification on a fatal error", async () => {+ // The display carries the app-server's cause, and the error data carries its+ // classification so the host can tell a transient upstream cut from a real+ // agent error. Without the classification the host skips its bounded turn+ // retry and the run dies.+ const stub = makeStubRpc({ "thread/start": { thread: { id: "t" } } });+ const { client, extNotifications } = 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("thread/tokenUsage/updated", {+ tokenUsage: {+ total: { inputTokens: 10, outputTokens: 5 },+ last: { inputTokens: 10, outputTokens: 5 },+ },+ });+ stub.emit("item/completed", {+ item: { type: "fileChange", id: "edit-1", changes: [] },+ });+ stub.emit("error", {+ willRetry: false,+ error: { message: "unexpected status 503 Service Unavailable: retry" },+ });++ const err = await done.then(+ () => {+ throw new Error("prompt resolved instead of rejecting");+ },+ (e: unknown) => e,+ );+ expect(err).toBeInstanceOf(RequestError);+ // Exact match: the client renders this sentence, so a stray "Internal+ // error: " prefix from RequestError.internalError() would be a regression a+ // substring assertion could not catch.+ expect((err as RequestError).message).toBe(+ "The agent stopped before completing this request: unexpected status 503 Service Unavailable: retry",+ );+ expect((err as RequestError).data).toMatchObject({+ classification: "upstream_provider_failure",+ result: "unexpected status 503",+ madeProgress: true,+ usage: {+ inputTokens: 10,+ outputTokens: 5,+ totalTokens: 15,+ },+ });+ expect(+ extNotifications.filter(+ (notification) => notification.method === "_posthog/turn_complete",+ ),+ ).toHaveLength(0);+ });+it("rejects the prompt when the fatal error is a gateway billing denial", async () => {// A silent refusal would hide the free-tier gate: the host only shows the// upgrade modal when the prompt rejects with the gateway's message.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 c39a3c7ea920..b230a543f6a5 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@@ -60,6 +60,11 @@ import {emptyBaseline,estimateTokens,} from "../claude/context-breakdown";+import {+ classifyAgentError,+ isRetryableUpstreamErrorClassification,+ sanitizeAgentErrorCause,+} from "../error-classification";import { isLocalSkillCommandChunk } from "../local-skill";import { LOCAL_TOOLS_MCP_NAME } from "../local-tools";import { visiblePromptBlocks } from "../prompt-blocks";@@ -106,21 +111,19 @@ import { parseStructuredOutput } from "./structured-output";import { TurnController } from "./turn-controller";import { mergeUsage, UsageTracker } from "./usage-tracker";-const ACP_INTERNAL_ERROR_CODE = -32603;const CYBER_POLICY_ERROR_MESSAGE ="This request was blocked because it may pose a cybersecurity risk. Revise the request and try again.";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. */+/** Keeps an excessively long upstream payload out of the chat bubble. */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.+ * Without the cause every unclassified failure looks the same to the user.*/function describeFatalError(upstream: string): string {const cause = upstream.trim();@@ -343,6 +346,8 @@ export class CodexAppServerAgent extends BaseAcpAgent {private readonly mcp = new McpManager();private readonly turns = new TurnController();private readonly usage = new UsageTracker();+ /** True after the current turn completes a tool that can have side effects. */+ private turnMadeProgress = false;/** Pause/clear can race a goal continuation already queued by app-server. */private cancelNextGoalTurn = false;/** Native goal ticks start outside prompt(), so TurnController does not own them. */@@ -1185,6 +1190,7 @@ export class CodexAppServerAgent extends BaseAcpAgent {this.lastAgentMessage = "";this.lastTurnError = undefined;this.resetUsage();+ this.turnMadeProgress = false;this.planProposal = undefined;this.streamedPlanToolCallId = undefined;// A new turn owns the idle boundary; its own completion emits the signal.@@ -1528,7 +1534,7 @@ export class CodexAppServerAgent extends BaseAcpAgent {/** Echo each user prompt block (text + image, so an image-only turn still renders) for the host log/UI. */private broadcastUserInput(prompt: PromptRequest["prompt"]): void {if (!this.sessionId) return;- for (const block of prompt) {+ for (const block of visiblePromptBlocks(prompt)) {if (block.type !== "text" && block.type !== "image") continue;void this.client.sessionUpdate({@@ -1672,6 +1678,19 @@ export class CodexAppServerAgent extends BaseAcpAgent {}if (method === APP_SERVER_NOTIFICATIONS.ITEM_COMPLETED) {+ const itemType = (params as { item?: AppServerItem })?.item?.type;+ if (+ itemType &&+ [+ "commandExecution",+ "fileChange",+ "mcpToolCall",+ "dynamicToolCall",+ "collabAgentToolCall",+ ].includes(itemType)+ ) {+ this.turnMadeProgress = true;+ }this.captureAgentMessage(params);this.capturePlanProposal(params);}@@ -1806,11 +1825,12 @@ export class CodexAppServerAgent extends BaseAcpAgent {void this.refuseTurnWithMessage(message);return;}+ // The client displays the full cause. The error data keeps only the+ // fields that can enter wider diagnostic sinks.+ const failure = this.classifiedTurnFailure(message);void this.failTurn(- new RequestError(- ACP_INTERNAL_ERROR_CODE,- describeFatalError(message),- ),+ failure.error,+ !isRetryableUpstreamErrorClassification(failure.classification),);}}@@ -2128,7 +2148,7 @@ export class CodexAppServerAgent extends BaseAcpAgent {});}- private async failTurn(error: Error): Promise<void> {+ private async failTurn(error: Error, emitTurnComplete = true): Promise<void> {this.turns.markInterrupted();const pending = this.turns.claim();if (!pending) return;@@ -2138,7 +2158,9 @@ export class CodexAppServerAgent extends BaseAcpAgent {}const usage = this.usage.perTurnUsage();pending.reject(error);- void this.emitTurnCompleteSignal("refusal", usage);+ if (emitTurnComplete) {+ void this.emitTurnCompleteSignal("refusal", usage);+ }void this.emitUsageBreakdown(this.usage.contextTokens());}@@ -2165,12 +2187,33 @@ export class CodexAppServerAgent extends BaseAcpAgent {turnId !== undefined &&saved.turnId !== turnId;const savedCause = saved && !mismatched ? saved.message : "";- this.refuseTurnWithMessage(- describeFatalError(terminalCause || savedCause),- );+ const cause = terminalCause || savedCause;+ const failure = this.classifiedTurnFailure(cause);+ if (isRetryableUpstreamErrorClassification(failure.classification)) {+ void this.failTurn(failure.error, false);+ return;+ }+ this.refuseTurnWithMessage(describeFatalError(cause));}, 250);}+ private classifiedTurnFailure(message: string): {+ classification: ReturnType<typeof classifyAgentError>;+ error: RequestError;+ } {+ const classification = classifyAgentError(message);+ const usage = this.usage.perTurnUsage();+ return {+ classification,+ error: new RequestError(-32603, describeFatalError(message), {+ classification,+ result: sanitizeAgentErrorCause(message, classification),+ madeProgress: this.turnMadeProgress,+ ...(usage ? { usage } : {}),+ }),+ };+ }+private refuseTurnWithMessage(message: string): void {if (this.session.cancelled) return;this.turns.markInterrupted();diff --git a/products/desktop/packages/agent/src/adapters/error-classification.test.ts b/products/desktop/packages/agent/src/adapters/error-classification.test.tsindex f4daa49d0b81..899fd02d2222 100644--- a/products/desktop/packages/agent/src/adapters/error-classification.test.ts+++ b/products/desktop/packages/agent/src/adapters/error-classification.test.ts@@ -2,6 +2,8 @@ import { describe, expect, it } from "vitest";import {classifyAgentError,isPromptTooLongError,+ isRetryableUpstreamErrorClassification,+ sanitizeAgentErrorCause,} from "./error-classification";describe("classifyAgentError", () => {@@ -30,6 +32,16 @@ describe("classifyAgentError", () => {"API Error: Content block is not a thinking block","content_block_rejection",],+ // The codex app-server reports provider HTTP failures with its own wording.+ [+ "unexpected status 429 Too Many Requests: slow down",+ "upstream_provider_failure",+ ],+ [+ "unexpected status 502 Bad Gateway: upstream unavailable",+ "upstream_provider_failure",+ ],+ ["unexpected status 403 Forbidden: needs a paid plan", "agent_error"],["[ede_diagnostic] result_type=user last_content_type=n/a stop_reason=null","turn_ended_without_response",@@ -56,6 +68,77 @@ describe("classifyAgentError", () => {});});+describe("isRetryableUpstreamErrorClassification", () => {+ it.each([+ ["upstream_stream_terminated", true],+ ["upstream_connection_error", true],+ ["upstream_timeout", true],+ ["upstream_provider_failure", true],+ ["content_block_rejection", false],+ ["turn_ended_without_response", false],+ ["subscription_usage_limit", false],+ ["agent_error", false],+ ] as const)("marks %s as retryable: %s", (classification, expected) => {+ expect(isRetryableUpstreamErrorClassification(classification)).toBe(+ expected,+ );+ });+});++describe("sanitizeAgentErrorCause", () => {+ it.each([+ [+ "unexpected status 503 Service Unavailable: private provider body",+ "upstream_provider_failure",+ "unexpected status 503",+ ],+ [+ "unexpected status 403 Forbidden: private provider body",+ "agent_error",+ "unexpected status 403",+ ],+ [+ "API Error: 529 private provider body",+ "upstream_provider_failure",+ "API Error: 529",+ ],+ [+ "Internal error: API Error: 403 private provider body",+ "agent_error",+ "API Error: 403",+ ],+ [+ "provider request failed without a status",+ "upstream_provider_failure",+ "upstream_provider_failure",+ ],+ [+ "Connection failed: private request details",+ "upstream_connection_error",+ "upstream_connection_error",+ ],+ [+ "Stream terminated after private tool output",+ "upstream_stream_terminated",+ "upstream_stream_terminated",+ ],+ [+ "Request timed out after sending private repository content",+ "upstream_timeout",+ "upstream_timeout",+ ],+ ["agent process exited", "agent_error", "agent process exited"],+ ] as const)("sanitizes %j as %j", (message, classification, expected) => {+ expect(sanitizeAgentErrorCause(message, classification)).toBe(expected);+ });++ it("limits an unclassified cause before persistence", () => {+ const cause = "private response content ".repeat(100);++ expect(sanitizeAgentErrorCause(cause, "agent_error")).toHaveLength(400);+ });+});+describe("isPromptTooLongError", () => {it.each([[diff --git a/products/desktop/packages/agent/src/adapters/error-classification.ts b/products/desktop/packages/agent/src/adapters/error-classification.tsindex dcbaca23447e..c15376bdf545 100644--- a/products/desktop/packages/agent/src/adapters/error-classification.ts+++ b/products/desktop/packages/agent/src/adapters/error-classification.ts@@ -10,7 +10,25 @@ export type AgentErrorClassification =| "subscription_usage_limit"| "agent_error";+const RETRYABLE_UPSTREAM_ERROR_CLASSIFICATIONS =+ new Set<AgentErrorClassification>([+ "upstream_stream_terminated",+ "upstream_connection_error",+ "upstream_timeout",+ "upstream_provider_failure",+ ]);++export function isRetryableUpstreamErrorClassification(+ classification: AgentErrorClassification,+): boolean {+ return RETRYABLE_UPSTREAM_ERROR_CLASSIFICATIONS.has(classification);+}+const UPSTREAM_PROVIDER_ERROR_STATUS_PATTERN = /API Error:\s*(?:429|5\d\d)\b/i;+// The codex app-server reports a provider HTTP failure as+// "unexpected status <code> <reason>: <body>" instead of the "API Error:" wording.+const CODEX_PROVIDER_ERROR_STATUS_PATTERN =+ /unexpected status\s*(?:429|5\d\d)\b/i;const TURN_ENDED_WITHOUT_RESPONSE_PATTERN =/\[ede_diagnostic\]\s+result_type=user\b/i;// Anthropic's exact CLI wording for a Claude Pro/Max own-subscription limit@@ -57,7 +75,10 @@ export function classifyAgentError(if (/API Error:.*\b(?:timed out|timeout)\b/i.test(text)) {return "upstream_timeout";}- if (UPSTREAM_PROVIDER_ERROR_STATUS_PATTERN.test(text)) {+ if (+ UPSTREAM_PROVIDER_ERROR_STATUS_PATTERN.test(text) ||+ CODEX_PROVIDER_ERROR_STATUS_PATTERN.test(text)+ ) {return "upstream_provider_failure";}if (/API Error:\s*Content block\b/i.test(text)) {@@ -72,6 +93,30 @@ export function classifyAgentError(return "agent_error";}+export function sanitizeAgentErrorCause(+ result: string,+ classification: AgentErrorClassification,+): string {+ const text = result.trim();+ const codexStatus = text.match(/\bunexpected status\s+(\d{3})\b/i);+ if (codexStatus) {+ return `unexpected status ${codexStatus[1]}`;+ }+ const apiStatus = text.match(/\bAPI Error:\s*(\d{3})\b/i);+ if (apiStatus) {+ return `API Error: ${apiStatus[1]}`;+ }+ if (+ classification === "upstream_provider_failure" ||+ classification === "upstream_connection_error" ||+ classification === "upstream_stream_terminated" ||+ classification === "upstream_timeout"+ ) {+ return classification;+ }+ return text.slice(0, 400);+}+/*** Hard API rejection: the prompt exceeds the model's context window* (Anthropic phrasing, or the LLM gateway's HTTP 413). Retrying the samediff --git a/products/desktop/packages/agent/src/otel-telemetry.ts b/products/desktop/packages/agent/src/otel-telemetry.tsindex a9c62f84f728..aa9bccc237be 100644--- a/products/desktop/packages/agent/src/otel-telemetry.ts+++ b/products/desktop/packages/agent/src/otel-telemetry.ts@@ -195,9 +195,11 @@ export function mapNotificationToLogRecord(// params.error is free text that can embed prompt or repo content// (exception messages, provider errors), so only its provenance is// exported. The raw message stays in the session log and on the task- // run's error_message.+ // run's error_message. The classification is a fixed vocabulary, so it is+ // safe to export and lets APM split failures by class.const attrs: Attributes = {};strAttr(attrs, "error_source", params.source);+ strAttr(attrs, "error_category", params.errorCategory);strAttr(attrs, "stop_reason", params.stopReason);return record(ERROR, "run error", method, attrs);}diff --git a/products/desktop/packages/agent/src/otel-trace-builder.ts b/products/desktop/packages/agent/src/otel-trace-builder.tsindex 1d1091d066e8..012fc7d23ee6 100644--- a/products/desktop/packages/agent/src/otel-trace-builder.ts+++ b/products/desktop/packages/agent/src/otel-trace-builder.ts@@ -283,9 +283,11 @@ export class RunTraceBuilder {this.closeTurn({ stopReason, errored: true }, time);// params.error is free text that can embed prompt or repo content, so// only the error's provenance is exported; the raw message stays in the- // session log and on the task run's error_message.+ // session log and on the task run's error_message. The classification is a+ // fixed vocabulary, so it is safe to export.const attrs: Attributes = {};strAttr(attrs, "error_source", params.source);+ strAttr(attrs, "error_category", params.errorCategory);this.rootSpan.setAttributes(attrs);this.rootSpan.setStatus({ code: SpanStatusCode.ERROR });return this.rootContext;diff --git a/products/desktop/packages/agent/src/server/agent-server.test.ts b/products/desktop/packages/agent/src/server/agent-server.test.tsindex 34678c60488d..eba2310cceea 100644--- a/products/desktop/packages/agent/src/server/agent-server.test.ts+++ b/products/desktop/packages/agent/src/server/agent-server.test.ts@@ -10,7 +10,7 @@ import {} from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";-import type { ContentBlock } from "@agentclientprotocol/sdk";+import { type ContentBlock, RequestError } from "@agentclientprotocol/sdk";import type { Adapter } from "@posthog/shared";import { zipSync } from "fflate";import jwt from "jsonwebtoken";@@ -32,6 +32,7 @@ import { SIMPLIFIED_TECHNICAL_ENGLISH_INSTRUCTION as STE100_INSTRUCTION } from "import type { PermissionMode } from "../execution-mode";import type { PostHogAPIClient } from "../posthog-api";import type { ResumeState } from "../resume";+import { SessionLogWriter } from "../session-log-writer";import {createMockApiClient,createTaskRun,@@ -45,6 +46,7 @@ import {isTurnCompleteNotification,PREWARMED_RESUME_IDLE_CAPABILITY,SSE_KEEPALIVE_INTERVAL_MS,+ UPSTREAM_PROVIDER_FAILURE_MESSAGE,} from "./agent-server";import { type JwtPayload, SANDBOX_CONNECTION_AUDIENCE } from "./jwt";import type { ExistingPrCheckoutResult } from "./pr-checkout";@@ -795,6 +797,7 @@ describe("AgentServer HTTP Mode", () => {payload: JwtPayload,stopReason: string,errorMessage?: string,+ options?: { errorCategory?: string },): Promise<void>;};testServer.eventStreamSender = {@@ -823,6 +826,7 @@ describe("AgentServer HTTP Mode", () => {},"error","boom",+ { errorCategory: "agent_error" },);expect(order).toEqual(["enqueue", "update", "stop"]);@@ -840,11 +844,240 @@ describe("AgentServer HTTP Mode", () => {"run-1",{status: "failed",- error_message: "boom",+ error_message: "agent_error: boom",},);});+ it("writes the terminal error to the session log before the final flush", async () => {+ // The Django drain reads the terminal `_posthog/error` from the S3 log,+ // which only the SessionLogWriter feeds. The event must be appended before+ // the final flush that ships the log to S3, or the drain never sees it and+ // falls back to the generic terminal message.+ const order: string[] = [];+ const appendRawLine = vi.fn((_sessionId: string, _line: string) => {+ order.push("append");+ });+ const flush = vi.fn(async () => {+ order.push("flush");+ });+ const testServer = new AgentServer({+ port,+ jwtPublicKey: TEST_PUBLIC_KEY,+ repositoryPath: repo.path,+ apiUrl: "http://localhost:8000",+ apiKey: "test-api-key",+ projectId: 1,+ mode: "interactive",+ taskId: "test-task-id",+ runId: "test-run-id",+ }) as unknown as {+ eventStreamSender: {+ enqueue: ReturnType<typeof vi.fn>;+ stop: () => Promise<void>;+ };+ posthogAPI: { updateTaskRun: ReturnType<typeof vi.fn> };+ session: unknown;+ signalTaskComplete(+ payload: JwtPayload,+ stopReason: string,+ errorMessage?: string,+ options?: { errorCategory?: string },+ ): Promise<void>;+ };+ testServer.eventStreamSender = {+ enqueue: vi.fn(),+ stop: vi.fn(async () => {}),+ };+ testServer.posthogAPI = { updateTaskRun: vi.fn(async () => ({})) };+ testServer.session = {+ acpSessionId: "acp-1",+ payload: { run_id: "run-1" },+ logWriter: { appendRawLine, flush },+ };++ await testServer.signalTaskComplete(+ {+ run_id: "run-1",+ task_id: "task-1",+ team_id: 1,+ user_id: 1,+ distinct_id: "distinct-id",+ mode: "interactive",+ },+ "error",+ "unexpected status 503",+ { errorCategory: "upstream_provider_failure" },+ );++ // Appended to the log, and before the flush.+ expect(order).toEqual(["append", "flush"]);+ // Exactly the notification the drain's `_extract_agent_error` parses.+ const rawLine = appendRawLine.mock.calls[0][1] as string;+ const notification = JSON.parse(rawLine);+ expect(notification.method).toBe("_posthog/error");+ expect(notification.params).toMatchObject({+ message: "unexpected status 503",+ errorCategory: "upstream_provider_failure",+ error_category: "upstream_provider_failure",+ });+ });++ it("does not send an old failure into a replacement session", async () => {+ const appendRawLine = vi.fn();+ const flush = vi.fn(async () => {});+ const shutdown = vi.fn(async () => {});+ const testServer = new AgentServer({+ port,+ jwtPublicKey: TEST_PUBLIC_KEY,+ repositoryPath: repo.path,+ apiUrl: "http://localhost:8000",+ apiKey: "test-api-key",+ projectId: 1,+ mode: "interactive",+ taskId: "test-task-id",+ runId: "test-run-id",+ }) as unknown as {+ eventStreamSender: {+ enqueue: ReturnType<typeof vi.fn>;+ stop: ReturnType<typeof vi.fn>;+ };+ posthogAPI: { updateTaskRun: ReturnType<typeof vi.fn> };+ session: unknown;+ handleTurnFailure(+ payload: JwtPayload,+ phase: "initial" | "resume" | "followup",+ error: unknown,+ ): Promise<void>;+ };+ testServer.eventStreamSender = {+ enqueue: vi.fn(),+ stop: vi.fn(async () => {}),+ };+ testServer.posthogAPI = { updateTaskRun: vi.fn(async () => ({})) };+ testServer.session = {+ payload: { run_id: "run-2" },+ logWriter: { appendRawLine, flush },+ telemetry: { shutdown },+ };++ await testServer.handleTurnFailure(+ {+ run_id: "run-1",+ task_id: "task-1",+ team_id: 1,+ user_id: 1,+ distinct_id: "distinct-id",+ mode: "interactive",+ },+ "initial",+ new Error("old run failed"),+ );++ expect(testServer.eventStreamSender.enqueue).not.toHaveBeenCalled();+ expect(testServer.eventStreamSender.stop).not.toHaveBeenCalled();+ expect(appendRawLine).not.toHaveBeenCalled();+ expect(flush).not.toHaveBeenCalled();+ expect(shutdown).not.toHaveBeenCalled();+ expect(testServer.posthogAPI.updateTaskRun).toHaveBeenCalledWith(+ "task-1",+ "run-1",+ {+ status: "failed",+ error_message: "agent_error: old run failed",+ },+ );+ });++ it("does not stop a replacement session after a final flush", async () => {+ let releaseFlush!: () => void;+ const flushPending = new Promise<void>((resolve) => {+ releaseFlush = resolve;+ });+ const flush = vi.fn(() => flushPending);+ const testServer = createFailureTestServer() as unknown as {+ eventStreamSender: {+ enqueue: ReturnType<typeof vi.fn>;+ stop: ReturnType<typeof vi.fn>;+ };+ posthogAPI: { updateTaskRun: ReturnType<typeof vi.fn> };+ session: unknown;+ signalTaskComplete(+ payload: JwtPayload,+ stopReason: string,+ errorMessage?: string,+ options?: { errorCategory?: string },+ ): Promise<void>;+ };+ testServer.session = {+ payload: { run_id: "run-1" },+ logWriter: { appendRawLine: vi.fn(), flush },+ telemetry: { shutdown: vi.fn(async () => {}) },+ };++ const completion = testServer.signalTaskComplete(+ interactivePayload,+ "error",+ "old run failed",+ { errorCategory: "agent_error" },+ );+ await vi.waitFor(() => expect(flush).toHaveBeenCalledOnce());+ testServer.session = {+ payload: { run_id: "run-2" },+ logWriter: { appendRawLine: vi.fn(), flush: vi.fn() },+ };+ releaseFlush();+ await completion;++ expect(testServer.eventStreamSender.stop).not.toHaveBeenCalled();+ });++ it("does not stop a replacement session after reporting savings", async () => {+ let releaseSavings!: () => void;+ const savingsPending = new Promise<void>((resolve) => {+ releaseSavings = resolve;+ });+ const testServer = createFailureTestServer() as unknown as {+ eventStreamSender: {+ enqueue: ReturnType<typeof vi.fn>;+ stop: ReturnType<typeof vi.fn>;+ };+ posthogAPI: { updateTaskRun: ReturnType<typeof vi.fn> };+ session: unknown;+ emitRtkSavings: ReturnType<typeof vi.fn>;+ signalTaskComplete(+ payload: JwtPayload,+ stopReason: string,+ errorMessage?: string,+ options?: { errorCategory?: string },+ ): Promise<void>;+ };+ testServer.emitRtkSavings = vi.fn(() => savingsPending);+ testServer.session = {+ payload: { run_id: "run-1" },+ logWriter: { appendRawLine: vi.fn(), flush: vi.fn(async () => {}) },+ telemetry: { shutdown: vi.fn(async () => {}) },+ };++ const completion = testServer.signalTaskComplete(+ interactivePayload,+ "error",+ "old run failed",+ { errorCategory: "agent_error" },+ );+ await vi.waitFor(() =>+ expect(testServer.emitRtkSavings).toHaveBeenCalledOnce(),+ );+ testServer.session = {+ payload: { run_id: "run-2" },+ logWriter: { appendRawLine: vi.fn(), flush: vi.fn() },+ };+ releaseSavings();+ await completion;++ expect(testServer.eventStreamSender.stop).not.toHaveBeenCalled();+ });+it("still stops event ingest when terminal failure status update fails", async () => {const testServer = new AgentServer({port,@@ -1095,7 +1328,22 @@ describe("AgentServer HTTP Mode", () => {// trace's root span only exports if telemetry is shut down at the run's// in-process terminal points.it("shuts down telemetry after mirroring the terminal failure record", async () => {+ // In production telemetry is the SessionLogWriter's sink, so the terminal+ // event reaches it through the log rather than a direct append. Wire it the+ // same way and assert the mirror still lands before shutdown, so the root+ // span exports with ERROR status.const order: string[] = [];+ const telemetry = {+ append: vi.fn((_sessionId: string, _entry: unknown) => {+ order.push("append");+ }),+ shutdown: vi.fn(async () => {+ order.push("shutdown");+ }),+ };+ const logWriter = new SessionLogWriter({ sinks: [telemetry] });+ logWriter.register("run-1", { taskId: "task-1", runId: "run-1" });+const testServer = new AgentServer({port,jwtPublicKey: TEST_PUBLIC_KEY,@@ -1107,14 +1355,7 @@ describe("AgentServer HTTP Mode", () => {taskId: "test-task-id",runId: "test-run-id",}) as unknown as {- session: {- payload: { run_id: string };- logWriter: { flush: ReturnType<typeof vi.fn> };- telemetry: {- append: ReturnType<typeof vi.fn>;- shutdown: ReturnType<typeof vi.fn>;- };- };+ session: unknown;eventStreamSender: {enqueue: (event: Record<string, unknown>) => void;stop: () => Promise<void>;@@ -1141,15 +1382,8 @@ describe("AgentServer HTTP Mode", () => {};testServer.session = {payload: { run_id: "run-1" },- logWriter: { flush: vi.fn(async () => {}) },- telemetry: {- append: vi.fn(() => {- order.push("append");- }),- shutdown: vi.fn(async () => {- order.push("shutdown");- }),- },+ logWriter,+ telemetry,};await testServer.signalTaskComplete(@@ -1168,6 +1402,11 @@ describe("AgentServer HTTP Mode", () => {// The error mirror must land before shutdown so the root span exports// with ERROR status.expect(order).toEqual(["append", "shutdown"]);+ const [, entry] = telemetry.append.mock.calls[0] as [+ string,+ { notification: { method: string } },+ ];+ expect(entry.notification.method).toBe("_posthog/error");});it.each([@@ -1327,6 +1566,20 @@ describe("AgentServer HTTP Mode", () => {}if (expectsFailed) {+ // The Django log drain reads `message` and `errorCategory` off this+ // event; without them a failed run only carries a generic wrapper.+ expect(testServer.eventStreamSender.enqueue).toHaveBeenCalledWith(+ expect.objectContaining({+ notification: expect.objectContaining({+ method: "_posthog/error",+ params: expect.objectContaining({+ message: errorMessage,+ errorCategory: expectedErrorType,+ error_category: expectedErrorType,+ }),+ }),+ }),+ );expect(testServer.posthogAPI.updateTaskRun).toHaveBeenCalledWith("task-1","run-1",@@ -1338,6 +1591,195 @@ describe("AgentServer HTTP Mode", () => {},);+ it("records usage from a recoverable interactive follow-up", async () => {+ const testServer = createFailureTestServer();+ const error = new RequestError(+ -32603,+ "The upstream provider did not complete this request.",+ {+ classification: "upstream_timeout",+ result: "API Error: The operation timed out.",+ usage: {+ inputTokens: 100,+ outputTokens: 50,+ totalTokens: 150,+ },+ },+ );++ const disposition = await testServer.handleTurnFailure(+ interactivePayload,+ "followup",+ error,+ );++ expect(disposition).toBe("recoverable");+ expect(testServer.posthogAPI.updateTaskRun).toHaveBeenCalledWith(+ "task-1",+ "run-1",+ {+ state: {+ token_usage: {+ input_tokens: 100,+ output_tokens: 50,+ cache_read_tokens: 0,+ cache_write_tokens: 0,+ thought_tokens: 0,+ total_tokens: 150,+ turns: 1,+ },+ },+ },+ );+ });++ it("keeps replaced-run usage and completion out of the active run", async () => {+ let releaseUsage!: () => void;+ const usagePending = new Promise<void>((resolve) => {+ releaseUsage = resolve;+ });+ const testServer = createFailureTestServer() as ReturnType<+ typeof createFailureTestServer+ > & {+ recordTurnUsage(+ usage: {+ inputTokens: number;+ outputTokens: number;+ totalTokens: number;+ },+ payload: JwtPayload,+ ): Promise<void>;+ };+ testServer.posthogAPI.updateTaskRun = vi+ .fn()+ .mockImplementationOnce(() => usagePending)+ .mockResolvedValue({});+ const error = new RequestError(-32603, "upstream timeout", {+ classification: "upstream_timeout",+ result: "upstream_timeout",+ usage: { inputTokens: 100, outputTokens: 50, totalTokens: 150 },+ });++ const failure = testServer.handleTurnFailure(+ interactivePayload,+ "followup",+ error,+ );+ await vi.waitFor(() =>+ expect(testServer.posthogAPI.updateTaskRun).toHaveBeenCalledOnce(),+ );+ const replacementPayload = { ...interactivePayload, run_id: "run-2" };+ testServer.session = {+ acpSessionId: "acp-2",+ payload: replacementPayload,+ };+ releaseUsage();++ await expect(failure).resolves.toBe("recoverable");+ expect(testServer.eventStreamSender.enqueue).not.toHaveBeenCalledWith(+ expect.objectContaining({+ notification: expect.objectContaining({+ method: POSTHOG_NOTIFICATIONS.TURN_COMPLETE,+ }),+ }),+ );++ await testServer.recordTurnUsage(+ { inputTokens: 20, outputTokens: 10, totalTokens: 30 },+ replacementPayload,+ );+ expect(testServer.posthogAPI.updateTaskRun).toHaveBeenLastCalledWith(+ "task-1",+ "run-2",+ expect.objectContaining({+ state: {+ token_usage: expect.objectContaining({+ input_tokens: 20,+ output_tokens: 10,+ total_tokens: 30,+ }),+ },+ }),+ );+ });++ it("reports the app-server cause, not the generic display text, on a fatal error", async () => {+ // A codex fatal error reaches the host as a RequestError whose display+ // text is generic; the real cause rides on `data.result`. The live client+ // keeps the generic text, but the terminal event and task-run update must+ // carry the cause so a failed run is diagnosable rather than one opaque+ // bucket.+ const testServer = createFailureTestServer();+ const cause = "unexpected status 403 Forbidden: needs a paid plan";+ const fatalError = RequestError.internalError(+ { classification: "agent_error", result: cause },+ "The agent stopped before completing this request. Please try again.",+ );++ await testServer.handleTurnFailure(+ interactivePayload,+ "initial",+ fatalError,+ );++ // Live client: the generic display text, not the raw cause.+ expect(testServer.eventStreamSender.enqueue).toHaveBeenCalledWith(+ expect.objectContaining({+ notification: expect.objectContaining({+ method: "session/update",+ params: expect.objectContaining({+ update: expect.objectContaining({+ sessionUpdate: "error",+ errorType: "agent_error",+ message: expect.stringContaining("The agent stopped"),+ }),+ }),+ }),+ }),+ );++ // Diagnostic path: the app-server cause.+ expect(testServer.eventStreamSender.enqueue).toHaveBeenCalledWith(+ expect.objectContaining({+ notification: expect.objectContaining({+ method: "_posthog/error",+ params: expect.objectContaining({+ message: "unexpected status 403",+ error: "unexpected status 403",+ errorCategory: "agent_error",+ }),+ }),+ }),+ );+ expect(testServer.posthogAPI.updateTaskRun).toHaveBeenCalledWith(+ "task-1",+ "run-1",+ expect.objectContaining({+ status: "failed",+ error_message: "agent_error: unexpected status 403",+ }),+ );+ });++ it("sanitizes an unstructured provider cause before persistence", async () => {+ const testServer = createFailureTestServer();++ await testServer.handleTurnFailure(+ interactivePayload,+ "initial",+ new Error("API Error: 503 private provider body"),+ );++ expect(testServer.posthogAPI.updateTaskRun).toHaveBeenCalledWith(+ "task-1",+ "run-1",+ expect.objectContaining({+ status: "failed",+ error_message: `upstream_provider_failure: ${UPSTREAM_PROVIDER_FAILURE_MESSAGE}`,+ }),+ );+ });+it("quietly ends an interactive follow-up when its idle ACP transport closed", async () => {const testServer = createFailureTestServer();@@ -1381,16 +1823,30 @@ describe("AgentServer HTTP Mode", () => {const testServer = createFailureTestServer();testServer.session = {acpSessionId: "acp-1",- payload: { run_id: "run-1" },+ payload: { run_id: "run-1", task_id: "task-1" },logWriter: { appendRawLine: vi.fn(), flush: vi.fn(async () => {}) },- clientConnection: { prompt },+ clientConnection: { prompt, cancel: vi.fn(async () => {}) },};return testServer as unknown as {eventStreamSender: { enqueue: ReturnType<typeof vi.fn> };- promptWithUpstreamRetry(request: {- sessionId: string;- prompt: ContentBlock[];- }): Promise<{ stopReason: string }>;+ posthogAPI: { updateTaskRun: ReturnType<typeof vi.fn> };+ session: unknown;+ executeCommand(+ method: string,+ params: Record<string, unknown>,+ ): Promise<unknown>;+ promptWithUpstreamRetry(+ request: {+ sessionId: string;+ prompt: ContentBlock[];+ },+ recordFailedUsage?: boolean,+ ): Promise<{+ stopReason: string;+ usage?: { inputTokens?: number; outputTokens?: number };+ }>;+ runStartupTurn<T>(operation: () => Promise<T>): Promise<T>;+ runRetryWrappedTurn<T>(operation: () => Promise<T>): Promise<T>;};}@@ -1403,10 +1859,12 @@ describe("AgentServer HTTP Mode", () => {.mockResolvedValueOnce({ stopReason: "end_turn" });const testServer = createRetryTestServer(prompt);- const resultPromise = testServer.promptWithUpstreamRetry({- sessionId: "acp-1",- prompt: [{ type: "text", text: "do the task" }],- });+ const resultPromise = testServer.runRetryWrappedTurn(() =>+ testServer.promptWithUpstreamRetry({+ sessionId: "acp-1",+ prompt: [{ type: "text", text: "do the task" }],+ }),+ );await vi.advanceTimersByTimeAsync(5_000);await expect(resultPromise).resolves.toEqual({@@ -1433,6 +1891,278 @@ describe("AgentServer HTTP Mode", () => {}});+ it("stops a retry after another session replaces its session", async () => {+ vi.useFakeTimers();+ try {+ const prompt = vi+ .fn()+ .mockRejectedValueOnce(new Error("API Error: Connection error."));+ const testServer = createRetryTestServer(prompt);+ const resultPromise = testServer.runStartupTurn(() =>+ testServer.promptWithUpstreamRetry({+ sessionId: "acp-1",+ prompt: [{ type: "text", text: "do the task" }],+ }),+ );+ const assertion = expect(resultPromise).rejects.toThrow(+ "Agent session changed before the turn could be retried",+ );+ await Promise.resolve();+ testServer.session = {+ acpSessionId: "acp-2",+ payload: { run_id: "run-2" },+ clientConnection: { prompt: vi.fn() },+ };+ await vi.advanceTimersByTimeAsync(5_000);++ await assertion;+ expect(prompt).toHaveBeenCalledOnce();+ } finally {+ vi.useRealTimers();+ }+ });++ it("keeps continuation mode after a second retryable failure", async () => {+ vi.useFakeTimers();+ try {+ const prompt = vi+ .fn()+ .mockRejectedValueOnce(new Error("API Error: terminated"))+ .mockRejectedValueOnce(new Error("API Error: Connection error."))+ .mockResolvedValueOnce({ stopReason: "end_turn" });+ const testServer = createRetryTestServer(prompt);+ const resultPromise = testServer.promptWithUpstreamRetry({+ sessionId: "acp-1",+ prompt: [{ type: "text", text: "do the task" }],+ });+ await vi.advanceTimersByTimeAsync(10_000);++ await expect(resultPromise).resolves.toEqual({+ stopReason: "end_turn",+ });+ expect(prompt).toHaveBeenCalledTimes(3);+ for (const call of prompt.mock.calls.slice(1)) {+ const retryRequest = call[0] as {+ prompt: Array<{ type: string; text: string }>;+ };+ expect(retryRequest.prompt[0].text).toContain(+ "Continue from where you left off",+ );+ }+ } finally {+ vi.useRealTimers();+ }+ });++ it("stops retrying when the user cancels during the retry delay", async () => {+ vi.useFakeTimers();+ try {+ const prompt = vi+ .fn()+ .mockRejectedValueOnce(new Error("API Error: Connection error."));+ const testServer = createRetryTestServer(prompt);+ const resultPromise = testServer.runRetryWrappedTurn(() =>+ testServer.promptWithUpstreamRetry({+ sessionId: "acp-1",+ prompt: [{ type: "text", text: "do the task" }],+ }),+ );+ await Promise.resolve();+ await testServer.executeCommand("cancel", {});+ await vi.advanceTimersByTimeAsync(5_000);++ await expect(resultPromise).resolves.toEqual({+ stopReason: "cancelled",+ });+ expect(prompt).toHaveBeenCalledOnce();+ } finally {+ vi.useRealTimers();+ }+ });++ it("does not dispatch a startup prompt after an earlier cancellation", async () => {+ const prompt = vi.fn();+ const testServer = createRetryTestServer(prompt);+ await expect(+ testServer.runStartupTurn(async () => {+ await testServer.executeCommand("cancel", {});+ return testServer.promptWithUpstreamRetry({+ sessionId: "acp-1",+ prompt: [{ type: "text", text: "do the task" }],+ });+ }),+ ).resolves.toEqual({ stopReason: "cancelled" });+ expect(prompt).not.toHaveBeenCalled();+ }, 20000);++ it("does not carry an idle cancellation into a later retry-wrapped turn", async () => {+ const prompt = vi.fn(async () => ({ stopReason: "end_turn" }));+ const testServer = createRetryTestServer(prompt);+ await testServer.executeCommand("cancel", {});++ await expect(+ testServer.promptWithUpstreamRetry({+ sessionId: "acp-1",+ prompt: [{ type: "text", text: "do the task" }],+ }),+ ).resolves.toEqual({ stopReason: "end_turn" });+ expect(prompt).toHaveBeenCalledOnce();+ });++ it("does not return an old cancellation after session replacement", async () => {+ vi.useFakeTimers();+ try {+ const prompt = vi+ .fn()+ .mockRejectedValueOnce(new Error("API Error: Connection error."));+ const testServer = createRetryTestServer(prompt);+ const resultPromise = testServer.runStartupTurn(() =>+ testServer.promptWithUpstreamRetry({+ sessionId: "acp-1",+ prompt: [{ type: "text", text: "do the task" }],+ }),+ );+ const assertion = expect(resultPromise).rejects.toThrow(+ "Agent session changed before the turn could be retried",+ );+ await Promise.resolve();+ await testServer.executeCommand("cancel", {});+ testServer.session = {+ acpSessionId: "acp-2",+ payload: { run_id: "run-2" },+ clientConnection: { prompt: vi.fn() },+ };+ await vi.advanceTimersByTimeAsync(5_000);++ await assertion;+ expect(prompt).toHaveBeenCalledOnce();+ } finally {+ vi.useRealTimers();+ }+ });++ it("waits for failed-attempt usage before rejecting the turn", async () => {+ let releaseUsage!: () => void;+ const usageStored = new Promise<void>((resolve) => {+ releaseUsage = resolve;+ });+ const prompt = vi.fn().mockRejectedValueOnce(+ new RequestError(-32603, "fatal failure", {+ classification: "agent_error",+ result: "agent failed",+ usage: { inputTokens: 10, outputTokens: 5, totalTokens: 15 },+ }),+ );+ const testServer = createRetryTestServer(prompt);+ testServer.posthogAPI.updateTaskRun = vi.fn(() => usageStored);+ let settled = false;+ const resultPromise = testServer+ .promptWithUpstreamRetry({+ sessionId: "acp-1",+ prompt: [{ type: "text", text: "do the task" }],+ })+ .finally(() => {+ settled = true;+ });++ await vi.waitFor(() =>+ expect(testServer.posthogAPI.updateTaskRun).toHaveBeenCalledWith(+ "task-1",+ "run-1",+ expect.objectContaining({ state: expect.any(Object) }),+ ),+ );+ expect(settled).toBe(false);+ releaseUsage();+ await expect(resultPromise).rejects.toThrow("fatal failure");+ });++ it("propagates accumulated failed usage for caller-owned persistence", async () => {+ vi.useFakeTimers();+ try {+ const prompt = vi.fn().mockRejectedValue(+ new RequestError(-32603, "transient failure", {+ classification: "upstream_provider_failure",+ result: "upstream_provider_failure",+ usage: { inputTokens: 10, outputTokens: 5, totalTokens: 15 },+ }),+ );+ const testServer = createRetryTestServer(prompt);+ const resultPromise = testServer.promptWithUpstreamRetry(+ {+ sessionId: "acp-1",+ prompt: [{ type: "text", text: "do the task" }],+ },+ false,+ );+ const assertion = expect(resultPromise).rejects.toMatchObject({+ data: expect.objectContaining({+ usage: {+ cachedReadTokens: 0,+ cachedWriteTokens: 0,+ inputTokens: 30,+ outputTokens: 15,+ thoughtTokens: 0,+ totalTokens: 45,+ },+ }),+ });++ await vi.advanceTimersByTimeAsync(10_000);+ await assertion;+ expect(testServer.posthogAPI.updateTaskRun).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });++ it("continues after tool progress and preserves usage across retries", async () => {+ vi.useFakeTimers();+ try {+ const prompt = vi+ .fn()+ .mockRejectedValueOnce(+ new RequestError(-32603, "transient failure", {+ classification: "upstream_provider_failure",+ result: "unexpected status 503",+ madeProgress: true,+ usage: {+ inputTokens: 10,+ outputTokens: 5,+ totalTokens: 15,+ },+ }),+ )+ .mockResolvedValueOnce({+ stopReason: "end_turn",+ usage: { inputTokens: 20, outputTokens: 10, totalTokens: 30 },+ });+ const testServer = createRetryTestServer(prompt);+ const resultPromise = testServer.promptWithUpstreamRetry({+ sessionId: "acp-1",+ prompt: [{ type: "text", text: "do the task" }],+ });+ await vi.advanceTimersByTimeAsync(5_000);++ await expect(resultPromise).resolves.toMatchObject({+ stopReason: "end_turn",+ usage: { inputTokens: 30, outputTokens: 15, totalTokens: 45 },+ });+ const retryRequest = prompt.mock.calls[1][0] as {+ prompt: Array<{+ text: string;+ _meta?: { ui?: { hidden?: boolean } };+ }>;+ };+ expect(retryRequest.prompt[0].text).toContain(+ "Continue from where you left off",+ );+ expect(retryRequest.prompt[0]._meta?.ui?.hidden).toBe(true);+ } finally {+ vi.useRealTimers();+ }+ });+it("re-sends the original prompt when the failure happened before the stream started", async () => {vi.useFakeTimers();try {@@ -1458,7 +2188,11 @@ describe("AgentServer HTTP Mode", () => {};expect(retryRequest.sessionId).toBe("acp-1");expect(retryRequest.prompt).toEqual([- { type: "text", text: "do the task" },+ {+ type: "text",+ text: "do the task",+ _meta: { ui: { hidden: true } },+ },]);} finally {vi.useRealTimers();@@ -1478,6 +2212,36 @@ describe("AgentServer HTTP Mode", () => {expect(prompt).toHaveBeenCalledTimes(1);});+ it("records usage from a subscription usage-limit error", async () => {+ const prompt = vi.fn().mockRejectedValue(+ new RequestError(-32603, "Usage limit reached", {+ classification: "subscription_usage_limit",+ usage: { inputTokens: 20, outputTokens: 10, totalTokens: 30 },+ }),+ );+ const testServer = createRetryTestServer(prompt);++ await expect(+ testServer.promptWithUpstreamRetry({+ sessionId: "acp-1",+ prompt: [{ type: "text", text: "do the task" }],+ }),+ ).rejects.toThrow("Usage limit reached");+ expect(testServer.posthogAPI.updateTaskRun).toHaveBeenCalledWith(+ "task-1",+ "run-1",+ expect.objectContaining({+ state: {+ token_usage: expect.objectContaining({+ input_tokens: 20,+ output_tokens: 10,+ total_tokens: 30,+ }),+ },+ }),+ );+ });+it("stops continuing once the bounded retry budget is exhausted", async () => {vi.useFakeTimers();try {@@ -4169,7 +4933,7 @@ describe("AgentServer HTTP Mode", () => {);}, 30000);- it("retries an oversized deferred native resume on a fresh session", async () => {+ it("uses the fresh session for a compact continuation after an oversized deferred resume", async () => {// `sendResumeContinuation` gets this through `runResumeTurn`'s retryOnOversizedPrompt, but a// prewarmed run defers its resume onto the first forwarded message and never takes that path.// Without a fallback the run just fails when the replayed transcript overflows the window.@@ -4241,20 +5005,25 @@ describe("AgentServer HTTP Mode", () => {jsonrpc: "2.0",id: "deferred-oversized",method: "user_message",- params: { content: "continue with this change" },+ params: { content: "/compact continue with this change" },}),});expect(response.status).toBe(200);expect(newSession).toHaveBeenCalledOnce();- expect(prompt).toHaveBeenCalledTimes(2);- const [, secondCall] = prompt.mock.calls as unknown as [+ expect(prompt).toHaveBeenCalledTimes(3);+ const [, secondCall, thirdCall] = prompt.mock.calls as unknown as [unknown,- [{ prompt: ContentBlock[] }],+ [{ prompt: ContentBlock[]; sessionId: string }],+ [{ prompt: ContentBlock[]; sessionId: string }],];expect((secondCall[0].prompt[0] as { text: string }).text).toContain("work completed so far",);+ expect(thirdCall[0].sessionId).toBe("fresh-session");+ expect((thirdCall[0].prompt[0] as { text: string }).text).toContain(+ "Compaction is complete",+ );}, 30000);it("hides synthetic resume context while keeping the pending user message visible", async () => {diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.tsindex c418bc2611db..87cfb325e571 100644--- a/products/desktop/packages/agent/src/server/agent-server.ts+++ b/products/desktop/packages/agent/src/server/agent-server.ts@@ -12,6 +12,7 @@ import {ClientSideConnection,ndJsonStream,PROTOCOL_VERSION,+ RequestError,} from "@agentclientprotocol/sdk";import { type ServerType, serve } from "@hono/node-server";import { execGh } from "@posthog/git/gh";@@ -66,10 +67,13 @@ import {import type { GatewayEnv } from "../adapters/claude/session/options";import { codexKeyMatchesMcpServerName } from "../adapters/codex-app-server/mcp-config";import { hasCodexThreadState } from "../adapters/codex-app-server/thread-state";+import { mergeUsage } from "../adapters/codex-app-server/usage-tracker";import {type AgentErrorClassification,classifyAgentError,isPromptTooLongError,+ isRetryableUpstreamErrorClassification,+ sanitizeAgentErrorCause,} from "../adapters/error-classification";import { GH_STACK_QUALIFIED_TOOL_NAME } from "../adapters/local-tools/tools/gh-stack";import { isSupportedReasoningEffort } from "../adapters/reasoning-effort";@@ -147,6 +151,7 @@ const agentErrorClassificationSchema = z.enum(["upstream_provider_failure","content_block_rejection","turn_ended_without_response",+ "subscription_usage_limit","agent_error",]) satisfies z.ZodType<AgentErrorClassification>;@@ -155,14 +160,6 @@ const INITIAL_TASK_RUN_REFRESH_TIMEOUT_MS = 5_000;export const UPSTREAM_PROVIDER_FAILURE_MESSAGE ="The upstream AI provider failed to process the request. Please retry the task in a few minutes.";-const upstreamProviderFailureClassifications =- new Set<AgentErrorClassification>([- "upstream_stream_terminated",- "upstream_connection_error",- "upstream_timeout",- "upstream_provider_failure",- ]);-type TurnFailureDisposition =| "terminal"| "recoverable"@@ -170,7 +167,23 @@ type TurnFailureDisposition =| "retryable_followup";const errorWithClassificationSchema = z.object({- data: z.object({ classification: agentErrorClassificationSchema }),+ data: z.object({+ classification: agentErrorClassificationSchema,+ // The adapter carries the app-server's own cause here, so the diagnostic+ // path can report it separately from the generic ACP display text.+ result: z.string().optional(),+ madeProgress: z.boolean().optional(),+ usage: z+ .object({+ inputTokens: z.number(),+ outputTokens: z.number(),+ cachedReadTokens: z.number().optional(),+ cachedWriteTokens: z.number().optional(),+ thoughtTokens: z.number().optional(),+ totalTokens: z.number(),+ })+ .optional(),+ }),});export const SSE_KEEPALIVE_INTERVAL_MS = 25_000;@@ -261,6 +274,16 @@ function hiddenTextBlock(text: string): ContentBlock {} as ContentBlock;}+function hiddenPromptBlock(block: ContentBlock): ContentBlock {+ const meta = block._meta as+ | { ui?: Record<string, unknown>; [key: string]: unknown }+ | undefined;+ return {+ ...block,+ _meta: { ...meta, ui: { ...meta?.ui, hidden: true } },+ } as ContentBlock;+}+function isManualCompactPrompt(prompt: ContentBlock[]): boolean {return /^\/compact(?:\s|$)/.test(promptBlocksToText(prompt).trimStart());}@@ -435,7 +458,9 @@ export class AgentServer {private questionRelayedToSlack = false;private adapterEmittedTurnComplete = false;private suppressAdapterTurnComplete = false;+ private readonly cancelledStartupSessions = new WeakSet<ActiveSession>();private runUsage = new RunUsageAccumulator();+ private runUsageRunId: string | null = null;private detectedPrUrl: string | null = null;private slackArtifactDelivery: SlackArtifactDelivery | null = null;private slackChartDelivery = false;@@ -475,6 +500,10 @@ export class AgentServer {private inFlightMessageDeliveries = new Map<string, Promise<unknown>>();private activeOwnedTurnCount = 0;private activeStartupTurnCount = 0;+ private readonly retryWrappedSessionDepth = new WeakMap<+ ActiveSession,+ number+ >();// 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();@@ -1272,16 +1301,20 @@ export class AgentServer {commandSession.payload.run_id,);- const acpSessionId = commandSession.acpSessionId;const continueAfterCompaction = (): Promise<PromptResponse> =>- this.promptWithUpstreamRetry({- sessionId: acpSessionId,- prompt: [- hiddenTextBlock(- "Compaction is complete. Continue working on the task from the compacted context, following the user's instructions from the /compact command.",- ),- ],- });+ this.runRetryWrappedTurn(() =>+ this.promptWithUpstreamRetry(+ {+ sessionId: commandSession.acpSessionId,+ prompt: [+ hiddenTextBlock(+ "Compaction is complete. Continue working on the task from the compacted context, following the user's instructions from the /compact command.",+ ),+ ],+ },+ false,+ ),+ );let result: PromptResponse;this.suppressAdapterTurnComplete =@@ -1442,6 +1475,9 @@ export class AgentServer {this.logger.debug("Cancel requested", {acpSessionId: this.session.acpSessionId,});+ if (this.isRetryWrappedSession(this.session)) {+ this.cancelledStartupSessions.add(this.session);+ }await this.session.clientConnection.cancel({sessionId: this.session.acpSessionId,});@@ -1746,6 +1782,8 @@ export class AgentServer {preTask?.repositories ??(preTask?.repository ? [preTask.repository] : []);+ this.runUsage = new RunUsageAccumulator();+ this.runUsageRunId = payload.run_id;seedRunUsage(this.runUsage, preTaskRun?.state.token_usage);this.prewarmedRun = preTaskRun?.state.prewarmed === true;this.prewarmedStartupTurnPending = this.prewarmedRun;@@ -2161,12 +2199,17 @@ export class AgentServer {this.logger.debug("Failed to set task run to in_progress", err),);- await this.sendInitialTaskMessage(payload, preTaskRun);+ await this.runStartupTurn(() =>+ this.sendInitialTaskMessage(payload, preTaskRun),+ );}private extractErrorClassification(error: unknown): {classification: AgentErrorClassification;message: string;+ cause: string;+ madeProgress: boolean;+ usage?: NonNullable<PromptResponse["usage"]>;} {const message =error instanceof Error ? error.message : String(error ?? "");@@ -2174,10 +2217,28 @@ export class AgentServer {// Prefer the structured `data` carried on RequestError if present.const parsed = errorWithClassificationSchema.safeParse(error);if (parsed.success) {- return { classification: parsed.data.data.classification, message };+ // The adapter puts a safe diagnostic cause on `data.result` because the+ // ACP message contains text for the live client.+ const cause = sanitizeAgentErrorCause(+ parsed.data.data.result || message,+ parsed.data.data.classification,+ );+ return {+ classification: parsed.data.data.classification,+ message,+ cause,+ madeProgress: parsed.data.data.madeProgress ?? false,+ usage: parsed.data.data.usage,+ };}- return { classification: classifyAgentError(message), message };+ const classification = classifyAgentError(message);+ return {+ classification,+ message,+ cause: sanitizeAgentErrorCause(message, classification),+ madeProgress: false,+ };}private async runOwnedTurn<T>(operation: () => Promise<T>): Promise<T> {@@ -2192,12 +2253,41 @@ export class AgentServer {private async runStartupTurn<T>(operation: () => Promise<T>): Promise<T> {this.activeStartupTurnCount += 1;try {- return await this.runOwnedTurn(operation);+ return await this.runRetryWrappedTurn(() => this.runOwnedTurn(operation));} finally {this.activeStartupTurnCount -= 1;}}+ private isRetryWrappedSession(session: ActiveSession): boolean {+ return (this.retryWrappedSessionDepth.get(session) ?? 0) > 0;+ }++ private async runRetryWrappedTurn<T>(+ operation: () => Promise<T>,+ ): Promise<T> {+ const session = this.session;+ if (session) {+ this.retryWrappedSessionDepth.set(+ session,+ (this.retryWrappedSessionDepth.get(session) ?? 0) + 1,+ );+ }+ try {+ return await operation();+ } finally {+ if (session) {+ const depth = this.retryWrappedSessionDepth.get(session) ?? 0;+ if (depth <= 1) {+ this.retryWrappedSessionDepth.delete(session);+ this.cancelledStartupSessions.delete(session);+ } else {+ this.retryWrappedSessionDepth.set(session, depth - 1);+ }+ }+ }+ }+private async acquireNonSteerDeliveryTurn(): Promise<() => void> {const previous = this.nonSteerDeliveryTail;let release!: () => void;@@ -2217,19 +2307,33 @@ export class AgentServer {* case retries with a hidden continuation; failures where the request may* never have been processed re-send the original prompt instead.*/- private async promptWithUpstreamRetry(request: {- sessionId: string;- prompt: ContentBlock[];- _meta?: Record<string, unknown>;- }): Promise<PromptResponse> {+ private async promptWithUpstreamRetry(+ request: {+ sessionId: string;+ prompt: ContentBlock[];+ _meta?: Record<string, unknown>;+ },+ recordFailedUsage = true,+ ): Promise<PromptResponse> {+ const originatingSession = this.session;+ if (+ !originatingSession ||+ originatingSession.acpSessionId !== request.sessionId+ ) {+ throw new Error("Agent session changed before the turn could be sent");+ }let retries = 0;let continueInterruptedTurn = false;+ let retryUsage: NonNullable<PromptResponse["usage"]> | undefined;+ if (this.cancelledStartupSessions.delete(originatingSession)) {+ return { stopReason: "cancelled" };+ }for (;;) {- // Re-read the session on every attempt: it can be torn down or- // replaced while the retry delay is pending.const session = this.session;- if (!session) {- throw new Error("Agent session ended before the turn could be sent");+ if (session !== originatingSession) {+ throw new Error(+ "Agent session changed before the turn could be retried",+ );}this.emitFirstCommandDispatched();const attempt = continueInterruptedTurn@@ -2242,23 +2346,52 @@ export class AgentServer {),],}- : { ...request, sessionId: session.acpSessionId };+ : {+ ...request,+ sessionId: session.acpSessionId,+ prompt:+ retries > 0+ ? request.prompt.map(hiddenPromptBlock)+ : request.prompt,+ };try {- return await session.clientConnection.prompt(attempt);+ const response = await session.clientConnection.prompt(attempt);+ if (this.session !== originatingSession) {+ throw new Error(+ "Agent session changed before the turn result was handled",+ );+ }+ const usage = mergeUsage(retryUsage, response.usage ?? undefined);+ return { ...response, ...(usage ? { usage } : {}) };} catch (error) {- const { classification, message } =+ const { classification, message, cause, madeProgress, usage } =this.extractErrorClassification(error);- if (- !upstreamProviderFailureClassifications.has(classification) ||- retries >= MAX_UPSTREAM_TURN_RETRIES- ) {+ const accumulatedUsage = mergeUsage(retryUsage, usage);+ const retryable =+ isRetryableUpstreamErrorClassification(classification);+ if (!retryable || retries >= MAX_UPSTREAM_TURN_RETRIES) {+ if (recordFailedUsage && this.session === originatingSession) {+ await this.recordTurnUsage(+ accumulatedUsage,+ originatingSession.payload,+ );+ }+ if (retryable && accumulatedUsage) {+ throw new RequestError(-32603, message, {+ classification,+ result: cause,+ madeProgress: continueInterruptedTurn || madeProgress,+ usage: accumulatedUsage,+ });+ }throw error;}+ retryUsage = accumulatedUsage;retries += 1;// Only a mid-response stream death guarantees the prompt reached the// model; connection/timeout/status failures re-send the original.- continueInterruptedTurn =- classification === "upstream_stream_terminated";+ continueInterruptedTurn ||=+ classification === "upstream_stream_terminated" || madeProgress;this.logger.warn("Turn hit a transient upstream failure; retrying after a short delay",{@@ -2271,6 +2404,17 @@ export class AgentServer {await new Promise((resolve) =>setTimeout(resolve, UPSTREAM_TURN_RETRY_DELAY_MS),);+ if (this.session !== originatingSession) {+ throw new Error(+ "Agent session changed before the turn could be retried",+ );+ }+ if (this.cancelledStartupSessions.delete(originatingSession)) {+ return {+ stopReason: "cancelled",+ ...(retryUsage ? { usage: retryUsage } : {}),+ };+ }}}}@@ -2280,9 +2424,10 @@ export class AgentServer {phase: "initial" | "resume" | "followup",error: unknown,): Promise<TurnFailureDisposition> {- const { classification, message } = this.extractErrorClassification(error);+ const { classification, message, cause, usage } =+ this.extractErrorClassification(error);const isUpstreamFailure =- upstreamProviderFailureClassifications.has(classification);+ isRetryableUpstreamErrorClassification(classification);const isTurnWithoutResponse =classification === "turn_ended_without_response";const displayMessage = isUpstreamFailure@@ -2298,6 +2443,8 @@ export class AgentServer {recoverable && /^ACP connection closed$/i.test(message.trim());const suppressClientError =retryableFollowup || expectedIdleTransportClosure;+ const activeSessionOwnsFailure =+ this.session?.payload.run_id === payload.run_id;this.logger.error(`send_${phase}_task_message_failed`, {classification,@@ -2306,16 +2453,24 @@ export class AgentServer {retryableDelivery,});+ if (phase === "followup" && activeSessionOwnsFailure) {+ await this.recordTurnUsage(usage, payload);+ }+ const failureSessionStillActive =+ this.session?.payload.run_id === payload.run_id;+if (retryableDelivery) {return "retryable_delivery";}- if (!suppressClientError) {+ if (!suppressClientError && failureSessionStillActive) {this.broadcastTurnFailure(classification, displayMessage);}if (recoverable) {- this.broadcastTurnComplete("error_recoverable");+ if (failureSessionStillActive) {+ this.broadcastTurnComplete("error_recoverable");+ }return "recoverable";}@@ -2323,7 +2478,15 @@ export class AgentServer {return "retryable_followup";}- await this.signalTaskComplete(payload, "error", displayMessage);+ // Keep the live-client message separate from a bounded diagnostic cause.+ // Upstream failures need the same actionable retry guidance in persisted+ // task state and Slack notifications.+ const persistedMessage = isUpstreamFailure+ ? displayMessage+ : cause || displayMessage;+ await this.signalTaskComplete(payload, "error", persistedMessage, {+ errorCategory: classification,+ });return "terminal";}@@ -2475,13 +2638,11 @@ export class AgentServer {}promptDispatched = true;- const result = await this.runStartupTurn(() =>- this.promptWithUpstreamRetry({- sessionId: acpSessionId,- prompt: initialPrompt,- ...(initialPromptMeta ? { _meta: initialPromptMeta } : {}),- }),- );+ const result = await this.promptWithUpstreamRetry({+ sessionId: acpSessionId,+ prompt: initialPrompt,+ ...(initialPromptMeta ? { _meta: initialPromptMeta } : {}),+ });this.logger.debug("Initial task message completed", {stopReason: result.stopReason,@@ -2526,55 +2687,57 @@ export class AgentServer {const resumeState = this.resumeState;taskRun = await this.refreshTaskRunForResume(payload, taskRun);- await this.runResumeTurn(payload, taskRun, "Resume message", async () => {- const conversationSummary = formatConversationForResume(- resumeState.conversation,- );+ await this.runStartupTurn(() =>+ this.runResumeTurn(payload, taskRun, "Resume message", async () => {+ const conversationSummary = formatConversationForResume(+ resumeState.conversation,+ );- const pendingUserPrompt = await this.getPendingUserPrompt(taskRun);+ const pendingUserPrompt = await this.getPendingUserPrompt(taskRun);- let resumePromptBlocks: ContentBlock[];- let resumePromptMeta: Record<string, unknown> | undefined;- let resumePromptMessageId: string | undefined;- if (pendingUserPrompt?.prompt.length) {- resumePromptMeta = pendingUserPrompt.meta;- resumePromptMessageId = pendingUserPrompt.messageId;- resumePromptBlocks = [- hiddenTextBlock(- "You are resuming a previous conversation. Use the current workspace contents together with the preserved conversation history below.\n\n" +- `Here is the conversation history from the previous session:\n\n` +- `${conversationSummary}\n\n` +- `The user has sent a new message:\n\n`,- ),- ...pendingUserPrompt.prompt,- hiddenTextBlock(- "\n\nRespond to the user's new message above. You have full context from the previous session.",- ),- ];- } else {- resumePromptBlocks = [- hiddenTextBlock(- "You are resuming a previous conversation. Use the current workspace contents together with the preserved conversation history below.\n\n" +- `Here is the conversation history from the previous session:\n\n` +- `${conversationSummary}\n\n` +- `Continue from where you left off. The user is waiting for your response.`,- ),- ];- }+ let resumePromptBlocks: ContentBlock[];+ let resumePromptMeta: Record<string, unknown> | undefined;+ let resumePromptMessageId: string | undefined;+ if (pendingUserPrompt?.prompt.length) {+ resumePromptMeta = pendingUserPrompt.meta;+ resumePromptMessageId = pendingUserPrompt.messageId;+ resumePromptBlocks = [+ hiddenTextBlock(+ "You are resuming a previous conversation. Use the current workspace contents together with the preserved conversation history below.\n\n" ++ `Here is the conversation history from the previous session:\n\n` ++ `${conversationSummary}\n\n` ++ `The user has sent a new message:\n\n`,+ ),+ ...pendingUserPrompt.prompt,+ hiddenTextBlock(+ "\n\nRespond to the user's new message above. You have full context from the previous session.",+ ),+ ];+ } else {+ resumePromptBlocks = [+ hiddenTextBlock(+ "You are resuming a previous conversation. Use the current workspace contents together with the preserved conversation history below.\n\n" ++ `Here is the conversation history from the previous session:\n\n` ++ `${conversationSummary}\n\n` ++ `Continue from where you left off. The user is waiting for your response.`,+ ),+ ];+ }- this.logger.debug("Sending resume message", {- taskId: payload.task_id,- conversationTurns: resumeState.conversation.length,- promptLength: promptBlocksToText(resumePromptBlocks).length,- hasPendingUserMessage: !!pendingUserPrompt?.prompt.length,- });+ this.logger.debug("Sending resume message", {+ taskId: payload.task_id,+ conversationTurns: resumeState.conversation.length,+ promptLength: promptBlocksToText(resumePromptBlocks).length,+ hasPendingUserMessage: !!pendingUserPrompt?.prompt.length,+ });- return {- prompt: resumePromptBlocks,- ...(resumePromptMeta ? { meta: resumePromptMeta } : {}),- messageId: resumePromptMessageId,- };- });+ return {+ prompt: resumePromptBlocks,+ ...(resumePromptMeta ? { meta: resumePromptMeta } : {}),+ messageId: resumePromptMessageId,+ };+ }),+ );}private async settleIdleResume(@@ -2723,34 +2886,38 @@ export class AgentServer {if (!this.session) return;taskRun = await this.refreshTaskRunForResume(payload, taskRun);- await this.runResumeTurn(- payload,- taskRun,- "Resume continuation",- async () => {- const pendingUserPrompt = await this.getPendingUserPrompt(taskRun);- const prompt: ContentBlock[] = pendingUserPrompt?.prompt.length- ? pendingUserPrompt.prompt- : [- {- type: "text",- text: "Continue from where you left off. The user is waiting for your response.",- },- ];- this.logger.debug("Sending resume continuation", {- taskId: payload.task_id,- sessionId: this.nativeResume?.sessionId,- warm: this.nativeResume?.warm,- hasPendingUserMessage: !!pendingUserPrompt?.prompt.length,- });+ await this.runStartupTurn(() =>+ this.runResumeTurn(+ payload,+ taskRun,+ "Resume continuation",+ async () => {+ const pendingUserPrompt = await this.getPendingUserPrompt(taskRun);+ const prompt: ContentBlock[] = pendingUserPrompt?.prompt.length+ ? pendingUserPrompt.prompt+ : [+ {+ type: "text",+ text: "Continue from where you left off. The user is waiting for your response.",+ },+ ];+ this.logger.debug("Sending resume continuation", {+ taskId: payload.task_id,+ sessionId: this.nativeResume?.sessionId,+ warm: this.nativeResume?.warm,+ hasPendingUserMessage: !!pendingUserPrompt?.prompt.length,+ });- return {- prompt,- ...(pendingUserPrompt?.meta ? { meta: pendingUserPrompt.meta } : {}),- messageId: pendingUserPrompt?.messageId,- };- },- { retryOnOversizedPrompt: true },+ return {+ prompt,+ ...(pendingUserPrompt?.meta+ ? { meta: pendingUserPrompt.meta }+ : {}),+ messageId: pendingUserPrompt?.messageId,+ };+ },+ { retryOnOversizedPrompt: true },+ ),);}@@ -2856,13 +3023,11 @@ export class AgentServer {}promptDispatched = true;- const result = await this.runStartupTurn(() =>- this.promptWithUpstreamRetry({- sessionId: acpSessionId,- prompt: builtPrompt.prompt,- ...(builtPrompt.meta ? { _meta: builtPrompt.meta } : {}),- }),- );+ const result = await this.promptWithUpstreamRetry({+ sessionId: acpSessionId,+ prompt: builtPrompt.prompt,+ ...(builtPrompt.meta ? { _meta: builtPrompt.meta } : {}),+ });this.logger.debug(`${logLabel} completed`, {stopReason: result.stopReason,@@ -4550,10 +4715,30 @@ ${commonInstructions}payload: JwtPayload,stopReason: string,errorMessage?: string,+ options?: { errorCategory?: AgentErrorClassification },): Promise<void> {- if (this.session?.payload.run_id === payload.run_id) {+ const currentSession = this.session;+ const sessionMatchesRun = currentSession?.payload.run_id === payload.run_id;+ const terminalErrorMessage = errorMessage ?? "Agent error";+ const persistedErrorMessage = options?.errorCategory+ ? `${options.errorCategory}: ${errorMessage ?? "Agent error"}`+ : terminalErrorMessage;+ // The Django drain reads this contract from the S3 log. Enqueue it before+ // the flush so the drain can report the safe classified cause.+ if (stopReason === "error" && (!currentSession || sessionMatchesRun)) {+ this.enqueueTaskTerminalEvent(POSTHOG_NOTIFICATIONS.ERROR, {+ source: "agent_server",+ stopReason,+ message: terminalErrorMessage,+ error: terminalErrorMessage,+ errorCategory: options?.errorCategory,+ error_category: options?.errorCategory,+ });+ }++ if (sessionMatchesRun) {try {- await this.session.logWriter.flush(payload.run_id, {+ await currentSession.logWriter.flush(payload.run_id, {coalesce: true,});} catch (error) {@@ -4574,28 +4759,31 @@ ${commonInstructions}const status = "failed";- this.enqueueTaskTerminalEvent(POSTHOG_NOTIFICATIONS.ERROR, {- source: "agent_server",- stopReason,- error: errorMessage ?? "Agent error",- });-try {await this.posthogAPI.updateTaskRun(payload.task_id, payload.run_id, {status,- error_message: errorMessage ?? "Agent error",+ error_message: persistedErrorMessage,});this.logger.debug("Task completion signaled", { status, stopReason });} catch (error) {this.logger.error("Failed to signal task completion", error);} finally {- await this.emitRtkSavings();- await this.eventStreamSender?.stop();+ if (+ (!currentSession || sessionMatchesRun) &&+ this.session === currentSession+ ) {+ await this.emitRtkSavings();+ if (this.session === currentSession) {+ await this.eventStreamSender?.stop();+ }+ }// The run is terminal and the sandbox is torn down right after — and// teardown kills this exec'd process without SIGTERM, so this is the// last chance to end the root span and drain the OTel queues. The// error mirror was appended above, so the root span exports as ERROR.- await this.session?.telemetry?.shutdown().catch(() => {});+ if (sessionMatchesRun) {+ await currentSession.telemetry?.shutdown().catch(() => {});+ }}}@@ -4615,10 +4803,16 @@ ${commonInstructions}},};this.eventStreamSender?.enqueue(entry);- // Terminal events bypass the SessionLogWriter (and its sinks), so mirror- // them onto the OTel writer directly — a failed run is exactly what the- // telemetry must record.- this.session?.telemetry?.append(this.session.payload.run_id, entry);+ // Persist to the session log too: the Django drain reads the terminal event+ // from the S3 log to report the real cause of a failed run, and only the+ // SessionLogWriter feeds that log. appendRawLine wraps the bare notification+ // in the same {type, timestamp, notification} envelope the drain parses, and+ // forwards it to the OTel sink — so telemetry still records the failed run+ // without a second append here.+ this.session?.logWriter.appendRawLine(+ this.session.payload.run_id,+ JSON.stringify(entry.notification),+ );}private configureEnvironment({@@ -5426,6 +5620,7 @@ ${commonInstructions}// Run usage is per run: a later session on this instance (e.g. a resume// with a different run_id) must not inherit the previous run's totals.this.runUsage = new RunUsageAccumulator();+ this.runUsageRunId = null;this.session = null;}@@ -5455,11 +5650,19 @@ ${commonInstructions}* to the backend, merged into `TaskRun.state.token_usage`. Best-effort: a* reporting failure must never affect the turn outcome.*/- private recordTurnUsage(usage: PromptResponse["usage"]): void {- if (!this.runUsage.add(usage)) return;- const payload = this.session?.payload;- if (!payload) return;- reportRunUsage(+ private recordTurnUsage(+ usage: PromptResponse["usage"],+ payload = this.session?.payload,+ ): Promise<void> {+ if (!payload || this.session?.payload.run_id !== payload.run_id) {+ return Promise.resolve();+ }+ if (this.runUsageRunId !== payload.run_id) {+ this.runUsage = new RunUsageAccumulator();+ this.runUsageRunId = payload.run_id;+ }+ if (!this.runUsage.add(usage)) return Promise.resolve();+ return reportRunUsage(this.runUsage,this.posthogAPI,payload.task_id,diff --git a/products/desktop/packages/agent/src/server/question-relay.test.ts b/products/desktop/packages/agent/src/server/question-relay.test.tsindex 1b8c5b84018a..5da67a74ebeb 100644--- a/products/desktop/packages/agent/src/server/question-relay.test.ts+++ b/products/desktop/packages/agent/src/server/question-relay.test.ts@@ -984,7 +984,7 @@ describe("Question relay", () => {expect(updateTaskRunSpy).not.toHaveBeenCalled();});- it("surfaces the shared provider failure message once upstream retries are exhausted", async () => {+ it("stores the classified cause once upstream retries are exhausted", async () => {vi.spyOn(server.posthogAPI, "getTask").mockResolvedValue({id: "test-task-id",title: "t",@@ -1031,7 +1031,7 @@ describe("Question relay", () => {"test-run-id",{status: "failed",- error_message: UPSTREAM_PROVIDER_FAILURE_MESSAGE,+ error_message: `upstream_connection_error: ${UPSTREAM_PROVIDER_FAILURE_MESSAGE}`,},);});diff --git a/products/tasks/backend/logic/services/custom_prompt_internals.py b/products/tasks/backend/logic/services/custom_prompt_internals.pyindex d8421cc15cd0..c400532b18d2 100644--- a/products/tasks/backend/logic/services/custom_prompt_internals.py+++ b/products/tasks/backend/logic/services/custom_prompt_internals.py@@ -683,7 +683,7 @@ def _extract_agent_error(log_content: str | None, skip_lines: int = 0) -> AgentE"""Scan log lines for the agent's structured terminal-error notification.Returns the last `_posthog/error` entry carrying a non-empty message (with the- classified `error_category` when the agent build provides it), or None when no+ classified `errorCategory` when the agent build provides it), or None when nosuch entry exists — e.g. an older agent build or a non-agent failure — in whichcase the caller falls back to the generic terminal-status message."""@@ -708,7 +708,7 @@ def _extract_agent_error(log_content: str | None, skip_lines: int = 0) -> AgentEmessage = params.get("message")if not isinstance(message, str) or not message.strip():continue- raw_category = params.get("error_category")+ raw_category = params.get("errorCategory") or params.get("error_category")category = raw_category.strip() if isinstance(raw_category, str) and raw_category.strip() else Nonefound = AgentError(message=message.strip(), category=category)return founddiff --git a/products/tasks/backend/tests/agent_log_fixtures.py b/products/tasks/backend/tests/agent_log_fixtures.pyindex f58fe46ddaae..73d3c9db9b90 100644--- a/products/tasks/backend/tests/agent_log_fixtures.py+++ b/products/tasks/backend/tests/agent_log_fixtures.py@@ -82,11 +82,11 @@ def _user_message_line(text: str) -> str:def _agent_error_line(message: str, category: str | None = None) -> str:"""Build a `_posthog/error` notification line as the sandbox agent emits on a- terminal failure. `category` mirrors classifyAgentError() output and is absent- on older agent builds."""- params: dict = {"message": message}+ terminal failure — the full param set the agent server writes. `category` mirrors+ classifyAgentError() output and is absent on older agent builds."""+ params: dict = {"source": "agent_server", "stopReason": "error", "message": message, "error": message}if category is not None:- params["error_category"] = category+ params["errorCategory"] = categoryreturn json.dumps({"notification": {"method": "_posthog/error", "params": params}})diff --git a/products/tasks/backend/tests/test_multi_turn_session.py b/products/tasks/backend/tests/test_multi_turn_session.pyindex 02be860497a8..d2ff659f09ab 100644--- a/products/tasks/backend/tests/test_multi_turn_session.py+++ b/products/tasks/backend/tests/test_multi_turn_session.py@@ -929,6 +929,16 @@ class TestExtractAgentError:assert result == AgentError(message=message, category=None)assert result.describe() == message+ def test_extracts_legacy_snake_case_category(self):+ message = "API Error: Connection error"+ log = _agent_error_line(message, category="upstream_connection_error").replace(+ '"errorCategory":', '"error_category":'+ )++ result = _extract_agent_error(log)++ assert result == AgentError(message=message, category="upstream_connection_error")+def test_returns_none_when_no_error_line(self):log = "\n".join([_agent_message_line("hello"), _end_turn_line()])assert _extract_agent_error(log) is None