Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions electron/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,13 @@ import { offersStarPrompt, REPO_URL, storeReviewUrl } from "./star-prompt";
import { registerSttIpc, shutdownStt } from "./stt";
import { checkLatestRelease } from "./update-checker";
import { loadUpdateMode, saveUpdateMode } from "./update-settings";
import {
doNotTrack,
loadUsagePingState,
sendUsagePing,
setUsagePingEnabled,
USAGE_PING_INTERVAL_MS,
} from "./usage-ping";
import { configureWaylandSupport } from "./wayland";
import {
createCountdownOverlayWindow,
Expand Down Expand Up @@ -652,6 +659,28 @@ function persistUpdateMode(mode: UpdateMode) {
updateTrayMenu(isRecording);
}

let usagePingEnabled = true;

/** Hidden where the ping never runs anyway: a dev build, or DO_NOT_TRACK set. */
function showUsagePingToggle(): boolean {
return getInstallChannel() !== "dev" && !doNotTrack(process.env);
}

function persistUsagePingEnabled(enabled: boolean) {
usagePingEnabled = enabled;
setUsagePingEnabled(app.getPath("userData"), enabled);
updateTrayMenu(isRecording);
}

function runUsagePing() {
void sendUsagePing(app.getPath("userData"), {
version: app.getVersion(),
os: process.platform,
arch: process.arch,
channel: getInstallChannel(),
});
}

async function downloadAndInstall(latestVersion: string) {
const result = await runUnblockedDownloadAndInstall({
download: downloadSelfUpdate,
Expand Down Expand Up @@ -946,6 +975,16 @@ function updateTrayMenu(recording: boolean = false) {
},
]
: []),
...(showUsagePingToggle()
? [
{
label: mainT("common", "actions.usagePing") || "Send Anonymous Usage Count",
type: "checkbox" as const,
checked: usagePingEnabled,
click: () => persistUsagePingEnabled(!usagePingEnabled),
},
]
: []),
// The About box's other homes are menu-bar items, and no window this app creates
// shows a menu bar: the HUD is frameless (electron/windows.ts), and the editor and
// notes windows call setAutoHideMenuBar(true) on Windows and Linux. Without this
Expand Down Expand Up @@ -1390,9 +1429,12 @@ appReady?.then(async () => {
// all (see auto-updater.ts getUpdater) — every real update path applies
// its settings lazily on first use.
currentUpdateMode = loadUpdateMode(app.getPath("userData"));
usagePingEnabled = loadUsagePingState(app.getPath("userData")).enabled;
createTray();
updateTrayMenu();
startBackgroundUpdateTimer();
runUsagePing();
setInterval(runUsagePing, USAGE_PING_INTERVAL_MS).unref();
configureAboutPanel();
setupApplicationMenu();
await ensureRecordingsDir();
Expand Down
112 changes: 112 additions & 0 deletions electron/usage-ping.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import { mkdtempSync, rmSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
loadUsagePingState,
periodKeys,
planUsagePing,
sendUsagePing,
setUsagePingEnabled,
type UsagePingFacts,
type UsagePingState,
} from "./usage-ping";

const temps: string[] = [];

afterEach(() => {
for (const dir of temps) rmSync(dir, { recursive: true, force: true });
temps.length = 0;
});

function tmp(): string {
const dir = mkdtempSync(path.join(os.tmpdir(), "usage-ping-"));
temps.push(dir);
return dir;
}

const fresh: UsagePingState = { enabled: true, day: null, week: null, month: null };
const facts: UsagePingFacts = { version: "2.0.0", os: "win32", arch: "x64", channel: "store" };
// Wednesday 14 October 2026.
const wednesday = new Date("2026-10-14T09:00:00Z");

describe("periodKeys", () => {
it("uses UTC and ISO weeks, which belong to the year of their Thursday", () => {
expect(periodKeys(wednesday)).toEqual({
day: "2026-10-14",
week: "2026-W42",
month: "2026-10",
});
expect(periodKeys(new Date("2027-01-01T12:00:00Z")).week).toBe("2026-W53");
expect(periodKeys(new Date("2026-01-01T12:00:00Z")).week).toBe("2026-W01");
});
});

describe("planUsagePing", () => {
it("stays silent when turned off, in dev, under DO_NOT_TRACK or CI, and twice a day", () => {
expect(planUsagePing({ ...fresh, enabled: false }, "store", {}, wednesday)).toBeNull();
expect(planUsagePing(fresh, "dev", {}, wednesday)).toBeNull();
expect(planUsagePing(fresh, "store", { DO_NOT_TRACK: "1" }, wednesday)).toBeNull();
expect(planUsagePing(fresh, "store", { CI: "true" }, wednesday)).toBeNull();
const today = { ...fresh, ...periodKeys(wednesday) };
expect(planUsagePing(today, "store", {}, wednesday)).toBeNull();
expect(planUsagePing(fresh, "store", { DO_NOT_TRACK: "0" }, wednesday)).not.toBeNull();
expect(planUsagePing(fresh, "store", { CI: "false" }, wednesday)).not.toBeNull();
});

it("flags the first ping of each week and month, so actives count without an ID", () => {
expect(planUsagePing(fresh, "nsis", {}, wednesday)).toMatchObject({
firstThisWeek: true,
firstThisMonth: true,
});
const tuesday = { ...fresh, ...periodKeys(new Date("2026-10-13T09:00:00Z")) };
expect(planUsagePing(tuesday, "nsis", {}, wednesday)).toMatchObject({
firstThisWeek: false,
firstThisMonth: false,
});
const lastSunday = { ...fresh, ...periodKeys(new Date("2026-10-11T09:00:00Z")) };
expect(planUsagePing(lastSunday, "nsis", {}, wednesday)).toMatchObject({
firstThisWeek: true,
firstThisMonth: false,
});
});
});

describe("sendUsagePing", () => {
it("sends no identifier and keeps the dates only once PostHog accepted the ping", async () => {
const dir = tmp();
const bodies: Record<string, unknown>[] = [];
const ok = async (_url: string, init: RequestInit) => {
bodies.push(JSON.parse(String(init.body)));
return { ok: true };
};

await sendUsagePing(dir, facts, {}, wednesday, async () => ({ ok: false }));
expect(loadUsagePingState(dir).day).toBeNull();

await sendUsagePing(dir, facts, {}, wednesday, ok);
await sendUsagePing(dir, facts, {}, wednesday, ok);
await sendUsagePing(dir, facts, {}, new Date("2026-10-15T09:00:00Z"), ok);
expect(bodies).toHaveLength(2);
expect(bodies[0].distinct_id).not.toBe(bodies[1].distinct_id);
expect(bodies[0].properties).toEqual({
$process_person_profile: false,
$geoip_disable: true,
version: "2.0.0",
os: "win32",
arch: "x64",
channel: "store",
first_this_week: true,
first_this_month: true,
});
});

it("keeps the checkbox off when it is unticked while a ping is in flight", async () => {
const dir = tmp();
await sendUsagePing(dir, facts, {}, wednesday, async () => {
setUsagePingEnabled(dir, false);
return { ok: true };
});
expect(loadUsagePingState(dir)).toMatchObject({ enabled: false, day: "2026-10-14" });
});
});
154 changes: 154 additions & 0 deletions electron/usage-ping.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
// One anonymous count of the installations that ran today, and nothing else.
//
// No identifier leaves the machine: no install ID, no hardware hash, no cookie. PostHog
// requires a distinct_id, so each ping gets a fresh random one that matches nothing, and
// PostHog builds no person from it. Weekly and monthly actives are counted the way Brave
// counts them, without an ID: the app remembers locally when it last pinged and says
// whether this is its first ping of the week and of the month, so WAU and MAU are plain
// counts of those flags. GeoIP is off on every event, and the PostHog project discards IP
// addresses. The website FAQ ("Does OpenScreen work offline?") lists this payload; keep it
// in step.

import { randomUUID } from "node:crypto";
import { readFileSync, writeFileSync } from "node:fs";
import path from "node:path";
import type { InstallChannel } from "./install-channel";

// A project token is public by design: it can only send events, not read them.
const POSTHOG_TOKEN = "phc_zhJDJHBBRDAJBwSb7zf2JuQ59v6RwBN96ZksM2y4oq8C";
const CAPTURE_URL = "https://eu.i.posthog.com/i/v0/e/";

/** Often enough that an app left running in the tray for days still counts every day. */
export const USAGE_PING_INTERVAL_MS = 6 * 60 * 60 * 1000;

export interface UsagePingState {
enabled: boolean;
/** UTC day, ISO week and month of the last ping that went through. */
day: string | null;
week: string | null;
month: string | null;
}

export interface UsagePingFacts {
version: string;
os: NodeJS.Platform;
arch: string;
channel: InstallChannel;
}

const DEFAULT_STATE: UsagePingState = { enabled: true, day: null, week: null, month: null };

/** An environment flag counts as set unless it is empty, "0" or "false": `CI=false` is off. */
const isSet = (value: string | undefined) =>
value !== undefined && !["", "0", "false"].includes(value.toLowerCase());

/** The usual opt-out convention (consoledonottrack.com). */
export function doNotTrack(env: Readonly<Record<string, string | undefined>>): boolean {
return isSet(env.DO_NOT_TRACK);
}

/** UTC, so the flags fall in the same buckets as PostHog's UTC days. */
export function periodKeys(now: Date): { day: string; week: string; month: string } {
const iso = now.toISOString();
// ISO 8601 week: the week belongs to the year of its Thursday.
const thursday = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
thursday.setUTCDate(thursday.getUTCDate() + 4 - (thursday.getUTCDay() || 7));
const year = thursday.getUTCFullYear();
const week = Math.ceil(((thursday.getTime() - Date.UTC(year, 0, 1)) / 86_400_000 + 1) / 7);
return {
day: iso.slice(0, 10),
week: `${year}-W${String(week).padStart(2, "0")}`,
month: iso.slice(0, 7),
};
}

/** The ping to send now, or null. Pure, so the whole matrix pins from any platform. */
export function planUsagePing(
state: UsagePingState,
channel: InstallChannel,
env: Readonly<Record<string, string | undefined>>,
now: Date,
): { firstThisWeek: boolean; firstThisMonth: boolean; keys: ReturnType<typeof periodKeys> } | null {
if (!state.enabled || channel === "dev" || doNotTrack(env) || isSet(env.CI)) return null;
const keys = periodKeys(now);
if (state.day === keys.day) return null;
return {
firstThisWeek: state.week !== keys.week,
firstThisMonth: state.month !== keys.month,
keys,
};
}

function statePath(userData: string): string {
return path.join(userData, "usage-ping.json");
}

export function loadUsagePingState(userData: string): UsagePingState {
try {
const raw = JSON.parse(readFileSync(statePath(userData), "utf8")) as Partial<UsagePingState>;
const text = (value: unknown) => (typeof value === "string" ? value : null);
return {
enabled: raw.enabled !== false,
day: text(raw.day),
week: text(raw.week),
month: text(raw.month),
};
} catch {
return { ...DEFAULT_STATE };
}
}

function saveUsagePingState(userData: string, state: UsagePingState): void {
try {
writeFileSync(statePath(userData), `${JSON.stringify(state)}\n`, "utf8");
} catch {
// Best-effort: a failed write only means the next launch pings again.
}
}

export function setUsagePingEnabled(userData: string, enabled: boolean): void {
saveUsagePingState(userData, { ...loadUsagePingState(userData), enabled });
}

type Fetch = (url: string, init: RequestInit) => Promise<{ ok: boolean }>;

/** Sends today's ping if none went through yet. Never throws: a failure only means the
* next attempt tries again, and the dates are saved only once PostHog accepted it. */
export async function sendUsagePing(
userData: string,
facts: UsagePingFacts,
env: Readonly<Record<string, string | undefined>> = process.env,
now: Date = new Date(),
fetchImpl: Fetch = fetch,
): Promise<void> {
const state = loadUsagePingState(userData);
const plan = planUsagePing(state, facts.channel, env, now);
if (!plan) return;
try {
const response = await fetchImpl(CAPTURE_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
api_key: POSTHOG_TOKEN,
event: "app_active",
distinct_id: randomUUID(),
properties: {
$process_person_profile: false,
$geoip_disable: true,
version: facts.version,
os: facts.os,
arch: facts.arch,
channel: facts.channel,
first_this_week: plan.firstThisWeek,
first_this_month: plan.firstThisMonth,
},
}),
signal: AbortSignal.timeout(15_000),
});
// Re-read rather than reuse `state`: the tray checkbox may have changed while this ran.
if (response.ok)
saveUsagePingState(userData, { ...loadUsagePingState(userData), ...plan.keys });
} catch {
// Offline, blocked or timed out: the next attempt tries again.
}
}
1 change: 1 addition & 0 deletions src/i18n/locales/ar/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"updateModeNotify": "إشعار عند توفر تحديث",
"updateModeDownload": "تنزيل التحديثات تلقائيًا",
"updateModeDownloadAndInstall": "تنزيل التحديثات وتثبيتها تلقائيًا",
"usagePing": "إرسال إحصاء استخدام مجهول الهوية",
"viewRelease": "عرض الإصدار",
"downloadUpdate": "تنزيل التحديث",
"restartNow": "إعادة التشغيل الآن",
Expand Down
1 change: 1 addition & 0 deletions src/i18n/locales/cs/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"updateModeNotify": "Upozornit na dostupnou aktualizaci",
"updateModeDownload": "Stahovat aktualizace automaticky",
"updateModeDownloadAndInstall": "Stahovat a instalovat aktualizace automaticky",
"usagePing": "Odesílat anonymní počet použití",
"viewRelease": "Zobrazit vydání",
"downloadUpdate": "Stáhnout aktualizaci",
"restartNow": "Restartovat nyní",
Expand Down
1 change: 1 addition & 0 deletions src/i18n/locales/de/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"updateModeNotify": "Benachrichtigen, wenn ein Update verfügbar ist",
"updateModeDownload": "Updates automatisch herunterladen",
"updateModeDownloadAndInstall": "Updates automatisch herunterladen und installieren",
"usagePing": "Anonyme Nutzungszählung senden",
"viewRelease": "Release ansehen",
"downloadUpdate": "Update herunterladen",
"restartNow": "Jetzt neu starten",
Expand Down
1 change: 1 addition & 0 deletions src/i18n/locales/en/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"updateModeNotify": "Notify when an update is available",
"updateModeDownload": "Download updates automatically",
"updateModeDownloadAndInstall": "Download and install updates automatically",
"usagePing": "Send Anonymous Usage Count",
"viewRelease": "View Release",
"downloadUpdate": "Download Update",
"restartNow": "Restart Now",
Expand Down
1 change: 1 addition & 0 deletions src/i18n/locales/es/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"updateModeNotify": "Avisar cuando haya una actualización",
"updateModeDownload": "Descargar actualizaciones automáticamente",
"updateModeDownloadAndInstall": "Descargar e instalar actualizaciones automáticamente",
"usagePing": "Enviar recuento de uso anónimo",
"viewRelease": "Ver versión",
"downloadUpdate": "Descargar actualización",
"restartNow": "Reiniciar ahora",
Expand Down
1 change: 1 addition & 0 deletions src/i18n/locales/fr/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"updateModeNotify": "Notifier lorsqu'une mise à jour est disponible",
"updateModeDownload": "Télécharger les mises à jour automatiquement",
"updateModeDownloadAndInstall": "Télécharger et installer les mises à jour automatiquement",
"usagePing": "Envoyer le comptage d'utilisation anonyme",
"viewRelease": "Voir la version",
"downloadUpdate": "Télécharger la mise à jour",
"restartNow": "Redémarrer maintenant",
Expand Down
1 change: 1 addition & 0 deletions src/i18n/locales/it/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"updateModeNotify": "Notifica quando è disponibile un aggiornamento",
"updateModeDownload": "Scarica gli aggiornamenti automaticamente",
"updateModeDownloadAndInstall": "Scarica e installa gli aggiornamenti automaticamente",
"usagePing": "Invia conteggio di utilizzo anonimo",
"viewRelease": "Visualizza versione",
"downloadUpdate": "Scarica aggiornamento",
"restartNow": "Riavvia ora",
Expand Down
Loading
Loading