Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Share polled and cached frontend state through the query client (#8075)

ConnorYoh4369f0a1a1bb
diff --git a/frontend/editor/src/cloud/hooks/useWallet.ts b/frontend/editor/src/cloud/hooks/useWallet.ts
index c432917502..157ee498c7 100644
--- a/frontend/editor/src/cloud/hooks/useWallet.ts
+++ b/frontend/editor/src/cloud/hooks/useWallet.ts
@@ -6,23 +6,12 @@
*
* <h2>Render efficiency</h2>
*
- * The hook is designed so {@code Plan}, {@code PaygFreeLeader/Member}, and
- * {@code PaygLeader/Member} re-render only on actual data change:
- *
- * <ul>
- * <li>{@link Wallet} snapshot is stored as a plain object — but every
- * successful fetch deep-compares with the previous snapshot and reuses
- * the prior reference if the payload is unchanged. Consumers that hold
- * a stable {@code wallet} reference get stable child memoisation.
- * <li>The returned {@link UseWalletResult} keeps stable callback identities
- * via {@code useCallback}. {@code Plan} can pass {@code markSubscribed}
- * to {@code UpgradeModal} without forcing a remount.
- * <li>{@code refetch / markSubscribed / updateCap} bump an internal counter
- * that the {@code useEffect} watches — no global state plumbing.
- * <li>A monotonic {@code requestId} ref drops stale responses so a slow
- * refetch from tick=N can't overwrite a faster one from tick=N+1
- * (out-of-order resolution would otherwise show old data).
- * </ul>
+ * {@code Plan}, {@code PaygFreeLeader/Member} and {@code PaygLeader/Member}
+ * re-render only on actual data change: the query client's structural sharing
+ * reuses the previous snapshot when the payload is unchanged, and drops a
+ * response superseded by a later one. The returned callbacks keep stable
+ * identities, so {@code Plan} can pass {@code markSubscribed} to
+ * {@code UpgradeModal} without forcing a remount.
*
* <h2>Mutation semantics</h2>
*
@@ -35,10 +24,11 @@
* <h2>Freshness</h2>
*
* The figures drain as metered work runs, so a mounted consumer re-reads the
- * wallet every {@link WALLET_POLL_MS} and again whenever the tab regains
- * visibility. Those refreshes are silent — they leave {@code loading} and
- * {@code error} alone and only commit fresher data — so consumers that gate on
- * those flags don't flicker on a background tick.
+ * wallet every {@link WALLET_POLL_MS} and again on returning to the tab once
+ * they are stale. Those refreshes are silent: {@code loading} tracks "nothing
+ * to show yet" rather than "a request is out", and a failure with a good
+ * snapshot behind it never surfaces — so consumers that gate on those flags
+ * don't flicker on a background tick.
*
* <h2>Dev preview fallback</h2>
*
@@ -53,8 +43,10 @@
* it. Desktop's cascade falls through to the cloud default (no dev preview), so
* it always fetches the real wallet.
*/
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useRef } from "react";
+import { useQuery } from "@tanstack/react-query";
import apiClient from "@app/services/apiClient";
+import { qk } from "@app/query/keys";
import { createPortalSession } from "@app/services/billing";
import { openExternal } from "@app/platform/openExternal";
import { getWalletDevPreview } from "@app/hooks/walletDevPreview";
@@ -114,80 +106,6 @@ export interface UseWalletResult {
// ─── Implementation ─────────────────────────────────────────────────────
-/**
- * Stable reference reuse — if the new payload deep-equals the previous one,
- * return the previous object so React's reference check short-circuits child
- * renders. Walks the top-level scalars first (cheapest), then the nested
- * {@code categoryBreakdown} object, then the {@code members} array. The
- * {@code recent} array is identity-compared only — Wave 1 always returns
- * {@code []} so a reference-stability check is sufficient; we'll deepen
- * this once the activity surface lands.
- */
-function reuseIfEqual(prev: Wallet | null, next: Wallet): Wallet {
- if (!prev) return next;
- if (
- prev.status !== next.status ||
- prev.teamId !== next.teamId ||
- prev.role !== next.role ||
- prev.billingPeriodStart !== next.billingPeriodStart ||
- prev.billingPeriodEnd !== next.billingPeriodEnd ||
- prev.billableUsed !== next.billableUsed ||
- prev.billableLimit !== next.billableLimit ||
- prev.freeAllowance !== next.freeAllowance ||
- prev.freeRemaining !== next.freeRemaining ||
- prev.includedPeriodStart !== next.includedPeriodStart ||
- prev.includedPeriodEnd !== next.includedPeriodEnd ||
- prev.pricePerDocMinor !== next.pricePerDocMinor ||
- prev.bundleRatePerCreditMinor !== next.bundleRatePerCreditMinor ||
- prev.currency !== next.currency ||
- prev.estimatedBillMinor !== next.estimatedBillMinor ||
- prev.capUsd !== next.capUsd ||
- prev.noCap !== next.noCap ||
- prev.stripeSubscriptionId !== next.stripeSubscriptionId ||
- prev.spendUnitsThisPeriod !== next.spendUnitsThisPeriod ||
- prev.docsProcessedThisPeriod !== next.docsProcessedThisPeriod ||
- prev.uniquePdfsThisPeriod !== next.uniquePdfsThisPeriod ||
- prev.sizeMultiplierPdfsThisPeriod !== next.sizeMultiplierPdfsThisPeriod ||
- prev.billingMode !== next.billingMode ||
- prev.prepaidUnitsRemaining !== next.prepaidUnitsRemaining ||
- prev.prepaidUnitsTotal !== next.prepaidUnitsTotal ||
- prev.prepaidExpiresAt !== next.prepaidExpiresAt
- ) {
- return next;
- }
- if (prev.recent.length !== next.recent.length) {
- return next;
- }
- if (
- prev.categoryBreakdown.api !== next.categoryBreakdown.api ||
- prev.categoryBreakdown.ai !== next.categoryBreakdown.ai ||
- prev.categoryBreakdown.automation !== next.categoryBreakdown.automation ||
- prev.categoryDocs.api !== next.categoryDocs.api ||
- prev.categoryDocs.ai !== next.categoryDocs.ai ||
- prev.categoryDocs.automation !== next.categoryDocs.automation
- ) {
- return next;
- }
- if (prev.members.length !== next.members.length) {
- return next;
- }
- for (let i = 0; i < prev.members.length; i++) {
- const a = prev.members[i];
- const b = next.members[i];
- if (
- a.userId !== b.userId ||
- a.name !== b.name ||
- a.email !== b.email ||
- a.spendUnits !== b.spendUnits
- ) {
- return next;
- }
- }
- // recent length-mismatch already returned `next` above; content (Wave 1 = []) is identical
- // otherwise, so reuse the prior reference for stable child memoisation.
- return prev;
-}
-
/**
* How often a mounted consumer re-reads the wallet. Matches the app query
* client's staleTime, so the sidebar meter and anything cached elsewhere age
@@ -204,150 +122,56 @@ export function useWallet(enabled = true): UseWalletResult {
// cloud/ may not touch directly.
const devPreview = useRef(getWalletDevPreview()).current;
- const [wallet, setWallet] = useState<Wallet | null>(null);
- const [loading, setLoading] = useState<boolean>(true);
- const [error, setError] = useState<string | null>(null);
- const [refetchTick, setRefetchTick] = useState(0);
-
- // Monotonic request id — used to discard stale responses if a faster
- // refetch lands first. Only the latest issued id is permitted to commit
- // its result.
- const latestReqId = useRef(0);
-
- // Promise tracking the most recent in-flight load. Mutations await this
- // so their resolution semantics are "the new state is visible," not
- // "the request fired." Cleared when no load is pending.
- const inFlight = useRef<Promise<void> | null>(null);
+ const {
+ data,
+ isPending,
+ error: readError,
+ refetch: read,
+ } = useQuery({
+ queryKey: qk.paygWallet(),
+ queryFn: async () =>
+ devPreview
+ ? devPreview.buildWallet(devPreview.role())
+ : (
+ await apiClient.get<Wallet>("/api/v1/payg/wallet", {
+ suppressErrorToast: true,
+ })
+ ).data,
+ enabled,
+ // The dev-preview wallet is synthesised locally, so there is nothing to
+ // re-read; a hidden tab pauses either way.
+ refetchInterval: devPreview ? false : WALLET_POLL_MS,
+ refetchOnWindowFocus: !devPreview,
+ // Deliberately not stale-timed: the key carries no team, and leaving a team
+ // changes which one the endpoint answers for without reloading the page. A
+ // mount and a tab return therefore always re-read, as they did before.
+ staleTime: 0,
+ // A failure self-heals on the next tick, so a retry only doubles the wait.
+ retry: false,
+ });
- // Set for refreshes the user didn't ask for (the poll below). Silence governs
- // whether a load may RAISE `loading` / `error`, never whether it may clear
- // them: consumers gate on both — the limit modals do
- // `if (loading || !wallet) return null`, and Plan swaps in an error alert —
- // so a background tick must not blink an open modal out or replace a working
- // page over a transient failure. Clearing is always the latest request's job,
- // silent or not; a silent load that skipped the clear would strand `loading`
- // true after superseding a visible one, which suppresses those modals for the
- // rest of the session.
- const silentRefresh = useRef(false);
+ // Disabling shows nothing, rather than the last team's figures.
+ const wallet = enabled ? (data ?? null) : null;
+ // A failed refresh with a snapshot behind it is a non-event: the figures
+ // stand and the next tick self-heals. Only a failure that leaves nothing to
+ // show surfaces.
+ const surfaced = enabled && !wallet ? readError : null;
+ // Once per failure, not once per tick, or an offline tab warns every poll.
+ const warned = useRef(false);
useEffect(() => {
- const reqId = ++latestReqId.current;
- let cancelled = false;
-
- const silent = silentRefresh.current;
- silentRefresh.current = false;
-
- if (!enabled) {
- setWallet(null);
- setLoading(false);
- setError(null);
+ if (!surfaced) {
+ warned.current = false;
return;
}
-
- const promise = (async () => {
- if (!silent) {
- setLoading(true);
- setError(null);
- }
-
- if (devPreview) {
- const synth = devPreview.buildWallet(devPreview.role());
- if (cancelled || reqId !== latestReqId.current) return;
- setWallet((prev) => reuseIfEqual(prev, synth));
- setLoading(false);
- return;
- }
-
- try {
- const res = await apiClient.get<Wallet>("/api/v1/payg/wallet", {
- suppressErrorToast: true,
- });
- if (cancelled || reqId !== latestReqId.current) return;
- setWallet((prev) => reuseIfEqual(prev, res.data));
- // Fresh data retires any earlier failure, including one a silent poll
- // is recovering from — otherwise Plan keeps its alert over good data.
- setError(null);
- } catch (e: unknown) {
- if (cancelled || reqId !== latestReqId.current) return;
- if (!silent) {
- console.warn("[useWallet] fetch failed", e);
- setError(e instanceof Error ? e.message : "Failed to load wallet");
- }
- // A failed background refresh is a non-event: the last good snapshot
- // stands and the next tick self-heals, so it neither surfaces nor
- // logs — otherwise an offline tab warns every WALLET_POLL_MS.
- } finally {
- // Deliberately not gated on `silent`: whichever load is latest owns
- // settling the flag, or a silent refresh that supersedes a visible one
- // leaves it stuck true.
- if (!cancelled && reqId === latestReqId.current) {
- setLoading(false);
- }
- }
- })();
-
- inFlight.current = promise;
-
- return () => {
- cancelled = true;
- // Don't clear inFlight here — let it resolve so mutations awaiting it
- // still see a definitive "load completed" point. The reqId guard
- // upstream ensures stale results don't commit.
- };
- }, [devPreview, enabled, refetchTick]);
-
- // The wallet drains as automation, AI and API work runs, so a figure fetched
- // on mount goes stale while the user watches it. Refresh on a timer, and
- // immediately on returning to the tab — coming back to a stale number is the
- // case people actually notice. Hidden tabs don't poll, and the dev-preview
- // wallet is synthesised locally so there is nothing to re-read.
- useEffect(() => {
- if (!enabled || devPreview) return;
-
- let timer: ReturnType<typeof setInterval> | undefined;
- const refresh = () => {
- silentRefresh.current = true;
- setRefetchTick((t) => t + 1);
- };
- const stop = () => {
- if (timer !== undefined) {
- clearInterval(timer);
- timer = undefined;
- }
- };
- const start = () => {
- stop();
- timer = setInterval(refresh, WALLET_POLL_MS);
- };
- const onVisibilityChange = () => {
- if (document.visibilityState === "visible") {
- refresh();
- start();
- } else {
- stop();
- }
- };
-
- if (document.visibilityState === "visible") start();
- document.addEventListener("visibilitychange", onVisibilityChange);
- return () => {
- stop();
- document.removeEventListener("visibilitychange", onVisibilityChange);
- };
- }, [devPreview, enabled]);
+ if (warned.current) return;
+ warned.current = true;
+ console.warn("[useWallet] fetch failed", surfaced);
+ }, [surfaced]);
const refetch = useCallback(async () => {
- setRefetchTick((t) => t + 1);
- // Snapshot the next-tick promise so the caller awaits this refetch
- // specifically — the in-flight ref will be updated to it on the next
- // effect run, but we can't reference that synchronously, so settle for
- // a microtask handoff: await the *current* effect to flush, then await
- // the new in-flight promise.
- await Promise.resolve();
- if (inFlight.current) {
- await inFlight.current;
- }
- }, []);
+ await read();
+ }, [read]);
const markSubscribed = useCallback(
async (capUsd: number | null) => {
@@ -430,8 +254,14 @@ export function useWallet(enabled = true): UseWalletResult {
return {
wallet,
- loading,
- error,
+ // "Nothing to show yet", not "a request is out": a background tick must not
+ // blink an open limit modal, which gates on `loading || !wallet`.
+ loading: enabled && isPending,
+ error: surfaced
+ ? surfaced instanceof Error
+ ? surfaced.message
+ : "Failed to load wallet"
+ : null,
refetch,
markSubscribed,
updateCap,
diff --git a/frontend/editor/src/core/components/filesPage/FileManagerView.tsx b/frontend/editor/src/core/components/filesPage/FileManagerView.tsx
index ca1d136646..da1640d91c 100644
--- a/frontend/editor/src/core/components/filesPage/FileManagerView.tsx
+++ b/frontend/editor/src/core/components/filesPage/FileManagerView.tsx
@@ -6,6 +6,7 @@ import React, {
useRef,
useState,
} from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { useLocation, useNavigate } from "react-router-dom";
import {
@@ -16,6 +17,7 @@ import {
TextInput,
Tooltip,
} from "@mantine/core";
+import { qk } from "@app/query/keys";
import { ActionIcon } from "@app/ui/ActionIcon";
import { SegmentedControl } from "@app/ui/SegmentedControl";
import { useMediaQuery } from "@mantine/hooks";
@@ -64,7 +66,10 @@ import {
FilesPageEntry,
type DiskFileState,
} from "@app/components/filesPage/FileGrid";
-import { useProcessingFolders } from "@app/hooks/useProcessingFolders";
+import {
+ useProcessingFolders,
+ type MountedFileState,
+} from "@app/hooks/useProcessingFolders";
import { FolderProcessingSetup } from "@app/components/policies/FolderProcessingSetup";
import { useServerProcessingBlock } from "@app/hooks/useServerProcessingBlock";
import { FolderSweepWall } from "@app/components/policies/SweepRunWall";
@@ -571,15 +576,6 @@ export default function FileManagerView() {
const outputDirectory = currentLocalDirectory
? currentProcessing?.outputDirectory
: undefined;
- // Per-file state from the backend's ledger: processing in place leaves no output folder to
- // infer it from. Polled while the folder is open so badges follow the sweep live.
- const [fileStates, setFileStates] = useState<Map<string, DiskFileState>>(
- new Map(),
- );
- // Files whose pre-processing original is archived and can be restored.
- const [revertables, setRevertables] = useState<ReadonlySet<string>>(
- new Set(),
- );
const processingRecordId = currentProcessing?.id;
// The state layer applies inside any working folder: a mount's directory listing or a
// server folder's stored files, both joined to the same ledger behind listFiles.
@@ -587,31 +583,49 @@ export default function FileManagerView() {
processingRecordId && (outputDirectory || !currentLocalDirectory),
);
const { listFiles, retryFile, revertFile } = processingApi;
- useEffect(() => {
- if (!processingView || !processingRecordId) {
- // Keep the empty value when it is already empty: a fresh Map/Set is never Object.is equal,
- // so setting one unconditionally re-renders, on every render of a folder with no processing.
- setFileStates((prev) => (prev.size === 0 ? prev : new Map()));
- setRevertables((prev) => (prev.size === 0 ? prev : new Set()));
- return;
- }
- let cancelled = false;
- const tick = async () => {
- const files = await listFiles(processingRecordId).catch(() => []);
- if (!cancelled) {
- setFileStates(new Map(files.map((f) => [f.name, f.state])));
- setRevertables(
- new Set(files.filter((f) => f.hasOriginal).map((f) => f.name)),
- );
- }
- };
- void tick();
- const timer = setInterval(() => void tick(), 3000);
- return () => {
- cancelled = true;
- clearInterval(timer);
- };
- }, [processingView, processingRecordId, listFiles]);
+ const queryClient = useQueryClient();
+ const processingFilesKey = qk.processingFolderFiles(processingRecordId ?? "");
+ // Per-file state from the backend's ledger: processing in place leaves no output folder to
+ // infer it from. Polled while the folder is open so badges follow the sweep live, and the
+ // poll stands down with the tab rather than asking every 3s into a background window.
+ const { data: processingFiles } = useQuery({
+ queryKey: processingFilesKey,
+ // A failed read reports no states rather than an error: the badges are ambient
+ // and the next tick retries.
+ queryFn: () => listFiles(processingRecordId!).catch(() => []),
+ enabled: processingView && Boolean(processingRecordId),
+ refetchInterval: PROCESSING_FILES_POLL_MS,
+ });
+
+ // Stable empties for a folder with no processing: a fresh Map/Set is never
+ // Object.is equal, so returning one would re-render every reader for nothing.
+ const fileStates = useMemo(
+ () =>
+ processingFiles
+ ? new Map(processingFiles.map((f) => [f.name, f.state]))
+ : EMPTY_FILE_STATES,
+ [processingFiles],
+ );
+ // Files whose pre-processing original is archived and can be restored.
+ const revertables = useMemo(
+ () =>
+ processingFiles
+ ? new Set(
+ processingFiles.filter((f) => f.hasOriginal).map((f) => f.name),
+ )
+ : EMPTY_REVERTABLES,
+ [processingFiles],
+ );
+ /** Shows a just-made change ahead of the next poll. */
+ const patchProcessingFile = useCallback(
+ (name: string, patch: Partial<MountedFileState>) =>
+ queryClient.setQueryData<MountedFileState[]>(
+ processingFilesKey,
+ (prev) =>
+ prev?.map((f) => (f.name === name ? { ...f, ...patch } : f)) ?? prev,
+ ),
+ [queryClient, processingFilesKey],
+ );
const [processingSetupFolder, setProcessingSetupFolder] =
useState<FolderRecord | null>(null);
@@ -645,14 +659,7 @@ export default function FileManagerView() {
(name: string) => {
if (!processingRecordId) return;
void retryFile(processingRecordId, name)
- .then(() =>
- // Show the retry took, ahead of the next poll.
- setFileStates((prev) => {
- const next = new Map(prev);
- next.set(name, "processing");
- return next;
- }),
- )
+ .then(() => patchProcessingFile(name, { state: "processing" }))
.catch((err) =>
folders.setError(
err instanceof Error
@@ -668,25 +675,17 @@ export default function FileManagerView() {
),
);
},
- [processingRecordId, retryFile, folders, t],
+ [processingRecordId, retryFile, folders, t, patchProcessingFile],
);
const revertFolderFile = useCallback(
(name: string) => {
if (!processingRecordId) return;
void revertFile(processingRecordId, name)
- .then(() => {
- // Reflect the restore ahead of the next poll.
- setFileStates((prev) => {
- const next = new Map(prev);
- next.set(name, "waiting");
- return next;
- });
- setRevertables((prev) => {
- const next = new Set(prev);
- next.delete(name);
- return next;
- });
- })
+ .then(() =>
+ // Reflect the restore ahead of the next poll; the original is gone, so
+ // the row stops offering one.
+ patchProcessingFile(name, { state: "waiting", hasOriginal: false }),
+ )
.catch((err) =>
folders.setError(
err instanceof Error
@@ -2164,6 +2163,11 @@ export default function FileManagerView() {
* A cheap identity for a directory listing, so a background re-read only re-renders the
* grid when something actually changed on disk.
*/
+/** How often a working folder's per-file states re-read while it is open. */
+const PROCESSING_FILES_POLL_MS = 3000;
+const EMPTY_FILE_STATES: ReadonlyMap<string, DiskFileState> = new Map();
+const EMPTY_REVERTABLES: ReadonlySet<string> = new Set();
+
function listingSignature(
files: { path: string; sizeBytes: number; lastModified: number }[],
): string {
diff --git a/frontend/editor/src/core/components/filesPage/processingFolderCounts.test.tsx b/frontend/editor/src/core/components/filesPage/processingFolderCounts.test.tsx
index 05a8f8ec9b..4590a1c3b1 100644
--- a/frontend/editor/src/core/components/filesPage/processingFolderCounts.test.tsx
+++ b/frontend/editor/src/core/components/filesPage/processingFolderCounts.test.tsx
@@ -1,14 +1,24 @@
-import { beforeEach, expect, test } from "vitest";
-import { render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { act, render, screen, waitFor } from "@testing-library/react";
+import { QueryClientProvider } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+import { createAppQueryClient } from "@app/query/queryClient";
import { useProcessingFolderCounts } from "@app/components/filesPage/processingFolderCounts";
+import {
+ resetTabVisibility,
+ setTabHidden,
+} from "@app/tests/utils/tabVisibility";
const COUNTS = '{"processing":1,"done":2}';
+const POLL_MS = 5000;
let calls = 0;
+let byRecord: string[] = [];
/** Stable identity, as the real call site's useCallback lister has. */
-const listFiles = async (): Promise<{ state: string }[]> => {
+const listFiles = async (recordId: string): Promise<{ state: string }[]> => {
calls += 1;
+ byRecord.push(recordId);
return [{ state: "processing" }, { state: "done" }, { state: "done" }];
};
@@ -19,12 +29,27 @@ function Counts({ recordId, testId }: { recordId: string; testId: string }) {
);
}
+/** The app's own defaults, so a test can't pass on a library default the app overrides. */
+function mount(ui: ReactNode) {
+ const client = createAppQueryClient();
+ const result = render(
+ <QueryClientProvider client={client}>{ui}</QueryClientProvider>,
+ );
+ return { ...result, client };
+}
+
beforeEach(() => {
calls = 0;
+ byRecord = [];
+});
+
+afterEach(() => {
+ resetTabVisibility();
+ vi.useRealTimers();
});
test("reads the folder once and reports what it found", async () => {
- render(<Counts recordId="rec-read" testId="only" />);
+ mount(<Counts recordId="rec-read" testId="only" />);
await waitFor(() =>
expect(screen.getByTestId("only")).toHaveTextContent(COUNTS),
@@ -33,7 +58,7 @@ test("reads the folder once and reports what it found", async () => {
});
test("a second view of the same folder rides on the first one's request", async () => {
- render(
+ mount(
<>
<Counts recordId="rec-shared" testId="card" />
<Counts recordId="rec-shared" testId="row" />
@@ -47,13 +72,25 @@ test("a second view of the same folder rides on the first one's request", async
expect(calls).toBe(1);
});
+test("two folders on screen each read their own", async () => {
+ mount(
+ <>
+ <Counts recordId="rec-a" testId="a" />
+ <Counts recordId="rec-b" testId="b" />
+ </>,
+ );
+
+ await waitFor(() => expect(calls).toBe(2));
+ expect(new Set(byRecord)).toEqual(new Set(["rec-a", "rec-b"]));
+});
+
/**
* The counts arriving re-renders every subscriber. When that re-render resubscribed -
* an inline subscribe closure is a new identity each time - the store dropped its last
* subscriber, cleared the numbers and read again, at the speed of the network.
*/
test("the render its own result causes does not start another read", async () => {
- render(<Counts recordId="rec-loop" testId="loop" />);
+ mount(<Counts recordId="rec-loop" testId="loop" />);
await waitFor(() =>
expect(screen.getByTestId("loop")).toHaveTextContent(COUNTS),
@@ -62,3 +99,80 @@ test("the render its own result causes does not start another read", async () =>
expect(calls).toBe(1);
});
+
+/** The footgun the old store documented: an unstable lister must not cost a request. */
+test("a lister whose identity changes every render does not re-read", async () => {
+ function Unstable() {
+ const counts = useProcessingFolderCounts(
+ "rec-unstable",
+ async (recordId: string) => listFiles(recordId),
+ );
+ return <span data-testid="unstable">{counts ? "ok" : "-"}</span>;
+ }
+
+ const { rerender, client } = mount(<Unstable />);
+ await waitFor(() =>
+ expect(screen.getByTestId("unstable")).toHaveTextContent("ok"),
+ );
+
+ for (let i = 0; i < 5; i += 1) {
+ rerender(
+ <QueryClientProvider client={client}>
+ <Unstable />
+ </QueryClientProvider>,
+ );
+ }
+ await new Promise((resolve) => setTimeout(resolve, 200));
+
+ expect(calls).toBe(1);
+});
+
+describe("polling", () => {
+ beforeEach(() => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ });
+
+ test("keeps the numbers current while the tab is visible", async () => {
+ mount(<Counts recordId="rec-visible" testId="visible" />);
+ await waitFor(() => expect(calls).toBe(1));
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(POLL_MS * 4);
+ });
+
+ expect(calls).toBe(5);
+ });
+
+ test("stops requesting while the tab is hidden, and resumes on the next tick", async () => {
+ mount(<Counts recordId="rec-hidden" testId="hidden" />);
+ await waitFor(() => expect(calls).toBe(1));
+
+ setTabHidden(true);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(POLL_MS * 12);
+ });
+ expect(calls).toBe(1);
+
+ setTabHidden(false);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(POLL_MS);
+ });
+ expect(calls).toBe(2);
+ });
+
+ test("one poll serves both views of the same folder", async () => {
+ mount(
+ <>
+ <Counts recordId="rec-both" testId="card" />
+ <Counts recordId="rec-both" testId="row" />
+ </>,
+ );
+ await waitFor(() => expect(calls).toBe(1));
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(POLL_MS * 3);
+ });
+
+ expect(calls).toBe(4);
+ });
+});
diff --git a/frontend/editor/src/core/components/filesPage/processingFolderCounts.ts b/frontend/editor/src/core/components/filesPage/processingFolderCounts.ts
index b61c700797..35178fbf6d 100644
--- a/frontend/editor/src/core/components/filesPage/processingFolderCounts.ts
+++ b/frontend/editor/src/core/components/filesPage/processingFolderCounts.ts
@@ -1,4 +1,5 @@
-import { useCallback, useSyncExternalStore } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { qk } from "@app/query/keys";
export type ProcessingCounts = Record<string, number>;
@@ -6,75 +7,30 @@ type Lister = (recordId: string) => Promise<{ state: string }[]>;
const POLL_MS = 5000;
-const counts = new Map<string, ProcessingCounts>();
-const subscribers = new Map<string, Set<() => void>>();
-const inFlight = new Set<string>();
-let timer: ReturnType<typeof setInterval> | null = null;
-let lister: Lister | null = null;
-
-async function read(recordId: string): Promise<void> {
- // One reading at a time per folder: a second subscriber, or a tick arriving
- // while the last is still out, joins the request in flight.
- if (!lister || inFlight.has(recordId)) return;
- inFlight.add(recordId);
- try {
- const files = await lister(recordId).catch(() => []);
- const next: ProcessingCounts = {};
- for (const file of files) next[file.state] = (next[file.state] ?? 0) + 1;
- counts.set(recordId, next);
- for (const notify of subscribers.get(recordId) ?? []) notify();
- } finally {
- inFlight.delete(recordId);
- }
-}
-
-/** One pass over every folder on screen, rather than one timer each. */
-function tick(): void {
- for (const recordId of subscribers.keys()) void read(recordId);
-}
-
-function subscribe(recordId: string, notify: () => void): () => void {
- const forRecord = subscribers.get(recordId) ?? new Set<() => void>();
- forRecord.add(notify);
- subscribers.set(recordId, forRecord);
- // Only a folder with no numbers yet pays for a request on subscribe, so
- // scrolling rows in and out cannot spray them.
- if (!counts.has(recordId)) void read(recordId);
- timer ??= setInterval(tick, POLL_MS);
- return () => {
- forRecord.delete(notify);
- // The numbers outlive their last subscriber, so the snapshot never flips to
- // null under a component that is still mounted.
- if (forRecord.size === 0) subscribers.delete(recordId);
- if (subscribers.size === 0 && timer) {
- clearInterval(timer);
- timer = null;
- }
- };
-}
-
/**
* Live per-state counts for a processing folder. The numbers are shared, so a folder
* shown as a card and as a row - or the same row remounted by the list's windowing -
* costs one request per interval rather than one per component.
*
- * `listFiles` must keep a stable identity across renders: React resubscribes
- * whenever it changes, and every subscription opens with a request.
+ * The poll stands down while the tab is hidden and resumes on the next tick: a files
+ * page left open in a background tab asked every 5s indefinitely before.
*/
export function useProcessingFolderCounts(
recordId: string,
listFiles: Lister,
): ProcessingCounts | null {
- const subscribeToRecord = useCallback(
- (notify: () => void) => {
- lister = listFiles;
- return subscribe(recordId, notify);
+ const { data } = useQuery({
+ queryKey: qk.processingFolderCounts(recordId),
+ queryFn: async () => {
+ // A failed read reports no states rather than an error: the badge is ambient,
+ // and the next tick retries anyway.
+ const files = await listFiles(recordId).catch(() => []);
+ const counts: ProcessingCounts = {};
+ for (const file of files)
+ counts[file.state] = (counts[file.state] ?? 0) + 1;
+ return counts;
},
- [recordId, listFiles],
- );
- return useSyncExternalStore(
- subscribeToRecord,
- () => counts.get(recordId) ?? null,
- () => null,
- );
+ refetchInterval: POLL_MS,
+ });
+ return data ?? null;
}
diff --git a/frontend/editor/src/core/hooks/useFormDetectionModelStatus.test.tsx b/frontend/editor/src/core/hooks/useFormDetectionModelStatus.test.tsx
index 54570d6f30..34c61ab8ab 100644
--- a/frontend/editor/src/core/hooks/useFormDetectionModelStatus.test.tsx
+++ b/frontend/editor/src/core/hooks/useFormDetectionModelStatus.test.tsx
@@ -1,6 +1,19 @@
-import { beforeEach, describe, expect, it, vi, type Mock } from "vitest";
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+ type Mock,
+} from "vitest";
import { act, render, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { createAppQueryClient } from "@app/query/queryClient";
+import {
+ resetTabVisibility,
+ setTabHidden,
+} from "@app/tests/utils/tabVisibility";
vi.mock("@app/services/apiClient", () => ({
default: { get: vi.fn(), post: vi.fn(), delete: vi.fn() },
@@ -13,9 +26,14 @@ import {
type FormDetectionModelStatus,
} from "@app/hooks/useFormDetectionModelStatus";
-function statusPayload(enabled: boolean): FormDetectionModelStatus {
+const POLL_MS = 1500;
+
+function statusPayload(
+ enabled: boolean,
+ status: FormDetectionModelStatus["status"] = "ready",
+): FormDetectionModelStatus {
return {
- status: "ready",
+ status,
progress: 100,
activeModelId: "test-model",
installed: ["test-model"],
@@ -38,11 +56,35 @@ function Probe() {
);
}
+/** The app's own defaults, so a test can't pass on a library default the app overrides. */
+function mountWithAppDefaults() {
+ const client = createAppQueryClient();
+ const el = render(
+ <QueryClientProvider client={client}>
+ <Probe />
+ </QueryClientProvider>,
+ ).getByTestId("enabled");
+ return { client, el };
+}
+
+/** One poll's worth of time, plus the microtasks its response resolves through. */
+async function polls(count: number) {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(POLL_MS * count);
+ });
+}
+
describe("useFormDetectionModelStatus", () => {
beforeEach(() => {
hook = null;
(apiClient.get as Mock).mockReset();
(apiClient.post as Mock).mockReset().mockResolvedValue({ data: {} });
+ (apiClient.delete as Mock).mockReset().mockResolvedValue({ data: {} });
+ });
+
+ afterEach(() => {
+ resetTabVisibility();
+ vi.useRealTimers();
});
it("refreshes the tool availability cache when the master switch flips", async () => {
@@ -75,4 +117,93 @@ describe("useFormDetectionModelStatus", () => {
queryKey: qk.endpointEnabled("form-detection"),
});
});
+
+ it("surfaces a load failure rather than sitting on the spinner", async () => {
+ (apiClient.get as Mock).mockRejectedValue(new Error("backend down"));
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+
+ render(
+ <QueryClientProvider client={client}>
+ <Probe />
+ </QueryClientProvider>,
+ );
+
+ await waitFor(() => expect(hook!.error).toBe("backend down"));
+ expect(hook!.loading).toBe(false);
+ });
+
+ it("reports a failed write to the caller", async () => {
+ (apiClient.get as Mock).mockResolvedValue({ data: statusPayload(true) });
+ (apiClient.post as Mock).mockRejectedValue(new Error("install refused"));
+ const { el } = mountWithAppDefaults();
+ await waitFor(() => expect(el.textContent).toBe("true"));
+
+ await expect(hook!.install("m1")).rejects.toThrow("install refused");
+ });
+
+ it("carries the re-read with the write rather than after it", async () => {
+ (apiClient.get as Mock).mockResolvedValue({ data: statusPayload(true) });
+ const { el } = mountWithAppDefaults();
+ await waitFor(() => expect(el.textContent).toBe("true"));
+ expect(apiClient.get as Mock).toHaveBeenCalledTimes(1);
+
+ (apiClient.get as Mock).mockResolvedValue({ data: statusPayload(false) });
+ await act(async () => {
+ await hook!.uninstall("m1");
+ });
+
+ // The status request is already spent when the write resolves; React commits
+ // the result a tick later, so the count - not the DOM - is what proves it.
+ expect(apiClient.get as Mock).toHaveBeenCalledTimes(2);
+ await waitFor(() => expect(el.textContent).toBe("false"));
+ expect(apiClient.get as Mock).toHaveBeenCalledTimes(2);
+ });
+
+ describe("polling", () => {
+ beforeEach(() => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ });
+
+ it("reads repeatedly while a download is in flight", async () => {
+ (apiClient.get as Mock).mockResolvedValue({
+ data: statusPayload(true, "downloading"),
+ });
+ mountWithAppDefaults();
+ await polls(0);
+ expect(apiClient.get as Mock).toHaveBeenCalledTimes(1);
+
+ await polls(3);
+
+ expect(apiClient.get as Mock).toHaveBeenCalledTimes(4);
+ });
+
+ it("does not poll once the model has settled", async () => {
+ (apiClient.get as Mock).mockResolvedValue({ data: statusPayload(true) });
+ mountWithAppDefaults();
+ await polls(0);
+
+ await polls(10);
+
+ expect(apiClient.get as Mock).toHaveBeenCalledTimes(1);
+ });
+
+ it("stops reading while the tab is hidden, and resumes on the next tick", async () => {
+ (apiClient.get as Mock).mockResolvedValue({
+ data: statusPayload(true, "downloading"),
+ });
+ mountWithAppDefaults();
+ await polls(0);
+ expect(apiClient.get as Mock).toHaveBeenCalledTimes(1);
+
+ setTabHidden(true);
+ await polls(20);
+ expect(apiClient.get as Mock).toHaveBeenCalledTimes(1);
+
+ setTabHidden(false);
+ await polls(1);
+ expect(apiClient.get as Mock).toHaveBeenCalledTimes(2);
+ });
+ });
});
diff --git a/frontend/editor/src/core/hooks/useFormDetectionModelStatus.ts b/frontend/editor/src/core/hooks/useFormDetectionModelStatus.ts
index 8817d6143b..2a138829de 100644
--- a/frontend/editor/src/core/hooks/useFormDetectionModelStatus.ts
+++ b/frontend/editor/src/core/hooks/useFormDetectionModelStatus.ts
@@ -1,5 +1,5 @@
-import { useCallback, useEffect, useState } from "react";
-import { useQueryClient } from "@tanstack/react-query";
+import { useEffect } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import apiClient from "@app/services/apiClient";
import { qk } from "@app/query/keys";
@@ -38,44 +38,38 @@ const INSTALL_URL = "/api/v1/form/form-detection-model/install";
const CONFIG_URL = "/api/v1/form/form-detection-model/config";
const MODEL_URL = "/api/v1/form/form-detection-model";
+/** How often to re-read progress while a model is downloading or verifying. */
+const POLL_MS = 1500;
+
/**
* Polls model status while an install is in flight and exposes the admin actions. Readiness flips
* invalidate the endpoint-availability cache so the tool tile enables/disables.
+ *
+ * The poll pauses while the tab is hidden - a download nobody is watching stops being
+ * narrated, and the next tick on return carries the invalidation the tile needs.
*/
export function useFormDetectionModelStatus() {
const queryClient = useQueryClient();
- const [status, setStatus] = useState<FormDetectionModelStatus | null>(null);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState<string | null>(null);
-
- const fetchStatus = useCallback(async () => {
- try {
- const res = await apiClient.get<FormDetectionModelStatus>(STATUS_URL);
- setStatus(res.data);
- setError(null);
- } catch (e) {
- setError(e instanceof Error ? e.message : "Failed to load model status");
- } finally {
- setLoading(false);
- }
- }, []);
+ const queryKey = qk.formDetectionModelStatus();
- useEffect(() => {
- fetchStatus();
- }, [fetchStatus]);
+ const {
+ data: status = null,
+ isPending,
+ error: queryError,
+ refetch,
+ } = useQuery({
+ queryKey,
+ queryFn: async () =>
+ (await apiClient.get<FormDetectionModelStatus>(STATUS_URL)).data,
+ refetchInterval: ({ state }) =>
+ state.data?.status === "downloading" || state.data?.status === "verifying"
+ ? POLL_MS
+ : false,
+ });
const active = status?.status;
const featureEnabled = status?.enabled;
- // Poll only while an install is in flight.
- useEffect(() => {
- if (active === "downloading" || active === "verifying") {
- const id = setInterval(fetchStatus, 1500);
- return () => clearInterval(id);
- }
- return undefined;
- }, [active, fetchStatus]);
-
// Readiness and the master switch both gate the endpoint, so either flipping must refresh
// the tool availability cache.
useEffect(() => {
@@ -89,40 +83,43 @@ export function useFormDetectionModelStatus() {
}
}, [active, featureEnabled, queryClient]);
- const install = useCallback(
- async (modelId: string) => {
- await apiClient.post(INSTALL_URL, { modelId });
- await fetchStatus();
- },
- [fetchStatus],
- );
+ /** Each write re-reads status, so the caller's await settles on the new state. */
+ const afterWrite = () => queryClient.invalidateQueries({ queryKey });
- const uninstall = useCallback(
- async (modelId?: string) => {
- const url = modelId
- ? `${MODEL_URL}?modelId=${encodeURIComponent(modelId)}`
- : MODEL_URL;
- await apiClient.delete(url);
- await fetchStatus();
- },
- [fetchStatus],
- );
+ const install = useMutation({
+ mutationFn: (modelId: string) => apiClient.post(INSTALL_URL, { modelId }),
+ onSuccess: afterWrite,
+ });
- const setConfig = useCallback(
- async (config: { enabled?: boolean }) => {
- await apiClient.post(CONFIG_URL, config);
- await fetchStatus();
- },
- [fetchStatus],
- );
+ const uninstall = useMutation({
+ mutationFn: (modelId?: string) =>
+ apiClient.delete(
+ modelId
+ ? `${MODEL_URL}?modelId=${encodeURIComponent(modelId)}`
+ : MODEL_URL,
+ ),
+ onSuccess: afterWrite,
+ });
+
+ const setConfig = useMutation({
+ mutationFn: (config: { enabled?: boolean }) =>
+ apiClient.post(CONFIG_URL, config),
+ onSuccess: afterWrite,
+ });
return {
status,
- loading,
- error,
- refetch: fetchStatus,
- install,
- uninstall,
- setConfig,
+ loading: isPending,
+ error: queryError
+ ? queryError instanceof Error
+ ? queryError.message
+ : "Failed to load model status"
+ : null,
+ refetch: async () => {
+ await refetch();
+ },
+ install: install.mutateAsync,
+ uninstall: uninstall.mutateAsync,
+ setConfig: setConfig.mutateAsync,
};
}
diff --git a/frontend/editor/src/core/hooks/useNotifications.test.ts b/frontend/editor/src/core/hooks/useNotifications.test.ts
index 5bfa81bccb..5b99542f32 100644
--- a/frontend/editor/src/core/hooks/useNotifications.test.ts
+++ b/frontend/editor/src/core/hooks/useNotifications.test.ts
@@ -1,5 +1,9 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { act, renderHook, waitFor } from "@testing-library/react";
+import {
+ resetTabVisibility,
+ setTabHidden,
+} from "@app/tests/utils/tabVisibility";
import type {
AppNotification,
FetchedNotifications,
@@ -204,6 +208,33 @@ describe("useNotifications", () => {
await waitFor(() => expect(result.current.notifications).toHaveLength(2));
});
+ it("stops reading while the tab is hidden, and catches up on return", async () => {
+ vi.useFakeTimers();
+ try {
+ const bell = renderHook(() => useNotifications());
+ await act(async () => {});
+ const onMount = fetchNotifications.mock.calls.length;
+
+ setTabHidden(true);
+ await act(async () => {
+ vi.advanceTimersByTime(30_000 * 10);
+ });
+ expect(fetchNotifications).toHaveBeenCalledTimes(onMount);
+
+ // Back to the tab: the bell may be ten minutes stale, so it re-reads at once
+ // rather than waiting out another interval.
+ await act(async () => {
+ setTabHidden(false);
+ await Promise.resolve();
+ });
+ expect(fetchNotifications).toHaveBeenCalledTimes(onMount + 1);
+ bell.unmount();
+ } finally {
+ resetTabVisibility();
+ vi.useRealTimers();
+ }
+ });
+
it("polls on one timer and stops it when the last bell unmounts", async () => {
vi.useFakeTimers();
try {
diff --git a/frontend/editor/src/core/hooks/useNotifications.ts b/frontend/editor/src/core/hooks/useNotifications.ts
index 06858d6e05..ea308dffb3 100644
--- a/frontend/editor/src/core/hooks/useNotifications.ts
+++ b/frontend/editor/src/core/hooks/useNotifications.ts
@@ -211,19 +211,36 @@ function loadFresh(): void {
});
}
+/**
+ * The bell sits in the quick-nav rail, which renders above AppProviders and so
+ * above the query client - hence this store rather than a query. The one thing
+ * the client would give for free has to be spelled out: a backgrounded tab
+ * otherwise reads every 30s for the whole session, on every page.
+ */
+function pollIfWatching(): void {
+ if (document.visibilityState === "visible") void load();
+}
+
function startPolling(): void {
cycle += 1;
// Nothing counts as read until a read names the viewer, which errs towards showing failures.
snapshot = NOTHING_LOADED;
- pollTimer = window.setInterval(() => void load(), POLL_INTERVAL_MS);
+ pollTimer = window.setInterval(pollIfWatching, POLL_INTERVAL_MS);
+ document.addEventListener("visibilitychange", onVisibilityChange);
void load();
}
+/** Coming back to a stale bell is the case people notice, so catch up on return. */
+function onVisibilityChange(): void {
+ if (document.visibilityState === "visible") void load();
+}
+
function stopPolling(): void {
if (pollTimer !== null) {
window.clearInterval(pollTimer);
pollTimer = null;
}
+ document.removeEventListener("visibilitychange", onVisibilityChange);
// Drop anything in flight: its cycle has nobody watching it.
cycle += 1;
inFlight = null;
diff --git a/frontend/editor/src/core/hooks/useProcessingFolders.ts b/frontend/editor/src/core/hooks/useProcessingFolders.ts
index ebb6113944..63c9c51ecf 100644
--- a/frontend/editor/src/core/hooks/useProcessingFolders.ts
+++ b/frontend/editor/src/core/hooks/useProcessingFolders.ts
@@ -60,6 +60,8 @@ export interface ProcessingFoldersApi {
/** Remove the processing behaviour and its history; the folder and files stay. */
remove: (folder: FolderRecord) => Promise<void>;
sweep: (folder: FolderRecord) => Promise<void>;
+ /** Re-read the list — for a caller that created a folder outside these actions. */
+ refresh: () => Promise<void>;
}
const EMPTY_IDS: ReadonlySet<string> = new Set();
@@ -85,6 +87,7 @@ const INERT: ProcessingFoldersApi = {
disable: async () => {},
remove: async () => {},
sweep: async () => {},
+ refresh: async () => {},
};
/**
@@ -94,8 +97,3 @@ const INERT: ProcessingFoldersApi = {
export function useProcessingFolders(): ProcessingFoldersApi {
return INERT;
}
-
-/** Reload the shared list. No-op in core, which has no processing folders. */
-export function refreshProcessingFolders(): Promise<void> {
- return Promise.resolve();
-}
diff --git a/frontend/editor/src/core/query/keys.ts b/frontend/editor/src/core/query/keys.ts
index 0a759001fb..a66540b285 100644
--- a/frontend/editor/src/core/query/keys.ts
+++ b/frontend/editor/src/core/query/keys.ts
@@ -9,12 +9,27 @@ export const qk = {
endpointEnabled: (endpoint: string) =>
["editor", "endpointEnabled", endpoint] as const,
footerInfo: () => ["editor", "footerInfo"] as const,
+ formDetectionModelStatus: () =>
+ ["editor", "formDetectionModelStatus"] as const,
groupEnabled: (group: string) => ["editor", "groupEnabled", group] as const,
signingSessions: (userId: string | null) =>
["editor", "signingSessions", userId] as const,
+ /** The PAYG wallet: usage, allowance and cap for the signed-in team. */
+ paygWallet: () => ["editor", "paygWallet"] as const,
/** Keyed on the asking identity: two users must never share one answer. */
portalAccess: (userId: string | null) =>
["editor", "portalAccess", userId] as const,
+ /** Per-state file counts for one processing folder, polled while on screen. */
+ processingFolderCounts: (recordId: string) =>
+ ["editor", "processingFolderCounts", recordId] as const,
+ /** Every processing-folder record; shared by every folder row on the files page. */
+ processingFolders: () => ["editor", "processingFolders"] as const,
+ /** A working folder's per-file pipeline states, polled while it is open. */
+ processingFolderFiles: (recordId: string) =>
+ ["editor", "processingFolderFiles", recordId] as const,
+ /** The runs feed behind one folder's live sweep wall. */
+ processingFolderRuns: (policyId: string) =>
+ ["editor", "processingFolderRuns", policyId] as const,
teamDetails: (teamId: number) => ["editor", "teamDetails", teamId] as const,
teams: () => ["editor", "teams"] as const,
toolRecommendations: (context: string, limit: number, completions: number) =>
diff --git a/frontend/editor/src/core/query/useFoldPoll.ts b/frontend/editor/src/core/query/useFoldPoll.ts
new file mode 100644
index 0000000000..743964287b
--- /dev/null
+++ b/frontend/editor/src/core/query/useFoldPoll.ts
@@ -0,0 +1,30 @@
+import { useEffect, useRef } from "react";
+
+/**
+ * Runs `fold` once for each poll that lands, for a query whose consumer keeps
+ * state accumulated across polls rather than derived from the latest one.
+ *
+ * Keyed on `dataUpdatedAt`, not the data: structural sharing keeps the previous
+ * value's identity when a poll changed nothing, which is exactly the poll a
+ * "nothing happened again" counter needs to see.
+ *
+ * A consumer whose query can be served a value cached before it started
+ * watching must keep that value out of the cache rather than filter it here —
+ * a query disabled on the first render has nothing to compare against yet.
+ */
+export function useFoldPoll<T>(
+ data: T | undefined,
+ dataUpdatedAt: number,
+ fold: (value: T) => void,
+): void {
+ const foldedAt = useRef(0);
+ const latest = useRef(fold);
+ latest.current = fold;
+
+ useEffect(() => {
+ if (data === undefined || !dataUpdatedAt) return;
+ if (dataUpdatedAt === foldedAt.current) return;
+ foldedAt.current = dataUpdatedAt;
+ latest.current(data);
+ }, [data, dataUpdatedAt]);
+}
diff --git a/frontend/editor/src/core/tests/utils/tabVisibility.ts b/frontend/editor/src/core/tests/utils/tabVisibility.ts
new file mode 100644
index 0000000000..b4ae3d257a
--- /dev/null
+++ b/frontend/editor/src/core/tests/utils/tabVisibility.ts
@@ -0,0 +1,20 @@
+/**
+ * Drives the tab-visibility signal TanStack Query's focusManager listens to.
+ *
+ * The event must bubble: query-core subscribes on `window`, while the real
+ * `visibilitychange` is dispatched at `document` and reaches window by bubbling.
+ * A non-bubbling event on document leaves the manager focused, and a poll test
+ * written that way passes against an implementation that never pauses.
+ */
+export function setTabHidden(hidden: boolean): void {
+ Object.defineProperty(document, "visibilityState", {
+ configurable: true,
+ get: () => (hidden ? "hidden" : "visible"),
+ });
+ document.dispatchEvent(new Event("visibilitychange", { bubbles: true }));
+}
+
+/** Restores the jsdom default, for a suite that hid the tab. */
+export function resetTabVisibility(): void {
+ setTabHidden(false);
+}
diff --git a/frontend/editor/src/desktop/hooks/useWallet.test.tsx b/frontend/editor/src/desktop/hooks/useWallet.test.tsx
index 8fd77745e1..2c3c123aaa 100644
--- a/frontend/editor/src/desktop/hooks/useWallet.test.tsx
+++ b/frontend/editor/src/desktop/hooks/useWallet.test.tsx
@@ -1,4 +1,6 @@
-import { act, renderHook, waitFor } from "@testing-library/react";
+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
+import { QueryClientProvider } from "@tanstack/react-query";
+import type { ReactNode } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ConnectionConfig } from "@app/services/connectionModeService";
@@ -26,6 +28,16 @@ vi.mock("@app/services/connectionModeService", () => ({
}));
import { useWallet } from "@app/hooks/useWallet";
+import { createAppQueryClient } from "@app/query/queryClient";
+
+/** The hook reads through the shared cache, so it needs the app's own client. */
+function wrapper({ children }: { children: ReactNode }) {
+ return (
+ <QueryClientProvider client={createAppQueryClient()}>
+ {children}
+ </QueryClientProvider>
+ );
+}
describe("desktop wallet connection mode", () => {
beforeEach(() => {
@@ -34,13 +46,17 @@ describe("desktop wallet connection mode", () => {
mocks.get.mockReset();
});
- afterEach(() => vi.useRealTimers());
+ afterEach(() => {
+ // Unmount before real timers, or a live poll fires outside act.
+ cleanup();
+ vi.useRealTimers();
+ });
it.each([null, "local", "selfhosted"] as const)(
"does not fetch or poll with mode %s",
async (mode) => {
mocks.mode = mode;
- const { result } = renderHook(() => useWallet());
+ const { result } = renderHook(() => useWallet(), { wrapper });
await act(async () => {
vi.advanceTimersByTime(60_000);
@@ -62,7 +78,7 @@ describe("desktop wallet connection mode", () => {
resolveWallet = resolve;
}),
);
- const { result } = renderHook(() => useWallet());
+ const { result } = renderHook(() => useWallet(), { wrapper });
await waitFor(() => expect(mocks.get).toHaveBeenCalledTimes(1));
await act(async () => {
diff --git a/frontend/editor/src/desktop/services/backgroundRequestErrors.test.ts b/frontend/editor/src/desktop/services/backgroundRequestErrors.test.ts
index 2a8feba9fb..2b2a9e05ea 100644
--- a/frontend/editor/src/desktop/services/backgroundRequestErrors.test.ts
+++ b/frontend/editor/src/desktop/services/backgroundRequestErrors.test.ts
@@ -1,3 +1,4 @@
+import { TestQueryProvider } from "@app/tests/utils/TestQueryProvider";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, renderHook, waitFor } from "@testing-library/react";
import { fetch } from "@tauri-apps/plugin-http";
@@ -92,7 +93,9 @@ describe("desktop background requests through the HTTP interceptors", () => {
async (mode) => {
vi.useFakeTimers({ shouldAdvanceTime: true });
vi.mocked(connectionModeService.getCurrentMode).mockResolvedValue(mode);
- const { result } = renderHook(() => useWallet());
+ const { result } = renderHook(() => useWallet(), {
+ wrapper: TestQueryProvider,
+ });
await act(async () => {
await vi.advanceTimersByTimeAsync(90_000);
});
@@ -106,7 +109,9 @@ describe("desktop background requests through the HTTP interceptors", () => {
vi.useFakeTimers({ shouldAdvanceTime: true });
allowConsole.warn(/\[useWallet\] fetch failed/);
failRequest(500);
- const { result } = renderHook(() => useWallet());
+ const { result } = renderHook(() => useWallet(), {
+ wrapper: TestQueryProvider,
+ });
await waitFor(() => expect(result.current.error).not.toBeNull());
const initialRequests = vi.mocked(fetch).mock.calls.length;
for (let poll = 0; poll < 3; poll++) {
diff --git a/frontend/editor/src/portal/components/infrastructure/EncryptionPanel.test.tsx b/frontend/editor/src/portal/components/infrastructure/EncryptionPanel.test.tsx
new file mode 100644
index 0000000000..13424eaa9c
--- /dev/null
+++ b/frontend/editor/src/portal/components/infrastructure/EncryptionPanel.test.tsx
@@ -0,0 +1,191 @@
+import { afterEach, beforeEach, expect, test, vi } from "vitest";
+import { act, render, screen, waitFor } from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ i18n: { changeLanguage: vi.fn() },
+ }),
+}));
+
+vi.mock("@portal/api/storageEncryption", async (importOriginal) => {
+ const actual =
+ await importOriginal<typeof import("@portal/api/storageEncryption")>();
+ return {
+ ...actual,
+ fetchEncryptionStatus: vi.fn(),
+ fetchMigrationStatus: vi.fn(),
+ };
+});
+
+import { baseQueryOptions } from "@app/query/queryClient";
+import {
+ fetchEncryptionStatus,
+ fetchMigrationStatus,
+ type MigrationState,
+ type MigrationStatus,
+ type StorageEncryptionStatus,
+} from "@portal/api/storageEncryption";
+import { EncryptionPanel } from "@portal/components/infrastructure/EncryptionPanel";
+import {
+ resetTabVisibility,
+ setTabHidden,
+} from "@app/tests/utils/tabVisibility";
+
+const POLL_MS = 2000;
+const status = vi.mocked(fetchEncryptionStatus);
+const migration = vi.mocked(fetchMigrationStatus);
+
+function encryptionStatus(): StorageEncryptionStatus {
+ return {
+ writeEnabled: true,
+ active: true,
+ masterKeyFingerprint: "abc123",
+ masterKeyVersion: 1,
+ masterKeySource: "config",
+ provider: "local",
+ encryptedFiles: 10,
+ plaintextFiles: 5,
+ pendingRotationRows: 0,
+ keys: [],
+ };
+}
+
+function migrationStatus(
+ state: MigrationState,
+ processed = 1,
+): MigrationStatus {
+ return {
+ state,
+ total: 10,
+ processed,
+ skipped: 0,
+ failed: 0,
+ startedAt: "2026-01-01T00:00:00Z",
+ finishedAt: state === "RUNNING" ? null : "2026-01-01T00:01:00Z",
+ };
+}
+
+/** The app's own defaults, so a test can't pass on a library default the app overrides. */
+function appClient() {
+ return new QueryClient({ defaultOptions: { queries: baseQueryOptions } });
+}
+
+function mount(ui: ReactNode, client: QueryClient = appClient()) {
+ return render(
+ <QueryClientProvider client={client}>
+ <MantineProvider>{ui}</MantineProvider>
+ </QueryClientProvider>,
+ );
+}
+
+/** One poll's worth of time, plus the microtasks its response resolves through. */
+async function polls(count: number) {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(POLL_MS * count);
+ });
+}
+
+beforeEach(() => {
+ status.mockReset().mockResolvedValue(encryptionStatus());
+ migration.mockReset().mockResolvedValue(migrationStatus("IDLE"));
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+});
+
+afterEach(() => {
+ resetTabVisibility();
+ vi.useRealTimers();
+});
+
+/** Past the loading skeleton, so the panel's own state is on screen. */
+async function loaded() {
+ await waitFor(() =>
+ expect(
+ screen.queryByText("portal.infrastructure.encryption.coverage.heading"),
+ ).not.toBeNull(),
+ );
+}
+
+test("does not poll when no migration is running", async () => {
+ mount(<EncryptionPanel />);
+ await loaded();
+ const afterLoad = migration.mock.calls.length;
+
+ await polls(5);
+
+ expect(migration).toHaveBeenCalledTimes(afterLoad);
+});
+
+test("polls progress while a migration runs", async () => {
+ migration.mockResolvedValue(migrationStatus("RUNNING"));
+ mount(<EncryptionPanel />);
+ await loaded();
+ const afterLoad = migration.mock.calls.length;
+
+ await polls(3);
+
+ expect(migration.mock.calls.length).toBeGreaterThan(afterLoad + 2);
+});
+
+test("re-reads the coverage counts once the run finishes", async () => {
+ migration.mockResolvedValue(migrationStatus("RUNNING"));
+ mount(<EncryptionPanel />);
+ await loaded();
+ const statusReads = status.mock.calls.length;
+
+ migration.mockResolvedValue(migrationStatus("COMPLETED", 10));
+ await polls(1);
+
+ // The run changed the encrypted/plaintext split, so the card must not keep
+ // its pre-run counts.
+ await waitFor(() =>
+ expect(status.mock.calls.length).toBeGreaterThan(statusReads),
+ );
+});
+
+test("stops polling once the run is no longer active", async () => {
+ migration.mockResolvedValue(migrationStatus("RUNNING"));
+ mount(<EncryptionPanel />);
+ await loaded();
+
+ migration.mockResolvedValue(migrationStatus("COMPLETED", 10));
+ await polls(2);
+ const settled = migration.mock.calls.length;
+
+ await polls(5);
+
+ expect(migration).toHaveBeenCalledTimes(settled);
+});
+
+test("a failed poll leaves the run on screen for the next tick", async () => {
+ migration.mockResolvedValue(migrationStatus("RUNNING"));
+ mount(<EncryptionPanel />);
+ await loaded();
+
+ migration.mockRejectedValue(new Error("network"));
+ await polls(2);
+ const failed = migration.mock.calls.length;
+
+ // Still polling: a transient failure must not be read as the run having ended.
+ await polls(2);
+ expect(migration.mock.calls.length).toBeGreaterThan(failed);
+});
+
+test("stops reading while the tab is hidden, and resumes on the next tick", async () => {
+ migration.mockResolvedValue(migrationStatus("RUNNING"));
+ mount(<EncryptionPanel />);
+ await loaded();
+ await polls(1);
+ const beforeHide = migration.mock.calls.length;
+
+ setTabHidden(true);
+ await polls(30);
+ expect(migration).toHaveBeenCalledTimes(beforeHide);
+
+ setTabHidden(false);
+ await polls(1);
+ expect(migration.mock.calls.length).toBe(beforeHide + 1);
+});
diff --git a/frontend/editor/src/portal/components/infrastructure/EncryptionPanel.tsx b/frontend/editor/src/portal/components/infrastructure/EncryptionPanel.tsx
index 9d9ff3cb6c..0aaeb6eeb1 100644
--- a/frontend/editor/src/portal/components/infrastructure/EncryptionPanel.tsx
+++ b/frontend/editor/src/portal/components/infrastructure/EncryptionPanel.tsx
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useRef, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import {
Banner,
@@ -27,6 +28,8 @@ import {
type MigrationStatus,
type StorageEncryptionStatus,
} from "@portal/api/storageEncryption";
+import { qk } from "@portal/queries/keys";
+import { useFoldPoll } from "@app/query/useFoldPoll";
import { InfoHint } from "@portal/components/InfoHint";
import { SectionHeader } from "@portal/components/infrastructure/SectionHeader";
import { EncryptionKeyTable } from "@portal/components/infrastructure/EncryptionKeyTable";
@@ -112,23 +115,28 @@ export function EncryptionPanel({
}, [load]);
// Progress lives in the backend's memory, so poll only while a run is active.
- useEffect(() => {
- if (migration?.state !== "RUNNING") return;
- const timer = window.setInterval(() => {
- void fetchMigrationStatus()
- .then((next) => {
- if (!mounted.current) return;
- setMigration(next);
- // The run has just changed the encrypted/plaintext split, so re-read
- // status: without this the coverage card keeps its pre-run counts.
- if (next.state !== "RUNNING") void load();
- })
- .catch(() => {
- /* transient: the next tick retries */
- });
- }, MIGRATION_POLL_MS);
- return () => window.clearInterval(timer);
- }, [migration?.state, load]);
+ // The poll also stands down while the tab is hidden: a long migration left in
+ // a background tab asked every 2s for its whole duration.
+ const { data: polled, dataUpdatedAt } = useQuery({
+ queryKey: qk.encryptionMigration(),
+ queryFn: fetchMigrationStatus,
+ enabled: migration?.state === "RUNNING",
+ refetchInterval: MIGRATION_POLL_MS,
+ // Not kept past the panel: a finished run left in the cache is served to the
+ // next mount ahead of its first read, and folding it reports a run that has
+ // only just started as already done.
+ gcTime: 0,
+ // A failed read is transient; the next tick retries and the progress on
+ // screen stands, so a retry here would only double the request.
+ retry: false,
+ });
+
+ useFoldPoll(polled, dataUpdatedAt, (run) => {
+ setMigration(run);
+ // The run has just changed the encrypted/plaintext split, so re-read
+ // status: without this the coverage card keeps its pre-run counts.
+ if (run.state !== "RUNNING") void load();
+ });
const runKeyAction = async (
key: EncryptionKeyInfo,
diff --git a/frontend/editor/src/portal/hooks/useFreeCreditsSummary.ts b/frontend/editor/src/portal/hooks/useFreeCreditsSummary.ts
index b66128dd80..aab07318a7 100644
--- a/frontend/editor/src/portal/hooks/useFreeCreditsSummary.ts
+++ b/frontend/editor/src/portal/hooks/useFreeCreditsSummary.ts
@@ -2,8 +2,7 @@ import { useAccountLinkOwner } from "@app/portal/hooks/useAccountLinkOwner";
import { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useLink } from "@app/portal/contexts/LinkContext";
-import { fetchWallet } from "@app/portal/api/billing";
-import { qk } from "@app/portal/queries/keys";
+import { walletQuery } from "@app/portal/queries/wallet";
import {
readCachedCredits,
writeCachedCredits,
@@ -32,13 +31,13 @@ import { type NavFooterCredits } from "@app/components/shared/navFooter/NavFoote
*/
export function useFreeCreditsSummary(): NavFooterCredits | null {
const { isLinked } = useLink();
+ // Shared definition, not just a shared key: per-observer options are resolved
+ // per-observer, so differing retry or interval settings here would make the
+ // behaviour depend on which reader happened to fetch.
const isOwner = useAccountLinkOwner();
const canRead = isLinked && isOwner;
- // Shared query key, so the footer rides the same cached snapshot as any other
- // wallet reader rather than adding a fetch per mount.
const { data: wallet } = useQuery({
- queryKey: qk.wallet(isLinked),
- queryFn: fetchWallet,
+ ...walletQuery(isLinked),
enabled: canRead,
});
// Shared with the editor's seam, so crossing between the two apps shows the
diff --git a/frontend/editor/src/portal/queries/keys.ts b/frontend/editor/src/portal/queries/keys.ts
index 2962f3f016..66f92ebf31 100644
--- a/frontend/editor/src/portal/queries/keys.ts
+++ b/frontend/editor/src/portal/queries/keys.ts
@@ -18,6 +18,10 @@ export const qk = {
policyPermissions: () => ["portal", "policies", "permissions"] as const,
fleetStats: () => ["portal", "fleetStats"] as const,
appConfig: () => ["portal", "appConfig"] as const,
+ /** Storage-encryption migration progress, polled while a run is active. */
+ encryptionMigration: () => ["portal", "encryptionMigration"] as const,
+ /** Usage accrued on this instance since the last sync; self-hosted only. */
+ localUsage: () => ["portal", "localUsage"] as const,
// Keyed on scope: the open queue and the closed one are different reads.
fileRunEvents: (scope: FileRunEventScope) =>
["portal", "fileRunEvents", scope] as const,
diff --git a/frontend/editor/src/portal/queries/wallet.ts b/frontend/editor/src/portal/queries/wallet.ts
new file mode 100644
index 0000000000..ebfa7f3252
--- /dev/null
+++ b/frontend/editor/src/portal/queries/wallet.ts
@@ -0,0 +1,39 @@
+import type { UseQueryOptions } from "@tanstack/react-query";
+import { qk } from "@app/portal/queries/keys";
+import { fetchWallet, type Wallet } from "@app/portal/api/billing";
+
+/** How often a reader re-reads the wallet while its tab is in front. */
+export const WALLET_POLL_MS = 30_000;
+
+/**
+ * One definition for every wallet reader. The billing page and the sidebar's
+ * credits row share a cache entry, and per-observer options are resolved
+ * per-observer: divergent retry or interval settings on the same key mean the
+ * behaviour depends on which one happened to fetch.
+ */
+export function walletQuery(
+ linked: boolean,
+): Pick<
+ UseQueryOptions<Wallet>,
+ | "queryKey"
+ | "queryFn"
+ | "enabled"
+ | "refetchInterval"
+ | "refetchOnWindowFocus"
+ | "staleTime"
+ | "retry"
+> {
+ return {
+ queryKey: qk.wallet(linked),
+ queryFn: fetchWallet,
+ enabled: linked,
+ refetchInterval: WALLET_POLL_MS,
+ // staleTime is what stops a return to the tab costing a request: this page
+ // used to reload in full on every window focus event, which fires for an
+ // alt-tab or a dialog closing, not just a real return.
+ refetchOnWindowFocus: true,
+ staleTime: WALLET_POLL_MS,
+ // A failure is surfaced to the operator, and the next tick retries.
+ retry: false,
+ };
+}
diff --git a/frontend/editor/src/portal/views/Usage.test.tsx b/frontend/editor/src/portal/views/Usage.test.tsx
index 8dfbc141f9..5aa6763675 100644
--- a/frontend/editor/src/portal/views/Usage.test.tsx
+++ b/frontend/editor/src/portal/views/Usage.test.tsx
@@ -1,7 +1,7 @@
vi.mock("@app/portal/queries/infrastructure", () => ({
useFleetStats: () => ({ data: null, loading: false, error: null }),
}));
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
act,
fireEvent,
@@ -13,7 +13,13 @@ import { MantineProvider } from "@mantine/core";
import type { ReactElement } from "react";
import { StrictMode } from "react";
import { MemoryRouter, useLocation } from "react-router-dom";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { UIProvider } from "@app/portal/contexts/UIContext";
+import { baseQueryOptions } from "@app/query/queryClient";
+import {
+ resetTabVisibility,
+ setTabHidden,
+} from "@app/tests/utils/tabVisibility";
import type { ProcurementSnapshot } from "@app/portal/api/procurement";
// Usage renders Mantine-backed @app/ui components (e.g. the "Manage Payment"
@@ -28,17 +34,25 @@ function Location() {
);
}
+// The app's own query defaults, so a test can't pass on a library default the
+// app overrides - staleTime and refetchOnWindowFocus both govern this page.
const renderUsage = (ui: ReactElement, entry = "/settings/billing") =>
render(
<StrictMode>
- <MemoryRouter initialEntries={[entry]}>
- <UIProvider>
- <MantineProvider>
- {ui}
- <Location />
- </MantineProvider>
- </UIProvider>
- </MemoryRouter>
+ <QueryClientProvider
+ client={
+ new QueryClient({ defaultOptions: { queries: baseQueryOptions } })
+ }
+ >
+ <MemoryRouter initialEntries={[entry]}>
+ <UIProvider>
+ <MantineProvider>
+ {ui}
+ <Location />
+ </MantineProvider>
+ </UIProvider>
+ </MemoryRouter>
+ </QueryClientProvider>
</StrictMode>,
);
@@ -499,7 +513,9 @@ describe("Usage — link-free wallet renderer", () => {
);
});
expect(screen.getAllByText("Renew billing access")).toHaveLength(1);
- expect(screen.getByText(/Your plan and usage will appear/)).toBeVisible();
+ expect(
+ await screen.findByText(/Your plan and usage will appear/),
+ ).toBeVisible();
expect(screen.queryByText("Session expired")).not.toBeInTheDocument();
});
@@ -511,7 +527,6 @@ describe("Usage — link-free wallet renderer", () => {
),
).rejects.toBeInstanceOf(SaasSessionRequiredError);
fetchWallet
- .mockRejectedValueOnce(new SaasSessionRequiredError())
.mockRejectedValueOnce(new SaasSessionRequiredError())
.mockResolvedValue(walletOf("free"));
const onWalletLoaded = vi.fn();
@@ -530,12 +545,11 @@ describe("Usage — link-free wallet renderer", () => {
);
expect(screen.queryByText(/Your plan and usage will appear/)).toBeNull();
expect(screen.getByText("This cycle")).toBeVisible();
- expect(fetchWallet).toHaveBeenCalledTimes(3);
+ expect(fetchWallet).toHaveBeenCalledTimes(2);
});
it("reloads billing and clears the expired-session view after renewal", async () => {
fetchWallet
- .mockRejectedValueOnce(new SaasSessionRequiredError())
.mockRejectedValueOnce(new SaasSessionRequiredError())
.mockResolvedValue(walletOf("free"));
const onWalletLoaded = vi.fn();
@@ -552,7 +566,7 @@ describe("Usage — link-free wallet renderer", () => {
);
expect(screen.queryByText(/Your plan and usage will appear/)).toBeNull();
expect(screen.getByText("This cycle")).toBeVisible();
- expect(fetchWallet).toHaveBeenCalledTimes(3);
+ expect(fetchWallet).toHaveBeenCalledTimes(2);
});
});
@@ -570,3 +584,121 @@ it("requests pending usage for a self-hosted instance", async () => {
renderUsage(<Usage localUsersInUse={null} />);
await waitFor(() => expect(fetchLocalUsage).toHaveBeenCalled());
});
+
+describe("Usage — refresh cost", () => {
+ const wallet = {
+ status: "free",
+ role: "member",
+ currency: "usd",
+ freeAllowance: 500,
+ freeRemaining: 500,
+ spendUnitsThisPeriod: 0,
+ docsProcessedThisPeriod: 0,
+ sizeMultiplierPdfsThisPeriod: 0,
+ estimatedBillMinor: 0,
+ pricePerDocMinor: 1,
+ billingPeriodStart: "2026-09-01T00:00:00",
+ billingPeriodEnd: "2026-10-01T00:00:00",
+ team: { held: false, licensedUsers: null, usersInUse: 1 },
+ processor: { active: false },
+ };
+
+ beforeEach(() => {
+ fetchWallet.mockReset().mockResolvedValue(wallet);
+ refreshWalletCache.mockReset().mockResolvedValue(undefined);
+ fetchLocalUsage.mockReset().mockResolvedValue(null);
+ bundleFlow.status = "none";
+ procurement.loading = false;
+ procurement.loadError = null;
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ });
+
+ afterEach(() => {
+ resetTabVisibility();
+ vi.useRealTimers();
+ });
+
+ /** Settles the mount read before counting anything after it. */
+ async function mounted() {
+ await waitFor(() => expect(fetchWallet).toHaveBeenCalled());
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ return fetchWallet.mock.calls.length;
+ }
+
+ it("does not re-read the wallet for every window focus", async () => {
+ renderUsage(<Usage />);
+ const base = await mounted();
+
+ // Alt-tab, closing a dialog, clicking back from another app: all fire this.
+ for (let i = 0; i < 5; i += 1) {
+ fireEvent.focus(window);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ }
+
+ expect(fetchWallet).toHaveBeenCalledTimes(base);
+ });
+
+ it("re-reads on a schedule while the page is open", async () => {
+ renderUsage(<Usage />);
+ const base = await mounted();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(90_000);
+ });
+
+ expect(fetchWallet.mock.calls.length).toBeGreaterThan(base);
+ });
+
+ it("catches up on a tab return, but not for a return inside the fresh window", async () => {
+ renderUsage(<Usage />);
+ const base = await mounted();
+
+ // Straight back: the figures are seconds old, so the return costs nothing.
+ setTabHidden(true);
+ setTabHidden(false);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(fetchWallet).toHaveBeenCalledTimes(base);
+
+ // Back after long enough that they are stale, which is worth a read.
+ setTabHidden(true);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(120_000);
+ });
+ setTabHidden(false);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(fetchWallet.mock.calls.length).toBeGreaterThan(base);
+ });
+
+ it("stops reading while the tab is hidden", async () => {
+ renderUsage(<Usage />);
+ const base = await mounted();
+
+ setTabHidden(true);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(300_000);
+ });
+
+ expect(fetchWallet).toHaveBeenCalledTimes(base);
+ });
+
+ it("keeps the figures on screen while it re-reads", async () => {
+ const view = renderUsage(<Usage />);
+ await mounted();
+ const shown = view.container.textContent;
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(60_000);
+ });
+
+ // A revalidation must not blank the page back to its loading state.
+ expect(view.container.textContent).toBe(shown);
+ });
+});
diff --git a/frontend/editor/src/portal/views/Usage.tsx b/frontend/editor/src/portal/views/Usage.tsx
index c828a17d95..38f0b8f895 100644
--- a/frontend/editor/src/portal/views/Usage.tsx
+++ b/frontend/editor/src/portal/views/Usage.tsx
@@ -4,10 +4,12 @@ import { fleetUsersInUse } from "@app/billing/fleetSeats";
import {
useCallback,
useEffect,
+ useMemo,
useRef,
useState,
type ReactNode,
} from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { useSearchParams } from "react-router-dom";
import { Banner, Button } from "@app/ui";
@@ -21,19 +23,17 @@ import {
refreshWalletCache,
type Wallet,
} from "@app/portal/api/billing";
-import {
- fetchLocalUsage,
- triggerLocalSync,
- type LocalUsage,
-} from "@app/portal/api/link";
+import { fetchLocalUsage, triggerLocalSync } from "@app/portal/api/link";
import { useAccountLinkOptional } from "@app/portal/contexts/AccountLinkContext";
-import { useStripePortal } from "@app/portal/hooks/useStripePortal";
import { usePortalSaasSession } from "@app/portal/hooks/usePortalSaasSession";
+import { useStripePortal } from "@app/portal/hooks/useStripePortal";
+import { useBundleFlowState } from "@app/portal/hooks/useBundleFlowState";
import { FreePlanView } from "@app/portal/components/billing/FreePlanView";
import { PaymentSection } from "@app/portal/components/billing/PaymentSection";
import { InvoicesSection } from "@app/portal/components/billing/InvoicesSection";
import { useFleetStats } from "@app/portal/queries/infrastructure";
-import { useBundleFlowState } from "@app/portal/hooks/useBundleFlowState";
+import { qk } from "@app/portal/queries/keys";
+import { walletQuery, WALLET_POLL_MS } from "@app/portal/queries/wallet";
import { useCheckoutOptional } from "@app/contexts/CheckoutContext";
import { SubscribedPlanView } from "@app/portal/components/billing/SubscribedPlanView";
import {
@@ -81,12 +81,34 @@ export function Usage({
renderLicenseSection,
}: UsageProps = {}) {
const { t } = useTranslation();
+ const queryClient = useQueryClient();
+ // The gate renders this page only for a linked instance.
+ const walletOptions = walletQuery(true);
+ const walletKey = walletOptions.queryKey!;
+ const {
+ data: loadedWallet = null,
+ isPending: walletPending,
+ error: walletError,
+ refetch: refetchWallet,
+ // Moves on every successful read, which is what the renewal notice wants as
+ // its cue to re-read: the same triggers the page's old refresh counter had.
+ dataUpdatedAt: walletReadAt,
+ } = useQuery(walletOptions);
+ const refresh = useCallback(() => {
+ void refetchWallet();
+ void queryClient.invalidateQueries({ queryKey: qk.localUsage() });
+ }, [refetchWallet, queryClient]);
const accountLink = useAccountLinkOptional();
const { revision: sessionRevision, required } = usePortalSaasSession();
- const [loadedWallet, setWallet] = useState<Wallet | null>(null);
- const [sessionExpired, setSessionExpired] = useState(false);
+ const sessionExpired = walletError instanceof SaasSessionRequiredError;
const needsRenewal = Boolean(sessionRecovery) && (sessionExpired || required);
const wallet = needsRenewal ? null : loadedWallet;
+ const previousSessionRevision = useRef(sessionRevision);
+ useEffect(() => {
+ if (previousSessionRevision.current === sessionRevision) return;
+ previousSessionRevision.current = sessionRevision;
+ refresh();
+ }, [sessionRevision, refresh]);
const procurement = useProcurement();
const { trialSetupRequested, clearTrialSetupRequest } = useUI();
const [searchParams, setSearchParams] = useSearchParams();
@@ -135,10 +157,15 @@ export function Usage({
// Locally-accrued usage SaaS hasn't billed yet; added to the synced figure so
// "current usage" reflects work since the last daily sync. Best-effort.
const hasLocalInstance = localUsersInUse !== undefined;
- const [localUsage, setLocalUsage] = useState<LocalUsage | null>(null);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState<string | null>(null);
- const [refreshKey, setRefreshKey] = useState(0);
+ const { data: localUsage = null } = useQuery({
+ queryKey: qk.localUsage(),
+ queryFn: () => fetchLocalUsage().catch(() => null),
+ enabled: hasLocalInstance,
+ refetchInterval: WALLET_POLL_MS,
+ refetchOnWindowFocus: true,
+ staleTime: WALLET_POLL_MS,
+ retry: false,
+ });
const previousDeal = useRef(procurement.data);
useEffect(() => {
const previous = previousDeal.current;
@@ -149,7 +176,7 @@ export function Usage({
void refreshWalletCache()
.catch(() => {})
.then(() => {
- if (!cancelled) setRefreshKey((key) => key + 1);
+ if (!cancelled) refresh();
});
return () => {
cancelled = true;
@@ -176,69 +203,28 @@ export function Usage({
};
}, []);
+ // Reported as a fact to the link gate, which derives "subscribed" from it.
useEffect(() => {
- let cancelled = false;
- setLoading(true);
- setError(null);
- setSessionExpired(false);
- // Independent of the wallet load — a local-usage failure must not break the
- // page; it just means no unsynced delta is shown.
- if (hasLocalInstance)
- fetchLocalUsage()
- .then((u) => {
- if (!cancelled) setLocalUsage(u);
- })
- .catch(() => {
- if (!cancelled) setLocalUsage(null);
- });
- fetchWallet()
- .then((w) => {
- if (cancelled) return;
- setWallet(w);
- onWalletLoaded?.(w);
- })
- .catch((e) => {
- if (cancelled) return;
- if (e instanceof SaasSessionRequiredError) {
- // The attended SaaS session expired — offer a re-sign-in.
- setSessionExpired(true);
- } else if (e instanceof SaasUnconfiguredError) {
- setError(e.message);
- } else if (e instanceof HttpError) {
- setError(
- t(
- "portal.usage.error.walletUnavailable",
- "Wallet unavailable: {{status}} {{statusText}}",
- {
- status: e.status,
- statusText: e.statusText,
- },
- ),
- );
- } else {
- setError(e instanceof Error ? e.message : String(e));
- }
- })
- .finally(() => {
- if (!cancelled) setLoading(false);
- });
- return () => {
- cancelled = true;
- };
- }, [refreshKey, onWalletLoaded, t, sessionRevision, hasLocalInstance]);
+ if (wallet) onWalletLoaded?.(wallet);
+ }, [wallet, onWalletLoaded]);
+
+ // The SaaS session has lapsed and needs a re-sign-in (self-hosted only).
+
+ const error = useMemo(() => {
+ if (!walletError || sessionExpired) return null;
+ if (walletError instanceof SaasUnconfiguredError)
+ return walletError.message;
+ if (walletError instanceof HttpError)
+ return t(
+ "portal.usage.error.walletUnavailable",
+ "Wallet unavailable: {{status}} {{statusText}}",
+ { status: walletError.status, statusText: walletError.statusText },
+ );
+ return walletError instanceof Error
+ ? walletError.message
+ : String(walletError);
+ }, [walletError, sessionExpired, t]);
- const refresh = useCallback(() => setRefreshKey((k) => k + 1), []);
- useEffect(() => {
- const refreshVisible = () => {
- if (document.visibilityState === "visible") refresh();
- };
- window.addEventListener("focus", refreshVisible);
- const interval = window.setInterval(refreshVisible, 30_000);
- return () => {
- window.removeEventListener("focus", refreshVisible);
- window.clearInterval(interval);
- };
- }, [refresh]);
useEffect(() => {
const onBillingUpdated = () => {
void refreshWalletCache()
@@ -286,10 +272,11 @@ export function Usage({
localUsersInUse > localUserLimit
? { users: localUsersInUse, limit: localUserLimit }
: undefined,
- onSuccess: () => setRefreshKey((k) => k + 1),
+ onSuccess: refresh,
});
}, [
checkout,
+ refresh,
heldLimit,
usersInUse,
serverPlan,
@@ -350,8 +337,7 @@ export function Usage({
const w = await fetchWallet();
if (!mounted.current) return false;
if (w.status === "subscribed") {
- setWallet(w);
- onWalletLoaded?.(w);
+ queryClient.setQueryData(walletKey, w);
// Nudge the local instance to refresh its gate now so billable work
// unblocks immediately rather than on its next poll. Fire-and-forget;
// a no-op on SaaS (no local instance to sync).
@@ -366,7 +352,7 @@ export function Usage({
}
// Webhook still hasn't landed: re-fetch once more and report back so the modal
// shows its "almost there" notice rather than the page silently self-healing.
- setRefreshKey((k) => k + 1);
+ refresh();
return false;
}, [onWalletLoaded, hasLocalInstance]);
@@ -401,12 +387,12 @@ export function Usage({
}
serverPlan={serverPlan}
serverPlanAction={serverPlanAction}
- loading={loading}
+ loading={walletPending}
pendingUnits={localUsage?.totalUnsyncedUnits ?? 0}
notices={
<>
{wallet?.team?.held && wallet.role === "leader" && (
- <TeamSubscriptionChange refreshKey={refreshKey} />
+ <TeamSubscriptionChange refreshKey={walletReadAt} />
)}
{procurement.loadError && (
<Banner
diff --git a/frontend/editor/src/proprietary/components/policies/ProcessingFolderSetupFlow.tsx b/frontend/editor/src/proprietary/components/policies/ProcessingFolderSetupFlow.tsx
index 936bce6839..6cb7509394 100644
--- a/frontend/editor/src/proprietary/components/policies/ProcessingFolderSetupFlow.tsx
+++ b/frontend/editor/src/proprietary/components/policies/ProcessingFolderSetupFlow.tsx
@@ -12,10 +12,7 @@ import { useFileHandler } from "@app/hooks/useFileHandler";
import { useServerFolderBlock } from "@app/hooks/useServerFolderBlock";
import { useAiEngineEnabled } from "@app/hooks/useAiEngineEnabled";
import { useDownloadsProcessing } from "@app/hooks/useDownloadsProcessing";
-import {
- useProcessingFolders,
- refreshProcessingFolders,
-} from "@app/hooks/useProcessingFolders";
+import { useProcessingFolders } from "@app/hooks/useProcessingFolders";
import { canPickDirectory, pickDirectory } from "@app/services/directoryPicker";
import { saveProcessingFolder } from "@app/services/processingFolderApi";
import {
@@ -150,7 +147,7 @@ export function ProcessingFolderSetupFlow({
parameters: step.parameters ?? {},
})),
});
- void refreshProcessingFolders();
+ void processing.refresh();
if (onDisk)
void deliverSweepResults(saved.id, null, addFiles, {
excludeRunIds: baseline,
@@ -175,7 +172,7 @@ export function ProcessingFolderSetupFlow({
loading={folders.loading || processing.loading || presets.loading}
loadError={processing.loadError ?? presets.error}
onRetry={() => {
- void refreshProcessingFolders();
+ void processing.refresh();
setReload((current) => current + 1);
}}
canPickDirectory={canPickDirectory}
diff --git a/frontend/editor/src/proprietary/components/policies/SweepRunWall.test.tsx b/frontend/editor/src/proprietary/components/policies/SweepRunWall.test.tsx
new file mode 100644
index 0000000000..8bf9c6b8a0
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/SweepRunWall.test.tsx
@@ -0,0 +1,171 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { act, render, screen, waitFor } from "@testing-library/react";
+import { QueryClientProvider } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+
+vi.mock("@app/services/processingFolderApi", () => ({
+ fetchProcessingFolderRuns: vi.fn(),
+}));
+
+import { createAppQueryClient } from "@app/query/queryClient";
+import {
+ fetchProcessingFolderRuns,
+ type ProcessingFolderRun,
+} from "@app/services/processingFolderApi";
+import { FolderSweepWall } from "@app/components/policies/SweepRunWall";
+import {
+ resetTabVisibility,
+ setTabHidden,
+} from "@app/tests/utils/tabVisibility";
+
+const POLL_MS = 2000;
+const fetchRuns = vi.mocked(fetchProcessingFolderRuns);
+
+function run(fileName: string, status: string): ProcessingFolderRun {
+ return { runId: `${fileName}-${status}`, fileName, status };
+}
+
+/** The app's own defaults, so a test can't pass on a library default the app overrides. */
+function mount(ui: ReactNode) {
+ const client = createAppQueryClient();
+ return render(
+ <QueryClientProvider client={client}>{ui}</QueryClientProvider>,
+ );
+}
+
+/** One poll's worth of time, plus the microtasks its response resolves through. */
+async function polls(count: number) {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(POLL_MS * count);
+ });
+}
+
+/** Lets the first read land. The cache notifies asynchronously, so a bare
+ * waitFor on the spy returns before React has applied the result. */
+const settle = () => polls(0);
+
+const wall = () => screen.queryByText("processingFolders.wall.title");
+
+beforeEach(() => {
+ fetchRuns.mockReset().mockResolvedValue([]);
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+});
+
+afterEach(() => {
+ resetTabVisibility();
+ vi.useRealTimers();
+});
+
+test("renders nothing without a policy, and never polls", async () => {
+ mount(<FolderSweepWall />);
+ await polls(3);
+
+ expect(wall()).toBeNull();
+ expect(fetchRuns).not.toHaveBeenCalled();
+});
+
+test("stays down for history that was already finished when it opened", async () => {
+ fetchRuns.mockResolvedValue([run("old.pdf", "COMPLETED")]);
+ mount(<FolderSweepWall policyId="p1" />);
+
+ await settle();
+ await polls(2);
+
+ expect(wall()).toBeNull();
+});
+
+test("raises itself for a live run and counts the settled ones", async () => {
+ fetchRuns.mockResolvedValue([run("a.pdf", "RUNNING")]);
+ mount(<FolderSweepWall policyId="p1" />);
+
+ await waitFor(() => expect(wall()).not.toBeNull());
+ expect(screen.getByText("0/1")).toBeInTheDocument();
+
+ fetchRuns.mockResolvedValue([
+ run("a.pdf", "COMPLETED"),
+ run("b.pdf", "RUNNING"),
+ ]);
+ await polls(1);
+
+ await waitFor(() => expect(screen.getByText("1/2")).toBeInTheDocument());
+});
+
+test("stands down after three settled polls", async () => {
+ fetchRuns.mockResolvedValue([run("a.pdf", "RUNNING")]);
+ mount(<FolderSweepWall policyId="p1" />);
+ await waitFor(() => expect(wall()).not.toBeNull());
+
+ fetchRuns.mockResolvedValue([run("a.pdf", "COMPLETED")]);
+ await polls(2);
+ expect(wall()).not.toBeNull();
+
+ await polls(1);
+ await waitFor(() => expect(wall()).toBeNull());
+});
+
+test("wakes again for the next sweep after standing down", async () => {
+ fetchRuns.mockResolvedValue([run("a.pdf", "RUNNING")]);
+ mount(<FolderSweepWall policyId="p1" />);
+ await waitFor(() => expect(wall()).not.toBeNull());
+
+ fetchRuns.mockResolvedValue([run("a.pdf", "COMPLETED")]);
+ await polls(3);
+ await waitFor(() => expect(wall()).toBeNull());
+
+ fetchRuns.mockResolvedValue([
+ run("a.pdf", "COMPLETED"),
+ run("b.pdf", "RUNNING"),
+ ]);
+ await polls(1);
+
+ await waitFor(() => expect(wall()).not.toBeNull());
+});
+
+test("a failed poll counts as a settled one rather than freezing the wall", async () => {
+ fetchRuns.mockResolvedValue([run("a.pdf", "RUNNING")]);
+ mount(<FolderSweepWall policyId="p1" />);
+ await waitFor(() => expect(wall()).not.toBeNull());
+
+ fetchRuns.mockRejectedValue(new Error("network"));
+ await polls(3);
+
+ await waitFor(() => expect(wall()).toBeNull());
+});
+
+describe("polling", () => {
+ test("keeps reading while the tab is visible", async () => {
+ mount(<FolderSweepWall policyId="p1" />);
+ await settle();
+ expect(fetchRuns).toHaveBeenCalledTimes(1);
+
+ await polls(4);
+
+ expect(fetchRuns).toHaveBeenCalledTimes(5);
+ });
+
+ test("stops reading while the tab is hidden, and resumes on the next tick", async () => {
+ mount(<FolderSweepWall policyId="p1" />);
+ await settle();
+ expect(fetchRuns).toHaveBeenCalledTimes(1);
+
+ setTabHidden(true);
+ await polls(30);
+ expect(fetchRuns).toHaveBeenCalledTimes(1);
+
+ setTabHidden(false);
+ await polls(1);
+ expect(fetchRuns).toHaveBeenCalledTimes(2);
+ });
+
+ test("a hidden tab does not stall a sweep that is already on screen", async () => {
+ fetchRuns.mockResolvedValue([run("a.pdf", "RUNNING")]);
+ mount(<FolderSweepWall policyId="p1" />);
+ await waitFor(() => expect(wall()).not.toBeNull());
+
+ setTabHidden(true);
+ await polls(10);
+
+ // Still up: pausing the poll must not be read as the sweep having settled.
+ expect(wall()).not.toBeNull();
+ });
+});
diff --git a/frontend/editor/src/proprietary/components/policies/SweepRunWall.tsx b/frontend/editor/src/proprietary/components/policies/SweepRunWall.tsx
index 7528491304..6c76c41844 100644
--- a/frontend/editor/src/proprietary/components/policies/SweepRunWall.tsx
+++ b/frontend/editor/src/proprietary/components/policies/SweepRunWall.tsx
@@ -1,6 +1,9 @@
-import { useEffect, useRef, useState } from "react";
+import { useRef, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { useLabelName } from "@app/data/labelDisplay";
+import { qk } from "@app/query/keys";
+import { useFoldPoll } from "@app/query/useFoldPoll";
import {
fetchProcessingFolderRuns,
type ProcessingFolderRun,
@@ -24,13 +27,18 @@ export interface SweepWallCard {
labels: string[];
}
-/** Fold one poll of the runs feed into the wall's cards; a done card never regresses. */
+/**
+ * Fold one poll of the runs feed into the wall's cards; a done card never regresses.
+ * Returns {@code prev} when the poll said nothing new, so a sweep that has settled
+ * stops re-rendering the wall on every tick.
+ */
export function mergeRunsIntoCards(
prev: SweepWallCard[],
runs: ProcessingFolderRun[],
): SweepWallCard[] {
const byName = new Map(prev.map((card) => [card.name, card]));
const next: SweepWallCard[] = [...prev];
+ let changed = false;
for (const run of [...runs].reverse()) {
const name = run.fileName?.trim();
if (!name) continue;
@@ -45,13 +53,15 @@ export function mergeRunsIntoCards(
const card: SweepWallCard = { name, state, labels: [] };
byName.set(name, card);
next.push(card);
+ changed = true;
} else if (existing.state !== state && existing.state !== "done") {
const index = next.indexOf(existing);
next[index] = { ...existing, state };
byName.set(name, next[index]);
+ changed = true;
}
}
- return next;
+ return changed ? next : prev;
}
/** The wall itself: every document a sweep took on, lighting up as its run settles.
@@ -101,8 +111,18 @@ export interface FolderSweepWallProps {
/**
* A working folder's live sweep, wherever it came from. Polls the runs feed and raises a
* one-line strip only while runs execute: the grid below already wears each file's badge.
+ *
+ * The poll stands down while the tab is hidden: the wall keeps watching for the next
+ * sweep long after it has hidden itself, so a background tab polled indefinitely.
*/
export function FolderSweepWall({ policyId }: FolderSweepWallProps) {
+ if (!policyId) return null;
+ // Keyed, so opening a different folder starts from a clean wall rather than
+ // inheriting the previous one's cards.
+ return <FolderSweepWallFor key={policyId} policyId={policyId} />;
+}
+
+function FolderSweepWallFor({ policyId }: { policyId: string }) {
const { t } = useTranslation();
const [cards, setCards] = useState<SweepWallCard[]>([]);
const [visible, setVisible] = useState(false);
@@ -112,42 +132,33 @@ export function FolderSweepWall({ policyId }: FolderSweepWallProps) {
const wokeRef = useRef(false);
const idleRef = useRef(0);
- useEffect(() => {
- setCards([]);
- setVisible(false);
- setAnyRunning(false);
- wokeRef.current = false;
- idleRef.current = 0;
- if (!policyId) return;
- let cancelled = false;
- const tick = async () => {
- const runs = await fetchProcessingFolderRuns(policyId).catch(
+ const { data: runs, dataUpdatedAt } = useQuery({
+ queryKey: qk.processingFolderRuns(policyId),
+ // A failed read is an empty poll, not an error: it still advances the
+ // stand-down count, so a wall left up by a broken feed comes down.
+ queryFn: () =>
+ fetchProcessingFolderRuns(policyId).catch(
() => [] as ProcessingFolderRun[],
- );
- if (cancelled) return;
- const live = runs.some((run) => !TERMINAL.includes(run.status));
- setAnyRunning(live);
- if (live) {
- wokeRef.current = true;
- idleRef.current = 0;
- setVisible(true);
- }
- if (wokeRef.current) {
- setCards((prev) => mergeRunsIntoCards(prev, runs));
- if (!live && ++idleRef.current >= IDLE_POLLS) {
- wokeRef.current = false;
- setVisible(false);
- setCards([]);
- }
- }
- };
- void tick();
- const timer = setInterval(() => void tick(), POLL_MS);
- return () => {
- cancelled = true;
- clearInterval(timer);
- };
- }, [policyId]);
+ ),
+ refetchInterval: POLL_MS,
+ });
+
+ useFoldPoll(runs, dataUpdatedAt, (feed) => {
+ const live = feed.some((run) => !TERMINAL.includes(run.status));
+ setAnyRunning(live);
+ if (live) {
+ wokeRef.current = true;
+ idleRef.current = 0;
+ setVisible(true);
+ }
+ if (!wokeRef.current) return;
+ setCards((prev) => mergeRunsIntoCards(prev, feed));
+ if (!live && ++idleRef.current >= IDLE_POLLS) {
+ wokeRef.current = false;
+ setVisible(false);
+ setCards([]);
+ }
+ });
if (!visible || cards.length === 0) return null;
const settled = cards.filter(
diff --git a/frontend/editor/src/proprietary/hooks/useProcessingFolders.test.tsx b/frontend/editor/src/proprietary/hooks/useProcessingFolders.test.tsx
new file mode 100644
index 0000000000..da926af724
--- /dev/null
+++ b/frontend/editor/src/proprietary/hooks/useProcessingFolders.test.tsx
@@ -0,0 +1,173 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { act, render, waitFor } from "@testing-library/react";
+import { QueryClientProvider } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+
+vi.mock("@app/services/processingFolderApi", () => ({
+ CLASSIFY_OPERATION: "classify",
+ classificationDefaults: (folderId: string) => ({
+ folderId,
+ enabled: true,
+ steps: [],
+ }),
+ deleteProcessingFolder: vi.fn(),
+ fetchMountedFiles: vi.fn().mockResolvedValue([]),
+ fetchProcessingFolderRuns: vi.fn().mockResolvedValue([]),
+ fetchProcessingFolders: vi.fn(),
+ retryMountedFile: vi.fn(),
+ revertAllMountedFiles: vi.fn(),
+ revertMountedFile: vi.fn(),
+ saveProcessingFolder: vi.fn(),
+ sweepProcessingFolder: vi.fn(),
+}));
+vi.mock("@app/hooks/useFileHandler", () => ({
+ useFileHandler: () => ({ addFiles: vi.fn() }),
+}));
+vi.mock("@app/services/processingRunDelivery", () => ({
+ currentRunIds: vi.fn().mockResolvedValue(new Set()),
+ deliverSweepResults: vi.fn(),
+}));
+
+import { createAppQueryClient } from "@app/query/queryClient";
+import {
+ deleteProcessingFolder,
+ fetchProcessingFolders,
+ saveProcessingFolder,
+ type ProcessingFolder,
+} from "@app/services/processingFolderApi";
+import { useProcessingFolders } from "@app/hooks/useProcessingFolders";
+import type { FolderRecord } from "@app/types/folder";
+
+const listFolders = vi.mocked(fetchProcessingFolders);
+const save = vi.mocked(saveProcessingFolder);
+const remove = vi.mocked(deleteProcessingFolder);
+
+const FOLDER = { id: "f1", name: "Invoices" } as unknown as FolderRecord;
+
+function record(enabled: boolean): ProcessingFolder {
+ return {
+ id: "rec-1",
+ folderId: "f1",
+ directory: null,
+ enabled,
+ steps: [],
+ output: {},
+ } as unknown as ProcessingFolder;
+}
+
+let api: ReturnType<typeof useProcessingFolders> | null = null;
+
+function Probe() {
+ api = useProcessingFolders();
+ return (
+ <span data-testid="state">
+ {api.loading ? "loading" : String(api.anyEnabled)}
+ </span>
+ );
+}
+
+function mount(children: ReactNode) {
+ const client = createAppQueryClient();
+ return render(
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>,
+ );
+}
+
+beforeEach(() => {
+ api = null;
+ listFolders.mockReset().mockResolvedValue([record(true)]);
+ save.mockReset().mockResolvedValue(record(true));
+ remove.mockReset().mockResolvedValue(undefined);
+});
+
+it("reads the list once however many rows ask for it", async () => {
+ // The files page calls this per folder card and per row.
+ mount(
+ <>
+ <Probe />
+ <Probe />
+ <Probe />
+ <Probe />
+ <Probe />
+ </>,
+ );
+
+ await waitFor(() => expect(listFolders).toHaveBeenCalled());
+ await act(async () => {});
+
+ expect(listFolders).toHaveBeenCalledTimes(1);
+});
+
+it("reports a load failure without folders, rather than breaking the page", async () => {
+ listFolders.mockRejectedValue(new Error("storage off"));
+ mount(<Probe />);
+
+ await waitFor(() => expect(api!.loading).toBe(false));
+ expect(api!.loadError).toBe("storage off");
+ expect(api!.anyEnabled).toBe(false);
+});
+
+describe("writes", () => {
+ it("carries the re-read with the write rather than after it", async () => {
+ mount(<Probe />);
+ await waitFor(() => expect(api!.loading).toBe(false));
+ const reads = listFolders.mock.calls.length;
+
+ listFolders.mockResolvedValue([record(false)]);
+ await act(async () => {
+ await api!.disable(FOLDER);
+ });
+
+ // The read is already spent when the write resolves; React commits it a tick
+ // later, so the count - not the returned state - is what proves it.
+ expect(listFolders.mock.calls.length).toBeGreaterThan(reads);
+ await waitFor(() => expect(api!.anyEnabled).toBe(false));
+ });
+
+ it("refreshes once for a write, not once per mounted row", async () => {
+ mount(
+ <>
+ <Probe />
+ <Probe />
+ <Probe />
+ </>,
+ );
+ await waitFor(() => expect(api!.loading).toBe(false));
+ const reads = listFolders.mock.calls.length;
+
+ await act(async () => {
+ await api!.remove(FOLDER);
+ });
+
+ expect(listFolders.mock.calls.length).toBe(reads + 1);
+ });
+
+ /**
+ * Invalidation cancels an in-flight refresh and starts another, deliberately: a
+ * read that began before the second write cannot be trusted to show it. So two
+ * writes cost two refreshes, and the survivor is the one issued last.
+ */
+ it("shows the last of two writes issued together", async () => {
+ mount(<Probe />);
+ await waitFor(() => expect(api!.loading).toBe(false));
+
+ listFolders.mockResolvedValue([record(false)]);
+ await act(async () => {
+ await Promise.all([api!.disable(FOLDER), api!.remove(FOLDER)]);
+ });
+
+ await waitFor(() => expect(api!.anyEnabled).toBe(false));
+ });
+
+ it("does not refresh for a sweep, which changes no record", async () => {
+ mount(<Probe />);
+ await waitFor(() => expect(api!.loading).toBe(false));
+ const reads = listFolders.mock.calls.length;
+
+ await act(async () => {
+ await api!.sweep(FOLDER);
+ });
+
+ expect(listFolders.mock.calls.length).toBe(reads);
+ });
+});
diff --git a/frontend/editor/src/proprietary/hooks/useProcessingFolders.ts b/frontend/editor/src/proprietary/hooks/useProcessingFolders.ts
index 5fdc47327a..0dd4ef33bc 100644
--- a/frontend/editor/src/proprietary/hooks/useProcessingFolders.ts
+++ b/frontend/editor/src/proprietary/hooks/useProcessingFolders.ts
@@ -1,4 +1,5 @@
-import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
+import { useCallback, useMemo } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
import {
CLASSIFY_OPERATION,
classificationDefaults,
@@ -14,6 +15,7 @@ import {
type ProcessingFolder,
} from "@app/services/processingFolderApi";
import { useFileHandler } from "@app/hooks/useFileHandler";
+import { qk } from "@app/query/keys";
import {
currentRunIds,
deliverSweepResults,
@@ -54,61 +56,39 @@ export interface ProcessingFoldersApi extends Omit<
recordFor: (folder: FolderRecord) => ProcessingRecordSummary | undefined;
}
-/** One shared list for every consumer: the files page calls this once per folder row, so
- * per-instance state would mean a request per row and stale siblings after a mutation. */
-let folders: ProcessingFolder[] = [];
-let loaded = false;
-let loadError: string | null = null;
-let inFlight: Promise<void> | null = null;
-const listeners = new Set<() => void>();
-
-function subscribe(listener: () => void): () => void {
- listeners.add(listener);
- return () => listeners.delete(listener);
-}
-
-/** Snapshot identity only changes when the list is replaced, so consumers re-render on real news. */
-function getSnapshot(): ProcessingFolder[] {
- return folders;
-}
-
-/** Load the list, sharing one request across concurrent callers; `force` bypasses an
- * in-flight read so a mutation observes its own effect. */
-function load(force = false): Promise<void> {
- if (inFlight && !force) return inFlight;
- const request = fetchProcessingFolders()
- .then((next) => {
- folders = next;
- loadError = null;
- })
- .catch((error: unknown) => {
- // Storage or login off, or unauthenticated: the files page works without these.
- folders = [];
- loadError = extractErrorMessage(error);
- })
- .finally(() => {
- loaded = true;
- if (inFlight === request) inFlight = null;
- listeners.forEach((listener) => listener());
- });
- inFlight = request;
- return request;
-}
+const EMPTY: ProcessingFolder[] = [];
/**
* Processing folders for the files page. Record identity is kind-shaped: a server folder
- * matches by storage folderId, a mount by the directory it mirrors. Every mutation reloads
+ * matches by storage folderId, a mount by the directory it mirrors. Every mutation invalidates
* rather than patching locally, so the list reflects what the server composed.
+ *
+ * One cache entry for every consumer: the files page calls this once per folder row, so a
+ * per-instance read would mean a request per row. Invalidating rather than force-reloading
+ * also collapses writes issued together into a single refresh.
*/
export function useProcessingFolders(): ProcessingFoldersApi {
- const current = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
- const loading = !loaded;
- const error = loadError;
+ const queryClient = useQueryClient();
const { addFiles } = useFileHandler();
+ const queryKey = qk.processingFolders();
- useEffect(() => {
- void load();
- }, []);
+ const {
+ data: current = EMPTY,
+ isPending: loading,
+ error: loadFailure,
+ } = useQuery({
+ queryKey,
+ queryFn: fetchProcessingFolders,
+ // Storage or login off, or unauthenticated: the files page works without these,
+ // so a failure reports itself rather than retrying into the same wall.
+ retry: false,
+ });
+ const error = loadFailure ? extractErrorMessage(loadFailure) : null;
+
+ const reload = useCallback(
+ () => queryClient.invalidateQueries({ queryKey }),
+ [queryClient],
+ );
const recordFor = useCallback(
(folder: FolderRecord): ProcessingFolder | undefined => {
@@ -206,7 +186,7 @@ export function useProcessingFolders(): ProcessingFoldersApi {
excludeRunIds: baseline,
});
}
- await load(true);
+ await reload();
return;
}
switch (folderKind(folder)) {
@@ -228,9 +208,9 @@ export function useProcessingFolders(): ProcessingFoldersApi {
default:
await saveProcessingFolder(classificationDefaults(folder.id));
}
- await load(true);
+ await reload();
},
- [recordFor, addFiles],
+ [recordFor, addFiles, reload],
);
// Pause, never delete: the kept history means resuming picks up only what is new.
@@ -246,9 +226,9 @@ export function useProcessingFolders(): ProcessingFoldersApi {
steps: existing.steps,
output: existing.output,
});
- await load(true);
+ await reload();
},
- [recordFor],
+ [recordFor, reload],
);
const remove = useCallback(
@@ -256,9 +236,9 @@ export function useProcessingFolders(): ProcessingFoldersApi {
const existing = recordFor(folder);
if (!existing) return;
await deleteProcessingFolder(existing.id);
- await load(true);
+ await reload();
},
- [recordFor],
+ [recordFor, reload],
);
const listActiveRuns = useCallback(
@@ -292,11 +272,14 @@ export function useProcessingFolders(): ProcessingFoldersApi {
[],
);
- const revertFile = useCallback(async (recordId: string, name: string) => {
- await revertMountedFile(recordId, name);
- // Revert pauses the folder server-side; reload so the pause shows at once.
- await load(true);
- }, []);
+ const revertFile = useCallback(
+ async (recordId: string, name: string) => {
+ await revertMountedFile(recordId, name);
+ // Revert pauses the folder server-side; reload so the pause shows at once.
+ await reload();
+ },
+ [reload],
+ );
const revertAll = useCallback(
async (folder: FolderRecord) => {
@@ -304,7 +287,7 @@ export function useProcessingFolders(): ProcessingFoldersApi {
if (!existing) return undefined;
const outcome = await revertAllMountedFiles(existing.id);
// Revert pauses the folder server-side; reload so the pause shows at once.
- await load(true);
+ await reload();
return outcome;
},
[recordFor],
@@ -343,6 +326,7 @@ export function useProcessingFolders(): ProcessingFoldersApi {
disable,
remove,
sweep,
+ refresh: reload,
}),
[
loading,
@@ -360,11 +344,7 @@ export function useProcessingFolders(): ProcessingFoldersApi {
disable,
remove,
sweep,
+ reload,
],
);
}
-
-/** Reload the shared list — for a caller that created a folder outside these actions. */
-export function refreshProcessingFolders(): Promise<void> {
- return load(true);
-}
diff --git a/frontend/editor/src/saas/hooks/useWallet.poll.test.tsx b/frontend/editor/src/saas/hooks/useWallet.poll.test.tsx
index e6c1a1ee11..52ae7b22dc 100644
--- a/frontend/editor/src/saas/hooks/useWallet.poll.test.tsx
+++ b/frontend/editor/src/saas/hooks/useWallet.poll.test.tsx
@@ -1,6 +1,12 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { renderHook, act, waitFor } from "@testing-library/react";
+import { renderHook, act, cleanup, waitFor } from "@testing-library/react";
+import { QueryClientProvider } from "@tanstack/react-query";
+import { useState, type ReactNode } from "react";
import { expectConsole } from "@app/tests/failOnConsole";
+import {
+ resetTabVisibility,
+ setTabHidden,
+} from "@app/tests/utils/tabVisibility";
const get = vi.fn();
vi.mock("@app/services/apiClient", () => ({
@@ -13,6 +19,13 @@ vi.mock("@app/services/billing", () => ({ createPortalSession: vi.fn() }));
vi.mock("@app/platform/openExternal", () => ({ openExternal: vi.fn() }));
const { useWallet } = await import("@app/hooks/useWallet");
+const { createAppQueryClient } = await import("@app/query/queryClient");
+
+/** The hook reads through the shared cache, so it needs the app's own client. */
+function wrapper({ children }: { children: ReactNode }) {
+ const [client] = useState(createAppQueryClient);
+ return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
+}
/** Full enough for the hook's deep-compare, which reads every field. */
function walletWith(freeRemaining: number) {
@@ -56,10 +69,13 @@ describe("useWallet — keeping the figures fresh", () => {
get.mockReset();
get.mockResolvedValue(walletWith(500));
});
- afterEach(() => vi.useRealTimers());
+ afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ });
it("re-reads the wallet on the poll interval", async () => {
- const { result } = renderHook(() => useWallet());
+ const { result } = renderHook(() => useWallet(), { wrapper });
await waitFor(() => expect(result.current.wallet).not.toBeNull());
expect(get).toHaveBeenCalledTimes(1);
@@ -72,7 +88,7 @@ describe("useWallet — keeping the figures fresh", () => {
});
it("polls silently, so consumers gating on loading/error don't flicker", async () => {
- const { result } = renderHook(() => useWallet());
+ const { result } = renderHook(() => useWallet(), { wrapper });
await waitFor(() => expect(result.current.wallet).not.toBeNull());
// A poll that fails must leave the last good snapshot, and must not raise
@@ -87,34 +103,30 @@ describe("useWallet — keeping the figures fresh", () => {
expect(result.current.wallet?.freeRemaining).toBe(500);
});
- it("settles loading when a silent poll supersedes an in-flight visible load", async () => {
- // The mount load raises `loading`; a poll firing before it lands cancels it.
- // If clearing the flag were the silent load's to skip, both would decline
- // and `loading` would stay true forever — which permanently suppresses the
- // limit modals, since they do `if (loading || !wallet) return null`.
- const visibility = vi.spyOn(document, "visibilityState", "get");
- visibility.mockReturnValue("visible");
-
+ it("settles loading when a poll arrives over an in-flight visible load", async () => {
+ // `loading` staying true would permanently suppress the limit modals, which
+ // do `if (loading || !wallet) return null`. A poll landing on top of the
+ // mount read is the case that used to risk it.
let landMount: (v: unknown) => void = () => {};
get.mockReturnValueOnce(
new Promise((resolve) => {
landMount = resolve;
}),
);
- const { result } = renderHook(() => useWallet());
+ const { result } = renderHook(() => useWallet(), { wrapper });
expect(result.current.loading).toBe(true);
get.mockResolvedValue(walletWith(470));
await act(async () => {
- document.dispatchEvent(new Event("visibilitychange"));
+ setTabHidden(false);
});
await act(async () => {
landMount(walletWith(500));
});
- await waitFor(() => expect(result.current.wallet?.freeRemaining).toBe(470));
- expect(result.current.loading).toBe(false);
- visibility.mockRestore();
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(result.current.wallet).not.toBeNull();
+ resetTabVisibility();
});
it("clears a stale error once a silent poll succeeds", async () => {
@@ -122,7 +134,7 @@ describe("useWallet — keeping the figures fresh", () => {
// retries stay quiet.
expectConsole.warn(/\[useWallet\] fetch failed/);
get.mockRejectedValueOnce(new Error("network blip"));
- const { result } = renderHook(() => useWallet());
+ const { result } = renderHook(() => useWallet(), { wrapper });
await waitFor(() => expect(result.current.error).not.toBeNull());
get.mockResolvedValue(walletWith(500));
@@ -135,31 +147,27 @@ describe("useWallet — keeping the figures fresh", () => {
});
it("stops polling while the tab is hidden and re-reads on return", async () => {
- const visibility = vi.spyOn(document, "visibilityState", "get");
- visibility.mockReturnValue("visible");
- const { result } = renderHook(() => useWallet());
+ const { result } = renderHook(() => useWallet(), { wrapper });
await waitFor(() => expect(result.current.wallet).not.toBeNull());
const afterMount = get.mock.calls.length;
- visibility.mockReturnValue("hidden");
await act(async () => {
- document.dispatchEvent(new Event("visibilitychange"));
+ setTabHidden(true);
vi.advanceTimersByTime(120_000);
});
expect(get).toHaveBeenCalledTimes(afterMount);
- visibility.mockReturnValue("visible");
await act(async () => {
- document.dispatchEvent(new Event("visibilitychange"));
+ setTabHidden(false);
});
await waitFor(() => expect(get.mock.calls.length).toBe(afterMount + 1));
- visibility.mockRestore();
+ resetTabVisibility();
});
it("stops a disabled reader and discards its in-flight wallet response", async () => {
const { result, rerender } = renderHook(
({ enabled }) => useWallet(enabled),
- { initialProps: { enabled: false } },
+ { initialProps: { enabled: false }, wrapper },
);
expect(get).not.toHaveBeenCalled();
diff --git a/frontend/editor/src/saas/hooks/useWallet.test.tsx b/frontend/editor/src/saas/hooks/useWallet.test.tsx
new file mode 100644
index 0000000000..79cf86c418
--- /dev/null
+++ b/frontend/editor/src/saas/hooks/useWallet.test.tsx
@@ -0,0 +1,298 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { act, cleanup, render, waitFor } from "@testing-library/react";
+import { QueryClientProvider } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+
+vi.mock("@app/services/apiClient", () => ({
+ default: { get: vi.fn(), post: vi.fn(), patch: vi.fn() },
+}));
+vi.mock("@app/services/billing", () => ({ createPortalSession: vi.fn() }));
+vi.mock("@app/platform/openExternal", () => ({ openExternal: vi.fn() }));
+vi.mock("@app/hooks/walletDevPreview", () => ({
+ getWalletDevPreview: () => null,
+}));
+
+import apiClient from "@app/services/apiClient";
+import { createAppQueryClient } from "@app/query/queryClient";
+// The saas cascade resolves this to cloud/hooks/useWallet, the build that ships
+// it; cloud/ has no test project of its own.
+import { useWallet, type Wallet } from "@app/hooks/useWallet";
+import {
+ resetTabVisibility,
+ setTabHidden,
+} from "@app/tests/utils/tabVisibility";
+import { expectConsole } from "@app/tests/failOnConsole";
+
+const POLL_MS = 30_000;
+const get = vi.mocked(apiClient.get);
+
+function wallet(over: Partial<Wallet> = {}): Wallet {
+ return {
+ status: "free",
+ teamId: 1,
+ role: "leader",
+ billingPeriodStart: "2026-09-01",
+ billingPeriodEnd: "2026-10-01",
+ billableUsed: 0,
+ billableLimit: 0,
+ freeAllowance: 500,
+ freeRemaining: 500,
+ includedPeriodStart: null,
+ includedPeriodEnd: null,
+ pricePerDocMinor: 1,
+ bundleRatePerCreditMinor: null,
+ currency: "usd",
+ estimatedBillMinor: 0,
+ capUsd: null,
+ noCap: true,
+ stripeSubscriptionId: null,
+ spendUnitsThisPeriod: 0,
+ docsProcessedThisPeriod: 0,
+ uniquePdfsThisPeriod: 0,
+ sizeMultiplierPdfsThisPeriod: 0,
+ billingMode: "payg",
+ prepaidUnitsRemaining: null,
+ prepaidUnitsTotal: null,
+ prepaidExpiresAt: null,
+ freeUserAllowance: 5,
+ categoryBreakdown: { api: 0, ai: 0, automation: 0 },
+ categoryDocs: { api: 0, ai: 0, automation: 0 },
+ members: [],
+ recent: [],
+ team: { held: false, licensedUsers: null, usersInUse: 1 },
+ processor: { active: false },
+ ...over,
+ } as unknown as Wallet;
+}
+
+let hook: ReturnType<typeof useWallet> | null = null;
+
+function Probe({ enabled = true }: { enabled?: boolean }) {
+ hook = useWallet(enabled);
+ // Renders a nested field too, so a test can tell whether a change to one
+ // actually reaches a consumer.
+ return (
+ <span data-testid="s">
+ {hook.wallet?.status ?? "none"}/
+ {String(hook.wallet?.processor?.active ?? "?")}
+ </span>
+ );
+}
+
+/** Mounts with the first read already landed, so nothing settles outside act. */
+async function mount(ui: ReactNode) {
+ let view!: ReturnType<typeof render>;
+ await act(async () => {
+ view = render(
+ <QueryClientProvider client={createAppQueryClient()}>
+ {ui}
+ </QueryClientProvider>,
+ );
+ });
+ await settle();
+ return view;
+}
+
+/**
+ * Flushes until the read has been applied. The cache notifies on a scheduled
+ * batch, and the render it triggers only lands on the following turn, so this
+ * needs several separate acts rather than one long one.
+ */
+async function settle() {
+ for (let i = 0; i < 4; i += 1) {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ }
+}
+
+async function polls(count: number) {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(POLL_MS * count);
+ });
+ // Separate turn: the notification the advance scheduled lands here.
+ await settle();
+}
+
+beforeEach(() => {
+ hook = null;
+ get.mockReset().mockResolvedValue({ data: wallet() });
+ vi.mocked(apiClient.post).mockReset().mockResolvedValue({ data: {} });
+ vi.mocked(apiClient.patch).mockReset().mockResolvedValue({ data: {} });
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+});
+
+afterEach(() => {
+ // Unmount first: restoring real timers under a mounted consumer lets its poll
+ // fire outside act, and the warning lands on whichever test runs next.
+ cleanup();
+ resetTabVisibility();
+ vi.useRealTimers();
+});
+
+it("reads the wallet on mount", async () => {
+ await mount(<Probe />);
+
+ expect(hook!.wallet).not.toBeNull();
+ expect(hook!.loading).toBe(false);
+ expect(get).toHaveBeenCalledWith("/api/v1/payg/wallet", {
+ suppressErrorToast: true,
+ });
+});
+
+it("re-reads on a schedule, and stops while the tab is hidden", async () => {
+ await mount(<Probe />);
+ await polls(2);
+ const visible = get.mock.calls.length;
+ expect(visible).toBeGreaterThan(1);
+
+ setTabHidden(true);
+ await polls(10);
+
+ expect(get).toHaveBeenCalledTimes(visible);
+});
+
+describe("background refreshes are silent", () => {
+ it("does not raise loading on a background tick", async () => {
+ await mount(<Probe />);
+
+ let raised = false;
+ const watch = setInterval(() => {
+ if (hook?.loading) raised = true;
+ }, 10);
+ await polls(3);
+ clearInterval(watch);
+
+ expect(raised).toBe(false);
+ });
+
+ it("keeps the last good snapshot when a background read fails", async () => {
+ await mount(<Probe />);
+ const held = hook!.wallet;
+
+ get.mockRejectedValue(new Error("offline"));
+ await polls(2);
+
+ // A failed background refresh is a non-event: the figures still stand, and
+ // it never logs, or an offline tab would warn on every tick.
+ expect(hook!.wallet).toBe(held);
+ expect(hook!.error).toBeNull();
+ });
+
+ it("surfaces a failure that leaves nothing to show", async () => {
+ get.mockRejectedValue(new Error("no wallet"));
+ expectConsole.warn(/\[useWallet\] fetch failed/);
+ await mount(<Probe />);
+
+ expect(hook!.error).toBe("no wallet");
+ expect(hook!.loading).toBe(false);
+ expect(hook!.wallet).toBeNull();
+ });
+
+ it("retires an earlier failure once fresh data lands", async () => {
+ get.mockRejectedValue(new Error("no wallet"));
+ expectConsole.warn(/\[useWallet\] fetch failed/);
+ await mount(<Probe />);
+ expect(hook!.error).toBe("no wallet");
+
+ get.mockResolvedValue({ data: wallet() });
+ await act(async () => {
+ await hook!.refetch();
+ });
+ await settle();
+
+ expect(hook!.error).toBeNull();
+ expect(hook!.wallet).not.toBeNull();
+ });
+});
+
+describe("snapshot identity", () => {
+ it("reuses the snapshot when the payload has not changed", async () => {
+ await mount(<Probe />);
+ const first = hook!.wallet;
+
+ await polls(3);
+
+ expect(hook!.wallet).toBe(first);
+ });
+
+ it("shows a change confined to a nested field", async () => {
+ const view = await mount(<Probe />);
+ expect(view.getByTestId("s")).toHaveTextContent("free/false");
+
+ // processor / team / freeUserAllowance sat outside the hand-written field
+ // list, so a change to one of them never reached a consumer.
+ get.mockResolvedValue({ data: wallet({ processor: { active: true } }) });
+ await polls(1);
+
+ await waitFor(() =>
+ expect(view.getByTestId("s")).toHaveTextContent("free/true"),
+ );
+ });
+});
+
+describe("mutations", () => {
+ it("resolves updateCap only once the new state is in hand", async () => {
+ await mount(<Probe />);
+ const reads = get.mock.calls.length;
+
+ get.mockResolvedValue({ data: wallet({ capUsd: 25, noCap: false }) });
+ await act(async () => {
+ await hook!.updateCap(25);
+ });
+ await settle();
+
+ expect(apiClient.patch).toHaveBeenCalledWith("/api/v1/payg/cap", {
+ capUsd: 25,
+ noCap: false,
+ });
+ expect(get.mock.calls.length).toBeGreaterThan(reads);
+ expect(hook!.wallet?.capUsd).toBe(25);
+ });
+
+ it("treats a missing dev mark-subscribed hook as normal", async () => {
+ await mount(<Probe />);
+ vi.mocked(apiClient.post).mockRejectedValue({ response: { status: 404 } });
+
+ await act(async () => {
+ await expect(hook!.markSubscribed(null)).resolves.toBeUndefined();
+ });
+ });
+
+ it("reports any other mark-subscribed failure", async () => {
+ await mount(<Probe />);
+ vi.mocked(apiClient.post).mockRejectedValue({ response: { status: 500 } });
+
+ await expect(hook!.markSubscribed(null)).rejects.toBeTruthy();
+ });
+});
+
+it("stops reading and shows nothing when disabled", async () => {
+ await mount(<Probe enabled={false} />);
+ await polls(3);
+
+ expect(get).not.toHaveBeenCalled();
+ expect(hook!.wallet).toBeNull();
+ expect(hook!.loading).toBe(false);
+});
+
+it("keeps its callbacks stable across re-renders", async () => {
+ const view = await mount(<Probe />);
+ const before = {
+ refetch: hook!.refetch,
+ updateCap: hook!.updateCap,
+ markSubscribed: hook!.markSubscribed,
+ };
+
+ await act(async () => {
+ view.rerender(
+ <QueryClientProvider client={createAppQueryClient()}>
+ <Probe />
+ </QueryClientProvider>,
+ );
+ });
+
+ expect(hook!.refetch).toBe(before.refetch);
+ expect(hook!.updateCap).toBe(before.updateCap);
+ expect(hook!.markSubscribed).toBe(before.markSubscribed);
+});