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

14.6 KB
Raw Blame
import type { ReactElement } from "react";
import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { WorkBuddyAccountSection } from "@/components/settings/auth/WorkBuddyAccountSection";

const mocks = vi.hoisted(() => ({
  useManagedAuth: vi.fn(),
  liveState: vi.fn(),
  importCurrent: vi.fn(),
  prepareNewLogin: vi.fn(),
  openApp: vi.fn(),
  setDefault: vi.fn(),
  quota: vi.fn(),
  toastSuccess: vi.fn(),
  toastError: vi.fn(),
  toastWarning: vi.fn(),
  toastInfo: vi.fn(),
}));

vi.mock("@/lib/toast", () => ({
  toast: {
    success: mocks.toastSuccess,
    error: mocks.toastError,
    warning: mocks.toastWarning,
    info: mocks.toastInfo,
  },
}));

vi.mock("@/components/providers/forms/hooks/useManagedAuth", () => ({
  useManagedAuth: mocks.useManagedAuth,
}));
vi.mock("@/lib/api", async (importOriginal) => {
  const actual = await importOriginal<typeof import("@/lib/api")>();
  return {
    ...actual,
    authApi: {
      ...actual.authApi,
      workbuddyAccountLiveState: mocks.liveState,
      workbuddyAccountImportCurrent: mocks.importCurrent,
      workbuddyAccountPrepareNewLogin: mocks.prepareNewLogin,
      workbuddyAccountOpenApp: mocks.openApp,
      authSetDefaultAccount: mocks.setDefault,
      workbuddyAccountQuota: mocks.quota,
    },
  };
});

const renderWithClient = (ui: ReactElement) =>
  render(
    <QueryClientProvider
      client={
        new QueryClient({
          defaultOptions: {
            queries: { retry: false },
            mutations: { retry: false },
          },
        })
      }
    >
      {ui}
    </QueryClientProvider>,
  );

const baseAuth = () => ({
  accounts: [] as unknown[],
  defaultAccountId: null as string | null,
  isStatusSuccess: true,
  isStatusError: false,
  isRemovingAccount: false,
  removeAccount: vi.fn(),
  logout: vi.fn(),
  refetchStatus: vi.fn(),
});

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

const live = (patch: Record<string, boolean> = {}) => ({
  running: false,
  signedIn: true,
  recognized: true,
  imported: true,
  ...patch,
});

describe("WorkBuddyAccountSection", () => {
  beforeEach(() => {
    for (const mock of Object.values(mocks)) mock.mockReset();
    mocks.liveState.mockResolvedValue(live());
    mocks.openApp.mockResolvedValue(undefined);
    mocks.quota.mockResolvedValue({
      snapshot: null,
      current: false,
      unavailable: "not_current",
      error: null,
    });
  });

  it("shows each account's plan and credits, and says when it is the last result", async () => {
    const auth = baseAuth();
    auth.accounts = [account("u-1"), account("u-2")];
    auth.defaultAccountId = "u-1";
    mocks.useManagedAuth.mockReturnValue(auth);
    mocks.quota.mockImplementation(async (id: string) =>
      id === "u-1"
        ? {
            snapshot: {
              planName: "体验版",
              isPaid: false,
              total: 1500,
              remaining: 750,
              used: 750,
              queriedAt: Date.now() - 60_000,
            },
            current: true,
            unavailable: "not_running",
            error: null,
          }
        : {
            snapshot: null,
            current: false,
            unavailable: "not_current",
            error: null,
          },
    );
    renderWithClient(<WorkBuddyAccountSection />);

    // 套餐在账号第二行(与其他服务一致),额度列只写积分,不重复套餐
    const meter = await screen.findByRole("meter", {
      name: "workbuddy.quota.credits: 750",
    });
    expect(await screen.findByText(/体验版/)).toBeInTheDocument();
    expect(meter.closest("[title]")?.getAttribute("title")).toContain(
      "workbuddy.quota.staleNotRunning",
    );
    // 没查到过的非当前账号不显示额度
    expect(screen.getAllByRole("meter")).toHaveLength(1);
    expect(mocks.quota).toHaveBeenCalledWith("u-1", false);
    expect(mocks.quota).toHaveBeenCalledWith("u-2", false);

    // ↻ 跳过缓存;WorkBuddy 没在运行、只拿回上次结果时说明原因,不然看着像点了没反应
    expect(mocks.toastInfo).not.toHaveBeenCalled();
    await userEvent.click(
      screen.getByRole("button", { name: "刷新 u-1 的额度" }),
    );
    await waitFor(() => expect(mocks.quota).toHaveBeenCalledWith("u-1", true));
    await waitFor(() =>
      expect(mocks.toastInfo).toHaveBeenCalledWith(
        "workbuddy.quota.staleNotRunning",
      ),
    );
  });

  it("marks the account WorkBuddy uses", async () => {
    const auth = baseAuth();
    auth.accounts = [
      account("u-1", { account_kind: "personal" }),
      account("u-2"),
    ];
    auth.defaultAccountId = "u-1";
    mocks.useManagedAuth.mockReturnValue(auth);
    renderWithClient(<WorkBuddyAccountSection />);

    expect(mocks.useManagedAuth).toHaveBeenCalledWith("workbuddy_account");
    const current = screen.getByText("u-1").parentElement!;
    expect(within(current).getByText("WorkBuddy 在用")).toBeInTheDocument();
    expect(screen.getByText(/personal/)).toBeInTheDocument();
    expect(
      screen.getByText(
        "快照只在这台电脑上有效(登录凭据绑定本机),不会随云同步,换电脑后需要重新收录。",
      ),
    ).toBeInTheDocument();

    // 分组没有「删除全部账号」:只能逐个删除
    expect(
      screen.queryByRole("button", { name: "WorkBuddy 的更多操作" }),
    ).not.toBeInTheDocument();

    // 在用的号 ⋯ 里没有切换项(已经在用),只有重新登录和删除
    await userEvent.click(
      screen.getByRole("button", { name: "u-1 的更多操作" }),
    );
    expect(
      await screen.findByRole("menuitem", { name: /删除/ }),
    ).toBeInTheDocument();
    expect(
      screen.getByRole("menuitem", { name: "重新登录" }),
    ).toBeInTheDocument();
    expect(
      screen.queryByRole("menuitem", { name: /切换/ }),
    ).not.toBeInTheDocument();
    expect(mocks.setDefault).not.toHaveBeenCalled();
  });

  it("switches WorkBuddy to another account from its menu", async () => {
    const auth = baseAuth();
    auth.accounts = [account("u-1"), account("u-2")];
    auth.defaultAccountId = "u-1";
    mocks.useManagedAuth.mockReturnValue(auth);
    mocks.setDefault.mockResolvedValue(undefined);
    renderWithClient(<WorkBuddyAccountSection />);

    await userEvent.click(
      screen.getByRole("button", { name: "u-2 的更多操作" }),
    );
    await userEvent.click(
      await screen.findByRole("menuitem", {
        name: "切换 WorkBuddy 到这个账号",
      }),
    );

    // 和供应商列表的官方卡走同一个切号命令
    await waitFor(() =>
      expect(mocks.setDefault).toHaveBeenCalledWith("workbuddy_account", "u-2"),
    );
    expect(mocks.toastSuccess).toHaveBeenCalledWith(
      "workbuddy.official.switched",
      expect.anything(),
    );
  });

  it("asks to quit WorkBuddy before switching while it runs", async () => {
    const auth = baseAuth();
    auth.accounts = [account("u-1"), account("u-2")];
    auth.defaultAccountId = "u-1";
    mocks.useManagedAuth.mockReturnValue(auth);
    mocks.liveState.mockResolvedValue(live({ running: true }));
    renderWithClient(<WorkBuddyAccountSection />);

    await userEvent.click(
      screen.getByRole("button", { name: "u-2 的更多操作" }),
    );
    await userEvent.click(
      await screen.findByRole("menuitem", {
        name: "切换 WorkBuddy 到这个账号",
      }),
    );

    await waitFor(() =>
      expect(mocks.toastError).toHaveBeenCalledWith(
        "workbuddy.official.quitFirst",
        expect.anything(),
      ),
    );
    expect(mocks.setDefault).not.toHaveBeenCalled();
  });

  it("imports the current sign-in from the header Add account", async () => {
    mocks.useManagedAuth.mockReturnValue(baseAuth());
    mocks.importCurrent.mockResolvedValue({
      account: account("u-1"),
      created: true,
    });
    renderWithClient(<WorkBuddyAccountSection />);

    await userEvent.click(screen.getByRole("button", { name: /添加账号/ }));
    await waitFor(() => expect(mocks.importCurrent).toHaveBeenCalledOnce());
  });

  it("explains how to add another account when the current one is known", async () => {
    const auth = baseAuth();
    auth.accounts = [account("u-1")];
    auth.defaultAccountId = "u-1";
    mocks.useManagedAuth.mockReturnValue(auth);
    mocks.importCurrent.mockResolvedValue({
      account: account("u-1"),
      created: false,
    });
    mocks.prepareNewLogin.mockResolvedValue(account("u-1"));
    renderWithClient(<WorkBuddyAccountSection />);

    await userEvent.click(screen.getByRole("button", { name: /添加账号/ }));
    expect(
      await screen.findByText("当前登录的账号已在列表里(副本已更新)"),
    ).toBeInTheDocument();
    await userEvent.click(
      screen.getByRole("button", { name: "登录另一个账号" }),
    );
    await waitFor(() => expect(mocks.prepareNewLogin).toHaveBeenCalledOnce());
    await waitFor(() => expect(mocks.openApp).toHaveBeenCalledOnce());
  });

  it("offers to open WorkBuddy when it isn't signed in", async () => {
    mocks.useManagedAuth.mockReturnValue(baseAuth());
    mocks.liveState.mockResolvedValue(live({ signedIn: false }));
    mocks.importCurrent.mockRejectedValue(new Error("not signed in"));
    renderWithClient(<WorkBuddyAccountSection />);

    await userEvent.click(screen.getByRole("button", { name: /添加账号/ }));
    expect(
      await screen.findByText("WorkBuddy 当前没有登录"),
    ).toBeInTheDocument();
    await userEvent.click(
      screen.getByRole("button", { name: "打开 WorkBuddy" }),
    );
    expect(mocks.openApp).toHaveBeenCalledOnce();
  });

  it("warns while WorkBuddy is running", async () => {
    const auth = baseAuth();
    auth.accounts = [account("u-1")];
    mocks.useManagedAuth.mockReturnValue(auth);
    mocks.liveState.mockResolvedValue(live({ running: true }));
    renderWithClient(<WorkBuddyAccountSection />);

    expect(await screen.findByText("WorkBuddy 正在运行")).toBeInTheDocument();
  });

  describe("sign in again", () => {
    it("shows the inline button only on expired accounts and starts a new login for it", async () => {
      const auth = baseAuth();
      auth.accounts = [
        account("u-1", { login: "Alice", requires_reauth: true }),
        account("u-2"),
      ];
      auth.defaultAccountId = "u-2";
      mocks.useManagedAuth.mockReturnValue(auth);
      mocks.prepareNewLogin.mockResolvedValue(account("u-2"));
      renderWithClient(<WorkBuddyAccountSection />);

      // 只有过期的那行有行内按钮
      const buttons = screen.getAllByRole("button", { name: "重新登录" });
      expect(buttons).toHaveLength(1);
      await userEvent.click(buttons[0]);

      await waitFor(() =>
        expect(mocks.prepareNewLogin).toHaveBeenCalledWith("u-1"),
      );
      await waitFor(() => expect(mocks.openApp).toHaveBeenCalledOnce());
      expect(mocks.toastSuccess).toHaveBeenCalledWith(
        expect.stringContaining("请登录 Alice"),
      );
    });

    it("offers sign in again in every account's menu", async () => {
      const auth = baseAuth();
      auth.accounts = [account("u-1"), account("u-2")];
      auth.defaultAccountId = "u-1";
      mocks.useManagedAuth.mockReturnValue(auth);
      mocks.prepareNewLogin.mockResolvedValue(account("u-1"));
      renderWithClient(<WorkBuddyAccountSection />);

      expect(
        screen.queryByRole("button", { name: "重新登录" }),
      ).not.toBeInTheDocument();
      await userEvent.click(
        screen.getByRole("button", { name: "u-1 的更多操作" }),
      );
      await userEvent.click(
        await screen.findByRole("menuitem", { name: "重新登录" }),
      );
      await waitFor(() =>
        expect(mocks.prepareNewLogin).toHaveBeenCalledWith("u-1"),
      );
      await waitFor(() => expect(mocks.openApp).toHaveBeenCalledOnce());
    });

    it("explains signing in again inside WorkBuddy while it runs", async () => {
      const auth = baseAuth();
      auth.accounts = [
        account("u-1", { login: "Alice", requires_reauth: true }),
      ];
      mocks.useManagedAuth.mockReturnValue(auth);
      mocks.liveState.mockResolvedValue(live({ running: true }));
      mocks.prepareNewLogin.mockRejectedValue(
        new Error("WorkBuddy is running"),
      );
      renderWithClient(<WorkBuddyAccountSection />);

      await userEvent.click(screen.getByRole("button", { name: "重新登录" }));
      await waitFor(() =>
        expect(mocks.toastError).toHaveBeenCalledWith(
          "WorkBuddy 正在运行,没法让它停在登录页",
          expect.objectContaining({
            description: expect.stringContaining("重新登录 Alice"),
          }),
        ),
      );
      expect(mocks.openApp).not.toHaveBeenCalled();
    });

    it("reports when the same account signed in again and its snapshot was replaced", async () => {
      const auth = baseAuth();
      auth.accounts = [account("u-1", { login: "Alice" })];
      mocks.useManagedAuth.mockReturnValue(auth);
      const outcome = {
        id: 101,
        targetId: "u-1",
        targetLogin: "Alice",
        accountId: "u-1",
        login: "Alice",
        sameAccount: true,
        created: false,
      };
      mocks.liveState.mockResolvedValue({ ...live(), reauth: outcome });
      renderWithClient(<WorkBuddyAccountSection />);

      await waitFor(() =>
        expect(mocks.toastSuccess).toHaveBeenCalledWith("Alice 已重新登录。"),
      );
      expect(auth.refetchStatus).toHaveBeenCalled();
      expect(mocks.toastWarning).not.toHaveBeenCalled();
    });

    it("says a different account was added when the sign-in isn't the original one", async () => {
      const auth = baseAuth();
      auth.accounts = [account("u-1", { login: "Alice" }), account("u-3")];
      mocks.useManagedAuth.mockReturnValue(auth);
      mocks.liveState.mockResolvedValue({
        ...live(),
        reauth: {
          id: 102,
          targetId: "u-1",
          targetLogin: "Alice",
          accountId: "u-3",
          login: "u-3",
          sameAccount: false,
          created: true,
        },
      });
      renderWithClient(<WorkBuddyAccountSection />);

      await waitFor(() =>
        expect(mocks.toastWarning).toHaveBeenCalledWith(
          "登录的不是 Alice,已把 u-3 作为新账号收录。",
        ),
      );
      expect(mocks.toastSuccess).not.toHaveBeenCalled();
    });
  });
});