Skip to content

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

feat: add analytics leaderboard (#2011)

void60bc697c0120
diff --git a/preload.js b/preload.js
index c1c3973ea..b20035329 100644
--- a/preload.js
+++ b/preload.js
@@ -128,17 +128,23 @@ contextBridge.exposeInMainWorld("electronAPI", {
ipcRenderer.invoke("db-get-transcriptions", limit, options),
recordAnalyticsEvent: (input) => ipcRenderer.invoke("analytics-record-event", input),
getAnalyticsSummary: () => ipcRenderer.invoke("analytics-get-summary"),
- getPendingAnalyticsEvents: (limit) => ipcRenderer.invoke("analytics-get-pending", limit),
- markAnalyticsEventsSynced: (eventIds) => ipcRenderer.invoke("analytics-mark-synced", eventIds),
- getPendingAnalyticsDeletes: (limit) => ipcRenderer.invoke("analytics-get-pending-deletes", limit),
- hardDeleteAnalyticsEvents: (eventIds) => ipcRenderer.invoke("analytics-hard-delete", eventIds),
- getPendingAnalyticsClear: () => ipcRenderer.invoke("analytics-get-pending-clear"),
- completeAnalyticsClear: (clearedThrough) =>
- ipcRenderer.invoke("analytics-complete-clear", clearedThrough),
- countUnclaimedAnalyticsEvents: () => ipcRenderer.invoke("analytics-count-unclaimed"),
- countAnalyticsEventsAwaitingUpload: () =>
- ipcRenderer.invoke("analytics-count-awaiting-upload"),
- claimAnonymousAnalyticsEvents: () => ipcRenderer.invoke("analytics-claim-anonymous"),
+ getPendingAnalyticsEvents: (limit, context) =>
+ ipcRenderer.invoke("analytics-get-pending", limit, context),
+ markAnalyticsEventsSynced: (eventIds, context) =>
+ ipcRenderer.invoke("analytics-mark-synced", eventIds, context),
+ getPendingAnalyticsDeletes: (limit, context) =>
+ ipcRenderer.invoke("analytics-get-pending-deletes", limit, context),
+ hardDeleteAnalyticsEvents: (eventIds, context) =>
+ ipcRenderer.invoke("analytics-hard-delete", eventIds, context),
+ getPendingAnalyticsClear: (context) => ipcRenderer.invoke("analytics-get-pending-clear", context),
+ completeAnalyticsClear: (clearedThrough, context) =>
+ ipcRenderer.invoke("analytics-complete-clear", clearedThrough, context),
+ countUnclaimedAnalyticsEvents: (context) =>
+ ipcRenderer.invoke("analytics-count-unclaimed", context),
+ countAnalyticsEventsAwaitingUpload: (context) =>
+ ipcRenderer.invoke("analytics-count-awaiting-upload", context),
+ claimAnonymousAnalyticsEvents: (accountId, expectedAuthGeneration) =>
+ ipcRenderer.invoke("analytics-claim-anonymous", accountId, expectedAuthGeneration),
clearTranscriptions: () => ipcRenderer.invoke("db-clear-transcriptions"),
deleteTranscription: (id) => ipcRenderer.invoke("db-delete-transcription", id),
@@ -379,6 +385,9 @@ contextBridge.exposeInMainWorld("electronAPI", {
promptAccessibilityPermission: () => ipcRenderer.invoke("prompt-accessibility-permission"),
readClipboard: () => ipcRenderer.invoke("read-clipboard"),
writeClipboard: (text) => ipcRenderer.invoke("write-clipboard", text),
+ copyLeaderboardImage: (dataUrl) => ipcRenderer.invoke("leaderboard-copy-image", dataUrl),
+ saveLeaderboardImage: (dataUrl, suggestedName) =>
+ ipcRenderer.invoke("leaderboard-save-image", dataUrl, suggestedName),
checkPasteTools: () => ipcRenderer.invoke("check-paste-tools"),
// Voice drafts (chat input recordings)
diff --git a/scripts/check-i18n.js b/scripts/check-i18n.js
index 589cda72e..b923acc0b 100644
--- a/scripts/check-i18n.js
+++ b/scripts/check-i18n.js
@@ -37,6 +37,75 @@ function arraysEqual(a, b) {
return a.length === b.length && a.every((v, i) => v === b[i]);
}
+const PLURAL_SUFFIX = /^(.*)_(zero|one|two|few|many|other)$/;
+// Counts a leaderboard, a member list or a streak can realistically carry.
+// Spanish, French, Italian and Portuguese reserve "many" for millions, and no
+// key here ever renders one, so requiring that form would fail every locale
+// file over a case no user reaches.
+const PROBE_LIMIT = 200;
+
+// Which counts each of a locale's plural categories actually selects.
+function pluralProbe(lang) {
+ const rules = new Intl.PluralRules(lang);
+ const selected = new Map();
+ for (let count = 0; count <= PROBE_LIMIT; count++) {
+ const category = rules.select(count);
+ if (!selected.has(category)) selected.set(category, []);
+ selected.get(category).push(count);
+ }
+ return selected;
+}
+
+/**
+ * i18next resolves a plural form with the locale's own CLDR rules and then falls
+ * back to English when that form is missing, so an absent form ships English
+ * text rather than a grammar slip. And a category is not always "exactly one":
+ * Russian's `one` also covers 21 and 31, French's covers 0, so a form for one of
+ * those has to interpolate the count instead of writing the digit.
+ */
+function checkPlurals(lang, namespace, flat) {
+ const selected = pluralProbe(lang);
+ const forms = new Map();
+
+ for (const key of Object.keys(flat)) {
+ const match = key.match(PLURAL_SUFFIX);
+ if (!match) continue;
+ if (!forms.has(match[1])) forms.set(match[1], new Set());
+ forms.get(match[1]).add(match[2]);
+ }
+
+ let missing = false;
+
+ for (const [base, categories] of forms) {
+ for (const [category, counts] of selected) {
+ if (!categories.has(category)) {
+ console.error(
+ `[i18n] Missing plural form ${lang}/${namespace}: ${base}_${category} (${lang} uses it for ${counts.slice(0, 3).join(", ")})`
+ );
+ missing = true;
+ }
+ }
+
+ for (const category of categories) {
+ const counts = selected.get(category);
+ if (!counts || counts.every((count) => count === 1)) continue;
+
+ const value = flat[`${base}_${category}`];
+ if (typeof value === "string" && !value.includes("{{count}}")) {
+ console.error(
+ `[i18n] Hardcoded count ${lang}/${namespace}: ${base}_${category} also renders for ${counts
+ .filter((count) => count !== 1)
+ .slice(0, 3)
+ .join(", ")}, so it must interpolate {{count}}`
+ );
+ missing = true;
+ }
+ }
+ }
+
+ return missing;
+}
+
const languages = fs
.readdirSync(LOCALES_DIR)
.filter((entry) => fs.statSync(path.join(LOCALES_DIR, entry)).isDirectory())
@@ -53,6 +122,7 @@ for (const namespace of NAMESPACES) {
}
const baseFlat = flatten(readJson(baseFile));
+ if (checkPlurals(BASE_LANG, namespace, baseFlat)) failed = true;
for (const lang of languages) {
if (lang === BASE_LANG) continue;
@@ -65,6 +135,7 @@ for (const namespace of NAMESPACES) {
}
const flat = flatten(readJson(file));
+ if (checkPlurals(lang, namespace, flat)) failed = true;
for (const key of Object.keys(baseFlat)) {
if (!(key in flat)) {
diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsx
index 1920b7b97..4cb0d2066 100644
--- a/src/components/ControlPanel.tsx
+++ b/src/components/ControlPanel.tsx
@@ -1178,7 +1178,12 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro
)}
{activeView === "insights" && (
<Suspense fallback={null}>
- <InsightsView />
+ <InsightsView
+ onSignIn={() => {
+ setSettingsSection("account");
+ setShowSettings(true);
+ }}
+ />
</Suspense>
)}
{activeView === "chat" && agentAllowedByPolicy && (
diff --git a/src/components/CreateWorkspaceDialog.tsx b/src/components/CreateWorkspaceDialog.tsx
index dac887aeb..e3f93cf66 100644
--- a/src/components/CreateWorkspaceDialog.tsx
+++ b/src/components/CreateWorkspaceDialog.tsx
@@ -17,12 +17,18 @@ import { useDelayedFlag } from "../hooks/useDelayedFlag";
import { useToast } from "./ui/useToast";
interface Props {
+ defaultName?: string;
open: boolean;
onOpenChange: (open: boolean) => void;
onCreated?: (workspaceId: string) => void;
}
-export default function CreateWorkspaceDialog({ open, onOpenChange, onCreated }: Props) {
+export default function CreateWorkspaceDialog({
+ defaultName,
+ open,
+ onOpenChange,
+ onCreated,
+}: Props) {
const { t } = useTranslation();
const { toast } = useToast();
const createWorkspace = useWorkspaceStore((s) => s.createWorkspace);
@@ -32,8 +38,8 @@ export default function CreateWorkspaceDialog({ open, onOpenChange, onCreated }:
const showSpinner = useDelayedFlag(submitting);
useEffect(() => {
- if (!open) setName("");
- }, [open]);
+ setName(open ? (defaultName ?? "") : "");
+ }, [defaultName, open]);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
diff --git a/src/components/InsightsView.tsx b/src/components/InsightsView.tsx
index b97196b7f..ff0f211d2 100644
--- a/src/components/InsightsView.tsx
+++ b/src/components/InsightsView.tsx
@@ -1,24 +1,34 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { BarChart3, Cloud, Flame, Gauge, Loader2, Mic2 } from "lucide-react";
+import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { BarChart3, Cloud, CloudUpload, Flame, Gauge, Loader2, Mic2, Trophy } from "lucide-react";
import { useTranslation } from "react-i18next";
import { useAuth } from "../hooks/useAuth";
import { useInsightsSyncOptIn } from "../hooks/useInsightsSyncOptIn";
import { useSettings } from "../hooks/useSettings";
+import { hasValidatedAuthContext } from "../lib/authRequestContext";
import {
getAccountAnalyticsSummary,
subscribeToAnalyticsRefresh,
- syncPendingAnalytics,
} from "../services/AnalyticsService";
+import { syncService } from "../services/SyncService";
import { buildAnalyticsActivityDays } from "../helpers/analytics";
import { canOfferAnalyticsClaim } from "../services/syncPassPolicy";
import { effectiveLocalHistoryEnabled } from "../stores/policyRules";
+import { useLeaderboardParticipationStore } from "../stores/leaderboardParticipationStore";
import { usePolicyStore } from "../stores/policyStore";
import type { AnalyticsDailyBucket, AnalyticsSummary } from "../types/electron";
import { cn } from "./lib/utils";
+import { Button } from "./ui/button";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { Tooltip } from "./ui/tooltip";
type ActivityDay = { date: string; words: number };
+interface InsightsViewProps {
+ onSignIn: () => void;
+}
+
+const LeaderboardView = lazy(() => import("./LeaderboardView"));
+
const ACTIVITY_INTENSITY_CLASSES = [
"bg-foreground/6 dark:bg-white/6",
"bg-primary/25",
@@ -207,19 +217,18 @@ function MetricCard({
);
}
-export default function InsightsView() {
+function YourUsage({
+ dataRetentionEnabled,
+ isLoaded,
+ onSyncErrorChange,
+ syncActive,
+}: {
+ dataRetentionEnabled: boolean;
+ isLoaded: boolean;
+ onSyncErrorChange: (error: boolean) => void;
+ syncActive: boolean;
+}) {
const { t, i18n } = useTranslation();
- const { isSignedIn, isLoaded } = useAuth();
- const { dataRetentionEnabled: personalDataRetentionEnabled, insightsSyncEnabled } = useSettings();
- const dataRetentionEnabled = usePolicyStore((policyState) =>
- effectiveLocalHistoryEnabled(policyState, personalDataRetentionEnabled)
- );
- const { enableInsightsSync, optInDialog, syncAllowedByPolicy, unclaimedCount } =
- useInsightsSyncOptIn();
- // A managed workspace that forbids cloud backup forbids these counters with
- // it, so the view stays device-scoped even with the preference left on.
- const syncActive =
- isSignedIn && insightsSyncEnabled && syncAllowedByPolicy && dataRetentionEnabled;
const [summary, setSummary] = useState<AnalyticsSummary | null>(null);
const [loading, setLoading] = useState(true);
const [syncError, setSyncError] = useState(false);
@@ -254,9 +263,10 @@ export default function InsightsView() {
try {
if (isLoaded && syncActive) {
- await syncPendingAnalytics();
- const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
- const account = await getAccountAnalyticsSummary(timeZone);
+ if (!(await syncService.syncAnalyticsNow())) {
+ throw new Error("Insights uploads are not enabled for this account");
+ }
+ const account = await getAccountAnalyticsSummary();
if (requestId !== requestIdRef.current) return;
setSummary(account);
} else {
@@ -274,6 +284,10 @@ export default function InsightsView() {
useEffect(() => subscribeToAnalyticsRefresh(load, syncActive), [load, syncActive]);
+ useEffect(() => {
+ onSyncErrorChange(syncError);
+ }, [onSyncErrorChange, syncError]);
+
// i18n.language, not the runtime default: the OS locale is not the language
// the app is being read in, so a Japanese UI rendered 12.3K where 1.2万
// belongs, next to correctly localized month labels in the same card.
@@ -284,18 +298,16 @@ export default function InsightsView() {
if (loadFailed) {
return (
- <div className="mx-auto w-full max-w-5xl px-6 py-8">
- <div className="rounded-lg border border-border bg-card/50 backdrop-blur-sm dark:bg-card/60">
- <div className="flex flex-col items-center justify-center gap-3 px-4 py-16 text-center">
- <p className="max-w-sm text-sm text-muted-foreground">{t("insights.loadError")}</p>
- <button
- type="button"
- onClick={() => void load()}
- className="rounded-md border border-border px-3 py-1.5 text-xs font-medium text-foreground hover:bg-accent"
- >
- {t("common.retry")}
- </button>
- </div>
+ <div className="rounded-lg border border-border bg-card/50 backdrop-blur-sm dark:bg-card/60">
+ <div className="flex flex-col items-center justify-center gap-3 px-4 py-16 text-center">
+ <p className="max-w-sm text-sm text-muted-foreground">{t("insights.loadError")}</p>
+ <button
+ type="button"
+ onClick={() => void load()}
+ className="rounded-md border border-border px-3 py-1.5 text-xs font-medium text-foreground hover:bg-accent"
+ >
+ {t("common.retry")}
+ </button>
</div>
</div>
);
@@ -303,35 +315,17 @@ export default function InsightsView() {
if (!summary) {
return (
- <div className="mx-auto w-full max-w-5xl px-6 py-8">
- <div className="rounded-lg border border-border bg-card/50 backdrop-blur-sm dark:bg-card/60">
- <div className="flex items-center justify-center gap-2 py-8">
- <Loader2 size={14} className="animate-spin text-primary" />
- <span className="text-sm text-muted-foreground">{t("controlPanel.loading")}</span>
- </div>
+ <div className="rounded-lg border border-border bg-card/50 backdrop-blur-sm dark:bg-card/60">
+ <div className="flex items-center justify-center gap-2 py-8">
+ <Loader2 size={14} className="animate-spin text-primary" />
+ <span className="text-sm text-muted-foreground">{t("controlPanel.loading")}</span>
</div>
</div>
);
}
return (
- <div className="mx-auto w-full max-w-5xl px-6 py-8">
- <div className="mb-6 flex items-start justify-between gap-4">
- <div>
- <h1 className="text-base! font-semibold! leading-none! tracking-normal! text-foreground">
- {t("insights.title")}
- </h1>
- </div>
- <div className="flex items-center gap-2 text-[11px] text-muted-foreground">
- <Cloud size={13} />
- {syncActive
- ? syncError
- ? t("insights.syncFallback")
- : t("insights.synced")
- : t("insights.onDevice")}
- </div>
- </div>
-
+ <>
{!dataRetentionEnabled && (
<div className="mb-5 rounded-lg border border-amber-500/30 bg-amber-500/5 dark:bg-amber-500/10 px-3.5 py-2.5 flex items-center gap-2.5">
<span className="text-amber-600 dark:text-amber-400 shrink-0 text-sm">⊘</span>
@@ -341,27 +335,6 @@ export default function InsightsView() {
</div>
)}
- {canOfferAnalyticsClaim({
- signedIn: isSignedIn,
- syncAllowedByPolicy,
- dataRetentionEnabled,
- insightsSyncEnabled,
- unclaimedCount,
- }) && (
- <div className="mb-5 flex items-center justify-between gap-4 rounded-xl border border-primary/15 bg-primary/5 px-4 py-3">
- <p className="text-xs text-muted-foreground">
- {t(insightsSyncEnabled ? "insights.claimTitle" : "insights.syncPrompt")}
- </p>
- <button
- type="button"
- onClick={enableInsightsSync}
- className="shrink-0 rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90"
- >
- {t(insightsSyncEnabled ? "insights.claimInclude" : "insights.enableSync")}
- </button>
- </div>
- )}
-
{summary.totalDictations === 0 ? (
<div className="rounded-lg border border-border bg-card/50 backdrop-blur-sm dark:bg-card/60">
<div className="flex flex-col items-center justify-center px-4 py-16 text-center">
@@ -412,7 +385,128 @@ export default function InsightsView() {
</div>
</>
)}
+ </>
+ );
+}
+export default function InsightsView({ onSignIn }: InsightsViewProps) {
+ const { t } = useTranslation();
+ const { isLoaded, isSignedIn } = useAuth();
+ const authValidated = hasValidatedAuthContext();
+ const { dataRetentionEnabled: personalDataRetentionEnabled, insightsSyncEnabled } = useSettings();
+ const dataRetentionEnabled = usePolicyStore((policyState) =>
+ effectiveLocalHistoryEnabled(policyState, personalDataRetentionEnabled)
+ );
+ const { canToggleSync, enableInsightsSync, optInDialog, syncAllowedByPolicy, unclaimedCount } =
+ useInsightsSyncOptIn();
+ const participationEnabled = useLeaderboardParticipationStore((state) => state.enabled);
+ const participationError = useLeaderboardParticipationStore((state) => state.error);
+ const participationReady = useLeaderboardParticipationStore((state) => state.ready);
+ const participationLeavePending = useLeaderboardParticipationStore((state) => state.leavePending);
+ const [activeTab, setActiveTab] = useState("usage");
+ const [syncError, setSyncError] = useState(false);
+ // A managed workspace that forbids cloud backup forbids these counters with
+ // it, so the page stays device-scoped even with the preference left on.
+ const syncActive =
+ isSignedIn &&
+ authValidated &&
+ insightsSyncEnabled &&
+ syncAllowedByPolicy &&
+ dataRetentionEnabled;
+ const claimAvailable = canOfferAnalyticsClaim({
+ signedIn: isSignedIn,
+ syncAllowedByPolicy,
+ dataRetentionEnabled,
+ insightsSyncEnabled,
+ unclaimedCount,
+ });
+ const showSyncAction =
+ activeTab === "usage" && isSignedIn && authValidated && (!syncActive || claimAvailable);
+ const syncActionDisabled = !canToggleSync || !dataRetentionEnabled || !syncAllowedByPolicy;
+ const syncStatusLabel = syncActive
+ ? syncError
+ ? t("insights.syncFallback")
+ : t("insights.synced")
+ : t("insights.onDevice");
+
+ return (
+ <div className="mx-auto flex min-h-full w-full max-w-5xl flex-col px-6 py-8">
+ <h1 className="text-base! font-semibold! leading-none! tracking-normal! text-foreground">
+ {t("insights.title")}
+ </h1>
+
+ <Tabs value={activeTab} onValueChange={setActiveTab} className="mt-6 flex flex-1 flex-col">
+ <div className="flex min-h-8 items-center justify-between gap-4">
+ <TabsList className="h-7 p-0.5 rounded-[7px]">
+ <TabsTrigger value="usage" className="h-6 px-2.5 text-xs rounded-[5px]">
+ {t("insights.yourUsage")}
+ </TabsTrigger>
+ <TabsTrigger value="leaderboard" className="h-6 px-2.5 text-xs rounded-[5px]">
+ {t("insights.leaderboard.title")}
+ </TabsTrigger>
+ </TabsList>
+
+ {activeTab === "usage" ? (
+ <div className="flex shrink-0 items-center gap-3">
+ <div className="flex items-center gap-2 text-[11px] text-muted-foreground">
+ <Cloud size={13} />
+ {syncStatusLabel}
+ </div>
+ {showSyncAction && (
+ <Button
+ type="button"
+ variant="default"
+ size="sm"
+ className="h-7 rounded-[7px] px-2.5 text-[11px]"
+ disabled={syncActionDisabled}
+ onClick={() => void enableInsightsSync()}
+ >
+ <CloudUpload size={13} />
+ {t(syncActive ? "insights.claimInclude" : "insights.enableSync")}
+ </Button>
+ )}
+ </div>
+ ) : (
+ isSignedIn &&
+ participationReady &&
+ participationError === null &&
+ !participationEnabled && (
+ <div className="flex items-center gap-2 text-[11px] text-muted-foreground">
+ <Trophy size={13} />
+ {t(
+ participationLeavePending
+ ? "insights.leaderboard.leavePending"
+ : "insights.leaderboard.disabled"
+ )}
+ </div>
+ )
+ )}
+ </div>
+
+ <TabsContent value="usage" className="mt-6 flex flex-1 flex-col">
+ <YourUsage
+ dataRetentionEnabled={dataRetentionEnabled}
+ isLoaded={isLoaded}
+ onSyncErrorChange={setSyncError}
+ syncActive={syncActive}
+ />
+ {isLoaded && !syncActive && (
+ <p className="mt-auto pt-8 text-center text-[11px] text-muted-foreground/70">
+ {t("insights.onDevicePrivacy")}
+ </p>
+ )}
+ </TabsContent>
+ <TabsContent value="leaderboard" className="mt-0">
+ <Suspense fallback={null}>
+ <LeaderboardView
+ enableInsightsSync={enableInsightsSync}
+ insightsSyncEnabled={insightsSyncEnabled}
+ onSignIn={onSignIn}
+ syncAllowedByPolicy={syncAllowedByPolicy}
+ />
+ </Suspense>
+ </TabsContent>
+ </Tabs>
{optInDialog}
</div>
);
diff --git a/src/components/LeaderboardAcceptInvitePreview.tsx b/src/components/LeaderboardAcceptInvitePreview.tsx
new file mode 100644
index 000000000..9abd4f72e
--- /dev/null
+++ b/src/components/LeaderboardAcceptInvitePreview.tsx
@@ -0,0 +1,46 @@
+import { Check, Loader2 } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import LeaderboardPreview from "./LeaderboardPreview";
+
+export default function LeaderboardAcceptInvitePreview({
+ className,
+ inviterName,
+ joining,
+ onAccept,
+ workspaceName,
+}: {
+ className?: string;
+ inviterName: string | null;
+ joining: boolean;
+ onAccept: () => void;
+ workspaceName: string;
+}) {
+ const { t } = useTranslation();
+
+ return (
+ <LeaderboardPreview
+ actionDisabled={joining}
+ actionIcon={joining ? Loader2 : Check}
+ actionIconClassName={joining ? "animate-spin" : undefined}
+ actionLabel={
+ joining ? t("insights.leaderboard.joining") : t("insights.leaderboard.acceptInviteCta")
+ }
+ badge={workspaceName}
+ className={className}
+ dataState="accept_invite"
+ description={
+ inviterName
+ ? t("insights.leaderboard.acceptInviteDescription", {
+ inviter: inviterName,
+ workspace: workspaceName,
+ })
+ : t("insights.leaderboard.acceptInviteDescriptionNoInviter", {
+ workspace: workspaceName,
+ })
+ }
+ icon={Check}
+ onAction={onAccept}
+ title={t("insights.leaderboard.acceptInviteTitle", { workspace: workspaceName })}
+ />
+ );
+}
diff --git a/src/components/LeaderboardEmptyStrip.tsx b/src/components/LeaderboardEmptyStrip.tsx
new file mode 100644
index 000000000..ca3b4e351
--- /dev/null
+++ b/src/components/LeaderboardEmptyStrip.tsx
@@ -0,0 +1,43 @@
+import { Check, Copy, Users } from "lucide-react";
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "./ui/button";
+import { useToast } from "./ui/useToast";
+
+export default function LeaderboardEmptyStrip({ missingCount }: { missingCount: number }) {
+ const { t } = useTranslation();
+ const { toast } = useToast();
+ const [copied, setCopied] = useState(false);
+
+ const copyNudge = async () => {
+ try {
+ const result = await window.electronAPI.writeClipboard(t("insights.leaderboard.nudgeText"));
+ if (!result.success) throw new Error("Clipboard write failed");
+ setCopied(true);
+ toast({ title: t("insights.leaderboard.nudgeCopied") });
+ } catch (error) {
+ console.error("Copying leaderboard nudge failed:", error);
+ toast({ title: t("insights.leaderboard.nudgeCopyError"), variant: "destructive" });
+ }
+ };
+
+ return (
+ <div
+ data-leaderboard-state="empty_strip"
+ className="flex flex-wrap items-center justify-between gap-3 border-b border-border/40 bg-primary/5 px-5 py-3"
+ >
+ <div className="flex min-w-0 items-center gap-3">
+ <div className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">
+ <Users size={15} />
+ </div>
+ <p className="text-xs leading-relaxed text-muted-foreground">
+ {t("insights.leaderboard.emptyStrip", { count: missingCount })}
+ </p>
+ </div>
+ <Button variant="outline-flat" size="sm" onClick={() => void copyNudge()}>
+ {copied ? <Check size={14} /> : <Copy size={14} />}
+ {copied ? t("insights.leaderboard.nudgeCopied") : t("insights.leaderboard.copyNudge")}
+ </Button>
+ </div>
+ );
+}
diff --git a/src/components/LeaderboardJoinPreview.tsx b/src/components/LeaderboardJoinPreview.tsx
new file mode 100644
index 000000000..2d437070e
--- /dev/null
+++ b/src/components/LeaderboardJoinPreview.tsx
@@ -0,0 +1,46 @@
+import { UserPlus } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import LeaderboardPreview from "./LeaderboardPreview";
+
+export default function LeaderboardJoinPreview({
+ canJoin,
+ error,
+ leavePending,
+ onJoin,
+ scopeName,
+ updating,
+}: {
+ canJoin: boolean;
+ error: boolean;
+ /** The account is still being taken off the boards this device left. */
+ leavePending: boolean;
+ onJoin: () => Promise<boolean>;
+ scopeName: string;
+ updating: boolean;
+}) {
+ const { t } = useTranslation();
+ return (
+ <LeaderboardPreview
+ actionDisabled={!canJoin || updating}
+ actionLabel={t(
+ updating ? "insights.leaderboard.joiningLeaderboard" : "insights.leaderboard.joinCta"
+ )}
+ badge={scopeName}
+ className="mt-6"
+ dataState="join"
+ description={t("insights.leaderboard.joinDescription")}
+ helperText={
+ error
+ ? t("insights.leaderboard.activationError")
+ : leavePending
+ ? t("insights.leaderboard.leavePending")
+ : !canJoin
+ ? t("insights.leaderboard.joinPolicyBlocked")
+ : undefined
+ }
+ icon={UserPlus}
+ onAction={() => void onJoin()}
+ title={t("insights.leaderboard.joinTitle", { scope: scopeName })}
+ />
+ );
+}
diff --git a/src/components/LeaderboardPodium.tsx b/src/components/LeaderboardPodium.tsx
new file mode 100644
index 000000000..cb46cd07a
--- /dev/null
+++ b/src/components/LeaderboardPodium.tsx
@@ -0,0 +1,111 @@
+import { Crown, Medal } from "lucide-react";
+import type { LeaderboardMember } from "../types/electron";
+import { cn } from "./lib/utils";
+import MemberAvatar from "./MemberAvatar";
+
+const PODIUM_PLACEMENTS = [
+ {
+ memberIndex: 0,
+ cardClass: "border-amber-400/25 bg-amber-400/5 sm:min-h-44 sm:-translate-y-1",
+ rankClass: "bg-amber-400/12 text-amber-600 dark:text-amber-400",
+ iconClass: "text-amber-500",
+ Icon: Crown,
+ },
+ {
+ memberIndex: 1,
+ cardClass: "border-slate-400/30 bg-slate-400/5 sm:min-h-40 dark:border-slate-300/20",
+ rankClass: "bg-slate-400/12 text-slate-600 dark:text-slate-300",
+ iconClass: "text-slate-500 dark:text-slate-300",
+ Icon: Medal,
+ },
+ {
+ memberIndex: 2,
+ cardClass: "border-orange-500/25 bg-orange-500/5 sm:min-h-40",
+ rankClass: "bg-orange-400/10 text-orange-600 dark:text-orange-400",
+ iconClass: "text-orange-500/80",
+ Icon: Medal,
+ },
+] as const;
+
+export default function LeaderboardPodium({
+ formatValue,
+ memberLabel,
+ members,
+ metricLabel,
+ periodLabel,
+ title,
+}: {
+ formatValue: (member: LeaderboardMember) => string;
+ memberLabel: (member: LeaderboardMember) => string;
+ members: LeaderboardMember[];
+ metricLabel: string;
+ periodLabel: string;
+ title: string;
+}) {
+ if (members.length === 0) return null;
+ const placements = PODIUM_PLACEMENTS.slice(0, Math.min(members.length, 3));
+
+ return (
+ <div className="px-5 pb-5 pt-4">
+ <div className="mb-4 flex flex-wrap items-center justify-between gap-2">
+ <div className="flex items-center gap-2 text-xs font-medium text-foreground">
+ <Medal size={14} className="text-amber-500" />
+ {title}
+ </div>
+ <p className="text-[11px] text-muted-foreground">
+ {metricLabel} · {periodLabel}
+ </p>
+ </div>
+
+ <div
+ className={cn(
+ "grid grid-cols-1 items-end gap-3",
+ members.length === 1 && "mx-auto max-w-md",
+ members.length === 2 && "mx-auto max-w-3xl sm:grid-cols-2",
+ members.length >= 3 && "sm:grid-cols-3"
+ )}
+ >
+ {placements.map(({ memberIndex, cardClass, rankClass, iconClass, Icon }) => {
+ const member = members[memberIndex];
+ if (!member) return null;
+
+ return (
+ <div
+ key={member.userId}
+ className={cn(
+ "relative flex min-h-36 flex-col items-center justify-center rounded-xl border px-4 py-4 text-center",
+ members.length >= 3 && member.rank === 1 && "sm:order-2",
+ members.length >= 3 && member.rank === 2 && "sm:order-1",
+ members.length >= 3 && member.rank === 3 && "sm:order-3",
+ cardClass
+ )}
+ >
+ <div
+ className={cn(
+ "absolute left-3 top-3 flex h-6 min-w-6 items-center justify-center gap-1 rounded-md px-1.5 text-[10px] font-semibold tabular-nums",
+ rankClass
+ )}
+ >
+ <Icon size={11} className={iconClass} />
+ {member.rank}
+ </div>
+
+ <div className="rounded-full ring-4 ring-background/70">
+ <MemberAvatar
+ name={member.name}
+ email={member.email}
+ image={member.image}
+ size="lg"
+ />
+ </div>
+ <p className="mt-3 max-w-full truncate text-sm font-medium">{memberLabel(member)}</p>
+ <p className="mt-1 text-2xl font-semibold tracking-tight tabular-nums">
+ {formatValue(member)}
+ </p>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/LeaderboardPreview.tsx b/src/components/LeaderboardPreview.tsx
new file mode 100644
index 000000000..e1eed010e
--- /dev/null
+++ b/src/components/LeaderboardPreview.tsx
@@ -0,0 +1,121 @@
+import type { ReactNode } from "react";
+import { Trophy, type LucideIcon } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { cn } from "./lib/utils";
+import { Badge } from "./ui/badge";
+import { Button } from "./ui/button";
+
+const PREVIEW_ROWS = [92, 84, 76, 68, 61] as const;
+
+interface LeaderboardPreviewProps {
+ actionDisabled?: boolean;
+ actionIcon?: LucideIcon;
+ actionIconClassName?: string;
+ actionLabel?: string;
+ badge?: string;
+ className?: string;
+ children?: ReactNode;
+ dataState?: string;
+ description: string;
+ helperText?: string;
+ icon: LucideIcon;
+ onAction?: () => void;
+ title: string;
+}
+
+export default function LeaderboardPreview({
+ actionIcon: ActionIcon,
+ actionIconClassName,
+ actionDisabled = false,
+ actionLabel,
+ badge,
+ className,
+ children,
+ dataState,
+ description,
+ helperText,
+ icon: Icon,
+ onAction,
+ title,
+}: LeaderboardPreviewProps) {
+ const { t } = useTranslation();
+
+ return (
+ <section
+ data-leaderboard-state={dataState}
+ className={cn(
+ "relative min-h-96 overflow-hidden rounded-2xl border border-border/50 bg-card/70 dark:border-white/8",
+ className
+ )}
+ >
+ <div className="pointer-events-none select-none opacity-35 blur-[1px]" aria-hidden="true">
+ <div className="flex items-center gap-2 border-b border-border/40 px-5 py-4">
+ <Trophy size={17} className="text-amber-500" />
+ <div className="h-4 w-28 rounded bg-foreground/20" />
+ </div>
+
+ <div className="grid grid-cols-3 items-end gap-3 px-8 py-6">
+ {[2, 1, 3].map((rank) => (
+ <div
+ key={rank}
+ className={cn(
+ "flex flex-col items-center rounded-xl border border-border/40 bg-background/40 px-3 py-4",
+ rank === 1 && "py-6"
+ )}
+ >
+ <div className="flex size-10 items-center justify-center rounded-full bg-muted text-xs font-semibold text-muted-foreground">
+ {rank}
+ </div>
+ <div className="mt-3 h-3 w-20 rounded bg-foreground/20" />
+ <div className="mt-2 h-4 w-14 rounded bg-foreground/25" />
+ </div>
+ ))}
+ </div>
+
+ <div className="border-t border-border/40 px-5 py-3">
+ <div className="mb-2 grid grid-cols-[3rem_1fr_6rem] gap-3 text-[10px] uppercase tracking-wide text-muted-foreground">
+ <span>{t("insights.leaderboard.rank")}</span>
+ <span>{t("insights.leaderboard.member")}</span>
+ <span className="text-right">{t("insights.leaderboard.metrics.total_words")}</span>
+ </div>
+ {PREVIEW_ROWS.map((width, index) => (
+ <div
+ key={width}
+ className="grid grid-cols-[3rem_1fr_6rem] items-center gap-3 border-t border-border/30 py-3"
+ >
+ <span className="text-xs tabular-nums text-muted-foreground">{index + 1}</span>
+ <div className="flex items-center gap-2.5">
+ <div className="size-7 rounded-full bg-muted" />
+ <div className="h-3 rounded bg-foreground/20" style={{ width: `${width}px` }} />
+ </div>
+ <div className="ml-auto h-3 w-12 rounded bg-foreground/25" />
+ </div>
+ ))}
+ </div>
+ </div>
+
+ <div className="absolute inset-0 flex items-center justify-center bg-gradient-to-b from-background/20 via-background/60 to-background/90 p-6 backdrop-blur-[2px]">
+ <div className="w-full max-w-sm rounded-2xl border border-border/60 bg-background/95 p-6 text-center shadow-xl">
+ <div className="mx-auto flex size-11 items-center justify-center rounded-full bg-primary/10 text-primary">
+ <Icon size={20} />
+ </div>
+ {badge && (
+ <Badge variant="secondary" className="mt-4">
+ {badge}
+ </Badge>
+ )}
+ <h2 className={cn("text-base font-semibold", badge ? "mt-3" : "mt-4")}>{title}</h2>
+ <p className="mt-2 text-xs leading-relaxed text-muted-foreground">{description}</p>
+ {actionLabel && onAction && (
+ <Button className="mt-5 w-full" onClick={onAction} disabled={actionDisabled}>
+ {ActionIcon && <ActionIcon size={14} className={actionIconClassName} />}
+ {actionLabel}
+ </Button>
+ )}
+ {helperText && <p className="mt-3 text-[11px] text-muted-foreground">{helperText}</p>}
+ {children}
+ </div>
+ </div>
+ </section>
+ );
+}
diff --git a/src/components/LeaderboardRequestJoinPreview.tsx b/src/components/LeaderboardRequestJoinPreview.tsx
new file mode 100644
index 000000000..c49915717
--- /dev/null
+++ b/src/components/LeaderboardRequestJoinPreview.tsx
@@ -0,0 +1,45 @@
+import { Check, Loader2, Send } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import LeaderboardPreview from "./LeaderboardPreview";
+
+export default function LeaderboardRequestJoinPreview({
+ className,
+ memberCount,
+ onRequest,
+ pending,
+ requesting,
+ workspaceName,
+}: {
+ className?: string;
+ memberCount: number;
+ onRequest: () => void;
+ pending: boolean;
+ requesting: boolean;
+ workspaceName: string;
+}) {
+ const { t } = useTranslation();
+ return (
+ <LeaderboardPreview
+ actionDisabled={pending || requesting}
+ actionIcon={pending ? Check : requesting ? Loader2 : Send}
+ actionIconClassName={requesting ? "animate-spin" : undefined}
+ actionLabel={
+ pending
+ ? t("insights.leaderboard.requestSent")
+ : requesting
+ ? t("insights.leaderboard.requesting")
+ : t("insights.leaderboard.requestJoinCta")
+ }
+ badge={workspaceName}
+ className={className}
+ dataState="request_join"
+ description={t("insights.leaderboard.requestJoinDescription", {
+ count: memberCount,
+ workspace: workspaceName,
+ })}
+ icon={Send}
+ onAction={onRequest}
+ title={t("insights.leaderboard.requestJoinTitle")}
+ />
+ );
+}
diff --git a/src/components/LeaderboardSection.tsx b/src/components/LeaderboardSection.tsx
new file mode 100644
index 000000000..263d0d2c2
--- /dev/null
+++ b/src/components/LeaderboardSection.tsx
@@ -0,0 +1,1247 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import {
+ ArrowUpDown,
+ Building2,
+ CalendarDays,
+ ChevronLeft,
+ ChevronRight,
+ Clock3,
+ Globe2,
+ Loader2,
+ LocateFixed,
+ LogOut,
+ MoreHorizontal,
+ RefreshCw,
+ Share2,
+ Users,
+ UserPlus,
+} from "lucide-react";
+import { useTranslation } from "react-i18next";
+import {
+ ALL_TIME_METRICS,
+ LEADERBOARD_PAGE_SIZE,
+ LEADERBOARD_REFRESH_INTERVAL_MS,
+ domainToWorkspaceName,
+ missingLeaderboardMembers,
+ memberValue,
+ leaderboardRequestKey,
+ mergeLeaderboardWeekStarts,
+ normalizeLeaderboardSelection,
+ pageCount,
+ pageForRank,
+ resolveLeaderboardScopeKey,
+ resolveLeaderboardSurface,
+ shouldFetchLeaderboardWeekStarts,
+ shouldShowLeaderboardEmptyStrip,
+ shouldShowLeaderboardJumpToMe,
+ selectionForRange,
+ WEEKLY_METRICS,
+ type LeaderboardWeekStartsCacheEntry,
+} from "../helpers/leaderboard";
+import { getValidatedAuthGeneration } from "../lib/authRequestContext";
+import { CloudApiError } from "../services/cloudApi";
+import { LeaderboardService } from "../services/LeaderboardService";
+import { InvitationsService } from "../services/InvitationsService";
+import { WorkspacesService } from "../services/WorkspacesService";
+import { afterWorkspaceJoined } from "../services/membershipActions";
+import { useWorkspaceStore } from "../stores/workspaceStore";
+import type {
+ Leaderboard,
+ LeaderboardAccess,
+ LeaderboardMember,
+ LeaderboardMetric,
+ LeaderboardRange,
+} from "../types/electron";
+import { cn } from "./lib/utils";
+import CreateWorkspaceDialog from "./CreateWorkspaceDialog";
+import InviteTeammateDialog from "./InviteTeammateDialog";
+import MemberAvatar from "./MemberAvatar";
+import LeaderboardRequestJoinPreview from "./LeaderboardRequestJoinPreview";
+import LeaderboardAcceptInvitePreview from "./LeaderboardAcceptInvitePreview";
+import LeaderboardEmptyStrip from "./LeaderboardEmptyStrip";
+import LeaderboardPodium from "./LeaderboardPodium";
+import LeaderboardSetupCard from "./LeaderboardSetupCard";
+import LeaderboardShareDialog from "./LeaderboardShareDialog";
+import LeaderboardSignInPreview from "./LeaderboardSignInPreview";
+import LeaderboardSoloEmptyState from "./LeaderboardSoloEmptyState";
+import LeaderboardWorkspaceNudge from "./LeaderboardWorkspaceNudge";
+import LeaderboardJoinPreview from "./LeaderboardJoinPreview";
+import { Button } from "./ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "./ui/dropdown-menu";
+import { Input } from "./ui/input";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
+import { Tooltip } from "./ui/tooltip";
+import { useToast } from "./ui/useToast";
+
+interface LeaderboardSectionProps {
+ accountId: string | null;
+ authGeneration: number | null;
+ /** The session has settled, so a missing credential will not arrive on its own. */
+ authSettled: boolean;
+ isSignedIn: boolean;
+ /** The account row says joined — what the roster and Leave hang on, not the device toggle. */
+ participating: boolean;
+ cloudAccessAllowed: boolean;
+ canJoin: boolean;
+ participationReady: boolean;
+ participationError: "read" | "write" | null;
+ participationUpdating: boolean;
+ /** A leave this device still owes the account; the Join surface says so. */
+ participationLeavePending: boolean;
+ /** Removes the account from every leaderboard without changing this device's Sync setting. */
+ onLeave: () => Promise<boolean>;
+ onJoin: () => Promise<boolean>;
+ onRefreshParticipation: () => void;
+ onSignIn: () => void;
+ onSsoSignIn: () => void;
+ ssoActionDisabled: boolean;
+ ssoRecoveryError: string | null;
+ ssoStarting: boolean;
+}
+
+const ERROR_CARD_CHROME = "mt-6 rounded-2xl border border-border/50 bg-card/70 dark:border-white/8";
+
+function LeaderboardRetryCard({
+ actionLabel,
+ actionDisabled = false,
+ className,
+ message,
+ onRetry,
+}: {
+ actionLabel?: string;
+ actionDisabled?: boolean;
+ className?: string;
+ message: string;
+ onRetry: () => void;
+}) {
+ const { t } = useTranslation();
+ return (
+ <div
+ className={cn(
+ "flex min-h-48 flex-col items-center justify-center gap-3 px-5 py-10 text-center",
+ className
+ )}
+ >
+ <p className="text-sm font-medium">{message}</p>
+ <Button variant="outline" size="sm" onClick={onRetry} disabled={actionDisabled}>
+ {actionLabel ?? t("insights.leaderboard.retry")}
+ </Button>
+ </div>
+ );
+}
+
+function scrollToRank(rank: number) {
+ requestAnimationFrame(() =>
+ document.getElementById(`leaderboard-rank-${rank}`)?.scrollIntoView({
+ behavior: "smooth",
+ block: "center",
+ })
+ );
+}
+
+export default function LeaderboardSection({
+ accountId,
+ authGeneration,
+ authSettled,
+ isSignedIn,
+ participating,
+ cloudAccessAllowed,
+ canJoin,
+ participationReady,
+ participationError,
+ participationUpdating,
+ participationLeavePending,
+ onJoin,
+ onLeave,
+ onRefreshParticipation,
+ onSignIn,
+ onSsoSignIn,
+ ssoActionDisabled,
+ ssoRecoveryError,
+ ssoStarting,
+}: LeaderboardSectionProps) {
+ const { t, i18n } = useTranslation();
+ const { toast } = useToast();
+ const loaded = useWorkspaceStore((state) => state.loaded);
+ const refresh = useWorkspaceStore((state) => state.refresh);
+ const [access, setAccess] = useState<LeaderboardAccess | null>(null);
+ const [accessLoading, setAccessLoading] = useState(true);
+ const [accessError, setAccessError] = useState<"auth" | "generic" | null>(null);
+ const [scopeKey, setScopeKey] = useState<string | null>(null);
+ const [metric, setMetric] = useState<LeaderboardMetric>("total_words");
+ const [range, setRange] = useState<LeaderboardRange>("week");
+ const [weekStart, setWeekStart] = useState<string | null>(null);
+ const [leaderboard, setLeaderboard] = useState<Leaderboard | null>(null);
+ const [loadedRequestKey, setLoadedRequestKey] = useState<string | null>(null);
+ const [loading, setLoading] = useState(false);
+ const [failure, setFailure] = useState<{
+ kind: "auth" | "generic" | "policy" | "sso";
+ requestKey: string;
+ } | null>(null);
+ const [requestingJoin, setRequestingJoin] = useState(false);
+ const [joiningInvitation, setJoiningInvitation] = useState(false);
+ const [pendingInvites, setPendingInvites] = useState<string[]>([]);
+ const [pendingInviteRevision, setPendingInviteRevision] = useState(0);
+ const [createWorkspaceOpen, setCreateWorkspaceOpen] = useState(false);
+ const [inviteWorkspace, setInviteWorkspace] = useState<{ id: string; name: string } | null>(null);
+ const [page, setPage] = useState(0);
+ const [editingRank, setEditingRank] = useState(false);
+ const [rankInput, setRankInput] = useState("");
+ const [shareOpen, setShareOpen] = useState(false);
+ const pendingScrollRankRef = useRef<number | null>(null);
+ const accessRequestIdRef = useRef(0);
+ const lastLoadedAtRef = useRef(0);
+ const requestIdRef = useRef(0);
+ const participationRecoveryAttemptedRef = useRef(false);
+ const skipAutomaticLoadRef = useRef<{
+ authGeneration: number | null;
+ requestKey: string;
+ } | null>(null);
+ const weekStartsCacheRef = useRef(new Map<string, LeaderboardWeekStartsCacheEntry>());
+ const scopes = useMemo(() => access?.scopes ?? [], [access]);
+ const selectedScope = scopes.find((scope) => scope.key === scopeKey);
+ const selectedRequestKey = leaderboardRequestKey(
+ selectedScope?.key ?? null,
+ metric,
+ range,
+ weekStart,
+ page
+ );
+ // A page turn, metric change or week change asks the same board a different
+ // question, so the answer already on screen stays there until the next one
+ // arrives — blanking it would take the board, the period picker, Share and
+ // the pagination control the user just clicked with it. A different scope is
+ // a different board, so that still clears.
+ const visibleLeaderboard =
+ leaderboard && selectedScope && leaderboard.scope.key === selectedScope.key
+ ? leaderboard
+ : null;
+ const leaderboardStale = visibleLeaderboard != null && loadedRequestKey !== selectedRequestKey;
+ // A board kept from the previous request does not answer the one that just
+ // failed, so failures still take the surface.
+ const noFreshLeaderboard = visibleLeaderboard == null || leaderboardStale;
+ const visibleFailure = failure?.requestKey === selectedRequestKey ? failure.kind : null;
+ const boardParticipantCount = visibleLeaderboard?.totalMembers ?? null;
+
+ const loadAccess = useCallback(
+ async (preferredScopeKey?: string) => {
+ const requestId = ++accessRequestIdRef.current;
+ if (!accountId) {
+ setAccess(null);
+ setAccessLoading(false);
+ setAccessError(null);
+ return;
+ }
+ if (authGeneration == null || getValidatedAuthGeneration() !== authGeneration) {
+ // Wait while the credential is still being established. Once the
+ // session has settled without one, it never will: useAuth keeps
+ // presenting a session whose refetch failed, so this would otherwise
+ // be a spinner with no message and no way out.
+ setAccessLoading(!authSettled);
+ setAccessError(authSettled ? "auth" : null);
+ return;
+ }
+ setAccessLoading(true);
+ setAccessError(null);
+ try {
+ const response = await LeaderboardService.getAccess();
+ if (requestId !== accessRequestIdRef.current) return;
+ setAccess(response);
+ setScopeKey((current) =>
+ resolveLeaderboardScopeKey(response.scopes, current, preferredScopeKey)
+ );
+ } catch (loadError) {
+ if (requestId !== accessRequestIdRef.current) return;
+ console.error("Loading leaderboard access failed:", loadError);
+ const requiresAccount =
+ loadError instanceof CloudApiError &&
+ (loadError.code === "ACCOUNT_REQUIRED" || loadError.status === 401);
+ setAccessError(requiresAccount ? "auth" : "generic");
+ } finally {
+ if (requestId === accessRequestIdRef.current) setAccessLoading(false);
+ }
+ },
+ [accountId, authGeneration, authSettled]
+ );
+
+ useEffect(() => {
+ const canListInvites =
+ selectedScope?.kind === "workspace" &&
+ selectedScope.state === "invite" &&
+ (selectedScope.role === "owner" || selectedScope.role === "admin");
+ if (!canListInvites) {
+ setPendingInvites([]);
+ return;
+ }
+
+ let cancelled = false;
+ InvitationsService.list(selectedScope.id)
+ .then((invitations) => {
+ if (cancelled) return;
+ const now = Date.now();
+ setPendingInvites(
+ invitations
+ .filter(
+ (invitation) =>
+ !invitation.accepted_at &&
+ !invitation.revoked_at &&
+ new Date(invitation.expires_at).getTime() > now
+ )
+ .map((invitation) => invitation.email)
+ );
+ })
+ .catch(() => {
+ if (!cancelled) setPendingInvites([]);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [pendingInviteRevision, selectedScope]);
+
+ useEffect(() => {
+ if (isSignedIn && !loaded) void refresh();
+ }, [isSignedIn, loaded, refresh]);
+
+ useEffect(() => {
+ void loadAccess();
+ }, [loadAccess]);
+
+ useEffect(() => {
+ requestIdRef.current += 1;
+ participationRecoveryAttemptedRef.current = false;
+ skipAutomaticLoadRef.current = null;
+ setLeaderboard((current) => (current?.scope.key === scopeKey ? current : null));
+ setWeekStart(null);
+ setPage(0);
+ }, [scopeKey]);
+
+ useEffect(() => {
+ if (!participating) {
+ requestIdRef.current += 1;
+ participationRecoveryAttemptedRef.current = false;
+ }
+ }, [participating]);
+
+ useEffect(() => {
+ participationRecoveryAttemptedRef.current = false;
+ skipAutomaticLoadRef.current = null;
+ }, [authGeneration]);
+
+ useEffect(() => {
+ if (cloudAccessAllowed) return;
+ requestIdRef.current += 1;
+ setLeaderboard(null);
+ setLoadedRequestKey(null);
+ }, [cloudAccessAllowed]);
+
+ const load = useCallback(async () => {
+ if (
+ !cloudAccessAllowed ||
+ !selectedScope ||
+ selectedScope.state !== "ready" ||
+ !participating ||
+ !participationReady
+ )
+ return;
+ const requestId = ++requestIdRef.current;
+ const cachedWeekStarts = weekStartsCacheRef.current.get(selectedScope.key);
+ const includeWeekStarts = shouldFetchLeaderboardWeekStarts(cachedWeekStarts);
+ setLoading(true);
+ setFailure(null);
+ try {
+ const response = await LeaderboardService.getLeaderboard(selectedScope, {
+ metric,
+ range,
+ weekStart,
+ includeWeekStarts,
+ page,
+ });
+ if (requestId !== requestIdRef.current) return;
+ const nextLeaderboard = includeWeekStarts
+ ? response
+ : {
+ ...response,
+ availableWeekStarts: mergeLeaderboardWeekStarts(
+ response.availableWeekStarts,
+ cachedWeekStarts?.values ?? []
+ ),
+ };
+ if (includeWeekStarts) {
+ weekStartsCacheRef.current.set(selectedScope.key, {
+ values: response.availableWeekStarts,
+ expiresAt: Date.now() + Math.max(60_000, response.refreshAfterSeconds * 1000),
+ });
+ }
+ participationRecoveryAttemptedRef.current = false;
+ const responseRequestKey = leaderboardRequestKey(
+ selectedScope.key,
+ metric,
+ range,
+ weekStart,
+ response.page
+ );
+ setLeaderboard(nextLeaderboard);
+ setLoadedRequestKey(responseRequestKey);
+ if (response.page !== page) {
+ skipAutomaticLoadRef.current = { authGeneration, requestKey: responseRequestKey };
+ setPage(response.page);
+ }
+ lastLoadedAtRef.current = Date.now();
+ } catch (loadError) {
+ if (requestId !== requestIdRef.current) return;
+ console.error("Loading leaderboard failed:", loadError);
+ // A 403 names the gate that moved under us, and retrying the same call
+ // can never clear it. Re-read exactly that gate so the surface settles on
+ // the card that matches reality instead of a dead "Try again".
+ const code = loadError instanceof CloudApiError ? loadError.code : undefined;
+ if (code === "SSO_REQUIRED") {
+ setLeaderboard(null);
+ setLoadedRequestKey(null);
+ setFailure({ kind: "sso", requestKey: selectedRequestKey });
+ return;
+ }
+ if (code === "LEADERBOARD_PARTICIPATION_REQUIRED") {
+ setLeaderboard(null);
+ setLoadedRequestKey(null);
+ if (participationRecoveryAttemptedRef.current) {
+ setFailure({ kind: "generic", requestKey: selectedRequestKey });
+ return;
+ }
+ participationRecoveryAttemptedRef.current = true;
+ onRefreshParticipation();
+ return;
+ }
+ if (code === "LEADERBOARD_DOMAIN_REQUIRED") {
+ setLeaderboard(null);
+ void loadAccess();
+ return;
+ }
+ if (code === "POLICY_CLOUD_BACKUP_BLOCKED" || code === "POLICY_UNRESOLVABLE") {
+ setLeaderboard(null);
+ setLoadedRequestKey(null);
+ setFailure({ kind: "policy", requestKey: selectedRequestKey });
+ return;
+ }
+ if (
+ code === "ACCOUNT_REQUIRED" ||
+ code === "AUTH_EXPIRED" ||
+ (loadError instanceof CloudApiError && loadError.status === 401)
+ ) {
+ setLeaderboard(null);
+ setLoadedRequestKey(null);
+ setFailure({ kind: "auth", requestKey: selectedRequestKey });
+ return;
+ }
+ if (
+ selectedScope.kind === "workspace" &&
+ loadError instanceof CloudApiError &&
+ loadError.status === 404
+ ) {
+ setLeaderboard(null);
+ setAccess(null);
+ void loadAccess();
+ return;
+ }
+ setFailure({ kind: "generic", requestKey: selectedRequestKey });
+ } finally {
+ if (requestId === requestIdRef.current) setLoading(false);
+ }
+ }, [
+ authGeneration,
+ cloudAccessAllowed,
+ loadAccess,
+ metric,
+ onRefreshParticipation,
+ page,
+ participating,
+ participationReady,
+ range,
+ selectedScope,
+ selectedRequestKey,
+ weekStart,
+ ]);
+
+ useEffect(() => {
+ if (authGeneration == null) return;
+ const skippedLoad = skipAutomaticLoadRef.current;
+ skipAutomaticLoadRef.current = null;
+ if (
+ skippedLoad?.authGeneration === authGeneration &&
+ skippedLoad.requestKey === selectedRequestKey
+ )
+ return;
+ void load();
+ }, [authGeneration, load, selectedRequestKey]);
+
+ // The server owns how big a page is and how long a snapshot stays fresh; the
+ // constants are only what to assume before the first response arrives.
+ const pageSize = leaderboard?.pageSize ?? LEADERBOARD_PAGE_SIZE;
+ const refreshIntervalMs = leaderboard
+ ? Math.max(60_000, leaderboard.refreshAfterSeconds * 1000)
+ : LEADERBOARD_REFRESH_INTERVAL_MS;
+
+ useEffect(() => {
+ if (
+ !cloudAccessAllowed ||
+ !selectedScope ||
+ selectedScope.state !== "ready" ||
+ !participating ||
+ !participationReady
+ )
+ return;
+ const refreshIfStale = () => {
+ if (
+ document.visibilityState === "visible" &&
+ Date.now() - lastLoadedAtRef.current >= refreshIntervalMs
+ ) {
+ void load();
+ }
+ };
+ const interval = window.setInterval(refreshIfStale, refreshIntervalMs);
+ window.addEventListener("focus", refreshIfStale);
+ document.addEventListener("visibilitychange", refreshIfStale);
+ return () => {
+ window.clearInterval(interval);
+ window.removeEventListener("focus", refreshIfStale);
+ document.removeEventListener("visibilitychange", refreshIfStale);
+ };
+ }, [
+ cloudAccessAllowed,
+ load,
+ participating,
+ participationReady,
+ refreshIntervalMs,
+ selectedScope,
+ ]);
+
+ const pages = pageCount(leaderboard?.totalMembers ?? 0, pageSize);
+ useEffect(() => setPage((current) => Math.min(current, pages - 1)), [pages]);
+
+ const visibleMembers = useMemo(() => visibleLeaderboard?.members ?? [], [visibleLeaderboard]);
+ const isSoloScope = selectedScope?.state === "invite";
+ const showJumpToMe = shouldShowLeaderboardJumpToMe(visibleLeaderboard?.totalMembers ?? 0);
+
+ useEffect(() => {
+ const rank = pendingScrollRankRef.current;
+ if (rank == null || !visibleMembers.some((member) => member.rank === rank)) return;
+ pendingScrollRankRef.current = null;
+ scrollToRank(rank);
+ }, [visibleMembers]);
+
+ const requestJoin = async () => {
+ const target = access?.joinableWorkspace;
+ if (!target || target.requestState === "pending" || requestingJoin) return;
+ setRequestingJoin(true);
+ try {
+ await WorkspacesService.requestJoin(target.id);
+ setAccess((current) =>
+ current?.joinableWorkspace
+ ? {
+ ...current,
+ joinableWorkspace: { ...current.joinableWorkspace, requestState: "pending" },
+ }
+ : current
+ );
+ toast({
+ title: t("workspaces.join.requestedTitle"),
+ description: t("workspaces.join.requestedDescription", { workspace: target.name }),
+ });
+ } catch (requestError) {
+ toast({
+ title: t("workspaces.join.requestErrorTitle"),
+ description:
+ requestError instanceof Error ? requestError.message : t("common.unknownError"),
+ variant: "destructive",
+ });
+ } finally {
+ setRequestingJoin(false);
+ }
+ };
+
+ const acceptInvitation = async () => {
+ const invitation = access?.invitation;
+ if (!invitation || joiningInvitation) return;
+ setJoiningInvitation(true);
+ try {
+ await WorkspacesService.join(invitation.workspaceId);
+ await afterWorkspaceJoined();
+ await loadAccess(`workspace:${invitation.workspaceId}`);
+ toast({
+ title: t("insights.leaderboard.inviteAcceptedTitle"),
+ description: t("insights.leaderboard.inviteAcceptedDescription", {
+ workspace: invitation.workspaceName,
+ }),
+ });
+ } catch (joinError) {
+ toast({
+ title: t("insights.leaderboard.inviteAcceptError"),
+ description: joinError instanceof Error ? joinError.message : t("common.unknownError"),
+ variant: "destructive",
+ });
+ void loadAccess();
+ } finally {
+ setJoiningInvitation(false);
+ }
+ };
+
+ const dialogs = (
+ <>
+ <CreateWorkspaceDialog
+ defaultName={domainToWorkspaceName(access?.domain ?? null)}
+ open={createWorkspaceOpen}
+ onOpenChange={setCreateWorkspaceOpen}
+ onCreated={(workspaceId) => {
+ const created = useWorkspaceStore
+ .getState()
+ .workspaces.find((workspace) => workspace.id === workspaceId);
+ setInviteWorkspace({ id: workspaceId, name: created?.name ?? t("common.unknown") });
+ void loadAccess();
+ }}
+ />
+ {inviteWorkspace && (
+ <InviteTeammateDialog
+ open
+ onOpenChange={(open) => {
+ if (!open) setInviteWorkspace(null);
+ }}
+ workspaceId={inviteWorkspace.id}
+ workspaceName={inviteWorkspace.name}
+ onInvited={() => {
+ setPendingInviteRevision((current) => current + 1);
+ void loadAccess();
+ }}
+ />
+ )}
+ </>
+ );
+
+ const showScopeSelect = scopes.length > 1 || (scopes.length === 1 && !selectedScope);
+ const scopeOptions = scopes.map((scope) => (
+ <SelectItem key={scope.key} value={scope.key}>
+ {scope.name}
+ </SelectItem>
+ ));
+ const scopeSelect = showScopeSelect ? (
+ <Select value={selectedScope?.key} onValueChange={setScopeKey}>
+ <SelectTrigger className="h-8 w-44 rounded-lg text-xs">
+ <SelectValue placeholder={t("insights.leaderboard.chooseBoard")} />
+ </SelectTrigger>
+ <SelectContent>{scopeOptions}</SelectContent>
+ </Select>
+ ) : null;
+ const funnelScopeSelect = scopeSelect ? (
+ <div className="mt-6 flex justify-end">{scopeSelect}</div>
+ ) : null;
+ const funnelCardClassName = funnelScopeSelect ? "mt-4" : "mt-6";
+
+ if (!isSignedIn) return <LeaderboardSignInPreview className="mt-6" onSignIn={onSignIn} />;
+ if (accessLoading && !access) {
+ return (
+ <section className="mt-6 flex min-h-48 items-center justify-center rounded-2xl border border-border/50 bg-card/70 text-muted-foreground dark:border-white/8">
+ <Loader2 size={18} className="animate-spin" />
+ </section>
+ );
+ }
+ if (accessError && !access) {
+ return (
+ <LeaderboardRetryCard
+ className={ERROR_CARD_CHROME}
+ actionLabel={accessError === "auth" ? t("auth.passwordForm.signInLink") : undefined}
+ message={
+ accessError === "auth"
+ ? t("insights.leaderboard.signInDescription")
+ : t("insights.leaderboard.accessError")
+ }
+ onRetry={accessError === "auth" ? onSignIn : () => void loadAccess()}
+ />
+ );
+ }
+ if (!access) return null;
+
+ const surface = resolveLeaderboardSurface({
+ access,
+ selectedScope: selectedScope ?? null,
+ participating,
+ participationReady,
+ participationError,
+ });
+
+ if (surface === "request_join" && access.joinableWorkspace) {
+ return (
+ <>
+ {funnelScopeSelect}
+ <LeaderboardRequestJoinPreview
+ className={funnelCardClassName}
+ memberCount={access.joinableWorkspace.memberCount}
+ workspaceName={access.joinableWorkspace.name}
+ pending={access.joinableWorkspace.requestState === "pending"}
+ requesting={requestingJoin}
+ onRequest={() => void requestJoin()}
+ />
+ </>
+ );
+ }
+ if (surface === "accept_invite" && access.invitation) {
+ return (
+ <>
+ {funnelScopeSelect}
+ <LeaderboardAcceptInvitePreview
+ className={funnelCardClassName}
+ inviterName={access.invitation.inviterName}
+ joining={joiningInvitation}
+ onAccept={() => void acceptInvitation()}
+ workspaceName={access.invitation.workspaceName}
+ />
+ </>
+ );
+ }
+ if (!selectedScope) {
+ return (
+ <>
+ {funnelScopeSelect}
+ <LeaderboardSetupCard
+ className={funnelCardClassName}
+ colleagueCount={access.colleagueCount}
+ domain={access.domain}
+ onCreate={() => setCreateWorkspaceOpen(true)}
+ />
+ {dialogs}
+ </>
+ );
+ }
+
+ if (surface === "participation_error") {
+ return (
+ <LeaderboardRetryCard
+ className={ERROR_CARD_CHROME}
+ message={t("insights.leaderboard.activationError")}
+ onRetry={onRefreshParticipation}
+ />
+ );
+ }
+ if (surface === "participation_loading") {
+ return (
+ <section className="mt-6 flex min-h-48 items-center justify-center rounded-2xl border border-border/50 bg-card/70 text-muted-foreground dark:border-white/8">
+ <Loader2 size={18} className="animate-spin" />
+ </section>
+ );
+ }
+ if (surface === "join") {
+ return (
+ <LeaderboardJoinPreview
+ canJoin={canJoin}
+ error={participationError === "write"}
+ leavePending={participationLeavePending}
+ onJoin={onJoin}
+ scopeName={selectedScope.name}
+ updating={participationUpdating}
+ />
+ );
+ }
+
+ const number = new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 0 });
+ const date = new Intl.DateTimeFormat(i18n.language, { month: "short", day: "numeric" });
+ const formatWeek = (value: string) => {
+ const start = new Date(`${value}T12:00:00`);
+ const end = new Date(start);
+ end.setDate(end.getDate() + 6);
+ return `${date.format(start)} – ${date.format(end)}`;
+ };
+ const activeWeekStart = weekStart ?? visibleLeaderboard?.weekStart;
+ const periodLabel =
+ range === "all"
+ ? t("insights.leaderboard.allTime")
+ : activeWeekStart
+ ? formatWeek(activeWeekStart)
+ : t("insights.leaderboard.thisWeek");
+ // A domain board withholds the address, so a member with no display name has
+ // nothing left to be called.
+ const memberLabel = (member: LeaderboardMember) =>
+ member.name || member.email || t("insights.leaderboard.unnamedMember");
+
+ const formatValue = (member: LeaderboardMember) => {
+ const value = memberValue(member, metric);
+ if (value == null) return "—";
+ if (metric === "words_per_minute") {
+ return t("insights.leaderboard.wpmValue", { count: value });
+ }
+ if (metric === "current_daily_streak") {
+ return t("insights.leaderboard.dayValue", { count: value });
+ }
+ return number.format(value);
+ };
+ const jumpToRank = (rank: number) => {
+ if (!visibleLeaderboard?.totalMembers) return;
+ const resolvedRank = Math.max(
+ 1,
+ Math.min(visibleLeaderboard.totalMembers, Math.trunc(rank) || 1)
+ );
+ const targetPage = pageForRank(resolvedRank, visibleLeaderboard.totalMembers, pageSize);
+ // Staying on the page renders nothing new, so the row is already there and
+ // the effect that scrolls after a page load never runs.
+ if (targetPage === page) {
+ scrollToRank(resolvedRank);
+ return;
+ }
+ pendingScrollRankRef.current = resolvedRank;
+ setPage(targetPage);
+ };
+ const domainNeedsWorkspace =
+ selectedScope.kind === "domain" && !scopes.some((scope) => scope.kind === "workspace");
+ const inviteableWorkspace =
+ selectedScope.kind === "workspace" &&
+ (selectedScope.role === "owner" || selectedScope.role === "admin")
+ ? selectedScope
+ : selectedScope.kind === "domain"
+ ? scopes.find(
+ (scope) =>
+ scope.kind === "workspace" && (scope.role === "owner" || scope.role === "admin")
+ )
+ : undefined;
+ const canGrowLeaderboard = domainNeedsWorkspace || Boolean(inviteableWorkspace);
+ const openLeaderboardGrowthAction = () => {
+ if (domainNeedsWorkspace) {
+ setCreateWorkspaceOpen(true);
+ return;
+ }
+ if (inviteableWorkspace) {
+ setInviteWorkspace({ id: inviteableWorkspace.id, name: inviteableWorkspace.name });
+ }
+ };
+ const leaveLeaderboards = () => {
+ void onLeave().then((left) => {
+ if (!left) toast({ title: t("insights.leaderboard.leavePending") });
+ });
+ };
+ const workspaceNudge =
+ selectedScope.state === "ready" && access.state === "accept_invite" && access.invitation ? (
+ <LeaderboardWorkspaceNudge
+ kind="accept_invite"
+ loading={joiningInvitation}
+ onAction={() => void acceptInvitation()}
+ pending={false}
+ workspaceName={access.invitation.workspaceName}
+ />
+ ) : selectedScope.state === "ready" &&
+ access.state === "request_join" &&
+ access.joinableWorkspace ? (
+ <LeaderboardWorkspaceNudge
+ kind="request_join"
+ loading={requestingJoin}
+ onAction={() => void requestJoin()}
+ pending={access.joinableWorkspace.requestState === "pending"}
+ workspaceName={access.joinableWorkspace.name}
+ />
+ ) : null;
+
+ return (
+ <section
+ data-leaderboard-state="board"
+ className="mt-6 overflow-hidden rounded-2xl border border-border/50 bg-card/70 dark:border-white/8"
+ >
+ <div className="flex flex-wrap items-center justify-between gap-4 border-b border-border/40 px-5 py-4">
+ <div className="flex min-w-0 items-center gap-3">
+ <div className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-primary/8 text-primary">
+ {selectedScope.kind === "workspace" ? <Building2 size={16} /> : <Globe2 size={16} />}
+ </div>
+ <div className="min-w-0">
+ {showScopeSelect ? (
+ <Select value={selectedScope.key} onValueChange={setScopeKey}>
+ <SelectTrigger
+ className="h-auto w-auto max-w-full gap-1 rounded-md border-0 bg-transparent p-0 text-sm font-semibold shadow-none hover:bg-transparent focus-visible:ring-2 focus-visible:ring-ring dark:border-0"
+ aria-label={t("insights.leaderboard.chooseBoard")}
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>{scopeOptions}</SelectContent>
+ </Select>
+ ) : (
+ <h2 className="truncate text-sm font-semibold">{selectedScope.name}</h2>
+ )}
+ <div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-[11px] text-muted-foreground">
+ {boardParticipantCount != null && (
+ <>
+ <span className="flex items-center gap-1">
+ <Users size={11} />
+ {t("workspaces.join.memberCount", { count: boardParticipantCount })}
+ </span>
+ <span
+ aria-hidden="true"
+ className="size-0.5 rounded-full bg-muted-foreground/50"
+ />
+ </>
+ )}
+ <span className="flex items-center gap-1">
+ <Clock3 size={11} />
+ {t("insights.leaderboard.refreshCadence")}
+ </span>
+ </div>
+ </div>
+ </div>
+ <div className="flex items-center gap-2">
+ {visibleLeaderboard && (
+ <Select
+ value={range === "all" ? "all" : activeWeekStart}
+ onValueChange={(value) => {
+ const nextRange: LeaderboardRange = value === "all" ? "all" : "week";
+ const next = selectionForRange(metric, nextRange);
+ setMetric(next.metric);
+ setRange(next.range);
+ setWeekStart(nextRange === "week" ? value : null);
+ setPage(0);
+ }}
+ >
+ <SelectTrigger className="h-8 w-44 rounded-lg border border-border/40 bg-background/30 px-2.5 text-xs font-medium shadow-none hover:bg-muted/40">
+ <CalendarDays size={13} className="text-muted-foreground" />
+ <SelectValue>
+ {range === "all"
+ ? t("insights.leaderboard.allTime")
+ : activeWeekStart
+ ? formatWeek(activeWeekStart)
+ : t("insights.leaderboard.thisWeek")}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">{t("insights.leaderboard.allTime")}</SelectItem>
+ {visibleLeaderboard.availableWeekStarts.map((value, index) => (
+ <SelectItem key={value} value={value}>
+ {index === 0
+ ? `${t("insights.leaderboard.thisWeek")} · ${formatWeek(value)}`
+ : formatWeek(value)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-8 text-muted-foreground"
+ aria-label={t("insights.leaderboard.moreActions")}
+ >
+ <MoreHorizontal size={15} />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="min-w-40">
+ {!isSoloScope && canGrowLeaderboard && (
+ <DropdownMenuItem className="gap-2 text-xs" onSelect={openLeaderboardGrowthAction}>
+ {domainNeedsWorkspace ? <Building2 size={13} /> : <UserPlus size={13} />}
+ {t(
+ domainNeedsWorkspace
+ ? "settingsPage.workspace.empty.create"
+ : "insights.leaderboard.inviteCta"
+ )}
+ </DropdownMenuItem>
+ )}
+ {visibleLeaderboard && (
+ <DropdownMenuItem className="gap-2 text-xs" onSelect={() => setShareOpen(true)}>
+ <Share2 size={13} />
+ {t("insights.leaderboard.share")}
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuItem
+ className="gap-2 text-xs"
+ disabled={loading || !cloudAccessAllowed}
+ onSelect={() => void load()}
+ >
+ <RefreshCw size={13} className={loading ? "animate-spin" : undefined} />
+ {t("insights.leaderboard.refresh")}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ {/* Participation remains undoable without changing this device's Sync setting. */}
+ <DropdownMenuItem
+ disabled={participationUpdating}
+ className="gap-2 text-xs text-destructive focus:bg-destructive/10 focus:text-destructive"
+ onSelect={leaveLeaderboards}
+ >
+ <LogOut size={13} />
+ {t("insights.leaderboard.leave")}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </div>
+
+ {workspaceNudge}
+
+ {surface === "board" && !cloudAccessAllowed ? (
+ <div className="flex min-h-48 items-center justify-center px-5 py-10 text-center">
+ <p className="text-sm font-medium">{t("insights.leaderboard.joinPolicyBlocked")}</p>
+ </div>
+ ) : isSoloScope ? (
+ <LeaderboardSoloEmptyState
+ scopeKind={selectedScope.kind}
+ scopeName={selectedScope.name}
+ onInvite={openLeaderboardGrowthAction}
+ pendingInvites={pendingInvites}
+ />
+ ) : visibleFailure === "policy" && noFreshLeaderboard ? (
+ <div className="flex min-h-48 items-center justify-center px-5 py-10 text-center">
+ <p className="text-sm font-medium">{t("insights.leaderboard.joinPolicyBlocked")}</p>
+ </div>
+ ) : visibleFailure && noFreshLeaderboard ? (
+ <LeaderboardRetryCard
+ actionDisabled={visibleFailure === "sso" && ssoActionDisabled}
+ actionLabel={
+ visibleFailure === "sso"
+ ? t(ssoStarting ? "auth.social.completeInBrowser" : "auth.sso.continueWithSSO")
+ : visibleFailure === "auth"
+ ? t("auth.passwordForm.signInLink")
+ : undefined
+ }
+ message={
+ visibleFailure === "sso"
+ ? (ssoRecoveryError ?? t("auth.sso.companySignInTitle"))
+ : visibleFailure === "auth"
+ ? t("insights.leaderboard.signInDescription")
+ : t("insights.leaderboard.error")
+ }
+ onRetry={
+ visibleFailure === "sso"
+ ? onSsoSignIn
+ : visibleFailure === "auth"
+ ? onSignIn
+ : () => void load()
+ }
+ />
+ ) : !visibleLeaderboard ? (
+ <div className="flex min-h-48 items-center justify-center text-muted-foreground">
+ <Loader2 size={18} className="animate-spin" />
+ </div>
+ ) : (
+ <div
+ aria-busy={leaderboardStale}
+ className={cn(
+ "motion-safe:transition-opacity motion-safe:duration-150",
+ leaderboardStale && "opacity-60"
+ )}
+ >
+ {shouldShowLeaderboardEmptyStrip(
+ selectedScope.memberCount,
+ visibleLeaderboard.totalMembers
+ ) && (
+ <LeaderboardEmptyStrip
+ missingCount={missingLeaderboardMembers(
+ selectedScope.memberCount,
+ visibleLeaderboard.totalMembers
+ )}
+ />
+ )}
+ <LeaderboardPodium
+ members={visibleLeaderboard.leaders}
+ formatValue={formatValue}
+ memberLabel={memberLabel}
+ metricLabel={t(`insights.leaderboard.metrics.${metric}`)}
+ periodLabel={periodLabel}
+ title={t("insights.leaderboard.topPerformers")}
+ />
+
+ <div className="overflow-x-auto">
+ <table className="w-full min-w-[560px] text-sm">
+ <thead className="bg-muted/10">
+ <tr className="border-y border-border/40 text-left text-[11px] uppercase tracking-wide text-muted-foreground">
+ <th scope="col" className="w-16 px-5 py-2.5 font-medium">
+ {t("insights.leaderboard.rank")}
+ </th>
+ <th scope="col" className="px-3 py-2.5 font-medium">
+ {t("insights.leaderboard.member")}
+ </th>
+ <th scope="col" className="w-56 px-5 py-2 text-right font-medium">
+ <Select
+ value={metric}
+ onValueChange={(value: LeaderboardMetric) => {
+ const next = normalizeLeaderboardSelection(value, range);
+ setMetric(next.metric);
+ setRange(next.range);
+ setWeekStart(next.range === "week" ? weekStart : null);
+ setPage(0);
+ }}
+ >
+ <SelectTrigger className="ml-auto h-8 w-48 rounded-lg border border-border/40 bg-background/30 px-2.5 text-xs font-medium normal-case tracking-normal shadow-none hover:bg-muted/40">
+ <ArrowUpDown size={12} className="text-muted-foreground" />
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {(range === "week" ? WEEKLY_METRICS : ALL_TIME_METRICS).map((value) => (
+ <SelectItem key={value} value={value}>
+ {t(`insights.leaderboard.metrics.${value}`)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {visibleMembers.map((member) => {
+ const isViewer = member.userId === visibleLeaderboard.viewerUserId;
+ return (
+ <tr
+ id={`leaderboard-rank-${member.rank}`}
+ key={member.userId}
+ className={cn(
+ "border-b border-border/30 transition-colors last:border-0 hover:bg-muted/20",
+ isViewer && "bg-primary/5 hover:bg-primary/7"
+ )}
+ >
+ <td className="px-5 py-3 tabular-nums">
+ <span
+ className={cn(
+ "inline-flex size-6 items-center justify-center rounded-md text-xs font-medium text-muted-foreground",
+ member.rank === 1 &&
+ "bg-amber-400/12 font-semibold text-amber-600 dark:text-amber-400",
+ member.rank === 2 && "bg-foreground/6 text-foreground/70",
+ member.rank === 3 &&
+ "bg-orange-400/10 text-orange-600 dark:text-orange-400"
+ )}
+ >
+ {member.rank}
+ </span>
+ </td>
+ <td className="px-3 py-3">
+ <div className="flex min-w-0 items-center gap-2.5">
+ <MemberAvatar
+ name={member.name}
+ email={member.email}
+ image={member.image}
+ size="sm"
+ />
+ <div className="min-w-0">
+ <p className="truncate font-medium">
+ {memberLabel(member)}
+ {isViewer && (
+ <span className="ml-1 text-xs font-normal text-primary">
+ {t("insights.leaderboard.you")}
+ </span>
+ )}
+ </p>
+ {member.name && member.email && (
+ <p className="truncate text-[11px] text-muted-foreground">
+ {member.email}
+ </p>
+ )}
+ </div>
+ </div>
+ </td>
+ <td className="px-5 py-3 text-right font-semibold tabular-nums">
+ {formatValue(member)}
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+
+ {(showJumpToMe || visibleLeaderboard.totalMembers > pageSize) && (
+ <div className="flex flex-wrap items-center justify-between gap-3 border-t border-border/40 bg-muted/10 px-5 py-3">
+ {showJumpToMe && (
+ <Tooltip
+ content={
+ visibleLeaderboard.viewerRank !== null
+ ? t("insights.leaderboard.jumpToMe")
+ : t("insights.leaderboard.jumpUnavailable")
+ }
+ >
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={visibleLeaderboard.viewerRank === null}
+ onClick={() =>
+ visibleLeaderboard.viewerRank !== null &&
+ jumpToRank(visibleLeaderboard.viewerRank)
+ }
+ >
+ <LocateFixed size={14} />
+ {visibleLeaderboard.viewerRank !== null &&
+ `#${visibleLeaderboard.viewerRank} · `}
+ {t("insights.leaderboard.jumpToMe")}
+ </Button>
+ </Tooltip>
+ )}
+
+ {visibleLeaderboard.totalMembers > pageSize && (
+ <div className="flex items-center gap-1.5">
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-8"
+ disabled={page === 0}
+ onClick={() => setPage((current) => Math.max(0, current - 1))}
+ aria-label={t("insights.leaderboard.previous")}
+ >
+ <ChevronLeft size={15} />
+ </Button>
+ {editingRank ? (
+ <form
+ onSubmit={(event) => {
+ event.preventDefault();
+ jumpToRank(Number(rankInput));
+ setEditingRank(false);
+ }}
+ >
+ <Input
+ autoFocus
+ type="number"
+ min={1}
+ max={visibleLeaderboard.totalMembers}
+ value={rankInput}
+ onChange={(event) => setRankInput(event.target.value)}
+ onBlur={() => setEditingRank(false)}
+ className="h-7 w-24 text-center text-xs"
+ aria-label={t("insights.leaderboard.jumpToRank")}
+ />
+ </form>
+ ) : (
+ <button
+ type="button"
+ className="rounded px-2 py-1 text-xs tabular-nums text-muted-foreground hover:bg-muted hover:text-foreground"
+ onClick={() => {
+ setRankInput(String(page * pageSize + 1));
+ setEditingRank(true);
+ }}
+ title={t("insights.leaderboard.jumpToRank")}
+ >
+ {page * pageSize + 1}–
+ {Math.min((page + 1) * pageSize, visibleLeaderboard.totalMembers)} /{" "}
+ {visibleLeaderboard.totalMembers}
+ </button>
+ )}
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-8"
+ disabled={page >= pages - 1}
+ onClick={() => setPage((current) => Math.min(pages - 1, current + 1))}
+ aria-label={t("insights.leaderboard.next")}
+ >
+ <ChevronRight size={15} />
+ </Button>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ )}
+
+ {visibleLeaderboard && (
+ <LeaderboardShareDialog
+ leaderboard={visibleLeaderboard}
+ metric={metric}
+ periodLabel={periodLabel}
+ open={shareOpen}
+ onOpenChange={setShareOpen}
+ />
+ )}
+ {dialogs}
+ </section>
+ );
+}
diff --git a/src/components/LeaderboardSetupCard.tsx b/src/components/LeaderboardSetupCard.tsx
new file mode 100644
index 000000000..8cb7911dd
--- /dev/null
+++ b/src/components/LeaderboardSetupCard.tsx
@@ -0,0 +1,42 @@
+import { UserPlus, Users } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { cn } from "./lib/utils";
+import { Button } from "./ui/button";
+
+export default function LeaderboardSetupCard({
+ className,
+ colleagueCount,
+ domain,
+ onCreate,
+}: {
+ className?: string;
+ colleagueCount: number;
+ domain: string | null;
+ onCreate: () => void;
+}) {
+ const { t } = useTranslation();
+
+ return (
+ <section
+ data-leaderboard-state="create"
+ className={cn(
+ "flex min-h-64 flex-col items-center justify-center rounded-2xl border border-border/50 bg-card/70 px-6 py-10 text-center dark:border-white/8",
+ className
+ )}
+ >
+ <div className="flex size-11 items-center justify-center rounded-full bg-primary/10 text-primary">
+ <Users size={20} />
+ </div>
+ <h2 className="mt-4 text-base font-semibold">{t("insights.leaderboard.setupTitle")}</h2>
+ <p className="mt-2 max-w-md text-xs leading-relaxed text-muted-foreground">
+ {domain && colleagueCount > 0
+ ? t("insights.leaderboard.setupDomainDescription", { count: colleagueCount, domain })
+ : t("insights.leaderboard.setupDescription")}
+ </p>
+ <Button className="mt-5" onClick={onCreate}>
+ <UserPlus size={14} />
+ {t("insights.leaderboard.setupCta")}
+ </Button>
+ </section>
+ );
+}
diff --git a/src/components/LeaderboardShareDialog.tsx b/src/components/LeaderboardShareDialog.tsx
new file mode 100644
index 000000000..a642a5e67
--- /dev/null
+++ b/src/components/LeaderboardShareDialog.tsx
@@ -0,0 +1,214 @@
+import { useCallback, useState } from "react";
+import { Check, Download, Loader2, Share2 } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import type { Leaderboard, LeaderboardMetric } from "../types/electron";
+import { Button } from "./ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "./ui/dialog";
+
+interface LeaderboardShareDialogProps {
+ leaderboard: Leaderboard;
+ metric: LeaderboardMetric;
+ periodLabel: string;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}
+
+function createLeaderboardCard(
+ leaderboard: Leaderboard,
+ cardTitle: string,
+ metricLabel: string,
+ periodLabel: string,
+ locale: string
+): string {
+ const canvas = document.createElement("canvas");
+ canvas.width = 1200;
+ canvas.height = 630;
+ const context = canvas.getContext("2d");
+ if (!context) throw new Error("Canvas is unavailable");
+
+ const gradient = context.createLinearGradient(0, 0, 1200, 630);
+ gradient.addColorStop(0, "#111827");
+ gradient.addColorStop(0.55, "#172554");
+ gradient.addColorStop(1, "#312e81");
+ context.fillStyle = gradient;
+ context.fillRect(0, 0, 1200, 630);
+
+ context.fillStyle = "rgba(255,255,255,0.07)";
+ context.beginPath();
+ context.arc(1080, 40, 260, 0, Math.PI * 2);
+ context.fill();
+ context.beginPath();
+ context.arc(80, 650, 230, 0, Math.PI * 2);
+ context.fill();
+
+ context.fillStyle = "#a5b4fc";
+ context.font = "600 24px Inter, system-ui, sans-serif";
+ context.fillText(cardTitle.toLocaleUpperCase(locale), 72, 74);
+ context.fillStyle = "#ffffff";
+ context.font = "700 104px Inter, system-ui, sans-serif";
+ const rank = leaderboard.viewerRank === null ? "—" : `#${leaderboard.viewerRank}`;
+ context.fillText(rank, 72, 300);
+ context.fillStyle = "#cbd5e1";
+ context.font = "500 30px Inter, system-ui, sans-serif";
+ context.fillText(`/ ${new Intl.NumberFormat(locale).format(leaderboard.totalMembers)}`, 76, 350);
+ context.font = "400 22px Inter, system-ui, sans-serif";
+ context.fillText(`${metricLabel} · ${periodLabel}`, 72, 410);
+ context.fillStyle = "#94a3b8";
+ context.font = "600 18px Inter, system-ui, sans-serif";
+ context.fillText("OpenWhispr", 72, 600);
+ return canvas.toDataURL("image/png");
+}
+
+export default function LeaderboardShareDialog({
+ leaderboard,
+ metric,
+ periodLabel,
+ open,
+ onOpenChange,
+}: LeaderboardShareDialogProps) {
+ const { t, i18n } = useTranslation();
+ const [busyAction, setBusyAction] = useState<string | null>(null);
+ const [status, setStatus] = useState<"copied" | "saved" | "failed" | null>(null);
+
+ const image = useCallback(
+ () =>
+ createLeaderboardCard(
+ leaderboard,
+ `OpenWhispr ${t("insights.leaderboard.title")}`,
+ t(`insights.leaderboard.metrics.${metric}`),
+ periodLabel,
+ i18n.language
+ ),
+ [i18n.language, leaderboard, metric, periodLabel, t]
+ );
+
+ const copyImage = useCallback(async () => {
+ const result = await window.electronAPI.copyLeaderboardImage(image());
+ if (!result.success) throw new Error(result.error || "Copy failed");
+ setStatus("copied");
+ }, [image]);
+
+ const run = useCallback(async (action: string, operation: () => Promise<void>) => {
+ setBusyAction(action);
+ setStatus(null);
+ try {
+ await operation();
+ } catch (error) {
+ console.error("Sharing leaderboard failed:", error);
+ setStatus("failed");
+ } finally {
+ setBusyAction(null);
+ }
+ }, []);
+
+ const shareText = t("insights.leaderboard.shareText");
+ const handleOpenChange = (nextOpen: boolean) => {
+ if (!nextOpen) setStatus(null);
+ onOpenChange(nextOpen);
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={handleOpenChange}>
+ <DialogContent className="sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>{t("insights.leaderboard.shareTitle")}</DialogTitle>
+ <DialogDescription>{t("insights.leaderboard.shareDescription")}</DialogDescription>
+ </DialogHeader>
+
+ <div className="rounded-xl bg-gradient-to-br from-slate-950 via-blue-950 to-indigo-900 p-5 text-white">
+ <p className="text-[10px] font-semibold tracking-[0.18em] text-indigo-200">
+ {`OpenWhispr ${t("insights.leaderboard.title")}`.toLocaleUpperCase(i18n.language)}
+ </p>
+ <p className="mt-1 text-xs text-slate-300">
+ {t(`insights.leaderboard.metrics.${metric}`)} · {periodLabel}
+ </p>
+ <div className="mt-6 rounded-lg bg-white/8 px-4 py-5">
+ <strong className="text-3xl">
+ {leaderboard.viewerRank === null ? "—" : `#${leaderboard.viewerRank}`}
+ </strong>
+ <span className="ml-2 text-sm text-slate-300">
+ / {new Intl.NumberFormat(i18n.language).format(leaderboard.totalMembers)}
+ </span>
+ </div>
+ </div>
+
+ <div className="grid grid-cols-2 gap-2">
+ <Button
+ variant="outline"
+ disabled={busyAction !== null}
+ onClick={() => void run("copy", copyImage)}
+ >
+ {busyAction === "copy" ? <Loader2 className="animate-spin" /> : <Share2 />}
+ {t("insights.leaderboard.copyImage")}
+ </Button>
+ <Button
+ variant="outline"
+ disabled={busyAction !== null}
+ onClick={() =>
+ void run("download", async () => {
+ const result = await window.electronAPI.saveLeaderboardImage(
+ image(),
+ "openwhispr-leaderboard.png"
+ );
+ if (!result.success) throw new Error(result.error || "Save failed");
+ if (!result.canceled) setStatus("saved");
+ })
+ }
+ >
+ {busyAction === "download" ? <Loader2 className="animate-spin" /> : <Download />}
+ {t("insights.leaderboard.download")}
+ </Button>
+ <Button
+ variant="outline"
+ disabled={busyAction !== null}
+ onClick={() =>
+ void run("x", async () => {
+ await copyImage();
+ const opened = await window.electronAPI.openExternal(
+ `https://x.com/intent/post?text=${encodeURIComponent(shareText)}`
+ );
+ if (!opened.success) throw new Error(opened.error || "Opening X failed");
+ })
+ }
+ >
+ {busyAction === "x" ? <Loader2 className="animate-spin" /> : <span>X</span>}
+ {t("insights.leaderboard.shareX")}
+ </Button>
+ <Button
+ variant="outline"
+ disabled={busyAction !== null}
+ onClick={() =>
+ void run("linkedin", async () => {
+ await copyImage();
+ const opened = await window.electronAPI.openExternal(
+ "https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fopenwhispr.com"
+ );
+ if (!opened.success) throw new Error(opened.error || "Opening LinkedIn failed");
+ })
+ }
+ >
+ {busyAction === "linkedin" ? (
+ <Loader2 className="animate-spin" />
+ ) : (
+ <span className="font-bold">in</span>
+ )}
+ {t("insights.leaderboard.shareLinkedIn")}
+ </Button>
+ </div>
+ {status && (
+ <p
+ role="status"
+ className={
+ status === "failed"
+ ? "text-center text-xs text-destructive"
+ : "flex items-center justify-center gap-1 text-xs text-emerald-600"
+ }
+ >
+ {status !== "failed" && <Check size={13} />}
+ {t(`insights.leaderboard.${status}`)}
+ </p>
+ )}
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/src/components/LeaderboardSignInPreview.tsx b/src/components/LeaderboardSignInPreview.tsx
new file mode 100644
index 000000000..c5255a904
--- /dev/null
+++ b/src/components/LeaderboardSignInPreview.tsx
@@ -0,0 +1,25 @@
+import { LogIn } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import LeaderboardPreview from "./LeaderboardPreview";
+
+export default function LeaderboardSignInPreview({
+ className,
+ onSignIn,
+}: {
+ className?: string;
+ onSignIn: () => void;
+}) {
+ const { t } = useTranslation();
+
+ return (
+ <LeaderboardPreview
+ actionIcon={LogIn}
+ actionLabel={t("auth.passwordForm.signInLink")}
+ className={className}
+ description={t("insights.leaderboard.signInDescription")}
+ icon={LogIn}
+ onAction={onSignIn}
+ title={t("insights.leaderboard.signInTitle")}
+ />
+ );
+}
diff --git a/src/components/LeaderboardSoloEmptyState.tsx b/src/components/LeaderboardSoloEmptyState.tsx
new file mode 100644
index 000000000..5ab38b469
--- /dev/null
+++ b/src/components/LeaderboardSoloEmptyState.tsx
@@ -0,0 +1,74 @@
+import { Building2, Clock3, Globe2, UserPlus, UserRound } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { Button } from "./ui/button";
+
+export default function LeaderboardSoloEmptyState({
+ scopeKind,
+ scopeName,
+ onInvite,
+ pendingInvites,
+}: {
+ scopeKind: "workspace" | "domain";
+ scopeName: string;
+ onInvite: () => void;
+ pendingInvites: string[];
+}) {
+ const { t } = useTranslation();
+ const ScopeIcon = scopeKind === "workspace" ? Building2 : Globe2;
+
+ return (
+ <div
+ data-leaderboard-state="invite"
+ className="relative isolate flex min-h-96 items-center justify-center overflow-hidden px-6 py-12 text-center"
+ >
+ <div
+ aria-hidden="true"
+ className="pointer-events-none absolute left-1/2 top-1/2 size-64 -translate-x-1/2 -translate-y-1/2 rounded-full bg-primary/5 blur-3xl"
+ />
+
+ <div className="relative flex max-w-lg flex-col items-center">
+ <div aria-hidden="true" className="flex items-center">
+ <div className="flex size-11 items-center justify-center rounded-full border border-dashed border-border/70 bg-muted/30 text-muted-foreground/45">
+ <UserRound size={18} />
+ </div>
+ <div className="w-9 border-t border-dashed border-border/70" />
+ <div className="flex size-14 items-center justify-center rounded-2xl border border-primary/20 bg-primary/10 text-primary shadow-sm">
+ <UserPlus size={24} />
+ </div>
+ <div className="w-9 border-t border-dashed border-border/70" />
+ <div className="flex size-11 items-center justify-center rounded-full border border-dashed border-border/70 bg-muted/30 text-muted-foreground/45">
+ <UserRound size={18} />
+ </div>
+ </div>
+
+ <div className="mt-6 inline-flex items-center gap-1.5 rounded-full border border-border/50 bg-muted/30 px-3 py-1 text-[11px] font-medium text-muted-foreground">
+ <ScopeIcon size={12} />
+ <span>{scopeName}</span>
+ </div>
+
+ <h3 className="mt-4 text-xl font-semibold tracking-tight">
+ {t("insights.leaderboard.soloTitle")}
+ </h3>
+ <p className="mt-2 max-w-md text-sm leading-relaxed text-muted-foreground">
+ {t("insights.leaderboard.soloDescription", { scope: scopeName })}
+ </p>
+
+ <Button size="lg" className="mt-6" onClick={onInvite}>
+ <UserPlus size={16} />
+ {t("insights.leaderboard.inviteCta")}
+ </Button>
+ <p className="mt-3 text-[11px] text-muted-foreground/75">
+ {t("insights.leaderboard.soloHint")}
+ </p>
+ {pendingInvites.length > 0 && (
+ <div className="mt-4 flex max-w-full items-start gap-2 rounded-lg border border-border/50 bg-muted/25 px-3 py-2 text-left text-[11px] text-muted-foreground">
+ <Clock3 size={13} className="mt-0.5 shrink-0" />
+ <p className="min-w-0 break-words">
+ {t("insights.leaderboard.invitedList", { emails: pendingInvites.join(", ") })}
+ </p>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/LeaderboardView.tsx b/src/components/LeaderboardView.tsx
new file mode 100644
index 000000000..e841e3b1e
--- /dev/null
+++ b/src/components/LeaderboardView.tsx
@@ -0,0 +1,128 @@
+import { useCallback, useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { useAuth } from "../hooks/useAuth";
+import { useLeaderboardParticipation } from "../hooks/useLeaderboardParticipation";
+import type { EnableInsightsSyncOptions } from "../hooks/useInsightsSyncOptIn";
+import { useSettings } from "../hooks/useSettings";
+import { signInWithSSO } from "../lib/auth";
+import { getValidatedAuthGeneration } from "../lib/authRequestContext";
+import { effectiveLocalHistoryEnabled } from "../stores/policyRules";
+import { usePolicyStore } from "../stores/policyStore";
+import LeaderboardSection from "./LeaderboardSection";
+
+interface LeaderboardViewProps {
+ enableInsightsSync: (options?: EnableInsightsSyncOptions) => Promise<boolean>;
+ insightsSyncEnabled: boolean;
+ onSignIn: () => void;
+ syncAllowedByPolicy: boolean;
+}
+
+export default function LeaderboardView({
+ enableInsightsSync,
+ insightsSyncEnabled,
+ onSignIn,
+ syncAllowedByPolicy,
+}: LeaderboardViewProps) {
+ const { t } = useTranslation();
+ const { isLoaded: authSettled, isSignedIn, user } = useAuth();
+ const authGeneration = getValidatedAuthGeneration();
+ const [oauthProtocolRegistered, setOauthProtocolRegistered] = useState<boolean | null>(null);
+ const [ssoStarting, setSsoStarting] = useState(false);
+ const [ssoError, setSsoError] = useState<string | null>(null);
+ const { dataRetentionEnabled: personalDataRetentionEnabled } = useSettings();
+ const {
+ enabled: participationEnabled,
+ error: participationError,
+ join: joinParticipation,
+ leave: leaveParticipation,
+ leavePending: participationLeavePending,
+ ready: participationReady,
+ refresh: refreshParticipation,
+ updating: participationUpdating,
+ } = useLeaderboardParticipation();
+ const dataRetentionEnabled = usePolicyStore((policyState) =>
+ effectiveLocalHistoryEnabled(policyState, personalDataRetentionEnabled)
+ );
+ useEffect(() => {
+ window.electronAPI
+ ?.getOAuthProtocolRegistered?.()
+ .then(setOauthProtocolRegistered)
+ .catch(() => setOauthProtocolRegistered(false));
+ }, []);
+
+ // A successful browser callback rotates the validated credential. That both
+ // releases the launch guard and gives LeaderboardSection a reason to retry
+ // the request that returned SSO_REQUIRED.
+ useEffect(() => {
+ setSsoStarting(false);
+ setSsoError(null);
+ }, [authGeneration]);
+
+ // Browser auth may end without a callback when the user closes or cancels
+ // the flow. Release the launch guard after focus returns so they can retry.
+ useEffect(() => {
+ if (!ssoStarting) return;
+
+ let timeout: ReturnType<typeof setTimeout>;
+ const handleFocus = () => {
+ timeout = setTimeout(() => setSsoStarting(false), 1000);
+ };
+
+ window.addEventListener("focus", handleFocus);
+ return () => {
+ window.removeEventListener("focus", handleFocus);
+ clearTimeout(timeout);
+ };
+ }, [ssoStarting]);
+
+ const startSsoSignIn = useCallback(async () => {
+ const email = user?.email;
+ if (!email) {
+ onSignIn();
+ return;
+ }
+ if (oauthProtocolRegistered !== true || ssoStarting) return;
+ setSsoStarting(true);
+ setSsoError(null);
+ const { error } = await signInWithSSO(email);
+ if (!error) return;
+ console.error("Starting leaderboard SSO sign-in failed:", error);
+ setSsoError(t("auth.sso.failed"));
+ setSsoStarting(false);
+ }, [oauthProtocolRegistered, onSignIn, ssoStarting, t, user?.email]);
+
+ const joinLeaderboard = useCallback(async () => {
+ if (!insightsSyncEnabled && !(await enableInsightsSync({ confirmWhenEmpty: true })))
+ return false;
+ return joinParticipation();
+ }, [enableInsightsSync, insightsSyncEnabled, joinParticipation]);
+
+ return (
+ <>
+ <LeaderboardSection
+ key={user?.id ?? "guest"}
+ accountId={user?.id ?? null}
+ authGeneration={authGeneration}
+ authSettled={authSettled}
+ isSignedIn={isSignedIn}
+ participating={isSignedIn && participationEnabled}
+ cloudAccessAllowed={syncAllowedByPolicy}
+ canJoin={isSignedIn && syncAllowedByPolicy && dataRetentionEnabled}
+ participationReady={participationReady}
+ participationError={participationError}
+ participationUpdating={participationUpdating}
+ participationLeavePending={participationLeavePending}
+ onJoin={joinLeaderboard}
+ onLeave={leaveParticipation}
+ onRefreshParticipation={refreshParticipation}
+ onSignIn={onSignIn}
+ onSsoSignIn={() => void startSsoSignIn()}
+ ssoActionDisabled={ssoStarting || oauthProtocolRegistered !== true}
+ ssoRecoveryError={
+ oauthProtocolRegistered === false ? t("auth.social.protocolUnavailable") : ssoError
+ }
+ ssoStarting={ssoStarting}
+ />
+ </>
+ );
+}
diff --git a/src/components/LeaderboardWorkspaceNudge.tsx b/src/components/LeaderboardWorkspaceNudge.tsx
new file mode 100644
index 000000000..5da6c9c47
--- /dev/null
+++ b/src/components/LeaderboardWorkspaceNudge.tsx
@@ -0,0 +1,55 @@
+import { Building2, Loader2 } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { Button } from "./ui/button";
+
+export default function LeaderboardWorkspaceNudge({
+ kind,
+ loading,
+ onAction,
+ pending,
+ workspaceName,
+}: {
+ kind: "accept_invite" | "request_join";
+ loading: boolean;
+ onAction: () => void;
+ pending: boolean;
+ workspaceName: string;
+}) {
+ const { t } = useTranslation();
+ const acceptingInvitation = kind === "accept_invite";
+ const actionLabel = loading
+ ? t(acceptingInvitation ? "insights.leaderboard.joining" : "insights.leaderboard.requesting")
+ : acceptingInvitation
+ ? t("insights.leaderboard.acceptInviteCta")
+ : t(pending ? "insights.leaderboard.requestSent" : "insights.leaderboard.requestJoinCta");
+
+ return (
+ <div
+ data-leaderboard-state="workspace_nudge"
+ className="flex flex-wrap items-center justify-between gap-3 border-b border-border/40 bg-primary/5 px-5 py-3"
+ >
+ <div className="flex min-w-0 items-center gap-3">
+ <div className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">
+ <Building2 size={15} />
+ </div>
+ <div className="min-w-0">
+ <p className="truncate text-xs font-medium text-foreground">
+ {t(
+ acceptingInvitation
+ ? "insights.leaderboard.acceptInviteTitle"
+ : "insights.leaderboard.requestJoinTitle",
+ { workspace: workspaceName }
+ )}
+ </p>
+ {!acceptingInvitation && (
+ <p className="mt-0.5 truncate text-[11px] text-muted-foreground">{workspaceName}</p>
+ )}
+ </div>
+ </div>
+ <Button variant="outline-flat" size="sm" disabled={loading || pending} onClick={onAction}>
+ {loading && <Loader2 size={14} className="animate-spin" />}
+ {actionLabel}
+ </Button>
+ </div>
+ );
+}
diff --git a/src/components/MemberAvatar.tsx b/src/components/MemberAvatar.tsx
index 97f89ac0d..573bb1451 100644
--- a/src/components/MemberAvatar.tsx
+++ b/src/components/MemberAvatar.tsx
@@ -4,11 +4,13 @@ import { cn } from "./lib/utils";
const SIZES = {
sm: { box: "w-5 h-5", text: "text-[9px]" },
md: { box: "w-7 h-7", text: "text-[10px]" },
+ lg: { box: "w-11 h-11", text: "text-xs" },
} as const;
interface MemberAvatarProps {
name: string | null;
- email: string;
+ // Null wherever the address is withheld, as it is on a domain leaderboard.
+ email: string | null;
image?: string | null;
size?: keyof typeof SIZES;
}
@@ -38,7 +40,7 @@ export default function MemberAvatar({ name, email, image, size = "md" }: Member
"rounded-full bg-primary/10 text-primary font-semibold flex items-center justify-center shrink-0"
)}
>
- {(name || email).slice(0, 2).toUpperCase()}
+ {(name || email || "?").slice(0, 2).toUpperCase()}
</span>
);
}
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index 01a373af9..56072bf14 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -64,6 +64,7 @@ import { Alert, AlertTitle, AlertDescription } from "./ui/alert";
import { useSettings } from "../hooks/useSettings";
import { useDialogs } from "../hooks/useDialogs";
import { useInsightsSyncOptIn } from "../hooks/useInsightsSyncOptIn";
+import { useLeaderboardParticipation } from "../hooks/useLeaderboardParticipation";
import { useWhisper } from "../hooks/useWhisper";
import { usePermissions } from "../hooks/usePermissions";
import { useSystemAudioPermission } from "../hooks/useSystemAudioPermission";
@@ -1253,7 +1254,6 @@ export default function SettingsPage({
cloudBackupEnabled,
setCloudBackupEnabled,
insightsSyncEnabled,
- setInsightsSyncEnabled,
telemetryEnabled,
setTelemetryEnabled,
audioRetentionDays,
@@ -1815,10 +1815,63 @@ export default function SettingsPage({
const { isSignedIn, isLoaded, user, refetch } = useAuth();
const {
canToggleSync: canToggleInsightsSync,
+ disableInsightsSync,
enableInsightsSync,
optInDialog: insightsOptInDialog,
syncAllowedByPolicy: insightsSyncAllowedByPolicy,
} = useInsightsSyncOptIn();
+ const {
+ enabled: leaderboardParticipationEnabled,
+ error: leaderboardParticipationError,
+ join: joinLeaderboard,
+ leave: leaveLeaderboard,
+ leavePending: leaderboardLeavePending,
+ ready: leaderboardParticipationReady,
+ updating: leaderboardParticipationUpdating,
+ } = useLeaderboardParticipation();
+ const [leaderboardPreferencePending, setLeaderboardPreferencePending] = useState(false);
+ const updateLeaderboardParticipation = useCallback(
+ async (enabled: boolean) => {
+ if (!isSignedIn || !leaderboardParticipationReady || leaderboardPreferencePending) return;
+ setLeaderboardPreferencePending(true);
+ try {
+ if (enabled) {
+ if (
+ !effectiveDataRetentionEnabled ||
+ !insightsSyncAllowedByPolicy ||
+ (!insightsSyncEnabled && !(await enableInsightsSync({ confirmWhenEmpty: true })))
+ )
+ return;
+ if (!(await joinLeaderboard())) {
+ toast({
+ title: t("insights.leaderboard.activationError"),
+ variant: "destructive",
+ });
+ }
+ return;
+ }
+
+ if (!(await leaveLeaderboard())) {
+ toast({ title: t("insights.leaderboard.leavePending") });
+ }
+ } finally {
+ setLeaderboardPreferencePending(false);
+ }
+ },
+ [
+ effectiveDataRetentionEnabled,
+ enableInsightsSync,
+ insightsSyncAllowedByPolicy,
+ insightsSyncEnabled,
+ isSignedIn,
+ joinLeaderboard,
+ leaderboardParticipationReady,
+ leaderboardPreferencePending,
+ leaveLeaderboard,
+ t,
+ toast,
+ ]
+ );
// 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";
@@ -4214,9 +4267,44 @@ EOF`,
!canToggleInsightsSync ||
(!effectiveDataRetentionEnabled && !insightsSyncEnabled)
}
- onChange={(enabled) =>
- enabled ? enableInsightsSync() : setInsightsSyncEnabled(false)
+ onChange={(enabled) => {
+ if (enabled) void enableInsightsSync();
+ else disableInsightsSync();
+ }}
+ />
+ </SettingsRow>
+ </SettingsPanelRow>
+ <SettingsPanelRow>
+ <SettingsRow
+ label={t("insights.leaderboard.title")}
+ description={
+ !isSignedIn
+ ? t("settingsPage.privacy.leaderboardRequiresAccount")
+ : leaderboardParticipationError === "read"
+ ? t("insights.leaderboard.activationError")
+ : leaderboardLeavePending
+ ? t("insights.leaderboard.leavePending")
+ : !insightsSyncAllowedByPolicy
+ ? t("common.managedByOrg")
+ : !effectiveDataRetentionEnabled
+ ? t("settingsPage.privacy.leaderboardRequiresHistory")
+ : t("settingsPage.privacy.leaderboardDescription")
+ }
+ >
+ <Toggle
+ checked={isSignedIn && leaderboardParticipationEnabled}
+ disabled={
+ !isSignedIn ||
+ !leaderboardParticipationReady ||
+ leaderboardPreferencePending ||
+ leaderboardParticipationUpdating ||
+ leaderboardParticipationError === "read" ||
+ (!leaderboardParticipationEnabled &&
+ (!effectiveDataRetentionEnabled ||
+ !insightsSyncAllowedByPolicy ||
+ (!insightsSyncEnabled && !canToggleInsightsSync)))
}
+ onChange={(enabled) => void updateLeaderboardParticipation(enabled)}
/>
</SettingsRow>
</SettingsPanelRow>
diff --git a/src/helpers/cloudApiRequest.js b/src/helpers/cloudApiRequest.js
index 464845628..b891defaa 100644
--- a/src/helpers/cloudApiRequest.js
+++ b/src/helpers/cloudApiRequest.js
@@ -98,6 +98,7 @@ function createCloudApiRequestHandler({
const headers = fence
? withPolicyRequestHeaders({ Authorization: fence.authorization }, getAppVersion())
: { "x-openwhispr-version": getAppVersion() };
+ headers["x-openwhispr-source"] = "desktop";
const fetchOptions = {
method,
headers,
diff --git a/src/helpers/database.js b/src/helpers/database.js
index 3bf60ac1e..ebc2f9c4c 100644
--- a/src/helpers/database.js
+++ b/src/helpers/database.js
@@ -1383,10 +1383,21 @@ class DatabaseManager {
}
}
- getPendingAnalyticsEvents(limit = 200) {
+ analyticsAccountId(expectedAccountId) {
+ if (expectedAccountId == null) return this.activeAccountId;
+ if (expectedAccountId !== this.activeAccountId) {
+ throw Object.assign(new Error("Analytics account context changed"), {
+ code: "AUTH_CONTEXT_CHANGED",
+ });
+ }
+ return expectedAccountId;
+ }
+
+ getPendingAnalyticsEvents(limit = 200, expectedAccountId) {
try {
if (!this.db) throw new Error("Database not initialized");
- if (!this.activeAccountId) return [];
+ const accountId = this.analyticsAccountId(expectedAccountId);
+ if (!accountId) return [];
const safeLimit = Math.max(1, Math.min(Number(limit) || 200, 200));
// The projection is the wire shape: AnalyticsService posts these rows
// verbatim, so every column here has to satisfy the batch endpoint's
@@ -1400,17 +1411,18 @@ class DatabaseManager {
WHERE account_id = ? AND sync_status = 'pending' AND deleted_at IS NULL
ORDER BY occurred_at ASC LIMIT ?`
)
- .all(this.activeAccountId, safeLimit);
+ .all(accountId, safeLimit);
} catch (error) {
debugLogger.error("Error reading pending analytics", { error: error.message }, "database");
throw error;
}
}
- markAnalyticsEventsSynced(eventIds) {
+ markAnalyticsEventsSynced(eventIds, expectedAccountId) {
try {
if (!this.db) throw new Error("Database not initialized");
- if (!this.activeAccountId || !Array.isArray(eventIds) || eventIds.length === 0) {
+ const accountId = this.analyticsAccountId(expectedAccountId);
+ if (!accountId || !Array.isArray(eventIds) || eventIds.length === 0) {
return { success: true, updated: 0 };
}
const placeholders = eventIds.map(() => "?").join(", ");
@@ -1420,7 +1432,7 @@ class DatabaseManager {
WHERE account_id = ? AND deleted_at IS NULL
AND event_id IN (${placeholders})`
)
- .run(this.activeAccountId, ...eventIds);
+ .run(accountId, ...eventIds);
return { success: true, updated: result.changes };
} catch (error) {
debugLogger.error("Error marking analytics synced", { error: error.message }, "database");
@@ -1428,10 +1440,11 @@ class DatabaseManager {
}
}
- getPendingAnalyticsDeletes(limit = 200) {
+ getPendingAnalyticsDeletes(limit = 200, expectedAccountId) {
try {
if (!this.db) throw new Error("Database not initialized");
- if (!this.activeAccountId) return [];
+ const accountId = this.analyticsAccountId(expectedAccountId);
+ if (!accountId) return [];
const safeLimit = Math.max(1, Math.min(Number(limit) || 200, 200));
return this.db
.prepare(
@@ -1439,7 +1452,7 @@ class DatabaseManager {
WHERE account_id = ? AND deleted_at IS NOT NULL AND sync_status = 'pending'
ORDER BY occurred_at ASC LIMIT ?`
)
- .all(this.activeAccountId, safeLimit);
+ .all(accountId, safeLimit);
} catch (error) {
debugLogger.error(
"Error reading pending analytics deletes",
@@ -1450,10 +1463,11 @@ class DatabaseManager {
}
}
- hardDeleteAnalyticsEvents(eventIds) {
+ hardDeleteAnalyticsEvents(eventIds, expectedAccountId) {
try {
if (!this.db) throw new Error("Database not initialized");
- if (!this.activeAccountId || !Array.isArray(eventIds) || eventIds.length === 0) {
+ const accountId = this.analyticsAccountId(expectedAccountId);
+ if (!accountId || !Array.isArray(eventIds) || eventIds.length === 0) {
return { success: true, deleted: 0 };
}
const placeholders = eventIds.map(() => "?").join(", ");
@@ -1463,7 +1477,7 @@ class DatabaseManager {
WHERE account_id = ? AND deleted_at IS NOT NULL
AND event_id IN (${placeholders})`
)
- .run(this.activeAccountId, ...eventIds);
+ .run(accountId, ...eventIds);
return { success: true, deleted: result.changes };
} catch (error) {
debugLogger.error(
@@ -1475,22 +1489,24 @@ class DatabaseManager {
}
}
- getPendingAnalyticsClear() {
+ getPendingAnalyticsClear(expectedAccountId) {
if (!this.db) throw new Error("Database not initialized");
- if (!this.activeAccountId) return null;
+ const accountId = this.analyticsAccountId(expectedAccountId);
+ if (!accountId) return null;
return (
this.db
.prepare(
`SELECT cleared_through FROM analytics_clear_requests
WHERE account_id = ? AND synced = 0`
)
- .get(this.activeAccountId) ?? null
+ .get(accountId) ?? null
);
}
- completeAnalyticsClear(clearedThrough) {
+ completeAnalyticsClear(clearedThrough, expectedAccountId) {
if (!this.db) throw new Error("Database not initialized");
- if (!this.activeAccountId || typeof clearedThrough !== "string") {
+ const accountId = this.analyticsAccountId(expectedAccountId);
+ if (!accountId || typeof clearedThrough !== "string") {
return { success: false, deleted: 0 };
}
@@ -1500,14 +1516,14 @@ class DatabaseManager {
`UPDATE analytics_clear_requests SET synced = 1
WHERE account_id = ? AND cleared_through = ? AND synced = 0`
)
- .run(this.activeAccountId, clearedThrough);
+ .run(accountId, clearedThrough);
if (request.changes === 0) return 0;
return this.db
.prepare(
`DELETE FROM analytics_events
WHERE account_id = ? AND occurred_at <= ?`
)
- .run(this.activeAccountId, clearedThrough).changes;
+ .run(accountId, clearedThrough).changes;
});
return { success: true, deleted: complete() };
}
@@ -1529,28 +1545,35 @@ class DatabaseManager {
// user who had been signed in for months had nothing "unclaimed" — the
// consent prompt never opened, and flipping the toggle uploaded their entire
// history in one pass.
- countAnalyticsEventsAwaitingUpload() {
+ countAnalyticsEventsAwaitingUpload(expectedAccountId) {
if (!this.db) throw new Error("Database not initialized");
+ const accountId = this.analyticsAccountId(expectedAccountId);
return this.db
.prepare(
`SELECT COUNT(*) AS count FROM analytics_events
WHERE deleted_at IS NULL AND sync_status <> 'synced'
AND (account_id IS NULL OR account_id = ?)`
)
- .get(this.activeAccountId).count;
+ .get(accountId).count;
}
// Device-local rows stay unattributed until the signed-in user explicitly
// asks for them, so signing in never silently adopts someone else's history.
- claimAnonymousAnalyticsEvents() {
+ claimAnonymousAnalyticsEvents(expectedAccountId) {
try {
if (!this.db) throw new Error("Database not initialized");
- if (!this.activeAccountId) return { success: false, claimed: 0 };
+ const accountId =
+ typeof expectedAccountId === "string" && expectedAccountId.trim().length > 0
+ ? expectedAccountId.trim()
+ : null;
+ if (!accountId || accountId !== this.activeAccountId) {
+ return { success: false, claimed: 0 };
+ }
const result = this.db
.prepare(
"UPDATE analytics_events SET account_id = ? WHERE account_id IS NULL AND deleted_at IS NULL"
)
- .run(this.activeAccountId);
+ .run(accountId);
return { success: true, claimed: result.changes };
} catch (error) {
debugLogger.error("Error claiming analytics events", { error: error.message }, "database");
diff --git a/src/helpers/insightsConsentCoordinator.ts b/src/helpers/insightsConsentCoordinator.ts
new file mode 100644
index 000000000..68eaaa89c
--- /dev/null
+++ b/src/helpers/insightsConsentCoordinator.ts
@@ -0,0 +1,58 @@
+export type InsightsConsentKind = "enable" | "claim";
+
+interface PendingInsightsConsent {
+ key: string;
+ owner: object;
+ promise: Promise<boolean>;
+ resolve: (accepted: boolean) => void;
+ close: () => void;
+}
+
+let pendingConsent: PendingInsightsConsent | null = null;
+
+function settle(consent: PendingInsightsConsent, accepted: boolean, closeDialog = true): void {
+ if (pendingConsent !== consent) return;
+ pendingConsent = null;
+ if (closeDialog) consent.close();
+ consent.resolve(accepted);
+}
+
+/**
+ * Coalesces the consent requested by the Settings, Insights, and Leaderboard
+ * hook instances. One account/generation gets one prompt and one answer.
+ */
+export function requestInsightsConsent({
+ accountId,
+ authGeneration,
+ kind,
+ owner,
+ open,
+ close,
+}: {
+ accountId: string;
+ authGeneration: number;
+ kind: InsightsConsentKind;
+ owner: object;
+ open: (kind: InsightsConsentKind) => void;
+ close: () => void;
+}): Promise<boolean> {
+ const key = JSON.stringify([accountId, authGeneration, kind]);
+ if (pendingConsent?.key === key) return pendingConsent.promise;
+ if (pendingConsent) settle(pendingConsent, false);
+
+ let resolve!: (accepted: boolean) => void;
+ const promise = new Promise<boolean>((answer) => {
+ resolve = answer;
+ });
+ pendingConsent = { key, owner, promise, resolve, close };
+ open(kind);
+ return promise;
+}
+
+export function answerInsightsConsent(owner: object, accepted: boolean): void {
+ if (pendingConsent?.owner === owner) settle(pendingConsent, accepted);
+}
+
+export function cancelInsightsConsent(owner: object, closeDialog = true): void {
+ if (pendingConsent?.owner === owner) settle(pendingConsent, false, closeDialog);
+}
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 02f41c928..db760014f 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -13,6 +13,7 @@ const { BYOK_API_KEYS } = require("../config/secretKeys");
const tokenStore = require("./tokenStore");
const accountScopeBinding = require("./accountScopeBinding");
const { createCloudApiRequestHandler } = require("./cloudApiRequest");
+const { decodeLeaderboardPngDataUrl, leaderboardImageFilename } = require("./leaderboardImage");
const { withPolicyRequestHeaders } = require("./policyRequestHeaders");
const {
createWorkspacePolicyManager,
@@ -44,6 +45,27 @@ const serializeIpcError =
return { error: error.message, code: error.code, messageKey: error.messageKey };
}
};
+
+// Analytics uploads cross two asynchronous boundaries: renderer -> main and
+// main -> cloud. Pin every local queue operation to the same authenticated
+// account generation so a delayed pass cannot adopt a replacement session.
+function assertAnalyticsSyncContext(context) {
+ if (context == null) return null;
+ const state = tokenStore.getState();
+ if (
+ typeof context !== "object" ||
+ typeof context.accountId !== "string" ||
+ context.accountId.length === 0 ||
+ !Number.isInteger(context.authGeneration) ||
+ !state.token ||
+ state.generation !== context.authGeneration
+ ) {
+ throw Object.assign(new Error("Authentication context changed during analytics sync"), {
+ code: "AUTH_CONTEXT_CHANGED",
+ });
+ }
+ return context.accountId;
+}
// Which diarization dialect a resolved endpoint speaks, for Custom endpoints
// that front a known provider. Null when the host offers no known dialect.
const diarizationHost = (endpoint) => {
@@ -1442,49 +1464,64 @@ class IPCHandlers {
return this.databaseManager.getAnalyticsSummary();
});
- ipcMain.handle("analytics-get-pending", async (_event, limit) => {
- return this.databaseManager.getPendingAnalyticsEvents(limit);
+ ipcMain.handle("analytics-get-pending", async (_event, limit, context) => {
+ const accountId = assertAnalyticsSyncContext(context);
+ return this.databaseManager.getPendingAnalyticsEvents(limit, accountId);
});
- ipcMain.handle("analytics-mark-synced", async (_event, eventIds) => {
- return this.databaseManager.markAnalyticsEventsSynced(eventIds);
+ ipcMain.handle("analytics-mark-synced", async (_event, eventIds, context) => {
+ const accountId = assertAnalyticsSyncContext(context);
+ return this.databaseManager.markAnalyticsEventsSynced(eventIds, accountId);
});
- ipcMain.handle("analytics-get-pending-deletes", async (_event, limit) => {
- return this.databaseManager.getPendingAnalyticsDeletes(limit);
+ ipcMain.handle("analytics-get-pending-deletes", async (_event, limit, context) => {
+ const accountId = assertAnalyticsSyncContext(context);
+ return this.databaseManager.getPendingAnalyticsDeletes(limit, accountId);
});
- ipcMain.handle("analytics-hard-delete", async (_event, eventIds) => {
- return this.databaseManager.hardDeleteAnalyticsEvents(eventIds);
+ ipcMain.handle("analytics-hard-delete", async (_event, eventIds, context) => {
+ const accountId = assertAnalyticsSyncContext(context);
+ return this.databaseManager.hardDeleteAnalyticsEvents(eventIds, accountId);
});
- ipcMain.handle("analytics-get-pending-clear", async () => {
- return this.databaseManager.getPendingAnalyticsClear();
+ ipcMain.handle("analytics-get-pending-clear", async (_event, context) => {
+ const accountId = assertAnalyticsSyncContext(context);
+ return this.databaseManager.getPendingAnalyticsClear(accountId);
});
- ipcMain.handle("analytics-complete-clear", async (_event, clearedThrough) => {
- return this.databaseManager.completeAnalyticsClear(clearedThrough);
+ ipcMain.handle("analytics-complete-clear", async (_event, clearedThrough, context) => {
+ const accountId = assertAnalyticsSyncContext(context);
+ return this.databaseManager.completeAnalyticsClear(clearedThrough, accountId);
});
- ipcMain.handle("analytics-count-unclaimed", async () => {
+ ipcMain.handle("analytics-count-unclaimed", async (_event, context) => {
+ assertAnalyticsSyncContext(context);
return this.databaseManager.countUnclaimedAnalyticsEvents();
});
- ipcMain.handle("analytics-count-awaiting-upload", async () => {
- return this.databaseManager.countAnalyticsEventsAwaitingUpload();
+ ipcMain.handle("analytics-count-awaiting-upload", async (_event, context) => {
+ const accountId = assertAnalyticsSyncContext(context);
+ return this.databaseManager.countAnalyticsEventsAwaitingUpload(accountId);
});
- ipcMain.handle("analytics-claim-anonymous", async () => {
- const result = this.databaseManager.claimAnonymousAnalyticsEvents();
- // Claimed rows are only pushed by the Insights view's reload, and the
- // claim itself changes nothing it renders, so tell it to reload.
- if (result?.claimed > 0) {
- setImmediate(() => {
- broadcastToWindows("analytics-changed");
- });
+ ipcMain.handle(
+ "analytics-claim-anonymous",
+ async (_event, accountId, expectedAuthGeneration) => {
+ const state = tokenStore.getState();
+ if (!state.token || state.generation !== expectedAuthGeneration) {
+ return { success: false, claimed: 0, code: "AUTH_CONTEXT_CHANGED" };
+ }
+ const result = this.databaseManager.claimAnonymousAnalyticsEvents(accountId);
+ // Claimed rows are only pushed by the Insights view's reload, and the
+ // claim itself changes nothing it renders, so tell it to reload.
+ if (result?.claimed > 0) {
+ setImmediate(() => {
+ broadcastToWindows("analytics-changed");
+ });
+ }
+ return result;
}
- return result;
- });
+ );
ipcMain.handle("db-clear-transcriptions", async (event) => {
this.audioStorageManager.deleteAllAudio();
@@ -2942,6 +2979,47 @@ class IPCHandlers {
return this.clipboardManager.writeClipboard(text, event.sender);
});
+ ipcMain.handle("leaderboard-copy-image", async (_event, dataUrl) => {
+ try {
+ const { clipboard, nativeImage } = require("electron");
+ const image = nativeImage.createFromBuffer(decodeLeaderboardPngDataUrl(dataUrl));
+ if (image.isEmpty()) throw new Error("Leaderboard image could not be decoded");
+ clipboard.writeImage(image);
+ return { success: true };
+ } catch (error) {
+ debugLogger.error(
+ "Failed to copy leaderboard image",
+ { error: error.message },
+ "analytics"
+ );
+ return { success: false, error: error.message };
+ }
+ });
+
+ ipcMain.handle("leaderboard-save-image", async (event, dataUrl, suggestedName) => {
+ try {
+ const { dialog } = require("electron");
+ const parentWindow = BrowserWindow.fromWebContents(event.sender);
+ const options = {
+ defaultPath: leaderboardImageFilename(suggestedName),
+ filters: [{ name: "PNG image", extensions: ["png"] }],
+ };
+ const result = parentWindow
+ ? await dialog.showSaveDialog(parentWindow, options)
+ : await dialog.showSaveDialog(options);
+ if (result.canceled || !result.filePath) return { success: true, canceled: true };
+ await fs.promises.writeFile(result.filePath, decodeLeaderboardPngDataUrl(dataUrl));
+ return { success: true, canceled: false };
+ } catch (error) {
+ debugLogger.error(
+ "Failed to save leaderboard image",
+ { error: error.message },
+ "analytics"
+ );
+ return { success: false, error: error.message };
+ }
+ });
+
ipcMain.handle("check-paste-tools", async () => {
return this.clipboardManager.checkPasteTools();
});
diff --git a/src/helpers/leaderboard.ts b/src/helpers/leaderboard.ts
new file mode 100644
index 000000000..eb9f1759b
--- /dev/null
+++ b/src/helpers/leaderboard.ts
@@ -0,0 +1,185 @@
+import type {
+ LeaderboardAccess,
+ LeaderboardAccessScope,
+ LeaderboardMember,
+ LeaderboardMetric,
+ LeaderboardRange,
+} from "../types/electron";
+
+// Fallbacks only: a loaded leaderboard carries the page size and refresh window
+// the server actually used, and those win over these.
+export const LEADERBOARD_PAGE_SIZE = 20;
+export const LEADERBOARD_REFRESH_INTERVAL_MS = 60 * 60 * 1000;
+
+export interface LeaderboardWeekStartsCacheEntry {
+ values: string[];
+ expiresAt: number;
+}
+
+// Which metrics a week can rank is one fact: the weekly ones are what the
+// picker offers under "This week", and the lifetime ones are what forces a
+// selection over to "All time".
+export const WEEKLY_METRICS: LeaderboardMetric[] = ["total_words", "desktop_words", "mobile_words"];
+const LIFETIME_METRICS: LeaderboardMetric[] = ["words_per_minute", "current_daily_streak"];
+export const ALL_TIME_METRICS: LeaderboardMetric[] = [...WEEKLY_METRICS, ...LIFETIME_METRICS];
+
+export type LeaderboardSurface =
+ | "accept_invite"
+ | "request_join"
+ | "create"
+ | "invite"
+ | "participation_loading"
+ | "participation_error"
+ | "join"
+ | "board";
+
+export function resolveLeaderboardSurface({
+ access,
+ selectedScope,
+ participating,
+ participationReady,
+ participationError,
+}: {
+ access: LeaderboardAccess;
+ selectedScope: LeaderboardAccessScope | null;
+ participating: boolean;
+ participationReady: boolean;
+ participationError: "read" | "write" | null;
+}): LeaderboardSurface {
+ if (
+ selectedScope?.state !== "ready" &&
+ (access.state === "accept_invite" || access.state === "request_join")
+ )
+ return access.state;
+ if (!selectedScope) {
+ return "create";
+ }
+ if (participationError === "read") return "participation_error";
+ if (!participationReady) return "participation_loading";
+ // Participation decides before the scope's own state does. A solo scope is
+ // still a board, and answering "invite someone" to an account that never
+ // opted in strands it: that surface has no way to join, so the funnel that
+ // sent the user here — Create workspace — would dead-end on itself.
+ if (!participating) return "join";
+ if (selectedScope.state === "invite") return "invite";
+ return "board";
+}
+
+export function shouldFetchLeaderboardWeekStarts(
+ cached: LeaderboardWeekStartsCacheEntry | undefined,
+ now: number = Date.now()
+): boolean {
+ return !cached || cached.expiresAt <= now;
+}
+
+export function mergeLeaderboardWeekStarts(...sources: string[][]): string[] {
+ return [...new Set(sources.flat())].sort((left, right) => right.localeCompare(left));
+}
+
+export function leaderboardRequestKey(
+ scopeKey: string | null,
+ metric: LeaderboardMetric,
+ range: LeaderboardRange,
+ weekStart: string | null,
+ page: number
+): string {
+ return JSON.stringify([scopeKey, metric, range, weekStart, page]);
+}
+
+export function domainToWorkspaceName(domain: string | null): string {
+ if (!domain) return "";
+ const label =
+ domain
+ .trim()
+ .toLowerCase()
+ .replace(/^www\./, "")
+ .split(".")[0] ?? "";
+ return label
+ .split(/[-_]+/)
+ .filter(Boolean)
+ .map((part) => `${part.charAt(0).toUpperCase()}${part.slice(1)}`)
+ .join(" ");
+}
+
+export function resolveLeaderboardScopeKey(
+ scopes: LeaderboardAccessScope[],
+ currentScopeKey: string | null,
+ preferredScopeKey?: string
+): string | null {
+ if (preferredScopeKey && scopes.some((scope) => scope.key === preferredScopeKey)) {
+ return preferredScopeKey;
+ }
+ if (currentScopeKey && scopes.some((scope) => scope.key === currentScopeKey)) {
+ return currentScopeKey;
+ }
+ return (
+ scopes.find((scope) => scope.kind === "workspace" && scope.state === "ready")?.key ??
+ scopes.find((scope) => scope.state === "ready")?.key ??
+ scopes.find((scope) => scope.kind === "workspace")?.key ??
+ null
+ );
+}
+
+export function missingLeaderboardMembers(memberCount: number, participantCount: number): number {
+ return Math.max(0, memberCount - participantCount);
+}
+
+export function shouldShowLeaderboardEmptyStrip(
+ memberCount: number,
+ participantCount: number
+): boolean {
+ return participantCount <= 1 && missingLeaderboardMembers(memberCount, participantCount) > 0;
+}
+
+export function shouldShowLeaderboardJumpToMe(memberCount: number): boolean {
+ return memberCount >= 10;
+}
+
+export function normalizeLeaderboardSelection(
+ metric: LeaderboardMetric,
+ range: LeaderboardRange
+): { metric: LeaderboardMetric; range: LeaderboardRange } {
+ if (LIFETIME_METRICS.includes(metric)) {
+ return { metric, range: "all" };
+ }
+ return { metric, range };
+}
+
+export function selectionForRange(
+ metric: LeaderboardMetric,
+ range: LeaderboardRange
+): { metric: LeaderboardMetric; range: LeaderboardRange } {
+ if (range === "week" && LIFETIME_METRICS.includes(metric)) {
+ return { metric: "total_words", range };
+ }
+ return { metric, range };
+}
+
+export function memberValue(member: LeaderboardMember, metric: LeaderboardMetric): number | null {
+ switch (metric) {
+ case "words_per_minute":
+ return member.averageWpm;
+ case "current_daily_streak":
+ return member.currentStreakDays;
+ case "desktop_words":
+ return member.desktopWords;
+ case "mobile_words":
+ return member.mobileWords;
+ case "total_words":
+ return member.totalWords;
+ }
+}
+
+export function pageForRank(
+ rank: number,
+ memberCount: number,
+ pageSize: number = LEADERBOARD_PAGE_SIZE
+): number {
+ if (memberCount <= 0) return 0;
+ const clampedRank = Math.max(1, Math.min(memberCount, Math.trunc(rank) || 1));
+ return Math.floor((clampedRank - 1) / pageSize);
+}
+
+export function pageCount(memberCount: number, pageSize: number = LEADERBOARD_PAGE_SIZE): number {
+ return Math.max(1, Math.ceil(memberCount / pageSize));
+}
diff --git a/src/helpers/leaderboardImage.js b/src/helpers/leaderboardImage.js
new file mode 100644
index 000000000..b82dfc672
--- /dev/null
+++ b/src/helpers/leaderboardImage.js
@@ -0,0 +1,37 @@
+const MAX_LEADERBOARD_PNG_BYTES = 12 * 1024 * 1024;
+const PNG_DATA_URL_PREFIX = "data:image/png;base64,";
+
+function decodeLeaderboardPngDataUrl(dataUrl) {
+ if (typeof dataUrl !== "string" || !dataUrl.startsWith(PNG_DATA_URL_PREFIX)) {
+ throw new Error("Leaderboard image must be a PNG data URL");
+ }
+ const payload = dataUrl.slice(PNG_DATA_URL_PREFIX.length);
+ if (!payload || payload.length > Math.ceil((MAX_LEADERBOARD_PNG_BYTES * 4) / 3) + 4) {
+ throw new Error("Leaderboard image is empty or too large");
+ }
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(payload) || payload.length % 4 !== 0) {
+ throw new Error("Leaderboard image is not valid base64");
+ }
+ const image = Buffer.from(payload, "base64");
+ if (
+ image.length === 0 ||
+ image.length > MAX_LEADERBOARD_PNG_BYTES ||
+ !image.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))
+ ) {
+ throw new Error("Leaderboard image is not a valid PNG");
+ }
+ return image;
+}
+
+function leaderboardImageFilename(value) {
+ const safe = String(value || "leaderboard.png")
+ .replace(/[^a-zA-Z0-9._-]+/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, 100);
+ return safe.toLowerCase().endsWith(".png") ? safe : `${safe || "leaderboard"}.png`;
+}
+
+module.exports = {
+ decodeLeaderboardPngDataUrl,
+ leaderboardImageFilename,
+};
diff --git a/src/hooks/useAuth.ts b/src/hooks/useAuth.ts
index a6d7305df..74e8dfadf 100644
--- a/src/hooks/useAuth.ts
+++ b/src/hooks/useAuth.ts
@@ -29,6 +29,7 @@ import logger from "../utils/logger";
import { useSettingsStore } from "../stores/settingsStore";
import { usePolicyStore } from "../stores/policyStore";
import { useEnterpriseIdentityStore } from "../stores/enterpriseIdentityStore";
+import { useLeaderboardParticipationStore } from "../stores/leaderboardParticipationStore";
const useStaticSession = () => ({
data: null,
@@ -181,6 +182,11 @@ export function useAuth() {
if (accountScopeRequiresPurge(resolvedUserId)) {
markAccountScopePurgeRequired();
useSettingsStore.getState().setInsightsSyncEnabled(false);
+ // The departing account's leaderboard answer must not outlive it, and a
+ // read still in flight for it must not land on the next one. The opt-out
+ // this device is still holding for that account is kept: it is queued in
+ // storage against that user id and is delivered whenever it signs back in.
+ useLeaderboardParticipationStore.getState().reset();
}
if (accountScopeRequiresReconciliation(resolvedUserId)) {
// This legacy marker drives every already-running SyncService window;
diff --git a/src/hooks/useInsightsSyncOptIn.tsx b/src/hooks/useInsightsSyncOptIn.tsx
index e3b8899c5..379236261 100644
--- a/src/hooks/useInsightsSyncOptIn.tsx
+++ b/src/hooks/useInsightsSyncOptIn.tsx
@@ -1,14 +1,23 @@
-import { useCallback, useEffect, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { ConfirmDialog } from "../components/ui/dialog";
+import { useToast } from "../components/ui/useToast";
+import {
+ answerInsightsConsent,
+ cancelInsightsConsent,
+ requestInsightsConsent,
+} from "../helpers/insightsConsentCoordinator";
+import { getValidatedAuthGeneration } from "../lib/authRequestContext";
import { canChangeCloudBackupPreference, isCloudBackupAllowed } from "../stores/policyRules";
import { usePolicyStore } from "../stores/policyStore";
import { syncService } from "../services/SyncService.js";
+import type { AnalyticsSyncContext } from "../types/electron";
+import { useAuth } from "./useAuth";
import { useSettings } from "./useSettings";
/**
- * Single owner of the "Sync personal Insights" opt-in, shared by the Settings
- * toggle and the Insights banner. Dictations recorded before signing in stay
+ * Single owner of the Insights Sync opt-in, shared by Settings and the Insights
+ * page. Dictations recorded before signing in stay
* unattributed until the user says otherwise here — signing in never adopts
* them on its own — so the prompt is the only path that claims them.
*
@@ -24,42 +33,83 @@ import { useSettings } from "./useSettings";
* user already had them.
*
* unclaimedCount is kept live rather than read only at opt-in time, because
- * more rows appear after it: the toggle survives sign-out, so anything spoken
- * before the next sign-in is unattributed with sync already on. It is what
- * canOfferAnalyticsClaim uses to keep offering this prompt.
+ * account-scope bootstrap can leave new rows unattributed even after the
+ * setting was enabled. It is what canOfferAnalyticsClaim uses to keep offering
+ * this prompt.
+ *
+ * Leaderboard participation is separate account-level consent. Enabling or
+ * disabling this device's Insights Sync never publishes or removes that account.
*/
+export interface EnableInsightsSyncOptions {
+ /** Join must obtain explicit Sync consent even when no rows are queued yet. */
+ confirmWhenEmpty?: boolean;
+}
+
export function useInsightsSyncOptIn() {
const { t } = useTranslation();
+ const { toast } = useToast();
+ const { user } = useAuth();
+ const userId = user?.id ?? null;
const { insightsSyncEnabled, setInsightsSyncEnabled } = useSettings();
const [unclaimedCount, setUnclaimedCount] = useState(0);
const [awaitingUploadCount, setAwaitingUploadCount] = useState(0);
+ const consentOwnerRef = useRef({});
// Separate from the counts: a live count must never be what holds the dialog
// open, or it reopens itself on mount for anyone with rows left behind.
// "enable" asks about everything the first pass would upload; "claim" is the
// narrower question that is left once sync is already on.
const [promptKind, setPromptKind] = useState<"enable" | "claim" | null>(null);
+ const promptAccountIdRef = useRef(userId);
const syncAllowedByPolicy = usePolicyStore(isCloudBackupAllowed);
const canToggleSync = canChangeCloudBackupPreference(syncAllowedByPolicy, insightsSyncEnabled);
+ const reportActivationFailure = useCallback(
+ (error: unknown) => {
+ console.error("Enabling Insights Sync failed:", error);
+ toast({ title: t("insights.syncEnableError"), variant: "destructive" });
+ },
+ [t, toast]
+ );
+
// The claim lands before the pass is requested so the rows it adopts go up
// with it, rather than waiting for the next ambient one.
- const activate = useCallback(
- async (claimAnonymous: boolean) => {
+ const prepareInsightsSync = useCallback(
+ async (claimAnonymous: boolean, expectedAccountId: string, expectedAuthGeneration: number) => {
if (claimAnonymous) {
- await window.electronAPI.claimAnonymousAnalyticsEvents().catch((error) => {
- console.error("Claiming earlier Insights events failed:", error);
- });
+ try {
+ const result = await window.electronAPI.claimAnonymousAnalyticsEvents(
+ expectedAccountId,
+ expectedAuthGeneration
+ );
+ if (!result.success) {
+ reportActivationFailure(result.code ?? "The local account scope changed");
+ return false;
+ }
+ } catch (error) {
+ reportActivationFailure(error);
+ return false;
+ }
}
+ if (
+ promptAccountIdRef.current !== expectedAccountId ||
+ getValidatedAuthGeneration() !== expectedAuthGeneration
+ )
+ return false;
setInsightsSyncEnabled(true);
syncService.requestSyncAll("manual");
+ return true;
},
- [setInsightsSyncEnabled]
+ [reportActivationFailure, setInsightsSyncEnabled]
);
- const refreshCounts = useCallback(async () => {
+ const disableInsightsSync = useCallback(() => {
+ setInsightsSyncEnabled(false);
+ }, [setInsightsSyncEnabled]);
+
+ const refreshCounts = useCallback(async (context?: AnalyticsSyncContext) => {
const [unclaimed, awaitingUpload] = await Promise.all([
- window.electronAPI.countUnclaimedAnalyticsEvents().catch(() => 0),
- window.electronAPI.countAnalyticsEventsAwaitingUpload().catch(() => 0),
+ window.electronAPI.countUnclaimedAnalyticsEvents(context),
+ window.electronAPI.countAnalyticsEventsAwaitingUpload(context),
]);
setUnclaimedCount(unclaimed);
setAwaitingUploadCount(awaitingUpload);
@@ -69,43 +119,116 @@ export function useInsightsSyncOptIn() {
// Every claim, purge and new dictation broadcasts analytics-changed, so the
// counts follow the rows without polling.
useEffect(() => {
- void refreshCounts();
- return window.electronAPI.onAnalyticsChanged?.(() => void refreshCounts());
+ const refresh = () => {
+ void refreshCounts().catch((error) => {
+ console.error("Reading Insights Sync counts failed:", error);
+ });
+ };
+ refresh();
+ return window.electronAPI.onAnalyticsChanged?.(refresh);
}, [refreshCounts]);
- const enableInsightsSync = useCallback(() => {
- if (!syncAllowedByPolicy) return;
- void (async () => {
- const { unclaimed, awaitingUpload } = await refreshCounts();
+ // Consent belongs to the account that opened the prompt. If auth changes
+ // while it is open, settle that account's request as declined and close it;
+ // otherwise accepting the stale dialog could publish the replacement account.
+ useEffect(() => {
+ if (promptAccountIdRef.current === userId) return;
+ promptAccountIdRef.current = userId;
+ cancelInsightsConsent(consentOwnerRef.current);
+ }, [userId]);
+
+ useEffect(() => {
+ const owner = consentOwnerRef.current;
+ // Unmount removes the dialog itself; only settle callers still awaiting it.
+ return () => cancelInsightsConsent(owner, false);
+ }, []);
+
+ const enableInsightsSync = useCallback(
+ async (options: EnableInsightsSyncOptions = {}) => {
+ if (!syncAllowedByPolicy) return false;
+ const requestedAccountId = userId;
+ const requestedAuthGeneration = getValidatedAuthGeneration();
+ if (!requestedAccountId || requestedAuthGeneration == null) return false;
+ let counts: { unclaimed: number; awaitingUpload: number };
+ try {
+ counts = await refreshCounts({
+ accountId: requestedAccountId,
+ authGeneration: requestedAuthGeneration,
+ });
+ } catch (error) {
+ reportActivationFailure(error);
+ return false;
+ }
+ const { unclaimed, awaitingUpload } = counts;
+ if (
+ promptAccountIdRef.current !== requestedAccountId ||
+ getValidatedAuthGeneration() !== requestedAuthGeneration
+ )
+ return false;
// Already on: the pre-sign-in rows are the only thing still unanswered.
- if (insightsSyncEnabled) {
- if (unclaimed > 0) setPromptKind("claim");
- else await activate(false);
- return;
+ // Turning it on: ask about everything the first pass would send, not just
+ // the pre-sign-in slice. Nothing queued means there is nothing to claim.
+ const pending = insightsSyncEnabled ? unclaimed : awaitingUpload;
+ if (pending === 0 && !options.confirmWhenEmpty) {
+ return prepareInsightsSync(false, requestedAccountId, requestedAuthGeneration);
}
- // Turning it on: ask about everything the first pass would send, not
- // just the pre-sign-in slice. Nothing queued means nothing to disclose.
- if (awaitingUpload > 0) setPromptKind("enable");
- else await activate(false);
- })();
- }, [activate, insightsSyncEnabled, refreshCounts, syncAllowedByPolicy]);
+ const accepted = await requestInsightsConsent({
+ accountId: requestedAccountId,
+ authGeneration: requestedAuthGeneration,
+ kind: insightsSyncEnabled ? "claim" : "enable",
+ owner: consentOwnerRef.current,
+ open: setPromptKind,
+ close: () => setPromptKind(null),
+ });
+ if (!accepted) return false;
+ return prepareInsightsSync(pending > 0, requestedAccountId, requestedAuthGeneration);
+ },
+ [
+ insightsSyncEnabled,
+ prepareInsightsSync,
+ refreshCounts,
+ reportActivationFailure,
+ syncAllowedByPolicy,
+ userId,
+ ]
+ );
const claiming = promptKind === "claim";
+ const promptCount = claiming ? unclaimedCount : awaitingUploadCount;
+ const answerClaimPrompt = (claimed: boolean) => {
+ answerInsightsConsent(consentOwnerRef.current, claimed);
+ };
+
const optInDialog = (
<ConfirmDialog
open={promptKind !== null}
onOpenChange={(open) => {
- if (!open) setPromptKind(null);
+ if (open) return;
+ setPromptKind(null);
+ // Also covers Esc and the overlay: a dismissed prompt is a declined one.
+ answerClaimPrompt(false);
}}
title={t(claiming ? "insights.claimTitle" : "insights.enableTitle")}
- description={t(claiming ? "insights.claimDescription" : "insights.enableDescription", {
- count: claiming ? unclaimedCount : awaitingUploadCount,
- })}
+ description={t(
+ promptCount === 0
+ ? "insights.syncPrompt"
+ : claiming
+ ? "insights.claimDescription"
+ : "insights.enableDescription",
+ { count: promptCount }
+ )}
confirmText={t(claiming ? "insights.claimInclude" : "insights.enableConfirm")}
cancelText={t("insights.claimSkip")}
- onConfirm={() => void activate(true)}
+ onConfirm={() => answerClaimPrompt(true)}
/>
);
- return { canToggleSync, enableInsightsSync, optInDialog, syncAllowedByPolicy, unclaimedCount };
+ return {
+ canToggleSync,
+ disableInsightsSync,
+ enableInsightsSync,
+ optInDialog,
+ syncAllowedByPolicy,
+ unclaimedCount,
+ };
}
diff --git a/src/hooks/useLeaderboardParticipation.ts b/src/hooks/useLeaderboardParticipation.ts
new file mode 100644
index 000000000..12a4daa8c
--- /dev/null
+++ b/src/hooks/useLeaderboardParticipation.ts
@@ -0,0 +1,72 @@
+import { useCallback, useEffect } from "react";
+import {
+ getAuthRequestContextSnapshot,
+ getValidatedAuthGeneration,
+} from "../lib/authRequestContext";
+import { writePendingLeaderboardLeave } from "../lib/pendingLeaderboardLeave";
+import { useLeaderboardParticipationStore } from "../stores/leaderboardParticipationStore";
+import type { LeaderboardParticipationAuthContext } from "../services/LeaderboardService";
+import { useAuth } from "./useAuth";
+
+function currentParticipationContext(userId: string): LeaderboardParticipationAuthContext | null {
+ const snapshot = getAuthRequestContextSnapshot();
+ const authGeneration = getValidatedAuthGeneration();
+ if (snapshot.sessionUserId !== userId || authGeneration == null) return null;
+ return { userId, authGeneration };
+}
+
+export function useLeaderboardParticipation() {
+ const { isLoaded, isSignedIn, user } = useAuth();
+ const userId = user?.id ?? null;
+ const authGeneration = getValidatedAuthGeneration();
+ const enabled = useLeaderboardParticipationStore((state) => state.enabled);
+ const ready = useLeaderboardParticipationStore((state) => state.ready);
+ const error = useLeaderboardParticipationStore((state) => state.error);
+ const updating = useLeaderboardParticipationStore((state) => state.updating);
+ const leavePending = useLeaderboardParticipationStore((state) => state.leavePending);
+
+ const refresh = useCallback(async () => {
+ const store = useLeaderboardParticipationStore.getState();
+ if (!isLoaded || !isSignedIn || !userId || authGeneration == null) {
+ store.reset();
+ return;
+ }
+ const context = currentParticipationContext(userId);
+ if (!context) {
+ store.reset();
+ return;
+ }
+ await store.refresh(context);
+ }, [authGeneration, isLoaded, isSignedIn, userId]);
+
+ useEffect(() => {
+ void refresh();
+ }, [refresh]);
+
+ const join = useCallback(async () => {
+ if (!userId) return false;
+ const store = useLeaderboardParticipationStore.getState();
+ if (store.updating) return false;
+ const context = currentParticipationContext(userId);
+ if (!context) return false;
+ return store.join(context);
+ }, [userId]);
+
+ const leave = useCallback(async () => {
+ if (!userId) return true;
+ const store = useLeaderboardParticipationStore.getState();
+ const snapshot = getAuthRequestContextSnapshot();
+ if (snapshot.sessionUserId !== userId) {
+ writePendingLeaderboardLeave(userId);
+ return false;
+ }
+ const context = currentParticipationContext(userId);
+ if (!context) {
+ store.queueLeave(userId);
+ return false;
+ }
+ return store.leave(context);
+ }, [userId]);
+
+ return { enabled, error, join, leave, leavePending, ready, refresh, updating };
+}
diff --git a/src/lib/pendingLeaderboardLeave.ts b/src/lib/pendingLeaderboardLeave.ts
new file mode 100644
index 000000000..4af1d3671
--- /dev/null
+++ b/src/lib/pendingLeaderboardLeave.ts
@@ -0,0 +1,87 @@
+// Each account owns its own key so two renderer windows changing different
+// accounts cannot lose either pending leave through shared read-modify-write state.
+const PENDING_PREFIX = "leaderboardLeavePending:";
+
+// A leave the network never delivered keeps its place forever — the account
+// asked to come off a leaderboard and only a delivered PATCH may retire that.
+// Its claim on *priority* is what expires: SyncService lets a pending leave
+// bypass the sync throttle, the in-flight guard and the ambient backoff, so a
+// leave that can never land would otherwise run an unthrottled full pass on
+// every focus, visibility change and online event for the life of the install.
+// After this many failed deliveries the record stays and keeps retrying on
+// ordinary passes, without commandeering them.
+export const MAX_PRIORITY_LEAVE_ATTEMPTS = 5;
+
+interface PendingLeave {
+ attempts: number;
+}
+
+function accountKey(userId: string): string {
+ return `${PENDING_PREFIX}${encodeURIComponent(userId)}`;
+}
+
+function readPendingLeave(userId: string): PendingLeave | null {
+ let raw: string | null;
+ try {
+ raw = localStorage.getItem(accountKey(userId));
+ } catch {
+ return null;
+ }
+ if (raw == null) return null;
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ if (typeof parsed === "object" && parsed !== null) {
+ const attempts = (parsed as { attempts?: unknown }).attempts;
+ if (typeof attempts === "number" && Number.isInteger(attempts) && attempts >= 0) {
+ return { attempts };
+ }
+ }
+ } catch {
+ // Builds before the attempt bound stored a bare "true", which is not JSON.
+ }
+ // A legacy or half-written value is still an account waiting to leave; only
+ // its attempt count is unknown, and restarting the count costs at most a few
+ // prioritized passes.
+ return { attempts: 0 };
+}
+
+function writePendingLeave(userId: string, attempts: number): void {
+ try {
+ localStorage.setItem(accountKey(userId), JSON.stringify({ attempts }));
+ } catch {
+ // Losing the record only costs the retry; the account preference is unchanged.
+ }
+}
+
+export function readPendingLeaderboardLeave(userId: string): boolean {
+ return readPendingLeave(userId) !== null;
+}
+
+/**
+ * Whether a pending leave may still preempt the sync throttle. Separate from
+ * {@link readPendingLeaderboardLeave} so an undeliverable leave keeps being
+ * retried without holding the throttle open — see MAX_PRIORITY_LEAVE_ATTEMPTS.
+ */
+export function pendingLeaderboardLeaveDeservesPriority(userId: string): boolean {
+ const pending = readPendingLeave(userId);
+ return pending !== null && pending.attempts < MAX_PRIORITY_LEAVE_ATTEMPTS;
+}
+
+export function writePendingLeaderboardLeave(userId: string): void {
+ writePendingLeave(userId, 0);
+}
+
+/** Records one undelivered attempt, retiring the record's priority in time. */
+export function recordPendingLeaderboardLeaveAttempt(userId: string): void {
+ const pending = readPendingLeave(userId);
+ if (pending === null || pending.attempts >= MAX_PRIORITY_LEAVE_ATTEMPTS) return;
+ writePendingLeave(userId, pending.attempts + 1);
+}
+
+export function clearPendingLeaderboardLeave(userId: string): void {
+ try {
+ localStorage.removeItem(accountKey(userId));
+ } catch {
+ // A failed clear only causes an idempotent leave retry.
+ }
+}
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index e04609896..b3bfb4a12 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -2392,6 +2392,9 @@
"insightsSyncDescription": "Synchronisieren Sie Wortanzahl, Datum und genaue Uhrzeit jedes Diktats, Dauer und Modelltyp geräteübergreifend. Transkriptionsinhalte werden nie übertragen. Wenn Sie angemeldet sind, werden diese Zähler beim Löschen des Verlaufs auch von diesem Gerät und aus Ihrem Konto entfernt.",
"insightsSyncRequiresAccount": "Melden Sie sich an, um inhaltsfreie Statistikdaten geräteübergreifend zu synchronisieren.",
"insightsSyncRequiresHistory": "Aktivieren Sie die Datenaufbewahrung, um Statistiken zu erfassen, bevor Sie sie geräteübergreifend synchronisieren.",
+ "leaderboardDescription": "Zeigen Sie Ihren Namen, Ihre E-Mail-Adresse und Ihre Aktivität in berechtigten Workspace- und Arbeitsdomain-Bestenlisten an. Transkripte bleiben privat.",
+ "leaderboardRequiresAccount": "Melden Sie sich an, um Ihre Teilnahme an Bestenlisten zu verwalten.",
+ "leaderboardRequiresHistory": "Aktivieren Sie die Datenaufbewahrung, bevor Sie Bestenlisten beitreten.",
"usageAnalytics": "Nutzungsanalysen",
"usageAnalyticsDescription": "Helfen Sie uns, OpenWhispr zu verbessern, indem Sie anonyme Leistungsdaten teilen. Wir senden niemals Transkriptionsinhalte – nur Timing- und Fehlerdaten.",
"audioRetention": "Audio-Aufbewahrung",
@@ -2720,6 +2723,7 @@
},
"insights": {
"title": "Statistiken",
+ "yourUsage": "Ihre Nutzung",
"description": "Ein privater Blick auf Ihre Diktiergewohnheiten und Ihren Fortschritt.",
"wordsSpoken": "Gesprochene Wörter",
"currentStreak": "Aktuelle Serie",
@@ -2740,22 +2744,108 @@
"dayTooltip_other": "{{date}}: {{count}} Wörter",
"dataRetentionDisabled": "Die Datenaufbewahrung ist deaktiviert, daher werden neue Diktate in den Statistiken nicht gezählt – weder auf diesem Gerät noch in Ihrem Konto. Bereits synchronisierte Zähler bleiben in Ihrem Konto.",
"onDevice": "Auf diesem Gerät",
+ "onDevicePrivacy": "Diese Insights werden auf diesem Gerät berechnet, um deine Privatsphäre zu schützen.",
"synced": "Geräteübergreifend synchronisiert",
"syncFallback": "Gerätedaten werden angezeigt – Synchronisierung nicht verfügbar",
"syncPrompt": "Synchronisieren Sie inhaltsfreie Zähler, um lokale und Cloud-Aktivität geräteübergreifend zusammenzuführen.",
"enableSync": "Synchronisierung aktivieren",
+ "syncEnableError": "Die Insights-Synchronisierung konnte nicht aktiviert werden. Versuchen Sie es erneut.",
"claimTitle": "Frühere Diktate einbeziehen?",
- "claimDescription_one": "{{count}} Diktat wurde auf diesem Gerät vor Ihrer Anmeldung aufgezeichnet. Wird es einbezogen, werden nur Wortanzahl, Datum und genaue Uhrzeit der Aufnahme, Dauer und Modelltyp übertragen – nie Transkriptionsinhalte.",
- "claimDescription_other": "{{count}} Diktate wurden auf diesem Gerät vor Ihrer Anmeldung aufgezeichnet. Werden sie einbezogen, werden nur Wortanzahl, Datum und genaue Uhrzeit der jeweiligen Aufnahme, Dauer und Modelltyp übertragen – nie Transkriptionsinhalte.",
+ "claimDescription_one": "Nutzung aus {{count}} früheren Diktat synchronisieren. Transkripte bleiben privat.",
+ "claimDescription_other": "Nutzung aus {{count}} früheren Diktaten synchronisieren. Transkripte bleiben privat.",
"claimInclude": "Einbeziehen",
"claimSkip": "Jetzt nicht",
"enableTitle": "Insights-Synchronisierung aktivieren?",
"enableConfirm": "Synchronisierung aktivieren",
- "enableDescription_one": "{{count}} bereits auf diesem Gerät aufgezeichnetes Diktat wird in Ihr Konto hochgeladen. Die Insights-Synchronisierung überträgt nur Wortanzahl, Datum und genaue Uhrzeit der jeweiligen Aufnahme, Dauer und Modelltyp – nie Transkriptionsinhalte.",
- "enableDescription_other": "{{count}} bereits auf diesem Gerät aufgezeichnete Diktate werden in Ihr Konto hochgeladen. Die Insights-Synchronisierung überträgt nur Wortanzahl, Datum und genaue Uhrzeit der jeweiligen Aufnahme, Dauer und Modelltyp – nie Transkriptionsinhalte.",
+ "enableDescription_one": "Nutzung aus {{count}} vorhandenem Diktat synchronisieren. Transkripte bleiben privat.",
+ "enableDescription_other": "Nutzung aus {{count}} vorhandenen Diktaten synchronisieren. Transkripte bleiben privat.",
"emptyTitle": "Noch keine Diktate",
"emptyBody": "Beginnen Sie zu diktieren – Ihre Wörter, Serien und tägliche Aktivität erscheinen dann hier.",
- "loadError": "Insights konnten von diesem Gerät nicht gelesen werden."
+ "loadError": "Insights konnten von diesem Gerät nicht gelesen werden.",
+ "leaderboard": {
+ "title": "Bestenliste",
+ "inviteCta": "Teammitglieder einladen",
+ "soloTitle": "Lade dein erstes Teammitglied ein",
+ "soloDescription": "Deine Bestenliste ist bereit. Lade jemanden zu {{scope}} ein, um Aktivitäten zu vergleichen und gemeinsam Fortschritte zu machen.",
+ "soloHint": "Die Person erscheint hier, sobald sie der Bestenliste beitritt.",
+ "topPerformers": "Top-Platzierte",
+ "refreshCadence": "Wird stündlich aktualisiert",
+ "moreActions": "Weitere Ranglistenaktionen",
+ "setupTitle": "Erstelle deine Team-Bestenliste",
+ "setupDescription": "Erstelle einen Workspace und lade dann Teammitglieder ein, um Aktivitäten zu vergleichen und gemeinsam Fortschritte zu machen.",
+ "setupDomainDescription_one": "{{count}} Person bei {{domain}} nimmt an Leaderboards teil. Erstelle einen Workspace und lade sie ein.",
+ "setupDomainDescription_other": "{{count}} Personen bei {{domain}} nehmen an Leaderboards teil. Erstelle einen Workspace und lade sie ein.",
+ "setupCta": "Workspace erstellen",
+ "accessError": "Der Zugriff auf die Bestenliste konnte nicht geprüft werden.",
+ "signInTitle": "Melde dich an, um deine Bestenliste zu sehen",
+ "signInDescription": "Bestenlisten vergleichen dich mit Teammitgliedern deines Kontos. Melde dich an, um zu sehen, ob deine verfügbar ist.",
+ "requestJoinTitle": "Dein Team ist bereits hier",
+ "requestJoinDescription_one": "{{workspace}} hat {{count}} Mitglied. Bitte einen Admin, dich hinzuzufügen.",
+ "requestJoinDescription_other": "{{workspace}} hat {{count}} Mitglieder. Bitte einen Admin, dich hinzuzufügen.",
+ "requestJoinCta": "Beitritt anfragen",
+ "requestSent": "Anfrage gesendet",
+ "requesting": "Anfrage wird gesendet…",
+ "acceptInviteTitle": "Du wurdest zu {{workspace}} eingeladen",
+ "acceptInviteDescription": "{{inviter}} hat dich eingeladen. Tritt bei, um die Team-Bestenliste zu sehen.",
+ "acceptInviteDescriptionNoInviter": "Tritt {{workspace}} bei, um die Team-Bestenliste zu sehen.",
+ "acceptInviteCta": "Team beitreten",
+ "joining": "Beitritt läuft…",
+ "inviteAcceptedTitle": "Workspace beigetreten",
+ "inviteAcceptedDescription": "Du kannst jetzt die Bestenliste von {{workspace}} sehen.",
+ "inviteAcceptError": "Beitritt zum Workspace fehlgeschlagen",
+ "invitedList": "Eingeladen: {{emails}}",
+ "chooseBoard": "Bestenliste auswählen",
+ "emptyStrip_one": "{{count}} Teammitglied ist der Bestenliste noch nicht beigetreten. Die Rangliste startet danach.",
+ "emptyStrip_other": "{{count}} Teammitglieder sind der Bestenliste noch nicht beigetreten. Die Rangliste startet danach.",
+ "copyNudge": "Erinnerung kopieren",
+ "nudgeText": "Treten Sie unter OpenWhispr → Insights der Bestenliste bei, damit wir die Team-Bestenliste sehen können.",
+ "nudgeCopied": "Erinnerung kopiert",
+ "nudgeCopyError": "Erinnerung konnte nicht kopiert werden",
+ "joinTitle": "Sehen Sie, wo Sie bei {{scope}} stehen",
+ "joinDescription": "Ihr Name, Ihre E-Mail-Adresse und Ihre Aktivität erscheinen in allen berechtigten Workspace- und Domain-Bestenlisten. Transkripte bleiben privat; Sie können jederzeit austreten.",
+ "joinCta": "Bestenlisten beitreten",
+ "joiningLeaderboard": "Beitritt…",
+ "joinPolicyBlocked": "Ihre Workspace-Richtlinie erlaubt keine Teilnahme an Bestenlisten.",
+ "activationError": "Ihre Teilnahme an der Bestenliste konnte nicht bestätigt werden. Prüfen Sie Ihre Verbindung und versuchen Sie es erneut.",
+ "disabled": "Bestenliste ist deaktiviert",
+ "leave": "Bestenlisten verlassen",
+ "leavePending": "Sobald Sie wieder online sind, schließen wir den Austritt aus den Bestenlisten ab.",
+ "allTime": "Gesamt",
+ "thisWeek": "Diese Woche",
+ "wpmValue": "{{count}} WPM",
+ "dayValue_one": "{{count}} Tag",
+ "dayValue_other": "{{count}} Tage",
+ "share": "Teilen",
+ "refresh": "Bestenliste aktualisieren",
+ "error": "Die Bestenliste konnte nicht geladen werden.",
+ "retry": "Erneut versuchen",
+ "rank": "Rang",
+ "member": "Mitglied",
+ "you": "(du)",
+ "jumpToMe": "Zu mir springen",
+ "jumpUnavailable": "Dein Konto konnte in dieser Bestenliste nicht identifiziert werden.",
+ "previous": "Vorherige Seite",
+ "jumpToRank": "Zu Rang springen",
+ "next": "Nächste Seite",
+ "metrics": {
+ "total_words": "Wörter insgesamt",
+ "words_per_minute": "Wörter pro Minute",
+ "current_daily_streak": "Aktuelle Tagesserie",
+ "desktop_words": "Desktop-Wörter",
+ "mobile_words": "Mobil-Wörter"
+ },
+ "shareText": "Sehen Sie, welchen Rang ich bei OpenWhispr habe.",
+ "shareTitle": "Bestenliste teilen",
+ "shareDescription": "Kopiere oder lade diese Karte herunter oder kopiere sie, bevor du einen Beitrag öffnest.",
+ "copyImage": "Bild kopieren",
+ "download": "Herunterladen",
+ "shareX": "Auf X teilen",
+ "shareLinkedIn": "Auf LinkedIn teilen",
+ "copied": "Bild kopiert — füge es in deinen Beitrag ein.",
+ "saved": "Bild heruntergeladen.",
+ "failed": "Die Karte konnte nicht erstellt werden.",
+ "unnamedMember": "Teammitglied"
+ }
},
"sidebar": {
"insights": "Statistiken",
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index f3f45e95a..7f32134ef 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -2394,6 +2394,9 @@
"insightsSyncDescription": "Sync word counts, the date and exact time of each dictation, durations, and model types across your devices. Transcript content is never included. When you're signed in, clearing history also removes these counters from this device and your account.",
"insightsSyncRequiresAccount": "Sign in to sync content-free Insights data across your devices.",
"insightsSyncRequiresHistory": "Turn on data retention to record Insights before syncing them across your devices.",
+ "leaderboardDescription": "Show your name, email, and activity on eligible workspace and work-domain leaderboards. Transcripts stay private.",
+ "leaderboardRequiresAccount": "Sign in to manage leaderboard participation.",
+ "leaderboardRequiresHistory": "Turn on data retention before joining leaderboards.",
"audioRetention": "Audio Retention",
"audioRetentionDescription": "Store dictation audio locally for re-transcription and download. Files are automatically deleted after the retention period. Meeting audio is never stored.",
"audioRetentionDisabled": "Disabled",
@@ -2745,6 +2748,7 @@
},
"insights": {
"title": "Insights",
+ "yourUsage": "Your Usage",
"description": "A private view of your dictation habits and momentum.",
"wordsSpoken": "Words spoken",
"currentStreak": "Current streak",
@@ -2765,22 +2769,108 @@
"dayTooltip_other": "{{date}}: {{count}} words",
"dataRetentionDisabled": "Data retention is off, so new dictations aren't counted in Insights — not on this device and not in your account. Counters already synced stay in your account.",
"onDevice": "On this device",
+ "onDevicePrivacy": "These insights are calculated on this device to protect your privacy.",
"synced": "Synced across devices",
"syncFallback": "Showing device data — sync unavailable",
"syncPrompt": "Sync content-free counters to combine local and cloud activity across devices.",
- "enableSync": "Enable sync",
+ "enableSync": "Enable Sync",
+ "syncEnableError": "Insights sync couldn't be enabled. Please try again.",
"claimTitle": "Include earlier dictations?",
- "claimDescription_one": "{{count}} dictation on this device was recorded before you signed in. Including it sends only word counts, the date and exact time it happened, its duration, and the model type — never transcript content.",
- "claimDescription_other": "{{count}} dictations on this device were recorded before you signed in. Including them sends only word counts, the date and exact time each one happened, durations, and model types — never transcript content.",
+ "claimDescription_one": "Sync usage from {{count}} earlier dictation. Transcripts stay private.",
+ "claimDescription_other": "Sync usage from {{count}} earlier dictations. Transcripts stay private.",
"claimInclude": "Include",
"claimSkip": "Not now",
"enableTitle": "Turn on Insights sync?",
"enableConfirm": "Turn on sync",
- "enableDescription_one": "{{count}} dictation already recorded on this device will be uploaded to your account. Insights sync sends only word counts, the date and exact time each one happened, durations, and model types — never transcript content.",
- "enableDescription_other": "{{count}} dictations already recorded on this device will be uploaded to your account. Insights sync sends only word counts, the date and exact time each one happened, durations, and model types — never transcript content.",
+ "enableDescription_one": "Sync usage from {{count}} existing dictation. Transcripts stay private.",
+ "enableDescription_other": "Sync usage from {{count}} existing dictations. Transcripts stay private.",
"emptyTitle": "No dictations yet",
"emptyBody": "Start dictating and your words, streaks, and daily activity will show up here.",
- "loadError": "Insights couldn't be read from this device."
+ "loadError": "Insights couldn't be read from this device.",
+ "leaderboard": {
+ "title": "Leaderboard",
+ "inviteCta": "Invite teammates",
+ "soloTitle": "Invite your first teammate",
+ "soloDescription": "Your leaderboard is ready. Invite someone to {{scope}} to start comparing activity and building momentum together.",
+ "soloHint": "They’ll appear here after they join the leaderboard.",
+ "topPerformers": "Top performers",
+ "refreshCadence": "Updates hourly",
+ "moreActions": "More leaderboard actions",
+ "setupTitle": "Create your team leaderboard",
+ "setupDescription": "Create a workspace, then invite teammates to start comparing activity and building momentum together.",
+ "setupDomainDescription_one": "{{count}} person at {{domain}} has joined leaderboards. Create a workspace and invite them.",
+ "setupDomainDescription_other": "{{count}} people at {{domain}} have joined leaderboards. Create a workspace and invite them.",
+ "setupCta": "Create workspace",
+ "accessError": "We couldn't check your leaderboard access.",
+ "signInTitle": "Sign in to see your leaderboard",
+ "signInDescription": "Leaderboards rank you against teammates on your account. Sign in to check whether yours is available.",
+ "requestJoinTitle": "Your team is already here",
+ "requestJoinDescription_one": "{{workspace}} has {{count}} member. Ask an admin to add you.",
+ "requestJoinDescription_other": "{{workspace}} has {{count}} members. Ask an admin to add you.",
+ "requestJoinCta": "Request to join",
+ "requestSent": "Request sent",
+ "requesting": "Sending request…",
+ "acceptInviteTitle": "You're invited to {{workspace}}",
+ "acceptInviteDescription": "{{inviter}} invited you. Join to see the team board.",
+ "acceptInviteDescriptionNoInviter": "Join {{workspace}} to see the team board.",
+ "acceptInviteCta": "Join Team",
+ "joining": "Joining…",
+ "inviteAcceptedTitle": "Workspace joined",
+ "inviteAcceptedDescription": "You can now see the {{workspace}} leaderboard.",
+ "inviteAcceptError": "Couldn't join this workspace",
+ "invitedList": "Invited: {{emails}}",
+ "chooseBoard": "Choose a board",
+ "emptyStrip_one": "{{count}} teammate hasn't joined the leaderboard yet. Rankings start when they do.",
+ "emptyStrip_other": "{{count}} teammates haven't joined the leaderboard yet. Rankings start when they do.",
+ "copyNudge": "Copy a nudge",
+ "nudgeText": "Join the leaderboard in OpenWhispr → Insights so we can see the team board.",
+ "nudgeCopied": "Nudge copied",
+ "nudgeCopyError": "Couldn't copy the nudge",
+ "joinTitle": "See where you rank in {{scope}}",
+ "joinDescription": "Your name, email, and activity appear on all your eligible workspace and work-domain leaderboards. Transcripts stay private, and you can leave at any time.",
+ "joinCta": "Join leaderboards",
+ "joiningLeaderboard": "Joining…",
+ "joinPolicyBlocked": "Your workspace policy doesn't allow leaderboard participation.",
+ "activationError": "We couldn't verify your leaderboard participation. Check your connection and try again.",
+ "disabled": "Leaderboard is disabled",
+ "leave": "Leave leaderboards",
+ "leavePending": "We'll finish leaving the leaderboards when you're online.",
+ "allTime": "All time",
+ "thisWeek": "This week",
+ "wpmValue": "{{count}} WPM",
+ "dayValue_one": "{{count}} day",
+ "dayValue_other": "{{count}} days",
+ "share": "Share",
+ "refresh": "Refresh leaderboard",
+ "error": "The leaderboard couldn't be loaded.",
+ "retry": "Try again",
+ "rank": "Rank",
+ "member": "Member",
+ "you": "(you)",
+ "jumpToMe": "Jump to me",
+ "jumpUnavailable": "Your account couldn't be identified in this leaderboard.",
+ "previous": "Previous page",
+ "jumpToRank": "Jump to rank",
+ "next": "Next page",
+ "metrics": {
+ "total_words": "Total words",
+ "words_per_minute": "Words per minute",
+ "current_daily_streak": "Current daily streak",
+ "desktop_words": "Desktop words",
+ "mobile_words": "Mobile words"
+ },
+ "shareText": "See where I rank on OpenWhispr.",
+ "shareTitle": "Share leaderboard",
+ "shareDescription": "Copy or download this card, or copy it before opening a social composer.",
+ "copyImage": "Copy image",
+ "download": "Download",
+ "shareX": "Share to X",
+ "shareLinkedIn": "Share to LinkedIn",
+ "copied": "Image copied — paste it into your post.",
+ "saved": "Image downloaded.",
+ "failed": "The share card couldn't be created.",
+ "unnamedMember": "Teammate"
+ }
},
"workspaces": {
"switcher": {
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index faaf63c0d..0d2a960d5 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -2151,6 +2151,9 @@
"insightsSyncDescription": "Sincroniza recuentos de palabras, la fecha y la hora exacta de cada dictado, duraciones y tipos de modelo entre tus dispositivos. El contenido de las transcripciones nunca se incluye. Cuando hayas iniciado sesión, borrar el historial también elimina estos recuentos de este dispositivo y de tu cuenta.",
"insightsSyncRequiresAccount": "Inicia sesión para sincronizar datos de Estadísticas sin contenido entre tus dispositivos.",
"insightsSyncRequiresHistory": "Activa la retención de datos para registrar las Estadísticas antes de sincronizarlas entre tus dispositivos.",
+ "leaderboardDescription": "Muestra tu nombre, correo electrónico y actividad en las clasificaciones de espacios de trabajo y dominios laborales disponibles. Las transcripciones siguen siendo privadas.",
+ "leaderboardRequiresAccount": "Inicia sesión para gestionar tu participación en las clasificaciones.",
+ "leaderboardRequiresHistory": "Activa la retención de datos antes de unirte a las clasificaciones.",
"usageAnalytics": "Analíticas de uso",
"usageAnalyticsDescription": "Ayúdanos a mejorar OpenWhispr compartiendo métricas de rendimiento anónimas. Nunca enviamos contenido de transcripciones, solo datos de tiempo y errores.",
"dataRetention": "Retención de datos",
@@ -3282,6 +3285,7 @@
},
"insights": {
"title": "Estadísticas",
+ "yourUsage": "Tu uso",
"description": "Una vista privada de tus hábitos de dictado y tu constancia.",
"wordsSpoken": "Palabras dictadas",
"currentStreak": "Racha actual",
@@ -3302,22 +3306,108 @@
"dayTooltip_other": "{{date}}: {{count}} palabras",
"dataRetentionDisabled": "La retención de datos está desactivada, así que los nuevos dictados no se cuentan en las Estadísticas: ni en este dispositivo ni en tu cuenta. Los contadores ya sincronizados permanecen en tu cuenta.",
"onDevice": "En este dispositivo",
+ "onDevicePrivacy": "Estas estadísticas se calculan en este dispositivo para proteger tu privacidad.",
"synced": "Sincronizado entre dispositivos",
"syncFallback": "Mostrando datos del dispositivo: sincronización no disponible",
"syncPrompt": "Sincroniza contadores sin contenido para combinar la actividad local y la de la nube entre dispositivos.",
"enableSync": "Activar sincronización",
+ "syncEnableError": "No se pudo activar la sincronización de Insights. Inténtalo de nuevo.",
"claimTitle": "¿Incluir dictados anteriores?",
- "claimDescription_one": "{{count}} dictado de este dispositivo se grabó antes de que iniciaras sesión. Al incluirlo solo se envían el recuento de palabras, la fecha y la hora exacta en que ocurrió, su duración y el tipo de modelo, nunca el contenido de las transcripciones.",
- "claimDescription_other": "{{count}} dictados de este dispositivo se grabaron antes de que iniciaras sesión. Al incluirlos solo se envían los recuentos de palabras, la fecha y la hora exacta de cada uno, las duraciones y los tipos de modelo, nunca el contenido de las transcripciones.",
+ "claimDescription_one": "Sincroniza el uso de {{count}} dictado anterior. Las transcripciones siguen siendo privadas.",
+ "claimDescription_other": "Sincroniza el uso de {{count}} dictados anteriores. Las transcripciones siguen siendo privadas.",
"claimInclude": "Incluir",
"claimSkip": "Ahora no",
"enableTitle": "¿Activar la sincronización de Insights?",
"enableConfirm": "Activar sincronización",
- "enableDescription_one": "{{count}} dictado ya grabado en este dispositivo se subirá a tu cuenta. La sincronización de Insights solo envía los recuentos de palabras, la fecha y la hora exacta de cada uno, las duraciones y los tipos de modelo, nunca el contenido de las transcripciones.",
- "enableDescription_other": "{{count}} dictados ya grabados en este dispositivo se subirán a tu cuenta. La sincronización de Insights solo envía los recuentos de palabras, la fecha y la hora exacta de cada uno, las duraciones y los tipos de modelo, nunca el contenido de las transcripciones.",
+ "enableDescription_one": "Sincroniza el uso de {{count}} dictado existente. Las transcripciones siguen siendo privadas.",
+ "enableDescription_other": "Sincroniza el uso de {{count}} dictados existentes. Las transcripciones siguen siendo privadas.",
"emptyTitle": "Aún no hay dictados",
"emptyBody": "Empieza a dictar y aquí aparecerán tus palabras, tus rachas y tu actividad diaria.",
- "loadError": "No se pudieron leer los Insights de este dispositivo."
+ "loadError": "No se pudieron leer los Insights de este dispositivo.",
+ "leaderboard": {
+ "title": "Clasificación",
+ "inviteCta": "Invitar a compañeros",
+ "soloTitle": "Invita a tu primer compañero",
+ "soloDescription": "Tu clasificación está lista. Invita a alguien a {{scope}} para empezar a comparar la actividad y avanzar juntos.",
+ "soloHint": "Aparecerá aquí cuando se una a la clasificación.",
+ "topPerformers": "Mejores clasificados",
+ "refreshCadence": "Se actualiza cada hora",
+ "moreActions": "Más acciones de la clasificación",
+ "setupTitle": "Crea la clasificación de tu equipo",
+ "setupDescription": "Crea un espacio de trabajo e invita a tus compañeros para comparar la actividad y avanzar juntos.",
+ "setupDomainDescription_one": "{{count}} persona de {{domain}} participa en las clasificaciones. Crea un espacio de trabajo e invítala.",
+ "setupDomainDescription_other": "{{count}} personas de {{domain}} participan en las clasificaciones. Crea un espacio de trabajo e invítalas.",
+ "setupCta": "Crear espacio de trabajo",
+ "accessError": "No pudimos comprobar tu acceso a la clasificación.",
+ "signInTitle": "Inicia sesión para ver tu clasificación",
+ "signInDescription": "Las clasificaciones te comparan con los compañeros de tu cuenta. Inicia sesión para comprobar si la tuya está disponible.",
+ "requestJoinTitle": "Tu equipo ya está aquí",
+ "requestJoinDescription_one": "{{workspace}} tiene {{count}} miembro. Pide a un administrador que te añada.",
+ "requestJoinDescription_other": "{{workspace}} tiene {{count}} miembros. Pide a un administrador que te añada.",
+ "requestJoinCta": "Solicitar acceso",
+ "requestSent": "Solicitud enviada",
+ "requesting": "Enviando solicitud…",
+ "acceptInviteTitle": "Te han invitado a {{workspace}}",
+ "acceptInviteDescription": "{{inviter}} te ha invitado. Únete para ver la clasificación del equipo.",
+ "acceptInviteDescriptionNoInviter": "Únete a {{workspace}} para ver la clasificación del equipo.",
+ "acceptInviteCta": "Unirse al equipo",
+ "joining": "Uniéndote…",
+ "inviteAcceptedTitle": "Te has unido al espacio de trabajo",
+ "inviteAcceptedDescription": "Ya puedes ver la clasificación de {{workspace}}.",
+ "inviteAcceptError": "No se pudo unir al espacio de trabajo",
+ "invitedList": "Invitados: {{emails}}",
+ "chooseBoard": "Elegir una clasificación",
+ "emptyStrip_one": "{{count}} compañero aún no se ha unido a la clasificación. La clasificación comenzará cuando lo haga.",
+ "emptyStrip_other": "{{count}} compañeros aún no se han unido a la clasificación. La clasificación comenzará cuando lo hagan.",
+ "copyNudge": "Copiar recordatorio",
+ "nudgeText": "Únete a la clasificación en OpenWhispr → Insights para que podamos ver la clasificación del equipo.",
+ "nudgeCopied": "Recordatorio copiado",
+ "nudgeCopyError": "No se pudo copiar el recordatorio",
+ "joinTitle": "Descubre tu posición en {{scope}}",
+ "joinDescription": "Tu nombre, correo y actividad aparecen en todas tus clasificaciones de espacios y dominios laborales. Las transcripciones son privadas y puedes salir cuando quieras.",
+ "joinCta": "Participar en las clasificaciones",
+ "joiningLeaderboard": "Uniéndote…",
+ "joinPolicyBlocked": "La política de tu espacio de trabajo no permite participar en clasificaciones.",
+ "activationError": "No pudimos verificar tu participación en la clasificación. Comprueba tu conexión e inténtalo de nuevo.",
+ "disabled": "La clasificación está desactivada",
+ "leave": "Salir de las clasificaciones",
+ "leavePending": "Terminaremos de sacarte de las clasificaciones cuando vuelvas a conectarte.",
+ "allTime": "Todo el tiempo",
+ "thisWeek": "Esta semana",
+ "wpmValue": "{{count}} PPM",
+ "dayValue_one": "{{count}} día",
+ "dayValue_other": "{{count}} días",
+ "share": "Compartir",
+ "refresh": "Actualizar clasificación",
+ "error": "No se pudo cargar la clasificación.",
+ "retry": "Intentar de nuevo",
+ "rank": "Puesto",
+ "member": "Miembro",
+ "you": "(tú)",
+ "jumpToMe": "Ir a mi puesto",
+ "jumpUnavailable": "No se pudo identificar tu cuenta en esta clasificación.",
+ "previous": "Página anterior",
+ "jumpToRank": "Ir al puesto",
+ "next": "Página siguiente",
+ "metrics": {
+ "total_words": "Palabras totales",
+ "words_per_minute": "Palabras por minuto",
+ "current_daily_streak": "Racha diaria actual",
+ "desktop_words": "Palabras en escritorio",
+ "mobile_words": "Palabras en móvil"
+ },
+ "shareText": "Mira mi posición en OpenWhispr.",
+ "shareTitle": "Compartir clasificación",
+ "shareDescription": "Copia o descarga esta tarjeta, o cópiala antes de abrir el editor de una red social.",
+ "copyImage": "Copiar imagen",
+ "download": "Descargar",
+ "shareX": "Compartir en X",
+ "shareLinkedIn": "Compartir en LinkedIn",
+ "copied": "Imagen copiada: pégala en tu publicación.",
+ "saved": "Imagen descargada.",
+ "failed": "No se pudo crear la tarjeta para compartir.",
+ "unnamedMember": "Compañero de equipo"
+ }
},
"sidebar": {
"insights": "Estadísticas",
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index c797c0a2f..3f05df531 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -2392,6 +2392,9 @@
"insightsSyncDescription": "Synchronisez le nombre de mots, la date et l'heure exacte de chaque dictée, les durées et les types de modèle entre vos appareils. Le contenu des transcriptions n'est jamais inclus. Lorsque vous êtes connecté, effacer l'historique supprime également ces compteurs de cet appareil et de votre compte.",
"insightsSyncRequiresAccount": "Connectez-vous pour synchroniser des données de Statistiques sans contenu entre vos appareils.",
"insightsSyncRequiresHistory": "Activez la conservation des données pour enregistrer les Statistiques avant de les synchroniser entre vos appareils.",
+ "leaderboardDescription": "Affichez votre nom, votre adresse e-mail et votre activité dans les classements des espaces de travail et domaines professionnels éligibles. Vos transcriptions restent privées.",
+ "leaderboardRequiresAccount": "Connectez-vous pour gérer votre participation aux classements.",
+ "leaderboardRequiresHistory": "Activez la conservation des données avant de rejoindre les classements.",
"usageAnalytics": "Analyse d'utilisation",
"usageAnalyticsDescription": "Aidez-nous à améliorer OpenWhispr en partageant des métriques de performance anonymes. Nous n'envoyons jamais le contenu de vos transcriptions — uniquement des données de performance et d'erreurs.",
"audioRetention": "Conservation de l'audio",
@@ -2720,6 +2723,7 @@
},
"insights": {
"title": "Statistiques",
+ "yourUsage": "Votre utilisation",
"description": "Une vue privée de vos habitudes de dictée et de votre régularité.",
"wordsSpoken": "Mots dictés",
"currentStreak": "Série en cours",
@@ -2740,22 +2744,108 @@
"dayTooltip_other": "{{date}} : {{count}} mots",
"dataRetentionDisabled": "La conservation des données est désactivée : les nouvelles dictées ne sont comptabilisées dans les Statistiques ni sur cet appareil ni dans votre compte. Les compteurs déjà synchronisés restent dans votre compte.",
"onDevice": "Sur cet appareil",
+ "onDevicePrivacy": "Ces statistiques sont calculées sur cet appareil afin de protéger votre vie privée.",
"synced": "Synchronisé entre les appareils",
"syncFallback": "Données de l'appareil affichées — synchronisation indisponible",
"syncPrompt": "Synchronisez des compteurs sans contenu pour combiner l'activité locale et cloud sur tous vos appareils.",
"enableSync": "Activer la synchronisation",
+ "syncEnableError": "La synchronisation d’Insights n’a pas pu être activée. Réessayez.",
"claimTitle": "Inclure les dictées antérieures ?",
- "claimDescription_one": "{{count}} dictée a été enregistrée sur cet appareil avant votre connexion. L'inclure n'envoie que le nombre de mots, la date et l'heure exacte à laquelle elle a eu lieu, sa durée et le type de modèle : jamais le contenu des transcriptions.",
- "claimDescription_other": "{{count}} dictées ont été enregistrées sur cet appareil avant votre connexion. Les inclure n'envoie que le nombre de mots, la date et l'heure exacte de chacune, les durées et les types de modèle : jamais le contenu des transcriptions.",
+ "claimDescription_one": "Synchronisez l’utilisation de {{count}} dictée antérieure. Les transcriptions restent privées.",
+ "claimDescription_other": "Synchronisez l’utilisation de {{count}} dictées antérieures. Les transcriptions restent privées.",
"claimInclude": "Inclure",
"claimSkip": "Pas maintenant",
"enableTitle": "Activer la synchronisation d'Insights ?",
"enableConfirm": "Activer la synchronisation",
- "enableDescription_one": "{{count}} dictée déjà enregistrée sur cet appareil sera envoyée vers votre compte. La synchronisation d'Insights n'envoie que le nombre de mots, la date et l'heure exacte de chacune, les durées et les types de modèle : jamais le contenu des transcriptions.",
- "enableDescription_other": "{{count}} dictées déjà enregistrées sur cet appareil seront envoyées vers votre compte. La synchronisation d'Insights n'envoie que le nombre de mots, la date et l'heure exacte de chacune, les durées et les types de modèle : jamais le contenu des transcriptions.",
+ "enableDescription_one": "Synchronisez l’utilisation de {{count}} dictée existante. Les transcriptions restent privées.",
+ "enableDescription_other": "Synchronisez l’utilisation de {{count}} dictées existantes. Les transcriptions restent privées.",
"emptyTitle": "Aucune dictée pour l'instant",
"emptyBody": "Commencez à dicter : vos mots, vos séries et votre activité quotidienne apparaîtront ici.",
- "loadError": "Impossible de lire les Insights depuis cet appareil."
+ "loadError": "Impossible de lire les Insights depuis cet appareil.",
+ "leaderboard": {
+ "title": "Classement",
+ "inviteCta": "Inviter des collègues",
+ "soloTitle": "Invitez votre premier collègue",
+ "soloDescription": "Votre classement est prêt. Invitez quelqu’un dans {{scope}} pour commencer à comparer l’activité et progresser ensemble.",
+ "soloHint": "Cette personne apparaîtra ici après avoir rejoint le classement.",
+ "topPerformers": "Meilleurs classements",
+ "refreshCadence": "Actualisé chaque heure",
+ "moreActions": "Plus d’actions du classement",
+ "setupTitle": "Créez le classement de votre équipe",
+ "setupDescription": "Créez un espace de travail, puis invitez des collègues pour comparer votre activité et progresser ensemble.",
+ "setupDomainDescription_one": "{{count}} personne chez {{domain}} participe aux classements. Créez un espace de travail et invitez-la.",
+ "setupDomainDescription_other": "{{count}} personnes chez {{domain}} participent aux classements. Créez un espace de travail et invitez-les.",
+ "setupCta": "Créer un espace de travail",
+ "accessError": "Nous n'avons pas pu vérifier votre accès au classement.",
+ "signInTitle": "Connectez-vous pour voir votre classement",
+ "signInDescription": "Les classements vous comparent aux coéquipiers de votre compte. Connectez-vous pour voir si le vôtre est disponible.",
+ "requestJoinTitle": "Votre équipe est déjà là",
+ "requestJoinDescription_one": "{{workspace}} compte {{count}} membre. Demandez à un administrateur de vous ajouter.",
+ "requestJoinDescription_other": "{{workspace}} compte {{count}} membres. Demandez à un administrateur de vous ajouter.",
+ "requestJoinCta": "Demander à rejoindre",
+ "requestSent": "Demande envoyée",
+ "requesting": "Envoi de la demande…",
+ "acceptInviteTitle": "Vous êtes invité dans {{workspace}}",
+ "acceptInviteDescription": "{{inviter}} vous a invité. Rejoignez l'espace pour voir le classement de l'équipe.",
+ "acceptInviteDescriptionNoInviter": "Rejoignez {{workspace}} pour voir le classement de l'équipe.",
+ "acceptInviteCta": "Rejoindre l’équipe",
+ "joining": "Connexion en cours…",
+ "inviteAcceptedTitle": "Espace de travail rejoint",
+ "inviteAcceptedDescription": "Vous pouvez maintenant voir le classement de {{workspace}}.",
+ "inviteAcceptError": "Impossible de rejoindre cet espace de travail",
+ "invitedList": "Invités : {{emails}}",
+ "chooseBoard": "Choisir un classement",
+ "emptyStrip_one": "{{count}} coéquipier n'a pas encore rejoint le classement. Le classement commencera ensuite.",
+ "emptyStrip_other": "{{count}} coéquipiers n'ont pas encore rejoint le classement. Le classement commencera ensuite.",
+ "copyNudge": "Copier un rappel",
+ "nudgeText": "Rejoignez le classement dans OpenWhispr → Insights pour que nous puissions voir le classement de l'équipe.",
+ "nudgeCopied": "Rappel copié",
+ "nudgeCopyError": "Impossible de copier le rappel",
+ "joinTitle": "Découvrez votre classement dans {{scope}}",
+ "joinDescription": "Votre nom, votre e-mail et votre activité figurent dans tous vos classements d’espaces et domaines professionnels. Les transcriptions restent privées et vous pouvez partir à tout moment.",
+ "joinCta": "Participer aux classements",
+ "joiningLeaderboard": "Inscription…",
+ "joinPolicyBlocked": "La politique de votre espace de travail n'autorise pas la participation aux classements.",
+ "activationError": "Nous n’avons pas pu vérifier votre participation au classement. Vérifiez votre connexion et réessayez.",
+ "disabled": "Le classement est désactivé",
+ "leave": "Quitter les classements",
+ "leavePending": "Vous quitterez les classements dès votre retour en ligne.",
+ "allTime": "Depuis toujours",
+ "thisWeek": "Cette semaine",
+ "wpmValue": "{{count}} MPM",
+ "dayValue_one": "{{count}} jour",
+ "dayValue_other": "{{count}} jours",
+ "share": "Partager",
+ "refresh": "Actualiser le classement",
+ "error": "Le classement n’a pas pu être chargé.",
+ "retry": "Réessayer",
+ "rank": "Rang",
+ "member": "Membre",
+ "you": "(vous)",
+ "jumpToMe": "Aller à mon rang",
+ "jumpUnavailable": "Votre compte n’a pas pu être identifié dans ce classement.",
+ "previous": "Page précédente",
+ "jumpToRank": "Aller au rang",
+ "next": "Page suivante",
+ "metrics": {
+ "total_words": "Nombre total de mots",
+ "words_per_minute": "Mots par minute",
+ "current_daily_streak": "Série quotidienne actuelle",
+ "desktop_words": "Mots sur ordinateur",
+ "mobile_words": "Mots sur mobile"
+ },
+ "shareText": "Découvrez mon classement sur OpenWhispr.",
+ "shareTitle": "Partager le classement",
+ "shareDescription": "Copiez ou téléchargez cette carte, ou copiez-la avant d’ouvrir un éditeur de publication.",
+ "copyImage": "Copier l’image",
+ "download": "Télécharger",
+ "shareX": "Partager sur X",
+ "shareLinkedIn": "Partager sur LinkedIn",
+ "copied": "Image copiée — collez-la dans votre publication.",
+ "saved": "Image téléchargée.",
+ "failed": "La carte de partage n’a pas pu être créée.",
+ "unnamedMember": "Coéquipier"
+ }
},
"sidebar": {
"insights": "Statistiques",
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index 13886bc37..504cadc6b 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -2103,6 +2103,9 @@
"insightsSyncDescription": "Sincronizza conteggi di parole, la data e l'ora esatta di ogni dettatura, durate e tipi di modello tra i tuoi dispositivi. Il contenuto delle trascrizioni non è mai incluso. Quando hai effettuato l'accesso, cancellare la cronologia rimuove questi conteggi anche da questo dispositivo e dal tuo account.",
"insightsSyncRequiresAccount": "Accedi per sincronizzare i dati delle Statistiche senza contenuti tra i tuoi dispositivi.",
"insightsSyncRequiresHistory": "Attiva la conservazione dei dati per registrare le Statistiche prima di sincronizzarle tra i tuoi dispositivi.",
+ "leaderboardDescription": "Mostra il tuo nome, l'indirizzo email e la tua attività nelle classifiche degli spazi di lavoro e dei domini aziendali idonei. Le trascrizioni restano private.",
+ "leaderboardRequiresAccount": "Accedi per gestire la partecipazione alle classifiche.",
+ "leaderboardRequiresHistory": "Attiva la conservazione dei dati prima di partecipare alle classifiche.",
"usageAnalytics": "Analisi dell'utilizzo",
"usageAnalyticsDescription": "Aiutaci a migliorare OpenWhispr condividendo metriche di prestazione anonime. Non inviamo mai il contenuto delle trascrizioni, solo dati su tempi ed errori.",
"dataRetention": "Conservazione dei dati",
@@ -3234,6 +3237,7 @@
},
"insights": {
"title": "Statistiche",
+ "yourUsage": "Il tuo utilizzo",
"description": "Una visione privata delle tue abitudini di dettatura e della tua costanza.",
"wordsSpoken": "Parole dettate",
"currentStreak": "Serie attuale",
@@ -3254,22 +3258,108 @@
"dayTooltip_other": "{{date}}: {{count}} parole",
"dataRetentionDisabled": "La conservazione dei dati è disattivata, quindi le nuove dettature non vengono conteggiate nelle Statistiche: né su questo dispositivo né nel tuo account. I conteggi già sincronizzati restano nel tuo account.",
"onDevice": "Su questo dispositivo",
+ "onDevicePrivacy": "Queste statistiche vengono calcolate su questo dispositivo per proteggere la tua privacy.",
"synced": "Sincronizzato tra i dispositivi",
"syncFallback": "Dati del dispositivo — sincronizzazione non disponibile",
"syncPrompt": "Sincronizza contatori senza contenuti per combinare l'attività locale e quella cloud su tutti i dispositivi.",
"enableSync": "Attiva la sincronizzazione",
+ "syncEnableError": "Non è stato possibile attivare la sincronizzazione di Insights. Riprova.",
"claimTitle": "Includere le dettature precedenti?",
- "claimDescription_one": "{{count}} dettatura è stata registrata su questo dispositivo prima dell'accesso. Includendola vengono inviati solo il conteggio delle parole, la data e l'ora esatta in cui è avvenuta, la sua durata e il tipo di modello, mai il contenuto delle trascrizioni.",
- "claimDescription_other": "{{count}} dettature sono state registrate su questo dispositivo prima dell'accesso. Includendole vengono inviati solo i conteggi delle parole, la data e l'ora esatta di ciascuna, le durate e i tipi di modello, mai il contenuto delle trascrizioni.",
+ "claimDescription_one": "Sincronizza l'utilizzo di {{count}} dettatura precedente. Le trascrizioni restano private.",
+ "claimDescription_other": "Sincronizza l'utilizzo di {{count}} dettature precedenti. Le trascrizioni restano private.",
"claimInclude": "Includi",
"claimSkip": "Non ora",
"enableTitle": "Attivare la sincronizzazione di Insights?",
"enableConfirm": "Attiva sincronizzazione",
- "enableDescription_one": "{{count}} dettatura già registrata su questo dispositivo verrà caricata sul tuo account. La sincronizzazione di Insights invia solo i conteggi delle parole, la data e l'ora esatta di ciascuna, le durate e i tipi di modello, mai il contenuto delle trascrizioni.",
- "enableDescription_other": "{{count}} dettature già registrate su questo dispositivo verranno caricate sul tuo account. La sincronizzazione di Insights invia solo i conteggi delle parole, la data e l'ora esatta di ciascuna, le durate e i tipi di modello, mai il contenuto delle trascrizioni.",
+ "enableDescription_one": "Sincronizza l'utilizzo di {{count}} dettatura esistente. Le trascrizioni restano private.",
+ "enableDescription_other": "Sincronizza l'utilizzo di {{count}} dettature esistenti. Le trascrizioni restano private.",
"emptyTitle": "Ancora nessuna dettatura",
"emptyBody": "Inizia a dettare: qui compariranno le tue parole, le serie e l'attività quotidiana.",
- "loadError": "Non è stato possibile leggere gli Insights da questo dispositivo."
+ "loadError": "Non è stato possibile leggere gli Insights da questo dispositivo.",
+ "leaderboard": {
+ "title": "Classifica",
+ "inviteCta": "Invita colleghi",
+ "soloTitle": "Invita il tuo primo collega",
+ "soloDescription": "La classifica è pronta. Invita qualcuno in {{scope}} per iniziare a confrontare l’attività e crescere insieme.",
+ "soloHint": "Apparirà qui dopo aver partecipato alla classifica.",
+ "topPerformers": "Migliori in classifica",
+ "refreshCadence": "Si aggiorna ogni ora",
+ "moreActions": "Altre azioni della classifica",
+ "setupTitle": "Crea la classifica del tuo team",
+ "setupDescription": "Crea uno spazio di lavoro e invita i colleghi per confrontare l’attività e crescere insieme.",
+ "setupDomainDescription_one": "{{count}} persona di {{domain}} partecipa alle classifiche. Crea uno spazio di lavoro e invitala.",
+ "setupDomainDescription_other": "{{count}} persone di {{domain}} partecipano alle classifiche. Crea uno spazio di lavoro e invitale.",
+ "setupCta": "Crea spazio di lavoro",
+ "accessError": "Non è stato possibile verificare l'accesso alla classifica.",
+ "signInTitle": "Accedi per vedere la tua classifica",
+ "signInDescription": "Le classifiche ti confrontano con i colleghi del tuo account. Accedi per scoprire se la tua è disponibile.",
+ "requestJoinTitle": "Il tuo team è già qui",
+ "requestJoinDescription_one": "{{workspace}} ha {{count}} membro. Chiedi a un amministratore di aggiungerti.",
+ "requestJoinDescription_other": "{{workspace}} ha {{count}} membri. Chiedi a un amministratore di aggiungerti.",
+ "requestJoinCta": "Richiedi di unirti",
+ "requestSent": "Richiesta inviata",
+ "requesting": "Invio richiesta…",
+ "acceptInviteTitle": "Hai ricevuto un invito a {{workspace}}",
+ "acceptInviteDescription": "{{inviter}} ti ha invitato. Entra per vedere la classifica del team.",
+ "acceptInviteDescriptionNoInviter": "Entra in {{workspace}} per vedere la classifica del team.",
+ "acceptInviteCta": "Unisciti al team",
+ "joining": "Accesso in corso…",
+ "inviteAcceptedTitle": "Spazio di lavoro aggiunto",
+ "inviteAcceptedDescription": "Ora puoi vedere la classifica di {{workspace}}.",
+ "inviteAcceptError": "Impossibile entrare nello spazio di lavoro",
+ "invitedList": "Invitati: {{emails}}",
+ "chooseBoard": "Scegli una classifica",
+ "emptyStrip_one": "{{count}} collega non partecipa ancora alla classifica. La classifica inizierà quando lo farà.",
+ "emptyStrip_other": "{{count}} colleghi non partecipano ancora alla classifica. La classifica inizierà quando lo faranno.",
+ "copyNudge": "Copia promemoria",
+ "nudgeText": "Partecipa alla classifica in OpenWhispr → Insights per visualizzare la classifica del team.",
+ "nudgeCopied": "Promemoria copiato",
+ "nudgeCopyError": "Impossibile copiare il promemoria",
+ "joinTitle": "Scopri la tua posizione in {{scope}}",
+ "joinDescription": "Nome, e-mail e attività compaiono in tutte le classifiche idonee dei tuoi spazi di lavoro e domini aziendali. Le trascrizioni restano private e puoi uscire in qualsiasi momento.",
+ "joinCta": "Partecipa alle classifiche",
+ "joiningLeaderboard": "Iscrizione…",
+ "joinPolicyBlocked": "I criteri del tuo spazio di lavoro non consentono di partecipare alle classifiche.",
+ "activationError": "Non è stato possibile verificare la tua partecipazione alla classifica. Controlla la connessione e riprova.",
+ "disabled": "La classifica è disattivata",
+ "leave": "Esci dalle classifiche",
+ "leavePending": "Completeremo l'uscita dalle classifiche quando tornerai online.",
+ "allTime": "Da sempre",
+ "thisWeek": "Questa settimana",
+ "wpmValue": "{{count}} PPM",
+ "dayValue_one": "{{count}} giorno",
+ "dayValue_other": "{{count}} giorni",
+ "share": "Condividi",
+ "refresh": "Aggiorna classifica",
+ "error": "Impossibile caricare la classifica.",
+ "retry": "Riprova",
+ "rank": "Posizione",
+ "member": "Membro",
+ "you": "(tu)",
+ "jumpToMe": "Vai alla mia posizione",
+ "jumpUnavailable": "Non è stato possibile identificare il tuo account in questa classifica.",
+ "previous": "Pagina precedente",
+ "jumpToRank": "Vai alla posizione",
+ "next": "Pagina successiva",
+ "metrics": {
+ "total_words": "Parole totali",
+ "words_per_minute": "Parole al minuto",
+ "current_daily_streak": "Serie giornaliera attuale",
+ "desktop_words": "Parole da desktop",
+ "mobile_words": "Parole da dispositivo mobile"
+ },
+ "shareText": "Guarda la mia posizione su OpenWhispr.",
+ "shareTitle": "Condividi classifica",
+ "shareDescription": "Copia o scarica questa scheda, oppure copiala prima di aprire l’editor di un social network.",
+ "copyImage": "Copia immagine",
+ "download": "Scarica",
+ "shareX": "Condividi su X",
+ "shareLinkedIn": "Condividi su LinkedIn",
+ "copied": "Immagine copiata — incollala nel tuo post.",
+ "saved": "Immagine scaricata.",
+ "failed": "Impossibile creare la scheda da condividere.",
+ "unnamedMember": "Compagno di squadra"
+ }
},
"sidebar": {
"insights": "Statistiche",
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index 22f11c7b9..f1d18bbe2 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -2103,6 +2103,9 @@
"insightsSyncDescription": "単語数、日付と各ディクテーションの正確な時刻、長さ、モデルの種類をデバイス間で同期します。文字起こしの内容は送信されません。サインイン中に履歴を消去すると、これらのカウントもこのデバイスとアカウントから削除されます。",
"insightsSyncRequiresAccount": "サインインすると、内容を含まない統計データをデバイス間で同期できます。",
"insightsSyncRequiresHistory": "データ保持を有効にすると統計が記録され、デバイス間で同期できるようになります。",
+ "leaderboardDescription": "対象となるワークスペースと勤務先ドメインのリーダーボードに、名前、メールアドレス、アクティビティを表示します。文字起こしは非公開のままです。",
+ "leaderboardRequiresAccount": "リーダーボードへの参加を管理するにはサインインしてください。",
+ "leaderboardRequiresHistory": "リーダーボードに参加する前にデータ保持を有効にしてください。",
"usageAnalytics": "使用状況の分析",
"usageAnalyticsDescription": "匿名のパフォーマンスデータを共有して OpenWhispr の改善にご協力ください。文字起こしの内容は送信されません。タイミングとエラーデータのみです。",
"dataRetention": "データ保持",
@@ -3234,6 +3237,7 @@
},
"insights": {
"title": "統計",
+ "yourUsage": "利用状況",
"description": "ディクテーションの習慣と継続状況をプライベートに確認できます。",
"wordsSpoken": "話した単語数",
"currentStreak": "現在の連続日数",
@@ -3254,22 +3258,108 @@
"dayTooltip_other": "{{date}}: {{count}} 語",
"dataRetentionDisabled": "データ保持が無効なため、新しいディクテーションは統計に集計されません。このデバイスでもアカウントでも加算されません。すでに同期済みのカウントはアカウントに残ります。",
"onDevice": "このデバイス上",
+ "onDevicePrivacy": "プライバシーを保護するため、これらのインサイトはこのデバイス上で計算されます。",
"synced": "デバイス間で同期済み",
"syncFallback": "デバイスのデータを表示中 — 同期は利用できません",
"syncPrompt": "内容を含まないカウンターを同期して、ローカルとクラウドのアクティビティをデバイス間でまとめます。",
"enableSync": "同期を有効にする",
+ "syncEnableError": "Insights の同期を有効にできませんでした。もう一度お試しください。",
"claimTitle": "以前のディクテーションを含めますか?",
- "claimDescription_one": "サインイン前にこのデバイスで記録されたディクテーションが {{count}} 件あります。含めると、送信されるのは単語数、日付と記録された正確な時刻、長さ、モデルの種類だけで、文字起こしの内容は送信されません。",
- "claimDescription_other": "サインイン前にこのデバイスで記録されたディクテーションが {{count}} 件あります。含めると、送信されるのは単語数、日付と記録された正確な時刻、長さ、モデルの種類だけで、文字起こしの内容は送信されません。",
+ "claimDescription_one": "以前のディクテーション {{count}} 件の利用状況を同期します。文字起こしは非公開のままです。",
+ "claimDescription_other": "以前のディクテーション {{count}} 件の利用状況を同期します。文字起こしは非公開のままです。",
"claimInclude": "含める",
"claimSkip": "今はしない",
"enableTitle": "Insights の同期をオンにしますか?",
"enableConfirm": "同期をオンにする",
- "enableDescription_one": "このデバイスで記録済みのディクテーション {{count}} 件がアカウントにアップロードされます。Insights の同期で送信されるのは単語数、日付と記録された正確な時刻、長さ、モデルの種類だけで、文字起こしの内容は送信されません。",
- "enableDescription_other": "このデバイスで記録済みのディクテーション {{count}} 件がアカウントにアップロードされます。Insights の同期で送信されるのは単語数、日付と記録された正確な時刻、長さ、モデルの種類だけで、文字起こしの内容は送信されません。",
+ "enableDescription_one": "既存のディクテーション {{count}} 件の利用状況を同期します。文字起こしは非公開のままです。",
+ "enableDescription_other": "既存のディクテーション {{count}} 件の利用状況を同期します。文字起こしは非公開のままです。",
"emptyTitle": "まだディクテーションがありません",
"emptyBody": "ディクテーションを始めると、単語数・連続記録・日々のアクティビティがここに表示されます。",
- "loadError": "このデバイスから Insights を読み取れませんでした。"
+ "loadError": "このデバイスから Insights を読み取れませんでした。",
+ "leaderboard": {
+ "title": "リーダーボード",
+ "inviteCta": "メンバーを招待",
+ "soloTitle": "最初のメンバーを招待しましょう",
+ "soloDescription": "リーダーボードの準備ができました。{{scope}} にメンバーを招待して、アクティビティの比較を始めましょう。",
+ "soloHint": "リーダーボードに参加すると、ここに表示されます。",
+ "topPerformers": "トップメンバー",
+ "refreshCadence": "1時間ごとに更新",
+ "moreActions": "ランキングのその他の操作",
+ "setupTitle": "チームのリーダーボードを作成",
+ "setupDescription": "ワークスペースを作成してメンバーを招待し、アクティビティを比較しながら一緒に成果を伸ばしましょう。",
+ "setupDomainDescription_one": "{{domain}} の {{count}} 人がリーダーボードに参加しています。ワークスペースを作成して招待しましょう。",
+ "setupDomainDescription_other": "{{domain}} の {{count}} 人がリーダーボードに参加しています。ワークスペースを作成して招待しましょう。",
+ "setupCta": "ワークスペースを作成",
+ "accessError": "リーダーボードへのアクセスを確認できませんでした。",
+ "signInTitle": "サインインしてリーダーボードを表示",
+ "signInDescription": "リーダーボードはアカウント内のチームメンバーと順位を比較します。利用できるかどうかはサインインして確認してください。",
+ "requestJoinTitle": "あなたのチームはすでに参加しています",
+ "requestJoinDescription_one": "{{workspace}} には {{count}} 人のメンバーがいます。管理者に追加を依頼してください。",
+ "requestJoinDescription_other": "{{workspace}} には {{count}} 人のメンバーがいます。管理者に追加を依頼してください。",
+ "requestJoinCta": "参加を申請",
+ "requestSent": "申請を送信しました",
+ "requesting": "申請を送信中…",
+ "acceptInviteTitle": "{{workspace}} に招待されています",
+ "acceptInviteDescription": "{{inviter}} さんから招待されました。参加してチームのリーダーボードを確認しましょう。",
+ "acceptInviteDescriptionNoInviter": "{{workspace}} に参加してチームのリーダーボードを確認しましょう。",
+ "acceptInviteCta": "チームに参加",
+ "joining": "参加中…",
+ "inviteAcceptedTitle": "ワークスペースに参加しました",
+ "inviteAcceptedDescription": "{{workspace}} のリーダーボードを表示できます。",
+ "inviteAcceptError": "ワークスペースに参加できませんでした",
+ "invitedList": "招待済み: {{emails}}",
+ "chooseBoard": "リーダーボードを選択",
+ "emptyStrip_one": "{{count}} 人のメンバーがまだリーダーボードに参加していません。参加するとランキングが始まります。",
+ "emptyStrip_other": "{{count}} 人のメンバーがまだリーダーボードに参加していません。参加するとランキングが始まります。",
+ "copyNudge": "案内をコピー",
+ "nudgeText": "チームのリーダーボードを表示するには、OpenWhispr → Insights でリーダーボードに参加してください。",
+ "nudgeCopied": "案内をコピーしました",
+ "nudgeCopyError": "案内をコピーできませんでした",
+ "joinTitle": "{{scope}} での順位を確認しましょう",
+ "joinDescription": "参加対象となるすべてのワークスペースおよび勤務先ドメインのリーダーボードに、名前、メールアドレス、アクティビティが表示されます。文字起こしは非公開で、いつでも退出できます。",
+ "joinCta": "リーダーボードに参加",
+ "joiningLeaderboard": "参加しています…",
+ "joinPolicyBlocked": "ワークスペースのポリシーによりリーダーボードへ参加できません。",
+ "activationError": "リーダーボードへの参加状況を確認できませんでした。接続を確認して、もう一度お試しください。",
+ "disabled": "リーダーボードは無効です",
+ "leave": "リーダーボードから退出",
+ "leavePending": "オンラインに戻り次第、リーダーボードからの退出を完了します。",
+ "allTime": "全期間",
+ "thisWeek": "今週",
+ "wpmValue": "{{count}} WPM",
+ "dayValue_one": "{{count}}日",
+ "dayValue_other": "{{count}}日",
+ "share": "共有",
+ "refresh": "リーダーボードを更新",
+ "error": "リーダーボードを読み込めませんでした。",
+ "retry": "再試行",
+ "rank": "順位",
+ "member": "メンバー",
+ "you": "(自分)",
+ "jumpToMe": "自分の順位へ移動",
+ "jumpUnavailable": "このリーダーボードでアカウントを特定できませんでした。",
+ "previous": "前のページ",
+ "jumpToRank": "指定順位へ移動",
+ "next": "次のページ",
+ "metrics": {
+ "total_words": "合計単語数",
+ "words_per_minute": "1分あたりの単語数",
+ "current_daily_streak": "現在の連続日数",
+ "desktop_words": "デスクトップの単語数",
+ "mobile_words": "モバイルの単語数"
+ },
+ "shareText": "OpenWhispr での私の順位をご覧ください。",
+ "shareTitle": "リーダーボードを共有",
+ "shareDescription": "このカードをコピーまたはダウンロードできます。SNS の投稿画面を開く前にコピーすることもできます。",
+ "copyImage": "画像をコピー",
+ "download": "ダウンロード",
+ "shareX": "X で共有",
+ "shareLinkedIn": "LinkedIn で共有",
+ "copied": "画像をコピーしました。投稿に貼り付けてください。",
+ "saved": "画像をダウンロードしました。",
+ "failed": "共有カードを作成できませんでした。",
+ "unnamedMember": "チームメイト"
+ }
},
"sidebar": {
"insights": "統計",
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index 0bbe7b304..62feb6b0b 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -2082,6 +2082,9 @@
"insightsSyncDescription": "Sincronize contagens de palavras, a data e a hora exata de cada ditado, durações e tipos de modelo entre seus dispositivos. O conteúdo das transcrições nunca é incluído. Quando você está conectado, limpar o histórico também remove essas contagens deste dispositivo e da sua conta.",
"insightsSyncRequiresAccount": "Entre na sua conta para sincronizar dados de Estatísticas sem conteúdo entre seus dispositivos.",
"insightsSyncRequiresHistory": "Ative a retenção de dados para registrar as Estatísticas antes de sincronizá-las entre seus dispositivos.",
+ "leaderboardDescription": "Mostre seu nome, e-mail e atividade nas classificações qualificadas de espaços de trabalho e domínios profissionais. As transcrições permanecem privadas.",
+ "leaderboardRequiresAccount": "Entre na sua conta para gerenciar sua participação nas classificações.",
+ "leaderboardRequiresHistory": "Ative a retenção de dados antes de participar das classificações.",
"usageAnalytics": "Análise de uso",
"usageAnalyticsDescription": "Ajude-nos a melhorar o OpenWhispr compartilhando métricas anônimas de desempenho. Nunca enviamos conteúdo de transcrição — apenas dados de tempo e erros.",
"dataRetention": "Retenção de dados",
@@ -3234,6 +3237,7 @@
},
"insights": {
"title": "Estatísticas",
+ "yourUsage": "Seu uso",
"description": "Uma visão privada dos seus hábitos de ditado e da sua constância.",
"wordsSpoken": "Palavras ditadas",
"currentStreak": "Sequência atual",
@@ -3254,22 +3258,108 @@
"dayTooltip_other": "{{date}}: {{count}} palavras",
"dataRetentionDisabled": "A retenção de dados está desativada, então novos ditados não são contados nas Estatísticas: nem neste dispositivo nem na sua conta. As contagens já sincronizadas permanecem na sua conta.",
"onDevice": "Neste dispositivo",
+ "onDevicePrivacy": "Estas informações são calculadas neste dispositivo para proteger sua privacidade.",
"synced": "Sincronizado entre dispositivos",
"syncFallback": "Mostrando dados do dispositivo — sincronização indisponível",
"syncPrompt": "Sincronize contadores sem conteúdo para combinar a atividade local e a da nuvem entre dispositivos.",
"enableSync": "Ativar sincronização",
+ "syncEnableError": "Não foi possível ativar a sincronização do Insights. Tente novamente.",
"claimTitle": "Incluir ditados anteriores?",
- "claimDescription_one": "{{count}} ditado foi gravado neste dispositivo antes de você entrar na conta. Ao incluí-lo, só são enviadas a contagem de palavras, a data e a hora exata em que ocorreu, sua duração e o tipo de modelo, nunca o conteúdo das transcrições.",
- "claimDescription_other": "{{count}} ditados foram gravados neste dispositivo antes de você entrar na conta. Ao incluí-los, só são enviadas as contagens de palavras, a data e a hora exata de cada um, as durações e os tipos de modelo, nunca o conteúdo das transcrições.",
+ "claimDescription_one": "Sincronize o uso de {{count}} ditado anterior. As transcrições permanecem privadas.",
+ "claimDescription_other": "Sincronize o uso de {{count}} ditados anteriores. As transcrições permanecem privadas.",
"claimInclude": "Incluir",
"claimSkip": "Agora não",
"enableTitle": "Ativar a sincronização do Insights?",
"enableConfirm": "Ativar sincronização",
- "enableDescription_one": "{{count}} ditado já gravado neste dispositivo será enviado para a sua conta. A sincronização do Insights só envia as contagens de palavras, a data e a hora exata de cada um, as durações e os tipos de modelo, nunca o conteúdo das transcrições.",
- "enableDescription_other": "{{count}} ditados já gravados neste dispositivo serão enviados para a sua conta. A sincronização do Insights só envia as contagens de palavras, a data e a hora exata de cada um, as durações e os tipos de modelo, nunca o conteúdo das transcrições.",
+ "enableDescription_one": "Sincronize o uso de {{count}} ditado existente. As transcrições permanecem privadas.",
+ "enableDescription_other": "Sincronize o uso de {{count}} ditados existentes. As transcrições permanecem privadas.",
"emptyTitle": "Ainda sem ditados",
"emptyBody": "Comece a ditar e as suas palavras, sequências e atividade diária aparecerão aqui.",
- "loadError": "Não foi possível ler os Insights deste dispositivo."
+ "loadError": "Não foi possível ler os Insights deste dispositivo.",
+ "leaderboard": {
+ "title": "Classificação",
+ "inviteCta": "Convidar colegas",
+ "soloTitle": "Convide o seu primeiro colega",
+ "soloDescription": "A sua classificação está pronta. Convide alguém para {{scope}} para começar a comparar a atividade e avançar em conjunto.",
+ "soloHint": "Essa pessoa aparecerá aqui depois de participar da classificação.",
+ "topPerformers": "Melhores classificados",
+ "refreshCadence": "Atualizado a cada hora",
+ "moreActions": "Mais ações da classificação",
+ "setupTitle": "Crie a classificação da sua equipa",
+ "setupDescription": "Crie um espaço de trabalho e convide colegas para comparar a atividade e avançar em conjunto.",
+ "setupDomainDescription_one": "{{count}} pessoa de {{domain}} participa nas classificações. Crie um espaço de trabalho e convide-a.",
+ "setupDomainDescription_other": "{{count}} pessoas de {{domain}} participam nas classificações. Crie um espaço de trabalho e convide-as.",
+ "setupCta": "Criar espaço de trabalho",
+ "accessError": "Não foi possível verificar o seu acesso à classificação.",
+ "signInTitle": "Entre para ver sua classificação",
+ "signInDescription": "As classificações comparam você com os colegas da sua conta. Entre para verificar se a sua está disponível.",
+ "requestJoinTitle": "A sua equipa já está aqui",
+ "requestJoinDescription_one": "{{workspace}} tem {{count}} membro. Peça a um administrador para o adicionar.",
+ "requestJoinDescription_other": "{{workspace}} tem {{count}} membros. Peça a um administrador para o adicionar.",
+ "requestJoinCta": "Pedir para participar",
+ "requestSent": "Pedido enviado",
+ "requesting": "A enviar pedido…",
+ "acceptInviteTitle": "Recebeu um convite para {{workspace}}",
+ "acceptInviteDescription": "{{inviter}} convidou-o. Entre para ver a classificação da equipa.",
+ "acceptInviteDescriptionNoInviter": "Entre em {{workspace}} para ver a classificação da equipa.",
+ "acceptInviteCta": "Entrar na equipe",
+ "joining": "A entrar…",
+ "inviteAcceptedTitle": "Entrou no espaço de trabalho",
+ "inviteAcceptedDescription": "Já pode ver a classificação de {{workspace}}.",
+ "inviteAcceptError": "Não foi possível entrar no espaço de trabalho",
+ "invitedList": "Convidados: {{emails}}",
+ "chooseBoard": "Escolher uma classificação",
+ "emptyStrip_one": "{{count}} colega ainda não participa da classificação. A classificação começa quando entrar.",
+ "emptyStrip_other": "{{count}} colegas ainda não participam da classificação. A classificação começa quando entrarem.",
+ "copyNudge": "Copiar lembrete",
+ "nudgeText": "Participe da classificação em OpenWhispr → Insights para podermos ver a classificação da equipa.",
+ "nudgeCopied": "Lembrete copiado",
+ "nudgeCopyError": "Não foi possível copiar o lembrete",
+ "joinTitle": "Veja sua posição em {{scope}}",
+ "joinDescription": "Seu nome, e-mail e atividade aparecem em todos os rankings elegíveis de espaços de trabalho e domínios profissionais. As transcrições permanecem privadas e você pode sair a qualquer momento.",
+ "joinCta": "Participar das classificações",
+ "joiningLeaderboard": "Entrando…",
+ "joinPolicyBlocked": "A política do seu espaço de trabalho não permite participar das classificações.",
+ "activationError": "Não foi possível verificar sua participação na classificação. Confira sua conexão e tente novamente.",
+ "disabled": "A classificação está desativada",
+ "leave": "Sair das classificações",
+ "leavePending": "Concluiremos sua saída das classificações quando você voltar a ficar online.",
+ "allTime": "Todo o período",
+ "thisWeek": "Esta semana",
+ "wpmValue": "{{count}} PPM",
+ "dayValue_one": "{{count}} dia",
+ "dayValue_other": "{{count}} dias",
+ "share": "Compartilhar",
+ "refresh": "Atualizar classificação",
+ "error": "Não foi possível carregar a classificação.",
+ "retry": "Tentar novamente",
+ "rank": "Posição",
+ "member": "Membro",
+ "you": "(você)",
+ "jumpToMe": "Ir para minha posição",
+ "jumpUnavailable": "Não foi possível identificar sua conta nesta classificação.",
+ "previous": "Página anterior",
+ "jumpToRank": "Ir para a posição",
+ "next": "Próxima página",
+ "metrics": {
+ "total_words": "Total de palavras",
+ "words_per_minute": "Palavras por minuto",
+ "current_daily_streak": "Sequência diária atual",
+ "desktop_words": "Palavras no computador",
+ "mobile_words": "Palavras no celular"
+ },
+ "shareText": "Veja minha posição no OpenWhispr.",
+ "shareTitle": "Compartilhar classificação",
+ "shareDescription": "Copie ou baixe este cartão, ou copie-o antes de abrir o editor de uma rede social.",
+ "copyImage": "Copiar imagem",
+ "download": "Baixar",
+ "shareX": "Compartilhar no X",
+ "shareLinkedIn": "Compartilhar no LinkedIn",
+ "copied": "Imagem copiada — cole-a na sua publicação.",
+ "saved": "Imagem baixada.",
+ "failed": "Não foi possível criar o cartão de compartilhamento.",
+ "unnamedMember": "Colega de equipe"
+ }
},
"sidebar": {
"insights": "Estatísticas",
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index ef1737940..a02ef1370 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -2107,6 +2107,9 @@
"insightsSyncDescription": "Синхронизируйте количество слов, дату и точное время каждой диктовки, длительность и типы моделей между устройствами. Содержимое транскрипций никогда не передаётся. Если вы вошли в аккаунт, очистка истории также удаляет эти счётчики с этого устройства и из вашего аккаунта.",
"insightsSyncRequiresAccount": "Войдите в аккаунт, чтобы синхронизировать статистику без содержимого между устройствами.",
"insightsSyncRequiresHistory": "Включите хранение данных, чтобы статистика записывалась до синхронизации между устройствами.",
+ "leaderboardDescription": "Показывайте своё имя, адрес электронной почты и активность в доступных рейтингах рабочих пространств и рабочих доменов. Транскрипции останутся конфиденциальными.",
+ "leaderboardRequiresAccount": "Войдите в аккаунт, чтобы управлять участием в рейтингах.",
+ "leaderboardRequiresHistory": "Включите хранение данных перед участием в рейтингах.",
"usageAnalytics": "Аналитика использования",
"usageAnalyticsDescription": "Помогите нам улучшить OpenWhispr, делясь анонимными метриками производительности. Мы никогда не отправляем содержимое транскрипций — только данные о времени и ошибках.",
"dataRetention": "Хранение данных",
@@ -3262,6 +3265,7 @@
},
"insights": {
"title": "Статистика",
+ "yourUsage": "Ваше использование",
"description": "Личный обзор ваших привычек диктовки и регулярности.",
"wordsSpoken": "Продиктовано слов",
"currentStreak": "Текущая серия",
@@ -3288,26 +3292,120 @@
"dayTooltip_other": "{{date}}: {{count}} слова",
"dataRetentionDisabled": "Хранение данных отключено, поэтому новые диктовки не учитываются в статистике — ни на этом устройстве, ни в вашем аккаунте. Уже синхронизированные счётчики остаются в аккаунте.",
"onDevice": "На этом устройстве",
+ "onDevicePrivacy": "Эта статистика рассчитывается на этом устройстве для защиты вашей конфиденциальности.",
"synced": "Синхронизировано между устройствами",
"syncFallback": "Показаны данные устройства — синхронизация недоступна",
"syncPrompt": "Синхронизируйте счётчики без содержимого, чтобы объединить локальную и облачную активность на всех устройствах.",
"enableSync": "Включить синхронизацию",
+ "syncEnableError": "Не удалось включить синхронизацию Insights. Повторите попытку.",
"claimTitle": "Включить прежние диктовки?",
- "claimDescription_one": "На этом устройстве до входа в аккаунт записана {{count}} диктовка. Если включить её, передаются только количество слов, дата и точное время записи, длительность и тип модели, но никогда содержимое транскрипций.",
- "claimDescription_few": "На этом устройстве до входа в аккаунт записаны {{count}} диктовки. Если включить их, передаются только количество слов, даты и точное время записи, длительность и типы моделей, но никогда содержимое транскрипций.",
- "claimDescription_many": "На этом устройстве до входа в аккаунт записано {{count}} диктовок. Если включить их, передаются только количество слов, даты и точное время записи, длительность и типы моделей, но никогда содержимое транскрипций.",
- "claimDescription_other": "На этом устройстве до входа в аккаунт записано {{count}} диктовки. Если включить их, передаются только количество слов, даты и точное время записи, длительность и типы моделей, но никогда содержимое транскрипций.",
+ "claimDescription_one": "Синхронизировать данные {{count}} прежней диктовки. Транскрипции останутся приватными.",
+ "claimDescription_few": "Синхронизировать данные {{count}} прежних диктовок. Транскрипции останутся приватными.",
+ "claimDescription_many": "Синхронизировать данные {{count}} прежних диктовок. Транскрипции останутся приватными.",
+ "claimDescription_other": "Синхронизировать данные {{count}} прежних диктовок. Транскрипции останутся приватными.",
"claimInclude": "Включить",
"claimSkip": "Не сейчас",
"enableTitle": "Включить синхронизацию Insights?",
"enableConfirm": "Включить синхронизацию",
- "enableDescription_one": "{{count}} диктовка, уже записанная на этом устройстве, будет загружена в ваш аккаунт. Синхронизация Insights передаёт только количество слов, даты и точное время записи, длительность и типы моделей, но никогда содержимое транскрипций.",
- "enableDescription_few": "{{count}} диктовки, уже записанные на этом устройстве, будут загружены в ваш аккаунт. Синхронизация Insights передаёт только количество слов, даты и точное время записи, длительность и типы моделей, но никогда содержимое транскрипций.",
- "enableDescription_many": "{{count}} диктовок, уже записанных на этом устройстве, будут загружены в ваш аккаунт. Синхронизация Insights передаёт только количество слов, даты и точное время записи, длительность и типы моделей, но никогда содержимое транскрипций.",
- "enableDescription_other": "{{count}} диктовки, уже записанные на этом устройстве, будут загружены в ваш аккаунт. Синхронизация Insights передаёт только количество слов, даты и точное время записи, длительность и типы моделей, но никогда содержимое транскрипций.",
+ "enableDescription_one": "Синхронизировать данные {{count}} существующей диктовки. Транскрипции останутся приватными.",
+ "enableDescription_few": "Синхронизировать данные {{count}} существующих диктовок. Транскрипции останутся приватными.",
+ "enableDescription_many": "Синхронизировать данные {{count}} существующих диктовок. Транскрипции останутся приватными.",
+ "enableDescription_other": "Синхронизировать данные {{count}} существующих диктовок. Транскрипции останутся приватными.",
"emptyTitle": "Диктовок пока нет",
"emptyBody": "Начните диктовать — здесь появятся ваши слова, серии и ежедневная активность.",
- "loadError": "Не удалось прочитать Insights с этого устройства."
+ "loadError": "Не удалось прочитать Insights с этого устройства.",
+ "leaderboard": {
+ "title": "Таблица лидеров",
+ "inviteCta": "Пригласить коллег",
+ "soloTitle": "Пригласите первого коллегу",
+ "soloDescription": "Рейтинг готов. Пригласите кого-нибудь в {{scope}}, чтобы начать сравнивать активность и развиваться вместе.",
+ "soloHint": "Пользователь появится здесь после присоединения к рейтингу.",
+ "topPerformers": "Лидеры",
+ "refreshCadence": "Обновляется каждый час",
+ "moreActions": "Другие действия с рейтингом",
+ "setupTitle": "Создайте рейтинг своей команды",
+ "setupDescription": "Создайте рабочее пространство и пригласите коллег, чтобы сравнивать активность и развиваться вместе.",
+ "setupDomainDescription_one": "{{count}} человек из {{domain}} участвует в рейтингах. Создайте рабочее пространство и пригласите коллег.",
+ "setupDomainDescription_few": "{{count}} человека из {{domain}} участвуют в рейтингах. Создайте рабочее пространство и пригласите коллег.",
+ "setupDomainDescription_many": "{{count}} человек из {{domain}} участвуют в рейтингах. Создайте рабочее пространство и пригласите коллег.",
+ "setupDomainDescription_other": "{{count}} человек из {{domain}} участвуют в рейтингах. Создайте рабочее пространство и пригласите их.",
+ "setupCta": "Создать рабочее пространство",
+ "accessError": "Не удалось проверить доступ к рейтингу.",
+ "signInTitle": "Войдите, чтобы увидеть таблицу лидеров",
+ "signInDescription": "Таблицы лидеров сравнивают вас с коллегами по вашей учётной записи. Войдите, чтобы проверить, доступна ли ваша.",
+ "requestJoinTitle": "Ваша команда уже здесь",
+ "requestJoinDescription_one": "В {{workspace}} {{count}} участник. Попросите администратора добавить вас.",
+ "requestJoinDescription_few": "В {{workspace}} {{count}} участника. Попросите администратора добавить вас.",
+ "requestJoinDescription_many": "В {{workspace}} {{count}} участников. Попросите администратора добавить вас.",
+ "requestJoinDescription_other": "В {{workspace}} {{count}} участников. Попросите администратора добавить вас.",
+ "requestJoinCta": "Запросить вступление",
+ "requestSent": "Запрос отправлен",
+ "requesting": "Запрос отправляется…",
+ "acceptInviteTitle": "Вас пригласили в {{workspace}}",
+ "acceptInviteDescription": "{{inviter}} пригласил вас. Присоединитесь, чтобы увидеть рейтинг команды.",
+ "acceptInviteDescriptionNoInviter": "Присоединитесь к {{workspace}}, чтобы увидеть рейтинг команды.",
+ "acceptInviteCta": "Присоединиться к команде",
+ "joining": "Присоединение…",
+ "inviteAcceptedTitle": "Вы присоединились к рабочему пространству",
+ "inviteAcceptedDescription": "Теперь вам доступен рейтинг {{workspace}}.",
+ "inviteAcceptError": "Не удалось присоединиться к рабочему пространству",
+ "invitedList": "Приглашены: {{emails}}",
+ "chooseBoard": "Выберите рейтинг",
+ "emptyStrip_one": "{{count}} коллега ещё не присоединился к рейтингу. После этого начнётся рейтинг.",
+ "emptyStrip_few": "{{count}} коллеги ещё не присоединились к рейтингу. После этого начнётся рейтинг.",
+ "emptyStrip_many": "{{count}} коллег ещё не присоединились к рейтингу. После этого начнётся рейтинг.",
+ "emptyStrip_other": "{{count}} коллег ещё не присоединились к рейтингу. После этого начнётся рейтинг.",
+ "copyNudge": "Скопировать напоминание",
+ "nudgeText": "Присоединитесь к рейтингу в OpenWhispr → Insights, чтобы мы могли увидеть рейтинг команды.",
+ "nudgeCopied": "Напоминание скопировано",
+ "nudgeCopyError": "Не удалось скопировать напоминание",
+ "joinTitle": "Узнайте своё место в {{scope}}",
+ "joinDescription": "Ваше имя, электронная почта и активность видны во всех доступных рейтингах рабочих пространств и рабочих доменов. Транскрипции остаются приватными, а выйти можно в любое время.",
+ "joinCta": "Участвовать в рейтингах",
+ "joiningLeaderboard": "Подключаем…",
+ "joinPolicyBlocked": "Политика рабочего пространства не разрешает участие в рейтингах.",
+ "activationError": "Не удалось проверить ваше участие в таблице лидеров. Проверьте подключение и повторите попытку.",
+ "disabled": "Таблица лидеров отключена",
+ "leave": "Выйти из рейтингов",
+ "leavePending": "Мы завершим выход из рейтингов, когда вы снова будете онлайн.",
+ "allTime": "За всё время",
+ "thisWeek": "Эта неделя",
+ "wpmValue": "{{count}} сл./мин",
+ "dayValue_one": "{{count}} день",
+ "dayValue_few": "{{count}} дня",
+ "dayValue_many": "{{count}} дней",
+ "dayValue_other": "{{count}} дня",
+ "share": "Поделиться",
+ "refresh": "Обновить таблицу лидеров",
+ "error": "Не удалось загрузить таблицу лидеров.",
+ "retry": "Повторить",
+ "rank": "Место",
+ "member": "Участник",
+ "you": "(вы)",
+ "jumpToMe": "Перейти к себе",
+ "jumpUnavailable": "Не удалось найти ваш аккаунт в этой таблице лидеров.",
+ "previous": "Предыдущая страница",
+ "jumpToRank": "Перейти к месту",
+ "next": "Следующая страница",
+ "metrics": {
+ "total_words": "Всего слов",
+ "words_per_minute": "Слов в минуту",
+ "current_daily_streak": "Текущая серия дней",
+ "desktop_words": "Слова на компьютере",
+ "mobile_words": "Слова на мобильном"
+ },
+ "shareText": "Посмотрите на мое место в рейтинге OpenWhispr.",
+ "shareTitle": "Поделиться таблицей лидеров",
+ "shareDescription": "Скопируйте или скачайте эту карточку либо скопируйте её перед открытием редактора публикации.",
+ "copyImage": "Скопировать изображение",
+ "download": "Скачать",
+ "shareX": "Поделиться в X",
+ "shareLinkedIn": "Поделиться в LinkedIn",
+ "copied": "Изображение скопировано — вставьте его в публикацию.",
+ "saved": "Изображение скачано.",
+ "failed": "Не удалось создать карточку для публикации.",
+ "unnamedMember": "Участник команды"
+ }
},
"sidebar": {
"insights": "Статистика",
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index 2f5de05df..90d1ed054 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -2103,6 +2103,9 @@
"insightsSyncDescription": "在你的设备之间同步字数、每次听写的日期和精确时间、时长和模型类型。转录内容永远不会包含在内。登录后清除历史记录,也会从此设备和你的账户中删除这些统计数据。",
"insightsSyncRequiresAccount": "登录后即可在设备之间同步不含内容的统计数据。",
"insightsSyncRequiresHistory": "开启数据保留后才会记录统计,之后才能跨设备同步。",
+ "leaderboardDescription": "在符合条件的工作区和工作域排行榜中显示你的姓名、电子邮件和活动。转录内容保持私密。",
+ "leaderboardRequiresAccount": "登录后即可管理排行榜参与状态。",
+ "leaderboardRequiresHistory": "加入排行榜前,请先开启数据保留。",
"usageAnalytics": "使用分析",
"usageAnalyticsDescription": "通过分享匿名性能数据帮助我们改进 OpenWhispr。我们绝不发送转录内容——仅发送计时和错误数据。",
"dataRetention": "数据保留",
@@ -3234,6 +3237,7 @@
},
"insights": {
"title": "统计",
+ "yourUsage": "你的使用情况",
"description": "私密查看你的听写习惯与坚持情况。",
"wordsSpoken": "已听写字数",
"currentStreak": "当前连续天数",
@@ -3254,22 +3258,108 @@
"dayTooltip_other": "{{date}}:{{count}} 字",
"dataRetentionDisabled": "数据保留已关闭,因此新的听写不会计入统计——本设备和你的账户都不会计数。已同步的计数会保留在你的账户中。",
"onDevice": "仅在本设备",
+ "onDevicePrivacy": "这些分析数据会在此设备上计算,以保护你的隐私。",
"synced": "已跨设备同步",
"syncFallback": "正在显示本设备数据 — 同步不可用",
"syncPrompt": "同步不含内容的计数,将本地与云端的活动跨设备合并。",
"enableSync": "启用同步",
+ "syncEnableError": "无法启用 Insights 同步。请重试。",
"claimTitle": "包含更早的听写吗?",
- "claimDescription_one": "本设备上有 {{count}} 次听写是在你登录前记录的。将其纳入只会发送字数、记录的日期和精确时间、时长和模型类型,不会发送转录内容。",
- "claimDescription_other": "本设备上有 {{count}} 次听写是在你登录前记录的。将它们纳入只会发送字数、记录的日期和精确时间、时长和模型类型,不会发送转录内容。",
+ "claimDescription_one": "同步 {{count}} 条较早听写的使用数据。转录内容保持私密。",
+ "claimDescription_other": "同步 {{count}} 条较早听写的使用数据。转录内容保持私密。",
"claimInclude": "包含",
"claimSkip": "暂不开启",
"enableTitle": "要开启 Insights 同步吗?",
"enableConfirm": "开启同步",
- "enableDescription_one": "本设备上已记录的 {{count}} 次听写将上传到你的账户。Insights 同步只会发送字数、记录的日期和精确时间、时长和模型类型,不会发送转录内容。",
- "enableDescription_other": "本设备上已记录的 {{count}} 次听写将上传到你的账户。Insights 同步只会发送字数、记录的日期和精确时间、时长和模型类型,不会发送转录内容。",
+ "enableDescription_one": "同步 {{count}} 条现有听写的使用数据。转录内容保持私密。",
+ "enableDescription_other": "同步 {{count}} 条现有听写的使用数据。转录内容保持私密。",
"emptyTitle": "还没有听写记录",
"emptyBody": "开始听写后,你的字数、连续记录和每日活动会显示在这里。",
- "loadError": "无法从本设备读取 Insights。"
+ "loadError": "无法从本设备读取 Insights。",
+ "leaderboard": {
+ "title": "排行榜",
+ "inviteCta": "邀请同事",
+ "soloTitle": "邀请第一位同事",
+ "soloDescription": "排行榜已准备就绪。邀请同事加入 {{scope}},即可开始比较活动数据、共同进步。",
+ "soloHint": "对方加入排行榜后会显示在这里。",
+ "topPerformers": "领先成员",
+ "refreshCadence": "每小时更新",
+ "moreActions": "更多排行榜操作",
+ "setupTitle": "创建团队排行榜",
+ "setupDescription": "创建工作区并邀请同事,以便比较活动数据、共同取得进步。",
+ "setupDomainDescription_one": "{{domain}} 有 {{count}} 人加入了排行榜。创建工作区并邀请对方吧。",
+ "setupDomainDescription_other": "{{domain}} 有 {{count}} 人加入了排行榜。创建工作区并邀请他们吧。",
+ "setupCta": "创建工作区",
+ "accessError": "无法检查你的排行榜访问权限。",
+ "signInTitle": "登录以查看排行榜",
+ "signInDescription": "排行榜会将你与账户中的团队成员进行对比。登录即可查看你的排行榜是否可用。",
+ "requestJoinTitle": "你的团队已在这里",
+ "requestJoinDescription_one": "{{workspace}} 有 {{count}} 名成员。请联系管理员将你加入工作区。",
+ "requestJoinDescription_other": "{{workspace}} 有 {{count}} 名成员。请联系管理员将你加入工作区。",
+ "requestJoinCta": "申请加入",
+ "requestSent": "申请已发送",
+ "requesting": "正在发送申请…",
+ "acceptInviteTitle": "你已受邀加入 {{workspace}}",
+ "acceptInviteDescription": "{{inviter}} 邀请了你。加入后即可查看团队排行榜。",
+ "acceptInviteDescriptionNoInviter": "加入 {{workspace}} 后即可查看团队排行榜。",
+ "acceptInviteCta": "加入团队",
+ "joining": "正在加入…",
+ "inviteAcceptedTitle": "已加入工作区",
+ "inviteAcceptedDescription": "你现在可以查看 {{workspace}} 的排行榜。",
+ "inviteAcceptError": "无法加入此工作区",
+ "invitedList": "已邀请:{{emails}}",
+ "chooseBoard": "选择排行榜",
+ "emptyStrip_one": "还有 {{count}} 位队友未加入排行榜。加入后即可开始排名。",
+ "emptyStrip_other": "还有 {{count}} 位队友未加入排行榜。加入后即可开始排名。",
+ "copyNudge": "复制提醒",
+ "nudgeText": "请在 OpenWhispr → Insights 中加入排行榜,这样我们就能查看团队排行榜。",
+ "nudgeCopied": "提醒已复制",
+ "nudgeCopyError": "无法复制提醒",
+ "joinTitle": "查看你在 {{scope}} 中的排名",
+ "joinDescription": "你的姓名、电子邮件和活动会显示在所有符合条件的工作区和工作域名排行榜中。转录内容保持私密,你可以随时退出。",
+ "joinCta": "加入排行榜",
+ "joiningLeaderboard": "正在加入…",
+ "joinPolicyBlocked": "你的工作区政策不允许加入排行榜。",
+ "activationError": "无法验证你的排行榜参与状态。请检查网络连接后重试。",
+ "disabled": "排行榜已停用",
+ "leave": "退出排行榜",
+ "leavePending": "恢复在线后,我们会完成退出排行榜。",
+ "allTime": "全部时间",
+ "thisWeek": "本周",
+ "wpmValue": "{{count}} 词/分钟",
+ "dayValue_one": "{{count}} 天",
+ "dayValue_other": "{{count}} 天",
+ "share": "分享",
+ "refresh": "刷新排行榜",
+ "error": "无法加载排行榜。",
+ "retry": "重试",
+ "rank": "排名",
+ "member": "成员",
+ "you": "(你)",
+ "jumpToMe": "跳到我的排名",
+ "jumpUnavailable": "无法在此排行榜中识别你的账户。",
+ "previous": "上一页",
+ "jumpToRank": "跳到指定排名",
+ "next": "下一页",
+ "metrics": {
+ "total_words": "总字数",
+ "words_per_minute": "每分钟字数",
+ "current_daily_streak": "当前连续天数",
+ "desktop_words": "桌面端字数",
+ "mobile_words": "移动端字数"
+ },
+ "shareText": "看看我在 OpenWhispr 上的排名。",
+ "shareTitle": "分享排行榜",
+ "shareDescription": "复制或下载此卡片,也可以在打开社交平台发帖页面前先复制。",
+ "copyImage": "复制图片",
+ "download": "下载",
+ "shareX": "分享到 X",
+ "shareLinkedIn": "分享到 LinkedIn",
+ "copied": "图片已复制,请粘贴到帖子中。",
+ "saved": "图片已下载。",
+ "failed": "无法创建分享卡片。",
+ "unnamedMember": "团队成员"
+ }
},
"sidebar": {
"insights": "统计",
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index bf1f4626e..0b79050b6 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -2103,6 +2103,9 @@
"insightsSyncDescription": "在你的裝置之間同步字數、每次聽寫的日期與精確時間、時長與模型類型。轉錄內容永遠不會包含在內。登入後清除記錄,也會從此裝置和你的帳戶中刪除這些統計資料。",
"insightsSyncRequiresAccount": "登入後即可在裝置之間同步不含內容的統計資料。",
"insightsSyncRequiresHistory": "開啟資料保留後才會記錄統計,之後才能跨裝置同步。",
+ "leaderboardDescription": "在符合條件的工作區與工作網域排行榜中顯示你的姓名、電子郵件和活動。轉錄內容維持私密。",
+ "leaderboardRequiresAccount": "登入後即可管理排行榜參與狀態。",
+ "leaderboardRequiresHistory": "加入排行榜前,請先開啟資料保留。",
"usageAnalytics": "使用分析",
"usageAnalyticsDescription": "分享匿名的效能指標,協助我們改善 OpenWhispr。我們絕不會傳送轉錄內容——只有計時和錯誤資料。",
"dataRetention": "資料保留",
@@ -3234,6 +3237,7 @@
},
"insights": {
"title": "統計",
+ "yourUsage": "你的使用情況",
"description": "私密檢視你的聽寫習慣與持續狀況。",
"wordsSpoken": "已聽寫字數",
"currentStreak": "目前連續天數",
@@ -3254,22 +3258,108 @@
"dayTooltip_other": "{{date}}:{{count}} 字",
"dataRetentionDisabled": "資料保留已關閉,因此新的聽寫不會計入統計——本裝置和你的帳戶都不會計數。已同步的計數會保留在你的帳戶中。",
"onDevice": "僅在本裝置",
+ "onDevicePrivacy": "這些分析資料會在此裝置上計算,以保護你的隱私。",
"synced": "已跨裝置同步",
"syncFallback": "正在顯示本裝置資料 — 同步無法使用",
"syncPrompt": "同步不含內容的計數,將本機與雲端的活動跨裝置合併。",
"enableSync": "啟用同步",
+ "syncEnableError": "無法啟用 Insights 同步。請再試一次。",
"claimTitle": "要包含較早的聽寫嗎?",
- "claimDescription_one": "本裝置上有 {{count}} 次聽寫是在你登入前記錄的。納入後只會傳送字數、記錄的日期與精確時間、時長與模型類型,不會傳送轉錄內容。",
- "claimDescription_other": "本裝置上有 {{count}} 次聽寫是在你登入前記錄的。納入後只會傳送字數、記錄的日期與精確時間、時長與模型類型,不會傳送轉錄內容。",
+ "claimDescription_one": "同步 {{count}} 則較早聽寫的使用資料。轉錄內容保持私密。",
+ "claimDescription_other": "同步 {{count}} 則較早聽寫的使用資料。轉錄內容保持私密。",
"claimInclude": "包含",
"claimSkip": "暫不開啟",
"enableTitle": "要開啟 Insights 同步嗎?",
"enableConfirm": "開啟同步",
- "enableDescription_one": "本裝置上已記錄的 {{count}} 次聽寫將上傳到你的帳戶。Insights 同步只會傳送字數、記錄的日期與精確時間、時長與模型類型,不會傳送轉錄內容。",
- "enableDescription_other": "本裝置上已記錄的 {{count}} 次聽寫將上傳到你的帳戶。Insights 同步只會傳送字數、記錄的日期與精確時間、時長與模型類型,不會傳送轉錄內容。",
+ "enableDescription_one": "同步 {{count}} 則現有聽寫的使用資料。轉錄內容保持私密。",
+ "enableDescription_other": "同步 {{count}} 則現有聽寫的使用資料。轉錄內容保持私密。",
"emptyTitle": "尚無聽寫記錄",
"emptyBody": "開始聽寫後,你的字數、連續記錄與每日活動會顯示在這裡。",
- "loadError": "無法從本裝置讀取 Insights。"
+ "loadError": "無法從本裝置讀取 Insights。",
+ "leaderboard": {
+ "title": "排行榜",
+ "inviteCta": "邀請同事",
+ "soloTitle": "邀請第一位同事",
+ "soloDescription": "排行榜已準備就緒。邀請同事加入 {{scope}},即可開始比較活動資料、一起累積成果。",
+ "soloHint": "對方加入排行榜後會顯示在這裡。",
+ "topPerformers": "領先成員",
+ "refreshCadence": "每小時更新",
+ "moreActions": "更多排行榜操作",
+ "setupTitle": "建立團隊排行榜",
+ "setupDescription": "建立工作區並邀請同事,以便比較活動資料、一起累積成果。",
+ "setupDomainDescription_one": "{{domain}} 有 {{count}} 人加入了排行榜。建立工作區並邀請對方吧。",
+ "setupDomainDescription_other": "{{domain}} 有 {{count}} 人加入了排行榜。建立工作區並邀請他們吧。",
+ "setupCta": "建立工作區",
+ "accessError": "無法檢查你的排行榜存取權限。",
+ "signInTitle": "登入以查看排行榜",
+ "signInDescription": "排行榜會將你與帳戶中的團隊成員進行比較。登入即可查看你的排行榜是否可用。",
+ "requestJoinTitle": "你的團隊已在這裡",
+ "requestJoinDescription_one": "{{workspace}} 有 {{count}} 名成員。請聯絡管理員將你加入工作區。",
+ "requestJoinDescription_other": "{{workspace}} 有 {{count}} 名成員。請聯絡管理員將你加入工作區。",
+ "requestJoinCta": "申請加入",
+ "requestSent": "申請已傳送",
+ "requesting": "正在傳送申請…",
+ "acceptInviteTitle": "你已受邀加入 {{workspace}}",
+ "acceptInviteDescription": "{{inviter}} 邀請了你。加入後即可查看團隊排行榜。",
+ "acceptInviteDescriptionNoInviter": "加入 {{workspace}} 後即可查看團隊排行榜。",
+ "acceptInviteCta": "加入團隊",
+ "joining": "正在加入…",
+ "inviteAcceptedTitle": "已加入工作區",
+ "inviteAcceptedDescription": "你現在可以查看 {{workspace}} 的排行榜。",
+ "inviteAcceptError": "無法加入此工作區",
+ "invitedList": "已邀請:{{emails}}",
+ "chooseBoard": "選擇排行榜",
+ "emptyStrip_one": "還有 {{count}} 位隊友尚未加入排行榜。加入後即可開始排名。",
+ "emptyStrip_other": "還有 {{count}} 位隊友尚未加入排行榜。加入後即可開始排名。",
+ "copyNudge": "複製提醒",
+ "nudgeText": "請在 OpenWhispr → Insights 中加入排行榜,這樣我們就能查看團隊排行榜。",
+ "nudgeCopied": "提醒已複製",
+ "nudgeCopyError": "無法複製提醒",
+ "joinTitle": "查看你在 {{scope}} 中的排名",
+ "joinDescription": "你的姓名、電子郵件與活動會顯示在所有符合條件的工作區和工作網域排行榜中。轉錄內容保持私密,你可以隨時退出。",
+ "joinCta": "加入排行榜",
+ "joiningLeaderboard": "正在加入…",
+ "joinPolicyBlocked": "你的工作區政策不允許加入排行榜。",
+ "activationError": "無法驗證你的排行榜參與狀態。請檢查網路連線後再試一次。",
+ "disabled": "排行榜已停用",
+ "leave": "退出排行榜",
+ "leavePending": "恢復連線後,我們會完成退出排行榜。",
+ "allTime": "全部時間",
+ "thisWeek": "本週",
+ "wpmValue": "{{count}} 字/分鐘",
+ "dayValue_one": "{{count}} 天",
+ "dayValue_other": "{{count}} 天",
+ "share": "分享",
+ "refresh": "重新整理排行榜",
+ "error": "無法載入排行榜。",
+ "retry": "再試一次",
+ "rank": "排名",
+ "member": "成員",
+ "you": "(你)",
+ "jumpToMe": "跳至我的排名",
+ "jumpUnavailable": "無法在此排行榜中識別你的帳戶。",
+ "previous": "上一頁",
+ "jumpToRank": "跳至指定排名",
+ "next": "下一頁",
+ "metrics": {
+ "total_words": "總字數",
+ "words_per_minute": "每分鐘字數",
+ "current_daily_streak": "目前連續天數",
+ "desktop_words": "桌面版字數",
+ "mobile_words": "行動版字數"
+ },
+ "shareText": "看看我在 OpenWhispr 上的排名。",
+ "shareTitle": "分享排行榜",
+ "shareDescription": "複製或下載此卡片,也可以在開啟社群貼文編輯器前先複製。",
+ "copyImage": "複製圖片",
+ "download": "下載",
+ "shareX": "分享到 X",
+ "shareLinkedIn": "分享到 LinkedIn",
+ "copied": "圖片已複製,請貼到你的貼文中。",
+ "saved": "圖片已下載。",
+ "failed": "無法建立分享卡片。",
+ "unnamedMember": "團隊成員"
+ }
},
"sidebar": {
"insights": "統計",
diff --git a/src/services/AnalyticsService.ts b/src/services/AnalyticsService.ts
index 2fd8b260f..c91590faa 100644
--- a/src/services/AnalyticsService.ts
+++ b/src/services/AnalyticsService.ts
@@ -1,5 +1,16 @@
-import { cloudDelete, cloudGet, cloudPost, isAuthContextError } from "./cloudApi";
-import type { AnalyticsSummary, PendingAnalyticsEvent } from "../types/electron";
+import {
+ cloudDelete,
+ cloudDeleteForAuthGeneration,
+ cloudGet,
+ cloudPost,
+ cloudPostForAuthGeneration,
+ isAuthContextError,
+} from "./cloudApi";
+import type {
+ AnalyticsSummary,
+ AnalyticsSyncContext,
+ PendingAnalyticsEvent,
+} from "../types/electron";
const BATCH_SIZE = 200;
export const ANALYTICS_SUMMARY_REFRESH_INTERVAL_MS = 5 * 60 * 1000;
@@ -91,27 +102,53 @@ export function subscribeToAnalyticsRefresh(
};
}
-async function pushAnalyticsDeletes(): Promise<void> {
+async function deleteFromCloud(
+ path: string,
+ body: unknown,
+ context?: AnalyticsSyncContext
+): Promise<void> {
+ if (context) {
+ await cloudDeleteForAuthGeneration(path, body, context.authGeneration);
+ return;
+ }
+ await cloudDelete(path, body);
+}
+
+async function postToCloud<T>(
+ path: string,
+ body: unknown,
+ context?: AnalyticsSyncContext
+): Promise<T> {
+ return context
+ ? cloudPostForAuthGeneration<T>(path, body, context.authGeneration)
+ : cloudPost<T>(path, body);
+}
+
+async function pushAnalyticsDeletes(context?: AnalyticsSyncContext): Promise<void> {
while (true) {
- const pending = await window.electronAPI.getPendingAnalyticsDeletes(BATCH_SIZE);
+ const pending = await window.electronAPI.getPendingAnalyticsDeletes(BATCH_SIZE, context);
if (pending.length === 0) return;
const eventIds = pending.map((row) => row.event_id);
- await cloudDelete("/api/analytics/events/delete", { eventIds });
- await window.electronAPI.hardDeleteAnalyticsEvents(eventIds);
+ await deleteFromCloud("/api/analytics/events/delete", { eventIds }, context);
+ await window.electronAPI.hardDeleteAnalyticsEvents(eventIds, context);
if (pending.length < BATCH_SIZE) return;
}
}
-async function pushAnalyticsClear(): Promise<void> {
- const pending = await window.electronAPI.getPendingAnalyticsClear();
+async function pushAnalyticsClear(context?: AnalyticsSyncContext): Promise<void> {
+ const pending = await window.electronAPI.getPendingAnalyticsClear(context);
if (!pending) return;
- await cloudDelete("/api/analytics/events/delete", {
- deleteAll: true,
- clearedThrough: pending.cleared_through,
- });
- await window.electronAPI.completeAnalyticsClear(pending.cleared_through);
+ await deleteFromCloud(
+ "/api/analytics/events/delete",
+ {
+ deleteAll: true,
+ clearedThrough: pending.cleared_through,
+ },
+ context
+ );
+ await window.electronAPI.completeAnalyticsClear(pending.cleared_through, context);
}
// Erasures and uploads are independent work that happens to share a pass. A
@@ -135,7 +172,13 @@ async function runStage(name: string, stage: () => Promise<void>): Promise<void>
// coalescing keeps a caller that may upload from joining one that may not.
let passQueue: Promise<unknown> = Promise.resolve();
-export function syncPendingAnalytics(options: { uploadAllowed?: boolean } = {}): Promise<number> {
+type AnalyticsUploadGate = boolean | (() => boolean | Promise<boolean>);
+interface AnalyticsSyncOptions {
+ uploadAllowed?: AnalyticsUploadGate;
+ context?: AnalyticsSyncContext;
+}
+
+export function syncPendingAnalytics(options: AnalyticsSyncOptions = {}): Promise<number> {
const pass = passQueue.then(
() => runAnalyticsPass(options),
() => runAnalyticsPass(options)
@@ -146,12 +189,18 @@ export function syncPendingAnalytics(options: { uploadAllowed?: boolean } = {}):
async function runAnalyticsPass({
uploadAllowed = true,
-}: { uploadAllowed?: boolean } = {}): Promise<number> {
+ context,
+}: AnalyticsSyncOptions = {}): Promise<number> {
// Erasures still go first, so a clear cannot race an older batch and
// recreate data the user asked us to erase.
- await runStage("clear", pushAnalyticsClear);
- await runStage("deletes", pushAnalyticsDeletes);
- if (!uploadAllowed) return 0;
+ await runStage("clear", () => pushAnalyticsClear(context));
+ await runStage("deletes", () => pushAnalyticsDeletes(context));
+ // Resolve functions only after this pass reaches the head of passQueue.
+ // Consent can be revoked while an earlier pass is still running, so queuing
+ // an already-resolved `true` would let the delayed pass upload afterward.
+ const canUpload = async (): Promise<boolean> =>
+ typeof uploadAllowed === "function" ? uploadAllowed() : uploadAllowed;
+ if (!(await canUpload())) return 0;
let synced = 0;
// Ids this pass has already offered. The server deliberately withholds rows
@@ -161,8 +210,13 @@ async function runAnalyticsPass({
const offered = new Set<string>();
while (true) {
- const events: PendingAnalyticsEvent[] =
- await window.electronAPI.getPendingAnalyticsEvents(BATCH_SIZE);
+ // Re-check between batches. Revoking consent while a >200-row drain is in
+ // flight cannot cancel the active request, but it must stop the next one.
+ if (!(await canUpload())) return synced;
+ const events: PendingAnalyticsEvent[] = await window.electronAPI.getPendingAnalyticsEvents(
+ BATCH_SIZE,
+ context
+ );
const fresh = events.filter((event) => !offered.has(event.event_id));
if (fresh.length === 0) return synced;
for (const event of fresh) offered.add(event.event_id);
@@ -174,12 +228,15 @@ async function runAnalyticsPass({
// deriving it from the sibling `rejected` field -- would leave a row that
// can never validate at the head of the queue forever. A batch the server
// refuses outright throws and stays pending for the next pass.
- const result = await cloudPost<{ accepted: string[] }>("/api/analytics/events/batch", {
- events: fresh,
- });
+ if (!(await canUpload())) return synced;
+ const result = await postToCloud<{ accepted: string[] }>(
+ "/api/analytics/events/batch",
+ { events: fresh },
+ context
+ );
const accepted = Array.isArray(result?.accepted) ? result.accepted : [];
- const { updated } = await window.electronAPI.markAnalyticsEventsSynced(accepted);
+ const { updated } = await window.electronAPI.markAnalyticsEventsSynced(accepted, context);
synced += updated;
// The whole queue fit in one read, so there is nothing behind this batch.
if (events.length < BATCH_SIZE) return synced;
@@ -237,10 +294,11 @@ function isAnalyticsSummary(value: unknown): value is AnalyticsSummary {
);
}
-export async function getAccountAnalyticsSummary(timeZone: string): Promise<AnalyticsSummary> {
- const summary = await cloudGet<unknown>(
- `/api/analytics/summary?timeZone=${encodeURIComponent(timeZone)}`
- );
+export async function getAccountAnalyticsSummary(): Promise<AnalyticsSummary> {
+ const params = new URLSearchParams({
+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC",
+ });
+ const summary = await cloudGet<unknown>(`/api/analytics/summary?${params}`);
// The cloud is an untrusted JSON boundary. Invalid buckets crash Heatmap
// during render, outside the caller's async fallback, so validate the whole
// shape before any part of it reaches component state.
diff --git a/src/services/LeaderboardService.ts b/src/services/LeaderboardService.ts
new file mode 100644
index 000000000..6088d2191
--- /dev/null
+++ b/src/services/LeaderboardService.ts
@@ -0,0 +1,437 @@
+import type {
+ AnalyticsParticipation,
+ Leaderboard,
+ LeaderboardAccess,
+ LeaderboardAccessScope,
+ LeaderboardMetric,
+ LeaderboardRange,
+} from "../types/electron";
+import {
+ clearPendingLeaderboardLeave,
+ readPendingLeaderboardLeave,
+ recordPendingLeaderboardLeaveAttempt,
+ writePendingLeaderboardLeave,
+} from "../lib/pendingLeaderboardLeave";
+import {
+ getAuthRequestContextSnapshot,
+ getValidatedAuthGeneration,
+} from "../lib/authRequestContext";
+import {
+ cloudGet,
+ cloudGetForAuthGeneration,
+ cloudPatchForAuthGeneration,
+ CloudApiError,
+} from "./cloudApi";
+
+export interface LeaderboardParticipationAuthContext {
+ userId: string;
+ authGeneration: number;
+}
+
+// The API lists 52 weeks of history plus the current week when it has no rows
+// of its own, so anything longer is not a board this client can have asked for.
+const LEADERBOARD_MAX_WEEK_STARTS = 53;
+
+// The refresh window drives setInterval, which silently clamps a delay past a
+// signed 32-bit millisecond count to 1ms — turning an implausible value into a
+// request loop against an endpoint that re-aggregates the roster on every call.
+const LEADERBOARD_MAX_REFRESH_SECONDS = 86_400;
+
+const LEADERBOARD_METRICS = new Set<LeaderboardMetric>([
+ "total_words",
+ "words_per_minute",
+ "current_daily_streak",
+ "desktop_words",
+ "mobile_words",
+]);
+const LEADERBOARD_ACCESS_STATES = new Set([
+ "ready",
+ "invite",
+ "accept_invite",
+ "request_join",
+ "create",
+]);
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function isNullableString(value: unknown): value is string | null {
+ return value === null || typeof value === "string";
+}
+
+function isNonnegativeInteger(value: unknown): value is number {
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
+}
+
+// The week picker formats these with Intl in the render body, where an
+// unparseable value throws past every async fallback. "Is a string" is not
+// enough: the round trip also rejects a well-shaped day that does not exist.
+function isCalendarDate(value: unknown): value is string {
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
+ const parsed = new Date(`${value}T00:00:00.000Z`);
+ return Number.isFinite(parsed.getTime()) && parsed.toISOString().slice(0, 10) === value;
+}
+
+function responseData(value: unknown, label: string): unknown {
+ if (!isRecord(value) || !("data" in value)) {
+ throw new Error(`Malformed ${label} response from cloud`);
+ }
+ return value.data;
+}
+
+function isParticipation(value: unknown): value is AnalyticsParticipation {
+ return (
+ isRecord(value) &&
+ typeof value.configured === "boolean" &&
+ typeof value.enabled === "boolean" &&
+ isNullableString(value.updatedAt)
+ );
+}
+
+function isAccessScope(value: unknown): value is LeaderboardAccessScope {
+ return (
+ isRecord(value) &&
+ typeof value.key === "string" &&
+ (value.kind === "workspace" || value.kind === "domain") &&
+ typeof value.id === "string" &&
+ typeof value.name === "string" &&
+ isNonnegativeInteger(value.memberCount) &&
+ (value.state === "ready" || value.state === "invite") &&
+ (value.role === null ||
+ value.role === "owner" ||
+ value.role === "admin" ||
+ value.role === "member")
+ );
+}
+
+function isInvitation(value: unknown): boolean {
+ return (
+ value === null ||
+ (isRecord(value) &&
+ typeof value.workspaceId === "string" &&
+ typeof value.workspaceName === "string" &&
+ isNullableString(value.inviterName))
+ );
+}
+
+function isJoinableWorkspace(value: unknown): boolean {
+ return (
+ value === null ||
+ (isRecord(value) &&
+ typeof value.id === "string" &&
+ typeof value.name === "string" &&
+ isNonnegativeInteger(value.memberCount) &&
+ (value.requestState === "none" || value.requestState === "pending"))
+ );
+}
+
+function isLeaderboardAccess(value: unknown): value is LeaderboardAccess {
+ return (
+ isRecord(value) &&
+ LEADERBOARD_ACCESS_STATES.has(String(value.state)) &&
+ Array.isArray(value.scopes) &&
+ value.scopes.every(isAccessScope) &&
+ isNullableString(value.domain) &&
+ isNonnegativeInteger(value.colleagueCount) &&
+ isInvitation(value.invitation) &&
+ isJoinableWorkspace(value.joinableWorkspace)
+ );
+}
+
+function isLeaderboardMember(value: unknown): boolean {
+ return (
+ isRecord(value) &&
+ typeof value.userId === "string" &&
+ isNullableString(value.name) &&
+ isNullableString(value.email) &&
+ isNullableString(value.image) &&
+ isNonnegativeInteger(value.totalWords) &&
+ isNonnegativeInteger(value.desktopWords) &&
+ isNonnegativeInteger(value.mobileWords) &&
+ (value.averageWpm === null || isNonnegativeInteger(value.averageWpm)) &&
+ isNonnegativeInteger(value.currentStreakDays) &&
+ isNonnegativeInteger(value.rank) &&
+ value.rank > 0
+ );
+}
+
+function isLeaderboard(value: unknown): value is Leaderboard {
+ if (!isRecord(value) || !isRecord(value.scope)) return false;
+ return (
+ typeof value.scope.key === "string" &&
+ (value.scope.kind === "workspace" || value.scope.kind === "domain") &&
+ typeof value.scope.id === "string" &&
+ typeof value.scope.name === "string" &&
+ isNullableString(value.viewerUserId) &&
+ LEADERBOARD_METRICS.has(value.metric as LeaderboardMetric) &&
+ (value.range === "week" || value.range === "all") &&
+ (value.weekStart === null || isCalendarDate(value.weekStart)) &&
+ Array.isArray(value.availableWeekStarts) &&
+ value.availableWeekStarts.length <= LEADERBOARD_MAX_WEEK_STARTS &&
+ value.availableWeekStarts.every(isCalendarDate) &&
+ Array.isArray(value.leaders) &&
+ value.leaders.every(isLeaderboardMember) &&
+ Array.isArray(value.members) &&
+ value.members.every(isLeaderboardMember) &&
+ isNonnegativeInteger(value.totalMembers) &&
+ (value.viewerRank === null ||
+ (isNonnegativeInteger(value.viewerRank) && value.viewerRank > 0)) &&
+ isNonnegativeInteger(value.page) &&
+ isNonnegativeInteger(value.pageSize) &&
+ value.pageSize > 0 &&
+ typeof value.generatedAt === "string" &&
+ typeof value.refreshAfterSeconds === "number" &&
+ Number.isFinite(value.refreshAfterSeconds) &&
+ value.refreshAfterSeconds > 0 &&
+ value.refreshAfterSeconds <= LEADERBOARD_MAX_REFRESH_SECONDS
+ );
+}
+
+const participationOperationTails = new Map<string, Promise<void>>();
+
+async function serializeParticipationOperation<T>(
+ context: LeaderboardParticipationAuthContext,
+ mutation: () => Promise<T>
+): Promise<T> {
+ const { userId, authGeneration } = context;
+ const previous = participationOperationTails.get(userId) ?? Promise.resolve();
+ let release!: () => void;
+ const tail = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ participationOperationTails.set(userId, tail);
+ await previous;
+ try {
+ const runForCapturedAccount = async () => {
+ const current = getAuthRequestContextSnapshot();
+ if (
+ current.sessionUserId !== userId ||
+ current.sessionGeneration !== authGeneration ||
+ getValidatedAuthGeneration() !== authGeneration
+ ) {
+ throw new CloudApiError(
+ "Authentication context changed before leaderboard participation could be reconciled",
+ 0,
+ "AUTH_CONTEXT_CHANGED"
+ );
+ }
+ return mutation();
+ };
+ const locks = globalThis.navigator?.locks;
+ if (locks) {
+ return await locks.request(
+ `openwhispr-leaderboard-participation:${userId}`,
+ runForCapturedAccount
+ );
+ }
+ return await runForCapturedAccount();
+ } finally {
+ release();
+ if (participationOperationTails.get(userId) === tail) {
+ participationOperationTails.delete(userId);
+ }
+ }
+}
+
+async function getParticipation(
+ context: LeaderboardParticipationAuthContext
+): Promise<AnalyticsParticipation> {
+ return serializeParticipationOperation(context, async () => {
+ try {
+ const response = await cloudGetForAuthGeneration<unknown>(
+ "/api/analytics/participation",
+ context.authGeneration
+ );
+ const participation = responseData(response, "leaderboard participation");
+ if (!isParticipation(participation)) {
+ throw new Error("Malformed leaderboard participation response from cloud");
+ }
+ return participation;
+ } catch (error) {
+ // During the staggered rollout, an older API has no participation route.
+ // Preserve the existing Insights preference until the API is upgraded.
+ if (error instanceof CloudApiError && error.status === 404) {
+ return { configured: false, enabled: false, updatedAt: null };
+ }
+ throw error;
+ }
+ });
+}
+
+async function setParticipation(
+ enabled: boolean,
+ authGeneration: number
+): Promise<AnalyticsParticipation> {
+ const response = await cloudPatchForAuthGeneration<unknown>(
+ "/api/analytics/participation",
+ { enabled },
+ authGeneration
+ );
+ const participation = responseData(response, "leaderboard participation");
+ if (!isParticipation(participation)) {
+ throw new Error("Malformed leaderboard participation response from cloud");
+ }
+ return participation;
+}
+
+// Codes the main process raises from its auth fence, which runs before the
+// request is put on the wire. Nothing reached the API under either of them.
+const LOCAL_AUTH_FENCE_CODES = new Set(["AUTH_CONTEXT_CHANGED", "AUTH_CONTEXT_UNVALIDATED"]);
+
+type ParticipationWriteOutcome = "applied" | "refused" | "not_sent" | "unknown";
+
+/**
+ * What a failed participation write actually did to the account row.
+ *
+ * `applied` — cloudPatchForAuthGeneration raises CloudApiError for every
+ * transport and HTTP failure, so any other error escaped while reading a body
+ * the API had already answered 2xx with. The write landed; only the answer was
+ * unreadable.
+ * `refused` — a 4xx is the server's own verdict on a request it declined to act
+ * on, so the row is untouched.
+ * `not_sent` — fenced on this device; the request never left.
+ * `unknown` — no response or a server error, so the row may or may not have moved.
+ *
+ * Only `unknown` needs compensating: banking a leave for the other three either
+ * undoes work the account asked for, or strands a record with nothing to undo.
+ */
+function classifyParticipationWriteFailure(error: unknown): ParticipationWriteOutcome {
+ if (!(error instanceof CloudApiError)) return "applied";
+ if (error.code != null && LOCAL_AUTH_FENCE_CODES.has(error.code)) return "not_sent";
+ if (error.status >= 400 && error.status < 500) return "refused";
+ return "unknown";
+}
+
+async function joinParticipation(
+ context: LeaderboardParticipationAuthContext
+): Promise<AnalyticsParticipation> {
+ const { userId, authGeneration } = context;
+ return serializeParticipationOperation(context, async () => {
+ clearPendingLeaderboardLeave(userId);
+ try {
+ return await setParticipation(true, authGeneration);
+ } catch (error) {
+ if (classifyParticipationWriteFailure(error) === "unknown") {
+ writePendingLeaderboardLeave(userId);
+ }
+ throw error;
+ }
+ });
+}
+
+async function leaveParticipation(
+ context: LeaderboardParticipationAuthContext
+): Promise<AnalyticsParticipation> {
+ const { userId, authGeneration } = context;
+ // Persist the intent before it can wait. If auth changes while this operation
+ // is queued, the request is fenced but the original account's leave survives.
+ writePendingLeaderboardLeave(userId);
+ return serializeParticipationOperation(context, async () => {
+ try {
+ const participation = await setParticipation(false, authGeneration);
+ clearPendingLeaderboardLeave(userId);
+ return participation;
+ } catch (error) {
+ settleUndeliveredLeave(userId, error);
+ throw error;
+ }
+ });
+}
+
+/**
+ * Retires a pending leave the API has already acted on or can never act on, and
+ * otherwise charges it one attempt so it cannot preempt the sync throttle
+ * forever. Returns whether the account is still waiting to come off the board.
+ */
+function settleUndeliveredLeave(userId: string, error: unknown): boolean {
+ const outcome = classifyParticipationWriteFailure(error);
+ // The row is already false — the API accepted the PATCH and only its answer
+ // was unreadable, so there is nothing left to retry.
+ if (outcome === "applied") {
+ clearPendingLeaderboardLeave(userId);
+ return false;
+ }
+ // An API without the participation route cannot be holding the account on a
+ // leaderboard, so the leave has nothing to deliver. Every other refusal is
+ // kept: a 429 or a 401 is answered by retrying later, not by dropping the
+ // account's opt-out.
+ if (outcome === "refused" && error instanceof CloudApiError && error.status === 404) {
+ clearPendingLeaderboardLeave(userId);
+ return false;
+ }
+ recordPendingLeaderboardLeaveAttempt(userId);
+ return true;
+}
+
+/**
+ * Retries a leave the user already asked for and the network never delivered,
+ * for that account only: a device may take itself off a leaderboard, never put
+ * itself on one. Returns whether the account is still waiting for it.
+ *
+ * The record survives every outcome that leaves the account row untouched, and
+ * flushes are trigger-driven (a sync pass, a participation read), so a request
+ * that keeps failing costs one call per trigger rather than a loop. It is
+ * retired only once the API has acted on it or has shown it never can — see
+ * settleUndeliveredLeave.
+ */
+async function flushPendingLeave(context: LeaderboardParticipationAuthContext): Promise<boolean> {
+ const { userId, authGeneration } = context;
+ return serializeParticipationOperation(context, async () => {
+ // Check inside the mutation lock: an explicit join queued ahead of this
+ // retry retires the older leave before it can issue a stale PATCH false.
+ if (!readPendingLeaderboardLeave(userId)) return false;
+ try {
+ await setParticipation(false, authGeneration);
+ clearPendingLeaderboardLeave(userId);
+ return false;
+ } catch (error) {
+ console.error("Retrying the leaderboard leave failed:", error);
+ return settleUndeliveredLeave(userId, error);
+ }
+ });
+}
+
+async function getAccess(): Promise<LeaderboardAccess> {
+ const response = await cloudGet<unknown>("/api/leaderboard/access");
+ const access = responseData(response, "leaderboard access");
+ if (!isLeaderboardAccess(access))
+ throw new Error("Malformed leaderboard access response from cloud");
+ return access;
+}
+
+async function getLeaderboard(
+ scope: LeaderboardAccessScope,
+ query: {
+ metric: LeaderboardMetric;
+ range: LeaderboardRange;
+ weekStart?: string | null;
+ includeWeekStarts?: boolean;
+ page: number;
+ }
+): Promise<Leaderboard> {
+ const params = new URLSearchParams({
+ metric: query.metric,
+ range: query.range,
+ page: String(query.page),
+ });
+ if (query.range === "week" && query.weekStart) params.set("weekStart", query.weekStart);
+ if (query.includeWeekStarts === false) params.set("includeWeekStarts", "false");
+ const path =
+ scope.kind === "workspace"
+ ? `/api/workspaces/${encodeURIComponent(scope.id)}/leaderboard`
+ : "/api/leaderboard/domain";
+ const response = await cloudGet<unknown>(`${path}?${params.toString()}`);
+ const leaderboard = responseData(response, "leaderboard");
+ if (!isLeaderboard(leaderboard)) throw new Error("Malformed leaderboard response from cloud");
+ return leaderboard;
+}
+
+export const LeaderboardService = {
+ flushPendingLeave,
+ getAccess,
+ getLeaderboard,
+ getParticipation,
+ joinParticipation,
+ leaveParticipation,
+};
diff --git a/src/services/SyncService.ts b/src/services/SyncService.ts
index d7032aadd..1d1a68648 100644
--- a/src/services/SyncService.ts
+++ b/src/services/SyncService.ts
@@ -15,8 +15,10 @@ import { syncPendingAnalytics } from "./AnalyticsService.js";
import { DictionaryService } from "./DictionaryService.js";
import { SnippetService, type CloudSnippetEntry } from "./SnippetService.js";
import { CloudApiError, isAuthContextError } from "./cloudApi.js";
+import { LeaderboardService } from "./LeaderboardService";
import {
assertAuthGenerationCurrent,
+ getAuthRequestContextSnapshot,
getValidatedAuthGeneration,
hasValidatedAuthContext,
} from "../lib/authRequestContext";
@@ -28,6 +30,7 @@ import {
} from "../lib/teamSpacesCapability";
import { readIsSubscribed, subscribeIsSubscribed } from "../lib/subscriptionFlag";
import { readNoteConflictIds } from "../lib/noteConflictRegistry";
+import { pendingLeaderboardLeaveDeservesPriority } from "../lib/pendingLeaderboardLeave";
import {
cloudBackupResumed,
effectiveLocalHistoryEnabled,
@@ -577,7 +580,16 @@ export class SyncService {
reason === "start" &&
this.canSyncTeamSpaces() &&
localStorage.getItem("teamSpacesCapability.probedAt") == null;
- const bypassThrottle = waitForLock || firstTeamSpacesProbe;
+ // A leaderboard opt-out is a user-requested account mutation, not ambient
+ // sync work. Retry it on the next trigger even when an otherwise idle
+ // collaboration-only pass has backed off. That priority is spent after a
+ // few undelivered attempts: an opt-out that can never land keeps being
+ // retried, but stops disabling the throttle, the in-flight guard and the
+ // ambient backoff for the life of the install.
+ const sessionUserId = getAuthRequestContextSnapshot().sessionUserId;
+ const pendingLeaderboardLeave =
+ sessionUserId != null && pendingLeaderboardLeaveDeservesPriority(sessionUserId);
+ const bypassThrottle = waitForLock || firstTeamSpacesProbe || pendingLeaderboardLeave;
if (
!bypassThrottle &&
(this.syncing || Date.now() - this.lastCompletedSyncAt() < AUTO_SYNC_THROTTLE_MS)
@@ -2193,15 +2205,65 @@ export class SyncService {
}
}
+ // The Insights view uses this same guarded path before reading the account
+ // summary, so queued uploads and foreground refreshes use one consent gate.
+ async syncAnalyticsNow(): Promise<boolean> {
+ return this.syncAnalytics();
+ }
+
// Push-only: the account summary is read live by the Insights view, so there
// is nothing to pull back into the device's own counters.
- private async syncAnalytics(): Promise<void> {
+ private async syncAnalytics(): Promise<boolean> {
const consent = this.consent();
- if (!consent.shared) return;
+ if (!consent.shared) return false;
+ const accountId = getAuthRequestContextSnapshot().sessionUserId;
+ const authGeneration = getValidatedAuthGeneration();
+ if (!accountId || authGeneration == null) return false;
+ const participationContext = { userId: accountId, authGeneration };
+ // A leaderboard opt-out outlives the window that made it, so every pass
+ // retries the one this account is still waiting for. It only ever leaves,
+ // and nothing below depends on whether it has landed, so it runs beside
+ // the pass rather than ahead of it: this method executes under
+ // SYNC_ALL_LOCK and cloud requests carry no timeout, so awaiting it here
+ // let one hung PATCH hold every window's sync behind the lock.
+ void LeaderboardService.flushPendingLeave(participationContext).catch((error: unknown) => {
+ // The account changing mid-queue is expected; the gate below sees it too.
+ if (!isAuthContextError(error)) {
+ console.error("Retrying the leaderboard leave failed:", error);
+ }
+ });
+ // Participation controls roster visibility, not analytics consent. A
+ // missing or failed participation route must never interrupt Insights Sync.
+ const uploadRequested = consent.analytics;
+ let uploadAllowed = false;
+ const verifyUploadAllowed = async (): Promise<boolean> => {
+ await assertAuthGenerationCurrent(authGeneration);
+ const current = getAuthRequestContextSnapshot();
+ if (
+ current.sessionUserId !== accountId ||
+ current.sessionGeneration !== authGeneration ||
+ current.validatedGeneration !== authGeneration
+ ) {
+ throw Object.assign(new Error("Authentication context changed during analytics sync"), {
+ code: "AUTH_CONTEXT_CHANGED",
+ });
+ }
+ // A pass requested while local sync was off may run erasures, but must
+ // never gain upload authority merely because a later setting changed.
+ uploadAllowed = uploadRequested && this.consent().analytics;
+ return uploadAllowed;
+ };
try {
// Revoking retention/Insights consent blocks new uploads, never deletion
- // of rows that may already exist in the account.
- if ((await syncPendingAnalytics({ uploadAllowed: consent.analytics })) > 0) {
+ // of rows that may already exist in the account. The gate itself reaches
+ // the head of AnalyticsService's queue before it resolves, so a local
+ // opt-out while another pass runs still wins before rows are read.
+ if (
+ (await syncPendingAnalytics({
+ uploadAllowed: verifyUploadAllowed,
+ context: { accountId, authGeneration },
+ })) > 0
+ ) {
this.analyticsPassMovedWork = true;
}
} catch (err) {
@@ -2209,7 +2271,9 @@ export class SyncService {
// A rejected batch stays pending for the next pass; the rest of this one
// still has folders, notes, and transcriptions to finish.
console.error("Analytics sync failed:", err);
+ return false;
}
+ return uploadAllowed && this.consent().analytics;
}
private async syncTranscriptions(): Promise<void> {
diff --git a/src/services/cloudApi.ts b/src/services/cloudApi.ts
index 36af61755..6c680dff2 100644
--- a/src/services/cloudApi.ts
+++ b/src/services/cloudApi.ts
@@ -68,6 +68,16 @@ export async function cloudGet<T = unknown>(path: string): Promise<T> {
return cloudRequest<T>("GET", path);
}
+// Account-scoped work may wait behind another renderer operation. Preserve the
+// credential generation from the caller so a queued request cannot adopt a
+// replacement account's token when it eventually reaches the main process.
+export async function cloudGetForAuthGeneration<T = unknown>(
+ path: string,
+ authGeneration: number
+): Promise<T> {
+ return cloudRequest<T>("GET", path, undefined, false, authGeneration);
+}
+
// Account-scope bootstrap is the only authenticated call allowed before the
// candidate session generation has been committed for ordinary sync.
export async function cloudGetForAuthValidation<T = unknown>(
@@ -86,17 +96,40 @@ export async function cloudPost<T = unknown>(path: string, body?: unknown): Prom
return cloudRequest<T>("POST", path, body);
}
+export async function cloudPostForAuthGeneration<T = unknown>(
+ path: string,
+ body: unknown,
+ authGeneration: number
+): Promise<T> {
+ return cloudRequest<T>("POST", path, body, false, authGeneration);
+}
+
export async function cloudPatch<T = unknown>(path: string, body?: unknown): Promise<T> {
return cloudRequest<T>("PATCH", path, body);
}
+export async function cloudPatchForAuthGeneration<T = unknown>(
+ path: string,
+ body: unknown,
+ authGeneration: number
+): Promise<T> {
+ return cloudRequest<T>("PATCH", path, body, false, authGeneration);
+}
+
export async function cloudDelete<T = unknown>(path: string, body?: unknown): Promise<T> {
return cloudRequest<T>("DELETE", path, body);
}
+export async function cloudDeleteForAuthGeneration<T = unknown>(
+ path: string,
+ body: unknown,
+ authGeneration: number
+): Promise<T> {
+ return cloudRequest<T>("DELETE", path, body, false, authGeneration);
+}
+
export function isAuthContextError(error: unknown): boolean {
- return (
- error instanceof CloudApiError &&
- (error.code === "AUTH_CONTEXT_CHANGED" || error.code === "AUTH_CONTEXT_UNVALIDATED")
- );
+ if (typeof error !== "object" || error === null || !("code" in error)) return false;
+ const code = (error as { code?: unknown }).code;
+ return code === "AUTH_CONTEXT_CHANGED" || code === "AUTH_CONTEXT_UNVALIDATED";
}
diff --git a/src/services/syncPassPolicy.ts b/src/services/syncPassPolicy.ts
index 8e9f9186e..1ebde5c45 100644
--- a/src/services/syncPassPolicy.ts
+++ b/src/services/syncPassPolicy.ts
@@ -47,12 +47,11 @@ export function resolveSyncConsent(state: {
/**
* Whether the Insights view offers to adopt the counters recorded while signed
* out. The offer is gated on there being rows to adopt, never on the sync
- * toggle: insightsSyncEnabled is device-scoped and survives sign-out, so
- * counters spoken between a sign-out and the next sign-in land unattributed
- * with the toggle still on. Gating the offer on the toggle left exactly those
- * rows unreachable — excluded from the account summary the view then shows,
- * so visible totals silently dropped after signing back in. Offering is not
- * adopting: the prompt still has to be confirmed (useInsightsSyncOptIn).
+ * toggle: account-scope bootstrap can leave rows unattributed while the local
+ * setting is on. Gating the offer on the toggle left exactly those rows
+ * unreachable — excluded from the account summary the view then shows, so
+ * visible totals silently dropped. Offering is not adopting: the prompt still
+ * has to be confirmed (useInsightsSyncOptIn).
*
* The other three inputs are the preconditions the offer always had. Retention
* being off is not a technicality here: it stops new counters being recorded,
diff --git a/src/stores/leaderboardParticipationStore.ts b/src/stores/leaderboardParticipationStore.ts
new file mode 100644
index 000000000..021f9a866
--- /dev/null
+++ b/src/stores/leaderboardParticipationStore.ts
@@ -0,0 +1,199 @@
+import { create } from "zustand";
+import {
+ readPendingLeaderboardLeave,
+ writePendingLeaderboardLeave,
+} from "../lib/pendingLeaderboardLeave";
+import {
+ LeaderboardService,
+ type LeaderboardParticipationAuthContext,
+} from "../services/LeaderboardService";
+
+/**
+ * The account's leaderboard participation, shared by every leaderboard surface
+ * that reads or changes it. It is independent of this device's Insights Sync
+ * setting.
+ *
+ * Nothing here joins on the user's behalf: only join() ever sends `true`, and
+ * a leave the network refused is held on the device and retried until the
+ * account takes it (see pendingLeaderboardLeave).
+ */
+interface LeaderboardParticipationState {
+ /** The account row says joined. False whenever the answer is unknown. */
+ enabled: boolean;
+ /** The account has explicitly chosen a participation state. */
+ configured: boolean;
+ ready: boolean;
+ /** Which side failed, because they need different offers: an unknown answer
+ * gets a Retry, a refused write gets the action that failed back. */
+ error: "read" | "write" | null;
+ updating: boolean;
+ /** An opt-out this device still owes the account. The toggle already reads
+ * off, so this is what keeps a leave that has not landed from passing as done. */
+ leavePending: boolean;
+ reset: () => void;
+ refresh: (context: LeaderboardParticipationAuthContext) => Promise<void>;
+ publishAnswer: (
+ enabled: boolean,
+ configured: boolean,
+ generation: number,
+ leavePending?: boolean
+ ) => void;
+ join: (context: LeaderboardParticipationAuthContext) => Promise<boolean>;
+ leave: (context: LeaderboardParticipationAuthContext) => Promise<boolean>;
+ queueLeave: (userId: string) => void;
+}
+
+// A completed write is the newest answer there is, so it retires every read
+// still in flight, which would otherwise settle the account on pre-write state.
+// Writes read the same counter: one taken out for the departing account has no
+// answer to give about the account that replaced it.
+let readId = 0;
+// Keep write invalidation separate so an older account cannot clear a newer account's pending state.
+let writeId = 0;
+let activeRefresh: { key: string; promise: Promise<void> } | null = null;
+
+export const useLeaderboardParticipationStore = create<LeaderboardParticipationState>(
+ (set, get) => ({
+ enabled: false,
+ configured: false,
+ ready: false,
+ error: null,
+ updating: false,
+ leavePending: false,
+
+ reset: () => {
+ readId += 1;
+ writeId += 1;
+ activeRefresh = null;
+ // Reset updating too: a write left running for the departing account must
+ // not make refresh() skip the replacement account's read.
+ set({
+ enabled: false,
+ configured: false,
+ ready: false,
+ error: null,
+ updating: false,
+ leavePending: false,
+ });
+ },
+
+ // The retired read never reports itself finished either, hence the ready flag.
+ publishAnswer: (enabled, configured, generation, leavePending = false) => {
+ if (generation !== readId) return;
+ readId += 1;
+ set({ enabled, configured, ready: true, error: null, leavePending });
+ },
+
+ // Read-only, and only when a caller asks: the account preference is the one
+ // source of truth for who is on a leaderboard, and nothing here may join or
+ // leave one on the user's behalf.
+ refresh: async (context) => {
+ const key = `${context.userId}:${context.authGeneration}`;
+ if (activeRefresh?.key === key) {
+ await activeRefresh.promise;
+ return;
+ }
+ // A write already in flight is the newer answer by definition — skip a
+ // read that could settle the account on the state it is mid-change.
+ if (get().updating) return;
+
+ const promise = (async () => {
+ const currentReadId = ++readId;
+ set({ ready: false, error: null });
+ try {
+ // An opt-out the network never delivered is retried first, so the answer
+ // below is the one the user asked for rather than the row it left behind.
+ const stillLeaving = await LeaderboardService.flushPendingLeave(context);
+ const participation = await LeaderboardService.getParticipation(context);
+ if (currentReadId !== readId) return;
+ set({
+ enabled: participation.enabled && !stillLeaving,
+ configured: participation.configured || stillLeaving,
+ leavePending: stillLeaving,
+ });
+ } catch (error) {
+ if (currentReadId !== readId) return;
+ console.error("Reading leaderboard participation failed:", error);
+ // A read that failed leaves participation unknown, so it has to fail
+ // closed. Keeping the last answer would also let the leaderboard's 403
+ // recovery re-read, fail, and immediately re-issue the same 403 forever.
+ // The surface offers a Retry rather than a Join, which would ask an
+ // account that may already be on a leaderboard to join it again.
+ set({ enabled: false, configured: false, error: "read" });
+ } finally {
+ if (currentReadId === readId) set({ ready: true });
+ }
+ })();
+ activeRefresh = { key, promise };
+ try {
+ await promise;
+ } finally {
+ if (activeRefresh?.promise === promise) activeRefresh = null;
+ }
+ },
+
+ join: async (context) => {
+ const generation = readId;
+ const currentWriteId = ++writeId;
+ set({ updating: true });
+ try {
+ const participation = await LeaderboardService.joinParticipation(context);
+ if (currentWriteId === writeId) {
+ get().publishAnswer(participation.enabled, participation.configured, generation);
+ }
+ return participation.enabled;
+ } catch (error) {
+ console.error("Joining the leaderboard failed:", error);
+ if (currentWriteId === writeId && generation === readId) {
+ readId += 1;
+ // A join whose outcome is unknown banks a compensating leave.
+ set({
+ enabled: false,
+ configured: true,
+ ready: true,
+ error: "write",
+ leavePending: readPendingLeaderboardLeave(context.userId),
+ });
+ }
+ return false;
+ } finally {
+ if (currentWriteId === writeId) set({ updating: false });
+ }
+ },
+
+ leave: async (context) => {
+ const generation = readId;
+ const currentWriteId = ++writeId;
+ set({ updating: true });
+ try {
+ const participation = await LeaderboardService.leaveParticipation(context);
+ if (currentWriteId === writeId) {
+ get().publishAnswer(participation.enabled, participation.configured, generation);
+ }
+ return true;
+ } catch (error) {
+ console.error("Leaving the leaderboard failed:", error);
+ // The opt-out is kept and retried until the account takes it, so this
+ // device stops showing the user as participating straight away rather
+ // than asking them to remember to try again — and says the leave is
+ // still owed, since the account row has not moved. A leave the API has
+ // already applied or can never apply retires the record instead.
+ if (currentWriteId === writeId) {
+ get().publishAnswer(false, true, generation, readPendingLeaderboardLeave(context.userId));
+ }
+ return false;
+ } finally {
+ if (currentWriteId === writeId) set({ updating: false });
+ }
+ },
+
+ // A click taken while auth is revalidating is still an opt-out. Stop
+ // presenting participation now and deliver the account-scoped leave as
+ // soon as that same account regains a validated credential.
+ queueLeave: (userId) => {
+ writePendingLeaderboardLeave(userId);
+ const generation = readId;
+ get().publishAnswer(false, true, generation, true);
+ },
+ })
+);
diff --git a/src/types/electron.ts b/src/types/electron.ts
index fe97ab007..149113518 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -190,6 +190,11 @@ export interface PendingAnalyticsClear {
cleared_through: string;
}
+export interface AnalyticsSyncContext {
+ accountId: string;
+ authGeneration: number;
+}
+
export interface AnalyticsDailyBucket {
date: string;
words: number;
@@ -208,6 +213,85 @@ export interface AnalyticsSummary {
daily: AnalyticsDailyBucket[];
}
+export type LeaderboardMetric =
+ "total_words" | "words_per_minute" | "current_daily_streak" | "desktop_words" | "mobile_words";
+
+export type LeaderboardRange = "week" | "all";
+
+export interface AnalyticsParticipation {
+ configured: boolean;
+ enabled: boolean;
+ updatedAt: string | null;
+}
+
+export interface LeaderboardMember {
+ userId: string;
+ name: string | null;
+ // Withheld (null) on a domain board, where a shared mail suffix is the only
+ // thing the listed people have in common.
+ email: string | null;
+ image: string | null;
+ totalWords: number;
+ desktopWords: number;
+ mobileWords: number;
+ averageWpm: number | null;
+ currentStreakDays: number;
+ rank: number;
+}
+
+export type LeaderboardAccessState =
+ "ready" | "invite" | "accept_invite" | "request_join" | "create";
+
+export interface LeaderboardAccessScope {
+ key: string;
+ kind: "workspace" | "domain";
+ id: string;
+ name: string;
+ memberCount: number;
+ state: "ready" | "invite";
+ role: WorkspaceRole | null;
+}
+
+export interface LeaderboardAccess {
+ state: LeaderboardAccessState;
+ scopes: LeaderboardAccessScope[];
+ domain: string | null;
+ colleagueCount: number;
+ invitation: {
+ workspaceId: string;
+ workspaceName: string;
+ inviterName: string | null;
+ } | null;
+ joinableWorkspace: {
+ id: string;
+ name: string;
+ memberCount: number;
+ requestState: "none" | "pending";
+ } | null;
+}
+
+export interface Leaderboard {
+ scope: {
+ key: string;
+ kind: "workspace" | "domain";
+ id: string;
+ name: string;
+ };
+ viewerUserId: string | null;
+ metric: LeaderboardMetric;
+ range: LeaderboardRange;
+ weekStart: string | null;
+ availableWeekStarts: string[];
+ leaders: LeaderboardMember[];
+ members: LeaderboardMember[];
+ totalMembers: number;
+ viewerRank: number | null;
+ page: number;
+ pageSize: number;
+ generatedAt: string;
+ refreshAfterSeconds: number;
+}
+
export interface NoteItem {
id: number;
title: string;
@@ -1182,21 +1266,35 @@ declare global {
input: AnalyticsEventInput
) => Promise<{ success: boolean; eventId?: string; ignored?: boolean }>;
getAnalyticsSummary: () => Promise<AnalyticsSummary>;
- getPendingAnalyticsEvents: (limit?: number) => Promise<PendingAnalyticsEvent[]>;
+ getPendingAnalyticsEvents: (
+ limit?: number,
+ context?: AnalyticsSyncContext
+ ) => Promise<PendingAnalyticsEvent[]>;
markAnalyticsEventsSynced: (
- eventIds: string[]
+ eventIds: string[],
+ context?: AnalyticsSyncContext
) => Promise<{ success: boolean; updated: number }>;
- getPendingAnalyticsDeletes: (limit?: number) => Promise<Array<{ event_id: string }>>;
+ getPendingAnalyticsDeletes: (
+ limit?: number,
+ context?: AnalyticsSyncContext
+ ) => Promise<Array<{ event_id: string }>>;
hardDeleteAnalyticsEvents: (
- eventIds: string[]
+ eventIds: string[],
+ context?: AnalyticsSyncContext
) => Promise<{ success: boolean; deleted: number }>;
- getPendingAnalyticsClear: () => Promise<PendingAnalyticsClear | null>;
+ getPendingAnalyticsClear: (
+ context?: AnalyticsSyncContext
+ ) => Promise<PendingAnalyticsClear | null>;
completeAnalyticsClear: (
- clearedThrough: string
+ clearedThrough: string,
+ context?: AnalyticsSyncContext
) => Promise<{ success: boolean; deleted: number }>;
- countUnclaimedAnalyticsEvents: () => Promise<number>;
- countAnalyticsEventsAwaitingUpload: () => Promise<number>;
- claimAnonymousAnalyticsEvents: () => Promise<{ success: boolean; claimed: number }>;
+ countUnclaimedAnalyticsEvents: (context?: AnalyticsSyncContext) => Promise<number>;
+ countAnalyticsEventsAwaitingUpload: (context?: AnalyticsSyncContext) => Promise<number>;
+ claimAnonymousAnalyticsEvents: (
+ accountId: string,
+ expectedAuthGeneration: number
+ ) => Promise<{ success: boolean; claimed: number; code?: string }>;
clearTranscriptions: () => Promise<{ cleared: number; success: boolean }>;
deleteTranscription: (id: number) => Promise<{ success: boolean }>;
getTranscriptionById: (id: number) => Promise<TranscriptionItem | null>;
@@ -1571,6 +1669,11 @@ declare global {
promptAccessibilityPermission: () => Promise<boolean>;
readClipboard: () => Promise<string>;
writeClipboard: (text: string) => Promise<{ success: boolean }>;
+ copyLeaderboardImage: (dataUrl: string) => Promise<{ success: boolean; error?: string }>;
+ saveLeaderboardImage: (
+ dataUrl: string,
+ suggestedName: string
+ ) => Promise<{ success: boolean; canceled?: boolean; error?: string }>;
checkPasteTools: () => Promise<PasteToolsResult>;
// Audio
diff --git a/test/components/leaderboardNavigation.test.js b/test/components/leaderboardNavigation.test.js
new file mode 100644
index 000000000..188ed5878
--- /dev/null
+++ b/test/components/leaderboardNavigation.test.js
@@ -0,0 +1,193 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const path = require("node:path");
+
+const read = (relativePath) => fs.readFileSync(path.join(__dirname, "../..", relativePath), "utf8");
+
+test("the leaderboard is tabbed inside the Insights view", () => {
+ const controlPanel = read("src/components/ControlPanel.tsx");
+ const sidebar = read("src/components/ControlPanelSidebar.tsx");
+ const insights = read("src/components/InsightsView.tsx");
+ const leaderboard = read("src/components/LeaderboardView.tsx");
+ const dictionary = read("src/components/DictionaryView.tsx");
+
+ assert.equal(sidebar.includes('| "leaderboard"'), false);
+ assert.equal(sidebar.includes('{ id: "leaderboard"'), false);
+ assert.equal(controlPanel.includes('activeView === "leaderboard"'), false);
+ assert.equal(controlPanel.includes('import("./LeaderboardView")'), false);
+ assert.ok(controlPanel.includes("<InsightsView"));
+ assert.ok(insights.includes('useState("usage")'));
+ assert.equal(insights.match(/<TabsTrigger/g)?.length, 2);
+ assert.ok(insights.includes('value="usage"'));
+ assert.ok(insights.includes('t("insights.yourUsage")'));
+ assert.ok(insights.includes('value="leaderboard"'));
+ assert.ok(dictionary.includes('className="h-7 p-0.5 rounded-[7px]"'));
+ assert.ok(insights.includes('className="h-7 p-0.5 rounded-[7px]"'));
+ assert.ok(dictionary.includes('className="h-6 px-2.5 text-xs rounded-[5px]"'));
+ assert.ok(insights.includes('className="h-6 px-2.5 text-xs rounded-[5px]"'));
+ assert.ok(insights.includes("<LeaderboardView"));
+ assert.ok(insights.includes("syncService.syncAnalyticsNow()"));
+ assert.ok(insights.includes("const authValidated = hasValidatedAuthContext()"));
+ assert.ok(insights.includes("isSignedIn &&\n authValidated &&\n insightsSyncEnabled"));
+ assert.equal(insights.includes("syncPendingAnalytics"), false);
+ assert.ok(insights.includes("onClick={() => void enableInsightsSync()}"));
+ assert.ok(insights.includes('"insights.enableSync"'));
+ assert.ok(insights.includes("onSyncErrorChange={setSyncError}"));
+ assert.ok(insights.includes('activeTab === "usage"'));
+ assert.ok(insights.includes('variant="default"'));
+ assert.ok(insights.includes("participationReady &&"));
+ assert.ok(insights.includes("participationError === null"));
+ assert.ok(insights.includes("!participationEnabled"));
+ assert.ok(insights.includes('"insights.leaderboard.disabled"'));
+ assert.ok(
+ insights.includes('"insights.leaderboard.leavePending"'),
+ "the chip has to say an opt-out is still owed rather than call it disabled"
+ );
+ const usageContent = insights.slice(
+ insights.indexOf('<TabsContent value="usage"'),
+ insights.indexOf('<TabsContent value="leaderboard"')
+ );
+ assert.ok(usageContent.includes("isLoaded && !syncActive"));
+ assert.ok(usageContent.includes('t("insights.onDevicePrivacy")'));
+ assert.ok(usageContent.includes("mt-auto pt-8"));
+ assert.equal(
+ insights
+ .slice(insights.indexOf('<TabsContent value="leaderboard"'))
+ .includes("onDevicePrivacy"),
+ false
+ );
+ assert.ok(leaderboard.includes("<LeaderboardSection"));
+ assert.equal(
+ leaderboard.includes("useInsightsSyncOptIn()"),
+ false,
+ "the nested tab must reuse the page's opt-in owner instead of duplicating analytics IPCs"
+ );
+ assert.ok(leaderboard.includes("onJoin={joinLeaderboard}"));
+ assert.equal(leaderboard.includes('<h1 className="text-base!'), false);
+ assert.equal(leaderboard.includes('t("insights.leaderboard.description")'), false);
+});
+
+test("analytics and leaderboard consent copy are concise and independently scoped", () => {
+ for (const locale of ["en", "de", "es", "fr", "it", "ja", "pt", "ru", "zh-CN", "zh-TW"]) {
+ const { insights } = JSON.parse(read(`src/locales/${locale}/translation.json`));
+ const descriptions = [
+ insights.leaderboard.joinDescription,
+ ...Object.entries(insights)
+ .filter(([key]) => /^(claim|enable)Description_/.test(key))
+ .map(([, value]) => value),
+ ];
+ for (const description of descriptions) {
+ assert.ok(description.length <= 190, `${locale} consent copy is too long`);
+ assert.doesNotMatch(description, /[—–]/, `${locale} consent copy must not use long dashes`);
+ }
+ }
+
+ const english = JSON.parse(read("src/locales/en/translation.json")).insights;
+ assert.match(english.leaderboard.joinDescription, /name, email, and activity/);
+ assert.doesNotMatch(english.enableDescription_other, /name|email|leaderboard/);
+});
+
+test("leaderboard access is plan agnostic and invitation led", () => {
+ const controlPanel = read("src/components/ControlPanel.tsx");
+ const section = read("src/components/LeaderboardSection.tsx");
+ const view = read("src/components/LeaderboardView.tsx");
+
+ assert.equal(section.includes("LeaderboardFreePreview"), false);
+ assert.equal(view.includes("onUpgrade"), false);
+ assert.ok(section.includes("openLeaderboardGrowthAction"));
+ assert.ok(section.includes('"insights.leaderboard.inviteCta"'));
+ assert.ok(section.includes('selectedScope.kind === "domain"'));
+ assert.ok(section.includes('scope.kind === "workspace"'));
+ assert.ok(section.includes('"settingsPage.workspace.empty.create"'));
+ assert.ok(section.includes("setCreateWorkspaceOpen(true)"));
+ assert.ok(section.includes("boardParticipantCount"));
+ assert.ok(section.includes("visibleLeaderboard?.totalMembers"));
+ assert.ok(section.includes("<LeaderboardSetupCard"));
+ assert.ok(section.includes("<LeaderboardSoloEmptyState"));
+ assert.ok(section.includes("<LeaderboardAcceptInvitePreview"));
+ assert.ok(section.includes("afterWorkspaceJoined"));
+ assert.ok(section.includes("InvitationsService.list"));
+ assert.ok(section.includes("<LeaderboardEmptyStrip"));
+ assert.ok(section.includes("<LeaderboardWorkspaceNudge"));
+ assert.ok(section.includes('data-leaderboard-state="board"'));
+ assert.ok(section.includes("resolveLeaderboardScopeKey"));
+ assert.ok(section.includes('t("insights.leaderboard.chooseBoard")'));
+ assert.ok(section.includes('selectedScope?.state === "invite"'));
+ assert.ok(section.includes("<LeaderboardJoinPreview"));
+ assert.equal(section.includes("<LeaderboardSyncRow"), false);
+ assert.equal(section.includes("activationDescription"), false);
+ assert.equal(controlPanel.includes("onInvite={() => setShowReferrals(true)}"), false);
+});
+
+test("participation disagreement retries once without entering an auth flow", () => {
+ const section = read("src/components/LeaderboardSection.tsx");
+ const recovery = section.slice(
+ section.indexOf('if (code === "LEADERBOARD_PARTICIPATION_REQUIRED")'),
+ section.indexOf('if (code === "LEADERBOARD_DOMAIN_REQUIRED")')
+ );
+
+ assert.ok(recovery.includes("participationRecoveryAttemptedRef.current"));
+ assert.ok(recovery.includes('setFailure({ kind: "generic", requestKey: selectedRequestKey })'));
+ assert.ok(recovery.includes("onRefreshParticipation()"));
+ assert.equal(recovery.includes("onSignIn"), false);
+ assert.equal(recovery.includes("signOut"), false);
+ assert.equal(recovery.includes("authClearSession"), false);
+});
+
+test("a server-clamped page stays visible without an automatic duplicate request", () => {
+ const section = read("src/components/LeaderboardSection.tsx");
+ const responseHandling = section.slice(
+ section.indexOf("const responseRequestKey = leaderboardRequestKey("),
+ section.indexOf("lastLoadedAtRef.current = Date.now()")
+ );
+ const automaticLoad = section.slice(
+ section.indexOf("const skippedLoad = skipAutomaticLoadRef.current"),
+ section.indexOf("// The server owns how big a page is")
+ );
+
+ assert.ok(responseHandling.includes("response.page"));
+ assert.ok(responseHandling.includes("setLoadedRequestKey(responseRequestKey)"));
+ assert.ok(responseHandling.includes("skipAutomaticLoadRef.current"));
+ assert.ok(automaticLoad.includes("skippedLoad.requestKey === selectedRequestKey"));
+ assert.ok(automaticLoad.indexOf("return;") < automaticLoad.indexOf("void load()"));
+});
+
+test("leaderboard access waits for validated auth and labels ranked participants", () => {
+ const section = read("src/components/LeaderboardSection.tsx");
+ const accessLoader = section.slice(
+ section.indexOf("const loadAccess"),
+ section.indexOf("useEffect(() =>", section.indexOf("const loadAccess"))
+ );
+ const boardHeader = section.slice(
+ section.indexOf('data-leaderboard-state="board"'),
+ section.indexOf("<DropdownMenu", section.indexOf('data-leaderboard-state="board"'))
+ );
+
+ assert.ok(
+ accessLoader.indexOf("authGeneration == null") <
+ accessLoader.indexOf("LeaderboardService.getAccess()")
+ );
+ assert.ok(accessLoader.includes("[accountId, authGeneration, authSettled]"));
+ assert.ok(boardHeader.includes("boardParticipantCount"));
+ assert.equal(boardHeader.includes("selectedScope.memberCount"), false);
+});
+
+test("an SSO-required board starts company reauthentication directly", () => {
+ const section = read("src/components/LeaderboardSection.tsx");
+ const view = read("src/components/LeaderboardView.tsx");
+ const recovery = section.slice(
+ section.indexOf('visibleFailure === "sso"'),
+ section.indexOf(") : !visibleLeaderboard")
+ );
+ assert.ok(
+ recovery.includes('"auth.sso.continueWithSSO"'),
+ "the recovery card must name the existing SSO action"
+ );
+ assert.ok(recovery.includes("onSsoSignIn"));
+ assert.ok(view.includes("signInWithSSO(email)"));
+ assert.ok(view.includes("getOAuthProtocolRegistered"));
+ assert.ok(view.includes('t("auth.social.protocolUnavailable")'));
+ assert.ok(view.includes("oauthProtocolRegistered !== true || ssoStarting"));
+ assert.ok(view.includes('window.addEventListener("focus", handleFocus)'));
+});
diff --git a/test/components/leaderboardStaleBoard.test.js b/test/components/leaderboardStaleBoard.test.js
new file mode 100644
index 000000000..d4ec063d4
--- /dev/null
+++ b/test/components/leaderboardStaleBoard.test.js
@@ -0,0 +1,78 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { readFileSync } = require("node:fs");
+const { join } = require("node:path");
+
+const read = (relativePath) => readFileSync(join(__dirname, "../..", relativePath), "utf8");
+
+// A page turn, metric change or week change asks the same board a different
+// question. Blanking the card while the answer is in flight takes the podium,
+// the table, the period picker, Share and the pagination control the user just
+// clicked with it, then snaps it all back a moment later.
+test("a board in flight keeps the previous answer on screen instead of blanking", () => {
+ const section = read("src/components/LeaderboardSection.tsx");
+
+ assert.ok(
+ section.includes("leaderboard.scope.key === selectedScope.key"),
+ "the board on screen is kept while the same scope reloads"
+ );
+ assert.ok(
+ section.includes("const leaderboardStale ="),
+ "the kept board has to be marked stale so it can be dimmed"
+ );
+ assert.ok(
+ section.includes("aria-busy={leaderboardStale}"),
+ "a dimmed board still has to announce that it is refreshing"
+ );
+
+ // The dim has to sit on an element that can actually take an opacity:
+ // `display: contents` produces no box, so opacity on it is inert.
+ const wrapper = section.slice(
+ section.indexOf("aria-busy={leaderboardStale}"),
+ section.indexOf("aria-busy={leaderboardStale}") + 240
+ );
+ assert.equal(
+ wrapper.includes('"contents'),
+ false,
+ "display:contents draws no box, so it cannot carry the stale opacity"
+ );
+});
+
+// The generic failure path leaves the previous board in state, so a guard of
+// "no board" would let a failed page turn quietly render stale rows.
+test("a failure still takes the surface even with a previous board on screen", () => {
+ const section = read("src/components/LeaderboardSection.tsx");
+
+ assert.ok(section.includes("const noFreshLeaderboard ="));
+ assert.ok(section.includes('visibleFailure === "policy" && noFreshLeaderboard'));
+ assert.ok(section.includes("visibleFailure && noFreshLeaderboard"));
+ assert.equal(
+ section.includes("visibleFailure && !visibleLeaderboard"),
+ false,
+ "a stale board does not answer the request that just failed"
+ );
+});
+
+// useAuth keeps presenting a session whose refetch failed, so a signed-in user
+// can hold a null validated generation indefinitely. Waiting on it forever is a
+// spinner with no message and no way out.
+test("a settled session with no validated credential offers a way out", () => {
+ const section = read("src/components/LeaderboardSection.tsx");
+ const view = read("src/components/LeaderboardView.tsx");
+
+ assert.ok(section.includes("authSettled: boolean;"), "the section is told when auth settled");
+ assert.ok(
+ section.includes("setAccessLoading(!authSettled)"),
+ "an unvalidated credential only reads as loading while the session is unsettled"
+ );
+ assert.ok(
+ section.includes('setAccessError(authSettled ? "auth" : null)'),
+ "once settled it becomes the retry surface, which already offers Sign in"
+ );
+ assert.ok(
+ section.includes("[accountId, authGeneration, authSettled]"),
+ "the loader has to re-run when the session settles"
+ );
+ assert.ok(view.includes("isLoaded: authSettled"), "useAuth's isLoaded is what settled means");
+ assert.ok(view.includes("authSettled={authSettled}"));
+});
diff --git a/test/components/leaderboardStates.test.js b/test/components/leaderboardStates.test.js
new file mode 100644
index 000000000..6fedbf17c
--- /dev/null
+++ b/test/components/leaderboardStates.test.js
@@ -0,0 +1,201 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const path = require("node:path");
+const { createElement } = require("react");
+const { renderToStaticMarkup } = require("react-dom/server");
+const i18next = require("i18next");
+const { initReactI18next } = require("react-i18next");
+
+globalThis.React = require("react");
+
+async function initializeI18n() {
+ if (i18next.isInitialized) return;
+ const en = JSON.parse(
+ fs.readFileSync(path.join(__dirname, "../../src/locales/en/translation.json"), "utf8")
+ );
+ await i18next.use(initReactI18next).init({
+ lng: "en",
+ resources: { en: { translation: en } },
+ interpolation: { escapeValue: false },
+ });
+}
+
+async function component(relativePath) {
+ await initializeI18n();
+ const module = await import(`../../src/components/${relativePath}.tsx`);
+ return module.default.default ?? module.default;
+}
+
+function assertState(markup, state, cta) {
+ assert.match(markup, new RegExp(`data-leaderboard-state="${state}"`));
+ assert.ok(markup.includes(cta), `expected ${state} to show “${cta}”`);
+}
+
+test("create renders the workspace funnel and its primary action", async () => {
+ const Setup = await component("LeaderboardSetupCard");
+ const markup = renderToStaticMarkup(
+ createElement(Setup, {
+ colleagueCount: 3,
+ domain: "acme.com",
+ onCreate() {},
+ })
+ );
+ assertState(markup, "create", "Create workspace");
+ assert.ok(markup.includes("3 people at acme.com have joined leaderboards"));
+});
+
+test("request_join names the matched team and preserves the pending CTA", async () => {
+ const RequestJoin = await component("LeaderboardRequestJoinPreview");
+ const markup = renderToStaticMarkup(
+ createElement(RequestJoin, {
+ memberCount: 14,
+ onRequest() {},
+ pending: true,
+ requesting: false,
+ workspaceName: "Acme",
+ })
+ );
+ assertState(markup, "request_join", "Request sent");
+ assert.ok(markup.includes("Acme has 14 members"));
+ // Matched by pattern rather than substring: a bare-hostname includes() check
+ // trips CodeQL's incomplete-URL-sanitization rule (js/incomplete-url-substring
+ // -sanitization), which cannot tell an assertion on markup from a host check.
+ assert.doesNotMatch(markup, /acme\.com/);
+});
+
+test("accept_invite attributes the inviter and offers a direct join", async () => {
+ const AcceptInvite = await component("LeaderboardAcceptInvitePreview");
+ const markup = renderToStaticMarkup(
+ createElement(AcceptInvite, {
+ inviterName: "Sam",
+ joining: false,
+ onAccept() {},
+ workspaceName: "Acme",
+ })
+ );
+ assertState(markup, "accept_invite", "Join Team");
+ assert.ok(markup.includes("Sam invited you"));
+});
+
+test("workspace actions stay secondary when a domain leaderboard is ready", async () => {
+ const WorkspaceNudge = await component("LeaderboardWorkspaceNudge");
+ const invitation = renderToStaticMarkup(
+ createElement(WorkspaceNudge, {
+ kind: "accept_invite",
+ loading: false,
+ onAction() {},
+ pending: false,
+ workspaceName: "Acme",
+ })
+ );
+ const pendingRequest = renderToStaticMarkup(
+ createElement(WorkspaceNudge, {
+ kind: "request_join",
+ loading: false,
+ onAction() {},
+ pending: true,
+ workspaceName: "Acme",
+ })
+ );
+
+ assertState(invitation, "workspace_nudge", "Join Team");
+ assert.ok(invitation.includes("You&#x27;re invited to Acme"));
+ assertState(pendingRequest, "workspace_nudge", "Request sent");
+});
+
+test("invite keeps the teammate action primary without a second sync control", async () => {
+ const Invite = await component("LeaderboardSoloEmptyState");
+ const markup = renderToStaticMarkup(
+ createElement(Invite, {
+ scopeKind: "workspace",
+ scopeName: "Acme",
+ onInvite() {},
+ pendingInvites: ["[email protected]"],
+ })
+ );
+ assertState(markup, "invite", "Invite teammates");
+ assert.doesNotMatch(markup, /role="switch"/);
+ assert.ok(markup.includes("Invited: [email protected]"));
+});
+
+test("ready while not participating offers an explicit leaderboard join", async () => {
+ const Join = await component("LeaderboardJoinPreview");
+ const markup = renderToStaticMarkup(
+ createElement(Join, {
+ canJoin: true,
+ error: false,
+ leavePending: false,
+ onJoin() {},
+ scopeName: "Acme",
+ updating: false,
+ })
+ );
+ assertState(markup, "join", "See where you rank in Acme");
+ assert.match(markup, /<button/);
+ assert.ok(markup.includes("Join leaderboards"));
+});
+
+// A leave the network never delivered leaves the toggle off and the Join card
+// up. The card has to say the account is still coming off the boards, or that
+// silence reads as done.
+test("join says so while an opt-out is still owed to the account", async () => {
+ const Join = await component("LeaderboardJoinPreview");
+ const markup = renderToStaticMarkup(
+ createElement(Join, {
+ canJoin: true,
+ error: false,
+ leavePending: true,
+ onJoin() {},
+ scopeName: "Acme",
+ updating: false,
+ })
+ );
+ assertState(markup, "join", "See where you rank in Acme");
+ assert.ok(markup.includes("We&#x27;ll finish leaving the leaderboards when you&#x27;re online."));
+});
+
+test("a ready board with one of five participants renders the inline nudge", async () => {
+ const EmptyStrip = await component("LeaderboardEmptyStrip");
+ const useToastModule = await import("../../src/components/ui/useToast.ts");
+ const ToastContext = useToastModule.ToastContext ?? useToastModule.default.ToastContext;
+ const markup = renderToStaticMarkup(
+ createElement(
+ ToastContext.Provider,
+ { value: { toast() {}, dismiss() {}, toastCount: 0, dictationErrorActionCount: 0 } },
+ createElement(EmptyStrip, { missingCount: 4 })
+ )
+ );
+ assertState(markup, "empty_strip", "Copy a nudge");
+ assert.ok(markup.includes("4 teammates haven&#x27;t joined the leaderboard yet"));
+});
+
+test("podium cards accent all three placements", async () => {
+ const Podium = await component("LeaderboardPodium");
+ const members = [1, 2, 3].map((rank) => ({
+ userId: `user-${rank}`,
+ name: `Member ${rank}`,
+ email: `member-${rank}@acme.com`,
+ image: null,
+ rank,
+ totalWords: 1_000 - rank,
+ desktopWords: 900 - rank,
+ mobileWords: 100,
+ wordsPerMinute: 120,
+ currentDailyStreak: 5,
+ }));
+ const markup = renderToStaticMarkup(
+ createElement(Podium, {
+ formatValue: (member) => String(member.totalWords),
+ memberLabel: (member) => member.name || member.email || "Teammate",
+ members,
+ metricLabel: "Total words",
+ periodLabel: "Sep 7 – Sep 13",
+ title: "Top performers",
+ })
+ );
+
+ assert.ok(markup.includes("border-amber-400/25 bg-amber-400/5"));
+ assert.ok(markup.includes("border-slate-400/30 bg-slate-400/5"));
+ assert.ok(markup.includes("border-orange-500/25 bg-orange-500/5"));
+});
diff --git a/test/helpers/analyticsDatabase.test.js b/test/helpers/analyticsDatabase.test.js
index 9f7a2d5cb..cb8f382b2 100644
--- a/test/helpers/analyticsDatabase.test.js
+++ b/test/helpers/analyticsDatabase.test.js
@@ -190,7 +190,9 @@ test("pre-sign-in analytics are attributed only by an explicit claim", (t) => {
"signing in alone never adopts device-local rows"
);
- assert.equal(db.claimAnonymousAnalyticsEvents().claimed, 2);
+ assert.equal(db.claimAnonymousAnalyticsEvents("account-b").success, false);
+ assert.equal(db.countUnclaimedAnalyticsEvents(), 2, "another account cannot consume the claim");
+ assert.equal(db.claimAnonymousAnalyticsEvents("account-a").claimed, 2);
assert.equal(db.countUnclaimedAnalyticsEvents(), 0);
assert.deepEqual(
db
diff --git a/test/helpers/cloudApiRequest.test.js b/test/helpers/cloudApiRequest.test.js
index 126c53186..e968313af 100644
--- a/test/helpers/cloudApiRequest.test.js
+++ b/test/helpers/cloudApiRequest.test.js
@@ -86,6 +86,7 @@ test("a stable authenticated request is bearer-only and returns parsed data", as
assert.equal(options.headers.Authorization, "Bearer token-a");
assert.equal(options.headers["x-openwhispr-policy-version"], "1");
assert.equal(options.headers["x-openwhispr-version"], "1.2.3");
+ assert.equal(options.headers["x-openwhispr-source"], "desktop");
return new Response(JSON.stringify({ data: [{ id: "space-a" }] }));
});
@@ -107,6 +108,7 @@ test("public requests carry neither bearer nor cookies", async () => {
assert.equal(options.headers.Authorization, undefined);
assert.equal(options.headers["x-openwhispr-policy-version"], undefined);
assert.equal(options.headers["x-openwhispr-version"], "1.2.3");
+ assert.equal(options.headers["x-openwhispr-source"], "desktop");
return new Response(JSON.stringify({ data: { invite: "preview" } }));
});
diff --git a/test/helpers/insightsConsentCoordinator.test.js b/test/helpers/insightsConsentCoordinator.test.js
new file mode 100644
index 000000000..1f8b10fd2
--- /dev/null
+++ b/test/helpers/insightsConsentCoordinator.test.js
@@ -0,0 +1,74 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const load = () => import("../../src/helpers/insightsConsentCoordinator.ts");
+
+test("hook instances share one consent prompt for one auth context", async () => {
+ const { answerInsightsConsent, requestInsightsConsent } = await load();
+ const firstOwner = {};
+ const secondOwner = {};
+ const opened = [];
+ let closed = 0;
+ const first = requestInsightsConsent({
+ accountId: "account-a",
+ authGeneration: 7,
+ kind: "enable",
+ owner: firstOwner,
+ open: (kind) => opened.push(`first:${kind}`),
+ close: () => {
+ closed += 1;
+ },
+ });
+ const second = requestInsightsConsent({
+ accountId: "account-a",
+ authGeneration: 7,
+ kind: "enable",
+ owner: secondOwner,
+ open: (kind) => opened.push(`second:${kind}`),
+ close: () => {
+ closed += 1;
+ },
+ });
+
+ assert.strictEqual(second, first);
+ assert.deepEqual(opened, ["first:enable"]);
+ answerInsightsConsent(secondOwner, true);
+ assert.equal(closed, 0, "a hook that does not own the dialog cannot answer it");
+ answerInsightsConsent(firstOwner, true);
+ assert.deepEqual(await Promise.all([first, second]), [true, true]);
+ assert.equal(closed, 1);
+});
+
+test("a new auth context declines and closes the stale consent", async () => {
+ const { answerInsightsConsent, requestInsightsConsent } = await load();
+ const firstOwner = {};
+ const secondOwner = {};
+ let firstClosed = 0;
+ let secondClosed = 0;
+ const first = requestInsightsConsent({
+ accountId: "account-a",
+ authGeneration: 7,
+ kind: "claim",
+ owner: firstOwner,
+ open() {},
+ close: () => {
+ firstClosed += 1;
+ },
+ });
+ const second = requestInsightsConsent({
+ accountId: "account-b",
+ authGeneration: 8,
+ kind: "claim",
+ owner: secondOwner,
+ open() {},
+ close: () => {
+ secondClosed += 1;
+ },
+ });
+
+ assert.equal(await first, false);
+ assert.equal(firstClosed, 1);
+ answerInsightsConsent(secondOwner, true);
+ assert.equal(await second, true);
+ assert.equal(secondClosed, 1);
+});
diff --git a/test/helpers/leaderboard.test.js b/test/helpers/leaderboard.test.js
new file mode 100644
index 000000000..5db0b2c4d
--- /dev/null
+++ b/test/helpers/leaderboard.test.js
@@ -0,0 +1,255 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const load = () => import("../../src/helpers/leaderboard.ts");
+
+test("lifetime metrics force all time and weekly selection hides them", async () => {
+ const { normalizeLeaderboardSelection, selectionForRange } = await load();
+ assert.deepEqual(normalizeLeaderboardSelection("words_per_minute", "week"), {
+ metric: "words_per_minute",
+ range: "all",
+ });
+ assert.deepEqual(selectionForRange("current_daily_streak", "week"), {
+ metric: "total_words",
+ range: "week",
+ });
+ assert.deepEqual(normalizeLeaderboardSelection("mobile_words", "week"), {
+ metric: "mobile_words",
+ range: "week",
+ });
+});
+
+// The picker's two tiers and the rules that move a selection between them are
+// one fact, so a metric offered under "This week" must survive that range.
+test("the metric tiers agree with the selection rules", async () => {
+ const { ALL_TIME_METRICS, WEEKLY_METRICS, normalizeLeaderboardSelection, selectionForRange } =
+ await load();
+ assert.deepEqual(WEEKLY_METRICS, ["total_words", "desktop_words", "mobile_words"]);
+ assert.deepEqual(ALL_TIME_METRICS, [
+ ...WEEKLY_METRICS,
+ "words_per_minute",
+ "current_daily_streak",
+ ]);
+ for (const metric of WEEKLY_METRICS) {
+ assert.deepEqual(normalizeLeaderboardSelection(metric, "week"), { metric, range: "week" });
+ assert.deepEqual(selectionForRange(metric, "week"), { metric, range: "week" });
+ }
+ for (const metric of ALL_TIME_METRICS.filter((value) => !WEEKLY_METRICS.includes(value))) {
+ assert.equal(normalizeLeaderboardSelection(metric, "week").range, "all");
+ assert.equal(selectionForRange(metric, "week").metric, "total_words");
+ }
+});
+
+test("rank jumps and pagination clamp safely at 20 rows per page", async () => {
+ const { LEADERBOARD_PAGE_SIZE, pageCount, pageForRank, shouldShowLeaderboardJumpToMe } =
+ await load();
+ assert.equal(LEADERBOARD_PAGE_SIZE, 20);
+ assert.equal(pageCount(0), 1);
+ assert.equal(pageCount(20), 1);
+ assert.equal(pageCount(21), 2);
+ assert.equal(pageForRank(1, 55), 0);
+ assert.equal(pageForRank(20, 55), 0);
+ assert.equal(pageForRank(21, 55), 1);
+ assert.equal(pageForRank(10_000, 55), 2);
+ assert.equal(shouldShowLeaderboardJumpToMe(9), false);
+ assert.equal(shouldShowLeaderboardJumpToMe(10), true);
+});
+
+// The response carries the page size the server actually used, so a server that
+// pages differently must not send jump-to-rank to the wrong page.
+test("pagination follows the page size the response reports", async () => {
+ const { pageCount, pageForRank } = await load();
+ assert.equal(pageCount(55, 10), 6);
+ assert.equal(pageForRank(21, 55, 10), 2);
+ assert.equal(pageForRank(55, 55, 50), 1);
+});
+
+test("leaderboard surfaces fail closed on unknown participation before scope state", async () => {
+ const { resolveLeaderboardSurface } = await load();
+ const access = {
+ state: "create",
+ scopes: [],
+ domain: null,
+ colleagueCount: 0,
+ invitation: null,
+ joinableWorkspace: null,
+ };
+ const scope = {
+ key: "workspace:one",
+ kind: "workspace",
+ id: "one",
+ name: "One",
+ memberCount: 1,
+ state: "invite",
+ role: "owner",
+ };
+ const surface = (overrides = {}) =>
+ resolveLeaderboardSurface({
+ access,
+ selectedScope: null,
+ participating: false,
+ participationReady: true,
+ participationError: null,
+ ...overrides,
+ });
+
+ assert.equal(surface(), "create");
+ assert.equal(surface({ access: { ...access, state: "accept_invite" } }), "accept_invite");
+ assert.equal(surface({ access: { ...access, state: "request_join" } }), "request_join");
+ assert.equal(
+ surface({ access: { ...access, state: "accept_invite" }, selectedScope: scope }),
+ "accept_invite"
+ );
+ assert.equal(
+ surface({ access: { ...access, state: "request_join" }, selectedScope: scope }),
+ "request_join"
+ );
+ assert.equal(
+ surface({
+ access: { ...access, state: "accept_invite" },
+ selectedScope: { ...scope, state: "ready" },
+ }),
+ "join",
+ "a ready domain board must not be hidden by a workspace invitation"
+ );
+ assert.equal(
+ surface({
+ access: { ...access, state: "request_join" },
+ selectedScope: { ...scope, state: "ready" },
+ participating: true,
+ }),
+ "board",
+ "a pending workspace request must not hide a ready domain board"
+ );
+ // A solo scope is still a board. Answering "invite someone" to an account
+ // that never opted in strands it: that surface carries no way to join, and
+ // the Create workspace funnel lands exactly there.
+ assert.equal(
+ surface({ selectedScope: scope, participating: false }),
+ "join",
+ "a solo scope must still ask an account that never opted in to join"
+ );
+ assert.equal(
+ surface({ selectedScope: scope, participating: true }),
+ "invite",
+ "once joined, a scope of one is the solo empty state"
+ );
+ assert.equal(
+ surface({ selectedScope: { ...scope, state: "ready" }, participating: true }),
+ "board"
+ );
+ assert.equal(
+ surface({ selectedScope: scope, participationReady: false }),
+ "participation_loading"
+ );
+ assert.equal(
+ surface({ selectedScope: scope, participationReady: false, participationError: "read" }),
+ "participation_error"
+ );
+ assert.equal(
+ surface({ selectedScope: { ...scope, state: "ready" }, participationReady: false }),
+ "participation_loading"
+ );
+ assert.equal(
+ surface({
+ selectedScope: { ...scope, state: "ready" },
+ participationReady: false,
+ participationError: "read",
+ }),
+ "participation_error"
+ );
+ assert.equal(surface({ selectedScope: { ...scope, state: "ready" } }), "join");
+ assert.equal(
+ surface({ selectedScope: { ...scope, state: "ready" }, participating: true }),
+ "board"
+ );
+ assert.equal(
+ surface({
+ selectedScope: { ...scope, state: "ready" },
+ participationReady: true,
+ participationError: "read",
+ }),
+ "participation_error",
+ "the store reports read failures after returning to its ready state"
+ );
+});
+
+test("leaderboard request identity changes with every ranking control", async () => {
+ const { leaderboardRequestKey } = await load();
+ const current = leaderboardRequestKey("workspace:one", "total_words", "week", null, 0);
+ assert.equal(current, leaderboardRequestKey("workspace:one", "total_words", "week", null, 0));
+ for (const changed of [
+ leaderboardRequestKey("workspace:two", "total_words", "week", null, 0),
+ leaderboardRequestKey("workspace:one", "desktop_words", "week", null, 0),
+ leaderboardRequestKey("workspace:one", "total_words", "all", null, 0),
+ leaderboardRequestKey("workspace:one", "total_words", "week", "2026-08-24", 0),
+ leaderboardRequestKey("workspace:one", "total_words", "week", null, 1),
+ ]) {
+ assert.notEqual(changed, current);
+ }
+});
+
+test("available leaderboard weeks refresh only when the per-scope cache expires", async () => {
+ const { mergeLeaderboardWeekStarts, shouldFetchLeaderboardWeekStarts } = await load();
+ const now = 1_000;
+
+ assert.equal(shouldFetchLeaderboardWeekStarts(undefined, now), true);
+ assert.equal(
+ shouldFetchLeaderboardWeekStarts({ values: ["2026-08-31"], expiresAt: now + 1 }, now),
+ false
+ );
+ assert.equal(
+ shouldFetchLeaderboardWeekStarts({ values: ["2026-08-31"], expiresAt: now }, now),
+ true
+ );
+ assert.deepEqual(
+ mergeLeaderboardWeekStarts(["2026-08-24", "2026-08-31"], ["2026-09-07", "2026-08-31"]),
+ ["2026-09-07", "2026-08-31", "2026-08-24"]
+ );
+});
+
+test("workspace defaults are readable and derived only from the company domain", async () => {
+ const { domainToWorkspaceName } = await load();
+ assert.equal(domainToWorkspaceName("acme.com"), "Acme");
+ assert.equal(domainToWorkspaceName("north-star.example.co.uk"), "North Star");
+ assert.equal(domainToWorkspaceName("WWW.EXAMPLE.COM"), "Example");
+ assert.equal(domainToWorkspaceName(null), "");
+});
+
+test("scope selection prefers a usable membership and then any usable board", async () => {
+ const { resolveLeaderboardScopeKey } = await load();
+ const domain = {
+ key: "domain:acme.com",
+ kind: "domain",
+ id: "acme.com",
+ name: "acme.com",
+ state: "ready",
+ };
+ const workspace = {
+ key: "workspace:one",
+ kind: "workspace",
+ id: "one",
+ name: "One",
+ state: "ready",
+ };
+ const unavailableDomain = { ...domain, key: "domain:solo.test", state: "invite" };
+ const soloWorkspace = { ...workspace, key: "workspace:solo", state: "invite" };
+
+ assert.equal(resolveLeaderboardScopeKey([domain], null), domain.key);
+ assert.equal(resolveLeaderboardScopeKey([unavailableDomain], null), null);
+ assert.equal(resolveLeaderboardScopeKey([domain, workspace], null), workspace.key);
+ assert.equal(resolveLeaderboardScopeKey([soloWorkspace, domain], null), domain.key);
+ assert.equal(resolveLeaderboardScopeKey([workspace, domain], domain.key), domain.key);
+ assert.equal(resolveLeaderboardScopeKey([domain, workspace], null, workspace.key), workspace.key);
+ assert.equal(resolveLeaderboardScopeKey([workspace], "workspace:gone"), workspace.key);
+});
+
+test("the partial-participation strip appears only while a board has at most one participant", async () => {
+ const { missingLeaderboardMembers, shouldShowLeaderboardEmptyStrip } = await load();
+ assert.equal(missingLeaderboardMembers(5, 1), 4);
+ assert.equal(missingLeaderboardMembers(2, 5), 0);
+ assert.equal(shouldShowLeaderboardEmptyStrip(5, 1), true);
+ assert.equal(shouldShowLeaderboardEmptyStrip(5, 0), true);
+ assert.equal(shouldShowLeaderboardEmptyStrip(5, 2), false);
+ assert.equal(shouldShowLeaderboardEmptyStrip(1, 1), false);
+});
diff --git a/test/helpers/leaderboardImage.test.js b/test/helpers/leaderboardImage.test.js
new file mode 100644
index 000000000..44ef4dc7f
--- /dev/null
+++ b/test/helpers/leaderboardImage.test.js
@@ -0,0 +1,23 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const {
+ decodeLeaderboardPngDataUrl,
+ leaderboardImageFilename,
+} = require("../../src/helpers/leaderboardImage");
+
+const PNG_HEADER = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
+
+test("leaderboard image IPC accepts bounded PNG data only", () => {
+ const decoded = decodeLeaderboardPngDataUrl(
+ `data:image/png;base64,${PNG_HEADER.toString("base64")}`
+ );
+ assert.deepEqual(decoded, PNG_HEADER);
+ assert.throws(() => decodeLeaderboardPngDataUrl("data:text/plain;base64,SGVsbG8="), /PNG/);
+ assert.throws(() => decodeLeaderboardPngDataUrl("data:image/png;base64,%%%%"), /base64/);
+});
+
+test("leaderboard downloads cannot inject paths through the suggested name", () => {
+ assert.equal(leaderboardImageFilename("Acme leaderboard"), "Acme-leaderboard.png");
+ assert.equal(leaderboardImageFilename("../../secret.txt"), "..-..-secret.txt.png");
+ assert.equal(leaderboardImageFilename("team.png"), "team.png");
+});
diff --git a/test/helpers/syncAnalyticsFlushDetach.test.js b/test/helpers/syncAnalyticsFlushDetach.test.js
new file mode 100644
index 000000000..577fa5072
--- /dev/null
+++ b/test/helpers/syncAnalyticsFlushDetach.test.js
@@ -0,0 +1,48 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const {
+ installBrowserGlobals,
+ resetBrowserGlobals,
+ enableSync,
+ establishValidatedAuth,
+ stopSyncTimers,
+ window: windowStub,
+} = require("./harness/browserGlobals.js");
+const { SyncService } = require("../../src/services/SyncService.ts");
+const { LeaderboardService } = require("../../src/services/LeaderboardService.ts");
+
+// syncAnalytics runs under SYNC_ALL_LOCK, and a cloud request carries no
+// timeout. Awaiting the pending-leave retry there let one hung PATCH hold every
+// window's sync behind the lock for as long as the socket stayed open.
+test("a hung leaderboard leave retry does not hold the analytics pass", async (t) => {
+ resetBrowserGlobals();
+ installBrowserGlobals();
+ enableSync();
+ // Just enough bridge to validate a session. There are no analytics rows and
+ // no upload path, which is exactly the pass that used to sit behind the retry.
+ windowStub.electronAPI = {
+ authGetTokenState: async () => ({ token: "harness-token", generation: 1 }),
+ };
+ await establishValidatedAuth();
+ const service = new SyncService();
+ t.after(() => stopSyncTimers(service));
+ t.mock.method(console, "error", () => {});
+
+ let retries = 0;
+ t.mock.method(LeaderboardService, "flushPendingLeave", () => {
+ retries += 1;
+ return new Promise(() => {});
+ });
+
+ const outcome = await Promise.race([
+ service.syncAnalyticsNow().then(
+ () => "settled",
+ () => "settled"
+ ),
+ new Promise((resolve) => setTimeout(() => resolve("held"), 1_000)),
+ ]);
+
+ assert.equal(retries, 1, "the retry is still issued on every pass");
+ assert.equal(outcome, "settled", "the pass may not wait on a request that never answers");
+});
diff --git a/test/hooks/insightsSyncOptIn.test.js b/test/hooks/insightsSyncOptIn.test.js
new file mode 100644
index 000000000..688ac7363
--- /dev/null
+++ b/test/hooks/insightsSyncOptIn.test.js
@@ -0,0 +1,190 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const React = require("react");
+const { createRoot } = require("react-dom/client");
+const {
+ createRendererServer,
+ installBrowserGlobals,
+ installHookDom,
+} = require("../lib/rendererTestHarness");
+
+test("Insights Sync opt-in changes only device analytics consent", async (t) => {
+ let root = null;
+ let hook;
+ t.mock.method(console, "error", () => {});
+ t.after(() => {
+ for (const key of [
+ "__insightsAwaitingUploadCount",
+ "__insightsClaimAccepted",
+ "__insightsClaimCalls",
+ "__insightsClaimMode",
+ "__insightsConsentRequests",
+ "__insightsAuthGeneration",
+ "__insightsSetEnabledValues",
+ "__insightsSyncEnabled",
+ "__insightsSyncRequests",
+ "__insightsToasts",
+ "__insightsUnclaimedCount",
+ ]) {
+ delete globalThis[key];
+ }
+ });
+
+ globalThis.__insightsAwaitingUploadCount = 1;
+ globalThis.__insightsClaimAccepted = true;
+ globalThis.__insightsClaimCalls = 0;
+ globalThis.__insightsClaimMode = "failure";
+ globalThis.__insightsConsentRequests = 0;
+ globalThis.__insightsAuthGeneration = 7;
+ globalThis.__insightsSetEnabledValues = [];
+ globalThis.__insightsSyncEnabled = false;
+ globalThis.__insightsSyncRequests = 0;
+ globalThis.__insightsToasts = [];
+ globalThis.__insightsUnclaimedCount = 1;
+
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ claimAnonymousAnalyticsEvents: async () => {
+ globalThis.__insightsClaimCalls += 1;
+ if (globalThis.__insightsClaimMode === "rejection") {
+ throw new Error("database unavailable");
+ }
+ if (globalThis.__insightsClaimMode === "auth-change-success") {
+ globalThis.__insightsAuthGeneration += 1;
+ }
+ return globalThis.__insightsClaimMode === "success" ||
+ globalThis.__insightsClaimMode === "auth-change-success"
+ ? { success: true, claimed: 1 }
+ : { success: false, claimed: 0, code: "AUTH_CONTEXT_CHANGED" };
+ },
+ countUnclaimedAnalyticsEvents: async () => globalThis.__insightsUnclaimedCount,
+ countAnalyticsEventsAwaitingUpload: async () => globalThis.__insightsAwaitingUploadCount,
+ onAnalyticsChanged: () => () => {},
+ },
+ },
+ });
+ const container = installHookDom(t);
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-insights-sync-opt-in-",
+ noExternal: ["react-i18next"],
+ mockModules: {
+ "/components/ui/dialog": "export const ConfirmDialog = () => null;",
+ "/components/ui/useToast": `
+ const toast = (props) => globalThis.__insightsToasts.push(props);
+ export const useToast = () => ({ toast });
+ `,
+ "/helpers/insightsConsentCoordinator": `
+ export const answerInsightsConsent = () => {};
+ export const cancelInsightsConsent = () => {};
+ export const requestInsightsConsent = async () => {
+ globalThis.__insightsConsentRequests += 1;
+ return globalThis.__insightsClaimAccepted;
+ };
+ `,
+ "./useAuth": `
+ export const useAuth = () => ({ user: { id: "account-1" } });
+ `,
+ "./useSettings": `
+ export const useSettings = () => ({
+ insightsSyncEnabled: globalThis.__insightsSyncEnabled,
+ setInsightsSyncEnabled: (enabled) => {
+ globalThis.__insightsSyncEnabled = enabled;
+ globalThis.__insightsSetEnabledValues.push(enabled);
+ }
+ });
+ `,
+ "/lib/authRequestContext": `
+ export const getValidatedAuthGeneration = () => globalThis.__insightsAuthGeneration;
+ `,
+ "/services/SyncService.js": `
+ export const syncService = {
+ requestSyncAll: () => { globalThis.__insightsSyncRequests += 1; }
+ };
+ `,
+ "/stores/policyRules": `
+ export const canChangeCloudBackupPreference = () => true;
+ export const isCloudBackupAllowed = () => true;
+ `,
+ "/stores/policyStore": `
+ export const usePolicyStore = (selector) => selector({});
+ `,
+ "react-i18next": `
+ const t = (key) => key;
+ export const useTranslation = () => ({ t });
+ `,
+ },
+ });
+ const { useInsightsSyncOptIn } = await vite.ssrLoadModule("/hooks/useInsightsSyncOptIn.tsx");
+
+ function Harness() {
+ hook = useInsightsSyncOptIn();
+ return null;
+ }
+
+ const render = async () => {
+ await React.act(async () => {
+ root.render(React.createElement(Harness));
+ await Promise.resolve();
+ });
+ };
+ const enable = async () => {
+ let result;
+ await React.act(async () => {
+ result = await hook.enableInsightsSync();
+ });
+ return result;
+ };
+
+ root = createRoot(container);
+ await render();
+
+ assert.equal(await enable(), false);
+ assert.deepEqual(globalThis.__insightsToasts, [
+ { title: "insights.syncEnableError", variant: "destructive" },
+ ]);
+ assert.deepEqual(globalThis.__insightsSetEnabledValues, []);
+ assert.equal(globalThis.__insightsSyncRequests, 0);
+
+ globalThis.__insightsClaimMode = "rejection";
+ assert.equal(await enable(), false);
+ assert.equal(globalThis.__insightsToasts.length, 2);
+ assert.deepEqual(globalThis.__insightsSetEnabledValues, []);
+
+ globalThis.__insightsClaimAccepted = false;
+ const claimCallsBeforeDecline = globalThis.__insightsClaimCalls;
+ assert.equal(await enable(), false);
+ assert.equal(globalThis.__insightsClaimCalls, claimCallsBeforeDecline);
+ assert.equal(globalThis.__insightsToasts.length, 2, "declining consent stays quiet");
+
+ globalThis.__insightsClaimAccepted = true;
+ globalThis.__insightsClaimMode = "success";
+ assert.equal(await enable(), true);
+ assert.deepEqual(globalThis.__insightsSetEnabledValues, [true]);
+ assert.equal(globalThis.__insightsSyncRequests, 1);
+
+ await React.act(async () => hook.disableInsightsSync());
+ assert.deepEqual(globalThis.__insightsSetEnabledValues, [true, false]);
+ assert.equal(globalThis.__insightsSyncRequests, 1);
+
+ await render();
+ globalThis.__insightsClaimMode = "auth-change-success";
+ const settingsWritesBeforeAuthChange = globalThis.__insightsSetEnabledValues.length;
+ assert.equal(await enable(), false);
+ assert.equal(globalThis.__insightsSetEnabledValues.length, settingsWritesBeforeAuthChange);
+
+ globalThis.__insightsAuthGeneration = 7;
+ globalThis.__insightsAwaitingUploadCount = 0;
+ globalThis.__insightsUnclaimedCount = 0;
+ globalThis.__insightsClaimMode = "success";
+ const consentRequestsBeforeEmptyEnable = globalThis.__insightsConsentRequests;
+ const claimCallsBeforeEmptyEnable = globalThis.__insightsClaimCalls;
+ await render();
+ assert.equal(await enable(), true);
+ assert.equal(globalThis.__insightsConsentRequests, consentRequestsBeforeEmptyEnable);
+ assert.equal(globalThis.__insightsClaimCalls, claimCallsBeforeEmptyEnable);
+ assert.equal(globalThis.__insightsSyncRequests, 2);
+
+ await React.act(async () => root.unmount());
+ root = null;
+});
diff --git a/test/hooks/leaderboardParticipation.test.js b/test/hooks/leaderboardParticipation.test.js
new file mode 100644
index 000000000..4f1e617b7
--- /dev/null
+++ b/test/hooks/leaderboardParticipation.test.js
@@ -0,0 +1,156 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const React = require("react");
+const { createRoot } = require("react-dom/client");
+const {
+ createRendererServer,
+ installBrowserGlobals,
+ installHookDom,
+} = require("../lib/rendererTestHarness");
+
+test("leaderboard participation is account-scoped across auth changes", async (t) => {
+ let root = null;
+ let hook;
+ t.after(() => {
+ for (const key of [
+ "__participationAuthGeneration",
+ "__participationJoinMode",
+ "__participationJoins",
+ "__participationLeaves",
+ "__participationPendingLeaves",
+ "__participationQueuedLeaves",
+ "__participationRefreshes",
+ "__participationResets",
+ "__participationSessionUserId",
+ ]) {
+ delete globalThis[key];
+ }
+ });
+
+ globalThis.__participationAuthGeneration = 7;
+ globalThis.__participationJoinMode = "success";
+ globalThis.__participationJoins = [];
+ globalThis.__participationLeaves = [];
+ globalThis.__participationPendingLeaves = [];
+ globalThis.__participationQueuedLeaves = [];
+ globalThis.__participationRefreshes = [];
+ globalThis.__participationResets = 0;
+ globalThis.__participationSessionUserId = "account-1";
+
+ installBrowserGlobals(t);
+ const container = installHookDom(t);
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-leaderboard-participation-hook-",
+ mockModules: {
+ "./useAuth": `
+ export const useAuth = () => ({
+ isLoaded: true,
+ isSignedIn: true,
+ user: { id: "account-1" }
+ });
+ `,
+ "/lib/authRequestContext": `
+ export const getAuthRequestContextSnapshot = () => ({
+ sessionUserId: globalThis.__participationSessionUserId
+ });
+ export const getValidatedAuthGeneration = () =>
+ globalThis.__participationAuthGeneration;
+ `,
+ "/lib/pendingLeaderboardLeave": `
+ export const writePendingLeaderboardLeave = (userId) => {
+ globalThis.__participationPendingLeaves.push(userId);
+ };
+ `,
+ "/stores/leaderboardParticipationStore": `
+ const state = {
+ enabled: false,
+ ready: true,
+ error: null,
+ updating: false,
+ refresh: async (context) => {
+ globalThis.__participationRefreshes.push(context);
+ },
+ reset: () => { globalThis.__participationResets += 1; },
+ join: async (context) => {
+ globalThis.__participationJoins.push(context);
+ if (globalThis.__participationJoinMode === "auth-change-success") {
+ globalThis.__participationAuthGeneration += 1;
+ }
+ return globalThis.__participationJoinMode !== "failure";
+ },
+ leave: async (context) => {
+ globalThis.__participationLeaves.push(context);
+ return true;
+ },
+ queueLeave: (userId) => {
+ globalThis.__participationQueuedLeaves.push(userId);
+ }
+ };
+ export const useLeaderboardParticipationStore = (selector) => selector(state);
+ useLeaderboardParticipationStore.getState = () => state;
+ `,
+ },
+ });
+ const { useLeaderboardParticipation } = await vite.ssrLoadModule(
+ "/hooks/useLeaderboardParticipation.ts"
+ );
+
+ function Harness() {
+ hook = useLeaderboardParticipation();
+ return null;
+ }
+
+ const render = async () => {
+ await React.act(async () => {
+ root.render(React.createElement(Harness));
+ await Promise.resolve();
+ });
+ };
+ const invoke = async (action) => {
+ let result;
+ await React.act(async () => {
+ result = await action();
+ });
+ return result;
+ };
+
+ root = createRoot(container);
+ await render();
+ assert.deepEqual(globalThis.__participationRefreshes, [
+ { userId: "account-1", authGeneration: 7 },
+ ]);
+
+ assert.equal(await invoke(hook.join), true);
+ assert.deepEqual(globalThis.__participationJoins.at(-1), {
+ userId: "account-1",
+ authGeneration: 7,
+ });
+
+ globalThis.__participationJoinMode = "failure";
+ assert.equal(await invoke(hook.join), false);
+ assert.deepEqual(globalThis.__participationPendingLeaves, []);
+
+ globalThis.__participationJoinMode = "auth-change-success";
+ assert.equal(await invoke(hook.join), true);
+ assert.deepEqual(globalThis.__participationPendingLeaves, []);
+
+ globalThis.__participationAuthGeneration = null;
+ globalThis.__participationJoinMode = "success";
+ await render();
+ assert.equal(globalThis.__participationResets, 1);
+ assert.equal(await invoke(hook.leave), false);
+ assert.deepEqual(globalThis.__participationQueuedLeaves, ["account-1"]);
+
+ globalThis.__participationSessionUserId = "account-2";
+ assert.equal(await invoke(hook.leave), false);
+ assert.deepEqual(globalThis.__participationPendingLeaves, ["account-1"]);
+
+ globalThis.__participationSessionUserId = "account-1";
+ globalThis.__participationAuthGeneration = 8;
+ await render();
+ assert.equal(await invoke(hook.leave), true);
+ assert.deepEqual(globalThis.__participationLeaves, [{ userId: "account-1", authGeneration: 8 }]);
+
+ await React.act(async () => root.unmount());
+ root = null;
+});
diff --git a/test/lib/pendingLeaderboardLeave.test.js b/test/lib/pendingLeaderboardLeave.test.js
new file mode 100644
index 000000000..8fc8361d3
--- /dev/null
+++ b/test/lib/pendingLeaderboardLeave.test.js
@@ -0,0 +1,59 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { installBrowserGlobals } = require("./rendererTestHarness");
+
+test("different accounts keep independent durable leaderboard leaves", async (t) => {
+ const { storage } = installBrowserGlobals(t);
+ const {
+ clearPendingLeaderboardLeave,
+ readPendingLeaderboardLeave,
+ writePendingLeaderboardLeave,
+ } = require("../../src/lib/pendingLeaderboardLeave.ts");
+
+ writePendingLeaderboardLeave("user/one");
+ writePendingLeaderboardLeave("user/two");
+ clearPendingLeaderboardLeave("user/one");
+
+ assert.equal(readPendingLeaderboardLeave("user/one"), false);
+ assert.equal(readPendingLeaderboardLeave("user/two"), true);
+ assert.equal(storage.getItem("leaderboardLeavePending:user%2Ftwo"), '{"attempts":0}');
+});
+
+// Builds before the attempt bound stored a bare "true". Reading one as anything
+// but a pending leave would silently put the account back on a leaderboard.
+test("a leave recorded by an older build still counts and can still be charged", async (t) => {
+ installBrowserGlobals(t, {
+ initialStorage: { "leaderboardLeavePending:user%2Fold": "true" },
+ });
+ const {
+ pendingLeaderboardLeaveDeservesPriority,
+ readPendingLeaderboardLeave,
+ recordPendingLeaderboardLeaveAttempt,
+ MAX_PRIORITY_LEAVE_ATTEMPTS,
+ } = require("../../src/lib/pendingLeaderboardLeave.ts");
+
+ assert.equal(readPendingLeaderboardLeave("user/old"), true);
+ assert.equal(pendingLeaderboardLeaveDeservesPriority("user/old"), true);
+
+ for (let attempt = 0; attempt < MAX_PRIORITY_LEAVE_ATTEMPTS; attempt += 1) {
+ recordPendingLeaderboardLeaveAttempt("user/old");
+ }
+
+ assert.equal(pendingLeaderboardLeaveDeservesPriority("user/old"), false);
+ assert.equal(readPendingLeaderboardLeave("user/old"), true);
+});
+
+test("an account with no pending leave is never charged an attempt", async (t) => {
+ const { storage } = installBrowserGlobals(t);
+ const {
+ pendingLeaderboardLeaveDeservesPriority,
+ readPendingLeaderboardLeave,
+ recordPendingLeaderboardLeaveAttempt,
+ } = require("../../src/lib/pendingLeaderboardLeave.ts");
+
+ recordPendingLeaderboardLeaveAttempt("user/none");
+
+ assert.equal(storage.getItem("leaderboardLeavePending:user%2Fnone"), null);
+ assert.equal(readPendingLeaderboardLeave("user/none"), false);
+ assert.equal(pendingLeaderboardLeaveDeservesPriority("user/none"), false);
+});
diff --git a/test/services/analyticsClaimContract.test.js b/test/services/analyticsClaimContract.test.js
index 8a2a0a3ce..8e58eac6d 100644
--- a/test/services/analyticsClaimContract.test.js
+++ b/test/services/analyticsClaimContract.test.js
@@ -3,45 +3,286 @@ const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
-const read = (relativePath) =>
- fs.readFileSync(path.join(__dirname, "../..", relativePath), "utf8");
-
-// Adopting unattributed counters is a consent decision, not a sync step. The
-// device-local rows carry no account precisely because nobody was signed in
-// when they were spoken, and insightsSyncEnabled is device-scoped and survives
-// sign-out while sign-out clears only isSignedIn. A claim inside the sync path
-// therefore reads as: user A signs out, dictates, user B signs in, and B's
-// first pass uploads A's counters into B's account -- unrevocably, since this
-// client never calls the cloud's analytics delete route. The claim must stay
-// where the user is actually asked (useInsightsSyncOptIn's dialog).
+const read = (relativePath) => fs.readFileSync(path.join(__dirname, "../..", relativePath), "utf8");
+
test("syncing analytics never adopts unattributed counters", () => {
assert.equal(
read("src/services/AnalyticsService.ts").includes("claimAnonymousAnalyticsEvents"),
false,
- "the sync path must never claim rows: it would move one account's counters into another"
+ "the sync path must never assign one account's local counters to another"
);
});
-test("the opt-in dialog is still the one path that claims them", () => {
- assert.ok(
- read("src/hooks/useInsightsSyncOptIn.tsx").includes("claimAnonymousAnalyticsEvents"),
- "the explicit claim prompt still owns adoption"
- );
+test("the explicit Insights prompt is the one path that claims local counters", () => {
+ assert.ok(read("src/hooks/useInsightsSyncOptIn.tsx").includes("claimAnonymousAnalyticsEvents"));
});
-// Source-contract pin: the banner has no unit-testable seam of its own (this
-// suite has no React harness), so this pins that the view asks the predicate
-// instead of re-deriving the gate from the sync toggle -- which is what left
-// counters recorded while signed out unclaimable.
-test("the Insights view asks the predicate whether to offer the claim", () => {
+test("the Insights view uses the shared predicate for the claim offer", () => {
const view = read("src/components/InsightsView.tsx");
+ assert.ok(view.includes("canOfferAnalyticsClaim({"));
+ assert.equal(
+ view.includes("!insightsSyncEnabled &&"),
+ false,
+ "sync left on across sign-out must not strand later unattributed counters"
+ );
+});
+
+test("Insights Sync and leaderboard participation have separate owners", () => {
+ const syncHook = read("src/hooks/useInsightsSyncOptIn.tsx");
+ const participationHook = read("src/hooks/useLeaderboardParticipation.ts");
+ const settings = read("src/components/SettingsPage.tsx");
+ const leaderboard = read("src/components/LeaderboardView.tsx");
+
+ assert.ok(syncHook.includes("const enableInsightsSync"));
+ assert.ok(syncHook.includes("const disableInsightsSync"));
+ assert.equal(syncHook.includes("LeaderboardParticipation"), false);
+ assert.equal(syncHook.includes("joinParticipation"), false);
+ assert.equal(syncHook.includes("leaveParticipation"), false);
+
+ assert.ok(participationHook.includes("store.join(context)"));
+ assert.ok(participationHook.includes("store.leave(context)"));
+ assert.equal(participationHook.includes("setInsightsSyncEnabled"), false);
+
+ assert.ok(settings.includes("if (enabled) void enableInsightsSync()"));
+ assert.ok(settings.includes("disableInsightsSync()"));
+ assert.ok(settings.includes("useLeaderboardParticipation()"));
+ assert.ok(settings.includes("join: joinLeaderboard"));
+ assert.ok(settings.includes("leave: leaveLeaderboard"));
+ assert.ok(settings.includes("updateLeaderboardParticipation"));
+ assert.ok(leaderboard.includes("useLeaderboardParticipation()"));
+});
+
+test("joining obtains explicit analytics consent first without rollback coupling", () => {
+ const view = read("src/components/LeaderboardView.tsx");
+ const joinStart = view.indexOf("const joinLeaderboard");
+ const join = view.slice(joinStart, view.indexOf("return (", joinStart));
+ assert.match(
+ join,
+ /!insightsSyncEnabled\s*&&\s*!\(await enableInsightsSync\(\{ confirmWhenEmpty: true \}\)\)/
+ );
assert.ok(
- view.includes("canOfferAnalyticsClaim({"),
- "the banner gate must come from canOfferAnalyticsClaim"
+ join.indexOf("await enableInsightsSync({") < join.indexOf("joinParticipation()"),
+ "analytics consent must land before the account is published"
);
assert.equal(
- view.includes("!insightsSyncEnabled &&"),
+ join.includes("disableInsightsSync"),
false,
- "gating the offer on the toggle alone strands counters recorded while signed out"
+ "a failed participation write must preserve accepted analytics consent"
+ );
+});
+
+test("the Privacy leaderboard toggle preserves the same consent ordering", () => {
+ const settings = read("src/components/SettingsPage.tsx");
+ const updateStart = settings.indexOf("const updateLeaderboardParticipation");
+ const update = settings.slice(updateStart, settings.indexOf("// Signed out", updateStart));
+
+ assert.ok(update.includes("enableInsightsSync({ confirmWhenEmpty: true })"));
+ assert.ok(
+ update.indexOf("await enableInsightsSync({") < update.indexOf("await joinLeaderboard()")
+ );
+ assert.ok(update.includes("await leaveLeaderboard()"));
+ assert.equal(update.includes("disableInsightsSync"), false);
+ assert.ok(settings.includes('label={t("insights.leaderboard.title")}'));
+ assert.ok(settings.includes("checked={isSignedIn && leaderboardParticipationEnabled}"));
+ assert.ok(settings.includes('t("settingsPage.privacy.leaderboardDescription")'));
+});
+
+test("enabling sync with no queued rows needs no empty-data prompt", () => {
+ const hook = read("src/hooks/useInsightsSyncOptIn.tsx");
+ const enable = hook.slice(
+ hook.indexOf("const enableInsightsSync"),
+ hook.indexOf("const claiming")
+ );
+ assert.ok(enable.includes("if (pending === 0 && !options.confirmWhenEmpty)"));
+ assert.ok(enable.includes("prepareInsightsSync(false"));
+ assert.ok(
+ enable.indexOf("if (pending === 0 && !options.confirmWhenEmpty)") <
+ enable.indexOf("requestInsightsConsent({"),
+ "an empty sync must finish before the data-upload prompt is requested"
+ );
+});
+
+test("joining cannot silently turn on future Insights uploads when the queue is empty", () => {
+ const hook = read("src/hooks/useInsightsSyncOptIn.tsx");
+ const leaderboard = read("src/components/LeaderboardView.tsx");
+ assert.ok(hook.includes("confirmWhenEmpty?: boolean"));
+ assert.ok(hook.includes("pending === 0 && !options.confirmWhenEmpty"));
+ assert.ok(leaderboard.includes("enableInsightsSync({ confirmWhenEmpty: true })"));
+});
+
+test("an account switch cancels pending Insights consent", () => {
+ const hook = read("src/hooks/useInsightsSyncOptIn.tsx");
+ const accountEffect = hook.slice(
+ hook.indexOf("if (promptAccountIdRef.current === userId) return"),
+ hook.indexOf("const owner = consentOwnerRef.current")
+ );
+ assert.ok(accountEffect.includes("cancelInsightsConsent(consentOwnerRef.current)"));
+ assert.ok(hook.includes("promptAccountIdRef.current !== requestedAccountId"));
+});
+
+test("claiming anonymous Insights is bound to the consenting auth context", () => {
+ const hook = read("src/hooks/useInsightsSyncOptIn.tsx");
+ const preload = read("preload.js");
+ const handlers = read("src/helpers/ipcHandlers.js");
+ const database = read("src/helpers/database.js");
+ assert.match(
+ hook,
+ /\.claimAnonymousAnalyticsEvents\(\s*expectedAccountId,\s*expectedAuthGeneration\s*\)/
+ );
+ assert.ok(hook.includes("getValidatedAuthGeneration() !== expectedAuthGeneration"));
+ assert.ok(preload.includes('"analytics-claim-anonymous", accountId, expectedAuthGeneration'));
+ assert.ok(handlers.includes("state.generation !== expectedAuthGeneration"));
+ assert.ok(database.includes("accountId !== this.activeAccountId"));
+});
+
+test("leaving the leaderboard changes participation only", () => {
+ const syncHook = read("src/hooks/useInsightsSyncOptIn.tsx");
+ const participationHook = read("src/hooks/useLeaderboardParticipation.ts");
+ const section = read("src/components/LeaderboardSection.tsx");
+ const view = read("src/components/LeaderboardView.tsx");
+
+ assert.ok(participationHook.includes("return store.leave(context)"));
+ assert.equal(participationHook.includes("setInsightsSyncEnabled"), false);
+ assert.equal(syncHook.includes("leaveParticipation"), false);
+ assert.ok(view.includes("onLeave={leaveParticipation}"));
+ assert.ok(section.includes('t("insights.leaderboard.leave")'));
+ assert.ok(section.includes("onLeave()"));
+ assert.ok(view.includes("participating={isSignedIn && participationEnabled}"));
+ assert.equal(
+ view.slice(view.indexOf("<LeaderboardSection")).includes("participating={insightsSyncEnabled}"),
+ false
+ );
+});
+
+test("turning Insights Sync off never calls the account participation endpoint", () => {
+ const hook = read("src/hooks/useInsightsSyncOptIn.tsx");
+ const disable = hook.slice(
+ hook.indexOf("const disableInsightsSync"),
+ hook.indexOf("const refreshCounts")
+ );
+ assert.ok(disable.includes("setInsightsSyncEnabled(false)"));
+ assert.equal(disable.includes("Leaderboard"), false);
+ assert.equal(disable.includes("leave"), false);
+});
+
+test("a failed participation read cannot leave the board looking joined", () => {
+ const store = read("src/stores/leaderboardParticipationStore.ts");
+ const refresh = store.slice(store.indexOf("refresh: async"), store.indexOf("join: async"));
+ assert.ok(refresh.slice(refresh.indexOf("} catch")).includes("enabled: false"));
+ assert.equal(refresh.includes("setParticipation("), false);
+ assert.ok(refresh.includes("LeaderboardService.flushPendingLeave(context)"));
+});
+
+test("an unknown participation answer offers retry instead of Join", () => {
+ const store = read("src/stores/leaderboardParticipationStore.ts");
+ const section = read("src/components/LeaderboardSection.tsx");
+ const refresh = store.slice(store.indexOf("refresh: async"), store.indexOf("join: async"));
+ assert.ok(refresh.includes('error: "read"'));
+ const retrySurface = section.slice(
+ section.indexOf('if (surface === "participation_error")'),
+ section.indexOf('if (surface === "participation_loading")')
+ );
+ const joinSurface = section.slice(
+ section.indexOf('if (surface === "join")'),
+ section.indexOf("const number =")
+ );
+ assert.ok(retrySurface.includes("onRetry={onRefreshParticipation}"));
+ assert.equal(retrySurface.includes("onJoin"), false);
+ assert.ok(joinSurface.includes("onJoin={onJoin}"));
+});
+
+test("an undelivered leave is durable and retried without gating analytics", () => {
+ const store = read("src/stores/leaderboardParticipationStore.ts");
+ const service = read("src/services/LeaderboardService.ts");
+ const sync = read("src/services/SyncService.ts");
+ const leave = store.slice(store.indexOf("leave: async"));
+ const serviceLeave = service.slice(
+ service.indexOf("async function leaveParticipation"),
+ service.indexOf("async function flushPendingLeave")
+ );
+ assert.ok(service.includes("writePendingLeaderboardLeave(userId)"));
+ assert.ok(
+ serviceLeave.indexOf("writePendingLeaderboardLeave(userId)") <
+ serviceLeave.indexOf("serializeParticipationOperation(context")
+ );
+ assert.ok(leave.includes("publishAnswer(false, true, generation"));
+ const flush = service.slice(
+ service.indexOf("async function flushPendingLeave"),
+ service.indexOf("async function getAccess")
+ );
+ assert.ok(flush.includes("setParticipation(false, authGeneration)"));
+ assert.equal(flush.includes("setParticipation(true,"), false);
+ assert.ok(sync.includes("LeaderboardService.flushPendingLeave("));
+ assert.ok(sync.includes("pendingLeaderboardLeave"));
+ assert.equal(sync.includes("LeaderboardService.getParticipation("), false);
+});
+
+test("only an ambiguous request failure compensates a join", () => {
+ const hook = read("src/hooks/useLeaderboardParticipation.ts");
+ const service = read("src/services/LeaderboardService.ts");
+ const serviceJoin = service.slice(
+ service.indexOf("async function joinParticipation"),
+ service.indexOf("async function leaveParticipation")
+ );
+ assert.ok(serviceJoin.includes("serializeParticipationOperation(context"));
+ assert.ok(serviceJoin.includes("writePendingLeaderboardLeave(userId)"));
+ assert.ok(
+ serviceJoin.indexOf("writePendingLeaderboardLeave(userId)") < serviceJoin.indexOf("throw error")
+ );
+ const hookJoin = hook.slice(hook.indexOf("const join"), hook.indexOf("const leave ="));
+ assert.ok(hookJoin.includes("return store.join(context)"));
+ assert.equal(hookJoin.includes("writePendingLeaderboardLeave(userId)"), false);
+});
+
+test("a completed participation write outranks reads already in flight", () => {
+ const store = read("src/stores/leaderboardParticipationStore.ts");
+ const publish = store.slice(
+ store.indexOf("publishAnswer: (enabled, configured, generation"),
+ store.indexOf("refresh: async")
+ );
+ assert.ok(publish.indexOf("readId += 1") < publish.indexOf("set({ enabled"));
+ assert.ok(publish.includes("ready: true"));
+ for (const [name, end] of [
+ ["join: async", "leave: async"],
+ ["leave: async", ""],
+ ]) {
+ assert.ok(
+ store
+ .slice(store.indexOf(name), end ? store.indexOf(end) : undefined)
+ .includes("publishAnswer(")
+ );
+ }
+});
+
+test("every leaderboard surface reads one shared participation source", () => {
+ const hook = read("src/hooks/useLeaderboardParticipation.ts");
+ const syncHook = read("src/hooks/useInsightsSyncOptIn.tsx");
+ for (const field of ["enabled", "ready", "error", "updating"]) {
+ assert.ok(hook.includes(`(state) => state.${field}`));
+ }
+ assert.equal(/useState[^\n]*[Pp]articipation/.test(hook), false);
+ assert.equal(syncHook.includes("useLeaderboardParticipationStore"), false);
+ assert.equal(hook.includes("participationReadIdRef"), false);
+});
+
+test("a participation read defers to a write already in flight", () => {
+ const store = read("src/stores/leaderboardParticipationStore.ts");
+ const refresh = store.slice(store.indexOf("refresh: async"), store.indexOf("join: async"));
+ assert.ok(refresh.indexOf("if (get().updating) return;") < refresh.indexOf("++readId"));
+});
+
+test("an account scope purge drops only the cached participation answer", () => {
+ const auth = read("src/hooks/useAuth.ts");
+ const store = read("src/stores/leaderboardParticipationStore.ts");
+ const purge = auth.slice(
+ auth.indexOf("if (accountScopeRequiresPurge(resolvedUserId)) {"),
+ auth.indexOf("if (accountScopeRequiresReconciliation(resolvedUserId)) {")
+ );
+ assert.ok(purge.includes("useLeaderboardParticipationStore.getState().reset()"));
+ const reset = store.slice(
+ store.indexOf("reset: () => {"),
+ store.indexOf("publishAnswer: (enabled, configured, generation")
);
+ assert.ok(reset.includes("readId += 1"));
+ assert.equal(/PendingLeaderboardLeave/.test(reset), false);
});
diff --git a/test/services/analyticsParticipationGate.test.js b/test/services/analyticsParticipationGate.test.js
new file mode 100644
index 000000000..ba4c40fe8
--- /dev/null
+++ b/test/services/analyticsParticipationGate.test.js
@@ -0,0 +1,146 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");
+
+test("analytics uploads depend on Sync consent, not leaderboard participation", async (t) => {
+ t.mock.method(console, "error", () => {});
+ t.after(() => {
+ for (const key of [
+ "__analyticsBeforeUpload",
+ "__analyticsFlushes",
+ "__analyticsLocalConsent",
+ "__analyticsParticipationReads",
+ "__analyticsSyncContexts",
+ "__analyticsSyncFailure",
+ "__analyticsUploadAllowed",
+ ]) {
+ delete globalThis[key];
+ }
+ });
+
+ installBrowserGlobals(t, {
+ initialStorage: {
+ dataRetentionEnabled: "true",
+ insightsSyncEnabled: "true",
+ isSignedIn: "true",
+ },
+ });
+ globalThis.__analyticsBeforeUpload = null;
+ globalThis.__analyticsFlushes = 0;
+ globalThis.__analyticsLocalConsent = true;
+ globalThis.__analyticsParticipationReads = 0;
+ globalThis.__analyticsSyncContexts = [];
+ globalThis.__analyticsSyncFailure = false;
+ globalThis.__analyticsUploadAllowed = [];
+
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-analytics-participation-gate-",
+ mockModules: {
+ "/services/NotesService.js": "export const NotesService = {};",
+ "/services/ConversationsService.js": "export const ConversationsService = {};",
+ "/services/FoldersService.js": "export const FoldersService = {};",
+ "/services/SpacesService.js": "export const SpacesService = {};",
+ "/services/TranscriptionsService.js": "export const TranscriptionsService = {};",
+ "/services/DictionaryService.js": "export const DictionaryService = {};",
+ "/services/SnippetService.js": "export const SnippetService = {};",
+ "./AnalyticsService.js": `
+ export const syncPendingAnalytics = async ({ uploadAllowed, context }) => {
+ await globalThis.__analyticsBeforeUpload;
+ globalThis.__analyticsSyncContexts.push(context);
+ if (globalThis.__analyticsSyncFailure) throw new Error("upload failed");
+ const allowed = typeof uploadAllowed === "function"
+ ? await uploadAllowed()
+ : uploadAllowed;
+ globalThis.__analyticsUploadAllowed.push(allowed);
+ return allowed ? 1 : 0;
+ };
+ `,
+ "./LeaderboardService": `
+ export const LeaderboardService = {
+ flushPendingLeave: async () => {
+ globalThis.__analyticsFlushes += 1;
+ return false;
+ },
+ getParticipation: () => {
+ globalThis.__analyticsParticipationReads += 1;
+ throw new Error("analytics sync must not read participation");
+ }
+ };
+ `,
+ "./cloudApi.js": `
+ export class CloudApiError extends Error {}
+ export const isAuthContextError = () => false;
+ `,
+ "/lib/authRequestContext": `
+ export const assertAuthGenerationCurrent = () => {};
+ export const getAuthRequestContextSnapshot = () => ({
+ sessionUserId: "user_1",
+ sessionGeneration: 7,
+ validatedGeneration: 7
+ });
+ export const getValidatedAuthGeneration = () => 7;
+ export const hasValidatedAuthContext = () => true;
+ `,
+ "/lib/teamSpacesCapability": `
+ export const clearTeamSpacesCapability = () => {};
+ export const readTeamSpacesCapability = () => false;
+ export const writeTeamSpacesCapability = () => {};
+ `,
+ "/lib/subscriptionFlag": `
+ export const readIsSubscribed = () => false;
+ export const subscribeIsSubscribed = () => () => {};
+ `,
+ "/lib/noteConflictRegistry": "export const readNoteConflictIds = () => [];",
+ "/stores/policyRules": `
+ export const cloudBackupResumed = () => false;
+ export const effectiveLocalHistoryEnabled = (_state, enabled) => enabled;
+ export const isCloudBackupAllowed = () => true;
+ `,
+ "/stores/policyStore": `
+ export const usePolicyStore = {
+ getState: () => ({}),
+ subscribe: () => () => {}
+ };
+ `,
+ },
+ });
+ const { SyncService } = await vite.ssrLoadModule("/services/SyncService.ts");
+ const service = new SyncService();
+ service.consent = () => ({
+ analytics: globalThis.__analyticsLocalConsent,
+ backup: false,
+ shared: true,
+ });
+
+ assert.equal(await service.syncAnalyticsNow(), true);
+ assert.deepEqual(globalThis.__analyticsUploadAllowed, [true]);
+ assert.deepEqual(globalThis.__analyticsSyncContexts, [
+ { accountId: "user_1", authGeneration: 7 },
+ ]);
+ assert.equal(globalThis.__analyticsParticipationReads, 0);
+ assert.equal(globalThis.__analyticsFlushes, 1, "a durable pending leave is still retried");
+
+ let releaseUpload;
+ globalThis.__analyticsBeforeUpload = new Promise((resolve) => {
+ releaseUpload = resolve;
+ });
+ const inFlight = service.syncAnalyticsNow();
+ globalThis.__analyticsLocalConsent = false;
+ releaseUpload();
+ assert.equal(await inFlight, false);
+ assert.equal(
+ globalThis.__analyticsUploadAllowed.at(-1),
+ false,
+ "a local opt-out during a pass wins before rows are uploaded"
+ );
+ assert.equal(globalThis.__analyticsParticipationReads, 0);
+
+ globalThis.__analyticsBeforeUpload = null;
+ globalThis.__analyticsLocalConsent = true;
+ globalThis.__analyticsSyncFailure = true;
+ assert.equal(
+ await service.syncAnalyticsNow(),
+ false,
+ "a failed foreground upload must not be reported as synchronized"
+ );
+});
diff --git a/test/services/analyticsService.test.js b/test/services/analyticsService.test.js
index 32fdc8356..de60e8659 100644
--- a/test/services/analyticsService.test.js
+++ b/test/services/analyticsService.test.js
@@ -243,24 +243,61 @@ test("a failed account clear stays pending without stalling the rest of the pass
});
test("account analytics accepts a complete cloud summary", async (t) => {
+ const requests = [];
installBrowserGlobals(t, {
window: {
electronAPI: {
- cloudApiRequest: async () => ({
- success: true,
- data: { ...VALID_SUMMARY, scope: "account", timeZone: "UTC" },
- }),
+ cloudApiRequest: async (request) => {
+ requests.push(request);
+ return {
+ success: true,
+ data: { ...VALID_SUMMARY, scope: "account", timeZone: "UTC" },
+ };
+ },
},
},
});
const vite = await createRendererServer(t);
const { getAccountAnalyticsSummary } = await vite.ssrLoadModule("/services/AnalyticsService.ts");
- assert.deepEqual(await getAccountAnalyticsSummary("UTC"), {
+ assert.deepEqual(await getAccountAnalyticsSummary(), {
...VALID_SUMMARY,
scope: "account",
timeZone: "UTC",
});
+ const requestUrl = new URL(requests[0].path, "https://api.openwhispr.com");
+ assert.equal(requestUrl.pathname, "/api/analytics/summary");
+ assert.equal(
+ requestUrl.searchParams.get("timeZone"),
+ Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"
+ );
+});
+
+test("account analytics sends UTC when the runtime exposes no timezone", async (t) => {
+ const requests = [];
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ cloudApiRequest: async (request) => {
+ requests.push(request);
+ return {
+ success: true,
+ data: { ...VALID_SUMMARY, scope: "account", timeZone: "UTC" },
+ };
+ },
+ },
+ },
+ });
+ const vite = await createRendererServer(t);
+ const { getAccountAnalyticsSummary } = await vite.ssrLoadModule("/services/AnalyticsService.ts");
+ t.mock.method(Intl, "DateTimeFormat", () => ({
+ resolvedOptions: () => ({ timeZone: "" }),
+ }));
+
+ await getAccountAnalyticsSummary();
+
+ const requestUrl = new URL(requests[0].path, "https://api.openwhispr.com");
+ assert.equal(requestUrl.searchParams.get("timeZone"), "UTC");
});
for (const [name, daily] of [
@@ -286,10 +323,7 @@ for (const [name, daily] of [
"/services/AnalyticsService.ts"
);
- await assert.rejects(
- getAccountAnalyticsSummary("UTC"),
- /Malformed analytics summary from cloud/
- );
+ await assert.rejects(getAccountAnalyticsSummary(), /Malformed analytics summary from cloud/);
});
}
@@ -582,6 +616,139 @@ test("overlapping passes are serialized rather than posting the same batch twice
assert.equal(second, 0);
});
+test("a queued analytics pass resolves its upload gate only when it starts", async (t) => {
+ let releaseFirstPass;
+ let markFirstPassStarted;
+ let clearReads = 0;
+ let eventReads = 0;
+ const firstPassStarted = new Promise((resolve) => {
+ markFirstPassStarted = resolve;
+ });
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ getPendingAnalyticsClear: async () => {
+ clearReads += 1;
+ if (clearReads === 1) {
+ markFirstPassStarted();
+ await new Promise((resolve) => {
+ releaseFirstPass = resolve;
+ });
+ }
+ return null;
+ },
+ getPendingAnalyticsDeletes: async () => [],
+ getPendingAnalyticsEvents: async () => {
+ eventReads += 1;
+ return [EVENT];
+ },
+ cloudApiRequest: async () => {
+ throw new Error("a revoked queued pass must not reach the API");
+ },
+ },
+ },
+ });
+ const vite = await createRendererServer(t);
+ const { syncPendingAnalytics } = await vite.ssrLoadModule("/services/AnalyticsService.ts");
+
+ const blocking = syncPendingAnalytics({ uploadAllowed: false });
+ await firstPassStarted;
+ let uploadAllowed = true;
+ let gateReads = 0;
+ const queued = syncPendingAnalytics({
+ uploadAllowed: async () => {
+ gateReads += 1;
+ return uploadAllowed;
+ },
+ });
+ uploadAllowed = false;
+ releaseFirstPass();
+
+ await Promise.all([blocking, queued]);
+ assert.equal(gateReads, 1);
+ assert.equal(eventReads, 0, "revocation is checked before pending rows are read");
+});
+
+test("revoking upload consent stops a multi-batch drain after its active request", async (t) => {
+ const pending = Array.from({ length: 201 }, (_, index) => ({
+ ...EVENT,
+ event_id: `event-${index}`,
+ }));
+ const retired = new Set();
+ const posted = [];
+ let uploadAllowed = true;
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ getPendingAnalyticsClear: async () => null,
+ getPendingAnalyticsDeletes: async () => [],
+ getPendingAnalyticsEvents: async (limit) =>
+ pending.filter((event) => !retired.has(event.event_id)).slice(0, limit),
+ markAnalyticsEventsSynced: async (eventIds) => {
+ eventIds.forEach((eventId) => retired.add(eventId));
+ return { success: true, updated: eventIds.length };
+ },
+ cloudApiRequest: async (request) => {
+ posted.push(request.body.events);
+ uploadAllowed = false;
+ return {
+ success: true,
+ data: { accepted: request.body.events.map((event) => event.event_id) },
+ };
+ },
+ },
+ },
+ });
+ const vite = await createRendererServer(t);
+ const { syncPendingAnalytics } = await vite.ssrLoadModule("/services/AnalyticsService.ts");
+
+ assert.equal(await syncPendingAnalytics({ uploadAllowed: () => uploadAllowed }), 200);
+ assert.equal(posted.length, 1);
+ assert.equal(posted[0].length, 200);
+ assert.equal(retired.has("event-200"), false, "the next batch stays pending after revocation");
+});
+
+test("analytics queue and cloud operations carry one pinned account context", async (t) => {
+ const context = { accountId: "account-1", authGeneration: 17 };
+ const localCalls = [];
+ const requests = [];
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ getPendingAnalyticsClear: async (received) => {
+ localCalls.push(["clear", received]);
+ return null;
+ },
+ getPendingAnalyticsDeletes: async (_limit, received) => {
+ localCalls.push(["deletes", received]);
+ return [];
+ },
+ getPendingAnalyticsEvents: async (_limit, received) => {
+ localCalls.push(["events", received]);
+ return [EVENT];
+ },
+ markAnalyticsEventsSynced: async (_eventIds, received) => {
+ localCalls.push(["synced", received]);
+ return { success: true, updated: 1 };
+ },
+ cloudApiRequest: async (request) => {
+ requests.push(request);
+ return { success: true, data: { accepted: [EVENT.event_id] } };
+ },
+ },
+ },
+ });
+ const vite = await createRendererServer(t);
+ const { syncPendingAnalytics } = await vite.ssrLoadModule("/services/AnalyticsService.ts");
+
+ assert.equal(await syncPendingAnalytics({ context }), 1);
+ assert.deepEqual(
+ localCalls,
+ ["clear", "deletes", "events", "synced"].map((name) => [name, context])
+ );
+ assert.equal(requests[0].expectedAuthGeneration, 17);
+});
+
test("a withheld row is offered once per pass, not once per batch behind it", async (t) => {
// The server withholds rows it could not store, which correctly keeps them
// pending. They sit at the head of an oldest-first queue, so re-reading from
diff --git a/test/services/leaderboardService.test.js b/test/services/leaderboardService.test.js
new file mode 100644
index 000000000..8a2c76a0a
--- /dev/null
+++ b/test/services/leaderboardService.test.js
@@ -0,0 +1,661 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { installBrowserGlobals } = require("../lib/rendererTestHarness");
+
+function captureRequests(t, responseData) {
+ const requests = [];
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ cloudApiRequest: async (request) => {
+ requests.push(request);
+ return { success: true, data: { data: responseData } };
+ },
+ },
+ },
+ });
+ return requests;
+}
+
+const pendingKey = (userId) => `leaderboardLeavePending:${encodeURIComponent(userId)}`;
+const pendingUserIds = (storage) =>
+ ["user_1", "user_2"].filter((userId) => storage.getItem(pendingKey(userId)) != null);
+const pendingAttempts = (storage, userId) =>
+ JSON.parse(storage.getItem(pendingKey(userId))).attempts;
+
+async function validateAuthContext(userId = "user_1", authGeneration = 7, reset = true) {
+ const auth = require("../../src/lib/authRequestContext.ts");
+ if (reset) auth.resetAuthRequestContextForTests();
+ const token = `token-${userId}-${authGeneration}`;
+ global.window.location ??= { origin: "https://desktop.openwhispr.test" };
+ global.window.electronAPI.authGetTokenState = async () => ({ token, generation: authGeneration });
+ await auth.handleAuthRequestSuccess({
+ data: { user: { id: userId } },
+ response: new Response("{}", { status: 200 }),
+ request: {
+ url: "https://auth.openwhispr.test/api/auth/get-session",
+ headers: new Headers({ Authorization: `Bearer ${token}` }),
+ openWhisprAuthGeneration: authGeneration,
+ },
+ });
+ assert.equal(auth.commitValidatedAuthContext(authGeneration, userId), true);
+ return { userId, authGeneration };
+}
+
+test("participation uses the account endpoint for reads, joins, and leaves", async (t) => {
+ const participation = { configured: true, enabled: true, updatedAt: null };
+ const requests = captureRequests(t, participation);
+ const context = await validateAuthContext();
+ const { LeaderboardService } = require("../../src/services/LeaderboardService.ts");
+
+ assert.deepEqual(await LeaderboardService.getParticipation(context), participation);
+ assert.deepEqual(await LeaderboardService.joinParticipation(context), participation);
+ assert.deepEqual(requests, [
+ {
+ method: "GET",
+ path: "/api/analytics/participation",
+ body: undefined,
+ public: false,
+ expectedAuthGeneration: 7,
+ },
+ {
+ method: "PATCH",
+ path: "/api/analytics/participation",
+ body: { enabled: true },
+ public: false,
+ expectedAuthGeneration: 7,
+ },
+ ]);
+});
+
+test("leaderboard access uses the authoritative production endpoint", async (t) => {
+ const response = {
+ state: "create",
+ scopes: [],
+ domain: null,
+ colleagueCount: 0,
+ invitation: null,
+ joinableWorkspace: null,
+ };
+ const requests = captureRequests(t, response);
+ const { LeaderboardService } = require("../../src/services/LeaderboardService.ts");
+
+ assert.deepEqual(await LeaderboardService.getAccess(), response);
+ assert.equal(requests[0].path, "/api/leaderboard/access");
+});
+
+test("a pre-leaderboard API preserves legacy Insights sync as unconfigured", async (t) => {
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ cloudApiRequest: async () => ({ success: false, status: 404, error: "Not found" }),
+ },
+ },
+ });
+ const context = await validateAuthContext();
+ const { LeaderboardService } = require("../../src/services/LeaderboardService.ts");
+
+ assert.deepEqual(await LeaderboardService.getParticipation(context), {
+ configured: false,
+ enabled: false,
+ updatedAt: null,
+ });
+});
+
+test("leaderboard services reject malformed success payloads", async (t) => {
+ captureRequests(t, { state: "ready" });
+ const { LeaderboardService } = require("../../src/services/LeaderboardService.ts");
+
+ await assert.rejects(LeaderboardService.getAccess(), /Malformed leaderboard access/);
+});
+
+test("leaderboard requests carry scope, pagination, filters and no body data", async (t) => {
+ const response = {
+ scope: {
+ key: "workspace:workspace/one",
+ kind: "workspace",
+ id: "workspace/one",
+ name: "Workspace",
+ },
+ viewerUserId: "user_1",
+ metric: "mobile_words",
+ range: "week",
+ weekStart: "2026-08-31",
+ availableWeekStarts: ["2026-08-31"],
+ leaders: [],
+ members: [],
+ totalMembers: 0,
+ viewerRank: null,
+ page: 0,
+ pageSize: 20,
+ generatedAt: "2026-09-09T00:00:00.000Z",
+ refreshAfterSeconds: 3600,
+ };
+ const requests = captureRequests(t, response);
+ const { LeaderboardService } = require("../../src/services/LeaderboardService.ts");
+
+ assert.deepEqual(
+ await LeaderboardService.getLeaderboard(
+ {
+ key: "workspace:workspace/one",
+ kind: "workspace",
+ id: "workspace/one",
+ name: "Workspace",
+ memberCount: 2,
+ state: "ready",
+ role: "member",
+ },
+ {
+ metric: "mobile_words",
+ range: "week",
+ weekStart: "2026-08-31",
+ page: 2,
+ }
+ ),
+ response
+ );
+ assert.equal(requests[0].method, "GET");
+ assert.equal(
+ requests[0].path,
+ "/api/workspaces/workspace%2Fone/leaderboard?metric=mobile_words&range=week&page=2&weekStart=2026-08-31"
+ );
+ assert.equal(requests[0].body, undefined);
+
+ await LeaderboardService.getLeaderboard(
+ {
+ key: "domain:acme.test",
+ kind: "domain",
+ id: "acme.test",
+ name: "acme.test",
+ memberCount: 3,
+ state: "ready",
+ role: null,
+ },
+ {
+ metric: "total_words",
+ range: "all",
+ includeWeekStarts: false,
+ page: 0,
+ }
+ );
+ assert.equal(
+ requests[1].path,
+ "/api/leaderboard/domain?metric=total_words&range=all&page=0&includeWeekStarts=false"
+ );
+});
+
+// The renderer formats these week values with Intl and drives a refresh timer
+// off refreshAfterSeconds, both outside any try block. A shape that survives
+// validation but not formatting throws during render, where the only boundary
+// left is the app-level one that replaces the whole control panel.
+const boardResponse = (overrides) => ({
+ scope: { key: "domain:acme.test", kind: "domain", id: "acme.test", name: "acme.test" },
+ viewerUserId: "user_1",
+ metric: "total_words",
+ range: "week",
+ weekStart: "2026-08-31",
+ availableWeekStarts: ["2026-08-31"],
+ leaders: [],
+ members: [],
+ totalMembers: 0,
+ viewerRank: null,
+ page: 0,
+ pageSize: 20,
+ generatedAt: "2026-09-09T00:00:00.000Z",
+ refreshAfterSeconds: 3600,
+ ...overrides,
+});
+
+const domainScope = {
+ key: "domain:acme.test",
+ kind: "domain",
+ id: "acme.test",
+ name: "acme.test",
+ memberCount: 3,
+ state: "ready",
+ role: null,
+};
+
+for (const [label, overrides] of [
+ ["an empty weekStart", { weekStart: "" }],
+ ["an unparseable weekStart", { weekStart: "not-a-date" }],
+ ["a weekStart that is not a real day", { weekStart: "2026-02-30" }],
+ ["a timestamp where a calendar day belongs", { weekStart: "2026-08-31T00:00:00.000Z" }],
+ ["an empty entry in availableWeekStarts", { availableWeekStarts: ["2026-08-31", ""] }],
+ ["an unparseable entry in availableWeekStarts", { availableWeekStarts: ["nope"] }],
+ [
+ "more weeks than a year can hold",
+ { availableWeekStarts: Array.from({ length: 54 }, () => "2026-08-31") },
+ ],
+ ["a refresh interval no timer can hold", { refreshAfterSeconds: 2 ** 31 }],
+]) {
+ test(`the leaderboard is rejected when it carries ${label}`, async (t) => {
+ captureRequests(t, boardResponse(overrides));
+ const { LeaderboardService } = require("../../src/services/LeaderboardService.ts");
+
+ await assert.rejects(
+ LeaderboardService.getLeaderboard(domainScope, { metric: "total_words", range: "week" }),
+ /Malformed leaderboard/
+ );
+ });
+}
+
+test("a board with no week selected and a full year of history stays valid", async (t) => {
+ captureRequests(
+ t,
+ boardResponse({
+ range: "all",
+ weekStart: null,
+ availableWeekStarts: Array.from({ length: 53 }, (_, week) =>
+ new Date(Date.UTC(2026, 0, 5 + week * 7)).toISOString().slice(0, 10)
+ ),
+ })
+ );
+ const { LeaderboardService } = require("../../src/services/LeaderboardService.ts");
+
+ const board = await LeaderboardService.getLeaderboard(domainScope, {
+ metric: "total_words",
+ range: "all",
+ });
+ assert.equal(board.weekStart, null);
+ assert.equal(board.availableWeekStarts.length, 53);
+});
+
+// An opt-out the network never delivered has to reach the account eventually,
+// and only ever in the leaving direction: the account preference is the one
+// source of truth for who is on a leaderboard, so a device may take itself off
+// but never put another account on.
+test("a pending leave is retried for the account that asked and cleared once it lands", async (t) => {
+ const requests = [];
+ const { storage } = installBrowserGlobals(t, {
+ initialStorage: { [pendingKey("user_1")]: "true", [pendingKey("user_2")]: "true" },
+ window: {
+ electronAPI: {
+ cloudApiRequest: async (request) => {
+ requests.push(request);
+ return {
+ success: true,
+ data: { data: { configured: true, enabled: false, updatedAt: null } },
+ };
+ },
+ },
+ },
+ });
+ const user1 = await validateAuthContext();
+ const { LeaderboardService } = require("../../src/services/LeaderboardService.ts");
+
+ const user3 = { userId: "user_3", authGeneration: user1.authGeneration };
+ await assert.rejects(LeaderboardService.flushPendingLeave(user3), {
+ code: "AUTH_CONTEXT_CHANGED",
+ });
+ assert.deepEqual(requests, [], "a leave another account recorded is never sent for this one");
+
+ assert.equal(await LeaderboardService.flushPendingLeave(user1), false);
+ assert.equal(requests.length, 1);
+ assert.equal(requests[0].method, "PATCH");
+ assert.equal(requests[0].path, "/api/analytics/participation");
+ assert.deepEqual(requests[0].body, { enabled: false });
+ assert.deepEqual(
+ pendingUserIds(storage),
+ ["user_2"],
+ "one account taking its leave must not discard another account's"
+ );
+
+ assert.equal(await LeaderboardService.flushPendingLeave(user1), false);
+ assert.equal(requests.length, 1, "nothing is retried once the account has taken the leave");
+});
+
+test("a retry that fails keeps the leave pending for the next trigger", async (t) => {
+ const { storage } = installBrowserGlobals(t, {
+ initialStorage: { [pendingKey("user_1")]: "true", [pendingKey("user_2")]: "true" },
+ window: {
+ electronAPI: {
+ cloudApiRequest: async () => ({ success: false, status: 0, error: "offline" }),
+ },
+ },
+ });
+ const context = await validateAuthContext();
+ const { LeaderboardService } = require("../../src/services/LeaderboardService.ts");
+
+ assert.equal(
+ await LeaderboardService.flushPendingLeave(context),
+ true,
+ "the caller has to know the account is still on the leaderboard the user left"
+ );
+ assert.deepEqual(pendingUserIds(storage), ["user_1", "user_2"]);
+});
+
+// A compensating leave covers a join that may have landed before the failure
+// surfaced. A status the server itself chose proves it did not land, so banking
+// one there strands a record nothing can clear: the retry PATCH draws the same
+// refusal, and SyncService treats a pending leave as a reason to bypass the
+// sync throttle for as long as it sits there.
+for (const status of [400, 401, 403, 404, 409, 422]) {
+ test(`a join refused with ${status} leaves no compensating leave behind`, async (t) => {
+ const { storage } = installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ cloudApiRequest: async () => ({ success: false, status, error: "Refused" }),
+ },
+ },
+ });
+ const context = await validateAuthContext();
+ const { LeaderboardService } = require("../../src/services/LeaderboardService.ts");
+
+ await assert.rejects(LeaderboardService.joinParticipation(context));
+ assert.deepEqual(pendingUserIds(storage), []);
+ });
+}
+
+for (const [label, response] of [
+ ["an offline device", { success: false, status: 0, error: "offline" }],
+ ["a server error", { success: false, status: 500, error: "boom" }],
+]) {
+ test(`a join failing through ${label} keeps a compensating leave`, async (t) => {
+ const { storage } = installBrowserGlobals(t, {
+ window: { electronAPI: { cloudApiRequest: async () => response } },
+ });
+ const context = await validateAuthContext();
+ const { LeaderboardService } = require("../../src/services/LeaderboardService.ts");
+
+ await assert.rejects(LeaderboardService.joinParticipation(context));
+ assert.deepEqual(
+ pendingUserIds(storage),
+ ["user_1"],
+ "the account may already be on a leaderboard the user was told it had not joined"
+ );
+ });
+}
+
+// A write the API answered 2xx for has already moved the row; the client only
+// failed to read the answer. Compensating it would undo the account's own join.
+test("a join whose success body is unreadable leaves no compensating leave behind", async (t) => {
+ const { storage } = installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ cloudApiRequest: async () => ({ success: true, data: { data: { enabled: "yes" } } }),
+ },
+ },
+ });
+ const context = await validateAuthContext();
+ const { LeaderboardService } = require("../../src/services/LeaderboardService.ts");
+
+ await assert.rejects(LeaderboardService.joinParticipation(context));
+ assert.deepEqual(
+ pendingUserIds(storage),
+ [],
+ "the API accepted the join, so there is nothing to take back"
+ );
+});
+
+// The main process fences an authenticated request before it reaches the wire.
+for (const code of ["AUTH_CONTEXT_CHANGED", "AUTH_CONTEXT_UNVALIDATED"]) {
+ test(`a join fenced with ${code} leaves no compensating leave behind`, async (t) => {
+ const { storage } = installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ cloudApiRequest: async () => ({ success: false, status: 0, code, error: "fenced" }),
+ },
+ },
+ });
+ const context = await validateAuthContext();
+ const { LeaderboardService } = require("../../src/services/LeaderboardService.ts");
+
+ await assert.rejects(LeaderboardService.joinParticipation(context));
+ assert.deepEqual(pendingUserIds(storage), [], "the request never left the device");
+ });
+}
+
+// A leave the API has already applied, or can never apply, must not keep a
+// record alive: SyncService treats one as a reason to bypass the sync throttle.
+for (const [label, response] of [
+ ["an API without the participation route", { success: false, status: 404, error: "gone" }],
+ ["a success body it cannot read", { success: true, data: { data: { enabled: "no" } } }],
+]) {
+ test(`a leave answered by ${label} retires the pending record`, async (t) => {
+ const { storage } = installBrowserGlobals(t, {
+ window: { electronAPI: { cloudApiRequest: async () => response } },
+ });
+ const context = await validateAuthContext();
+ const { LeaderboardService } = require("../../src/services/LeaderboardService.ts");
+
+ await assert.rejects(LeaderboardService.leaveParticipation(context));
+ assert.deepEqual(pendingUserIds(storage), []);
+ });
+}
+
+// A refusal that a later retry could answer differently keeps the opt-out.
+for (const status of [401, 429, 500]) {
+ test(`a leave refused with ${status} keeps the opt-out and charges one attempt`, async (t) => {
+ const { storage } = installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ cloudApiRequest: async () => ({ success: false, status, error: "refused" }),
+ },
+ },
+ });
+ const context = await validateAuthContext();
+ const { LeaderboardService } = require("../../src/services/LeaderboardService.ts");
+
+ await assert.rejects(LeaderboardService.leaveParticipation(context));
+ assert.deepEqual(pendingUserIds(storage), ["user_1"]);
+ assert.equal(pendingAttempts(storage, "user_1"), 1);
+ });
+}
+
+// The blocker this bound exists for: an undeliverable leave used to keep
+// bypassing the sync throttle, the in-flight guard and the ambient backoff on
+// every focus, visibility change and online event, for the life of the install.
+test("an undeliverable leave stops preempting the sync throttle but keeps retrying", async (t) => {
+ let calls = 0;
+ const { storage } = installBrowserGlobals(t, {
+ initialStorage: { [pendingKey("user_1")]: "true" },
+ window: {
+ electronAPI: {
+ cloudApiRequest: async () => {
+ calls += 1;
+ return { success: false, status: 403, error: "refused" };
+ },
+ },
+ },
+ });
+ const context = await validateAuthContext();
+ const { LeaderboardService } = require("../../src/services/LeaderboardService.ts");
+ const {
+ MAX_PRIORITY_LEAVE_ATTEMPTS,
+ pendingLeaderboardLeaveDeservesPriority,
+ readPendingLeaderboardLeave,
+ } = require("../../src/lib/pendingLeaderboardLeave.ts");
+
+ for (let attempt = 0; attempt < MAX_PRIORITY_LEAVE_ATTEMPTS; attempt += 1) {
+ assert.equal(
+ pendingLeaderboardLeaveDeservesPriority("user_1"),
+ true,
+ `the opt-out still deserves priority before attempt ${attempt + 1}`
+ );
+ assert.equal(await LeaderboardService.flushPendingLeave(context), true);
+ }
+
+ assert.equal(
+ pendingLeaderboardLeaveDeservesPriority("user_1"),
+ false,
+ "a leave that cannot land may not hold the sync throttle open forever"
+ );
+ assert.equal(
+ readPendingLeaderboardLeave("user_1"),
+ true,
+ "the account still asked to leave, so the record itself survives"
+ );
+
+ assert.equal(await LeaderboardService.flushPendingLeave(context), true);
+ assert.equal(calls, MAX_PRIORITY_LEAVE_ATTEMPTS + 1, "ordinary passes keep retrying it");
+ assert.equal(pendingAttempts(storage, "user_1"), MAX_PRIORITY_LEAVE_ATTEMPTS);
+});
+
+test("an explicit join stays newer than a pending leave already in flight", async (t) => {
+ const requests = [];
+ let serverEnabled = true;
+ let releasePendingLeave;
+ let markLeaveStarted;
+ const pendingLeaveStarted = new Promise((resolve) => {
+ markLeaveStarted = resolve;
+ });
+ const pendingLeaveResponse = new Promise((resolve) => {
+ releasePendingLeave = resolve;
+ });
+ t.after(() => releasePendingLeave());
+ const { storage } = installBrowserGlobals(t, {
+ initialStorage: { [pendingKey("user_1")]: "true" },
+ window: {
+ electronAPI: {
+ cloudApiRequest: async (request) => {
+ requests.push(request);
+ if (request.method === "PATCH") {
+ if (request.body.enabled === false) {
+ markLeaveStarted();
+ await pendingLeaveResponse;
+ }
+ serverEnabled = request.body.enabled;
+ }
+ return {
+ success: true,
+ data: {
+ data: { configured: true, enabled: serverEnabled, updatedAt: null },
+ },
+ };
+ },
+ },
+ },
+ });
+ const context = await validateAuthContext();
+ const { LeaderboardService } = require("../../src/services/LeaderboardService.ts");
+
+ const flush = LeaderboardService.flushPendingLeave(context);
+ await pendingLeaveStarted;
+ const join = LeaderboardService.joinParticipation(context);
+ const reconciliation = flush.then(() => LeaderboardService.getParticipation(context));
+ await Promise.resolve();
+ assert.deepEqual(
+ requests.map((request) => request.body),
+ [{ enabled: false }],
+ "the newer join must wait rather than race the in-flight leave"
+ );
+
+ releasePendingLeave();
+ const [, joined, reconciled] = await Promise.all([flush, join, reconciliation]);
+ assert.deepEqual(
+ requests.map(({ method, body }) => ({ method, body })),
+ [
+ { method: "PATCH", body: { enabled: false } },
+ { method: "PATCH", body: { enabled: true } },
+ { method: "GET", body: undefined },
+ ]
+ );
+ assert.equal(joined.enabled, true);
+ assert.equal(reconciled.enabled, true);
+ assert.equal(serverEnabled, true);
+ assert.deepEqual(pendingUserIds(storage), []);
+});
+
+test("a queued participation write cannot adopt a replacement account's auth", async (t) => {
+ const requests = [];
+ let releasePendingLeave;
+ let markLeaveStarted;
+ const pendingLeaveStarted = new Promise((resolve) => {
+ markLeaveStarted = resolve;
+ });
+ const pendingLeaveResponse = new Promise((resolve) => {
+ releasePendingLeave = resolve;
+ });
+ t.after(() => releasePendingLeave());
+ installBrowserGlobals(t, {
+ initialStorage: { [pendingKey("user_1")]: "true" },
+ window: {
+ electronAPI: {
+ cloudApiRequest: async (request) => {
+ requests.push(request);
+ markLeaveStarted();
+ await pendingLeaveResponse;
+ return {
+ success: true,
+ data: { data: { configured: true, enabled: false, updatedAt: null } },
+ };
+ },
+ },
+ },
+ });
+ const user1 = await validateAuthContext();
+ const { LeaderboardService } = require("../../src/services/LeaderboardService.ts");
+
+ const flush = LeaderboardService.flushPendingLeave(user1);
+ await pendingLeaveStarted;
+ const staleJoin = LeaderboardService.joinParticipation(user1);
+ await validateAuthContext("user_2", 8, false);
+ releasePendingLeave();
+
+ assert.equal(await flush, false);
+ await assert.rejects(staleJoin, { code: "AUTH_CONTEXT_CHANGED" });
+ assert.deepEqual(
+ requests.map(({ method, body, expectedAuthGeneration }) => ({
+ method,
+ body,
+ expectedAuthGeneration,
+ })),
+ [{ method: "PATCH", body: { enabled: false }, expectedAuthGeneration: 7 }],
+ "the queued user_1 join must be rejected before it can use user_2's credential"
+ );
+});
+
+test("a leave queued across an auth switch remains pending for its original account", async (t) => {
+ const requests = [];
+ let releaseRead;
+ let markReadStarted;
+ const readStarted = new Promise((resolve) => {
+ markReadStarted = resolve;
+ });
+ const readResponse = new Promise((resolve) => {
+ releaseRead = resolve;
+ });
+ t.after(() => releaseRead());
+ const { storage } = installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ cloudApiRequest: async (request) => {
+ requests.push(request);
+ markReadStarted();
+ await readResponse;
+ return {
+ success: true,
+ data: { data: { configured: true, enabled: true, updatedAt: null } },
+ };
+ },
+ },
+ },
+ });
+ const user1 = await validateAuthContext();
+ const { LeaderboardService } = require("../../src/services/LeaderboardService.ts");
+
+ const read = LeaderboardService.getParticipation(user1);
+ await readStarted;
+ const staleLeave = LeaderboardService.leaveParticipation(user1);
+ assert.deepEqual(pendingUserIds(storage), ["user_1"]);
+ await validateAuthContext("user_2", 8, false);
+ releaseRead();
+
+ await read;
+ await assert.rejects(staleLeave, { code: "AUTH_CONTEXT_CHANGED" });
+ assert.deepEqual(
+ requests.map(({ method, body, expectedAuthGeneration }) => ({
+ method,
+ body,
+ expectedAuthGeneration,
+ })),
+ [{ method: "GET", body: undefined, expectedAuthGeneration: 7 }],
+ "the queued user_1 leave must not be sent with user_2's credential"
+ );
+ assert.deepEqual(
+ pendingUserIds(storage),
+ ["user_1"],
+ "the fenced leave must retry when user_1 has a validated credential again"
+ );
+});
diff --git a/test/services/syncPassPolicy.test.js b/test/services/syncPassPolicy.test.js
index 58ed47d3a..a8766464a 100644
--- a/test/services/syncPassPolicy.test.js
+++ b/test/services/syncPassPolicy.test.js
@@ -80,8 +80,8 @@ test("consent: disabling local history stops pending Insights uploads", async ()
});
// --- canOfferAnalyticsClaim -------------------------------------------------
-// insightsSyncEnabled is device-scoped and survives sign-out, so counters
-// spoken before the next sign-in are unattributed with the toggle still on.
+// Account-scope bootstrap can leave rows unattributed while the local setting
+// is on, so those counters can still need a claim after sign-in.
const OFFER = {
signedIn: true,
diff --git a/test/stores/leaderboardParticipationStore.test.js b/test/stores/leaderboardParticipationStore.test.js
new file mode 100644
index 000000000..82b1caea2
--- /dev/null
+++ b/test/stores/leaderboardParticipationStore.test.js
@@ -0,0 +1,453 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { installBrowserGlobals } = require("../lib/rendererTestHarness");
+
+// Participation is one account preference shared by every surface, so these
+// cover the transitions a single hook instance could never see: a leave taken
+// in Settings while the leaderboard is mounted behind it, and the re-read that
+// the sync-toggle flip fires before that leave has reached the account.
+
+const pendingKey = (userId) => `leaderboardLeavePending:${encodeURIComponent(userId)}`;
+// The record carries a delivery-attempt count, so presence is the signal.
+const pendingUserIds = (storage) =>
+ ["user_1", "user_2"].filter((userId) => storage.getItem(pendingKey(userId)) != null);
+const waitFor = async (predicate) => {
+ for (let attempt = 0; attempt < 20; attempt += 1) {
+ if (predicate()) return;
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+ assert.fail("timed out waiting for the mocked request to start");
+};
+
+async function validateAuthContext(userId = "user_1", authGeneration = 7, reset = true) {
+ const auth = require("../../src/lib/authRequestContext.ts");
+ if (reset) auth.resetAuthRequestContextForTests();
+ const token = `token-${userId}-${authGeneration}`;
+ global.window.location ??= { origin: "https://desktop.openwhispr.test" };
+ global.window.electronAPI.authGetTokenState = async () => ({ token, generation: authGeneration });
+ await auth.handleAuthRequestSuccess({
+ data: { user: { id: userId } },
+ response: new Response("{}", { status: 200 }),
+ request: {
+ url: "https://auth.openwhispr.test/api/auth/get-session",
+ headers: new Headers({ Authorization: `Bearer ${token}` }),
+ openWhisprAuthGeneration: authGeneration,
+ },
+ });
+ assert.equal(auth.commitValidatedAuthContext(authGeneration, userId), true);
+ return { userId, authGeneration };
+}
+
+async function loadStore(t, { initialStorage = {}, cloudApiRequest }) {
+ const requests = [];
+ const { storage } = installBrowserGlobals(t, {
+ initialStorage,
+ window: {
+ electronAPI: {
+ cloudApiRequest: async (request) => {
+ requests.push(request);
+ return cloudApiRequest(request);
+ },
+ },
+ },
+ });
+ const {
+ useLeaderboardParticipationStore,
+ } = require("../../src/stores/leaderboardParticipationStore.ts");
+ // The module is cached across cases in this file, so each starts from unknown.
+ useLeaderboardParticipationStore.setState({
+ enabled: false,
+ configured: false,
+ ready: false,
+ error: null,
+ updating: false,
+ });
+ const context = await validateAuthContext();
+ return { context, requests, storage, store: useLeaderboardParticipationStore };
+}
+
+const participation = (enabled) => ({
+ success: true,
+ data: { data: { configured: true, enabled, updatedAt: null } },
+});
+
+test("a leave the account refused stops showing the user as participating", async (t) => {
+ const { context, storage, store } = await loadStore(t, {
+ cloudApiRequest: async () => ({ success: false, status: 0, error: "offline" }),
+ });
+
+ assert.equal(await store.getState().leave(context), false);
+ assert.equal(store.getState().enabled, false);
+ assert.equal(store.getState().configured, true);
+ assert.equal(store.getState().ready, true);
+ assert.equal(store.getState().updating, false);
+ assert.deepEqual(
+ pendingUserIds(storage),
+ ["user_1"],
+ "the opt-out has to survive the network that refused it"
+ );
+ assert.equal(
+ store.getState().leavePending,
+ true,
+ "the toggle reads off, so this is what stops the leave from passing as done"
+ );
+});
+
+// An API without the participation route cannot be holding the account on a
+// board, so there is no leave left to owe — and nothing to keep telling the
+// user about.
+test("a leave the API can no longer act on is not reported as still owed", async (t) => {
+ const { context, storage, store } = await loadStore(t, {
+ cloudApiRequest: async () => ({ success: false, status: 404, error: "gone" }),
+ });
+
+ assert.equal(await store.getState().leave(context), false);
+ assert.equal(store.getState().enabled, false);
+ assert.equal(store.getState().leavePending, false);
+ assert.deepEqual(pendingUserIds(storage), []);
+});
+
+test("a refresh reports a leave the account is still waiting on", async (t) => {
+ const { context, store } = await loadStore(t, {
+ initialStorage: { [pendingKey("user_1")]: "true" },
+ cloudApiRequest: async (request) =>
+ request.method === "PATCH"
+ ? { success: false, status: 500, error: "boom" }
+ : { success: true, data: { data: { configured: true, enabled: true, updatedAt: null } } },
+ });
+
+ await store.getState().refresh(context);
+
+ assert.equal(store.getState().enabled, false, "the row still says joined, but the user left");
+ assert.equal(store.getState().leavePending, true);
+});
+
+test("a delivered leave, or a newer join, retires the owed-leave notice", async (t) => {
+ let patchFails = true;
+ // The account row: a PATCH that lands moves it, a GET reads it back.
+ let serverEnabled = true;
+ const { context, store } = await loadStore(t, {
+ initialStorage: { [pendingKey("user_1")]: "true" },
+ cloudApiRequest: async (request) => {
+ if (request.method === "PATCH") {
+ if (patchFails) return { success: false, status: 500, error: "boom" };
+ serverEnabled = request.body.enabled;
+ }
+ return {
+ success: true,
+ data: { data: { configured: true, enabled: serverEnabled, updatedAt: null } },
+ };
+ },
+ });
+
+ await store.getState().refresh(context);
+ assert.equal(store.getState().leavePending, true);
+
+ patchFails = false;
+ await store.getState().refresh(context);
+ assert.equal(store.getState().leavePending, false, "the retry landed on this read");
+ assert.equal(store.getState().enabled, false);
+
+ assert.equal(await store.getState().join(context), true);
+ assert.equal(store.getState().leavePending, false);
+ assert.equal(store.getState().enabled, true);
+});
+
+// A refresh trigger can arrive while the leave PATCH is still in flight. The
+// read must not report the row the leave is busy changing.
+test("a read started during a leave never reports the account still joined", async (t) => {
+ let releaseLeave;
+ const { context, requests, store } = await loadStore(t, {
+ cloudApiRequest: async (request) => {
+ if (request.method === "PATCH") {
+ await new Promise((resolve) => {
+ releaseLeave = resolve;
+ });
+ return { success: false, status: 500, error: "server error" };
+ }
+ return participation(true);
+ },
+ });
+
+ const leaving = store.getState().leave(context);
+ await waitFor(() => typeof releaseLeave === "function");
+ await store.getState().refresh(context);
+ assert.deepEqual(
+ requests.map((request) => request.method),
+ ["PATCH"],
+ "the read must defer to the write already changing the row"
+ );
+
+ releaseLeave();
+ assert.equal(await leaving, false);
+ assert.equal(store.getState().enabled, false);
+ assert.equal(store.getState().ready, true);
+});
+
+test("a read that resolves after a write is retired by it", async (t) => {
+ let releaseRead;
+ const { context, store } = await loadStore(t, {
+ cloudApiRequest: async (request) => {
+ if (request.method === "GET") {
+ await new Promise((resolve) => {
+ releaseRead = resolve;
+ });
+ return participation(true);
+ }
+ return participation(false);
+ },
+ });
+
+ const reading = store.getState().refresh(context);
+ await waitFor(() => typeof releaseRead === "function");
+ const leaving = store.getState().leave(context);
+
+ releaseRead();
+ await reading;
+ await leaving;
+ assert.equal(
+ store.getState().enabled,
+ false,
+ "the completed leave is newer than the read it overtook"
+ );
+});
+
+test("a join retires the queued leave before its own request goes out", async (t) => {
+ const { context, requests, storage, store } = await loadStore(t, {
+ initialStorage: { [pendingKey("user_1")]: "true", [pendingKey("user_2")]: "true" },
+ cloudApiRequest: async () => participation(true),
+ });
+
+ assert.equal(await store.getState().join(context), true);
+ assert.deepEqual(requests, [
+ {
+ method: "PATCH",
+ path: "/api/analytics/participation",
+ body: { enabled: true },
+ public: false,
+ expectedAuthGeneration: 7,
+ },
+ ]);
+ assert.deepEqual(
+ pendingUserIds(storage),
+ ["user_2"],
+ "only the joining account's leave is retired"
+ );
+ assert.equal(store.getState().enabled, true);
+ assert.equal(store.getState().configured, true);
+ assert.equal(store.getState().error, null);
+});
+
+test("a failed join reports that participation did not change", async (t) => {
+ const { context, storage, store } = await loadStore(t, {
+ cloudApiRequest: async () => ({ success: false, status: 500, error: "server error" }),
+ });
+
+ assert.equal(await store.getState().join(context), false);
+ assert.equal(store.getState().enabled, false);
+ assert.equal(store.getState().configured, true);
+ assert.equal(store.getState().error, "write");
+ assert.equal(store.getState().updating, false);
+ assert.deepEqual(
+ pendingUserIds(storage),
+ ["user_1"],
+ "an ambiguous failure must compensate if the server committed before the response was lost"
+ );
+});
+
+test("a newer join clears an older ambiguous join failure", async (t) => {
+ let releaseFirstJoin;
+ let requestCount = 0;
+ const { context, requests, storage, store } = await loadStore(t, {
+ cloudApiRequest: async () => {
+ requestCount += 1;
+ if (requestCount === 1) {
+ await new Promise((resolve) => {
+ releaseFirstJoin = resolve;
+ });
+ return { success: false, status: 0, error: "response lost" };
+ }
+ return participation(true);
+ },
+ });
+
+ const firstJoin = store.getState().join(context);
+ await waitFor(() => typeof releaseFirstJoin === "function");
+ const secondJoin = store.getState().join(context);
+ await Promise.resolve();
+ assert.equal(requests.length, 1, "same-account writes must not race at the API");
+
+ releaseFirstJoin();
+ assert.equal(await firstJoin, false);
+ assert.equal(await secondJoin, true);
+ assert.deepEqual(pendingUserIds(storage), [], "the latest explicit join wins");
+ assert.equal(store.getState().enabled, true);
+ assert.equal(store.getState().updating, false);
+});
+
+test("a newer join clears an older failed leave without being undone later", async (t) => {
+ let releaseLeave;
+ let requestCount = 0;
+ const { context, requests, storage, store } = await loadStore(t, {
+ cloudApiRequest: async () => {
+ requestCount += 1;
+ if (requestCount === 1) {
+ await new Promise((resolve) => {
+ releaseLeave = resolve;
+ });
+ return { success: false, status: 0, error: "offline" };
+ }
+ return participation(true);
+ },
+ });
+
+ const leave = store.getState().leave(context);
+ await waitFor(() => typeof releaseLeave === "function");
+ const join = store.getState().join(context);
+ await Promise.resolve();
+ assert.equal(requests.length, 1, "the newer join waits for the leave to settle");
+
+ releaseLeave();
+ assert.equal(await leave, false);
+ assert.equal(await join, true);
+ assert.deepEqual(pendingUserIds(storage), [], "the latest explicit join retires the leave");
+ assert.equal(store.getState().enabled, true);
+});
+
+test("a refresh flushes the pending leave before reporting the answer", async (t) => {
+ let accountEnabled = true;
+ const { context, requests, storage, store } = await loadStore(t, {
+ initialStorage: { [pendingKey("user_1")]: "true" },
+ cloudApiRequest: async (request) => {
+ if (request.method === "PATCH") accountEnabled = request.body.enabled;
+ return participation(accountEnabled);
+ },
+ });
+
+ await store.getState().refresh(context);
+ assert.deepEqual(
+ requests.map((request) => request.method),
+ ["PATCH", "GET"],
+ "the opt-out has to land before the read that reports it"
+ );
+ assert.deepEqual(pendingUserIds(storage), []);
+ assert.equal(store.getState().enabled, false);
+});
+
+test("a participation read that fails offers a retry rather than a stale answer", async (t) => {
+ const { context, store } = await loadStore(t, {
+ cloudApiRequest: async () => ({ success: false, status: 0, error: "offline" }),
+ });
+ store.setState({ enabled: true, ready: true });
+
+ await store.getState().refresh(context);
+ assert.equal(store.getState().enabled, false);
+ assert.equal(store.getState().error, "read");
+ assert.equal(store.getState().ready, true);
+});
+
+test("simultaneous participation reads for one account share one request", async (t) => {
+ let releaseRead;
+ const { context, requests, store } = await loadStore(t, {
+ cloudApiRequest: async () => {
+ await new Promise((resolve) => {
+ releaseRead = resolve;
+ });
+ return participation(true);
+ },
+ });
+
+ const first = store.getState().refresh(context);
+ const second = store.getState().refresh(context);
+ await waitFor(() => typeof releaseRead === "function");
+ assert.equal(requests.length, 1);
+
+ releaseRead();
+ await Promise.all([first, second]);
+ assert.equal(store.getState().enabled, true);
+});
+
+test("signing out drops the previous account's answer", async (t) => {
+ const { store } = await loadStore(t, { cloudApiRequest: async () => participation(true) });
+ store.setState({ enabled: true, ready: true, error: "read" });
+
+ store.getState().reset();
+ assert.equal(store.getState().enabled, false);
+ assert.equal(store.getState().ready, false);
+ assert.equal(store.getState().error, null);
+});
+
+// An account switch resets the store while a write is still out. Its answer is
+// about the account that left, so it must not settle the one that replaced it,
+// and the read it defers must not stay deferred for as long as it takes to fail.
+test("a write left over from the departing account cannot settle the next one", async (t) => {
+ let releaseLeave;
+ const { context, storage, store } = await loadStore(t, {
+ cloudApiRequest: async () => {
+ await new Promise((resolve) => {
+ releaseLeave = resolve;
+ });
+ return { success: false, status: 0, error: "offline" };
+ },
+ });
+
+ const leaving = store.getState().leave(context);
+ await waitFor(() => typeof releaseLeave === "function");
+ store.getState().reset();
+ assert.equal(
+ store.getState().updating,
+ false,
+ "the departed account's write must stop deferring the next account's read"
+ );
+
+ releaseLeave();
+ assert.equal(await leaving, false);
+ assert.equal(store.getState().enabled, false);
+ assert.equal(store.getState().ready, false, "the stale write must not report an answer");
+ assert.deepEqual(
+ pendingUserIds(storage),
+ ["user_1"],
+ "the opt-out is tagged with the account that asked, so the reset cannot drop it"
+ );
+});
+
+test("a departing account's write cannot clear a newer account's write state", async (t) => {
+ let releaseFirstWrite;
+ let releaseSecondWrite;
+ let requestCount = 0;
+ const { context, store } = await loadStore(t, {
+ cloudApiRequest: async () => {
+ requestCount += 1;
+ if (requestCount === 1) {
+ await new Promise((resolve) => {
+ releaseFirstWrite = resolve;
+ });
+ return { success: false, status: 0, error: "offline" };
+ }
+ await new Promise((resolve) => {
+ releaseSecondWrite = resolve;
+ });
+ return participation(true);
+ },
+ });
+
+ const firstWrite = store.getState().leave(context);
+ await waitFor(() => typeof releaseFirstWrite === "function");
+ store.getState().reset();
+ const user2 = await validateAuthContext("user_2", 8, false);
+ const secondWrite = store.getState().join(user2);
+
+ releaseFirstWrite();
+ await firstWrite;
+ assert.equal(
+ store.getState().updating,
+ true,
+ "the first account must not make the second account's pending write look complete"
+ );
+
+ await waitFor(() => typeof releaseSecondWrite === "function");
+ releaseSecondWrite();
+ await secondWrite;
+ assert.equal(store.getState().updating, false);
+ assert.equal(store.getState().enabled, true);
+});