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

18.0 KB
Raw Blame
import { QueryClientProvider } from "@tanstack/react-query";
import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { AgyOAuthSection } from "@/components/providers/forms/AgyOAuthSection";
import { createTestQueryClient } from "../utils/testQueryClient";

const mocks = vi.hoisted(() => ({
  useManagedAuth: vi.fn(),
  openExternal: vi.fn(),
  openLoginTerminal: vi.fn(() => Promise.resolve()),
  openDesktop: vi.fn(() => Promise.resolve()),
  submitPaste: vi.fn(() => Promise.resolve()),
  authSetDefaultAccount: vi.fn(),
  toastError: vi.fn(),
  toastSuccess: vi.fn(),
  toastWarning: vi.fn(),
}));

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

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

vi.mock("@/components/providers/forms/hooks/useManagedAuth", () => ({
  useManagedAuth: mocks.useManagedAuth,
}));
// 「N 个供应商在用」要读供应商列表(React Query);这里不关心,给空
vi.mock("@/components/providers/forms/hooks/useManagedAccountUsers", () => ({
  useManagedAccountUsers: () => () => [],
}));
// 额度列单独查询(React Query);这里只看每个号有没有挂上
vi.mock("@/components/settings/auth/AccountQuota", () => ({
  AgyAccountQuota: ({ accountId }: { accountId: string }) => (
    <span data-testid="agy-quota">{accountId}</span>
  ),
}));
vi.mock("@/lib/api", async (importOriginal) => {
  const actual = await importOriginal<typeof import("@/lib/api")>();
  return {
    ...actual,
    settingsApi: { ...actual.settingsApi, openExternal: mocks.openExternal },
    authApi: {
      ...actual.authApi,
      agyAccountOpenLoginTerminal: mocks.openLoginTerminal,
      agyAccountOpenDesktop: mocks.openDesktop,
      agyAccountSubmitPaste: mocks.submitPaste,
      authSetDefaultAccount: mocks.authSetDefaultAccount,
    },
  };
});

const renderSection = (client = createTestQueryClient()) =>
  render(
    <QueryClientProvider client={client}>
      <AgyOAuthSection />
    </QueryClientProvider>,
  );

const baseAuth = () => ({
  accounts: [] as unknown[],
  defaultAccountId: null as string | null,
  isStatusSuccess: true,
  isStatusError: false,
  pollingState: "idle" as "idle" | "polling" | "success" | "error",
  deviceCode: null as unknown,
  error: null as string | null,
  lastCompletedLogin: null as {
    account: { id: string; login: string };
    created: boolean;
  } | 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) => ({
  id,
  provider: "agy_oauth",
  login,
  avatar_url: null,
  authenticated_at: 0,
  is_default: false,
  github_domain: "google.com",
  requires_reauth: false,
});

describe("AgyOAuthSection", () => {
  beforeEach(() => {
    window.localStorage.removeItem("cc-switch.authCenter.openBrowser");
    mocks.useManagedAuth.mockReset();
    mocks.openExternal.mockReset();
    mocks.openLoginTerminal.mockReset();
    mocks.openLoginTerminal.mockResolvedValue(undefined);
    mocks.openDesktop.mockReset();
    mocks.openDesktop.mockResolvedValue(undefined);
    mocks.submitPaste.mockReset();
    mocks.submitPaste.mockResolvedValue(undefined);
    mocks.authSetDefaultAccount.mockReset();
    mocks.toastError.mockReset();
    mocks.toastSuccess.mockReset();
    mocks.toastWarning.mockReset();
    mocks.authSetDefaultAccount.mockResolvedValue(undefined);
  });

  it("marks the account Antigravity is signed in with and switches from the menu", async () => {
    const auth = baseAuth();
    auth.accounts = [
      account("a", "[email protected]"),
      account("b", "[email protected]"),
    ];
    auth.defaultAccountId = "a";
    mocks.useManagedAuth.mockReturnValue(auth);
    const client = createTestQueryClient();
    const providersKey = ["providers", "agy"];
    client.setQueryData(providersKey, { currentProviderId: "provider-a" });
    renderSection(client);

    expect(mocks.useManagedAuth).toHaveBeenCalledWith("agy_oauth");
    const current = screen.getByText("[email protected]").parentElement!;
    expect(within(current).getByText("Antigravity 在用")).toBeInTheDocument();

    // 当前那个号的菜单里没有「切换」,另一个号有
    await userEvent.click(
      screen.getByRole("button", { name: "[email protected] 的更多操作" }),
    );
    await userEvent.click(
      await screen.findByRole("menuitem", {
        name: "切换 Antigravity 到这个账号",
      }),
    );
    await waitFor(() => {
      expect(mocks.authSetDefaultAccount).toHaveBeenCalledWith(
        "agy_oauth",
        "b",
      );
      expect(client.getQueryState(providersKey)?.isInvalidated).toBe(true);
    });
    expect(mocks.toastSuccess).toHaveBeenCalledTimes(1);
  });

  it("allows adding and switching accounts without a quit-first warning banner", async () => {
    const auth = baseAuth();
    auth.accounts = [
      account("a", "[email protected]"),
      account("b", "[email protected]"),
    ];
    auth.defaultAccountId = "a";
    mocks.useManagedAuth.mockReturnValue(auth);
    renderSection();

    expect(
      screen.queryByText(/请先.*退出.*Antigravity/),
    ).not.toBeInTheDocument();

    await userEvent.click(screen.getByRole("button", { name: "添加账号" }));
    expect(auth.addAccount).toHaveBeenCalledTimes(1);

    await userEvent.click(
      screen.getByRole("button", { name: "[email protected] 的更多操作" }),
    );
    await userEvent.click(
      await screen.findByRole("menuitem", {
        name: "切换 Antigravity 到这个账号",
      }),
    );

    await waitFor(() => {
      expect(mocks.authSetDefaultAccount).toHaveBeenCalledWith(
        "agy_oauth",
        "b",
      );
    });
    expect(mocks.toastSuccess).toHaveBeenCalledTimes(1);
    expect(mocks.toastSuccess).toHaveBeenCalledWith(
      expect.stringContaining("若 Antigravity 正在运行,重启后生效"),
      expect.anything(),
    );
    expect(mocks.toastError).not.toHaveBeenCalled();
  });

  it("asks to sign in within agy in the terminal instead of a browser page", async () => {
    const auth = baseAuth();
    Object.assign(auth, {
      isPolling: true,
      isAddingAccount: true,
      pollingState: "polling",
      deviceCode: {
        provider: "agy_oauth",
        device_code: "flow",
        user_code: "",
        verification_uri: "",
        expires_in: 600,
        interval: 2,
      },
    });
    mocks.useManagedAuth.mockReturnValue(auth);
    renderSection();

    expect(screen.getByText(/已在终端打开 agy/)).toBeInTheDocument();
    expect(screen.queryByText(/已在浏览器打开/)).not.toBeInTheDocument();
    expect(
      screen.queryByRole("button", { name: "复制登录链接" }),
    ).not.toBeInTheDocument();
    await userEvent.click(screen.getByRole("button", { name: "重新打开终端" }));
    expect(mocks.openLoginTerminal).toHaveBeenCalled();
    expect(mocks.openExternal).not.toHaveBeenCalled();
  });

  it("guides desktop sign-in when no agy CLI exists", async () => {
    const auth = baseAuth();
    Object.assign(auth, {
      isPolling: true,
      isAddingAccount: true,
      pollingState: "polling",
      deviceCode: {
        provider: "agy_oauth",
        device_code: "flow",
        user_code: "",
        verification_uri: "",
        expires_in: 600,
        interval: 2,
        login_surface: "desktop",
      },
    });
    mocks.useManagedAuth.mockReturnValue(auth);
    renderSection();

    // 提示切到桌面端登录:不动钥匙串,等桌面端登录的新号
    expect(screen.getByText(/已改用桌面端登录/)).toBeInTheDocument();
    expect(screen.queryByText(/已在终端打开 agy/)).not.toBeInTheDocument();
    // 「打开 Antigravity」走 agy_account_open_desktop,不再开终端
    await userEvent.click(
      screen.getByRole("button", { name: "打开 Antigravity" }),
    );
    expect(mocks.openDesktop).toHaveBeenCalled();
    expect(mocks.openLoginTerminal).not.toHaveBeenCalled();
  });

  it("shows quota for every account that can still sign in", () => {
    const auth = baseAuth();
    auth.accounts = [
      account("a", "[email protected]"),
      { ...account("b", "[email protected]"), requires_reauth: true },
      account("c", "[email protected]"),
    ];
    auth.defaultAccountId = "a";
    mocks.useManagedAuth.mockReturnValue(auth);
    renderSection();

    const quotas = screen
      .getAllByTestId("agy-quota")
      .map((el) => el.textContent);
    // 不只是 agy 在用的号,其他号也查;登录失效的不查
    expect(quotas).toEqual(["a", "c"]);
  });

  it("forwards target accountId on reauth and uses retryAuth on error retry", async () => {
    const auth = baseAuth();
    auth.accounts = [
      account("a", "[email protected]"),
      account("b", "[email protected]"),
    ];
    auth.defaultAccountId = "a";
    mocks.useManagedAuth.mockReturnValue(auth);
    const client = createTestQueryClient();
    const { rerender } = renderSection(client);

    await userEvent.click(
      screen.getByRole("button", { name: "[email protected] 的更多操作" }),
    );
    await userEvent.click(
      await screen.findByRole("menuitem", { name: "重新登录" }),
    );
    expect(auth.reauthAccount).toHaveBeenCalledWith("b");

    // Failed state -> Retry button calls retryAuth (preserving target), not addAccount.
    auth.pollingState = "error";
    auth.error = "login expired";
    mocks.useManagedAuth.mockReturnValue({ ...auth });
    rerender(
      <QueryClientProvider client={client}>
        <AgyOAuthSection />
      </QueryClientProvider>,
    );

    await userEvent.click(screen.getByRole("button", { name: "重试" }));
    expect(auth.retryAuth).toHaveBeenCalledTimes(1);
    expect(auth.addAccount).not.toHaveBeenCalled();
  });

  it.each([
    {
      name: "same account reauth succeeds",
      completed: {
        account: { id: "b", login: "[email protected]" },
        created: false,
      },
      expectedSuccess: "[email protected] 已重新登录。",
      expectedWarning: null,
    },
    {
      name: "different existing account warns updated",
      completed: {
        account: { id: "a", login: "[email protected]" },
        created: false,
      },
      expectedSuccess: null,
      expectedWarning:
        "登录的不是 [email protected],[email protected] 已在列表里,副本已更新。",
    },
    {
      name: "different new account warns added",
      completed: {
        account: { id: "c", login: "[email protected]" },
        created: true,
      },
      expectedSuccess: null,
      expectedWarning:
        "登录的不是 [email protected],已把 [email protected] 作为新账号收录。",
    },
  ])(
    "handles reauth outcome: $name",
    async ({ completed, expectedSuccess, expectedWarning }) => {
      const auth = baseAuth();
      auth.accounts = [
        account("a", "[email protected]"),
        account("b", "[email protected]"),
      ];
      auth.defaultAccountId = "a";
      mocks.useManagedAuth.mockReturnValue(auth);
      const client = createTestQueryClient();
      const { rerender } = renderSection(client);

      await userEvent.click(
        screen.getByRole("button", { name: "[email protected] 的更多操作" }),
      );
      await userEvent.click(
        await screen.findByRole("menuitem", { name: "重新登录" }),
      );

      mocks.useManagedAuth.mockReturnValue({
        ...auth,
        pollingState: "success",
        lastCompletedLogin: completed,
      });
      rerender(
        <QueryClientProvider client={client}>
          <AgyOAuthSection />
        </QueryClientProvider>,
      );

      if (expectedSuccess) {
        expect(mocks.toastSuccess).toHaveBeenCalledWith(expectedSuccess);
        expect(mocks.toastWarning).not.toHaveBeenCalled();
      }
      if (expectedWarning) {
        expect(mocks.toastWarning).toHaveBeenCalledWith(expectedWarning);
        expect(mocks.toastSuccess).not.toHaveBeenCalled();
      }
    },
  );

  it("clears reauthTarget when cancelling pending login or closing an error notice", async () => {
    const auth = baseAuth();
    auth.accounts = [
      account("a", "[email protected]"),
      account("b", "[email protected]"),
    ];
    auth.defaultAccountId = "a";
    mocks.useManagedAuth.mockReturnValue(auth);
    const client = createTestQueryClient();
    const { rerender } = renderSection(client);
    const rerenderWith = (next: ReturnType<typeof baseAuth>) => {
      mocks.useManagedAuth.mockReturnValue(next);
      rerender(
        <QueryClientProvider client={client}>
          <AgyOAuthSection />
        </QueryClientProvider>,
      );
    };

    await userEvent.click(
      screen.getByRole("button", { name: "[email protected] 的更多操作" }),
    );
    await userEvent.click(
      await screen.findByRole("menuitem", { name: "重新登录" }),
    );
    rerenderWith({
      ...auth,
      pollingState: "error",
      error: "boom",
    });
    await userEvent.click(screen.getByRole("button", { name: "关闭" }));
    expect(auth.cancelAuth).toHaveBeenCalledTimes(1);

    rerenderWith({
      ...auth,
      pollingState: "success",
      lastCompletedLogin: {
        account: { id: "d", login: "[email protected]" },
        created: true,
      },
    });
    expect(mocks.toastSuccess).toHaveBeenCalledWith(
      "已添加 Antigravity 账号。",
    );
  });

  it("disables switching while a sign-in is in progress", async () => {
    const auth = baseAuth();
    auth.accounts = [
      account("a", "[email protected]"),
      account("b", "[email protected]"),
    ];
    auth.defaultAccountId = "a";
    Object.assign(auth, {
      isPolling: true,
      isAddingAccount: true,
      pollingState: "polling",
      deviceCode: {
        provider: "agy_oauth",
        device_code: "flow",
        user_code: "",
        verification_uri: "",
        expires_in: 600,
        interval: 2,
      },
    });
    mocks.useManagedAuth.mockReturnValue(auth);
    renderSection();

    // 等待登录时切号会改写钥匙串,被当成这次登录的结果:菜单项禁用
    await userEvent.click(
      screen.getByRole("button", { name: "[email protected] 的更多操作" }),
    );
    expect(
      await screen.findByRole("menuitem", {
        name: "切换 Antigravity 到这个账号",
      }),
    ).toHaveAttribute("aria-disabled", "true");
  });

  it("renders the ACP browser flow with expanded paste box and no terminal or desktop reopen", async () => {
    const user = userEvent.setup();
    const auth = baseAuth();
    Object.assign(auth, {
      isPolling: true,
      isAddingAccount: true,
      pollingState: "polling",
      deviceCode: {
        provider: "agy_oauth",
        device_code: "acp-flow-1",
        user_code: "",
        verification_uri:
          "https://accounts.google.com/o/oauth2/auth?response_type=code&state=s1",
        expires_in: 600,
        interval: 1,
        login_surface: "acp",
      },
    });
    mocks.useManagedAuth.mockReturnValue(auth);
    renderSection();

    expect(
      screen.getByText(/已在浏览器打开 Google 登录页/),
    ).toBeInTheDocument();
    expect(
      screen.getByRole("button", { name: "复制登录链接" }),
    ).toBeInTheDocument();
    expect(
      screen.getByRole("button", { name: "重新打开登录页" }),
    ).toBeInTheDocument();
    expect(
      screen.queryByRole("button", { name: "重新打开终端" }),
    ).not.toBeInTheDocument();
    expect(
      screen.queryByRole("button", { name: "打开 Antigravity" }),
    ).not.toBeInTheDocument();

    // 粘贴框直接展开,支持提交失败提示与 Enter / 按钮提交成功
    const input = screen.getByRole("textbox", { name: "授权代码或回调地址" });
    mocks.submitPaste.mockRejectedValueOnce(new Error("无效回调地址"));
    await user.type(input, "bad-paste{enter}");
    expect(mocks.submitPaste).toHaveBeenCalledWith("acp-flow-1", "bad-paste");
    expect(await screen.findByText("无效回调地址")).toBeInTheDocument();
    expect(mocks.toastError).toHaveBeenCalledWith("无效回调地址");

    mocks.submitPaste.mockResolvedValueOnce(undefined);
    await user.clear(input);
    await user.type(input, "good-code");
    await user.click(screen.getByRole("button", { name: "提交" }));
    expect(mocks.submitPaste).toHaveBeenLastCalledWith(
      "acp-flow-1",
      "good-code",
    );
    expect(
      await screen.findByText("已提交,正在完成登录…"),
    ).toBeInTheDocument();

    await user.click(screen.getByRole("button", { name: "重新打开登录页" }));
    expect(mocks.openExternal).toHaveBeenCalledWith(
      "https://accounts.google.com/o/oauth2/auth?response_type=code&state=s1",
    );
  });

  it("respects disabled auto-open browser in ACP flow", () => {
    window.localStorage.setItem("cc-switch.authCenter.openBrowser", "0");
    const auth = baseAuth();
    Object.assign(auth, {
      isPolling: true,
      isAddingAccount: true,
      pollingState: "polling",
      deviceCode: {
        provider: "agy_oauth",
        device_code: "acp-flow-2",
        user_code: "",
        verification_uri:
          "https://accounts.google.com/o/oauth2/auth?response_type=code&state=s2",
        expires_in: 600,
        interval: 1,
        login_surface: "acp",
      },
    });
    mocks.useManagedAuth.mockReturnValue(auth);
    renderSection();

    expect(screen.getByText(/登录链接已复制/)).toBeInTheDocument();
    expect(
      screen.getByRole("button", { name: "复制登录链接" }),
    ).toBeInTheDocument();
    expect(
      screen.queryByRole("button", { name: "重新打开登录页" }),
    ).not.toBeInTheDocument();
    expect(
      screen.queryByRole("button", { name: "重新打开终端" }),
    ).not.toBeInTheDocument();
    expect(
      screen.queryByRole("button", { name: "打开 Antigravity" }),
    ).not.toBeInTheDocument();
    expect(
      screen.getByRole("textbox", { name: "授权代码或回调地址" }),
    ).toBeInTheDocument();
  });
});