Skip to content

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io

23.0 KB
Raw Blame
import { act, fireEvent, render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { TFunction } from "i18next";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { CopilotAuthSection } from "@/components/providers/forms/CopilotAuthSection";
import { CodexOAuthSection } from "@/components/providers/forms/CodexOAuthSection";
import { XaiOAuthSection } from "@/components/providers/forms/XaiOAuthSection";

const mocks = vi.hoisted(() => ({
  useCopilotAuth: vi.fn(),
  useCodexOauth: vi.fn(),
  useXaiOauth: vi.fn(),
}));

vi.mock("@/lib/query/accountPlans", () => ({
  useAccountQuotaPlans: () => ({}),
}));

vi.mock("@/components/providers/forms/hooks/useCopilotAuth", () => ({
  useCopilotAuth: mocks.useCopilotAuth,
}));
vi.mock("@/components/providers/forms/hooks/useCodexOauth", () => ({
  useCodexOauth: mocks.useCodexOauth,
}));
vi.mock("@/components/providers/forms/hooks/useXaiOauth", () => ({
  useXaiOauth: mocks.useXaiOauth,
}));
// 「N 个供应商在用」要读供应商列表(React Query);这里不关心,给空
vi.mock("@/components/providers/forms/hooks/useManagedAccountUsers", () => ({
  useManagedAccountUsers: () => () => [],
}));
// 额度各自走 React Query;这里只看账号区本身
vi.mock("@/components/settings/auth/AccountQuota", async (importOriginal) => {
  const actual =
    await importOriginal<
      typeof import("@/components/settings/auth/AccountQuota")
    >();
  return {
    ...actual,
    CopilotAccountQuota: ({ accountId }: { accountId: string }) => (
      <span data-testid="copilot-quota">{accountId}</span>
    ),
    XaiAccountQuota: ({ accountId }: { accountId: string }) => (
      <span data-testid="xai-quota">{accountId}</span>
    ),
  };
});

const baseAuth = () => ({
  accounts: [],
  defaultAccountId: null,
  migrationError: null,
  isStatusSuccess: true,
  isStatusError: false,
  hasAnyAccount: false,
  isAuthenticated: false,
  pollingState: "idle" as const,
  deviceCode: null,
  error: null,
  isPolling: false,
  isAddingAccount: false,
  isRemovingAccount: false,
  isSettingDefaultAccount: false,
  addAccount: vi.fn(),
  reauthAccount: vi.fn(),
  retryAuth: vi.fn(),
  removeAccount: vi.fn(),
  setDefaultAccount: vi.fn(),
  cancelAuth: vi.fn(),
  logout: vi.fn(),
  refetchStatus: vi.fn(),
});

const account = (
  id: string,
  login: string,
  extra: Record<string, unknown> = {},
) => ({
  id,
  provider: "github_copilot",
  login,
  avatar_url: null,
  authenticated_at: 0,
  is_default: false,
  github_domain: "github.com",
  reauth_required: false,
  requires_reauth: false,
  ...extra,
});

describe("Auth Center account groups", () => {
  beforeEach(() => {
    mocks.useCopilotAuth.mockReturnValue(baseAuth());
    mocks.useCodexOauth.mockReturnValue(baseAuth());
    mocks.useXaiOauth.mockReturnValue(baseAuth());
  });

  it("asks for the GitHub deployment before signing in to Copilot", async () => {
    const user = userEvent.setup();
    const auth = {
      ...baseAuth(),
      hasAnyAccount: true,
      accounts: [
        account("octocat", "octocat"),
        account("corp", "corp-dev", { github_domain: "ghe.example.com" }),
      ],
      defaultAccountId: "octocat",
    };
    mocks.useCopilotAuth.mockReturnValue(auth);
    render(<CopilotAuthSection />);

    // 第二行写部署位置;企业版带「Enterprise Server」
    expect(
      screen.getByText(/ghe\.example\.com · Enterprise Server/),
    ).toBeInTheDocument();
    expect(screen.getAllByTestId("copilot-quota")).toHaveLength(2);

    await user.click(screen.getByRole("button", { name: "添加账号" }));
    const deploy = screen.getByRole("group", { name: "GitHub 部署类型" });
    await user.click(
      within(deploy).getByRole("button", { name: "GitHub Enterprise Server" }),
    );

    // 企业域名没填:不登录,字段下面写怎么改
    await user.click(screen.getByRole("button", { name: "使用 GitHub 登录" }));
    expect(auth.addAccount).not.toHaveBeenCalled();
    expect(
      screen.getByText("先填企业域名,例如 company.ghe.com"),
    ).toBeInTheDocument();

    await user.type(
      screen.getByPlaceholderText("例如:company.ghe.com"),
      "https://company.ghe.com/",
    );
    expect(mocks.useCopilotAuth).toHaveBeenLastCalledWith("company.ghe.com");
    await user.click(screen.getByRole("button", { name: "使用 GitHub 登录" }));
    expect(auth.addAccount).toHaveBeenCalledTimes(1);
  });

  it("keeps Copilot re-login out of the account menu", async () => {
    const user = userEvent.setup();
    mocks.useCopilotAuth.mockReturnValue({
      ...baseAuth(),
      hasAnyAccount: true,
      accounts: [account("octocat", "octocat")],
      defaultAccountId: "octocat",
    });
    render(<CopilotAuthSection />);

    // 标题行没有 ⋯,只有账号行有
    expect(
      screen.queryByRole("button", { name: "GitHub Copilot 的更多操作" }),
    ).not.toBeInTheDocument();
    await user.click(
      screen.getByRole("button", { name: "octocat 的更多操作" }),
    );
    expect(
      await screen.findByRole("menuitem", { name: "删除账号…" }),
    ).toBeInTheDocument();
    expect(
      screen.queryByRole("menuitem", { name: "重新登录" }),
    ).not.toBeInTheDocument();
    expect(
      screen.queryByRole("menuitem", { name: "设为默认" }),
    ).not.toBeInTheDocument();
  });

  it("offers a retry when the account status fails to load", async () => {
    const user = userEvent.setup();
    const auth = { ...baseAuth(), isStatusSuccess: false, isStatusError: true };
    mocks.useCopilotAuth.mockReturnValue(auth);
    render(<CopilotAuthSection />);

    expect(
      screen.getByText("无法加载 GitHub Copilot 账号状态,请重试。"),
    ).toBeInTheDocument();
    // 页面一打开就在的提示不用 role=alert
    expect(screen.queryByRole("alert")).not.toBeInTheDocument();
    await user.click(screen.getByRole("button", { name: "重试" }));
    expect(auth.refetchStatus).toHaveBeenCalledTimes(1);
  });

  it("keeps the add button in the header when there are no accounts", async () => {
    const user = userEvent.setup();
    const auth = baseAuth();
    mocks.useCodexOauth.mockReturnValue(auth);
    render(<CodexOAuthSection showAccountQuota />);

    expect(screen.getByText("还没有登录 ChatGPT 账号。")).toBeInTheDocument();
    await user.click(screen.getByRole("button", { name: "添加账号" }));
    expect(auth.addAccount).toHaveBeenCalledTimes(1);
  });

  it("re-signs an expired xAI account and hides its quota", async () => {
    const user = userEvent.setup();
    const auth = {
      ...baseAuth(),
      hasAnyAccount: true,
      isAuthenticated: true,
      accounts: [
        account("ok", "[email protected]", { provider: "xai_oauth" }),
        account("expired", "[email protected]", {
          provider: "xai_oauth",
          requires_reauth: true,
        }),
      ],
      defaultAccountId: "ok",
    };
    mocks.useXaiOauth.mockReturnValue(auth);
    render(<XaiOAuthSection mode="manage" />);

    expect(
      screen.getAllByTestId("xai-quota").map((q) => q.textContent),
    ).toEqual(["ok"]);
    expect(screen.getByText("需要重新登录")).toBeInTheDocument();
    expect(
      screen.getByText("登录凭据已失效,用到它的供应商无法使用"),
    ).toBeInTheDocument();

    // xAI 不能指定账号重新登录:发起一次普通登录(同一个账号登录会替换旧凭据)
    await user.click(screen.getByRole("button", { name: "重新登录" }));
    expect(auth.addAccount).toHaveBeenCalledTimes(1);
  });

  it("uses the form layout when a provider form passes onAccountSelect", () => {
    mocks.useXaiOauth.mockReturnValue({
      ...baseAuth(),
      hasAnyAccount: true,
      isAuthenticated: true,
      accounts: [account("ok", "[email protected]", { provider: "xai_oauth" })],
      defaultAccountId: "ok",
    });
    render(
      <XaiOAuthSection selectedAccountId={null} onAccountSelect={vi.fn()} />,
    );

    expect(screen.getByRole("combobox")).toBeInTheDocument();
    expect(screen.queryByTestId("xai-quota")).not.toBeInTheDocument();
  });

  it("forwards helpSide and updated help copy to HelpTip", async () => {
    const user = userEvent.setup();
    const { rerender } = render(<CopilotAuthSection helpSide="top" />);

    await user.click(
      screen.getByRole("button", { name: "GitHub Copilot 账号怎么用" }),
    );
    const copilotTip = await screen.findByRole("tooltip");
    expect(copilotTip).toHaveAttribute("data-side", "top");
    expect(copilotTip).toHaveTextContent(/Codex/);
    expect(copilotTip).toHaveTextContent(/Copilot CLI/);

    rerender(<CodexOAuthSection showAccountQuota helpSide="top" />);
    await user.click(
      screen.getByRole("button", { name: "ChatGPT 账号怎么用" }),
    );
    expect(await screen.findByRole("tooltip")).toHaveAttribute(
      "data-side",
      "top",
    );

    rerender(<XaiOAuthSection mode="manage" helpSide="bottom" />);
    await user.click(screen.getByRole("button", { name: "xAI 账号怎么用" }));
    const xaiTip = await screen.findByRole("tooltip");
    expect(xaiTip).toHaveAttribute("data-side", "bottom");
    expect(xaiTip).toHaveTextContent(/Grok Build/);
  });

  it("retries AccountAvatar up to twice with backoff and resets when avatarUrl changes", () => {
    vi.useFakeTimers();
    try {
      const renderWithAvatar = (avatarUrl: string | null) => ({
        ...baseAuth(),
        hasAnyAccount: true,
        accounts: [
          account("octocat", "octocat", {
            avatar_url: avatarUrl,
          }),
        ],
        defaultAccountId: "octocat",
      });

      // 空白字符串视为无头像,直接回退首字母
      mocks.useCopilotAuth.mockReturnValue(renderWithAvatar("   "));
      const { container, rerender, unmount } = render(<CopilotAuthSection />);
      const avatarImg = () => container.querySelector(".auth-account-row img");
      expect(avatarImg()).toBeNull();
      expect(screen.getByText("O")).toBeInTheDocument();

      mocks.useCopilotAuth.mockReturnValue(
        renderWithAvatar("https://avatars.example.com/u/1?v=1"),
      );
      rerender(<CopilotAuthSection />);

      const firstImg = avatarImg();
      expect(firstImg?.getAttribute("src")).toBe(
        "https://avatars.example.com/u/1?v=1",
      );

      // 第 1 次加载失败:先回退首字母,1000ms 后静默发起第 1 次重试
      fireEvent.error(firstImg!);
      expect(avatarImg()).toBeNull();
      expect(screen.getByText("O")).toBeInTheDocument();

      act(() => vi.advanceTimersByTime(999));
      expect(avatarImg()).toBeNull();
      act(() => vi.advanceTimersByTime(1));
      const secondImg = avatarImg();
      expect(secondImg).not.toBeNull();
      expect(secondImg).not.toBe(firstImg);

      // 第 2 次失败:3000ms 后发起第 2 次重试
      fireEvent.error(secondImg!);
      expect(avatarImg()).toBeNull();
      act(() => vi.advanceTimersByTime(2999));
      expect(avatarImg()).toBeNull();
      act(() => vi.advanceTimersByTime(1));
      const thirdImg = avatarImg();
      expect(thirdImg).not.toBeNull();
      expect(thirdImg).not.toBe(secondImg);

      // 第 3 次失败(2 次重试已耗尽):保持首字母回退,不再继续安排定时器
      fireEvent.error(thirdImg!);
      expect(avatarImg()).toBeNull();
      expect(vi.getTimerCount()).toBe(0);
      act(() => vi.advanceTimersByTime(60_000));
      expect(avatarImg()).toBeNull();

      // avatarUrl 变更后立刻重置失败状态并加载新地址
      mocks.useCopilotAuth.mockReturnValue(
        renderWithAvatar("https://avatars.example.com/u/1?v=2"),
      );
      rerender(<CopilotAuthSection />);
      expect(avatarImg()?.getAttribute("src")).toBe(
        "https://avatars.example.com/u/1?v=2",
      );

      // 退避等待中途切换回旧地址(A -> B(waiting) -> A):立刻取消旧定时器并重新尝试 A
      fireEvent.error(avatarImg()!);
      expect(avatarImg()).toBeNull();
      mocks.useCopilotAuth.mockReturnValue(
        renderWithAvatar("https://avatars.example.com/u/1?v=1"),
      );
      rerender(<CopilotAuthSection />);
      const reloaded = avatarImg();
      expect(reloaded?.getAttribute("src")).toBe(
        "https://avatars.example.com/u/1?v=1",
      );
      expect(vi.getTimerCount()).toBe(0);
      act(() => vi.advanceTimersByTime(5000));
      expect(avatarImg()).toBe(reloaded);

      // 退避等待期间卸载不残留定时器
      fireEvent.error(reloaded!);
      expect(vi.getTimerCount()).toBe(1);
      unmount();
      expect(vi.getTimerCount()).toBe(0);
      act(() => vi.advanceTimersByTime(10_000));
    } finally {
      vi.useRealTimers();
    }
  });

  it("retries CopilotAccountAvatar with backoff and resets on avatarUrl change", () => {
    vi.useFakeTimers();
    try {
      const renderSelect = (avatarUrl: string | null) => ({
        ...baseAuth(),
        hasAnyAccount: true,
        accounts: [
          account("octocat", "octocat", {
            avatar_url: avatarUrl,
          }),
        ],
        defaultAccountId: "octocat",
      });

      mocks.useCopilotAuth.mockReturnValue(
        renderSelect("https://avatars.example.com/u/2?v=1"),
      );
      const { rerender } = render(
        <CopilotAuthSection
          mode="select"
          selectedAccountId="octocat"
          onAccountSelect={vi.fn()}
        />,
      );

      const initialImg = screen.getByAltText("octocat");
      expect(initialImg.getAttribute("src")).toBe(
        "https://avatars.example.com/u/2?v=1",
      );

      // 2 次退避重试均失败后停留在回退图标,直到 avatarUrl 变化再重置
      fireEvent.error(initialImg);
      expect(screen.queryByAltText("octocat")).not.toBeInTheDocument();

      act(() => vi.advanceTimersByTime(1000));
      const retry1 = screen.getByAltText("octocat");
      fireEvent.error(retry1);
      act(() => vi.advanceTimersByTime(3000));
      const retry2 = screen.getByAltText("octocat");
      fireEvent.error(retry2);
      act(() => vi.advanceTimersByTime(10_000));
      expect(screen.queryByAltText("octocat")).not.toBeInTheDocument();

      mocks.useCopilotAuth.mockReturnValue(
        renderSelect("https://avatars.example.com/u/2?v=2"),
      );
      rerender(
        <CopilotAuthSection
          mode="select"
          selectedAccountId="octocat"
          onAccountSelect={vi.fn()}
        />,
      );
      const nextImg = screen.getByAltText("octocat");
      expect(nextImg.getAttribute("src")).toBe(
        "https://avatars.example.com/u/2?v=2",
      );

      // 退避等待期间切换 URL 会立刻取消退避并加载新地址
      fireEvent.error(nextImg);
      expect(screen.queryByAltText("octocat")).not.toBeInTheDocument();
      mocks.useCopilotAuth.mockReturnValue(
        renderSelect("https://avatars.example.com/u/2?v=3"),
      );
      rerender(
        <CopilotAuthSection
          mode="select"
          selectedAccountId="octocat"
          onAccountSelect={vi.fn()}
        />,
      );
      const switchedImg = screen.getByAltText("octocat");
      expect(switchedImg.getAttribute("src")).toBe(
        "https://avatars.example.com/u/2?v=3",
      );
      act(() => vi.advanceTimersByTime(5000));
      expect(screen.getByAltText("octocat")).toBe(switchedImg);
    } finally {
      vi.useRealTimers();
    }
  });
});

describe("subscriptionQuotaState", () => {
  const t = ((key: string, opts?: { defaultValue?: string }) =>
    opts?.defaultValue ?? key) as unknown as TFunction;

  it("writes remaining quota per tier and flags a failed query", async () => {
    const { subscriptionQuotaState } = await import(
      "@/components/settings/auth/AccountQuota"
    );
    const ok = subscriptionQuotaState(
      t,
      {
        tool: "codex",
        credentialStatus: "valid",
        credentialMessage: null,
        success: true,
        tiers: [
          { name: "five_hour", utilization: 38, resetsAt: null },
          { name: "seven_day", utilization: 95, resetsAt: null },
        ],
        extraUsage: null,
        error: null,
        queriedAt: 1,
      },
      false,
      "zh",
    );
    expect(ok?.kind).toBe("rows");
    if (ok?.kind === "rows") {
      expect(ok.rows.map((row) => [row.line.left, row.line.tone])).toEqual([
        [62, "normal"],
        [5, "warning"],
      ]);
    }

    expect(
      subscriptionQuotaState(
        t,
        {
          tool: "codex",
          credentialStatus: "valid",
          credentialMessage: null,
          success: false,
          tiers: [],
          extraUsage: null,
          error: "HTTP 500",
          queriedAt: 1,
        },
        false,
        "zh",
      ),
    ).toEqual({ kind: "failed", reason: "HTTP 500" });
    expect(subscriptionQuotaState(t, undefined, true, "zh")).toEqual({
      kind: "loading",
    });
  });
});

describe("AccountQuotaColumn", () => {
  it("opens the saved resets to list when each one expires", async () => {
    const user = userEvent.setup();
    const { AccountQuotaColumn } = await import(
      "@/components/settings/auth/AccountQuota"
    );
    render(
      <AccountQuotaColumn
        login="[email protected]"
        loading={false}
        onRefresh={vi.fn()}
        state={{
          kind: "rows",
          rows: [
            {
              label: "重置",
              line: {
                key: "reset_credits",
                text: "重置剩余 3 次",
                value: "剩余 3 次",
                caption: "10月6日到期",
                tone: "warning",
                left: Infinity,
                breakdown: {
                  title: "存下的限额重置",
                  openLabel: "查看 3 次重置各自的到期时间",
                  items: [
                    {
                      key: "a",
                      label: "10月6日",
                      hint: "2d0h后",
                      value: "2 次",
                      tone: "warning",
                    },
                    {
                      key: "b",
                      label: "不会过期",
                      value: "1 次",
                      tone: "normal",
                    },
                  ],
                },
              },
            },
          ],
        }}
      />,
    );

    expect(screen.queryByText("存下的限额重置")).not.toBeInTheDocument();
    await user.click(
      screen.getByRole("button", { name: "查看 3 次重置各自的到期时间" }),
    );
    const dialog = await screen.findByRole("dialog", {
      name: "存下的限额重置",
    });
    expect(
      within(dialog)
        .getAllByRole("listitem")
        .map((item) => item.textContent),
    ).toEqual(["10月6日2d0h后2 次", "不会过期1 次"]);
  });

  it("caps static quota states and protects caption and value cells from overflowing", async () => {
    const { AccountQuotaColumn } = await import(
      "@/components/settings/auth/AccountQuota"
    );
    const { container, rerender } = render(
      <AccountQuotaColumn
        login="[email protected]"
        loading={false}
        onRefresh={vi.fn()}
        state={{ kind: "failed", reason: "HTTP 500 internal server error" }}
      />,
    );

    expect(container.querySelector(".auth-quota-col")).toHaveClass(
      "auth-quota-col-static",
    );
    expect(container.querySelector(".auth-quota-refresh")).toBeInTheDocument();

    rerender(
      <AccountQuotaColumn
        login="[email protected]"
        loading={false}
        onRefresh={vi.fn()}
        state={{
          kind: "rows",
          rows: [
            {
              label: "重置",
              line: {
                key: "reset_credits",
                text: "重置剩余 10 次",
                value: "重置剩余 10 次",
                caption: "2027年12月2日到期",
                tone: "normal",
                left: Infinity,
              },
            },
          ],
        }}
      />,
    );

    expect(container.querySelector(".auth-quota-col")).not.toHaveClass(
      "auth-quota-col-static",
    );
    const captionText = screen.getByText("2027年12月2日到期");
    expect(captionText).toHaveClass("min-w-0", "truncate");
    expect(captionText.parentElement).not.toHaveClass("shrink-0");
    const valueCell = screen.getByText("重置剩余 10 次");
    expect(valueCell).toHaveClass(
      "min-w-[var(--auth-quota-value)]",
      "whitespace-nowrap",
    );
    expect(valueCell).not.toHaveClass("truncate");
  });

  it("keeps long note text within the static column and exposes it via title", async () => {
    const { AccountQuotaColumn } = await import(
      "@/components/settings/auth/AccountQuota"
    );
    const longNote = "Wechsle zu diesem Konto, um sein Kontingent abzufragen";
    const { container, rerender } = render(
      <AccountQuotaColumn
        login="[email protected]"
        loading={false}
        onRefresh={vi.fn()}
        state={{ kind: "note", text: longNote }}
      />,
    );

    expect(container.querySelector(".auth-quota-col")).toHaveClass(
      "auth-quota-col-static",
    );
    const note = screen.getByText(longNote);
    expect(note).toHaveAttribute("title", longNote);
    expect(note).toHaveClass(
      "me-[calc(var(--auth-quota-reset)+var(--auth-quota-gap))]",
      "max-w-[calc(100%-var(--auth-quota-reset)-var(--auth-quota-gap))]",
      "truncate",
      "self-end",
    );
    expect(note).not.toHaveClass("max-w-full");

    rerender(
      <AccountQuotaColumn
        login="[email protected]"
        loading={false}
        onRefresh={vi.fn()}
        state={null}
        idle
      />,
    );

    expect(container.querySelector(".auth-quota-col")).toHaveClass(
      "auth-quota-col-static",
    );
    const idleNote = screen.getByText("quota.manualIdle");
    expect(idleNote).toHaveAttribute("title", "quota.manualIdle");
    expect(idleNote).toHaveClass(
      "me-[calc(var(--auth-quota-reset)+var(--auth-quota-gap))]",
      "max-w-[calc(100%-var(--auth-quota-reset)-var(--auth-quota-gap))]",
      "truncate",
      "self-end",
    );
    expect(idleNote).not.toHaveClass("max-w-full");
  });

  it("keeps the last-updated text while refreshing so the quota bar does not shift", async () => {
    const { QuotaRefreshCell } = await import(
      "@/components/settings/auth/AccountQuota"
    );
    const queriedAt = Date.now() - 11 * 24 * 60 * 60 * 1000;
    const { container, rerender } = render(
      <QuotaRefreshCell
        login="[email protected]"
        queriedAt={queriedAt}
        loading={false}
        onRefresh={vi.fn()}
      />,
    );
    const cell = container.querySelector(".auth-quota-refresh");
    const before = cell?.textContent;
    expect(before).toBe("usage.daysAgo");

    rerender(
      <QuotaRefreshCell
        login="[email protected]"
        queriedAt={queriedAt}
        loading
        onRefresh={vi.fn()}
      />,
    );
    // 刷新中只转圈,文字不换成「更新中…」,格子宽度不变
    expect(container.querySelector(".auth-quota-refresh")?.textContent).toBe(
      before,
    );
    const button = screen.getByRole("button", {
      name: "刷新 [email protected] 的额度",
    });
    expect(button).toHaveAttribute("aria-busy", "true");
    expect(button).toHaveAttribute("aria-disabled", "true");
  });
});