Files
cc-switch/tests/hooks/useUsageEventBridge.test.tsx
Jason 7a8087f688 feat(usage): scan session logs at the selected interval while the usage page is open
The usage page's auto-refresh interval only re-read the database, so
session usage still waited for the fixed 60-second background scan, and
routed usage already updated in real time through usage-log-recorded.
The interval now controls how often session logs are scanned:

- The background scan drops to every 10 minutes as a safety net against
  CLIs pruning old session files.
- While the usage page is visible it scans right away, again whenever
  the window becomes visible, and then at the selected interval
  (5/10/30/60s, default 60s). The first scan waits until settings load,
  so it never runs when automatic scanning is off.
- The "Off" option is removed (a saved 0 falls back to 60s), and the
  interval menu is hidden when automatic scanning is off.
- Statistics no longer poll. Imports refresh them through the
  usage-log-recorded event, which is always on again, and time-relative
  ranges re-run once a minute so "Today" rolls over at midnight and
  rolling windows drop old records without new usage.

Copy is updated in zh, zh-TW, en, ja and tr, and in the zh/en/ja manual.
2026-10-14 17:42:42 +08:00

30 lines
1.3 KiB
TypeScript

import type { PropsWithChildren } from "react";
import { act, cleanup, renderHook } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, describe, expect, it, vi } from "vitest";
import { useUsageEventBridge } from "@/hooks/useUsageEventBridge";
import { usageKeys } from "@/lib/query/usage";
import { emitTauriEvent } from "../msw/tauriMocks";
describe("useUsageEventBridge", () => {
afterEach(cleanup);
it("refreshes usage queries on every backend event until unmount", async () => {
const client = new QueryClient();
const invalidate = vi.spyOn(client, "invalidateQueries");
const wrapper = ({ children }: PropsWithChildren) => (
<QueryClientProvider client={client}>{children}</QueryClientProvider>
);
const { unmount } = renderHook(() => useUsageEventBridge(), { wrapper });
await act(async () => {});
act(() => emitTauriEvent("usage-log-recorded", null));
act(() => emitTauriEvent("usage-log-recorded", null));
expect(invalidate).toHaveBeenCalledTimes(2);
expect(invalidate).toHaveBeenCalledWith({ queryKey: usageKeys.all });
unmount();
act(() => emitTauriEvent("usage-log-recorded", null));
expect(invalidate).toHaveBeenCalledTimes(2);
client.clear();
});
});