Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6962 fix(daemon): give environment preparation failures their own failure reason (#7915)

Bohan Jianga2d819ea4016
diff --git a/apps/docs/content/docs/tasks.ja.mdx b/apps/docs/content/docs/tasks.ja.mdx
index d6d0313341..f3b2d384fe 100644
--- a/apps/docs/content/docs/tasks.ja.mdx
+++ b/apps/docs/content/docs/tasks.ja.mdx
@@ -96,6 +96,7 @@ import { Callout } from "fumadocs-ui/components/callout";
| `runtime_offline` | 実行中にランタイムがオフラインになった | ランタイムを復旧してからリトライ。[デーモンとランタイム](/daemon-runtimes)を参照 |
| `queued_expired` | ランタイムが再接続猶予を超えてハートビートを停止し、かつその作業も同じ時間キューで待っていた | ランタイムがオンラインであることを確認してからリトライ |
| `runtime_recovery` | デーモンが再起動後、中断された実行を回収した | そのままリトライ |
+| `environment_prepare_failed` | デーモンがこの実行の実行環境(作業ディレクトリ、およびそこに書き込むローカルランタイム設定)を準備できなかった | 生のエラーでどの段階が失敗したかを確認し、そのマシンのディスク空き容量・権限・ディレクトリの使用状況、AI コーディングツールのローカル設定を点検 |
| `cancelled` | 手動で停止されたか、アーカイブ・削除に伴ってキャンセルされた | 対処不要 |
| `timeout` | デーモンに設定された実行時間の上限を超えた | タスクの範囲を狭めるか、デーモンの `agent_timeout` を調整する |
| `iteration_limit` | 実行の反復回数の上限に達した | タスクの範囲を狭める |
diff --git a/apps/docs/content/docs/tasks.ko.mdx b/apps/docs/content/docs/tasks.ko.mdx
index 79b145bad0..e273b38eec 100644
--- a/apps/docs/content/docs/tasks.ko.mdx
+++ b/apps/docs/content/docs/tasks.ko.mdx
@@ -96,6 +96,7 @@ heartbeat가 정상인 런타임은 장시간 작업도 실행할 수 있으며
| `runtime_offline` | 실행 중 런타임이 오프라인이 됨 | 런타임을 복구한 뒤 재시도합니다. [데몬과 런타임](/daemon-runtimes) 참고 |
| `queued_expired` | 런타임이 재연결 유예를 넘겨 하트비트를 멈췄고, 작업도 그만큼 큐에서 기다림 | 런타임이 온라인인지 확인한 뒤 재시도 |
| `runtime_recovery` | 데몬 재시작 후 중단된 실행을 회수함 | 바로 재시도 |
+| `environment_prepare_failed` | 데몬이 이번 실행의 실행 환경(작업 디렉터리, 그리고 거기에 기록되는 로컬 런타임 설정)을 준비하지 못함 | 원본 오류로 어느 단계가 실패했는지 확인한 뒤 해당 머신의 디스크 여유 공간, 권한, 디렉터리 사용 여부, AI 코딩 도구의 로컬 설정을 점검 |
| `cancelled` | 수동으로 중지되었거나 보관 또는 삭제와 함께 취소됨 | 별도 처리 불필요 |
| `timeout` | 데몬에 설정된 실행 시간 상한을 초과함 | 태스크 범위를 줄이거나 데몬의 `agent_timeout` 조정 |
| `iteration_limit` | 실행 반복 횟수 상한에 도달함 | 태스크 범위 축소 |
diff --git a/apps/docs/content/docs/tasks.mdx b/apps/docs/content/docs/tasks.mdx
index b7667f9e24..4d6c0ea080 100644
--- a/apps/docs/content/docs/tasks.mdx
+++ b/apps/docs/content/docs/tasks.mdx
@@ -96,6 +96,7 @@ The failure reasons shown in the execution log and usage stats fall into two gro
| `runtime_offline` | The runtime went offline during the run | Restore the runtime and retry; see [Daemon and runtimes](/daemon-runtimes) |
| `queued_expired` | The runtime stopped heartbeating for longer than the reconnect grace, and the task had also been queued that long | Confirm the runtime is online, then retry |
| `runtime_recovery` | The daemon reclaimed an interrupted run after restarting | Retry directly |
+| `environment_prepare_failed` | The daemon could not set up the execution environment for this run — its working directory, or the local runtime config written into it | Read the raw error to see which step failed, then check that machine: disk space, permissions, a directory still in use, or the AI coding tool's local config |
| `cancelled` | Stopped manually, or cancelled along with an archive or delete | Nothing to do |
| `timeout` | Exceeded the daemon's configured execution time limit | Narrow the issue scope, or adjust the daemon's `agent_timeout` |
| `iteration_limit` | Hit the iteration cap for a run | Narrow the issue scope |
diff --git a/apps/docs/content/docs/tasks.zh.mdx b/apps/docs/content/docs/tasks.zh.mdx
index baf98ccf50..1c73f662f2 100644
--- a/apps/docs/content/docs/tasks.zh.mdx
+++ b/apps/docs/content/docs/tasks.zh.mdx
@@ -96,6 +96,7 @@ import { Callout } from "fumadocs-ui/components/callout";
| `runtime_offline` | 执行期间运行时离线 | 恢复运行时后重试,见[守护进程与运行时](/daemon-runtimes) |
| `queued_expired` | 运行时心跳缺席超过重连宽限期,且该 task 也已排队满这么久 | 确认运行时在线后重试 |
| `runtime_recovery` | 守护进程重启后回收了中断的执行 | 直接重试 |
+| `environment_prepare_failed` | 守护进程没能准备好本次执行的运行环境——工作目录,或写入其中的本地运行时配置 | 先看原始错误定位是哪一步失败,再检查那台机器:磁盘空间、权限、目录是否仍被占用,或 AI 编程工具的本地配置 |
| `cancelled` | 被手动停止,或随归档、删除一并取消 | 无需处理 |
| `timeout` | 超过守护进程配置的执行时长上限 | 缩小任务范围,或调整守护进程的 `agent_timeout` |
| `iteration_limit` | 达到执行轮次上限 | 缩小任务范围 |
diff --git a/apps/mobile/components/issue/run-row.tsx b/apps/mobile/components/issue/run-row.tsx
index 3cdbcb6a20..7383fc7f3b 100644
--- a/apps/mobile/components/issue/run-row.tsx
+++ b/apps/mobile/components/issue/run-row.tsx
@@ -16,6 +16,7 @@ import { Text } from "@/components/ui/text";
import { ActorAvatar } from "@/components/ui/actor-avatar";
import { useCancelTask } from "@/data/mutations/issues";
import { useActorLookup } from "@/data/use-actor-name";
+import { runFailureBadgeLabel } from "@/lib/run-failure-badge";
import { timeAgo } from "@/lib/time-ago";
interface Props {
@@ -66,8 +67,8 @@ function StatusBadge({ task }: { task: AgentTask }) {
const cls = STATUS_CLASS[task.status] ?? "text-muted-foreground";
// For failed tasks, surface the failure_reason inline so users don't have
// to drill in. Missing / empty / unrecognised stays as just "Failed".
- if (task.status === "failed" && task.failure_reason) {
- const reasonLabel = FAILURE_REASON_LABEL[task.failure_reason];
+ if (task.status === "failed") {
+ const reasonLabel = runFailureBadgeLabel(task.failure_reason);
if (reasonLabel) {
return (
<Text className={`text-xs ${cls}`}>
@@ -149,44 +150,3 @@ const STATUS_CLASS: Record<AgentTask["status"], string> = {
failed: "text-destructive",
cancelled: "text-muted-foreground",
};
-
-// Short badge copy — deliberately terser than lib/failure-reason-label.ts,
-// which backs a full-width chat bubble; this one shares a single line with the
-// status word and a timestamp.
-//
-// Keyed by the raw wire value, not a closed enum: `failure_reason` is an open
-// string that grows as classifier rules land. It held only the six
-// pre-MUL-1949 coarse values until MUL-5370, so every refined `agent_error.*`
-// the backend has written since fell through and the badge read just "Failed".
-// An unrecognised reason still does — a compact badge is the one place where
-// web's raw-wire-value fallback would overflow the row.
-const FAILURE_REASON_LABEL: Record<string, string> = {
- queued_expired: "Queue expired",
- runtime_offline: "Runtime offline",
- runtime_recovery: "Runtime recovery",
- timeout: "Timeout",
- iteration_limit: "Iteration limit",
- agent_blocked: "Needs input",
- api_invalid_request: "Request rejected",
- skill_bundle_unavailable: "Skill download failed",
- runtime_cli_timeout: "Runtime CLI timeout",
-
- "agent_error.provider_auth_or_access": "Auth failed",
- "agent_error.provider_quota_limit": "Quota exhausted",
- "agent_error.provider_capacity_or_rate_limit": "Rate limited",
- "agent_error.provider_server_error": "Provider error",
- "agent_error.provider_network": "Network error",
- "agent_error.process_failure": "Process crashed",
- "agent_error.empty_or_unparseable_output": "No usable output",
- "agent_error.agent_timeout": "Agent timeout",
- "agent_error.context_overflow": "Context overflow",
- "agent_error.missing_config": "Config missing",
- "agent_error.model_not_found_or_unavailable": "Model unavailable",
- "agent_error.runtime_version_unsupported": "CLI unsupported",
- "agent_error.runtime_missing_executable": "CLI not installed",
- "agent_error.unknown": "Agent error",
-
- agent_error: "Agent error",
- codex_semantic_inactivity: "Codex inactivity",
- manual: "Manual",
-};
diff --git a/apps/mobile/data/agent-task-schema.test.ts b/apps/mobile/data/agent-task-schema.test.ts
new file mode 100644
index 0000000000..f8f4c0677b
--- /dev/null
+++ b/apps/mobile/data/agent-task-schema.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from "vitest";
+
+import { runFailureBadgeLabel } from "@/lib/run-failure-badge";
+import { AgentTaskSchema } from "./schemas";
+
+function parseFailedTask(failure_reason: unknown) {
+ return AgentTaskSchema.parse({
+ id: "task-1",
+ status: "failed",
+ failure_reason,
+ });
+}
+
+describe("AgentTaskSchema failure_reason (#7913 regression)", () => {
+ // The field was a closed six-value enum with `.catch("")`, so every refined
+ // reason the backend has written since MUL-1949 was erased to undefined
+ // before any surface could read it. The badge map was widened in MUL-5370
+ // and has been unreachable ever since — the parser, not the map, was the
+ // reason a failed run said only "Failed".
+ it("keeps a refined reason the backend classifies today", () => {
+ expect(parseFailedTask("agent_error.provider_network").failure_reason).toBe(
+ "agent_error.provider_network",
+ );
+ expect(parseFailedTask("environment_prepare_failed").failure_reason).toBe(
+ "environment_prepare_failed",
+ );
+ });
+
+ it("keeps a reason newer than this build", () => {
+ // The taxonomy grows on the backend's cadence and installed builds lag it.
+ // Dropping an unknown value here would re-create the dead-map bug the next
+ // time a reason lands, which is the whole point of parsing it open.
+ expect(parseFailedTask("some_future_reason").failure_reason).toBe(
+ "some_future_reason",
+ );
+ });
+
+ it("still normalizes the not-failed sentinel to undefined", () => {
+ // Go's `omitempty` sends "" on a task that did not fail. Downstream truthy
+ // checks depend on that becoming undefined rather than an empty string.
+ expect(parseFailedTask("").failure_reason).toBeUndefined();
+ expect(parseFailedTask(undefined).failure_reason).toBeUndefined();
+ expect(parseFailedTask(42).failure_reason).toBeUndefined();
+ });
+
+ it("hands the run row a value its badge map can name", () => {
+ // The end-to-end shape of the bug: parse, then look up. Either half alone
+ // passed while the run row still rendered a bare "Failed".
+ const task = parseFailedTask("environment_prepare_failed");
+ expect(runFailureBadgeLabel(task.failure_reason)).toBe(
+ "Environment setup failed",
+ );
+ });
+});
diff --git a/apps/mobile/data/schemas.ts b/apps/mobile/data/schemas.ts
index 679f634143..68e4083979 100644
--- a/apps/mobile/data/schemas.ts
+++ b/apps/mobile/data/schemas.ts
@@ -404,9 +404,11 @@ export const EMPTY_SEARCH_PROJECTS_RESPONSE: SearchProjectsResponse = {
// Mirrors AgentTask in packages/core/types/agent.ts. Backend handlers:
// GET /api/issues/{id}/active-task → { tasks: AgentTask[] } (may be empty)
// GET /api/issues/{id}/task-runs → AgentTask[]
-// Lenient on every field — status / kind / failure_reason all use `.catch()`
-// so a future server-side enum value renders a generic fallback rather than
-// crashing the row (root CLAUDE.md "Enum drift downgrades, not crashes").
+// Lenient on every field — status / kind use `.catch()` so a future
+// server-side enum value renders a generic fallback rather than crashing the
+// row (root CLAUDE.md "Enum drift downgrades, not crashes"). failure_reason is
+// an open string instead: its taxonomy grows on the backend's cadence, so a
+// value this build has never seen must survive parsing and degrade at render.
export const AgentTaskSchema: z.ZodType<AgentTask> = z.object({
id: z.string(),
@@ -422,14 +424,27 @@ export const AgentTaskSchema: z.ZodType<AgentTask> = z.object({
completed_at: z.string().nullable().default(null),
result: z.unknown().default(null),
error: z.string().nullable().default(null),
+ // Open string, not an enum — same contract as `failure_reason` in
+ // packages/core/types/agent.ts and as the chat message schema above. The
+ // backend taxonomy passed the six coarse values at MUL-1949 and keeps
+ // growing (26 canonical reasons today), so an installed build meets reasons
+ // it predates.
+ //
+ // This field WAS a closed six-value enum, which made the whole thing moot:
+ // `.catch("")` erased every refined reason to `undefined`, so run-row's
+ // badge map has been unreachable for anything but the coarse values since
+ // MUL-5370 widened it, and every agent_error.* / skill_bundle_unavailable /
+ // environment_prepare_failed run rendered a bare "Failed" (#7913). Unknown
+ // reasons are the badge map's problem to degrade, not the parser's to drop.
+ //
// Backend uses empty string ("") as the "not failed" sentinel (Go
// `omitempty` on a custom string-typed enum). Normalize that to `undefined`
// so downstream truthy checks (`if (task.failure_reason)`) don't have to
// special-case both null/undefined AND "".
failure_reason: z
- .enum(["agent_error", "timeout", "runtime_offline", "runtime_recovery", "manual", ""])
+ .string()
.optional()
- .catch("")
+ .catch(undefined)
.transform((v) => (v === "" ? undefined : v)),
created_at: z.string().default(""),
chat_session_id: z.string().optional(),
diff --git a/apps/mobile/lib/failure-reason-label.ts b/apps/mobile/lib/failure-reason-label.ts
index 20a7adb067..ab5695e89f 100644
--- a/apps/mobile/lib/failure-reason-label.ts
+++ b/apps/mobile/lib/failure-reason-label.ts
@@ -28,6 +28,7 @@ const LABELS: Record<string, string> = {
api_invalid_request: "Rejected by the model API",
skill_bundle_unavailable: "Couldn't download the agent's skills",
runtime_cli_timeout: "Local runtime CLI timed out",
+ environment_prepare_failed: "Couldn't prepare the execution environment",
// Agent process side — provider.
"agent_error.provider_auth_or_access": "Provider auth failed",
diff --git a/apps/mobile/lib/run-failure-badge.test.ts b/apps/mobile/lib/run-failure-badge.test.ts
new file mode 100644
index 0000000000..c079fbb57d
--- /dev/null
+++ b/apps/mobile/lib/run-failure-badge.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from "vitest";
+
+import { runFailureBadgeLabel } from "./run-failure-badge";
+
+describe("runFailureBadgeLabel", () => {
+ it("names the reasons the backend classifies today", () => {
+ expect(runFailureBadgeLabel("agent_error.provider_network")).toBe(
+ "Network error",
+ );
+ expect(runFailureBadgeLabel("skill_bundle_unavailable")).toBe(
+ "Skill download failed",
+ );
+ // #7913: the run died setting up its environment on the executing
+ // machine. The badge has to say so — "Failed" alone is what sent the
+ // original report's diagnosis at a model provider.
+ expect(runFailureBadgeLabel("environment_prepare_failed")).toBe(
+ "Environment setup failed",
+ );
+ });
+
+ it("keeps the pre-MUL-1949 coarse values readable", () => {
+ expect(runFailureBadgeLabel("agent_error")).toBe("Agent error");
+ expect(runFailureBadgeLabel("manual")).toBe("Manual");
+ });
+
+ it("degrades to no badge for a reason newer than this build", () => {
+ // The row renders a bare status word instead. Unlike web, a compact badge
+ // has no room for the raw wire value, so silence is the fallback — but it
+ // must be a miss on THIS map, not a value the parser threw away upstream.
+ expect(runFailureBadgeLabel("some_future_reason")).toBeUndefined();
+ expect(runFailureBadgeLabel(undefined)).toBeUndefined();
+ expect(runFailureBadgeLabel("")).toBeUndefined();
+ });
+});
diff --git a/apps/mobile/lib/run-failure-badge.ts b/apps/mobile/lib/run-failure-badge.ts
new file mode 100644
index 0000000000..c15688d171
--- /dev/null
+++ b/apps/mobile/lib/run-failure-badge.ts
@@ -0,0 +1,57 @@
+/**
+ * Short badge copy for a run's `failure_reason`, shown inline on the agent-runs
+ * row next to the status word and a timestamp.
+ *
+ * Deliberately terser than `lib/failure-reason-label.ts`, which backs a
+ * full-width chat bubble; this one shares a single line.
+ *
+ * Keyed by the raw wire value, not a closed enum: `failure_reason` is an open
+ * string that grows as classifier rules land, and an installed build will meet
+ * reasons it predates. An unrecognised reason returns undefined so the row
+ * falls back to a bare status word — a compact badge is the one place where
+ * web's raw-wire-value fallback would overflow the row.
+ *
+ * Lives in lib/ rather than inside run-row.tsx so the lookup is covered by
+ * mobile's node-only vitest lane: the map spent from MUL-5370 to #7913 holding
+ * copy that no run could reach, because AgentTaskSchema was erasing every
+ * refined reason before the row ever looked one up. A map no test can see is
+ * how that goes unnoticed.
+ */
+const FAILURE_REASON_BADGE: Record<string, string> = {
+ queued_expired: "Queue expired",
+ runtime_offline: "Runtime offline",
+ runtime_recovery: "Runtime recovery",
+ timeout: "Timeout",
+ iteration_limit: "Iteration limit",
+ agent_blocked: "Needs input",
+ api_invalid_request: "Request rejected",
+ skill_bundle_unavailable: "Skill download failed",
+ runtime_cli_timeout: "Runtime CLI timeout",
+ environment_prepare_failed: "Environment setup failed",
+
+ "agent_error.provider_auth_or_access": "Auth failed",
+ "agent_error.provider_quota_limit": "Quota exhausted",
+ "agent_error.provider_capacity_or_rate_limit": "Rate limited",
+ "agent_error.provider_server_error": "Provider error",
+ "agent_error.provider_network": "Network error",
+ "agent_error.process_failure": "Process crashed",
+ "agent_error.empty_or_unparseable_output": "No usable output",
+ "agent_error.agent_timeout": "Agent timeout",
+ "agent_error.context_overflow": "Context overflow",
+ "agent_error.missing_config": "Config missing",
+ "agent_error.model_not_found_or_unavailable": "Model unavailable",
+ "agent_error.runtime_version_unsupported": "CLI unsupported",
+ "agent_error.runtime_missing_executable": "CLI not installed",
+ "agent_error.unknown": "Agent error",
+
+ agent_error: "Agent error",
+ codex_semantic_inactivity: "Codex inactivity",
+ manual: "Manual",
+};
+
+export function runFailureBadgeLabel(
+ reason: string | null | undefined,
+): string | undefined {
+ if (!reason) return undefined;
+ return FAILURE_REASON_BADGE[reason];
+}
diff --git a/packages/core/dashboard/failure-class.test.ts b/packages/core/dashboard/failure-class.test.ts
index 1b47720b9c..0bf026760f 100644
--- a/packages/core/dashboard/failure-class.test.ts
+++ b/packages/core/dashboard/failure-class.test.ts
@@ -18,6 +18,11 @@ describe("failureClassOf", () => {
// MUL-5370: the run never reached the model provider, so this belongs
// with the substrate failures an operator fixes by checking the daemon.
expect(failureClassOf("skill_bundle_unavailable")).toBe("runtime");
+ // #7913: a host filesystem failure during preparation. It has to leave
+ // the agent class, not just get a nicer name — while it lived under
+ // agent_error.* every operator read of "agent problems" counted a full
+ // disk as one.
+ expect(failureClassOf("environment_prepare_failed")).toBe("runtime");
expect(failureClassOf("agent_error.process_failure")).toBe("agent");
// MUL-5722: the daemon and the provider are both healthy — codex could
// not hand its own stored thread back — so this reads as an agent-side
diff --git a/packages/core/dashboard/failure-class.ts b/packages/core/dashboard/failure-class.ts
index a374442447..5d4b661738 100644
--- a/packages/core/dashboard/failure-class.ts
+++ b/packages/core/dashboard/failure-class.ts
@@ -1,6 +1,6 @@
// Display grouping for `agent_task_queue.failure_reason`.
//
-// The backend taxonomy (server/pkg/taskfailure) has 22 reasons, which is far
+// The backend taxonomy (server/pkg/taskfailure) has 26 reasons, which is far
// too many series for a stacked chart or a scannable breakdown list. These
// seven classes are the granularity an operator actually acts on: an auth
// spike means "go re-auth", a rate-limit spike means "back off or raise the
@@ -23,7 +23,7 @@ export const FAILURE_CLASSES = [
export type FailureClass = (typeof FAILURE_CLASSES)[number];
-// Reason → class. Keys are the wire values written by the backend: the 22
+// Reason → class. Keys are the wire values written by the backend: the 26
// canonical `taskfailure.Reason` strings, the `"unclassified"` sentinel the
// failure rollups substitute for a failed row with an empty column, and the
// pre-MUL-1949 coarse values that still sit in historical rows.
@@ -70,6 +70,12 @@ const REASON_CLASS: Record<string, FailureClass> = {
// fix is on the host running the daemon — a faster CLI or a raised timeout —
// not with the model provider, which was never contacted.
runtime_cli_timeout: "runtime",
+ // The daemon could not build or re-open the task's execution environment on
+ // its own host — its workspace directory, or the local runtime config
+ // written into it. The reason this class exists at all: these rows used to
+ // arrive as agent_error.* and inflated the agent class with problems only a
+ // machine owner can fix (#7913).
+ environment_prepare_failed: "runtime",
// The agent process itself produced the failure.
"agent_error.process_failure": "agent",
diff --git a/packages/views/agents/components/tabs/task-failure.ts b/packages/views/agents/components/tabs/task-failure.ts
index dac7daee5b..3e174ca62c 100644
--- a/packages/views/agents/components/tabs/task-failure.ts
+++ b/packages/views/agents/components/tabs/task-failure.ts
@@ -18,6 +18,7 @@ export const FAILURE_REASON_I18N_KEYS = {
api_invalid_request: "api_invalid_request",
skill_bundle_unavailable: "skill_bundle_unavailable",
runtime_cli_timeout: "runtime_cli_timeout",
+ environment_prepare_failed: "environment_prepare_failed",
invalid_task_identity: "invalid_task_identity",
// Agent process side — provider.
diff --git a/packages/views/chat/components/chat-message-list.test.tsx b/packages/views/chat/components/chat-message-list.test.tsx
index cbada14519..3e832f5227 100644
--- a/packages/views/chat/components/chat-message-list.test.tsx
+++ b/packages/views/chat/components/chat-message-list.test.tsx
@@ -457,6 +457,20 @@ describe("ChatMessageList failure copy (MUL-5370 regression)", () => {
expect(screen.queryByText(FALLBACK)).not.toBeInTheDocument();
});
+ it("renders dedicated copy for a failed environment preparation", async () => {
+ // #7913. Without an entry of its own this reason has no agent_error
+ // family to degrade into, so it would land on the generic fallback —
+ // and the one thing the reader needs to know is that the problem is on
+ // the machine running the agent, which the fallback cannot say.
+ renderFailure("environment_prepare_failed");
+ expect(
+ await screen.findByText(
+ enChat.message_list.failure.environment_prepare_failed,
+ ),
+ ).toBeInTheDocument();
+ expect(screen.queryByText(FALLBACK)).not.toBeInTheDocument();
+ });
+
it("renders dedicated copy for a refined reason the map names", async () => {
renderFailure("agent_error.provider_network");
expect(
diff --git a/packages/views/chat/components/chat-message-list.tsx b/packages/views/chat/components/chat-message-list.tsx
index c5d5e9fdc7..5677ecbdd7 100644
--- a/packages/views/chat/components/chat-message-list.tsx
+++ b/packages/views/chat/components/chat-message-list.tsx
@@ -983,6 +983,7 @@ function FailureBubble({
cancelled: t(($) => $.message_list.failure.manual),
skill_bundle_unavailable: t(($) => $.message_list.failure.skill_bundle_unavailable),
runtime_cli_timeout: t(($) => $.message_list.failure.runtime_cli_timeout),
+ environment_prepare_failed: t(($) => $.message_list.failure.environment_prepare_failed),
"agent_error.provider_network": t(($) => $.message_list.failure.provider_network),
"agent_error.provider_auth_or_access": t(($) => $.message_list.failure.provider_auth_or_access),
"agent_error.provider_quota_limit": t(($) => $.message_list.failure.provider_quota_limit),
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index 7872f933c1..9b5db6ccf2 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -916,6 +916,7 @@
"api_invalid_request": "Rejected by the model API",
"skill_bundle_unavailable": "Couldn't download the agent's skills",
"runtime_cli_timeout": "Local runtime CLI timed out",
+ "environment_prepare_failed": "Couldn't prepare the execution environment",
"invalid_task_identity": "Task identity mismatch",
"agent_error_provider_auth_or_access": "Provider auth failed",
"agent_error_provider_quota_limit": "Provider quota exhausted",
diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.json
index 6d1a0c4df4..dde89c91c1 100644
--- a/packages/views/locales/en/chat.json
+++ b/packages/views/locales/en/chat.json
@@ -62,6 +62,7 @@
"manual": "This reply was cancelled.",
"skill_bundle_unavailable": "The agent's skills couldn't be downloaded, so it never got started. This is usually a connection problem — please try again.",
"runtime_cli_timeout": "The local OpenClaw CLI didn't answer in time, so this run never started. It's a local startup timeout, not a network problem — retrying won't help until the CLI gets faster or the timeout is raised (MULTICA_OPENCLAW_CLI_TIMEOUT).",
+ "environment_prepare_failed": "The machine running the agent couldn't set this run up, so it never started. The error below says what failed there — often disk space, a permission, a folder still in use, or a local config that couldn't be read. It isn't the agent or the model provider.",
"provider_network": "The connection to the model provider dropped before the reply finished. Check your network and try again.",
"provider_auth_or_access": "The agent's model account isn't signed in any more. Sign in again, then retry.",
"provider_quota_limit": "The agent's model account has run out of credit. Top it up or switch accounts, then retry.",
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index 64d1abcf3d..d1f36c8e50 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -790,6 +790,7 @@
"api_invalid_request": "モデル API に拒否されました",
"skill_bundle_unavailable": "エージェントのスキルをダウンロードできませんでした",
"runtime_cli_timeout": "ローカルランタイム CLI がタイムアウトしました",
+ "environment_prepare_failed": "実行環境を準備できませんでした",
"invalid_task_identity": "作業のエージェント情報が一致しません",
"agent_error_provider_auth_or_access": "プロバイダーの認証に失敗しました",
"agent_error_provider_quota_limit": "プロバイダーのクォータを使い切りました",
diff --git a/packages/views/locales/ja/chat.json b/packages/views/locales/ja/chat.json
index 92bf90bcd1..59a338dfa2 100644
--- a/packages/views/locales/ja/chat.json
+++ b/packages/views/locales/ja/chat.json
@@ -60,6 +60,7 @@
"manual": "この返信はキャンセルされました。",
"skill_bundle_unavailable": "エージェントの skill をダウンロードできず、返信を開始できませんでした。多くの場合はネットワークの問題です。もう一度お試しください。",
"runtime_cli_timeout": "ローカルの OpenClaw CLI が時間内に応答せず、この実行は開始されませんでした。ネットワークではなくローカルの起動タイムアウトです。CLI が速くなるか、タイムアウト(MULTICA_OPENCLAW_CLI_TIMEOUT)を延ばすまで再試行しても成功しません。",
+ "environment_prepare_failed": "エージェントを実行しているマシンでこの実行を準備できず、開始されませんでした。何が失敗したかは下のエラーに出ています——ディスクの空き容量、権限、使用中のフォルダー、読み取れないローカル設定などが多いです。エージェントやモデルプロバイダーの問題ではありません。",
"provider_network": "モデルサービスとの接続が切断され、返信を完了できませんでした。ネットワークを確認してから再度お試しください。",
"provider_auth_or_access": "エージェントのモデルアカウントのログインが無効になりました。再度ログインしてからお試しください。",
"provider_quota_limit": "エージェントのモデルアカウントの残高が不足しています。チャージするかアカウントを切り替えてからお試しください。",
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index 85ee26185a..a5f6770c98 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -798,6 +798,7 @@
"api_invalid_request": "모델 API에서 요청을 거부함",
"skill_bundle_unavailable": "에이전트 스킬을 다운로드할 수 없음",
"runtime_cli_timeout": "로컬 런타임 CLI 시간 초과",
+ "environment_prepare_failed": "실행 환경을 준비하지 못함",
"invalid_task_identity": "작업 ID 정보가 일치하지 않음",
"agent_error_provider_auth_or_access": "공급자 인증 실패",
"agent_error_provider_quota_limit": "공급자 할당량 소진",
diff --git a/packages/views/locales/ko/chat.json b/packages/views/locales/ko/chat.json
index 211aff846b..804773054e 100644
--- a/packages/views/locales/ko/chat.json
+++ b/packages/views/locales/ko/chat.json
@@ -60,6 +60,7 @@
"manual": "이 답변이 취소되었습니다.",
"skill_bundle_unavailable": "에이전트의 skill을 내려받지 못해 답변을 시작하지 못했습니다. 대개 네트워크 연결 문제입니다. 다시 시도해 주세요.",
"runtime_cli_timeout": "로컬 OpenClaw CLI가 제한 시간 안에 응답하지 않아 이번 실행이 시작되지 못했습니다. 네트워크 문제가 아니라 로컬 실행 지연입니다. CLI가 빨라지거나 제한 시간(MULTICA_OPENCLAW_CLI_TIMEOUT)을 늘리기 전에는 다시 시도해도 실패합니다.",
+ "environment_prepare_failed": "에이전트를 실행하는 머신에서 이번 실행을 준비하지 못해 시작되지 못했습니다. 무엇이 실패했는지는 아래 오류에 나옵니다 — 디스크 공간, 권한, 사용 중인 폴더, 읽을 수 없는 로컬 설정 등이 흔합니다. 에이전트나 모델 제공자의 문제가 아닙니다.",
"provider_network": "모델 서비스와의 연결이 끊겨 답변을 완료하지 못했습니다. 네트워크를 확인한 뒤 다시 시도해 주세요.",
"provider_auth_or_access": "에이전트의 모델 계정 로그인이 만료되었습니다. 다시 로그인한 뒤 시도해 주세요.",
"provider_quota_limit": "에이전트의 모델 계정 잔액이 부족합니다. 충전하거나 계정을 변경한 뒤 시도해 주세요.",
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index c589034626..9da3aa608a 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -897,6 +897,7 @@
"api_invalid_request": "模型 API 拒绝了请求",
"skill_bundle_unavailable": "无法下载智能体的 skill",
"runtime_cli_timeout": "本地运行时 CLI 超时",
+ "environment_prepare_failed": "无法准备执行环境",
"invalid_task_identity": "task 身份不匹配",
"agent_error_provider_auth_or_access": "提供商认证失败",
"agent_error_provider_quota_limit": "提供商配额已用尽",
diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.json
index 5bc64aea86..7147a51ea6 100644
--- a/packages/views/locales/zh-Hans/chat.json
+++ b/packages/views/locales/zh-Hans/chat.json
@@ -60,6 +60,7 @@
"manual": "这次回复已取消。",
"skill_bundle_unavailable": "没能下载到智能体的 skill,这次回复没有启动。通常是网络连接问题,请重试。",
"runtime_cli_timeout": "本机 OpenClaw CLI 没能在超时时间内响应,这次运行没有启动。这是本地启动超时,不是网络问题——除非 CLI 变快或调大超时(MULTICA_OPENCLAW_CLI_TIMEOUT),否则重试也不会成功。",
+ "environment_prepare_failed": "运行智能体的那台机器没能把这次运行准备好,任务没有启动。下方的原始错误会说明是哪一步失败——常见的是磁盘空间、权限、目录仍被占用,或本地配置读不出来。与智能体和模型厂商无关。",
"provider_network": "与模型服务的连接中断,回复没能完成。检查网络后重试。",
"provider_auth_or_access": "智能体的模型账号登录已失效。重新登录后再试。",
"provider_quota_limit": "智能体的模型账号额度已用尽。充值或更换账号后再试。",
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 2acf6db5ec..992e81ed41 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -5553,6 +5553,32 @@ type worktreePreservedError struct{ err error }
func (e *worktreePreservedError) Error() string { return e.err.Error() }
func (e *worktreePreservedError) Unwrap() error { return e.err }
+// environmentSetupError marks a failure to build or re-open the task's
+// execution environment: everything execenv.Prepare / execenv.Reuse does on
+// this host before the agent process exists — the workspace directory and its
+// overlay homes, plus the per-provider local config written or validated
+// inside it. Its causes are local, and not only filesystem ones: a full
+// volume, a read-only or permission-denied workspaces root, a directory
+// another process still holds open, an I/O error on the disk underneath, or a
+// local runtime config the daemon refuses to boot past.
+//
+// It carries the wrapped error's message unchanged and exists purely so
+// taskRunFailureReason can recognise the phase structurally. Without it the
+// OS error text falls through to taskfailure.Classify, a classifier written
+// to read agent and provider output, and lands in agent_error.* — today the
+// catchall, historically provider_server_error, which pointed one bug report
+// at an LLM vendor for hours (#7913). The task never reached an agent, so no
+// reason in that namespace can be right.
+type environmentSetupError struct{ err error }
+
+func (e *environmentSetupError) Error() string { return e.err.Error() }
+func (e *environmentSetupError) Unwrap() error { return e.err }
+
+// asEnvironmentSetupFailure tags err as an execution-environment setup
+// failure. The message is untouched, so the wrapper is invisible to everything
+// except taskRunFailureReason.
+func asEnvironmentSetupFailure(err error) error { return &environmentSetupError{err: err} }
+
func taskRunFailureReason(err error) string {
if errors.Is(err, errInvalidTaskIdentity) {
return taskfailure.ReasonInvalidTaskIdentity.String()
@@ -5577,6 +5603,18 @@ func taskRunFailureReason(err error) string {
if errors.Is(err, execenv.ErrOpenclawCLITimeout) {
return taskfailure.ReasonRuntimeCLITimeout.String()
}
+ // Everything else that failed while building or re-opening the execution
+ // environment. Last of the structural branches: the four sentinels above
+ // each name a cause the daemon already recognises on its own (task
+ // identity, the prepare budget, skill downloads, the local runtime CLI)
+ // and stay the better label. What is left is the rest of preparation on
+ // this host — filesystem faults, and the per-provider local config
+ // Prepare writes or validates — whose text Classify can only read as
+ // agent output (#7913).
+ var envSetupErr *environmentSetupError
+ if errors.As(err, &envSetupErr) {
+ return taskfailure.ReasonEnvironmentPrepareFailed.String()
+ }
return taskfailure.Classify(err.Error()).String()
}
@@ -7457,7 +7495,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
Task: taskCtx,
})
if err != nil {
- return TaskResult{}, fmt.Errorf("reuse execution environment: %w", err)
+ return TaskResult{}, asEnvironmentSetupFailure(fmt.Errorf("reuse execution environment: %w", err))
}
// Reuse resolves priorWorkDir by name, so confirm what it actually
// opened is still the directory we hold the lock on. An fd cannot cross
@@ -7571,7 +7609,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
env, err = d.prepareExecutionEnvironment(prepareCtx, prepParams)
release()
if err != nil {
- return TaskResult{}, fmt.Errorf("prepare execution environment: %w", err)
+ return TaskResult{}, asEnvironmentSetupFailure(fmt.Errorf("prepare execution environment: %w", err))
}
} else {
if localAssignment != nil {
@@ -7579,7 +7617,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
}
env, err = d.prepareExecutionEnvironment(prepareCtx, prepParams)
if err != nil {
- return TaskResult{}, fmt.Errorf("prepare execution environment: %w", err)
+ return TaskResult{}, asEnvironmentSetupFailure(fmt.Errorf("prepare execution environment: %w", err))
}
}
}
diff --git a/server/internal/daemon/environment_prepare_failure_test.go b/server/internal/daemon/environment_prepare_failure_test.go
new file mode 100644
index 0000000000..b910dbf47e
--- /dev/null
+++ b/server/internal/daemon/environment_prepare_failure_test.go
@@ -0,0 +1,127 @@
+package daemon
+
+import (
+ "errors"
+ "fmt"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/daemon/execenv"
+ "github.com/multica-ai/multica/server/pkg/taskfailure"
+)
+
+// TestTaskRunFailureReasonLabelsEnvironmentSetup is the daemon half of #7913.
+// The first four messages are the real ones: the Windows lock from the
+// original report, and the three shapes main produces today. The last two are
+// the other half of what preparation does — the per-provider local config it
+// writes and validates. Every one of them is the machine running the agent
+// talking, and every one of them used to be handed to taskfailure.Classify —
+// a classifier that only knows how to read agent and provider output — so
+// they landed in agent_error.* and made a host problem look like a
+// model-provider fault on the board.
+func TestTaskRunFailureReasonLabelsEnvironmentSetup(t *testing.T) {
+ cases := map[string]error{
+ "windows lock": asEnvironmentSetupFailure(fmt.Errorf("prepare execution environment: %w",
+ errors.New(`execenv: remove existing env: unlinkat C:\Users\u\multica_workspaces_p\ws\prefix\workdir: `+
+ "The process cannot access the file because it is being used by another process"))),
+ "disk full": asEnvironmentSetupFailure(fmt.Errorf("prepare execution environment: %w",
+ errors.New("execenv: mkdir /home/u/multica_workspaces/ws: no space left on device"))),
+ "permission denied": asEnvironmentSetupFailure(fmt.Errorf("prepare execution environment: %w",
+ errors.New("execenv: open ownership manifest: permission denied"))),
+ "reuse io error": asEnvironmentSetupFailure(fmt.Errorf("reuse execution environment: %w",
+ errors.New("stat workdir: input/output error"))),
+ // Not every preparation failure is the filesystem. Prepare also writes
+ // and validates the per-provider local config — Codex home, the Hermes
+ // overlay, Cursor MCP, and an OpenClaw config it deliberately fails
+ // closed on when the CLI cannot read it (execenv.Prepare). Those are
+ // the same verdict: the machine running the agent could not set the run
+ // up. Losing them to Classify would put a broken local config back in
+ // the provider's namespace, and the user-facing copy must stay wide
+ // enough to send the reader to the raw error rather than only to df.
+ "malformed openclaw config": asEnvironmentSetupFailure(fmt.Errorf("prepare execution environment: %w",
+ errors.New("execenv: prepare openclaw config: read openclaw agents.list: exit status 1"))),
+ "codex home": asEnvironmentSetupFailure(fmt.Errorf("prepare execution environment: %w",
+ errors.New("execenv: prepare codex-home: seed config.toml: invalid TOML at line 3"))),
+ }
+
+ want := taskfailure.ReasonEnvironmentPrepareFailed.String()
+ for name, err := range cases {
+ t.Run(name, func(t *testing.T) {
+ if got := taskRunFailureReason(err); got != want {
+ t.Errorf("taskRunFailureReason = %q, want %q", got, want)
+ }
+ if taskfailure.Reason(taskRunFailureReason(err)).IsAgentError() {
+ t.Error("an environment that never launched an agent must not be filed under agent_error.*")
+ }
+ })
+ }
+}
+
+// TestEnvironmentSetupFailurePreservesMessage pins the tag as invisible on the
+// wire. The wrapper exists to be read by taskRunFailureReason, not by a person:
+// the text is what gets persisted into agent_task_queue.error and shown under
+// the chat bubble, and it is also the witness NormalizeDaemonReason keys on for
+// daemons too old to send the reason. Prefixing it would break both.
+func TestEnvironmentSetupFailurePreservesMessage(t *testing.T) {
+ inner := fmt.Errorf("prepare execution environment: %w", errors.New("execenv: mkdir: no space left on device"))
+ tagged := asEnvironmentSetupFailure(inner)
+
+ if tagged.Error() != inner.Error() {
+ t.Errorf("tagged message = %q, want %q unchanged", tagged.Error(), inner.Error())
+ }
+ if !errors.Is(tagged, inner) {
+ t.Error("the tag must unwrap to the error it carries")
+ }
+ if got := taskfailure.NormalizeDaemonReason(taskfailure.Classify(tagged.Error()).String(), tagged.Error()); got != taskfailure.ReasonEnvironmentPrepareFailed {
+ t.Errorf("server-side normalization of the same text = %q, want %q", got, taskfailure.ReasonEnvironmentPrepareFailed)
+ }
+}
+
+// TestTaskRunFailureReasonPrefersSpecificPreparationSentinels guards the branch
+// order. Preparation is one phase with several known causes, and three of them
+// already have their own reason. The generic bucket is what is left over, so it
+// has to be checked last — a run that died on the OpenClaw CLI deadline still
+// needs the copy naming MULTICA_OPENCLAW_CLI_TIMEOUT, and one that ran out of
+// skill downloads still needs to be retryable.
+func TestTaskRunFailureReasonPrefersSpecificPreparationSentinels(t *testing.T) {
+ cases := map[string]struct {
+ err error
+ want string
+ }{
+ "openclaw cli timeout": {
+ err: asEnvironmentSetupFailure(fmt.Errorf(
+ "prepare execution environment: execenv: prepare openclaw config: locate openclaw active config: %w",
+ fmt.Errorf("openclaw config file: context deadline exceeded (process: signal: killed): %w", execenv.ErrOpenclawCLITimeout))),
+ want: taskfailure.ReasonRuntimeCLITimeout.String(),
+ },
+ "skill bundle unavailable": {
+ err: asEnvironmentSetupFailure(fmt.Errorf("prepare execution environment: %w",
+ fmt.Errorf("%w: download skill: connection refused", errSkillBundleUnavailable))),
+ want: taskfailure.ReasonSkillBundleUnavailable.String(),
+ },
+ "prepare budget exhausted": {
+ err: fmt.Errorf("%w after 5m0s", errTaskPrepareTimeout),
+ want: taskfailure.ReasonTimeout.String(),
+ },
+ }
+
+ for name, tc := range cases {
+ t.Run(name, func(t *testing.T) {
+ if got := taskRunFailureReason(tc.err); got != tc.want {
+ t.Errorf("taskRunFailureReason = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+// TestTaskRunFailureReasonLeavesAgentErrorsAlone pins the other side of the
+// boundary: only errors the daemon itself tagged move out of the agent
+// namespace. An untagged failure is one the agent process produced, and its
+// text remains the best evidence available.
+func TestTaskRunFailureReasonLeavesAgentErrorsAlone(t *testing.T) {
+ err := errors.New("API Error: 429 rate limit exceeded")
+
+ want := taskfailure.ReasonAgentProviderCapacityOrRateLimit.String()
+ if got := taskRunFailureReason(err); got != want {
+ t.Errorf("taskRunFailureReason = %q, want %q", got, want)
+ }
+}
diff --git a/server/internal/service/task_complete_race_test.go b/server/internal/service/task_complete_race_test.go
index 91879e9577..66e4e9e905 100644
--- a/server/internal/service/task_complete_race_test.go
+++ b/server/internal/service/task_complete_race_test.go
@@ -305,6 +305,27 @@ func TestRuntimeCLITimeoutIsNotAutoRetried(t *testing.T) {
}
}
+// TestEnvironmentPrepareFailureIsNotAutoRetried pins the retry posture for
+// #7913. The reason moved out of agent_error.* purely so the label is honest —
+// it must not quietly buy the failure a retry it never had. Its causes are the
+// host's: a full volume, a denied permission, a directory another process
+// holds. None of them changes because Multica asked a second time, and
+// preparation already waits out the one transient case it knows about (a prior
+// run still holding the directory) before it fails.
+//
+// Resume stays safe: the agent process never started, so the session the user's
+// next message resumes is untouched.
+func TestEnvironmentPrepareFailureIsNotAutoRetried(t *testing.T) {
+ const reason = "environment_prepare_failed"
+
+ if retryableReasons[reason] {
+ t.Errorf("retryableReasons[%q] = true, want false: the disk or permission problem is the same on the next attempt", reason)
+ }
+ if resumeUnsafeFailureReason(reason) {
+ t.Errorf("resumeUnsafeFailureReason(%q) = true, want false: the agent never started", reason)
+ }
+}
+
// TestOpencodeStreamEndedFailureRetries walks the full chain for #6522: the
// error string pkg/agent/opencode.go's terminal-signal guard produces, through
// taskfailure.Classify, into the retry gate.
diff --git a/server/pkg/taskfailure/classify.go b/server/pkg/taskfailure/classify.go
index 10a91404b8..adaee013d9 100644
--- a/server/pkg/taskfailure/classify.go
+++ b/server/pkg/taskfailure/classify.go
@@ -406,6 +406,16 @@ var legacyOpenclawCLITimeoutReasons = map[string]bool{
"agent_error": true,
}
+// legacyEnvironmentPrepareWitnesses are the two wrappers the daemon puts on a
+// failed execenv.Prepare / execenv.Reuse. Each opens the error at character
+// zero, and no other code path emits them, so the prefix alone establishes
+// that the run died setting up its workspace directory and never reached an
+// agent.
+var legacyEnvironmentPrepareWitnesses = []string{
+ "prepare execution environment:",
+ "reuse execution environment:",
+}
+
func isPiProviderNetworkError(lower string) bool {
for _, message := range []string{"connection error.", "request timed out."} {
if lower == message ||
@@ -497,6 +507,19 @@ func NormalizeDaemonReason(reason, rawError string) Reason {
containsAll(strings.ToLower(rawError), legacyOpenclawCLITimeoutWitnesses...) {
return ReasonRuntimeCLITimeout
}
+ // #7913: the same mixed-version gap on environment preparation. A daemon
+ // predating the structural tag classifies the host's own filesystem error
+ // from its text and reports some agent_error.* value — the catchall today,
+ // provider_server_error on the report that opened the issue. Every one of
+ // them is wrong by construction: the prefix proves the task died before an
+ // agent process existed, so the whole agent_error.* namespace is upgraded
+ // here rather than an enumerated subset of it.
+ //
+ // Last, so the openclaw rule above keeps its own preparation failure: that
+ // one names a specific cause inside this same phase and says strictly more.
+ if isAgentSideReason(reason) && hasAnyPrefix(lowerError, legacyEnvironmentPrepareWitnesses...) {
+ return ReasonEnvironmentPrepareFailed
+ }
return Reason(reason)
}
@@ -513,6 +536,28 @@ func containsAll(s string, subs ...string) bool {
return len(subs) > 0
}
+// hasAnyPrefix reports whether s starts with any of the supplied prefixes.
+// Used where the witness is the wrapper opening an error rather than a phrase
+// somewhere inside it, which is what makes it unambiguous. Caller
+// pre-lowercases s, same contract as containsAny.
+func hasAnyPrefix(s string, prefixes ...string) bool {
+ for _, prefix := range prefixes {
+ if strings.HasPrefix(s, prefix) {
+ return true
+ }
+ }
+ return false
+}
+
+// isAgentSideReason reports whether a wire value blames the agent process —
+// any refined agent_error.* sub-reason, or the pre-MUL-1949 coarse bucket they
+// were split out of. Used by normalization rules whose witness proves the run
+// never reached an agent, so that every such label is known to be wrong
+// without enumerating them.
+func isAgentSideReason(reason string) bool {
+ return Reason(reason).IsAgentError() || reason == "agent_error"
+}
+
// containsAny reports whether s contains any of the supplied substrings.
// Caller is responsible for lowercasing s ahead of time so the helper
// stays cheap on the hot path — pre-lowercasing once is faster than
diff --git a/server/pkg/taskfailure/environment_prepare_test.go b/server/pkg/taskfailure/environment_prepare_test.go
new file mode 100644
index 0000000000..0630e9cc1e
--- /dev/null
+++ b/server/pkg/taskfailure/environment_prepare_test.go
@@ -0,0 +1,127 @@
+package taskfailure
+
+import "testing"
+
+// TestNormalizeDaemonReasonUpgradesEnvironmentPrepare covers the mixed-version
+// window for #7913. Installed daemons update on their own cadence, so until a
+// host carries the structural tag it keeps classifying its own setup errors
+// with a classifier built for agent output — and reports a non-empty
+// agent_error.* value, which FailTask's "classify only when empty" branch
+// deliberately leaves alone. Recognising the wrapper the daemon has always
+// written moves those rows out of the agent namespace the moment the server
+// deploys.
+//
+// The witnesses are the real messages from the report and from main: the
+// Windows lock that opened the issue, a full volume, a denied permission, a
+// reuse that could not stat the prior workdir, and a local runtime config the
+// daemon refused to boot past.
+func TestNormalizeDaemonReasonUpgradesEnvironmentPrepare(t *testing.T) {
+ t.Parallel()
+
+ rawErrors := map[string]string{
+ "windows lock": "prepare execution environment: execenv: remove existing env: unlinkat " +
+ `C:\Users\u\multica_workspaces_p\ws\prefix\workdir: ` +
+ "The process cannot access the file because it is being used by another process",
+ "disk full": "prepare execution environment: execenv: mkdir /home/u/multica_workspaces/ws: no space left on device",
+ "permission denied": "prepare execution environment: execenv: open ownership manifest: permission denied",
+ "reuse io error": "reuse execution environment: stat workdir: input/output error",
+ // Preparation is not only filesystem work: it also writes and validates
+ // the per-provider local config. "exit status 1" is exactly the text
+ // Classify reads as agent_error.process_failure, and a config the
+ // OpenClaw CLI cannot parse is not a process the agent ran.
+ "malformed openclaw config": "prepare execution environment: execenv: prepare openclaw config: " +
+ "read openclaw agents.list: exit status 1",
+ }
+
+ // Every agent-side label an older daemon can produce here is wrong for the
+ // same reason — the run died before an agent process existed — so the whole
+ // namespace is upgraded, not an enumerated subset. provider_server_error is
+ // what the original report saw; unknown is where main lands today.
+ legacyReasons := []string{
+ string(ReasonAgentUnknown),
+ string(ReasonAgentProviderServerError),
+ string(ReasonAgentProviderNetwork),
+ string(ReasonAgentProcessFailure),
+ "agent_error",
+ }
+
+ for name, rawError := range rawErrors {
+ for _, legacy := range legacyReasons {
+ if got := NormalizeDaemonReason(legacy, rawError); got != ReasonEnvironmentPrepareFailed {
+ t.Errorf("%s: NormalizeDaemonReason(%q) = %q, want %q", name, legacy, got, ReasonEnvironmentPrepareFailed)
+ }
+ }
+ // A current daemon already reports the precise reason; normalization
+ // must leave it alone.
+ if got := NormalizeDaemonReason(string(ReasonEnvironmentPrepareFailed), rawError); got != ReasonEnvironmentPrepareFailed {
+ t.Errorf("%s: NormalizeDaemonReason(environment_prepare_failed) = %q, want it preserved", name, got)
+ }
+ }
+}
+
+// TestNormalizeDaemonReasonEnvironmentPrepareStaysNarrow pins the three ways
+// this rule must NOT fire. Each protects something the rule would otherwise
+// take away: a finer label for the same phase, a platform-side reason that was
+// never a misattribution, and an agent failure whose text merely quotes the
+// wrapper.
+func TestNormalizeDaemonReasonEnvironmentPrepareStaysNarrow(t *testing.T) {
+ t.Parallel()
+
+ cases := map[string]struct {
+ reason string
+ rawError string
+ want Reason
+ }{
+ // The OpenClaw config-discovery stall is a preparation failure too, and
+ // its own rule runs first because it names the specific cause. Losing
+ // that to the generic bucket would drop the copy that tells the user to
+ // raise MULTICA_OPENCLAW_CLI_TIMEOUT.
+ "openclaw cli timeout keeps its own reason": {
+ reason: string(ReasonAgentProviderNetwork),
+ rawError: "prepare execution environment: execenv: prepare openclaw config: " +
+ "locate openclaw active config: openclaw config file: context deadline exceeded " +
+ "(process: signal: killed)",
+ want: ReasonRuntimeCLITimeout,
+ },
+ // A platform-side reason was never a misattribution: whatever wrote it
+ // knew more than the wrapper does. The prepare budget running out is
+ // classified structurally by the daemon and stays a timeout.
+ "platform-side reason is untouched": {
+ reason: string(ReasonTimeout),
+ rawError: "prepare execution environment: execenv: mkdir: no space left on device",
+ want: ReasonTimeout,
+ },
+ // The witness has to OPEN the error. An agent that printed the phrase
+ // mid-run — a log tail, a quoted earlier failure — did reach an agent,
+ // and its own classification is the true one.
+ "prefix only, not a mention anywhere": {
+ reason: string(ReasonAgentProcessFailure),
+ rawError: "agent crashed while reading logs: prepare execution environment: execenv: mkdir failed",
+ want: ReasonAgentProcessFailure,
+ },
+ }
+
+ for name, tc := range cases {
+ if got := NormalizeDaemonReason(tc.reason, tc.rawError); got != tc.want {
+ t.Errorf("%s: NormalizeDaemonReason = %q, want %q", name, got, tc.want)
+ }
+ }
+}
+
+// TestClassifyStillReadsPrepareErrorsAsAgentErrors documents what the text
+// classifier does with these messages on its own, and why the fix could not be
+// a new Classify rule. Classify is handed agent and provider output; a host
+// that could not set the run up is neither, and no bucket it owns is correct. The
+// classification has to happen upstream — structurally in the daemon, or from
+// the wrapper prefix at the normalization boundary.
+func TestClassifyStillReadsPrepareErrorsAsAgentErrors(t *testing.T) {
+ t.Parallel()
+
+ const rawError = "prepare execution environment: execenv: mkdir /home/u/multica_workspaces/ws: no space left on device"
+ if got := Classify(rawError); !got.IsAgentError() {
+ t.Fatalf("Classify(prepare error) = %q; the premise of this fix is that Classify cannot label these", got)
+ }
+ if got := NormalizeDaemonReason(Classify(rawError).String(), rawError); got != ReasonEnvironmentPrepareFailed {
+ t.Errorf("NormalizeDaemonReason(Classify(...)) = %q, want %q — the empty-reason path must land on the same reason", got, ReasonEnvironmentPrepareFailed)
+ }
+}
diff --git a/server/pkg/taskfailure/failure.go b/server/pkg/taskfailure/failure.go
index e24acc71c6..56d59a8e0d 100644
--- a/server/pkg/taskfailure/failure.go
+++ b/server/pkg/taskfailure/failure.go
@@ -26,7 +26,8 @@
// queued_expired, runtime_offline, runtime_reconnect_timeout,
// runtime_recovery, timeout, iteration_limit, agent_blocked,
// api_invalid_request, skill_bundle_unavailable,
-// runtime_cli_timeout, invalid_task_identity
+// runtime_cli_timeout, environment_prepare_failed,
+// invalid_task_identity
//
// - 14 agent-side values (with `agent_error.` prefix) produced by
// Classify(rawError) when the agent process surfaced an error string.
@@ -131,6 +132,43 @@ const (
// taskRunFailureReason in daemon/daemon.go.
ReasonRuntimeCLITimeout Reason = "runtime_cli_timeout"
+ // ReasonEnvironmentPrepareFailed: the daemon could not build or re-open
+ // the task's execution environment on this host, so the agent process was
+ // never launched.
+ //
+ // That phase is everything execenv.Prepare / Reuse does before launch —
+ // the workspace directory and its overlay homes, AND the per-provider
+ // local config written or validated inside it (Codex home, Hermes
+ // overlay, Cursor MCP, OpenClaw config, which fails closed on a config
+ // the CLI cannot read). So the causes are wider than a disk fault: a full
+ // volume, a read-only or permission-denied workspaces root, a directory
+ // another process still holds open (Windows) and an I/O error all land
+ // here, and so does a malformed local runtime config. What they share is
+ // the machine — every one is fixed on the host running the daemon, and
+ // the raw error is what names which step failed.
+ //
+ // Copy that narrows this to "check your disk" therefore sends the user
+ // past half the real causes, which is the same defect in miniature that
+ // this reason exists to fix. Read the wording in the chat bundles and the
+ // docs failure-reason table as part of the contract.
+ //
+ // Platform-side, and that is the point (#7913). Before this reason
+ // existed the wrapped OS error went through Classify — a classifier
+ // written to read agent and provider output — and landed somewhere in
+ // agent_error.*: today the catchall, historically provider_server_error,
+ // which sent one report's diagnosis at an LLM vendor for hours. The task
+ // never reached an agent, so no value in that namespace can be correct,
+ // and any fleet health read grouping by the agent_error.* prefix
+ // over-reports agent problems by exactly these rows.
+ //
+ // Deliberately NOT retryable: a full disk or a denied permission
+ // reproduces identically on the next attempt, and preparation already
+ // waits out the one transient case it knows about (a prior run still
+ // holding the directory) before it fails. Written by
+ // taskRunFailureReason in daemon/daemon.go; resume-safe, because no
+ // session was touched.
+ ReasonEnvironmentPrepareFailed Reason = "environment_prepare_failed"
+
// ReasonInvalidTaskIdentity: the daemon refused a claimed task because
// the task row's authoritative agent_id was absent or disagreed with the
// nested agent payload. The agent process is never launched. This is
@@ -213,7 +251,7 @@ const (
ReasonAgentUnknown Reason = "agent_error.unknown"
)
-// allReasons is the canonical ordered list of the 25 reasons. Order is
+// allReasons is the canonical ordered list of the 26 reasons. Order is
// stable so callers (e.g. Prometheus collectors that pre-warm series via
// AllReasons) can build deterministic label sets across restarts.
//
@@ -234,6 +272,7 @@ var allReasons = []Reason{
ReasonAPIInvalidRequest,
ReasonSkillBundleUnavailable,
ReasonRuntimeCLITimeout,
+ ReasonEnvironmentPrepareFailed,
ReasonInvalidTaskIdentity,
// Agent process side: provider errors.
diff --git a/server/pkg/taskfailure/failure_test.go b/server/pkg/taskfailure/failure_test.go
index 2a5f0eed0c..1c2abade08 100644
--- a/server/pkg/taskfailure/failure_test.go
+++ b/server/pkg/taskfailure/failure_test.go
@@ -29,6 +29,7 @@ func TestReasonStringWireValues(t *testing.T) {
{ReasonAPIInvalidRequest, "api_invalid_request"},
{ReasonSkillBundleUnavailable, "skill_bundle_unavailable"},
{ReasonRuntimeCLITimeout, "runtime_cli_timeout"},
+ {ReasonEnvironmentPrepareFailed, "environment_prepare_failed"},
{ReasonInvalidTaskIdentity, "invalid_task_identity"},
// Agent-side.
{ReasonAgentProviderAuthOrAccess, "agent_error.provider_auth_or_access"},
@@ -47,7 +48,7 @@ func TestReasonStringWireValues(t *testing.T) {
{ReasonAgentUnknown, "agent_error.unknown"},
}
- if got, want := len(cases), 25; got != want {
+ if got, want := len(cases), 26; got != want {
t.Fatalf("constant count = %d, want %d (canonical taxonomy size)", got, want)
}
@@ -77,6 +78,7 @@ func TestIsAgentError(t *testing.T) {
ReasonAPIInvalidRequest,
ReasonSkillBundleUnavailable,
ReasonRuntimeCLITimeout,
+ ReasonEnvironmentPrepareFailed,
ReasonInvalidTaskIdentity,
}
for _, r := range platformSide {
@@ -118,8 +120,8 @@ func TestAllReasonsContents(t *testing.T) {
t.Parallel()
got := AllReasons()
- if len(got) != 25 {
- t.Fatalf("AllReasons() returned %d entries, want 25", len(got))
+ if len(got) != 26 {
+ t.Fatalf("AllReasons() returned %d entries, want 26", len(got))
}
seen := make(map[Reason]bool, len(got))
@@ -136,8 +138,8 @@ func TestAllReasonsContents(t *testing.T) {
}
}
- if platformCount != 11 {
- t.Errorf("AllReasons(): platform-side count = %d, want 11", platformCount)
+ if platformCount != 12 {
+ t.Errorf("AllReasons(): platform-side count = %d, want 12", platformCount)
}
if agentCount != 14 {
t.Errorf("AllReasons(): agent-side count = %d, want 14", agentCount)
@@ -152,7 +154,8 @@ func TestAllReasonsContents(t *testing.T) {
ReasonRuntimeRecovery,
ReasonTimeout, ReasonIterationLimit, ReasonAgentBlocked,
ReasonAPIInvalidRequest, ReasonSkillBundleUnavailable,
- ReasonRuntimeCLITimeout, ReasonInvalidTaskIdentity,
+ ReasonRuntimeCLITimeout, ReasonEnvironmentPrepareFailed,
+ ReasonInvalidTaskIdentity,
ReasonAgentProviderAuthOrAccess, ReasonAgentProviderQuotaLimit,
ReasonAgentProviderCapacityOrRateLimit, ReasonAgentProviderServerError,
ReasonAgentProviderNetwork, ReasonAgentProcessFailure,