diff --git a/backend/docs/API.md b/backend/docs/API.md index 52a80febc7..0619bf0ebd 100644 --- a/backend/docs/API.md +++ b/backend/docs/API.md @@ -2184,6 +2184,24 @@ when the frontend runs with `pnpm start` and no nginx) from gzipping and therefo buffering the stream; `X-Accel-Buffering: no` does the same for nginx. A reverse proxy you put in front of the Gateway should not compress `text/event-stream`. +### SSE run errors + +An `error` event from the run worker carries a JSON object with `message` and +`name`. If the error supplies a string `code`, the event also includes that code +and any of these fields that have the expected type. + +| Field | When included | +|---|---| +| `retryable` | The error supplies a boolean indicating whether retrying may help. | +| `retry_after_seconds` | The error supplies a finite number of seconds to wait before retrying. Missing values, booleans, `NaN`, and infinities are omitted. | + +Errors without a string `code` carry only `message` and `name`. Sandbox capacity +errors use `SANDBOX_CAPACITY_EXCEEDED`. + +The JavaScript LangGraph SDK's `StreamError` exposes `message` and `name` from +the payload. To use the optional fields, read the JSON `data` from the raw SSE +`error` event. + ### SSE replay retention and gaps Clients may reconnect to a run stream with `Last-Event-ID`. Replay history is diff --git a/backend/packages/harness/deerflow/runtime/runs/worker.py b/backend/packages/harness/deerflow/runtime/runs/worker.py index 759a3b02d9..6f74fecefd 100644 --- a/backend/packages/harness/deerflow/runtime/runs/worker.py +++ b/backend/packages/harness/deerflow/runtime/runs/worker.py @@ -20,6 +20,7 @@ import copy import gc import inspect import logging +import math import os import sys import threading @@ -1128,6 +1129,27 @@ async def _drain_run_finalization(task: asyncio.Task[None], *, on_host_cancel: C raise deferred +def _run_error_frame(message: str, exc: BaseException) -> dict[str, object]: + """Build the run ``error`` event, keeping a structured error's retry fields. + + Errors such as ``SandboxCapacityExceededError`` carry a machine-readable + ``details`` dict. Clients get its code and retry hint as fields instead of + parsing them out of the message. + """ + frame: dict[str, object] = {"message": message, "name": type(exc).__name__} + details = getattr(exc, "details", None) + if isinstance(details, dict) and isinstance(details.get("code"), str): + frame["code"] = details["code"] + if isinstance(details.get("retryable"), bool): + frame["retryable"] = details["retryable"] + retry_after = details.get("retry_after_seconds") + # A NaN or infinite hint would be written as a bare token the SDK + # rejects, losing the whole frame; omit it and keep the rest. + if isinstance(retry_after, int | float) and not isinstance(retry_after, bool) and math.isfinite(retry_after): + frame["retry_after_seconds"] = retry_after + return frame + + @run_producer_context async def run_agent( bridge: StreamBridge, @@ -1225,7 +1247,7 @@ async def run_agent( # the verdict alone. goal_participated = False produced_output_paths: list[str] | None = None - terminal_error_frame: dict[str, str] | None = None + terminal_error_frame: dict[str, object] | None = None # Journal construction moved ahead of preflight so every terminal run can # emit a receipt. Completion persistence keeps its prior boundary: before # #4272 the journal did not exist until preflight had succeeded, so early @@ -2226,10 +2248,7 @@ async def run_agent( if cancel_action is not None: await _finish_cancellation(cancel_action, restore_checkpoint=not checkpoint_resume_rejected) elif not record.ownership_lost: - error_frame = { - "message": error_msg, - "name": type(exc).__name__, - } + error_frame = _run_error_frame(error_msg, exc) if record.status not in (RunStatus.pending, RunStatus.running) and getattr(record, "terminal_status_persisted", True): await bridge.publish( run_id, diff --git a/backend/tests/test_run_worker_delivery.py b/backend/tests/test_run_worker_delivery.py index 6c5109def4..a1f9dc2b53 100644 --- a/backend/tests/test_run_worker_delivery.py +++ b/backend/tests/test_run_worker_delivery.py @@ -21,6 +21,7 @@ from deerflow.runtime.runs.schemas import RunStatus from deerflow.runtime.runs.store.memory import MemoryRunStore from deerflow.runtime.runs.worker import RunContext, _delivery_content_with_outputs, run_agent from deerflow.runtime.user_context import get_effective_user_id +from deerflow.sandbox.exceptions import SandboxCapacityExceededError, SandboxCommandError from deerflow.workspace_changes import WorkspaceChangeLimits, capture_workspace_snapshot from deerflow.workspace_changes.api import get_workspace_changes_response @@ -436,6 +437,48 @@ async def test_unpresented_outputs_publish_an_error_frame_before_end(monkeypatch assert bridge.events[-1][0] == "end" +_CAPACITY_ERROR = SandboxCapacityExceededError(active=4, replicas=4, retry_after_seconds=30.0) + + +@pytest.mark.anyio +@pytest.mark.parametrize( + ("exc", "extra"), + [ + # A run that acquires its sandbox before the model runs fails with the + # provider's capacity error; clients get its code and retry hint (#8586). + (_CAPACITY_ERROR, {"code": "SANDBOX_CAPACITY_EXCEEDED", "retryable": True, "retry_after_seconds": 30.0}), + # A non-finite hint is dropped; the code and retryable flag still arrive. + (SandboxCapacityExceededError(active=4, replicas=4, retry_after_seconds=float("nan")), {"code": "SANDBOX_CAPACITY_EXCEEDED", "retryable": True}), + (SandboxCapacityExceededError(active=4, replicas=4, retry_after_seconds=float("inf")), {"code": "SANDBOX_CAPACITY_EXCEEDED", "retryable": True}), + (SandboxCommandError("bash failed", exit_code=2), {}), + (RuntimeError("boom"), {}), + ], +) +async def test_run_error_frame_keeps_a_structured_errors_retry_fields(exc, extra): + run_manager = RunManager() + record = await run_manager.create("thread-1") + bridge = _RecordingBridge() + + class FailingAgent: + async def astream(self, graph_input, config=None, stream_mode=None, subgraphs=False): + raise exc + yield # pragma: no cover - make this an async generator + + await run_agent( + bridge, + run_manager, + record, + ctx=RunContext(checkpointer=None, event_store=MemoryRunEventStore()), + agent_factory=lambda *, config: FailingAgent(), + graph_input={}, + config={}, + ) + + assert record.status == RunStatus.error + assert [payload for event, payload in bridge.events if event == "error"] == [{"message": str(exc), "name": type(exc).__name__, **extra}] + assert bridge.events[-1][0] == "end" + + @pytest.mark.anyio async def test_unpersisted_delivery_receipt_publishes_an_error_frame_before_end(monkeypatch): """The receipt failure also flips the record to ``error``; the stream must follow.""" diff --git a/frontend/src/core/i18n/locales/en-US.ts b/frontend/src/core/i18n/locales/en-US.ts index 5a09a505f3..54dbbfd5ef 100644 --- a/frontend/src/core/i18n/locales/en-US.ts +++ b/frontend/src/core/i18n/locales/en-US.ts @@ -1729,6 +1729,8 @@ export const enUS: Translations = { branchFailed: "Failed to branch conversation.", streamReplayGap: "Some live updates expired. The conversation was restored from saved state.", + sandboxBusy: + "Sandboxes are temporarily unavailable. Please try again shortly.", streamServerError: (status) => `The service is temporarily unavailable (HTTP ${status}). Please try again.`, outlineLabel: "Conversation outline", diff --git a/frontend/src/core/i18n/locales/types.ts b/frontend/src/core/i18n/locales/types.ts index b020d2290e..b296984b14 100644 --- a/frontend/src/core/i18n/locales/types.ts +++ b/frontend/src/core/i18n/locales/types.ts @@ -1447,6 +1447,7 @@ export interface Translations { branchCreated: string; branchFailed: string; streamReplayGap: string; + sandboxBusy: string; streamServerError: (status: number) => string; outlineLabel: string; outlineAttachmentFallback: string; diff --git a/frontend/src/core/i18n/locales/zh-CN.ts b/frontend/src/core/i18n/locales/zh-CN.ts index a1e20adabc..fd853c7c95 100644 --- a/frontend/src/core/i18n/locales/zh-CN.ts +++ b/frontend/src/core/i18n/locales/zh-CN.ts @@ -1619,6 +1619,7 @@ export const zhCN: Translations = { branchCreated: "已创建分叉对话", branchFailed: "创建分叉对话失败。", streamReplayGap: "部分实时更新已过期,已从持久化状态恢复对话。", + sandboxBusy: "沙箱暂时不可用,请稍后重试。", streamServerError: (status) => `服务暂时不可用(HTTP ${status}),请稍后重试。`, outlineLabel: "对话章节", diff --git a/frontend/src/core/threads/hooks.ts b/frontend/src/core/threads/hooks.ts index b32d764736..169f3a0d27 100644 --- a/frontend/src/core/threads/hooks.ts +++ b/frontend/src/core/threads/hooks.ts @@ -2101,11 +2101,21 @@ function getHttpStatus(error: unknown): number | undefined { return undefined; } -function getStreamErrorToastMessage( +export function getStreamErrorToastMessage( error: unknown, t: Translations, showApprovalErrors = false, ): string { + // The run's error event names the exception; a full sandbox pool is + // temporary, so say so instead of showing the provider's raw text. + if ( + typeof error === "object" && + error !== null && + (Reflect.get(error, "name") === "SandboxCapacityExceededError" || + Reflect.get(error, "code") === "SANDBOX_CAPACITY_EXCEEDED") + ) { + return t.conversation.sandboxBusy; + } const status = getHttpStatus(error); if (status !== undefined && status >= 500 && status < 600) { console.warn("Chat stream request failed:", getStreamErrorMessage(error)); diff --git a/frontend/tests/unit/core/threads/stream-error-toast.test.ts b/frontend/tests/unit/core/threads/stream-error-toast.test.ts new file mode 100644 index 0000000000..efa1a52585 --- /dev/null +++ b/frontend/tests/unit/core/threads/stream-error-toast.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from "@rstest/core"; + +import { enUS } from "@/core/i18n/locales/en-US"; +import { getStreamErrorToastMessage } from "@/core/threads/hooks"; + +describe("getStreamErrorToastMessage", () => { + it("says sandboxes are temporarily unavailable for a capacity run error", () => { + // The SDK turns the run's error event into an Error named after the + // backend exception; the message holds the provider's raw details. + const error = new Error( + "All sandbox replica slots are in use (code=SANDBOX_CAPACITY_EXCEEDED, retry_after_seconds=30.0)", + ); + error.name = "SandboxCapacityExceededError"; + + expect(getStreamErrorToastMessage(error, enUS)).toBe( + enUS.conversation.sandboxBusy, + ); + }); + + it("says sandboxes are temporarily unavailable for a raw frame with the code", () => { + expect( + getStreamErrorToastMessage( + { message: "raw", code: "SANDBOX_CAPACITY_EXCEEDED" }, + enUS, + ), + ).toBe(enUS.conversation.sandboxBusy); + }); + + it("keeps other run errors' messages", () => { + const error = new Error("boom"); + error.name = "RuntimeError"; + + expect(getStreamErrorToastMessage(error, enUS)).toBe("boom"); + }); +});