Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(desktop): keep provider rejections out of session recovery (#116816)

Alessandro Pogliaghi0ac82fd83a73
diff --git a/packages/agent/packages/agent-contracts/src/errors.test.ts b/packages/agent/packages/agent-contracts/src/errors.test.ts
index 527b204d1551..4d1a5d0bb9b2 100644
--- a/packages/agent/packages/agent-contracts/src/errors.test.ts
+++ b/packages/agent/packages/agent-contracts/src/errors.test.ts
@@ -294,6 +294,35 @@ describe("classifyPromptFailure", () => {
["Cloud usage limit reached", undefined, "usage_limit", false],
["API Error: 529 overloaded", undefined, "transient", true],
["boom", "upstream_timeout", "transient", true],
+ ["boom", "upstream_stream_terminated", "transient", true],
+ ["boom", "upstream_connection_error", "transient", true],
+ ["boom", "upstream_provider_failure", "transient", true],
+ ["boom", "upstream_unknown", "unknown", false],
+ ["boom", "upstream_request_rejected", "request_rejected", false],
+ [
+ "API Error: Request timed out",
+ "upstream_request_rejected",
+ "request_rejected",
+ false,
+ ],
+ [
+ "Internal error: API Error: 400 invalid_request_error",
+ undefined,
+ "request_rejected",
+ false,
+ ],
+ [
+ "unexpected status 422 Unprocessable Entity",
+ undefined,
+ "request_rejected",
+ false,
+ ],
+ [
+ '{"error":{"type":"invalid_request_error","message":"Unsupported parameter"}}',
+ undefined,
+ "request_rejected",
+ false,
+ ],
[
"[ede_diagnostic] result_type=user last_content_type=n/a stop_reason=null",
"turn_ended_without_response",
@@ -368,7 +397,11 @@ describe("isFatalSessionError", () => {
"exceeded this model context window limit",
'API Error: 413 {"error":{"message":"Request rejected"}}',
"api error:413",
- ])("does not treat the request size error %j as fatal", (message) => {
+ "API Error: 400 invalid_request_error",
+ "API Error: 404 Not Found",
+ "unexpected status 422 Unprocessable Entity",
+ '{"error":{"type":"invalid_request_error","message":"Unsupported parameter"}}',
+ ])("does not treat the request rejection %j as fatal", (message) => {
expect(isFatalSessionError(`Internal error: ${message}`)).toBe(false);
expect(isFatalSessionError("Internal error", message)).toBe(false);
});
diff --git a/packages/agent/packages/agent-contracts/src/errors.ts b/packages/agent/packages/agent-contracts/src/errors.ts
index b652f7306de5..50437f0a87e2 100644
--- a/packages/agent/packages/agent-contracts/src/errors.ts
+++ b/packages/agent/packages/agent-contracts/src/errors.ts
@@ -162,6 +162,19 @@ const UPSTREAM_TRANSIENT_ERROR_REGEXES = [
const TURN_ENDED_WITHOUT_RESPONSE_REGEX =
/\[ede_diagnostic\]\s+result_type=user\b/i;
+const UPSTREAM_REQUEST_REJECTED_REGEX =
+ /invalid_request_error|unexpected status\s*(?:400|404|422)\b|API Error:\s*(?:400|404|422)\b/i;
+
+export function isUpstreamRequestRejected(
+ errorMessage: string,
+ errorDetails?: string,
+): boolean {
+ return (
+ UPSTREAM_REQUEST_REJECTED_REGEX.test(errorMessage) ||
+ (!!errorDetails && UPSTREAM_REQUEST_REJECTED_REGEX.test(errorDetails))
+ );
+}
+
function includesAny(
value: string | undefined,
patterns: readonly string[],
@@ -275,6 +288,7 @@ export function isTurnEndedWithoutResponseError(
export type PromptFailureKind =
| "usage_limit"
| "transient"
+ | "request_rejected"
| "authentication"
| "fatal_session"
| "unknown";
@@ -313,8 +327,14 @@ export function classifyPromptFailure(
};
}
if (
- errorType?.startsWith("upstream_") ||
- isTransientUpstreamError(message, errorDetails)
+ errorType !== "upstream_request_rejected" &&
+ ([
+ "upstream_stream_terminated",
+ "upstream_connection_error",
+ "upstream_timeout",
+ "upstream_provider_failure",
+ ].includes(errorType ?? "") ||
+ isTransientUpstreamError(message, errorDetails))
) {
return {
kind: "transient",
@@ -323,6 +343,18 @@ export function classifyPromptFailure(
limitCause: null,
};
}
+ if (
+ errorType === "upstream_request_rejected" ||
+ isUpstreamRequestRejected(message, errorDetails)
+ ) {
+ return {
+ kind: "request_rejected",
+ message:
+ "The AI provider couldn't process this request. Try starting a new task.",
+ retryable: false,
+ limitCause: null,
+ };
+ }
if (isNotAuthenticatedError(error) || isAuthError(error)) {
return {
kind: "authentication",
@@ -362,6 +394,7 @@ export function isFatalSessionError(
if (isRateLimitError(errorMessage, errorDetails)) return false;
if (isTurnEndedWithoutResponseError(errorMessage, errorDetails)) return false;
if (isTransientUpstreamError(errorMessage, errorDetails)) return false;
+ if (isUpstreamRequestRejected(errorMessage, errorDetails)) return false;
if (classifyGatewayLimitError(errorMessage, errorDetails) !== null) {
return false;
}
diff --git a/packages/agent/packages/agent-contracts/src/index.ts b/packages/agent/packages/agent-contracts/src/index.ts
index ea5dda4bc54b..77e429a1c647 100644
--- a/packages/agent/packages/agent-contracts/src/index.ts
+++ b/packages/agent/packages/agent-contracts/src/index.ts
@@ -141,6 +141,7 @@ export {
isRateLimitError,
isTransientUpstreamError,
isTurnEndedWithoutResponseError,
+ isUpstreamRequestRejected,
NotAuthenticatedError,
type PromptFailure,
type PromptFailureKind,
diff --git a/packages/agent/packages/agent/src/adapters/error-classification.ts b/packages/agent/packages/agent/src/adapters/error-classification.ts
index 505c0b95a4a3..7fcbaf6b8a69 100644
--- a/packages/agent/packages/agent/src/adapters/error-classification.ts
+++ b/packages/agent/packages/agent/src/adapters/error-classification.ts
@@ -1,4 +1,7 @@
-import { getErrorMessage } from "@posthog/agent-contracts";
+import {
+ getErrorMessage,
+ isUpstreamRequestRejected,
+} from "@posthog/agent-contracts";
export type AgentErrorClassification =
| "upstream_stream_terminated"
@@ -31,8 +34,6 @@ const UPSTREAM_PROVIDER_ERROR_STATUS_PATTERN = /API Error:\s*(?:429|5\d\d)\b/i;
// "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 UPSTREAM_REQUEST_REJECTED_PATTERN =
- /invalid_request_error|unexpected status\s*(?:400|404|422)\b|API Error:\s*(?:400|404|422)\b/i;
const SANDBOX_TASK_SPEND_LIMIT_PATTERN =
/This agent run reached its spend limit/i;
const TURN_ENDED_WITHOUT_RESPONSE_PATTERN =
@@ -99,7 +100,7 @@ export function classifyAgentError(
if (SUBSCRIPTION_USAGE_LIMIT_PATTERN.test(text)) {
return "subscription_usage_limit";
}
- if (UPSTREAM_REQUEST_REJECTED_PATTERN.test(text)) {
+ if (isUpstreamRequestRejected(text)) {
return "upstream_request_rejected";
}
return "agent_error";
diff --git a/products/desktop/docs/ARCHITECTURE.md b/products/desktop/docs/ARCHITECTURE.md
index 6228cdf3f9b6..ff5005d8d14d 100644
--- a/products/desktop/docs/ARCHITECTURE.md
+++ b/products/desktop/docs/ARCHITECTURE.md
@@ -51,6 +51,11 @@ failure. A failed replacement keeps its session when available, or restores the
previous session with an error. A later retry can send the original prompt.
A retry without a session reports failure instead of successful recovery.
+Provider request rejections are non-retryable prompt failures. Desktop keeps the
+local session connected, restores the submitted message when the composer is
+still empty, and suggests starting a new task. It does not restart the session
+or automatically resend the rejected request.
+
Claude initialization includes the repository's `SessionStart` hooks. These hooks
can prepare a new worktree and install dependencies before the SDK becomes ready.
An observed setup hook gets a separate, bounded wait of ten minutes. Startup with
diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.ts
index d3a95d1dfddc..38314e6e6ecf 100644
--- a/products/desktop/packages/core/src/sessions/sessionService.ts
+++ b/products/desktop/packages/core/src/sessions/sessionService.ts
@@ -25,6 +25,7 @@ import {
type BedrockGatewayVariant,
type CloudRegion,
classifyGatewayLimitError,
+ classifyPromptFailure,
customModelMeta,
type ExecutionMode,
flattenSelectOptions,
@@ -4748,6 +4749,11 @@ export class SessionService {
);
}
+ const failure = classifyPromptFailure(error, errorDetails);
+ if (failure.kind === "request_rejected") {
+ throw new Error(failure.message, { cause: error });
+ }
+
throw error;
}
}
diff --git a/products/desktop/packages/core/src/sessions/sessionServicePromptRecovery.test.ts b/products/desktop/packages/core/src/sessions/sessionServicePromptRecovery.test.ts
index 26f868dc0eeb..a449204cc9dc 100644
--- a/products/desktop/packages/core/src/sessions/sessionServicePromptRecovery.test.ts
+++ b/products/desktop/packages/core/src/sessions/sessionServicePromptRecovery.test.ts
@@ -158,6 +158,36 @@ describe("SessionService prompt recovery on fatal session errors", () => {
},
);
+ it.each(["message", "details"] as const)(
+ "surfaces a request rejection in %s without restarting the session",
+ async (location) => {
+ const { service, sessions, promptMutate, recoverSpy } = createHarness();
+ const message = "API Error: 400 invalid_request_error";
+ const error =
+ location === "message"
+ ? new Error(`Internal error: ${message}`)
+ : Object.assign(new Error("Internal error"), {
+ data: { details: message },
+ });
+ promptMutate.mockRejectedValue(error);
+
+ await expect(
+ service.sendPrompt(TASK_ID, "keep this message"),
+ ).rejects.toThrow(
+ "The AI provider couldn't process this request. Try starting a new task.",
+ );
+
+ expect(promptMutate).toHaveBeenCalledTimes(1);
+ expect(recoverSpy).not.toHaveBeenCalled();
+ expect(sessions[TASK_RUN_ID]).toMatchObject({
+ status: "connected",
+ isPromptPending: false,
+ isCompacting: false,
+ promptStartedAt: null,
+ });
+ },
+ );
+
it.each([
{
case: "recovery fails",