Skip to content

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

Go
11.8 KB
Raw Blame
// @vitest-environment jsdom

import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import {
  act,
  cleanup,
  fireEvent,
  render,
  screen,
} from "@testing-library/react";
import { I18nProvider } from "@multica/core/i18n/react";
import enCommon from "../../locales/en/common.json";
import enSettings from "../../locales/en/settings.json";

// wecom-scan-install-dialog.test.tsx — the QR install dialog.
//
// What matters here is the poll loop's shape: the QR only exists after a later
// poll (begin returns a session in `creating`), a terminal status stops polling,
// and a 404 mid-poll is terminal rather than an infinite retry on a dead session.

const mockBegin = vi.hoisted(() => vi.fn());
const mockStatus = vi.hoisted(() => vi.fn());
const mockInvalidate = vi.hoisted(() => vi.fn());
const mockToastSuccess = vi.hoisted(() => vi.fn());

// Hoisted with the mocks: vi.mock factories run before top-level declarations,
// so a plain class here would be referenced before initialization.
const FakeApiError = vi.hoisted(
  () =>
    class FakeApiError extends Error {
      status: number;
      body: unknown;
      constructor(status: number, message: string, body?: unknown) {
        super(message);
        this.status = status;
        this.body = body;
      }
    },
);

vi.mock("@tanstack/react-query", () => ({
  useQueryClient: () => ({ invalidateQueries: mockInvalidate }),
}));

vi.mock("@multica/core/wecom", () => ({
  wecomKeys: {
    installations: (wsId: string) => ["wecom", "installations", wsId],
  },
}));

vi.mock("@multica/core/api", () => ({
  api: { beginWecomInstall: mockBegin, getWecomInstallStatus: mockStatus },
  ApiError: FakeApiError,
  // Same contract as the real helper: the body's `code`, when there is one.
  errorCode: (e: unknown) =>
    e instanceof FakeApiError
      ? (e.body as { code?: string } | undefined)?.code
      : undefined,
}));

vi.mock("sonner", () => ({
  toast: { success: mockToastSuccess, error: vi.fn(), message: vi.fn() },
}));

// react-qr-code renders an <svg> that jsdom does not need; a stub keeps the
// assertion on "the QR is showing" rather than on its pixels.
vi.mock("react-qr-code", () => ({
  QRCode: ({ value }: { value: string }) => (
    <div data-testid="qr" data-value={value} />
  ),
}));

import { WecomChannelAuthorization } from "./wecom-channel-authorization";

const TEST_RESOURCES = { en: { common: enCommon, settings: enSettings } };

afterEach(() => {
  cleanup();
  vi.useRealTimers();
});

async function renderDialog(onClose = vi.fn()) {
  await act(async () => {
    render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <WecomChannelAuthorization
          wsId="workspace-1"
          agentId="agent-1"
          onClose={onClose}
        />
      </I18nProvider>,
    );
  });
}

async function advanceTime(milliseconds: number) {
  await act(() => vi.advanceTimersByTimeAsync(milliseconds));
}

beforeEach(() => {
  vi.useFakeTimers();
  vi.clearAllMocks();
  // jsdom has no crypto.randomUUID in every environment version.
  if (!globalThis.crypto?.randomUUID) {
    Object.defineProperty(globalThis, "crypto", {
      value: {
        ...globalThis.crypto,
        randomUUID: () => "11111111-1111-1111-1111-111111111111",
      },
      configurable: true,
    });
  }
});

describe("WecomChannelAuthorization", () => {
  it("shows the preparing state before the QR exists, then renders it", async () => {
    mockBegin.mockResolvedValue({
      session_id: "session-1",
      status: "creating",
      poll_interval_seconds: 1,
    });
    // The QR arrives on a later poll — begin never carries it.
    mockStatus
      .mockResolvedValueOnce({ status: "creating", poll_interval_seconds: 1 })
      .mockResolvedValue({
        status: "pending",
        qr_code_url: "https://work.weixin.qq.com/ai/qc/scan?scode=abc",
        expires_in_seconds: 240,
        poll_interval_seconds: 2,
      });

    await renderDialog();

    expect(screen.getByTestId("wecom-scan-starting")).toBeTruthy();
    await advanceTime(1000);
    expect(mockStatus).toHaveBeenCalledTimes(1);
    expect(screen.queryByTestId("qr")).toBeNull();
    await advanceTime(1000);
    const qr = screen.getByTestId("qr");
    expect(qr.getAttribute("data-value")).toContain("scode=abc");
    expect(screen.getByTestId("wecom-scan-expiry").textContent).toContain(
      "240",
    );
  });

  it("invalidates the installations cache and closes on success", async () => {
    const onClose = vi.fn();
    mockBegin.mockResolvedValue({
      session_id: "session-1",
      status: "creating",
      poll_interval_seconds: 1,
    });
    mockStatus.mockResolvedValue({
      status: "success",
      installation_id: "install-1",
      poll_interval_seconds: 2,
    });

    await renderDialog(onClose);
    await advanceTime(1000);

    expect(mockToastSuccess).toHaveBeenCalled();
    expect(mockInvalidate).toHaveBeenCalledWith({
      queryKey: ["wecom", "installations", "workspace-1"],
    });
    await advanceTime(799);
    expect(onClose).not.toHaveBeenCalled();
    await advanceTime(1);
    expect(onClose).toHaveBeenCalledTimes(1);
  });

  it("renders the reason for a terminal error and stops polling", async () => {
    mockBegin.mockResolvedValue({
      session_id: "session-1",
      status: "creating",
      poll_interval_seconds: 1,
    });
    mockStatus.mockResolvedValue({
      status: "error",
      error_reason: "expired",
      poll_interval_seconds: 2,
    });

    await renderDialog();
    await advanceTime(1000);

    const err = screen.getByTestId("wecom-scan-error");
    expect(err.textContent).toBe(enSettings.wecom.scan_error_expired);

    const callsAfterError = mockStatus.mock.calls.length;
    await advanceTime(6000);
    expect(mockStatus.mock.calls.length).toBe(callsAfterError);
  });

  // An unknown reason must still render copy rather than a blank panel.
  it("falls back to generic copy for an unrecognized error reason", async () => {
    mockBegin.mockResolvedValue({
      session_id: "session-1",
      status: "creating",
      poll_interval_seconds: 1,
    });
    mockStatus.mockResolvedValue({
      status: "error",
      error_reason: "some_future_reason",
      poll_interval_seconds: 2,
    });

    await renderDialog();
    await advanceTime(1000);

    const err = screen.getByTestId("wecom-scan-error");
    expect(err.textContent).toContain(
      enSettings.wecom.scan_error_internal_error,
    );
  });

  // The two ways a scanned bot fails to bind need different actions from the
  // admin: one bot is held elsewhere, the other exists in WeCom unconnected.
  it.each([
    ["installation_conflict", "scan_error_installation_conflict"],
    ["bind_failed", "scan_error_bind_failed"],
  ] as const)("renders its own copy for a %s bind", async (reason, key) => {
    mockBegin.mockResolvedValue({
      session_id: "session-1",
      status: "creating",
      poll_interval_seconds: 1,
    });
    mockStatus.mockResolvedValue({
      status: "error",
      error_reason: reason,
      poll_interval_seconds: 2,
    });

    await renderDialog();
    await advanceTime(1000);

    const err = screen.getByTestId("wecom-scan-error");
    expect(err.textContent).toBe(enSettings.wecom[key]);
  });

  // A 404 means the session is gone (purged, or never existed). Polling on would
  // trap the user watching a stale QR with no feedback.
  it("treats a 404 mid-poll as a lost session", async () => {
    mockBegin.mockResolvedValue({
      session_id: "session-1",
      status: "creating",
      poll_interval_seconds: 1,
    });
    mockStatus.mockRejectedValue(
      new FakeApiError(404, "install session not found"),
    );

    await renderDialog();
    await advanceTime(1000);

    const err = screen.getByTestId("wecom-scan-error");
    expect(err.textContent).toContain(enSettings.wecom.scan_error_session_lost);
  });

  it("surfaces a 503 begin as the unconfigured reason", async () => {
    mockBegin.mockRejectedValue(
      new FakeApiError(503, "wecom scan install not enabled"),
    );

    await renderDialog();

    const err = screen.getByTestId("wecom-scan-error");
    expect(err.textContent).toContain(
      enSettings.wecom.scan_error_integration_unconfigured,
    );
    // Nothing to poll when begin never produced a session.
    expect(mockStatus).not.toHaveBeenCalled();
  });

  it("starts a brand-new session on retry", async () => {
    mockBegin.mockResolvedValue({
      session_id: "session-1",
      status: "creating",
      poll_interval_seconds: 1,
    });
    mockStatus.mockResolvedValue({
      status: "error",
      error_reason: "expired",
      poll_interval_seconds: 2,
    });

    await renderDialog();
    await advanceTime(1000);
    expect(screen.getByTestId("wecom-scan-error")).toBeTruthy();

    const beginCalls = mockBegin.mock.calls.length;
    await act(async () => {
      fireEvent.click(screen.getByTestId("wecom-scan-retry"));
    });
    expect(mockBegin.mock.calls.length).toBe(beginCalls + 1);
    // A fresh idempotency key, or "get a new code" would replay the expired
    // session instead of starting over.
    const firstKey = mockBegin.mock.calls[0]?.[2];
    const secondKey = mockBegin.mock.calls[beginCalls]?.[2];
    expect(firstKey).toBeTruthy();
    expect(secondKey).toBeTruthy();
    expect(secondKey).not.toBe(firstKey);
  });

  // A refused begin is told apart by its code and shown in the admin's own
  // words; the server's English sentence never reaches the dialog.
  it.each([
    [409, "wecom_agent_already_connected", "scan_error_already_connected"],
    [429, "wecom_scan_install_rate_limited", "scan_error_rate_limited"],
    [
      503,
      "wecom_scan_install_unavailable",
      "scan_error_integration_unconfigured",
    ],
  ] as const)(
    "shows a %i %s begin refusal as %s",
    async (status, code, key) => {
      const sentence = "the server's own English sentence";
      mockBegin.mockRejectedValue(
        new FakeApiError(status, sentence, { error: sentence, code }),
      );

      await renderDialog();

      const err = screen.getByTestId("wecom-scan-error");
      expect(err.textContent).toBe(enSettings.wecom[key]);
      expect(screen.queryByText(sentence, { exact: false })).toBeNull();
      expect(mockStatus).not.toHaveBeenCalled();
    },
  );

  it("reports a malformed begin response as an error instead of polling forever", async () => {
    // parseWithFallback degrades an unparseable body to an empty session id.
    mockBegin.mockResolvedValue({
      session_id: "",
      status: "error",
      poll_interval_seconds: 1,
    });

    await renderDialog();

    expect(screen.getByTestId("wecom-scan-error")).toBeTruthy();
    expect(mockStatus).not.toHaveBeenCalled();
  });

  // crypto.randomUUID is SecureContext-gated: it is simply absent over plain
  // HTTP. A self-hosted deployment on http:// is the ordinary case, and minting
  // the idempotency key through it threw inside the begin try-block, so the
  // dialog showed "something went wrong" and never called the API at all.
  it("still begins the install where crypto.randomUUID is unavailable", async () => {
    const realCrypto = globalThis.crypto;
    // A non-secure context keeps getRandomValues and loses randomUUID.
    vi.stubGlobal("crypto", {
      getRandomValues: (b: Uint8Array<ArrayBuffer>) =>
        realCrypto.getRandomValues(b),
    });
    try {
      mockBegin.mockResolvedValue({
        session_id: "S1",
        status: "creating",
        poll_interval_seconds: 1,
      });
      mockStatus.mockResolvedValue({
        status: "pending",
        qr_code_url: "https://work.weixin.qq.com/qr",
        poll_interval_seconds: 1,
      });

      await renderDialog();

      expect(mockBegin).toHaveBeenCalled();
      const key = mockBegin.mock.calls[0]?.[2];
      expect(typeof key).toBe("string");
      expect(key).toBeTruthy();
      expect(screen.queryByTestId("wecom-scan-error")).toBeNull();
    } finally {
      vi.stubGlobal("crypto", realCrypto);
    }
  });
});