Files
faceclaw/tests/notification-filter.test.cjs
T

351 lines
18 KiB
JavaScript

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');
function evaluate(source, requireModule, globals = {}) {
const context = { exports: {}, require: requireModule, ...globals };
vm.runInNewContext(ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, context);
return context.exports;
}
const source = (file) => fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
const load = (file, requireModule) => evaluate(source(file), requireModule);
function store(settings = new Map()) {
return load('app/native/notification-sources.ts', () => ({
getStringSetting: (key, fallback) => settings.get(key) ?? fallback,
setStringSetting: (key, value) => settings.set(key, value),
}));
}
const mail = { packageName: 'com.mail', appName: 'Mail' };
test('sources default on and retain per-package choices and names across restart and rediscovery', () => {
const settings = new Map();
let prefs = store(settings);
assert.equal(prefs.shouldShowNotificationOnGlasses(mail.packageName), true);
prefs.rememberNotificationSources([mail, mail, { packageName: 'com.other', appName: 'Mail' }]);
assert.equal(prefs.readNotificationSources().length, 2);
prefs.setNotificationSourceEnabled({ ...mail, text: 'private notification content' }, false);
assert.ok(!Array.from(settings.values()).join('').includes('private notification content'));
prefs = store(settings);
prefs.rememberNotificationSources([{ ...mail, appName: 'Renamed Mail' }, { packageName: 'com.new', appName: '' }]);
assert.equal(prefs.shouldShowNotificationOnGlasses(mail.packageName), false);
assert.equal(prefs.shouldShowNotificationOnGlasses('com.other'), true);
assert.equal(prefs.shouldShowNotificationOnGlasses('com.new'), true);
assert.equal(prefs.readNotificationSources().find((s) => s.packageName === mail.packageName).appName, 'Renamed Mail');
prefs.setNotificationSourceEnabled(mail, true);
assert.equal(store(settings).shouldShowNotificationOnGlasses(mail.packageName), true);
});
test('invalid saved source data falls back to enabled', () => {
for (const raw of ['invalid', '{}', '[null, {}, {"packageName": 1}]']) {
assert.equal(store(new Map([['notifications.sources', raw]])).shouldShowNotificationOnGlasses('com.mail'), true);
}
});
function ui(fontSize = 12) {
const prefs = store();
let active = [{ ...mail, key: 'key', title: 'Message', text: 'Hello', bigText: '', lines: [], actions: [], postTime: 0 }];
let dismissals = 0;
let closes = 0;
const textwrap = load('app/graphics/textwrap.ts');
const graphics = require('../.test-build/app/graphics/image.js');
const { BdfFont } = load('app/graphics/bdffont.ts', () => ({}));
const font = BdfFont.parse(source(`app/fonts/terminus/ter-u${fontSize}n.bdf`));
class RecordingImage extends graphics.GrayImage {
texts = [];
drawMenuSelection(source, x, y, ...args) {
this.texts.push(...source.texts.map(t => ({ ...t, x: t.x + x, y: t.y + y })));
super.drawMenuSelection(source, x, y, ...args);
}
drawText(font, x, y, text, value) {
this.texts.push({ x, y, text });
super.drawText(font, x, y, text, value);
}
}
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 }),
};
const dependencies = {
'../graphics/image': { ...graphics, GrayImage: RecordingImage },
'../graphics/textwrap': textwrap,
'../graphics/ui-fonts': { getDefaultSmallFont: () => font },
'../util/numeric-util': { clamp: (n, lo, hi) => Math.max(lo, Math.min(hi, n)) },
'~/util/numeric-util': { clamp: (n, lo, hi) => Math.max(lo, Math.min(hi, n)) },
'~/util/date-util': { formatRelativeTime: () => '' },
'../native/notification-icons': native,
'../native/notification-sources': prefs,
'../native/notification-types': require('../.test-build/app/native/notification-types.js'),
'../native/notification-access': { isNotificationListenerEnabled: () => true },
'../util/render-freshness': { renderPassAllowsStaleData: () => false },
'./menu-highlight-motion': require('../.test-build/app/ui/menu-highlight-motion.js'), '../graphics/menu-scroll-list': require('../.test-build/app/graphics/menu-scroll-list.js'), './menu-scroll-motion': require('../.test-build/app/ui/menu-scroll-motion.js'), '../graphics/draw-expression': require('../.test-build/app/graphics/draw-expression.js'),
'./metrics': load('app/ui/metrics.ts'),
'./menu-animation-pref': require('../.test-build/app/ui/menu-animation-pref.js'), './animation-speed': require('../.test-build/app/ui/animation-speed.js'), '../native/settings-store': { getStringSetting: (_key, fallback) => fallback },
'./gestures': {},
};
const requireModule = (name) => {
assert.ok(name in dependencies, `Unexpected dependency ${name}`);
return dependencies[name];
};
dependencies['./menu-core'] = load('app/ui/menu-core.ts', requireModule);
dependencies['./menu'] = load('app/ui/menu.ts', requireModule);
const { SingleNotificationLayer } = load('app/ui/notifications.ts', requireModule);
const { NotificationFilterLayer } = load('app/ui/notification-filter.ts', requireModule);
const ctx = { stack: { getBaseSize: () => ({ width: 540, height: 224 }), isFocused: () => true, pop: () => closes++ } };
const popup = new SingleNotificationLayer('key', { origin: 'new-notification-modal', onClose: () => closes++ });
const trayCloses = [];
const tray = new SingleNotificationLayer('key', { origin: 'notification-tray', onClose: (_ctx, gone) => trayCloses.push(gone) });
const filter = new NotificationFilterLayer();
let paintedBelow = 0;
const paint = (layer) => layer.paint(ctx, () => { paintedBelow++; return new RecordingImage(540, 224); });
const input = (layer, type) => layer.handleInput({ type }, ctx);
return { prefs, popup, tray, filter, paint, input, active: (value) => { active = value; },
dismissals: () => dismissals, closes: () => closes, trayCloses, paintedBelow: () => paintedBelow };
}
test('a notification the switcher selected reports back and dismissal to it, and repeats its last frame once gone', async () => {
const app = ui();
const labels = (image) => image.texts.map(({ text }) => text);
assert.ok(labels(app.paint(app.tray)).includes('Back'));
assert.ok(!labels(app.paint(app.tray)).some((text) => text.includes("Don't show")));
await app.input(app.tray, 'double-click');
await app.input(app.tray, 'click');
assert.deepEqual(app.trayCloses, [false, false]);
await app.input(app.tray, 'scroll-down');
const last = app.paint(app.tray);
await app.input(app.tray, 'click');
assert.equal(app.dismissals(), 1);
assert.deepEqual(app.trayCloses, [false, false, true]);
// The switcher swaps in a neighbour after the paint; until then the paint
// holds what was showing rather than the list below.
const again = app.paint(app.tray);
assert.deepEqual(app.trayCloses, [false, false, true, true]);
assert.equal(app.paintedBelow(), 0);
// (Compared unbaked: the menu highlight's draws animate with the clock.)
assert.deepEqual(Buffer.from(again.pixels), Buffer.from(last.pixels));
assert.deepEqual(again.drawList, last.drawList);
});
test('popup dismisses before confirmation; confirming disables the source even after the notification disappears', async () => {
const app = ui();
await app.input(app.popup, 'scroll-down');
await app.input(app.popup, 'scroll-down');
await app.input(app.popup, 'click');
assert.equal(app.dismissals(), 1);
assert.equal(app.closes(), 0);
assert.equal(app.prefs.shouldShowNotificationOnGlasses(mail.packageName), true);
assert.ok(app.paint(app.popup).texts.some(({ text }) => text.includes('Mail')));
assert.equal(app.closes(), 0);
await app.input(app.popup, 'scroll-down');
await app.input(app.popup, 'click');
assert.equal(app.prefs.shouldShowNotificationOnGlasses(mail.packageName), false);
assert.equal(app.closes(), 1);
});
test('cancel and back dismiss the popup without changing source preferences', async () => {
for (const cancel of ['click', 'double-click']) {
const app = ui();
await app.input(app.popup, 'scroll-down');
await app.input(app.popup, 'scroll-down');
await app.input(app.popup, 'click');
await app.input(app.popup, cancel);
assert.equal(app.dismissals(), 1);
assert.equal(app.closes(), 1);
assert.equal(app.prefs.shouldShowNotificationOnGlasses(mail.packageName), true);
}
});
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' }]);
const image = app.paint(app.filter);
assert.ok(image.texts.some(({ text }) => text === 'Alpha'));
assert.ok(image.texts.some(({ text }) => text === 'Mail'));
// A source inserted before the selection must not move the toggle to another app.
await app.input(app.filter, 'click');
assert.equal(app.prefs.shouldShowNotificationOnGlasses(mail.packageName), true);
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);
await app.input(app.popup, 'scroll-down');
await app.input(app.popup, 'scroll-down');
const image = app.paint(app.popup);
assert.ok(image.texts.map(({ text }) => text).join(' ').includes("Don't show on glasses again"));
assert.ok(image.texts.every(({ y }) => y >= 0 && y < image.height));
}
});
test('controller filters before waking or opening a popup, and still refreshes the tray', () => {
const file = ts.createSourceFile('controller.ts', source('app/g2/dashboard-controller.ts'), ts.ScriptTarget.Latest, true);
const controller = file.statements.find((node) => ts.isClassDeclaration(node) && node.name.text === 'DashboardController');
const members = ['handleAndroidNotificationPosted', 'handleAndroidNotificationRemoved', 'popUpAndroidNotification']
.map((name) => controller.members.find((node) => node.name?.getText(file) === name).getText(file));
const { NotificationPopupDelay, notificationPopupDelayMs } = require('../.test-build/app/ui/shell/notification-popup-delay.js');
const prefs = store();
let active = [{ ...mail, key: 'key' }];
let wakes = 0, popups = 0, renders = 0;
const removed = [];
const { Harness } = evaluate(`export class Harness { ${members.join('\n')} }`, null, {
ALL_NOTIFICATIONS: 0x7fffffff,
readActiveNotifications: () => active,
shouldShowNotificationOnGlasses: prefs.shouldShowNotificationOnGlasses,
notificationPopupDelayMs,
shell: {
isScreenOn: () => false,
wake: () => { wakes++; return true; },
openNotificationModal: () => popups++,
notificationRemoved: (key) => removed.push(key),
},
});
// Popup delays run when the test says so.
let timers = [];
const elapse = () => { const due = timers; timers = []; for (const timer of due) if (!timer.cancelled) timer.run(); };
const instance = new Harness();
instance.notificationPopups = new NotificationPopupDelay((key) => instance.popUpAndroidNotification(key), (run) => {
const timer = { run, cancelled: false };
timers.push(timer);
return () => { timer.cancelled = true; };
});
instance.requestShellRender = () => renders++;
instance.appendLog = () => {};
prefs.setNotificationSourceEnabled(mail, false);
instance.handleAndroidNotificationPosted('key');
instance.handleAndroidNotificationPosted('gone');
elapse();
assert.equal(wakes, 0);
assert.equal(popups, 0);
assert.equal(renders, 2);
prefs.setNotificationSourceEnabled(mail, true);
instance.handleAndroidNotificationPosted('key');
assert.equal(popups, 0, 'the popup waits out its delay');
elapse();
assert.equal(wakes, 1);
assert.equal(popups, 1);
// Withdrawn by its source during the delay: no wake, no popup, and the shell hears of it.
active = [{ ...mail, key: 'working', foregroundService: true }];
instance.handleAndroidNotificationPosted('working');
active = [];
instance.handleAndroidNotificationRemoved('working');
elapse();
assert.equal(wakes, 1);
assert.equal(popups, 1);
assert.deepEqual(removed, ['working']);
// The filter is checked again once the delay is over.
active = [{ ...mail, key: 'key' }];
instance.handleAndroidNotificationPosted('key');
prefs.setNotificationSourceEnabled(mail, false);
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);
});