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

19.1 KB
Raw Blame
import type { ReactNode } from "react";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { QueryClientProvider } from "@tanstack/react-query";
import UsageScriptModal from "@/components/UsageScriptModal";
import type { Provider, UsageScript } from "@/types";
import { createTestQueryClient } from "../utils/testQueryClient";

vi.mock("@/components/common/FullScreenPanel", () => ({
  FullScreenPanel: ({
    isOpen,
    children,
    footer,
  }: {
    isOpen: boolean;
    children: ReactNode;
    footer?: ReactNode;
  }) =>
    isOpen ? (
      <div>
        <div>{children}</div>
        <div>{footer}</div>
      </div>
    ) : null,
}));

vi.mock("@/components/JsonEditor", () => ({
  default: ({ value }: { value: string }) => (
    <textarea data-testid="usage-script-code" value={value} readOnly />
  ),
}));

const provider: Provider = {
  id: "sub2api-site",
  name: "Example Sub2API",
  settingsConfig: {
    env: {
      ANTHROPIC_BASE_URL: "https://api.example.com",
      ANTHROPIC_AUTH_TOKEN: "sk-test",
    },
  },
  meta: {
    usage_script: {
      enabled: true,
      language: "javascript",
      code: "({ request: { url: '' }, extractor: function () { return {}; } })",
    },
  },
};

function renderModal(
  onSave: (script: UsageScript) => void,
  usageScript?: UsageScript,
) {
  const client = createTestQueryClient();
  render(
    <QueryClientProvider client={client}>
      <UsageScriptModal
        provider={
          usageScript
            ? { ...provider, meta: { usage_script: usageScript } }
            : provider
        }
        appId="claude"
        isOpen
        onClose={() => {}}
        onSave={onSave}
      />
    </QueryClientProvider>,
  );
}

describe("UsageScriptModal Sub2API template", () => {
  it.each(["qoder"] as const)(
    "reads %s credentials from its native provider",
    async (appId) => {
      const client = createTestQueryClient();
      render(
        <QueryClientProvider client={client}>
          <UsageScriptModal
            provider={{
              ...provider,
              settingsConfig: {
                baseUrl: "https://native.example/v1",
                apiKey: "native-key",
              },
            }}
            appId={appId}
            isOpen
            onClose={() => {}}
            onSave={vi.fn()}
          />
        </QueryClientProvider>,
      );
      await userEvent.click(
        screen.getByRole("button", { name: "usageScript.templateCustom" }),
      );
      expect(screen.getByText("https://native.example/v1")).toBeInTheDocument();
      await userEvent.click(
        screen.getByRole("button", { name: "apiKeyInput.show" }),
      );
      expect(screen.getByText("native-key")).toBeInTheDocument();
    },
  );
  it("fills the /v1/usage script and saves it as the sub2api template", async () => {
    const onSave = vi.fn();
    renderModal(onSave);

    await userEvent.click(
      screen.getByRole("button", { name: "usageScript.templateSub2API" }),
    );

    const code = (
      screen.getByTestId("usage-script-code") as HTMLTextAreaElement
    ).value;
    expect(code).toContain('+ "/v1/usage"');
    expect(code).toContain("Bearer {{apiKey}}");
    // 与通用模板一样只用 API Key 和地址,不显示访问令牌、用户 ID
    expect(screen.getByLabelText(/API Key/)).toBeInTheDocument();
    expect(
      screen.queryByLabelText("usageScript.accessToken"),
    ).not.toBeInTheDocument();

    await userEvent.click(
      screen.getByRole("button", { name: "usageScript.saveConfig" }),
    );
    expect(onSave).toHaveBeenCalledWith(
      expect.objectContaining({ templateType: "sub2api", code }),
    );
  });

  it("reopens a script saved with the sub2api template as that template", async () => {
    const onSave = vi.fn();
    renderModal(onSave, {
      ...provider.meta!.usage_script!,
      templateType: "sub2api",
    });

    await userEvent.click(
      screen.getByRole("button", { name: "usageScript.saveConfig" }),
    );
    expect(onSave).toHaveBeenCalledWith(
      expect.objectContaining({ templateType: "sub2api" }),
    );
  });
});

describe("UsageScriptModal official subscription hint", () => {
  // agy 的额度靠它自己的 /usage 命令查,不读登录凭据
  it("explains Antigravity's quota check instead of reading OAuth credentials", () => {
    const client = createTestQueryClient();
    render(
      <QueryClientProvider client={client}>
        <UsageScriptModal
          provider={{
            id: "agy-official",
            name: "Google Official",
            category: "official",
            settingsConfig: { env: {}, config: {} },
            meta: {
              usage_script: {
                enabled: true,
                language: "javascript",
                code: "",
                templateType: "official_subscription",
              },
            },
          }}
          appId="agy"
          isOpen
          onClose={() => {}}
          onSave={vi.fn()}
        />
      </QueryClientProvider>,
    );
    expect(
      screen.getByText("usageScript.officialSubscriptionHintAgy"),
    ).toBeInTheDocument();
    expect(
      screen.queryByText("usageScript.officialSubscriptionHint"),
    ).not.toBeInTheDocument();
  });
});

describe("UsageScriptModal Claude official card bound to an account", () => {
  // 卡片和托盘在没保存开关时默认查这个号的额度,配置页也要显示为已开
  it("shows usage enabled by default when nothing was saved", async () => {
    const onSave = vi.fn();
    const client = createTestQueryClient();
    render(
      <QueryClientProvider client={client}>
        <UsageScriptModal
          provider={{
            id: "claude-bound",
            name: "Claude Official",
            category: "official",
            settingsConfig: { env: {} },
            meta: {
              authBinding: {
                source: "managed_account",
                authProvider: "claude_official",
                accountId: "acct-1",
              },
            },
          }}
          appId="claude"
          isOpen
          onClose={() => {}}
          onSave={onSave}
        />
      </QueryClientProvider>,
    );

    await userEvent.click(
      screen.getByRole("button", { name: "usageScript.saveConfig" }),
    );
    expect(onSave).toHaveBeenCalledWith(
      expect.objectContaining({
        enabled: true,
        templateType: "official_subscription",
      }),
    );
  });
});

describe("UsageScriptModal Grok official card bound to an xAI account", () => {
  const grokProvider: Provider = {
    id: "grok-bound",
    name: "Grok Official",
    category: "official",
    settingsConfig: {},
    meta: {
      authBinding: {
        source: "managed_account",
        authProvider: "xai_oauth",
        accountId: "xai-acct-1",
      },
    },
  };

  // 卡片和托盘在没保存开关时默认查这个号的额度,配置页也要显示为已开
  it("shows usage enabled by default when nothing was saved", async () => {
    const onSave = vi.fn();
    const client = createTestQueryClient();
    render(
      <QueryClientProvider client={client}>
        <UsageScriptModal
          provider={grokProvider}
          appId="grokbuild"
          isOpen
          onClose={() => {}}
          onSave={onSave}
        />
      </QueryClientProvider>,
    );

    await userEvent.click(
      screen.getByRole("button", { name: "usageScript.saveConfig" }),
    );
    expect(onSave).toHaveBeenCalledWith(
      expect.objectContaining({
        enabled: true,
        templateType: "official_subscription",
      }),
    );
  });

  // 测试要查绑定的 xAI 账号,不能去读 ~/.grok/auth.json 当前登录的号
  it("tests the bound xAI account's quota and caches it under that account", async () => {
    const { subscriptionApi } = await import("@/lib/api/subscription");
    const quota = {
      tool: "grokbuild",
      credentialStatus: "valid",
      credentialMessage: null,
      success: true,
      tiers: [{ name: "weekly", utilization: 42, resetsAt: null }],
      extraUsage: null,
      error: null,
      queriedAt: 1,
    } as unknown as Awaited<ReturnType<typeof subscriptionApi.getQuota>>;
    const getXaiOauthQuota = vi
      .spyOn(subscriptionApi, "getXaiOauthQuota")
      .mockResolvedValue(quota);
    const getQuota = vi
      .spyOn(subscriptionApi, "getQuota")
      .mockResolvedValue(quota);

    try {
      const client = createTestQueryClient();
      render(
        <QueryClientProvider client={client}>
          <UsageScriptModal
            provider={grokProvider}
            appId="grokbuild"
            isOpen
            onClose={() => {}}
            onSave={() => {}}
          />
        </QueryClientProvider>,
      );

      await userEvent.click(
        screen.getByRole("button", { name: "usageScript.testScript" }),
      );

      expect(getXaiOauthQuota).toHaveBeenCalledWith("xai-acct-1");
      expect(getQuota).not.toHaveBeenCalled();
      expect(client.getQueryData(["xai_oauth", "quota", "xai-acct-1"])).toBe(
        quota,
      );
      expect(
        client.getQueryData(["subscription", "quota", "grokbuild"]),
      ).toBeUndefined();
    } finally {
      getXaiOauthQuota.mockRestore();
      getQuota.mockRestore();
    }
  });
});

/**
 * Oh My Pi has its own `AppId` ("omp"), so it never matched the `pi` branch
 * and both built-in tests reported "API key is empty" on an omp card. The
 * provider key and base URL must reach the balance API like they do for Pi.
 */
describe("UsageScriptModal Oh My Pi credentials", () => {
  it("passes the omp provider's key and base URL to the balance test", async () => {
    const getBalance = vi.fn().mockResolvedValue({ success: true, data: [] });
    vi.doMock("@/lib/api/subscription", () => ({
      subscriptionApi: { getBalance },
    }));
    const { default: Modal } = await import("@/components/UsageScriptModal");
    const client = createTestQueryClient();
    render(
      <QueryClientProvider client={client}>
        <Modal
          provider={{
            id: "cc-switch-demo",
            name: "Demo",
            // A base URL the balance template recognises, so the test reaches
            // `getBalance` instead of stopping at the template picker.
            settingsConfig: {
              baseUrl: "https://api.deepseek.com/v1",
              apiKey: "sk-omp",
              api: "openai-completions",
            },
          }}
          appId="omp"
          isOpen
          onClose={() => {}}
          onSave={() => {}}
        />
      </QueryClientProvider>,
    );

    // The usage query is off by default; enabling it asks for confirmation once.
    await userEvent.click(screen.getByRole("switch"));
    await userEvent.click(
      screen.getByRole("button", { name: "confirm.usage.confirm" }),
    );
    await userEvent.click(
      screen.getByRole("button", { name: "usageScript.testScript" }),
    );

    expect(getBalance).toHaveBeenCalledWith(
      "https://api.deepseek.com/v1",
      "sk-omp",
    );
  });
});

describe("UsageScriptModal DeepSeek Harness credentials", () => {
  const dshProvider: Provider = {
    id: "deepseek-dsh",
    name: "DeepSeek",
    settingsConfig: {
      api: "openai-completions",
      options: {
        baseURL: "https://api.deepseek.com/v1/",
        apiKey: "sk-test-dsh",
      },
      models: {},
    },
    meta: {
      usage_script: {
        enabled: true,
        language: "javascript",
        code: "",
      },
    },
  };

  function renderDshModal() {
    const client = createTestQueryClient();
    render(
      <QueryClientProvider client={client}>
        <UsageScriptModal
          provider={dshProvider}
          appId="dsh"
          isOpen
          onClose={() => {}}
          onSave={() => {}}
        />
      </QueryClientProvider>,
    );
  }

  it("detects the official balance template from the DSH provider endpoint", () => {
    renderDshModal();

    expect(screen.getByText("usageScript.balanceHint")).toBeInTheDocument();
    expect(screen.queryByTestId("usage-script-code")).not.toBeInTheDocument();
  });

  it("passes the saved DSH key and normalized endpoint to the balance test", async () => {
    const { subscriptionApi } = await import("@/lib/api/subscription");
    const getBalance = vi
      .spyOn(subscriptionApi, "getBalance")
      .mockResolvedValue({
        success: true,
        data: [{ isValid: true, remaining: 1, unit: "CNY" }],
      });

    try {
      renderDshModal();
      await userEvent.click(
        screen.getByRole("button", { name: "usageScript.templateBalance" }),
      );
      await userEvent.click(
        screen.getByRole("button", { name: "usageScript.testScript" }),
      );

      expect(getBalance).toHaveBeenCalledWith(
        "https://api.deepseek.com/v1",
        "sk-test-dsh",
      );
    } finally {
      getBalance.mockRestore();
    }
  });

  it("shows inherited DSH credentials in the custom template variables", async () => {
    renderDshModal();
    await userEvent.click(
      screen.getByRole("button", { name: "usageScript.templateCustom" }),
    );

    expect(screen.getByText("https://api.deepseek.com/v1")).toBeInTheDocument();
    await userEvent.click(
      screen.getByRole("button", { name: "apiKeyInput.show" }),
    );
    expect(screen.getByText("sk-test-dsh")).toBeInTheDocument();
  });
});

describe("UsageScriptModal WorkBuddy credentials", () => {
  const workbuddyProvider: Provider = {
    id: "workbuddy-deepseek",
    name: "DeepSeek",
    settingsConfig: {
      models: [
        {
          id: "deepseek-chat",
          url: "https://api.deepseek.com/v1/chat/completions",
          apiKey: "sk-test-workbuddy",
        },
      ],
    },
    meta: {
      usage_script: {
        enabled: true,
        language: "javascript",
        code: "",
      },
    },
  };

  it("passes the model's key and endpoint without /chat/completions to the balance test", async () => {
    const { subscriptionApi } = await import("@/lib/api/subscription");
    const getBalance = vi
      .spyOn(subscriptionApi, "getBalance")
      .mockResolvedValue({
        success: true,
        data: [{ isValid: true, remaining: 1, unit: "CNY" }],
      });

    try {
      const client = createTestQueryClient();
      render(
        <QueryClientProvider client={client}>
          <UsageScriptModal
            provider={workbuddyProvider}
            appId="workbuddy"
            isOpen
            onClose={() => {}}
            onSave={() => {}}
          />
        </QueryClientProvider>,
      );
      expect(screen.getByText("usageScript.balanceHint")).toBeInTheDocument();
      await userEvent.click(
        screen.getByRole("button", { name: "usageScript.templateBalance" }),
      );
      await userEvent.click(
        screen.getByRole("button", { name: "usageScript.testScript" }),
      );

      expect(getBalance).toHaveBeenCalledWith(
        "https://api.deepseek.com/v1",
        "sk-test-workbuddy",
      );
    } finally {
      getBalance.mockRestore();
    }
  });
});

describe("UsageScriptModal CodeBuddy credentials", () => {
  const codebuddyProvider: Provider = {
    id: "codebuddy-deepseek",
    name: "DeepSeek",
    settingsConfig: {
      id: "deepseek-chat",
      name: "DeepSeek",
      vendor: "DeepSeek",
      url: "https://api.deepseek.com/v1/chat/completions",
      apiKey: "sk-test-codebuddy",
    },
    meta: {
      usage_script: {
        enabled: true,
        language: "javascript",
        code: "",
      },
    },
  };

  it("passes the entry's key and endpoint without /chat/completions to the balance test", async () => {
    const { subscriptionApi } = await import("@/lib/api/subscription");
    const getBalance = vi
      .spyOn(subscriptionApi, "getBalance")
      .mockResolvedValue({
        success: true,
        data: [{ isValid: true, remaining: 1, unit: "CNY" }],
      });

    try {
      const client = createTestQueryClient();
      render(
        <QueryClientProvider client={client}>
          <UsageScriptModal
            provider={codebuddyProvider}
            appId="codebuddy"
            isOpen
            onClose={() => {}}
            onSave={() => {}}
          />
        </QueryClientProvider>,
      );
      expect(screen.getByText("usageScript.balanceHint")).toBeInTheDocument();
      await userEvent.click(
        screen.getByRole("button", { name: "usageScript.templateBalance" }),
      );
      await userEvent.click(
        screen.getByRole("button", { name: "usageScript.testScript" }),
      );

      expect(getBalance).toHaveBeenCalledWith(
        "https://api.deepseek.com/v1",
        "sk-test-codebuddy",
      );
    } finally {
      getBalance.mockRestore();
    }
  });
});

describe.each([
  {
    appId: "mcode" as const,
    settingsConfig: {
      kind: "custom",
      api: "openai-completions",
      options: {
        baseURL: "https://api.deepseek.com/v1/",
        apiKey: "sk-test-mcode",
      },
      models: {},
    },
    apiKey: "sk-test-mcode",
  },
  {
    appId: "kimi" as const,
    settingsConfig: {
      provider: {
        type: "openai",
        base_url: "https://api.deepseek.com/v1/",
        api_key: "sk-test-kimi",
      },
    },
    apiKey: "sk-test-kimi",
  },
])(
  "UsageScriptModal $appId credentials",
  ({ appId, settingsConfig, apiKey }) => {
    function renderAppModal() {
      const client = createTestQueryClient();
      render(
        <QueryClientProvider client={client}>
          <UsageScriptModal
            provider={{
              id: `deepseek-${appId}`,
              name: "DeepSeek",
              settingsConfig,
              meta: {
                usage_script: {
                  enabled: true,
                  language: "javascript",
                  code: "",
                },
              },
            }}
            appId={appId}
            isOpen
            onClose={() => {}}
            onSave={() => {}}
          />
        </QueryClientProvider>,
      );
    }

    it("passes the saved key and normalized endpoint to the balance test", async () => {
      const { subscriptionApi } = await import("@/lib/api/subscription");
      const getBalance = vi
        .spyOn(subscriptionApi, "getBalance")
        .mockResolvedValue({
          success: true,
          data: [{ isValid: true, remaining: 1, unit: "CNY" }],
        });

      try {
        renderAppModal();
        // The DeepSeek endpoint auto-selects the official balance template.
        expect(screen.getByText("usageScript.balanceHint")).toBeInTheDocument();
        await userEvent.click(
          screen.getByRole("button", { name: "usageScript.testScript" }),
        );

        expect(getBalance).toHaveBeenCalledWith(
          "https://api.deepseek.com/v1",
          apiKey,
        );
      } finally {
        getBalance.mockRestore();
      }
    });

    it("shows inherited credentials in the custom template variables", async () => {
      renderAppModal();
      await userEvent.click(
        screen.getByRole("button", { name: "usageScript.templateCustom" }),
      );

      expect(
        screen.getByText("https://api.deepseek.com/v1"),
      ).toBeInTheDocument();
      await userEvent.click(
        screen.getByRole("button", { name: "apiKeyInput.show" }),
      );
      expect(screen.getByText(apiKey)).toBeInTheDocument();
    });
  },
);