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

7.9 KB
Raw Blame
import {
  act,
  fireEvent,
  render,
  screen,
  waitFor,
} from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { useState } from "react";
import { CodexQuotaProtectionSettings } from "@/components/settings/CodexQuotaProtectionSettings";
import type { SettingsFormState } from "@/hooks/useSettings";

vi.mock("react-i18next", () => ({
  useTranslation: () => ({ t: (key: string) => key }),
}));

const { toastError } = vi.hoisted(() => ({ toastError: vi.fn() }));
vi.mock("@/lib/toast", () => ({ toast: { error: toastError } }));

const key = (name: string) => `settings.codexQuotaProtection.${name}`;

const ENABLED = { enabled: true, fiveHourThreshold: 95, weeklyThreshold: 98 };

function setup(
  initial: Partial<SettingsFormState> = { codexQuotaProtection: ENABLED },
  save = vi.fn().mockResolvedValue(true),
) {
  function Form() {
    const [settings, setSettings] = useState(initial as SettingsFormState);
    return (
      <CodexQuotaProtectionSettings
        settings={settings}
        onChange={async (updates) => {
          // Match SettingsPage: update optimistically, then roll back on failure.
          const previous = settings;
          setSettings({ ...settings, ...updates });
          try {
            const saved = await save(updates);
            if (saved === false) setSettings(previous);
            return saved;
          } catch (error) {
            setSettings(previous);
            throw error;
          }
        }}
      />
    );
  }
  render(<Form />);
  return save;
}

describe("Codex official quota protection settings", () => {
  it.each(["false", "reject"])(
    "preserves both drafts after an optimistic update rolls back (%s), then retries",
    async (failure) => {
      let complete!: (value: boolean) => void;
      let reject!: (error: Error) => void;
      const pending = new Promise<boolean>((resolve, fail) => {
        complete = resolve;
        reject = fail;
      });
      const save = setup(
        undefined,
        vi.fn().mockReturnValueOnce(pending).mockResolvedValue(true),
      );
      const fiveHour = screen.getByRole("spinbutton", {
        name: key("fiveHour"),
      });
      const weekly = screen.getByRole("spinbutton", { name: key("weekly") });
      const submit = screen.getByRole("button", { name: key("save") });
      fireEvent.change(fiveHour, { target: { value: "89" } });
      fireEvent.change(weekly, { target: { value: "92" } });
      fireEvent.click(submit);
      await waitFor(() => expect(fiveHour).toBeDisabled());
      await act(async () => {
        if (failure === "false") complete(false);
        else reject(new Error("disk full"));
      });
      expect(fiveHour).toHaveValue(89);
      expect(weekly).toHaveValue(92);
      expect(submit).toBeEnabled();
      await act(async () => {
        fireEvent.click(submit);
      });
      expect(save).toHaveBeenCalledTimes(2);
      expect(save).toHaveBeenLastCalledWith({
        codexQuotaProtection: {
          enabled: true,
          fiveHourThreshold: 89,
          weeklyThreshold: 92,
        },
      });
      expect(submit).toBeDisabled();
    },
  );

  it("keeps typed thresholds when restoring defaults fails", async () => {
    setup(undefined, vi.fn().mockResolvedValue(false));
    const fiveHour = screen.getByRole("spinbutton", { name: key("fiveHour") });
    fireEvent.change(fiveHour, { target: { value: "89" } });
    await act(async () => {
      fireEvent.click(screen.getByRole("button", { name: key("reset") }));
    });
    expect(fiveHour).toHaveValue(89);
    expect(screen.getByRole("button", { name: key("save") })).toBeEnabled();
  });

  it("reports a rejected save and leaves the draft retryable", async () => {
    setup(undefined, vi.fn().mockRejectedValue(new Error("disk full")));
    fireEvent.change(
      screen.getByRole("spinbutton", { name: key("fiveHour") }),
      {
        target: { value: "91" },
      },
    );
    await act(async () => {
      fireEvent.click(screen.getByRole("button", { name: key("save") }));
    });
    expect(toastError).toHaveBeenCalledWith("notifications.saveFailedGeneric");
    expect(screen.getByRole("button", { name: key("save") })).toBeEnabled();
  });
  it("is on by default with the 95% / 98% defaults and can be turned off", async () => {
    const save = setup({});
    const toggle = screen.getByRole("switch", { name: key("title") });
    expect(toggle).toHaveAttribute("aria-checked", "true");
    expect(
      screen.getByRole("spinbutton", { name: key("fiveHour") }),
    ).toHaveValue(95);
    await act(async () => {
      fireEvent.click(toggle);
    });
    expect(save).toHaveBeenLastCalledWith({
      codexQuotaProtection: { ...ENABLED, enabled: false },
    });
    expect(screen.queryByRole("spinbutton")).not.toBeInTheDocument();
    await act(async () => {
      fireEvent.click(toggle);
    });
    expect(save).toHaveBeenLastCalledWith({ codexQuotaProtection: ENABLED });
    expect(
      screen.getByRole("spinbutton", { name: key("fiveHour") }),
    ).toHaveValue(95);
    expect(screen.getByRole("spinbutton", { name: key("weekly") })).toHaveValue(
      98,
    );
  });

  it("saves independently edited thresholds together", async () => {
    const save = setup();
    expect(screen.getByRole("switch", { name: key("title") })).toHaveAttribute(
      "aria-checked",
      "true",
    );
    const fiveHour = screen.getByRole("spinbutton", { name: key("fiveHour") });
    const weekly = screen.getByRole("spinbutton", { name: key("weekly") });
    expect(fiveHour).toHaveValue(95);
    expect(weekly).toHaveValue(98);
    expect(screen.getByRole("button", { name: key("save") })).toBeDisabled();
    fireEvent.change(fiveHour, { target: { value: "90" } });
    expect(save).not.toHaveBeenCalled();
    fireEvent.click(screen.getByRole("button", { name: key("save") }));
    await waitFor(() =>
      expect(save).toHaveBeenCalledWith({
        codexQuotaProtection: {
          enabled: true,
          fiveHourThreshold: 90,
          weeklyThreshold: 98,
        },
      }),
    );
    await waitFor(() =>
      expect(screen.getByRole("button", { name: key("save") })).toBeDisabled(),
    );
  });

  it.each(["", "0", "100", "95.5", "-1"])(
    "rejects invalid threshold %j without persisting it",
    (value) => {
      const save = setup();
      fireEvent.change(
        screen.getByRole("spinbutton", { name: key("weekly") }),
        { target: { value } },
      );
      expect(screen.getByRole("alert")).toHaveTextContent(key("invalid"));
      expect(screen.getByRole("button", { name: key("save") })).toBeDisabled();
      expect(save).not.toHaveBeenCalled();
    },
  );

  it("restores defaults and preserves the ability to disable protection", async () => {
    const save = setup({
      codexQuotaProtection: {
        enabled: true,
        fiveHourThreshold: 85,
        weeklyThreshold: 90,
      },
    });
    fireEvent.click(screen.getByRole("button", { name: key("reset") }));
    await waitFor(() =>
      expect(
        screen.getByRole("spinbutton", { name: key("fiveHour") }),
      ).toHaveValue(95),
    );
    await act(async () => {
      fireEvent.click(screen.getByRole("switch", { name: key("title") }));
    });
    expect(save).toHaveBeenLastCalledWith({
      codexQuotaProtection: {
        enabled: false,
        fiveHourThreshold: 95,
        weeklyThreshold: 98,
      },
    });
    expect(screen.queryByRole("spinbutton")).not.toBeInTheDocument();
  });

  it("keeps unsaved edits retryable when saving fails", async () => {
    const save = setup(undefined, vi.fn().mockResolvedValue(false));
    fireEvent.change(
      screen.getByRole("spinbutton", { name: key("fiveHour") }),
      { target: { value: "89" } },
    );
    await act(async () => {
      fireEvent.click(screen.getByRole("button", { name: key("save") }));
    });
    expect(save).toHaveBeenCalledTimes(1);
    expect(screen.getByRole("button", { name: key("save") })).toBeEnabled();
    expect(
      screen.getByRole("spinbutton", { name: key("fiveHour") }),
    ).toHaveValue(89);
  });
});