Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5370 fix: label stalled skill-bundle downloads, align failure-reason copy with the backend taxonomy (#6001)
Bohan Jiangc271f80999ef
diff --git a/apps/mobile/components/issue/run-row.tsx b/apps/mobile/components/issue/run-row.tsxindex de53d76bbd..d4b2d9c151 100644--- a/apps/mobile/components/issue/run-row.tsx+++ b/apps/mobile/components/issue/run-row.tsx@@ -11,7 +11,7 @@* ok-plan-linked-taco.md.*/import { Alert, Pressable, View } from "react-native";-import type { AgentTask, TaskFailureReason } from "@multica/core/types";+import type { AgentTask } from "@multica/core/types";import { Text } from "@/components/ui/text";import { ActorAvatar } from "@/components/ui/actor-avatar";import { useCancelTask } from "@/data/mutations/issues";@@ -65,7 +65,7 @@ function StatusBadge({ task }: { task: AgentTask }) {const label = STATUS_LABEL[task.status] ?? task.status;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. Reasons are coarse enums; missing/empty stays as just "Failed".+ // 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 (reasonLabel) {@@ -150,11 +150,42 @@ const STATUS_CLASS: Record<AgentTask["status"], string> = {cancelled: "text-muted-foreground",};-const FAILURE_REASON_LABEL: Record<TaskFailureReason, string> = {- agent_error: "Agent error",- timeout: "Timeout",- codex_semantic_inactivity: "Codex inactivity",+// 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",++ "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/lib/failure-reason-label.ts b/apps/mobile/lib/failure-reason-label.tsindex 7424a75742..7a641c6cd5 100644--- a/apps/mobile/lib/failure-reason-label.ts+++ b/apps/mobile/lib/failure-reason-label.ts@@ -1,32 +1,58 @@/**- * Mirror of `packages/views/agents/components/tabs/task-failure.ts:failureReasonLabel`.+ * Mirror of `packages/views/agents/components/tabs/task-failure.ts:REASON_LABEL`.** Why mirror: mobile cannot import from packages/views per the apps/mobile- * CLAUDE.md sharing rule. The enum itself comes from packages/core/types- * (type-only import is fine); only the human copy is mobile-owned.+ * CLAUDE.md sharing rule. Only the human copy is mobile-owned.*- * Used by the destructive chat bubble. The default branch handles enum- * drift — unknown values render a generic "Failed" rather than crashing- * or rendering the raw enum string, matching the root CLAUDE.md "Enum- * drift downgrades, not crashes" rule.+ * Keyed by the raw wire value rather than a closed enum, same as the web map:+ * `failure_reason` is an open string that grows as classifier rules land, and+ * an installed build will meet reasons it predates. Before MUL-5370 this was a+ * `Record<TaskFailureReason, string>` holding only the six pre-MUL-1949 coarse+ * values, so every refined `agent_error.*` the backend has written since+ * missed the lookup and rendered a bare "Failed".+ *+ * Divergence from web, deliberate: the web helper falls back to the raw wire+ * value, which is machine-y but searchable — right for an operator reading the+ * execution log. This one backs a chat bubble read by the person who just sent+ * a message, so an unrecognised reason degrades to a plain "Failed" instead of+ * leaking an enum string at them.*/-import type { TaskFailureReason } from "@multica/core/types";+const LABELS: Record<string, string> = {+ // Platform / scheduler side.+ queued_expired: "Expired in queue",+ runtime_offline: "Daemon offline",+ runtime_recovery: "Daemon restarted",+ timeout: "Task timed out",+ iteration_limit: "Hit the iteration limit",+ agent_blocked: "Waiting on human input",+ api_invalid_request: "Rejected by the model API",+ skill_bundle_unavailable: "Couldn't download the agent's skills",++ // Agent process side — provider.+ "agent_error.provider_auth_or_access": "Provider auth failed",+ "agent_error.provider_quota_limit": "Provider quota exhausted",+ "agent_error.provider_capacity_or_rate_limit": "Rate limited by provider",+ "agent_error.provider_server_error": "Provider server error",+ "agent_error.provider_network": "Network error reaching provider",-const LABELS: Record<TaskFailureReason, string> = {+ // Agent process side — agent / runner.+ "agent_error.process_failure": "Agent process crashed",+ "agent_error.empty_or_unparseable_output": "Agent returned no usable output",+ "agent_error.agent_timeout": "Agent timed out",+ "agent_error.context_overflow": "Context window exceeded",+ "agent_error.missing_config": "Missing API key or configuration",+ "agent_error.model_not_found_or_unavailable": "Model unavailable",+ "agent_error.runtime_version_unsupported": "Runner CLI version unsupported",+ "agent_error.runtime_missing_executable": "Runner CLI not installed",+ "agent_error.unknown": "Agent execution error",++ // Pre-MUL-1949 coarse values, still present on historical rows.agent_error: "Agent execution error",- timeout: "Task timed out",codex_semantic_inactivity: "Codex semantic inactivity timeout",- runtime_offline: "Daemon offline",- runtime_recovery: "Daemon restarted",manual: "Cancelled by user",};-export function failureReasonLabel(- reason: TaskFailureReason | string | null | undefined,-): string {+export function failureReasonLabel(reason: string | null | undefined): string {if (!reason) return "Failed";- if (reason in LABELS) {- return LABELS[reason as TaskFailureReason];- }- return "Failed";+ return LABELS[reason] ?? "Failed";}diff --git a/packages/core/agents/failure-reason.test.ts b/packages/core/agents/failure-reason.test.tsnew file mode 100644index 0000000000..58a1d5aea2--- /dev/null+++ b/packages/core/agents/failure-reason.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from "vitest";+import { resolveFailureReasonKey } from "./failure-reason";++const COPY = {+ agent_error: "family",+ "agent_error.provider_network": "refined",+ timeout: "platform",+} as const;++describe("resolveFailureReasonKey", () => {+ it("prefers an exact match over the coarse family", () => {+ expect(resolveFailureReasonKey("agent_error.provider_network", COPY)).toBe(+ "agent_error.provider_network",+ );+ });++ it("degrades a refined reason to its family when there is no exact copy", () => {+ // The MUL-5370 regression: before this, agent_error.unknown missed the+ // lookup entirely and the UI rendered a generic fallback instead of the+ // agent_error line the backend's classification had earned.+ expect(resolveFailureReasonKey("agent_error.unknown", COPY)).toBe(+ "agent_error",+ );+ });++ it("degrades a reason the client has never seen to its family", () => {+ expect(+ resolveFailureReasonKey("agent_error.some_future_bucket", COPY),+ ).toBe("agent_error");+ });++ it("matches a platform-side reason exactly", () => {+ expect(resolveFailureReasonKey("timeout", COPY)).toBe("timeout");+ });++ it("returns undefined when neither the reason nor its family is known", () => {+ expect(resolveFailureReasonKey("skill_bundle_unavailable", COPY)).toBeUndefined();+ expect(resolveFailureReasonKey("brand_new.thing", COPY)).toBeUndefined();+ });++ it("returns undefined for empty and nullish input", () => {+ expect(resolveFailureReasonKey("", COPY)).toBeUndefined();+ expect(resolveFailureReasonKey(null, COPY)).toBeUndefined();+ expect(resolveFailureReasonKey(undefined, COPY)).toBeUndefined();+ });++ it("ignores inherited Object properties so a reason named like one cannot spoof a key", () => {+ expect(resolveFailureReasonKey("constructor", COPY)).toBeUndefined();+ expect(resolveFailureReasonKey("toString", COPY)).toBeUndefined();+ });++ it("does not treat a leading dot as a family separator", () => {+ expect(resolveFailureReasonKey(".agent_error", COPY)).toBeUndefined();+ });+});diff --git a/packages/core/agents/failure-reason.ts b/packages/core/agents/failure-reason.tsnew file mode 100644index 0000000000..1f01cdecc6--- /dev/null+++ b/packages/core/agents/failure-reason.ts@@ -0,0 +1,40 @@+import type { TaskFailureReason } from "../types";++/**+ * Picks the copy key a UI surface should render for a server-supplied+ * `failure_reason`, degrading instead of falling off a cliff.+ *+ * Resolution order:+ * 1. Exact match — the surface has copy for this precise reason.+ * 2. Coarse family — `agent_error.provider_network` degrades to+ * `agent_error` when the surface only has family-level copy.+ * 3. `undefined` — nothing usable; the caller renders its own fallback.+ *+ * Why this exists: the backend's taxonomy is refined (`agent_error.*`) and+ * grows independently of shipped clients. Before MUL-5370 the surfaces did an+ * exact `Record` lookup against the six-value coarse enum, so every refined+ * reason missed and rendered a generic "something went wrong" — the useful+ * classification the backend had already computed was thrown away at the last+ * step. Step 2 makes an unseen `agent_error.<new_thing>` land on the family+ * line rather than the fallback, which is the repo's "enum drift downgrades,+ * not crashes" rule applied to copy.+ *+ * Pure and dependency-free so mobile can import it directly.+ */+export function resolveFailureReasonKey<K extends string>(+ reason: TaskFailureReason | string | null | undefined,+ copy: Readonly<Partial<Record<K, unknown>>>,+): K | undefined {+ if (!reason) return undefined;+ if (Object.prototype.hasOwnProperty.call(copy, reason)) {+ return reason as K;+ }+ const separator = reason.indexOf(".");+ if (separator > 0) {+ const family = reason.slice(0, separator);+ if (Object.prototype.hasOwnProperty.call(copy, family)) {+ return family as K;+ }+ }+ return undefined;+}diff --git a/packages/core/agents/index.ts b/packages/core/agents/index.tsindex f26e288bbb..c689d569e5 100644--- a/packages/core/agents/index.ts+++ b/packages/core/agents/index.ts@@ -1,5 +1,6 @@export * from "./types";export * from "./derive-presence";+export * from "./failure-reason";export * from "./effective-access";export * from "./queries";export * from "./use-agent-presence";diff --git a/packages/core/dashboard/failure-class.test.ts b/packages/core/dashboard/failure-class.test.tsindex 9b71e8f1e5..e647ee4268 100644--- a/packages/core/dashboard/failure-class.test.ts+++ b/packages/core/dashboard/failure-class.test.ts@@ -15,6 +15,9 @@ describe("failureClassOf", () => {expect(failureClassOf("agent_error.provider_server_error")).toBe("provider");expect(failureClassOf("runtime_offline")).toBe("runtime");expect(failureClassOf("queued_expired")).toBe("runtime");+ // 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");expect(failureClassOf("agent_error.process_failure")).toBe("agent");});diff --git a/packages/core/dashboard/failure-class.ts b/packages/core/dashboard/failure-class.tsindex ba30ec2f37..31ea676179 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 21 reasons, which is far+// The backend taxonomy (server/pkg/taskfailure) has 22 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 21+// Reason → class. Keys are the wire values written by the backend: the 22// 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.@@ -60,6 +60,11 @@ const REASON_CLASS: Record<string, FailureClass> = {queued_expired: "runtime","agent_error.runtime_missing_executable": "runtime","agent_error.runtime_version_unsupported": "runtime",+ // The daemon could not fetch the agent's skills from the control plane, so+ // the run never started. Grouped with runtime rather than provider: the+ // operator response is "check the daemon's link to Multica", the same as a+ // daemon that went offline — the model provider is not involved.+ skill_bundle_unavailable: "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.tsindex 1cac1723b7..1e8ceb8f4b 100644--- a/packages/views/agents/components/tabs/task-failure.ts+++ b/packages/views/agents/components/tabs/task-failure.ts@@ -23,6 +23,7 @@ const REASON_LABEL: Record<string, string> = {iteration_limit: "Hit the iteration limit",agent_blocked: "Waiting on human input",api_invalid_request: "Rejected by the model API",+ skill_bundle_unavailable: "Couldn't download the agent's skills",// Agent process side — provider."agent_error.provider_auth_or_access": "Provider auth failed",diff --git a/packages/views/chat/components/chat-message-list.test.tsx b/packages/views/chat/components/chat-message-list.test.tsxindex e5bbb42e9e..ba4fe386eb 100644--- a/packages/views/chat/components/chat-message-list.test.tsx+++ b/packages/views/chat/components/chat-message-list.test.tsx@@ -165,3 +165,71 @@ describe("ChatMessageList live timeline (MUL-3960 regression)", () => {expect(screen.queryByText(/Hidden protocol/)).not.toBeInTheDocument();});});++describe("ChatMessageList failure copy (MUL-5370 regression)", () => {+ // The backend moved to the refined taxonomy (agent_error.*) in MUL-2946 but+ // the copy map stayed on the six coarse values, so an exact-key lookup+ // missed every refined reason and fell through to the generic fallback.+ // A user whose skill bundle download stalled was told only "Something went+ // wrong", and the maintainer debugging it had nothing better to go on.+ function renderFailure(reason: string) {+ return render(+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <QueryClientProvider client={new QueryClient()}>+ <ChatMessageList+ messages={[+ {+ id: "m1",+ chat_session_id: "s1",+ role: "assistant",+ content: "skill bundle unavailable: skill \"x\"",+ task_id: null,+ created_at: new Date(0).toISOString(),+ failure_reason: reason,+ },+ ]}+ pendingTask={undefined}+ availability="online"+ />+ </QueryClientProvider>+ </I18nProvider>,+ );+ }++ const FALLBACK = enChat.message_list.failure.fallback;++ it("renders dedicated copy for a stalled skill bundle download", async () => {+ renderFailure("skill_bundle_unavailable");+ expect(+ await screen.findByText(enChat.message_list.failure.skill_bundle_unavailable),+ ).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(+ await screen.findByText(enChat.message_list.failure.provider_network),+ ).toBeInTheDocument();+ });++ it("degrades an unnamed refined reason to its agent_error family", async () => {+ renderFailure("agent_error.unknown");+ expect(+ await screen.findByText(enChat.message_list.failure.agent_error),+ ).toBeInTheDocument();+ expect(screen.queryByText(FALLBACK)).not.toBeInTheDocument();+ });++ it("degrades a reason newer than this build to its agent_error family", async () => {+ renderFailure("agent_error.some_future_bucket");+ expect(+ await screen.findByText(enChat.message_list.failure.agent_error),+ ).toBeInTheDocument();+ });++ it("still falls back when neither the reason nor its family is known", async () => {+ renderFailure("something_entirely_new");+ expect(await screen.findByText(FALLBACK)).toBeInTheDocument();+ });+});diff --git a/packages/views/chat/components/chat-message-list.tsx b/packages/views/chat/components/chat-message-list.tsxindex cec109038c..42556dfe22 100644--- a/packages/views/chat/components/chat-message-list.tsx+++ b/packages/views/chat/components/chat-message-list.tsx@@ -25,10 +25,10 @@ import { RichContentScrollRootProvider } from "../../rich-content/scroll-root";import { copyText } from "@multica/ui/lib/clipboard";import { AttachmentList } from "../../issues/components/comment-card";import type { AgentAvailability } from "@multica/core/agents";+import { resolveFailureReasonKey } from "@multica/core/agents";import type {ChatMessage,ChatPendingTask,- TaskFailureReason,TaskMessagePayload,} from "@multica/core/types";import type { ChatTimelineItem } from "@multica/core/chat";@@ -602,19 +602,47 @@ function FailureBubble({// Chat gets its own friendly, reassuring copy per failure reason — plain// language + a "try again" nudge — instead of the terse developer labels// (`failureReasonLabel`) used on the agent-detail / execution-log surfaces.- // An unknown reason (a future enum value this build doesn't ship yet) falls- // back to a generic friendly line. The raw error stays tucked under the- // collapsible below for anyone who wants the technical detail.- const chatFailureCopy: Record<TaskFailureReason, string> = {+ // The raw error stays tucked under the collapsible below for anyone who+ // wants the technical detail.+ //+ // Keyed by the raw wire value, not a closed enum — `failure_reason` is an+ // open string that grows as classifier rules land, same as+ // `failureReasonLabel`'s map. Deliberately partial: the taxonomy is larger+ // than the set worth writing distinct chat copy for, so an entry earns its+ // place only when it can say something the `agent_error` family line can't,+ // usually a different next step (re-auth, top up, check the network).+ //+ // Where this diverges from the operator surfaces: they fall back to the raw+ // wire value, which is machine-y but searchable. A chat bubble is read by+ // the person who just sent a message, so it degrades through+ // `resolveFailureReasonKey` to the family line and finally to friendly+ // generic copy. The raw error is still one click away under the collapsible.+ const chatFailureCopy: Record<string, string> = {agent_error: t(($) => $.message_list.failure.agent_error),timeout: t(($) => $.message_list.failure.timeout),codex_semantic_inactivity: t(($) => $.message_list.failure.codex_semantic_inactivity),runtime_offline: t(($) => $.message_list.failure.runtime_offline),runtime_recovery: t(($) => $.message_list.failure.runtime_recovery),manual: t(($) => $.message_list.failure.manual),+ cancelled: t(($) => $.message_list.failure.manual),+ skill_bundle_unavailable: t(($) => $.message_list.failure.skill_bundle_unavailable),+ "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),+ "agent_error.provider_capacity_or_rate_limit": t(+ ($) => $.message_list.failure.provider_capacity_or_rate_limit,+ ),+ "agent_error.context_overflow": t(($) => $.message_list.failure.context_overflow),+ "agent_error.runtime_missing_executable": t(+ ($) => $.message_list.failure.runtime_missing_executable,+ ),+ "agent_error.runtime_version_unsupported": t(+ ($) => $.message_list.failure.runtime_version_unsupported,+ ),};+ const copyKey = resolveFailureReasonKey(reason, chatFailureCopy);const label =- chatFailureCopy[reason as TaskFailureReason] ??+ (copyKey && chatFailureCopy[copyKey]) ??t(($) => $.message_list.failure.fallback);return (diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.jsonindex fc7c53fb31..2b2ef55d59 100644--- a/packages/views/locales/en/chat.json+++ b/packages/views/locales/en/chat.json@@ -42,6 +42,14 @@"runtime_offline": "The agent is offline right now, so it couldn't reply. Please try again once it's back online.","runtime_recovery": "The agent restarted before it could finish. Please try again.","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.",+ "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.",+ "provider_capacity_or_rate_limit": "The model provider is busy or rate-limiting this account. Please try again in a moment.",+ "context_overflow": "This conversation got too long for the model. Start a new session, or break your request into smaller steps.",+ "runtime_missing_executable": "The agent's CLI couldn't be found on this machine. Check that it's installed and on PATH, then retry.",+ "runtime_version_unsupported": "The agent's CLI is too old for this runtime. Upgrade it, then retry.","fallback": "Something went wrong and the agent couldn't finish replying. Please try again."},"tools_one": "{{count}} tool",diff --git a/packages/views/locales/ja/chat.json b/packages/views/locales/ja/chat.jsonindex c86e66fab0..76ff5c6946 100644--- a/packages/views/locales/ja/chat.json+++ b/packages/views/locales/ja/chat.json@@ -41,6 +41,14 @@"runtime_offline": "エージェントは現在オフラインのため、返信できませんでした。オンラインに戻ってから再度お試しください。","runtime_recovery": "完了する前にエージェントが再起動しました。もう一度お試しください。","manual": "この返信はキャンセルされました。",+ "skill_bundle_unavailable": "エージェントの skill をダウンロードできず、返信を開始できませんでした。多くの場合はネットワークの問題です。もう一度お試しください。",+ "provider_network": "モデルサービスとの接続が切断され、返信を完了できませんでした。ネットワークを確認してから再度お試しください。",+ "provider_auth_or_access": "エージェントのモデルアカウントのログインが無効になりました。再度ログインしてからお試しください。",+ "provider_quota_limit": "エージェントのモデルアカウントの残高が不足しています。チャージするかアカウントを切り替えてからお試しください。",+ "provider_capacity_or_rate_limit": "モデルサービスが混雑しているか、レート制限がかかっています。しばらくしてからお試しください。",+ "context_overflow": "この会話がモデルのコンテキスト長を超えました。新しいセッションを開始するか、リクエストを分けてみてください。",+ "runtime_missing_executable": "このデバイスでエージェントの CLI が見つかりません。インストール済みで PATH に含まれているか確認してから、もう一度お試しください。",+ "runtime_version_unsupported": "エージェントの CLI のバージョンが古すぎます。アップグレードしてからお試しください。","fallback": "問題が発生し、エージェントは返信を完了できませんでした。もう一度お試しください。"},"tools_other": "ツール {{count}}個",diff --git a/packages/views/locales/ko/chat.json b/packages/views/locales/ko/chat.jsonindex 8cd1bb58d9..288d8f85d5 100644--- a/packages/views/locales/ko/chat.json+++ b/packages/views/locales/ko/chat.json@@ -41,6 +41,14 @@"runtime_offline": "에이전트가 현재 오프라인 상태여서 답변할 수 없습니다. 다시 온라인이 되면 시도해 주세요.","runtime_recovery": "완료 전에 에이전트가 다시 시작되었습니다. 다시 시도해 주세요.","manual": "이 답변이 취소되었습니다.",+ "skill_bundle_unavailable": "에이전트의 skill을 내려받지 못해 답변을 시작하지 못했습니다. 대개 네트워크 연결 문제입니다. 다시 시도해 주세요.",+ "provider_network": "모델 서비스와의 연결이 끊겨 답변을 완료하지 못했습니다. 네트워크를 확인한 뒤 다시 시도해 주세요.",+ "provider_auth_or_access": "에이전트의 모델 계정 로그인이 만료되었습니다. 다시 로그인한 뒤 시도해 주세요.",+ "provider_quota_limit": "에이전트의 모델 계정 잔액이 부족합니다. 충전하거나 계정을 변경한 뒤 시도해 주세요.",+ "provider_capacity_or_rate_limit": "모델 서비스가 혼잡하거나 요청 한도에 걸렸습니다. 잠시 후 다시 시도해 주세요.",+ "context_overflow": "이 대화가 모델의 컨텍스트 길이를 초과했습니다. 새 세션을 시작하거나 요청을 더 작게 나눠 보세요.",+ "runtime_missing_executable": "이 기기에서 에이전트의 CLI를 찾을 수 없습니다. 설치되어 있고 PATH에 있는지 확인한 뒤 다시 시도해 주세요.",+ "runtime_version_unsupported": "에이전트의 CLI 버전이 너무 낮습니다. 업그레이드한 뒤 다시 시도해 주세요.","fallback": "문제가 발생하여 에이전트가 답변을 완료하지 못했습니다. 다시 시도해 주세요."},"tools_other": "도구 {{count}}개",diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.jsonindex befe45b027..9c1c352a13 100644--- a/packages/views/locales/zh-Hans/chat.json+++ b/packages/views/locales/zh-Hans/chat.json@@ -41,6 +41,14 @@"runtime_offline": "智能体当前离线,暂时无法回复。等它恢复在线后再试。","runtime_recovery": "智能体在完成前重启了。请重试。","manual": "这次回复已取消。",+ "skill_bundle_unavailable": "没能下载到智能体的 skill,这次回复没有启动。通常是网络连接问题,请重试。",+ "provider_network": "与模型服务的连接中断,回复没能完成。检查网络后重试。",+ "provider_auth_or_access": "智能体的模型账号登录已失效。重新登录后再试。",+ "provider_quota_limit": "智能体的模型账号额度已用尽。充值或更换账号后再试。",+ "provider_capacity_or_rate_limit": "模型服务繁忙或触发了限流。稍后再试。",+ "context_overflow": "这次对话超出了模型的上下文长度。开一个新会话,或把需求拆得更小一些。",+ "runtime_missing_executable": "在这台设备上找不到智能体的 CLI。确认已安装并且在 PATH 中,然后重试。",+ "runtime_version_unsupported": "智能体的 CLI 版本过低。升级后重试。","fallback": "出了点问题,智能体未能完成回复。请重试。"},"tools_other": "{{count}} 个工具",diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 5fee113404..f9dd55869c 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -55,6 +55,14 @@ var ErrNoRuntimesToRegister = errors.New("no agent runtimes could be registered"// recover the task on a fresh attempt.var errTaskPrepareTimeout = errors.New("task preparation timed out")+// errSkillBundleUnavailable marks a task that died in preparation because the+// daemon could not download one of the agent's skill bundles. Carrying it as a+// sentinel — rather than leaving handleTask to pattern-match the wrapped+// transport error — is what lets the failure land on the platform-side+// skill_bundle_unavailable reason instead of agent_error.unknown, which is not+// on the server's retry allowlist. (MUL-5370)+var errSkillBundleUnavailable = errors.New("skill bundle unavailable")+const (taskSlotWaitTimeout = 2 * time.SecondtaskSlotCapacityBackoff = 5 * time.Second@@ -3559,6 +3567,14 @@ func taskRunFailureReason(err error) string {if errors.Is(err, errTaskPrepareTimeout) {return taskfailure.ReasonTimeout.String()}+ // Checked after the prepare deadline: when the whole prepare budget ran+ // out, runTask has already collapsed the error into errTaskPrepareTimeout+ // and that classification is the more accurate one. This branch is for the+ // per-skill download deadline firing inside a prepare budget that still had+ // room (MUL-5370).+ if errors.Is(err, errSkillBundleUnavailable) {+ return taskfailure.ReasonSkillBundleUnavailable.String()+ }return taskfailure.Classify(err.Error()).String()}@@ -4107,9 +4123,18 @@ func (d *Daemon) ensureTaskSkillBundles(ctx context.Context, task *Task) error {// that ultimately fails leaves the skills it did fetch cached for the next// one. (GitHub #4505 / MUL-3650)for _, ref := range misses {+ started := time.Now()bundle, err := d.resolveSkillBundle(ctx, task, ref)if err != nil {- return fmt.Errorf("resolve skill bundles: %w", err)+ // Name the skill, its declared size, and how long we actually+ // waited. The bare "resolve skill bundles: context deadline+ // exceeded" this replaced was indistinguishable from a generic+ // network fault, and cost a community thread three hours of+ // guesswork (MUL-5370): size + elapsed separate "this bundle is+ // too big for the link" from "the link is dead".+ return fmt.Errorf("%w: skill %q (id=%s, %d bytes) after %s: %w",+ errSkillBundleUnavailable, ref.Name, ref.ID, ref.SizeBytes,+ time.Since(started).Round(time.Millisecond), err)}resolved[skillRefKey(bundle.Source, bundle.ID)] = bundle}diff --git a/server/internal/daemon/skill_bundle_resolve_test.go b/server/internal/daemon/skill_bundle_resolve_test.goindex 5fbc85ae02..6c0f0243df 100644--- a/server/internal/daemon/skill_bundle_resolve_test.go+++ b/server/internal/daemon/skill_bundle_resolve_test.go@@ -3,11 +3,15 @@ package daemonimport ("context""encoding/json"+ "errors""net/http""net/http/httptest"+ "strings""sync""testing""time"++ "github.com/multica-ai/multica/server/pkg/taskfailure")func TestSkillBundleResolveTimeout(t *testing.T) {@@ -227,3 +231,62 @@ func TestEnsureTaskSkillBundles_AcceptsServerSideSkillUpdate(t *testing.T) {t.Error("updated bundle should be cached under its own (new) hash")}}++// TestEnsureTaskSkillBundles_DeadlineIsLabelledStructurally is the MUL-5370+// regression. A stalled bundle download used to surface as the bare string+// "resolve skill bundles: context deadline exceeded", which taskfailure.Classify+// could only file under agent_error.unknown — a bucket that is NOT on the+// server's retry allowlist. So a transient stall became a terminal chat failure+// carrying a label nobody could act on, and the user was told only "something+// went wrong". The wrap must now (a) name the skill and how long we waited,+// (b) preserve the transport cause, and (c) carry a sentinel that+// taskRunFailureReason maps to the retryable platform-side reason.+func TestEnsureTaskSkillBundles_DeadlineIsLabelledStructurally(t *testing.T) {+ defer noSleepRetry(t)()++ block := make(chan struct{})+ srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {+ // Accept the connection and never answer — the shape of a link that+ // is up but cannot carry the response (blocked route, missing proxy).+ <-block+ }))+ // LIFO: release the handler before tearing the server down, so Close+ // doesn't block on an in-flight request.+ defer srv.Close()+ defer close(block)++ ref := skillRefFromBundle(makeResolvableSkillBundle("frontend-review"))+ d := &Daemon{+ client: NewClient(srv.URL),+ skillCache: NewSkillBundleCache(t.TempDir()),+ }+ task := &Task{+ ID: "task-1",+ RuntimeID: "rt-1",+ WorkspaceID: "ws-1",+ Agent: &AgentData{ID: "agent-1", SkillRefs: []SkillRefData{ref}},+ }++ // Squeeze the parent below the per-skill floor so the deadline fires+ // without the test waiting skillBundleResolveMinTimeout for it.+ ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)+ defer cancel()++ err := d.ensureTaskSkillBundles(ctx, task)+ if err == nil {+ t.Fatal("expected an error when the bundle download never completes")+ }+ if !errors.Is(err, errSkillBundleUnavailable) {+ t.Errorf("error must carry the skill-bundle sentinel, got %v", err)+ }+ if !errors.Is(err, context.DeadlineExceeded) {+ t.Errorf("error must preserve the transport cause, got %v", err)+ }+ if !strings.Contains(err.Error(), "frontend-review") {+ t.Errorf("error must name the skill that failed, got %v", err)+ }+ want := taskfailure.ReasonSkillBundleUnavailable.String()+ if got := taskRunFailureReason(err); got != want {+ t.Errorf("taskRunFailureReason = %q, want %q (retryable platform-side reason)", got, want)+ }+}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 39248ad8fe..08a6e08167 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -3106,6 +3106,15 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,if failureReason == "" {failureReason = taskfailure.Classify(errMsg).String()}+ // MUL-5370: daemons upgrade on their own cadence, so a fix that depends on+ // a new daemon-side label only reaches hosts that happened to update. An+ // older daemon reports a *non-empty* catchall for a failed skill-bundle+ // download, which the branch above deliberately leaves alone — without this+ // the retry and the actionable copy would both skip every un-upgraded host.+ // Runs after the empty-reason branch so a legacy reason synthesised there+ // is normalised too, and before the retry pre-compute below so the upgraded+ // reason is what decides retry eligibility.+ failureReason = taskfailure.NormalizeDaemonReason(failureReason, errMsg).String()// Pre-compute the auto-retry so the retry child can be created inside the// SAME transaction as the fail (MUL-4351). Doing it atomically closes the@@ -3313,12 +3322,17 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,// the platform retry it directly (MUL-4910). It is resume-safe (not in// resumeUnsafeFailureReason), so the retry child inherits the session and// continues the truncated conversation rather than restarting from scratch.+// skill_bundle_unavailable is retryable for the same reason: the agent process+// never started, so there is nothing to be idempotent about, and every bundle+// that did download is already cached on disk — a retry resumes from there+// instead of re-fetching the whole set (MUL-5370).var retryableReasons = map[string]bool{"runtime_offline": true,"runtime_recovery": true,"timeout": true,"codex_semantic_inactivity": true,- string(taskfailure.ReasonAgentProviderNetwork): true,+ string(taskfailure.ReasonAgentProviderNetwork): true,+ string(taskfailure.ReasonSkillBundleUnavailable): true,}// Transient provider stream cuts (provider_network) get a bespoke three-tierdiff --git a/server/internal/service/task_complete_race_test.go b/server/internal/service/task_complete_race_test.goindex ee9d69b5e6..653588c0fe 100644--- a/server/internal/service/task_complete_race_test.go+++ b/server/internal/service/task_complete_race_test.go@@ -11,6 +11,7 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/events"db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/taskfailure")// mockRow implements pgx.Row, returning either a scanned task or pgx.ErrNoRows.@@ -278,3 +279,48 @@ func TestTaskFailureClassifiers(t *testing.T) {})}}++// TestSkillBundleFailureFromLegacyDaemonRetries is the mixed-version+// regression for MUL-5370. It walks the exact chain FailTask runs for a task+// an un-upgraded daemon just failed, and asserts the user-visible outcome:+// the run is retried instead of dying.+//+// The trap this guards: the daemon-side fix labels the failure structurally,+// but an old daemon reports a NON-EMPTY catchall, so FailTask's "classify only+// when the caller gave us nothing" branch leaves it alone. Without+// NormalizeDaemonReason the reason stays agent_error.unknown, which is not on+// retryableReasons — meaning the fix would reach only hosts that happened to+// update, while the un-upgraded hosts most likely to be hitting the bug keep+// failing terminally.+func TestSkillBundleFailureFromLegacyDaemonRetries(t *testing.T) {+ const legacyErr = "resolve skill bundles: context deadline exceeded"+ task := db.AgentTaskQueue{+ Attempt: 1,+ MaxAttempts: 2,+ IssueID: pgtype.UUID{Bytes: [16]byte{1}, Valid: true},+ }++ // What an old daemon puts on the wire, and what FailTask does with it.+ legacyReason := taskfailure.ReasonAgentUnknown.String()+ if retryEligible(legacyReason, task) {+ t.Fatal("precondition: the raw catchall must not be retryable, or this test proves nothing")+ }++ normalized := taskfailure.NormalizeDaemonReason(legacyReason, legacyErr).String()+ if normalized != taskfailure.ReasonSkillBundleUnavailable.String() {+ t.Fatalf("normalized reason = %q, want %q", normalized, taskfailure.ReasonSkillBundleUnavailable)+ }+ if !retryEligible(normalized, task) {+ t.Errorf("a skill-bundle failure reported by an old daemon must still be retried; got reason %q", normalized)+ }++ // A current daemon supplies the reason itself and must reach the same+ // outcome — the two versions converge rather than diverging by client.+ current := taskfailure.NormalizeDaemonReason(+ taskfailure.ReasonSkillBundleUnavailable.String(),+ `skill bundle unavailable: skill "x" (id=1, 10 bytes) after 30s: context deadline exceeded`,+ ).String()+ if !retryEligible(current, task) {+ t.Errorf("a skill-bundle failure reported by a current daemon must be retried; got reason %q", current)+ }+}diff --git a/server/migrations/233_backfill_skill_bundle_unavailable.down.sql b/server/migrations/233_backfill_skill_bundle_unavailable.down.sqlnew file mode 100644index 0000000000..747345ae58--- /dev/null+++ b/server/migrations/233_backfill_skill_bundle_unavailable.down.sql@@ -0,0 +1,16 @@+-- Reverse the backfill: return the re-classified rows to agent_error.unknown,+-- the single bucket the up migration took them from. Restricting the filter to+-- the old wrapper prefix keeps the inverse exact — rows this migration never+-- touched (a new daemon writes skill_bundle_unavailable directly, with a+-- "skill bundle unavailable: ..." error string) are left alone rather than+-- being relabelled into a bucket they were never in.+UPDATE agent_task_queue+SET failure_reason = 'agent_error.unknown'+WHERE status = 'failed'+ AND failure_reason = 'skill_bundle_unavailable'+ AND error LIKE 'resolve skill bundles:%';++UPDATE chat_message+SET failure_reason = 'agent_error.unknown'+WHERE failure_reason = 'skill_bundle_unavailable'+ AND content LIKE 'resolve skill bundles:%';diff --git a/server/migrations/233_backfill_skill_bundle_unavailable.up.sql b/server/migrations/233_backfill_skill_bundle_unavailable.up.sqlnew file mode 100644index 0000000000..af8ad491f1--- /dev/null+++ b/server/migrations/233_backfill_skill_bundle_unavailable.up.sql@@ -0,0 +1,33 @@+-- Backfill the skill_bundle_unavailable reason introduced in MUL-5370.+--+-- The daemon now labels "could not download the agent's skill bundles"+-- structurally instead of letting the wrapped transport error fall through+-- taskfailure.Classify into agent_error.unknown. That change is forward-only:+-- historical rows still sit in the unknown bucket, which makes the failure+-- invisible on the Usage page's Errors breakdown — exactly the observability+-- gap that let this bug survive in the wild.+--+-- The witness is the old wrapper prefix these rows were written with+-- ("resolve skill bundles: ..."), which is stable and unambiguous: no other+-- code path produced it.+--+-- Scoped to agent_error.unknown alone, and that is exhaustive rather than+-- conservative: the wrapper string first shipped 2026-06-23 (MUL-3281,+-- 5038c983c), three weeks after the in-flight classifier landed 2026-06-03+-- (MUL-2946, 10afd1af1). Every row that can carry this prefix was therefore+-- written through taskfailure.Classify and landed in agent_error.unknown --+-- none can hold the pre-MUL-1949 coarse 'agent_error'. Keeping the source+-- bucket single-valued is what makes the down migration an exact inverse.+UPDATE agent_task_queue+SET failure_reason = 'skill_bundle_unavailable'+WHERE status = 'failed'+ AND failure_reason = 'agent_error.unknown'+ AND error LIKE 'resolve skill bundles:%';++-- chat_message mirrors the task's failure_reason for chat turns, and the chat+-- bubble reads it directly — leaving these behind would keep showing the+-- generic "something went wrong" copy on historical turns.+UPDATE chat_message+SET failure_reason = 'skill_bundle_unavailable'+WHERE failure_reason = 'agent_error.unknown'+ AND content LIKE 'resolve skill bundles:%';diff --git a/server/pkg/taskfailure/classify.go b/server/pkg/taskfailure/classify.goindex 9e33d41a93..62c5e744f1 100644--- a/server/pkg/taskfailure/classify.go+++ b/server/pkg/taskfailure/classify.go@@ -63,7 +63,7 @@ func Classify(rawError string) Reason {trimmed := strings.TrimSpace(rawError)if trimmed == "" {// SQL maps NULL/empty to a separate bucket ("empty_error"),- // but that bucket is not part of the canonical 21. In-flight+ // but that bucket is not part of the canonical 22. In-flight// callers should never hand us empty input — if they do, the// safest landing is the catchall.return ReasonAgentUnknown@@ -167,6 +167,16 @@ func Classify(rawError string) Reason {// instead of falling through to agent_error.unknown / process_failure// and terminating the task (MUL-4910). Checked before rule 13 so the// "... exited with error: exit status N ..." variant still routes here.+ //+ // "deadline exceeded" covers every Go-side context deadline that+ // reaches the classifier as text — `context deadline exceeded` from a+ // cancelled request, and net/http's `Client.Timeout exceeded while+ // awaiting headers` variant. Before MUL-5370 these all landed in+ // agent_error.unknown, which is not on the retry allowlist, so a+ // transient stall became a terminal failure with no usable label.+ // Note this only catches deadlines that arrive as a bare string;+ // callers holding the error value should classify structurally+ // instead (see taskRunFailureReason in daemon/daemon.go).// Mirror these substrings into the MUL-1949 offline backfill SQL.case containsAny(lower,"stream disconnected",@@ -179,6 +189,8 @@ func Classify(rawError string) Reason {"connectionrefused","dns","i/o timeout",+ "deadline exceeded",+ "timeout exceeded while awaiting",):return ReasonAgentProviderNetwork@@ -242,6 +254,47 @@ func Classify(rawError string) Reason {return ReasonAgentUnknown}+// legacySkillBundlePrefix is the exact wrapper a pre-MUL-5370 daemon put on a+// failed skill-bundle download. It is an unambiguous witness: no other code+// path ever produced it, and a current daemon writes "skill bundle+// unavailable: ..." instead.+const legacySkillBundlePrefix = "resolve skill bundles:"++// legacySkillBundleReasons are the buckets an older daemon's own classifier+// could land that failure in. All three mean "we only knew it was some+// transport fault": agent_error.unknown from a daemon predating the deadline+// rule, agent_error.provider_network from one that has it, and the+// pre-MUL-1949 coarse agent_error. None of them carries information that+// upgrading would discard.+var legacySkillBundleReasons = map[string]bool{+ string(ReasonAgentUnknown): true,+ string(ReasonAgentProviderNetwork): true,+ "agent_error": true,+}++// NormalizeDaemonReason upgrades a failure_reason reported by an older daemon+// onto the taxonomy this server understands, using the raw error text as the+// witness. It returns the reason unchanged when nothing applies.+//+// Why this exists (MUL-5370): installed daemons upgrade on their own cadence,+// so a fix that only labels a failure correctly on the daemon side reaches+// nobody until every host updates. The daemon reports a non-empty reason, so+// FailTask's "classify when empty" guard does not fire, and the server would+// persist the stale label — no auto-retry, and the chat bubble falls back to+// generic copy. Recognising the wire shape an old daemon produces closes that+// gap the moment the server deploys.+//+// This is a boundary compatibility shim, not internal fallback logic: it can+// be deleted once no daemon old enough to emit legacySkillBundlePrefix is+// still reporting.+func NormalizeDaemonReason(reason, rawError string) Reason {+ if legacySkillBundleReasons[reason] &&+ strings.HasPrefix(strings.TrimSpace(rawError), legacySkillBundlePrefix) {+ return ReasonSkillBundleUnavailable+ }+ return Reason(reason)+}+// 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 thandiff --git a/server/pkg/taskfailure/classify_test.go b/server/pkg/taskfailure/classify_test.goindex acdb7dd577..9cd240b6f1 100644--- a/server/pkg/taskfailure/classify_test.go+++ b/server/pkg/taskfailure/classify_test.go@@ -102,6 +102,12 @@ func TestClassifyRules(t *testing.T) {{"connectionrefused single", "ConnectionRefused", ReasonAgentProviderNetwork},{"dns", "dns lookup failed", ReasonAgentProviderNetwork},{"i/o timeout", "read tcp 1.2.3.4:443: i/o timeout", ReasonAgentProviderNetwork},+ // MUL-5370: every Go-side context deadline used to land in+ // agent_error.unknown, which is not on the retry allowlist — a+ // transient stall became a terminal failure with a useless label.+ {"context deadline exceeded", "context deadline exceeded", ReasonAgentProviderNetwork},+ {"wrapped context deadline", `Post "https://api.example.com/v1": context deadline exceeded`, ReasonAgentProviderNetwork},+ {"http client timeout", `Get "https://api.example.com": net/http: request canceled (Client.Timeout exceeded while awaiting headers)`, ReasonAgentProviderNetwork},// 8. Model not found / unavailable.{"model not found", "Error: model claude-3-opus-99 not found", ReasonAgentModelNotFoundOrUnavailable},@@ -265,3 +271,108 @@ func TestClassifyAlwaysReturnsAgentSide(t *testing.T) {}}}++// TestNormalizeDaemonReason is the mixed-version regression for MUL-5370.+//+// The daemon-side fix labels a failed skill-bundle download structurally, but+// installed daemons upgrade on their own cadence. An un-upgraded daemon reports+// a NON-EMPTY catchall, which FailTask's "classify only when empty" guard+// deliberately preserves — so without this normalisation the fix would reach+// only hosts that happened to update: no auto-retry (the catchall is not on the+// retry allowlist) and generic chat copy, on exactly the hosts most likely to+// be hitting the bug.+func TestNormalizeDaemonReason(t *testing.T) {+ t.Parallel()++ const legacyErr = "resolve skill bundles: context deadline exceeded"++ cases := []struct {+ name string+ reason string+ raw string+ want Reason+ }{+ {+ name: "old daemon catchall is upgraded",+ reason: string(ReasonAgentUnknown),+ raw: legacyErr,+ want: ReasonSkillBundleUnavailable,+ },+ {+ // A daemon new enough to classify the deadline as network, but not+ // new enough to know the failure was a skill bundle.+ name: "old daemon network guess is upgraded",+ reason: string(ReasonAgentProviderNetwork),+ raw: legacyErr,+ want: ReasonSkillBundleUnavailable,+ },+ {+ name: "pre-MUL-1949 coarse reason is upgraded",+ reason: "agent_error",+ raw: legacyErr,+ want: ReasonSkillBundleUnavailable,+ },+ {+ name: "leading whitespace does not defeat the witness",+ reason: string(ReasonAgentUnknown),+ raw: " " + legacyErr,+ want: ReasonSkillBundleUnavailable,+ },+ {+ // A current daemon already sends the right reason and a different+ // error string; nothing to do.+ name: "current daemon reason passes through",+ reason: string(ReasonSkillBundleUnavailable),+ raw: `skill bundle unavailable: skill "x" (id=1, 10 bytes) after 30s: context deadline exceeded`,+ want: ReasonSkillBundleUnavailable,+ },+ {+ // The witness is a prefix, not a substring: an agent that merely+ // mentions the old wrapper in its output must not be relabelled.+ name: "prefix only, not substring",+ reason: string(ReasonAgentUnknown),+ raw: "the agent said it could not resolve skill bundles: and then gave up",+ want: ReasonAgentUnknown,+ },+ {+ name: "unrelated reason with the witness is left alone",+ reason: string(ReasonAgentProviderAuthOrAccess),+ raw: legacyErr,+ want: ReasonAgentProviderAuthOrAccess,+ },+ {+ name: "catchall without the witness is left alone",+ reason: string(ReasonAgentUnknown),+ raw: "claude exited with error: exit status 1",+ want: ReasonAgentUnknown,+ },+ {+ name: "empty reason is left alone for the caller's classifier",+ reason: "",+ raw: legacyErr,+ want: Reason(""),+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got := NormalizeDaemonReason(tc.reason, tc.raw); got != tc.want {+ t.Errorf("NormalizeDaemonReason(%q, %q) = %q, want %q", tc.reason, tc.raw, got, tc.want)+ }+ })+ }+}++// TestNormalizeDaemonReason_UpgradedReasonIsRetryable pins the property that+// actually matters to the user: the normalised reason must be one the server+// retries. If someone later drops skill_bundle_unavailable from+// internal/service/task.go's retryableReasons, the label survives but the+// self-healing this PR is for silently disappears.+func TestNormalizeDaemonReason_UpgradedReasonIsPlatformSide(t *testing.T) {+ t.Parallel()++ got := NormalizeDaemonReason(string(ReasonAgentUnknown), "resolve skill bundles: context deadline exceeded")+ if got.IsAgentError() {+ t.Errorf("%q must be platform-side: the agent process never started", got)+ }+}diff --git a/server/pkg/taskfailure/failure.go b/server/pkg/taskfailure/failure.goindex 4eab95a395..fa01478590 100644--- a/server/pkg/taskfailure/failure.go+++ b/server/pkg/taskfailure/failure.go@@ -12,19 +12,20 @@// This package lifts that classifier into the in-flight write path so the// stored failure_reason is already refined when the row is first// persisted, and so server / daemon / cloud share a single source of-// truth for the canonical 21 values. PR1 of the Grafana board plan+// truth for the canonical 22 values. PR1 of the Grafana board plan// ([MUL-2946](https://multica/issues/MUL-2946)). Subsequent PRs use// AllReasons() to pre-warm the Prometheus failure_reason label set.//-// The 21 canonical values fall into two groups:+// The 22 canonical values fall into two groups://-// - 7 platform-side values (no `agent_error.` prefix) emitted by the+// - 8 platform-side values (no `agent_error.` prefix) emitted by the// server-side sweepers and daemon classifiers when the failure is// attributable to the platform/scheduler/runtime layer rather than// anything the agent process did://// queued_expired, runtime_offline, runtime_recovery, timeout,-// iteration_limit, agent_blocked, api_invalid_request+// iteration_limit, agent_blocked, api_invalid_request,+// skill_bundle_unavailable//// - 14 agent-side values (with `agent_error.` prefix) produced by// Classify(rawError) when the agent process surfaced an error string.@@ -47,7 +48,7 @@ type Reason string// agentErrorPrefix marks the 14 sub-reasons that originate inside the// agent process (provider error, runner crash, context overflow, etc.)-// as opposed to the 7 platform-side reasons (queue expiry, runtime+// as opposed to the 8 platform-side reasons (queue expiry, runtime// offline, sweeper timeout, etc.). IsAgentError uses this prefix so// callers don't have to enumerate the agent-side reasons by hand.const agentErrorPrefix = "agent_error."@@ -99,6 +100,17 @@ const (// resume lookup. Written by classifyPoisonedError in daemon/poisoned.go.ReasonAPIInvalidRequest Reason = "api_invalid_request"+ // ReasonSkillBundleUnavailable: the daemon could not download the+ // agent's skill bundles from the control plane during task+ // preparation — the agent process was never launched. Platform-side+ // because nothing the agent did caused it: the usual triggers are a+ // slow/blocked link to the API or a daemon that inherited no proxy+ // configuration (MUL-5370). Retryable, and cheap to retry: every+ // bundle that *did* arrive is cached on disk, so successive attempts+ // converge instead of re-downloading the whole set. Written by+ // taskRunFailureReason in daemon/daemon.go.+ ReasonSkillBundleUnavailable Reason = "skill_bundle_unavailable"+// Agent process side: failure surfaced by the agent CLI / SDK as// an error string. Classify(rawError) is responsible for picking// the right sub-reason from the string. IsAgentError returns true@@ -174,7 +186,7 @@ const (ReasonAgentUnknown Reason = "agent_error.unknown")-// allReasons is the canonical ordered list of the 21 reasons. Order is+// allReasons is the canonical ordered list of the 22 reasons. Order is// stable so callers (e.g. Prometheus collectors that pre-warm series via// AllReasons) can build deterministic label sets across restarts.//@@ -192,6 +204,7 @@ var allReasons = []Reason{ReasonIterationLimit,ReasonAgentBlocked,ReasonAPIInvalidRequest,+ ReasonSkillBundleUnavailable,// Agent process side: provider errors.ReasonAgentProviderAuthOrAccess,@@ -231,7 +244,7 @@ func (r Reason) IsAgentError() bool {return strings.HasPrefix(string(r), agentErrorPrefix)}-// AllReasons returns the canonical 21 reasons in a stable order. The+// AllReasons returns the canonical 22 reasons in a stable order. The// caller MUST NOT mutate the returned slice; a copy is returned so// concurrent callers can append to their local copy without corrupting// the package-level fixture.diff --git a/server/pkg/taskfailure/failure_test.go b/server/pkg/taskfailure/failure_test.goindex 35ad2bd3cc..4f1a9a980d 100644--- a/server/pkg/taskfailure/failure_test.go+++ b/server/pkg/taskfailure/failure_test.go@@ -26,6 +26,7 @@ func TestReasonStringWireValues(t *testing.T) {{ReasonIterationLimit, "iteration_limit"},{ReasonAgentBlocked, "agent_blocked"},{ReasonAPIInvalidRequest, "api_invalid_request"},+ {ReasonSkillBundleUnavailable, "skill_bundle_unavailable"},// Agent-side.{ReasonAgentProviderAuthOrAccess, "agent_error.provider_auth_or_access"},{ReasonAgentProviderQuotaLimit, "agent_error.provider_quota_limit"},@@ -43,7 +44,7 @@ func TestReasonStringWireValues(t *testing.T) {{ReasonAgentUnknown, "agent_error.unknown"},}- if got, want := len(cases), 21; got != want {+ if got, want := len(cases), 22; got != want {t.Fatalf("constant count = %d, want %d (canonical taxonomy size)", got, want)}@@ -70,6 +71,7 @@ func TestIsAgentError(t *testing.T) {ReasonIterationLimit,ReasonAgentBlocked,ReasonAPIInvalidRequest,+ ReasonSkillBundleUnavailable,}for _, r := range platformSide {if r.IsAgentError() {@@ -110,8 +112,8 @@ func TestAllReasonsContents(t *testing.T) {t.Parallel()got := AllReasons()- if len(got) != 21 {- t.Fatalf("AllReasons() returned %d entries, want 21", len(got))+ if len(got) != 22 {+ t.Fatalf("AllReasons() returned %d entries, want 22", len(got))}seen := make(map[Reason]bool, len(got))@@ -128,8 +130,8 @@ func TestAllReasonsContents(t *testing.T) {}}- if platformCount != 7 {- t.Errorf("AllReasons(): platform-side count = %d, want 7", platformCount)+ if platformCount != 8 {+ t.Errorf("AllReasons(): platform-side count = %d, want 8", platformCount)}if agentCount != 14 {t.Errorf("AllReasons(): agent-side count = %d, want 14", agentCount)@@ -142,7 +144,7 @@ func TestAllReasonsContents(t *testing.T) {required := []Reason{ReasonQueuedExpired, ReasonRuntimeOffline, ReasonRuntimeRecovery,ReasonTimeout, ReasonIterationLimit, ReasonAgentBlocked,- ReasonAPIInvalidRequest,+ ReasonAPIInvalidRequest, ReasonSkillBundleUnavailable,ReasonAgentProviderAuthOrAccess, ReasonAgentProviderQuotaLimit,ReasonAgentProviderCapacityOrRateLimit, ReasonAgentProviderServerError,ReasonAgentProviderNetwork, ReasonAgentProcessFailure,