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): show policy refusals in chat (#86740)

Matt Pua6b05d4cba0cb
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.ts
index 1b8c222f7234..e748031a9cd0 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
@@ -2103,7 +2103,7 @@ describe("CodexAppServerAgent", () => {
stub.emit("turn/completed", { turn: { status: "completed" } });
});
- it("finalizes the turn on a non-retried error notification", async () => {
+ it("rejects the prompt on a non-retried error notification", async () => {
const stub = makeStubRpc({ "thread/start": { thread: { id: "t" } } });
const { client } = makeFakeClient();
const agent = new CodexAppServerAgent(client, {
@@ -2116,10 +2116,273 @@ describe("CodexAppServerAgent", () => {
sessionId: "t",
prompt: [{ type: "text", text: "go" }],
} as unknown as PromptRequest);
- // willRetry:false must resolve the turn rather than hang until stream close.
+ // willRetry:false must reject the turn rather than hang until stream close.
stub.emit("error", { willRetry: false, error: { message: "boom" } });
+ await expect(done).rejects.toThrow(
+ "The agent stopped before completing this request. Please try again.",
+ );
+ });
+
+ it("renders a non-retried policy error as agent output", async () => {
+ const stub = makeStubRpc({
+ "thread/start": { thread: { id: "t" } },
+ "turn/start": { turn: { id: "turn_1", status: "inProgress" } },
+ });
+ const sessionUpdates: unknown[] = [];
+ const messageDelivery = new Promise<void>(() => {});
+ const client = {
+ sessionUpdate: async (notification: unknown) => {
+ sessionUpdates.push(notification);
+ await messageDelivery;
+ },
+ requestPermission: async () => ({
+ outcome: "selected" as const,
+ optionId: "allow",
+ }),
+ extNotification: async () => {},
+ } as unknown as AgentSideConnection;
+ 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("error", {
+ willRetry: false,
+ error: {
+ message: "This content was flagged for possible cybersecurity risk.",
+ codexErrorInfo: "cyberPolicy",
+ },
+ });
+ stub.emit("turn/completed", {
+ turn: { id: "turn_1", status: "failed" },
+ });
+
expect((await done).stopReason).toBe("refusal");
+ expect(sessionUpdates).toContainEqual({
+ sessionId: "t",
+ update: {
+ sessionUpdate: "agent_message_chunk",
+ content: {
+ type: "text",
+ text: "This request was blocked because it may pose a cybersecurity risk. Revise the request and try again.",
+ },
+ },
+ });
+ });
+
+ it("renders a gateway usage policy error as agent output", 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: "go" }],
+ } as unknown as PromptRequest);
+ stub.emit("error", {
+ willRetry: false,
+ error: {
+ message:
+ "Invalid prompt: your prompt was flagged as potentially violating our usage policy.",
+ codexErrorInfo: "other",
+ },
+ });
+
+ expect((await done).stopReason).toBe("refusal");
+ expect(sessionUpdates).toContainEqual({
+ sessionId: "t",
+ update: {
+ sessionUpdate: "agent_message_chunk",
+ content: {
+ type: "text",
+ text: "This request was blocked by a safety policy. Revise the request and try again.",
+ },
+ },
+ });
+ });
+
+ it("renders a policy error after the turn already completed", async () => {
+ const stub = makeStubRpc({
+ "thread/start": { thread: { id: "t" } },
+ "turn/start": { turn: { id: "turn_1", status: "inProgress" } },
+ });
+ const { client, sessionUpdates } = makeFakeClient();
+ const agent = new CodexAppServerAgent(client, {
+ processOptions: { binaryPath: "/x/codex" },
+ rpcFactory: stub.factory,
+ });
+
+ await agent.newSession({ cwd: "/r" } as unknown as NewSessionRequest);
+ const done = agent.prompt({
+ sessionId: "t",
+ prompt: [{ type: "text", text: "go" }],
+ } as unknown as PromptRequest);
+ stub.emit("turn/completed", {
+ turn: { status: "failed" },
+ });
+ stub.emit("error", {
+ willRetry: false,
+ error: {
+ message: "This content was flagged for possible cybersecurity risk.",
+ codexErrorInfo: "cyberPolicy",
+ },
+ });
+
+ await vi.waitFor(() => {
+ expect(sessionUpdates).toContainEqual({
+ sessionId: "t",
+ update: {
+ sessionUpdate: "agent_message_chunk",
+ content: {
+ type: "text",
+ text: "This request was blocked because it may pose a cybersecurity risk. Revise the request and try again.",
+ },
+ },
+ });
+ });
+ await expect(done).resolves.toMatchObject({ stopReason: "refusal" });
+ });
+
+ it("ignores a policy error from a failed previous turn", async () => {
+ vi.useFakeTimers();
+ const stub = makeStubRpc({
+ "thread/start": { thread: { id: "t" } },
+ "turn/start": { turn: { id: "turn_1", status: "inProgress" } },
+ });
+ 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 first = agent.prompt({
+ sessionId: "t",
+ prompt: [{ type: "text", text: "first" }],
+ } as unknown as PromptRequest);
+ stub.emit("turn/completed", {
+ turn: { id: "turn_1", status: "failed" },
+ });
+ await vi.advanceTimersByTimeAsync(250);
+ await expect(first).resolves.toMatchObject({ stopReason: "refusal" });
+
+ const second = agent.prompt({
+ sessionId: "t",
+ prompt: [{ type: "text", text: "second" }],
+ } as unknown as PromptRequest);
+ stub.emit("turn/started", { turn: { id: "turn_2" } });
+ stub.emit("error", {
+ turnId: "turn_1",
+ willRetry: false,
+ error: {
+ message: "This content was flagged for possible cybersecurity risk.",
+ codexErrorInfo: "cyberPolicy",
+ },
+ });
+
+ expect(sessionUpdates).not.toContainEqual({
+ sessionId: "t",
+ update: {
+ sessionUpdate: "agent_message_chunk",
+ content: {
+ type: "text",
+ text: "This request was blocked because it may pose a cybersecurity risk. Revise the request and try again.",
+ },
+ },
+ });
+ stub.emit("turn/completed", {
+ turn: { id: "turn_2", status: "completed" },
+ });
+ await expect(second).resolves.toMatchObject({ stopReason: "end_turn" });
+ vi.useRealTimers();
+ });
+
+ it("settles a failed completion when Codex omits turn/started", async () => {
+ vi.useFakeTimers();
+ const stub = makeStubRpc({ "thread/start": { thread: { id: "t" } } });
+ const { client } = makeFakeClient();
+ const agent = new CodexAppServerAgent(client, {
+ processOptions: { binaryPath: "/x/codex" },
+ rpcFactory: stub.factory,
+ });
+
+ await agent.newSession({ cwd: "/r" } as unknown as NewSessionRequest);
+ const done = agent.prompt({
+ sessionId: "t",
+ prompt: [{ type: "text", text: "go" }],
+ } as unknown as PromptRequest);
+ stub.emit("turn/completed", {
+ turn: { id: "turn_1", status: "failed" },
+ });
+
+ await vi.advanceTimersByTimeAsync(250);
+ await expect(done).resolves.toMatchObject({ stopReason: "refusal" });
+ vi.useRealTimers();
+ });
+
+ it("does not let an ID-less failed completion refuse a later prompt", async () => {
+ vi.useFakeTimers();
+ const stub = makeStubRpc({ "thread/start": { thread: { id: "t" } } });
+ const { client } = makeFakeClient();
+ const agent = new CodexAppServerAgent(client, {
+ processOptions: { binaryPath: "/x/codex" },
+ rpcFactory: stub.factory,
+ });
+
+ await agent.newSession({ cwd: "/r" } as unknown as NewSessionRequest);
+ const first = agent.prompt({
+ sessionId: "t",
+ prompt: [{ type: "text", text: "first" }],
+ } as unknown as PromptRequest);
+ stub.emit("turn/completed", {
+ turn: { status: "failed" },
+ });
+ stub.emit("error", { willRetry: false, error: { message: "boom" } });
+ await expect(first).rejects.toThrow(
+ "The agent stopped before completing this request. Please try again.",
+ );
+
+ const second = agent.prompt({
+ sessionId: "t",
+ prompt: [{ type: "text", text: "second" }],
+ } as unknown as PromptRequest);
+ await vi.advanceTimersByTimeAsync(250);
+ stub.emit("turn/completed", {
+ turn: { status: "completed" },
+ });
+
+ await expect(second).resolves.toMatchObject({ stopReason: "end_turn" });
+ vi.useRealTimers();
+ });
+
+ it("rejects a malformed fatal error payload", async () => {
+ const stub = makeStubRpc({ "thread/start": { thread: { id: "t" } } });
+ const { client } = makeFakeClient();
+ const agent = new CodexAppServerAgent(client, {
+ processOptions: { binaryPath: "/x/codex" },
+ rpcFactory: stub.factory,
+ });
+
+ await agent.newSession({ cwd: "/r" } as unknown as NewSessionRequest);
+ const done = agent.prompt({
+ sessionId: "t",
+ prompt: [{ type: "text", text: "go" }],
+ } as unknown as PromptRequest);
+ stub.emit("error", { willRetry: false, error: { message: {} } });
+
+ await expect(done).rejects.toThrow(
+ "The agent stopped before completing this request. Please try again.",
+ );
});
it("rejects the prompt when the fatal error is a gateway billing denial", async () => {
@@ -2205,7 +2468,7 @@ describe("CodexAppServerAgent", () => {
expect(stub.requests.some((r) => r.method === "turn/start")).toBe(false);
});
- it("finalizes a turn once when error and turn/completed both arrive", async () => {
+ it("settles a turn once when error and turn/completed both arrive", async () => {
const stub = makeStubRpc({ "thread/start": { thread: { id: "t" } } });
const outputs: Array<Record<string, unknown>> = [];
const { client, extNotifications } = makeFakeClient();
@@ -2234,12 +2497,14 @@ describe("CodexAppServerAgent", () => {
stub.emit("item/completed", {
item: { type: "agentMessage", id: "a1", text: '{"ok":true}' },
});
- // error + turn/completed for one turn must not double-fire turn_complete (idempotent).
+ // error + turn/completed for one turn must settle the prompt and idle signal once.
stub.emit("error", { willRetry: false, error: { message: "boom" } });
stub.emit("turn/completed", { turn: { status: "failed" } });
- await done;
+ await expect(done).rejects.toThrow(
+ "The agent stopped before completing this request. Please try again.",
+ );
- // Structured output is gated on a clean end_turn: a refused turn records nothing.
+ // Structured output is gated on a clean end_turn: a failed turn records nothing.
expect(outputs).toEqual([]);
expect(
extNotifications.filter((n) => n.method === "_posthog/turn_complete")
@@ -3315,12 +3580,14 @@ describe("CodexAppServerAgent", () => {
sessionId: "t",
prompt: [{ type: "text", text: "go" }],
} as unknown as PromptRequest);
- // A fatal error ends the turn before item/completed; the finalize-time recovery still fires the boundary.
+ // A fatal error ends the turn before item/completed; failure recovery still fires the boundary.
stub.emit("item/started", {
item: { type: "contextCompaction", id: "c1" },
});
stub.emit("error", { willRetry: false, error: { message: "boom" } });
- await done;
+ await expect(done).rejects.toThrow(
+ "The agent stopped before completing this request. Please try again.",
+ );
expect(
extNotifications.find((n) => n.method === "_posthog/compact_boundary")
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts
index 00779bb9e11a..8775ffc214fc 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
@@ -100,6 +100,14 @@ 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.";
+
type AppServerSessionMeta = {
// The host sends either a plain string or the Claude-style `{ append }` form.
systemPrompt?: string | { append?: string };
@@ -1407,15 +1415,14 @@ export class CodexAppServerAgent extends BaseAcpAgent {
/** Emit a plain agent message (user-facing status the model didn't produce). */
private broadcastAgentText(text: string): void {
if (!this.sessionId) return;
- void this.client
- .sessionUpdate({
- sessionId: this.sessionId,
- update: {
- sessionUpdate: "agent_message_chunk",
- content: { type: "text", text },
- },
- })
- .catch(() => undefined);
+ const notification = {
+ sessionId: this.sessionId,
+ update: {
+ sessionUpdate: "agent_message_chunk",
+ content: { type: "text", text },
+ },
+ } as unknown as Parameters<AgentSideConnection["sessionUpdate"]>[0];
+ this.emitSessionNotification(notification);
}
/** The mode's sandbox with the session's extra writable roots folded into workspaceWrite. */
@@ -1615,6 +1622,13 @@ export class CodexAppServerAgent extends BaseAcpAgent {
}
// Drop the late completion of an already-interrupted turn (else it cancels the follow-up).
if (this.turns.shouldDropCompletion(turn?.id)) return;
+ if (turn?.status === "failed") {
+ this.deferFailedTurnFinalization(
+ turn?.id,
+ this.turns.currentGeneration,
+ );
+ return;
+ }
void this.finalizeTurn(mapTurnStopReason(turn?.status));
}
@@ -1634,32 +1648,36 @@ export class CodexAppServerAgent extends BaseAcpAgent {
if (method === APP_SERVER_NOTIFICATIONS.ERROR) {
// A non-retried fatal error: resolve the turn so prompt() returns rather than hangs.
- const { willRetry, error } = (params ?? {}) as {
+ const { willRetry, turnId, error } = (params ?? {}) as {
willRetry?: boolean;
- error?: { message?: string };
+ turnId?: string;
+ error?: { message?: unknown; codexErrorInfo?: unknown };
};
if (willRetry === false) {
+ if (turnId && turnId !== this.turns.activeTurnId) {
+ return;
+ }
this.logger.warn("codex app-server fatal error notification", {
params,
});
- const message = error?.message ?? "";
+ const message = typeof error?.message === "string" ? error.message : "";
+ const codexErrorInfo =
+ typeof error?.codexErrorInfo === "string"
+ ? error.codexErrorInfo
+ : undefined;
// A gateway billing denial rejects the prompt so the host classifies
// it and shows the upgrade gate. It must be a RequestError: a plain
// Error serializes to a bare "Internal error" at the ACP boundary,
// which the host reads as fatal and answers with a respawn loop.
if (classifyGatewayLimitError(message) !== null) {
- if (this.compactionActive) {
- this.compactionActive = false;
- this.emitCompactionBoundary();
- }
- this.turns.fail(RequestError.internalError(undefined, message));
+ void this.failTurn(RequestError.internalError(undefined, message));
return;
}
if (
message.includes("413") ||
message.toLowerCase().includes("request body too large")
) {
- this.turns.fail(
+ void this.failTurn(
RequestError.internalError(
undefined,
"This conversation is too large to continue. Start a new task and carry over a text summary instead of image or tool output.",
@@ -1667,7 +1685,22 @@ export class CodexAppServerAgent extends BaseAcpAgent {
);
return;
}
- void this.finalizeTurn("refusal");
+ let policyErrorMessage: string | null = null;
+ if (codexErrorInfo === "cyberPolicy") {
+ policyErrorMessage = CYBER_POLICY_ERROR_MESSAGE;
+ } else if (message.toLowerCase().includes("usage policy")) {
+ policyErrorMessage = POLICY_ERROR_MESSAGE;
+ }
+ if (policyErrorMessage) {
+ void this.refuseTurnWithMessage(policyErrorMessage);
+ return;
+ }
+ void this.failTurn(
+ new RequestError(
+ ACP_INTERNAL_ERROR_CODE,
+ GENERIC_FATAL_ERROR_MESSAGE,
+ ),
+ );
}
}
}
@@ -1984,6 +2017,57 @@ export class CodexAppServerAgent extends BaseAcpAgent {
});
}
+ private async failTurn(error: Error): Promise<void> {
+ this.turns.markInterrupted();
+ const pending = this.turns.claim();
+ if (!pending) return;
+ if (this.compactionActive) {
+ this.compactionActive = false;
+ this.emitCompactionBoundary();
+ }
+ const usage = this.usage.perTurnUsage();
+ pending.reject(error);
+ void this.emitTurnCompleteSignal("refusal", usage);
+ void this.emitUsageBreakdown(this.usage.contextTokens());
+ }
+
+ private deferFailedTurnFinalization(
+ turnId: string | undefined,
+ generation: number,
+ ): void {
+ setTimeout(() => {
+ if (generation !== this.turns.currentGeneration) return;
+ if (
+ turnId &&
+ this.turns.activeTurnId &&
+ this.turns.activeTurnId !== turnId
+ ) {
+ return;
+ }
+ if (!this.turns.isPending) return;
+ this.refuseTurnWithMessage(GENERIC_FATAL_ERROR_MESSAGE);
+ }, 250);
+ }
+
+ private refuseTurnWithMessage(message: string): void {
+ if (this.session.cancelled) return;
+ this.turns.markInterrupted();
+ const pending = this.turns.claim();
+ if (!pending) return;
+ this.broadcastAgentText(message);
+ if (this.compactionActive) {
+ this.compactionActive = false;
+ this.emitCompactionBoundary();
+ }
+ const usage = this.usage.perTurnUsage();
+ void this.emitTurnCompleteSignal("refusal", usage);
+ void this.emitUsageBreakdown(this.usage.contextTokens());
+ pending.resolve({
+ stopReason: "refusal",
+ ...(usage ? { usage } : {}),
+ });
+ }
+
/** Whether maybeOfferPlanImplementation will run for a turn that ended this way. */
private willOfferPlanHandoff(reason: StopReason): boolean {
return (
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/turn-controller.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/turn-controller.ts
index 2edf7fac0d6d..eb3c50cfdbdd 100644
--- a/products/desktop/packages/agent/src/adapters/codex-app-server/turn-controller.ts
+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/turn-controller.ts
@@ -30,6 +30,10 @@ export class TurnController {
return this.turnId;
}
+ get currentGeneration(): number {
+ return this.generation;
+ }
+
get isPending(): boolean {
return this.pending !== undefined;
}