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 unified analytics insights (#1959)

voidc749d6e1ea59
diff --git a/preload.js b/preload.js
index 79157a38f..5cd94212e 100644
--- a/preload.js
+++ b/preload.js
@@ -126,6 +126,19 @@ contextBridge.exposeInMainWorld("electronAPI", {
ipcRenderer.invoke("db-save-transcription", text, rawText, options),
getTranscriptions: (limit, options) =>
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"),
clearTranscriptions: () => ipcRenderer.invoke("db-clear-transcriptions"),
deleteTranscription: (id) => ipcRenderer.invoke("db-delete-transcription", id),
@@ -346,6 +359,11 @@ contextBridge.exposeInMainWorld("electronAPI", {
ipcRenderer.on("transcription-updated", listener);
return () => ipcRenderer.removeListener("transcription-updated", listener);
},
+ onAnalyticsChanged: (callback) => {
+ const listener = () => callback?.();
+ ipcRenderer.on("analytics-changed", listener);
+ return () => ipcRenderer.removeListener("analytics-changed", listener);
+ },
// BYOK API keys (get/save for every provider in the secretKeys manifest)
...secretKeyApi,
diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsx
index 7b9339c64..e15627be7 100644
--- a/src/components/ControlPanel.tsx
+++ b/src/components/ControlPanel.tsx
@@ -101,6 +101,7 @@ const toggleIconClass =
const SettingsModal = React.lazy(() => import("./SettingsModal"));
const ReferralModal = React.lazy(() => import("./ReferralModal"));
const PersonalNotesView = React.lazy(() => import("./notes/PersonalNotesView"));
+const InsightsView = React.lazy(() => import("./InsightsView"));
const DictionaryView = React.lazy(() => import("./DictionaryView"));
const UploadAudioView = React.lazy(() => import("./notes/UploadAudioView"));
const IntegrationsView = React.lazy(() => import("./IntegrationsView"));
@@ -542,7 +543,11 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro
const clearAllTranscriptions = useCallback(() => {
showConfirmDialog({
title: t("controlPanel.history.clearAllTitle"),
- description: t("controlPanel.history.clearAllDescription"),
+ description: t(
+ isSignedIn
+ ? "controlPanel.history.clearAllDescription"
+ : "controlPanel.history.clearAllDescriptionDevice"
+ ),
onConfirm: async () => {
try {
const result = await window.electronAPI.clearTranscriptions();
@@ -569,7 +574,7 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro
},
variant: "destructive",
});
- }, [showConfirmDialog, showAlertDialog, toast, t]);
+ }, [isSignedIn, showConfirmDialog, showAlertDialog, toast, t]);
const showAudioInFolder = useCallback(
async (id: number) => {
@@ -1173,6 +1178,11 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro
onOpenIntegrations={() => setActiveView("integrations")}
/>
)}
+ {activeView === "insights" && (
+ <Suspense fallback={null}>
+ <InsightsView />
+ </Suspense>
+ )}
{activeView === "chat" && agentAllowedByPolicy && (
<Suspense fallback={null}>
<ChatView />
diff --git a/src/components/ControlPanelSidebar.tsx b/src/components/ControlPanelSidebar.tsx
index f9f354220..77102dfcb 100644
--- a/src/components/ControlPanelSidebar.tsx
+++ b/src/components/ControlPanelSidebar.tsx
@@ -1,6 +1,7 @@
import React, { useState } from "react";
import {
Home,
+ BarChart3,
MessageSquare,
NotebookPen,
BookOpen,
@@ -35,7 +36,7 @@ const rowButtonClass =
"group flex items-center gap-2.5 w-full h-8 px-2.5 rounded-md text-left outline-none hover:bg-foreground/4 dark:hover:bg-white/4 focus-visible:ring-1 focus-visible:ring-primary/30 transition-colors duration-150";
export type ControlPanelView =
- "home" | "chat" | "personal-notes" | "dictionary" | "upload" | "integrations";
+ "home" | "insights" | "chat" | "personal-notes" | "dictionary" | "upload" | "integrations";
interface ControlPanelSidebarProps {
activeView: ControlPanelView;
@@ -87,6 +88,7 @@ export default function ControlPanelSidebar({
icon: React.ComponentType<{ size?: number; className?: string }>;
}[] = [
{ id: "home", label: t("sidebar.home"), icon: Home },
+ { id: "insights", label: t("sidebar.insights"), icon: BarChart3 },
...(agentAllowed
? [{ id: "chat" as const, label: t("sidebar.chat"), icon: MessageSquare }]
: []),
diff --git a/src/components/InsightsView.tsx b/src/components/InsightsView.tsx
new file mode 100644
index 000000000..b97196b7f
--- /dev/null
+++ b/src/components/InsightsView.tsx
@@ -0,0 +1,419 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { BarChart3, Cloud, Flame, Gauge, Loader2, Mic2 } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { useAuth } from "../hooks/useAuth";
+import { useInsightsSyncOptIn } from "../hooks/useInsightsSyncOptIn";
+import { useSettings } from "../hooks/useSettings";
+import {
+ getAccountAnalyticsSummary,
+ subscribeToAnalyticsRefresh,
+ syncPendingAnalytics,
+} from "../services/AnalyticsService";
+import { buildAnalyticsActivityDays } from "../helpers/analytics";
+import { canOfferAnalyticsClaim } from "../services/syncPassPolicy";
+import { effectiveLocalHistoryEnabled } from "../stores/policyRules";
+import { usePolicyStore } from "../stores/policyStore";
+import type { AnalyticsDailyBucket, AnalyticsSummary } from "../types/electron";
+import { cn } from "./lib/utils";
+import { Tooltip } from "./ui/tooltip";
+
+type ActivityDay = { date: string; words: number };
+
+const ACTIVITY_INTENSITY_CLASSES = [
+ "bg-foreground/6 dark:bg-white/6",
+ "bg-primary/25",
+ "bg-primary/45",
+ "bg-primary/70",
+ "bg-primary",
+] as const;
+
+function dateFromLocalKey(value: string) {
+ const [year, month, day] = value.split("-").map(Number);
+ return new Date(year, month - 1, day, 12);
+}
+
+function Heatmap({ daily }: { daily: AnalyticsDailyBucket[] }) {
+ const { t, i18n } = useTranslation();
+ const calendar = useMemo(() => {
+ const days: ActivityDay[] = buildAnalyticsActivityDays(daily);
+ const cells: Array<ActivityDay | null> = [
+ ...Array(dateFromLocalKey(days[0].date).getDay()).fill(null),
+ ...days,
+ ];
+ while (cells.length % 7 !== 0) cells.push(null);
+
+ const weeks = Array.from({ length: cells.length / 7 }, (_, index) =>
+ cells.slice(index * 7, index * 7 + 7)
+ );
+ const monthFormatter = new Intl.DateTimeFormat(i18n.language, { month: "short" });
+ let previousMonth = "";
+ const monthLabels = weeks.map((week, index) => {
+ const labelDay =
+ week.find((day) => day?.date.endsWith("-01")) ||
+ (index === 0 ? week.find((day) => day !== null) : null);
+ if (!labelDay) return null;
+ const month = labelDay.date.slice(0, 7);
+ if (month === previousMonth) return null;
+ previousMonth = month;
+ return monthFormatter.format(dateFromLocalKey(labelDay.date));
+ });
+
+ return {
+ maxWords: Math.max(1, ...days.map((day) => day.words)),
+ monthLabels,
+ todayDate: days[days.length - 1].date,
+ weeks,
+ };
+ }, [daily, i18n.language]);
+
+ const weekdayLabels = useMemo(
+ () =>
+ Array.from({ length: 7 }, (_, index) =>
+ new Intl.DateTimeFormat(i18n.language, { weekday: "short" }).format(
+ new Date(2024, 0, 7 + index, 12)
+ )
+ ),
+ [i18n.language]
+ );
+ // Fixed tracks, sized to the 1.5rem cells they hold. minmax(0, 1fr) let every
+ // week column collapse toward zero while the cells stayed 24px wide, so the
+ // squares overflowed their tracks and overlapped each other; the grid also
+ // contributed no intrinsic width, leaving overflow-x nothing to scroll, so
+ // the newest weeks — today's cell among them — were painted outside the
+ // scrollable area on any window narrower than about 1050px.
+ const columnStyle = { gridTemplateColumns: `repeat(${calendar.weeks.length}, 1.5rem)` };
+
+ return (
+ // Focusable, so the chart can be scrolled without a mouse. role="img" used
+ // to sit on the container, which made every descendant presentational and
+ // silently discarded the per-day labels below it; the cells carry it now
+ // and the group only names the chart.
+ <div
+ className="overflow-x-auto rounded-sm pb-1 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/40"
+ tabIndex={0}
+ role="group"
+ aria-label={t("insights.activityLabel")}
+ >
+ <div className="w-max">
+ <div className="grid grid-cols-[auto_max-content] gap-x-3">
+ <div aria-hidden="true" />
+ <div className="grid h-4 gap-2" style={columnStyle} aria-hidden="true">
+ {calendar.monthLabels.map((label, index) => (
+ <span
+ key={index}
+ className="truncate text-[10px] font-medium text-muted-foreground/70"
+ >
+ {label}
+ </span>
+ ))}
+ </div>
+
+ <div className="grid grid-rows-7 gap-0.5" aria-hidden="true">
+ {weekdayLabels.map((label) => (
+ <span key={label} className="flex items-center text-[10px] text-muted-foreground/70">
+ {label}
+ </span>
+ ))}
+ </div>
+
+ <div className="grid gap-2" style={columnStyle}>
+ {calendar.weeks.map((week, weekIndex) => (
+ <div key={weekIndex} className="grid grid-rows-7 gap-0.5">
+ {week.map((day, dayIndex) => {
+ if (!day) {
+ return (
+ <div
+ key={dayIndex}
+ aria-hidden="true"
+ className="size-6 justify-self-center"
+ />
+ );
+ }
+ const intensity =
+ day.words === 0
+ ? 0
+ : Math.max(1, Math.ceil((day.words / calendar.maxWords) * 4));
+ const tooltip = t("insights.dayTooltip", {
+ date: day.date,
+ count: day.words,
+ });
+ return (
+ <div key={day.date} className="justify-self-center">
+ <Tooltip content={tooltip}>
+ <div
+ role="img"
+ aria-label={tooltip}
+ className={cn(
+ "size-6 rounded-sm",
+ ACTIVITY_INTENSITY_CLASSES[intensity],
+ day.date === calendar.todayDate &&
+ "ring-1 ring-primary ring-offset-1 ring-offset-card"
+ )}
+ />
+ </Tooltip>
+ </div>
+ );
+ })}
+ </div>
+ ))}
+ </div>
+ </div>
+
+ <div className="mt-2 flex items-center text-[10px] text-muted-foreground">
+ <div className="flex items-center gap-2">
+ <span>{t("insights.activityLess")}</span>
+ <div className="flex items-center gap-1" aria-hidden="true">
+ {ACTIVITY_INTENSITY_CLASSES.slice(1).map((className) => (
+ <span key={className} className={cn("size-3 rounded-sm", className)} />
+ ))}
+ </div>
+ <span>{t("insights.activityMore")}</span>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function MetricCard({
+ icon: Icon,
+ label,
+ value,
+ detail,
+ largeValue = false,
+}: {
+ icon: typeof BarChart3;
+ label: string;
+ value: string;
+ detail: string;
+ largeValue?: boolean;
+}) {
+ return (
+ <div className="rounded-xl border border-border/40 dark:border-white/8 bg-card/70 p-4">
+ <div className="flex items-center gap-2 text-muted-foreground">
+ <Icon size={14} />
+ <span className="text-xs">{label}</span>
+ </div>
+ <p
+ className={cn(
+ "mt-3 font-semibold tracking-tight text-foreground",
+ largeValue ? "text-3xl" : "text-2xl"
+ )}
+ >
+ {value}
+ </p>
+ <p className="mt-1 text-[11px] text-muted-foreground/70">{detail}</p>
+ </div>
+ );
+}
+
+export default function InsightsView() {
+ 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);
+ const [loadFailed, setLoadFailed] = useState(false);
+ // Every dictation broadcasts analytics-changed, so loads overlap; only the
+ // newest one may write state, or a slow reply overwrites a fresher summary.
+ // A superseded load also bails before syncing, so two passes cannot share a
+ // batch and leave the winner reading a summary the other has not finished.
+ const requestIdRef = useRef(0);
+
+ const load = useCallback(async () => {
+ const requestId = ++requestIdRef.current;
+ setLoading(true);
+ setSyncError(false);
+
+ // The device read stands on its own. Folding it into the same catch as the
+ // cloud fetch meant a failed local read fell through to a summary of
+ // zeros — under a confident "On this device", with no error anywhere — and
+ // told the user their history was empty.
+ let local: AnalyticsSummary;
+ try {
+ local = await window.electronAPI.getAnalyticsSummary();
+ } catch (error) {
+ if (requestId !== requestIdRef.current) return;
+ console.error("Reading local Insights failed:", error);
+ setLoadFailed(true);
+ setLoading(false);
+ return;
+ }
+ if (requestId !== requestIdRef.current) return;
+ setLoadFailed(false);
+
+ try {
+ if (isLoaded && syncActive) {
+ await syncPendingAnalytics();
+ const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
+ const account = await getAccountAnalyticsSummary(timeZone);
+ if (requestId !== requestIdRef.current) return;
+ setSummary(account);
+ } else {
+ setSummary(local);
+ }
+ } catch {
+ if (requestId !== requestIdRef.current) return;
+ // Real device data, and the pill says the cloud is the part that failed.
+ setSummary(local);
+ setSyncError(true);
+ } finally {
+ if (requestId === requestIdRef.current) setLoading(false);
+ }
+ }, [isLoaded, syncActive]);
+
+ useEffect(() => subscribeToAnalyticsRefresh(load, syncActive), [load, syncActive]);
+
+ // 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.
+ const number = useMemo(
+ () => new Intl.NumberFormat(i18n.language, { notation: "compact", maximumFractionDigits: 1 }),
+ [i18n.language]
+ );
+
+ 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>
+ </div>
+ );
+ }
+
+ 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>
+ </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>
+ <p className="text-xs text-amber-700 dark:text-amber-300/90 leading-relaxed">
+ {t("insights.dataRetentionDisabled")}
+ </p>
+ </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">
+ <BarChart3 size={40} className="mb-4 text-foreground/15" aria-hidden="true" />
+ <h2 className="text-sm font-medium text-foreground">{t("insights.emptyTitle")}</h2>
+ <p className="mt-1.5 max-w-sm text-xs text-muted-foreground">
+ {t("insights.emptyBody")}
+ </p>
+ </div>
+ </div>
+ ) : (
+ <>
+ <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
+ <MetricCard
+ icon={Mic2}
+ label={t("insights.wordsSpoken")}
+ value={number.format(summary.totalWords)}
+ detail={t("insights.allTime")}
+ largeValue
+ />
+ <MetricCard
+ icon={Gauge}
+ label={t("insights.wordsPerMinute")}
+ value={summary.averageWpm == null ? "—" : number.format(summary.averageWpm)}
+ detail={t("insights.wpmCoverage", { count: summary.wpmCoveragePercent })}
+ largeValue
+ />
+ <MetricCard
+ icon={BarChart3}
+ label={t("insights.dictations")}
+ value={number.format(summary.totalDictations)}
+ detail={t("insights.allTime")}
+ largeValue
+ />
+ <MetricCard
+ icon={Flame}
+ label={t("insights.currentStreak")}
+ value={t("insights.days", { count: summary.currentStreakDays })}
+ detail={t("insights.longestStreak", { count: summary.longestStreakDays })}
+ />
+ </div>
+
+ <div className="mt-5 rounded-2xl border border-border/50 bg-card/70 px-5 py-2.5 dark:border-white/8">
+ <h2 className="text-base font-medium text-foreground">{t("insights.activity")}</h2>
+ <div className="mt-2">
+ <Heatmap daily={summary.daily} />
+ </div>
+ </div>
+ </>
+ )}
+
+ {optInDialog}
+ </div>
+ );
+}
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index a4b9984b8..74a86f59c 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -62,6 +62,7 @@ import {
import { Alert, AlertTitle, AlertDescription } from "./ui/alert";
import { useSettings } from "../hooks/useSettings";
import { useDialogs } from "../hooks/useDialogs";
+import { useInsightsSyncOptIn } from "../hooks/useInsightsSyncOptIn";
import { useWhisper } from "../hooks/useWhisper";
import { usePermissions } from "../hooks/usePermissions";
import { useSystemAudioPermission } from "../hooks/useSystemAudioPermission";
@@ -1138,6 +1139,8 @@ export default function SettingsPage({
setPanelStartPosition,
cloudBackupEnabled,
setCloudBackupEnabled,
+ insightsSyncEnabled,
+ setInsightsSyncEnabled,
telemetryEnabled,
setTelemetryEnabled,
audioRetentionDays,
@@ -1697,6 +1700,12 @@ export default function SettingsPage({
}, [isRemovingModels, cachePathHint, showConfirmDialog, showAlertDialog, t]);
const { isSignedIn, isLoaded, user, refetch } = useAuth();
+ const {
+ canToggleSync: canToggleInsightsSync,
+ enableInsightsSync,
+ optInDialog: insightsOptInDialog,
+ syncAllowedByPolicy: insightsSyncAllowedByPolicy,
+ } = useInsightsSyncOptIn();
// 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";
@@ -4070,6 +4079,38 @@ EOF`,
)}
<SettingsPanel>
+ <SettingsPanelRow>
+ <SettingsRow
+ label={t("settingsPage.privacy.insightsSync")}
+ description={
+ !isSignedIn
+ ? t("settingsPage.privacy.insightsSyncRequiresAccount")
+ : !insightsSyncAllowedByPolicy
+ ? t("common.managedByOrg")
+ : effectiveDataRetentionEnabled
+ ? t("settingsPage.privacy.insightsSyncDescription")
+ : t("settingsPage.privacy.insightsSyncRequiresHistory")
+ }
+ >
+ {/* With history off nothing is counted anywhere: this
+ device records no counter, and the cloud writes none
+ either, because analyticsSyncEnabled withholds the
+ localDate its analytics write requires. Turning this on
+ could therefore only promise a sync that never happens —
+ but an already-on toggle must stay switchable off. */}
+ <Toggle
+ checked={insightsSyncEnabled}
+ disabled={
+ !isSignedIn ||
+ !canToggleInsightsSync ||
+ (!effectiveDataRetentionEnabled && !insightsSyncEnabled)
+ }
+ onChange={(enabled) =>
+ enabled ? enableInsightsSync() : setInsightsSyncEnabled(false)
+ }
+ />
+ </SettingsRow>
+ </SettingsPanelRow>
<SettingsPanelRow>
<SettingsRow
label={t("settingsPage.privacy.usageAnalytics")}
@@ -4578,6 +4619,8 @@ EOF`,
return (
<>
+ {insightsOptInDialog}
+
<ConfirmDialog
open={confirmDialog.open}
onOpenChange={(open) => !open && hideConfirmDialog()}
diff --git a/src/helpers/analytics.js b/src/helpers/analytics.js
new file mode 100644
index 000000000..12e3bc0a0
--- /dev/null
+++ b/src/helpers/analytics.js
@@ -0,0 +1,155 @@
+// ESM like calendarAvailability.js: this module is shared with the renderer,
+// where Vite only handles ESM source files; main-process CJS callers load it
+// via Node's require(esm) with module-syntax detection.
+const DAY_MS = 86_400_000;
+export const ANALYTICS_ACTIVITY_MONTH_COUNT = 6;
+export const ANALYTICS_COUNTER_VERSION = 2;
+
+const CJK_SCRIPT_PATTERN =
+ /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
+
+function countWhitespaceDelimitedWords(text) {
+ const trimmed = typeof text === "string" ? text.trim() : "";
+ return trimmed ? trimmed.split(/\s+/).length : 0;
+}
+
+export function countSpokenWords(text) {
+ const fallbackCount = countWhitespaceDelimitedWords(text);
+ if (fallbackCount === 0 || !CJK_SCRIPT_PATTERN.test(text)) return fallbackCount;
+
+ try {
+ if (typeof Intl === "undefined" || !Intl.Segmenter) return fallbackCount;
+ const segmenter = new Intl.Segmenter("und", { granularity: "word" });
+ const segmentedCount = Array.from(segmenter.segment(text)).filter(
+ (segment) => segment.isWordLike
+ ).length;
+ return segmentedCount || fallbackCount;
+ } catch {
+ return fallbackCount;
+ }
+}
+
+export function localDateKey(date = new Date()) {
+ const year = date.getFullYear();
+ const month = String(date.getMonth() + 1).padStart(2, "0");
+ const day = String(date.getDate()).padStart(2, "0");
+ return `${year}-${month}-${day}`;
+}
+
+export function buildAnalyticsActivityDays(daily, today = new Date()) {
+ const byDate = new Map(daily.map((bucket) => [bucket.date, bucket]));
+ const startDate = new Date(
+ today.getFullYear(),
+ today.getMonth() - ANALYTICS_ACTIVITY_MONTH_COUNT + 1,
+ 1,
+ 12
+ );
+ const endDate = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 12);
+ const days = [];
+
+ for (
+ let date = startDate;
+ date <= endDate;
+ date = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1, 12)
+ ) {
+ const key = localDateKey(date);
+ days.push({ date: key, words: byDate.get(key)?.words || 0 });
+ }
+
+ return days;
+}
+
+function modeFromSettings({ useLocalWhisper, transcriptionMode, cloudTranscriptionMode }) {
+ if (useLocalWhisper || transcriptionMode === "local") return "local";
+ if (transcriptionMode === "self-hosted") return "self_hosted";
+ if (cloudTranscriptionMode === "openwhispr" || transcriptionMode === "openwhispr") {
+ return "openwhispr_cloud";
+ }
+ if (transcriptionMode === "providers") return "byok";
+ return "unknown";
+}
+
+function modeFromStoredProvider(provider) {
+ if (!provider) return "unknown";
+ if (provider.startsWith("local")) return "local";
+ if (provider === "openwhispr") return "openwhispr_cloud";
+ if (provider.includes("self-hosted") || provider === "lan") return "self_hosted";
+ return "byok";
+}
+
+// The provider that actually ran wins when it names a concrete engine or ends
+// in "-fallback", which proves the selected route never ran. Streaming provider
+// names ("deepgram-streaming") are too coarse to tell BYOK from OpenWhispr
+// Cloud, so everything else defers to the selected settings.
+export function resolveAnalyticsMode(settings, provider) {
+ const providerMode = modeFromStoredProvider(provider);
+ if (providerMode === "local" || providerMode === "self_hosted") return providerMode;
+ if (provider?.endsWith("-fallback")) return providerMode;
+ const selected = modeFromSettings(settings);
+ return selected === "unknown" ? providerMode : selected;
+}
+
+function dayNumber(value) {
+ return Math.floor(Date.parse(`${value}T00:00:00Z`) / DAY_MS);
+}
+
+export function calculateStreaks(ascendingDays, today) {
+ const days = [...new Set(ascendingDays)].sort();
+ if (days.length === 0) return { currentStreakDays: 0, longestStreakDays: 0 };
+
+ let run = 1;
+ let longestStreakDays = 1;
+ for (let index = 1; index < days.length; index += 1) {
+ run = dayNumber(days[index]) - dayNumber(days[index - 1]) === 1 ? run + 1 : 1;
+ longestStreakDays = Math.max(longestStreakDays, run);
+ }
+
+ if (dayNumber(today) - dayNumber(days[days.length - 1]) > 1) {
+ return { currentStreakDays: 0, longestStreakDays };
+ }
+
+ let currentStreakDays = 1;
+ for (let index = days.length - 1; index > 0; index -= 1) {
+ if (dayNumber(days[index]) - dayNumber(days[index - 1]) !== 1) break;
+ currentStreakDays += 1;
+ }
+ return { currentStreakDays, longestStreakDays };
+}
+
+// Takes one row per local date (grouped in SQL so the row count stays bounded
+// by calendar days) and stays the single owner of every derived figure.
+export function summarizeAnalyticsDays(days, today = localDateKey()) {
+ const daily = [...days].sort((a, b) => a.date.localeCompare(b.date));
+ let totalWords = 0;
+ let totalDictations = 0;
+ let totalSpokenDurationMs = 0;
+ let coveredWords = 0;
+
+ for (const day of daily) {
+ totalWords += day.words;
+ totalDictations += day.dictations;
+ totalSpokenDurationMs += day.spokenDurationMs;
+ coveredWords += day.coveredWords;
+ }
+
+ return {
+ totalWords,
+ totalDictations,
+ totalSpokenDurationMs,
+ averageWpm:
+ totalSpokenDurationMs > 0
+ ? Math.round((coveredWords * 60_000) / totalSpokenDurationMs)
+ : null,
+ ...calculateStreaks(
+ daily.map((day) => day.date),
+ today
+ ),
+ wpmCoveragePercent: totalWords > 0 ? Math.round((coveredWords / totalWords) * 100) : 0,
+ daily: daily.slice(-366).map(({ date, words, dictations, spokenDurationMs }) => ({
+ date,
+ words,
+ dictations,
+ spokenDurationMs,
+ })),
+ };
+}
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index 3d600cebc..cfd0a3f3b 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -29,6 +29,12 @@ import { followsSystemDefaultMic } from "./micSelectionRecovery";
import { isCacheableMicrophoneResolution, resolvePreferredMicrophone } from "./microphoneSelection";
import { isStaleDeviceError } from "./staleMicDevice";
import { shouldSaveDiscardedRecording } from "./discardedRecording";
+import {
+ ANALYTICS_COUNTER_VERSION,
+ countSpokenWords,
+ localDateKey,
+ resolveAnalyticsMode,
+} from "./analytics";
import {
getSettings,
useSettingsStore,
@@ -38,10 +44,12 @@ import {
isCloudTranslationMode,
selectResolvedLLMConfig,
} from "../stores/settingsStore";
+
import {
effectiveAudioRetentionDays,
effectiveLocalHistoryEnabled,
isAgentAllowed,
+ isCloudBackupAllowed,
isTranscriptionContextAllowed,
isTranscriptionSelectionAllowed,
} from "../stores/policyRules";
@@ -136,6 +144,20 @@ function getEffectiveRetentionPreferences() {
};
}
+// Insights sync is opt-in, so nothing analytics-only may ride along on a cloud
+// request until the user has enabled it. History retention gates it too: the
+// local write below the same gate is skipped, and the cloud must not keep rows
+// the device never recorded. Managed workspaces that forbid cloud backup forbid
+// these counters with it — they are user data leaving the device like any other.
+function analyticsSyncEnabled(settings = getSettings()) {
+ return (
+ settings.isSignedIn &&
+ settings.insightsSyncEnabled &&
+ isCloudBackupAllowed(usePolicyStore.getState()) &&
+ getEffectiveRetentionPreferences().dataRetentionEnabled
+ );
+}
+
const providerSupportsImages = (providerId) =>
!!(providerId && PROVIDER_REGISTRY[providerId]?.supportsImages);
@@ -1484,6 +1506,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
const durationSeconds = this.recordingStartTime
? (Date.now() - this.recordingStartTime) / 1000
: null;
+ const analyticsOccurredAt = new Date(this.recordingStartTime || Date.now()).toISOString();
this.recordingStartTime = null;
const recordingCheck = evaluateFinishedRecording({
blobSize: audioBlob.size,
@@ -1516,6 +1539,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
audioBlob,
{
durationSeconds,
+ analyticsOccurredAt,
...(salvagedRecording ? { salvagedRecording: true } : {}),
...(previewStop?.streamed ? { streamedText: previewStop.text } : {}),
},
@@ -1881,7 +1905,13 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
result = withSalvageWarning(result, metadata.salvagedRecording);
- result = { ...result, ...this._takePendingResultExtras() };
+ result = {
+ ...result,
+ ...(metadata.analyticsOccurredAt
+ ? { analyticsOccurredAt: metadata.analyticsOccurredAt }
+ : {}),
+ ...this._takePendingResultExtras(),
+ };
this.onTranscriptionComplete?.(result);
if (result?.source === "openwhispr") {
@@ -3129,7 +3159,12 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
const audioSizeBytes = audioBlob.size;
const audioFormat = audioBlob.type;
const opts = {};
+ const analyticsOccurredAt = new Date(metadata.analyticsOccurredAt || Date.now());
if (language) opts.language = language;
+ if (analyticsSyncEnabled(settings)) {
+ opts.analyticsOccurredAt = analyticsOccurredAt.toISOString();
+ opts.localDate = localDateKey(analyticsOccurredAt);
+ }
const cleanupCloudMode = settings.cleanupCloudMode || "openwhispr";
if (
(settings.useCleanupModel && cleanupCloudMode === "openwhispr") ||
@@ -3293,6 +3328,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
wordsUsed: result.wordsUsed,
wordsRemaining: result.wordsRemaining,
clientTranscriptionId: result.clientTranscriptionId,
+ analyticsOccurredAt: analyticsOccurredAt.toISOString(),
...(result.warning ? { warning: result.warning } : {}),
};
}
@@ -3750,7 +3786,11 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
}
}
- async saveTranscription(text, rawText = null, { clientTranscriptionId } = {}) {
+ async saveTranscription(
+ text,
+ rawText = null,
+ { clientTranscriptionId, analyticsOccurredAt } = {}
+ ) {
const { dataRetentionEnabled, audioRetentionDays } = getEffectiveRetentionPreferences();
if (!dataRetentionEnabled) {
logger.debug("Skipping transcription save — data retention disabled", {}, "audio");
@@ -3759,9 +3799,31 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
return true;
}
+ const eventId = clientTranscriptionId || crypto.randomUUID();
+ const occurredAt = analyticsOccurredAt ? new Date(analyticsOccurredAt) : new Date();
+ const metadata = this.lastAudioMetadata || {};
+ try {
+ await window.electronAPI.recordAnalyticsEvent({
+ eventId,
+ wordCount: countSpokenWords(rawText || text),
+ occurredAt: occurredAt.toISOString(),
+ localDate: localDateKey(occurredAt),
+ spokenDurationMs: metadata.durationMs || null,
+ mode: resolveAnalyticsMode(getSettings(), metadata.provider),
+ provider: metadata.provider || null,
+ model: metadata.model || null,
+ });
+ } catch (analyticsError) {
+ logger.warn(
+ "Failed to record local analytics event",
+ { error: analyticsError.message },
+ "analytics"
+ );
+ }
+
try {
const result = await window.electronAPI.saveTranscription(text, rawText, {
- clientTranscriptionId,
+ clientTranscriptionId: eventId,
routeKind: this.translationRequested ? "translation" : null,
});
if (result?.id) syncService.debouncedPush("transcription", result.id);
@@ -4621,6 +4683,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
const durationSeconds = this.recordingStartTime
? (Date.now() - this.recordingStartTime) / 1000
: null;
+ const analyticsOccurredAt = new Date(this.recordingStartTime || Date.now());
// Enter processing synchronously, before any mic/provider await. This is
// the authoritative guard that makes a second hotkey a no-op for the full
@@ -4756,7 +4819,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
const streamingAudioBytesSent = stopResult?.audioBytesSent || 0;
const streamingSttLanguage =
getBaseLanguageCode(this.getEffectiveSttLanguage(stSettings)) || undefined;
- const streamingSttWordCount = finalText ? finalText.split(/\s+/).filter(Boolean).length : 0;
+ const streamingSttWordCount = countSpokenWords(finalText);
// Reasoning below reassigns `finalText` to the cleaned-up/agent output, so
// snapshot the pre-reasoning transcript now to report as `rawText` — matching
// the batch path, which already keeps raw and processed text separate.
@@ -4918,6 +4981,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
// and cloud audio never cross over (see resolveStreamingFallbackTarget).
let usedBatchFallback = false;
let batchWarning = null;
+ let batchFallbackResult = null;
if (!finalText && durationSeconds > 2 && fallbackBlob?.size > 0) {
const target = resolveStreamingFallbackTarget(getSettings());
if (target === "skip") {
@@ -4938,7 +5002,10 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
target === "cloud"
? await this.processWithOpenWhisprCloud(
fallbackBlob,
- { durationSeconds },
+ {
+ durationSeconds,
+ analyticsOccurredAt: analyticsOccurredAt.toISOString(),
+ },
wasCancelled
)
: await this.processWithOpenAIAPI(fallbackBlob, { durationSeconds }, wasCancelled);
@@ -4946,6 +5013,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
if (batchResult?.text) {
finalText = batchResult.text;
usedBatchFallback = true;
+ batchFallbackResult = batchResult;
batchWarning = batchResult.warning || null;
logger.info("Batch fallback succeeded", { textLength: finalText.length }, "streaming");
}
@@ -4964,19 +5032,25 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
}
const tBeforePaste = performance.now();
const clientTotalMs = Math.round(tBeforePaste - t0);
+ const clientTranscriptionId =
+ batchFallbackResult?.clientTranscriptionId || crypto.randomUUID();
+ const resultAnalyticsOccurredAt =
+ batchFallbackResult?.analyticsOccurredAt || analyticsOccurredAt.toISOString();
this.lastAudioMetadata = {
durationMs: durationSeconds
? Math.round(durationSeconds * 1000)
: Math.round(tBeforePaste - t0),
- provider: `${this.getStreamingProviderName()}-streaming`,
- model: streamingSttModel || null,
+ provider: batchFallbackResult?.source || `${this.getStreamingProviderName()}-streaming`,
+ model: batchFallbackResult ? null : streamingSttModel || null,
};
if (wasCancelled()) return true;
this.onTranscriptionComplete?.({
success: true,
text: finalText,
- rawText: rawStreamingText || finalText,
- source: `${this.getStreamingProviderName()}-streaming`,
+ rawText: batchFallbackResult?.rawText || rawStreamingText || finalText,
+ source: batchFallbackResult?.source || `${this.getStreamingProviderName()}-streaming`,
+ clientTranscriptionId,
+ analyticsOccurredAt: resultAnalyticsOccurredAt,
...this._takePendingResultExtras(),
...(batchWarning ? { warning: batchWarning } : {}),
});
@@ -4997,6 +5071,27 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
audioSizeBytes: streamingAudioBytesSent || undefined,
audioFormat: "linear16",
clientTotalMs,
+ // Always sent, like the batch cloud path: this id is what
+ // makes the row the server writes and the local one the same
+ // event. Held back until opt-in, a later sync would push the
+ // local copy under a second id and double every total.
+ // Cosmetic caveat: the server labels its row mode
+ // "openwhispr_cloud" whatever actually transcribed the audio,
+ // and BYOK streaming reaches here too (tinfoil-realtime,
+ // corti, openai-realtime — see resolveStreamingProviderName).
+ // That row only exists when localDate rides along, which is
+ // exactly when this device also pushes its own copy under the
+ // same id, and last-write-wins replaces the label with the
+ // real mode. Neither summary renders mode either way.
+ clientTranscriptionId,
+ ...(analyticsSyncEnabled()
+ ? {
+ localDate: localDateKey(analyticsOccurredAt),
+ analyticsOccurredAt: analyticsOccurredAt.toISOString(),
+ analyticsWordCount: streamingSttWordCount,
+ analyticsCounterVersion: ANALYTICS_COUNTER_VERSION,
+ }
+ : {}),
}
);
if (!res.success) {
diff --git a/src/helpers/cloudChunkPolicy.js b/src/helpers/cloudChunkPolicy.js
index 34e8e177f..eb58d0203 100644
--- a/src/helpers/cloudChunkPolicy.js
+++ b/src/helpers/cloudChunkPolicy.js
@@ -52,6 +52,11 @@ const FATAL_CHUNK_CODES = new Set(["AUTH_EXPIRED", "LIMIT_REACHED"]);
const NON_RETRYABLE_CHUNK_CODES = new Set([...FATAL_CHUNK_CODES, "NO_SPEECH_DETECTED"]);
+function withoutChunkAnalytics(fields) {
+ const { localDate, analyticsOccurredAt, ...transcriptionFields } = fields;
+ return transcriptionFields;
+}
+
function isTransientChunkError(err) {
if (NON_RETRYABLE_CHUNK_CODES.has(err.code)) return false;
return !err.statusCode || err.statusCode >= 500;
@@ -245,4 +250,5 @@ module.exports = {
abortableSleep,
createTeardownGate,
createUploadSlots,
+ withoutChunkAnalytics,
};
diff --git a/src/helpers/database.js b/src/helpers/database.js
index c826e0321..3bf60ac1e 100644
--- a/src/helpers/database.js
+++ b/src/helpers/database.js
@@ -6,6 +6,7 @@ const debugLogger = require("./debugLogger");
const { buildNoteSearchQuery } = require("./noteSearch");
const { normalizeStoredSpeakerCount } = require("./speakerCount");
const { parseEventTime } = require("./calendarAvailability");
+const { ANALYTICS_COUNTER_VERSION, summarizeAnalyticsDays } = require("./analytics");
const { app } = require("electron");
// Server-enforced trigger cap (openwhispr-api); enforced here so one oversized
@@ -957,6 +958,42 @@ class DatabaseManager {
this.db.exec(
"CREATE UNIQUE INDEX IF NOT EXISTS idx_transcriptions_client_id ON transcriptions(client_transcription_id)"
);
+
+ this.db.exec(`
+ CREATE TABLE IF NOT EXISTS analytics_events (
+ event_id TEXT PRIMARY KEY,
+ account_id TEXT,
+ occurred_at TEXT NOT NULL,
+ local_date TEXT NOT NULL,
+ word_count INTEGER NOT NULL CHECK (word_count > 0),
+ spoken_duration_ms INTEGER,
+ mode TEXT NOT NULL,
+ provider TEXT,
+ model TEXT,
+ counter_version INTEGER NOT NULL DEFAULT 1,
+ sync_status TEXT NOT NULL DEFAULT 'pending',
+ deleted_at TEXT,
+ created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
+ );
+ CREATE INDEX IF NOT EXISTS idx_analytics_events_account_date
+ ON analytics_events(account_id, local_date);
+ CREATE TABLE IF NOT EXISTS analytics_clear_requests (
+ account_id TEXT PRIMARY KEY,
+ cleared_through TEXT NOT NULL,
+ synced INTEGER NOT NULL DEFAULT 0
+ );
+ CREATE TABLE IF NOT EXISTS analytics_device_clear_state (
+ id INTEGER PRIMARY KEY CHECK (id = 1),
+ cleared_through TEXT NOT NULL
+ );
+ `);
+ // Repair databases created before analytics deletion tombstones were
+ // introduced. SQLite has no ADD COLUMN IF NOT EXISTS syntax.
+ try {
+ this.db.exec("ALTER TABLE analytics_events ADD COLUMN deleted_at TEXT");
+ } catch (err) {
+ if (!err.message.includes("duplicate column")) throw err;
+ }
this.db.exec(
"CREATE UNIQUE INDEX IF NOT EXISTS idx_custom_dictionary_client_id ON custom_dictionary(client_dict_id)"
);
@@ -1255,6 +1292,272 @@ class DatabaseManager {
}
}
+ recordAnalyticsEvent({
+ eventId,
+ wordCount,
+ occurredAt,
+ localDate,
+ spokenDurationMs = null,
+ mode = "unknown",
+ provider = null,
+ model = null,
+ }) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ if (wordCount === 0) return { success: true, ignored: true };
+ // Clear History is device-wide, so an in-flight recording must stay
+ // cleared even if its account changes before this late write lands.
+ const cleared = this.db
+ .prepare(
+ `SELECT 1 FROM analytics_device_clear_state
+ WHERE id = 1 AND ? <= cleared_through`
+ )
+ .get(occurredAt);
+ if (cleared) return { success: true, ignored: true };
+ this.db
+ .prepare(
+ `INSERT INTO analytics_events (
+ event_id, account_id, occurred_at, local_date, word_count,
+ spoken_duration_ms, mode, provider, model, counter_version
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(event_id) DO UPDATE SET
+ account_id = COALESCE(analytics_events.account_id, excluded.account_id),
+ occurred_at = excluded.occurred_at,
+ local_date = excluded.local_date,
+ word_count = excluded.word_count,
+ spoken_duration_ms = COALESCE(
+ excluded.spoken_duration_ms,
+ analytics_events.spoken_duration_ms
+ ),
+ mode = excluded.mode,
+ provider = COALESCE(excluded.provider, analytics_events.provider),
+ model = COALESCE(excluded.model, analytics_events.model),
+ counter_version = excluded.counter_version,
+ sync_status = 'pending'
+ WHERE analytics_events.deleted_at IS NULL`
+ )
+ .run(
+ eventId,
+ this.activeAccountId,
+ occurredAt,
+ localDate,
+ wordCount,
+ Number(spokenDurationMs) > 0 ? Number(spokenDurationMs) : null,
+ mode,
+ provider,
+ model,
+ ANALYTICS_COUNTER_VERSION
+ );
+ return { success: true, eventId };
+ } catch (error) {
+ debugLogger.error("Error recording analytics event", { error: error.message }, "database");
+ throw error;
+ }
+ }
+
+ getAnalyticsSummary() {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ // Grouped in SQL so the row count is bounded by distinct days rather than
+ // by dictations; summarizeAnalyticsDays still owns every derived figure.
+ // Device-scoped by design: account_id only attributes rows for cloud
+ // sync, so filtering on it here would blank the view on every sign-out.
+ const days = this.db
+ .prepare(
+ `SELECT local_date AS date,
+ SUM(word_count) AS words,
+ COUNT(*) AS dictations,
+ SUM(CASE WHEN spoken_duration_ms > 0 THEN spoken_duration_ms ELSE 0 END)
+ AS spokenDurationMs,
+ SUM(CASE WHEN spoken_duration_ms > 0 THEN word_count ELSE 0 END)
+ AS coveredWords
+ FROM analytics_events
+ WHERE deleted_at IS NULL
+ GROUP BY local_date`
+ )
+ .all();
+ return summarizeAnalyticsDays(days);
+ } catch (error) {
+ debugLogger.error("Error reading analytics summary", { error: error.message }, "database");
+ throw error;
+ }
+ }
+
+ getPendingAnalyticsEvents(limit = 200) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ if (!this.activeAccountId) 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
+ // event schema -- occurred_at included, which that schema requires
+ // alongside local_date. It also orders the batch, oldest dictation first.
+ return this.db
+ .prepare(
+ `SELECT event_id, occurred_at, local_date, word_count, spoken_duration_ms,
+ mode, provider, model, counter_version
+ FROM analytics_events
+ WHERE account_id = ? AND sync_status = 'pending' AND deleted_at IS NULL
+ ORDER BY occurred_at ASC LIMIT ?`
+ )
+ .all(this.activeAccountId, safeLimit);
+ } catch (error) {
+ debugLogger.error("Error reading pending analytics", { error: error.message }, "database");
+ throw error;
+ }
+ }
+
+ markAnalyticsEventsSynced(eventIds) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ if (!this.activeAccountId || !Array.isArray(eventIds) || eventIds.length === 0) {
+ return { success: true, updated: 0 };
+ }
+ const placeholders = eventIds.map(() => "?").join(", ");
+ const result = this.db
+ .prepare(
+ `UPDATE analytics_events SET sync_status = 'synced'
+ WHERE account_id = ? AND deleted_at IS NULL
+ AND event_id IN (${placeholders})`
+ )
+ .run(this.activeAccountId, ...eventIds);
+ return { success: true, updated: result.changes };
+ } catch (error) {
+ debugLogger.error("Error marking analytics synced", { error: error.message }, "database");
+ throw error;
+ }
+ }
+
+ getPendingAnalyticsDeletes(limit = 200) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ if (!this.activeAccountId) return [];
+ const safeLimit = Math.max(1, Math.min(Number(limit) || 200, 200));
+ return this.db
+ .prepare(
+ `SELECT event_id FROM analytics_events
+ WHERE account_id = ? AND deleted_at IS NOT NULL AND sync_status = 'pending'
+ ORDER BY occurred_at ASC LIMIT ?`
+ )
+ .all(this.activeAccountId, safeLimit);
+ } catch (error) {
+ debugLogger.error(
+ "Error reading pending analytics deletes",
+ { error: error.message },
+ "database"
+ );
+ throw error;
+ }
+ }
+
+ hardDeleteAnalyticsEvents(eventIds) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ if (!this.activeAccountId || !Array.isArray(eventIds) || eventIds.length === 0) {
+ return { success: true, deleted: 0 };
+ }
+ const placeholders = eventIds.map(() => "?").join(", ");
+ const result = this.db
+ .prepare(
+ `DELETE FROM analytics_events
+ WHERE account_id = ? AND deleted_at IS NOT NULL
+ AND event_id IN (${placeholders})`
+ )
+ .run(this.activeAccountId, ...eventIds);
+ return { success: true, deleted: result.changes };
+ } catch (error) {
+ debugLogger.error(
+ "Error deleting synced analytics tombstones",
+ { error: error.message },
+ "database"
+ );
+ throw error;
+ }
+ }
+
+ getPendingAnalyticsClear() {
+ if (!this.db) throw new Error("Database not initialized");
+ if (!this.activeAccountId) return null;
+ return (
+ this.db
+ .prepare(
+ `SELECT cleared_through FROM analytics_clear_requests
+ WHERE account_id = ? AND synced = 0`
+ )
+ .get(this.activeAccountId) ?? null
+ );
+ }
+
+ completeAnalyticsClear(clearedThrough) {
+ if (!this.db) throw new Error("Database not initialized");
+ if (!this.activeAccountId || typeof clearedThrough !== "string") {
+ return { success: false, deleted: 0 };
+ }
+
+ const complete = this.db.transaction(() => {
+ const request = this.db
+ .prepare(
+ `UPDATE analytics_clear_requests SET synced = 1
+ WHERE account_id = ? AND cleared_through = ? AND synced = 0`
+ )
+ .run(this.activeAccountId, 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;
+ });
+ return { success: true, deleted: complete() };
+ }
+
+ countUnclaimedAnalyticsEvents() {
+ if (!this.db) throw new Error("Database not initialized");
+ return this.db
+ .prepare(
+ "SELECT COUNT(*) AS count FROM analytics_events WHERE account_id IS NULL AND deleted_at IS NULL"
+ )
+ .get().count;
+ }
+
+ // Everything turning Insights sync on would upload: this account's queued
+ // rows plus the pre-sign-in ones the prompt offers to claim.
+ //
+ // The claim count alone is not that number and badly understates it. Every
+ // dictation made while signed in is already attributed to the account, so a
+ // 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() {
+ if (!this.db) throw new Error("Database not initialized");
+ 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;
+ }
+
+ // 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() {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ if (!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);
+ return { success: true, claimed: result.changes };
+ } catch (error) {
+ debugLogger.error("Error claiming analytics events", { error: error.message }, "database");
+ throw error;
+ }
+ }
+
getTranscriptions(limit = 50, { includeDiscarded = false } = {}) {
try {
if (!this.db) {
@@ -1281,9 +1584,64 @@ class DatabaseManager {
"UPDATE transcriptions SET deleted_at = datetime('now'), sync_status = 'pending' WHERE cloud_id IS NOT NULL AND deleted_at IS NULL"
);
const hardDelete = this.db.prepare("DELETE FROM transcriptions WHERE cloud_id IS NULL");
- const clearAll = this.db.transaction(
- () => tombstone.run().changes + hardDelete.run().changes
+ // One rule decides every row: a counter the cloud never received is
+ // erased outright, and only a counter it did receive leaves a tombstone
+ // behind for the delete pusher.
+ //
+ // It matters in both directions. Tombstoning a row that was never
+ // uploaded sent its event id to the server on the next pass — for an
+ // account that never turned Insights sync on, that was the only
+ // analytics traffic it ever produced, and the server stores a row per id
+ // it is asked to delete. Hard-deleting a row that *was* uploaded stranded
+ // it in the cloud with nothing left on the device to erase it, which is
+ // what signing out before clearing used to do.
+ //
+ // Scope follows the credentials: only the active account can be erased
+ // remotely, so another account's synced rows keep their tombstones until
+ // that account signs in here again.
+ const hardDeleteLocalAnalytics = this.db.prepare(
+ `DELETE FROM analytics_events
+ WHERE account_id IS NULL OR (sync_status <> 'synced' AND deleted_at IS NULL)`
+ );
+ const tombstoneSyncedAnalytics = this.db.prepare(
+ `UPDATE analytics_events
+ SET deleted_at = ?, sync_status = 'pending'
+ WHERE sync_status = 'synced' AND deleted_at IS NULL`
);
+ const countSyncedAnalytics = this.db.prepare(
+ "SELECT COUNT(*) AS count FROM analytics_events WHERE account_id = ? AND sync_status = 'synced'"
+ );
+ const queueAnalyticsClear = this.db.prepare(
+ `INSERT INTO analytics_clear_requests (account_id, cleared_through, synced)
+ VALUES (?, ?, 0)
+ ON CONFLICT(account_id) DO UPDATE SET
+ cleared_through = MAX(analytics_clear_requests.cleared_through, excluded.cleared_through),
+ synced = 0`
+ );
+ const updateDeviceClearState = this.db.prepare(
+ `INSERT INTO analytics_device_clear_state (id, cleared_through)
+ VALUES (1, ?)
+ ON CONFLICT(id) DO UPDATE SET
+ cleared_through = MAX(analytics_device_clear_state.cleared_through, excluded.cleared_through)`
+ );
+ const clearedThrough = new Date().toISOString();
+ const clearAll = this.db.transaction(() => {
+ const cleared = tombstone.run().changes + hardDelete.run().changes;
+ updateDeviceClearState.run(clearedThrough);
+ // The account-wide cutoff is what erases rows this device no longer
+ // has — another device's uploads. It is only meaningful once this
+ // account has actually put something in the cloud; queueing it for an
+ // account that never synced would be a bare request to the analytics
+ // API from a user who never opted in.
+ const hasSyncedRows =
+ this.activeAccountId && countSyncedAnalytics.get(this.activeAccountId).count > 0;
+ tombstoneSyncedAnalytics.run(clearedThrough);
+ hardDeleteLocalAnalytics.run();
+ if (hasSyncedRows) {
+ queueAnalyticsClear.run(this.activeAccountId, clearedThrough);
+ }
+ return cleared;
+ });
return { cleared: clearAll(), success: true };
} catch (error) {
debugLogger.error("Error clearing transcriptions", { error: error.message }, "database");
@@ -1291,8 +1649,9 @@ class DatabaseManager {
}
}
- /** Purges transcriptions older than the retention window. Returns the affected ids so
- * callers can drop the matching audio files. */
+ /** Purges transcriptions and their Insights counters older than the retention window.
+ * Returns the affected transcription ids so callers can drop the matching audio files.
+ * Runs even with no expired transcriptions: counters outlive tombstoned rows. */
deleteTranscriptionsExpiredBefore(retentionDays) {
try {
if (!this.db) {
@@ -1306,7 +1665,6 @@ class DatabaseManager {
.prepare("SELECT id FROM transcriptions WHERE deleted_at IS NULL AND created_at < ?")
.all(cutoff)
.map((row) => row.id);
- if (expired.length === 0) return { ids: [] };
const tombstone = this.db.prepare(
"UPDATE transcriptions SET deleted_at = datetime('now'), sync_status = 'pending' WHERE cloud_id IS NOT NULL AND deleted_at IS NULL AND created_at < ?"
@@ -1314,11 +1672,33 @@ class DatabaseManager {
const hardDelete = this.db.prepare(
"DELETE FROM transcriptions WHERE cloud_id IS NULL AND created_at < ?"
);
+ // Counters follow the transcripts they describe, on the same cutoff and
+ // in the same transaction. Matched on created_at, never occurred_at:
+ // created_at uses the same SQLite timestamp format as the cutoff.
+ //
+ // Same rule as clearTranscriptions: only a row the cloud actually holds
+ // leaves a tombstone. Attribution alone is not enough — every dictation
+ // made while signed in carries an account_id whether or not Insights
+ // sync was ever turned on, so tombstoning on that basis shipped the event
+ // ids of a user who never opted in.
+ const tombstoneSyncedAnalytics = this.db.prepare(
+ `UPDATE analytics_events
+ SET deleted_at = datetime('now'), sync_status = 'pending'
+ WHERE sync_status = 'synced' AND deleted_at IS NULL AND created_at < ?`
+ );
+ const purgeUnsyncedAnalytics = this.db.prepare(
+ `DELETE FROM analytics_events
+ WHERE (account_id IS NULL OR sync_status <> 'synced')
+ AND deleted_at IS NULL AND created_at < ?`
+ );
+ let analyticsPurged = 0;
this.db.transaction(() => {
tombstone.run(cutoff);
hardDelete.run(cutoff);
+ analyticsPurged =
+ tombstoneSyncedAnalytics.run(cutoff).changes + purgeUnsyncedAnalytics.run(cutoff).changes;
})();
- return { ids: expired };
+ return { ids: expired, analyticsPurged };
} catch (error) {
debugLogger.error(
"Error purging expired transcriptions",
@@ -2587,6 +2967,8 @@ class DatabaseManager {
.prepare(`DELETE FROM folders WHERE id IN (${folderPlaceholders})`)
.run(...deletedFolderIds);
}
+ this.db.prepare("DELETE FROM analytics_events WHERE account_id = ?").run(accountId);
+ this.db.prepare("DELETE FROM analytics_clear_requests WHERE account_id = ?").run(accountId);
this.db.prepare("DELETE FROM space_accounts WHERE account_id = ?").run(accountId);
};
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 3a358cb59..445eee763 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -190,6 +190,7 @@ const {
abortableSleep,
createTeardownGate,
createUploadSlots,
+ withoutChunkAnalytics,
} = require("./cloudChunkPolicy");
// Chunk retries need their own connection pool: recovering a wedged chunk pool
@@ -430,7 +431,7 @@ async function chunkedCloudTranscribe({
fs.readFileSync(chunkPaths[index]),
path.basename(chunkPaths[index]),
"audio/mpeg",
- multipartFields
+ withoutChunkAnalytics(multipartFields)
);
const data = await postMultipart(url, body, boundary, policyHeaders, {
signal: AbortSignal.any([jobSignal, timeoutSignal]),
@@ -997,12 +998,13 @@ class IPCHandlers {
const { audioRetentionDays, transcriptRetentionDays } = this._retentionSettings;
try {
if (transcriptRetentionDays > 0) {
- const { ids } =
+ const { ids, analyticsPurged } =
this.databaseManager.deleteTranscriptionsExpiredBefore(transcriptRetentionDays);
for (const id of ids) {
this.audioStorageManager.deleteAudio(id);
broadcastToWindows("transcription-deleted", { id });
}
+ if (analyticsPurged > 0) broadcastToWindows("analytics-changed");
}
if (audioRetentionDays > 0) {
this.audioStorageManager.cleanupExpiredAudio(audioRetentionDays, this.databaseManager);
@@ -1397,6 +1399,66 @@ class IPCHandlers {
return this.databaseManager.getTranscriptions(limit, options);
});
+ ipcMain.handle("analytics-record-event", async (_event, input) => {
+ const result = this.databaseManager.recordAnalyticsEvent(input);
+ // Dictation and the control panel are separate renderers, so the
+ // Insights view can only learn about a new event through the main process.
+ if (result?.success && !result.ignored) {
+ setImmediate(() => {
+ broadcastToWindows("analytics-changed");
+ });
+ }
+ return result;
+ });
+
+ ipcMain.handle("analytics-get-summary", async () => {
+ return this.databaseManager.getAnalyticsSummary();
+ });
+
+ ipcMain.handle("analytics-get-pending", async (_event, limit) => {
+ return this.databaseManager.getPendingAnalyticsEvents(limit);
+ });
+
+ ipcMain.handle("analytics-mark-synced", async (_event, eventIds) => {
+ return this.databaseManager.markAnalyticsEventsSynced(eventIds);
+ });
+
+ ipcMain.handle("analytics-get-pending-deletes", async (_event, limit) => {
+ return this.databaseManager.getPendingAnalyticsDeletes(limit);
+ });
+
+ ipcMain.handle("analytics-hard-delete", async (_event, eventIds) => {
+ return this.databaseManager.hardDeleteAnalyticsEvents(eventIds);
+ });
+
+ ipcMain.handle("analytics-get-pending-clear", async () => {
+ return this.databaseManager.getPendingAnalyticsClear();
+ });
+
+ ipcMain.handle("analytics-complete-clear", async (_event, clearedThrough) => {
+ return this.databaseManager.completeAnalyticsClear(clearedThrough);
+ });
+
+ ipcMain.handle("analytics-count-unclaimed", async () => {
+ return this.databaseManager.countUnclaimedAnalyticsEvents();
+ });
+
+ ipcMain.handle("analytics-count-awaiting-upload", async () => {
+ return this.databaseManager.countAnalyticsEventsAwaitingUpload();
+ });
+
+ 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");
+ });
+ }
+ return result;
+ });
+
ipcMain.handle("db-clear-transcriptions", async (event) => {
this.audioStorageManager.deleteAllAudio();
const result = this.databaseManager.clearTranscriptions();
@@ -1405,6 +1467,7 @@ class IPCHandlers {
broadcastToWindows("transcriptions-cleared", {
cleared: result.cleared,
});
+ broadcastToWindows("analytics-changed");
});
}
return result;
@@ -5751,6 +5814,8 @@ class IPCHandlers {
clientVersion: app.getVersion(),
sessionId: this.sessionId,
clientTranscriptionId,
+ localDate: opts.localDate,
+ analyticsOccurredAt: opts.analyticsOccurredAt,
};
debugLogger.debug("Cloud transcribe request", { audioSize: audioData.length }, "cloud-api");
@@ -8927,10 +8992,10 @@ class IPCHandlers {
const response = await proxyFetch(`${apiUrl}/api/streaming-usage`, {
method: "POST",
- headers: {
+ headers: withPolicyHeaders({
"Content-Type": "application/json",
...authHeader,
- },
+ }),
body: JSON.stringify({
text,
audioDurationSeconds,
@@ -8946,6 +9011,11 @@ class IPCHandlers {
audioFormat: opts.audioFormat,
clientTotalMs: opts.clientTotalMs,
sendLogs: opts.sendLogs,
+ clientTranscriptionId: opts.clientTranscriptionId,
+ localDate: opts.localDate,
+ analyticsOccurredAt: opts.analyticsOccurredAt,
+ analyticsWordCount: opts.analyticsWordCount,
+ analyticsCounterVersion: opts.analyticsCounterVersion,
}),
});
diff --git a/src/hooks/useAudioRecording.js b/src/hooks/useAudioRecording.js
index 359b4178a..7db3c8af4 100644
--- a/src/hooks/useAudioRecording.js
+++ b/src/hooks/useAudioRecording.js
@@ -538,6 +538,13 @@ export const useAudioRecording = (toast, options = {}) => {
const persistencePromise = audioManagerRef.current
.saveTranscription(result.text, result.rawText ?? result.text, {
clientTranscriptionId: result.clientTranscriptionId,
+ // Spread rather than set: a result with no analytics timestamp
+ // must not gain the key as undefined, matching how audioManager
+ // carries this field and keeping the options object exactly what
+ // callers without Insights data expect.
+ ...(result.analyticsOccurredAt
+ ? { analyticsOccurredAt: result.analyticsOccurredAt }
+ : {}),
})
.then(
(persisted) => {
diff --git a/src/hooks/useAuth.ts b/src/hooks/useAuth.ts
index 938f2fcea..a6d7305df 100644
--- a/src/hooks/useAuth.ts
+++ b/src/hooks/useAuth.ts
@@ -180,6 +180,7 @@ export function useAuth() {
if (accountScopeRequiresPurge(resolvedUserId)) {
markAccountScopePurgeRequired();
+ useSettingsStore.getState().setInsightsSyncEnabled(false);
}
if (accountScopeRequiresReconciliation(resolvedUserId)) {
// This legacy marker drives every already-running SyncService window;
diff --git a/src/hooks/useInsightsSyncOptIn.tsx b/src/hooks/useInsightsSyncOptIn.tsx
new file mode 100644
index 000000000..e3b8899c5
--- /dev/null
+++ b/src/hooks/useInsightsSyncOptIn.tsx
@@ -0,0 +1,111 @@
+import { useCallback, useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { ConfirmDialog } from "../components/ui/dialog";
+import { canChangeCloudBackupPreference, isCloudBackupAllowed } from "../stores/policyRules";
+import { usePolicyStore } from "../stores/policyStore";
+import { syncService } from "../services/SyncService.js";
+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
+ * 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.
+ *
+ * These counters are user data leaving the device, so they ride on the same
+ * managed-workspace permission as cloud backup: a policy that forbids backup
+ * forbids the sync, and an already-on toggle stays switchable off.
+ *
+ * Declining the prompt declines the whole opt-in, exactly like dismissing it:
+ * turning sync on while leaving those rows behind would swap the dashboard to
+ * the account summary they are not in, dropping totals the user just chose to
+ * keep. Enabling therefore always means "these counters too". With sync already
+ * on that swap has happened, so declining there just leaves the rows where the
+ * 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.
+ */
+export function useInsightsSyncOptIn() {
+ const { t } = useTranslation();
+ const { insightsSyncEnabled, setInsightsSyncEnabled } = useSettings();
+ const [unclaimedCount, setUnclaimedCount] = useState(0);
+ const [awaitingUploadCount, setAwaitingUploadCount] = useState(0);
+ // 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 syncAllowedByPolicy = usePolicyStore(isCloudBackupAllowed);
+ const canToggleSync = canChangeCloudBackupPreference(syncAllowedByPolicy, insightsSyncEnabled);
+
+ // 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) => {
+ if (claimAnonymous) {
+ await window.electronAPI.claimAnonymousAnalyticsEvents().catch((error) => {
+ console.error("Claiming earlier Insights events failed:", error);
+ });
+ }
+ setInsightsSyncEnabled(true);
+ syncService.requestSyncAll("manual");
+ },
+ [setInsightsSyncEnabled]
+ );
+
+ const refreshCounts = useCallback(async () => {
+ const [unclaimed, awaitingUpload] = await Promise.all([
+ window.electronAPI.countUnclaimedAnalyticsEvents().catch(() => 0),
+ window.electronAPI.countAnalyticsEventsAwaitingUpload().catch(() => 0),
+ ]);
+ setUnclaimedCount(unclaimed);
+ setAwaitingUploadCount(awaitingUpload);
+ return { unclaimed, awaitingUpload };
+ }, []);
+
+ // 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());
+ }, [refreshCounts]);
+
+ const enableInsightsSync = useCallback(() => {
+ if (!syncAllowedByPolicy) return;
+ void (async () => {
+ const { unclaimed, awaitingUpload } = await refreshCounts();
+ // 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 nothing to disclose.
+ if (awaitingUpload > 0) setPromptKind("enable");
+ else await activate(false);
+ })();
+ }, [activate, insightsSyncEnabled, refreshCounts, syncAllowedByPolicy]);
+
+ const claiming = promptKind === "claim";
+ const optInDialog = (
+ <ConfirmDialog
+ open={promptKind !== null}
+ onOpenChange={(open) => {
+ if (!open) setPromptKind(null);
+ }}
+ title={t(claiming ? "insights.claimTitle" : "insights.enableTitle")}
+ description={t(claiming ? "insights.claimDescription" : "insights.enableDescription", {
+ count: claiming ? unclaimedCount : awaitingUploadCount,
+ })}
+ confirmText={t(claiming ? "insights.claimInclude" : "insights.enableConfirm")}
+ cancelText={t("insights.claimSkip")}
+ onConfirm={() => void activate(true)}
+ />
+ );
+
+ return { canToggleSync, enableInsightsSync, optInDialog, syncAllowedByPolicy, unclaimedCount };
+}
diff --git a/src/hooks/useSettings.ts b/src/hooks/useSettings.ts
index 2850ae5ca..9fe74d363 100644
--- a/src/hooks/useSettings.ts
+++ b/src/hooks/useSettings.ts
@@ -94,6 +94,7 @@ export interface ApiKeySettings {
export interface PrivacySettings {
cloudBackupEnabled: boolean;
+ insightsSyncEnabled: boolean;
telemetryEnabled: boolean;
audioRetentionDays: number;
transcriptRetentionDays: number;
@@ -411,6 +412,8 @@ function useSettingsInternal() {
setWhisperVadSamplesOverlap: store.setWhisperVadSamplesOverlap,
cloudBackupEnabled: store.cloudBackupEnabled,
setCloudBackupEnabled: store.setCloudBackupEnabled,
+ insightsSyncEnabled: store.insightsSyncEnabled,
+ setInsightsSyncEnabled: store.setInsightsSyncEnabled,
telemetryEnabled: store.telemetryEnabled,
setTelemetryEnabled: store.setTelemetryEnabled,
audioRetentionDays: store.audioRetentionDays,
diff --git a/src/lib/authAccountScope.ts b/src/lib/authAccountScope.ts
index f14600a68..9330933b4 100644
--- a/src/lib/authAccountScope.ts
+++ b/src/lib/authAccountScope.ts
@@ -172,6 +172,10 @@ async function applyReconcile(
// Persist before cleanup starts: capability flags may disappear even when
// a database operation fails, and must not reopen the gate.
markAccountScopePurgeRequired();
+ // Insights consent belongs to the account that granted it. Clear the
+ // device flag before the identity boundary opens so a replacement account
+ // can never inherit the previous user's upload permission.
+ storage()?.setItem("insightsSyncEnabled", "false");
}
pendingAction = action;
notify();
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index f3f73f763..15e65d498 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -661,7 +661,8 @@
"rawTranscript": "Rohtranskript",
"clearAll": "Alle löschen",
"clearAllTitle": "Alle Transkriptionen löschen",
- "clearAllDescription": "Alle Transkriptionen und Audiodateien werden dauerhaft entfernt.",
+ "clearAllDescription": "Alle Transkriptionen, Audiodateien und Insights-Zähler werden dauerhaft von diesem Gerät und aus Ihrem Konto entfernt.",
+ "clearAllDescriptionDevice": "Alle Transkriptionen, Audiodateien und Insights-Zähler werden dauerhaft von diesem Gerät entfernt. Bereits mit einem Konto synchronisierte Zähler bleiben davon unberührt.",
"clearAllSuccess": "Verlauf gelöscht",
"clearAllErrorTitle": "Verlauf konnte nicht gelöscht werden",
"clearAllErrorDescription": "Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut.",
@@ -2385,6 +2386,10 @@
"cloudNotesMigrationDone": "Alle Notizen gesichert",
"description": "Steuern Sie, welche Daten Ihr Gerät verlassen. Standardmäßig ist alles deaktiviert.",
"title": "Datenschutz",
+ "insightsSync": "Persönliche Statistiken synchronisieren",
+ "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.",
"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",
@@ -2401,7 +2406,7 @@
"dataRetention": "Datenaufbewahrung",
"dataRetentionDescription": "Transkriptionen und Audio lokal im Verlauf speichern. Wenn deaktiviert, werden Transkriptionen eingefügt, aber nicht gespeichert.",
"transcriptRetention": "Transkript-Aufbewahrung",
- "transcriptRetentionDescription": "Gespeicherte Transkriptionen und deren Audio nach diesem Zeitraum automatisch löschen.",
+ "transcriptRetentionDescription": "Gespeicherte Transkriptionen, deren Audio und deren Insights-Zähler nach diesem Zeitraum automatisch löschen.",
"transcriptRetentionForever": "Unbegrenzt",
"hoursAgo": "vor {{count}} Std.",
"justNow": "gerade eben",
@@ -2704,7 +2709,47 @@
}
}
},
+ "insights": {
+ "title": "Statistiken",
+ "description": "Ein privater Blick auf Ihre Diktiergewohnheiten und Ihren Fortschritt.",
+ "wordsSpoken": "Gesprochene Wörter",
+ "currentStreak": "Aktuelle Serie",
+ "wordsPerMinute": "Wörter pro Minute",
+ "dictations": "Diktate",
+ "allTime": "Gesamt",
+ "days_one": "{{count}} Tag",
+ "days_other": "{{count}} Tage",
+ "longestStreak_one": "Längste: {{count}} Tag",
+ "longestStreak_other": "Längste: {{count}} Tage",
+ "wpmCoverage": "Basierend auf {{count}} % der gemessenen Wörter",
+ "activity": "Sprechaktivität",
+ "activityDescription": "Gesprochene Wörter der letzten 6 Monate",
+ "activityLabel": "Heatmap der Sprechaktivität über 6 Monate",
+ "activityLess": "Weniger",
+ "activityMore": "Mehr",
+ "dayTooltip_one": "{{date}}: {{count}} Wort",
+ "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",
+ "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",
+ "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.",
+ "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.",
+ "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."
+ },
"sidebar": {
+ "insights": "Statistiken",
"home": "Startseite",
"notes": "Notizen",
"upload": "Hochladen",
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index 4be582f55..c5eb62d33 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -661,7 +661,8 @@
"rawTranscript": "Raw Transcript",
"clearAll": "Clear all",
"clearAllTitle": "Clear All Transcriptions",
- "clearAllDescription": "All transcriptions and audio files will be permanently removed.",
+ "clearAllDescription": "All transcriptions, audio files, and Insights counters will be permanently removed from this device and your account.",
+ "clearAllDescriptionDevice": "All transcriptions, audio files, and Insights counters will be permanently removed from this device. Counters already synced to an account are not affected.",
"clearAllSuccess": "History cleared",
"clearAllErrorTitle": "Couldn't clear history",
"clearAllErrorDescription": "Something went wrong. Please try again.",
@@ -2387,6 +2388,10 @@
"title": "Privacy",
"usageAnalytics": "Usage analytics",
"usageAnalyticsDescription": "Help us improve OpenWhispr by sharing anonymous performance metrics. We never send transcription content — only timing and error data.",
+ "insightsSync": "Sync personal Insights",
+ "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.",
"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",
@@ -2401,7 +2406,7 @@
"dataRetention": "Data Retention",
"dataRetentionDescription": "Store transcriptions and audio locally in your history. When disabled, transcriptions are pasted but not saved.",
"transcriptRetention": "Transcript Retention",
- "transcriptRetentionDescription": "Automatically delete saved transcriptions and their audio after this period.",
+ "transcriptRetentionDescription": "Automatically delete saved transcriptions, their audio, and their Insights counters after this period.",
"transcriptRetentionForever": "Forever",
"hoursAgo": "{{count}}h ago",
"justNow": "just now",
@@ -2706,6 +2711,7 @@
},
"sidebar": {
"home": "Home",
+ "insights": "Insights",
"notes": "Notes",
"upload": "Upload",
"dictionary": "Dictionary",
@@ -2728,6 +2734,45 @@
"collapse": "Collapse sidebar",
"expand": "Expand sidebar"
},
+ "insights": {
+ "title": "Insights",
+ "description": "A private view of your dictation habits and momentum.",
+ "wordsSpoken": "Words spoken",
+ "currentStreak": "Current streak",
+ "wordsPerMinute": "Words per minute",
+ "dictations": "Dictations",
+ "allTime": "All time",
+ "days_one": "{{count}} day",
+ "days_other": "{{count}} days",
+ "longestStreak_one": "Longest: {{count}} day",
+ "longestStreak_other": "Longest: {{count}} days",
+ "wpmCoverage": "Based on {{count}}% of measured words",
+ "activity": "Speaking activity",
+ "activityDescription": "Words spoken over the last 6 months",
+ "activityLabel": "6-month speaking activity heatmap",
+ "activityLess": "Less",
+ "activityMore": "More",
+ "dayTooltip_one": "{{date}}: {{count}} word",
+ "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",
+ "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",
+ "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.",
+ "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.",
+ "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."
+ },
"workspaces": {
"switcher": {
"workspaces": "Workspaces",
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index c6ce109b7..3cdca944c 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -656,7 +656,8 @@
"failedOffline": "Sin conexión",
"clearAll": "Borrar todo",
"clearAllTitle": "Borrar todas las transcripciones",
- "clearAllDescription": "Todas las transcripciones y archivos de audio se eliminarán permanentemente.",
+ "clearAllDescription": "Todas las transcripciones, los archivos de audio y los recuentos de Insights se eliminarán permanentemente de este dispositivo y de tu cuenta.",
+ "clearAllDescriptionDevice": "Todas las transcripciones, los archivos de audio y los recuentos de Insights se eliminarán permanentemente de este dispositivo. Los recuentos ya sincronizados con una cuenta no se verán afectados.",
"clearAllSuccess": "Historial borrado",
"clearAllErrorTitle": "No se pudo borrar el historial",
"clearAllErrorDescription": "Algo salió mal. Inténtalo de nuevo.",
@@ -2144,12 +2145,16 @@
"cloudNotesMigrationDone": "Todas las notas respaldadas",
"description": "Controla qué datos salen de tu dispositivo. Todo está desactivado por defecto.",
"title": "Privacidad",
+ "insightsSync": "Sincronizar Estadísticas personales",
+ "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.",
"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",
"dataRetentionDescription": "Almacenar transcripciones y audio localmente en tu historial. Cuando está desactivado, las transcripciones se pegan pero no se guardan.",
"transcriptRetention": "Retención de transcripciones",
- "transcriptRetentionDescription": "Eliminar automáticamente las transcripciones guardadas y su audio después de este período.",
+ "transcriptRetentionDescription": "Eliminar automáticamente las transcripciones guardadas, su audio y sus contadores de Insights después de este período.",
"transcriptRetentionForever": "Para siempre",
"hoursAgo": "hace {{count}}h",
"justNow": "ahora mismo",
@@ -3250,7 +3255,47 @@
"importList": "Importar una lista",
"agentDefault": "Añadido por defecto"
},
+ "insights": {
+ "title": "Estadísticas",
+ "description": "Una vista privada de tus hábitos de dictado y tu constancia.",
+ "wordsSpoken": "Palabras dictadas",
+ "currentStreak": "Racha actual",
+ "wordsPerMinute": "Palabras por minuto",
+ "dictations": "Dictados",
+ "allTime": "Histórico",
+ "days_one": "{{count}} día",
+ "days_other": "{{count}} días",
+ "longestStreak_one": "Máxima: {{count}} día",
+ "longestStreak_other": "Máxima: {{count}} días",
+ "wpmCoverage": "Basado en el {{count}} % de las palabras medidas",
+ "activity": "Actividad de dictado",
+ "activityDescription": "Palabras dictadas en los últimos 6 meses",
+ "activityLabel": "Mapa de calor de actividad de dictado de 6 meses",
+ "activityLess": "Menos",
+ "activityMore": "Más",
+ "dayTooltip_one": "{{date}}: {{count}} palabra",
+ "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",
+ "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",
+ "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.",
+ "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.",
+ "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."
+ },
"sidebar": {
+ "insights": "Estadísticas",
"home": "Inicio",
"notes": "Notas",
"upload": "Subir",
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index 141c6ba59..efcaf51bb 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -661,7 +661,8 @@
"rawTranscript": "Transcription brute",
"clearAll": "Tout effacer",
"clearAllTitle": "Effacer toutes les transcriptions",
- "clearAllDescription": "Toutes les transcriptions et fichiers audio seront définitivement supprimés.",
+ "clearAllDescription": "Toutes les transcriptions, tous les fichiers audio et les compteurs Insights seront définitivement supprimés de cet appareil et de votre compte.",
+ "clearAllDescriptionDevice": "Toutes les transcriptions, tous les fichiers audio et les compteurs Insights seront définitivement supprimés de cet appareil. Les compteurs déjà synchronisés avec un compte ne seront pas affectés.",
"clearAllSuccess": "Historique effacé",
"clearAllErrorTitle": "Impossible d'effacer l'historique",
"clearAllErrorDescription": "Une erreur est survenue. Veuillez réessayer.",
@@ -2385,6 +2386,10 @@
"cloudNotesMigrationDone": "Toutes les notes sauvegardées",
"description": "Contrôlez quelles données quittent votre appareil. Tout est désactivé par défaut.",
"title": "Confidentialité",
+ "insightsSync": "Synchroniser les Statistiques personnelles",
+ "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.",
"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",
@@ -2401,7 +2406,7 @@
"dataRetention": "Conservation des données",
"dataRetentionDescription": "Stocker les transcriptions et l'audio localement dans votre historique. Lorsque désactivé, les transcriptions sont collées mais pas enregistrées.",
"transcriptRetention": "Conservation des transcriptions",
- "transcriptRetentionDescription": "Supprimer automatiquement les transcriptions enregistrées et leur audio après cette période.",
+ "transcriptRetentionDescription": "Supprimer automatiquement les transcriptions enregistrées, leur audio et leurs compteurs Insights après cette période.",
"transcriptRetentionForever": "Toujours",
"hoursAgo": "il y a {{count}}h",
"justNow": "à l'instant",
@@ -2704,7 +2709,47 @@
}
}
},
+ "insights": {
+ "title": "Statistiques",
+ "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",
+ "wordsPerMinute": "Mots par minute",
+ "dictations": "Dictées",
+ "allTime": "Depuis le début",
+ "days_one": "{{count}} jour",
+ "days_other": "{{count}} jours",
+ "longestStreak_one": "Record : {{count}} jour",
+ "longestStreak_other": "Record : {{count}} jours",
+ "wpmCoverage": "Basé sur {{count}} % des mots mesurés",
+ "activity": "Activité de dictée",
+ "activityDescription": "Mots dictés au cours des 6 derniers mois",
+ "activityLabel": "Carte de chaleur de l'activité de dictée sur 6 mois",
+ "activityLess": "Moins",
+ "activityMore": "Plus",
+ "dayTooltip_one": "{{date}} : {{count}} mot",
+ "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",
+ "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",
+ "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.",
+ "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.",
+ "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."
+ },
"sidebar": {
+ "insights": "Statistiques",
"home": "Accueil",
"notes": "Notes",
"upload": "Importer",
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index e405834c9..3940efef1 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -647,7 +647,8 @@
"failedOffline": "Offline",
"clearAll": "Cancella tutto",
"clearAllTitle": "Cancella tutte le trascrizioni",
- "clearAllDescription": "Tutte le trascrizioni e i file audio verranno rimossi definitivamente.",
+ "clearAllDescription": "Tutte le trascrizioni, i file audio e i conteggi di Insights verranno rimossi definitivamente da questo dispositivo e dal tuo account.",
+ "clearAllDescriptionDevice": "Tutte le trascrizioni, i file audio e i conteggi di Insights verranno rimossi definitivamente da questo dispositivo. I conteggi già sincronizzati con un account non saranno interessati.",
"clearAllSuccess": "Cronologia cancellata",
"clearAllErrorTitle": "Impossibile cancellare la cronologia",
"clearAllErrorDescription": "Qualcosa è andato storto. Riprova.",
@@ -2096,12 +2097,16 @@
"cloudNotesMigrationDone": "Tutte le note salvate nel cloud",
"description": "Controlla quali dati escono dal tuo dispositivo. Tutto è disattivato per impostazione predefinita.",
"title": "Privacy",
+ "insightsSync": "Sincronizza le Statistiche personali",
+ "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.",
"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",
"dataRetentionDescription": "Salva trascrizioni e audio localmente nella cronologia. Se disattivato, le trascrizioni vengono incollate ma non salvate.",
"transcriptRetention": "Conservazione delle trascrizioni",
- "transcriptRetentionDescription": "Elimina automaticamente le trascrizioni salvate e il relativo audio dopo questo periodo.",
+ "transcriptRetentionDescription": "Elimina automaticamente le trascrizioni salvate, il relativo audio e i relativi contatori di Insights dopo questo periodo.",
"transcriptRetentionForever": "Per sempre",
"hoursAgo": "{{count}}h fa",
"justNow": "adesso",
@@ -3202,7 +3207,47 @@
"importList": "Importa un elenco",
"agentDefault": "Aggiunto di default"
},
+ "insights": {
+ "title": "Statistiche",
+ "description": "Una visione privata delle tue abitudini di dettatura e della tua costanza.",
+ "wordsSpoken": "Parole dettate",
+ "currentStreak": "Serie attuale",
+ "wordsPerMinute": "Parole al minuto",
+ "dictations": "Dettature",
+ "allTime": "Da sempre",
+ "days_one": "{{count}} giorno",
+ "days_other": "{{count}} giorni",
+ "longestStreak_one": "Record: {{count}} giorno",
+ "longestStreak_other": "Record: {{count}} giorni",
+ "wpmCoverage": "Basato sul {{count}} % delle parole misurate",
+ "activity": "Attività di dettatura",
+ "activityDescription": "Parole dettate negli ultimi 6 mesi",
+ "activityLabel": "Mappa di calore dell'attività di dettatura su 6 mesi",
+ "activityLess": "Meno",
+ "activityMore": "Più",
+ "dayTooltip_one": "{{date}}: {{count}} parola",
+ "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",
+ "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",
+ "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.",
+ "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.",
+ "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."
+ },
"sidebar": {
+ "insights": "Statistiche",
"home": "Home",
"notes": "Note",
"upload": "Carica",
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index c420e05c6..8108412eb 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -647,7 +647,8 @@
"failedOffline": "オフラインです",
"clearAll": "すべて削除",
"clearAllTitle": "すべての文字起こしを削除",
- "clearAllDescription": "すべての文字起こしと音声ファイルが完全に削除されます。",
+ "clearAllDescription": "すべての文字起こし、音声ファイル、Insights のカウントが、このデバイスとアカウントから完全に削除されます。",
+ "clearAllDescriptionDevice": "すべての文字起こし、音声ファイル、Insights のカウントが、このデバイスから完全に削除されます。アカウントに同期済みのカウントには影響しません。",
"clearAllSuccess": "履歴を削除しました",
"clearAllErrorTitle": "履歴を削除できませんでした",
"clearAllErrorDescription": "問題が発生しました。もう一度お試しください。",
@@ -2096,12 +2097,16 @@
"cloudNotesMigrationDone": "すべてのノートがバックアップされました",
"description": "デバイスからのデータ送信を管理します。初期設定ではすべてオフです。",
"title": "プライバシー",
+ "insightsSync": "個人の統計を同期",
+ "insightsSyncDescription": "単語数、日付と各ディクテーションの正確な時刻、長さ、モデルの種類をデバイス間で同期します。文字起こしの内容は送信されません。サインイン中に履歴を消去すると、これらのカウントもこのデバイスとアカウントから削除されます。",
+ "insightsSyncRequiresAccount": "サインインすると、内容を含まない統計データをデバイス間で同期できます。",
+ "insightsSyncRequiresHistory": "データ保持を有効にすると統計が記録され、デバイス間で同期できるようになります。",
"usageAnalytics": "使用状況の分析",
"usageAnalyticsDescription": "匿名のパフォーマンスデータを共有して OpenWhispr の改善にご協力ください。文字起こしの内容は送信されません。タイミングとエラーデータのみです。",
"dataRetention": "データ保持",
"dataRetentionDescription": "文字起こしと音声を履歴にローカル保存します。無効にすると、文字起こしは貼り付けられますが保存されません。",
"transcriptRetention": "文字起こしの保持",
- "transcriptRetentionDescription": "保存された文字起こしとその音声を、この期間の経過後に自動的に削除します。",
+ "transcriptRetentionDescription": "保存された文字起こし、その音声、およびその Insights カウンターを、この期間の経過後に自動的に削除します。",
"transcriptRetentionForever": "無期限",
"hoursAgo": "{{count}}時間前",
"justNow": "たった今",
@@ -3202,7 +3207,47 @@
"playSignal": "シグナルを再生"
}
},
+ "insights": {
+ "title": "統計",
+ "description": "ディクテーションの習慣と継続状況をプライベートに確認できます。",
+ "wordsSpoken": "話した単語数",
+ "currentStreak": "現在の連続日数",
+ "wordsPerMinute": "1分あたりの単語数",
+ "dictations": "ディクテーション数",
+ "allTime": "全期間",
+ "days_one": "{{count}} 日",
+ "days_other": "{{count}} 日",
+ "longestStreak_one": "最長: {{count}} 日",
+ "longestStreak_other": "最長: {{count}} 日",
+ "wpmCoverage": "計測できた単語の {{count}}% に基づく",
+ "activity": "発話アクティビティ",
+ "activityDescription": "過去6か月間に話した単語数",
+ "activityLabel": "6か月間の発話アクティビティのヒートマップ",
+ "activityLess": "少ない",
+ "activityMore": "多い",
+ "dayTooltip_one": "{{date}}: {{count}} 語",
+ "dayTooltip_other": "{{date}}: {{count}} 語",
+ "dataRetentionDisabled": "データ保持が無効なため、新しいディクテーションは統計に集計されません。このデバイスでもアカウントでも加算されません。すでに同期済みのカウントはアカウントに残ります。",
+ "onDevice": "このデバイス上",
+ "synced": "デバイス間で同期済み",
+ "syncFallback": "デバイスのデータを表示中 — 同期は利用できません",
+ "syncPrompt": "内容を含まないカウンターを同期して、ローカルとクラウドのアクティビティをデバイス間でまとめます。",
+ "enableSync": "同期を有効にする",
+ "claimTitle": "以前のディクテーションを含めますか?",
+ "claimDescription_one": "サインイン前にこのデバイスで記録されたディクテーションが {{count}} 件あります。含めると、送信されるのは単語数、日付と記録された正確な時刻、長さ、モデルの種類だけで、文字起こしの内容は送信されません。",
+ "claimDescription_other": "サインイン前にこのデバイスで記録されたディクテーションが {{count}} 件あります。含めると、送信されるのは単語数、日付と記録された正確な時刻、長さ、モデルの種類だけで、文字起こしの内容は送信されません。",
+ "claimInclude": "含める",
+ "claimSkip": "今はしない",
+ "enableTitle": "Insights の同期をオンにしますか?",
+ "enableConfirm": "同期をオンにする",
+ "enableDescription_one": "このデバイスで記録済みのディクテーション {{count}} 件がアカウントにアップロードされます。Insights の同期で送信されるのは単語数、日付と記録された正確な時刻、長さ、モデルの種類だけで、文字起こしの内容は送信されません。",
+ "enableDescription_other": "このデバイスで記録済みのディクテーション {{count}} 件がアカウントにアップロードされます。Insights の同期で送信されるのは単語数、日付と記録された正確な時刻、長さ、モデルの種類だけで、文字起こしの内容は送信されません。",
+ "emptyTitle": "まだディクテーションがありません",
+ "emptyBody": "ディクテーションを始めると、単語数・連続記録・日々のアクティビティがここに表示されます。",
+ "loadError": "このデバイスから Insights を読み取れませんでした。"
+ },
"sidebar": {
+ "insights": "統計",
"home": "ホーム",
"notes": "ノート",
"upload": "アップロード",
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index b14654509..319df3221 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -626,7 +626,8 @@
"failedOffline": "Sem conexão",
"clearAll": "Limpar tudo",
"clearAllTitle": "Limpar todas as transcrições",
- "clearAllDescription": "Todas as transcrições e arquivos de áudio serão removidos permanentemente.",
+ "clearAllDescription": "Todas as transcrições, os arquivos de áudio e as contagens do Insights serão removidos permanentemente deste dispositivo e da sua conta.",
+ "clearAllDescriptionDevice": "Todas as transcrições, os arquivos de áudio e as contagens do Insights serão removidos permanentemente deste dispositivo. As contagens já sincronizadas com uma conta não serão afetadas.",
"clearAllSuccess": "Histórico limpo",
"clearAllErrorTitle": "Não foi possível limpar o histórico",
"clearAllErrorDescription": "Algo deu errado. Tente novamente.",
@@ -2075,12 +2076,16 @@
"cloudNotesMigrationDone": "Todas as notas salvas na nuvem",
"description": "Controle quais dados saem do seu dispositivo. Tudo está desativado por padrão.",
"title": "Privacidade",
+ "insightsSync": "Sincronizar Estatísticas pessoais",
+ "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.",
"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",
"dataRetentionDescription": "Armazenar transcrições e áudio localmente no seu histórico. Quando desativado, as transcrições são coladas mas não salvas.",
"transcriptRetention": "Retenção de transcrições",
- "transcriptRetentionDescription": "Excluir automaticamente as transcrições salvas e o áudio delas após este período.",
+ "transcriptRetentionDescription": "Excluir automaticamente as transcrições salvas, o áudio delas e os contadores do Insights delas após este período.",
"transcriptRetentionForever": "Para sempre",
"hoursAgo": "há {{count}}h",
"justNow": "agora mesmo",
@@ -3202,7 +3207,47 @@
"importList": "Importar uma lista",
"agentDefault": "Adicionado por padrão"
},
+ "insights": {
+ "title": "Estatísticas",
+ "description": "Uma visão privada dos seus hábitos de ditado e da sua constância.",
+ "wordsSpoken": "Palavras ditadas",
+ "currentStreak": "Sequência atual",
+ "wordsPerMinute": "Palavras por minuto",
+ "dictations": "Ditados",
+ "allTime": "Desde o início",
+ "days_one": "{{count}} dia",
+ "days_other": "{{count}} dias",
+ "longestStreak_one": "Recorde: {{count}} dia",
+ "longestStreak_other": "Recorde: {{count}} dias",
+ "wpmCoverage": "Com base em {{count}}% das palavras medidas",
+ "activity": "Atividade de ditado",
+ "activityDescription": "Palavras ditadas nos últimos 6 meses",
+ "activityLabel": "Mapa de calor da atividade de ditado de 6 meses",
+ "activityLess": "Menos",
+ "activityMore": "Mais",
+ "dayTooltip_one": "{{date}}: {{count}} palavra",
+ "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",
+ "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",
+ "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.",
+ "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.",
+ "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."
+ },
"sidebar": {
+ "insights": "Estatísticas",
"home": "Início",
"notes": "Notas",
"upload": "Enviar",
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index ca94eb036..0b6cb4fa6 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -647,7 +647,8 @@
"failedOffline": "Нет подключения",
"clearAll": "Очистить все",
"clearAllTitle": "Очистить все транскрипции",
- "clearAllDescription": "Все транскрипции и аудиофайлы будут безвозвратно удалены.",
+ "clearAllDescription": "Все транскрипции, аудиофайлы и счётчики Insights будут безвозвратно удалены с этого устройства и из вашего аккаунта.",
+ "clearAllDescriptionDevice": "Все транскрипции, аудиофайлы и счётчики Insights будут безвозвратно удалены с этого устройства. Уже синхронизированные с аккаунтом счётчики не будут затронуты.",
"clearAllSuccess": "История очищена",
"clearAllErrorTitle": "Не удалось очистить историю",
"clearAllErrorDescription": "Что-то пошло не так. Попробуйте ещё раз.",
@@ -2100,12 +2101,16 @@
"cloudNotesMigrationDone": "Все заметки скопированы в облако",
"description": "Контролируйте, какие данные покидают ваше устройство. По умолчанию всё отключено.",
"title": "Конфиденциальность",
+ "insightsSync": "Синхронизировать личную статистику",
+ "insightsSyncDescription": "Синхронизируйте количество слов, дату и точное время каждой диктовки, длительность и типы моделей между устройствами. Содержимое транскрипций никогда не передаётся. Если вы вошли в аккаунт, очистка истории также удаляет эти счётчики с этого устройства и из вашего аккаунта.",
+ "insightsSyncRequiresAccount": "Войдите в аккаунт, чтобы синхронизировать статистику без содержимого между устройствами.",
+ "insightsSyncRequiresHistory": "Включите хранение данных, чтобы статистика записывалась до синхронизации между устройствами.",
"usageAnalytics": "Аналитика использования",
"usageAnalyticsDescription": "Помогите нам улучшить OpenWhispr, делясь анонимными метриками производительности. Мы никогда не отправляем содержимое транскрипций — только данные о времени и ошибках.",
"dataRetention": "Хранение данных",
"dataRetentionDescription": "Сохранять транскрипции и аудио локально в истории. При отключении транскрипции вставляются, но не сохраняются.",
"transcriptRetention": "Хранение транскрипций",
- "transcriptRetentionDescription": "Автоматически удалять сохранённые транскрипции и их аудио по истечении этого срока.",
+ "transcriptRetentionDescription": "Автоматически удалять сохранённые транскрипции, их аудио и их счётчики Insights по истечении этого срока.",
"transcriptRetentionForever": "Бессрочно",
"hoursAgo": "{{count}}ч назад",
"justNow": "только что",
@@ -3230,7 +3235,57 @@
"importList": "Импортировать список",
"agentDefault": "Добавлено по умолчанию"
},
+ "insights": {
+ "title": "Статистика",
+ "description": "Личный обзор ваших привычек диктовки и регулярности.",
+ "wordsSpoken": "Продиктовано слов",
+ "currentStreak": "Текущая серия",
+ "wordsPerMinute": "Слов в минуту",
+ "dictations": "Диктовки",
+ "allTime": "За всё время",
+ "days_one": "{{count}} день",
+ "days_few": "{{count}} дня",
+ "days_many": "{{count}} дней",
+ "days_other": "{{count}} дня",
+ "longestStreak_one": "Рекорд: {{count}} день",
+ "longestStreak_few": "Рекорд: {{count}} дня",
+ "longestStreak_many": "Рекорд: {{count}} дней",
+ "longestStreak_other": "Рекорд: {{count}} дня",
+ "wpmCoverage": "На основе {{count}} % измеренных слов",
+ "activity": "Речевая активность",
+ "activityDescription": "Продиктованные слова за последние 6 месяцев",
+ "activityLabel": "Тепловая карта речевой активности за 6 месяцев",
+ "activityLess": "Меньше",
+ "activityMore": "Больше",
+ "dayTooltip_one": "{{date}}: {{count}} слово",
+ "dayTooltip_few": "{{date}}: {{count}} слова",
+ "dayTooltip_many": "{{date}}: {{count}} слов",
+ "dayTooltip_other": "{{date}}: {{count}} слова",
+ "dataRetentionDisabled": "Хранение данных отключено, поэтому новые диктовки не учитываются в статистике — ни на этом устройстве, ни в вашем аккаунте. Уже синхронизированные счётчики остаются в аккаунте.",
+ "onDevice": "На этом устройстве",
+ "synced": "Синхронизировано между устройствами",
+ "syncFallback": "Показаны данные устройства — синхронизация недоступна",
+ "syncPrompt": "Синхронизируйте счётчики без содержимого, чтобы объединить локальную и облачную активность на всех устройствах.",
+ "enableSync": "Включить синхронизацию",
+ "claimTitle": "Включить прежние диктовки?",
+ "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 передаёт только количество слов, даты и точное время записи, длительность и типы моделей, но никогда содержимое транскрипций.",
+ "emptyTitle": "Диктовок пока нет",
+ "emptyBody": "Начните диктовать — здесь появятся ваши слова, серии и ежедневная активность.",
+ "loadError": "Не удалось прочитать Insights с этого устройства."
+ },
"sidebar": {
+ "insights": "Статистика",
"home": "Главная",
"notes": "Заметки",
"upload": "Загрузить",
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index e5083efbc..5c140a755 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -647,7 +647,8 @@
"failedOffline": "离线",
"clearAll": "全部清除",
"clearAllTitle": "清除所有转录",
- "clearAllDescription": "所有转录和音频文件将被永久删除。",
+ "clearAllDescription": "所有转录、音频文件和 Insights 统计数据都将从此设备和你的账户中永久删除。",
+ "clearAllDescriptionDevice": "所有转录、音频文件和 Insights 统计数据都将从此设备中永久删除。已同步到账户的统计数据不受影响。",
"clearAllSuccess": "历史记录已清除",
"clearAllErrorTitle": "无法清除历史记录",
"clearAllErrorDescription": "出了点问题,请重试。",
@@ -2096,12 +2097,16 @@
"cloudNotesMigrationDone": "所有笔记已备份",
"description": "控制哪些数据会离开你的设备。默认全部关闭。",
"title": "隐私",
+ "insightsSync": "同步个人统计",
+ "insightsSyncDescription": "在你的设备之间同步字数、每次听写的日期和精确时间、时长和模型类型。转录内容永远不会包含在内。登录后清除历史记录,也会从此设备和你的账户中删除这些统计数据。",
+ "insightsSyncRequiresAccount": "登录后即可在设备之间同步不含内容的统计数据。",
+ "insightsSyncRequiresHistory": "开启数据保留后才会记录统计,之后才能跨设备同步。",
"usageAnalytics": "使用分析",
"usageAnalyticsDescription": "通过分享匿名性能数据帮助我们改进 OpenWhispr。我们绝不发送转录内容——仅发送计时和错误数据。",
"dataRetention": "数据保留",
"dataRetentionDescription": "将转录和音频本地保存到历史记录中。禁用后,转录内容会被粘贴但不会被保存。",
"transcriptRetention": "转录保留",
- "transcriptRetentionDescription": "在此期限后自动删除已保存的转录及其音频。",
+ "transcriptRetentionDescription": "在此期限后自动删除已保存的转录、其音频及其 Insights 计数。",
"transcriptRetentionForever": "永久",
"hoursAgo": "{{count}}小时前",
"justNow": "刚刚",
@@ -3202,7 +3207,47 @@
"importList": "导入列表",
"agentDefault": "默认添加"
},
+ "insights": {
+ "title": "统计",
+ "description": "私密查看你的听写习惯与坚持情况。",
+ "wordsSpoken": "已听写字数",
+ "currentStreak": "当前连续天数",
+ "wordsPerMinute": "每分钟字数",
+ "dictations": "听写次数",
+ "allTime": "全部时间",
+ "days_one": "{{count}} 天",
+ "days_other": "{{count}} 天",
+ "longestStreak_one": "最长:{{count}} 天",
+ "longestStreak_other": "最长:{{count}} 天",
+ "wpmCoverage": "基于 {{count}}% 已测量的字数",
+ "activity": "听写活跃度",
+ "activityDescription": "过去 6 个月内听写的字数",
+ "activityLabel": "6 个月听写活跃度热力图",
+ "activityLess": "较少",
+ "activityMore": "较多",
+ "dayTooltip_one": "{{date}}:{{count}} 字",
+ "dayTooltip_other": "{{date}}:{{count}} 字",
+ "dataRetentionDisabled": "数据保留已关闭,因此新的听写不会计入统计——本设备和你的账户都不会计数。已同步的计数会保留在你的账户中。",
+ "onDevice": "仅在本设备",
+ "synced": "已跨设备同步",
+ "syncFallback": "正在显示本设备数据 — 同步不可用",
+ "syncPrompt": "同步不含内容的计数,将本地与云端的活动跨设备合并。",
+ "enableSync": "启用同步",
+ "claimTitle": "包含更早的听写吗?",
+ "claimDescription_one": "本设备上有 {{count}} 次听写是在你登录前记录的。将其纳入只会发送字数、记录的日期和精确时间、时长和模型类型,不会发送转录内容。",
+ "claimDescription_other": "本设备上有 {{count}} 次听写是在你登录前记录的。将它们纳入只会发送字数、记录的日期和精确时间、时长和模型类型,不会发送转录内容。",
+ "claimInclude": "包含",
+ "claimSkip": "暂不开启",
+ "enableTitle": "要开启 Insights 同步吗?",
+ "enableConfirm": "开启同步",
+ "enableDescription_one": "本设备上已记录的 {{count}} 次听写将上传到你的账户。Insights 同步只会发送字数、记录的日期和精确时间、时长和模型类型,不会发送转录内容。",
+ "enableDescription_other": "本设备上已记录的 {{count}} 次听写将上传到你的账户。Insights 同步只会发送字数、记录的日期和精确时间、时长和模型类型,不会发送转录内容。",
+ "emptyTitle": "还没有听写记录",
+ "emptyBody": "开始听写后,你的字数、连续记录和每日活动会显示在这里。",
+ "loadError": "无法从本设备读取 Insights。"
+ },
"sidebar": {
+ "insights": "统计",
"home": "首页",
"notes": "笔记",
"upload": "上传",
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index 9eeefc9ff..dc0e80199 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -647,7 +647,8 @@
"failedOffline": "離線",
"clearAll": "全部清除",
"clearAllTitle": "清除所有轉錄",
- "clearAllDescription": "所有轉錄和音訊檔案將被永久刪除。",
+ "clearAllDescription": "所有轉錄、音訊檔案和 Insights 統計資料都將從此裝置和你的帳戶中永久刪除。",
+ "clearAllDescriptionDevice": "所有轉錄、音訊檔案和 Insights 統計資料都將從此裝置中永久刪除。已同步至帳戶的統計資料不受影響。",
"clearAllSuccess": "歷史紀錄已清除",
"clearAllErrorTitle": "無法清除歷史紀錄",
"clearAllErrorDescription": "發生錯誤,請重試。",
@@ -2096,12 +2097,16 @@
"cloudNotesMigrationDone": "所有筆記已備份",
"description": "控制哪些資料會離開你的裝置。預設全部關閉。",
"title": "隱私權",
+ "insightsSync": "同步個人統計",
+ "insightsSyncDescription": "在你的裝置之間同步字數、每次聽寫的日期與精確時間、時長與模型類型。轉錄內容永遠不會包含在內。登入後清除記錄,也會從此裝置和你的帳戶中刪除這些統計資料。",
+ "insightsSyncRequiresAccount": "登入後即可在裝置之間同步不含內容的統計資料。",
+ "insightsSyncRequiresHistory": "開啟資料保留後才會記錄統計,之後才能跨裝置同步。",
"usageAnalytics": "使用分析",
"usageAnalyticsDescription": "分享匿名的效能指標,協助我們改善 OpenWhispr。我們絕不會傳送轉錄內容——只有計時和錯誤資料。",
"dataRetention": "資料保留",
"dataRetentionDescription": "將轉錄和音訊本地儲存至歷史記錄。停用後,轉錄內容會被貼上但不會被儲存。",
"transcriptRetention": "轉錄保留",
- "transcriptRetentionDescription": "在此期限後自動刪除已儲存的轉錄及其音訊。",
+ "transcriptRetentionDescription": "在此期限後自動刪除已儲存的轉錄、其音訊及其 Insights 計數。",
"transcriptRetentionForever": "永久",
"hoursAgo": "{{count}}小時前",
"justNow": "剛剛",
@@ -3202,7 +3207,47 @@
"importList": "匯入清單",
"agentDefault": "預設加入"
},
+ "insights": {
+ "title": "統計",
+ "description": "私密檢視你的聽寫習慣與持續狀況。",
+ "wordsSpoken": "已聽寫字數",
+ "currentStreak": "目前連續天數",
+ "wordsPerMinute": "每分鐘字數",
+ "dictations": "聽寫次數",
+ "allTime": "全部時間",
+ "days_one": "{{count}} 天",
+ "days_other": "{{count}} 天",
+ "longestStreak_one": "最長:{{count}} 天",
+ "longestStreak_other": "最長:{{count}} 天",
+ "wpmCoverage": "根據 {{count}}% 已測量的字數",
+ "activity": "聽寫活躍度",
+ "activityDescription": "過去 6 個月內聽寫的字數",
+ "activityLabel": "6 個月聽寫活躍度熱圖",
+ "activityLess": "較少",
+ "activityMore": "較多",
+ "dayTooltip_one": "{{date}}:{{count}} 字",
+ "dayTooltip_other": "{{date}}:{{count}} 字",
+ "dataRetentionDisabled": "資料保留已關閉,因此新的聽寫不會計入統計——本裝置和你的帳戶都不會計數。已同步的計數會保留在你的帳戶中。",
+ "onDevice": "僅在本裝置",
+ "synced": "已跨裝置同步",
+ "syncFallback": "正在顯示本裝置資料 — 同步無法使用",
+ "syncPrompt": "同步不含內容的計數,將本機與雲端的活動跨裝置合併。",
+ "enableSync": "啟用同步",
+ "claimTitle": "要包含較早的聽寫嗎?",
+ "claimDescription_one": "本裝置上有 {{count}} 次聽寫是在你登入前記錄的。納入後只會傳送字數、記錄的日期與精確時間、時長與模型類型,不會傳送轉錄內容。",
+ "claimDescription_other": "本裝置上有 {{count}} 次聽寫是在你登入前記錄的。納入後只會傳送字數、記錄的日期與精確時間、時長與模型類型,不會傳送轉錄內容。",
+ "claimInclude": "包含",
+ "claimSkip": "暫不開啟",
+ "enableTitle": "要開啟 Insights 同步嗎?",
+ "enableConfirm": "開啟同步",
+ "enableDescription_one": "本裝置上已記錄的 {{count}} 次聽寫將上傳到你的帳戶。Insights 同步只會傳送字數、記錄的日期與精確時間、時長與模型類型,不會傳送轉錄內容。",
+ "enableDescription_other": "本裝置上已記錄的 {{count}} 次聽寫將上傳到你的帳戶。Insights 同步只會傳送字數、記錄的日期與精確時間、時長與模型類型,不會傳送轉錄內容。",
+ "emptyTitle": "尚無聽寫記錄",
+ "emptyBody": "開始聽寫後,你的字數、連續記錄與每日活動會顯示在這裡。",
+ "loadError": "無法從本裝置讀取 Insights。"
+ },
"sidebar": {
+ "insights": "統計",
"home": "首頁",
"notes": "筆記",
"upload": "上傳",
diff --git a/src/services/AnalyticsService.ts b/src/services/AnalyticsService.ts
new file mode 100644
index 000000000..2fd8b260f
--- /dev/null
+++ b/src/services/AnalyticsService.ts
@@ -0,0 +1,251 @@
+import { cloudDelete, cloudGet, cloudPost, isAuthContextError } from "./cloudApi";
+import type { AnalyticsSummary, PendingAnalyticsEvent } from "../types/electron";
+
+const BATCH_SIZE = 200;
+export const ANALYTICS_SUMMARY_REFRESH_INTERVAL_MS = 5 * 60 * 1000;
+export const ANALYTICS_REMOTE_REFRESH_DEBOUNCE_MS = 250;
+
+export function subscribeToAnalyticsRefresh(
+ refresh: () => void | Promise<void>,
+ cloudInsightsActive: boolean
+): () => void {
+ let disposed = false;
+ let refreshRunning = false;
+ let trailingLocalRefreshRequested = false;
+ let trailingRemoteRefreshRequested = false;
+ const runRefresh = async (remoteOnly = false): Promise<void> => {
+ if (disposed || (remoteOnly && window.document.visibilityState !== "visible")) {
+ return;
+ }
+ if (refreshRunning) {
+ if (remoteOnly) trailingRemoteRefreshRequested = true;
+ else trailingLocalRefreshRequested = true;
+ return;
+ }
+
+ refreshRunning = true;
+ try {
+ await refresh();
+ } catch (error) {
+ console.error("Refreshing analytics failed:", error);
+ } finally {
+ refreshRunning = false;
+ const runLocalRefresh = trailingLocalRefreshRequested;
+ const runRemoteRefresh = trailingRemoteRefreshRequested;
+ trailingLocalRefreshRequested = false;
+ trailingRemoteRefreshRequested = false;
+ if (!disposed && runLocalRefresh) {
+ void runRefresh();
+ } else if (!disposed && runRemoteRefresh && window.document.visibilityState === "visible") {
+ void runRefresh(true);
+ }
+ }
+ };
+ const requestLocalRefresh = (): void => {
+ void runRefresh();
+ };
+ const requestRemoteRefresh = (): void => {
+ void runRefresh(true);
+ };
+
+ const disposeLocal = window.electronAPI.onAnalyticsChanged?.(requestLocalRefresh);
+ requestLocalRefresh();
+ if (!cloudInsightsActive) {
+ return () => {
+ disposed = true;
+ disposeLocal?.();
+ };
+ }
+
+ let remoteRefreshTimeoutId: number | null = null;
+ const refreshRemoteWhenVisible = (): void => {
+ if (window.document.visibilityState !== "visible") {
+ trailingRemoteRefreshRequested = false;
+ if (remoteRefreshTimeoutId !== null) {
+ window.clearTimeout(remoteRefreshTimeoutId);
+ remoteRefreshTimeoutId = null;
+ }
+ return;
+ }
+ if (remoteRefreshTimeoutId !== null) window.clearTimeout(remoteRefreshTimeoutId);
+ remoteRefreshTimeoutId = window.setTimeout(() => {
+ remoteRefreshTimeoutId = null;
+ requestRemoteRefresh();
+ }, ANALYTICS_REMOTE_REFRESH_DEBOUNCE_MS);
+ };
+
+ window.addEventListener("focus", refreshRemoteWhenVisible);
+ window.document.addEventListener("visibilitychange", refreshRemoteWhenVisible);
+ const intervalId = window.setInterval(
+ refreshRemoteWhenVisible,
+ ANALYTICS_SUMMARY_REFRESH_INTERVAL_MS
+ );
+
+ return () => {
+ disposed = true;
+ disposeLocal?.();
+ window.removeEventListener("focus", refreshRemoteWhenVisible);
+ window.document.removeEventListener("visibilitychange", refreshRemoteWhenVisible);
+ window.clearInterval(intervalId);
+ if (remoteRefreshTimeoutId !== null) window.clearTimeout(remoteRefreshTimeoutId);
+ };
+}
+
+async function pushAnalyticsDeletes(): Promise<void> {
+ while (true) {
+ const pending = await window.electronAPI.getPendingAnalyticsDeletes(BATCH_SIZE);
+ 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);
+ if (pending.length < BATCH_SIZE) return;
+ }
+}
+
+async function pushAnalyticsClear(): Promise<void> {
+ const pending = await window.electronAPI.getPendingAnalyticsClear();
+ if (!pending) return;
+
+ await cloudDelete("/api/analytics/events/delete", {
+ deleteAll: true,
+ clearedThrough: pending.cleared_through,
+ });
+ await window.electronAPI.completeAnalyticsClear(pending.cleared_through);
+}
+
+// Erasures and uploads are independent work that happens to share a pass. A
+// clear the server keeps refusing must not stop queued deletes from draining,
+// and neither may block an upload — running them in one try block meant a
+// single stuck request wedged the whole feature until it cleared. Auth-context
+// errors still escape, because SyncService uses them to abandon the pass.
+async function runStage(name: string, stage: () => Promise<void>): Promise<void> {
+ try {
+ await stage();
+ } catch (error) {
+ if (isAuthContextError(error)) throw error;
+ console.error(`Analytics ${name} failed:`, error);
+ }
+}
+
+// One pass at a time. InsightsView flushes on its own schedule — focus, the
+// analytics-changed broadcast, a five-minute timer — while SyncService runs
+// passes inside SYNC_ALL_LOCK, and the two share no lock. Overlapping passes
+// read the same pending rows and post them twice. Queueing rather than
+// 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> {
+ const pass = passQueue.then(
+ () => runAnalyticsPass(options),
+ () => runAnalyticsPass(options)
+ );
+ passQueue = pass.catch(() => {});
+ return pass;
+}
+
+async function runAnalyticsPass({
+ uploadAllowed = true,
+}: { uploadAllowed?: boolean } = {}): 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;
+
+ let synced = 0;
+ // Ids this pass has already offered. The server deliberately withholds rows
+ // it could not store, which keeps them pending — but they stay at the head
+ // of an oldest-first queue, so without this they ride along in every later
+ // batch and one stuck row costs an extra POST per batch behind it.
+ const offered = new Set<string>();
+
+ while (true) {
+ const events: PendingAnalyticsEvent[] =
+ await window.electronAPI.getPendingAnalyticsEvents(BATCH_SIZE);
+ 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);
+
+ // `accepted` is an ack list, not a list of stored rows. The endpoint
+ // validates per event and deliberately echoes back the ids it refused as
+ // permanently invalid, so marking exactly `accepted` as synced is what
+ // retires them. Narrowing this to the ids that were actually stored -- or
+ // 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,
+ });
+ const accepted = Array.isArray(result?.accepted) ? result.accepted : [];
+
+ const { updated } = await window.electronAPI.markAnalyticsEventsSynced(accepted);
+ synced += updated;
+ // The whole queue fit in one read, so there is nothing behind this batch.
+ if (events.length < BATCH_SIZE) return synced;
+ }
+}
+
+const REQUIRED_NONNEGATIVE_SUMMARY_FIELDS = [
+ "totalWords",
+ "totalDictations",
+ "totalSpokenDurationMs",
+ "currentStreakDays",
+ "longestStreakDays",
+] as const;
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function isNonnegativeFiniteNumber(value: unknown): value is number {
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
+}
+
+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 isAnalyticsDailyBucket(value: unknown): boolean {
+ return (
+ isRecord(value) &&
+ isCalendarDate(value.date) &&
+ isNonnegativeFiniteNumber(value.words) &&
+ isNonnegativeFiniteNumber(value.dictations) &&
+ isNonnegativeFiniteNumber(value.spokenDurationMs)
+ );
+}
+
+function isAnalyticsSummary(value: unknown): value is AnalyticsSummary {
+ if (!isRecord(value)) return false;
+ const totalsAreValid = REQUIRED_NONNEGATIVE_SUMMARY_FIELDS.every((field) =>
+ isNonnegativeFiniteNumber(value[field])
+ );
+ const averageWpmIsValid =
+ value.averageWpm === null || isNonnegativeFiniteNumber(value.averageWpm);
+ const coverageIsValid =
+ isNonnegativeFiniteNumber(value.wpmCoveragePercent) && value.wpmCoveragePercent <= 100;
+ return (
+ totalsAreValid &&
+ averageWpmIsValid &&
+ coverageIsValid &&
+ Array.isArray(value.daily) &&
+ value.daily.length <= 366 &&
+ value.daily.every(isAnalyticsDailyBucket)
+ );
+}
+
+export async function getAccountAnalyticsSummary(timeZone: string): Promise<AnalyticsSummary> {
+ const summary = await cloudGet<unknown>(
+ `/api/analytics/summary?timeZone=${encodeURIComponent(timeZone)}`
+ );
+ // 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.
+ if (!isAnalyticsSummary(summary)) {
+ throw new Error("Malformed analytics summary from cloud");
+ }
+ return summary;
+}
diff --git a/src/services/SyncService.ts b/src/services/SyncService.ts
index 212d33331..d7032aadd 100644
--- a/src/services/SyncService.ts
+++ b/src/services/SyncService.ts
@@ -11,6 +11,7 @@ import { ConversationsService } from "./ConversationsService.js";
import { FoldersService } from "./FoldersService.js";
import { SpacesService, type MySpace } from "./SpacesService.js";
import { TranscriptionsService } from "./TranscriptionsService.js";
+import { syncPendingAnalytics } from "./AnalyticsService.js";
import { DictionaryService } from "./DictionaryService.js";
import { SnippetService, type CloudSnippetEntry } from "./SnippetService.js";
import { CloudApiError, isAuthContextError } from "./cloudApi.js";
@@ -27,7 +28,11 @@ import {
} from "../lib/teamSpacesCapability";
import { readIsSubscribed, subscribeIsSubscribed } from "../lib/subscriptionFlag";
import { readNoteConflictIds } from "../lib/noteConflictRegistry";
-import { cloudBackupResumed, isCloudBackupAllowed } from "../stores/policyRules";
+import {
+ cloudBackupResumed,
+ effectiveLocalHistoryEnabled,
+ isCloudBackupAllowed,
+} from "../stores/policyRules";
import { usePolicyStore } from "../stores/policyStore";
import {
buildNoteCreatePayload,
@@ -41,6 +46,7 @@ import {
isPermissionDenialCode,
isSpaceAccessErrorCode,
keepPurgedSpaceEntry,
+ nextAmbientEmptyStreak,
normalizePurgedSpaceEntries,
prunePurgedSpaceEntries,
recordUpdate404,
@@ -123,9 +129,16 @@ const TEAM_SPACES_MAX_RETRY_MS = AUTO_SYNC_INTERVAL_MS;
// Web Lock name serializing syncAll() across windows (each renderer has its
// own SyncService instance, but localStorage and the local DB are shared).
const SYNC_ALL_LOCK = "openwhispr-sync-all";
-// localStorage keys gating canSync(); a change in another window means sync
-// may have just become possible (sign-in, subscription, backup enabled).
-const CAN_SYNC_KEYS = ["isSignedIn", "cloudBackupEnabled", "isSubscribed"];
+// localStorage keys gating what a pass may sync; a change in another window
+// means sync may have just become possible (sign-in, subscription, backup
+// enabled, Insights opt-in).
+const CAN_SYNC_KEYS = [
+ "isSignedIn",
+ "cloudBackupEnabled",
+ "isSubscribed",
+ "insightsSyncEnabled",
+ "dataRetentionEnabled",
+];
// Cross-window guard against a space purge racing an in-flight pull: every
// purge initiator records the cloud space id here, and pull/upsert paths park
@@ -242,14 +255,23 @@ export class SyncService {
// Set by any pass that actually moves team or shared content; drives the
// ambient team-only backoff (see shouldRunAmbientTeamOnlyPass).
private teamPassMovedWork = false;
+ // The same, for Insights counters. Kept separate so neither kind of work is
+ // ever inferred from the other (see nextAmbientEmptyStreak).
+ private analyticsPassMovedWork = false;
private consent(): SyncConsent {
+ const policyState = usePolicyStore.getState();
return resolveSyncConsent({
authValidated: hasValidatedAuthContext(),
signedIn: localStorage.getItem("isSignedIn") === "true",
backupEnabled: localStorage.getItem("cloudBackupEnabled") === "true",
subscribed: readIsSubscribed(),
- backupAllowedByPolicy: isCloudBackupAllowed(usePolicyStore.getState()),
+ backupAllowedByPolicy: isCloudBackupAllowed(policyState),
+ dataRetentionEnabled: effectiveLocalHistoryEnabled(
+ policyState,
+ localStorage.getItem("dataRetentionEnabled") !== "false"
+ ),
+ insightsSyncEnabled: localStorage.getItem("insightsSyncEnabled") === "true",
});
}
@@ -287,7 +309,12 @@ export class SyncService {
const streak = Number(localStorage.getItem("teamOnlyPass.emptyStreak") ?? 0);
localStorage.setItem(
"teamOnlyPass.emptyStreak",
- String(this.teamPassMovedWork ? 0 : streak + 1)
+ String(
+ nextAmbientEmptyStreak(streak, {
+ team: this.teamPassMovedWork,
+ analytics: this.analyticsPassMovedWork,
+ })
+ )
);
localStorage.setItem("teamOnlyPass.lastAt", String(Date.now()));
}
@@ -460,6 +487,7 @@ export class SyncService {
}
this.syncing = true;
this.teamPassMovedWork = false;
+ this.analyticsPassMovedWork = false;
let teamSpacesReady = false;
try {
// Ambient passes skip when another window holds the lock — that pass
@@ -495,9 +523,18 @@ export class SyncService {
await this.syncFolders(true);
if (!hasValidatedAuthContext()) return;
await this.syncNotes(true);
- this.recordTeamOnlyPass();
}
if (!hasValidatedAuthContext()) return;
+ // Outside the branch above: Insights uploads ride their own opt-in,
+ // while queued erasures run for every authenticated account.
+ await this.syncAnalytics();
+ // Stamped after the push, so a pass that moved counters is recorded as
+ // work rather than as another empty one. A pass that loses auth before
+ // reaching here now leaves the streak unstamped where it used to stamp
+ // it, which only makes the next pass due immediately -- the right answer
+ // after an interruption.
+ if (!full) this.recordTeamOnlyPass();
+ if (!hasValidatedAuthContext()) return;
if (teamSpacesReady) {
if (this.teamSpacesRetryTimer) {
clearTimeout(this.teamSpacesRetryTimer);
@@ -2156,6 +2193,25 @@ export class SyncService {
}
}
+ // 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> {
+ const consent = this.consent();
+ if (!consent.shared) return;
+ 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) {
+ this.analyticsPassMovedWork = true;
+ }
+ } catch (err) {
+ if (isAuthContextError(err)) throw err;
+ // 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);
+ }
+ }
+
private async syncTranscriptions(): Promise<void> {
await this.pushPendingTranscriptions();
await this.pushTranscriptionDeletes();
diff --git a/src/services/syncPassPolicy.ts b/src/services/syncPassPolicy.ts
index f48f2db4d..8e9f9186e 100644
--- a/src/services/syncPassPolicy.ts
+++ b/src/services/syncPassPolicy.ts
@@ -6,6 +6,8 @@ export interface SyncConsent {
backup: boolean;
/** Shared notes and team-space content. */
shared: boolean;
+ /** Content-free Insights counters. */
+ analytics: boolean;
}
/**
@@ -15,6 +17,11 @@ export interface SyncConsent {
* gave deliberately, so it syncs whenever they are signed in — collaboration
* is not a paid feature, and gating it on the *invitee's* plan silently
* stranded free teammates in workspaces they had already been added to.
+ *
+ * Insights counters carry no content and are free, so they answer to their own
+ * opt-in rather than the backup toggle or the plan. They still require local
+ * history and are user data leaving the device, so org policy gates them like
+ * backup.
*/
export function resolveSyncConsent(state: {
authValidated: boolean;
@@ -22,14 +29,46 @@ export function resolveSyncConsent(state: {
backupEnabled: boolean;
subscribed: boolean;
backupAllowedByPolicy: boolean;
+ dataRetentionEnabled: boolean;
+ insightsSyncEnabled: boolean;
}): SyncConsent {
const shared = state.authValidated && state.signedIn;
return {
shared,
backup: shared && state.backupEnabled && state.subscribed && state.backupAllowedByPolicy,
+ analytics:
+ shared &&
+ state.insightsSyncEnabled &&
+ state.backupAllowedByPolicy &&
+ state.dataRetentionEnabled,
};
}
+/**
+ * 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).
+ *
+ * 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,
+ * so a sync the user turns on would have nothing to carry.
+ */
+export function canOfferAnalyticsClaim(state: {
+ signedIn: boolean;
+ syncAllowedByPolicy: boolean;
+ dataRetentionEnabled: boolean;
+ insightsSyncEnabled: boolean;
+ unclaimedCount: number;
+}): boolean {
+ if (!state.signedIn || !state.syncAllowedByPolicy || !state.dataRetentionEnabled) return false;
+ return !state.insightsSyncEnabled || state.unclaimedCount > 0;
+}
+
const TEAM_ONLY_PASS_BASE_MS = 5 * 60 * 1000;
const TEAM_ONLY_PASS_MAX_MS = 60 * 60 * 1000;
@@ -59,6 +98,21 @@ export function shouldRunAmbientTeamOnlyPass(state: {
return state.now - state.lastPassAt >= teamOnlyPassDelayMs(state.emptyStreak);
}
+/**
+ * The empty streak after an ambient pass. Insights counters are the second kind
+ * of work such a pass can move, and they get their own input rather than
+ * borrowing the team flag: a pass that uploaded counters did real work and
+ * resets the backoff, while merely having the opt-in on does not — that
+ * conflation would pin every backup-off Insights account to the 5-minute
+ * cadence teamOnlyPassDelayMs exists to remove.
+ */
+export function nextAmbientEmptyStreak(
+ emptyStreak: number,
+ moved: { team: boolean; analytics: boolean }
+): number {
+ return moved.team || moved.analytics ? 0 : emptyStreak + 1;
+}
+
export interface PullCursorAdvance {
// The pass's own cursor ("lastSyncedAt.<kind>", or ".<kind>.team" on a
// team-only pass).
diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.ts
index da518e2e0..db5adb041 100644
--- a/src/stores/settingsStore.ts
+++ b/src/stores/settingsStore.ts
@@ -292,6 +292,7 @@ const BOOLEAN_SETTINGS = new Set([
"translationDisableThinking",
"preferBuiltInMic",
"cloudBackupEnabled",
+ "insightsSyncEnabled",
"telemetryEnabled",
"audioCuesEnabled",
"pauseMediaOnDictation",
@@ -953,6 +954,7 @@ export interface SettingsState
setTheme: (value: "light" | "dark" | "auto") => void;
setCloudBackupEnabled: (value: boolean) => void;
+ setInsightsSyncEnabled: (value: boolean) => void;
setTelemetryEnabled: (value: boolean) => void;
setAudioRetentionDays: (days: number) => void;
setTranscriptRetentionDays: (days: number) => void;
@@ -1358,6 +1360,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
return "auto" as const;
})(),
cloudBackupEnabled: readBoolean("cloudBackupEnabled", false),
+ insightsSyncEnabled: readBoolean("insightsSyncEnabled", false),
telemetryEnabled: readBoolean("telemetryEnabled", false),
audioRetentionDays: readNumber("audioRetentionDays", 30),
transcriptRetentionDays: readNumber("transcriptRetentionDays", 0),
@@ -2108,6 +2111,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
},
setCloudBackupEnabled: createBooleanSetter("cloudBackupEnabled"),
+ setInsightsSyncEnabled: createBooleanSetter("insightsSyncEnabled"),
setTelemetryEnabled: createBooleanSetter("telemetryEnabled"),
setMicWarmHoldSeconds: (value: number) => {
const snapped = snapMicWarmHold(value);
diff --git a/src/types/electron.ts b/src/types/electron.ts
index f033aafbe..d4f0644d2 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -152,6 +152,53 @@ export interface TranscriptionItem {
deleted_at: string | null;
}
+export type AnalyticsMode = "local" | "openwhispr_cloud" | "byok" | "self_hosted" | "unknown";
+
+export interface AnalyticsEventInput {
+ eventId: string;
+ wordCount: number;
+ occurredAt: string;
+ localDate: string;
+ spokenDurationMs?: number | null;
+ mode: AnalyticsMode;
+ provider?: string | null;
+ model?: string | null;
+}
+
+export interface PendingAnalyticsEvent {
+ event_id: string;
+ occurred_at: string;
+ local_date: string;
+ word_count: number;
+ spoken_duration_ms: number | null;
+ mode: AnalyticsMode;
+ provider: string | null;
+ model: string | null;
+ counter_version: number;
+}
+
+export interface PendingAnalyticsClear {
+ cleared_through: string;
+}
+
+export interface AnalyticsDailyBucket {
+ date: string;
+ words: number;
+ dictations: number;
+ spokenDurationMs: number;
+}
+
+export interface AnalyticsSummary {
+ totalWords: number;
+ totalDictations: number;
+ totalSpokenDurationMs: number;
+ averageWpm: number | null;
+ currentStreakDays: number;
+ longestStreakDays: number;
+ wpmCoveragePercent: number;
+ daily: AnalyticsDailyBucket[];
+}
+
export interface NoteItem {
id: number;
title: string;
@@ -1101,6 +1148,25 @@ declare global {
limit?: number,
options?: { includeDiscarded?: boolean }
) => Promise<TranscriptionItem[]>;
+ recordAnalyticsEvent: (
+ input: AnalyticsEventInput
+ ) => Promise<{ success: boolean; eventId?: string; ignored?: boolean }>;
+ getAnalyticsSummary: () => Promise<AnalyticsSummary>;
+ getPendingAnalyticsEvents: (limit?: number) => Promise<PendingAnalyticsEvent[]>;
+ markAnalyticsEventsSynced: (
+ eventIds: string[]
+ ) => Promise<{ success: boolean; updated: number }>;
+ getPendingAnalyticsDeletes: (limit?: number) => Promise<Array<{ event_id: string }>>;
+ hardDeleteAnalyticsEvents: (
+ eventIds: string[]
+ ) => Promise<{ success: boolean; deleted: number }>;
+ getPendingAnalyticsClear: () => Promise<PendingAnalyticsClear | null>;
+ completeAnalyticsClear: (
+ clearedThrough: string
+ ) => Promise<{ success: boolean; deleted: number }>;
+ countUnclaimedAnalyticsEvents: () => Promise<number>;
+ countAnalyticsEventsAwaitingUpload: () => Promise<number>;
+ claimAnonymousAnalyticsEvents: () => Promise<{ success: boolean; claimed: number }>;
clearTranscriptions: () => Promise<{ cleared: number; success: boolean }>;
deleteTranscription: (id: number) => Promise<{ success: boolean }>;
getTranscriptionById: (id: number) => Promise<TranscriptionItem | null>;
@@ -1435,6 +1501,7 @@ declare global {
onTranscriptionUpdated?: (callback: (item: TranscriptionItem) => void) => () => void;
onTranscriptionDeleted?: (callback: (payload: { id: number }) => void) => () => void;
onTranscriptionsCleared?: (callback: (payload: { cleared: number }) => void) => () => void;
+ onAnalyticsChanged?: (callback: () => void) => () => void;
// API key management
getOpenAIKey: () => Promise<string>;
@@ -2065,7 +2132,14 @@ declare global {
// OpenWhispr Cloud API
cloudTranscribe?: (
audioBuffer: ArrayBuffer,
- opts: { language?: string; prompt?: string; useCase?: string; diarization?: boolean }
+ opts: {
+ language?: string;
+ prompt?: string;
+ useCase?: string;
+ diarization?: boolean;
+ localDate?: string;
+ analyticsOccurredAt?: string;
+ }
) => Promise<
{
success: boolean;
@@ -2116,6 +2190,11 @@ declare global {
audioSizeBytes?: number;
audioFormat?: string;
clientTotalMs?: number;
+ clientTranscriptionId?: string;
+ localDate?: string;
+ analyticsOccurredAt?: string;
+ analyticsWordCount?: number;
+ analyticsCounterVersion?: number;
}
) => Promise<{
success: boolean;
diff --git a/test/helpers/accountOwnershipDatabase.test.js b/test/helpers/accountOwnershipDatabase.test.js
index ddeaafbf4..b813578b3 100644
--- a/test/helpers/accountOwnershipDatabase.test.js
+++ b/test/helpers/accountOwnershipDatabase.test.js
@@ -86,10 +86,25 @@ function createDatabaseManager() {
original_updated_at TEXT,
PRIMARY KEY (folder_id, entity_type, entity_id)
);
+ CREATE TABLE analytics_events (
+ event_id TEXT PRIMARY KEY,
+ account_id TEXT
+ );
+ CREATE TABLE analytics_clear_requests (
+ account_id TEXT PRIMARY KEY,
+ cleared_through TEXT NOT NULL
+ );
INSERT INTO spaces (id, kind) VALUES (1, 'private'), (2, 'team'), (3, 'team');
INSERT INTO space_accounts (space_id, account_id) VALUES
(2, 'account-a'),
(3, 'account-b');
+ INSERT INTO analytics_events (event_id, account_id) VALUES
+ ('event-a', 'account-a'),
+ ('event-b', 'account-b'),
+ ('event-guest', NULL);
+ INSERT INTO analytics_clear_requests (account_id, cleared_through) VALUES
+ ('account-a', '2026-08-30T10:00:00.000Z'),
+ ('account-b', '2026-08-30T10:00:00.000Z');
`);
const manager = Object.create(DatabaseManager.prototype);
@@ -249,6 +264,20 @@ test("deleting one account removes only its personal rows and dependent private
.get().count,
0
);
+ assert.deepEqual(
+ sqlite
+ .prepare("SELECT event_id FROM analytics_events ORDER BY event_id")
+ .all()
+ .map((row) => row.event_id),
+ ["event-b", "event-guest"]
+ );
+ assert.deepEqual(
+ sqlite
+ .prepare("SELECT account_id FROM analytics_clear_requests ORDER BY account_id")
+ .all()
+ .map((row) => row.account_id),
+ ["account-b"]
+ );
});
test("account deletion refuses to target an account outside the active scope", (t) => {
diff --git a/test/helpers/analytics.test.js b/test/helpers/analytics.test.js
new file mode 100644
index 000000000..055ee0684
--- /dev/null
+++ b/test/helpers/analytics.test.js
@@ -0,0 +1,114 @@
+const assert = require("node:assert/strict");
+const test = require("node:test");
+const {
+ ANALYTICS_ACTIVITY_MONTH_COUNT,
+ buildAnalyticsActivityDays,
+ calculateStreaks,
+ countSpokenWords,
+ resolveAnalyticsMode,
+ summarizeAnalyticsDays,
+} = require("../../src/helpers/analytics.js");
+
+test("analytics activity covers this month and the previous five calendar months", () => {
+ const days = buildAnalyticsActivityDays(
+ [
+ { date: "2026-03-31", words: 99 },
+ { date: "2026-04-01", words: 3 },
+ { date: "2026-09-15", words: 7 },
+ ],
+ new Date(2026, 8, 15, 12)
+ );
+
+ assert.equal(ANALYTICS_ACTIVITY_MONTH_COUNT, 6);
+ assert.deepEqual(days[0], { date: "2026-04-01", words: 3 });
+ assert.deepEqual(days.at(-1), { date: "2026-09-15", words: 7 });
+ assert.deepEqual(
+ [...new Set(days.map((day) => day.date.slice(0, 7)))],
+ ["2026-04", "2026-05", "2026-06", "2026-07", "2026-08", "2026-09"]
+ );
+});
+
+test("analytics counts raw whitespace-delimited spoken words", () => {
+ assert.equal(countSpokenWords(" one two\nthree "), 3);
+ assert.equal(countSpokenWords("hello,world"), 1);
+ assert.equal(countSpokenWords(""), 0);
+});
+
+test("analytics segments Chinese and Japanese speech without requiring spaces", () => {
+ assert.equal(countSpokenWords("今天我们测试语音输入"), 5);
+ assert.equal(countSpokenWords("今日は良い天気です"), 5);
+ assert.equal(countSpokenWords("OpenWhisprで音声入力を試します"), 7);
+});
+
+test("analytics resolves local, cloud, and BYOK modes", () => {
+ assert.equal(resolveAnalyticsMode({ useLocalWhisper: true }, "local-whisper"), "local");
+ assert.equal(
+ resolveAnalyticsMode(
+ { transcriptionMode: "openwhispr", cloudTranscriptionMode: "openwhispr" },
+ "openwhispr"
+ ),
+ "openwhispr_cloud"
+ );
+ assert.equal(resolveAnalyticsMode({ transcriptionMode: "providers" }, "openai"), "byok");
+});
+
+test("analytics credits a fallback to the provider that actually ran", () => {
+ // Local whisper failed and the user's OpenAI key transcribed instead.
+ assert.equal(resolveAnalyticsMode({ useLocalWhisper: true }, "openai-fallback"), "byok");
+ // A streaming provider name cannot tell BYOK from OpenWhispr Cloud, so the
+ // selected settings still decide.
+ assert.equal(
+ resolveAnalyticsMode(
+ { transcriptionMode: "openwhispr", cloudTranscriptionMode: "openwhispr" },
+ "deepgram-streaming"
+ ),
+ "openwhispr_cloud"
+ );
+});
+
+test("analytics computes weighted WPM, coverage, and streaks from day totals", () => {
+ const summary = summarizeAnalyticsDays(
+ [
+ {
+ date: "2026-08-30",
+ words: 100,
+ dictations: 2,
+ spokenDurationMs: 30_000,
+ coveredWords: 100,
+ },
+ {
+ date: "2026-08-28",
+ words: 100,
+ dictations: 1,
+ spokenDurationMs: 60_000,
+ coveredWords: 100,
+ },
+ { date: "2026-08-29", words: 50, dictations: 1, spokenDurationMs: 0, coveredWords: 0 },
+ ],
+ "2026-08-30"
+ );
+ assert.equal(summary.totalWords, 250);
+ assert.equal(summary.totalDictations, 4);
+ assert.equal(summary.averageWpm, 133);
+ assert.equal(summary.wpmCoveragePercent, 80);
+ assert.equal(summary.currentStreakDays, 3);
+ assert.equal(summary.longestStreakDays, 3);
+ // Unsorted input still yields ascending buckets carrying only view fields.
+ assert.deepEqual(
+ summary.daily.map((bucket) => bucket.date),
+ ["2026-08-28", "2026-08-29", "2026-08-30"]
+ );
+ assert.deepEqual(Object.keys(summary.daily[0]).sort(), [
+ "date",
+ "dictations",
+ "spokenDurationMs",
+ "words",
+ ]);
+});
+
+test("analytics expires a stale current streak", () => {
+ assert.deepEqual(calculateStreaks(["2026-08-27", "2026-08-28"], "2026-08-30"), {
+ currentStreakDays: 0,
+ longestStreakDays: 2,
+ });
+});
diff --git a/test/helpers/analyticsDatabase.test.js b/test/helpers/analyticsDatabase.test.js
new file mode 100644
index 000000000..9f7a2d5cb
--- /dev/null
+++ b/test/helpers/analyticsDatabase.test.js
@@ -0,0 +1,290 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const { createDb } = require("./harness/db.js");
+
+function recordEvent(db, eventId, overrides = {}) {
+ db.recordAnalyticsEvent({
+ eventId,
+ wordCount: 4,
+ occurredAt: "2026-08-30T10:00:00.000Z",
+ localDate: "2026-08-30",
+ spokenDurationMs: 2_000,
+ mode: "local",
+ provider: "local-whisper",
+ model: "small",
+ ...overrides,
+ });
+}
+
+test("analytics stays content-free and idempotent, and only syncs the signed-in account", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+
+ recordEvent(db, "event-1");
+ recordEvent(db, "event-1", { wordCount: 5, provider: null, model: null });
+
+ const columns = db.db.prepare("PRAGMA table_info(analytics_events)").all();
+ assert.equal(
+ columns.some((column) => column.name === "text"),
+ false
+ );
+ assert.equal(db.getAnalyticsSummary().totalWords, 5);
+ assert.equal(db.getAnalyticsSummary().totalDictations, 1);
+
+ db.setActiveAccountId("account-a");
+ assert.equal(db.getAnalyticsSummary().totalWords, 5, "guest activity stays visible on-device");
+ assert.deepEqual(db.getPendingAnalyticsEvents(), [], "guest activity is never attributed");
+
+ recordEvent(db, "event-2");
+ const pending = db.getPendingAnalyticsEvents();
+ assert.equal(pending.length, 1);
+ assert.equal(pending[0].event_id, "event-2");
+ assert.equal(pending[0].counter_version, 2, "new rows identify the Unicode-aware counting rule");
+ assert.equal(db.markAnalyticsEventsSynced(["event-2"]).updated, 1);
+ assert.deepEqual(db.getPendingAnalyticsEvents(), []);
+});
+
+test("clearing history and deleting account data both erase analytics rows", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+
+ recordEvent(db, "event-1");
+ db.clearTranscriptions();
+ assert.equal(db.getAnalyticsSummary().totalDictations, 0);
+ const { cleared_through: deviceClearedThrough } = db.db
+ .prepare("SELECT cleared_through FROM analytics_device_clear_state WHERE id = 1")
+ .get();
+ const afterClear = new Date(Date.parse(deviceClearedThrough) + 1_000).toISOString();
+
+ db.setActiveAccountId("account-a");
+ recordEvent(db, "event-2", { occurredAt: afterClear });
+ db.setActiveAccountId("account-b");
+ recordEvent(db, "event-3", { occurredAt: afterClear });
+ db.deleteAccountData("account-b");
+
+ const remaining = db.db.prepare("SELECT event_id FROM analytics_events").all();
+ assert.deepEqual(
+ remaining.map((row) => row.event_id),
+ ["event-2"],
+ "only the deleted account's rows go"
+ );
+});
+
+test("clearing history tombstones only the counters the cloud actually holds", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+
+ recordEvent(db, "guest-1");
+ db.setActiveAccountId("account-a");
+ recordEvent(db, "synced-1");
+ recordEvent(db, "pending-1");
+ db.markAnalyticsEventsSynced(["synced-1"]);
+ db.setActiveAccountId("account-b");
+ recordEvent(db, "other-account");
+ recordEvent(db, "other-account-tombstone");
+ db.db
+ .prepare(
+ "UPDATE analytics_events SET deleted_at = datetime('now') WHERE event_id = 'other-account-tombstone'"
+ )
+ .run();
+ db.setActiveAccountId("account-a");
+
+ db.clearTranscriptions();
+
+ assert.equal(db.getAnalyticsSummary().totalDictations, 0);
+ assert.deepEqual(db.getPendingAnalyticsEvents(), []);
+ assert.equal(db.countUnclaimedAnalyticsEvents(), 0);
+ assert.deepEqual(
+ db.db
+ .prepare(
+ "SELECT event_id FROM analytics_events WHERE account_id = 'account-a' AND deleted_at IS NOT NULL"
+ )
+ .all()
+ .map((row) => row.event_id)
+ .sort(),
+ ["synced-1"],
+ "only an uploaded counter leaves a tombstone; pending-1 never reached the cloud"
+ );
+ assert.deepEqual(
+ db.db
+ .prepare("SELECT event_id FROM analytics_events WHERE account_id = 'account-b'")
+ .all()
+ .map((row) => row.event_id),
+ ["other-account-tombstone"],
+ "another account's pending cloud deletion survives"
+ );
+
+ // A batch already in flight when the clear landed still gets accepted; the
+ // late ack must not retire the delete tombstone.
+ assert.equal(db.markAnalyticsEventsSynced(["pending-1"]).updated, 0);
+ assert.deepEqual(
+ db
+ .getPendingAnalyticsDeletes()
+ .map((row) => row.event_id)
+ .sort(),
+ ["synced-1"],
+ "the erase queued for the cloud covers exactly what the cloud was given"
+ );
+
+ // A delayed producer for the same dictation must not revive a tombstone.
+ recordEvent(db, "pending-1", { wordCount: 99 });
+ assert.equal(db.getAnalyticsSummary().totalDictations, 0);
+ assert.deepEqual(
+ db
+ .getPendingAnalyticsDeletes()
+ .map((row) => row.event_id)
+ .sort(),
+ ["synced-1"]
+ );
+
+ const pendingClear = db.getPendingAnalyticsClear();
+ assert.match(pendingClear.cleared_through, /^\d{4}-\d{2}-\d{2}T/);
+ recordEvent(db, "late-pre-clear", {
+ occurredAt: new Date(Date.parse(pendingClear.cleared_through) - 1).toISOString(),
+ });
+ assert.equal(db.getAnalyticsSummary().totalDictations, 0);
+
+ db.setActiveAccountId("account-b");
+ assert.equal(db.getPendingAnalyticsClear(), null, "the clear belongs to the active account");
+ recordEvent(db, "late-other-account", {
+ occurredAt: new Date(Date.parse(pendingClear.cleared_through) - 1).toISOString(),
+ });
+ assert.equal(db.getAnalyticsSummary().totalDictations, 0);
+ db.setActiveAccountId("account-a");
+ recordEvent(db, "newer-retention", {
+ occurredAt: new Date(Date.parse(pendingClear.cleared_through) + 1_000).toISOString(),
+ });
+ db.db
+ .prepare(
+ "UPDATE analytics_events SET deleted_at = datetime('now') WHERE event_id = 'newer-retention'"
+ )
+ .run();
+
+ assert.equal(db.completeAnalyticsClear("2000-01-01T00:00:00.000Z").deleted, 0);
+ assert.deepEqual(db.getPendingAnalyticsClear(), pendingClear);
+ // One, not two: pending-1 was erased outright at clear time rather than
+ // tombstoned, because the cloud never received it.
+ assert.equal(db.completeAnalyticsClear(pendingClear.cleared_through).deleted, 1);
+ assert.equal(db.getPendingAnalyticsClear(), null);
+ recordEvent(db, "later-pre-clear", {
+ occurredAt: new Date(Date.parse(pendingClear.cleared_through) - 1).toISOString(),
+ });
+ assert.equal(db.getAnalyticsSummary().totalDictations, 0);
+ assert.deepEqual(db.getPendingAnalyticsDeletes(), [{ event_id: "newer-retention" }]);
+});
+
+test("pre-sign-in analytics are attributed only by an explicit claim", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+
+ recordEvent(db, "guest-1");
+ recordEvent(db, "guest-2");
+ db.setActiveAccountId("account-a");
+ recordEvent(db, "account-1");
+
+ assert.equal(db.countUnclaimedAnalyticsEvents(), 2);
+ assert.deepEqual(
+ db.getPendingAnalyticsEvents().map((row) => row.event_id),
+ ["account-1"],
+ "signing in alone never adopts device-local rows"
+ );
+
+ assert.equal(db.claimAnonymousAnalyticsEvents().claimed, 2);
+ assert.equal(db.countUnclaimedAnalyticsEvents(), 0);
+ assert.deepEqual(
+ db
+ .getPendingAnalyticsEvents()
+ .map((row) => row.event_id)
+ .sort(),
+ ["account-1", "guest-1", "guest-2"]
+ );
+});
+
+test("signed-out clearing is device-only and preserves queued account deletions", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+
+ db.setActiveAccountId("account-a");
+ recordEvent(db, "live-account-event");
+ recordEvent(db, "pending-account-delete");
+ db.db
+ .prepare(
+ "UPDATE analytics_events SET deleted_at = datetime('now') WHERE event_id = 'pending-account-delete'"
+ )
+ .run();
+ db.setActiveAccountId(null);
+
+ db.clearTranscriptions();
+
+ assert.equal(db.getAnalyticsSummary().totalDictations, 0);
+ assert.equal(db.getPendingAnalyticsClear(), null);
+ const { cleared_through: deviceClearedThrough } = db.db
+ .prepare("SELECT cleared_through FROM analytics_device_clear_state WHERE id = 1")
+ .get();
+ recordEvent(db, "late-guest-event", {
+ occurredAt: new Date(Date.parse(deviceClearedThrough) - 1).toISOString(),
+ });
+ assert.equal(db.getAnalyticsSummary().totalDictations, 0);
+ db.setActiveAccountId("account-a");
+ assert.deepEqual(db.getPendingAnalyticsDeletes(), [{ event_id: "pending-account-delete" }]);
+});
+
+// The batch endpoint requires occurred_at as well as local_date, and rejects
+// an event that is missing either. Dropping it from the projection to keep the
+// timestamp on the device would 400 every batch, so the wire shape is pinned
+// here rather than left to the consent copy to imply.
+test("the pending batch carries both the precise timestamp and the local date", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+
+ db.setActiveAccountId("account-a");
+ recordEvent(db, "later", { occurredAt: "2026-08-30T18:00:00.000Z" });
+ recordEvent(db, "earlier", { occurredAt: "2026-08-30T09:00:00.000Z" });
+
+ const pending = db.getPendingAnalyticsEvents();
+ assert.deepEqual(
+ pending.map((row) => row.event_id),
+ ["earlier", "later"],
+ "the device orders the batch by when each dictation happened"
+ );
+ assert.deepEqual(
+ pending.map((row) => row.occurred_at),
+ ["2026-08-30T09:00:00.000Z", "2026-08-30T18:00:00.000Z"],
+ "occurred_at is required by the batch schema, so it has to be on the wire"
+ );
+ for (const row of pending) {
+ assert.equal(row.local_date, "2026-08-30");
+ }
+});
+
+test("the opt-in count covers everything turning sync on would upload", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+
+ // The prompt used to be driven by the pre-sign-in count alone. Every
+ // dictation made while signed in is already attributed, so a long-signed-in
+ // user had nothing "unclaimed", saw no prompt, and uploaded their whole
+ // history on the next pass.
+ recordEvent(db, "before-sign-in");
+ db.setActiveAccountId("account-a");
+ recordEvent(db, "while-signed-in-1");
+ recordEvent(db, "while-signed-in-2");
+
+ assert.equal(db.countUnclaimedAnalyticsEvents(), 1, "only the pre-sign-in row is unclaimed");
+ assert.equal(
+ db.countAnalyticsEventsAwaitingUpload(),
+ 3,
+ "but three rows would actually leave the device"
+ );
+
+ db.markAnalyticsEventsSynced(["while-signed-in-1"]);
+ assert.equal(db.countAnalyticsEventsAwaitingUpload(), 2, "an uploaded row is no longer pending");
+
+ db.setActiveAccountId("account-b");
+ assert.equal(
+ db.countAnalyticsEventsAwaitingUpload(),
+ 1,
+ "another account sees only the unattributed row, never account-a's"
+ );
+});
diff --git a/test/helpers/audioManagerCancelLifecycle.test.js b/test/helpers/audioManagerCancelLifecycle.test.js
index 210bf9abf..a55df7d48 100644
--- a/test/helpers/audioManagerCancelLifecycle.test.js
+++ b/test/helpers/audioManagerCancelLifecycle.test.js
@@ -47,6 +47,7 @@ function createManager(AudioManager, transcription) {
function createBatchFinalizationManager(AudioManager, merge) {
let processAudioCalls = 0;
+ let processAudioMetadata = null;
const mergedBlob = new Blob([new Uint8Array(512)], { type: "audio/webm" });
const manager = Object.assign(Object.create(AudioManager.prototype), {
isRecording: true,
@@ -68,17 +69,43 @@ function createBatchFinalizationManager(AudioManager, merge) {
shouldShowPreviewCleanupState: () => false,
mergeRecordedSegments: () => merge.promise,
getLargestRecordedSegment: () => null,
- processAudio: async () => {
+ processAudio: async (_audioBlob, metadata) => {
processAudioCalls += 1;
+ processAudioMetadata = metadata;
},
onStateChange() {},
});
manager._requestStreamingCancellation = () => {
manager._streamingCancellationGeneration += 1;
};
- return { manager, mergedBlob, getProcessAudioCalls: () => processAudioCalls };
+ return {
+ manager,
+ mergedBlob,
+ getProcessAudioCalls: () => processAudioCalls,
+ getProcessAudioMetadata: () => processAudioMetadata,
+ };
}
+test("batch finalization keeps the recording occurrence time", async (t) => {
+ const { AudioManager } = await loadManagerClass(t);
+ const merge = deferred();
+ const recordingStartedAt = Date.parse("2026-09-02T14:00:00.000Z");
+ const { manager, mergedBlob, getProcessAudioMetadata } = createBatchFinalizationManager(
+ AudioManager,
+ merge
+ );
+ manager.recordingStartTime = recordingStartedAt;
+
+ const finalization = manager.finalizeBatchRecording(mergedBlob);
+ merge.resolve(mergedBlob);
+ await finalization;
+
+ assert.equal(
+ getProcessAudioMetadata().analyticsOccurredAt,
+ new Date(recordingStartedAt).toISOString()
+ );
+});
+
test("cancelling while batch segments merge never starts transcription", async (t) => {
const { AudioManager } = await loadManagerClass(t);
const merge = deferred();
@@ -127,6 +154,23 @@ test("a cancelled older pipeline cannot publish or clear a newer pipeline", asyn
assert.deepEqual(completed, ["new"]);
});
+test("batch processing carries its occurrence time into completion", async (t) => {
+ const { AudioManager } = await loadManagerClass(t);
+ const transcription = deferred();
+ const { manager } = createManager(AudioManager, transcription);
+ const analyticsOccurredAt = "2026-09-02T14:00:00.000Z";
+ let completion;
+ manager.onTranscriptionComplete = (result) => {
+ completion = result;
+ };
+
+ const processing = manager.processAudio(new Blob(["audio"]), { analyticsOccurredAt });
+ transcription.resolve({ success: true, text: "same event", source: "local", timings: {} });
+ await processing;
+
+ assert.equal(completion.analyticsOccurredAt, analyticsOccurredAt);
+});
+
test("a cancelled current pipeline clears busy when its pending work settles", async (t) => {
const { AudioManager } = await loadManagerClass(t);
const transcription = deferred();
diff --git a/test/helpers/audioManagerStreamingFinalization.test.js b/test/helpers/audioManagerStreamingFinalization.test.js
index 394928733..ff3f099b5 100644
--- a/test/helpers/audioManagerStreamingFinalization.test.js
+++ b/test/helpers/audioManagerStreamingFinalization.test.js
@@ -117,6 +117,24 @@ test("streaming silence publishes its empty outcome only after processing settle
assert.deepEqual(order, ["processing", "idle", "empty"]);
});
+test("streaming completion keeps the recording occurrence time", async (t) => {
+ const AudioManager = await loadManagerClass(t);
+ const { manager } = createFinalizingManager(AudioManager);
+ globalThis.window.dispatchEvent = () => true;
+ const recordingStartedAt = Date.parse("2026-09-02T14:00:00.000Z");
+ let completion;
+ manager.recordingStartTime = recordingStartedAt;
+ manager.streamingFinalText = "same event";
+ manager.finalizeChineseScript = async (text) => text;
+ manager.onTranscriptionComplete = (result) => {
+ completion = result;
+ };
+
+ await manager.stopStreamingRecording();
+
+ assert.equal(completion.analyticsOccurredAt, new Date(recordingStartedAt).toISOString());
+});
+
test("cancelling an active streaming recording discards it without publishing text", async (t) => {
const AudioManager = await loadManagerClass(t);
const { manager, states, getProviderStopCalls } = createFinalizingManager(AudioManager);
diff --git a/test/helpers/audioManagerWakeWordLanguage.test.js b/test/helpers/audioManagerWakeWordLanguage.test.js
index 23e9891ed..e79350d35 100644
--- a/test/helpers/audioManagerWakeWordLanguage.test.js
+++ b/test/helpers/audioManagerWakeWordLanguage.test.js
@@ -123,3 +123,63 @@ test("cloud auto-language routing uses detected speech before the UI language",
const italianResult = await createManager().processWithOpenWhisprCloud(audioBlob);
assert.equal(italianResult.text, "agent output");
});
+
+test("cloud transcription returns the occurrence time sent with analytics", async (t) => {
+ const { window, setSettings, createManager } = await loadAudioManager(t);
+ const analyticsOccurredAt = "2026-09-02T14:00:00.000Z";
+ const audioBlob = {
+ type: "audio/webm",
+ size: 1024,
+ arrayBuffer: async () => new ArrayBuffer(8),
+ };
+ let requestOptions;
+
+ setSettings({
+ preferredLanguage: "auto",
+ useCleanupModel: false,
+ customDictionary: [],
+ snippets: [],
+ isSignedIn: true,
+ insightsSyncEnabled: true,
+ dataRetentionEnabled: true,
+ });
+ window.electronAPI.cloudTranscribe = async (_audio, options) => {
+ requestOptions = options;
+ return {
+ success: true,
+ text: "same event",
+ clientTranscriptionId: "event-1",
+ };
+ };
+
+ const result = await createManager().processWithOpenWhisprCloud(audioBlob, {
+ analyticsOccurredAt,
+ });
+
+ assert.equal(requestOptions.analyticsOccurredAt, analyticsOccurredAt);
+ assert.equal(result.analyticsOccurredAt, analyticsOccurredAt);
+});
+
+test("local analytics save uses the propagated occurrence time", async (t) => {
+ const { window, setSettings, createManager } = await loadAudioManager(t);
+ const analyticsOccurredAt = "2026-09-02T14:00:00.000Z";
+ let recordedEvent;
+
+ setSettings({
+ dataRetentionEnabled: true,
+ audioRetentionDays: 0,
+ customDictionary: [],
+ snippets: [],
+ });
+ window.electronAPI.recordAnalyticsEvent = async (event) => {
+ recordedEvent = event;
+ };
+ window.electronAPI.saveTranscription = async () => ({});
+
+ await createManager().saveTranscription("same event", "same event", {
+ clientTranscriptionId: "event-1",
+ analyticsOccurredAt,
+ });
+
+ assert.equal(recordedEvent.occurredAt, analyticsOccurredAt);
+});
diff --git a/test/helpers/cloudChunkPolicy.test.js b/test/helpers/cloudChunkPolicy.test.js
index 8d6101aaa..0e2dc716e 100644
--- a/test/helpers/cloudChunkPolicy.test.js
+++ b/test/helpers/cloudChunkPolicy.test.js
@@ -20,6 +20,7 @@ const {
abortableSleep,
createTeardownGate,
createUploadSlots,
+ withoutChunkAnalytics,
} = require("../../src/helpers/cloudChunkPolicy");
const { changeLanguage } = require("../../src/helpers/i18nMain");
const { createAbortError } = require("../../src/helpers/abortError");
@@ -34,6 +35,22 @@ test("policy constants match the issue-1326 contract", () => {
assert.equal(CLOUD_CHUNK_GLOBAL_CONCURRENCY, 5);
});
+test("chunk requests keep transcription identity without writing partial analytics", () => {
+ const fields = {
+ clientTranscriptionId: "dictation-1",
+ language: "en",
+ localDate: "2026-09-02",
+ analyticsOccurredAt: "2026-09-02T14:00:00.000Z",
+ };
+
+ assert.deepEqual(withoutChunkAnalytics(fields), {
+ clientTranscriptionId: "dictation-1",
+ language: "en",
+ });
+ assert.equal(fields.localDate, "2026-09-02", "the shared inline fields stay unchanged");
+ assert.equal(fields.analyticsOccurredAt, "2026-09-02T14:00:00.000Z");
+});
+
// A wedge fails every in-flight chunk at once, and closeAllConnections is
// session-wide, so an ungated teardown would let each failure abort its healthy
// siblings — and their retries in turn.
diff --git a/test/helpers/harness/electronApiBridge.js b/test/helpers/harness/electronApiBridge.js
index 606f46a1c..6c94050cc 100644
--- a/test/helpers/harness/electronApiBridge.js
+++ b/test/helpers/harness/electronApiBridge.js
@@ -36,6 +36,23 @@ function inertSnippetApi() {
};
}
+// Every analytics binding syncPendingAnalytics reaches for. A missing one does
+// not fail loudly here -- SyncService catches the TypeError and logs it -- so
+// the pass silently does nothing and the test that asserts it drained still
+// reads as a behaviour failure. Keep this in step with preload.js.
+function inertAnalyticsApi() {
+ return {
+ getPendingAnalyticsClear: async () => null,
+ completeAnalyticsClear: async () => ({ success: true, deleted: 0 }),
+ getPendingAnalyticsDeletes: async () => [],
+ hardDeleteAnalyticsEvents: async () => ({ success: true, deleted: 0 }),
+ getPendingAnalyticsEvents: async () => [],
+ markAnalyticsEventsSynced: async () => ({ success: true, updated: 0 }),
+ countUnclaimedAnalyticsEvents: async () => 0,
+ countAnalyticsEventsAwaitingUpload: async () => 0,
+ };
+}
+
function createElectronApi(db, options = {}) {
if (!db) throw new TypeError("createElectronApi requires a DatabaseManager");
const cloud = options.cloud;
@@ -67,8 +84,22 @@ function createElectronApi(db, options = {}) {
getNoteByClientId: async (clientNoteId) => db.getNoteByClientId(clientNoteId),
upsertNoteFromCloud: async (cloudNote, localFolderId, localSpaceId) =>
db.upsertNoteFromCloud(cloudNote, localFolderId, localSpaceId),
- acknowledgeNoteCreate: async (id, snapshot, cloudId, cloudUpdatedAt, ownerUserId, settleIfUnchanged) =>
- db.acknowledgeNoteCreate(id, snapshot, cloudId, cloudUpdatedAt, ownerUserId, settleIfUnchanged),
+ acknowledgeNoteCreate: async (
+ id,
+ snapshot,
+ cloudId,
+ cloudUpdatedAt,
+ ownerUserId,
+ settleIfUnchanged
+ ) =>
+ db.acknowledgeNoteCreate(
+ id,
+ snapshot,
+ cloudId,
+ cloudUpdatedAt,
+ ownerUserId,
+ settleIfUnchanged
+ ),
markNoteSyncedIfUnchanged: async (id, snapshot, expectedCloudId, cloudUpdatedAt, ownerUserId) =>
db.markNoteSyncedIfUnchanged(id, snapshot, expectedCloudId, cloudUpdatedAt, ownerUserId),
markNoteSyncError: async (id) => db.markNoteSyncError(id),
@@ -151,6 +182,7 @@ function createElectronApi(db, options = {}) {
...inertDictionaryApi(),
...inertSnippetApi(),
+ ...inertAnalyticsApi(),
};
}
diff --git a/test/helpers/ipcPolicyHeaderCoverage.test.js b/test/helpers/ipcPolicyHeaderCoverage.test.js
index f0a7d11e7..327e275bc 100644
--- a/test/helpers/ipcPolicyHeaderCoverage.test.js
+++ b/test/helpers/ipcPolicyHeaderCoverage.test.js
@@ -15,7 +15,6 @@ const helperSources = fs
}));
const NON_POLICY_ROUTE_REASONS = new Map([
- ["streaming-usage", "usage accounting does not perform a policy-gated action"],
["usage", "entitlement and recovery status must remain available"],
["stripe/switch-plan", "billing recovery must remain available"],
["stripe/preview-switch", "billing recovery must remain available"],
diff --git a/test/helpers/syncServiceNotes.test.js b/test/helpers/syncServiceNotes.test.js
index 017ace49f..3a80fa862 100644
--- a/test/helpers/syncServiceNotes.test.js
+++ b/test/helpers/syncServiceNotes.test.js
@@ -511,6 +511,41 @@ test("canSync gating: sign-out blocks every call; plan and backup gates protect
);
});
+test("retention opt-out still drains analytics deletes without uploading counters", async (t) => {
+ const ctx = await setup(t);
+ if (!ctx) return;
+ const { api, service } = ctx;
+ localStorageStub.setItem("insightsSyncEnabled", "true");
+ localStorageStub.setItem("dataRetentionEnabled", "false");
+
+ let deleteReads = 0;
+ let localDeletes = 0;
+ let uploadReads = 0;
+ api.getPendingAnalyticsDeletes = async () =>
+ deleteReads++ === 0 ? [{ event_id: "deleted-event" }] : [];
+ api.hardDeleteAnalyticsEvents = async (eventIds) => {
+ localDeletes += eventIds.length;
+ return { success: true, deleted: eventIds.length };
+ };
+ api.getPendingAnalyticsEvents = async () => {
+ uploadReads += 1;
+ return [];
+ };
+ api.markAnalyticsEventsSynced = async () => ({ success: true, updated: 0 });
+ const request = api.cloudApiRequest;
+ api.cloudApiRequest = async (options) => {
+ if (options.path === "/api/analytics/events/delete") {
+ return { success: true, data: { deleted: options.body.eventIds } };
+ }
+ return request(options);
+ };
+
+ await service.syncAll(true);
+
+ assert.equal(localDeletes, 1, "the acknowledged privacy tombstone is retired locally");
+ assert.equal(uploadReads, 0, "retention opt-out must not inspect or send pending counters");
+});
+
test("an ambient pass bows out when another window holds the lock, a manual pass waits", async (t) => {
const ctx = await setup(t);
if (!ctx) return;
diff --git a/test/helpers/transcriptRetention.test.js b/test/helpers/transcriptRetention.test.js
index 17cdce6a9..2e69af55e 100644
--- a/test/helpers/transcriptRetention.test.js
+++ b/test/helpers/transcriptRetention.test.js
@@ -99,3 +99,50 @@ test("ignores rows that are already tombstoned", (t) => {
1
);
});
+
+function insertAnalytics(db, eventId, ageDays) {
+ db.recordAnalyticsEvent({
+ eventId,
+ wordCount: 4,
+ occurredAt: "2026-08-30T10:00:00.000Z",
+ localDate: "2026-08-30",
+ spokenDurationMs: 2_000,
+ mode: "local",
+ provider: "local-whisper",
+ model: "small",
+ });
+ // Backdated explicitly on created_at: that is the column the purge compares,
+ // and it is the only one whose format matches the cutoff (see the purge).
+ db.db
+ .prepare("UPDATE analytics_events SET created_at = datetime('now', ?) WHERE event_id = ?")
+ .run(`-${ageDays} days`, eventId);
+}
+
+test("retention purges analytics counters on the same schedule as transcripts", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+
+ db.setActiveAccountId("account-a");
+ insertAnalytics(db, "stale-pending", 10);
+ insertAnalytics(db, "stale-synced", 10);
+ insertAnalytics(db, "fresh", 0);
+ db.markAnalyticsEventsSynced(["stale-synced"]);
+
+ const { analyticsPurged } = db.deleteTranscriptionsExpiredBefore(7);
+
+ assert.equal(analyticsPurged, 2);
+ assert.deepEqual(
+ (db.getPendingAnalyticsDeletes?.() ?? []).map((row) => row.event_id).sort(),
+ ["stale-synced"],
+ "only the counter the cloud received needs erasing there; stale-pending never left"
+ );
+ assert.deepEqual(
+ db.db
+ .prepare("SELECT event_id FROM analytics_events WHERE deleted_at IS NULL")
+ .all()
+ .map((row) => row.event_id),
+ ["fresh"],
+ "a counter never uploaded is still deleted: retention is an instruction to delete"
+ );
+ assert.equal(db.getAnalyticsSummary().totalDictations, 1);
+});
diff --git a/test/helpers/useAudioRecordingClipboardPersistence.test.js b/test/helpers/useAudioRecordingClipboardPersistence.test.js
index 43df62ae0..efc4157f1 100644
--- a/test/helpers/useAudioRecordingClipboardPersistence.test.js
+++ b/test/helpers/useAudioRecordingClipboardPersistence.test.js
@@ -325,3 +325,32 @@ test("a false persistence result is logged instead of silently ignored", async (
);
assert.deepEqual(harness.navigatorWrites, []);
});
+
+test("the Insights timestamp rides along on the persistence call", async (t) => {
+ // Persistence moved ahead of the paste so history survives a failed
+ // clipboard delivery (#1979). The analytics timestamp has to travel with it:
+ // recordAnalyticsEvent reads it from these options, and losing it here would
+ // silently backdate every counter to the write time instead of the moment
+ // the recording started.
+ const harness = await mountCompletionHarness(t, {});
+
+ await harness.complete({
+ success: true,
+ text: "Final text",
+ rawText: "Raw text",
+ clientTranscriptionId: "client-analytics",
+ analyticsOccurredAt: "2026-09-04T09:00:00.000Z",
+ source: "openai",
+ });
+
+ assert.deepEqual(harness.saves, [
+ [
+ "Final text",
+ "Raw text",
+ {
+ clientTranscriptionId: "client-analytics",
+ analyticsOccurredAt: "2026-09-04T09:00:00.000Z",
+ },
+ ],
+ ]);
+});
diff --git a/test/lib/authAccountScope.test.js b/test/lib/authAccountScope.test.js
index 2eeba1dda..6fe88c4c8 100644
--- a/test/lib/authAccountScope.test.js
+++ b/test/lib/authAccountScope.test.js
@@ -56,6 +56,44 @@ test("a direct account replacement purges before remembering the new user", () =
assert.equal(decide({ userId: "user-b", previousUserId: "user-a", wasSignedIn: true }), "purge");
});
+test("an account replacement clears the previous user's Insights sync consent", async (t) => {
+ const { values, restore } = installStorage({
+ "openwhispr:accountScopeUserId": "user-a",
+ "openwhispr:accountScopeValidated": "true",
+ isSignedIn: "true",
+ insightsSyncEnabled: "true",
+ });
+ t.after(restore);
+
+ await reconcileAccountScope("user-b", {
+ purge: async () => {},
+ verify: async () => {
+ throw new Error("unexpected verification");
+ },
+ });
+
+ assert.equal(values.get("insightsSyncEnabled"), "false");
+});
+
+test("sign-out clears the previous user's Insights sync consent", async (t) => {
+ const { values, restore } = installStorage({
+ "openwhispr:accountScopeUserId": "user-a",
+ "openwhispr:accountScopeValidated": "true",
+ isSignedIn: "true",
+ insightsSyncEnabled: "true",
+ });
+ t.after(restore);
+
+ await reconcileAccountScope(null, {
+ purge: async () => {},
+ verify: async () => {
+ throw new Error("unexpected verification");
+ },
+ });
+
+ assert.equal(values.get("insightsSyncEnabled"), "false");
+});
+
test("reauthentication after signed-out state purges any retained account scope", () => {
assert.equal(decide({ userId: "user-a", previousUserId: "user-a", wasSignedIn: false }), "purge");
});
diff --git a/test/locales/analyticsClearCopy.test.js b/test/locales/analyticsClearCopy.test.js
new file mode 100644
index 000000000..990e1108b
--- /dev/null
+++ b/test/locales/analyticsClearCopy.test.js
@@ -0,0 +1,18 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const en = require("../../src/locales/en/translation.json");
+
+test("Clear History discloses that synced Insights are removed from the account", () => {
+ const privacyCopy = en.settingsPage.privacy.insightsSyncDescription;
+ const confirmationCopy = en.controlPanel.history.clearAllDescription;
+ const signedOutConfirmationCopy = en.controlPanel.history.clearAllDescriptionDevice;
+
+ for (const copy of [privacyCopy, confirmationCopy]) {
+ assert.match(copy, /Insights|counters/);
+ assert.match(copy, /account/);
+ }
+ assert.doesNotMatch(privacyCopy, /won't remove/);
+ assert.match(signedOutConfirmationCopy, /device/);
+ assert.match(signedOutConfirmationCopy, /not affected/);
+});
diff --git a/test/services/analyticsClaimContract.test.js b/test/services/analyticsClaimContract.test.js
new file mode 100644
index 000000000..8a2a0a3ce
--- /dev/null
+++ b/test/services/analyticsClaimContract.test.js
@@ -0,0 +1,47 @@
+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");
+
+// 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).
+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"
+ );
+});
+
+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"
+ );
+});
+
+// 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", () => {
+ const view = read("src/components/InsightsView.tsx");
+ assert.ok(
+ view.includes("canOfferAnalyticsClaim({"),
+ "the banner gate must come from canOfferAnalyticsClaim"
+ );
+ assert.equal(
+ view.includes("!insightsSyncEnabled &&"),
+ false,
+ "gating the offer on the toggle alone strands counters recorded while signed out"
+ );
+});
diff --git a/test/services/analyticsPassAccountingContract.test.js b/test/services/analyticsPassAccountingContract.test.js
new file mode 100644
index 000000000..bac4705b0
--- /dev/null
+++ b/test/services/analyticsPassAccountingContract.test.js
@@ -0,0 +1,37 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const path = require("node:path");
+
+const source = () =>
+ fs.readFileSync(path.join(__dirname, "../..", "src/services/SyncService.ts"), "utf8");
+
+// Pinned at the source level because the pass accounting hangs off ordering and
+// field ownership inside one private method, which no unit test can reach.
+test("an analytics push records its own work and never writes the team flag", () => {
+ const body = source().match(/private async syncAnalytics\(\)([\s\S]*?)\n {2}}/);
+ assert.ok(body, "syncAnalytics is present");
+ assert.ok(
+ body[1].includes("this.analyticsPassMovedWork = true"),
+ "a counter upload must record itself as pass work"
+ );
+ assert.equal(
+ body[1].includes("teamPassMovedWork"),
+ false,
+ "teamPassMovedWork means team or shared content moved; overloading it pins " +
+ "every backup-off Insights account to the 5-minute ambient cadence"
+ );
+});
+
+test("the empty-streak stamp is taken after analytics has had its chance to move work", () => {
+ const pass = source().match(/async syncAll\(waitForLock = false\)([\s\S]*?)\n {2}}/);
+ assert.ok(pass, "syncAll is present");
+ const analyticsAt = pass[1].indexOf("this.syncAnalytics()");
+ const stampAt = pass[1].indexOf("this.recordTeamOnlyPass()");
+ assert.ok(analyticsAt !== -1 && stampAt !== -1, "both calls are present in the pass");
+ assert.ok(
+ stampAt > analyticsAt,
+ "stamping the streak before syncAnalytics runs makes the analytics signal land " +
+ "a pass late, so the fix silently stops working"
+ );
+});
diff --git a/test/services/analyticsService.test.js b/test/services/analyticsService.test.js
new file mode 100644
index 000000000..32fdc8356
--- /dev/null
+++ b/test/services/analyticsService.test.js
@@ -0,0 +1,626 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");
+
+const EVENT = {
+ event_id: "upload-after-delete",
+ occurred_at: "2026-08-30T10:00:00.000Z",
+ local_date: "2026-08-30",
+ word_count: 4,
+ spoken_duration_ms: 2_000,
+ mode: "local",
+ provider: "local-whisper",
+ model: "small",
+ counter_version: 1,
+};
+
+const VALID_SUMMARY = {
+ totalWords: 12,
+ totalDictations: 2,
+ totalSpokenDurationMs: 6_000,
+ averageWpm: 120,
+ currentStreakDays: 1,
+ longestStreakDays: 2,
+ wpmCoveragePercent: 100,
+ daily: [
+ {
+ date: "2026-08-30",
+ words: 12,
+ dictations: 2,
+ spokenDurationMs: 6_000,
+ },
+ ],
+};
+
+test("analytics deletion tombstones reach the cloud before pending uploads", async (t) => {
+ const requests = [];
+ const localMutations = [];
+ let deleteRead = 0;
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ getPendingAnalyticsClear: async () => null,
+ getPendingAnalyticsDeletes: async () =>
+ deleteRead++ === 0 ? [{ event_id: "deleted-event" }] : [],
+ hardDeleteAnalyticsEvents: async (eventIds) => {
+ localMutations.push(["delete", eventIds]);
+ return { success: true, deleted: eventIds.length };
+ },
+ getPendingAnalyticsEvents: async () => [EVENT],
+ markAnalyticsEventsSynced: async (eventIds) => {
+ localMutations.push(["sync", eventIds]);
+ return { success: true, updated: eventIds.length };
+ },
+ cloudApiRequest: async (request) => {
+ requests.push(request);
+ return {
+ success: true,
+ data: request.method === "POST" ? { accepted: [EVENT.event_id] } : {},
+ };
+ },
+ },
+ },
+ });
+ const vite = await createRendererServer(t);
+ const { syncPendingAnalytics } = await vite.ssrLoadModule("/services/AnalyticsService.ts");
+
+ assert.equal(await syncPendingAnalytics(), 1);
+ assert.deepEqual(
+ requests.map(({ method, path }) => [method, path]),
+ [
+ ["DELETE", "/api/analytics/events/delete"],
+ ["POST", "/api/analytics/events/batch"],
+ ]
+ );
+ assert.deepEqual(localMutations, [
+ ["delete", ["deleted-event"]],
+ ["sync", [EVENT.event_id]],
+ ]);
+});
+
+test("a failed cloud deletion preserves its tombstone without blocking uploads", async (t) => {
+ // A tombstone the server refuses must survive locally, but it must not hold
+ // the user's consented uploads hostage while it keeps failing.
+ const requests = [];
+ let hardDeletes = 0;
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ getPendingAnalyticsClear: async () => null,
+ getPendingAnalyticsDeletes: async () => [{ event_id: "deleted-event" }],
+ hardDeleteAnalyticsEvents: async () => {
+ hardDeletes += 1;
+ return { success: true, deleted: 1 };
+ },
+ getPendingAnalyticsEvents: async () => [EVENT],
+ markAnalyticsEventsSynced: async () => ({ success: true, updated: 1 }),
+ cloudApiRequest: async (request) => {
+ requests.push(request);
+ if (request.method === "DELETE") {
+ return { success: false, status: 500, error: "delete failed" };
+ }
+ 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(), 1);
+ assert.deepEqual(
+ requests.map(({ method }) => method),
+ ["DELETE", "POST"]
+ );
+ assert.equal(hardDeletes, 0, "the tombstone survives a failed cloud delete");
+});
+
+test("a delete-only pass clears cloud tombstones without enabling uploads", async (t) => {
+ const requests = [];
+ let deleteRead = 0;
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ getPendingAnalyticsClear: async () => null,
+ getPendingAnalyticsDeletes: async () =>
+ deleteRead++ === 0 ? [{ event_id: "deleted-event" }] : [],
+ hardDeleteAnalyticsEvents: async (eventIds) => ({
+ success: true,
+ deleted: eventIds.length,
+ }),
+ getPendingAnalyticsEvents: async () => {
+ throw new Error("analytics uploads must stay disabled");
+ },
+ markAnalyticsEventsSynced: async () => ({ success: true, updated: 0 }),
+ cloudApiRequest: async (request) => {
+ requests.push(request);
+ return { success: true, data: {} };
+ },
+ },
+ },
+ });
+ const vite = await createRendererServer(t);
+ const { syncPendingAnalytics } = await vite.ssrLoadModule("/services/AnalyticsService.ts");
+
+ assert.equal(await syncPendingAnalytics({ uploadAllowed: false }), 0);
+ assert.deepEqual(
+ requests.map(({ method, path }) => [method, path]),
+ [["DELETE", "/api/analytics/events/delete"]]
+ );
+});
+
+test("an account clear reaches the cloud before newer analytics upload", async (t) => {
+ const clearedThrough = "2026-08-30T10:00:00.000Z";
+ const requests = [];
+ const localMutations = [];
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ getPendingAnalyticsClear: async () => ({ cleared_through: clearedThrough }),
+ completeAnalyticsClear: async (value) => {
+ localMutations.push(["clear", value]);
+ return { success: true, deleted: 1 };
+ },
+ getPendingAnalyticsDeletes: async () => [],
+ getPendingAnalyticsEvents: async () => [EVENT],
+ markAnalyticsEventsSynced: async (eventIds) => {
+ localMutations.push(["sync", eventIds]);
+ return { success: true, updated: eventIds.length };
+ },
+ cloudApiRequest: async (request) => {
+ requests.push(request);
+ return {
+ success: true,
+ data: request.method === "POST" ? { accepted: [EVENT.event_id] } : {},
+ };
+ },
+ },
+ },
+ });
+ const vite = await createRendererServer(t);
+ const { syncPendingAnalytics } = await vite.ssrLoadModule("/services/AnalyticsService.ts");
+
+ assert.equal(await syncPendingAnalytics(), 1);
+ assert.deepEqual(
+ requests.map(({ method, body }) => [method, body]),
+ [
+ ["DELETE", { deleteAll: true, clearedThrough }],
+ ["POST", { events: [EVENT] }],
+ ]
+ );
+ assert.deepEqual(localMutations, [
+ ["clear", clearedThrough],
+ ["sync", [EVENT.event_id]],
+ ]);
+});
+
+test("a failed account clear stays pending without stalling the rest of the pass", async (t) => {
+ // The clear used to be the first and only thing that had to succeed: one
+ // server error and neither the queued deletes nor the uploads ran, on this
+ // pass or any later one, until it cleared. Each stage stands alone now.
+ const requests = [];
+ let completed = 0;
+ let hardDeletes = 0;
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ getPendingAnalyticsClear: async () => ({
+ cleared_through: "2026-08-30T10:00:00.000Z",
+ }),
+ completeAnalyticsClear: async () => {
+ completed += 1;
+ return { success: true, deleted: 0 };
+ },
+ getPendingAnalyticsDeletes: async () =>
+ requests.length === 0 ? [] : [{ event_id: "deleted-event" }],
+ hardDeleteAnalyticsEvents: async () => {
+ hardDeletes += 1;
+ return { success: true, deleted: 1 };
+ },
+ getPendingAnalyticsEvents: async () => (hardDeletes === 0 ? [] : [EVENT]),
+ markAnalyticsEventsSynced: async () => ({ success: true, updated: 1 }),
+ cloudApiRequest: async (request) => {
+ requests.push(request);
+ if (request.body?.deleteAll) {
+ return { success: false, status: 500, error: "clear failed" };
+ }
+ 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(), 1, "the upload still happens");
+ assert.deepEqual(
+ requests.map(({ method }) => method),
+ ["DELETE", "DELETE", "POST"],
+ "the failed clear is attempted, then deletes drain, then uploads go"
+ );
+ assert.equal(completed, 0, "an unacknowledged clear stays queued for the next pass");
+ assert.equal(hardDeletes, 1);
+});
+
+test("account analytics accepts a complete cloud summary", async (t) => {
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ cloudApiRequest: async () => ({
+ 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"), {
+ ...VALID_SUMMARY,
+ scope: "account",
+ timeZone: "UTC",
+ });
+});
+
+for (const [name, daily] of [
+ ["a null bucket", [null]],
+ ["an impossible date", [{ ...VALID_SUMMARY.daily[0], date: "2026-02-30" }]],
+ ["non-numeric words", [{ ...VALID_SUMMARY.daily[0], words: "12" }]],
+ ["negative dictations", [{ ...VALID_SUMMARY.daily[0], dictations: -1 }]],
+ ["a non-numeric duration", [{ ...VALID_SUMMARY.daily[0], spokenDurationMs: null }]],
+]) {
+ test(`account analytics rejects a cloud summary with ${name}`, async (t) => {
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ cloudApiRequest: async () => ({
+ success: true,
+ data: { ...VALID_SUMMARY, daily },
+ }),
+ },
+ },
+ });
+ const vite = await createRendererServer(t);
+ const { getAccountAnalyticsSummary } = await vite.ssrLoadModule(
+ "/services/AnalyticsService.ts"
+ );
+
+ await assert.rejects(
+ getAccountAnalyticsSummary("UTC"),
+ /Malformed analytics summary from cloud/
+ );
+ });
+}
+
+test("analytics refreshes locally on change and remotely only while cloud Insights are active", async (t) => {
+ const windowListeners = new Map();
+ const documentListeners = new Map();
+ const intervals = new Map();
+ const timeouts = new Map();
+ const clearedIntervals = [];
+ const clearedTimeouts = [];
+ let nextIntervalId = 1;
+ let nextTimeoutId = 100;
+ let localChangeListener;
+ let localListenerDisposed = false;
+ const fakeDocument = {
+ visibilityState: "visible",
+ addEventListener: (name, listener) => documentListeners.set(name, listener),
+ removeEventListener: (name, listener) => {
+ if (documentListeners.get(name) === listener) documentListeners.delete(name);
+ },
+ };
+ installBrowserGlobals(t, {
+ window: {
+ document: fakeDocument,
+ addEventListener: (name, listener) => windowListeners.set(name, listener),
+ removeEventListener: (name, listener) => {
+ if (windowListeners.get(name) === listener) windowListeners.delete(name);
+ },
+ setInterval: (callback, delay) => {
+ const id = nextIntervalId++;
+ intervals.set(id, { callback, delay });
+ return id;
+ },
+ clearInterval: (id) => {
+ clearedIntervals.push(id);
+ intervals.delete(id);
+ },
+ setTimeout: (callback, delay) => {
+ const id = nextTimeoutId++;
+ timeouts.set(id, { callback, delay });
+ return id;
+ },
+ clearTimeout: (id) => {
+ clearedTimeouts.push(id);
+ timeouts.delete(id);
+ },
+ electronAPI: {
+ onAnalyticsChanged: (listener) => {
+ localChangeListener = listener;
+ return () => {
+ localListenerDisposed = true;
+ };
+ },
+ },
+ },
+ });
+ const vite = await createRendererServer(t);
+ const {
+ ANALYTICS_REMOTE_REFRESH_DEBOUNCE_MS,
+ ANALYTICS_SUMMARY_REFRESH_INTERVAL_MS,
+ subscribeToAnalyticsRefresh,
+ } = await vite.ssrLoadModule("/services/AnalyticsService.ts");
+ let refreshes = 0;
+ const dispose = subscribeToAnalyticsRefresh(() => {
+ refreshes += 1;
+ }, true);
+
+ assert.equal(refreshes, 1, "the mounted view loads immediately");
+ await Promise.resolve();
+ localChangeListener();
+ assert.equal(refreshes, 2, "local database changes refresh immediately");
+ await Promise.resolve();
+
+ documentListeners.get("visibilitychange")();
+ await Promise.resolve();
+ windowListeners.get("focus")();
+ assert.equal(refreshes, 2, "separate-task visibility and focus events are debounced");
+ assert.deepEqual(clearedTimeouts, [100], "focus replaces the visibility debounce");
+ const [focusTimeoutId, focusTimeout] = [...timeouts.entries()][0];
+ assert.equal(focusTimeout.delay, ANALYTICS_REMOTE_REFRESH_DEBOUNCE_MS);
+ timeouts.delete(focusTimeoutId);
+ focusTimeout.callback();
+ assert.equal(refreshes, 3);
+ await Promise.resolve();
+
+ const [{ callback: poll, delay }] = intervals.values();
+ assert.equal(delay, ANALYTICS_SUMMARY_REFRESH_INTERVAL_MS);
+ poll();
+ const [pollTimeoutId, pollTimeout] = [...timeouts.entries()][0];
+ timeouts.delete(pollTimeoutId);
+ pollTimeout.callback();
+ assert.equal(refreshes, 4, "a visible mounted view eventually sees remote-device changes");
+ await Promise.resolve();
+
+ windowListeners.get("focus")();
+ fakeDocument.visibilityState = "hidden";
+ documentListeners.get("visibilitychange")();
+ assert.equal(timeouts.size, 0, "hiding cancels a focus refresh that has not started");
+ poll();
+ await Promise.resolve();
+ assert.equal(refreshes, 4, "background polling does not issue cloud work");
+ assert.equal(timeouts.size, 0);
+
+ dispose();
+ assert.equal(localListenerDisposed, true);
+ assert.equal(windowListeners.size, 0);
+ assert.equal(documentListeners.size, 0);
+ assert.deepEqual(clearedIntervals, [1]);
+});
+
+test("analytics refresh does not install cloud triggers while account sync is inactive", async (t) => {
+ const windowListeners = new Map();
+ const documentListeners = new Map();
+ let intervalCount = 0;
+ let localChangeListener;
+ installBrowserGlobals(t, {
+ window: {
+ document: {
+ visibilityState: "visible",
+ addEventListener: (name, listener) => documentListeners.set(name, listener),
+ removeEventListener() {},
+ },
+ addEventListener: (name, listener) => windowListeners.set(name, listener),
+ removeEventListener() {},
+ setInterval: () => {
+ intervalCount += 1;
+ return 1;
+ },
+ electronAPI: {
+ onAnalyticsChanged: (listener) => {
+ localChangeListener = listener;
+ return () => {};
+ },
+ },
+ },
+ });
+ const vite = await createRendererServer(t);
+ const { subscribeToAnalyticsRefresh } = await vite.ssrLoadModule("/services/AnalyticsService.ts");
+ let refreshes = 0;
+ const dispose = subscribeToAnalyticsRefresh(() => {
+ refreshes += 1;
+ }, false);
+
+ assert.equal(windowListeners.size, 0);
+ assert.equal(documentListeners.size, 0);
+ assert.equal(intervalCount, 0);
+ assert.equal(refreshes, 1, "device-local summaries load immediately");
+ await Promise.resolve();
+ localChangeListener();
+ assert.equal(refreshes, 2, "device-local summaries remain live");
+ dispose();
+});
+
+test("analytics refresh serializes triggers and runs one trailing refresh", async (t) => {
+ let localChangeListener;
+ let releaseFirstRefresh;
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ onAnalyticsChanged: (listener) => {
+ localChangeListener = listener;
+ return () => {};
+ },
+ },
+ },
+ });
+ const vite = await createRendererServer(t);
+ const { subscribeToAnalyticsRefresh } = await vite.ssrLoadModule("/services/AnalyticsService.ts");
+ let activeRefreshes = 0;
+ let refreshes = 0;
+ let maximumConcurrentRefreshes = 0;
+ const dispose = subscribeToAnalyticsRefresh(async () => {
+ refreshes += 1;
+ activeRefreshes += 1;
+ maximumConcurrentRefreshes = Math.max(maximumConcurrentRefreshes, activeRefreshes);
+ if (refreshes === 1) {
+ await new Promise((resolve) => {
+ releaseFirstRefresh = resolve;
+ });
+ }
+ activeRefreshes -= 1;
+ }, false);
+
+ assert.equal(refreshes, 1);
+ localChangeListener();
+ localChangeListener();
+ assert.equal(refreshes, 1, "new triggers wait for the active refresh");
+
+ releaseFirstRefresh();
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ assert.equal(refreshes, 2, "multiple waiting triggers collapse into one trailing refresh");
+ assert.equal(maximumConcurrentRefreshes, 1);
+ dispose();
+});
+
+test("analytics drops remote-only trailing work when the view becomes hidden", async (t) => {
+ const windowListeners = new Map();
+ const documentListeners = new Map();
+ const timeouts = new Map();
+ let nextTimeoutId = 1;
+ let releaseInitialRefresh;
+ const fakeDocument = {
+ visibilityState: "visible",
+ addEventListener: (name, listener) => documentListeners.set(name, listener),
+ removeEventListener: (name, listener) => {
+ if (documentListeners.get(name) === listener) documentListeners.delete(name);
+ },
+ };
+ installBrowserGlobals(t, {
+ window: {
+ document: fakeDocument,
+ addEventListener: (name, listener) => windowListeners.set(name, listener),
+ removeEventListener: (name, listener) => {
+ if (windowListeners.get(name) === listener) windowListeners.delete(name);
+ },
+ setInterval: () => 1,
+ clearInterval: () => {},
+ setTimeout: (callback) => {
+ const id = nextTimeoutId++;
+ timeouts.set(id, callback);
+ return id;
+ },
+ clearTimeout: (id) => timeouts.delete(id),
+ electronAPI: {
+ onAnalyticsChanged: () => () => {},
+ },
+ },
+ });
+ const vite = await createRendererServer(t);
+ const { subscribeToAnalyticsRefresh } = await vite.ssrLoadModule("/services/AnalyticsService.ts");
+ let refreshes = 0;
+ const dispose = subscribeToAnalyticsRefresh(async () => {
+ refreshes += 1;
+ if (refreshes === 1) {
+ await new Promise((resolve) => {
+ releaseInitialRefresh = resolve;
+ });
+ }
+ }, true);
+
+ windowListeners.get("focus")();
+ const [timeoutId, remoteRefresh] = [...timeouts.entries()][0];
+ timeouts.delete(timeoutId);
+ remoteRefresh();
+ assert.equal(refreshes, 1, "the remote refresh waits behind the initial load");
+
+ fakeDocument.visibilityState = "hidden";
+ documentListeners.get("visibilitychange")();
+ releaseInitialRefresh();
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ assert.equal(refreshes, 1, "hidden views discard queued remote-only refreshes");
+ dispose();
+});
+
+test("overlapping passes are serialized rather than posting the same batch twice", async (t) => {
+ // InsightsView flushes on focus, on every analytics-changed broadcast and on
+ // a timer, while SyncService runs passes under its own lock. The two share
+ // no lock, so without serializing here both read the same pending rows.
+ const requests = [];
+ let synced = false;
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ getPendingAnalyticsClear: async () => null,
+ getPendingAnalyticsDeletes: async () => [],
+ getPendingAnalyticsEvents: async () => (synced ? [] : [EVENT]),
+ markAnalyticsEventsSynced: async () => {
+ synced = true;
+ return { success: true, updated: 1 };
+ },
+ cloudApiRequest: async (request) => {
+ requests.push(request);
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ return { success: true, data: { accepted: [EVENT.event_id] } };
+ },
+ },
+ },
+ });
+ const vite = await createRendererServer(t);
+ const { syncPendingAnalytics } = await vite.ssrLoadModule("/services/AnalyticsService.ts");
+
+ const [first, second] = await Promise.all([syncPendingAnalytics(), syncPendingAnalytics()]);
+
+ assert.equal(requests.length, 1, "the second pass waits and then finds nothing left to send");
+ assert.equal(first, 1);
+ assert.equal(second, 0);
+});
+
+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
+ // the head each iteration made every later batch carry them again.
+ const posted = [];
+ const pending = Array.from({ length: 3 }, (_, index) => ({
+ ...EVENT,
+ event_id: `event-${index}`,
+ }));
+ const retired = new Set();
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ getPendingAnalyticsClear: async () => null,
+ getPendingAnalyticsDeletes: async () => [],
+ getPendingAnalyticsEvents: async () =>
+ pending.filter((event) => !retired.has(event.event_id)),
+ markAnalyticsEventsSynced: async (ids) => {
+ ids.forEach((id) => retired.add(id));
+ return { success: true, updated: ids.length };
+ },
+ cloudApiRequest: async (request) => {
+ posted.push(request.body.events.map((event) => event.event_id));
+ // event-0 is withheld: in neither accepted nor rejected.
+ return {
+ success: true,
+ data: {
+ accepted: request.body.events.map((e) => e.event_id).filter((id) => id !== "event-0"),
+ },
+ };
+ },
+ },
+ },
+ });
+ const vite = await createRendererServer(t);
+ const { syncPendingAnalytics } = await vite.ssrLoadModule("/services/AnalyticsService.ts");
+
+ await syncPendingAnalytics();
+
+ assert.deepEqual(posted, [["event-0", "event-1", "event-2"]]);
+ assert.equal(retired.has("event-0"), false, "the withheld row stays pending for a later pass");
+});
diff --git a/test/services/syncPassPolicy.test.js b/test/services/syncPassPolicy.test.js
index 856de00ff..58ed47d3a 100644
--- a/test/services/syncPassPolicy.test.js
+++ b/test/services/syncPassPolicy.test.js
@@ -14,6 +14,8 @@ const SIGNED_IN = {
backupEnabled: true,
subscribed: true,
backupAllowedByPolicy: true,
+ dataRetentionEnabled: true,
+ insightsSyncEnabled: true,
};
test("consent: a free account still syncs shared notes and team spaces", async () => {
@@ -31,7 +33,7 @@ test("consent: a free account still syncs shared notes and team spaces", async (
test("consent: sharing survives the cloud-backup toggle being off", async () => {
const { resolveSyncConsent } = await load();
const consent = resolveSyncConsent({ ...SIGNED_IN, backupEnabled: false });
- assert.deepEqual(consent, { shared: true, backup: false });
+ assert.deepEqual(consent, { shared: true, backup: false, analytics: true });
});
test("consent: backup needs the plan, the toggle, and org policy together", async () => {
@@ -51,12 +53,75 @@ test("consent: nothing syncs without a validated signed-in session", async () =>
for (const off of ["authValidated", "signedIn"]) {
assert.deepEqual(
resolveSyncConsent({ ...SIGNED_IN, [off]: false }),
- { shared: false, backup: false },
+ { shared: false, backup: false, analytics: false },
`${off} off must stop every pass`
);
}
});
+test("consent: Insights counters answer to their own opt-in, not the plan", async () => {
+ const { resolveSyncConsent } = await load();
+ assert.equal(
+ resolveSyncConsent({ ...SIGNED_IN, backupEnabled: false, subscribed: false }).analytics,
+ true
+ );
+ for (const off of ["insightsSyncEnabled", "backupAllowedByPolicy"]) {
+ assert.equal(
+ resolveSyncConsent({ ...SIGNED_IN, [off]: false }).analytics,
+ false,
+ `analytics must not run with ${off} off`
+ );
+ }
+});
+
+test("consent: disabling local history stops pending Insights uploads", async () => {
+ const { resolveSyncConsent } = await load();
+ assert.equal(resolveSyncConsent({ ...SIGNED_IN, dataRetentionEnabled: false }).analytics, false);
+});
+
+// --- canOfferAnalyticsClaim -------------------------------------------------
+// insightsSyncEnabled is device-scoped and survives sign-out, so counters
+// spoken before the next sign-in are unattributed with the toggle still on.
+
+const OFFER = {
+ signedIn: true,
+ syncAllowedByPolicy: true,
+ dataRetentionEnabled: true,
+ insightsSyncEnabled: false,
+ unclaimedCount: 0,
+};
+
+test("claim offer: counters stay offerable once sync is already on", async () => {
+ const { canOfferAnalyticsClaim } = await load();
+ // The bug: signed out, dictated, signed back in. Those rows are excluded
+ // from the account summary the view then shows, so hiding the offer behind
+ // the toggle dropped the visible totals with no way to get them back.
+ assert.equal(
+ canOfferAnalyticsClaim({ ...OFFER, insightsSyncEnabled: true, unclaimedCount: 2 }),
+ true
+ );
+ // Sync on and nothing left behind: there is nothing to ask about.
+ assert.equal(canOfferAnalyticsClaim({ ...OFFER, insightsSyncEnabled: true }), false);
+});
+
+test("claim offer: the opt-in prompt still shows before sync is turned on", async () => {
+ const { canOfferAnalyticsClaim } = await load();
+ assert.equal(canOfferAnalyticsClaim(OFFER), true);
+ for (const off of ["signedIn", "syncAllowedByPolicy", "dataRetentionEnabled"]) {
+ assert.equal(canOfferAnalyticsClaim({ ...OFFER, [off]: false }), false, `${off} off`);
+ assert.equal(
+ canOfferAnalyticsClaim({
+ ...OFFER,
+ [off]: false,
+ insightsSyncEnabled: true,
+ unclaimedCount: 2,
+ }),
+ false,
+ `${off} off must hide the claim offer too`
+ );
+ }
+});
+
// --- ambient team-only pass backoff ----------------------------------------
// Most signed-in accounts have no shared notes and no team spaces; before the
// backoff they spent three requests every five minutes confirming that.
@@ -95,6 +160,18 @@ test("team-only backoff: an idle account waits, and the first launch always runs
assert.equal(shouldRunAmbientTeamOnlyPass({ emptyStreak: 9, lastPassAt: null, now }), true);
});
+test("ambient streak: a counter upload counts as work without borrowing the team flag", async () => {
+ const { nextAmbientEmptyStreak } = await load();
+ // The bug: an analytics push was not pass work at all, so a backup-off
+ // account with Insights on backed off to hourly while counters queued up.
+ assert.equal(nextAmbientEmptyStreak(3, { team: false, analytics: true }), 0);
+ // The over-correction: setting the team flag on any analytics consent pinned
+ // every such account to the 5-minute cadence. Work, not consent, resets it.
+ assert.equal(nextAmbientEmptyStreak(3, { team: false, analytics: false }), 4);
+ assert.equal(nextAmbientEmptyStreak(3, { team: true, analytics: false }), 0);
+ assert.equal(nextAmbientEmptyStreak(0, { team: false, analytics: false }), 1);
+});
+
// --- resolvePullCursorAdvance ----------------------------------------------
// The matrix mirrors SyncService's pullFolders/pullNotes cursor semantics: a
// wrongly advanced cursor silently drops teammate edits from the delta pulls.