Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0f62573b1c
|
||
|
|
1959e57d02
|
No files matched your search
@@ -1,47 +0,0 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
import android.content.Context
|
||||
import android.security.keystore.KeyGenParameterSpec
|
||||
import android.security.keystore.KeyProperties
|
||||
import android.util.AtomicFile
|
||||
import java.io.File
|
||||
import java.security.KeyStore
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.KeyGenerator
|
||||
import javax.crypto.SecretKey
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
|
||||
/** This credential cannot be restored onto a device lacking its Keystore key. */
|
||||
object FaceclawHealthExportSecret {
|
||||
private const val ALIAS = "faceclaw.health.export"
|
||||
private fun file(context: Context) = AtomicFile(File(context.noBackupFilesDir, "health-export-key"))
|
||||
private fun key(): SecretKey {
|
||||
val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
||||
(store.getKey(ALIAS, null) as? SecretKey)?.let { return it }
|
||||
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply {
|
||||
init(KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
|
||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).build())
|
||||
}.generateKey()
|
||||
}
|
||||
@JvmStatic @Synchronized fun read(context: Context): String {
|
||||
val held = file(context)
|
||||
if (!held.baseFile.exists()) return ""
|
||||
return try {
|
||||
val bytes = held.readFully()
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||
cipher.init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, bytes.copyOfRange(0, 12)))
|
||||
String(cipher.doFinal(bytes.copyOfRange(12, bytes.size)), Charsets.UTF_8)
|
||||
} catch (_: Exception) { "" } // Require re-entry after key loss; never log the credential.
|
||||
}
|
||||
@JvmStatic @Synchronized fun write(context: Context, value: String) {
|
||||
val held = file(context)
|
||||
if (value.isEmpty()) { held.delete(); return }
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||
cipher.init(Cipher.ENCRYPT_MODE, key())
|
||||
val bytes = cipher.iv + cipher.doFinal(value.toByteArray(Charsets.UTF_8))
|
||||
val stream = held.startWrite()
|
||||
try { stream.write(bytes); held.finishWrite(stream) }
|
||||
catch (error: Exception) { held.failWrite(stream); throw error }
|
||||
}
|
||||
}
|
||||
+12
@@ -504,6 +504,18 @@ class FaceclawMediaNotificationListenerService : NotificationListenerService() {
|
||||
}
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun dismissAllNotifications(): Boolean {
|
||||
val service = activeService ?: return false
|
||||
return try {
|
||||
service.cancelAllNotifications()
|
||||
true
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "failed to dismiss all notifications", t)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun emitNotificationPosted(key: String?) {
|
||||
emitNotificationEvent(key) { listener, eventKey -> listener.onNotificationPosted(eventKey) }
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NotificationsListLayer } from "../../ui/notifications";
|
||||
import { NotificationFilterLayer } from "../../ui/notification-filter";
|
||||
import { onAndroidNotificationsChanged } from "../../native/notification-icons";
|
||||
import { ALL_NOTIFICATIONS, dismissAllNotifications, onAndroidNotificationsChanged, readActiveNotifications } from "../../native/notification-icons";
|
||||
import {
|
||||
createInProcessWindow,
|
||||
YieldAtRootLayer,
|
||||
@@ -32,6 +32,15 @@ export function createNotificationsAppWindow(options: InProcessAppOptions): InPr
|
||||
ctx.stack.pop();
|
||||
ctx.stack.push(new NotificationFilterLayer());
|
||||
},
|
||||
}, {
|
||||
label: "Dismiss all notifications",
|
||||
description: "Dismiss notifications on the phone and glasses. System-protected notifications may remain.",
|
||||
disabled: () => readActiveNotifications(ALL_NOTIFICATIONS).length === 0,
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.pop();
|
||||
dismissAllNotifications();
|
||||
created.requestRender();
|
||||
},
|
||||
}],
|
||||
actions: options.actions,
|
||||
baseLayer: new YieldAtRootLayer(new NotificationsListLayer()),
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { startHealthExport } from "./health/health-export"
|
||||
import { Application } from '@nativescript/core'
|
||||
import { registerShareIntentHandler } from './native/share-intents'
|
||||
import { installNativeUserAgent } from './util/http'
|
||||
@@ -19,7 +18,6 @@ Application.on(Application.launchEvent, () => {
|
||||
// they are closed would be lost if the process restarted first, so this keeps
|
||||
// them reaching disk regardless. No-op when there is nothing new.
|
||||
startLiveHealthSync()
|
||||
startHealthExport()
|
||||
|
||||
// Collect from the ring on a wall-clock cadence (:01 and :31). Without this
|
||||
// nothing drives a pull on a timer at all - only onRingReady() on reconnect -
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
import { healthStore } from "./health-store-files";
|
||||
import { isFixtureData } from "./health-seed";
|
||||
import { healthExportEnabledSetting, healthExportUrlSetting, healthExportKeySetting } from "../ui/dashboard-settings";
|
||||
import { getStringSetting, setStringSetting } from "../native/settings-store";
|
||||
import { fetchTextWithUserAgent } from "../util/http";
|
||||
|
||||
let running = false;
|
||||
let started = false;
|
||||
let status = "Not synchronized";
|
||||
export function healthExportStatus(): string { return status; }
|
||||
|
||||
/** One bounded batch, with durable acknowledgement and no overlapping requests. */
|
||||
export async function syncHealthExport(): Promise<void> {
|
||||
if (running) return;
|
||||
running = true;
|
||||
try {
|
||||
if (!healthExportEnabledSetting.get()) { status = "Export disabled"; return; }
|
||||
if (isFixtureData()) { status = "Sample data is never exported"; return; }
|
||||
const url = healthExportUrlSetting.get();
|
||||
const key = healthExportKeySetting.get();
|
||||
if (!url || healthExportUrlSetting.validationError() || !key) {
|
||||
status = "Configure an HTTPS endpoint and API key";
|
||||
return;
|
||||
}
|
||||
const generation = getStringSetting("health.export.generation", "0");
|
||||
let held: { url?: string; generation?: string; offsets?: Record<string, number> } = {};
|
||||
try { held = JSON.parse(getStringSetting("health.export.cursor", "{}")) ?? {}; } catch { /* First sync. */ }
|
||||
const offsets = held.url === url && held.generation === generation ? held.offsets ?? {} : {};
|
||||
let limit = 200;
|
||||
let batch = healthStore().exportBatch(offsets, limit);
|
||||
let body = JSON.stringify({ version: 1, samples: batch.samples, sleep: batch.sleep });
|
||||
// Normalized records contain only ASCII keys, numbers and metric names.
|
||||
// Large sleep histories must fit the server body limit as well as its record limit.
|
||||
while (body.length > 240_000 && limit > 1) {
|
||||
limit = Math.max(1, Math.floor(limit / 2));
|
||||
batch = healthStore().exportBatch(offsets, limit);
|
||||
body = JSON.stringify({ version: 1, samples: batch.samples, sleep: batch.sleep });
|
||||
}
|
||||
if (body.length > 240_000) { status = "A health record exceeds the export size limit"; return; }
|
||||
if (!batch.scanned) { status = "Up to date"; return; }
|
||||
if (batch.samples.length || batch.sleep.length) {
|
||||
status = "Sending health data";
|
||||
const response = await fetchTextWithUserAgent(url, {
|
||||
method: "POST", headers: { "Authorization": `Bearer ${key}`, "Content-Type": "application/json" },
|
||||
body,
|
||||
timeoutMs: 30_000, dontFollowRedirects: true,
|
||||
});
|
||||
if (response.status !== 200) {
|
||||
status = response.status === 401 || response.status === 403
|
||||
? "API key refused; check configuration" : `Server refused batch (HTTP ${response.status}); will retry`;
|
||||
return;
|
||||
}
|
||||
const ack = await response.json<{ accepted?: boolean }>();
|
||||
if (ack.accepted !== true) { status = "Invalid server acknowledgement; will retry"; return; }
|
||||
}
|
||||
// An edit during the request must not acknowledge data on a different destination.
|
||||
if (url !== healthExportUrlSetting.get() || generation !== getStringSetting("health.export.generation", "0")) return;
|
||||
setStringSetting("health.export.cursor", JSON.stringify({ url, generation, offsets: batch.cursor }));
|
||||
status = "Batch synchronized; remaining history follows automatically";
|
||||
} catch {
|
||||
// Errors may include request headers or data: never log or display them.
|
||||
status = "Synchronization failed; will retry automatically";
|
||||
} finally { running = false; }
|
||||
}
|
||||
|
||||
/** Android app process only; no extra BLE pulls, wake locks, or background service. */
|
||||
export function startHealthExport(): void {
|
||||
if (started) return;
|
||||
started = true;
|
||||
setTimeout(() => { void syncHealthExport(); }, 10_000);
|
||||
setInterval(() => { void syncHealthExport(); }, 60_000);
|
||||
}
|
||||
@@ -48,7 +48,6 @@
|
||||
|
||||
import {
|
||||
HOUR_MS,
|
||||
HEART_RATE_MEASUREMENT_SPAN_MS,
|
||||
TEN_MINUTES_MS,
|
||||
type HealthSample,
|
||||
type SleepSession,
|
||||
@@ -66,8 +65,6 @@ export type WireHourlyRecord = {
|
||||
* zero bytes instead.
|
||||
*/
|
||||
anchorMs: number | null;
|
||||
/** Latest reading, only from live pages; raw journal replay does not guess its clock. */
|
||||
latest?: { timestampSeconds: number; value: number; receivedAtMs: number; clockOffsetMs: number };
|
||||
groups: readonly { hourIndex: number; avg: number; max: number; min: number }[];
|
||||
};
|
||||
|
||||
@@ -149,22 +146,6 @@ export function convertRecords(records: readonly WireRecord[]): ConversionResult
|
||||
* guesses. Dropping loses a page; guessing corrupts the history silently.
|
||||
*/
|
||||
function convertHourly(record: WireHourlyRecord, result: ConversionResult): void {
|
||||
if (record.metric === "heartRate" && record.latest) {
|
||||
const { timestampSeconds, value, receivedAtMs, clockOffsetMs } = record.latest;
|
||||
const startMs = timestampSeconds * 1000 - clockOffsetMs;
|
||||
// Invert the existing handshake clock shift, never replace measurement time
|
||||
// with reception time or snap it onto an invented ten-minute bucket.
|
||||
// Older pages can mix clock domains: only accept a recent live reading.
|
||||
if (Number.isSafeInteger(timestampSeconds) && Number.isSafeInteger(receivedAtMs)
|
||||
&& Number.isFinite(clockOffsetMs) && Number.isInteger(value) && value > 0 && value <= 300
|
||||
&& startMs >= 946684800000 && startMs <= receivedAtMs + 120_000
|
||||
&& receivedAtMs - startMs <= 20 * 60_000) {
|
||||
result.samples.push({ metric: "heartRate", startMs, spanMs: HEART_RATE_MEASUREMENT_SPAN_MS,
|
||||
min: value, max: value, avg: value, total: value });
|
||||
} else {
|
||||
result.skipped.push({ what: "latest heart rate", why: "invalid, stale or unresolved measurement timestamp/value" });
|
||||
}
|
||||
}
|
||||
if (record.anchorMs === null) {
|
||||
result.skipped.push({
|
||||
what: `${record.metric} page, ${record.groups.length} groups`,
|
||||
|
||||
+14
-17
@@ -240,7 +240,7 @@ function accumulateStepBuckets(
|
||||
return merged;
|
||||
}
|
||||
|
||||
function toWire(record: any, includeLatest: boolean): WireRecord | null {
|
||||
function toWire(record: any): WireRecord | null {
|
||||
const cmdHi = Number(record.cmdHi);
|
||||
|
||||
const metric = HOURLY_METRIC[cmdHi];
|
||||
@@ -256,12 +256,7 @@ function toWire(record: any, includeLatest: boolean): WireRecord | null {
|
||||
min: Number(group.min),
|
||||
});
|
||||
}
|
||||
const receivedAtMs = Number(record.receivedAtMs);
|
||||
const latest = includeLatest && metric === "heartRate" && Number(record.tagRaw) > 0 ? {
|
||||
timestampSeconds: Number(record.tagRaw), value: Number(record.current), receivedAtMs,
|
||||
clockOffsetMs: ringClockOffsetMs(receivedAtMs),
|
||||
} : undefined;
|
||||
return { kind: "hourly", metric, anchorMs: anchorToMs(Number(record.anchorUnixSeconds), true), groups, latest };
|
||||
return { kind: "hourly", metric, anchorMs: anchorToMs(Number(record.anchorUnixSeconds), true), groups };
|
||||
}
|
||||
|
||||
if (cmdHi === CMD_STEPS) {
|
||||
@@ -396,12 +391,12 @@ type StoreResult = Omit<LiveSyncResult, "seen">;
|
||||
* fails, so the caller keeps whatever it would otherwise mark as consumed.
|
||||
* Shared by the live batch and the journal replay.
|
||||
*/
|
||||
function storeRecords(records: JavaRecordList, includeLatest = true): StoreResult {
|
||||
function storeRecords(records: JavaRecordList): StoreResult {
|
||||
const wire: WireRecord[] = [];
|
||||
const size = records.size();
|
||||
for (let i = 0; i < size; i++) {
|
||||
try {
|
||||
const converted = toWire(records.get(i), includeLatest);
|
||||
const converted = toWire(records.get(i));
|
||||
if (converted) wire.push(converted);
|
||||
} catch (error) {
|
||||
console.warn("health live: skipped an undecodable record", error);
|
||||
@@ -485,7 +480,7 @@ function replayFrameJournalOnce(): void {
|
||||
const records: JavaRecordList = ringProtocol.decodeFrameJournal(File.fromPath(journalPath).readTextSync(), after);
|
||||
const size = records.size();
|
||||
if (size > 0) {
|
||||
const result = storeRecords(records, false);
|
||||
const result = storeRecords(records);
|
||||
let through = after;
|
||||
for (let i = 0; i < size; i++) through = Math.max(through, Number(records.get(i).receivedAtMs));
|
||||
const next: ReplayCursor = { version: JOURNAL_DECODER_VERSION, throughReceivedAtMs: through };
|
||||
@@ -548,7 +543,7 @@ export function syncLiveRecords(): LiveSyncResult {
|
||||
|
||||
/**
|
||||
* Ask the ring for a fresh pull now, rather than waiting out the automatic
|
||||
* ten-minute cycle. Returns immediately; the pull itself takes ~15s on the
|
||||
* 30-minute cycle. Returns immediately; the pull itself takes ~15s on the
|
||||
* communicator's worker thread and lands through the next `syncLiveRecords()`.
|
||||
*
|
||||
* Throttled communicator-side to one a minute — see
|
||||
@@ -589,17 +584,19 @@ export function startLiveHealthSync(): void {
|
||||
}
|
||||
|
||||
/**
|
||||
* Pull the ring every ten minutes, one minute after each bucket boundary.
|
||||
* Pull the ring on a wall-clock-aligned cadence: :01 and :31, every hour.
|
||||
*
|
||||
* This collects the latest heart-rate observation at roughly the cadence
|
||||
* the stock app documents, as well as the existing historical buckets.
|
||||
* It does not force the sensor to take a new measurement.
|
||||
* Chris, 2026-09-12: *"I think we should be polling the ring on the 30 minute
|
||||
* cycle (that was my intent, not a floor honestly)."* The 30-minute value in
|
||||
* `RING_HEALTH_MIN_PULL_INTERVAL_MS` was always meant as a collection rhythm
|
||||
* and got built as a throttle, so a connected, stable ring pulled never —
|
||||
* nothing in the system drives a pull on a timer at all.
|
||||
*
|
||||
* Two reasons this is aligned to the wall clock rather than a plain interval:
|
||||
*
|
||||
* 1. **The ring's own step buckets close on 10-minute boundaries.** Pulling on
|
||||
* the boundary collects a just-closed bucket instead of a half-formed one.
|
||||
* 2. **An elapsed timer drifts.** A pull at :07 sets the next at :17, then :27,
|
||||
* 2. **An elapsed timer drifts.** A pull at :07 sets the next at :37, then :07,
|
||||
* wandering away from the boundary it is supposed to track. Re-arming
|
||||
* against the clock each time cannot drift.
|
||||
*
|
||||
@@ -609,7 +606,7 @@ export function startLiveHealthSync(): void {
|
||||
* This only *requests* a pull. The communicator still applies its own anti-spam
|
||||
* floor, so an extra call here can never hammer the ring.
|
||||
*/
|
||||
const ALIGNED_PULL_MINUTES = [1, 11, 21, 31, 41, 51];
|
||||
const ALIGNED_PULL_MINUTES = [1, 31];
|
||||
let alignedPullTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
function msUntilNextAlignedPull(now: Date): number {
|
||||
|
||||
@@ -59,7 +59,6 @@
|
||||
|
||||
import {
|
||||
type HealthSample,
|
||||
isHeartRateMeasurement,
|
||||
type Rollup,
|
||||
type SampleMetric,
|
||||
type SleepSession,
|
||||
@@ -229,51 +228,12 @@ export class HealthStore {
|
||||
// -------------------------------------------------------------------------
|
||||
// Reading
|
||||
|
||||
/** Append-journal cursor, committed by the exporter only after server acknowledgement.
|
||||
* Revisions appended to an old month are exported too; a time watermark would lose them.
|
||||
*/
|
||||
exportBatch(cursor: Record<string, number>, limit = 200): {
|
||||
cursor: Record<string, number>; samples: HealthSample[]; sleep: SleepSession[]; scanned: number;
|
||||
} {
|
||||
const next = { ...cursor };
|
||||
const samples: HealthSample[] = [];
|
||||
const sleep: SleepSession[] = [];
|
||||
let scanned = 0;
|
||||
for (const name of this.backend.list().filter(candidate => /^samples-\d{4}-\d{2}\.jsonl$/.test(candidate) || candidate === SLEEP_FILE).sort()) {
|
||||
const text = this.backend.read(name);
|
||||
if (text === null) throw new Error("Health export could not read history");
|
||||
let offset = next[name] ?? 0;
|
||||
if (!Number.isSafeInteger(offset) || offset < 0 || offset > text.length) offset = 0;
|
||||
while (scanned < limit) {
|
||||
const end = text.indexOf("\n", offset);
|
||||
if (end < 0) break; // Never consume a partially written final record.
|
||||
const line = text.slice(offset, end);
|
||||
offset = end + 1;
|
||||
scanned++;
|
||||
if (name === SLEEP_FILE) {
|
||||
try {
|
||||
const session = JSON.parse(line) as SleepSession;
|
||||
if (session?.timeResolved === true) sleep.push(session);
|
||||
} catch { /* Ignore incomplete/corrupt journal lines as the local reader does. */ }
|
||||
} else {
|
||||
const sample = fromLine(line);
|
||||
if (sample) samples.push(sample);
|
||||
}
|
||||
}
|
||||
next[name] = offset;
|
||||
if (scanned >= limit) break;
|
||||
}
|
||||
return { cursor: next, samples, sleep, scanned };
|
||||
}
|
||||
|
||||
/** Bucket samples in [startMs, endMs). Point observations are opt-in so
|
||||
* existing charts and daily averages never combine two overlapping series. */
|
||||
samplesInRange(startMs: number, endMs: number, includeMeasurements = false): HealthSample[] {
|
||||
/** Every stored sample overlapping [startMs, endMs). Exact - reads shards. */
|
||||
samplesInRange(startMs: number, endMs: number): HealthSample[] {
|
||||
const out: HealthSample[] = [];
|
||||
for (const name of this.shardNamesInRange(startMs, endMs)) {
|
||||
for (const sample of this.loadShard(name).values()) {
|
||||
if (sample.startMs >= startMs && sample.startMs < endMs
|
||||
&& (includeMeasurements || !isHeartRateMeasurement(sample))) out.push(sample);
|
||||
if (sample.startMs >= startMs && sample.startMs < endMs) out.push(sample);
|
||||
}
|
||||
}
|
||||
out.sort((a, b) => a.startMs - b.startMs);
|
||||
@@ -337,7 +297,6 @@ export class HealthStore {
|
||||
for (const name of this.backend.list()) {
|
||||
if (!name.startsWith(SAMPLE_PREFIX) || !name.endsWith(SAMPLE_SUFFIX)) continue;
|
||||
for (const sample of this.loadShard(name).values()) {
|
||||
if (isHeartRateMeasurement(sample)) continue;
|
||||
const key = dayKey(sample.startMs);
|
||||
let byMetric = perDay.get(key);
|
||||
if (!byMetric) {
|
||||
@@ -364,9 +323,7 @@ export class HealthStore {
|
||||
private updateRollupsFor(samples: readonly HealthSample[]): void {
|
||||
const file = this.loadRollups();
|
||||
const touched = new Set<string>();
|
||||
for (const sample of samples) {
|
||||
if (!isHeartRateMeasurement(sample)) touched.add(dayKey(sample.startMs));
|
||||
}
|
||||
for (const sample of samples) touched.add(dayKey(sample.startMs));
|
||||
for (const key of touched) {
|
||||
const parts = key.split("-").map(Number);
|
||||
const dayStart = new Date(parts[0]!, parts[1]! - 1, parts[2]!).getTime();
|
||||
|
||||
@@ -36,12 +36,6 @@ export function isCumulative(metric: SampleMetric): boolean {
|
||||
|
||||
export const HOUR_MS = 3_600_000;
|
||||
export const TEN_MINUTES_MS = 600_000;
|
||||
/** Point observation, not a ten-minute average. Distinct from hourly buckets. */
|
||||
export const HEART_RATE_MEASUREMENT_SPAN_MS = 1;
|
||||
|
||||
export function isHeartRateMeasurement(sample: HealthSample): boolean {
|
||||
return sample.metric === "heartRate" && sample.spanMs === HEART_RATE_MEASUREMENT_SPAN_MS;
|
||||
}
|
||||
export const DAY_MS = 86_400_000;
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
import { Utils } from "@nativescript/core";
|
||||
declare const com: any;
|
||||
|
||||
/** Android Keystore-backed, excluded from backups. Never falls back to plain settings. */
|
||||
export function readHealthExportSecret(): string {
|
||||
if (!global.isAndroid) return "";
|
||||
return String(com.faceclaw.app.FaceclawHealthExportSecret.read(Utils.android.getApplicationContext()));
|
||||
}
|
||||
|
||||
export function writeHealthExportSecret(value: string): void {
|
||||
if (!global.isAndroid) throw new Error("Health export is available on Android only");
|
||||
com.faceclaw.app.FaceclawHealthExportSecret.write(Utils.android.getApplicationContext(), value);
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import type { GrayImage } from '../graphics/image'
|
||||
import { pebbleIcon } from '../graphics/pebble-icons'
|
||||
import { AncsClient, ANCS_CONNECT_MESSAGE, type AncsState } from '../g2/ancs-client'
|
||||
import { notificationAppIcon, notificationCategoryIcon } from './notification-app-icons'
|
||||
import { rememberNotificationSources } from './notification-sources'
|
||||
import { rememberNotificationSources, shouldShowNotificationOnGlasses } from './notification-sources'
|
||||
import type { AndroidNotification } from './notification-types'
|
||||
export type { AndroidNotification, AndroidNotificationAction } from './notification-types'
|
||||
export type { NotificationIconsResult, NotificationIconResult, NotificationImageResult } from './notification-icons'
|
||||
@@ -24,8 +24,23 @@ export function onIosNotificationPopup(listener: (key: string) => void): () => v
|
||||
export function iosNotificationMessage(): string { return active?.statusMessage ?? ANCS_CONNECT_MESSAGE }
|
||||
export function iosNotificationState(): AncsState { return active?.state ?? 'disconnected' }
|
||||
export function readActiveNotifications(maxNotifications = 50) { return active?.read(maxNotifications) ?? [] }
|
||||
export function readVisibleNotifications(maxNotifications = 50) {
|
||||
return readActiveNotifications(ALL_NOTIFICATIONS)
|
||||
.filter(notification => shouldShowNotificationOnGlasses(notification.packageName))
|
||||
.slice(0, Math.max(0, maxNotifications))
|
||||
}
|
||||
export function invokeNotificationAction(key: string, index: number): boolean { return active?.action(key,index) ?? false }
|
||||
export function dismissNotification(key: string): boolean { return active?.dismiss(key) ?? false }
|
||||
export function dismissAllNotifications(): boolean {
|
||||
const client = active
|
||||
if (!client) return false
|
||||
// Snapshot: removals may arrive while dismissal requests are being sent.
|
||||
let accepted = true
|
||||
for (const notification of [...client.read(ALL_NOTIFICATIONS)]) {
|
||||
if (!client.dismiss(notification.key)) accepted = false
|
||||
}
|
||||
return accepted
|
||||
}
|
||||
export function onAndroidNotificationPosted(listener: (key: string) => void): () => void {
|
||||
listeners.add(listener); return () => { listeners.delete(listener) }
|
||||
}
|
||||
@@ -44,7 +59,7 @@ function notificationIcon(notification: AndroidNotification): GrayImage {
|
||||
export function readActiveNotificationIcons(maxIcons: number, _allowStale: boolean) {
|
||||
// One icon per source, standing for its first notification.
|
||||
const sources = new Map<string, AndroidNotification>()
|
||||
for (const n of readActiveNotifications(ALL_NOTIFICATIONS)) if (!sources.has(n.packageName)) sources.set(n.packageName, n)
|
||||
for (const n of readVisibleNotifications(ALL_NOTIFICATIONS)) if (!sources.has(n.packageName)) sources.set(n.packageName, n)
|
||||
const shown = Array.from(sources.values()).slice(0,Math.max(0,maxIcons))
|
||||
return {icons: shown.map(notificationIcon),keys: shown.map(n => n.key),stale:false}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { GrayImage } from "../graphics/image";
|
||||
import { logCurrent, spanCurrent } from "./frame-timings";
|
||||
import { toUint8Array } from "../util/array-util";
|
||||
import { rememberNotificationSources } from "./notification-sources";
|
||||
import { rememberNotificationSources, shouldShowNotificationOnGlasses } from "./notification-sources";
|
||||
import { PHOTO_TONE, grayImageFromPacket } from "./image-files";
|
||||
import { NOTIFICATION_ICON_SIZE } from "./notification-types";
|
||||
|
||||
@@ -21,6 +21,7 @@ const ICON_CACHE_MS = 60_000;
|
||||
|
||||
let cachedIcons: GrayImage[] = [];
|
||||
let cachedKeys: string[] = [];
|
||||
let cachedPackages = new Map<string, string>();
|
||||
let cachedAtMs = 0;
|
||||
const keyedIconCache = new Map<string, { icon: GrayImage | null; atMs: number }>();
|
||||
const KEYED_ICON_CACHE_MAX = 128;
|
||||
@@ -95,6 +96,7 @@ export function readActiveNotificationIcons(maxIcons: number, allowStale: boolea
|
||||
keys.push(index < keyList.size() ? String(keyList.get(index)) : "");
|
||||
}
|
||||
|
||||
cachedPackages = new Map(readActiveNotifications(ALL_NOTIFICATIONS).map(n => [n.key, n.packageName]));
|
||||
cachedIcons = icons;
|
||||
cachedKeys = keys;
|
||||
cachedAtMs = now;
|
||||
@@ -103,7 +105,12 @@ export function readActiveNotificationIcons(maxIcons: number, allowStale: boolea
|
||||
|
||||
/** Copies of the first maxIcons cached icons, with their keys. */
|
||||
function cachedIconsResult(maxIcons: number, stale: boolean): NotificationIconsResult {
|
||||
return { icons: cachedIcons.slice(0, maxIcons).map(icon => icon.clone()), keys: cachedKeys.slice(0, maxIcons), stale };
|
||||
// Reapply preferences even to a warm/stale cache: toggles take effect immediately.
|
||||
const indices = cachedKeys.map((_, index) => index).filter(index => {
|
||||
const packageName = cachedPackages.get(cachedKeys[index]!);
|
||||
return packageName !== undefined && shouldShowNotificationOnGlasses(packageName);
|
||||
}).slice(0, maxIcons);
|
||||
return { icons: indices.map(index => cachedIcons[index]!.clone()), keys: indices.map(index => cachedKeys[index]!), stale };
|
||||
}
|
||||
|
||||
export type NotificationIconResult = {
|
||||
@@ -318,6 +325,13 @@ export function readActiveNotifications(maxNotifications = 50): AndroidNotificat
|
||||
}
|
||||
}
|
||||
|
||||
/** Glasses display only; discover all sources and filter before the display limit. */
|
||||
export function readVisibleNotifications(maxNotifications = 50): AndroidNotification[] {
|
||||
return readActiveNotifications(ALL_NOTIFICATIONS)
|
||||
.filter(notification => shouldShowNotificationOnGlasses(notification.packageName))
|
||||
.slice(0, Math.max(0, maxNotifications));
|
||||
}
|
||||
|
||||
export function invokeNotificationAction(notificationKey: string, actionIndex: number): boolean {
|
||||
if (!global.isAndroid || !notificationKey) return false;
|
||||
invalidateIconCaches();
|
||||
@@ -337,6 +351,13 @@ export function dismissNotification(notificationKey: string): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
/** Explicit user action: dismiss on the phone as well as on the glasses. */
|
||||
export function dismissAllNotifications(): boolean {
|
||||
if (!global.isAndroid) return false;
|
||||
invalidateIconCaches();
|
||||
return Boolean(com.faceclaw.app.FaceclawMediaNotificationListenerService.dismissAllNotifications());
|
||||
}
|
||||
|
||||
export function onAndroidNotificationPosted(listener: (notificationKey: string) => void): () => void {
|
||||
return addNotificationListener(notificationPostedListeners, listener);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,16 @@
|
||||
import { getStringSetting, setStringSetting } from "./settings-store";
|
||||
|
||||
const SOURCES_KEY = "notifications.sources";
|
||||
const DEFAULT_KEY = "notifications.newAppsEnabledByDefault";
|
||||
|
||||
/** Unset preserves the behavior of existing installations. */
|
||||
export function newNotificationAppsEnabledByDefault(): boolean {
|
||||
return getStringSetting(DEFAULT_KEY, "true") !== "false";
|
||||
}
|
||||
|
||||
export function setNewNotificationAppsEnabledByDefault(enabled: boolean): void {
|
||||
setStringSetting(DEFAULT_KEY, String(enabled));
|
||||
}
|
||||
|
||||
export type NotificationSource = {
|
||||
packageName: string;
|
||||
@@ -8,8 +18,15 @@ export type NotificationSource = {
|
||||
showOnGlasses: boolean;
|
||||
};
|
||||
|
||||
type SavedSource = Omit<NotificationSource, "showOnGlasses"> & { showOnGlasses?: boolean };
|
||||
|
||||
/** Sources outlive their active notifications so a muted app can always be re-enabled. */
|
||||
export function readNotificationSources(): NotificationSource[] {
|
||||
const enabled = newNotificationAppsEnabledByDefault();
|
||||
return readSavedSources().map((source) => ({ ...source, showOnGlasses: source.showOnGlasses ?? enabled }));
|
||||
}
|
||||
|
||||
function readSavedSources(): SavedSource[] {
|
||||
try {
|
||||
const parsed = JSON.parse(getStringSetting(SOURCES_KEY, "[]"));
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
@@ -17,7 +34,7 @@ export function readNotificationSources(): NotificationSource[] {
|
||||
.map((source) => ({
|
||||
packageName: source.packageName,
|
||||
appName: typeof source.appName === "string" && source.appName ? source.appName : source.packageName,
|
||||
showOnGlasses: source.showOnGlasses !== false,
|
||||
showOnGlasses: typeof source.showOnGlasses === "boolean" ? source.showOnGlasses : undefined,
|
||||
}));
|
||||
} catch {
|
||||
return [];
|
||||
@@ -25,7 +42,7 @@ export function readNotificationSources(): NotificationSource[] {
|
||||
}
|
||||
|
||||
export function rememberNotificationSources(notifications: { packageName: string; appName: string }[]): void {
|
||||
const sources = new Map(readNotificationSources().map((source) => [source.packageName, source]));
|
||||
const sources = new Map(readSavedSources().map((source) => [source.packageName, source]));
|
||||
let changed = false;
|
||||
for (const notification of notifications) {
|
||||
if (!notification.packageName) continue;
|
||||
@@ -35,7 +52,7 @@ export function rememberNotificationSources(notifications: { packageName: string
|
||||
sources.set(notification.packageName, {
|
||||
packageName: notification.packageName,
|
||||
appName,
|
||||
showOnGlasses: previous?.showOnGlasses ?? true,
|
||||
showOnGlasses: previous?.showOnGlasses,
|
||||
});
|
||||
changed = true;
|
||||
}
|
||||
@@ -44,12 +61,13 @@ export function rememberNotificationSources(notifications: { packageName: string
|
||||
}
|
||||
|
||||
export function shouldShowNotificationOnGlasses(packageName: string): boolean {
|
||||
return readNotificationSources().find((source) => source.packageName === packageName)?.showOnGlasses ?? true;
|
||||
return readNotificationSources().find((source) => source.packageName === packageName)?.showOnGlasses
|
||||
?? newNotificationAppsEnabledByDefault();
|
||||
}
|
||||
|
||||
export function setNotificationSourceEnabled(source: { packageName: string; appName: string }, enabled: boolean): void {
|
||||
if (!source.packageName) return;
|
||||
const sources = new Map(readNotificationSources().map((item) => [item.packageName, item]));
|
||||
const sources = new Map(readSavedSources().map((item) => [item.packageName, item]));
|
||||
sources.set(source.packageName, {
|
||||
packageName: source.packageName,
|
||||
appName: source.appName || source.packageName,
|
||||
@@ -57,3 +75,10 @@ export function setNotificationSourceEnabled(source: { packageName: string; appN
|
||||
});
|
||||
setStringSetting(SOURCES_KEY, JSON.stringify(Array.from(sources.values())));
|
||||
}
|
||||
|
||||
/** Set explicit choices only for sources already discovered; leave the future default alone. */
|
||||
export function setAllNotificationSourcesEnabled(enabled: boolean): void {
|
||||
setStringSetting(SOURCES_KEY, JSON.stringify(readSavedSources().map((source) => ({
|
||||
...source, showOnGlasses: enabled,
|
||||
}))));
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import { readHealthExportSecret, writeHealthExportSecret } from "../native/health-export-secret";
|
||||
import { normalizeNightscoutThreshold, type NightscoutThresholds } from "../apps/nightscout/nightscout-alerts";
|
||||
import { GESTURE_DOUBLE_CLICK, InputEvent } from "./gestures";
|
||||
import { DEFAULT_BRIGHTNESS_CURVE, normalizeBrightnessCurve, brightnessCurveError } from "../g2/brightness-curve";
|
||||
@@ -261,39 +260,6 @@ export class ConfigSettingString<TId extends string = string> extends ConfigSett
|
||||
}
|
||||
|
||||
|
||||
/** A changed credential starts a new delivery history without retaining the old secret. */
|
||||
class HealthExportKeySetting extends ConfigSettingString {
|
||||
get(): string { return readHealthExportSecret(); }
|
||||
set(value: string): string {
|
||||
const normalized = value.trim();
|
||||
if (normalized !== this.get()) {
|
||||
writeHealthExportSecret(normalized);
|
||||
setStringSetting("health.export.cursor", "");
|
||||
setStringSetting("health.export.generation", String(Number(getStringSetting("health.export.generation", "0")) + 1));
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
getValidValue(): string { return this.get(); }
|
||||
}
|
||||
|
||||
export const healthExportEnabledSetting = new ConfigSettingBoolean({
|
||||
id: "healthExportEnabled", label: "Export health data", storageKey: "health.export.enabled",
|
||||
defaultValue: false, reportInAnalytics: false,
|
||||
description: "Send saved R1 health history to your server over HTTPS. Retries while Faceclaw is running; phone storage is retained.",
|
||||
});
|
||||
export const healthExportUrlSetting = new ConfigSettingString({
|
||||
id: "healthExportUrl", label: "Endpoint URL", storageKey: "health.export.url", defaultValue: "",
|
||||
normalize: value => (value ?? "").trim(),
|
||||
validate: value => !value || /^https:\/\/[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?(?::\d{1,5})?(?:\/[^\s?#]*)?$/i.test(value)
|
||||
? null : "Use an HTTPS URL without credentials, query or fragment",
|
||||
description: "Full ingestion URL, for example https://health.undefined-dev.fr/v1/health",
|
||||
});
|
||||
export const healthExportKeySetting = new HealthExportKeySetting({
|
||||
id: "healthExportKey", label: "API key", storageKey: "health.export.key", defaultValue: "",
|
||||
inputKind: "password", formatValue: value => value ? "Configured" : "(empty)",
|
||||
description: "Device-specific write-only key, stored using Android Keystore.",
|
||||
});
|
||||
|
||||
export const batteryDisplayModeSetting = new ConfigSettingEnum<BatteryDisplayMode>({
|
||||
id: "batteryDisplayMode",
|
||||
label: "Style",
|
||||
@@ -1714,7 +1680,7 @@ export class EditTextSettingLayer implements Layer {
|
||||
for (let index = 0; index < message.length; index++) {
|
||||
image.drawText(font, 22, messageTop + index * step, message[index]!, 200);
|
||||
}
|
||||
image.drawText(font, 22, messageTop + (message.length + 2) * step, truncateSetting(this.setting.inputKind === "password" ? this.setting.displayValue() : this.setting.get(), 52), 220);
|
||||
image.drawText(font, 22, messageTop + (message.length + 2) * step, truncateSetting(this.setting.get(), 52), 220);
|
||||
const error = this.setting.validationError();
|
||||
if (error) wrapText(font, error, width - 48).forEach((line, index) =>
|
||||
image.drawText(font, 22, messageTop + (message.length + 4 + index) * step, line, 180));
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { healthExportStatus, syncHealthExport } from "../../health/health-export";
|
||||
import { remoteInputMenuItem } from "./remote-input-menu";
|
||||
import { knownFolders } from "@nativescript/core";
|
||||
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
|
||||
@@ -29,9 +28,6 @@ import type { LayerContext } from "../layers";
|
||||
import { drawRightValueMenuItem, openModalMenu, submenuItem, type MenuItem } from "../menu";
|
||||
import { shell } from "../shell/shell";
|
||||
import {
|
||||
healthExportEnabledSetting,
|
||||
healthExportUrlSetting,
|
||||
healthExportKeySetting,
|
||||
anthropicApiKeySetting,
|
||||
appSwitcherPositionSetting,
|
||||
statusBarPositionSetting,
|
||||
@@ -191,16 +187,6 @@ function settingsSections(): SettingsSection[] {
|
||||
];
|
||||
},
|
||||
},
|
||||
...(!global.isIOS ? [{
|
||||
label: "Health export",
|
||||
get items() { return [
|
||||
toggleSettingMenuItem(healthExportEnabledSetting),
|
||||
textSettingMenuItem(healthExportUrlSetting),
|
||||
textSettingMenuItem(healthExportKeySetting),
|
||||
{ label: "Sync now", description: healthExportStatus(), onSelect: () => { void syncHealthExport(); } },
|
||||
{ label: healthExportStatus(), disabled: true, onSelect: () => {} },
|
||||
]; },
|
||||
}] : []),
|
||||
{
|
||||
label: "API Keys",
|
||||
items: [
|
||||
|
||||
@@ -2,7 +2,7 @@ import { getDefaultSmallFont } from "../graphics/ui-fonts";
|
||||
import { GrayImage } from "../graphics/image";
|
||||
import { truncateText } from "../graphics/textwrap";
|
||||
import { ALL_NOTIFICATIONS, readActiveNotifications } from "../native/notification-icons";
|
||||
import { readNotificationSources, setNotificationSourceEnabled, shouldShowNotificationOnGlasses } from "../native/notification-sources";
|
||||
import { newNotificationAppsEnabledByDefault, setNewNotificationAppsEnabledByDefault, setAllNotificationSourcesEnabled, readNotificationSources, setNotificationSourceEnabled, shouldShowNotificationOnGlasses } from "../native/notification-sources";
|
||||
import { type InputEvent } from "./gestures";
|
||||
import { type Layer, type LayerContext, type PaintBelow } from "./layers";
|
||||
import { drawToggleMenuItem, MenuLayer, type MenuItem } from "./menu";
|
||||
@@ -11,14 +11,26 @@ import { drawToggleMenuItem, MenuLayer, type MenuItem } from "./menu";
|
||||
export class NotificationFilterLayer implements Layer {
|
||||
private menu: MenuLayer | null = null;
|
||||
private menuWidth = 0;
|
||||
/** The package behind each current row, parallel to the menu's items. */
|
||||
/** Stable row keys, including controls, parallel to the menu's items. */
|
||||
private packages: string[] = [];
|
||||
|
||||
private currentMenu(ctx: LayerContext): MenuLayer {
|
||||
readActiveNotifications(ALL_NOTIFICATIONS);
|
||||
const sources = readNotificationSources().sort((a, b) =>
|
||||
a.appName.localeCompare(b.appName) || a.packageName.localeCompare(b.packageName));
|
||||
const items: MenuItem[] = sources.map((source) => ({
|
||||
const items: MenuItem[] = [{
|
||||
label: "New apps enabled by default",
|
||||
onSelect: () => setNewNotificationAppsEnabledByDefault(!newNotificationAppsEnabledByDefault()),
|
||||
render: ({ image, x, y, width, selected }) => {
|
||||
const font = getDefaultSmallFont();
|
||||
drawToggleMenuItem(image, font, x, y, width,
|
||||
truncateText(font, "New apps enabled by default", width - 48), newNotificationAppsEnabledByDefault(), selected);
|
||||
},
|
||||
}, {
|
||||
label: "Enable all", onSelect: () => setAllNotificationSourcesEnabled(true),
|
||||
}, {
|
||||
label: "Disable all", onSelect: () => setAllNotificationSourcesEnabled(false),
|
||||
}, ...sources.map<MenuItem>((source) => ({
|
||||
label: source.appName,
|
||||
onSelect: () => setNotificationSourceEnabled(source, !shouldShowNotificationOnGlasses(source.packageName)),
|
||||
render: ({ image, x, y, width, selected }) => {
|
||||
@@ -26,11 +38,11 @@ export class NotificationFilterLayer implements Layer {
|
||||
drawToggleMenuItem(image, font, x, y, width, truncateText(font, source.appName, width - 48),
|
||||
shouldShowNotificationOnGlasses(source.packageName), selected);
|
||||
},
|
||||
}));
|
||||
if (!items.length) items.push({ label: "No notification sources discovered yet.", disabled: true, onSelect: () => {} });
|
||||
}))];
|
||||
if (!sources.length) items.push({ label: "No notification sources discovered yet.", disabled: true, onSelect: () => {} });
|
||||
const selectedPackage = this.menu?.selectedIndex != null ? this.packages[this.menu.selectedIndex] : undefined;
|
||||
const index = sources.findIndex((source) => source.packageName === selectedPackage);
|
||||
this.packages = sources.map((source) => source.packageName);
|
||||
this.packages = ["default", "enable-all", "disable-all", ...sources.map((source) => `source:${source.packageName}`)];
|
||||
const index = selectedPackage === undefined ? 0 : this.packages.indexOf(selectedPackage);
|
||||
|
||||
const width = ctx.stack.getBaseSize().width;
|
||||
if (!this.menu || width !== this.menuWidth) {
|
||||
@@ -38,7 +50,7 @@ export class NotificationFilterLayer implements Layer {
|
||||
this.menu = new MenuLayer("Notification filter", items, {
|
||||
x: 8, y: 8, width: width - 16,
|
||||
opaque: true, showBorder: false,
|
||||
footer: "On = show popups on glasses",
|
||||
footer: "On = show notifications on glasses",
|
||||
}).selectItem(Math.max(0, index));
|
||||
} else {
|
||||
this.menu.setItems(items, index >= 0 ? index : undefined);
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
ALL_NOTIFICATIONS,
|
||||
dismissNotification,
|
||||
invokeNotificationAction,
|
||||
readActiveNotifications,
|
||||
readVisibleNotifications,
|
||||
readNotificationCustomView,
|
||||
readNotificationIconByKey,
|
||||
readNotificationLargeIcon,
|
||||
@@ -141,7 +141,7 @@ export class NotificationsListLayer implements Layer {
|
||||
const image = new GrayImage(width, height, 0);
|
||||
const cardWidth = width - 2 * CARD_X;
|
||||
const cardTextWidth = cardWidth - CARD_TEXT_X - 14;
|
||||
const notifications = readActiveNotifications(MAX_NOTIFICATIONS);
|
||||
const notifications = readVisibleNotifications(MAX_NOTIFICATIONS);
|
||||
const selectedIndex = this.resolveSelectedIndex(notifications);
|
||||
const layouts = notifications.map((notification, index) =>
|
||||
buildNotificationCardLayout(font, notification, index === selectedIndex, cardTextWidth),
|
||||
@@ -185,7 +185,7 @@ export class NotificationsListLayer implements Layer {
|
||||
}
|
||||
|
||||
handleInput(event: InputEvent, ctx: LayerContext): void {
|
||||
const notifications = readActiveNotifications(MAX_NOTIFICATIONS);
|
||||
const notifications = readVisibleNotifications(MAX_NOTIFICATIONS);
|
||||
const selectedIndex = this.resolveSelectedIndex(notifications);
|
||||
if (event.type === "double-click") {
|
||||
// At the app's root this is intercepted by the yield wrapper; reached
|
||||
@@ -252,7 +252,7 @@ export class SingleNotificationLayer implements Layer {
|
||||
const font = getDefaultSmallFont();
|
||||
const { width, height } = ctx.stack.getBaseSize();
|
||||
const image = new GrayImage(width, height, 0);
|
||||
const notification = readActiveNotifications(ALL_NOTIFICATIONS).find((item) => item.key === this.notificationKey);
|
||||
const notification = readVisibleNotifications(ALL_NOTIFICATIONS).find((item) => item.key === this.notificationKey);
|
||||
|
||||
if (!notification) {
|
||||
return this.closeUnavailableNotification(ctx, paintBelow);
|
||||
@@ -273,7 +273,7 @@ export class SingleNotificationLayer implements Layer {
|
||||
else await menu.handleInput(event);
|
||||
return;
|
||||
}
|
||||
const notification = readActiveNotifications(ALL_NOTIFICATIONS).find((item) => item.key === this.notificationKey);
|
||||
const notification = readVisibleNotifications(ALL_NOTIFICATIONS).find((item) => item.key === this.notificationKey);
|
||||
if (!notification) {
|
||||
this.closeUnavailableNotification(ctx);
|
||||
return;
|
||||
@@ -297,7 +297,7 @@ export class SingleNotificationLayer implements Layer {
|
||||
this.close(ctx);
|
||||
} else if (item.kind === "action") {
|
||||
invokeNotificationAction(this.notificationKey, item.action.index);
|
||||
if (!readActiveNotifications(ALL_NOTIFICATIONS).some((active) => active.key === this.notificationKey)) {
|
||||
if (!readVisibleNotifications(ALL_NOTIFICATIONS).some((active) => active.key === this.notificationKey)) {
|
||||
this.closeUnavailableNotification(ctx);
|
||||
}
|
||||
} else if (item.kind === "dismiss") {
|
||||
@@ -310,7 +310,7 @@ export class SingleNotificationLayer implements Layer {
|
||||
menu: new Menu<ConfirmationItem>({
|
||||
items: [
|
||||
{ label: "Cancel", run: (runCtx) => this.close(runCtx) },
|
||||
{ label: "Turn off popups", run: (runCtx) => {
|
||||
{ label: "Hide on glasses", run: (runCtx) => {
|
||||
setNotificationSourceEnabled(notification, false);
|
||||
this.close(runCtx);
|
||||
} },
|
||||
@@ -341,7 +341,7 @@ export class SingleNotificationLayer implements Layer {
|
||||
};
|
||||
menu.paint(image, menuBox, ctx.stack.isFocused());
|
||||
const top = menuBox.y + menuBox.height + CONFIRM_PROMPT_GAP;
|
||||
const prompt = `Turn off notification popups from ${source.appName || source.packageName}? You can turn them back on in the Notifications app's Notification filter.`;
|
||||
const prompt = `Hide notifications on glasses from ${source.appName || source.packageName}? You can turn them back on in the Notifications app's Notification filter.`;
|
||||
const lines = wrapText(font, prompt, width - 2 * CONFIRM_X);
|
||||
const maxLines = Math.max(1, Math.floor((height - top - 12) / lineStep(font)));
|
||||
for (let index = 0; index < Math.min(lines.length, maxLines); index++) {
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# Dismiss all notifications
|
||||
|
||||
The Notifications app menu offers Dismiss all notifications, disabled when the
|
||||
list is empty. This explicit action dismisses notifications on the phone too;
|
||||
popup filtering and source/default preferences remain independent.
|
||||
|
||||
Android uses NotificationListenerService.cancelAllNotifications, so dismissal
|
||||
is not limited to the 50 items displayed by the list and Android controls which
|
||||
notifications are removable. The normal removal callbacks update the list and
|
||||
popups. Missing listener access returns false without changing preferences.
|
||||
iOS uses the existing ANCS dismissal operation on a snapshot of all known keys;
|
||||
notifications without a negative action may remain.
|
||||
|
||||
Software tests cover menu action/disabled state, more than 50 notifications,
|
||||
native bridge dispatch, disconnected access and ANCS bulk dismissal.
|
||||
On a device, verify the permission-granted/revoked cases, protected or ongoing
|
||||
notifications, notification groups, and consistency with the phone's tray.
|
||||
Hardware validation remains pending.
|
||||
|
||||
Reference: https://developer.android.com/reference/android/service/notification/NotificationListenerService#cancelAllNotifications()
|
||||
@@ -1,71 +0,0 @@
|
||||
# R1 health export
|
||||
|
||||
Android Settings → Health export uses the existing toggle and text/password
|
||||
editors. Export defaults off; URL and API key default empty. Only the API key
|
||||
uses AES-GCM with Android Keystore and an AtomicFile in noBackupFilesDir. Keys
|
||||
are masked on both glasses and phone. The URL/cursor use shared settings.
|
||||
|
||||
The API/image pipeline lives in the dedicated Infrastructure/FaceclawHealth Git
|
||||
repository. Kubernetes manifests live in the Infrastructure repository under
|
||||
FaceclawHealth, and SQL dashboards in GrafanaDashboards/Health. Protocol v1 sends normalized HealthSample/SleepSession
|
||||
fields with original millisecond timestamps. Batches contain at most 200 records
|
||||
and 240 KB. HTTPS is mandatory, redirects are refused, and only HTTP 200 with
|
||||
accepted:true advances the cursor. No health content or keys are logged.
|
||||
|
||||
The exporter reads existing append journals, including revisions to old months,
|
||||
without extra BLE pulls. Partial trailing lines are retried. Unresolved sleep
|
||||
sessions and sample fixtures are excluded. Replayed data is upserted server-side.
|
||||
A new URL/key resets delivery history safely. One batch runs per minute while
|
||||
the Android process is alive; this adds no background service or wake lock and
|
||||
does not promise synchronization while the app is stopped. Disable preserves
|
||||
local history and existing server data. Watch/iOS export is outside this change.
|
||||
|
||||
Software validation: exporter tests for replay, revisions, failed/malformed
|
||||
acknowledgements, redirects, destination/credential edits, fixtures, partial
|
||||
records and overlapping requests; full JS suite, TypeScript and Android release
|
||||
compilation. API tests additionally cover PostgreSQL rollback and deduplication.
|
||||
|
||||
Hardware/end-to-end validation remains pending: enable ring health sync, configure
|
||||
the deployed URL/key, then compare measured timestamps/values and sleep durations
|
||||
with Grafana. Test offline/reconnect, app restart, disable/re-enable and rotated
|
||||
keys. Check key masking, log redaction and preservation of other preferences.
|
||||
No firmware modification is needed.
|
||||
|
||||
## Latest heart-rate observations
|
||||
|
||||
Live HR pages also carry a last-measured timestamp and value. These are now
|
||||
stored as `heartRate` with `spanMs: 1`, at the exact measurement timestamp:
|
||||
this denotes a point observation, **not** a ten-minute average. Existing hourly
|
||||
records retain `spanMs: 3600000`. The existing local and PostgreSQL keys include
|
||||
span, so readings and summaries coexist without collisions. Equal BPM at a new
|
||||
timestamp is a new measurement; repeated timestamps are deduplicated across
|
||||
restarts and corrected values update the same observation. Local bucket charts
|
||||
and daily rollups exclude points, including when the cache is rebuilt.
|
||||
|
||||
The existing aligned ring pull changes from :01/:31 to :01/:11/:21/:31/:41/:51.
|
||||
This is a collection cadence, not a sensor setting or a guarantee of six readings
|
||||
per hour. It uses the same ring worker, connection windows and anti-spam guards;
|
||||
it makes more collection attempts than before. Offline gaps remain gaps and
|
||||
there is no new background service. The exporter still sends at most one batch
|
||||
per minute while the Android process runs.
|
||||
|
||||
Timestamp handling deliberately retains the current handshake's legacy clock
|
||||
convention, inverting its existing phone-timezone offset once. Only a live point
|
||||
within 20 minutes of page reception and no more than two minutes in the future
|
||||
is accepted; invalid/missing timestamps and BPM outside 1–300 are skipped.
|
||||
Reception time is never substituted for measurement time. Old frame-journal
|
||||
replay continues restoring hourly history but does not reconstruct point readings:
|
||||
old pages may mix clock domains. No firmware/time-sync migration is attempted.
|
||||
A timezone change around measurement or an older value can therefore leave a gap;
|
||||
correct placement across such transitions still requires hardware validation.
|
||||
|
||||
The deployed v1 API already accepts span 1 and upserts on device/metric/time/span.
|
||||
No API image, schema migration, Infrastructure change or key rotation is needed.
|
||||
The Grafana overview shows separate hourly-average and latest-reading series,
|
||||
with point markers for readings, not interpolated ten-minute averages.
|
||||
|
||||
Software checks cover latest-page conversion, invalid/stale/future readings,
|
||||
timezone offsets, restart/deduplication, unchanged hourly rollups, export and
|
||||
all six scheduling slots. Hardware checks remain pending: record raw/current
|
||||
measurement times across several pulls, compare BPM/time with the stock app,
|
||||
and check reconnect, timezone/DST transitions and collection battery impact.
|
||||
@@ -0,0 +1,35 @@
|
||||
# Notification filter validation
|
||||
|
||||
Software: `npm test` and `bash lint.sh app/native/notification-sources.ts app/ui/notification-filter.ts`.
|
||||
The notification suite covers legacy preferences, reloads of the settings store,
|
||||
discovery, default changes without overwriting exceptions, both bulk actions,
|
||||
empty lists, stable menu selection and popup suppression before wake.
|
||||
|
||||
Hardware validation (pending; no glasses tested):
|
||||
|
||||
1. On an existing installation, check that enabled and muted applications retain
|
||||
their behavior before touching the new default.
|
||||
2. Turn “New apps enabled by default” off; restart the app. Send a notification
|
||||
from a previously unknown package: it must appear in the filter and on the
|
||||
phone, without waking the glasses or showing a glasses popup.
|
||||
3. Enable that package individually; send another notification and check its popup.
|
||||
4. Change the default in both directions; verify individual exceptions survive.
|
||||
5. Use “Disable all”, then discover another package: it follows the default.
|
||||
Repeat with “Enable all” while the default is off.
|
||||
6. Restart and repeat notifications from enabled and disabled sources. Check that
|
||||
bulk actions and filtering never dismiss notifications on the phone.
|
||||
|
||||
The same source preferences now filter glasses popups, the Notifications list,
|
||||
and the notification tray/status icons. Filtering happens before display limits;
|
||||
source discovery and the phone notification lifecycle remain unfiltered.
|
||||
Cached tray icons reapply the current preferences on each read, including stale
|
||||
reads, so a changed toggle cannot leave a muted icon visible.
|
||||
|
||||
Additional software coverage: Android list limits and warm/stale icon caches,
|
||||
Disable all / re-enable without a new post, and iOS list/tray filtering.
|
||||
|
||||
Additional hardware validation (pending): with mixed enabled/disabled sources,
|
||||
check the list and status bar together. Toggle a source while its notification
|
||||
is already active, then Disable all and Enable all. Verify immediate removal /
|
||||
restoration without a new notification, including after restart, and verify
|
||||
notifications remain available in the phone notification shade.
|
||||
@@ -40,7 +40,6 @@ function settingsEnv(initialUrl = '', initialModel = 'openai-compatible') {
|
||||
},
|
||||
});
|
||||
const load = loader({ global: { isIOS: false, isAndroid: true } }, {
|
||||
'../../health/health-export': { healthExportStatus: () => 'Export disabled', syncHealthExport() {} },
|
||||
'./remote-input-menu': { remoteInputMenuItem: () => ({ label: 'Remote input' }) },
|
||||
'@nativescript/core': { knownFolders: {} },
|
||||
'../../graphics/ui-fonts': { getDefaultSmallFont: () => ({}) },
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { loader } = require('./helpers/load-typescript.cjs');
|
||||
|
||||
test('Notifications menu dismisses all, including beyond the visible list, and leaves filters untouched', () => {
|
||||
let options, active = Array.from({ length: 80 }, (_, i) => ({ key: String(i) }));
|
||||
let dismissals = 0, renders = 0, pops = 0;
|
||||
const load = loader({}, {
|
||||
'../../ui/notifications': { NotificationsListLayer: class {} },
|
||||
'../../ui/notification-filter': { NotificationFilterLayer: class {} },
|
||||
'../../native/notification-icons': {
|
||||
ALL_NOTIFICATIONS: 0x7fffffff,
|
||||
readActiveNotifications(max) { assert.equal(max, 0x7fffffff); return active; },
|
||||
dismissAllNotifications() { dismissals++; active = []; return true; },
|
||||
onAndroidNotificationsChanged: () => () => {},
|
||||
},
|
||||
'../../ui/shell/in-process-window': {
|
||||
YieldAtRootLayer: class {},
|
||||
createInProcessWindow(value) { options = value; return { requestRender() { renders++; } }; },
|
||||
},
|
||||
});
|
||||
load('app/apps/notifications/notifications-app.ts').createNotificationsAppWindow({});
|
||||
const items = options.menuItems();
|
||||
assert.equal(items[0].label, 'Notification filter');
|
||||
const action = items.find(x => x.label === 'Dismiss all notifications');
|
||||
assert.equal(action.disabled(), false);
|
||||
assert.equal(dismissals, 0);
|
||||
action.onSelect({ stack: { pop() { pops++; } } });
|
||||
assert.equal(dismissals, 1);
|
||||
assert.equal(pops, 1);
|
||||
assert.equal(renders, 1);
|
||||
assert.equal(action.disabled(), true);
|
||||
});
|
||||
|
||||
test('Android bulk action uses the native listener and propagates unavailable access', () => {
|
||||
let calls = 0, allowed = false;
|
||||
const load = loader({ global: { isAndroid: true }, com: { faceclaw: { app: {
|
||||
FaceclawMediaNotificationListenerService: { dismissAllNotifications() { calls++; return allowed; } },
|
||||
} } } }, {
|
||||
'../graphics/image': {}, './frame-timings': {}, '../util/array-util': {},
|
||||
'./notification-sources': {}, './image-files': { PHOTO_TONE: { gamma: 1 } }, './notification-types': { NOTIFICATION_ICON_SIZE: 24 },
|
||||
});
|
||||
const api = load('app/native/notification-icons.ts');
|
||||
assert.equal(api.dismissAllNotifications(), false);
|
||||
allowed = true;
|
||||
assert.equal(api.dismissAllNotifications(), true);
|
||||
assert.equal(calls, 2);
|
||||
});
|
||||
|
||||
test('iOS snapshots all ANCS keys and continues when a notification cannot be dismissed', () => {
|
||||
const load = loader({}, {
|
||||
'../graphics/pebble-icons': {}, '../g2/ancs-client': {}, './notification-app-icons': {}, './notification-sources': {},
|
||||
});
|
||||
const api = load('app/native/notification-icons.ios.ts');
|
||||
assert.equal(api.dismissAllNotifications(), false);
|
||||
const active = Array.from({ length: 80 }, (_, i) => ({ key: String(i) })), attempted = [];
|
||||
api.bindIosNotifications({
|
||||
read(max) { assert.equal(max, api.ALL_NOTIFICATIONS); return active; },
|
||||
dismiss(key) {
|
||||
attempted.push(key);
|
||||
if (key === '1') return false;
|
||||
active.splice(active.findIndex(x => x.key === key), 1);
|
||||
return true;
|
||||
},
|
||||
});
|
||||
assert.equal(api.dismissAllNotifications(), false);
|
||||
assert.equal(attempted.length, 80);
|
||||
assert.deepEqual(active, [{ key: '1' }]);
|
||||
});
|
||||
@@ -1,122 +0,0 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { loader } = require('./helpers/load-typescript.cjs');
|
||||
|
||||
function setup() {
|
||||
const files = new Map();
|
||||
const backend = { list: () => [...files.keys()], read: name => files.get(name) ?? null,
|
||||
exists: name => files.has(name), append: (name, text) => files.set(name, (files.get(name) ?? '') + text),
|
||||
write: (name, text) => files.set(name, text) };
|
||||
const { HealthStore } = loader()('app/health/health-store.ts');
|
||||
const store = new HealthStore(backend);
|
||||
const settings = new Map();
|
||||
let url = 'https://health.example/v1/health', key = 'private-test-key', enabled = true, fixture = false;
|
||||
let response = { status: 200, json: async () => ({ accepted: true }) };
|
||||
const requests = [];
|
||||
const exporter = loader({ setTimeout, setInterval }, {
|
||||
'./health-store-files': { healthStore: () => store },
|
||||
'./health-seed': { isFixtureData: () => fixture },
|
||||
'../ui/dashboard-settings': {
|
||||
healthExportEnabledSetting: { get: () => enabled },
|
||||
healthExportUrlSetting: { get: () => url, validationError: () => url.startsWith('https://') ? null : 'HTTPS required' },
|
||||
healthExportKeySetting: { get: () => key },
|
||||
},
|
||||
'../native/settings-store': { getStringSetting: (k, d) => settings.get(k) ?? d, setStringSetting: (k, v) => settings.set(k, v) },
|
||||
'../util/http': { fetchTextWithUserAgent: async (url, options) => { requests.push({ url, options }); return typeof response === 'function' ? response() : response; } },
|
||||
})('app/health/health-export.ts');
|
||||
return { store, files, settings, exporter, requests,
|
||||
configure: options => { if ('url' in options) url=options.url; if ('enabled' in options) enabled=options.enabled; if ('fixture' in options) fixture=options.fixture; if ('response' in options) response=options.response; } };
|
||||
}
|
||||
const sample = { metric:'heartRate',startMs:1700000000000,spanMs:3600000,min:60,max:90,avg:75,total:0 };
|
||||
|
||||
test('exports original measurements, acknowledges durably and catches revisions to old buckets', async () => {
|
||||
const h=setup();h.store.ingestSamples([sample]);
|
||||
await h.exporter.syncHealthExport();
|
||||
assert.equal(h.requests.length,1);
|
||||
assert.deepEqual(JSON.parse(h.requests[0].options.body),{version:1,samples:[sample],sleep:[]});
|
||||
assert.equal(h.requests[0].options.dontFollowRedirects,true);
|
||||
assert.ok(!h.settings.get('health.export.cursor').includes('private-test-key'));
|
||||
await h.exporter.syncHealthExport();assert.equal(h.requests.length,1);
|
||||
h.store.ingestSamples([{...sample,avg:80}]);await h.exporter.syncHealthExport();
|
||||
assert.equal(JSON.parse(h.requests[1].options.body).samples[0].avg,80);
|
||||
h.configure({url:'https://another.example/v1/health'});await h.exporter.syncHealthExport();
|
||||
assert.equal(h.requests.length,3);
|
||||
});
|
||||
|
||||
test('failed or malformed acknowledgements retain cursor for replay; no secret in status', async () => {
|
||||
for (const response of [{status:401},{status:503},{status:302},{status:200,json:async()=>({})},()=>Promise.reject(new Error('private-test-key'))]) {
|
||||
const h=setup();h.store.ingestSamples([sample]);h.configure({response});await h.exporter.syncHealthExport();
|
||||
assert.equal(h.settings.has('health.export.cursor'),false);
|
||||
assert.ok(!h.exporter.healthExportStatus().includes('private-test-key'));
|
||||
h.configure({response:{status:200,json:async()=>({accepted:true})}});
|
||||
await h.exporter.syncHealthExport();assert.equal(h.requests.length,2);
|
||||
}
|
||||
});
|
||||
|
||||
test('disabled export, fixtures, missing key configuration and HTTP never upload', async () => {
|
||||
for (const config of [{enabled:false},{fixture:true},{url:'http://health.example/v1/health'},{url:''}]) {
|
||||
const h=setup();h.store.ingestSamples([sample]);h.configure(config);
|
||||
await h.exporter.syncHealthExport();assert.equal(h.requests.length,0);
|
||||
}
|
||||
});
|
||||
|
||||
test('bounded batches preserve partial lines, unresolved sleep and late appends', () => {
|
||||
const h=setup();h.store.ingestSamples([sample]);
|
||||
const name=[...h.files.keys()].find(n=>n.startsWith('samples-'));
|
||||
const first=h.store.exportBatch({},1);assert.equal(first.scanned,1);
|
||||
const second=h.store.exportBatch(first.cursor,200);assert.equal(second.samples.length,1);
|
||||
h.files.set(name,h.files.get(name)+'{"m":');
|
||||
const partial=h.store.exportBatch(second.cursor);assert.equal(partial.scanned,0);
|
||||
h.files.set(name,h.files.get(name)+'"hrv","t":1700000000000,"s":3600000,"n":1,"x":3,"a":2,"u":0}\n');
|
||||
assert.equal(h.store.exportBatch(partial.cursor).samples[0].metric,'hrv');
|
||||
h.files.set('sleep.jsonl',JSON.stringify({timeResolved:false,startMs:12})+'\n');
|
||||
assert.equal(h.store.exportBatch({}).sleep.length,0);
|
||||
});
|
||||
|
||||
test('concurrent ticks and changed credentials cannot incorrectly acknowledge a batch', async () => {
|
||||
const h=setup();h.store.ingestSamples([sample]);let release;
|
||||
h.configure({response:()=>new Promise(resolve=>{release=resolve;})});
|
||||
const first=h.exporter.syncHealthExport();await h.exporter.syncHealthExport();
|
||||
assert.equal(h.requests.length,1);
|
||||
h.settings.set('health.export.generation','1');release({status:200,json:async()=>({accepted:true})});
|
||||
await first;assert.equal(h.settings.has('health.export.cursor'),false);
|
||||
});
|
||||
|
||||
test('large sleep histories split into bounded bodies without losing sessions', async () => {
|
||||
const h=setup();
|
||||
const sessions=Array.from({length:6},(_,i)=>({timeResolved:true,startMs:1700000000000+i*86400000,
|
||||
endMs:1700028800000+i*86400000,dayStartMs:1699920000000+i*86400000,
|
||||
totalSec:28000,wakeSec:800,remSec:4000,lightSec:18000,deepSec:6000,
|
||||
segments:Array.from({length:2000},()=>({stageId:2,halfMinutes:1}))}));
|
||||
h.files.set('sleep.jsonl',sessions.map(s=>JSON.stringify(s)+'\n').join(''));
|
||||
for(let i=0;i<10;i++) await h.exporter.syncHealthExport();
|
||||
assert.ok(h.requests.length>1);
|
||||
assert.ok(h.requests.every(r=>r.options.body.length<=240000));
|
||||
assert.equal(h.requests.reduce((n,r)=>n+JSON.parse(r.options.body).sleep.length,0),sessions.length);
|
||||
});
|
||||
|
||||
test('point heart rates and hourly summaries export separately with original timestamps', async () => {
|
||||
const h = setup();
|
||||
const point = { ...sample, spanMs: 1, startMs: sample.startMs + 123456, min: 72, max: 72, avg: 72, total: 72 };
|
||||
h.store.ingestSamples([sample, point]);
|
||||
await h.exporter.syncHealthExport();
|
||||
const body = JSON.parse(h.requests[0].options.body);
|
||||
assert.deepEqual(body.samples, [sample, point]);
|
||||
h.store.resetCache();
|
||||
assert.equal(h.store.ingestSamples([point]), 0);
|
||||
await h.exporter.syncHealthExport();
|
||||
assert.equal(h.requests.length, 1);
|
||||
});
|
||||
|
||||
test('a corrected point replaces its old value without changing hourly summaries', async () => {
|
||||
const h = setup();
|
||||
const point = { ...sample, spanMs: 1, min: 72, max: 72, avg: 72, total: 72 };
|
||||
h.store.ingestSamples([sample, point]);
|
||||
await h.exporter.syncHealthExport();
|
||||
const correction = { ...point, min: 74, max: 74, avg: 74, total: 74 };
|
||||
h.store.ingestSamples([correction]);
|
||||
await h.exporter.syncHealthExport();
|
||||
assert.deepEqual(JSON.parse(h.requests[1].options.body).samples, [correction]);
|
||||
assert.equal(h.store.samplesInRange(sample.startMs, sample.startMs + 1, true).length, 2);
|
||||
assert.equal(h.store.samplesInRange(sample.startMs, sample.startMs + 1)[0].avg, sample.avg);
|
||||
});
|
||||
@@ -1,48 +0,0 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { loader } = require('./helpers/load-typescript.cjs');
|
||||
const { convertRecords } = loader()('app/health/health-ingest.ts');
|
||||
const receivedAtMs = Date.UTC(2026, 10, 8, 12);
|
||||
const page = {
|
||||
kind: 'hourly', metric: 'heartRate', anchorMs: receivedAtMs,
|
||||
groups: [{ hourIndex: 0, min: 50, max: 90, avg: 65 }],
|
||||
latest: { timestampSeconds: (receivedAtMs - 60000) / 1000, value: 72, receivedAtMs, clockOffsetMs: 0 },
|
||||
};
|
||||
|
||||
test('latest observation remains a point, independent of hourly averages and page anchor', () => {
|
||||
const result = convertRecords([{ ...page, anchorMs: null }]);
|
||||
assert.equal(result.samples.length, 1);
|
||||
assert.equal(result.samples[0].spanMs, 1);
|
||||
assert.equal(result.samples[0].startMs, receivedAtMs - 60000);
|
||||
assert.equal(result.samples[0].min, 72);
|
||||
assert.equal(result.samples[0].max, 72);
|
||||
assert.equal(result.samples[0].avg, 72);
|
||||
});
|
||||
|
||||
test('legacy handshake timezone offset is inverted once, preserving exact timestamps', () => {
|
||||
for (const clockOffsetMs of [-3600000, -7200000, 7 * 3600000, 0, -19800000]) {
|
||||
const latest = { ...page.latest, clockOffsetMs,
|
||||
timestampSeconds: (receivedAtMs - 60000 + clockOffsetMs) / 1000 };
|
||||
const samples = convertRecords([{ ...page, latest }]).samples;
|
||||
assert.equal(samples[0].startMs, receivedAtMs - 60000);
|
||||
assert.equal(samples[1].spanMs, 3600000);
|
||||
}
|
||||
});
|
||||
|
||||
test('invalid, stale and future latest values never corrupt hourly history', () => {
|
||||
for (const patch of [
|
||||
{ value: 0 }, { value: -1 }, { value: 301 }, { value: NaN }, { value: 72.5 },
|
||||
{ timestampSeconds: -1 }, { timestampSeconds: 0 }, { timestampSeconds: NaN },
|
||||
{ timestampSeconds: receivedAtMs / 1000 + 121 },
|
||||
{ timestampSeconds: receivedAtMs / 1000 - 1201 },
|
||||
{ receivedAtMs: NaN }, { clockOffsetMs: NaN },
|
||||
]) {
|
||||
const result = convertRecords([{ ...page, latest: { ...page.latest, ...patch } }]);
|
||||
assert.equal(result.samples.length, 1, JSON.stringify(patch));
|
||||
assert.equal(result.samples[0].spanMs, 3600000);
|
||||
assert.equal(result.skipped.length, 1);
|
||||
}
|
||||
for (const metric of ['spo2', 'hrv']) {
|
||||
assert.equal(convertRecords([{ ...page, metric }]).samples.length, 1);
|
||||
}
|
||||
});
|
||||
@@ -210,56 +210,3 @@ test("a failed journal replay is retried on the next sync and never blocks the l
|
||||
live.syncLiveRecords();
|
||||
assert.equal(failures, -1, "replay was not retried");
|
||||
});
|
||||
|
||||
test("live latest heart rate retains measurement time and survives restart without duplicates", () => {
|
||||
const measuredAt = Math.floor(Date.now() / 1000) * 1000 - 60_000;
|
||||
function sync(previous, time) {
|
||||
const env = liveEnvironment();
|
||||
if (previous) for (const [name, text] of previous.files) env.files.set(name, text);
|
||||
Object.assign(env.record, {
|
||||
receivedAtMs: time + 60_000,
|
||||
tagRaw: (time + new Date(time + 60_000).getTimezoneOffset() * 60_000) / 1000,
|
||||
current: 72,
|
||||
});
|
||||
env.load("health-live").syncLiveRecords();
|
||||
return env;
|
||||
}
|
||||
const first = sync(null, measuredAt);
|
||||
const repeated = sync(first, measuredAt);
|
||||
const next = sync(repeated, measuredAt + 600_000);
|
||||
const store = next.load("health-store-files").healthStore();
|
||||
const batch = store.exportBatch({});
|
||||
const points = Array.from(batch.samples).filter(s => s.spanMs === 1);
|
||||
assert.deepEqual(points.map(s => [s.startMs, s.avg]), [[measuredAt, 72], [measuredAt + 600_000, 72]]);
|
||||
assert.equal(batch.samples.filter(s => s.spanMs === 3600000).length, 1);
|
||||
assert.equal(store.samplesInRange(measuredAt - 86400000, measuredAt + 86400000).length, 1,
|
||||
"existing health charts only see bucket samples");
|
||||
const counts = () => Array.from(store.dailyRollups('heartRate', measuredAt - 86400000, measuredAt + 86400000).values()).reduce((n, r) => n + r.count, 0);
|
||||
assert.equal(counts(), 1);
|
||||
store.rebuildRollups();
|
||||
assert.equal(counts(), 1, "rebuilding must not mix point readings with hourly aggregates");
|
||||
});
|
||||
|
||||
test("aligned health collection requests all six ten-minute slots without timer drift", () => {
|
||||
const { msUntilNextAlignedPull, ALIGNED_PULL_MINUTES } = liveEnvironment().load('health-live').__alignedPullInternals;
|
||||
assert.deepEqual(Array.from(ALIGNED_PULL_MINUTES), [1, 11, 21, 31, 41, 51]);
|
||||
for (const minute of ALIGNED_PULL_MINUTES) {
|
||||
assert.equal(msUntilNextAlignedPull(new Date(2026, 10, 8, 12, minute, 0)), 600000);
|
||||
assert.equal(msUntilNextAlignedPull(new Date(2026, 10, 8, 12, minute - 1, 30)), 30000);
|
||||
}
|
||||
assert.equal(msUntilNextAlignedPull(new Date(2026, 10, 8, 12, 59, 0)), 120000);
|
||||
});
|
||||
|
||||
test("journal replay restores hourly history without assigning a clock to old point readings", () => {
|
||||
const receivedAtMs = Math.floor(Date.now() / 1000) * 1000;
|
||||
let replay;
|
||||
const ringProtocol = { decodeFrameJournal: () => ({ size: () => 1, get: () => replay }) };
|
||||
const env = liveEnvironment({ ringProtocol });
|
||||
replay = { ...env.record, current: 80, receivedAtMs,
|
||||
tagRaw: (receivedAtMs + new Date(receivedAtMs).getTimezoneOffset() * 60000) / 1000 };
|
||||
env.files.set('/health/ring-frames.jsonl', 'synthetic journal');
|
||||
env.load('health-live').syncLiveRecords();
|
||||
const samples = env.load('health-store-files').healthStore().exportBatch({}).samples;
|
||||
assert.equal(samples.length, 1);
|
||||
assert.equal(samples[0].spanMs, 3600000);
|
||||
});
|
||||
@@ -9,7 +9,7 @@ const generator = require('../scripts/generate-pebble-icons.cjs');
|
||||
function setup(notifications) {
|
||||
const load = loader({}, {
|
||||
'../g2/ancs-client': { AncsClient: class {}, ANCS_CONNECT_MESSAGE: '' },
|
||||
'./notification-sources': { rememberNotificationSources() {} },
|
||||
'./notification-sources': { rememberNotificationSources() {}, shouldShowNotificationOnGlasses: packageName => packageName !== "muted" },
|
||||
});
|
||||
const icons = load('app/native/notification-icons.ios.ts');
|
||||
icons.bindIosNotifications({ read: () => notifications });
|
||||
@@ -106,3 +106,11 @@ test('the icon generator inverts Pebble art: black ink lights up, white fills hi
|
||||
const decoded = loader({}, { './pebble-icons-data': loader({}, {})(dataFile) })('app/graphics/pebble-icons.ts').pebbleIcon('probe');
|
||||
assert.deepEqual([...decoded.pixels], [...pixels]);
|
||||
});
|
||||
|
||||
test('muted sources are hidden before list and icon limits without removing phone notifications', () => {
|
||||
const notifications = [notification('hidden', 'muted', '0'), notification('shown', 'allowed', '0')];
|
||||
const { icons } = setup(notifications);
|
||||
assert.deepEqual([...icons.readVisibleNotifications(1)].map(n => n.key), ['shown']);
|
||||
assert.deepEqual([...icons.readActiveNotificationIcons(1, false).keys], ['shown']);
|
||||
assert.equal(icons.readActiveNotifications(10).length, 2);
|
||||
});
|
||||
@@ -70,6 +70,7 @@ function ui(fontSize = 12) {
|
||||
const native = {
|
||||
ALL_NOTIFICATIONS: 0x7fffffff,
|
||||
readActiveNotifications: () => { prefs.rememberNotificationSources(active); return active; },
|
||||
readVisibleNotifications: () => { prefs.rememberNotificationSources(active); return active.filter(n => prefs.shouldShowNotificationOnGlasses(n.packageName)); },
|
||||
dismissNotification: () => { dismissals++; active = []; return true; },
|
||||
readNotificationIconByKey: () => ({ icon: null, stale: false }),
|
||||
};
|
||||
@@ -165,6 +166,7 @@ test('cancel and back dismiss the popup without changing source preferences', as
|
||||
test('filter toggles persist after notifications disappear and discovers new sources while open', async () => {
|
||||
const app = ui();
|
||||
app.paint(app.filter);
|
||||
for (let i = 0; i < 3; i++) await app.input(app.filter, 'scroll-down');
|
||||
await app.input(app.filter, 'click');
|
||||
assert.equal(app.prefs.shouldShowNotificationOnGlasses(mail.packageName), false);
|
||||
app.active([{ packageName: 'com.alpha', appName: 'Alpha' }]);
|
||||
@@ -177,6 +179,68 @@ test('filter toggles persist after notifications disappear and discovers new sou
|
||||
assert.equal(app.prefs.shouldShowNotificationOnGlasses('com.alpha'), true);
|
||||
});
|
||||
|
||||
test('default persists without overwriting explicit choices, including legacy saved sources', () => {
|
||||
const settings = new Map([['notifications.sources', JSON.stringify([
|
||||
{ ...mail, showOnGlasses: true },
|
||||
{ packageName: 'muted', appName: 'Muted', showOnGlasses: false },
|
||||
])]]);
|
||||
let prefs = store(settings);
|
||||
prefs.rememberNotificationSources([{ packageName: 'discovered', appName: 'Discovered' }]);
|
||||
prefs.setNewNotificationAppsEnabledByDefault(false);
|
||||
prefs = store(settings);
|
||||
assert.equal(prefs.newNotificationAppsEnabledByDefault(), false);
|
||||
assert.equal(prefs.shouldShowNotificationOnGlasses(mail.packageName), true);
|
||||
assert.equal(prefs.shouldShowNotificationOnGlasses('muted'), false);
|
||||
assert.equal(prefs.shouldShowNotificationOnGlasses('discovered'), false);
|
||||
assert.equal(prefs.shouldShowNotificationOnGlasses('future'), false);
|
||||
prefs.rememberNotificationSources([{ packageName: 'future', appName: 'Future' }]);
|
||||
prefs.setNotificationSourceEnabled({ packageName: 'future', appName: 'Future' }, true);
|
||||
prefs.setNewNotificationAppsEnabledByDefault(true);
|
||||
prefs.setNewNotificationAppsEnabledByDefault(false);
|
||||
assert.equal(store(settings).shouldShowNotificationOnGlasses('future'), true);
|
||||
});
|
||||
|
||||
test('bulk choices persist for known sources without changing the default for future sources', () => {
|
||||
const settings = new Map();
|
||||
let prefs = store(settings);
|
||||
prefs.rememberNotificationSources([mail]);
|
||||
prefs.setAllNotificationSourcesEnabled(false);
|
||||
prefs = store(settings);
|
||||
assert.equal(prefs.shouldShowNotificationOnGlasses(mail.packageName), false);
|
||||
assert.equal(prefs.shouldShowNotificationOnGlasses('future'), true);
|
||||
prefs.setNewNotificationAppsEnabledByDefault(false);
|
||||
prefs.setAllNotificationSourcesEnabled(true);
|
||||
prefs = store(settings);
|
||||
assert.equal(prefs.shouldShowNotificationOnGlasses(mail.packageName), true);
|
||||
assert.equal(prefs.shouldShowNotificationOnGlasses('future'), false);
|
||||
prefs.rememberNotificationSources([{ packageName: 'future', appName: 'Future' }]);
|
||||
assert.equal(prefs.shouldShowNotificationOnGlasses('future'), false);
|
||||
prefs.setAllNotificationSourcesEnabled(false);
|
||||
assert.ok(prefs.readNotificationSources().every(source => !source.showOnGlasses));
|
||||
});
|
||||
|
||||
test('filter controls work with an empty list and keep selection as sources arrive', async () => {
|
||||
const app = ui();
|
||||
app.active([]);
|
||||
const labels = app.paint(app.filter).texts.map(({ text }) => text);
|
||||
assert.ok(labels.includes('New apps enabled by default'));
|
||||
assert.ok(labels.includes('Enable all'));
|
||||
assert.ok(labels.includes('Disable all'));
|
||||
await app.input(app.filter, 'click');
|
||||
assert.equal(app.prefs.newNotificationAppsEnabledByDefault(), false);
|
||||
app.active([mail]);
|
||||
app.paint(app.filter);
|
||||
assert.equal(app.prefs.shouldShowNotificationOnGlasses(mail.packageName), false);
|
||||
await app.input(app.filter, 'scroll-down');
|
||||
await app.input(app.filter, 'click');
|
||||
assert.equal(app.prefs.shouldShowNotificationOnGlasses(mail.packageName), true);
|
||||
assert.equal(app.prefs.newNotificationAppsEnabledByDefault(), false);
|
||||
await app.input(app.filter, 'scroll-down');
|
||||
await app.input(app.filter, 'click');
|
||||
assert.equal(app.prefs.shouldShowNotificationOnGlasses(mail.packageName), false);
|
||||
assert.equal(app.dismissals(), 0);
|
||||
});
|
||||
|
||||
test('popup action wraps fully and stays visible with small and large fonts', async () => {
|
||||
for (const size of [12, 20]) {
|
||||
const app = ui(size);
|
||||
@@ -254,3 +318,33 @@ test('controller filters before waking or opening a popup, and still refreshes t
|
||||
elapse();
|
||||
assert.equal(popups, 1);
|
||||
});
|
||||
|
||||
test('Android display filters before limits and reapplies preferences to cached tray icons', () => {
|
||||
const prefs = store();
|
||||
const active = [{ ...mail, key: 'hidden' }, { packageName: 'allowed', appName: 'Allowed', key: 'shown' }];
|
||||
const file = ts.createSourceFile('icons.ts', source('app/native/notification-icons.ts'), ts.ScriptTarget.Latest, true);
|
||||
const functions = file.statements.filter(node => ts.isFunctionDeclaration(node) &&
|
||||
['readVisibleNotifications', 'cachedIconsResult'].includes(node.name?.text)).map(node => node.getText(file));
|
||||
const { readVisibleNotifications, cachedIconsResult } = evaluate(functions.join('\n') + '\nexport { cachedIconsResult };', null, {
|
||||
ALL_NOTIFICATIONS: 0x7fffffff,
|
||||
readActiveNotifications: () => { prefs.rememberNotificationSources(active); return active; },
|
||||
shouldShowNotificationOnGlasses: prefs.shouldShowNotificationOnGlasses,
|
||||
cachedKeys: ['hidden', 'shown'],
|
||||
cachedPackages: new Map(active.map(n => [n.key, n.packageName])),
|
||||
cachedIcons: [{ clone: () => 'mail-icon' }, { clone: () => 'allowed-icon' }],
|
||||
});
|
||||
prefs.setNotificationSourceEnabled(mail, false);
|
||||
assert.deepEqual(Array.from(readVisibleNotifications(1), n => n.key), ['shown']);
|
||||
for (const stale of [false, true]) {
|
||||
const result = cachedIconsResult(1, stale);
|
||||
assert.deepEqual(Array.from(result.keys), ['shown']);
|
||||
assert.deepEqual(Array.from(result.icons), ['allowed-icon']);
|
||||
assert.equal(result.stale, stale);
|
||||
}
|
||||
prefs.setAllNotificationSourcesEnabled(false);
|
||||
assert.equal(cachedIconsResult(10, false).keys.length, 0);
|
||||
assert.equal(readVisibleNotifications(50).length, 0);
|
||||
prefs.setNotificationSourceEnabled(mail, true);
|
||||
assert.deepEqual(Array.from(cachedIconsResult(1, false).keys), ['hidden']);
|
||||
assert.equal(active.length, 2);
|
||||
});
|
||||
Reference in new issue
Block a user