mirror of
https://git.undefined-dev.fr/Blendman974/faceclaw.git
synced 2026-11-19 21:03:09 +00:00
Merge pull request 'feat(notifications): suivre le mode Ne pas déranger du téléphone' (#17) from MasterControl/faceclaw:feat/follow-phone-dnd into build/all-features
Reviewed-on: https://git.undefined-dev.fr/Blendman974/faceclaw/pulls/17
This commit is contained in:
commit
3dd307483d
14 files changed
+574
-20
No files matched your search
+24
-1
@@ -125,6 +125,27 @@ class FaceclawMediaNotificationListenerService : NotificationListenerService() {
|
||||
return "connecting"
|
||||
}
|
||||
|
||||
/** Fresh, read-only phone DND state; unavailable filters retain normal wake behavior. */
|
||||
@JvmStatic
|
||||
fun isPhoneDoNotDisturbEnabled(context: Context?): Boolean {
|
||||
val filter = try {
|
||||
val manager = context?.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager
|
||||
manager?.currentInterruptionFilter
|
||||
} catch (t: Throwable) {
|
||||
null
|
||||
} ?: try {
|
||||
activeService?.currentInterruptionFilter
|
||||
} catch (t: Throwable) {
|
||||
null
|
||||
}
|
||||
return when (filter) {
|
||||
NotificationManager.INTERRUPTION_FILTER_PRIORITY,
|
||||
NotificationManager.INTERRUPTION_FILTER_NONE,
|
||||
NotificationManager.INTERRUPTION_FILTER_ALARMS -> true
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
/** Run on the main thread whenever getListenerState may have changed. */
|
||||
@JvmStatic
|
||||
fun addListenerStateObserver(observer: Runnable?) {
|
||||
@@ -517,7 +538,9 @@ class FaceclawMediaNotificationListenerService : NotificationListenerService() {
|
||||
}
|
||||
|
||||
private fun emitNotificationPosted(key: String?) {
|
||||
emitNotificationEvent(key) { listener, eventKey -> listener.onNotificationPosted(eventKey) }
|
||||
// Capture before mainHandler posting: a later DND change must not alter this arrival.
|
||||
val canWakeScreen = !isPhoneDoNotDisturbEnabled(activeService)
|
||||
emitNotificationEvent(key) { listener, eventKey -> listener.onNotificationPosted(eventKey, canWakeScreen) }
|
||||
}
|
||||
|
||||
private fun emitNotificationRemoved(key: String?) {
|
||||
|
||||
@@ -16,6 +16,7 @@ import { mediaControllerBridge } from "../native/media-controller";
|
||||
import { nightscoutBridge } from "../native/nightscout-bridge";
|
||||
import { weatherBridge } from "../native/weather";
|
||||
import { ALL_NOTIFICATIONS, onAndroidNotificationPosted, onAndroidNotificationRemoved, readActiveNotifications } from "../native/notification-icons";
|
||||
import { isPhoneDoNotDisturbEnabled } from "../native/phone-do-not-disturb";
|
||||
import { watchNotificationListenerBinding } from "../native/notification-access";
|
||||
import { openEvenAppSettings, readEvenAppNotificationState } from "../native/even-app-conflict";
|
||||
import { defaultRingName, setGlassesRingLink } from "../native/ring-status";
|
||||
@@ -364,7 +365,7 @@ class DashboardController {
|
||||
private offAndroidNotification: (() => void) | null = null;
|
||||
private offAndroidNotificationRemoved: (() => void) | null = null;
|
||||
/** New notifications wait here briefly before popping up (see NotificationPopupDelay). */
|
||||
private readonly notificationPopups = new NotificationPopupDelay((notificationKey) => this.popUpAndroidNotification(notificationKey));
|
||||
private readonly notificationPopups = new NotificationPopupDelay((notificationKey, canWakeScreen) => this.popUpAndroidNotification(notificationKey, canWakeScreen));
|
||||
private lastInput = "waiting...";
|
||||
private lastSys = "none yet";
|
||||
private shellRenderInProgress = false;
|
||||
@@ -472,7 +473,7 @@ class DashboardController {
|
||||
app.boot?.(this.buildAppContext(app));
|
||||
}
|
||||
timerEngine.onChange(() => this.refreshAlarmReliabilityWarning());
|
||||
this.offAndroidNotification = onAndroidNotificationPosted((notificationKey) => this.handleAndroidNotificationPosted(notificationKey));
|
||||
this.offAndroidNotification = onAndroidNotificationPosted((notificationKey, canWakeScreen) => this.handleAndroidNotificationPosted(notificationKey, canWakeScreen));
|
||||
this.offAndroidNotificationRemoved = onAndroidNotificationRemoved((notificationKey) => this.handleAndroidNotificationRemoved(notificationKey));
|
||||
watchNotificationListenerBinding();
|
||||
readActiveNotifications(ALL_NOTIFICATIONS);
|
||||
@@ -3008,12 +3009,13 @@ class DashboardController {
|
||||
this.schedulePreviewUpdate();
|
||||
}
|
||||
|
||||
private handleAndroidNotificationPosted(notificationKey: string): void {
|
||||
private handleAndroidNotificationPosted(notificationKey: string, canWakeScreen = true): void {
|
||||
// The tray shows the notification at once; its popup waits out a short
|
||||
// delay, so one withdrawn right away (see NotificationPopupDelay) never shows.
|
||||
const notification = readActiveNotifications(ALL_NOTIFICATIONS).find((item) => item.key === notificationKey);
|
||||
if (notification && shouldPopUpNewNotification(notification.packageName)) {
|
||||
this.notificationPopups.post(notificationKey, notificationPopupDelayMs(notification));
|
||||
this.notificationPopups.post(notificationKey, notificationPopupDelayMs(notification),
|
||||
canWakeScreen && !isPhoneDoNotDisturbEnabled());
|
||||
}
|
||||
this.requestShellRender();
|
||||
}
|
||||
@@ -3031,10 +3033,13 @@ class DashboardController {
|
||||
}
|
||||
|
||||
/** A posted notification waited out its popup delay: show it, if it is still there. */
|
||||
private popUpAndroidNotification(notificationKey: string): void {
|
||||
private popUpAndroidNotification(notificationKey: string, canWakeScreen = true): void {
|
||||
try {
|
||||
const notification = readActiveNotifications(ALL_NOTIFICATIONS).find((item) => item.key === notificationKey);
|
||||
if (!notification || !shouldPopUpNewNotification(notification.packageName)) return;
|
||||
// Keep the arrival-time restriction and re-check DND immediately before
|
||||
// waking: a delayed popup must neither outlive DND nor bypass a new DND.
|
||||
if (!shell.isScreenOn() && (!canWakeScreen || isPhoneDoNotDisturbEnabled())) return;
|
||||
// New notifications open a shell modal over the app viewport; if the
|
||||
// screen was off, wake for it and go back to sleep when it is closed.
|
||||
// Waking while already on would steal focus, so only wake from sleep.
|
||||
|
||||
@@ -26,7 +26,7 @@ let cachedAtMs = 0;
|
||||
const keyedIconCache = new Map<string, { icon: GrayImage | null; atMs: number }>();
|
||||
const KEYED_ICON_CACHE_MAX = 128;
|
||||
let notificationListenerProxy: any = null;
|
||||
const notificationPostedListeners = new Set<(notificationKey: string) => void>();
|
||||
const notificationPostedListeners = new Set<(notificationKey: string, canWakeScreen?: boolean) => void>();
|
||||
const notificationRemovedListeners = new Set<(notificationKey: string) => void>();
|
||||
let listenerStateObserver: any = null;
|
||||
const listenerStateListeners = new Set<() => void>();
|
||||
@@ -358,7 +358,7 @@ export function dismissAllNotifications(): boolean {
|
||||
return Boolean(com.faceclaw.app.FaceclawMediaNotificationListenerService.dismissAllNotifications());
|
||||
}
|
||||
|
||||
export function onAndroidNotificationPosted(listener: (notificationKey: string) => void): () => void {
|
||||
export function onAndroidNotificationPosted(listener: (notificationKey: string, canWakeScreen?: boolean) => void): () => void {
|
||||
return addNotificationListener(notificationPostedListeners, listener);
|
||||
}
|
||||
|
||||
@@ -412,8 +412,8 @@ function onListenerStateChanged(listener: () => void): () => void {
|
||||
}
|
||||
|
||||
function addNotificationListener(
|
||||
listeners: Set<(notificationKey: string) => void>,
|
||||
listener: (notificationKey: string) => void,
|
||||
listeners: Set<(notificationKey: string, canWakeScreen?: boolean) => void>,
|
||||
listener: (notificationKey: string, canWakeScreen?: boolean) => void,
|
||||
): () => void {
|
||||
listeners.add(listener);
|
||||
ensureNativeNotificationListener();
|
||||
@@ -458,8 +458,8 @@ function normalizeNotification(value: any): AndroidNotification | null {
|
||||
function ensureNativeNotificationListener(): void {
|
||||
if (!global.isAndroid || notificationListenerProxy) return;
|
||||
notificationListenerProxy = new com.faceclaw.app.FaceclawNotificationListener({
|
||||
onNotificationPosted: (notificationKey: string) => {
|
||||
dispatchNotificationEvent(notificationPostedListeners, notificationKey);
|
||||
onNotificationPosted: (notificationKey: string, canWakeScreen?: boolean) => {
|
||||
dispatchNotificationEvent(notificationPostedListeners, notificationKey, canWakeScreen);
|
||||
},
|
||||
onNotificationRemoved: (notificationKey: string) => {
|
||||
dispatchNotificationEvent(notificationRemovedListeners, notificationKey);
|
||||
@@ -470,13 +470,21 @@ function ensureNativeNotificationListener(): void {
|
||||
);
|
||||
}
|
||||
|
||||
function dispatchNotificationEvent(listeners: Set<(notificationKey: string) => void>, notificationKey: string): void {
|
||||
function dispatchNotificationEvent(
|
||||
listeners: Set<(notificationKey: string, canWakeScreen?: boolean) => void>,
|
||||
notificationKey: string,
|
||||
canWakeScreen = true,
|
||||
): void {
|
||||
invalidateIconCaches();
|
||||
const key = String(notificationKey);
|
||||
const snapshot = Array.from(listeners);
|
||||
setTimeout(() => {
|
||||
for (const listener of snapshot) {
|
||||
listener(key);
|
||||
if (listeners === notificationPostedListeners) {
|
||||
listener(key, canWakeScreen);
|
||||
} else {
|
||||
listener(key);
|
||||
}
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { Utils } from "@nativescript/core";
|
||||
|
||||
declare const com: any;
|
||||
|
||||
/** Read the phone's current interruption filter; never change its DND policy. */
|
||||
export function isPhoneDoNotDisturbEnabled(): boolean {
|
||||
if (!global.isAndroid) return false;
|
||||
try {
|
||||
return Boolean(com.faceclaw.app.FaceclawMediaNotificationListenerService.isPhoneDoNotDisturbEnabled(
|
||||
Utils.android.getApplicationContext(),
|
||||
));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -33,11 +33,11 @@ export const scheduleTimeout: ScheduleFn = (run, delayMs) => {
|
||||
};
|
||||
|
||||
export class NotificationPopupDelay {
|
||||
private readonly pending = new Map<string, { dueAtMs: number; cancel: () => void }>();
|
||||
private readonly pending = new Map<string, { dueAtMs: number; cancel: () => void; wakePolicy: { canWakeScreen: boolean } }>();
|
||||
|
||||
/** `ready` receives each notification that survived its delay, to re-check and pop up. */
|
||||
constructor(
|
||||
private readonly ready: (notificationKey: string) => void,
|
||||
private readonly ready: (notificationKey: string, canWakeScreen: boolean) => void,
|
||||
private readonly schedule: ScheduleFn = scheduleTimeout,
|
||||
private readonly now: () => number = Date.now,
|
||||
) {}
|
||||
@@ -49,18 +49,22 @@ export class NotificationPopupDelay {
|
||||
* foreground-service placeholder into a real message (same key) gets the
|
||||
* shorter delay.
|
||||
*/
|
||||
post(notificationKey: string, delayMs: number): void {
|
||||
post(notificationKey: string, delayMs: number, canWakeScreen = true): void {
|
||||
const dueAtMs = this.now() + delayMs;
|
||||
const existing = this.pending.get(notificationKey);
|
||||
// Share this object with an existing timer: a repost may restrict wake,
|
||||
// but cannot turn a DND-silenced pending notification into a fresh alert.
|
||||
const wakePolicy = existing?.wakePolicy ?? { canWakeScreen: true };
|
||||
wakePolicy.canWakeScreen = wakePolicy.canWakeScreen && canWakeScreen;
|
||||
if (existing) {
|
||||
if (existing.dueAtMs <= dueAtMs) return;
|
||||
existing.cancel();
|
||||
}
|
||||
const cancel = this.schedule(() => {
|
||||
this.pending.delete(notificationKey);
|
||||
this.ready(notificationKey);
|
||||
this.ready(notificationKey, wakePolicy.canWakeScreen);
|
||||
}, delayMs);
|
||||
this.pending.set(notificationKey, { dueAtMs, cancel });
|
||||
this.pending.set(notificationKey, { dueAtMs, cancel, wakePolicy });
|
||||
}
|
||||
|
||||
/** The notification went away before popping up; returns whether it was waiting. */
|
||||
|
||||
@@ -75,6 +75,7 @@ import { ShellModalLayer } from "./modal-layer";
|
||||
import { NotificationModalQueue } from "./notification-modal-queue";
|
||||
import { NotificationPopupTimeout } from "./notification-popup-timeout";
|
||||
import { ALL_NOTIFICATIONS, readActiveNotifications } from "../../native/notification-icons";
|
||||
import { isPhoneDoNotDisturbEnabled } from "../../native/phone-do-not-disturb";
|
||||
import { ToolDebugMenuLayer } from "./tool-debug-layer";
|
||||
import type { InProcessWindow } from "./in-process-window";
|
||||
import { BrightnessPickerLayer } from "./brightness-picker-layer";
|
||||
@@ -939,6 +940,7 @@ class Shell {
|
||||
* shown: in the notification modal, waking the screen for it if it was off.
|
||||
*/
|
||||
postAppNotification(notification: AppNotification): void {
|
||||
if (!this.screenOn && isPhoneDoNotDisturbEnabled()) return;
|
||||
this.appNotifications.set(notification.key, notification);
|
||||
const wokeScreen = this.screenOn ? false : this.wake("sidebar");
|
||||
this.openNotificationModal(notification.key, wokeScreen);
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
# Phone Do Not Disturb and notification wake
|
||||
|
||||
## Behavior
|
||||
|
||||
Faceclaw automatically follows **Android's current Do Not Disturb interruption
|
||||
filter** for notification-triggered screen wake. No separate Faceclaw setting or
|
||||
notification-policy modification is needed.
|
||||
|
||||
- Phone DND active and glasses asleep: a mirrored notification does **not** wake
|
||||
the glasses or open a sleeping-screen popup. The notification is not dismissed
|
||||
on the phone and stays available in the Notifications app/status tray.
|
||||
- Glasses already awake: popups keep their normal behavior, including the visible
|
||||
app background and the existing source filters/display timeout. DND does not
|
||||
force an awake screen off or steal focus.
|
||||
- DND off: new eligible notifications wake normally. Silenced notifications are
|
||||
not kept in a wake backlog and disabling DND does not replay them.
|
||||
- Priority-only, total-silence and alarms-only filters all count as DND. Android
|
||||
priority exceptions do not make a mirrored notification wake the glasses.
|
||||
- App-generated notification popups also respect DND while asleep, including
|
||||
Nightscout alerts; those local-only popups are not retained for replay. The
|
||||
dedicated Timers alarm engine and manual/ring/head-up wake are unchanged.
|
||||
- iOS Focus/DND synchronization is **not implemented** by this Android reader;
|
||||
the non-Android reader returns false and preserves existing behavior.
|
||||
|
||||
Reading the filter is read-only. No setter, policy-access permission request,
|
||||
new broadcast receiver or polling loop is introduced. If the Android service or
|
||||
filter cannot be read, the reader reports DND inactive/unknown and preserves the
|
||||
previous wake behavior; it does not pretend to know an unavailable phone state.
|
||||
|
||||
## Race handling
|
||||
|
||||
The native listener captures wake eligibility before posting its asynchronous
|
||||
notification callback. The TypeScript bridge forwards that immutable flag. The
|
||||
controller combines it with a fresh DND read on JS delivery and retains the
|
||||
restriction through the existing 500 ms/foreground-service popup delay. Reposts
|
||||
can restrict a pending notification but cannot make a DND-silenced pending alert
|
||||
eligible to wake by shortening or retaining its timer.
|
||||
|
||||
Immediately before waking, the controller checks DND again. This covers both
|
||||
DND becoming active during a delay and DND being disabled after a notification
|
||||
arrived silently. The flag limits **wake**, not a popup on an already-awake
|
||||
screen. On listener reconnect, the existing recent-notification reconciliation
|
||||
samples the current phone filter; it cannot reconstruct historical DND changes
|
||||
while the listener/process was disconnected.
|
||||
|
||||
## Validation
|
||||
|
||||
Commands from the repository root:
|
||||
|
||||
```sh
|
||||
npm test
|
||||
npm exec -- tsc --noEmit
|
||||
npm run lint
|
||||
npm run test:kotlin
|
||||
git diff --check
|
||||
```
|
||||
|
||||
Baseline on `build/all-features` commit `54ba6b4f`: 1,335 tests, 1,332 passed,
|
||||
3 skipped, no failures. With the feature, the full suite passes 1,351 tests
|
||||
(1,354 total, 3 skipped), with no failures. TypeScript `--noEmit` and lint pass;
|
||||
lint retains five warnings in untouched files and no warning from this feature.
|
||||
The targeted wake/bridge/delay suite passes all 23 tests; the initial broader
|
||||
regression selection also passed all 62 tests covering controller behavior,
|
||||
delay/reposts, source filters, modal queue/backdrop and existing shell consumers.
|
||||
|
||||
New wake-policy tests were observed failing first (DND caused an unwanted wake,
|
||||
arrival metadata was lost, and reposts could unsilence a delayed popup), then
|
||||
passing after implementation. Native-boundary tests use the actual transpiled
|
||||
bridge with a fake Android boundary; Kotlin source-contract checks do not prove
|
||||
an Android compilation or actual OEM DND behavior.
|
||||
|
||||
Native Kotlin tests were attempted but cannot start in this environment:
|
||||
`JAVA_HOME is not set and no 'java' command could be found in your PATH.` No APK,
|
||||
physical phone/glasses test or release is claimed by these checks.
|
||||
|
||||
## Device acceptance checks before release
|
||||
|
||||
1. Grant the app its usual notification-listener access and connect the glasses.
|
||||
2. With glasses asleep, enable each supported Android DND mode and send a
|
||||
notification from an enabled source. Verify the glasses remain asleep and
|
||||
the notification can still be opened manually from the Notifications app.
|
||||
3. Turn DND off: verify no old notification wakes the glasses. Send a new
|
||||
notification and verify normal popup/wake and return-to-sleep behavior.
|
||||
4. With the glasses already awake, enable DND and send a notification. Verify
|
||||
the normal popup and visible app background, with no focus-stealing wake.
|
||||
5. Enable/disable DND during the popup delay, including a foreground-service
|
||||
placeholder and updates under the same notification key. Verify no delayed
|
||||
DND arrival wakes the glasses after the restriction changes.
|
||||
6. Check local-only app notification wake, normal manual/ring/head-up wake,
|
||||
Timers, disabled sources, notification withdrawal and listener reconnect.
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
interface FaceclawNotificationListener {
|
||||
fun onNotificationPosted(key: String?): Unit
|
||||
fun onNotificationPosted(key: String?, canWakeScreen: Boolean): Unit
|
||||
fun onNotificationRemoved(key: String?): Unit
|
||||
}
|
||||
@@ -288,6 +288,7 @@ function shellEnv({ wakeAction = 'voice-input', skipConfirmation = false } = {})
|
||||
'./brightness-picker-layer': {}, './notification-modal-queue': load('app/ui/shell/notification-modal-queue.ts', {}),
|
||||
'./notification-popup-timeout': {},
|
||||
'../../native/notification-icons': {}, '../../native/notification-sources': {},
|
||||
'../../native/phone-do-not-disturb': { isPhoneDoNotDisturbEnabled: () => false },
|
||||
'../../assistant/tool-registry': {}, './geometry': {
|
||||
sidebarWidth: () => 64, minWindowTop: () => 96, switcherPosition: () => 'left', uiDepth: () => 0,
|
||||
screenWidth: () => 640, screenHeight: () => 480,
|
||||
|
||||
@@ -136,6 +136,7 @@ test('system menu hides brightness in Auto and opens its picker between Voice in
|
||||
'../dashboard-settings': f.settings, './geometry': f.geometry, './brightness-picker-layer': f.picker,
|
||||
'./chrome-layer': { ShellChromeLayer: class {} },
|
||||
'./notification-modal-queue': load('app/ui/shell/notification-modal-queue.ts'),
|
||||
'../../native/phone-do-not-disturb': { isPhoneDoNotDisturbEnabled: () => false },
|
||||
});
|
||||
shell.registerWindow({ windowId: 'test', appId: 'test', closeable: true, handleInput() {} });
|
||||
shell.openSystemMenu('test');
|
||||
|
||||
@@ -304,6 +304,7 @@ test('controller filters before waking or opening a popup, and still refreshes t
|
||||
ALL_NOTIFICATIONS: 0x7fffffff,
|
||||
readActiveNotifications: () => active,
|
||||
shouldPopUpNewNotification,
|
||||
isPhoneDoNotDisturbEnabled: () => false,
|
||||
notificationPopupDelayMs,
|
||||
shell: {
|
||||
isScreenOn: () => false,
|
||||
|
||||
@@ -84,6 +84,32 @@ test("reposts can bring a popup forward but never push it back", () => {
|
||||
assert.deepEqual(ready, ["a", "b"], "the earlier timer was cancelled");
|
||||
});
|
||||
|
||||
test("a notification retains its arrival-time no-wake policy through the popup delay", () => {
|
||||
const clock = makeClock();
|
||||
const ready = [];
|
||||
const delay = new NotificationPopupDelay((key, canWakeScreen) => ready.push([key, canWakeScreen]), clock.schedule, clock.now);
|
||||
delay.post("quiet", 500, false);
|
||||
delay.post("normal", 500);
|
||||
clock.advance(500);
|
||||
assert.deepEqual(ready, [["quiet", false], ["normal", true]]);
|
||||
});
|
||||
|
||||
test("a repost cannot re-enable wake after a DND arrival or discard a new DND restriction", () => {
|
||||
for (const firstAllowed of [false, true]) {
|
||||
for (const nextDelay of [500, 100]) {
|
||||
const clock = makeClock();
|
||||
const ready = [];
|
||||
const delay = new NotificationPopupDelay((key, canWakeScreen) => ready.push([key, canWakeScreen]), clock.schedule, clock.now);
|
||||
delay.post("message", 500, firstAllowed);
|
||||
clock.advance(50);
|
||||
delay.post("message", nextDelay, !firstAllowed);
|
||||
clock.advance(1000);
|
||||
assert.deepEqual(ready, [["message", false]], `firstAllowed=${firstAllowed}, nextDelay=${nextDelay}`);
|
||||
assert.deepEqual(delay.pendingKeys(), []);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("foreground-service notifications wait longer, unless urgent", () => {
|
||||
assert.equal(notificationPopupDelayMs({ category: "msg" }), NOTIFICATION_POPUP_DELAY_MS);
|
||||
assert.equal(notificationPopupDelayMs({ category: "", foregroundService: true }), FOREGROUND_SERVICE_POPUP_DELAY_MS);
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { loader } = require('./helpers/load-typescript.cjs');
|
||||
|
||||
const kotlinServicePath = 'App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaNotificationListenerService.kt';
|
||||
function source(file) { return fs.readFileSync(path.resolve(__dirname, '..', file), 'utf8'); }
|
||||
|
||||
// Structural source contracts only: these do not compile or execute Android/Kotlin.
|
||||
test('structural Kotlin contract: fresh read-only DND getter maps restrictive filters and fails open', () => {
|
||||
const service = source(kotlinServicePath);
|
||||
const getter = service.match(/@JvmStatic\s+fun isPhoneDoNotDisturbEnabled\(context: Context\?\): Boolean \{([\s\S]*?)\n \}/);
|
||||
assert.ok(getter, 'missing static context-based DND getter');
|
||||
assert.match(getter[1], /context\?\.getSystemService\(Context\.NOTIFICATION_SERVICE\) as\? NotificationManager/);
|
||||
assert.match(getter[1], /manager\?\.currentInterruptionFilter/);
|
||||
assert.match(getter[1], /activeService\?\.currentInterruptionFilter/);
|
||||
assert.match(getter[1], /catch \([^)]*: Throwable\)/);
|
||||
assert.match(getter[1], /NotificationManager\.INTERRUPTION_FILTER_PRIORITY,\s*NotificationManager\.INTERRUPTION_FILTER_NONE,\s*NotificationManager\.INTERRUPTION_FILTER_ALARMS -> true/);
|
||||
assert.match(getter[1], /else -> false/);
|
||||
assert.doesNotMatch(getter[1], /setInterruptionFilter|requestInterruptionFilter|Settings\.|postDelayed/);
|
||||
assert.doesNotMatch(service, /override fun onInterruptionFilterChanged/);
|
||||
assert.match(source('App_Resources/Android/app.gradle'), /minSdkVersion 24\b/);
|
||||
});
|
||||
|
||||
test('structural Kotlin contract: posted callback snapshots DND before main-handler delivery, including reconnect', () => {
|
||||
const service = source(kotlinServicePath);
|
||||
const emit = service.match(/private fun emitNotificationPosted\(key: String\?\) \{([\s\S]*?)\n \}/);
|
||||
assert.ok(emit);
|
||||
assert.match(emit[1], /val canWakeScreen = !isPhoneDoNotDisturbEnabled\(activeService\)/);
|
||||
assert.match(emit[1], /listener\.onNotificationPosted\(eventKey, canWakeScreen\)/);
|
||||
assert.ok(emit[1].indexOf('val canWakeScreen') < emit[1].indexOf('emitNotificationEvent('));
|
||||
assert.equal((emit[1].match(/isPhoneDoNotDisturbEnabled/g) ?? []).length, 1);
|
||||
const dispatch = service.match(/private fun emitNotificationEvent\([\s\S]*?\n \}/)[0];
|
||||
assert.match(dispatch, /mainHandler\.post \{[\s\S]*deliver\(listener, key\)/);
|
||||
assert.doesNotMatch(dispatch, /isPhoneDoNotDisturbEnabled/);
|
||||
assert.match(service, /for \(key in posted\) \{\s*emitNotificationPosted\(key\)/);
|
||||
assert.match(service, /private fun emitNotificationRemoved\(key: String\?\) \{\s*emitNotificationEvent\(key\) \{ listener, eventKey -> listener\.onNotificationRemoved\(eventKey\) \}/);
|
||||
const callback = source('native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/callbacks/FaceclawNotificationListener.kt');
|
||||
assert.match(callback, /fun onNotificationPosted\(key: String\?, canWakeScreen: Boolean\): Unit/);
|
||||
assert.match(callback, /fun onNotificationRemoved\(key: String\?\): Unit/);
|
||||
});
|
||||
|
||||
function notificationBridge() {
|
||||
const tasks = [];
|
||||
let proxy;
|
||||
let observer;
|
||||
const service = {
|
||||
addNotificationListener(value) { proxy = value; },
|
||||
removeNotificationListener(value) { assert.equal(value, proxy); proxy = undefined; },
|
||||
addListenerStateObserver(value) { observer = value; },
|
||||
removeListenerStateObserver(value) { assert.equal(value, observer); observer = undefined; },
|
||||
};
|
||||
const api = loader({
|
||||
global: { isAndroid: true },
|
||||
setTimeout(fn, delay) { assert.equal(delay, 0); tasks.push(fn); },
|
||||
com: { faceclaw: { app: {
|
||||
FaceclawMediaNotificationListenerService: service,
|
||||
FaceclawNotificationListener: function (callbacks) { return callbacks; },
|
||||
} } },
|
||||
java: { lang: { Runnable: function (callbacks) { return callbacks; } } },
|
||||
}, {
|
||||
'../graphics/image': {}, './frame-timings': { spanCurrent: (_name, fn) => fn() },
|
||||
'../util/array-util': { toUint8Array: value => value },
|
||||
'./notification-sources': {}, './image-files': { PHOTO_TONE: { gamma: 1 } },
|
||||
'./notification-types': { NOTIFICATION_ICON_SIZE: 24 },
|
||||
})('app/native/notification-icons.ts');
|
||||
return {
|
||||
api, service, get proxy() { return proxy; }, get observer() { return observer; },
|
||||
flush() { while (tasks.length) tasks.shift()(); },
|
||||
};
|
||||
}
|
||||
|
||||
test('native posted wake permission remains immutable across asynchronous bridge dispatch', () => {
|
||||
const bridge = notificationBridge();
|
||||
const posted = [];
|
||||
const off = bridge.api.onAndroidNotificationPosted((key, canWakeScreen) => posted.push([key, canWakeScreen]));
|
||||
let dnd = true;
|
||||
bridge.service.isPhoneDoNotDisturbEnabled = () => dnd;
|
||||
const reader = loadDnd({ service: bridge.service });
|
||||
bridge.proxy.onNotificationPosted('dnd-active', !reader.isPhoneDoNotDisturbEnabled());
|
||||
dnd = false;
|
||||
bridge.proxy.onNotificationPosted('dnd-off', !reader.isPhoneDoNotDisturbEnabled());
|
||||
bridge.proxy.onNotificationPosted('legacy');
|
||||
assert.deepEqual(posted, []);
|
||||
bridge.flush();
|
||||
assert.deepEqual(posted, [['dnd-active', false], ['dnd-off', true], ['legacy', true]]);
|
||||
dnd = true;
|
||||
assert.equal(reader.isPhoneDoNotDisturbEnabled(), true);
|
||||
dnd = false;
|
||||
assert.equal(reader.isPhoneDoNotDisturbEnabled(), false);
|
||||
bridge.flush();
|
||||
assert.equal(posted.length, 3, 'DND transitions alone do not replay notification posts');
|
||||
off();
|
||||
assert.equal(bridge.proxy, undefined);
|
||||
});
|
||||
|
||||
test('removed callbacks retain their key-only contract', () => {
|
||||
const bridge = notificationBridge();
|
||||
const removed = [];
|
||||
const off = bridge.api.onAndroidNotificationRemoved((...args) => removed.push(args));
|
||||
bridge.proxy.onNotificationRemoved('gone');
|
||||
bridge.flush();
|
||||
assert.deepEqual(removed, [['gone']]);
|
||||
off();
|
||||
});
|
||||
|
||||
test('posted, removed and listener-state observers retain async dispatch and eager cache invalidation', () => {
|
||||
const bridge = notificationBridge();
|
||||
const posted = [];
|
||||
const removed = [];
|
||||
let changed = 0;
|
||||
let iconReads = 0;
|
||||
bridge.service.getNotificationIconGrayForKey = () => { iconReads++; return new Uint8Array(); };
|
||||
const offPosted = bridge.api.onAndroidNotificationPosted(key => posted.push(key));
|
||||
const offRemoved = bridge.api.onAndroidNotificationRemoved(key => removed.push(key));
|
||||
const offChanged = bridge.api.onAndroidNotificationsChanged(() => changed++);
|
||||
const readIcon = () => bridge.api.readNotificationIconByKey('same-key', false);
|
||||
readIcon();
|
||||
readIcon();
|
||||
assert.equal(iconReads, 1);
|
||||
bridge.proxy.onNotificationPosted('same-key', false);
|
||||
readIcon();
|
||||
assert.equal(iconReads, 2, 'DND-blocked post still invalidates cached icons eagerly');
|
||||
assert.equal(changed, 0);
|
||||
bridge.flush();
|
||||
assert.deepEqual(posted, ['same-key']);
|
||||
assert.equal(changed, 1);
|
||||
bridge.proxy.onNotificationRemoved('same-key');
|
||||
readIcon();
|
||||
assert.equal(iconReads, 3);
|
||||
assert.deepEqual(removed, []);
|
||||
bridge.flush();
|
||||
assert.deepEqual(removed, ['same-key']);
|
||||
assert.equal(changed, 2);
|
||||
bridge.observer.run();
|
||||
readIcon();
|
||||
assert.equal(iconReads, 4);
|
||||
assert.equal(changed, 2);
|
||||
bridge.flush();
|
||||
assert.equal(changed, 3);
|
||||
assert.deepEqual(posted, ['same-key'], 'listener-state changes do not replay posts');
|
||||
offPosted();
|
||||
offRemoved();
|
||||
assert.ok(bridge.proxy, 'changed observer retains its native listeners');
|
||||
offChanged();
|
||||
assert.equal(bridge.proxy, undefined);
|
||||
assert.equal(bridge.observer, undefined);
|
||||
});
|
||||
|
||||
function loadDnd({ isAndroid = true, service, context = {} } = {}) {
|
||||
return loader({
|
||||
global: { isAndroid },
|
||||
com: { faceclaw: { app: { FaceclawMediaNotificationListenerService: service } } },
|
||||
}, { '@nativescript/core': { Utils: { android: { getApplicationContext: () => context } } } })(
|
||||
'app/native/phone-do-not-disturb.ts',
|
||||
);
|
||||
}
|
||||
|
||||
test('phone DND reader samples the native getter with application context on every Android read', () => {
|
||||
const context = {};
|
||||
let enabled = false;
|
||||
let reads = 0;
|
||||
const api = loadDnd({ context, service: {
|
||||
isPhoneDoNotDisturbEnabled(actualContext) {
|
||||
assert.equal(actualContext, context);
|
||||
reads++;
|
||||
return enabled;
|
||||
},
|
||||
} });
|
||||
assert.equal(api.isPhoneDoNotDisturbEnabled(), false);
|
||||
enabled = true;
|
||||
assert.equal(api.isPhoneDoNotDisturbEnabled(), true);
|
||||
enabled = false;
|
||||
assert.equal(api.isPhoneDoNotDisturbEnabled(), false);
|
||||
assert.equal(reads, 3);
|
||||
});
|
||||
|
||||
test('phone DND reader returns false when the native boundary is unavailable or throws', () => {
|
||||
for (const service of [undefined, {}, { isPhoneDoNotDisturbEnabled() { throw new Error('unavailable'); } }]) {
|
||||
assert.equal(loadDnd({ service }).isPhoneDoNotDisturbEnabled(), false);
|
||||
}
|
||||
const api = loader({ global: { isAndroid: true } }, {
|
||||
'@nativescript/core': { Application: {} },
|
||||
})('app/native/phone-do-not-disturb.ts');
|
||||
assert.equal(api.isPhoneDoNotDisturbEnabled(), false);
|
||||
});
|
||||
|
||||
test('phone DND reader returns false outside Android without touching native APIs', () => {
|
||||
const service = { isPhoneDoNotDisturbEnabled() { assert.fail('native getter must not run'); } };
|
||||
assert.equal(loadDnd({ isAndroid: false, service }).isPhoneDoNotDisturbEnabled(), false);
|
||||
const api = loader({ global: { isIOS: true } }, {
|
||||
'@nativescript/core': { Application: {} },
|
||||
})('app/native/phone-do-not-disturb.ts');
|
||||
assert.equal(api.isPhoneDoNotDisturbEnabled(), false);
|
||||
});
|
||||
@@ -0,0 +1,182 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const ts = require('typescript');
|
||||
const { NotificationPopupDelay, notificationPopupDelayMs } = require('../.test-build/app/ui/shell/notification-popup-delay.js');
|
||||
|
||||
function evaluateMembers(fileName, className, names, globals) {
|
||||
const source = ts.createSourceFile(fileName, fs.readFileSync(path.join(__dirname, '..', fileName), 'utf8'), ts.ScriptTarget.Latest, true);
|
||||
const declaration = source.statements.find(node => ts.isClassDeclaration(node) && node.name.text === className);
|
||||
const members = names.map(name => {
|
||||
const member = declaration.members.find(node => node.name?.getText(source) === name);
|
||||
assert.ok(member, `production member ${className}.${name} exists`);
|
||||
return member.getText(source);
|
||||
});
|
||||
const context = { exports: {}, ...globals };
|
||||
vm.runInNewContext(ts.transpileModule(`export class Harness { ${members.join('\n')} }`, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
|
||||
}).outputText, context);
|
||||
return context.exports.Harness;
|
||||
}
|
||||
|
||||
function controller() {
|
||||
const state = {
|
||||
dnd: false, screenOn: false, sourceAllowed: true, wakes: 0, renders: 0,
|
||||
modals: [], removed: [], active: [{ key: 'message', packageName: 'com.mail', category: 'msg' }],
|
||||
};
|
||||
let now = 0;
|
||||
const timers = [];
|
||||
const clock = {
|
||||
schedule(run, delay) {
|
||||
const timer = { due: now + delay, run, cancelled: false };
|
||||
timers.push(timer);
|
||||
return () => { timer.cancelled = true; };
|
||||
},
|
||||
advance(ms = 500) {
|
||||
const end = now + ms;
|
||||
for (;;) {
|
||||
const next = timers.filter(t => !t.cancelled && t.due <= end).sort((a, b) => a.due - b.due)[0];
|
||||
if (!next) break;
|
||||
now = next.due;
|
||||
next.cancelled = true;
|
||||
next.run();
|
||||
}
|
||||
now = end;
|
||||
},
|
||||
};
|
||||
const Harness = evaluateMembers('app/g2/dashboard-controller.ts', 'DashboardController', [
|
||||
'notificationPopups', 'handleAndroidNotificationPosted', 'handleAndroidNotificationRemoved', 'popUpAndroidNotification',
|
||||
], {
|
||||
NotificationPopupDelay: class extends NotificationPopupDelay {
|
||||
constructor(ready) { super(ready, clock.schedule, () => now); }
|
||||
},
|
||||
ALL_NOTIFICATIONS: 0x7fffffff,
|
||||
readActiveNotifications: () => state.active,
|
||||
shouldPopUpNewNotification: () => state.sourceAllowed,
|
||||
notificationPopupDelayMs,
|
||||
isPhoneDoNotDisturbEnabled: () => state.dnd,
|
||||
shell: {
|
||||
isScreenOn: () => state.screenOn,
|
||||
wake: () => { state.wakes++; state.screenOn = true; return true; },
|
||||
openNotificationModal: (key, woke) => state.modals.push({ key, woke }),
|
||||
notificationRemoved: key => state.removed.push(key),
|
||||
},
|
||||
});
|
||||
const host = new Harness();
|
||||
host.requestShellRender = () => state.renders++;
|
||||
host.appendLog = () => {};
|
||||
host.formatError = String;
|
||||
return { state, host, advance: clock.advance };
|
||||
}
|
||||
|
||||
test('phone DND prevents a mirrored notification waking sleeping glasses without deleting it', () => {
|
||||
const { host, state, advance } = controller();
|
||||
state.dnd = true;
|
||||
host.handleAndroidNotificationPosted('message');
|
||||
advance();
|
||||
assert.equal(state.wakes, 0);
|
||||
assert.deepEqual(state.modals, []);
|
||||
assert.equal(state.renders, 1, 'the notification tray still refreshes');
|
||||
assert.equal(state.active.length, 1, 'the phone notification stays available for manual viewing');
|
||||
});
|
||||
|
||||
test('a notification captured during phone DND cannot wake after DND turns off during its delay', () => {
|
||||
const { host, state, advance } = controller();
|
||||
// Native captured DND before its asynchronous callback; it is off by JS delivery.
|
||||
host.handleAndroidNotificationPosted('message', false);
|
||||
advance();
|
||||
assert.equal(state.wakes, 0);
|
||||
assert.deepEqual(state.modals, []);
|
||||
});
|
||||
|
||||
test('DND sampled at JS arrival remains restrictive if disabled before the popup timer', () => {
|
||||
const { host, state, advance } = controller();
|
||||
state.dnd = true;
|
||||
host.handleAndroidNotificationPosted('message', true);
|
||||
state.dnd = false;
|
||||
advance();
|
||||
assert.equal(state.wakes, 0);
|
||||
assert.deepEqual(state.modals, []);
|
||||
});
|
||||
|
||||
test('enabling DND during the popup delay prevents a previously eligible wake', () => {
|
||||
const { host, state, advance } = controller();
|
||||
host.handleAndroidNotificationPosted('message', true);
|
||||
state.dnd = true;
|
||||
advance();
|
||||
assert.equal(state.wakes, 0);
|
||||
assert.deepEqual(state.modals, []);
|
||||
});
|
||||
|
||||
test('DND leaves an already-awake notification popup normal without stealing focus', () => {
|
||||
const { host, state, advance } = controller();
|
||||
state.screenOn = true;
|
||||
state.dnd = true;
|
||||
host.handleAndroidNotificationPosted('message', false);
|
||||
advance();
|
||||
assert.equal(state.wakes, 0);
|
||||
assert.deepEqual(state.modals, [{ key: 'message', woke: false }]);
|
||||
});
|
||||
|
||||
test('DND silent arrivals are not replayed on disable, but new notifications wake normally', () => {
|
||||
const { host, state, advance } = controller();
|
||||
state.dnd = true;
|
||||
host.handleAndroidNotificationPosted('message', false);
|
||||
advance();
|
||||
state.dnd = false;
|
||||
advance(10_000);
|
||||
assert.equal(state.wakes, 0);
|
||||
assert.deepEqual(state.modals, []);
|
||||
assert.deepEqual(Array.from(host.notificationPopups.pendingKeys()), []);
|
||||
host.handleAndroidNotificationPosted('message', true);
|
||||
advance();
|
||||
assert.equal(state.wakes, 1);
|
||||
assert.deepEqual(state.modals, [{ key: 'message', woke: true }]);
|
||||
});
|
||||
|
||||
test('a DND popup arriving while awake cannot wake the screen if it sleeps during the delay', () => {
|
||||
const { host, state, advance } = controller();
|
||||
state.screenOn = true;
|
||||
state.dnd = true;
|
||||
host.handleAndroidNotificationPosted('message', false);
|
||||
state.screenOn = false;
|
||||
state.dnd = false;
|
||||
advance();
|
||||
assert.equal(state.wakes, 0);
|
||||
assert.deepEqual(state.modals, []);
|
||||
});
|
||||
|
||||
function appNotificationHost() {
|
||||
const state = { dnd: true, wakes: 0, modals: [] };
|
||||
const Harness = evaluateMembers('app/ui/shell/shell.ts', 'Shell', ['postAppNotification'], {
|
||||
isPhoneDoNotDisturbEnabled: () => state.dnd,
|
||||
});
|
||||
const host = new Harness();
|
||||
host.screenOn = false;
|
||||
host.appNotifications = new Map();
|
||||
host.wake = () => { state.wakes++; host.screenOn = true; return true; };
|
||||
host.openNotificationModal = (key, woke) => state.modals.push({ key, woke });
|
||||
return { host, state };
|
||||
}
|
||||
|
||||
test('phone DND also prevents an app-generated notification waking sleeping glasses without retaining an unreachable popup', () => {
|
||||
const { host, state } = appNotificationHost();
|
||||
host.postAppNotification({ key: 'local-alert' });
|
||||
assert.equal(state.wakes, 0);
|
||||
assert.deepEqual(state.modals, []);
|
||||
assert.equal(host.appNotifications.size, 0);
|
||||
});
|
||||
|
||||
test('app-generated notifications keep normal awake behavior during DND and wake normally when DND is off', () => {
|
||||
for (const screenOn of [true, false]) {
|
||||
const { host, state } = appNotificationHost();
|
||||
host.screenOn = screenOn;
|
||||
state.dnd = screenOn;
|
||||
host.postAppNotification({ key: 'local-alert' });
|
||||
assert.equal(state.wakes, screenOn ? 0 : 1);
|
||||
assert.deepEqual(state.modals, [{ key: 'local-alert', woke: !screenOn }]);
|
||||
assert.equal(host.appNotifications.size, 1);
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user