diff --git a/crates/ide-agent/src/native/codex/mod.rs b/crates/ide-agent/src/native/codex/mod.rs index 0c963b133..575c03837 100644 --- a/crates/ide-agent/src/native/codex/mod.rs +++ b/crates/ide-agent/src/native/codex/mod.rs @@ -1481,14 +1481,13 @@ fn stop_reason(turn: &Value, last_error: Option, rate_limits: Option<&Val let e = turn.get("error").filter(|e| !e.is_null()).cloned().or(last_error).unwrap_or(json!({})); let message = translate::error_message(&e); return match translate::classify(&e, rate_limits) { - Failure::Refusal => Ok(json!({ "stopReason": "refusal" })), Failure::UsageLimit(resets) => Err(ResponseError { code: codes::INTERNAL_ERROR, message, data: Some(json!({ "openidea": { "usageLimit": { "resetsAtMs": resets } } })), }), Failure::Auth => Err(error(AUTH_REQUIRED, format!("Codex authentication failed: {message}"))), - Failure::Other => Err(error(codes::INTERNAL_ERROR, message)), + Failure::Refusal | Failure::Other => Err(error(codes::INTERNAL_ERROR, message)), }; } _ => "end_turn", diff --git a/crates/ide-agent/src/native/codex/tests.rs b/crates/ide-agent/src/native/codex/tests.rs index 4e7394a8e..34c9d45a4 100644 --- a/crates/ide-agent/src/native/codex/tests.rs +++ b/crates/ide-agent/src/native/codex/tests.rs @@ -455,6 +455,90 @@ fn failures_are_classified() { assert_eq!(stop_reason(&json!({"status": "interrupted"}), None, None).unwrap(), json!({"stopReason": "cancelled"})); } +#[test] +fn failed_turns_preserve_codex_error_diagnostics() { + let policy = json!({ + "message": "This content was flagged for possible cybersecurity risk.", + "additionalDetails": "Contact support if this is unexpected.", + "codexErrorInfo": "cyberPolicy" + }); + let expected = "This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy"; + for (turn_error, last_error) in [(policy.clone(), None), (Value::Null, Some(policy.clone()))] { + let failure = stop_reason(&json!({ "status": "failed", "error": turn_error }), last_error, None).unwrap_err(); + assert_eq!(failure.code, codes::INTERNAL_ERROR); + assert_eq!(failure.message, expected); + } + // A completed turn's own error wins over an older error notification. + let failure = stop_reason( + &json!({ "status": "failed", "error": policy }), + Some(json!({ "message": "An earlier retry failed.", "codexErrorInfo": "other" })), + None, + ) + .unwrap_err(); + assert_eq!(failure.message, expected); +} + +#[test] +fn failed_turn_diagnostics_include_string_and_structured_error_codes() { + for (value, expected) in [ + ( + json!({ "message": "Context is full.", "codexErrorInfo": "contextWindowExceeded" }), + "Context is full.\nCodex error: contextWindowExceeded", + ), + ( + json!({ "message": "The stream disconnected.", "codexErrorInfo": { "responseStreamDisconnected": { "httpStatusCode": 502 } } }), + "The stream disconnected.\nCodex error: responseStreamDisconnected (HTTP 502)", + ), + ( + json!({ "message": "Failed\nbecause", "additionalDetails": "because", "codexErrorInfo": null }), + "Failed\nbecause", + ), + ( + json!({ "message": " ", "additionalDetails": " Details ", "codexErrorInfo": "cyberPolicy" }), + "Codex failed\nDetails\nCodex error: cyberPolicy", + ), + (json!({ "message": "Failed", "codexErrorInfo": "" }), "Failed"), + (json!({}), "Codex failed"), + ] { + assert_eq!(error_message(&value), expected); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn policy_failure_is_forwarded_over_acp_with_its_original_diagnostics() { + for notification_only in [false, true] { + let mut transcript = load(Scenario::UsageLimit.file()); + let policy = json!({ + "message": "This content was flagged for possible cybersecurity risk.", + "additionalDetails": "Contact support if this is unexpected.", + "codexErrorInfo": "cyberPolicy" + }); + for (out, frame) in &mut transcript.frames { + if *out { + continue; + } + match frame["method"].as_str() { + Some("error") => frame["params"]["error"] = policy.clone(), + Some("turn/completed") => { + frame["params"]["turn"]["error"] = if notification_only { Value::Null } else { policy.clone() } + } + _ => {} + } + } + let (results, _client, _frames, _meta, _codex) = replay_transcript(Scenario::Simple, transcript).await; + match result(&results, "prompt") { + Err(RpcError::Server { code, message, .. }) => { + assert_eq!(*code, codes::INTERNAL_ERROR); + assert_eq!( + message, + "This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy" + ); + } + response => panic!("the failed turn must reach the task as an error, got {response:?}"), + } + } +} + #[test] fn approvals_offer_what_codex_offers_and_always_a_decline() { let params = json!({"availableDecisions": ["accept", diff --git a/crates/ide-agent/src/native/codex/translate.rs b/crates/ide-agent/src/native/codex/translate.rs index 63f3a5d7d..1db204339 100644 --- a/crates/ide-agent/src/native/codex/translate.rs +++ b/crates/ide-agent/src/native/codex/translate.rs @@ -740,7 +740,7 @@ pub(super) enum Failure { UsageLimit(Option), /// Signed out or refused. Auth, - /// The model declined. + /// The server blocked the turn under a safety policy. Refusal, Other, } @@ -780,13 +780,27 @@ fn resets_at(rate_limits: Option<&Value>) -> Option { exhausted.map(|s| s * 1000.0) } -/// The text a failed turn reports: codex's message, with its details. +/// The text a failed turn reports: Codex's message, details and diagnostic code. pub(super) fn error_message(error: &Value) -> String { - let message = error.get("message").and_then(Value::as_str).unwrap_or("Codex failed").trim(); - match error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty()) { - Some(details) if !message.contains(details) => format!("{message}\n{details}"), - _ => message.to_owned(), + let original = + error.get("message").and_then(Value::as_str).map(str::trim).filter(|m| !m.is_empty()).unwrap_or("Codex failed"); + let mut message = original.to_owned(); + if let Some(details) = + error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty()) + && !original.contains(details) + { + message.push('\n'); + message.push_str(details); } + let info = error.get("codexErrorInfo").unwrap_or(&Value::Null); + let code = info.as_str().or_else(|| info.as_object()?.keys().next().map(String::as_str)); + if let Some(code) = code.map(str::trim).filter(|c| !c.is_empty()) { + message.push_str(&format!("\nCodex error: {code}")); + if let Some(status) = info.get(code).and_then(|details| details.get("httpStatusCode")).and_then(Value::as_u64) { + message.push_str(&format!(" (HTTP {status})")); + } + } + message } /// One choice of an approval: what ACP shows and what codex gets back. diff --git a/e2e/agentErrorDetails.spec.ts b/e2e/agentErrorDetails.spec.ts new file mode 100644 index 000000000..a9eab5b46 --- /dev/null +++ b/e2e/agentErrorDetails.spec.ts @@ -0,0 +1,81 @@ +import type { Page } from "@playwright/test"; +import type { AgentEntry, AgentTask } from "../src/bindings"; +import { expect, openFromTree, test } from "./fixtures"; + +const policyMessage = "This content was flagged for possible cybersecurity risk."; +const policyDetails = "Contact support if this is unexpected."; +const diagnostics = `${policyMessage}\n${policyDetails}\nCodex error: cyberPolicy`; +const now = Date.now(); +const task: AgentTask = { + id: "sample-policy-failure", + title: "Investigate sample editor crash", + provider: "codex", + model: null, + status: "failed", + isolation: "local", + cwd: "/dev/acme-api", + branch: null, + base: null, + baseCommit: null, + error: diagnostics, + createdMs: now - 2000, + updatedMs: now, + config: [], + commands: [], + usage: null, + queue: [], +}; +const entries: AgentEntry[] = [ + { + type: "user", + text: "Investigate and fix the sample editor shutdown crash.", + attachments: [], + sentMs: now - 2000, + doneMs: now - 1000, + }, + { type: "agent", text: "I will check the shutdown sequence and run the regression tests." }, + { type: "error", message: diagnostics }, +]; + +async function showFailure(page: Page) { + await page.evaluate( + async ({ task, entries }) => { + const storePath = "/src/features/agents/store.ts"; + const ipcPath = "/src/platform/ipc.ts"; + const store = await import(storePath); + const { commands } = await import(ipcPath); + commands.agentEntries = async () => ({ status: "ok", data: entries }); + commands.agentChanges = async () => ({ status: "ok", data: [] }); + store.useAgents.setState({ + loaded: true, + error: null, + providers: [], + tasks: new Map([[task.id, task]]), + entries: new Map(), + unread: new Set(), + }); + await store.openTaskInEditorLocation(task.id); + }, + { task, entries }, + ); +} + +for (const width of [1400, 700]) { + test(`preserves saved Codex error details and code at width ${width}`, async ({ workbench: page }) => { + await page.setViewportSize({ width, height: 900 }); + await showFailure(page); + const error = page.getByRole("alert").filter({ hasText: policyMessage }); + await expect(error).toBeVisible(); + await expect(error).toContainText(policyDetails); + await expect(error).toContainText("Codex error: cyberPolicy"); + await expect(error).toHaveCSS("white-space", "pre-wrap"); + await expect(page.getByText("The agent declined to continue.", { exact: true })).toHaveCount(0); + await expect(error.getByRole("button", { name: "Sign In…" })).toHaveCount(0); + expect(await error.evaluate((element) => element.scrollWidth <= element.clientWidth)).toBe(true); + // A different editor must not replace the saved failure with a generic task status. + await openFromTree(page, "README.md"); + await page.getByRole("button", { name: "Agents", exact: true }).click(); + await page.getByRole("tree", { name: "Agent tasks", exact: true }).getByText(task.title, { exact: true }).click(); + await expect(error).toContainText(diagnostics); + }); +}