Add stats collection and first-run on-glasses onboarding app

This commit is contained in:
James Babcock committed 2026-10-10 17:33:32 -07:00
1 parent 84baee9c76
commit 406cefe0c5
73 files changed
+3906 -98

No files matched your search

+29
View File
@@ -27,6 +27,35 @@ jobs:
- run: npm ci - run: npm ci
- run: npm run test:kotlin - run: npm run test:kotlin
# The stats.faceclaw.org server: typecheck, and the tests including the
# database one against a throwaway Postgres.
stats-server:
runs-on: ubuntu-latest
defaults:
run:
working-directory: stats-server
services:
postgres:
image: postgres:16
env:
POSTGRES_PASSWORD: postgres
ports: ["5432:5432"]
options: >-
--health-cmd pg_isready --health-interval 5s --health-timeout 5s --health-retries 10
env:
PGHOST: localhost
PGUSER: postgres
PGPASSWORD: postgres
STATS_TEST_DATABASE: postgres
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
- run: npm ci
- run: npm run check
- run: npm test
# The @faceclaw/evenhub-extensions npm package: typecheck (including # The @faceclaw/evenhub-extensions npm package: typecheck (including
# compatibility with the stock SDK's container classes), build, and check # compatibility with the stock SDK's container classes), build, and check
# that the committed API reference matches the source. # that the committed API reference matches the source.
@@ -507,6 +507,7 @@ class FaceclawBleManager(context: Context) {
override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
val address = gatt.device.address val address = gatt.device.address
Log.i(TAG, "onConnectionStateChange: address=$address status=$status newState=$newState") Log.i(TAG, "onConnectionStateChange: address=$address status=$status newState=$newState")
if (status != BluetoothGatt.GATT_SUCCESS) ConnectionCounters.increment("ble.gatt-status.$status")
val link = links[address] val link = links[address]
val current = link?.gatt val current = link?.gatt
if (link == null || (current != null && current !== gatt)) { if (link == null || (current != null && current !== gatt)) {
+1 -1
View File
@@ -2,7 +2,7 @@ IPHONEOS_DEPLOYMENT_TARGET = 15.1;
TARGETED_DEVICE_FAMILY = 1; TARGETED_DEVICE_FAMILY = 1;
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
// Select the local signing team in Xcode or pass --teamId to the iOS scripts. // Set IOS_TEAM_ID in build_paths.sh (or pass --teamId) to choose the signing team.
OTHER_LDFLAGS = $(inherited) -framework CoreBluetooth -framework CoreLocation -framework CoreText -framework Speech -framework AVFoundation -framework WebKit -framework UniformTypeIdentifiers -framework ImageIO -framework EventKit OTHER_LDFLAGS = $(inherited) -framework CoreBluetooth -framework CoreLocation -framework CoreText -framework Speech -framework AVFoundation -framework WebKit -framework UniformTypeIdentifiers -framework ImageIO -framework EventKit
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+3 -1
View File
@@ -4,7 +4,9 @@
* Fix several issues that would cause disconnection and disconnect-looping * Fix several issues that would cause disconnection and disconnect-looping
* Add a client for T3 Code * Add a client for T3 Code
* Weather app shows an icon for current conditions, and can add the weather to the status bar and the Glanceboard system card (Weather menu > Settings) * Weather app is more graphical, and can appear on the status bar and glanceboard Glanceboard system card
* Optional anonymous usage statistics (Settings>Privacy>Data collection; off by default)
* Add an on-glasses Onboarding app, which prompts you to configure some things
## 0.8.2 - 2026-10-03 ## 0.8.2 - 2026-10-03
+45 -5
View File
@@ -1,10 +1,50 @@
# Faceclaw Privacy Policy # Faceclaw Privacy Policy
Faceclaw is a privacy-conscious app. The developers of Faceclaw don't collect Faceclaw is a privacy-conscious app. Unless you choose to share anonymous
or store user data. Faceclaw does integrate with some third-party services, usage statistics (described below), the developers of Faceclaw don't collect
which have their own privacy policies; this document describes what those or store any data about you or how you use the app. Faceclaw does integrate
services are, what they're used for and what data they collect, and links to with some third-party services, which have their own privacy policies; this
their privacy policies. document describes what those services are, what they're used for and what
data they collect, and links to their privacy policies.
## Usage Statistics
The first time you connect your glasses, Faceclaw asks whether to share
anonymous usage statistics with its developers, to help them fix problems and
improve the app. The choices are None, Minimal and Full, and you can change
your choice at any time in Settings > Privacy. Until you choose, it is None.
With None, Faceclaw sends nothing and keeps no statistics on your phone.
With Minimal, Faceclaw keeps counts on your phone and sends them about once a
day to stats.faceclaw.org, a server run by Faceclaw's developers:
- the Faceclaw version, whether it runs on Android or iOS, and whether it is
an official release or a build someone compiled themselves;
- whether glasses and a ring are paired, and which devices (glasses, ring,
Wear OS watch) were in use each day;
- counts of connection events: connection attempts, disconnections and
their causes, message timeouts and retries, Bluetooth error codes, and
how long connections lasted.
With Full, it also sends:
- which kinds of API key are set (for example, that an Anthropic key is
set), but never the keys themselves;
- how many terminal and T3 Code connections are set up, and which of
Faceclaw's built-in fonts is in use;
- the values of settings chosen from fixed options, such as on/off
switches and pick-one lists. Settings you type in, such as addresses,
URLs and names, are never sent.
Statistics never include your name or contact details, your location,
Bluetooth device addresses, anything you say or type, or what is shown on
your glasses. Each report carries a random identifier, created when you turn
statistics on, which links your reports to each other but not to you.
Turning statistics off deletes that identifier and everything kept on the
phone, and stops all reports; turning them back on starts a new identifier.
The statistics server doesn't record the IP addresses reports come from.
## Audio ## Audio
+84
View File
@@ -0,0 +1,84 @@
/**
* The app-wide things analytics reports (the reliability counts come from
* Kotlin, drained in analytics.ts):
* - Minimal: which devices are paired, and which were in use each day;
* - Full: which kinds of API key are set, how many terminal and T3 Code
* connections there are, the UI font, and every fixed-choice setting.
* Never anything a person typed in: no keys, addresses, names or URLs.
*/
import { loadEnvironments } from "../apps/t3code/t3-environments";
import { loadConnections } from "../apps/terminal/connections";
import { loadDeviceAddresses } from "../g2/device-addresses";
import { onGlassesPresenceChanged } from "../g2/glasses-presence";
import { isPreinstalledFont } from "../graphics/installed-fonts";
import { getUiFontSelection } from "../graphics/ui-fonts";
import { getStringSetting } from "../native/settings-store";
import { isPreviewOnlyMode } from "../phone-ui/onboarding-state";
import { fixedChoiceSettingValues, ringConnectionModeSetting } from "../ui/dashboard-settings";
import { addInputListener } from "../ui/input-monitor";
import { flagAnalyticsEvent, registerAnalyticsSnapshot, startAnalytics } from "./analytics";
import type { Snapshot } from "./analytics-store";
/** Settings holding API keys and tokens, reported only as set or not, by kind. */
const API_KEY_SETTINGS: Record<string, string> = {
anthropic: "llm.anthropicApiKey",
openai: "voice.openAiApiKey",
elevenlabs: "voice.elevenLabsApiKey",
soniox: "voice.sonioxApiKey",
mapbox: "maps.mapboxApiKey",
roam: "integrations.roam.apiToken",
nightscout: "integrations.nightscout.apiToken",
"agent-bridge": "assistant.bridgeToken",
evenhub: "integrations.evenhub.token",
};
let started = false;
/** Registers the sources above and starts analytics. Main thread, at boot. */
export function startAppAnalytics(): void {
if (started) return;
started = true;
registerAnalyticsSnapshot("minimal", deviceSnapshot);
registerAnalyticsSnapshot("full", configurationSnapshot);
onGlassesPresenceChanged((presence) => {
if (presence.connected) flagAnalyticsEvent("minimal", "device.g2.used");
});
addInputListener((event) => {
if (!("source" in event)) return;
if (event.source === "ring") flagAnalyticsEvent("minimal", "device.r1.used");
else if (event.source === "left-arm" || event.source === "right-arm") flagAnalyticsEvent("minimal", "device.g2.touchpad-used");
});
startAnalytics();
}
function deviceSnapshot(): Snapshot {
const addresses = loadDeviceAddresses();
return {
"device.g2.paired": Boolean(addresses.left && addresses.right),
"device.g2.preview-only": isPreviewOnlyMode(),
"device.r1.paired": Boolean(addresses.ring),
"device.r1.connection": ringConnectionModeSetting.get(),
};
}
function configurationSnapshot(): Snapshot {
const snapshot: Snapshot = {};
for (const [kind, storageKey] of Object.entries(API_KEY_SETTINGS)) {
snapshot[`apikey.${kind}`] = getStringSetting(storageKey, "").trim() !== "";
}
snapshot["config.nightscout-site"] = getStringSetting("integrations.nightscout.siteUrl", "").trim() !== "";
snapshot["config.terminal-connections"] = loadConnections().length;
snapshot["config.t3code-environments"] = loadEnvironments().length;
const font = getUiFontSelection();
snapshot["config.ui-font"] =
font.kind === "bitmap"
? font.face
: `${isPreinstalledFont(font.file) ? font.file.replace(/\.ttf$/i, "") : "installed"}:${font.size}`;
for (const [storageKey, value] of Object.entries(fixedChoiceSettingValues())) {
snapshot[`setting.${storageKey}`] = value;
}
return snapshot;
}
+410
View File
@@ -0,0 +1,410 @@
/**
* Opt-in analytics, held on the phone between daily uploads to
* stats.faceclaw.org. This is the platform-free core: storage, clock, the
* data-collection setting and the network are passed in (analytics.ts wires
* them up), so the tests can drive it directly.
*
* Data is recorded at a level, and only while the data-collection setting is
* at that level or above:
* - "minimal": the app version and build, which devices are paired and in
* use, and connection-reliability counts;
* - "full": also API-key presence (never the keys) and settings chosen from
* fixed options.
* Turning the setting down discards what was kept above the new level;
* turning it off deletes everything, including the install id, and stops all
* writes and uploads.
*
* Counters accumulate in pending.json (per UTC day). Once a day the pending
* counters and a snapshot of the current state are sealed into an outbox
* report, and every outbox report is posted; each stays until the server
* accepts it, under a report id the server deduplicates on. The report
* format is stats-server/PROTOCOL.md.
*/
export type AnalyticsLevel = "minimal" | "full";
export type DataCollectionLevel = "none" | AnalyticsLevel;
export type SnapshotValue = boolean | number | string;
export type Snapshot = Record<string, SnapshotValue>;
export interface AppInfo {
version: string;
platform: string;
build: string;
}
/** Named text files in the analytics directory. */
export interface AnalyticsStorage {
read(name: string): string | null;
write(name: string, text: string): void;
remove(name: string): void;
list(): string[];
/** Deletes the directory and everything in it. */
removeAll(): void;
}
export interface AnalyticsDeps {
storage: AnalyticsStorage;
/** The data-collection setting, read fresh on every use. */
level(): DataCollectionLevel;
appInfo(): AppInfo;
now(): number;
randomId(): string;
/** The current state to report at `level` (each level's keys, not cumulative). */
snapshot(level: AnalyticsLevel): Snapshot;
/** POSTs a report body; resolves to the HTTP status, rejects on network failure. */
send(body: string): Promise<number>;
log?(message: string): void;
}
/** UTC day (YYYY-MM-DD) → counter name → count. */
type Counters = Record<string, Record<string, number>>;
type ByLevel<T> = { minimal: T; full: T };
interface PendingFile {
format: 1;
/** The app version the counts were made under; a different one seals them. */
version: string;
counters: ByLevel<Counters>;
}
interface OutboxReport {
format: 1;
reportId: string;
createdAt: string;
app: AppInfo;
counters: ByLevel<Counters>;
snapshot: ByLevel<Snapshot>;
}
interface StateFile {
format: 1;
installId: string;
lastSealAt: number;
/** When to retry after a failed upload; 0 when none failed. */
retryAt: number;
}
export const REPORT_SCHEMA_VERSION = 1;
export const DAY_MS = 24 * 60 * 60 * 1000;
export const RETRY_MS = 60 * 60 * 1000;
/** Unsent reports kept while the server is unreachable; the oldest go first. */
export const MAX_OUTBOX_REPORTS = 30;
/** Distinct counter names per day and level, so a runaway name can't grow the file. */
export const MAX_NAMES_PER_DAY = 300;
const FLUSH_DELAY_MS = 15_000;
const PENDING_FILE = "pending.json";
const STATE_FILE = "state.json";
const OUTBOX_PREFIX = "outbox-";
/** Counter names and snapshot keys the server accepts (stats-server/src/report.ts). */
const COUNTER_NAME = /^[a-z0-9][a-z0-9_.:-]{0,119}$/;
const SNAPSHOT_KEY = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,119}$/;
const MAX_SNAPSHOT_STRING = 200;
export class AnalyticsStore {
private pending: PendingFile | null = null;
private dirty = false;
private flushTimer: ReturnType<typeof setTimeout> | null = null;
private uploading = false;
/** Bumped by discardAll, so an upload in flight knows not to write its state back. */
private generation = 0;
constructor(private readonly deps: AnalyticsDeps) {}
/** Whether data at `level` is being kept. */
allows(level: AnalyticsLevel): boolean {
const setting = this.deps.level();
return setting === "full" || (setting === "minimal" && level === "minimal");
}
/** Adds `amount` to today's count of `name`. */
count(level: AnalyticsLevel, name: string, amount = 1): void {
if (!this.allows(level) || !(amount > 0)) return;
if (!COUNTER_NAME.test(name)) {
this.log(`analytics: dropping bad counter name ${name}`);
return;
}
const day = this.dayCounters(level);
if (day[name] === undefined && Object.keys(day).length >= MAX_NAMES_PER_DAY) return;
day[name] = (day[name] ?? 0) + Math.round(amount);
this.markDirty();
}
/** Records that `name` happened today (a count of 1, however often it happens). */
flag(level: AnalyticsLevel, name: string): void {
if (!this.allows(level)) return;
if (!COUNTER_NAME.test(name)) {
this.log(`analytics: dropping bad counter name ${name}`);
return;
}
const day = this.dayCounters(level);
if (day[name] !== undefined || Object.keys(day).length >= MAX_NAMES_PER_DAY) return;
day[name] = 1;
this.markDirty();
}
/**
* Brings the files in line with the setting: off deletes everything,
* minimal drops what was kept for full. Called at start and whenever the
* setting changes.
*/
applyLevel(): void {
const setting = this.deps.level();
if (setting === "none") {
this.discardAll();
return;
}
if (setting === "full") return;
const pending = this.loadPending();
if (Object.keys(pending.counters.full).length) {
pending.counters.full = {};
this.writePending(pending);
}
for (const name of this.outboxNames()) {
const report = this.readJson(name) as OutboxReport | null;
if (!report) continue;
if (Object.keys(report.counters.full).length || Object.keys(report.snapshot.full).length) {
report.counters.full = {};
report.snapshot.full = {};
this.deps.storage.write(name, JSON.stringify(report));
}
}
}
/** Writes pending counts now, if any changed. */
flush(): void {
if (this.flushTimer !== null) {
clearTimeout(this.flushTimer);
this.flushTimer = null;
}
if (!this.dirty || !this.pending) return;
this.dirty = false;
if (this.deps.level() === "none") {
this.discardAll();
return;
}
this.writePending(this.pending);
}
/**
* The daily upload: once a day, seal the pending counts into a report and
* post every unsent report; after a failure, retry hourly. Does nothing,
* and makes no connection, while the setting is off.
*/
async uploadIfDue(): Promise<void> {
if (this.uploading) return;
if (this.deps.level() === "none") {
this.discardAll();
return;
}
this.uploading = true;
const generation = this.generation;
try {
const now = this.deps.now();
const state = this.loadState();
let sealed = false;
// A clock set backwards shouldn't stall the schedule until it catches up.
if (now - state.lastSealAt >= DAY_MS || now < state.lastSealAt) {
this.seal();
state.lastSealAt = now;
this.writeState(state);
sealed = true;
}
if (!sealed && !(state.retryAt > 0 && now >= state.retryAt)) return;
for (const name of this.outboxNames()) {
const report = this.readJson(name) as OutboxReport | null;
if (!report) {
this.deps.storage.remove(name);
continue;
}
let status: number | null;
try {
status = await this.deps.send(this.reportBody(report, state.installId));
} catch (error) {
this.log(`analytics: upload failed: ${error}`);
status = null;
}
// The setting may have been turned off (and maybe on again) while the
// request was out; then everything this upload knew about is gone.
if (this.deps.level() === "none") {
this.discardAll();
return;
}
if (this.generation !== generation) return;
if (status !== null && status >= 200 && status < 300) {
this.deps.storage.remove(name);
} else if (status === 400 || status === 413) {
// Rejected as malformed or too large: sending it again won't help.
// (Anything else, like a 404 from a misconfigured server, is retried.)
this.log(`analytics: server rejected report ${report.reportId} (HTTP ${status})`);
this.deps.storage.remove(name);
} else {
state.retryAt = now + RETRY_MS;
this.writeState(state);
return;
}
}
if (state.retryAt !== 0) {
state.retryAt = 0;
this.writeState(state);
}
} finally {
this.uploading = false;
}
}
/** Deletes everything kept, including the install id. */
discardAll(): void {
if (this.flushTimer !== null) {
clearTimeout(this.flushTimer);
this.flushTimer = null;
}
this.pending = null;
this.dirty = false;
this.generation++;
this.deps.storage.removeAll();
}
/** The JSON body posted for `report`, including only what the current setting allows. */
reportBody(report: OutboxReport, installId: string): string {
const level: AnalyticsLevel = this.deps.level() === "full" ? "full" : "minimal";
const counters: Counters = {};
for (const source of level === "full" ? [report.counters.minimal, report.counters.full] : [report.counters.minimal]) {
for (const [day, counts] of Object.entries(source)) {
const target = (counters[day] ??= {});
for (const [name, count] of Object.entries(counts)) target[name] = (target[name] ?? 0) + count;
}
}
return JSON.stringify({
schema: REPORT_SCHEMA_VERSION,
reportId: report.reportId,
installId,
level,
createdAt: report.createdAt,
app: report.app,
counters,
snapshot: level === "full" ? { ...report.snapshot.minimal, ...report.snapshot.full } : report.snapshot.minimal,
});
}
private dayCounters(level: AnalyticsLevel): Record<string, number> {
const day = new Date(this.deps.now()).toISOString().slice(0, 10);
return (this.loadPending().counters[level][day] ??= {});
}
private markDirty(): void {
this.dirty = true;
this.flushTimer ??= setTimeout(() => {
this.flushTimer = null;
this.flush();
}, FLUSH_DELAY_MS);
}
private loadPending(): PendingFile {
if (this.pending) return this.pending;
const version = this.deps.appInfo().version;
const stored = this.readJson(PENDING_FILE) as PendingFile | null;
if (stored && stored.format === 1 && stored.counters?.minimal && stored.counters?.full) {
this.pending = stored;
if (stored.version !== version && hasCounts(stored)) {
// Counts from before an upgrade go out under the version they were made with.
this.seal();
}
}
return (this.pending ??= emptyPending(version));
}
/** Moves the pending counts, with a snapshot of the current state, into a new outbox report. */
private seal(): void {
const pending = this.loadPending();
const app = { ...this.deps.appInfo(), version: pending.version };
const report: OutboxReport = {
format: 1,
reportId: this.deps.randomId(),
createdAt: new Date(this.deps.now()).toISOString(),
app,
counters: pending.counters,
snapshot: {
minimal: this.takeSnapshot("minimal"),
full: this.allows("full") ? this.takeSnapshot("full") : {},
},
};
this.deps.storage.write(`${OUTBOX_PREFIX}${report.createdAt.replace(/[^0-9]/g, "")}-${report.reportId}.json`, JSON.stringify(report));
this.pending = emptyPending(this.deps.appInfo().version);
this.dirty = false;
this.writePending(this.pending);
const outbox = this.outboxNames();
for (const name of outbox.slice(0, Math.max(0, outbox.length - MAX_OUTBOX_REPORTS))) this.deps.storage.remove(name);
}
private takeSnapshot(level: AnalyticsLevel): Snapshot {
const snapshot: Snapshot = {};
let entries: [string, SnapshotValue][];
try {
entries = Object.entries(this.deps.snapshot(level));
} catch (error) {
this.log(`analytics: ${level} snapshot failed: ${error}`);
return snapshot;
}
for (const [key, value] of entries) {
const ok =
SNAPSHOT_KEY.test(key) &&
(typeof value === "boolean" ||
(typeof value === "number" && Number.isFinite(value)) ||
(typeof value === "string" && value.length <= MAX_SNAPSHOT_STRING));
if (ok) snapshot[key] = value;
else this.log(`analytics: dropping bad snapshot entry ${key}`);
}
return snapshot;
}
/** Outbox file names, oldest first (the names start with the seal time). */
private outboxNames(): string[] {
return this.deps.storage
.list()
.filter((name) => name.startsWith(OUTBOX_PREFIX))
.sort();
}
private loadState(): StateFile {
const stored = this.readJson(STATE_FILE) as StateFile | null;
if (stored && stored.format === 1 && typeof stored.installId === "string") return stored;
const state: StateFile = { format: 1, installId: this.deps.randomId(), lastSealAt: 0, retryAt: 0 };
this.writeState(state);
return state;
}
private writeState(state: StateFile): void {
this.deps.storage.write(STATE_FILE, JSON.stringify(state));
}
private writePending(pending: PendingFile): void {
this.deps.storage.write(PENDING_FILE, JSON.stringify(pending));
}
private readJson(name: string): unknown {
const text = this.deps.storage.read(name);
if (text === null) return null;
try {
return JSON.parse(text);
} catch {
this.log(`analytics: discarding unreadable ${name}`);
this.deps.storage.remove(name);
return null;
}
}
private log(message: string): void {
this.deps.log?.(message);
}
}
function emptyPending(version: string): PendingFile {
return { format: 1, version, counters: { minimal: {}, full: {} } };
}
function hasCounts(pending: PendingFile): boolean {
return Object.keys(pending.counters.minimal).length > 0 || Object.keys(pending.counters.full).length > 0;
}
+182
View File
@@ -0,0 +1,182 @@
/**
* The app's analytics API. What is collected, when it's kept and when it's
* sent is described in analytics-store.ts; the snapshot providers (devices,
* API-key presence, settings) are in analytics-snapshots.ts.
*
* Record from the main thread only. The store is created by startAnalytics()
* at boot, which app workers never run, so calls made in a worker are
* dropped. Kotlin-side connection events go through ConnectionCounters
* (drained here) instead.
*/
import { File, Folder, knownFolders, path as fsPath } from "@nativescript/core";
import { buildKind } from "../native/build-info";
import { drainConnectionCounters } from "../native/connection-counters";
import { onSettingsStoreChanged } from "../native/settings-store";
import { DATA_COLLECTION_KEY, dataCollectionSetting } from "../ui/dashboard-settings";
import { fetchTextWithUserAgent } from "../util/http";
import { FACECLAW_VERSION } from "../version";
import {
AnalyticsStore,
type AnalyticsLevel,
type AnalyticsStorage,
type Snapshot,
} from "./analytics-store";
export type { AnalyticsLevel, Snapshot } from "./analytics-store";
declare const global: any;
const REPORT_URL = "https://stats.faceclaw.org/v1/report";
const REQUEST_TIMEOUT_MS = 30_000;
/** How often to see whether the daily upload is due (it usually isn't). */
const UPLOAD_CHECK_INTERVAL_MS = 60 * 60 * 1000;
/** The first check, a little after boot or after analytics is turned on. */
const FIRST_UPLOAD_CHECK_DELAY_MS = 2 * 60 * 1000;
/** How often the Kotlin connection counts are moved into the store. */
const DRAIN_INTERVAL_MS = 5 * 60 * 1000;
let store: AnalyticsStore | null = null;
let firstCheckTimer: ReturnType<typeof setTimeout> | null = null;
const snapshotProviders: { level: AnalyticsLevel; provide: () => Snapshot }[] = [];
/**
* Adds `amount` to today's count of `name`, if the data-collection setting
* includes `level`. Names are lowercase, dot-separated (e.g. "g2.connect").
*/
export function countAnalyticsEvent(level: AnalyticsLevel, name: string, amount = 1): void {
store?.count(level, name, amount);
}
/** Records that `name` happened today: a count of 1 however often it happens. */
export function flagAnalyticsEvent(level: AnalyticsLevel, name: string): void {
store?.flag(level, name);
}
/**
* Adds state to report with each daily upload, when the setting includes
* `level`. Called when the report is sealed; keys must be namespaced like
* "device.g2.paired", and values booleans, numbers or short strings.
*/
export function registerAnalyticsSnapshot(level: AnalyticsLevel, provide: () => Snapshot): void {
snapshotProviders.push({ level, provide });
}
/** Starts the store, the daily upload schedule and the counter drain. Main thread, once, at boot. */
export function startAnalytics(): void {
if (store) return;
const analytics = new AnalyticsStore({
storage: createStorage(),
level: () => dataCollectionSetting.get(),
appInfo: () => ({ version: FACECLAW_VERSION, platform: global.isIOS ? "ios" : "android", build: buildKind() }),
now: () => Date.now(),
randomId: randomUuid,
snapshot: collectSnapshot,
send: sendReport,
log: (message) => console.log(message),
});
store = analytics;
analytics.applyLevel();
onSettingsStoreChanged((key) => {
if (key !== DATA_COLLECTION_KEY) return;
analytics.applyLevel();
if (dataCollectionSetting.get() !== "none") scheduleFirstCheck(analytics);
});
setInterval(() => drainKotlinCounters(analytics), DRAIN_INTERVAL_MS);
setInterval(() => void checkUpload(analytics), UPLOAD_CHECK_INTERVAL_MS);
scheduleFirstCheck(analytics);
}
function scheduleFirstCheck(analytics: AnalyticsStore): void {
if (firstCheckTimer !== null) clearTimeout(firstCheckTimer);
firstCheckTimer = setTimeout(() => {
firstCheckTimer = null;
void checkUpload(analytics);
}, FIRST_UPLOAD_CHECK_DELAY_MS);
}
async function checkUpload(analytics: AnalyticsStore): Promise<void> {
drainKotlinCounters(analytics);
try {
await analytics.uploadIfDue();
} catch (error) {
console.warn(`analytics: upload check failed: ${error}`);
}
}
function drainKotlinCounters(analytics: AnalyticsStore): void {
let counts: Record<string, number>;
try {
counts = drainConnectionCounters();
} catch (error) {
console.warn(`analytics: could not read connection counters: ${error}`);
return;
}
// Drained either way, so counts from while analytics was off don't pile up.
for (const [name, count] of Object.entries(counts)) analytics.count("minimal", name, count);
analytics.flush();
}
function collectSnapshot(level: AnalyticsLevel): Snapshot {
const snapshot: Snapshot = {};
for (const provider of snapshotProviders) {
if (provider.level !== level) continue;
try {
Object.assign(snapshot, provider.provide());
} catch (error) {
console.warn(`analytics: snapshot provider failed: ${error}`);
}
}
return snapshot;
}
async function sendReport(body: string): Promise<number> {
let timeout: ReturnType<typeof setTimeout> | undefined;
const timedOut = new Promise<never>((_resolve, reject) => {
timeout = setTimeout(() => reject(new Error("timed out")), REQUEST_TIMEOUT_MS);
});
try {
const response = await Promise.race([
fetchTextWithUserAgent(REPORT_URL, { method: "POST", headers: { "Content-Type": "application/json" }, body }),
timedOut,
]);
return response.status;
} finally {
clearTimeout(timeout);
}
}
/**
* Files in an `analytics` directory: the app's private files directory on
* Android; on iOS, Library rather than Documents, which the Files app shows.
*/
function createStorage(): AnalyticsStorage {
const base = global.isIOS ? knownFolders.ios.library().path : knownFolders.documents().path;
const dir = fsPath.join(base, "analytics");
const filePath = (name: string) => fsPath.join(dir, name);
return {
read: (name) => (File.exists(filePath(name)) ? File.fromPath(filePath(name)).readTextSync() : null),
write: (name, text) => {
Folder.fromPath(dir);
File.fromPath(filePath(name)).writeTextSync(text);
},
remove: (name) => {
if (File.exists(filePath(name))) File.fromPath(filePath(name)).removeSync();
},
list: () => (Folder.exists(dir) ? Folder.fromPath(dir).getEntitiesSync().map((entity) => entity.name) : []),
removeAll: () => {
if (Folder.exists(dir)) Folder.fromPath(dir).removeSync();
},
};
}
function randomUuid(): string {
const bytes = new Uint8Array(16);
const crypto = (globalThis as { crypto?: { getRandomValues?: (array: Uint8Array) => Uint8Array } }).crypto;
if (crypto?.getRandomValues) crypto.getRandomValues(bytes);
else for (let index = 0; index < bytes.length; index++) bytes[index] = Math.floor(Math.random() * 256);
bytes[6] = (bytes[6]! & 0x0f) | 0x40;
bytes[8] = (bytes[8]! & 0x3f) | 0x80;
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
+2
View File
@@ -26,6 +26,7 @@ import developerApp from "./developer";
import evenhubApp from "./evenhub"; import evenhubApp from "./evenhub";
import glanceboardApp from "./glanceboard"; import glanceboardApp from "./glanceboard";
import settingsApp from "./settings"; import settingsApp from "./settings";
import onboardingApp from "./onboarding";
/** /**
* Every app, in launcher-grid order (the launcher itself is first but hidden * Every app, in launcher-grid order (the launcher itself is first but hidden
@@ -60,4 +61,5 @@ export const ALL_APPS: readonly AppDefinition[] = [
evenhubApp, evenhubApp,
glanceboardApp, glanceboardApp,
settingsApp, settingsApp,
onboardingApp,
]; ];
@@ -0,0 +1,75 @@
import type { GrayImage } from "../../graphics/image";
import { truncateText } from "../../graphics/textwrap";
import { dataCollectionSetting, dataCollectionSummary, type DataCollectionLevel } from "../../ui/dashboard-settings";
import type { InputEvent } from "../../ui/gestures";
import { Menu, type MenuDrawArgs } from "../../ui/menu-core";
import { LIST_ROW_TEXT_INSET, listRowHeight } from "../../ui/metrics";
import { onboardingFont } from "./onboarding-fonts";
import { drawPageHeading, PAGE_X, type OnboardingNav, type OnboardingPage } from "./onboarding-page";
const CONTENT_GAP = 10;
const BOTTOM_MARGIN = 8;
const LABEL_GAP = 24;
/** None / Minimal / Full, each with a one-line summary; a tap saves the selected level. */
export class DataCollectionPage implements OnboardingPage {
/** Width of the level-name column, measured each paint. */
private labelColumnWidth = 0;
private readonly menu = new Menu<DataCollectionLevel>({
items: dataCollectionSetting.values,
wrap: false,
rowGap: 2,
highlight: { radius: 8 },
getHeight: () => listRowHeight(onboardingFont("body")),
draw: (args) => this.drawRow(args),
});
enter(): void {
this.menu.select(dataCollectionSetting.values.indexOf(dataCollectionSetting.get()));
}
paint(image: GrayImage, focused: boolean): void {
const top = drawPageHeading(
image,
"Data collection",
"Choose what Faceclaw may send its developers to help fix problems and improve the app. " +
"You can change this later in Settings > Privacy.",
3,
) + CONTENT_GAP;
const body = onboardingFont("body");
this.labelColumnWidth =
Math.max(...dataCollectionSetting.values.map((level) => body.measureText(dataCollectionSetting.displayValue(level)))) +
LABEL_GAP;
this.menu.paint(
image,
{ x: PAGE_X - 10, y: top, width: image.width - 2 * (PAGE_X - 10), height: image.height - top - BOTTOM_MARGIN },
focused,
);
}
handleInput(event: InputEvent, nav: OnboardingNav): void {
switch (event.type) {
case "scroll-up":
case "scroll-down":
void this.menu.handleInput(event);
return;
case "click": {
const level = this.menu.selectedItem;
if (level !== null) dataCollectionSetting.set(level);
nav.next();
return;
}
default:
return;
}
}
private drawRow({ image, item: level, x, y, width, height, selected }: MenuDrawArgs<DataCollectionLevel>): void {
const body = onboardingFont("body");
const detail = onboardingFont("detail");
image.drawText(body, x + 10, y + LIST_ROW_TEXT_INSET, dataCollectionSetting.displayValue(level), selected ? 255 : 200);
const summaryX = x + 10 + this.labelColumnWidth;
const summary = truncateText(detail, dataCollectionSummary(level), x + width - 10 - summaryX);
image.drawText(detail, summaryX, y + Math.round((height - detail.lineHeight) / 2), summary, selected ? 210 : 150);
}
}
+17
View File
@@ -0,0 +1,17 @@
import { type AppDefinition } from "../app-definition";
import { createOnboardingAppWindow, ONBOARDING_SURFACE_ID, ONBOARDING_WINDOW_ID } from "./onboarding-app";
import { ONBOARDING_APP_ID } from "./onboarding-progress";
/**
* First-run setup on the glasses: welcome, text size, data-collection
* preference. The connection controllers open it on their own when it is
* due (claimGlassesOnboardingAutoLaunch); the launcher entry reruns it.
*/
const onboardingApp: AppDefinition = {
appId: ONBOARDING_APP_ID,
title: "Onboarding",
icon: "sparkles",
launch: (ctx) => ctx.launchInProcessApp(ONBOARDING_WINDOW_ID, ONBOARDING_SURFACE_ID, createOnboardingAppWindow),
};
export default onboardingApp;
+98
View File
@@ -0,0 +1,98 @@
import { GrayImage } from "../../graphics/image";
import type { InputEvent } from "../../ui/gestures";
import type { Layer, LayerActions, LayerContext } from "../../ui/layers";
import { createInProcessWindow, type InProcessAppOptions, type InProcessWindow } from "../../ui/shell/in-process-window";
import { shell } from "../../ui/shell/shell";
import { findSoundEffect, playSoundEffect } from "../../ui/sound-effects";
import { DataCollectionPage } from "./data-collection-page";
import { markGlassesOnboardingFinished, ONBOARDING_APP_ID } from "./onboarding-progress";
import type { OnboardingPage } from "./onboarding-page";
import { TextSizePage } from "./text-size-page";
import { WelcomePage } from "./welcome-page";
export const ONBOARDING_WINDOW_ID = "onboarding";
export const ONBOARDING_SURFACE_ID = "window:onboarding";
/**
* The on-glasses onboarding: a fixed sequence of pages, opened automatically
* on the first connection after phone-side setup and after each upgrade
* (see onboarding-progress.ts), and from the launcher any time. Finishing
* the last page records this version as onboarded and closes the window;
* closing it early leaves onboarding due.
*/
export function createOnboardingAppWindow(options: InProcessAppOptions): InProcessWindow {
const pages: OnboardingPage[] = [new WelcomePage(), new TextSizePage(), new DataCollectionPage()];
const app = createInProcessWindow({
appId: ONBOARDING_APP_ID,
windowId: ONBOARDING_WINDOW_ID,
title: "Onboarding",
iconLetter: "On",
icon: "sparkles",
closeable: true,
actions: options.actions,
baseLayer: new OnboardingLayer(pages, () => {
markGlassesOnboardingFinished();
shell.closeWindow(ONBOARDING_WINDOW_ID);
}),
submitFrame: options.submitFrame,
setSurfaceVisible: options.setSurfaceVisible,
removeSurface: options.removeSurface,
reconfigureSurface: options.reconfigureSurface,
onClosed: options.onClosed,
});
playWelcomeSound(options.actions);
return app;
}
/** The celebratory jingle that greets the welcome page (formerly played on the first connection). */
function playWelcomeSound(actions: LayerActions): void {
const effect = findSoundEffect("questcomplete");
if (!effect) return;
playSoundEffect(
effect,
(payload) => actions.playBuzzerSequence(payload),
(ms) => new Promise((resolve) => setTimeout(resolve, ms)),
).catch((error) => console.warn(`onboarding welcome sound failed: ${error}`));
}
/**
* Hosts the current page. Double-click steps back a page, or leaves the app
* from the first one (the standard yield to the app switcher); every other
* gesture goes to the page.
*/
class OnboardingLayer implements Layer {
private index = 0;
constructor(
private readonly pages: readonly OnboardingPage[],
private readonly finish: () => void,
) {
pages[0]!.enter?.();
}
paint(ctx: LayerContext): GrayImage {
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
this.pages[this.index]!.paint(image, ctx.stack.isFocused());
return image;
}
async handleInput(event: InputEvent): Promise<void> {
if (event.type === "double-click") {
if (this.index === 0) shell.yieldFocusToSidebar();
else this.show(this.index - 1);
return;
}
await this.pages[this.index]!.handleInput(event, { next: () => this.next() });
}
private next(): void {
if (this.index + 1 < this.pages.length) this.show(this.index + 1);
else this.finish();
}
private show(index: number): void {
this.index = index;
this.pages[index]!.enter?.();
}
}
+38
View File
@@ -0,0 +1,38 @@
/**
* The onboarding's own fonts: bundled Roboto at fixed sizes, deliberately
* not the user's UI font, so the pages are readable before (and while) the
* text size is being chosen. Bitmap Terminus stands in where TTF rendering
* is unavailable.
*/
import { getFont, getTerminusFont } from "../../graphics/bdffont";
import type { UiFont } from "../../graphics/image";
import { ensurePreinstalledFonts, installedFontPath } from "../../graphics/installed-fonts";
import { TtfFont } from "../../graphics/ttf-font";
export type OnboardingFontRole = "hero" | "title" | "body" | "detail";
const ROLE_FONTS: Record<OnboardingFontRole, { file: string; size: number; fallback: () => UiFont }> = {
/** The welcome page's "Faceclaw". */
hero: { file: "Roboto-Regular.ttf", size: 44, fallback: () => getFont("terminus32") },
/** Page titles. */
title: { file: "Roboto-Regular.ttf", size: 26, fallback: () => getFont("terminus24") },
/** Prompts and choices. */
body: { file: "Roboto-Regular.ttf", size: 20, fallback: () => getTerminusFont(20, false) ?? getFont("terminus16") },
/** Explanations under titles and beside choices. */
detail: { file: "Roboto-Regular.ttf", size: 16, fallback: () => getFont("terminus16") },
};
let fontsEnsured = false;
export function onboardingFont(role: OnboardingFontRole): UiFont {
if (!fontsEnsured) {
fontsEnsured = true;
try {
ensurePreinstalledFonts(); // onboarding may be the first thing to draw TTF text
} catch (error) {
console.warn(`onboarding font preinstall failed: ${error}`);
}
}
const spec = ROLE_FONTS[role];
return TtfFont.load(installedFontPath(spec.file), spec.size) ?? spec.fallback();
}
+48
View File
@@ -0,0 +1,48 @@
import type { GrayImage } from "../../graphics/image";
import { wrapText } from "../../graphics/textwrap";
import type { InputEvent } from "../../ui/gestures";
import { onboardingFont } from "./onboarding-fonts";
/** Page-to-flow navigation, handed to a page's input handler. */
export type OnboardingNav = {
/** Go to the next page, or finish onboarding from the last one. */
next: () => void;
};
/**
* One onboarding step. The flow owns the page list, back navigation
* (double-click) and finishing; a page paints itself into the window's
* viewport and handles every other gesture.
*/
export interface OnboardingPage {
/** The page became current, going forward or back. */
enter?(): void;
paint(image: GrayImage, focused: boolean): void;
handleInput(event: InputEvent, nav: OnboardingNav): void | Promise<void>;
}
/** Left margin and title position shared by the pages (the UI-wide (18, 10) title spot). */
export const PAGE_X = 18;
export const TITLE_Y = 10;
/**
* Draw a page's title and its wrapped explanation (at most `maxLines`
* lines) in the onboarding fonts. Returns the y just below the explanation.
*/
export function drawPageHeading(
image: GrayImage,
title: string,
explanation: string,
maxLines = 2,
): number {
const titleFont = onboardingFont("title");
const detailFont = onboardingFont("detail");
image.drawText(titleFont, PAGE_X, TITLE_Y, title, 230);
let y = TITLE_Y + titleFont.lineHeight + 2;
const lines = wrapText(detailFont, explanation, image.width - 2 * PAGE_X).slice(0, maxLines);
for (const line of lines) {
image.drawText(detailFont, PAGE_X, y, line, 160);
y += detailFont.lineHeight;
}
return y;
}
@@ -0,0 +1,34 @@
/**
* Whether the on-glasses onboarding is due: it is recorded as finished per
* Faceclaw version, so it runs on the first connection after phone-side
* setup and again after any upgrade. The key shares the phone onboarding's
* "onboarding." prefix so scripts/resetOnboarding.sh clears it too.
*/
import { getStringSetting, setStringSetting } from "../../native/settings-store";
import { FACECLAW_VERSION } from "../../version";
export const ONBOARDING_APP_ID = "onboarding";
const FINISHED_VERSION_KEY = "onboarding.glassesFinishedVersion";
export function isGlassesOnboardingDue(): boolean {
return getStringSetting(FINISHED_VERSION_KEY, "") !== FACECLAW_VERSION;
}
export function markGlassesOnboardingFinished(): void {
setStringSetting(FINISHED_VERSION_KEY, FACECLAW_VERSION);
}
let autoLaunchChecked = false;
/**
* Asked by the connection controllers on each rendered frame (the session
* is warm by then, so the onboarding's welcome jingle won't be dropped).
* True at most once per run, and only when onboarding is due: closing it
* unfinished brings it back on the next app start, not on every reconnect.
*/
export function claimGlassesOnboardingAutoLaunch(): boolean {
if (autoLaunchChecked) return false;
autoLaunchChecked = true;
return isGlassesOnboardingDue();
}
+159
View File
@@ -0,0 +1,159 @@
import { GrayImage, type UiFont } from "../../graphics/image";
import { installedFontPath } from "../../graphics/installed-fonts";
import { wrapText } from "../../graphics/textwrap";
import { TtfFont } from "../../graphics/ttf-font";
import {
fontSelectionLabel,
getDefaultSmallFont,
getUiFontSelection,
setUiFontSelection,
uiFontSizeAllowed,
} from "../../graphics/ui-fonts";
import { FONT_SIZE_CHOICES } from "../../ui/font-picker";
import type { InputEvent } from "../../ui/gestures";
import { Menu, MENU_HIGHLIGHT_FILL, MENU_HIGHLIGHT_STROKE, type MenuBox, type MenuDrawArgs } from "../../ui/menu-core";
import { LIST_ROW_TEXT_INSET, listRowHeight } from "../../ui/metrics";
import { onboardingFont } from "./onboarding-fonts";
import { drawPageHeading, PAGE_X, type OnboardingNav, type OnboardingPage } from "./onboarding-page";
const CONTENT_GAP = 10;
const BOTTOM_MARGIN = 8;
const SIZE_COLUMN_WIDTH = 84;
const COLUMN_GAP = 12;
const PREVIEW_PADDING = 10;
const ROW_GAP = 2;
const PREVIEW_TEXT = "This is how text will look on your glasses.";
/** Drawn while they fit, so smaller sizes visibly show more rows. */
const PREVIEW_ROWS = ["Timers", "Weather", "Music", "Settings", "Files"];
/** The UI font's face, as far as this page is concerned: resizable (TTF) or not (bitmap). */
type Face =
| { kind: "sized"; file: string; path: string; sizes: number[] }
| { kind: "fixed"; label: string };
/**
* The UI font's size, over a preview of list rows and body text in the
* chosen size. The face and weight stay as they are (they live in the
* Settings font picker); a bitmap face has only one size, so the page just
* says so. The size is saved on tap, not while scrolling.
*/
export class TextSizePage implements OnboardingPage {
private face: Face = { kind: "fixed", label: "Terminus" };
private readonly sizeMenu = new Menu<number>({
wrap: false,
rowGap: ROW_GAP,
highlight: { radius: 8 },
getHeight: () => listRowHeight(onboardingFont("body")),
draw: (args) => this.drawSizeRow(args),
});
enter(): void {
// Re-read on every visit: the face may have changed in Settings meanwhile.
const selection = getUiFontSelection();
if (selection.kind === "ttf") {
const path = installedFontPath(selection.file);
const sizes = FONT_SIZE_CHOICES.filter((size) => uiFontSizeAllowed(path, size));
if (sizes.length) {
this.face = { kind: "sized", file: selection.file, path, sizes };
this.sizeMenu.setItems(sizes, nearestIndex(sizes, selection.size));
return;
}
}
// An unloadable TTF selection renders as Terminus, so call it that.
this.face = { kind: "fixed", label: selection.kind === "bitmap" ? fontSelectionLabel(selection) : "Terminus" };
}
paint(image: GrayImage, focused: boolean): void {
if (this.face.kind === "fixed") {
const top = drawPageHeading(
image,
"Text size",
`Your UI font, ${this.face.label}, comes in one size. To choose a size, pick a different font in ` +
"Settings > Customization. Tap to continue.",
3,
) + CONTENT_GAP;
drawPreview(image, getDefaultSmallFont(), {
x: PAGE_X - 10,
y: top,
width: image.width - 2 * (PAGE_X - 10),
height: image.height - top - BOTTOM_MARGIN,
});
return;
}
const top = drawPageHeading(
image,
"Text size",
"Swipe to choose a size, then tap to continue. The typeface and weight can be changed in Settings.",
) + CONTENT_GAP;
const height = image.height - top - BOTTOM_MARGIN;
const menuBox = { x: PAGE_X - 10, y: top, width: SIZE_COLUMN_WIDTH, height };
this.sizeMenu.paint(image, menuBox, focused);
const previewX = menuBox.x + menuBox.width + COLUMN_GAP;
const size = this.sizeMenu.selectedItem;
const font = (size !== null ? TtfFont.load(this.face.path, size) : null) ?? getDefaultSmallFont();
drawPreview(image, font, { x: previewX, y: top, width: image.width - (PAGE_X - 10) - previewX, height });
}
handleInput(event: InputEvent, nav: OnboardingNav): void {
switch (event.type) {
case "scroll-up":
case "scroll-down":
if (this.face.kind === "sized") void this.sizeMenu.handleInput(event);
return;
case "click":
this.save();
nav.next();
return;
default:
return;
}
}
private save(): void {
const size = this.sizeMenu.selectedItem;
if (this.face.kind !== "sized" || size === null) return;
const current = getUiFontSelection();
if (current.kind === "ttf" && current.file === this.face.file && current.size === size) return;
setUiFontSelection({ kind: "ttf", file: this.face.file, size });
}
private drawSizeRow({ image, item: size, x, y, selected }: MenuDrawArgs<number>): void {
image.drawText(onboardingFont("body"), x + 10, y + LIST_ROW_TEXT_INSET, `${size} px`, selected ? 255 : 190);
}
}
/** A framed sample in `font`: a sentence, then menu rows with the first one selected, as many as fit. */
function drawPreview(image: GrayImage, font: UiFont, box: MenuBox): void {
image.drawRoundedRect(box.x, box.y, box.width, box.height, 60, 8);
const left = box.x + PREVIEW_PADDING;
const width = box.width - 2 * PREVIEW_PADDING;
const bottom = box.y + box.height - PREVIEW_PADDING;
let y = box.y + PREVIEW_PADDING;
for (const line of wrapText(font, PREVIEW_TEXT, width)) {
if (y + font.lineHeight > bottom) return;
image.drawText(font, left, y, line, 220);
y += font.lineHeight;
}
y += PREVIEW_PADDING;
const rowHeight = listRowHeight(font);
for (let index = 0; index < PREVIEW_ROWS.length; index++) {
if (y + rowHeight - ROW_GAP > bottom) return;
const label = PREVIEW_ROWS[index]!;
if (index === 0) {
const row = new GrayImage(width, rowHeight - ROW_GAP, 0);
row.drawText(font, 10, LIST_ROW_TEXT_INSET, label, 255);
image.drawMenuSelection(row, left, y, MENU_HIGHLIGHT_FILL, MENU_HIGHLIGHT_STROKE, 8, 0);
} else {
image.drawText(font, left + 10, y + LIST_ROW_TEXT_INSET, label, 200);
}
y += rowHeight;
}
}
function nearestIndex(values: readonly number[], target: number): number {
let best = 0;
for (let index = 1; index < values.length; index++) {
if (Math.abs(values[index]! - target) < Math.abs(values[best]! - target)) best = index;
}
return best;
}
+51
View File
@@ -0,0 +1,51 @@
import type { GrayImage, UiFont } from "../../graphics/image";
import { getFullLogo } from "../../graphics/logo";
import { wrapText } from "../../graphics/textwrap";
import type { InputEvent } from "../../ui/gestures";
import { FACECLAW_VERSION } from "../../version";
import { onboardingFont } from "./onboarding-fonts";
import { PAGE_X, type OnboardingNav, type OnboardingPage } from "./onboarding-page";
const LOGO_MAX_HEIGHT = 180;
const LOGO_MARGIN = 12;
const LOGO_TEXT_GAP = 28;
const PROMPT_GAP = 22;
const PROMPT = "Tap the ring or touchpad to continue";
type TextLine = { font: UiFont; text: string; value: number; spaceBefore: number };
/** The splash: logo beside the name, version and how to go on, centred as one group. */
export class WelcomePage implements OnboardingPage {
paint(image: GrayImage): void {
const { width, height } = image;
const logo = getFullLogo(Math.min(LOGO_MAX_HEIGHT, height - 2 * LOGO_MARGIN));
const logoWidth = logo ? logo.width + LOGO_TEXT_GAP : 0;
const body = onboardingFont("body");
const lines: TextLine[] = [
{ font: onboardingFont("hero"), text: "Faceclaw", value: 240, spaceBefore: 0 },
{ font: body, text: `Version ${FACECLAW_VERSION}`, value: 150, spaceBefore: 0 },
...wrapText(body, PROMPT, width - 2 * PAGE_X - logoWidth).map((text, index) => ({
font: body,
text,
value: 215,
spaceBefore: index === 0 ? PROMPT_GAP : 0,
})),
];
const textWidth = Math.max(...lines.map((line) => line.font.measureText(line.text)));
const textHeight = lines.reduce((total, line) => total + line.spaceBefore + line.font.lineHeight, 0);
const left = Math.max(PAGE_X, Math.round((width - logoWidth - textWidth) / 2));
if (logo) {
image.bitBlt(logo, left, Math.round((height - logo.height) / 2), { transparentZero: true });
}
let y = Math.round((height - textHeight) / 2);
for (const line of lines) {
y += line.spaceBefore;
image.drawText(line.font, left + logoWidth, y, line.text, line.value);
y += line.font.lineHeight;
}
}
handleInput(event: InputEvent, nav: OnboardingNav): void {
if (event.type === "click") nav.next();
}
}
+5
View File
@@ -6,5 +6,10 @@ import { registerPhoneRotation } from './native/phone-rotation'
installNativeUserAgent() installNativeUserAgent()
registerShareIntentHandler() registerShareIntentHandler()
registerPhoneRotation() registerPhoneRotation()
// Opt-in analytics (app/analytics/), started once the app is up rather than
// loading its imports on the boot path.
Application.on(Application.launchEvent, () => {
setTimeout(() => require('./analytics/analytics-sources').startAppAnalytics(), 0)
})
Application.run({ moduleName: 'app-root' }) Application.run({ moduleName: 'app-root' })
+4
View File
@@ -4,6 +4,10 @@ declare const FaceclawConfigPort: any
// Apply transferred preferences before settings getters or app workers load. // Apply transferred preferences before settings getters or app workers load.
FaceclawConfigPort.processPendingRequest() FaceclawConfigPort.processPendingRequest()
require('./phone-ui/onboarding-register.ios') require('./phone-ui/onboarding-register.ios')
// Opt-in analytics (app/analytics/), started once the app is up.
Application.on(Application.launchEvent, () => {
setTimeout(() => require('./analytics/analytics-sources').startAppAnalytics(), 0)
})
const { hasCompletedOnboarding } = require('./phone-ui/onboarding-state') as typeof import('./phone-ui/onboarding-state') const { hasCompletedOnboarding } = require('./phone-ui/onboarding-state') as typeof import('./phone-ui/onboarding-state')
Application.run({ create: () => { Application.run({ create: () => {
const frame = new Frame() const frame = new Frame()
+8 -26
View File
@@ -45,10 +45,10 @@ const MIRROR_TOUCH_GESTURES: Record<Exclude<MirrorTouchKind, "tap">, WearRemoteI
"swipe-left": "swipe-left", "swipe-left": "swipe-left",
"swipe-right": "swipe-right", "swipe-right": "swipe-right",
}; };
import { findSoundEffect, playSoundEffect } from "../ui/sound-effects";
import { GlanceHost } from "./glance-host"; import { GlanceHost } from "./glance-host";
import { type GlanceEvent } from "./glance-state"; import { type GlanceEvent } from "./glance-state";
import { isPreviewOnlyMode, isWelcomeSoundPending, setWelcomeSoundPending } from "../phone-ui/onboarding-state"; import { isPreviewOnlyMode } from "../phone-ui/onboarding-state";
import { claimGlassesOnboardingAutoLaunch, ONBOARDING_APP_ID } from "../apps/onboarding/onboarding-progress";
import { beginRenderPass, endRenderPass } from "../util/render-freshness"; import { beginRenderPass, endRenderPass } from "../util/render-freshness";
import { voiceControlBridge } from "../native/voice-control"; import { voiceControlBridge } from "../native/voice-control";
import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage } from "../graphics/image"; import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage } from "../graphics/image";
@@ -278,9 +278,6 @@ class DashboardController {
// drop-off right after a low reading can be explained as a flat battery. // drop-off right after a low reading can be explained as a flat battery.
private lastHeadsetBattery: number | null = null; private lastHeadsetBattery: number | null = null;
private readonly listeners = new Set<DashboardListener>(); private readonly listeners = new Set<DashboardListener>();
// Set at connect time from the persisted flag; the one-time post-onboarding
// welcome sound plays on the first rendered frame (proof the session is warm).
private welcomeSoundArmed = false;
private communicator: FaceclawCommunicatorBridge | null = null; private communicator: FaceclawCommunicatorBridge | null = null;
// Headless stand-in for the compositor when no glasses are paired // Headless stand-in for the compositor when no glasses are paired
@@ -1413,7 +1410,6 @@ class DashboardController {
this.teardownPreviewDisplay(); this.teardownPreviewDisplay();
this.lastInput = "waiting..."; this.lastInput = "waiting...";
this.lastSys = "none yet"; this.lastSys = "none yet";
this.welcomeSoundArmed = isWelcomeSoundPending();
this.firmwareWarningMessage = ""; this.firmwareWarningMessage = "";
this.glassesWorn = null; this.glassesWorn = null;
this.wakeAfterChargingReconnect = false; this.wakeAfterChargingReconnect = false;
@@ -1580,11 +1576,12 @@ class DashboardController {
// parked by the previous session (or by an EvenHub suspend) resumes. // parked by the previous session (or by an EvenHub suspend) resumes.
this.resumeVoiceCapture(); this.resumeVoiceCapture();
// A rendered frame means the session is warmed up (fixedLayoutCreated), // A rendered frame means the session is warmed up (fixedLayoutCreated),
// so the buzzer won't be dropped. Play the one-time welcome sound now. // so the onboarding's welcome jingle won't be dropped. Open the
if (this.welcomeSoundArmed) { // on-glasses onboarding if this version hasn't been through it.
this.welcomeSoundArmed = false; if (claimGlassesOnboardingAutoLaunch()) {
setWelcomeSoundPending(false); this.launchApp(ONBOARDING_APP_ID).catch((error) => {
void this.playWelcomeSound(); this.appendLog(`onboarding launch failed: ${this.formatError(error)}`);
});
} }
} }
}); });
@@ -2741,21 +2738,6 @@ class DashboardController {
await this.communicator.playBuzzerSequence(payload); await this.communicator.playBuzzerSequence(payload);
} }
/** One-time celebratory jingle on the first connection after onboarding. */
private async playWelcomeSound(): Promise<void> {
const effect = findSoundEffect("questcomplete");
if (!effect) return;
try {
await playSoundEffect(
effect,
(payload) => this.playBuzzerSequence(payload),
(ms) => new Promise((resolve) => setTimeout(resolve, ms)),
);
} catch (error) {
this.appendLog(`welcome sound failed: ${this.formatError(error)}`);
}
}
private clearDashboardTimer(): void { private clearDashboardTimer(): void {
this.cancelEvenHubSuspendTimer(); this.cancelEvenHubSuspendTimer();
if (this.shellRefreshTimer) { if (this.shellRefreshTimer) {
+8 -12
View File
@@ -48,8 +48,7 @@ import { DISPLAY_MODE_VALUES, displayModeLabel, displayModeSetting, onAnySetting
previewColorSetting, lockScreenEnabledSetting, getBrightnessPreferences, getStringSettingById, previewColorSetting, lockScreenEnabledSetting, getBrightnessPreferences, getStringSettingById,
nightscoutSiteUrlSetting, nightscoutApiTokenSetting } from '../ui/dashboard-settings' nightscoutSiteUrlSetting, nightscoutApiTokenSetting } from '../ui/dashboard-settings'
import type { PhoneGesture } from '../phone-ui/phone-gestures' import type { PhoneGesture } from '../phone-ui/phone-gestures'
import { isWelcomeSoundPending, setWelcomeSoundPending } from '../phone-ui/onboarding-state' import { claimGlassesOnboardingAutoLaunch, ONBOARDING_APP_ID } from '../apps/onboarding/onboarding-progress'
import { findSoundEffect, playSoundEffect } from '../ui/sound-effects'
const SHELL_SURFACE_ID = 'shell' const SHELL_SURFACE_ID = 'shell'
const SHELL_SURFACE_Z_ORDER = 1 const SHELL_SURFACE_Z_ORDER = 1
@@ -681,7 +680,7 @@ export class IosPreviewController {
private emitState(): void { private emitState(): void {
if (this.state.phase !== 'connected') resetRingInputFilter() if (this.state.phase !== 'connected') resetRingInputFilter()
this.pushBrightness() this.pushBrightness()
this.maybePlayWelcomeSound(this.state) this.maybeLaunchOnboarding(this.state)
if (this.state.phase !== 'connected' && this.state.phase !== 'connecting') this.glassesWorn = null if (this.state.phase !== 'connected' && this.state.phase !== 'connecting') this.glassesWorn = null
if (this.state.phase !== 'connected') iosVoiceInput.handleSessionEnded() if (this.state.phase !== 'connected') iosVoiceInput.handleSessionEnded()
shell.setBatteryLevels({ headset: this.state.battery, headsetCharging: this.state.charging }) shell.setBatteryLevels({ headset: this.state.battery, headsetCharging: this.state.charging })
@@ -770,7 +769,7 @@ export class IosPreviewController {
if (this.communicator !== communicator) return if (this.communicator !== communicator) return
this.state = { ...this.state, frames: this.state.frames + 1 } this.state = { ...this.state, frames: this.state.frames + 1 }
this.onActivity() this.onActivity()
this.maybePlayWelcomeSound(this.state) this.maybeLaunchOnboarding(this.state)
if (this.active) this.onConnectionState({ ...this.state }) if (this.active) this.onConnectionState({ ...this.state })
this.schedulePreviewUpdate() this.schedulePreviewUpdate()
}), }),
@@ -878,16 +877,13 @@ export class IosPreviewController {
this.glance.reset() this.glance.reset()
await communicator.close().catch(error => this.logBluetooth(`Close: ${String(error)}`)) await communicator.close().catch(error => this.logBluetooth(`Close: ${String(error)}`))
} }
private maybePlayWelcomeSound(state: SessionState): void { private maybeLaunchOnboarding(state: SessionState): void {
const firstNewFrame = state.frames > this.acknowledgedFrames const firstNewFrame = state.frames > this.acknowledgedFrames
this.acknowledgedFrames = state.frames this.acknowledgedFrames = state.frames
// Match Android: wait for an acknowledged frame before consuming the jingle. // Match Android: wait for an acknowledged frame (a warm session, so the
if (!firstNewFrame || state.phase !== 'connected' || !isWelcomeSoundPending()) return // onboarding's welcome jingle isn't dropped) before opening it.
setWelcomeSoundPending(false) if (!firstNewFrame || state.phase !== 'connected' || !claimGlassesOnboardingAutoLaunch()) return
const effect = findSoundEffect('questcomplete') void this.launchApp(ONBOARDING_APP_ID)
if (effect) void playSoundEffect(effect, payload => this.actions.playBuzzerSequence(payload),
ms => new Promise(resolve => setTimeout(resolve, ms)))
.catch(error => this.logBluetooth(`Welcome sound failed: ${error}`))
} }
startVoiceInput(): void { if (!this.glassesLocked) shell.startVoiceInput() } startVoiceInput(): void { if (!this.glassesLocked) shell.startVoiceInput() }
private async prepareVoiceCapture(): Promise<boolean> { private async prepareVoiceCapture(): Promise<boolean> {
+3
View File
@@ -23,6 +23,7 @@
* Transport is app/native/wear-bridge.ts (Java FaceclawWearBridge); the * Transport is app/native/wear-bridge.ts (Java FaceclawWearBridge); the
* message shapes are documented in wear/PROTOCOL.md. * message shapes are documented in wear/PROTOCOL.md.
*/ */
import { flagAnalyticsEvent } from "../analytics/analytics";
import { type AppDefinition } from "../apps/app-definition"; import { type AppDefinition } from "../apps/app-definition";
import { getInstalledEvenHubApps, installedEvenHubAppId } from "../apps/evenhub/installed-apps"; import { getInstalledEvenHubApps, installedEvenHubAppId } from "../apps/evenhub/installed-apps";
import { WEAR_PATHS, wearBridge, type WearMessage } from "../native/wear-bridge"; import { WEAR_PATHS, wearBridge, type WearMessage } from "../native/wear-bridge";
@@ -167,6 +168,7 @@ export class WearRemote {
// with it (no placeholder). // with it (no placeholder).
if (changed) this.watchBatteryPollsUnanswered = 0; if (changed) this.watchBatteryPollsUnanswered = 0;
if (connection.reachable) { if (connection.reachable) {
flagAnalyticsEvent("minimal", "device.wear.reachable");
this.publishNow(true); this.publishNow(true);
this.pollWatchBattery(true); this.pollWatchBattery(true);
} else if (changed) { } else if (changed) {
@@ -326,6 +328,7 @@ export class WearRemote {
return; return;
} }
flagAnalyticsEvent("minimal", "device.wear.used");
switch (message.path) { switch (message.path) {
case WEAR_PATHS.input: case WEAR_PATHS.input:
await this.handleInput(message.payload, ack); await this.handleInput(message.payload, ack);
+2
View File
@@ -76,6 +76,8 @@ export const ICON_SVGS = {
'<svg viewBox="0 0 24 24" fill="none"><path d="M14 2v6a2 2 0 0 0 .245.96l5.51 10.08A2 2 0 0 1 18 22H6a2 2 0 0 1-1.755-2.96l5.51-10.08A2 2 0 0 0 10 8V2"/><path d="M6.453 15h11.094"/><path d="M8.5 2h7"/></svg>', '<svg viewBox="0 0 24 24" fill="none"><path d="M14 2v6a2 2 0 0 0 .245.96l5.51 10.08A2 2 0 0 1 18 22H6a2 2 0 0 1-1.755-2.96l5.51-10.08A2 2 0 0 0 10 8V2"/><path d="M6.453 15h11.094"/><path d="M8.5 2h7"/></svg>',
wrench: wrench:
'<svg viewBox="0 0 24 24" fill="none"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>', '<svg viewBox="0 0 24 24" fill="none"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>',
sparkles:
'<svg viewBox="0 0 24 24" fill="none"><path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/><path d="M5 3v4"/><path d="M19 17v4"/><path d="M3 5h4"/><path d="M17 19h4"/></svg>',
settings: settings:
'<svg viewBox="0 0 24 24" fill="none"><path d="M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"/><circle cx="12" cy="12" r="3"/></svg>', '<svg viewBox="0 0 24 24" fill="none"><path d="M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"/><circle cx="12" cy="12" r="3"/></svg>',
mic: mic:
+8 -2
View File
@@ -6,7 +6,12 @@ declare const interop: any;
const UPNG = require("upng-js"); const UPNG = require("upng-js");
export function loadPngAsGrayImage(path: string): GrayImage { /**
* Decode a PNG to grayscale, premultiplied by alpha so transparency reads as
* black. With `invert`, the PNG is dark art on a light or transparent ground
* (e.g. the phone-side logo) and its ink is drawn white instead.
*/
export function loadPngAsGrayImage(path: string, options: { invert?: boolean } = {}): GrayImage {
const file = resolveFile(path); const file = resolveFile(path);
const raw = file.readSync(); const raw = file.readSync();
const pngBuffer = toArrayBuffer(raw); const pngBuffer = toArrayBuffer(raw);
@@ -25,7 +30,8 @@ export function loadPngAsGrayImage(path: string): GrayImage {
const g = rgba[offset + 1] ?? 0; const g = rgba[offset + 1] ?? 0;
const b = rgba[offset + 2] ?? 0; const b = rgba[offset + 2] ?? 0;
const a = (rgba[offset + 3] ?? 0) / 255; const a = (rgba[offset + 3] ?? 0) / 255;
const gray = Math.round((0.2126 * r + 0.7152 * g + 0.0722 * b) * a); const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
const gray = Math.round((options.invert ? 255 - luminance : luminance) * a);
image.pixels[y * decoded.width + x] = gray; image.pixels[y * decoded.width + x] = gray;
} }
} }
+5
View File
@@ -44,6 +44,11 @@ export type InstalledFont = {
monospace: boolean; monospace: boolean;
}; };
/** Whether `fileName` is one of the fonts the app ships, rather than one the user installed. */
export function isPreinstalledFont(fileName: string): boolean {
return (PREINSTALLED_FONT_FILES as readonly string[]).includes(fileName);
}
/** The app-internal fonts directory (created on first use). */ /** The app-internal fonts directory (created on first use). */
export function installedFontsDir(): string { export function installedFontsDir(): string {
return knownFolders.documents().getFolder("fonts").path; return knownFolders.documents().getFolder("fonts").path;
+54
View File
@@ -14,3 +14,57 @@ export function getDashboardLogo(): GrayImage | null {
} }
return cachedDashboardLogo; return cachedDashboardLogo;
} }
const FULL_LOGO_PATH = "images/faceclaw-logo.png";
let fullLogoSource: GrayImage | null | undefined;
const scaledFullLogos = new Map<number, GrayImage>();
/**
* The full Faceclaw logo (the lobster over the smiley face), white on black,
* scaled to `height` pixels tall for splash screens. The source is the phone
* UI's black-on-transparent PNG, inverted, and area-averaged down so the
* edges stay antialiased.
*/
export function getFullLogo(height: number): GrayImage | null {
const targetHeight = Math.max(1, Math.round(height));
const cached = scaledFullLogos.get(targetHeight);
if (cached) return cached;
if (fullLogoSource === undefined) {
try {
fullLogoSource = loadPngAsGrayImage(FULL_LOGO_PATH, { invert: true });
} catch (error) {
console.warn(`Could not load ${FULL_LOGO_PATH}: ${error}`);
fullLogoSource = null;
}
}
if (!fullLogoSource) return null;
const scale = Math.min(1, targetHeight / fullLogoSource.height);
const scaled = downscaleArea(
fullLogoSource,
Math.max(1, Math.round(fullLogoSource.width * scale)),
Math.max(1, Math.round(fullLogoSource.height * scale)),
);
scaledFullLogos.set(targetHeight, scaled);
return scaled;
}
/** Box-filter downscale: each output pixel averages the source pixels it covers. */
function downscaleArea(source: GrayImage, width: number, height: number): GrayImage {
if (width === source.width && height === source.height) return source;
const output = new GrayImage(width, height, 0);
for (let y = 0; y < height; y++) {
const y0 = Math.floor((y * source.height) / height);
const y1 = Math.max(y0 + 1, Math.floor(((y + 1) * source.height) / height));
for (let x = 0; x < width; x++) {
const x0 = Math.floor((x * source.width) / width);
const x1 = Math.max(x0 + 1, Math.floor(((x + 1) * source.width) / width));
let sum = 0;
for (let sy = y0; sy < y1; sy++) {
const row = sy * source.width;
for (let sx = x0; sx < x1; sx++) sum += source.pixels[row + sx]!;
}
output.pixels[y * width + x] = Math.round(sum / ((y1 - y0) * (x1 - x0)));
}
}
return output;
}
+19
View File
@@ -0,0 +1,19 @@
import type { BuildKind } from './build-info'
declare const NSBundle: any
declare const NSProcessInfo: any
let cached: BuildKind | null = null
/**
* App Store (and TestFlight) builds carry no provisioning profile; anything
* installed from Xcode or as an ad hoc build does. Simulator builds have none
* either, so they're recognized by the simulator's environment.
*/
export function buildKind(): BuildKind {
if (cached) return cached
if (NSProcessInfo.processInfo.environment.objectForKey('SIMULATOR_DEVICE_NAME')) cached = 'debug'
else if (NSBundle.mainBundle.pathForResourceOfType('embedded', 'mobileprovision')) cached = 'self-built'
else cached = 'official'
return cached
}
+54
View File
@@ -0,0 +1,54 @@
/**
* Which kind of build this is, for analytics: an official release, or one
* compiled by somebody else. Official releases are signed with the key
* scripts/release.sh uses; anything else was built by whoever installed it.
*/
import { Utils } from "@nativescript/core";
declare const android: any;
declare const java: any;
/**
* `debug` is a debuggable build (build.sh / build_and_run.sh); `self-built`
* is a release build signed with someone else's key.
*/
export type BuildKind = "official" | "self-built" | "debug" | "unknown";
/** SHA-256 of the release signing certificate (`apksigner verify --print-certs dist/Faceclaw-*.apk`). */
const OFFICIAL_SIGNING_CERT_SHA256 = "c1efe42d74f3fc4e9a13bcfc8c99e018344a55525e5b300fa960c89431e382ad";
let cached: BuildKind | null = null;
export function buildKind(): BuildKind {
cached ??= detectBuildKind();
return cached;
}
function detectBuildKind(): BuildKind {
try {
const context = Utils.android.getApplicationContext();
const packageManager = context.getPackageManager();
const PackageManager = android.content.pm.PackageManager;
const signatures =
android.os.Build.VERSION.SDK_INT >= 28
? packageManager
.getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNING_CERTIFICATES)
.signingInfo.getApkContentsSigners()
: packageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES).signatures;
for (let index = 0; index < signatures.length; index++) {
const digest = java.security.MessageDigest.getInstance("SHA-256").digest(signatures[index].toByteArray());
if (hex(digest) === OFFICIAL_SIGNING_CERT_SHA256) return "official";
}
const debuggable = (context.getApplicationInfo().flags & android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE) !== 0;
return debuggable ? "debug" : "self-built";
} catch (error) {
console.warn(`build-info: could not read the signing certificate: ${error}`);
return "unknown";
}
}
function hex(bytes: any): string {
let text = "";
for (let index = 0; index < bytes.length; index++) text += ((bytes[index] & 0xff) + 0x100).toString(16).slice(1);
return text;
}
+10
View File
@@ -0,0 +1,10 @@
declare const FaceclawKitConnectionCounters: any
export function drainConnectionCounters(): Record<string, number> {
const counts: Record<string, number> = {}
const parsed = JSON.parse(String(FaceclawKitConnectionCounters.shared.drain())) as Record<string, unknown>
for (const [name, count] of Object.entries(parsed)) {
if (typeof count === 'number' && count > 0) counts[name] = count
}
return counts
}
+14
View File
@@ -0,0 +1,14 @@
declare const com: any;
/**
* Connection-reliability event counts since the last call, from the shared
* Kotlin session core (ConnectionCounters.kt), which keeps them process-wide.
*/
export function drainConnectionCounters(): Record<string, number> {
const counts: Record<string, number> = {};
const parsed = JSON.parse(String(com.faceclaw.app.ConnectionCounters.drain())) as Record<string, unknown>;
for (const [name, count] of Object.entries(parsed)) {
if (typeof count === "number" && count > 0) counts[name] = count;
}
return counts;
}
+4 -19
View File
@@ -2,32 +2,17 @@ import { ApplicationSettings } from "@nativescript/core";
const ONBOARDING_COMPLETE_KEY = "onboarding.complete"; const ONBOARDING_COMPLETE_KEY = "onboarding.complete";
const PREVIEW_ONLY_KEY = "onboarding.previewOnly"; const PREVIEW_ONLY_KEY = "onboarding.previewOnly";
const WELCOME_SOUND_PENDING_KEY = "onboarding.welcomeSoundPending";
export function hasCompletedOnboarding(): boolean { export function hasCompletedOnboarding(): boolean {
return ApplicationSettings.getBoolean(ONBOARDING_COMPLETE_KEY, false); return ApplicationSettings.getBoolean(ONBOARDING_COMPLETE_KEY, false);
} }
export function setOnboardingCompleted(completed: boolean): void {
const wasCompleted = hasCompletedOnboarding();
ApplicationSettings.setBoolean(ONBOARDING_COMPLETE_KEY, completed);
// Arm the one-time welcome sound on the first-ever completion (not on the
// idempotent re-completions that happen when installing from the main menu).
if (completed && !wasCompleted) {
setWelcomeSoundPending(true);
}
}
/** /**
* True when onboarding just completed and the celebratory sound hasn't played * Phone-side onboarding. The on-glasses onboarding that follows it on the
* yet. Consumed (and cleared) on the first successful glasses connection. * first connection is tracked separately (app/apps/onboarding/).
*/ */
export function isWelcomeSoundPending(): boolean { export function setOnboardingCompleted(completed: boolean): void {
return ApplicationSettings.getBoolean(WELCOME_SOUND_PENDING_KEY, false); ApplicationSettings.setBoolean(ONBOARDING_COMPLETE_KEY, completed);
}
export function setWelcomeSoundPending(pending: boolean): void {
ApplicationSettings.setBoolean(WELCOME_SOUND_PENDING_KEY, pending);
} }
/** /**
+62
View File
@@ -23,6 +23,7 @@ import { MENU_ANIMATION_KEY } from "./menu-animation-pref";
import { LIST_ROW_TEXT_INSET, lineStep } from "./metrics"; import { LIST_ROW_TEXT_INSET, lineStep } from "./metrics";
import { Layer, type LayerContext } from "./layers"; import { Layer, type LayerContext } from "./layers";
import { GrayImage } from "~/graphics/image"; import { GrayImage } from "~/graphics/image";
import type { DataCollectionLevel } from "../analytics/analytics-store";
export type NightscoutSettings = { export type NightscoutSettings = {
siteUrl: string; siteUrl: string;
@@ -47,6 +48,11 @@ type ConfigSettingOptions<TValue, TId extends string> = {
formatValue?: (value: TValue) => string; formatValue?: (value: TValue) => string;
/** Extended description shown in the Settings panel when the row is selected. */ /** Extended description shown in the Settings panel when the row is selected. */
description?: string; description?: string;
/**
* Boolean and enum settings only take fixed values, so Full analytics
* reports them (fixedChoiceSettingValues); false keeps this one out.
*/
reportInAnalytics?: boolean;
}; };
// Fired after any setting changes, in any isolate (storage lives in the Java // Fired after any setting changes, in any isolate (storage lives in the Java
@@ -74,6 +80,21 @@ onSettingsStoreChanged(() => {
}, 0); }, 0);
}); });
// Boolean and enum settings by storage key, for fixedChoiceSettingValues.
// Settings built repeatedly (per-app or per-slot) just replace themselves.
const fixedChoiceSettings = new Map<string, ConfigSetting<boolean> | ConfigSetting<string>>();
/**
* The current value of every boolean and enum setting this isolate has
* loaded, keyed by storage key: what Full analytics reports as settings.
* Free-text settings never appear.
*/
export function fixedChoiceSettingValues(): Record<string, boolean | string> {
const values: Record<string, boolean | string> = {};
for (const [storageKey, setting] of fixedChoiceSettings) values[storageKey] = setting.get();
return values;
}
export abstract class ConfigSetting<TValue, TId extends string = string> { export abstract class ConfigSetting<TValue, TId extends string = string> {
readonly id: TId; readonly id: TId;
readonly label: string; readonly label: string;
@@ -104,6 +125,7 @@ export class ConfigSettingBoolean<TId extends string = string> extends ConfigSet
// Widens ConfigSetting's protected constructor. // Widens ConfigSetting's protected constructor.
public constructor(options: ConfigSettingOptions<boolean, TId>) { public constructor(options: ConfigSettingOptions<boolean, TId>) {
super(options); super(options);
if (options.reportInAnalytics !== false) fixedChoiceSettings.set(options.storageKey, this);
} }
get(): boolean { get(): boolean {
@@ -134,6 +156,7 @@ export class ConfigSettingEnum<TValue extends string, TId extends string = strin
constructor(options: ConfigSettingEnumOptions<TValue, TId>) { constructor(options: ConfigSettingEnumOptions<TValue, TId>) {
super(options); super(options);
if (options.reportInAnalytics !== false) fixedChoiceSettings.set(options.storageKey, this);
this.values = options.values; this.values = options.values;
this.disabledPredicate = options.isDisabled ?? (() => false); this.disabledPredicate = options.isDisabled ?? (() => false);
if (options.normalize) { if (options.normalize) {
@@ -660,6 +683,45 @@ export const navigateVerticalPositionSetting = appVerticalPositionSetting("navig
export const terminalDisplayModeSetting = appDisplayModeSetting("terminal", "default"); export const terminalDisplayModeSetting = appDisplayModeSetting("terminal", "default");
export const terminalVerticalPositionSetting = appVerticalPositionSetting("terminal"); export const terminalVerticalPositionSetting = appVerticalPositionSetting("terminal");
export type { DataCollectionLevel };
/** The data-collection setting's key, for observers (app/analytics/analytics.ts). */
export const DATA_COLLECTION_KEY = "privacy.dataCollection";
const DATA_COLLECTION_LABELS: Record<DataCollectionLevel, string> = {
none: "None",
minimal: "Minimal",
full: "Full",
};
// What each level collects is set out in app/analytics/analytics-store.ts and
// the privacy policy (PRIVACY); keep these in step with both.
const DATA_COLLECTION_SUMMARIES: Record<DataCollectionLevel, string> = {
none: "Send nothing",
minimal: "Version, devices, connection reliability",
full: "Also settings and API-key presence",
};
/** One-line summary of what a data-collection level sends (onboarding, settings). */
export function dataCollectionSummary(level: DataCollectionLevel): string {
return DATA_COLLECTION_SUMMARIES[level];
}
/** Chosen in the on-glasses onboarding; changeable in Settings > Privacy. */
export const dataCollectionSetting = new ConfigSettingEnum<DataCollectionLevel>({
id: "data-collection",
label: "Data collection",
storageKey: DATA_COLLECTION_KEY,
defaultValue: "none",
values: ["none", "minimal", "full"],
formatValue: (value) => DATA_COLLECTION_LABELS[value],
description:
"Anonymous statistics Faceclaw may send its developers once a day, to help fix problems and improve the " +
"app. None: send nothing, and keep nothing on the phone. Minimal: the app version, which devices are " +
"paired and in use, and how reliable the connection to them is. Full: also settings chosen from fixed " +
"options, and which kinds of API key are set (never the keys themselves).",
});
export const voiceControlEnabledSetting = new ConfigSettingBoolean({ export const voiceControlEnabledSetting = new ConfigSettingBoolean({
id: "voice-control-enabled", id: "voice-control-enabled",
label: "Enable", label: "Enable",
+8
View File
@@ -45,6 +45,7 @@ import {
autoBrightnessMinSetting, autoBrightnessMinSetting,
autoBrightnessMaxSetting, autoBrightnessMaxSetting,
autoBrightnessCurveSetting, autoBrightnessCurveSetting,
dataCollectionSetting,
glassesBatteryVisibilitySetting, glassesBatteryVisibilitySetting,
phoneBatteryVisibilitySetting, phoneBatteryVisibilitySetting,
ringBatteryVisibilitySetting, ringBatteryVisibilitySetting,
@@ -191,6 +192,13 @@ function settingsSections(): SettingsSection[] {
toggleSettingMenuItem(showBleBandwidthSetting), toggleSettingMenuItem(showBleBandwidthSetting),
], ],
}, },
{
label: "Privacy",
items: [
// First chosen in the on-glasses onboarding (app/apps/onboarding/).
enumSettingMenuItem(dataCollectionSetting),
],
},
{ {
label: "About", label: "About",
// The version/license blurb (renderDetail) draws above the bundled // The version/license blurb (renderDetail) draws above the bundled
+5 -4
View File
@@ -31,7 +31,8 @@ import { Menu, type MenuDrawArgs } from "./menu-core";
import { LIST_ROW_TEXT_INSET, listRowHeight } from "./metrics"; import { LIST_ROW_TEXT_INSET, listRowHeight } from "./metrics";
import type { Layer, LayerContext } from "./layers"; import type { Layer, LayerContext } from "./layers";
const SIZE_CHOICES = [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 24, 26, 28] as const; /** Pixel sizes offered for TTF faces (also by the onboarding's text-size page). */
export const FONT_SIZE_CHOICES = [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 24, 26, 28] as const;
const DEFAULT_TTF_SIZE = 16; const DEFAULT_TTF_SIZE = 16;
const PREVIEW_TEXT = "The quick brown fox jumps over 0123456789"; const PREVIEW_TEXT = "The quick brown fox jumps over 0123456789";
const INHERIT_UI_FONT_LABEL = "Same as UI font"; const INHERIT_UI_FONT_LABEL = "Same as UI font";
@@ -279,7 +280,7 @@ export class FontPickerLayer implements Layer {
const allowed = this.options.sizeAllowed; const allowed = this.options.sizeAllowed;
if (!allowed || allowed(font.path, size)) return size; if (!allowed || allowed(font.path, size)) return size;
let best = -1; let best = -1;
for (const candidate of SIZE_CHOICES) { for (const candidate of FONT_SIZE_CHOICES) {
if (!allowed(font.path, candidate)) continue; if (!allowed(font.path, candidate)) continue;
if (best < 0 || Math.abs(candidate - size) < Math.abs(best - size)) best = candidate; if (best < 0 || Math.abs(candidate - size) < Math.abs(best - size)) best = candidate;
} }
@@ -302,7 +303,7 @@ export class FontPickerLayer implements Layer {
private openSizeMenu(ctx: LayerContext): void { private openSizeMenu(ctx: LayerContext): void {
if (this.draft.kind !== "ttf") return; if (this.draft.kind !== "ttf") return;
const draft = this.draft; const draft = this.draft;
const sizes = SIZE_CHOICES.filter((size) => const sizes = FONT_SIZE_CHOICES.filter((size) =>
this.options.sizeAllowed === undefined || this.options.sizeAllowed(draft.font.path, size), this.options.sizeAllowed === undefined || this.options.sizeAllowed(draft.font.path, size),
); );
const items = sizes.map((size): MenuItem => ({ const items = sizes.map((size): MenuItem => ({
@@ -312,7 +313,7 @@ export class FontPickerLayer implements Layer {
innerCtx.stack.pop(); innerCtx.stack.pop();
}, },
})); }));
openModalMenu(ctx, "Size", items, Math.max(0, sizes.indexOf(draft.size as (typeof SIZE_CHOICES)[number]))); openModalMenu(ctx, "Size", items, Math.max(0, sizes.indexOf(draft.size as (typeof FONT_SIZE_CHOICES)[number])));
} }
} }
+2
View File
@@ -6,4 +6,6 @@
#export PATH= #export PATH=
#export ANDROID_KEYSTORE= #export ANDROID_KEYSTORE=
#export DEVICE_ID= #export DEVICE_ID=
# Apple signing team for iOS device builds (Xcode > Settings > Accounts)
#export IOS_TEAM_ID=
@@ -0,0 +1,44 @@
package com.faceclaw.app
import kotlin.jvm.JvmStatic
/**
* Process-wide counts of connection-reliability events: connect attempts,
* transport failures by reason, ack timeouts, CFW replays, arm drops, how long
* sessions lasted, and the like. The phone app's analytics drains them
* (app/native/connection-counters.ts, app/analytics/). Only counts under fixed
* event names are kept, never addresses or message contents. They pile up in
* memory whether or not analytics is on; the app throws a drain away when it
* is off.
*/
object ConnectionCounters {
/** Distinct names kept between drains; new names past this are dropped. */
private const val MAX_NAMES = 200
private val lock = protocolPlatform().createLock()
private var counts = LinkedHashMap<String, Long>()
@JvmStatic
fun increment(name: String) {
lock.withLock {
val current = counts[name]
if (current != null) counts[name] = current + 1
else if (counts.size < MAX_NAMES) counts[name] = 1
}
}
/** The counts since the last drain, as a JSON object of name to count, and starts over. */
@JvmStatic
fun drain(): String {
val drained = lock.withLock {
val out = counts
counts = LinkedHashMap()
out
}
return Json.write(drained)
}
/** An event name from fixed text: "CFW recovery retry limit" -> "cfw-recovery-retry-limit". */
@JvmStatic
fun slug(text: String): String = text.lowercase().replace(Regex("[^a-z0-9]+"), "-").trim('-').take(60)
}
@@ -359,6 +359,7 @@ internal fun GlassesSessionCore.firstUnpairedArm(): String? {
*/ */
internal fun GlassesSessionCore.handleUnpairedFailure(address: String) { internal fun GlassesSessionCore.handleUnpairedFailure(address: String) {
logError("Connect failed and $address is not paired; suspending reconnect") logError("Connect failed and $address is not paired; suspending reconnect")
ConnectionCounters.increment("g2.unpaired")
monitor.withLock { haltReconnectLocked("arm not paired: $address") } monitor.withLock { haltReconnectLocked("arm not paired: $address") }
if (!userDisconnectRequested) { if (!userDisconnectRequested) {
setStateDisplay( setStateDisplay(
@@ -387,6 +388,7 @@ internal fun GlassesSessionCore.handleIncompatibleFirmware() {
incompatibleFirmware = null incompatibleFirmware = null
pending pending
} ?: return } ?: return
ConnectionCounters.increment("g2.incompatible-firmware")
logError("Glasses report incompatible firmware L=" + info.leftVersion + " R=" + info.rightVersion logError("Glasses report incompatible firmware L=" + info.leftVersion + " R=" + info.rightVersion
+ " ext=\"" + info.extension + "\" (need Faceclaw/" + requiredFirmwareRevision + "); suspending reconnect") + " ext=\"" + info.extension + "\" (need Faceclaw/" + requiredFirmwareRevision + "); suspending reconnect")
monitor.withLock { haltReconnectLocked("incompatible firmware") } monitor.withLock { haltReconnectLocked("incompatible firmware") }
@@ -429,11 +431,13 @@ internal fun GlassesSessionCore.haltReconnectLocked(reason: String) {
*/ */
internal fun GlassesSessionCore.handleTransportFailure(reason: String?, displayStatus: String? = null) { internal fun GlassesSessionCore.handleTransportFailure(reason: String?, displayStatus: String? = null) {
logError("Transport failure: $reason") logError("Transport failure: $reason")
ConnectionCounters.increment("g2.failure." + ConnectionCounters.slug(reason ?: "unknown"))
val retryDelayMs: Long val retryDelayMs: Long
monitor.withLock { monitor.withLock {
maybeEmitEvenAppConflictLocked(reason) maybeEmitEvenAppConflictLocked(reason)
finishBenchmarkLocked(true, "transport failure") finishBenchmarkLocked(true, "transport failure")
val sessionWasReady = sessionReady val sessionWasReady = sessionReady
if (sessionWasReady) countSessionEnded("failure")
sessionReady = false sessionReady = false
fixedLayoutCreated = false fixedLayoutCreated = false
startupProbePending = false startupProbePending = false
@@ -460,6 +464,23 @@ internal fun GlassesSessionCore.handleTransportFailure(reason: String?, displayS
interruptibleSleep.interrupt() interruptibleSleep.interrupt()
} }
/**
* Counts a ready session ending, by [cause] and by how long it had been up
* (for the analytics in app/analytics/).
*/
internal fun GlassesSessionCore.countSessionEnded(cause: String) {
ConnectionCounters.increment("g2.session-end.$cause")
val minutes = (now() - lastSessionReadyAtMs) / 60_000
ConnectionCounters.increment(
"g2.session-length." + when {
minutes < 1 -> "under-1m"
minutes < 10 -> "1m-10m"
minutes < 60 -> "10m-1h"
else -> "over-1h"
}
)
}
/** /**
* Set [reconnectAfterMs] for the next attempt after a failure and return the delay. Repeated * Set [reconnectAfterMs] for the next attempt after a failure and return the delay. Repeated
* failures back off along RECONNECT_BACKOFF_MS; a session that stayed up for * failures back off along RECONNECT_BACKOFF_MS; a session that stayed up for
@@ -737,6 +758,7 @@ internal fun GlassesSessionCore.maybeEmitEvenAppConflictLocked(reason: String?)
return return
} }
lastEvenAppConflictAtMs = now lastEvenAppConflictAtMs = now
ConnectionCounters.increment("g2.even-app-conflict")
emitEvenAppConflict("The Even Realities app still appears to be running. It can hold the glasses BLE link and cause Faceclaw write failures. Open its app settings and force stop it, then reconnect Faceclaw.") emitEvenAppConflict("The Even Realities app still appears to be running. It can hold the glasses BLE link and cause Faceclaw write failures. Open its app settings and force stop it, then reconnect Faceclaw.")
} }
@@ -410,6 +410,8 @@ class GlassesSessionCore(
releaseFaceclawFramebufferLease() releaseFaceclawFramebufferLease()
} }
monitor.withLock { monitor.withLock {
ConnectionCounters.increment("g2.disconnect-requested")
if (sessionReady) countSessionEnded("requested")
userDisconnectRequested = true userDisconnectRequested = true
running = false running = false
audioCaptureActive = false audioCaptureActive = false
@@ -1384,6 +1386,7 @@ class GlassesSessionCore(
val ingress = if (message.isLeftArmMessage) leftAddress else rightAddress val ingress = if (message.isLeftArmMessage) leftAddress else rightAddress
if (message.sid == CfwTransport.SID && address.equals(ingress, ignoreCase = true) && message.magic == ack.streamId) { if (message.sid == CfwTransport.SID && address.equals(ingress, ignoreCase = true) && message.magic == ack.streamId) {
message.acceptCfwAck(ack) message.acceptCfwAck(ack)
if (ack.nack) ConnectionCounters.increment("g2.cfw-nack")
logLine("CFW " + (if (ack.nack) "NACK" else "ACK") + " id=" + ack.streamId logLine("CFW " + (if (ack.nack) "NACK" else "ACK") + " id=" + ack.streamId
+ " ordinal=" + ack.messageId + " lens=" + ack.lens + " txseq=" + (data[2].toInt() and 255) + " ordinal=" + ack.messageId + " lens=" + ack.lens + " txseq=" + (data[2].toInt() and 255)
+ " redundant=" + (ack !== acks[0]) + " redundant=" + (ack !== acks[0])
@@ -1583,6 +1586,11 @@ class GlassesSessionCore(
if (decoded.eventType == BleProtocol.EVENT_ABNORMAL_EXIT || decoded.eventType == BleProtocol.EVENT_SYSTEM_EXIT) { if (decoded.eventType == BleProtocol.EVENT_ABNORMAL_EXIT || decoded.eventType == BleProtocol.EVENT_SYSTEM_EXIT) {
if (shutdownRequested) { if (shutdownRequested) {
lastShutdownExitAtMs = now() lastShutdownExitAtMs = now()
} else {
ConnectionCounters.increment(
if (decoded.eventType == BleProtocol.EVENT_ABNORMAL_EXIT) "g2.firmware-abnormal-exit"
else "g2.firmware-system-exit"
)
} }
fixedLayoutCreated = false fixedLayoutCreated = false
displayedFingerprint = "" displayedFingerprint = ""
@@ -1691,6 +1699,7 @@ class GlassesSessionCore(
ringReconnectAfterMs = now() + ConnectionOptions.RING_RECONNECT_DELAY_MS ringReconnectAfterMs = now() + ConnectionOptions.RING_RECONNECT_DELAY_MS
} }
} }
ConnectionCounters.increment(if (connected) "ring.direct.connect" else "ring.direct.disconnect")
logLine(if (connected) "direct ring BLE connected" else "direct ring BLE disconnected") logLine(if (connected) "direct ring BLE connected" else "direct ring BLE disconnected")
interruptibleSleep.interrupt() interruptibleSleep.interrupt()
return return
@@ -1709,6 +1718,12 @@ class GlassesSessionCore(
// dropping mid-setup): the connect sequence notices on its own and // dropping mid-setup): the connect sequence notices on its own and
// schedules the retry, so leave the backoff alone. // schedules the retry, so leave the backoff alone.
lostSession = sessionReady lostSession = sessionReady
if (lostSession) {
ConnectionCounters.increment(
if (address.equals(rightAddress, ignoreCase = true)) "g2.arm-drop.right" else "g2.arm-drop.left"
)
countSessionEnded("arm-drop")
}
sessionReady = false sessionReady = false
fixedLayoutCreated = false fixedLayoutCreated = false
startupProbePending = false startupProbePending = false
@@ -1740,6 +1755,7 @@ class GlassesSessionCore(
wearState = -1 wearState = -1
} }
setStateDisplay("connecting", "Connecting to the glasses...") setStateDisplay("connecting", "Connecting to the glasses...")
ConnectionCounters.increment("g2.connect-attempt")
try { try {
// Dial both arms at once, so the left arm's attempt is already pending (and // Dial both arms at once, so the left arm's attempt is already pending (and
// can land) while the right arm is being set up; they share one window. // can land) while the right arm is being set up; they share one window.
@@ -1793,6 +1809,7 @@ class GlassesSessionCore(
} }
} }
setStateDisplay("connected", "Connected.") setStateDisplay("connected", "Connected.")
ConnectionCounters.increment("g2.session-ready")
logLine("session ready") logLine("session ready")
monitor.withLock { monitor.withLock {
// Query settings at the start of every session so firmware // Query settings at the start of every session so firmware
@@ -1999,6 +2016,7 @@ class GlassesSessionCore(
monitor.withLock { monitor.withLock {
if (!inFlightMessages.isEmpty()) { if (!inFlightMessages.isEmpty()) {
clearInFlightMessagesLocked("security auth timeout") clearInFlightMessagesLocked("security auth timeout")
ConnectionCounters.increment("g2.auth-unacknowledged")
logLine("security auth not acknowledged; continuing (2.2.9 stock requires it; older/custom firmware may not answer)") logLine("security auth not acknowledged; continuing (2.2.9 stock requires it; older/custom firmware may not answer)")
return return
} }
@@ -2025,7 +2043,7 @@ class GlassesSessionCore(
prelude.onAck = MessageCallback { prelude.onAck = MessageCallback {
} }
prelude.onTimeout = MessageCallback { prelude.onTimeout = MessageCallback {
handleTransportFailure("ack timeout") handleTransportFailure("prelude ack timeout")
} }
prelude.sentAtMs = now prelude.sentAtMs = now
writeMessage(prelude) writeMessage(prelude)
@@ -87,6 +87,7 @@ internal fun GlassesSessionCore.driveSession(): Long {
val oldest = inFlightMessages.firstOrNull() val oldest = inFlightMessages.firstOrNull()
val replay = CfwMessageWindow.replayWindow(inFlightMessages, now) val replay = CfwMessageWindow.replayWindow(inFlightMessages, now)
if (!replay.isEmpty()) { if (!replay.isEmpty()) {
ConnectionCounters.increment("g2.cfw-replay")
logLine("CFW recovery: replay " + replay.size logLine("CFW recovery: replay " + replay.size
+ " unresolved message(s) from id=" + replay[0].magic) + " unresolved message(s) from id=" + replay[0].magic)
for (candidate in replay) { for (candidate in replay) {
@@ -665,7 +666,7 @@ internal fun GlassesSessionCore.enqueueCreateLayoutLocked() {
} }
startupProbePending = false startupProbePending = false
} }
handleTransportFailure("ack timeout") handleTransportFailure("create layout ack timeout")
} }
pendingMessages.addLast(message) pendingMessages.addLast(message)
logLine("queue create layout") logLine("queue create layout")
@@ -706,7 +707,7 @@ internal fun GlassesSessionCore.enqueueStartupProbeLocked() {
if (hasPendingOrInflightKindLocked("create-layout")) { if (hasPendingOrInflightKindLocked("create-layout")) {
return@MessageCallback return@MessageCallback
} }
handleTransportFailure("ack timeout") handleTransportFailure("startup probe ack timeout")
} }
pendingMessages.addLast(message) pendingMessages.addLast(message)
startupProbePending = true startupProbePending = true
@@ -1279,6 +1280,7 @@ internal fun GlassesSessionCore.hasPendingMagicLocked(sid: Int, magic: Int): Boo
internal fun GlassesSessionCore.handleAckTimeoutLocked(message: OutboundMessage) { internal fun GlassesSessionCore.handleAckTimeoutLocked(message: OutboundMessage) {
consecutiveAckTimeouts += 1 consecutiveAckTimeouts += 1
ConnectionCounters.increment("g2.ack-timeout")
val onTimeout = message.onTimeout val onTimeout = message.onTimeout
if (onTimeout != null) { if (onTimeout != null) {
@@ -584,6 +584,7 @@ class IosBleCentral(private val platform: ProtocolPlatform = IosProtocolPlatform
private fun onDisconnected(peripheral: CBPeripheral, error: NSError?) { private fun onDisconnected(peripheral: CBPeripheral, error: NSError?) {
val peer = remember(peripheral) val peer = remember(peripheral)
if (error != null) ConnectionCounters.increment("ble.ios-disconnect-error." + error.code)
failPeer(peer, error?.localizedDescription ?: "Disconnected", notifyListeners = true) failPeer(peer, error?.localizedDescription ?: "Disconnected", notifyListeners = true)
} }
Binary file not shown.
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env python3
"""Locate the LVGL font descriptors that app/g2/firmware-fonts.ts extracts.
Usage: scripts/find-firmware-fonts.py <stock EVENOTA .bin> [<another .bin>...]
Scans the main-app component (ota/s200_firmware_ota.bin, loaded at 0x438000
after a 0x20-byte preamble) for lv_font_fmt_txt_dsc_t structs with 4 bpp,
bitmap format 3 and a plausible cmap table, and prints one row per font. After
a firmware rebase, match rows to FONT_SPECS by cmap count / code-point count
(the EvenHub fallback chain is n=12/8081, n=9/9566, n=4/11590) and copy the
new `dsc` addresses into firmware-fonts.ts.
"""
import struct, sys
BASE=0x438000
def mainapp(path):
d=open(path,'rb').read()
for i in range(8):
toc=0x40+i*16; off=struct.unpack_from('<I',d,toc+4)[0]
if not off or off>len(d): continue
size=struct.unpack_from('<I',d,off+8)[0]
name=d[off+48:off+128].split(b'\0')[0]
if name==b'ota/s200_firmware_ota.bin':
p=off+128+0x20; return d[p:p+size-0x20]
class Img:
def __init__(s,b): s.b=b; s.end=BASE+len(b)
def ok(s,a,n=4): return BASE<=a and a+n<=s.end
def u32(s,a): return struct.unpack_from('<I',s.b,a-BASE)[0]
def u16(s,a): return struct.unpack_from('<H',s.b,a-BASE)[0]
def i16(s,a): return struct.unpack_from('<h',s.b,a-BASE)[0]
def find_dscs(img):
out=[]
for off in range(0,len(img.b)-20,4):
a=BASE+off
bm,gd,cm,kd=struct.unpack_from('<IIII',img.b,off)
if not(img.ok(bm) and img.ok(gd) and img.ok(cm)): continue
if kd!=0 and not img.ok(kd): continue
packed=img.u16(a+18); n=packed&0x1ff; bpp=(packed>>9)&0xf; fmt=(packed>>14)&3
if bpp!=4 or fmt!=3 or n==0 or n>64: continue
# cmap entries 20 bytes: range_start u32, range_length u16, glyph_id_start u16, list ptr, list ptr, list_length u16, type u8
good=True; total=0
for i in range(n):
c=cm+i*20
if not img.ok(c,20): good=False;break
rs=img.u32(c); rl=img.u16(c+4); t=img.b[c-BASE+19]
if t>3 or rl==0 or rs>0x10FFFF: good=False;break
total+=rl
if not good: continue
out.append((a,bm,gd,cm,kd,n,total))
return out
for path in sys.argv[1:]:
print("==",path); img=Img(mainapp(path))
for a,bm,gd,cm,kd,n,total in find_dscs(img):
print(f"dsc 0x{a:08x} bitmap 0x{bm:08x} glyphs 0x{gd:08x} cmaps 0x{cm:08x} n={n} codepoints={total}")
+9
View File
@@ -20,4 +20,13 @@ if command -v ruby >/dev/null 2>&1; then
fi fi
node scripts/install-hooks.cjs node scripts/install-hooks.cjs
# NativeScript otherwise guesses the signing team from installed provisioning
# profiles; once a free team's profile expires and Xcode deletes it, the guess
# is null and the generated project gets an unloadable DEVELOPMENT_TEAM.
if [[ -n "${IOS_TEAM_ID:-}" && " $* " != *" --teamId"* ]]; then
case "${1:-}" in
build|run|debug|deploy) set -- "$@" --teamId "$IOS_TEAM_ID" ;;
esac
fi
exec ns "$@" exec ns "$@"
+2 -1
View File
@@ -4,7 +4,8 @@
# pre-onboarding state, for testing the onboarding flow repeatedly. # pre-onboarding state, for testing the onboarding flow repeatedly.
# #
# By default this only clears the onboarding-related preference keys # By default this only clears the onboarding-related preference keys
# (onboarding.complete, onboarding.previewOnly, ...) and leaves everything # (onboarding.complete, onboarding.previewOnly, the on-glasses onboarding's
# onboarding.glassesFinishedVersion, ...) and leaves everything
# else — notably the saved glasses/ring MAC addresses — intact, so you don't # else — notably the saved glasses/ring MAC addresses — intact, so you don't
# have to re-scan devices on every test pass. Pass --all to wipe ALL app data # have to re-scan devices on every test pass. Pass --all to wipe ALL app data
# (a true fresh-install state, addresses included). # (a true fresh-install state, addresses included).
+188
View File
@@ -0,0 +1,188 @@
#!/usr/bin/env python3
"""Annotate a pulled faceclaw_settings.xml with placeholders for unset settings.
Settings that have never been configured are absent from the SharedPreferences
file, which makes it unclear what keys exist or where to add them. This script
scans the app's TypeScript source for ConfigSetting declarations (the settings
catalog) and appends a commented-out XML node for every setting not already
present in the file, so pull_config.sh -> edit -> push_config.sh is a
convenient way to configure things like API keys.
Usage: annotate_config.py [settings-xml] [app-src-dir]
Defaults: faceclaw_settings.xml, <repo>/app (relative to this script).
"""
import re
import sys
import xml.etree.ElementTree as ET
from pathlib import Path
def find_setting_blocks(source: str):
"""Yield (kind, block_text) for each `new ConfigSetting*({...})` in source."""
for match in re.finditer(
r"new\s+ConfigSetting(Boolean|Enum|String)(?:<[^>(]*>)?\s*\(\s*\{", source
):
kind = match.group(1)
# Walk to the matching close brace of the options object literal.
depth = 1
pos = match.end()
while pos < len(source) and depth > 0:
ch = source[pos]
if ch == "{":
depth += 1
elif ch == "}":
depth -= 1
pos += 1
yield kind, source[match.end() : pos - 1]
STRING_LITERAL = r'"((?:[^"\\]|\\.)*)"'
def unescape(literal: str) -> str:
return re.sub(r"\\(.)", r"\1", literal)
def field_string(block: str, name: str):
m = re.search(rf"{name}:\s*{STRING_LITERAL}", block)
return unescape(m.group(1)) if m else None
def field_string_or_ident(block: str, name: str):
"""Return ('literal', value) or ('ident', name) or None."""
m = re.search(rf"{name}:\s*(?:{STRING_LITERAL}|([A-Za-z_][A-Za-z0-9_]*))", block)
if not m:
return None
if m.group(1) is not None:
return ("literal", unescape(m.group(1)))
return ("ident", m.group(2))
def parse_string_array(text: str):
return [unescape(m.group(1)) for m in re.finditer(STRING_LITERAL, text)]
def build_constant_tables(sources):
"""Map identifier -> string value, and identifier -> list of strings."""
string_consts = {}
array_consts = {}
for source in sources:
for m in re.finditer(
rf"const\s+([A-Za-z_][A-Za-z0-9_]*)\s*=\s*{STRING_LITERAL}", source
):
string_consts[m.group(1)] = unescape(m.group(2))
for m in re.finditer(
r"const\s+([A-Za-z_][A-Za-z0-9_]*)\s*=\s*\[([^\]]*)\]", source, re.S
):
values = parse_string_array(m.group(2))
if values:
array_consts[m.group(1)] = values
return string_consts, array_consts
def collect_settings(app_dir: Path):
sources = [p.read_text(encoding="utf-8") for p in sorted(app_dir.rglob("*.ts"))]
string_consts, array_consts = build_constant_tables(sources)
settings = []
for source in sources:
for kind, block in find_setting_blocks(source):
key_ref = field_string_or_ident(block, "storageKey")
if key_ref is None:
continue
key = key_ref[1] if key_ref[0] == "literal" else string_consts.get(key_ref[1])
if key is None:
print(
f"warning: could not resolve storageKey {key_ref[1]}",
file=sys.stderr,
)
continue
if kind == "Boolean":
m = re.search(r"defaultValue:\s*(true|false)", block)
default = m.group(1) if m else "false"
else:
default = field_string(block, "defaultValue") or ""
values = None
if kind == "Enum":
m = re.search(r"values:\s*(?:\[([^\]]*)\]|([A-Za-z_][A-Za-z0-9_]*))", block, re.S)
if m and m.group(1) is not None:
values = parse_string_array(m.group(1))
elif m:
values = array_consts.get(m.group(2))
settings.append(
{
"key": key,
"kind": kind,
"default": default,
"label": field_string(block, "label"),
"description": field_string(block, "description"),
"values": values,
}
)
return settings
def xml_escape(text: str) -> str:
return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
def comment_safe(text: str) -> str:
# "--" is illegal inside an XML comment.
return re.sub(r"-{2,}", "-", text)
def placeholder_comment(setting) -> str:
lines = []
title = setting["label"] or setting["key"]
desc = f": {setting['description']}" if setting["description"] else ""
lines.append(f"{title}{desc}")
if setting["values"]:
lines.append(f"Allowed values: {', '.join(setting['values'])}")
if setting["kind"] == "Boolean":
node = f'<boolean name="{setting["key"]}" value="{setting["default"]}" />'
else:
node = f'<string name="{setting["key"]}">{xml_escape(setting["default"])}</string>'
lines.append(node)
body = "\n ".join(comment_safe(line) for line in lines)
return f" <!-- {body} -->"
def main() -> int:
xml_path = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("faceclaw_settings.xml")
app_dir = (
Path(sys.argv[2]) if len(sys.argv) > 2 else Path(__file__).resolve().parent.parent / "app"
)
content = xml_path.read_text(encoding="utf-8")
present = {
child.get("name")
for child in ET.fromstring(content)
if child.get("name") is not None
}
missing = [s for s in collect_settings(app_dir) if s["key"] not in present]
if not missing:
return 0
missing.sort(key=lambda s: s["key"])
close_tag = content.rfind("</map>")
if close_tag < 0:
print(f"error: no </map> in {xml_path}", file=sys.stderr)
return 1
header = (
" <!-- Settings below have never been set on the device and show their\n"
" default values. To configure one, uncomment its node (keep it\n"
" inside <map>), fill in the value, and run scripts/push_config.sh. -->\n"
)
block = header + "\n".join(placeholder_comment(s) for s in missing) + "\n"
xml_path.write_text(content[:close_tag] + block + content[close_tag:], encoding="utf-8")
print(f"Added placeholders for {len(missing)} unset setting(s) to {xml_path}")
return 0
if __name__ == "__main__":
sys.exit(main())
+207
View File
@@ -0,0 +1,207 @@
#!/usr/bin/env node
/**
* Preprocess Even's extracted 20px firmware fonts into a single asset Faceclaw
* bundles and renders (app/fonts/evenhub/evenhub-20.json).
*
* Source: reverse-engineered LVGL lv_font_fmt_txt glyph data under
* g2/downloads/s200_embedded_fonts/{background_latin_20, background_greek_
* cyrillic_20, shared_emoji_20}. The Chinese font is intentionally excluded
* (we will substitute an OFL font for CJK later).
*
* Only glyph BITMAPS + boxes are taken from here; text SIZING/KERNING at
* runtime comes from @evenrealities/pretext, whose advance tables these
* bitmaps were cross-validated against. The three fonts are merged with the
* EvenHub fallback priority (latin > greek/cyrillic > emoji); the first font
* that owns a codepoint wins, matching pretext's chain.
*
* Bitmaps are 4bpp, high-nibble-first, row stride = floor(box_w/2)+1 (Even's
* pipeline pads every row by a nibble). The UI fonts are effectively 1-bit
* (nibbles are 0 or 0xF) but we keep 4bpp verbatim so any anti-aliasing
* survives.
*
* Output JSON:
* { lineHeight, baseline, glyphs: { "<cp>": [boxW, boxH, ofsX, ofsY, off, len] },
* bitmapBase64 }
* where off/len index the decoded bitmap blob. lineHeight/baseline come from
* the latin font (the layout reference; pretext uses the same 27px height).
*/
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
const here = dirname(fileURLToPath(import.meta.url));
const FONT_SRC = join(here, "../../downloads/s200_embedded_fonts");
const OUT = join(here, "../app/fonts/evenhub/evenhub-20.json");
// Priority order = EvenHub fallback chain (minus cn).
const FONTS = ["background_latin_20", "background_greek_cyrillic_20", "shared_emoji_20"];
function rowStride(boxW) {
return Math.floor(boxW / 2) + 1;
}
const merged = new Map(); // codepoint -> {boxW,boxH,ofsX,ofsY,bytes:Uint8Array}
for (const font of FONTS) {
const dir = join(FONT_SRC, font);
const glyphs = JSON.parse(readFileSync(join(dir, "glyphs.json"), "utf8"));
const bitmap = readFileSync(join(dir, "glyph_bitmap.bin"));
for (const g of glyphs) {
if (g.codepoint === undefined) continue; // reserved / unmapped glyph slots
if (merged.has(g.codepoint)) continue; // earlier font in the chain wins
const len = g.box_height > 0 && g.box_width > 0 ? rowStride(g.box_width) * g.box_height : 0;
// Guard against the known slightly-truncated bitmap tails: pad short reads.
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) bytes[i] = bitmap[g.bitmap_index + i] ?? 0;
merged.set(g.codepoint, {
boxW: g.box_width,
boxH: g.box_height,
ofsX: g.offset_x,
ofsY: g.offset_y,
bytes,
});
}
}
// Layout metrics from the latin font (also what pretext uses: 27px line).
const latinFont = JSON.parse(readFileSync(join(FONT_SRC, "background_latin_20", "manifest.json"), "utf8"));
const lineHeight = latinFont.line_height; // 27
const baseline = lineHeight - latinFont.base_line; // 27 - 5 = 22 (px below line top)
// ---------------------------------------------------------------------------
// Symbol / fullwidth glyphs from the CJK flash font (s200_font.bin).
//
// The three embedded UI fonts above cover latin/greek/emoji only, so grid-
// graphics apps come out blank: snake draws its board from U+3000 (ideographic
// space), U+25A6/U+25C6 (pieces) and fullwidth forms; block/box-drawing bars
// use U+2500-259F. Those glyphs live only in the SourceHanSans CJK font on the
// separate flash partition. We pull just the non-Han SYMBOL ranges from it
// (not the 21k ideographs — those wait for the OFL substitute) so grid UIs
// render. pretext already returns 20px advances for these, so only the bitmaps
// were missing. Format per notes/font-formats.txt (LVGL lv_font_fmt_txt in the
// "ZZZZ" flash wrapper, memory-mapped at 0x80100000).
const CJK_FONT = join(here, "../../downloads/s200_font.bin");
const CJK_MMAP_BASE = 0x80100000;
// Non-Han symbol ranges grid/graphics apps rely on (inclusive).
const SYMBOL_RANGES = [
[0x2000, 0x206f], // general punctuation (incl. various spaces/dashes)
[0x2100, 0x214f], // letterlike symbols (℃ ℉ №, etc.)
[0x2190, 0x21ff], // arrows
[0x2200, 0x22ff], // mathematical operators
[0x2500, 0x257f], // box drawing
[0x2580, 0x259f], // block elements
[0x25a0, 0x25ff], // geometric shapes (snake pieces)
[0x2600, 0x26ff], // miscellaneous symbols
[0x2700, 0x27bf], // dingbats
[0x3000, 0x303f], // CJK symbols & punctuation (ideographic space)
[0xff00, 0xffef], // halfwidth & fullwidth forms
];
function loadCjkSymbols(existing) {
let added = 0;
const cjk = readFileSync(CJK_FONT);
const off = (ptr) => ptr - CJK_MMAP_BASE;
const descPtr = cjk.readUInt32LE(0x34);
const cjkLineHeight = cjk.readUInt16LE(0x38);
const cjkBaseLine = cjk.readUInt16LE(0x3a);
const cjkBaseline = cjkLineHeight - cjkBaseLine; // 25 - 6 = 19
// Our single composite baseline differs, so shift ofsY to keep the glyph's
// designed vertical placement when drawn against our baseline.
const baselineShift = baseline - cjkBaseline;
let d = off(descPtr);
const glyphBitmapOff = off(cjk.readUInt32LE(d));
const glyphDscOff = off(cjk.readUInt32LE(d + 4));
const cmapOff = off(cjk.readUInt32LE(d + 8));
// kerning ptr (d+12) is null; packed field after gives cmap_num.
const packed = cjk.readUInt16LE(d + 18);
const cmapNum = packed & 0x1ff;
// Parse the cmap table into lookup records.
const cmaps = [];
for (let i = 0; i < cmapNum; i++) {
const base = cmapOff + i * 20;
cmaps.push({
rangeStart: cjk.readUInt32LE(base),
rangeLength: cjk.readUInt16LE(base + 4),
glyphIdStart: cjk.readUInt16LE(base + 6),
unicodeListPtr: cjk.readUInt32LE(base + 8),
glyphIdOfsListPtr: cjk.readUInt32LE(base + 12),
listLength: cjk.readUInt16LE(base + 16),
type: cjk.readUInt8(base + 18),
});
}
const glyphIdFor = (cp) => {
for (const c of cmaps) {
if (cp < c.rangeStart || cp >= c.rangeStart + c.rangeLength) continue;
const rel = cp - c.rangeStart;
if (c.type === 2) return c.glyphIdStart + rel; // contiguous
if (c.type === 0) {
// u8 glyph-id-offset array
return c.glyphIdStart + cjk.readUInt8(off(c.glyphIdOfsListPtr) + rel);
}
if (c.type === 3) {
// sparse: u16 unicode-delta list; index in the list is the glyph offset
const listOff = off(c.unicodeListPtr);
for (let k = 0; k < c.listLength; k++) {
if (cjk.readUInt16LE(listOff + k * 2) === rel) {
const gid = c.glyphIdOfsListPtr
? cjk.readUInt8(off(c.glyphIdOfsListPtr) + k)
: k;
return c.glyphIdStart + gid;
}
}
return 0;
}
}
return 0;
};
for (const [start, end] of SYMBOL_RANGES) {
for (let cp = start; cp <= end; cp++) {
if (existing.has(cp)) continue; // don't override latin/greek/emoji
const gid = glyphIdFor(cp);
if (!gid) continue;
const dsc = glyphDscOff + gid * 16;
const bitmapIndex = cjk.readUInt32LE(dsc);
const boxW = cjk.readUInt16LE(dsc + 8);
const boxH = cjk.readUInt16LE(dsc + 10);
const ofsX = cjk.readInt16LE(dsc + 12);
const ofsY = cjk.readInt16LE(dsc + 14);
const len = boxW > 0 && boxH > 0 ? rowStride(boxW) * boxH : 0;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) bytes[i] = cjk[glyphBitmapOff + bitmapIndex + i] ?? 0;
existing.set(cp, { boxW, boxH, ofsX, ofsY: ofsY + baselineShift, bytes });
added++;
}
}
return added;
}
const cjkAdded = loadCjkSymbols(merged);
// Concatenate bitmaps and record offsets.
const chunks = [];
let offset = 0;
const glyphRecords = {};
for (const [cp, g] of [...merged].sort((a, b) => a[0] - b[0])) {
chunks.push(g.bytes);
glyphRecords[cp] = [g.boxW, g.boxH, g.ofsX, g.ofsY, offset, g.bytes.length];
offset += g.bytes.length;
}
const blob = Buffer.concat(chunks.map((c) => Buffer.from(c)));
const asset = {
lineHeight,
baseline,
glyphs: glyphRecords,
bitmapBase64: blob.toString("base64"),
};
mkdirSync(dirname(OUT), { recursive: true });
writeFileSync(OUT, JSON.stringify(asset));
console.log(
`wrote ${OUT}: ${merged.size} glyphs (${cjkAdded} from CJK symbols), ` +
`${blob.length} bitmap bytes, ${(JSON.stringify(asset).length / 1024).toFixed(1)} KiB json`,
);
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env node
/**
* Pack a web-app directory into an EvenHub .ehpk, dependency-free (Node >= 22.15
* for node:zlib zstd). Format reverse-engineered in
* ../../ehpk-unpacker/ehpk_unpack.py and consumed by app/apps/evenhub/ehpk.ts:
*
* header "EHPK" | u16 major=1 | u16 minor=1 | u32 firstRecord=20
* | u32 recordCount | u32 reserved=0
* FILE E4 BA A9 BA | u32 compLen | u32 uncompLen | u16 tag=0xB701
* | u16 nameLen | xor(path) | xor(zstd(content))
* DIR E5 BA A9 BA | u16 tag=0xAABD | u16 nameLen | xor(path)
* FOOTER E3 BA A9 BA | sha512 of every byte before this record
*
* Paths and content are XORed with the repeating key "EVEN REALITIES".
* The manifest is stored as "app.json", project files under "dist/".
*
* Usage: node scripts/pack-ehpk.mjs <app.json> <projectDir> [-o out.ehpk]
*/
import { readFileSync, writeFileSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { createHash } from "node:crypto";
import { zstdCompressSync } from "node:zlib";
const KEY = Buffer.from("EVEN REALITIES", "ascii");
function xor(buf) {
const out = Buffer.from(buf);
for (let i = 0; i < out.length; i++) out[i] ^= KEY[i % KEY.length];
return out;
}
function fileRecord(path, content) {
const comp = xor(zstdCompressSync(content));
const name = xor(Buffer.from(path, "utf8"));
const head = Buffer.alloc(16);
head.writeUInt32LE(0xbaa9bae4, 0);
head.writeUInt32LE(comp.length, 4);
head.writeUInt32LE(content.length, 8);
head.writeUInt16LE(0xb701, 12);
head.writeUInt16LE(name.length, 14);
return Buffer.concat([head, name, comp]);
}
function dirRecord(path) {
const name = xor(Buffer.from(path, "utf8"));
const head = Buffer.alloc(8);
head.writeUInt32LE(0xbaa9bae5, 0);
head.writeUInt16LE(0xaabd, 4);
head.writeUInt16LE(name.length, 6);
return Buffer.concat([head, name]);
}
function walk(dir, archivePrefix, records) {
for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
if (entry.name.startsWith(".") || entry.name.endsWith(".ehpk")) continue;
const archivePath = `${archivePrefix}/${entry.name}`;
if (entry.isDirectory()) {
records.push(dirRecord(archivePath));
walk(join(dir, entry.name), archivePath, records);
} else if (entry.isFile()) {
records.push(fileRecord(archivePath, readFileSync(join(dir, entry.name))));
}
}
}
const args = process.argv.slice(2);
const outIndex = args.indexOf("-o");
const output = outIndex >= 0 ? args.splice(outIndex, 2)[1] : "out.ehpk";
const [manifestPath, projectDir] = args;
if (!manifestPath || !projectDir) {
console.error("usage: pack-ehpk.mjs <app.json> <projectDir> [-o out.ehpk]");
process.exit(1);
}
const records = [fileRecord("app.json", readFileSync(manifestPath)), dirRecord("dist")];
walk(projectDir, "dist", records);
const header = Buffer.alloc(20);
header.write("EHPK", 0, "ascii");
header.writeUInt16LE(1, 4);
header.writeUInt16LE(1, 6);
header.writeUInt32LE(20, 8);
header.writeUInt32LE(records.length + 1, 12); // + footer
header.writeUInt32LE(0, 16);
const body = Buffer.concat([header, ...records]);
const footerHead = Buffer.alloc(4);
footerHead.writeUInt32LE(0xbaa9bae3, 0);
const footer = Buffer.concat([footerHead, createHash("sha512").update(body).digest()]);
writeFileSync(output, Buffer.concat([body, footer]));
console.log(`${output}: ${records.length + 1} records, ${body.length + footer.length} bytes`);
+302
View File
@@ -0,0 +1,302 @@
// Headless verification harness for the pinball worker's table geometry and
// physics. Ported 1:1 from app/workers/pinball-app.worker.ts (keep in sync by
// hand if the worker changes). Renders the table plus simulated trajectories
// to grayscale PGM files and logs events/anomalies.
const fs = require("fs");
// --- geometry (must match worker) ---
const LEFT = 10, RIGHT = 260, TOP = 4, BOTTOM = 256, LANE_X = 232;
const BALL_R = 6;
const PLUNGER_X = (LANE_X + RIGHT) / 2, PLUNGER_Y = 240;
const GRAVITY = 240, DRAG_PER_S = 0.12, MAX_SPEED = 600, PHYSICS_DT = 1 / 120;
const LAUNCH_SPEEDS = [320, 380, 440, 500, 560];
const BUMPER_KICK = 340, SLING_KICK = 300;
const FLIPPER_LEN = 37, FLIPPER_R = 5;
const FLIPPER_REST_DEG = 32, FLIPPER_UP_DEG = -34;
const FLIPPER_RISE_DEG_PER_S = 950, FLIPPER_FALL_DEG_PER_S = 480;
const FLIPPER_HOLD_MS = 140, FLIPPER_E = 0.4;
function seg(x0, y0, x1, y1, e, shade = 150, kind = "wall") {
return { x0, y0, x1, y1, e, kind, shade };
}
function chain(points, e, shade = 150) {
const out = [];
for (let i = 1; i < points.length; i++)
out.push(seg(points[i - 1][0], points[i - 1][1], points[i][0], points[i][1], e, shade));
return out;
}
const SEGMENTS = [
...chain([[LEFT, BOTTOM], [LEFT, 54], [16, 24], [34, 8], [58, TOP]], 0.45, 160),
seg(58, TOP, 210, TOP, 0.45, 160),
...chain([[210, TOP], [236, 10], [254, 26], [RIGHT, 56]], 0.35, 160),
seg(RIGHT, 56, RIGHT, BOTTOM, 0.3, 160),
seg(LANE_X, BOTTOM, RIGHT, BOTTOM, 0.3, 160),
seg(LANE_X, 66, LANE_X, BOTTOM, 0.3, 140),
seg(RIGHT, 56, 226, 68, 0.2, 90, "gate"),
seg(103, 20, 103, 46, 0.35, 130),
seg(139, 20, 139, 46, 0.35, 130),
seg(LEFT, 184, 83, 230.5, 0.35, 150),
seg(LANE_X, 184, 159, 230.5, 0.35, 150),
seg(58, 166, 84, 204, 0.4, 170, "sling"),
seg(58, 166, 58, 196, 0.4, 130),
seg(58, 196, 84, 204, 0.4, 130),
seg(184, 166, 158, 204, 0.4, 170, "sling"),
seg(184, 166, 184, 196, 0.4, 130),
seg(158, 204, 184, 196, 0.4, 130),
];
const BUMPERS = [
{ x: 75, y: 78, r: 13 },
{ x: 167, y: 78, r: 13 },
{ x: 121, y: 128, r: 13 },
];
const ROLLOVERS = [{ x: 85, y: 34 }, { x: 121, y: 34 }, { x: 157, y: 34 }];
const FLIPPER_PIVOTS = [
{ x: 76, y: 232, mirror: 1 },
{ x: 166, y: 232, mirror: -1 },
];
const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
function makeState() {
return {
ballX: PLUNGER_X, ballY: PLUNGER_Y, ballVx: 0, ballVy: 0,
flippers: FLIPPER_PIVOTS.map((p) => ({
pivotX: p.x, pivotY: p.y, mirror: p.mirror,
angleDeg: FLIPPER_REST_DEG, state: "rest", holdUntilMs: 0,
})),
nowMs: 0, events: [], drained: false,
};
}
function flipperOmega(f) {
if (f.state === "rising") return (-FLIPPER_RISE_DEG_PER_S * Math.PI) / 180;
if (f.state === "falling") return (FLIPPER_FALL_DEG_PER_S * Math.PI) / 180;
return 0;
}
function stepFlippers(s, dt) {
for (const f of s.flippers) {
switch (f.state) {
case "rising":
f.angleDeg -= FLIPPER_RISE_DEG_PER_S * dt;
if (f.angleDeg <= FLIPPER_UP_DEG) {
f.angleDeg = FLIPPER_UP_DEG; f.state = "hold"; f.holdUntilMs = s.nowMs + FLIPPER_HOLD_MS;
}
break;
case "hold":
if (s.nowMs >= f.holdUntilMs) f.state = "falling";
break;
case "falling":
f.angleDeg += FLIPPER_FALL_DEG_PER_S * dt;
if (f.angleDeg >= FLIPPER_REST_DEG) { f.angleDeg = FLIPPER_REST_DEG; f.state = "rest"; }
break;
}
}
}
function collideSegment(s, segment) {
const dx = segment.x1 - segment.x0, dy = segment.y1 - segment.y0;
const lengthSq = dx * dx + dy * dy;
const t = clamp(((s.ballX - segment.x0) * dx + (s.ballY - segment.y0) * dy) / lengthSq, 0, 1);
const cx = segment.x0 + t * dx, cy = segment.y0 + t * dy;
const offX = s.ballX - cx, offY = s.ballY - cy;
const dist = Math.hypot(offX, offY);
if (dist >= BALL_R || dist === 0) return;
const nx = offX / dist, ny = offY / dist;
if (segment.kind === "gate" && ny > -0.3) return;
s.ballX += nx * (BALL_R - dist);
s.ballY += ny * (BALL_R - dist);
const vn = s.ballVx * nx + s.ballVy * ny;
if (vn >= 0) return;
if (segment.kind === "sling") {
s.ballVx = s.ballVx - vn * nx + nx * SLING_KICK;
s.ballVy = s.ballVy - vn * ny + ny * SLING_KICK;
s.events.push(`${(s.nowMs / 1000).toFixed(2)}s sling`);
return;
}
s.ballVx -= (1 + segment.e) * vn * nx;
s.ballVy -= (1 + segment.e) * vn * ny;
}
function collideFlipper(s, f) {
const angle = (f.angleDeg * Math.PI) / 180;
const dirX = f.mirror * Math.cos(angle), dirY = Math.sin(angle);
const relX = s.ballX - f.pivotX, relY = s.ballY - f.pivotY;
const t = clamp(relX * dirX + relY * dirY, 0, FLIPPER_LEN);
const cx = f.pivotX + t * dirX, cy = f.pivotY + t * dirY;
const offX = s.ballX - cx, offY = s.ballY - cy;
const dist = Math.hypot(offX, offY);
const reach = BALL_R + FLIPPER_R;
if (dist >= reach || dist === 0) return;
const nx = offX / dist, ny = offY / dist;
s.ballX += nx * (reach - dist);
s.ballY += ny * (reach - dist);
const omega = flipperOmega(f);
const surfaceVx = -t * omega * f.mirror * dirY;
const surfaceVy = t * omega * f.mirror * dirX;
const relVn = (s.ballVx - surfaceVx) * nx + (s.ballVy - surfaceVy) * ny;
if (relVn >= 0) return;
s.ballVx -= (1 + FLIPPER_E) * relVn * nx;
s.ballVy -= (1 + FLIPPER_E) * relVn * ny;
}
function collideBumpers(s) {
for (const b of BUMPERS) {
const offX = s.ballX - b.x, offY = s.ballY - b.y;
const dist = Math.hypot(offX, offY);
const reach = BALL_R + b.r;
if (dist >= reach || dist === 0) continue;
const nx = offX / dist, ny = offY / dist;
s.ballX += nx * (reach - dist);
s.ballY += ny * (reach - dist);
const tangential = s.ballVx * -ny + s.ballVy * nx;
s.ballVx = nx * BUMPER_KICK + -ny * tangential * 0.3;
s.ballVy = ny * BUMPER_KICK + nx * tangential * 0.3;
s.events.push(`${(s.nowMs / 1000).toFixed(2)}s bumper`);
}
}
function stepPhysics(s) {
const dt = PHYSICS_DT;
s.nowMs += dt * 1000;
stepFlippers(s, dt);
if (s.drained) return;
s.ballVy += GRAVITY * dt;
const drag = Math.max(0, 1 - DRAG_PER_S * dt);
s.ballVx *= drag; s.ballVy *= drag;
const speed = Math.hypot(s.ballVx, s.ballVy);
if (speed > MAX_SPEED) { s.ballVx *= MAX_SPEED / speed; s.ballVy *= MAX_SPEED / speed; }
s.ballX += s.ballVx * dt;
s.ballY += s.ballVy * dt;
for (let pass = 0; pass < 2; pass++) {
for (const segment of SEGMENTS) collideSegment(s, segment);
for (const f of s.flippers) collideFlipper(s, f);
collideBumpers(s);
}
if (s.ballY > BOTTOM + 2 * BALL_R || s.ballY < TOP - 40 || s.ballX < LEFT - 40 || s.ballX > RIGHT + 40) {
s.drained = true;
s.events.push(`${(s.nowMs / 1000).toFixed(2)}s DRAIN at x=${s.ballX.toFixed(0)}`);
}
}
// --- rendering ---
const W = 276, H = 276;
function render(trailPoints, label) {
const px = new Uint8Array(W * H);
const line = (x0, y0, x1, y1, v) => {
const steps = Math.max(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 2 + 1;
for (let i = 0; i <= steps; i++) {
const x = Math.round(x0 + ((x1 - x0) * i) / steps);
const y = Math.round(y0 + ((y1 - y0) * i) / steps);
if (x >= 0 && y >= 0 && x < W && y < H) px[y * W + x] = v;
}
};
for (const s of SEGMENTS) line(s.x0, s.y0, s.x1, s.y1, s.shade);
for (const b of BUMPERS)
for (let a = 0; a < 120; a++) {
const x = Math.round(b.x + b.r * Math.cos((a / 120) * 2 * Math.PI));
const y = Math.round(b.y + b.r * Math.sin((a / 120) * 2 * Math.PI));
if (x >= 0 && y >= 0 && x < W && y < H) px[y * W + x] = 130;
}
for (const r of ROLLOVERS)
for (let a = 0; a < 40; a++) {
const x = Math.round(r.x + 5 * Math.cos((a / 40) * 2 * Math.PI));
const y = Math.round(r.y + 5 * Math.sin((a / 40) * 2 * Math.PI));
if (x >= 0 && y >= 0 && x < W && y < H) px[y * W + x] = 110;
}
for (const f of FLIPPER_PIVOTS) {
const a = (FLIPPER_REST_DEG * Math.PI) / 180;
line(f.x, f.y, f.x + f.mirror * FLIPPER_LEN * Math.cos(a), f.y + FLIPPER_LEN * Math.sin(a), 255);
}
for (const [x, y] of trailPoints) {
const xi = Math.round(x), yi = Math.round(y);
if (xi >= 0 && yi >= 0 && xi < W && yi < H) px[yi * W + xi] = Math.max(px[yi * W + xi], 220);
}
const header = Buffer.from(`P5\n${W} ${H}\n255\n`);
fs.writeFileSync(`${__dirname}/pinball-${label}.pgm`, Buffer.concat([header, Buffer.from(px)]));
}
// --- scenarios ---
function runScenario(label, power, flipPolicy, maxSeconds = 40) {
const s = makeState();
s.ballY = PLUNGER_Y - 2;
s.ballVy = -LAUNCH_SPEEDS[power - 1];
const trail = [];
let stuckMs = 0, stuckReported = null, minY = 999;
const steps = Math.round(maxSeconds / PHYSICS_DT);
for (let i = 0; i < steps && !s.drained; i++) {
stepPhysics(s);
minY = Math.min(minY, s.ballY);
if (!Number.isFinite(s.ballX) || !Number.isFinite(s.ballY)) {
s.events.push(`${(s.nowMs / 1000).toFixed(2)}s NON-FINITE POSITION`);
break;
}
if (i % 4 === 0) trail.push([s.ballX, s.ballY]);
const speed = Math.hypot(s.ballVx, s.ballVy);
if (speed < 6) stuckMs += PHYSICS_DT * 1000; else stuckMs = 0;
// A slow ball near the flippers may just be trapped on one (legitimate);
// fire the flippers and only call it stuck if that fails to eject it.
if (stuckMs > 1200 && Math.round(stuckMs) % 600 < PHYSICS_DT * 1000) {
for (const f of s.flippers) if (f.state === "rest") f.state = "rising";
}
if (stuckMs > 2500 && !stuckReported) {
stuckReported = `STUCK ~2.5s at (${s.ballX.toFixed(0)},${s.ballY.toFixed(0)})`;
s.events.push(stuckReported);
}
flipPolicy(s);
}
render(trail, label);
const outcome = s.drained ? "drained" : stuckReported ? "stuck" : "still live at timeout";
console.log(`\n=== ${label} (power ${power}): ${outcome}, minY=${minY.toFixed(0)}, ${(s.nowMs / 1000).toFixed(1)}s sim ===`);
const counts = {};
for (const e of s.events) {
const kind = e.split(" ")[1] || e;
counts[kind] = (counts[kind] || 0) + 1;
}
console.log("events:", JSON.stringify(counts));
console.log("last events:", s.events.slice(-6).join(" | "));
}
const noFlips = () => {};
// Flip both flippers whenever the ball descends into the flipper zone.
function reactiveFlips(s) {
if (s.ballVy > 0 && s.ballY > 195 && s.ballY < 235 && s.ballX > 55 && s.ballX < 190) {
for (const f of s.flippers) if (f.state === "rest") f.state = "rising";
}
}
runScenario("p1-noflip", 1, noFlips);
runScenario("p3-noflip", 3, noFlips);
runScenario("p5-noflip", 5, noFlips);
runScenario("p4-flips", 4, reactiveFlips, 90);
runScenario("p2-flips", 2, reactiveFlips, 90);
// Randomized robustness sweep: random power, jittery/erratic flipping.
let bad = 0;
for (let run = 0; run < 30; run++) {
const power = 1 + Math.floor(Math.random() * 5);
const policy = (s) => {
if (Math.random() < 0.004) {
const f = s.flippers[Math.floor(Math.random() * 2)];
if (f.state === "rest") f.state = "rising";
}
reactiveFlips(s);
};
const s = makeState();
s.ballY = PLUNGER_Y - 2;
s.ballVy = -LAUNCH_SPEEDS[power - 1];
let stuckMs = 0, failed = null;
for (let i = 0; i < Math.round(120 / PHYSICS_DT) && !s.drained; i++) {
stepPhysics(s);
if (!Number.isFinite(s.ballX) || !Number.isFinite(s.ballY)) { failed = "non-finite"; break; }
const speed = Math.hypot(s.ballVx, s.ballVy);
if (speed < 6) stuckMs += PHYSICS_DT * 1000; else stuckMs = 0;
if (stuckMs > 1200 && Math.round(stuckMs) % 600 < PHYSICS_DT * 1000) {
for (const f of s.flippers) if (f.state === "rest") f.state = "rising";
}
if (stuckMs > 2500) { failed = `stuck at (${s.ballX.toFixed(0)},${s.ballY.toFixed(0)})`; break; }
policy(s);
}
if (failed) { bad++; console.log(`run ${run} power ${power}: ${failed}`); }
}
console.log(`\nrandom sweep: ${bad}/30 runs failed`);
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env bash
#
# resetAndRun.sh — rebuild Faceclaw and put a phone into an approximately
# never-had-faceclaw state for onboarding-flow testing, then install and
# launch the fresh build. Unlike resetOnboarding.sh this also forgets the
# glasses/ring Bluetooth pairings, and takes the target device explicitly
# (we test on several phones now, so no hardcoded default).
#
# Steps: build → uninstall → install → unpair "EVEN R1*" / "Even G2*" bonds
# → wipe app data + reset BLUETOOTH_CONNECT to undecided → launch.
#
# Usage:
# scripts/resetAndRun.sh <adb-device-id> # serial or host:port
#
# Android has no adb command to remove a Bluetooth bond, so the unpair step
# works through FaceclawDebugUnpairReceiver inside the app: we install the
# fresh build first, temporarily `pm grant` BLUETOOTH_CONNECT, broadcast the
# unpair request, then `pm clear` + revoke so the app still looks
# freshly-installed when it launches.
set -euo pipefail
PACKAGE="com.faceclaw.app"
UNPAIR_PREFIXES="EVEN R1,Even G2"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT="$(dirname "$SCRIPT_DIR")"
APK="$ROOT/platforms/android/app/build/outputs/apk/debug/app-debug.apk"
if [ $# -ne 1 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
sed -n '2,20p' "$0" | sed 's/^# \{0,1\}//'
exit 2
fi
DEVICE_ID="$1"
# Match build.sh's tool locations so adb is on PATH even from a bare shell.
export ANDROID_HOME="${ANDROID_HOME:-/Users/jbabcock/Library/Android/sdk}"
export PATH="$ANDROID_HOME/platform-tools:$PATH"
ADB="adb -s $DEVICE_ID"
# Network devices (host:port) need an explicit connect first.
case "$DEVICE_ID" in
*:*) adb connect "$DEVICE_ID" >/dev/null ;;
esac
if ! $ADB get-state >/dev/null 2>&1; then
echo "error: adb device '$DEVICE_ID' not connected." >&2
echo " Connected devices:" >&2
adb devices -l | sed '1d' >&2
exit 1
fi
echo "==> Building..."
"$ROOT/build.sh"
[ -f "$APK" ] || { echo "error: build produced no APK at $APK" >&2; exit 1; }
echo "==> Uninstalling $PACKAGE..."
$ADB uninstall "$PACKAGE" >/dev/null 2>&1 || echo " (was not installed)"
echo "==> Installing $(basename "$APK")..."
$ADB install "$APK"
echo "==> Unpairing Bluetooth devices matching: $UNPAIR_PREFIXES"
# The receiver needs BLUETOOTH_CONNECT; grant it just for this step. The
# whole remote command must be ONE quoted string — adb flattens multi-arg
# commands, which would lose the quoting around the space-containing extras.
$ADB shell pm grant "$PACKAGE" android.permission.BLUETOOTH_CONNECT
UNPAIR_OUT="$($ADB shell "am broadcast -n $PACKAGE/.FaceclawDebugUnpairReceiver \
-a com.faceclaw.app.action.DEBUG_UNPAIR --es prefixes '$UNPAIR_PREFIXES'")"
UNPAIR_RESULT="$(printf '%s\n' "$UNPAIR_OUT" | sed -n 's/.*data="\(.*\)".*/\1/p')"
echo " ${UNPAIR_RESULT:-no result from unpair receiver: $UNPAIR_OUT}"
case "$UNPAIR_RESULT" in
error:*|"") echo " WARNING: unpair step did not run cleanly; pairings may remain." >&2 ;;
esac
# Return the app to fresh-install state: the broadcast booted the app process
# (which may have written data), and the grant above must not leak into the
# onboarding permissions test. clear-permission-flags removes the user-set
# mark pm revoke leaves, so the permission dialog is still allowed to appear.
echo "==> Resetting app data and permissions to fresh-install state..."
$ADB shell am force-stop "$PACKAGE"
$ADB shell pm clear "$PACKAGE" >/dev/null
$ADB shell pm revoke "$PACKAGE" android.permission.BLUETOOTH_CONNECT
$ADB shell pm clear-permission-flags "$PACKAGE" \
android.permission.BLUETOOTH_CONNECT user-set user-fixed
echo "==> Launching..."
$ADB shell am start -n "$PACKAGE/com.tns.NativeScriptActivity" >/dev/null
echo "Done. Faceclaw should be starting its first-run onboarding."
+4
View File
@@ -0,0 +1,4 @@
#!/bin/bash
adb shell settings put secure show_ime_with_hard_keyboard 1
+92
View File
@@ -0,0 +1,92 @@
# Analytics report protocol
The phone app (app/analytics/) sends opt-in usage statistics to
`https://stats.faceclaw.org/v1/report`, at most about once a day per install,
plus hourly retries after a failure. Nothing is sent, or kept on the phone,
while Settings > Privacy > Data collection is None. What each level collects
is described in app/analytics/analytics-store.ts and in the privacy policy
(../PRIVACY); this file is the wire format.
## Request
`POST /v1/report` with a JSON body of at most 64 KiB:
```json
{
"schema": 1,
"reportId": "0f8fad5b-d9cb-469f-a165-70867728950e",
"installId": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
"level": "minimal",
"createdAt": "2026-10-10T12:00:00.000Z",
"app": { "version": "0.8.3", "platform": "android", "build": "official" },
"counters": { "2026-10-10": { "g2.connect-attempt": 3, "g2.session-ready": 3 } },
"snapshot": { "device.g2.paired": true, "device.r1.paired": false }
}
```
- `reportId`: a random UUID per report. The phone resends a report until it
gets a 2xx, so the server stores each id once and treats repeats as
success.
- `installId`: a random UUID made when analytics is first turned on, deleted
(with everything else) when it is turned off. It ties one install's reports
together and nothing else.
- `level`: `minimal` or `full`, the setting when the report was sent. A
minimal report carries only minimal data.
- `createdAt`: when the phone sealed the report (its counters may cover
earlier days, e.g. after a failed upload).
- `app.build`: `official` (signed with the release key), `self-built` (a
release build signed with another key), `debug` (a debuggable build), or
`unknown`.
- `counters`: UTC day, then counter name (`[a-z0-9][a-z0-9_.:-]*`), then a
non-negative integer count.
- `snapshot`: state when the report was sealed, as flat keys
(`[A-Za-z0-9][A-Za-z0-9_.:-]*`) to a boolean, number or string of up to 200
characters.
The server ignores unknown fields and rejects (400) a report with anything
malformed or over its limits (100 days, 2000 counters, 500 snapshot keys).
## Response
`200 {"ok": true}` once stored (or already stored). Errors are
`{"error": "..."}` with 400 (malformed, not retried), 405, 413 (too large),
429 (rate-limited by nginx, retried) or 500 (retried). Later versions may add
fields to the 200 response, such as the latest released version for update
checks.
## Current counters and snapshot keys
Minimal level:
| Name | Kind | Meaning |
| --- | --- | --- |
| `g2.connect-attempt`, `g2.session-ready` | counter | Connection attempts to the glasses, and those that got a working session |
| `g2.failure.<reason>` | counter | Transport failures that dropped or aborted a session, by reason (e.g. `ack-timeout`, `write-failed`, `glasses-not-found`, `left-arm-not-found`, `heartbeat-ack-timeout`, `cfw-recovery-retry-limit`) |
| `g2.session-end.<cause>` | counter | Working sessions ending: `failure`, `arm-drop`, `requested` |
| `g2.session-length.<bucket>` | counter | How long ended sessions lasted: `under-1m`, `1m-10m`, `10m-1h`, `over-1h` |
| `g2.arm-drop.left`, `g2.arm-drop.right` | counter | An arm's BLE link dropping mid-session |
| `g2.disconnect-requested` | counter | Disconnects the app asked for |
| `g2.unpaired`, `g2.incompatible-firmware` | counter | Connections halted for a missing bond or incompatible firmware |
| `g2.ack-timeout`, `g2.cfw-replay`, `g2.cfw-nack` | counter | Recovered message-level problems |
| `g2.firmware-abnormal-exit`, `g2.firmware-system-exit` | counter | Firmware closing the app's page outside a shutdown |
| `g2.auth-unacknowledged`, `g2.even-app-conflict` | counter | Security auth not acked; write failures blamed on the Even app |
| `ring.direct.connect`, `ring.direct.disconnect` | counter | Direct (not via glasses) R1 ring links |
| `ble.gatt-status.<code>` | counter | Android GATT connection-state callbacks with a non-success status (e.g. 8, 133) |
| `ble.ios-disconnect-error.<code>` | counter | iOS disconnects with an error |
| `device.g2.used`, `device.g2.touchpad-used`, `device.r1.used`, `device.wear.reachable`, `device.wear.used` | counter (1 per day) | Which devices were in use that day |
| `device.g2.paired`, `device.r1.paired` | snapshot | Whether glasses and a ring are paired |
| `device.g2.preview-only` | snapshot | Whether the app is in phone-preview-only mode |
| `device.r1.connection` | snapshot | `glasses` or `direct` ring connection |
Full level adds:
| Name | Kind | Meaning |
| --- | --- | --- |
| `apikey.<kind>` | snapshot | Whether an API key or token of that kind is set (`anthropic`, `openai`, `elevenlabs`, `soniox`, `mapbox`, `roam`, `nightscout`, `agent-bridge`, `evenhub`), never the key |
| `config.nightscout-site` | snapshot | Whether a Nightscout site is set (not its URL) |
| `config.terminal-connections`, `config.t3code-environments` | snapshot | How many are configured |
| `config.ui-font` | snapshot | The UI font: a bundled font's name and size, `installed:<size>` for a user-installed one, or the bitmap face |
| `setting.<key>` | snapshot | The value of every setting chosen from fixed options (on/off and pick-one settings), by its storage key; free-text settings are never included |
Connection counts are kept by the shared Kotlin session core
(ConnectionCounters.kt) and drained into the app's store every few minutes.
+64
View File
@@ -0,0 +1,64 @@
# stats.faceclaw.org
Receives the opt-in analytics reports the phone app sends (format:
PROTOCOL.md) and stores them in Postgres. A small Node server with no
framework, behind nginx on the `cumulus` VPS.
src/server.ts HTTP server: POST /v1/report, GET /healthz
src/report.ts report validation
src/db.ts storing a report
schema.sql tables and views (idempotent, applied on every deploy)
deploy.sh deploy from this working tree
deploy/ systemd unit, nginx site, env and one-time setup script
Node runs the TypeScript directly (type stripping, Node 22.18 or later), so
there is no build step. `npm run check` type-checks; `npm test` runs the
tests. The database test needs a scratch database:
`STATS_TEST_DATABASE=<name> npm test`, with the other `PG*` variables
pointing at its server.
## Deploying
./deploy.sh
copies this directory to `~/faceclaw-stats` on the server, installs the
dependencies, applies `schema.sql` and restarts the service. The first
time, it stops after copying, and the one-time root setup must be run there:
ssh -t cumulus 'sudo bash ~/faceclaw-stats/deploy/setup-server.sh'
That creates a Postgres role named after the deploy user and the
`faceclaw_stats` database on the Postgres 16 cluster (port 5433; the older
14 cluster on 5432 is left alone), installs and starts
`faceclaw-stats.service`, adds the nginx site, and gets its certificate
with certbot. It is safe to rerun. The nginx site is only installed the first
time, since certbot edits it afterwards, so later changes to
`deploy/nginx-site.conf` have to be made on the server too.
The service runs as the deploy user with `Restart=always`, so `deploy.sh`
restarts it by ending the process, without needing root.
## Privacy
nginx keeps no access log for this site and the server stores only the
report body, so the database has no IP addresses. Reports carry a random
install id that the phone deletes when analytics is turned off.
## Looking at the data
ssh cumulus psql -p 5433 faceclaw_stats
Views:
- `daily_counters`: counter totals per day, split by version, platform and
build, with how many installs reported each.
- `latest_reports`: each install's most recent report.
- `latest_snapshot_values`: snapshot values across installs' latest reports.
For example, installs and connection failures per version over the last
week:
select app_version, name, sum(total) as total, max(installs) as installs
from daily_counters
where day > current_date - 7 and name like 'g2.failure.%'
group by 1, 2 order by 1, 3 desc;
+32
View File
@@ -0,0 +1,32 @@
#!/bin/bash
# Deploys the stats server from this working tree to the VPS: copies the
# sources to ~/faceclaw-stats, installs dependencies and, once the one-time
# root setup (deploy/setup-server.sh) has been done, applies schema.sql and
# restarts the service. Set FACECLAW_STATS_HOST to deploy somewhere other
# than the `cumulus` ssh host.
set -euo pipefail
cd "$(dirname "$0")"
HOST="${FACECLAW_STATS_HOST:-cumulus}"
DIR=faceclaw-stats
rsync -az --delete --exclude node_modules --exclude .DS_Store ./ "$HOST:$DIR/"
ssh "$HOST" bash -s -- "$DIR" "$HOST" <<'REMOTE'
set -euo pipefail
cd "$HOME/$1"
export NVM_DIR="$HOME/.nvm"
. "$NVM_DIR/nvm.sh" >/dev/null
nvm use 22 >/dev/null
npm ci --omit=dev --no-audit --no-fund --loglevel=error --no-update-notifier
if [ ! -f /etc/systemd/system/faceclaw-stats.service ]; then
echo "Copied. Now run the one-time setup: ssh -t $2 'sudo bash ~/$1/deploy/setup-server.sh'"
exit 0
fi
set -a; . deploy/stats.env; set +a
psql -v ON_ERROR_STOP=1 -q -f schema.sql
# The service runs as this user with Restart=always, so ending the process
# restarts it on the new code without needing root.
pkill -TERM -u "$USER" -f "$PWD/src/server.ts" || true
sleep 3
systemctl is-active faceclaw-stats
curl -fsS "http://127.0.0.1:$PORT/healthz" && echo
REMOTE
@@ -0,0 +1,21 @@
# Template: setup-server.sh fills in @USER@ and @DIR@ and installs it as
# /etc/systemd/system/faceclaw-stats.service.
[Unit]
Description=Faceclaw stats server (stats.faceclaw.org)
After=network.target postgresql.service
[Service]
Type=simple
User=@USER@
WorkingDirectory=@DIR@
EnvironmentFile=@DIR@/deploy/stats.env
ExecStart=@DIR@/deploy/run.sh
# deploy.sh restarts the server by ending the process.
Restart=always
RestartSec=2
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=full
[Install]
WantedBy=multi-user.target
+33
View File
@@ -0,0 +1,33 @@
# stats.faceclaw.org, installed by setup-server.sh as
# /etc/nginx/sites-available/stats.faceclaw.org. certbot then adds the TLS
# server block and the HTTP-to-HTTPS redirect to the installed copy, so
# setup-server.sh never overwrites it; make later changes on the server too.
limit_req_zone $binary_remote_addr zone=faceclaw_stats:1m rate=10r/m;
server {
listen 80;
server_name stats.faceclaw.org;
# Reports are anonymous: don't keep the IP addresses they come from.
access_log off;
limit_req_log_level notice;
client_max_body_size 64k;
location = /v1/report {
limit_req zone=faceclaw_stats burst=20 nodelay;
limit_req_status 429;
proxy_pass http://127.0.0.1:8290;
proxy_http_version 1.1;
proxy_set_header Host $host;
}
location = /healthz {
proxy_pass http://127.0.0.1:8290;
}
location / {
default_type text/plain;
return 200 "Faceclaw's opt-in usage statistics endpoint. See https://faceclaw.org/privacy.html\n";
}
}
+9
View File
@@ -0,0 +1,9 @@
#!/bin/bash
# Started by faceclaw-stats.service, with deploy/stats.env in the environment.
# Node comes from nvm, as for the other services on this host.
cd "$(dirname "$0")/.."
export NVM_DIR="$HOME/.nvm"
. "$NVM_DIR/nvm.sh"
nvm use 22 >/dev/null
# The absolute path lets deploy.sh find this process to restart it.
exec node "$PWD/src/server.ts"
+57
View File
@@ -0,0 +1,57 @@
#!/bin/bash
# One-time root setup for the stats server on the VPS; safe to rerun. Run it
# via sudo, as the user that owns the deployed copy (deploy.sh puts it there):
#
# ssh -t cumulus 'sudo bash ~/faceclaw-stats/deploy/setup-server.sh'
#
# It creates a Postgres role (named after that user, so the service and
# psql connect by peer auth) and the database on the cluster in stats.env,
# installs and starts the systemd service, adds the nginx site, and gets the
# site's Let's Encrypt certificate with certbot.
set -euo pipefail
[ "$(id -u)" = 0 ] || { echo "Run this with sudo." >&2; exit 1; }
DEPLOY_USER="${SUDO_USER:?Run this via sudo from the user that owns the deployed copy.}"
DIR="$(cd "$(dirname "$0")/.." && pwd)"
DOMAIN=stats.faceclaw.org
set -a; . "$DIR/deploy/stats.env"; set +a
cd /
echo "== Postgres: role $DEPLOY_USER, database $PGDATABASE (port $PGPORT)"
pg_lsclusters --no-header | awk -v port="$PGPORT" '$3 == port && $4 == "online" { found = 1 } END { exit !found }' \
|| { echo "No online Postgres cluster on port $PGPORT." >&2; exit 1; }
sudo -u postgres psql -p "$PGPORT" -v ON_ERROR_STOP=1 -q -c \
"do \$\$ begin if not exists (select from pg_roles where rolname = '$DEPLOY_USER') then create role \"$DEPLOY_USER\" login; end if; end \$\$;"
if ! sudo -u postgres psql -p "$PGPORT" -Atc "select 1 from pg_database where datname = '$PGDATABASE'" | grep -q 1; then
sudo -u postgres createdb -p "$PGPORT" -O "$DEPLOY_USER" "$PGDATABASE"
fi
sudo -u "$DEPLOY_USER" psql -h "$PGHOST" -p "$PGPORT" -d "$PGDATABASE" -v ON_ERROR_STOP=1 -q -f "$DIR/schema.sql"
echo "== systemd: faceclaw-stats.service"
[ -d "$DIR/node_modules" ] || { echo "No node_modules in $DIR; run deploy.sh first." >&2; exit 1; }
sed -e "s|@USER@|$DEPLOY_USER|g" -e "s|@DIR@|$DIR|g" "$DIR/deploy/faceclaw-stats.service" \
> /etc/systemd/system/faceclaw-stats.service
systemctl daemon-reload
systemctl enable faceclaw-stats.service
systemctl restart faceclaw-stats.service
echo "== nginx: $DOMAIN"
SITE="/etc/nginx/sites-available/$DOMAIN"
# certbot edits the installed copy, so only install it the first time.
[ -e "$SITE" ] || cp "$DIR/deploy/nginx-site.conf" "$SITE"
ln -sf "$SITE" "/etc/nginx/sites-enabled/$DOMAIN"
if ! nginx -t; then
# Don't leave a broken site enabled: it would block reloads for every site.
rm -f "/etc/nginx/sites-enabled/$DOMAIN"
echo "nginx rejected the site config; it has been disabled again." >&2
exit 1
fi
systemctl reload nginx
echo "== TLS certificate"
if [ ! -d "/etc/letsencrypt/live/$DOMAIN" ]; then
certbot --nginx -d "$DOMAIN" --non-interactive --redirect
fi
echo "== Checking https://$DOMAIN/healthz"
sleep 2
curl -fsS "https://$DOMAIN/healthz" && echo
+7
View File
@@ -0,0 +1,7 @@
# Server settings, read by the systemd unit (EnvironmentFile) and sourced by
# setup-server.sh and deploy.sh. The database is on the Postgres 16 cluster
# (port 5433); the server's older 14 cluster on 5432 is left alone.
PORT=8290
PGHOST=/var/run/postgresql
PGPORT=5433
PGDATABASE=faceclaw_stats
+211
View File
@@ -0,0 +1,211 @@
{
"name": "faceclaw-stats-server",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "faceclaw-stats-server",
"license": "GPL-3.0-or-later",
"dependencies": {
"pg": "^8.16.3"
},
"devDependencies": {
"@types/node": "^22.18.0",
"@types/pg": "^8.15.5",
"typescript": "~5.9.0"
},
"engines": {
"node": ">=22.18"
}
},
"node_modules/@types/node": {
"version": "22.20.5",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/@types/pg": {
"version": "8.23.1",
"resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.23.1.tgz",
"integrity": "sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*",
"pg-protocol": "*",
"pg-types": "^2.2.0"
}
},
"node_modules/pg": {
"version": "8.23.1",
"resolved": "https://registry.npmjs.org/pg/-/pg-8.23.1.tgz",
"integrity": "sha512-aL96AHANtWjPLDOLqnhx+ngp9+UK7ETEU8VJrDCGvsSSi/mGLcWYsS6Herg7lmaBJe4uwrfqsa7gTEFaSizDoQ==",
"license": "MIT",
"dependencies": {
"pg-connection-string": "^2.14.1",
"pg-pool": "^3.14.0",
"pg-protocol": "^1.16.1",
"pg-types": "2.2.0",
"pgpass": "1.0.5"
},
"engines": {
"node": ">= 16.0.0"
},
"optionalDependencies": {
"pg-cloudflare": "^1.4.1"
},
"peerDependencies": {
"pg-native": ">=3.0.1"
},
"peerDependenciesMeta": {
"pg-native": {
"optional": true
}
}
},
"node_modules/pg-cloudflare": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.1.tgz",
"integrity": "sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==",
"license": "MIT",
"optional": true
},
"node_modules/pg-connection-string": {
"version": "2.14.1",
"resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.1.tgz",
"integrity": "sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA==",
"license": "MIT"
},
"node_modules/pg-int8": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",
"integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",
"license": "ISC",
"engines": {
"node": ">=4.0.0"
}
},
"node_modules/pg-pool": {
"version": "3.14.0",
"resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz",
"integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==",
"license": "MIT",
"peerDependencies": {
"pg": ">=8.0"
}
},
"node_modules/pg-protocol": {
"version": "1.16.1",
"resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.16.1.tgz",
"integrity": "sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==",
"license": "MIT"
},
"node_modules/pg-types": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",
"integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
"license": "MIT",
"dependencies": {
"pg-int8": "1.0.1",
"postgres-array": "~2.0.0",
"postgres-bytea": "~1.0.0",
"postgres-date": "~1.0.4",
"postgres-interval": "^1.1.0"
},
"engines": {
"node": ">=4"
}
},
"node_modules/pgpass": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",
"integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",
"license": "MIT",
"dependencies": {
"split2": "^4.1.0"
}
},
"node_modules/postgres-array": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
"integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",
"license": "MIT",
"engines": {
"node": ">=4"
}
},
"node_modules/postgres-bytea": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",
"integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/postgres-date": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",
"integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/postgres-interval": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",
"integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",
"license": "MIT",
"dependencies": {
"xtend": "^4.0.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/split2": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
"integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
"license": "ISC",
"engines": {
"node": ">= 10.x"
}
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"dev": true,
"license": "MIT"
},
"node_modules/xtend": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
"license": "MIT",
"engines": {
"node": ">=0.4"
}
}
}
}
+23
View File
@@ -0,0 +1,23 @@
{
"name": "faceclaw-stats-server",
"private": true,
"description": "Receives Faceclaw's opt-in analytics reports at stats.faceclaw.org and stores them in Postgres.",
"license": "GPL-3.0-or-later",
"type": "module",
"engines": {
"node": ">=22.18"
},
"scripts": {
"start": "node src/server.ts",
"check": "tsc -p tsconfig.json",
"test": "node --test test/*.test.ts"
},
"dependencies": {
"pg": "^8.16.3"
},
"devDependencies": {
"@types/node": "^22.18.0",
"@types/pg": "^8.15.5",
"typescript": "~5.9.0"
}
}
+57
View File
@@ -0,0 +1,57 @@
-- Schema for the analytics reports (PROTOCOL.md). Idempotent: deploy.sh
-- applies it on every deploy, so changes must be written as additive
-- `if not exists` / `create or replace` statements.
create table if not exists reports (
report_id uuid primary key,
install_id uuid not null,
received_at timestamptz not null default now(),
created_at timestamptz not null,
schema_version integer not null,
level text not null,
app_version text not null,
platform text not null,
build text not null,
-- The validated report as received, for anything the tables below don't cover.
payload jsonb not null
);
create index if not exists reports_received_at_idx on reports (received_at);
create index if not exists reports_install_idx on reports (install_id, received_at);
create table if not exists report_counters (
report_id uuid not null references reports (report_id) on delete cascade,
day date not null,
name text not null,
value bigint not null,
primary key (report_id, day, name)
);
create index if not exists report_counters_day_name_idx on report_counters (day, name);
create table if not exists report_snapshot (
report_id uuid not null references reports (report_id) on delete cascade,
key text not null,
value jsonb not null,
primary key (report_id, key)
);
-- Counter totals per day, split by version, platform and build, with how
-- many installs reported each.
create or replace view daily_counters as
select r.app_version, r.platform, r.build, c.day, c.name,
sum(c.value) as total, count(distinct r.install_id) as installs
from report_counters c
join reports r using (report_id)
group by r.app_version, r.platform, r.build, c.day, c.name;
-- Each install's most recent report.
create or replace view latest_reports as
select distinct on (install_id) *
from reports
order by install_id, received_at desc;
-- Snapshot values from each install's most recent report, counted.
create or replace view latest_snapshot_values as
select r.app_version, r.platform, s.key, s.value, count(*) as installs
from latest_reports r
join report_snapshot s using (report_id)
group by r.app_version, r.platform, s.key, s.value;
+69
View File
@@ -0,0 +1,69 @@
import type { Pool } from "pg";
import type { Report } from "./report.ts";
/**
* Stores one report and its rows in a single transaction. The phone keeps
* resending a report until it sees a 2xx, so a report id that is already
* stored is a retry whose response was lost, not new data.
*/
export async function saveReport(pool: Pool, report: Report): Promise<"saved" | "duplicate"> {
const client = await pool.connect();
try {
await client.query("begin");
const inserted = await client.query(
`insert into reports
(report_id, install_id, created_at, schema_version, level, app_version, platform, build, payload)
values ($1, $2, $3, $4, $5, $6, $7, $8, $9)
on conflict (report_id) do nothing`,
[
report.reportId,
report.installId,
report.createdAt,
report.schema,
report.level,
report.app.version,
report.app.platform,
report.app.build,
JSON.stringify(report),
],
);
if (inserted.rowCount === 0) {
await client.query("rollback");
return "duplicate";
}
const days: string[] = [];
const names: string[] = [];
const values: number[] = [];
for (const [day, counts] of Object.entries(report.counters)) {
for (const [name, value] of Object.entries(counts)) {
days.push(day);
names.push(name);
values.push(value);
}
}
if (names.length) {
await client.query(
`insert into report_counters (report_id, day, name, value)
select $1, day::date, name, value from unnest($2::text[], $3::text[], $4::bigint[]) as t(day, name, value)`,
[report.reportId, days, names, values],
);
}
const keys = Object.keys(report.snapshot);
if (keys.length) {
await client.query(
`insert into report_snapshot (report_id, key, value)
select $1, key, value from unnest($2::text[], $3::jsonb[]) as t(key, value)`,
[report.reportId, keys, keys.map((key) => JSON.stringify(report.snapshot[key]))],
);
}
await client.query("commit");
return "saved";
} catch (error) {
await client.query("rollback").catch(() => undefined);
throw error;
} finally {
client.release();
}
}
+126
View File
@@ -0,0 +1,126 @@
/**
* The analytics report format the phone app uploads (PROTOCOL.md), and its
* validation. The app-side producer is app/analytics/analytics-report.ts;
* keep the two in step.
*
* Everything is checked against tight limits so a malformed or hostile
* client can't store much: unknown fields are ignored, and anything
* out of range rejects the whole report.
*/
export const REPORT_SCHEMA_VERSION = 1;
export type ReportLevel = "minimal" | "full";
export type SnapshotValue = boolean | number | string;
export interface Report {
schema: number;
reportId: string;
installId: string;
level: ReportLevel;
/** When the phone sealed the report (ISO 8601). */
createdAt: string;
app: { version: string; platform: string; build: string };
/** UTC day (YYYY-MM-DD) → counter name → count. */
counters: Record<string, Record<string, number>>;
/** Point-in-time state (devices, API-key presence, settings), flat namespaced keys. */
snapshot: Record<string, SnapshotValue>;
}
export class ReportError extends Error {}
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
const VERSION = /^[0-9A-Za-z.+-]{1,32}$/;
const TOKEN = /^[a-z0-9-]{1,24}$/;
const DAY = /^\d{4}-\d{2}-\d{2}$/;
const COUNTER_NAME = /^[a-z0-9][a-z0-9_.:-]{0,119}$/;
// Snapshot keys embed the app's settings keys, which are camelCase.
const SNAPSHOT_KEY = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,119}$/;
const MAX_DAYS = 100;
const MAX_COUNTERS = 2000;
const MAX_COUNT = 1_000_000_000;
const MAX_SNAPSHOT_KEYS = 500;
const MAX_SNAPSHOT_STRING = 200;
export function parseReport(value: unknown): Report {
const body = record(value, "report");
if (body.schema !== REPORT_SCHEMA_VERSION) throw new ReportError(`unsupported schema ${String(body.schema)}`);
const level = body.level;
if (level !== "minimal" && level !== "full") throw new ReportError("bad level");
const app = record(body.app, "app");
return {
schema: REPORT_SCHEMA_VERSION,
reportId: uuid(body.reportId, "reportId"),
installId: uuid(body.installId, "installId"),
level,
createdAt: timestamp(body.createdAt, "createdAt"),
app: {
version: matching(app.version, VERSION, "app.version"),
platform: matching(app.platform, TOKEN, "app.platform"),
build: matching(app.build, TOKEN, "app.build"),
},
counters: counters(body.counters ?? {}),
snapshot: snapshot(body.snapshot ?? {}),
};
}
function counters(value: unknown): Report["counters"] {
const days = record(value, "counters");
const dayKeys = Object.keys(days);
if (dayKeys.length > MAX_DAYS) throw new ReportError("too many days");
const result: Report["counters"] = {};
let total = 0;
for (const day of dayKeys) {
if (!DAY.test(day) || Number.isNaN(Date.parse(`${day}T00:00:00Z`))) throw new ReportError(`bad day ${day}`);
const entries = record(days[day], `counters.${day}`);
const counts: Record<string, number> = {};
for (const [name, count] of Object.entries(entries)) {
if (!COUNTER_NAME.test(name)) throw new ReportError(`bad counter name ${name}`);
if (typeof count !== "number" || !Number.isSafeInteger(count) || count < 0 || count > MAX_COUNT) {
throw new ReportError(`bad count for ${name}`);
}
if (++total > MAX_COUNTERS) throw new ReportError("too many counters");
counts[name] = count;
}
result[day] = counts;
}
return result;
}
function snapshot(value: unknown): Report["snapshot"] {
const entries = Object.entries(record(value, "snapshot"));
if (entries.length > MAX_SNAPSHOT_KEYS) throw new ReportError("too many snapshot keys");
const result: Report["snapshot"] = {};
for (const [key, item] of entries) {
if (!SNAPSHOT_KEY.test(key)) throw new ReportError(`bad snapshot key ${key}`);
const ok =
typeof item === "boolean" ||
(typeof item === "number" && Number.isFinite(item)) ||
(typeof item === "string" && item.length <= MAX_SNAPSHOT_STRING);
if (!ok) throw new ReportError(`bad snapshot value for ${key}`);
result[key] = item;
}
return result;
}
function record(value: unknown, what: string): Record<string, unknown> {
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new ReportError(`${what} must be an object`);
return value as Record<string, unknown>;
}
function uuid(value: unknown, what: string): string {
const text = typeof value === "string" ? value.toLowerCase() : "";
if (!UUID.test(text)) throw new ReportError(`bad ${what}`);
return text;
}
function matching(value: unknown, pattern: RegExp, what: string): string {
if (typeof value !== "string" || !pattern.test(value)) throw new ReportError(`bad ${what}`);
return value;
}
function timestamp(value: unknown, what: string): string {
if (typeof value !== "string" || value.length > 40 || Number.isNaN(Date.parse(value))) throw new ReportError(`bad ${what}`);
return new Date(value).toISOString();
}
+91
View File
@@ -0,0 +1,91 @@
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import { Pool } from "pg";
import { saveReport } from "./db.ts";
import { parseReport, ReportError } from "./report.ts";
/**
* Receives the phone app's daily analytics reports (PROTOCOL.md) and stores
* them in Postgres. Runs behind nginx, which terminates TLS and rate-limits;
* the database connection comes from the standard PG* environment variables.
*
* Nothing about the request itself is stored or logged: no IP address, no
* headers, only the report body.
*/
const PORT = Number(process.env.PORT ?? 8290);
const HOST = process.env.HOST ?? "127.0.0.1";
const MAX_BODY_BYTES = 64 * 1024;
const pool = new Pool({ max: 4 });
pool.on("error", (error) => console.error("idle database client failed:", error.message));
const server = createServer((request, response) => {
handle(request, response).catch((error: unknown) => {
console.error("request failed:", error instanceof Error ? error.message : error);
if (!response.headersSent) reply(response, 500, { error: "internal error" });
});
});
async function handle(request: IncomingMessage, response: ServerResponse): Promise<void> {
const path = (request.url ?? "/").split("?")[0];
if (path === "/v1/report") {
if (request.method !== "POST") return reply(response, 405, { error: "POST only" });
if (Number(request.headers["content-length"] ?? 0) > MAX_BODY_BYTES) {
response.setHeader("connection", "close");
return reply(response, 413, { error: "too large" });
}
const body = await readBody(request);
if (body === null) return reply(response, 413, { error: "too large" });
let report;
try {
report = parseReport(JSON.parse(body));
} catch (error) {
if (error instanceof SyntaxError || error instanceof ReportError) {
return reply(response, 400, { error: error.message });
}
throw error;
}
await saveReport(pool, report);
// Room for more later (e.g. the latest released version, for update checks).
return reply(response, 200, { ok: true });
}
if (path === "/healthz" && request.method === "GET") {
await pool.query("select 1");
return reply(response, 200, { ok: true });
}
reply(response, 404, { error: "not found" });
}
/**
* The request body as text, or null if it is over MAX_BODY_BYTES. An
* oversized body is still read to the end (and dropped) so the client gets
* the 413 instead of a reset connection; nginx caps it before it gets here.
*/
function readBody(request: IncomingMessage): Promise<string | null> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
let size = 0;
request.on("data", (chunk: Buffer) => {
size += chunk.length;
if (size <= MAX_BODY_BYTES) chunks.push(chunk);
});
request.on("end", () => resolve(size > MAX_BODY_BYTES ? null : Buffer.concat(chunks).toString("utf8")));
request.on("error", reject);
});
}
function reply(response: ServerResponse, status: number, body: object): void {
response.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
response.end(JSON.stringify(body));
}
function shutdown(): void {
server.close(() => {
void pool.end().finally(() => process.exit(0));
});
setTimeout(() => process.exit(0), 5000).unref();
}
process.on("SIGTERM", shutdown);
process.on("SIGINT", shutdown);
server.listen(PORT, HOST, () => console.log(`faceclaw-stats listening on ${HOST}:${PORT}`));
+43
View File
@@ -0,0 +1,43 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "node:test";
import { Pool } from "pg";
import { saveReport } from "../src/db.ts";
import { parseReport } from "../src/report.ts";
import { sampleReport } from "./sample.ts";
// Needs a scratch database: set STATS_TEST_DATABASE to its name (the other
// PG* variables pick the server). The tables are created if missing, and
// emptied before the test.
const database = process.env.STATS_TEST_DATABASE;
void test("stores a report once, with its counters and snapshot", { skip: !database && "STATS_TEST_DATABASE not set" }, async () => {
const pool = new Pool({ database });
try {
await pool.query(readFileSync(new URL("../schema.sql", import.meta.url), "utf8"));
await pool.query("truncate reports cascade");
const report = parseReport(sampleReport());
assert.equal(await saveReport(pool, report), "saved");
assert.equal(await saveReport(pool, report), "duplicate");
const counters = await pool.query(
"select day::text, name, value::int from report_counters order by day, name",
);
assert.deepEqual(counters.rows, [
{ day: "2026-10-09", name: "g2.connect", value: 3 },
{ day: "2026-10-09", name: "g2.disconnect", value: 2 },
{ day: "2026-10-10", name: "g2.connect", value: 1 },
]);
const snapshot = await pool.query("select key, value from report_snapshot order by key");
assert.deepEqual(snapshot.rows, [
{ key: "apikey.anthropic", value: false },
{ key: "device.g2.paired", value: true },
{ key: "setting.ui-font", value: "Roboto-Light.ttf:16" },
]);
const daily = await pool.query("select total::int, installs::int from daily_counters where name = 'g2.connect' and day = '2026-10-09'");
assert.deepEqual(daily.rows, [{ total: 3, installs: 1 }]);
} finally {
await pool.end();
}
});
+61
View File
@@ -0,0 +1,61 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { parseReport, ReportError } from "../src/report.ts";
import { sampleReport } from "./sample.ts";
void test("accepts a well-formed report and normalizes ids and timestamps", () => {
const report = parseReport(
sampleReport({ reportId: "0F8FAD5B-D9CB-469F-A165-70867728950E", createdAt: "2026-10-10T08:00:00-04:00" }),
);
assert.equal(report.reportId, "0f8fad5b-d9cb-469f-a165-70867728950e");
assert.equal(report.createdAt, "2026-10-10T12:00:00.000Z");
assert.deepEqual(report.counters["2026-10-09"], { "g2.connect": 3, "g2.disconnect": 2 });
assert.equal(report.snapshot["setting.ui-font"], "Roboto-Light.ttf:16");
});
void test("accepts camelCase snapshot keys but only lowercase counter names", () => {
assert.equal(parseReport(sampleReport({ snapshot: { "setting.display.timeFormat": "12h" } })).snapshot["setting.display.timeFormat"], "12h");
assert.throws(() => parseReport(sampleReport({ counters: { "2026-10-10": { "g2.Connect": 1 } } })), ReportError);
});
void test("ignores unknown fields", () => {
const report = parseReport(sampleReport({ extra: "x" }));
assert.equal("extra" in report, false);
});
void test("rejects malformed reports", () => {
const bad: Record<string, unknown>[] = [
{ schema: 2 },
{ level: "everything" },
{ reportId: "not-a-uuid" },
{ app: { version: "0.8.3; drop table", platform: "android", build: "official" } },
{ app: { version: "0.8.3", platform: "Android", build: "official" } },
{ createdAt: "yesterday" },
{ counters: { "2026-13-45": { a: 1 } } },
{ counters: { "2026-10-10": { "Bad Name": 1 } } },
{ counters: { "2026-10-10": { a: -1 } } },
{ counters: { "2026-10-10": { a: 1.5 } } },
{ counters: [] },
{ snapshot: { a: { nested: true } } },
{ snapshot: { "bad key": true } },
{ snapshot: { a: "x".repeat(201) } },
{ snapshot: { a: Number.NaN } },
];
for (const overrides of bad) {
assert.throws(() => parseReport(sampleReport(overrides)), ReportError, JSON.stringify(overrides));
}
assert.throws(() => parseReport(null), ReportError);
assert.throws(() => parseReport([]), ReportError);
});
void test("caps how many counters and snapshot keys a report may carry", () => {
const manyDays: Record<string, Record<string, number>> = {};
for (let day = 0; day < 101; day++) {
manyDays[new Date(Date.UTC(2026, 0, 1 + day)).toISOString().slice(0, 10)] = { a: 1 };
}
assert.throws(() => parseReport(sampleReport({ counters: manyDays })), /too many days/);
const manyKeys: Record<string, boolean> = {};
for (let index = 0; index < 501; index++) manyKeys[`k${index}`] = true;
assert.throws(() => parseReport(sampleReport({ snapshot: manyKeys })), /too many snapshot keys/);
});
+14
View File
@@ -0,0 +1,14 @@
/** A valid report body, with top-level fields replaced by `overrides`. */
export function sampleReport(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
schema: 1,
reportId: "0f8fad5b-d9cb-469f-a165-70867728950e",
installId: "7c9e6679-7425-40de-944b-e07fc1f90ae7",
level: "full",
createdAt: "2026-10-10T12:00:00.000Z",
app: { version: "0.8.3", platform: "android", build: "official" },
counters: { "2026-10-09": { "g2.connect": 3, "g2.disconnect": 2 }, "2026-10-10": { "g2.connect": 1 } },
snapshot: { "device.g2.paired": true, "apikey.anthropic": false, "setting.ui-font": "Roboto-Light.ttf:16" },
...overrides,
};
}
+17
View File
@@ -0,0 +1,17 @@
{
// Node runs the .ts sources directly (type stripping, Node >= 22.18), so
// this is for type checking only.
"compilerOptions": {
"target": "ES2023",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"noEmit": true,
"allowImportingTsExtensions": true,
"erasableSyntaxOnly": true,
"verbatimModuleSyntax": true,
"skipLibCheck": true,
"types": ["node"]
},
"include": ["src/**/*", "test/**/*"]
}
+205
View File
@@ -0,0 +1,205 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { loader } = require('./helpers/load-typescript.cjs');
const DAY_MS = 24 * 60 * 60 * 1000;
const HOUR_MS = 60 * 60 * 1000;
const START = Date.parse('2026-10-10T12:00:00Z');
/** analytics-store.ts over in-memory files, a settable clock and setting, and a fake server. */
function harness({ level = 'minimal', version = '0.8.3', statuses = [] } = {}) {
const files = new Map();
const sent = [];
const h = {
files, sent, level, version, now: START, statuses: [...statuses],
pendingSend: null,
snapshots: { minimal: { 'device.g2.paired': true }, full: { 'apikey.anthropic': true } },
};
let nextId = 1;
const { AnalyticsStore } = loader({
setTimeout: () => 0,
clearTimeout: () => {},
})('app/analytics/analytics-store.ts');
h.store = new AnalyticsStore({
storage: {
read: name => files.get(name) ?? null,
write: (name, text) => files.set(name, text),
remove: name => files.delete(name),
list: () => [...files.keys()],
removeAll: () => files.clear(),
},
level: () => h.level,
appInfo: () => ({ version: h.version, platform: 'android', build: 'official' }),
now: () => h.now,
randomId: () => `00000000-0000-4000-8000-${String(nextId++).padStart(12, '0')}`,
snapshot: level => ({ ...h.snapshots[level] }),
send: async body => {
sent.push(JSON.parse(body));
if (h.pendingSend) await h.pendingSend;
const status = h.statuses.length ? h.statuses.shift() : 200;
if (status === 'network') throw new Error('offline');
return status;
},
});
h.outbox = () => [...files.keys()].filter(name => name.startsWith('outbox-'));
h.state = () => JSON.parse(files.get('state.json'));
return h;
}
test('Analytics keeps only what the data-collection setting allows', () => {
const h = harness({ level: 'minimal' });
h.store.count('minimal', 'g2.connect');
h.store.count('full', 'app.launch.timer');
h.store.flush();
const pending = JSON.parse(h.files.get('pending.json'));
assert.deepEqual(pending.counters.minimal, { '2026-10-10': { 'g2.connect': 1 } });
assert.deepEqual(pending.counters.full, {});
const off = harness({ level: 'none' });
off.store.count('minimal', 'g2.connect');
off.store.flush();
off.store.applyLevel();
assert.equal(off.files.size, 0);
});
test('Analytics drops bad counter names and flags count once a day', () => {
const h = harness();
h.store.count('minimal', 'Bad Name');
h.store.flag('minimal', 'device.r1.used');
h.store.flag('minimal', 'device.r1.used');
h.store.count('minimal', 'g2.ack-timeout', 3);
h.store.flush();
assert.deepEqual(JSON.parse(h.files.get('pending.json')).counters.minimal['2026-10-10'], {
'device.r1.used': 1, 'g2.ack-timeout': 3,
});
});
test('Analytics seals and uploads a report once a day', async () => {
const h = harness({ level: 'full' });
h.store.count('minimal', 'g2.connect', 2);
h.store.count('full', 'feature.used');
await h.store.uploadIfDue();
assert.equal(h.sent.length, 1);
const [report] = h.sent;
assert.equal(report.schema, 1);
assert.equal(report.level, 'full');
assert.match(report.installId, /^00000000-/);
assert.deepEqual(report.app, { version: '0.8.3', platform: 'android', build: 'official' });
assert.deepEqual(report.counters, { '2026-10-10': { 'g2.connect': 2, 'feature.used': 1 } });
assert.deepEqual(report.snapshot, { 'device.g2.paired': true, 'apikey.anthropic': true });
assert.deepEqual(h.outbox(), []);
h.store.count('minimal', 'g2.connect');
h.now += 3 * HOUR_MS;
await h.store.uploadIfDue();
assert.equal(h.sent.length, 1, 'not due again the same day');
h.now = START + DAY_MS;
await h.store.uploadIfDue();
assert.equal(h.sent.length, 2);
assert.equal(h.sent[1].installId, report.installId);
assert.notEqual(h.sent[1].reportId, report.reportId);
assert.deepEqual(h.sent[1].counters, { '2026-10-10': { 'g2.connect': 1 } });
});
test('Analytics retries a failed upload hourly with the same report id, and drops rejected ones', async () => {
const h = harness({ statuses: ['network', 503] });
h.store.count('minimal', 'g2.connect');
await h.store.uploadIfDue();
assert.equal(h.outbox().length, 1);
h.now += 30 * 60 * 1000;
await h.store.uploadIfDue();
assert.equal(h.sent.length, 1, 'no retry within the hour');
h.now = START + HOUR_MS;
await h.store.uploadIfDue();
assert.equal(h.sent.length, 2);
assert.equal(h.sent[1].reportId, h.sent[0].reportId);
assert.equal(h.outbox().length, 1, 'kept after a 503');
h.now = START + 2 * HOUR_MS;
await h.store.uploadIfDue();
assert.equal(h.sent.length, 3);
assert.deepEqual(h.outbox(), []);
assert.equal(h.state().retryAt, 0);
const rejected = harness({ statuses: [400] });
await rejected.store.uploadIfDue();
assert.deepEqual(rejected.outbox(), [], 'a 400 is not retried');
});
test('Analytics turned off deletes everything, and a new install id is made when it comes back', async () => {
const h = harness();
h.store.count('minimal', 'g2.connect');
await h.store.uploadIfDue();
const firstInstall = h.sent[0].installId;
h.store.count('minimal', 'g2.connect');
h.store.flush();
h.level = 'none';
h.store.applyLevel();
assert.equal(h.files.size, 0);
await h.store.uploadIfDue();
assert.equal(h.sent.length, 1, 'no connection while off');
h.level = 'minimal';
h.now += DAY_MS;
await h.store.uploadIfDue();
assert.equal(h.sent.length, 2);
assert.notEqual(h.sent[1].installId, firstInstall);
assert.deepEqual(h.sent[1].counters, {}, 'counts from before turning off are gone');
});
test('Analytics turned down to minimal drops what was kept for full', async () => {
const h = harness({ level: 'full', statuses: ['network'] });
h.store.count('minimal', 'g2.connect');
h.store.count('full', 'feature.used');
await h.store.uploadIfDue();
h.store.count('full', 'feature.used');
h.store.flush();
h.level = 'minimal';
h.store.applyLevel();
assert.deepEqual(JSON.parse(h.files.get('pending.json')).counters.full, {});
const [outbox] = h.outbox();
assert.deepEqual(JSON.parse(h.files.get(outbox)).snapshot.full, {});
h.now += HOUR_MS;
await h.store.uploadIfDue();
const retried = h.sent[1];
assert.equal(retried.level, 'minimal');
assert.deepEqual(retried.counters, { '2026-10-10': { 'g2.connect': 1 } });
assert.deepEqual(retried.snapshot, { 'device.g2.paired': true });
});
test('Analytics sends counts from before an upgrade under the old version', async () => {
const h = harness({ version: '0.8.3' });
h.store.count('minimal', 'g2.connect');
h.store.flush();
// A new process after the upgrade.
const files = h.files;
const upgraded = harness({ version: '0.8.4' });
for (const [name, text] of files) upgraded.files.set(name, text);
upgraded.store.count('minimal', 'g2.connect', 5);
await upgraded.store.uploadIfDue();
assert.deepEqual(upgraded.sent.map(report => [report.app.version, report.counters['2026-10-10']]), [
['0.8.3', { 'g2.connect': 1 }],
['0.8.4', { 'g2.connect': 5 }],
]);
});
test('Analytics turned off and on during an upload keeps none of the old state', async () => {
const h = harness();
let release;
h.pendingSend = new Promise(resolve => { release = resolve; });
const upload = h.store.uploadIfDue();
await Promise.resolve();
h.level = 'none';
h.store.applyLevel();
h.level = 'minimal';
release();
await upload;
assert.equal(h.files.size, 0, 'the old install id is not written back');
});
+27 -21
View File
@@ -269,31 +269,37 @@ test('iOS compositor rejects missing and removed surfaces before crossing into K
assert.equal(nativeSubmissions, 1); assert.equal(nativeSubmissions, 1);
}); });
test('iOS welcome sound waits for a new acknowledged frame and is consumed once', async () => { test('iOS opens the on-glasses onboarding on a new acknowledged frame, once per run while due', () => {
let pending = true; const settings = new Map();
const played = [], sounds = load('app/ui/sound-effects.ts', { require: name => { assert.equal(name, '../g2/cfw-message-type'); return load('app/g2/cfw-message-type.ts', {}); } }); const progress = load('app/apps/onboarding/onboarding-progress.ts', {
const { IosPreviewController } = load('app/g2/ios-preview-controller.ts', {
require: id => ({ require: id => ({
'../phone-ui/onboarding-state': { isWelcomeSoundPending: () => pending, setWelcomeSoundPending: value => { pending = value; } }, '../../native/settings-store': {
'../ui/sound-effects': sounds, getStringSetting: (key, fallback) => settings.get(key) ?? fallback,
})[id] ?? {}, setStringSetting: (key, value) => settings.set(key, value),
setTimeout: fn => { fn(); return 1; }, },
'../../version': { FACECLAW_VERSION: '9.9.9' },
})[id],
});
const launched = [];
const { IosPreviewController } = load('app/g2/ios-preview-controller.ts', {
require: id => ({ '../apps/onboarding/onboarding-progress': progress })[id] ?? {},
}); });
const host = Object.create(IosPreviewController.prototype); const host = Object.create(IosPreviewController.prototype);
host.acknowledgedFrames = 0; host.acknowledgedFrames = 0;
host.actions = { playBuzzerSequence: bytes => played.push([...bytes]) }; host.launchApp = id => { launched.push(id); return Promise.resolve(); };
host.logBluetooth = assert.fail; host.maybeLaunchOnboarding({ phase: 'connecting', frames: 0 });
host.maybePlayWelcomeSound({ phase: 'connecting', frames: 0 }); host.maybeLaunchOnboarding({ phase: 'connected', frames: 0 });
host.maybePlayWelcomeSound({ phase: 'connected', frames: 0 }); assert.deepEqual(launched, []);
assert.equal(pending, true); assert.equal(played.length, 0); host.maybeLaunchOnboarding({ phase: 'connected', frames: 1 });
host.maybePlayWelcomeSound({ phase: 'connected', frames: 1 }); assert.deepEqual(launched, ['onboarding']);
assert.equal(pending, false); // Still unfinished, but a reconnect in the same run doesn't reopen it.
await new Promise(resolve => setImmediate(resolve)); host.maybeLaunchOnboarding({ phase: 'connected', frames: 2 });
assert.ok(played.length > 0); assert.deepEqual(launched, ['onboarding']);
const count = played.length; assert.equal(progress.isGlassesOnboardingDue(), true);
host.maybePlayWelcomeSound({ phase: 'connected', frames: 1 }); progress.markGlassesOnboardingFinished();
host.maybePlayWelcomeSound({ phase: 'connected', frames: 2 }); assert.equal(progress.isGlassesOnboardingDue(), false);
assert.equal(played.length, count); settings.set('onboarding.glassesFinishedVersion', '9.9.8');
assert.equal(progress.isGlassesOnboardingDue(), true, 'an upgrade makes onboarding due again');
}); });
test('iOS preview voice uses the phone microphone, while connected capture stays on glasses', async () => { test('iOS preview voice uses the phone microphone, while connected capture stays on glasses', async () => {
+1 -2
View File
@@ -153,8 +153,7 @@ function fixture() {
'../apps/evenhub/installed-apps': {}, '../apps/evenhub/manager': {}, '../apps/evenhub/updates': {}, '../apps/evenhub': {}, '../apps/evenhub/installed-apps': {}, '../apps/evenhub/manager': {}, '../apps/evenhub/updates': {}, '../apps/evenhub': {},
'../apps/launcher/launcher-app': { createLauncherWindow: () => window, LAUNCHER_SURFACE_ID: 'launcher' }, '../apps/launcher/launcher-app': { createLauncherWindow: () => window, LAUNCHER_SURFACE_ID: 'launcher' },
'../apps/all-apps': { ALL_APPS: [{ appId: 'glanceboard', glanceboard: provider }] }, '../apps/all-apps': { ALL_APPS: [{ appId: 'glanceboard', glanceboard: provider }] },
'../phone-ui/onboarding-state': { isWelcomeSoundPending: () => false }, '../apps/onboarding/onboarding-progress': { claimGlassesOnboardingAutoLaunch: () => false },
'../ui/sound-effects': {},
'../ui/shell/worker-window': {}, '../ui/shell/in-process-window': {}, '../ui/shell/worker-window': {}, '../ui/shell/in-process-window': {},
'../ui/dashboard-settings': { brightnessSetting: { get: () => 'auto' }, brightnessSettingToLevel: () => null, getBrightnessPreferences: () => ({ auto: true, level: 50, minimum: 2, maximum: 100, curve: '0:0,1000:100', fadeMs: 280 }), lockScreenEnabledSetting: { get: () => settings.lock }, onAnySettingChanged: fn => { settingsChanged = fn; return () => {}; }, previewColorSetting: { get: () => 'white' } }, '../ui/dashboard-settings': { brightnessSetting: { get: () => 'auto' }, brightnessSettingToLevel: () => null, getBrightnessPreferences: () => ({ auto: true, level: 50, minimum: 2, maximum: 100, curve: '0:0,1000:100', fadeMs: 280 }), lockScreenEnabledSetting: { get: () => settings.lock }, onAnySettingChanged: fn => { settingsChanged = fn; return () => {}; }, previewColorSetting: { get: () => 'white' } },
'../native/phone-battery': { readPhoneBatteryState: () => ({ battery: 80, charging: false }) }, '../native/phone-battery': { readPhoneBatteryState: () => ({ battery: 80, charging: false }) },
@@ -0,0 +1,33 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
class ConnectionCountersTest {
@Test
fun drainReturnsTheCountsSinceTheLastDrain() {
ConnectionCounters.drain()
ConnectionCounters.increment("g2.connect-attempt")
ConnectionCounters.increment("g2.connect-attempt")
ConnectionCounters.increment("g2.session-ready")
assertEquals("""{"g2.connect-attempt":2,"g2.session-ready":1}""", ConnectionCounters.drain())
assertEquals("{}", ConnectionCounters.drain())
}
@Test
fun keepsCountingKnownNamesPastTheNameCap() {
ConnectionCounters.drain()
for (index in 0 until 250) ConnectionCounters.increment("name-$index")
ConnectionCounters.increment("name-0")
val drained = Json.parseObject(ConnectionCounters.drain())
assertEquals(200, drained.size)
assertEquals(JsonNumber("2"), drained["name-0"])
}
@Test
fun slugsFailureReasons() {
assertEquals("cfw-recovery-retry-limit", ConnectionCounters.slug("CFW recovery retry limit"))
assertEquals("left-arm-not-found", ConnectionCounters.slug("left arm not found"))
assertEquals("evenhub-resume-prelude-failed", ConnectionCounters.slug("EvenHub resume prelude failed"))
}
}
+25 -1
View File
@@ -27,7 +27,31 @@
<div class="wrap prose"> <div class="wrap prose">
<!-- BEGIN GENERATED: privacy --> <!-- BEGIN GENERATED: privacy -->
<h1>Faceclaw Privacy Policy</h1> <h1>Faceclaw Privacy Policy</h1>
<p>Faceclaw is a privacy-conscious app. The developers of Faceclaw don't collect or store user data. Faceclaw does integrate with some third-party services, which have their own privacy policies; this document describes what those services are, what they're used for and what data they collect, and links to their privacy policies.</p> <p>Faceclaw is a privacy-conscious app. Unless you choose to share anonymous usage statistics (described below), the developers of Faceclaw don't collect or store any data about you or how you use the app. Faceclaw does integrate with some third-party services, which have their own privacy policies; this document describes what those services are, what they're used for and what data they collect, and links to their privacy policies.</p>
<h2>Usage Statistics</h2>
<p>The first time you connect your glasses, Faceclaw asks whether to share anonymous usage statistics with its developers, to help them fix problems and improve the app. The choices are None, Minimal and Full, and you can change your choice at any time in Settings &gt; Privacy. Until you choose, it is None.</p>
<p>With None, Faceclaw sends nothing and keeps no statistics on your phone.</p>
<p>With Minimal, Faceclaw keeps counts on your phone and sends them about once a day to stats.faceclaw.org, a server run by Faceclaw's developers:</p>
<ul class="links">
<li>- the Faceclaw version, whether it runs on Android or iOS, and whether it is</li>
<li>an official release or a build someone compiled themselves;</li>
<li>- whether glasses and a ring are paired, and which devices (glasses, ring,</li>
<li>Wear OS watch) were in use each day;</li>
<li>- counts of connection events: connection attempts, disconnections and</li>
<li>their causes, message timeouts and retries, Bluetooth error codes, and</li>
<li>how long connections lasted.</li>
</ul>
<p>With Full, it also sends:</p>
<ul class="links">
<li>- which kinds of API key are set (for example, that an Anthropic key is</li>
<li>set), but never the keys themselves;</li>
<li>- how many terminal and T3 Code connections are set up, and which of</li>
<li>Faceclaw's built-in fonts is in use;</li>
<li>- the values of settings chosen from fixed options, such as on/off</li>
<li>switches and pick-one lists. Settings you type in, such as addresses,</li>
<li>URLs and names, are never sent.</li>
</ul>
<p>Statistics never include your name or contact details, your location, Bluetooth device addresses, anything you say or type, or what is shown on your glasses. Each report carries a random identifier, created when you turn statistics on, which links your reports to each other but not to you. Turning statistics off deletes that identifier and everything kept on the phone, and stops all reports; turning them back on starts a new identifier. The statistics server doesn't record the IP addresses reports come from.</p>
<h2>Audio</h2> <h2>Audio</h2>
<p>Faceclaw allows users to transcribe audio (for use with the voice assistant, the Transcribe app, typing into Terminal, and other apps). The default setting is that this is done using an on-device model running on your phone. If an on-device model is selected, audio never leaves your device, and is not stored after it is processed.</p> <p>Faceclaw allows users to transcribe audio (for use with the voice assistant, the Transcribe app, typing into Terminal, and other apps). The default setting is that this is done using an on-device model running on your phone. If an on-device model is selected, audio never leaves your device, and is not stored after it is processed.</p>
<p>Users can also provide their own API key for a third-party transcription service such as OpenAI Whisper, ElevenLabs, or Soniox, which may offer better accuracy. Faceclaw never transmits audio to any party other than a user-selected transcription service. If a third-party transcription service is selected, audio will be sent to that third party, is linked to the account with which that API key was created, and is subject to that party's privacy and retention policies:</p> <p>Users can also provide their own API key for a third-party transcription service such as OpenAI Whisper, ElevenLabs, or Soniox, which may offer better accuracy. Faceclaw never transmits audio to any party other than a user-selected transcription service. If a third-party transcription service is selected, audio will be sent to that third party, is linked to the account with which that API key was created, and is subject to that party's privacy and retention policies:</p>