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(tasks): keep a content-block rejection from dropping a follow-up (#93181)

posthog[bot]67c5c8afbebf
diff --git a/products/desktop/packages/agent/src/adapters/error-classification.test.ts b/products/desktop/packages/agent/src/adapters/error-classification.test.ts
index 3e1369e417eb..441887602bdf 100644
--- a/products/desktop/packages/agent/src/adapters/error-classification.test.ts
+++ b/products/desktop/packages/agent/src/adapters/error-classification.test.ts
@@ -25,6 +25,11 @@ describe("classifyAgentError", () => {
["API Error: Request timed out.", "upstream_timeout"],
["API Error: 429 rate limited", "upstream_provider_failure"],
["API Error: 529 overloaded", "upstream_provider_failure"],
+ ["API Error: Content block not found", "content_block_rejection"],
+ [
+ "API Error: Content block is not a thinking block",
+ "content_block_rejection",
+ ],
[
"[ede_diagnostic] result_type=user last_content_type=n/a stop_reason=null",
"turn_ended_without_response",
diff --git a/products/desktop/packages/agent/src/adapters/error-classification.ts b/products/desktop/packages/agent/src/adapters/error-classification.ts
index f063069a8005..04920fe038a6 100644
--- a/products/desktop/packages/agent/src/adapters/error-classification.ts
+++ b/products/desktop/packages/agent/src/adapters/error-classification.ts
@@ -5,6 +5,7 @@ export type AgentErrorClassification =
| "upstream_connection_error"
| "upstream_timeout"
| "upstream_provider_failure"
+ | "content_block_rejection"
| "turn_ended_without_response"
| "agent_error";
@@ -53,6 +54,9 @@ export function classifyAgentError(
if (UPSTREAM_PROVIDER_ERROR_STATUS_PATTERN.test(text)) {
return "upstream_provider_failure";
}
+ if (/API Error:\s*Content block\b/i.test(text)) {
+ return "content_block_rejection";
+ }
if (TURN_ENDED_WITHOUT_RESPONSE_PATTERN.test(text)) {
return "turn_ended_without_response";
}
diff --git a/products/desktop/packages/agent/src/server/agent-server.test.ts b/products/desktop/packages/agent/src/server/agent-server.test.ts
index b69ae5332023..b12c4e2c77fc 100644
--- a/products/desktop/packages/agent/src/server/agent-server.test.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.test.ts
@@ -1218,7 +1218,7 @@ describe("AgentServer HTTP Mode", () => {
payload: JwtPayload,
phase: "initial" | "resume" | "followup",
error: unknown,
- ): Promise<void>;
+ ): Promise<unknown>;
};
testServer.eventStreamSender = {
enqueue: vi.fn(),
@@ -1243,37 +1243,74 @@ describe("AgentServer HTTP Mode", () => {
};
it.each([
- ["genuine agent error (terminal)", "boom", "agent_error", true],
+ [
+ "genuine agent error (terminal)",
+ "interactive",
+ "boom",
+ "terminal",
+ "agent_error",
+ true,
+ ],
[
"transient upstream timeout (recoverable)",
+ "interactive",
"API Error: The operation timed out.",
+ "recoverable",
"upstream_timeout",
false,
],
+ [
+ "interactive content-block rejection (retryable delivery)",
+ "interactive",
+ "API Error: Content block is not a thinking block",
+ "retryable_delivery",
+ null,
+ false,
+ ],
+ [
+ "background content-block rejection (retryable delivery)",
+ "background",
+ "API Error: Content block is not a thinking block",
+ "retryable_delivery",
+ null,
+ false,
+ ],
] as const)(
"tags and handles a follow-up %s",
- async (_name, errorMessage, expectedErrorType, expectsFailed) => {
+ async (
+ _name,
+ mode,
+ errorMessage,
+ expectedDisposition,
+ expectedErrorType,
+ expectsFailed,
+ ) => {
const testServer = createFailureTestServer();
- await testServer.handleTurnFailure(
- interactivePayload,
+ const disposition = await testServer.handleTurnFailure(
+ { ...interactivePayload, mode },
"followup",
new Error(errorMessage),
);
- expect(testServer.eventStreamSender.enqueue).toHaveBeenCalledWith(
- expect.objectContaining({
- notification: expect.objectContaining({
- method: "session/update",
- params: expect.objectContaining({
- update: expect.objectContaining({
- sessionUpdate: "error",
- errorType: expectedErrorType,
+ expect(disposition).toBe(expectedDisposition);
+ if (expectedErrorType) {
+ expect(testServer.eventStreamSender.enqueue).toHaveBeenCalledWith(
+ expect.objectContaining({
+ notification: expect.objectContaining({
+ method: "session/update",
+ params: expect.objectContaining({
+ update: expect.objectContaining({
+ sessionUpdate: "error",
+ errorType: expectedErrorType,
+ }),
}),
}),
}),
- }),
- );
+ );
+ } else {
+ expect(testServer.eventStreamSender.enqueue).not.toHaveBeenCalled();
+ }
if (expectsFailed) {
expect(testServer.posthogAPI.updateTaskRun).toHaveBeenCalledWith(
@@ -1321,7 +1358,7 @@ describe("AgentServer HTTP Mode", () => {
),
);
- expect(result).toEqual({ recoverable: false });
+ expect(result).toBe("retryable_followup");
expect(testServer.eventStreamSender.enqueue).not.toHaveBeenCalled();
expect(testServer.posthogAPI.updateTaskRun).not.toHaveBeenCalled();
});
@@ -3270,6 +3307,64 @@ describe("AgentServer HTTP Mode", () => {
expect(prompt).toHaveBeenCalledTimes(1);
}, 20000);
+ it.each(["interactive", "background"] as const)(
+ "redelivers a content-block rejection with the same messageId in %s mode",
+ async (mode) => {
+ const s = createServer({ mode });
+ await s.start();
+ const prompt = vi
+ .fn(async (_params: { _meta?: Record<string, unknown> }) => ({
+ stopReason: "end_turn",
+ }))
+ .mockRejectedValueOnce(
+ new Error("API Error: Content block is not a thinking block"),
+ );
+ const serverInternals = s as unknown as {
+ session: { clientConnection: { prompt: typeof prompt } };
+ };
+ serverInternals.session.clientConnection.prompt = prompt;
+
+ const token = createToken({ mode });
+ const send = async (requestId: string) =>
+ fetch(`http://localhost:${port}/command`, {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${token}`,
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ jsonrpc: "2.0",
+ id: requestId,
+ method: "user_message",
+ params: {
+ content: "do the thing",
+ messageId: "m-content-block",
+ },
+ }),
+ });
+
+ const first = await send("first-attempt");
+ await expect(first.json()).resolves.toMatchObject({
+ error: {
+ message: expect.stringContaining(
+ "Content block is not a thinking block",
+ ),
+ },
+ });
+ expect(prompt).toHaveBeenCalledTimes(1);
+
+ const retry = await send("retry");
+ await expect(retry.json()).resolves.toMatchObject({
+ result: { stopReason: "end_turn" },
+ });
+ expect(prompt).toHaveBeenCalledTimes(2);
+ expect(
+ prompt.mock.calls.map(([params]) => params._meta?.messageId),
+ ).toEqual(["m-content-block", "m-content-block"]);
+ },
+ 20000,
+ );
+
it("shares a failed in-flight messageId outcome with concurrent retries", async () => {
const s = createServer();
await s.start();
diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.ts
index fe45cc04b85f..fd7e44092e46 100644
--- a/products/desktop/packages/agent/src/server/agent-server.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.ts
@@ -144,6 +144,7 @@ const agentErrorClassificationSchema = z.enum([
"upstream_connection_error",
"upstream_timeout",
"upstream_provider_failure",
+ "content_block_rejection",
"turn_ended_without_response",
"agent_error",
]) satisfies z.ZodType<AgentErrorClassification>;
@@ -161,6 +162,12 @@ const upstreamProviderFailureClassifications =
"upstream_provider_failure",
]);
+type TurnFailureDisposition =
+ | "terminal"
+ | "recoverable"
+ | "retryable_delivery"
+ | "retryable_followup";
+
const errorWithClassificationSchema = z.object({
data: z.object({ classification: agentErrorClassificationSchema }),
});
@@ -1315,6 +1322,7 @@ export class AgentServer {
];
const promptMeta: Record<string, unknown> = {
...(builtPrompt.meta ?? {}),
+ ...(messageId ? { messageId } : {}),
...(hostContext.length > 0
? { prContext: hostContext.join("\n\n") }
: {}),
@@ -1450,12 +1458,12 @@ export class AgentServer {
}
} catch (error) {
await commandSession.logWriter.flushAll();
- const { recoverable } = await this.handleTurnFailure(
+ const failureDisposition = await this.handleTurnFailure(
commandSession.payload,
"followup",
error,
);
- if (!recoverable) {
+ if (failureDisposition !== "recoverable") {
throw error;
}
commitDelivery();
@@ -2388,48 +2396,52 @@ export class AgentServer {
payload: JwtPayload,
phase: "initial" | "resume" | "followup",
error: unknown,
- ): Promise<{ recoverable: boolean }> {
+ ): Promise<TurnFailureDisposition> {
const { classification, message } = this.extractErrorClassification(error);
const isUpstreamFailure =
upstreamProviderFailureClassifications.has(classification);
const isTurnWithoutResponse =
classification === "turn_ended_without_response";
- const retryableFollowup =
- isTurnWithoutResponse &&
- phase === "followup" &&
- this.getEffectiveMode(payload) === "interactive";
const displayMessage = isUpstreamFailure
? UPSTREAM_PROVIDER_FAILURE_MESSAGE
: message || "Agent error";
- const recoverable =
- isUpstreamFailure &&
- phase === "followup" &&
- this.getEffectiveMode(payload) === "interactive";
+ const isInteractiveFollowup =
+ phase === "followup" && this.getEffectiveMode(payload) === "interactive";
+ const retryableFollowup = isTurnWithoutResponse && isInteractiveFollowup;
+ const retryableDelivery =
+ classification === "content_block_rejection" && phase === "followup";
+ const recoverable = isUpstreamFailure && isInteractiveFollowup;
+ const expectedIdleTransportClosure =
+ recoverable && /^ACP connection closed$/i.test(message.trim());
const suppressClientError =
- retryableFollowup ||
- (recoverable && /^ACP connection closed$/i.test(message.trim()));
+ retryableFollowup || expectedIdleTransportClosure;
this.logger.error(`send_${phase}_task_message_failed`, {
classification,
message,
recoverable,
+ retryableDelivery,
});
+ if (retryableDelivery) {
+ return "retryable_delivery";
+ }
+
if (!suppressClientError) {
this.broadcastTurnFailure(classification, displayMessage);
}
if (recoverable) {
this.broadcastTurnComplete("error_recoverable");
- return { recoverable: true };
+ return "recoverable";
}
if (retryableFollowup) {
- return { recoverable: false };
+ return "retryable_followup";
}
await this.signalTaskComplete(payload, "error", displayMessage);
- return { recoverable: false };
+ return "terminal";
}
private broadcastTurnFailure(
diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.ts
index 10fadde10694..5e0994e1e86e 100644
--- a/products/desktop/packages/core/src/sessions/sessionService.ts
+++ b/products/desktop/packages/core/src/sessions/sessionService.ts
@@ -4355,35 +4355,39 @@ export class SessionService {
* Called internally when a turn completes and there are queued messages.
* Only the head message is dequeued (`max: 1`) so a queue drains one turn at
* a time — when this turn completes, the drain fires again for the next one.
- * The message is removed from the queue before sending; if sending fails it
- * is lost (acceptable since the user can re-type; avoids complex retry logic).
+ * The message is removed before sending and restored if the send fails.
*/
private async sendQueuedMessages(
taskId: string,
): Promise<{ stopReason: string }> {
- const combinedText = this.d.store.dequeueMessagesAsText(taskId, {
+ const drained = this.d.store.dequeueMessages(taskId, {
stopAtEdited: true,
max: 1,
});
- if (!combinedText) {
+ const message = drained[0];
+ if (!message) {
return { stopReason: "skipped" };
}
+ const prompt = message.rawPrompt ?? message.content;
+ const promptText = extractPromptText(prompt);
+
const session = this.d.store.getSessionByTaskId(taskId);
if (!session) {
- this.d.log.warn("No session found for queued messages, messages lost", {
+ this.d.store.prependQueuedMessages(taskId, drained);
+ this.d.log.warn("No session found for queued messages; re-enqueued", {
taskId,
- lostMessageLength: combinedText.length,
+ promptLength: promptText.length,
});
return { stopReason: "no_session" };
}
this.d.log.info("Sending next queued message as prompt", {
taskId,
- promptLength: combinedText.length,
+ promptLength: promptText.length,
});
- let blocks = normalizePromptToBlocks(combinedText);
+ let blocks = normalizePromptToBlocks(prompt);
const shellExecutes = getUserShellExecutesSinceLastPrompt(session.events);
if (shellExecutes.length > 0) {
@@ -4395,18 +4399,29 @@ export class SessionService {
task_id: taskId,
is_initial: false,
execution_type: "local",
- prompt_length_chars: combinedText.length,
+ prompt_length_chars: promptText.length,
});
try {
- return await this.sendLocalPrompt(session, blocks, combinedText);
+ const result = await this.sendLocalPrompt(session, blocks, promptText);
+ if (result.stopReason === "rate_limited") {
+ this.d.store.prependQueuedMessages(taskId, drained);
+ this.d.log.warn("Queued message hit a gateway limit; re-enqueued", {
+ taskId,
+ promptLength: promptText.length,
+ });
+ }
+ return result;
} catch (error) {
- // Log that queued messages were lost due to send failure
- this.d.log.error("Failed to send queued messages, messages lost", {
+ this.d.store.prependQueuedMessages(taskId, drained);
+ this.d.log.error("Failed to send queued messages; re-enqueued", {
taskId,
- lostMessageLength: combinedText.length,
+ promptLength: promptText.length,
error,
});
+ this.d.toast.error("Couldn't send the queued message", {
+ description: "Your message is still queued. Use Steer to try again.",
+ });
throw error;
}
}
@@ -4535,9 +4550,9 @@ export class SessionService {
);
}
- // A provider request that timed out or dropped leaves the session
- // healthy — no recovery ran above — so tell the user to just re-send
- // instead of surfacing the raw "Internal error: API Error: …" text.
+ // A provider request that timed out, dropped, or was refused leaves the
+ // session healthy — no recovery ran above — so tell the user to just
+ // re-send instead of surfacing the raw "Internal error: API Error: …" text.
if (isTransientUpstreamError(errorMessage, errorDetails)) {
this.d.log.warn("Transient upstream provider failure during prompt", {
taskRunId: session.taskRunId,
@@ -4545,7 +4560,7 @@ export class SessionService {
errorDetails,
});
throw new Error(
- "The AI provider timed out or dropped the connection. Your session is unaffected — please send the message again.",
+ "The AI provider could not complete the request. Your session is unaffected, so please send the message again.",
{ cause: error },
);
}
diff --git a/products/desktop/packages/shared/src/errors.test.ts b/products/desktop/packages/shared/src/errors.test.ts
index 85cf0ff41bb8..999586e3eb55 100644
--- a/products/desktop/packages/shared/src/errors.test.ts
+++ b/products/desktop/packages/shared/src/errors.test.ts
@@ -198,6 +198,7 @@ describe("isFatalSessionError", () => {
"Internal error: API Error: terminated",
"Internal error: API Error: Connection error",
"Internal error: API Error: 529 overloaded_error",
+ "Internal error: API Error: Content block is not a thinking block",
])("does not treat the transient upstream failure %j as fatal", (message) => {
expect(isFatalSessionError(message)).toBe(false);
});
@@ -241,6 +242,8 @@ describe("isTransientUpstreamError", () => {
"Internal error: API Error: Connection closed mid-response. The response above may be incomplete.",
"The socket connection was closed unexpectedly.",
"socket connection closed",
+ "Internal error: API Error: Content block not found",
+ "Internal error: API Error: Content block is not a thinking block",
])("recognises %j", (message) => {
expect(isTransientUpstreamError(message)).toBe(true);
});
diff --git a/products/desktop/packages/shared/src/errors.ts b/products/desktop/packages/shared/src/errors.ts
index d7d5cd15d696..3b827f135350 100644
--- a/products/desktop/packages/shared/src/errors.ts
+++ b/products/desktop/packages/shared/src/errors.ts
@@ -116,6 +116,10 @@ const UPSTREAM_TRANSIENT_ERROR_REGEXES = [
/socket connection (?:was )?closed/i,
/API Error:.*\b(?:timed out|timeout)\b/i,
/API Error:\s*(?:429|5\d\d)\b/i,
+ // The provider refuses a turn whose transcript content blocks do not line up
+ // ("Content block not found", "Content block is not a thinking block"). The
+ // wording changes with the provider, so match the family, not each string.
+ /API Error:\s*Content block\b/i,
] as const;
const TURN_ENDED_WITHOUT_RESPONSE_REGEX =
diff --git a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.test.ts b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.test.ts
index 8c2d8ecc4a1f..b01cfc1068d1 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.test.ts
@@ -37,7 +37,12 @@ function progressMsg(
};
}
-function userPromptMsg(ts: number, id: number, text: string): AcpMessage {
+function userPromptMsg(
+ ts: number,
+ id: number,
+ text: string,
+ messageId?: string,
+): AcpMessage {
return {
type: "acp_message",
ts,
@@ -45,7 +50,10 @@ function userPromptMsg(ts: number, id: number, text: string): AcpMessage {
jsonrpc: "2.0",
id,
method: "session/prompt",
- params: { prompt: [{ type: "text", text }] },
+ params: {
+ prompt: [{ type: "text", text }],
+ ...(messageId ? { _meta: { messageId } } : {}),
+ },
},
};
}
@@ -227,6 +235,22 @@ describe("buildConversationItems", () => {
]);
});
+ it("renders one user message when a delivery is retried", () => {
+ const result = buildConversationItems(
+ [
+ userPromptMsg(1, 1, "do the thing", "delivery-1"),
+ userPromptMsg(2, 2, "do the thing", "delivery-1"),
+ agentMessageMsg(3, "Done"),
+ promptResponseMsg(4, 2),
+ ],
+ null,
+ );
+
+ expect(result.items.filter((item) => item.type === "user_message")).toEqual(
+ [expect.objectContaining({ content: "do the thing" })],
+ );
+ });
+
it("keeps item ids stable when older history is prepended", () => {
const older: AcpMessage[] = [
userPromptMsg(1, 1, "first question"),
diff --git a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts
index 8414a46810f1..95e246f3ee14 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts
@@ -133,6 +133,7 @@ export interface ItemBuilder {
* frozen and only re-derive the active turn. */
currentTurnStartIndex: number;
pendingPrompts: Map<number | string, TurnState>;
+ promptDeliveryIds: Set<string>;
shellExecutes: Map<string, { item: UserShellExecute; index: number }>;
isCompacting: boolean;
isClearing: boolean;
@@ -172,6 +173,7 @@ export function createItemBuilder(): ItemBuilder {
currentTurn: null,
currentTurnStartIndex: 0,
pendingPrompts: new Map(),
+ promptDeliveryIds: new Set(),
shellExecutes: new Map(),
isCompacting: false,
isClearing: false,
@@ -584,6 +586,13 @@ function handlePromptRequest(
const userPrompt = extractUserPrompt(msg.params);
const userContent = userPrompt.content;
+ const messageId = (msg.params as { _meta?: { messageId?: unknown } } | null)
+ ?._meta?.messageId;
+ const isRedelivery =
+ typeof messageId === "string" && b.promptDeliveryIds.has(messageId);
+ if (typeof messageId === "string") {
+ b.promptDeliveryIds.add(messageId);
+ }
if (userContent.trim().length === 0 && userPrompt.attachments.length === 0) {
return;
@@ -656,7 +665,7 @@ function handlePromptRequest(
id: `${turnId}-skill-action`,
buttonId: skillButtonId,
});
- } else {
+ } else if (!isRedelivery) {
b.items.splice(insertIndex, 0, {
type: "user_message",
id: `${turnId}-user`,
diff --git a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
index fea96c9c5972..46dadbf37c60 100644
--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
@@ -55,6 +55,8 @@ const mockTrpcSkills = vi.hoisted(() => ({
resolveDependencies: { query: vi.fn() },
}));
+const mockToast = vi.hoisted(() => ({ error: vi.fn(), info: vi.fn() }));
+
const mockSessionStoreSetters = vi.hoisted(() => ({
setSession: vi.fn(),
removeSession: vi.fn(),
@@ -325,7 +327,7 @@ vi.mock("../../shell/logger", () => ({
},
}));
vi.mock("@posthog/ui/primitives/toast", () => ({
- toast: { error: vi.fn(), info: vi.fn() },
+ toast: mockToast,
}));
vi.mock("@posthog/di/container", () => ({
resolveService: (token: unknown) => {
@@ -8207,19 +8209,20 @@ describe("SessionService", () => {
);
});
- it("does not run session recovery for a transient upstream API timeout", async () => {
+ it.each([
+ "Internal error: API Error: the operation timed out",
+ "Internal error: API Error: Content block is not a thinking block",
+ ])("does not run session recovery for %j", async (providerError) => {
const service = getSessionService();
const mockSession = createMockSession();
mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(mockSession);
mockSessionStoreSetters.getSessions.mockReturnValue({
"run-123": mockSession,
});
- mockTrpcAgent.prompt.mutate.mockRejectedValue(
- new Error("Internal error: API Error: the operation timed out"),
- );
+ mockTrpcAgent.prompt.mutate.mockRejectedValue(new Error(providerError));
await expect(service.sendPrompt("task-123", "Hello")).rejects.toThrow(
- /provider timed out/,
+ /could not complete the request/,
);
// The session stays as-is: no recovery reconnect, no error overlay —
@@ -8255,9 +8258,9 @@ describe("SessionService", () => {
mockSessionStoreSetters.setSession.mockImplementation((next) => {
session = next as AgentSession;
});
- mockSessionStoreSetters.dequeueMessagesAsText.mockReturnValue(
- "follow up",
- );
+ mockSessionStoreSetters.dequeueMessages.mockReturnValue([
+ { id: "q-1", content: "follow up", queuedAt: 1 },
+ ]);
mockBuildAuthenticatedClient.mockReturnValue({
...mockAuthenticatedClient,
@@ -8405,9 +8408,7 @@ describe("SessionService", () => {
expect(
mockNotificationService.notifyPromptComplete,
).toHaveBeenCalledWith("Test Task", "end_turn", "task-123", undefined);
- expect(
- mockSessionStoreSetters.dequeueMessagesAsText,
- ).not.toHaveBeenCalled();
+ expect(mockSessionStoreSetters.dequeueMessages).not.toHaveBeenCalled();
expect(mockTrpcAgent.prompt.mutate).not.toHaveBeenCalled();
} finally {
vi.useRealTimers();
@@ -8429,9 +8430,7 @@ describe("SessionService", () => {
onData(promptResponse(42, "cancelled"));
await vi.advanceTimersByTimeAsync(20);
- expect(
- mockSessionStoreSetters.dequeueMessagesAsText,
- ).not.toHaveBeenCalled();
+ expect(mockSessionStoreSetters.dequeueMessages).not.toHaveBeenCalled();
expect(mockTrpcAgent.prompt.mutate).not.toHaveBeenCalled();
} finally {
vi.useRealTimers();
@@ -8452,9 +8451,9 @@ describe("SessionService", () => {
],
}),
);
- mockSessionStoreSetters.dequeueMessagesAsText
- .mockReturnValueOnce("first")
- .mockReturnValueOnce("second");
+ mockSessionStoreSetters.dequeueMessages
+ .mockReturnValueOnce([{ id: "q-1", content: "first", queuedAt: 1 }])
+ .mockReturnValueOnce([{ id: "q-2", content: "second", queuedAt: 2 }]);
mockTrpcAgent.prompt.mutate.mockResolvedValue({
stopReason: "end_turn",
});
@@ -8464,7 +8463,7 @@ describe("SessionService", () => {
expect(mockTrpcAgent.prompt.mutate).toHaveBeenCalledTimes(1);
expect(
- mockSessionStoreSetters.dequeueMessagesAsText,
+ mockSessionStoreSetters.dequeueMessages,
).toHaveBeenLastCalledWith("task-123", { stopAtEdited: true, max: 1 });
// The sent message's turn runs and completes: its prompt echo claims a
@@ -8483,9 +8482,9 @@ describe("SessionService", () => {
await vi.advanceTimersByTimeAsync(20);
expect(mockTrpcAgent.prompt.mutate).toHaveBeenCalledTimes(2);
- expect(
- mockSessionStoreSetters.dequeueMessagesAsText,
- ).toHaveBeenCalledTimes(2);
+ expect(mockSessionStoreSetters.dequeueMessages).toHaveBeenCalledTimes(
+ 2,
+ );
} finally {
vi.useRealTimers();
}
@@ -8506,9 +8505,9 @@ describe("SessionService", () => {
editingQueuedId: "q-2",
}),
);
- mockSessionStoreSetters.dequeueMessagesAsText
- .mockReturnValueOnce("first")
- .mockReturnValueOnce("second");
+ mockSessionStoreSetters.dequeueMessages
+ .mockReturnValueOnce([{ id: "q-1", content: "first", queuedAt: 1 }])
+ .mockReturnValueOnce([{ id: "q-2", content: "second", queuedAt: 2 }]);
// Keep the first send in flight so the raced timer must observe it.
mockTrpcAgent.prompt.mutate.mockImplementation(
() => new Promise(() => {}),
@@ -8523,9 +8522,83 @@ describe("SessionService", () => {
await vi.advanceTimersByTimeAsync(20);
expect(mockTrpcAgent.prompt.mutate).toHaveBeenCalledTimes(1);
+ expect(mockSessionStoreSetters.dequeueMessages).toHaveBeenCalledTimes(
+ 1,
+ );
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it.each([
+ "Internal error: API Error: Content block not found",
+ "Internal error: API Error: Content block is not a thinking block",
+ ])("restores a queued message after %j", async (providerError) => {
+ const { onData, setSession } = await connectWithLiveSession();
+ vi.useFakeTimers();
+ try {
+ const queuedMessage = {
+ id: "q-1",
+ content: "follow up",
+ rawPrompt: [{ type: "text" as const, text: "follow up" }],
+ queuedAt: 1,
+ };
+ setSession(
+ createMockSession({
+ currentPromptId: 42,
+ isPromptPending: true,
+ messageQueue: [queuedMessage],
+ }),
+ );
+ mockSessionStoreSetters.dequeueMessages
+ .mockReset()
+ .mockReturnValue([queuedMessage]);
+ mockTrpcAgent.prompt.mutate.mockRejectedValue(new Error(providerError));
+
+ onData(promptResponse(42, "end_turn"));
+ await vi.advanceTimersByTimeAsync(20);
+
expect(
- mockSessionStoreSetters.dequeueMessagesAsText,
- ).toHaveBeenCalledTimes(1);
+ mockSessionStoreSetters.prependQueuedMessages,
+ ).toHaveBeenCalledWith("task-123", [queuedMessage]);
+ expect(mockToast.error).toHaveBeenCalledWith(
+ "Couldn't send the queued message",
+ {
+ description:
+ "Your message is still queued. Use Steer to try again.",
+ },
+ );
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("restores a rate-limited queued message", async () => {
+ const { onData, setSession } = await connectWithLiveSession();
+ vi.useFakeTimers();
+ try {
+ const queuedMessage = { id: "q-1", content: "follow up", queuedAt: 1 };
+ setSession(
+ createMockSession({
+ currentPromptId: 42,
+ isPromptPending: true,
+ messageQueue: [queuedMessage],
+ }),
+ );
+ mockSessionStoreSetters.dequeueMessages
+ .mockReset()
+ .mockReturnValue([queuedMessage]);
+ mockTrpcAgent.prompt.mutate.mockRejectedValue(
+ new Error("Rate limit exceeded: User burst rate limit exceeded"),
+ );
+
+ onData(promptResponse(42, "end_turn"));
+ await vi.advanceTimersByTimeAsync(20);
+
+ expect(
+ mockSessionStoreSetters.prependQueuedMessages,
+ ).toHaveBeenCalledWith("task-123", [queuedMessage]);
+ expect(mockToast.error).not.toHaveBeenCalled();
} finally {
vi.useRealTimers();
}
@@ -8783,7 +8856,9 @@ describe("SessionService", () => {
try {
const service = getSessionService();
seedEditedIdleSession();
- mockSessionStoreSetters.dequeueMessagesAsText.mockReturnValue("edited");
+ mockSessionStoreSetters.dequeueMessages.mockReturnValue([
+ { id: "q-1", content: "edited", queuedAt: 1 },
+ ]);
mockTrpcAgent.prompt.mutate.mockResolvedValue({
stopReason: "end_turn",
});
@@ -8802,9 +8877,10 @@ describe("SessionService", () => {
expect(
mockSessionStoreSetters.clearEditingQueuedMessage,
).toHaveBeenCalledWith("task-123");
- expect(
- mockSessionStoreSetters.dequeueMessagesAsText,
- ).toHaveBeenCalledWith("task-123", { stopAtEdited: true, max: 1 });
+ expect(mockSessionStoreSetters.dequeueMessages).toHaveBeenCalledWith(
+ "task-123",
+ { stopAtEdited: true, max: 1 },
+ );
expect(mockTrpcAgent.prompt.mutate).toHaveBeenCalledWith(
expect.objectContaining({ sessionId: "run-123" }),
);
@@ -8847,9 +8923,7 @@ describe("SessionService", () => {
mockSessionStoreSetters.clearEditingQueuedMessage,
).toHaveBeenCalledWith("task-123");
// Left for the turn-end drain — nothing sent mid-turn.
- expect(
- mockSessionStoreSetters.dequeueMessagesAsText,
- ).not.toHaveBeenCalled();
+ expect(mockSessionStoreSetters.dequeueMessages).not.toHaveBeenCalled();
expect(mockTrpcAgent.prompt.mutate).not.toHaveBeenCalled();
} finally {
vi.useRealTimers();
@@ -8861,7 +8935,9 @@ describe("SessionService", () => {
try {
const service = getSessionService();
seedEditedIdleSession();
- mockSessionStoreSetters.dequeueMessagesAsText.mockReturnValue("q-1");
+ mockSessionStoreSetters.dequeueMessages.mockReturnValue([
+ { id: "q-1", content: "q-1", queuedAt: 1 },
+ ]);
mockTrpcAgent.prompt.mutate.mockResolvedValue({
stopReason: "end_turn",
});
@@ -8869,9 +8945,10 @@ describe("SessionService", () => {
service.clearEditingQueuedMessage("task-123");
await vi.advanceTimersByTimeAsync(0);
- expect(
- mockSessionStoreSetters.dequeueMessagesAsText,
- ).toHaveBeenCalledWith("task-123", { stopAtEdited: true, max: 1 });
+ expect(mockSessionStoreSetters.dequeueMessages).toHaveBeenCalledWith(
+ "task-123",
+ { stopAtEdited: true, max: 1 },
+ );
expect(mockTrpcAgent.prompt.mutate).toHaveBeenCalled();
} finally {
vi.useRealTimers();
diff --git a/products/tasks/backend/logic/services/agent_command.py b/products/tasks/backend/logic/services/agent_command.py
index ba8478960cca..306136786f8d 100644
--- a/products/tasks/backend/logic/services/agent_command.py
+++ b/products/tasks/backend/logic/services/agent_command.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import re
import socket
import ipaddress
from dataclasses import dataclass
@@ -39,18 +40,21 @@ BLOCKED_IP_RANGES = [
]
NO_ACTIVE_SESSION_ERROR = "No active session for this run"
-CONTENT_BLOCK_STREAM_ERROR = "API Error: Content block not found"
-CONTENT_BLOCK_STREAM_USER_ERROR = "The model response could not be completed. Please retry the task."
+# The provider rejects a turn whose transcript content blocks do not line up
+# ("Content block not found", "Content block is not a thinking block"). The
+# wording changes with the provider, so match the family, not each string.
+CONTENT_BLOCK_ERROR = re.compile(r"API Error:\s*Content block\b", re.IGNORECASE)
+CONTENT_BLOCK_USER_ERROR = "The model response could not be completed. Please retry the task."
TURN_ENDED_WITHOUT_RESPONSE_ERROR = "[ede_diagnostic] result_type=user"
def is_retryable_agent_rpc_error(error: str) -> bool:
- return CONTENT_BLOCK_STREAM_ERROR in error or TURN_ENDED_WITHOUT_RESPONSE_ERROR in error
+ return bool(CONTENT_BLOCK_ERROR.search(error)) or TURN_ENDED_WITHOUT_RESPONSE_ERROR in error
def user_facing_agent_error(error: str | None) -> str:
- if error and CONTENT_BLOCK_STREAM_ERROR in error:
- return CONTENT_BLOCK_STREAM_USER_ERROR
+ if error and CONTENT_BLOCK_ERROR.search(error):
+ return CONTENT_BLOCK_USER_ERROR
return error or "Failed to send message to sandbox"
diff --git a/products/tasks/backend/logic/services/tests/test_agent_command.py b/products/tasks/backend/logic/services/tests/test_agent_command.py
index 91e606bcccaa..621e0f4cdefd 100644
--- a/products/tasks/backend/logic/services/tests/test_agent_command.py
+++ b/products/tasks/backend/logic/services/tests/test_agent_command.py
@@ -6,6 +6,7 @@ from django.test import override_settings
import requests
from products.tasks.backend.logic.services.agent_command import (
+ CONTENT_BLOCK_USER_ERROR,
REFRESH_SESSION_METHOD,
REFRESH_TIMEOUT_SECONDS,
CommandResult,
@@ -15,6 +16,7 @@ from products.tasks.backend.logic.services.agent_command import (
send_cancel,
send_refresh_session,
send_user_message,
+ user_facing_agent_error,
validate_sandbox_url,
)
@@ -323,13 +325,20 @@ class TestSendAgentCommand:
@patch("products.tasks.backend.logic.services.agent_command.validate_sandbox_url", return_value=None)
@patch("products.tasks.backend.logic.services.agent_command.requests.post")
- def test_content_block_stream_error_is_retryable(self, mock_post, mock_validate):
+ @pytest.mark.parametrize(
+ "message",
+ [
+ "Internal error: API Error: Content block not found",
+ "Internal error: API Error: Content block is not a thinking block",
+ ],
+ )
+ def test_content_block_error_is_retryable(self, mock_post, mock_validate, message):
mock_resp = MagicMock()
mock_resp.status_code = 200
mock_resp.json.return_value = {
"jsonrpc": "2.0",
"id": 1,
- "error": {"code": -32603, "message": "Internal error: API Error: Content block not found"},
+ "error": {"code": -32603, "message": message},
}
mock_post.return_value = mock_resp
@@ -569,3 +578,17 @@ class TestBuildRequestArgsHoglandParam:
headers, query_params = _build_request_args("hog-tok", None, token_param="token")
assert "Authorization" not in headers
assert query_params == {"token": "hog-tok"}
+
+
+class TestUserFacingAgentError:
+ @pytest.mark.parametrize(
+ "error,expected",
+ [
+ ("Internal error: API Error: Content block not found", CONTENT_BLOCK_USER_ERROR),
+ ("Internal error: API Error: Content block is not a thinking block", CONTENT_BLOCK_USER_ERROR),
+ ("Internal error: API Error: 402 admission rejected", "Internal error: API Error: 402 admission rejected"),
+ (None, "Failed to send message to sandbox"),
+ ],
+ )
+ def test_content_block_rejections_are_rewritten(self, error, expected):
+ assert user_facing_agent_error(error) == expected