Skip to content

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

Go
11.0 KB
Raw Blame
// @vitest-environment node
import type { TFunction } from "i18next";
import { createI18n } from "@multica/core/i18n/react";
import type { SupportedLocale } from "@multica/core/i18n";
import { describe, expect, it } from "vitest";
import enAgents from "../../../locales/en/agents.json";
import frAgents from "../../../locales/fr/agents.json";
import esAgents from "../../../locales/es/agents.json";
import jaAgents from "../../../locales/ja/agents.json";
import koAgents from "../../../locales/ko/agents.json";
import zhHansAgents from "../../../locales/zh-Hans/agents.json";
import ruAgents from "../../../locales/ru/agents.json";
import zhHantAgents from "../../../locales/zh-Hant/agents.json";
// Generated from server/pkg/taskfailure AllReasons; the Go test
// TestClientFailureReasonFixture keeps it in step with the backend.
import serverFailureReasons from "./test-fixtures/server-failure-reasons.json";

import {
  FAILURE_REASON_I18N_KEYS,
  cancellationActorLabel,
  cancelReasonLabel,
  failureNeedsAction,
  failureReasonLabel,
  isCancelledOutcome,
  runOutcomeLabel,
} from "./task-failure";

const AGENT_RESOURCES = {
  en: enAgents,
  "zh-Hans": zhHansAgents,
  "zh-Hant": zhHantAgents,
  ja: jaAgents,
  ko: koAgents,
  fr: frAgents,
  es: esAgents,
  ru: ruAgents,
} as const;

function fixedT(locale: SupportedLocale): TFunction<"agents"> {
  const resources =
    locale === "en"
      ? { en: { agents: enAgents } }
      : {
          en: { agents: enAgents },
          [locale]: { agents: AGENT_RESOURCES[locale] },
        };
  const i18n = createI18n(locale, resources);
  return i18n.getFixedT(locale, "agents") as TFunction<"agents">;
}

const enT = fixedT("en");

describe("FAILURE_REASON_I18N_KEYS", () => {
  // Every reason the backend can write needs a label, otherwise the run row
  // shows the raw code.
  it("has a label for every reason the server taxonomy defines", () => {
    const missing = serverFailureReasons.filter(
      (reason) => !Object.prototype.hasOwnProperty.call(FAILURE_REASON_I18N_KEYS, reason),
    );
    expect(missing).toEqual([]);
  });

  it("labels a run whose process cleanup was not confirmed", () => {
    expect(failureReasonLabel("cleanup_unconfirmed", enT)).toBe(
      "Couldn't confirm the agent process stopped",
    );
    expect(failureReasonLabel("cleanup_blocked", enT)).toBe(
      "Previous run may be active; rerun manually",
    );
  });
});

describe("cancellationActorLabel", () => {
  it("names the member that cancelled a run", () => {
    expect(cancellationActorLabel({
      status: "cancelled",
      cancelled_by: { type: "member", name: "Jiayuan" },
    }, enT)).toBe("Cancelled by Jiayuan");
  });

  it("localizes system cancellation and preserves the legacy fallback", () => {
    expect(cancellationActorLabel({
      status: "cancelled",
      cancelled_by: { type: "system" },
    }, fixedT("zh-Hans"))).toBe("已由系统取消");
    expect(cancellationActorLabel({
      status: "cancelled",
      cancelled_by: { type: "member", name: "Jiayuan" },
    }, fixedT("zh-Hans"))).toBe("已由 Jiayuan 取消");
    expect(cancellationActorLabel({ status: "cancelled" }, enT)).toBeNull();
  });

  it("preserves the legacy fallback for an unknown actor type", () => {
    expect(cancellationActorLabel({
      status: "cancelled",
      cancelled_by: { type: "future_actor", name: "Someone" },
    }, enT)).toBeNull();
  });
});

// cancelReasonLabel decides which cancelled rows explain themselves. The rule
// it must hold: a SERVER-cancelled row (persisted reason) reads like a failed
// row. Actor provenance is handled independently by cancellationActorLabel.
describe("cancelReasonLabel", () => {
  it("localizes access revocation without calling the cancelled run a failure", () => {
    for (const locale of Object.keys(AGENT_RESOURCES) as SupportedLocale[]) {
      expect(cancelReasonLabel({ status: "cancelled", failure_reason: "runtime_access_revoked" }, fixedT(locale)))
        .toBe(AGENT_RESOURCES[locale].task_failure.reasons.runtime_access_revoked);
    }
  });
  it("returns null for a user-initiated cancel", () => {
    expect(
      cancelReasonLabel(
        { status: "cancelled", error: null, failure_reason: null },
        enT,
      ),
    ).toBeNull();
  });

  it("only ever labels cancelled rows — failed rows have their own path", () => {
    expect(
      cancelReasonLabel(
        { status: "failed", error: "boom", failure_reason: "timeout" },
        enT,
      ),
    ).toBeNull();
  });

  it("labels the worktree claim gate's cancellation", () => {
    expect(
      cancelReasonLabel(
        {
          status: "cancelled",
          error: "worktree mode needs daemon version 0.4.24 or newer",
          failure_reason: "local_directory_error",
        },
        enT,
      ),
    ).toBe("Local directory error");
  });

  it("localizes a generic system cancellation in every supported locale", () => {
    const expected: Record<SupportedLocale, string> = {
      en: "Cancelled by the system",
      "zh-Hans": "已由系统取消",
      "zh-Hant": "已由系統取消",
      ja: "システムによってキャンセルされました",
      ko: "시스템에서 취소함",
      fr: "Annulée par le système",
      es: "Cancelada por el sistema",
      ru: "Отменено системой",
    };

    for (const locale of Object.keys(expected) as SupportedLocale[]) {
      expect(
        cancelReasonLabel(
          {
            status: "cancelled",
            error: "work preserved in the worktree at /env/worktree",
            failure_reason: null,
          },
          fixedT(locale),
        ),
      ).toBe(expected[locale]);
    }
  });

  it.each(["system", "member", "agent"])(
    "does not add a generic system reason when %s actor provenance exists",
    (type) => {
      expect(cancelReasonLabel({
        status: "cancelled",
        error: "automatic cancellation",
        failure_reason: null,
        cancelled_by: { type },
      }, enT)).toBeNull();
    },
  );
});

describe("failureReasonLabel", () => {
  it("renders every known reason through i18n in every supported locale", () => {
    for (const locale of Object.keys(AGENT_RESOURCES) as SupportedLocale[]) {
      const t = fixedT(locale);
      for (const reason of Object.keys(FAILURE_REASON_I18N_KEYS)) {
        const label = failureReasonLabel(reason, t);
        expect(label, `${locale}: ${reason}`).not.toBe(reason);
        expect(label, `${locale}: ${reason}`).not.toContain("task_failure.");
        expect(label, `${locale}: ${reason}`).not.toBe("");
      }
    }
  });

  it("covers platform reasons added after the original hardcoded map", () => {
    expect(failureReasonLabel("invalid_task_identity", enT)).toBe(
      "Run identity mismatch",
    );
  });

  it("maps runtime access denial to actionable recovery copy", () => {
    const label = failureReasonLabel("runtime_access_denied", enT);
    expect(label).toMatch(/make the runtime public/i);
    expect(label).toMatch(/rebind\/copy/i);
    expect(label).not.toBe("Task identity mismatch");
  });

  it("covers operational reasons emitted outside the canonical taxonomy", () => {
    expect(failureReasonLabel("agent_fallback_message", enT)).toBe(
      "Agent couldn't produce a valid reply",
    );
    expect(failureReasonLabel("idle_watchdog", enT)).toBe(
      "Agent stopped after inactivity",
    );
    expect(failureReasonLabel("cancelled", enT)).toBe(
      "Cancelled by the system",
    );
  });

  // MUL-9665: a project's linked folder that was deleted used to read as the
  // generic "Local directory error", which never said the folder was gone.
  it("names a deleted project folder instead of a generic local directory error", () => {
    expect(failureReasonLabel("local_directory_missing", enT)).toBe(
      "Project's local folder no longer exists",
    );
    expect(failureReasonLabel("local_directory_missing", fixedT("zh-Hans"))).toBe(
      "项目的本地文件夹已不存在",
    );
  });

  it("localizes the legacy user cancellation value retained by the service", () => {
    expect(failureReasonLabel("user_cancelled", enT)).toBe(
      "Cancelled by user",
    );
  });

  it("uses native copy for representative refined reasons", () => {
    expect(
      failureReasonLabel(
        "agent_error.provider_quota_limit",
        fixedT("zh-Hans"),
      ),
    ).toBe("提供方额度已用尽");
    expect(
      failureReasonLabel("agent_error.context_overflow", fixedT("ja")),
    ).toBe("コンテキストウィンドウを超過しました");
    expect(
      failureReasonLabel("agent_error.missing_config", fixedT("ko")),
    ).toBe("API 키 또는 설정 누락");
  });

  it("still falls back to the raw wire value for unknown reasons", () => {
    for (const locale of Object.keys(AGENT_RESOURCES) as SupportedLocale[]) {
      expect(failureReasonLabel("brand_new_reason", fixedT(locale))).toBe(
        "brand_new_reason",
      );
    }
  });

  it.each(["constructor", "toString", "__proto__"])(
    "treats inherited Object property %s as an unknown wire value",
    (reason) => {
      expect(failureReasonLabel(reason, enT)).toBe(reason);
    },
  );

  it("returns null when the server supplied no reason", () => {
    expect(failureReasonLabel(null, enT)).toBeNull();
    expect(failureReasonLabel(undefined, enT)).toBeNull();
    expect(failureReasonLabel("", enT)).toBeNull();
  });
});

describe("run outcome", () => {
  it("reads a failed row with a cancellation reason as cancelled", () => {
    expect(isCancelledOutcome({ status: "failed", failure_reason: "cancelled" })).toBe(true);
    expect(isCancelledOutcome({ status: "failed", failure_reason: "user_cancelled" })).toBe(true);
    expect(isCancelledOutcome({ status: "cancelled" })).toBe(true);
    expect(isCancelledOutcome({ status: "failed", failure_reason: "timeout" })).toBe(false);
    expect(isCancelledOutcome({ status: "failed" })).toBe(false);
  });

  it("flags only failures that need a configuration change", () => {
    expect(failureNeedsAction({ status: "failed", failure_reason: "agent_error.provider_auth_or_access" })).toBe(true);
    expect(failureNeedsAction({ status: "failed", failure_reason: "runtime_access_denied" })).toBe(true);
    expect(failureNeedsAction({ status: "failed", failure_reason: "agent_error.provider_capacity_or_rate_limit" })).toBe(false);
    expect(failureNeedsAction({ status: "cancelled", failure_reason: "runtime_access_denied" })).toBe(false);
  });

  it("labels a run once: reason first, then who cancelled it", () => {
    expect(runOutcomeLabel({ status: "failed", failure_reason: "cancelled" }, enT)).toBe("Cancelled by the system");
    expect(runOutcomeLabel({ status: "failed", failure_reason: null }, enT)).toBeNull();
    expect(runOutcomeLabel({
      status: "cancelled", failure_reason: "queued_expired", cancelled_by: { type: "system" },
    }, enT)).toBe("Expired in queue");
    expect(runOutcomeLabel({
      status: "cancelled", cancelled_by: { type: "member", name: "Jiayuan" },
    }, enT)).toBe("Cancelled by Jiayuan");
    expect(runOutcomeLabel({ status: "cancelled" }, enT)).toBeNull();
  });
});