[verified] feat: follow phone Do Not Disturb for notification wake

This commit is contained in:
MasterControl committed 2026-11-11 17:43:35 +00:00
1 parent 54ba6b4f10
commit 9ca3574ae7
14 files changed
+574 -20

No files matched your search

+1
View File
@@ -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,
+1
View File
@@ -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');
+1
View File
@@ -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,
+26
View File
@@ -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);
+196
View File
@@ -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);
});
+182
View File
@@ -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);
}
});