Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix(billing): never report unknown entitlement as a free plan

Chadpiha160e7595f9e6
diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsx
index 5aa281065..9df42cef7 100644
--- a/src/components/ControlPanel.tsx
+++ b/src/components/ControlPanel.tsx
@@ -21,6 +21,7 @@ import { useUpdater } from "../hooks/useUpdater";
import { useSettings } from "../hooks/useSettings";
import { useAuth } from "../hooks/useAuth";
import { useUsage } from "../hooks/useUsage";
+import { decideUpsell } from "../lib/upsell";
import { useCollapsibleSidebar } from "../hooks/useCollapsibleSidebar";
import {
useTranscriptions,
@@ -158,6 +159,12 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro
} = useSettings();
const { isSignedIn, isLoaded: authLoaded, user } = useAuth();
const usage = useUsage();
+ const upsell = decideUpsell({
+ authLoaded,
+ isSignedIn,
+ hasPaidAccess: usage?.hasPaidAccess ?? null,
+ isPastDue: usage?.isPastDue ?? false,
+ });
const {
status: updateStatus,
@@ -306,7 +313,8 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro
}, [toast, t]);
useEffect(() => {
- if (!usage?.isPastDue || !usage.hasLoaded) return;
+ // isPastDue is only ever true on a successful usage response.
+ if (!usage?.isPastDue) return;
if (sessionStorage.getItem("pastDueNotified")) return;
sessionStorage.setItem("pastDueNotified", "true");
toast({
@@ -315,7 +323,7 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro
variant: "destructive",
duration: 8000,
});
- }, [usage?.isPastDue, usage?.hasLoaded, toast, t]);
+ }, [usage?.isPastDue, toast, t]);
useEffect(() => {
const unsubscribe = window.electronAPI?.onWorkspaceInvitationToken?.((token) => {
@@ -955,8 +963,7 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro
userImage={user?.image}
isSignedIn={isSignedIn}
authLoaded={authLoaded}
- isProUser={!!(usage?.isSubscribed || usage?.isTrial)}
- usageLoaded={usage?.hasLoaded ?? false}
+ upsell={upsell}
updateAction={
!updateStatus.isDevelopment &&
(updateStatus.updateAvailable ||
@@ -1148,7 +1155,7 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro
{activeView === "integrations" && (
<Suspense fallback={null}>
<IntegrationsView
- isPaid={!!(usage?.isSubscribed || usage?.isTrial)}
+ isPaid={usage?.hasPaidAccessOptimistic ?? false}
onUpgrade={() => {
setSettingsSection("plansBilling");
setShowSettings(true);
diff --git a/src/components/ControlPanelSidebar.tsx b/src/components/ControlPanelSidebar.tsx
index 0eef45f73..389181feb 100644
--- a/src/components/ControlPanelSidebar.tsx
+++ b/src/components/ControlPanelSidebar.tsx
@@ -18,6 +18,7 @@ import { useTranslation } from "react-i18next";
import { cn } from "./lib/utils";
import SupportDropdown from "./ui/SupportDropdown";
import { getCachedPlatform } from "../utils/platform";
+import type { UpsellDecision } from "../lib/upsell";
const platform = getCachedPlatform();
@@ -44,8 +45,7 @@ interface ControlPanelSidebarProps {
userImage?: string | null;
isSignedIn?: boolean;
authLoaded?: boolean;
- isProUser?: boolean;
- usageLoaded?: boolean;
+ upsell: UpsellDecision;
updateAction?: React.ReactNode;
}
@@ -62,8 +62,7 @@ export default function ControlPanelSidebar({
userImage,
isSignedIn,
authLoaded,
- isProUser,
- usageLoaded,
+ upsell,
updateAction,
}: ControlPanelSidebarProps) {
const { t } = useTranslation();
@@ -71,13 +70,10 @@ export default function ControlPanelSidebar({
() => localStorage.getItem("upgradeProDismissed") === "true"
);
- const showLimitBanner = authLoaded && isSignedIn && !isProUser && isOverLimit;
- const showUpgradeBanner =
- !showLimitBanner &&
- authLoaded &&
- (!isSignedIn || usageLoaded !== false) &&
- !isProUser &&
- !upgradeDismissed;
+ // "unknown" renders neither banner: an unloaded or failed usage response is
+ // not evidence the account is free.
+ const showLimitBanner = upsell === "show" && Boolean(isSignedIn) && Boolean(isOverLimit);
+ const showUpgradeBanner = upsell === "show" && !showLimitBanner && !upgradeDismissed;
const navItems: {
id: ControlPanelView;
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index be79ab462..2928ed3ee 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -38,6 +38,7 @@ import {
} from "lucide-react";
import { useAuth } from "../hooks/useAuth";
import { AUTH_URL, signOut, deleteAccount } from "../lib/auth";
+import { useBillingPortal } from "../hooks/useBillingPortal";
import MicPermissionWarning from "./ui/MicPermissionWarning";
import MicrophoneSettings from "./ui/MicrophoneSettings";
import PermissionCard from "./ui/PermissionCard";
@@ -1342,9 +1343,12 @@ export default function SettingsPage({
}, [isRemovingModels, cachePathHint, showConfirmDialog, showAlertDialog, t]);
const { isSignedIn, isLoaded, user, refetch } = useAuth();
+ // Signed out there is nothing to load and the plan grid is purely
+ // promotional; signed in, no card may claim a plan until usage confirms one.
+ const planStateKnown = !isSignedIn || usage?.status === "success";
const [isSigningOut, setIsSigningOut] = useState(false);
const [isDeletingAccount, setIsDeletingAccount] = useState(false);
- const [isOpeningBilling, setIsOpeningBilling] = useState(false);
+ const { openBillingPortal, isOpening: isOpeningBilling } = useBillingPortal(usage);
const [billingState, setBillingState] = useState<Record<string, boolean>>({
pro: true,
business: true,
@@ -1368,16 +1372,6 @@ export default function SettingsPage({
window.location.reload();
}, []);
- const handleBillingPortal = useCallback(async () => {
- const result = await usage.openBillingPortal();
- if (!result.success) {
- toast({
- title: t("settingsPage.account.checkout.couldNotOpenTitle"),
- description: t("settingsPage.account.checkout.couldNotOpenDescription"),
- });
- }
- }, [usage, toast, t]);
-
const handleSwitchPlan = useCallback(
async (plan: "monthly" | "annual", tier: "pro" | "business") => {
setPreviewLoading(true);
@@ -1793,7 +1787,29 @@ export default function SettingsPage({
{isSignedIn ? (
<div className="space-y-5">
<SectionHeader title={t("settingsPage.unifiedBilling.personalPlanTitle")} />
- {!usage || !usage.hasLoaded ? (
+ {usage?.status === "error" ? (
+ <SettingsPanel>
+ <SettingsPanelRow>
+ <SettingsRow
+ label={t("settingsPage.account.planUnavailable.title")}
+ description={t("settingsPage.account.planUnavailable.description")}
+ >
+ <Button
+ onClick={() => void usage.retry()}
+ variant="outline"
+ size="sm"
+ disabled={usage.isRetrying}
+ >
+ {usage.isRetrying ? (
+ <Loader2 size={14} className="animate-spin" />
+ ) : (
+ t("common.retry")
+ )}
+ </Button>
+ </SettingsRow>
+ </SettingsPanelRow>
+ </SettingsPanel>
+ ) : usage?.status !== "success" ? (
<SettingsPanel>
<SettingsPanelRow>
<div className="flex items-center justify-between">
@@ -1932,23 +1948,7 @@ export default function SettingsPage({
<SettingsPanelRow>
{usage.isPastDue ? (
<Button
- onClick={async () => {
- setIsOpeningBilling(true);
- try {
- const result = await usage.openBillingPortal();
- if (!result.success) {
- toast({
- title: t("settingsPage.account.billing.couldNotOpenTitle"),
- description: t(
- "settingsPage.account.billing.couldNotOpenDescription"
- ),
- variant: "destructive",
- });
- }
- } finally {
- setIsOpeningBilling(false);
- }
- }}
+ onClick={() => void openBillingPortal()}
disabled={isOpeningBilling}
size="sm"
className="w-full"
@@ -1964,24 +1964,13 @@ export default function SettingsPage({
</Button>
) : usage.isPersonallySubscribed && !usage.isTrial ? (
<Button
- onClick={async () => {
- const result = await usage.openBillingPortal();
- if (!result.success) {
- toast({
- title: t("settingsPage.account.billing.couldNotOpenTitle"),
- description: t(
- "settingsPage.account.billing.couldNotOpenDescription"
- ),
- variant: "destructive",
- });
- }
- }}
+ onClick={() => void openBillingPortal()}
variant="outline"
size="sm"
className="w-full"
- disabled={usage.checkoutLoading}
+ disabled={isOpeningBilling}
>
- {usage.checkoutLoading
+ {isOpeningBilling
? t("settingsPage.account.billing.opening")
: t("settingsPage.account.billing.manageBilling")}
</Button>
@@ -2025,7 +2014,7 @@ export default function SettingsPage({
<div
className={cn(
"rounded-md p-2.5 flex flex-col",
- !usage?.isPersonallySubscribed && !usage?.isTrial
+ planStateKnown && !usage?.isPersonallySubscribed && !usage?.isTrial
? "border-2 border-primary/30 bg-primary/3 dark:border-primary/20 dark:bg-primary/5"
: "border border-border/50 dark:border-border-subtle/60 bg-card/30 dark:bg-surface-2/30"
)}
@@ -2076,20 +2065,23 @@ export default function SettingsPage({
</Button>
) : usage?.isPersonallySubscribed && !usage?.isTrial ? (
<Button
- onClick={handleBillingPortal}
+ onClick={() => void openBillingPortal()}
variant="outline"
size="sm"
className="mt-2 w-full h-6 text-[10px]"
+ disabled={isOpeningBilling}
>
- {t("settingsPage.account.pricing.downgrade")}
+ {isOpeningBilling
+ ? t("settingsPage.account.billing.opening")
+ : t("settingsPage.account.pricing.downgrade")}
</Button>
- ) : (
+ ) : planStateKnown ? (
<div className="mt-2 text-center">
<span className="text-[9px] font-medium text-primary/70">
{t("settingsPage.account.pricing.currentPlan")}
</span>
</div>
- )}
+ ) : null}
</div>
<div
@@ -2173,7 +2165,7 @@ export default function SettingsPage({
t("settingsPage.account.pricing.downgrade")
)}
</Button>
- ) : (
+ ) : planStateKnown ? (
<Button
onClick={() =>
handleCheckout(billingState.pro ? "annual" : "monthly", "pro")
@@ -2188,7 +2180,7 @@ export default function SettingsPage({
t("settingsPage.account.pricing.pro.cta")
)}
</Button>
- )}
+ ) : null}
</div>
<div className="rounded-md border-2 border-primary/50 bg-primary/8 dark:border-primary/40 dark:bg-primary/10 p-2.5 flex flex-col relative">
diff --git a/src/components/UpgradePrompt.tsx b/src/components/UpgradePrompt.tsx
index b59a49d07..a41ca8841 100644
--- a/src/components/UpgradePrompt.tsx
+++ b/src/components/UpgradePrompt.tsx
@@ -2,6 +2,7 @@ import { Dialog, DialogContent } from "./ui/dialog";
import { ChevronRight } from "lucide-react";
import { useTranslation } from "react-i18next";
import { useUsage } from "../hooks/useUsage";
+import { useBillingPortal } from "../hooks/useBillingPortal";
import { useSettingsStore } from "../stores/settingsStore";
interface UpgradePromptProps {
@@ -19,6 +20,7 @@ export default function UpgradePrompt({
}: UpgradePromptProps) {
const { t } = useTranslation();
const usage = useUsage();
+ const { openBillingPortal } = useBillingPortal(usage);
const isPastDue = usage?.isPastDue ?? false;
return (
@@ -51,9 +53,7 @@ export default function UpgradePrompt({
<OptionCard
title={t("upgradePrompt.updatePayment")}
description={t("upgradePrompt.updatePaymentDescription")}
- onClick={() => {
- usage?.openBillingPortal();
- }}
+ onClick={() => void openBillingPortal()}
highlighted
disabled={usage?.checkoutLoading}
/>
diff --git a/src/components/UsageDisplay.tsx b/src/components/UsageDisplay.tsx
index 28b530564..6a474a11c 100644
--- a/src/components/UsageDisplay.tsx
+++ b/src/components/UsageDisplay.tsx
@@ -1,15 +1,18 @@
import { useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import { useUsage } from "../hooks/useUsage";
+import { useBillingPortal } from "../hooks/useBillingPortal";
import { useToast } from "./ui/useToast";
import { Badge } from "./ui/badge";
import { Progress } from "./ui/progress";
import { Button } from "./ui/button";
+import { Skeleton } from "./ui/skeleton";
import { useSettingsStore } from "../stores/settingsStore";
export default function UsageDisplay() {
const { t } = useTranslation();
const usage = useUsage();
+ const { openBillingPortal, isOpening } = useBillingPortal(usage);
const { toast } = useToast();
const hasShownApproachingToast = useRef(false);
@@ -29,6 +32,26 @@ export default function UsageDisplay() {
}, [usage?.isApproachingLimit, usage?.wordsUsed, usage?.limit, toast, t]);
if (!usage) return null;
+ // An unresolved entitlement is not a free plan: hold the card's space rather
+ // than claim a "Free" badge and an allowance the account may not be on.
+ if (usage.status !== "success") {
+ return (
+ <div className="bg-card border border-border rounded-xl p-4 space-y-3">
+ <div className="flex items-center justify-between">
+ <Skeleton className="h-4 w-28" />
+ <Skeleton className="h-5 w-16 rounded-full" />
+ </div>
+ <div className="space-y-1.5">
+ <Skeleton className="h-2 w-full rounded-full" />
+ <div className="flex items-center justify-between">
+ <Skeleton className="h-4 w-24" />
+ <Skeleton className="h-3 w-20" />
+ </div>
+ </div>
+ <Skeleton className="h-5 w-32" />
+ </div>
+ );
+ }
// Pro plan or trial — minimal display
if (usage.isSubscribed) {
@@ -50,7 +73,12 @@ export default function UsageDisplay() {
{usage.isTrial ? t("usage.unlimitedTrial") : t("usage.unlimited")}
</p>
{!usage.isTrial && (
- <Button variant="outline" size="sm" onClick={() => usage.openBillingPortal()}>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => void openBillingPortal()}
+ disabled={isOpening}
+ >
{t("usage.manageSubscription")}
</Button>
)}
diff --git a/src/components/notes/UploadAudioView.tsx b/src/components/notes/UploadAudioView.tsx
index 52a109578..3d017fc24 100644
--- a/src/components/notes/UploadAudioView.tsx
+++ b/src/components/notes/UploadAudioView.tsx
@@ -226,7 +226,9 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa
const { isSignedIn } = useAuth();
const usage = useUsage();
- const isProUser = usage?.isSubscribed || usage?.isTrial;
+ // The server enforces the free-tier size limit regardless, so an unresolved
+ // entitlement should not block a payer's upload.
+ const isProUser = usage?.hasPaidAccessOptimistic ?? false;
const {
openaiApiKey,
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 3ac551e74..500bcd682 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -7450,8 +7450,12 @@ class IPCHandlers {
const authHeader = await getAuthHeader(event);
if (!Object.keys(authHeader).length) throw new Error("Not authenticated");
+ // Entitlement must never be served from Chromium's HTTP cache: the
+ // desktop authenticates with a bearer token, so a cached response can
+ // outlive both the account that produced it and a mid-flight upgrade.
const response = await proxyFetch(`${apiUrl}/api/usage`, {
headers: authHeader,
+ cache: "no-store",
});
if (!response.ok) {
@@ -7461,7 +7465,12 @@ class IPCHandlers {
if (response.status === 503) {
return { success: false, error: "Request timed out", code: "SERVER_ERROR" };
}
- throw new Error(`API error: ${response.status}`);
+ const errorData = await response.json().catch(() => ({}));
+ const message = errorData.error || `API error: ${response.status}`;
+ debugLogger.error(`Cloud usage fetch error: ${message}`);
+ // The refusal code drives the renderer's retry policy — a coded
+ // refusal must not be retried as if it were a transport blip.
+ return { success: false, error: message, code: errorData.code };
}
const data = await response.json();
@@ -7497,7 +7506,11 @@ class IPCHandlers {
return { success: false, error: "Request timed out", code: "SERVER_ERROR" };
}
const errorData = await response.json().catch(() => ({}));
- throw new Error(errorData.error || `API error: ${response.status}`);
+ const message = errorData.error || `API error: ${response.status}`;
+ debugLogger.error(`${errorPrefix}: ${message}`);
+ // The refusal code lets the renderer branch on why — a non-owner of a
+ // past-due workspace needs different copy from a generic failure.
+ return { success: false, error: message, code: errorData.code };
}
const data = await response.json();
diff --git a/src/hooks/useBillingPortal.ts b/src/hooks/useBillingPortal.ts
new file mode 100644
index 000000000..0a75787aa
--- /dev/null
+++ b/src/hooks/useBillingPortal.ts
@@ -0,0 +1,43 @@
+import { useCallback, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { useToast } from "../components/ui/useToast";
+import { billingPortalErrorCopy } from "../lib/billingPortalError";
+import type { UseUsageResult } from "./useUsage";
+
+interface UseBillingPortalReturn {
+ openBillingPortal: () => Promise<void>;
+ isOpening: boolean;
+}
+
+/**
+ * Opens Stripe's portal and reports a refusal with the copy that fits its code.
+ * Every entry point shares this so the same failure never reads two ways.
+ *
+ * Takes the caller's usage object rather than calling `useUsage` itself: the
+ * in-flight guard behind `openBillingPortal` is per-instance, so a second
+ * instance would let a checkout and a portal open at the same time.
+ */
+export function useBillingPortal(usage: UseUsageResult | null): UseBillingPortalReturn {
+ const { t } = useTranslation();
+ const { toast } = useToast();
+ const [isOpening, setIsOpening] = useState(false);
+
+ const openBillingPortal = useCallback(async () => {
+ if (!usage) return;
+ setIsOpening(true);
+ try {
+ const result = await usage.openBillingPortal();
+ if (result.success) return;
+ const copy = billingPortalErrorCopy(result.code);
+ toast({
+ title: t(copy.titleKey),
+ description: t(copy.descriptionKey),
+ variant: "destructive",
+ });
+ } finally {
+ setIsOpening(false);
+ }
+ }, [usage, toast, t]);
+
+ return { openBillingPortal, isOpening };
+}
diff --git a/src/hooks/useNotesOnboarding.ts b/src/hooks/useNotesOnboarding.ts
index eec0194df..a08e6da80 100644
--- a/src/hooks/useNotesOnboarding.ts
+++ b/src/hooks/useNotesOnboarding.ts
@@ -12,8 +12,9 @@ interface UseNotesOnboardingReturn {
export function useNotesOnboarding(): UseNotesOnboardingReturn {
const usage = useUsage();
- const isProUser = !!(usage?.isSubscribed || usage?.isTrial);
- const isProLoading = usage !== null && !usage.hasLoaded;
+ // Unknown entitlement is treated as loading, never as free.
+ const isProUser = usage?.hasPaidAccess === true;
+ const isProLoading = usage !== null && usage.status !== "success";
const useCleanupModel = useSettingsStore((s) => s.useCleanupModel);
const effectiveModel = useSettingsStore((s) => s.cleanupModel);
const isCloudCleanup = useSettingsStore(selectIsCloudCleanupMode);
diff --git a/src/hooks/useUsage.ts b/src/hooks/useUsage.ts
index 6b2970e6f..1b22902ee 100644
--- a/src/hooks/useUsage.ts
+++ b/src/hooks/useUsage.ts
@@ -1,30 +1,36 @@
-import { useState, useEffect, useCallback, useRef } from "react";
+import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";
import { useAuth } from "./useAuth";
-import { CACHE_CONFIG } from "../config/constants";
import { withSessionRefresh } from "../lib/auth";
-import { writeIsSubscribed } from "../lib/subscriptionFlag";
+import {
+ getUsageState,
+ isPastDueUsage,
+ loadUsage,
+ retryUsage,
+ setUsageAccount,
+ subscribeUsage,
+ watchForUpgrade,
+ type UsageResponse,
+ type UsageState,
+} from "../lib/usageStore";
-interface UsageData {
- wordsUsed: number;
- wordsRemaining: number;
- limit: number;
- plan: string;
- status: string;
- isSubscribed: boolean;
- isTrial: boolean;
- trialDaysLeft: number | null;
- currentPeriodEnd: string | null;
- billingInterval: "monthly" | "annual" | null;
- resetAt: string;
- entitlementSources: {
- personal: boolean;
- workspaceIds: string[];
- };
-}
-
-interface UseUsageResult {
+export interface UseUsageResult {
+ /** Entitlement is only known when this is `"success"`. Gate billing UI on it. */
+ status: UsageState["status"];
+ isRefreshing: boolean;
+ isRetrying: boolean;
+ error: string | null;
+ retry: () => Promise<void>;
+ refetch: () => Promise<void>;
+ /** `null` while the entitlement is unknown — never assume free. */
+ hasPaidAccess: boolean | null;
+ /**
+ * `hasPaidAccess` with the unknown case resolved in the account's favour, for
+ * gates where wrongly locking out a payer costs more than briefly over-granting
+ * (the server stays authoritative). Signed out the hook is `null`, so a
+ * `?? false` at the call site keeps that a known "not entitled".
+ */
+ hasPaidAccessOptimistic: boolean;
plan: string;
- status: string;
isPastDue: boolean;
wordsUsed: number;
wordsRemaining: number;
@@ -39,16 +45,18 @@ interface UseUsageResult {
isOverLimit: boolean;
isApproachingLimit: boolean;
resetAt: string | null;
- isLoading: boolean;
- hasLoaded: boolean;
- error: string | null;
+ /**
+ * Any Stripe action — checkout, switch-plan or portal — is in flight. They
+ * share one in-flight guard, so this is what sibling buttons disable on.
+ * `useBillingPortal`'s `isOpening` narrows it to the portal, for the buttons
+ * whose own label changes while it opens.
+ */
checkoutLoading: boolean;
- refetch: () => Promise<void>;
openCheckout: (opts?: {
plan?: "monthly" | "annual";
tier?: "pro" | "business";
}) => Promise<{ success: boolean; error?: string }>;
- openBillingPortal: () => Promise<{ success: boolean; error?: string }>;
+ openBillingPortal: () => Promise<{ success: boolean; error?: string; code?: string }>;
switchPlan: (opts: {
plan: "monthly" | "annual";
tier: "pro" | "business";
@@ -67,104 +75,49 @@ interface UseUsageResult {
}>;
}
-const USAGE_CACHE_TTL = CACHE_CONFIG.API_KEY_TTL; // 1 hour
-const PAID_PLANS = new Set(["pro", "business", "enterprise"]);
+async function fetchUsageResponse(): Promise<UsageResponse> {
+ const cloudUsage = window.electronAPI?.cloudUsage;
+ if (!cloudUsage) throw new Error("App not ready");
+ return withSessionRefresh(async () => {
+ const result = await cloudUsage();
+ if (!result.success) {
+ const error: Error & { code?: string } = new Error(result.error || "Failed to fetch usage");
+ error.code = result.code;
+ throw error;
+ }
+ return result;
+ });
+}
export function useUsage(): UseUsageResult | null {
- const { isSignedIn, isLoaded } = useAuth();
- const [data, setData] = useState<UsageData | null>(null);
- const [isLoading, setIsLoading] = useState(true);
- const [hasLoaded, setHasLoaded] = useState(false);
- const [error, setError] = useState<string | null>(null);
+ const { isSignedIn, isLoaded, user } = useAuth();
+ const state = useSyncExternalStore(subscribeUsage, getUsageState);
const [checkoutLoading, setCheckoutLoading] = useState(false);
const checkoutInFlightRef = useRef(false);
- const lastFetchRef = useRef<number>(0);
-
- const fetchUsage = useCallback(async () => {
- if (!window.electronAPI?.cloudUsage) return;
+ const pendingRefetchRef = useRef(false);
- setIsLoading(true);
- setError(null);
+ const accountId = isSignedIn ? (user?.id ?? null) : null;
- try {
- await withSessionRefresh(async () => {
- const result = await window.electronAPI.cloudUsage();
- if (result.success) {
- setData({
- wordsUsed: result.wordsUsed ?? 0,
- wordsRemaining: result.wordsRemaining ?? 0,
- limit: result.limit ?? 2000,
- plan: result.plan ?? "free",
- status: result.status ?? "active",
- isSubscribed: result.isSubscribed ?? false,
- isTrial: result.isTrial ?? false,
- trialDaysLeft: result.trialDaysLeft ?? null,
- currentPeriodEnd: result.currentPeriodEnd ?? null,
- billingInterval: result.billingInterval ?? null,
- resetAt: result.resetAt ?? "rolling",
- entitlementSources: result.entitlementSources ?? {
- personal:
- result.isTrial === true ||
- (PAID_PLANS.has(result.plan ?? "free") &&
- ["active", "trialing"].includes(result.status ?? "active")),
- workspaceIds: [],
- },
- });
- lastFetchRef.current = Date.now();
- writeIsSubscribed(result.isSubscribed ?? false);
- } else {
- const error: any = new Error(result.error || "Failed to fetch usage");
- error.code = result.code;
- throw error;
- }
- });
- } catch (err) {
- setError(err instanceof Error ? err.message : "Failed to fetch usage");
- } finally {
- setIsLoading(false);
- setHasLoaded(true);
- }
- }, []);
-
- const pendingRefetchRef = useRef(false);
+ useEffect(() => {
+ if (!isLoaded) return;
+ setUsageAccount(accountId);
+ }, [isLoaded, accountId]);
useEffect(() => {
- if (!isLoaded || !isSignedIn) {
- lastFetchRef.current = 0;
- setData(null);
- return;
- }
+ if (!isLoaded || !accountId) return;
- const shouldFetch = Date.now() - lastFetchRef.current > USAGE_CACHE_TTL;
- if (shouldFetch) {
- fetchUsage();
- } else {
- setIsLoading(false);
- setHasLoaded(true);
- }
+ void loadUsage(fetchUsageResponse);
const handleFocus = () => {
- if (pendingRefetchRef.current) {
- pendingRefetchRef.current = false;
- lastFetchRef.current = 0;
- fetchUsage();
- }
+ if (!pendingRefetchRef.current) return;
+ pendingRefetchRef.current = false;
+ void loadUsage(fetchUsageResponse, { force: true });
};
const handleUsageChanged = () => {
- lastFetchRef.current = 0;
- fetchUsage();
+ void loadUsage(fetchUsageResponse, { force: true });
};
- const handleUpgradeSuccess = async () => {
- lastFetchRef.current = 0;
- await fetchUsage();
- // Retry if webhook hasn't updated DB yet
- for (let i = 0; i < 3; i++) {
- const result = await window.electronAPI.cloudUsage();
- if (result.success && result.isSubscribed) break;
- await new Promise((r) => setTimeout(r, 2000 * (i + 1)));
- lastFetchRef.current = 0;
- await fetchUsage();
- }
+ const handleUpgradeSuccess = () => {
+ void watchForUpgrade(fetchUsageResponse);
};
window.addEventListener("focus", handleFocus);
window.addEventListener("usage-changed", handleUsageChanged);
@@ -174,7 +127,10 @@ export function useUsage(): UseUsageResult | null {
window.removeEventListener("usage-changed", handleUsageChanged);
window.removeEventListener("upgrade-success", handleUpgradeSuccess);
};
- }, [isLoaded, isSignedIn, fetchUsage]);
+ }, [isLoaded, accountId]);
+
+ const refetch = useCallback(() => loadUsage(fetchUsageResponse, { force: true }), []);
+ const retry = useCallback(() => retryUsage(fetchUsageResponse), []);
const openCheckout = useCallback(
async (opts?: {
@@ -204,7 +160,11 @@ export function useUsage(): UseUsageResult | null {
[]
);
- const openBillingPortal = useCallback(async (): Promise<{ success: boolean; error?: string }> => {
+ const openBillingPortal = useCallback(async (): Promise<{
+ success: boolean;
+ error?: string;
+ code?: string;
+ }> => {
if (checkoutInFlightRef.current) return { success: false, error: "Already loading" };
if (!window.electronAPI?.cloudBillingPortal || !window.electronAPI?.openExternal) {
return { success: false, error: "App not ready" };
@@ -218,7 +178,11 @@ export function useUsage(): UseUsageResult | null {
await window.electronAPI.openExternal(result.url);
return { success: true };
}
- return { success: false, error: result.error || "Failed to open billing portal" };
+ return {
+ success: false,
+ error: result.error || "Failed to open billing portal",
+ code: result.code,
+ };
} finally {
checkoutInFlightRef.current = false;
setCheckoutLoading(false);
@@ -238,16 +202,14 @@ export function useUsage(): UseUsageResult | null {
setCheckoutLoading(true);
try {
const result = await window.electronAPI.cloudSwitchPlan(opts);
- if (result.success) {
- await fetchUsage();
- }
+ if (result.success) await refetch();
return result;
} finally {
checkoutInFlightRef.current = false;
setCheckoutLoading(false);
}
},
- [fetchUsage]
+ [refetch]
);
const previewSwitchPlan = useCallback(
@@ -262,37 +224,41 @@ export function useUsage(): UseUsageResult | null {
if (!isSignedIn) return null;
+ const data = state.status === "success" ? state.data : null;
const wordsUsed = data?.wordsUsed ?? 0;
- const limit = data?.limit ?? 2000;
+ const limit = data?.limit ?? 0;
const isSubscribed = data?.isSubscribed ?? false;
- const isPersonallySubscribed = data?.entitlementSources.personal ?? false;
- const status = data?.status ?? "active";
- const isPastDue = PAID_PLANS.has(data?.plan ?? "free") && status === "past_due";
- const isOverLimit = !isSubscribed && limit > 0 && wordsUsed >= limit;
- const isApproachingLimit = !isSubscribed && limit > 0 && wordsUsed >= limit * 0.8 && !isOverLimit;
+ const isTrial = data?.isTrial ?? false;
+ const hasPaidAccess = data ? data.isSubscribed || data.isTrial : null;
+ const isOverLimit = Boolean(data) && !isSubscribed && limit > 0 && wordsUsed >= limit;
+ const isApproachingLimit =
+ Boolean(data) && !isSubscribed && limit > 0 && wordsUsed >= limit * 0.8 && !isOverLimit;
return {
+ status: state.status,
+ isRefreshing: state.status === "success" && state.isRefreshing,
+ isRetrying: state.status === "error" && state.isRetrying,
+ error: state.status === "error" ? state.error : null,
+ retry,
+ refetch,
+ hasPaidAccess,
+ hasPaidAccessOptimistic: hasPaidAccess !== false,
plan: data?.plan ?? "free",
- status,
- isPastDue,
+ isPastDue: data ? isPastDueUsage(data) : false,
wordsUsed,
- wordsRemaining: data?.wordsRemaining ?? (limit > 0 ? limit - wordsUsed : -1),
+ wordsRemaining: data?.wordsRemaining ?? 0,
limit,
isSubscribed,
- isPersonallySubscribed,
+ isPersonallySubscribed: data?.entitlementSources.personal ?? false,
entitledWorkspaceIds: data?.entitlementSources.workspaceIds ?? [],
- isTrial: data?.isTrial ?? false,
+ isTrial,
trialDaysLeft: data?.trialDaysLeft ?? null,
currentPeriodEnd: data?.currentPeriodEnd ?? null,
billingInterval: data?.billingInterval ?? null,
isOverLimit,
isApproachingLimit,
resetAt: data?.resetAt ?? null,
- isLoading,
- hasLoaded,
- error,
checkoutLoading,
- refetch: fetchUsage,
openCheckout,
openBillingPortal,
switchPlan,
diff --git a/src/lib/billingPortalError.ts b/src/lib/billingPortalError.ts
new file mode 100644
index 000000000..1e45bf738
--- /dev/null
+++ b/src/lib/billingPortalError.ts
@@ -0,0 +1,17 @@
+// A non-owner of a workspace-billed subscription has no self-serve recovery,
+// so the generic "couldn't open billing" copy is a dead end for them.
+export function billingPortalErrorCopy(code?: string): {
+ titleKey: string;
+ descriptionKey: string;
+} {
+ if (code === "not_workspace_owner") {
+ return {
+ titleKey: "settingsPage.account.billing.contactOwnerTitle",
+ descriptionKey: "settingsPage.account.billing.contactOwnerDescription",
+ };
+ }
+ return {
+ titleKey: "settingsPage.account.billing.couldNotOpenTitle",
+ descriptionKey: "settingsPage.account.billing.couldNotOpenDescription",
+ };
+}
diff --git a/src/lib/subscriptionFlag.ts b/src/lib/subscriptionFlag.ts
index 8828606ee..0b4af1977 100644
--- a/src/lib/subscriptionFlag.ts
+++ b/src/lib/subscriptionFlag.ts
@@ -1,4 +1,4 @@
-import { createReactiveLocalFlag } from "./reactiveLocalFlag";
+import { createReactiveLocalFlag } from "./reactiveLocalFlag.ts";
// Written by useUsage after each usage fetch; read by surfaces that gate on
// subscription without paying a usage fetch (e.g. the note share affordance).
diff --git a/src/lib/upsell.ts b/src/lib/upsell.ts
new file mode 100644
index 000000000..cedd84885
--- /dev/null
+++ b/src/lib/upsell.ts
@@ -0,0 +1,28 @@
+export type UpsellDecision = "show" | "hide" | "unknown";
+
+export interface UpsellInput {
+ authLoaded: boolean;
+ isSignedIn: boolean;
+ /** `null` while the entitlement is unresolved — see `useUsage`. */
+ hasPaidAccess: boolean | null;
+ isPastDue: boolean;
+}
+
+/**
+ * Three-way so an unknown entitlement is never rendered as free. Signed-out
+ * users still get the CTA — there is no usage response to confirm, and the
+ * upsell is the point of the screen for them.
+ */
+export function decideUpsell({
+ authLoaded,
+ isSignedIn,
+ hasPaidAccess,
+ isPastDue,
+}: UpsellInput): UpsellDecision {
+ if (!authLoaded) return "unknown";
+ if (!isSignedIn) return "show";
+ if (hasPaidAccess === null) return "unknown";
+ // Past due already has its own banner, toast and recovery button.
+ if (isPastDue || hasPaidAccess) return "hide";
+ return "show";
+}
diff --git a/src/lib/usageStore.ts b/src/lib/usageStore.ts
new file mode 100644
index 000000000..e0ed2590c
--- /dev/null
+++ b/src/lib/usageStore.ts
@@ -0,0 +1,263 @@
+import { CACHE_CONFIG } from "../config/constants.ts";
+import { clearIsSubscribed, writeIsSubscribed } from "./subscriptionFlag.ts";
+
+// One account-scoped entitlement result shared by every consumer, so two
+// screens can never disagree about the same account. Unknown is a real state:
+// nothing here manufactures a free plan out of missing data.
+
+const USAGE_ACCOUNT_KEY = "openwhispr:usageAccountId";
+const USAGE_CACHE_TTL = CACHE_CONFIG.API_KEY_TTL;
+const RETRY_DELAYS_MS = [2000, 4000, 8000];
+const PAID_PLANS = new Set(["pro", "business", "enterprise"]);
+
+export interface UsageData {
+ wordsUsed: number;
+ wordsRemaining: number;
+ limit: number;
+ plan: string;
+ subscriptionStatus: string;
+ isSubscribed: boolean;
+ isTrial: boolean;
+ trialDaysLeft: number | null;
+ currentPeriodEnd: string | null;
+ billingInterval: "monthly" | "annual" | null;
+ resetAt: string;
+ entitlementSources: {
+ personal: boolean;
+ workspaceIds: string[];
+ };
+}
+
+/** Raw `/api/usage` payload. Every field is optional: older API builds omit some. */
+export interface UsageResponse {
+ wordsUsed?: number;
+ wordsRemaining?: number;
+ limit?: number;
+ plan?: string;
+ status?: string;
+ isSubscribed?: boolean;
+ isTrial?: boolean;
+ trialDaysLeft?: number | null;
+ currentPeriodEnd?: string | null;
+ billingInterval?: "monthly" | "annual" | null;
+ resetAt?: string;
+ entitlementSources?: {
+ personal: boolean;
+ workspaceIds: string[];
+ };
+}
+
+/** Resolves with the payload or throws; `error.code` carries the API refusal code. */
+export type UsageFetcher = () => Promise<UsageResponse>;
+
+export type UsageState =
+ | { status: "idle"; accountId: string | null }
+ | { status: "loading"; accountId: string }
+ | { status: "success"; accountId: string; data: UsageData; isRefreshing: boolean }
+ | { status: "error"; accountId: string; error: string; code: string | null; isRetrying: boolean };
+
+const IDLE_SIGNED_OUT: UsageState = { status: "idle", accountId: null };
+
+let state: UsageState = IDLE_SIGNED_OUT;
+// Bumped on every account change; a response whose generation is stale is
+// dropped, so user A's in-flight request cannot land on user B's session.
+let generation = 0;
+let lastFetchAt = 0;
+let inFlight: Promise<void> | null = null;
+let retryAttempt = 0;
+let retryTimer: ReturnType<typeof setTimeout> | null = null;
+let queuedForce: Promise<void> | null = null;
+let upgradeWatchActive = false;
+const subscribers = new Set<() => void>();
+
+function storage(): Storage | null {
+ if (typeof window === "undefined") return null;
+ try {
+ return window.localStorage;
+ } catch {
+ return null;
+ }
+}
+
+function setState(next: UsageState): void {
+ state = next;
+ subscribers.forEach((subscriber) => subscriber());
+}
+
+function cancelRetry(): void {
+ if (retryTimer) clearTimeout(retryTimer);
+ retryTimer = null;
+}
+
+export function getUsageState(): UsageState {
+ return state;
+}
+
+export function subscribeUsage(onChange: () => void): () => void {
+ subscribers.add(onChange);
+ return () => subscribers.delete(onChange);
+}
+
+export function normalizeUsage(response: UsageResponse): UsageData {
+ const plan = response.plan ?? "free";
+ const subscriptionStatus = response.status ?? "active";
+ return {
+ wordsUsed: response.wordsUsed ?? 0,
+ wordsRemaining: response.wordsRemaining ?? 0,
+ // Not the free-tier allowance: a missing limit is an unknown one, and every
+ // meter is guarded on `limit > 0` so it stays hidden rather than wrong.
+ limit: response.limit ?? 0,
+ plan,
+ subscriptionStatus,
+ isSubscribed: response.isSubscribed ?? false,
+ isTrial: response.isTrial ?? false,
+ trialDaysLeft: response.trialDaysLeft ?? null,
+ currentPeriodEnd: response.currentPeriodEnd ?? null,
+ billingInterval: response.billingInterval ?? null,
+ resetAt: response.resetAt ?? "rolling",
+ // Pre-unified-billing API builds have no entitlementSources; infer a
+ // personal source from the plan so those clients keep working.
+ entitlementSources: response.entitlementSources ?? {
+ personal:
+ response.isTrial === true ||
+ (PAID_PLANS.has(plan) && ["active", "trialing"].includes(subscriptionStatus)),
+ workspaceIds: [],
+ },
+ };
+}
+
+export function isPastDueUsage(data: UsageData): boolean {
+ return PAID_PLANS.has(data.plan) && data.subscriptionStatus === "past_due";
+}
+
+/**
+ * Point the store at the authenticated account. Any previous account's data,
+ * in-flight request, retry timer and persisted subscription flag are dropped
+ * atomically, so user B never inherits user A's entitlement.
+ */
+export function setUsageAccount(accountId: string | null): void {
+ if (state.accountId === accountId) return;
+
+ generation += 1;
+ cancelRetry();
+ inFlight = null;
+ queuedForce = null;
+ lastFetchAt = 0;
+ retryAttempt = 0;
+
+ // The flag survives only for the account that produced it: a relaunch of the
+ // same account keeps it, so offline sessions still sync before the first
+ // successful usage fetch. Sign-out, a different account, or a build that
+ // never recorded an owner all invalidate it — an unattributable `true` would
+ // hand user B user A's entitlement.
+ const store = storage();
+ const previousAccountId = store?.getItem(USAGE_ACCOUNT_KEY) ?? null;
+ if (accountId === null || previousAccountId !== accountId) clearIsSubscribed();
+ if (accountId) store?.setItem(USAGE_ACCOUNT_KEY, accountId);
+ else store?.removeItem(USAGE_ACCOUNT_KEY);
+
+ setState({ status: "idle", accountId });
+}
+
+function toFailure(error: unknown): { message: string; code: string | null } {
+ if (error instanceof Error) {
+ const code = (error as Error & { code?: unknown }).code;
+ return { message: error.message, code: typeof code === "string" ? code : null };
+ }
+ return { message: "Failed to fetch usage", code: null };
+}
+
+function startLoad(accountId: string, fetcher: UsageFetcher): Promise<void> {
+ const requestGeneration = generation;
+ cancelRetry();
+ setState(
+ state.status === "success" ? { ...state, isRefreshing: true } : { status: "loading", accountId }
+ );
+
+ const run = (async () => {
+ try {
+ const response = await fetcher();
+ if (requestGeneration !== generation) return;
+ const data = normalizeUsage(response);
+ lastFetchAt = Date.now();
+ retryAttempt = 0;
+ writeIsSubscribed(data.isSubscribed);
+ setState({ status: "success", accountId, data, isRefreshing: false });
+ } catch (error) {
+ if (requestGeneration !== generation) return;
+ const { message, code } = toFailure(error);
+ // An expired session is resolved by the auth layer, not by retrying.
+ const willRetry = code !== "AUTH_EXPIRED" && retryAttempt < RETRY_DELAYS_MS.length;
+ setState({ status: "error", accountId, error: message, code, isRetrying: willRetry });
+ if (willRetry) {
+ const delay = RETRY_DELAYS_MS[retryAttempt];
+ retryAttempt += 1;
+ retryTimer = setTimeout(() => {
+ retryTimer = null;
+ if (requestGeneration === generation) void startLoad(accountId, fetcher);
+ }, delay);
+ }
+ } finally {
+ if (requestGeneration === generation) inFlight = null;
+ }
+ })();
+
+ inFlight = run;
+ return run;
+}
+
+/**
+ * Fetch usage for the active account. Concurrent callers share one request, and
+ * a successful result is reused for the cache TTL — mounting another consumer
+ * costs nothing. Errors are never TTL-cached.
+ */
+export function loadUsage(fetcher: UsageFetcher, opts: { force?: boolean } = {}): Promise<void> {
+ const { accountId } = state;
+ if (!accountId) return Promise.resolve();
+ if (inFlight) {
+ if (!opts.force) return inFlight;
+ // A forced caller knows something the in-flight request predates — words
+ // just spent, a plan just switched — so its answer is already stale.
+ // Every such caller coalesces into one follow-up rather than stampeding.
+ const forceGeneration = generation;
+ queuedForce ??= inFlight.then(() => {
+ // Clear before the check and a stale chain would wipe the follow-up the
+ // *current* account queued in the meantime, costing it a duplicate fetch.
+ if (forceGeneration !== generation) return;
+ queuedForce = null;
+ return loadUsage(fetcher, { force: true });
+ });
+ return queuedForce;
+ }
+ if (!opts.force && state.status === "success" && Date.now() - lastFetchAt < USAGE_CACHE_TTL) {
+ return Promise.resolve();
+ }
+ return startLoad(accountId, fetcher);
+}
+
+/** Manual retry: clears the backoff budget so the user gets an immediate attempt. */
+export function retryUsage(fetcher: UsageFetcher): Promise<void> {
+ retryAttempt = 0;
+ return loadUsage(fetcher, { force: true });
+}
+
+/**
+ * Post-checkout poll that outlives webhook lag. Guarded so mounting N consumers
+ * still runs one poll.
+ */
+export async function watchForUpgrade(fetcher: UsageFetcher): Promise<void> {
+ if (upgradeWatchActive) return;
+ upgradeWatchActive = true;
+ const startGeneration = generation;
+ try {
+ for (let attempt = 0; attempt <= RETRY_DELAYS_MS.length; attempt += 1) {
+ await loadUsage(fetcher, { force: true });
+ if (generation !== startGeneration) return;
+ if (state.status === "success" && state.data.isSubscribed) return;
+ await new Promise((resolve) => setTimeout(resolve, RETRY_DELAYS_MS[attempt] ?? 0));
+ if (generation !== startGeneration) return;
+ }
+ } finally {
+ upgradeWatchActive = false;
+ }
+}
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index 52da2425d..0b018faf3 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -1434,7 +1434,9 @@
"couldNotOpenTitle": "Abrechnung konnte nicht geöffnet werden",
"manageBilling": "Abrechnung verwalten",
"opening": "Wird geöffnet...",
- "updatePaymentMethod": "Zahlungsmethode aktualisieren"
+ "updatePaymentMethod": "Zahlungsmethode aktualisieren",
+ "contactOwnerTitle": "Wenden Sie sich an den Workspace-Inhaber",
+ "contactOwnerDescription": "Nur der Workspace-Inhaber kann die Abrechnung für diesen Workspace ändern."
},
"checkout": {
"couldNotOpenDescription": "Die Checkout-Seite konnte nicht geöffnet werden. Bitte versuchen Sie es erneut.",
@@ -1631,6 +1633,10 @@
"noPassword": "Für dieses Konto ist kein Passwort festgelegt.",
"generic": "Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut."
}
+ },
+ "planUnavailable": {
+ "title": "Tarif nicht verfügbar",
+ "description": "Ihr Tarif konnte gerade nicht geladen werden. Ihr Zugriff bleibt unverändert."
}
},
"agentConfig": {
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index 811dacfef..700890e04 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -1434,7 +1434,9 @@
"couldNotOpenTitle": "Couldn't open billing",
"manageBilling": "Manage Billing",
"opening": "Opening...",
- "updatePaymentMethod": "Update Payment Method"
+ "updatePaymentMethod": "Update Payment Method",
+ "contactOwnerTitle": "Contact your workspace owner",
+ "contactOwnerDescription": "Only the workspace owner can update billing for this workspace."
},
"checkout": {
"couldNotOpenDescription": "We had trouble opening the checkout page. Please try again.",
@@ -1631,6 +1633,10 @@
"noPassword": "No password is set for this account.",
"generic": "Something went wrong. Please try again."
}
+ },
+ "planUnavailable": {
+ "title": "Plan unavailable",
+ "description": "We couldn't load your plan right now. Your access is unchanged."
}
},
"agentConfig": {
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index ef94b86f3..ce9c7f497 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -1204,7 +1204,9 @@
"couldNotOpenTitle": "No se pudo abrir facturación",
"manageBilling": "Administrar facturación",
"opening": "Abriendo...",
- "updatePaymentMethod": "Actualizar método de pago"
+ "updatePaymentMethod": "Actualizar método de pago",
+ "contactOwnerTitle": "Contacta al propietario del espacio de trabajo",
+ "contactOwnerDescription": "Solo el propietario del espacio de trabajo puede actualizar su facturación."
},
"checkout": {
"couldNotOpenDescription": "Tuvimos problemas al abrir la página de pago. Inténtalo de nuevo.",
@@ -1401,6 +1403,10 @@
"noPassword": "Esta cuenta no tiene una contraseña configurada.",
"generic": "Algo salió mal. Inténtalo de nuevo."
}
+ },
+ "planUnavailable": {
+ "title": "Plan no disponible",
+ "description": "No pudimos cargar tu plan ahora mismo. Tu acceso no ha cambiado."
}
},
"agentConfig": {
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index cfe19c4ad..aea5d4801 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -1434,7 +1434,9 @@
"couldNotOpenTitle": "Impossible d'ouvrir la facturation",
"manageBilling": "Gérer la facturation",
"opening": "Ouverture...",
- "updatePaymentMethod": "Mettre à jour le moyen de paiement"
+ "updatePaymentMethod": "Mettre à jour le moyen de paiement",
+ "contactOwnerTitle": "Contactez le propriétaire de l'espace de travail",
+ "contactOwnerDescription": "Seul le propriétaire de l'espace de travail peut modifier sa facturation."
},
"checkout": {
"couldNotOpenDescription": "Nous avons eu un problème pour ouvrir la page de paiement. Veuillez réessayer.",
@@ -1631,6 +1633,10 @@
"noPassword": "Aucun mot de passe n'est défini pour ce compte.",
"generic": "Une erreur est survenue. Veuillez réessayer."
}
+ },
+ "planUnavailable": {
+ "title": "Forfait indisponible",
+ "description": "Nous n'avons pas pu charger votre forfait pour le moment. Votre accès reste inchangé."
}
},
"agentConfig": {
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index a68aca523..6b921bf9f 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -1156,7 +1156,9 @@
"couldNotOpenTitle": "Impossibile aprire la fatturazione",
"manageBilling": "Gestisci fatturazione",
"opening": "Apertura...",
- "updatePaymentMethod": "Aggiorna metodo di pagamento"
+ "updatePaymentMethod": "Aggiorna metodo di pagamento",
+ "contactOwnerTitle": "Contatta il proprietario dell'area di lavoro",
+ "contactOwnerDescription": "Solo il proprietario dell'area di lavoro può aggiornarne la fatturazione."
},
"checkout": {
"couldNotOpenDescription": "Si è verificato un problema nell'apertura della pagina di pagamento. Riprova.",
@@ -1353,6 +1355,10 @@
"noPassword": "Nessuna password è impostata per questo account.",
"generic": "Qualcosa è andato storto. Riprova."
}
+ },
+ "planUnavailable": {
+ "title": "Piano non disponibile",
+ "description": "Non siamo riusciti a caricare il tuo piano. Il tuo accesso resta invariato."
}
},
"agentConfig": {
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index 24e7ed5ca..7082781d2 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -1156,7 +1156,9 @@
"couldNotOpenTitle": "請求を開けませんでした",
"manageBilling": "請求を管理",
"opening": "開いています...",
- "updatePaymentMethod": "お支払い方法を更新"
+ "updatePaymentMethod": "お支払い方法を更新",
+ "contactOwnerTitle": "ワークスペースのオーナーにご連絡ください",
+ "contactOwnerDescription": "このワークスペースの請求を更新できるのはオーナーのみです。"
},
"checkout": {
"couldNotOpenDescription": "購入ページを開く際に問題が発生しました。もう一度お試しください。",
@@ -1353,6 +1355,10 @@
"noPassword": "このアカウントにはパスワードが設定されていません。",
"generic": "問題が発生しました。もう一度お試しください。"
}
+ },
+ "planUnavailable": {
+ "title": "プランを取得できません",
+ "description": "現在プランを読み込めませんでした。ご利用の権限は変わりません。"
}
},
"agentConfig": {
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index 4b79b1486..1f68dd6d0 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -1135,7 +1135,9 @@
"couldNotOpenTitle": "Não foi possível abrir cobrança",
"manageBilling": "Gerenciar cobrança",
"opening": "Abrindo...",
- "updatePaymentMethod": "Atualizar forma de pagamento"
+ "updatePaymentMethod": "Atualizar forma de pagamento",
+ "contactOwnerTitle": "Fale com o proprietário do workspace",
+ "contactOwnerDescription": "Apenas o proprietário do workspace pode atualizar a cobrança dele."
},
"checkout": {
"couldNotOpenDescription": "Tivemos dificuldade em abrir a página de checkout. Tente novamente.",
@@ -1332,6 +1334,10 @@
"noPassword": "Nenhuma senha está definida para esta conta.",
"generic": "Algo deu errado. Tente novamente."
}
+ },
+ "planUnavailable": {
+ "title": "Plano indisponível",
+ "description": "Não conseguimos carregar seu plano agora. Seu acesso permanece o mesmo."
}
},
"agentConfig": {
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index 934e706d1..f40fc9be0 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -1162,7 +1162,9 @@
"couldNotOpenTitle": "Не удалось открыть оплату",
"manageBilling": "Управление оплатой",
"opening": "Открытие...",
- "updatePaymentMethod": "Обновить способ оплаты"
+ "updatePaymentMethod": "Обновить способ оплаты",
+ "contactOwnerTitle": "Обратитесь к владельцу рабочего пространства",
+ "contactOwnerDescription": "Только владелец рабочего пространства может изменить его оплату."
},
"checkout": {
"couldNotOpenDescription": "Не удалось открыть страницу оформления. Попробуйте ещё раз.",
@@ -1359,6 +1361,10 @@
"noPassword": "Для этого аккаунта не установлен пароль.",
"generic": "Что-то пошло не так. Попробуйте ещё раз."
}
+ },
+ "planUnavailable": {
+ "title": "План недоступен",
+ "description": "Не удалось загрузить ваш план. Доступ при этом не изменился."
}
},
"agentConfig": {
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index eb732ee1b4..ec7dbfa9b 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -1156,7 +1156,9 @@
"couldNotOpenTitle": "无法打开账单",
"manageBilling": "管理账单",
"opening": "正在打开...",
- "updatePaymentMethod": "更新支付方式"
+ "updatePaymentMethod": "更新支付方式",
+ "contactOwnerTitle": "请联系工作区所有者",
+ "contactOwnerDescription": "只有工作区所有者才能更新该工作区的账单。"
},
"checkout": {
"couldNotOpenDescription": "打开结账页面时出错,请重试。",
@@ -1353,6 +1355,10 @@
"noPassword": "此账户未设置密码。",
"generic": "出了点问题,请重试。"
}
+ },
+ "planUnavailable": {
+ "title": "无法获取方案",
+ "description": "暂时无法加载你的方案,你的使用权限不受影响。"
}
},
"agentConfig": {
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index 0ea32af26..a05c4f983 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -1156,7 +1156,9 @@
"couldNotOpenTitle": "無法開啟帳單頁面",
"manageBilling": "管理帳單",
"opening": "開啟中...",
- "updatePaymentMethod": "更新付款方式"
+ "updatePaymentMethod": "更新付款方式",
+ "contactOwnerTitle": "請聯絡工作區擁有者",
+ "contactOwnerDescription": "只有工作區擁有者才能更新該工作區的帳單。"
},
"checkout": {
"couldNotOpenDescription": "開啟結帳頁面時發生問題。請再試一次。",
@@ -1353,6 +1355,10 @@
"noPassword": "此帳戶尚未設定密碼。",
"generic": "發生錯誤,請再試一次。"
}
+ },
+ "planUnavailable": {
+ "title": "無法取得方案",
+ "description": "目前無法載入你的方案,你的使用權限不受影響。"
}
},
"agentConfig": {
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 589056768..7f327d46f 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -1,5 +1,6 @@
import type { ModelDefinition } from "../models/ModelRegistry";
import type { TinfoilCatalogModel } from "../models/tinfoilModels";
+import type { UsageResponse } from "../lib/usageStore";
export type LocalTranscriptionProvider = "whisper" | "nvidia";
@@ -1602,26 +1603,13 @@ declare global {
code?: string;
messageKey?: string;
}>;
- cloudUsage?: () => Promise<{
- success: boolean;
- wordsUsed?: number;
- wordsRemaining?: number;
- limit?: number;
- plan?: string;
- status?: string;
- isSubscribed?: boolean;
- isTrial?: boolean;
- trialDaysLeft?: number | null;
- currentPeriodEnd?: string | null;
- billingInterval?: "monthly" | "annual" | null;
- entitlementSources?: {
- personal: boolean;
- workspaceIds: string[];
- };
- resetAt?: string;
- error?: string;
- code?: string;
- }>;
+ cloudUsage?: () => Promise<
+ UsageResponse & {
+ success: boolean;
+ error?: string;
+ code?: string;
+ }
+ >;
cloudCheckout?: (opts?: {
plan?: "monthly" | "annual";
tier?: "pro" | "business";
diff --git a/test/lib/billingPortalError.test.js b/test/lib/billingPortalError.test.js
new file mode 100644
index 000000000..970bbc29f
--- /dev/null
+++ b/test/lib/billingPortalError.test.js
@@ -0,0 +1,19 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const { billingPortalErrorCopy } = require("../../src/lib/billingPortalError.ts");
+
+test("a non-owner refusal points at the workspace owner", () => {
+ const copy = billingPortalErrorCopy("not_workspace_owner");
+ assert.equal(copy.titleKey, "settingsPage.account.billing.contactOwnerTitle");
+ assert.equal(copy.descriptionKey, "settingsPage.account.billing.contactOwnerDescription");
+});
+
+test("every other failure keeps the generic copy", () => {
+ for (const code of [undefined, "no_subscription", "no_workspace_customer"]) {
+ assert.equal(
+ billingPortalErrorCopy(code).titleKey,
+ "settingsPage.account.billing.couldNotOpenTitle"
+ );
+ }
+});
diff --git a/test/lib/upsell.test.js b/test/lib/upsell.test.js
new file mode 100644
index 000000000..163c291db
--- /dev/null
+++ b/test/lib/upsell.test.js
@@ -0,0 +1,22 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const { decideUpsell } = require("../../src/lib/upsell.ts");
+
+test("the upgrade CTA survives sign-out and is withheld while entitlement is unknown", () => {
+ const decide = (overrides) =>
+ decideUpsell({
+ authLoaded: true,
+ isSignedIn: true,
+ hasPaidAccess: false,
+ isPastDue: false,
+ ...overrides,
+ });
+
+ assert.equal(decide({ isSignedIn: false }), "show");
+ assert.equal(decide({ authLoaded: false, isSignedIn: false }), "unknown");
+ assert.equal(decide({ hasPaidAccess: null }), "unknown");
+ assert.equal(decide({ hasPaidAccess: true }), "hide");
+ assert.equal(decide({ isPastDue: true }), "hide");
+ assert.equal(decide({}), "show");
+});
diff --git a/test/lib/usageStore.test.js b/test/lib/usageStore.test.js
new file mode 100644
index 000000000..97a287592
--- /dev/null
+++ b/test/lib/usageStore.test.js
@@ -0,0 +1,419 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const values = new Map();
+const storage = {
+ getItem: (key) => values.get(key) ?? null,
+ setItem: (key, value) => values.set(key, String(value)),
+ removeItem: (key) => values.delete(key),
+};
+global.localStorage = storage;
+global.window = {
+ localStorage: storage,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+};
+
+const {
+ getUsageState,
+ isPastDueUsage,
+ loadUsage,
+ normalizeUsage,
+ retryUsage,
+ setUsageAccount,
+ watchForUpgrade,
+} = require("../../src/lib/usageStore.ts");
+
+const BUSINESS = { plan: "business", status: "active", isSubscribed: true, limit: -1 };
+
+function deferred() {
+ let resolve;
+ let reject;
+ const promise = new Promise((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+}
+
+function reset() {
+ setUsageAccount(null);
+ values.clear();
+}
+
+const flush = () => new Promise((resolve) => setImmediate(resolve));
+
+test("an old response shape still resolves a personal entitlement", () => {
+ const legacy = normalizeUsage({ plan: "business", status: "active", isSubscribed: true });
+ assert.deepEqual(legacy.entitlementSources, { personal: true, workspaceIds: [] });
+ assert.equal(legacy.isSubscribed, true);
+
+ const trial = normalizeUsage({ plan: "free", status: "active", isTrial: true });
+ assert.equal(trial.entitlementSources.personal, true);
+
+ const free = normalizeUsage({ plan: "free", status: "active" });
+ assert.equal(free.entitlementSources.personal, false);
+});
+
+test("a missing limit is unknown, not the free-tier allowance", () => {
+ // 2000 here would put a business account whose limit the API omitted onto a
+ // free-tier meter; 0 fails the `limit > 0` guard every meter is behind.
+ assert.equal(normalizeUsage({ plan: "business", isSubscribed: true }).limit, 0);
+ assert.equal(normalizeUsage({ plan: "free", limit: 2000 }).limit, 2000);
+ assert.equal(normalizeUsage({ plan: "business", limit: -1 }).limit, -1);
+});
+
+test("an explicit entitlementSources block wins over the inferred one", () => {
+ const migrated = normalizeUsage({
+ plan: "free",
+ status: "active",
+ isSubscribed: true,
+ entitlementSources: { personal: false, workspaceIds: ["ws-1"] },
+ });
+ assert.deepEqual(migrated.entitlementSources, { personal: false, workspaceIds: ["ws-1"] });
+});
+
+test("past due is only derived from a paid plan", () => {
+ assert.equal(isPastDueUsage(normalizeUsage({ plan: "business", status: "past_due" })), true);
+ assert.equal(isPastDueUsage(normalizeUsage({ plan: "free", status: "past_due" })), false);
+});
+
+test("a successful load publishes the account's entitlement and the persisted flag", async (t) => {
+ t.after(reset);
+ reset();
+
+ setUsageAccount("user-a");
+ await loadUsage(async () => BUSINESS);
+
+ const state = getUsageState();
+ assert.equal(state.status, "success");
+ assert.equal(state.accountId, "user-a");
+ assert.equal(state.data.isSubscribed, true);
+ assert.equal(localStorage.getItem("isSubscribed"), "true");
+});
+
+test("switching accounts drops the previous account's in-flight response and flag", async (t) => {
+ t.after(reset);
+ reset();
+
+ localStorage.setItem("isSubscribed", "true");
+ setUsageAccount("user-a");
+ const gate = deferred();
+ const inFlight = loadUsage(() => gate.promise);
+
+ setUsageAccount("user-b");
+ gate.resolve(BUSINESS);
+ await inFlight;
+
+ const state = getUsageState();
+ assert.equal(state.accountId, "user-b");
+ assert.equal(state.status, "idle");
+ assert.equal(localStorage.getItem("isSubscribed"), null);
+});
+
+test("relaunching the same account keeps the persisted flag", (t) => {
+ t.after(reset);
+ reset();
+
+ // A restart starts from a null in-memory account with both markers persisted;
+ // clearing here would strand an offline session with sync disabled.
+ localStorage.setItem("openwhispr:usageAccountId", "user-a");
+ localStorage.setItem("isSubscribed", "true");
+
+ setUsageAccount("user-a");
+
+ assert.equal(localStorage.getItem("isSubscribed"), "true");
+});
+
+test("a flag with no recorded owner is not inherited", (t) => {
+ t.after(reset);
+ reset();
+
+ // The first launch of a build that records the owner: the flag on disk was
+ // written by whoever was signed in before, and cannot be attributed.
+ localStorage.setItem("isSubscribed", "true");
+
+ setUsageAccount("user-b");
+
+ assert.equal(localStorage.getItem("isSubscribed"), null);
+});
+
+test("signing out clears the persisted flag", async (t) => {
+ t.after(reset);
+ reset();
+
+ setUsageAccount("user-a");
+ await loadUsage(async () => BUSINESS);
+ setUsageAccount(null);
+
+ assert.equal(localStorage.getItem("isSubscribed"), null);
+ assert.deepEqual(getUsageState(), { status: "idle", accountId: null });
+});
+
+test("a failed load reports an error instead of a free plan", async (t) => {
+ t.after(reset);
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ reset();
+
+ setUsageAccount("user-a");
+ await loadUsage(async () => {
+ throw new Error("Network unreachable");
+ });
+
+ const state = getUsageState();
+ assert.equal(state.status, "error");
+ assert.equal(state.error, "Network unreachable");
+ assert.equal(state.isRetrying, true);
+ assert.equal(localStorage.getItem("isSubscribed"), null);
+});
+
+test("transient failures retry with bounded backoff, then stop", async (t) => {
+ t.after(reset);
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ reset();
+
+ let attempts = 0;
+ const failing = async () => {
+ attempts += 1;
+ throw new Error("boom");
+ };
+
+ setUsageAccount("user-a");
+ await loadUsage(failing);
+ assert.equal(attempts, 1);
+
+ for (const delay of [2000, 4000, 8000]) {
+ t.mock.timers.tick(delay);
+ await flush();
+ }
+
+ assert.equal(attempts, 4);
+ assert.equal(getUsageState().isRetrying, false, "backoff budget is exhausted");
+});
+
+test("an expired session is not retried", async (t) => {
+ t.after(reset);
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ reset();
+
+ setUsageAccount("user-a");
+ await loadUsage(async () => {
+ const error = new Error("Session expired");
+ error.code = "AUTH_EXPIRED";
+ throw error;
+ });
+
+ const state = getUsageState();
+ assert.equal(state.code, "AUTH_EXPIRED");
+ assert.equal(state.isRetrying, false);
+});
+
+test("a manual retry restores the backoff budget and refetches", async (t) => {
+ t.after(reset);
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ reset();
+
+ let attempts = 0;
+ setUsageAccount("user-a");
+ await loadUsage(async () => {
+ attempts += 1;
+ const error = new Error("Session expired");
+ error.code = "AUTH_EXPIRED";
+ throw error;
+ });
+ assert.equal(getUsageState().isRetrying, false);
+
+ await retryUsage(async () => BUSINESS);
+ assert.equal(attempts, 1);
+ assert.equal(getUsageState().status, "success");
+});
+
+test("consumers share one request and one cached result", async (t) => {
+ t.after(reset);
+ reset();
+
+ let calls = 0;
+ const gate = deferred();
+ const fetcher = () => {
+ calls += 1;
+ return gate.promise;
+ };
+
+ setUsageAccount("user-a");
+ const first = loadUsage(fetcher);
+ const second = loadUsage(fetcher);
+ gate.resolve(BUSINESS);
+ await Promise.all([first, second]);
+ assert.equal(calls, 1, "concurrent mounts share the in-flight request");
+
+ await loadUsage(fetcher);
+ assert.equal(calls, 1, "a later mount reuses the cached success");
+
+ await loadUsage(async () => ({ ...BUSINESS, isSubscribed: false }), { force: true });
+ assert.equal(getUsageState().data.isSubscribed, false, "force bypasses the cache");
+});
+
+test("a forced load during an in-flight request refetches instead of adopting it", async (t) => {
+ t.after(reset);
+ reset();
+
+ let calls = 0;
+ const gate = deferred();
+ const fetcher = () => {
+ calls += 1;
+ // Only the first call waits on the gate; the follow-up resolves immediately
+ // with the words the forced caller knew about.
+ return calls === 1 ? gate.promise : Promise.resolve({ ...BUSINESS, wordsUsed: 500 });
+ };
+
+ setUsageAccount("user-a");
+ const initial = loadUsage(fetcher);
+ const forced = loadUsage(fetcher, { force: true });
+ const alsoForced = loadUsage(fetcher, { force: true });
+ gate.resolve({ ...BUSINESS, wordsUsed: 100 });
+ await Promise.all([initial, forced, alsoForced]);
+
+ assert.equal(calls, 2, "concurrent forced callers coalesce into one follow-up");
+ assert.equal(getUsageState().data.wordsUsed, 500);
+});
+
+test("a forced load queued across a sign-out does not fetch for the next account", async (t) => {
+ t.after(reset);
+ reset();
+
+ let calls = 0;
+ const gate = deferred();
+ const fetcher = () => {
+ calls += 1;
+ return gate.promise;
+ };
+
+ setUsageAccount("user-a");
+ const initial = loadUsage(fetcher);
+ const forced = loadUsage(fetcher, { force: true });
+ setUsageAccount(null);
+ gate.resolve(BUSINESS);
+ await Promise.all([initial, forced]);
+
+ assert.equal(calls, 1);
+ assert.equal(getUsageState().status, "idle");
+});
+
+test("a stale queued force does not clobber the next account's queued one", async (t) => {
+ t.after(reset);
+ reset();
+
+ let calls = 0;
+ const gateA = deferred();
+ const gateB = deferred();
+ const fetcher = () => {
+ calls += 1;
+ if (calls === 1) return gateA.promise;
+ if (calls === 2) return gateB.promise;
+ return Promise.resolve(BUSINESS);
+ };
+
+ setUsageAccount("user-a");
+ const staleInitial = loadUsage(fetcher);
+ const staleForced = loadUsage(fetcher, { force: true });
+
+ setUsageAccount("user-b");
+ const initial = loadUsage(fetcher);
+ const forced = loadUsage(fetcher, { force: true });
+
+ // user-a's request lands only after user-b has queued a force of its own.
+ gateA.resolve(BUSINESS);
+ await Promise.all([staleInitial, staleForced]);
+
+ const alsoForced = loadUsage(fetcher, { force: true });
+ gateB.resolve(BUSINESS);
+ await Promise.all([initial, forced, alsoForced]);
+
+ assert.equal(calls, 3, "the later forced caller joins user-b's surviving follow-up");
+ assert.equal(getUsageState().accountId, "user-b");
+});
+
+test("the post-checkout poll keeps refetching until the webhook lands", async (t) => {
+ t.after(reset);
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ reset();
+
+ let calls = 0;
+ const fetcher = async () => {
+ calls += 1;
+ return calls < 3 ? { ...BUSINESS, isSubscribed: false } : BUSINESS;
+ };
+
+ setUsageAccount("user-a");
+ const watching = watchForUpgrade(fetcher);
+ for (const delay of [2000, 4000]) {
+ await flush();
+ t.mock.timers.tick(delay);
+ }
+ await watching;
+
+ assert.equal(calls, 3);
+ assert.equal(getUsageState().data.isSubscribed, true);
+});
+
+test("a second upgrade watch is a no-op while one is running", async (t) => {
+ t.after(reset);
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ reset();
+
+ let calls = 0;
+ const fetcher = async () => {
+ calls += 1;
+ return { ...BUSINESS, isSubscribed: false };
+ };
+
+ setUsageAccount("user-a");
+ const watching = watchForUpgrade(fetcher);
+ await watchForUpgrade(fetcher);
+ assert.equal(calls, 1, "a second consumer does not start its own poll");
+
+ for (const delay of [2000, 4000, 8000, 1]) {
+ await flush();
+ t.mock.timers.tick(delay);
+ }
+ await watching;
+
+ assert.equal(calls, 4, "a webhook that never lands gives up after a bounded number of attempts");
+});
+
+test("an upgrade watch stops when the account changes", async (t) => {
+ t.after(reset);
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ reset();
+
+ let calls = 0;
+ const fetcher = async () => {
+ calls += 1;
+ return { ...BUSINESS, isSubscribed: false };
+ };
+
+ setUsageAccount("user-a");
+ const watching = watchForUpgrade(fetcher);
+ await flush();
+
+ setUsageAccount("user-b");
+ t.mock.timers.tick(2000);
+ await watching;
+
+ assert.equal(calls, 1, "the poll does not carry into the next account");
+ assert.equal(getUsageState().accountId, "user-b");
+});
+
+test("an error is never cached: the next consumer retries", async (t) => {
+ t.after(reset);
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ reset();
+
+ setUsageAccount("user-a");
+ await loadUsage(async () => {
+ throw new Error("boom");
+ });
+
+ await loadUsage(async () => BUSINESS);
+ assert.equal(getUsageState().status, "success");
+});