From bf92a5a2cef8c1b7aea35be4ff2fbf0db9d8f7f0 Mon Sep 17 00:00:00 2001 From: James Babcock Date: Wed, 14 Oct 2026 02:03:51 -0700 Subject: [PATCH] Clear notification popups when they're dismissed on the phone, and avoid showing some notifications that are spurious --- ...aceclawMediaNotificationListenerService.kt | 32 +++++-- CHANGELOG | 2 + app/apps/glanceboard/widgets/system-card.ts | 4 +- app/apps/notifications/notifications-app.ts | 8 +- app/g2/dashboard-controller.ts | 61 ++++++++---- app/native/notification-icons.ios.ts | 4 + app/native/notification-icons.ts | 67 +++++++++---- app/native/notification-types.ts | 2 + app/ui/notifications.ts | 5 + app/ui/shell/notification-modal-queue.ts | 11 +++ app/ui/shell/notification-popup-delay.ts | 79 ++++++++++++++++ app/ui/shell/shell.ts | 48 +++++++--- .../callbacks/FaceclawNotificationListener.kt | 1 + tests/notification-filter.test.cjs | 56 +++++++++-- tests/notification-modal-queue.test.cjs | 18 ++++ tests/notification-popup-delay.test.cjs | 93 +++++++++++++++++++ tests/tsconfig.json | 1 + 17 files changed, 422 insertions(+), 70 deletions(-) create mode 100644 app/ui/shell/notification-popup-delay.ts create mode 100644 tests/notification-popup-delay.test.cjs diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaNotificationListenerService.kt b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaNotificationListenerService.kt index c0f6f229..5ca84df2 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaNotificationListenerService.kt +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaNotificationListenerService.kt @@ -267,13 +267,21 @@ class FaceclawMediaNotificationListenerService : NotificationListenerService() { } private fun emitNotificationPosted(key: String?) { + emitNotificationEvent(key) { listener, eventKey -> listener.onNotificationPosted(eventKey) } + } + + private fun emitNotificationRemoved(key: String?) { + emitNotificationEvent(key) { listener, eventKey -> listener.onNotificationRemoved(eventKey) } + } + + private fun emitNotificationEvent(key: String?, deliver: (FaceclawNotificationListener, String) -> Unit) { if (key == null || key.isEmpty() || notificationListeners.isEmpty()) { return } for (listener in notificationListeners) { mainHandler.post { try { - listener.onNotificationPosted(key) + deliver(listener, key) } catch (t: Throwable) { Log.w(TAG, "notification listener failed", t) } @@ -319,16 +327,17 @@ class FaceclawMediaNotificationListenerService : NotificationListenerService() { return !alreadyActive || !isPersistentNotification(statusBarNotification) } - private fun forgetActiveNotificationWakeKey(statusBarNotification: StatusBarNotification?) { + /** Stop tracking a notification; returns whether it was tracked (i.e. listed on the glasses). */ + private fun forgetActiveNotificationWakeKey(statusBarNotification: StatusBarNotification?): Boolean { if (statusBarNotification == null) { - return + return false } val key: String? = statusBarNotification.key if (key == null || key.isEmpty()) { - return + return false } synchronized(activeNotificationWakeKeys) { - activeNotificationWakeKeys.remove(key) + return activeNotificationWakeKeys.remove(key) } } @@ -531,6 +540,7 @@ class FaceclawMediaNotificationListenerService : NotificationListenerService() { out.put("appName", getNotificationAppName(service, statusBarNotification)) out.put("postTime", statusBarNotification.postTime) out.put("when", notification.`when`) + out.put("foregroundService", (notification.flags and Notification.FLAG_FOREGROUND_SERVICE) != 0) putString(out, "category", notification.category) if (extras != null) { putCharSequence(out, "title", firstNonEmpty( @@ -654,7 +664,10 @@ class FaceclawMediaNotificationListenerService : NotificationListenerService() { override fun onNotificationPosted(statusBarNotification: StatusBarNotification?) { super.onNotificationPosted(statusBarNotification) if (!shouldShowNotificationInList(this, statusBarNotification)) { - forgetActiveNotificationWakeKey(statusBarNotification) + // An update that takes a listed notification off the list removes it as far as the glasses go. + if (forgetActiveNotificationWakeKey(statusBarNotification)) { + emitNotificationRemoved(statusBarNotification!!.key) + } return } if (shouldEmitNotificationPosted(statusBarNotification!!)) { @@ -663,7 +676,12 @@ class FaceclawMediaNotificationListenerService : NotificationListenerService() { } override fun onNotificationRemoved(statusBarNotification: StatusBarNotification?) { - forgetActiveNotificationWakeKey(statusBarNotification) + // Includes notifications their source cancels on its own, e.g. a + // short-lived foreground-service notification that was standing in + // for one posted moments later under another key. + if (forgetActiveNotificationWakeKey(statusBarNotification)) { + emitNotificationRemoved(statusBarNotification!!.key) + } super.onNotificationRemoved(statusBarNotification) } } diff --git a/CHANGELOG b/CHANGELOG index 3685eff3..26616618 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -10,6 +10,8 @@ * Glanceboard compass shows calibration-accuracy indicator * Status-bar widgets (nightscout, weather, timer) are selectable * Roam app: Add a date-picker for navigating to a daily page +* Clear notification popups when they're dismissed on the phone, and avoid showing some notifications that are spurious +* Add depth effects to some modals that didn't have them ### Bug fixes diff --git a/app/apps/glanceboard/widgets/system-card.ts b/app/apps/glanceboard/widgets/system-card.ts index 1de9303a..e823cb5e 100644 --- a/app/apps/glanceboard/widgets/system-card.ts +++ b/app/apps/glanceboard/widgets/system-card.ts @@ -8,7 +8,7 @@ import { } from "../../../graphics/battery"; import { type GrayImage, type UiFont } from "../../../graphics/image"; import { ensureLocationPermission, hasLocationPermission } from "../../../native/location-permissions"; -import { onAndroidNotificationPosted, readActiveNotificationIcons } from "../../../native/notification-icons"; +import { onAndroidNotificationsChanged, readActiveNotificationIcons } from "../../../native/notification-icons"; import { readPhoneBatteryState } from "../../../native/phone-battery"; import { weatherBridge } from "../../../native/weather"; import { formatClockDate, formatClockTime } from "../../../ui/clock-format"; @@ -162,7 +162,7 @@ export class SystemCardWidget implements GlanceWidget { start(requestRender: () => void): void { this.requestRender = requestRender; this.scheduleMinuteTick(); - this.unsubscribeNotifications = onAndroidNotificationPosted(() => this.requestRender?.()); + this.unsubscribeNotifications = onAndroidNotificationsChanged(() => this.requestRender?.()); this.unsubscribeSettings = onAnySettingChanged(() => this.requestRender?.()); this.unsubscribeTimers = timerEngine.onChange(() => { this.syncSecondTick(); diff --git a/app/apps/notifications/notifications-app.ts b/app/apps/notifications/notifications-app.ts index a7f0bf75..65719b3f 100644 --- a/app/apps/notifications/notifications-app.ts +++ b/app/apps/notifications/notifications-app.ts @@ -1,6 +1,6 @@ import { NotificationsListLayer } from "../../ui/notifications"; import { NotificationFilterLayer } from "../../ui/notification-filter"; -import { onAndroidNotificationPosted } from "../../native/notification-icons"; +import { onAndroidNotificationsChanged } from "../../native/notification-icons"; import { createInProcessWindow, YieldAtRootLayer, @@ -18,7 +18,7 @@ export const NOTIFICATIONS_SURFACE_ID = "window:notifications"; */ export function createNotificationsAppWindow(options: InProcessAppOptions): InProcessWindow { // Newly posted notifications repaint the list while the window is open. - let offNotificationPosted: (() => void) | null = null; + let offNotificationsChanged: (() => void) | null = null; const created = createInProcessWindow({ appId: "notifications", windowId: NOTIFICATIONS_WINDOW_ID, @@ -39,10 +39,10 @@ export function createNotificationsAppWindow(options: InProcessAppOptions): InPr setSurfaceVisible: options.setSurfaceVisible, removeSurface: options.removeSurface, onClosed: () => { - offNotificationPosted?.(); + offNotificationsChanged?.(); options.onClosed(); }, }); - offNotificationPosted = onAndroidNotificationPosted(() => created.requestRender()); + offNotificationsChanged = onAndroidNotificationsChanged(() => created.requestRender()); return created; } diff --git a/app/g2/dashboard-controller.ts b/app/g2/dashboard-controller.ts index 49e0ac8d..5be7b828 100644 --- a/app/g2/dashboard-controller.ts +++ b/app/g2/dashboard-controller.ts @@ -15,7 +15,7 @@ import { startForegroundNotification, stopForegroundNotification, updateForegrou import { mediaControllerBridge } from "../native/media-controller"; import { nightscoutBridge } from "../native/nightscout-bridge"; import { weatherBridge } from "../native/weather"; -import { ALL_NOTIFICATIONS, onAndroidNotificationPosted, readActiveNotifications } from "../native/notification-icons"; +import { ALL_NOTIFICATIONS, onAndroidNotificationPosted, onAndroidNotificationRemoved, readActiveNotifications } from "../native/notification-icons"; import { shouldShowNotificationOnGlasses } from "../native/notification-sources"; import { openEvenAppSettings, readEvenAppNotificationState } from "../native/even-app-conflict"; import { grayImageToPreviewSource } from "../native/gray-image-preview"; @@ -57,6 +57,7 @@ import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../graphi import { prepareFrameDraws } from "../graphics/glyph-wire"; import { createLockScreenImage, LOCK_SCREEN_SURFACE_ID } from "./lock-screen"; import { rawInputEventToInputEvent, shell, type ShellInputOutcome } from "../ui/shell/shell"; +import { NotificationPopupDelay, notificationPopupDelayMs } from "../ui/shell/notification-popup-delay"; import { type InputEvent } from "../ui/gestures"; import { registerSystemTools } from "../assistant/system-tools"; import { updateGlassesPresence } from "./glasses-presence"; @@ -338,6 +339,9 @@ class DashboardController { private offFirmwareInfo: (() => void) | null = null; private offVoiceStatus: (() => void) | null = null; 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 lastInput = "waiting..."; private lastSys = "none yet"; private shellRenderInProgress = false; @@ -441,11 +445,8 @@ class DashboardController { app.boot?.(this.buildAppContext(app)); } timerEngine.onChange(() => this.refreshAlarmReliabilityWarning()); - this.offAndroidNotification = onAndroidNotificationPosted((notificationKey) => { - void this.handleAndroidNotificationPosted(notificationKey).catch((error) => { - this.appendLog(`notification wake failed: ${this.formatError(error)}`); - }); - }); + this.offAndroidNotification = onAndroidNotificationPosted((notificationKey) => this.handleAndroidNotificationPosted(notificationKey)); + this.offAndroidNotificationRemoved = onAndroidNotificationRemoved((notificationKey) => this.handleAndroidNotificationRemoved(notificationKey)); readActiveNotifications(ALL_NOTIFICATIONS); // Settings toggled from the glasses can change what the phone UI shows // (e.g. the text-setting editor), so re-emit the snapshot on any change. @@ -2758,23 +2759,47 @@ class DashboardController { this.schedulePreviewUpdate(); } - private async handleAndroidNotificationPosted(notificationKey: string): Promise { + private handleAndroidNotificationPosted(notificationKey: string): 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 || !shouldShowNotificationOnGlasses(notification.packageName)) { - this.requestShellRender(); - return; + if (notification && shouldShowNotificationOnGlasses(notification.packageName)) { + this.notificationPopups.post(notificationKey, notificationPopupDelayMs(notification)); } - // 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. - const wokeScreen = shell.isScreenOn() ? false : shell.wake("sidebar"); - if (wokeScreen) { - this.appendLog("android notification woke the screen"); - } - shell.openNotificationModal(notificationKey, wokeScreen); this.requestShellRender(); } + private handleAndroidNotificationRemoved(notificationKey: string): void { + if (this.notificationPopups.withdraw(notificationKey)) { + this.appendLog(`android notification ${notificationKey} withdrawn before its popup`); + } + try { + shell.notificationRemoved(notificationKey); + } catch (error) { + this.appendLog(`closing a removed notification's popup failed: ${this.formatError(error)}`); + } + this.requestShellRender(); + } + + /** A posted notification waited out its popup delay: show it, if it is still there. */ + private popUpAndroidNotification(notificationKey: string): void { + try { + const notification = readActiveNotifications(ALL_NOTIFICATIONS).find((item) => item.key === notificationKey); + if (!notification || !shouldShowNotificationOnGlasses(notification.packageName)) 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. + const wokeScreen = shell.isScreenOn() ? false : shell.wake("sidebar"); + if (wokeScreen) { + this.appendLog("android notification woke the screen"); + } + shell.openNotificationModal(notificationKey, wokeScreen); + this.requestShellRender(); + } catch (error) { + this.appendLog(`notification popup failed: ${this.formatError(error)}`); + } + } + private async playBuzzerSequence(payload: Uint8Array): Promise { if (this.phase !== "connected" || !this.communicator) { return; diff --git a/app/native/notification-icons.ios.ts b/app/native/notification-icons.ios.ts index 4b327118..31cec178 100644 --- a/app/native/notification-icons.ios.ts +++ b/app/native/notification-icons.ios.ts @@ -28,6 +28,10 @@ export function dismissNotification(key: string): boolean { return active?.dismi export function onAndroidNotificationPosted(listener: (key: string) => void): () => void { listeners.add(listener); return () => { listeners.delete(listener) } } +// ANCS removals carry no key and already reach the posted listeners above +// (they hear every change), and an open popup closes on the repaint that follows. +export function onAndroidNotificationRemoved(_listener: (key: string) => void): () => void { return () => {} } +export function onAndroidNotificationsChanged(listener: () => void): () => void { return onAndroidNotificationPosted(listener) } // ANCS does not provide app icons, so show one for the notification's ANCS // category; never fetch notification sources or content from a third-party // icon service. Indexed by CategoryID: Other, IncomingCall, MissedCall, diff --git a/app/native/notification-icons.ts b/app/native/notification-icons.ts index 242e12e8..c0ded10b 100644 --- a/app/native/notification-icons.ts +++ b/app/native/notification-icons.ts @@ -10,7 +10,7 @@ const ICON_SIZE = 24; /** Ask the native listener for every active source, including those below the list's display limit. */ export const ALL_NOTIFICATIONS = 0x7fffffff; // Backstop TTL only: the icon caches are invalidated eagerly whenever a -// notification is posted or dismissed (see invalidateIconCaches callers), so +// notification is posted or removed (see invalidateIconCaches callers), so // the tray is kept fresh by invalidation, not by expiry. A short TTL just // forced a blocking main-thread re-fetch (~40-100ms of Java icon // rasterization) every few seconds — usually producing a no-change frame that @@ -24,6 +24,7 @@ const keyedIconCache = new Map const KEYED_ICON_CACHE_MAX = 128; let notificationListenerProxy: any = null; const notificationPostedListeners = new Set<(notificationKey: string) => void>(); +const notificationRemovedListeners = new Set<(notificationKey: string) => void>(); function invalidateIconCaches(): void { cachedAtMs = 0; @@ -190,12 +191,38 @@ export function dismissNotification(notificationKey: string): boolean { } export function onAndroidNotificationPosted(listener: (notificationKey: string) => void): () => void { - notificationPostedListeners.add(listener); - ensureNotificationPostedListener(); + return addNotificationListener(notificationPostedListeners, listener); +} + +/** + * A listed notification went away: cancelled by its source (including one + * withdrawn moments after it was posted), dismissed on the phone or from the + * glasses, or updated into one the glasses don't list. + */ +export function onAndroidNotificationRemoved(listener: (notificationKey: string) => void): () => void { + return addNotificationListener(notificationRemovedListeners, listener); +} + +/** Any change to the listed notifications (a post or a removal), for views that just repaint. */ +export function onAndroidNotificationsChanged(listener: () => void): () => void { + const offPosted = onAndroidNotificationPosted(listener); + const offRemoved = onAndroidNotificationRemoved(listener); return () => { - notificationPostedListeners.delete(listener); - if (notificationPostedListeners.size === 0) { - removeNotificationPostedListener(); + offPosted(); + offRemoved(); + }; +} + +function addNotificationListener( + listeners: Set<(notificationKey: string) => void>, + listener: (notificationKey: string) => void, +): () => void { + listeners.add(listener); + ensureNativeNotificationListener(); + return () => { + listeners.delete(listener); + if (notificationPostedListeners.size === 0 && notificationRemovedListeners.size === 0) { + removeNativeNotificationListener(); } }; } @@ -222,21 +249,18 @@ function normalizeNotification(value: any): AndroidNotification | null { postTime: Number(value.postTime) || 0, when: Number(value.when) || 0, actions, + foregroundService: Boolean(value.foregroundService), }; } -function ensureNotificationPostedListener(): void { +function ensureNativeNotificationListener(): void { if (!global.isAndroid || notificationListenerProxy) return; notificationListenerProxy = new com.faceclaw.app.FaceclawNotificationListener({ onNotificationPosted: (notificationKey: string) => { - invalidateIconCaches(); - const key = String(notificationKey); - const listeners = Array.from(notificationPostedListeners); - setTimeout(() => { - for (const listener of listeners) { - listener(key); - } - }, 0); + dispatchNotificationEvent(notificationPostedListeners, notificationKey); + }, + onNotificationRemoved: (notificationKey: string) => { + dispatchNotificationEvent(notificationRemovedListeners, notificationKey); }, }); com.faceclaw.app.FaceclawMediaNotificationListenerService.addNotificationListener( @@ -244,7 +268,18 @@ function ensureNotificationPostedListener(): void { ); } -function removeNotificationPostedListener(): void { +function dispatchNotificationEvent(listeners: Set<(notificationKey: string) => void>, notificationKey: string): void { + invalidateIconCaches(); + const key = String(notificationKey); + const snapshot = Array.from(listeners); + setTimeout(() => { + for (const listener of snapshot) { + listener(key); + } + }, 0); +} + +function removeNativeNotificationListener(): void { if (!global.isAndroid || !notificationListenerProxy) return; com.faceclaw.app.FaceclawMediaNotificationListenerService.removeNotificationListener( notificationListenerProxy, diff --git a/app/native/notification-types.ts b/app/native/notification-types.ts index b7a6581f..a8cd93f7 100644 --- a/app/native/notification-types.ts +++ b/app/native/notification-types.ts @@ -5,6 +5,8 @@ export type AndroidNotification = { bigText: string; subText: string; infoText: string; summaryText: string; category: string; lines: string[]; postTime: number; when: number; actions: AndroidNotificationAction[]; dismissLabel?: string; + /** Posted by a foreground service (Android): a "this app is working" status notification. */ + foregroundService?: boolean; /** Full message size reported by iOS, even when the fetched text is bounded. */ messageSize?: number; }; diff --git a/app/ui/notifications.ts b/app/ui/notifications.ts index 3a3da2ba..c2c3c57d 100644 --- a/app/ui/notifications.ts +++ b/app/ui/notifications.ts @@ -216,6 +216,11 @@ export class SingleNotificationLayer implements Layer { private readonly options: SingleNotificationLayerOptions, ) {} + /** Whether the layer stays up once its notification is gone: the disable-source confirmation dismisses it first. */ + outlivesNotification(): boolean { + return this.confirmation !== null; + } + paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage { if (this.confirmation) return this.paintConfirmation(ctx); const font = getDefaultSmallFont(); diff --git a/app/ui/shell/notification-modal-queue.ts b/app/ui/shell/notification-modal-queue.ts index bf6f8eff..6a9081e9 100644 --- a/app/ui/shell/notification-modal-queue.ts +++ b/app/ui/shell/notification-modal-queue.ts @@ -74,6 +74,17 @@ export class NotificationModalQueue { this.openNext(current.wokeScreen); } + /** + * The notification went away on the phone (its source cancelled it, or it + * was dismissed there). Drops it from the queue, and returns the open modal + * if that is the one showing it, for the host to close (via closed()). + */ + withdrawn(notificationKey: string): M | null { + const index = this.queued.findIndex((entry) => entry.notificationKey === notificationKey); + if (index >= 0) this.queued.splice(index, 1); + return this.current?.notificationKey === notificationKey ? this.current.modal : null; + } + /** Notifications waiting behind the open modal (for diagnostics and tests). */ queuedKeys(): string[] { return this.queued.map((entry) => entry.notificationKey); diff --git a/app/ui/shell/notification-popup-delay.ts b/app/ui/shell/notification-popup-delay.ts new file mode 100644 index 00000000..7bf16d45 --- /dev/null +++ b/app/ui/shell/notification-popup-delay.ts @@ -0,0 +1,79 @@ +/** + * Holds each newly posted notification back briefly before it pops up on the + * glasses, so one that its source withdraws right away never shows (nor wakes + * the screen). Google Messages, for one, posts a "Messages is working in the + * background" foreground-service notification whenever it handles an incoming + * message or a background sync, then cancels it a second or two later, after + * posting the message's own notification under a different key (if any). + */ + +/** Delay for ordinary notifications: enough to skip one withdrawn or replaced as soon as it is posted. */ +export const NOTIFICATION_POPUP_DELAY_MS = 500; +/** + * Delay for foreground-service notifications. They are "app is working" + * status, often gone within seconds; Android itself defers showing them for + * 10s for the same reason. Messages' lasts up to ~2s (Pixel usage-stats timings). + */ +export const FOREGROUND_SERVICE_POPUP_DELAY_MS = 5000; + +/** Categories that must pop up promptly even from a foreground service (an incoming call, a ringing alarm). */ +const URGENT_CATEGORIES = new Set(["call", "alarm"]); + +export function notificationPopupDelayMs(notification: { foregroundService?: boolean; category: string }): number { + return notification.foregroundService && !URGENT_CATEGORIES.has(notification.category) + ? FOREGROUND_SERVICE_POPUP_DELAY_MS : NOTIFICATION_POPUP_DELAY_MS; +} + +/** Runs `run` after `delayMs`; returns a function that cancels it. */ +export type ScheduleFn = (run: () => void, delayMs: number) => () => void; + +const scheduleTimeout: ScheduleFn = (run, delayMs) => { + const timer = setTimeout(run, delayMs); + return () => clearTimeout(timer); +}; + +export class NotificationPopupDelay { + private readonly pending = new Map void }>(); + + /** `ready` receives each notification that survived its delay, to re-check and pop up. */ + constructor( + private readonly ready: (notificationKey: string) => void, + private readonly schedule: ScheduleFn = scheduleTimeout, + private readonly now: () => number = Date.now, + ) {} + + /** + * A notification was posted, to pop up after `delayMs`. A repost while it + * waits can only bring the popup forward: a notification its source keeps + * updating is not held back indefinitely, and one rewritten from a + * foreground-service placeholder into a real message (same key) gets the + * shorter delay. + */ + post(notificationKey: string, delayMs: number): void { + const dueAtMs = this.now() + delayMs; + const existing = this.pending.get(notificationKey); + if (existing) { + if (existing.dueAtMs <= dueAtMs) return; + existing.cancel(); + } + const cancel = this.schedule(() => { + this.pending.delete(notificationKey); + this.ready(notificationKey); + }, delayMs); + this.pending.set(notificationKey, { dueAtMs, cancel }); + } + + /** The notification went away before popping up; returns whether it was waiting. */ + withdraw(notificationKey: string): boolean { + const existing = this.pending.get(notificationKey); + if (!existing) return false; + existing.cancel(); + this.pending.delete(notificationKey); + return true; + } + + /** Notifications waiting out their delay (for diagnostics and tests). */ + pendingKeys(): string[] { + return Array.from(this.pending.keys()); + } +} diff --git a/app/ui/shell/shell.ts b/app/ui/shell/shell.ts index 5285ce5b..001adcbb 100644 --- a/app/ui/shell/shell.ts +++ b/app/ui/shell/shell.ts @@ -239,6 +239,9 @@ export type TrayWidget = { openWindow: () => { window: ShellWindow; opened: boolean } | null; }; +/** A new-notification popup: the shell modal, and the notification view inside it. */ +type NotificationPopup = { modal: ShellModalLayer; content: SingleNotificationLayer }; + /** * The app switcher's selection while it is on a status bar item rather than * a window's icon (bottom switcher only; see Shell.moveSelection): a @@ -434,7 +437,7 @@ class Shell { private readonly trayIcons = new Map(); private activeVoiceLayer: VoiceInputLayer | null = null; private activeKeyboardLayer: KeyboardInputLayer | null = null; - private readonly notificationModals = new NotificationModalQueue({ + private readonly notificationModals = new NotificationModalQueue({ open: (notificationKey) => this.pushNotificationModal(notificationKey), isAvailable: (notificationKey) => { const notification = readActiveNotifications(ALL_NOTIFICATIONS).find((item) => item.key === notificationKey); @@ -853,25 +856,40 @@ class Shell { this.config.requestShellRender(); } - private pushNotificationModal(notificationKey: string): ShellModalLayer { - const modal: ShellModalLayer = new ShellModalLayer( - new SingleNotificationLayer(notificationKey, { - origin: "new-notification-modal", - onClose: () => this.closeNotificationModal(modal), - }), - this.config.actions, - () => this.notificationModals.removed(modal, this.screenOn), - ); - this.stack.push(modal); - return modal; + /** + * A notification went away on the phone: cancelled by its source (e.g. a + * placeholder replaced moments later by the real notification under another + * key), or dismissed. A popup queued for it is dropped, and one showing it + * closes so the next one opens, as if the user had closed it -- unless it + * is asking to confirm turning off its source, which outlives the + * notification it dismissed. + */ + notificationRemoved(notificationKey: string): void { + const popup = this.notificationModals.withdrawn(notificationKey); + if (popup && !popup.content.outlivesNotification()) { + this.closeNotificationModal(popup); + } } - private closeNotificationModal(modal: ShellModalLayer): void { + private pushNotificationModal(notificationKey: string): NotificationPopup { + const content = new SingleNotificationLayer(notificationKey, { + origin: "new-notification-modal", + onClose: () => this.closeNotificationModal(popup), + }); + const popup: NotificationPopup = { + content, + modal: new ShellModalLayer(content, this.config.actions, () => this.notificationModals.removed(popup, this.screenOn)), + }; + this.stack.push(popup.modal); + return popup; + } + + private closeNotificationModal(popup: NotificationPopup): void { // The queue first: it opens the next notification or puts the screen back // to sleep, and then ignores the removal below. remove() rather than a // pop, so a menu opened over the modal doesn't leave it stuck. - this.notificationModals.closed(modal); - this.stack.remove(modal); + this.notificationModals.closed(popup); + this.stack.remove(popup.modal); this.config.requestShellRender(); } diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/callbacks/FaceclawNotificationListener.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/callbacks/FaceclawNotificationListener.kt index 35cf0523..93b3d2bf 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/callbacks/FaceclawNotificationListener.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/callbacks/FaceclawNotificationListener.kt @@ -2,4 +2,5 @@ package com.faceclaw.app interface FaceclawNotificationListener { fun onNotificationPosted(key: String?): Unit + fun onNotificationRemoved(key: String?): Unit } diff --git a/tests/notification-filter.test.cjs b/tests/notification-filter.test.cjs index 2c266f19..dbfccce3 100644 --- a/tests/notification-filter.test.cjs +++ b/tests/notification-filter.test.cjs @@ -187,29 +187,69 @@ test('popup action wraps fully and stays visible with small and large fonts', as } }); -test('controller filters before waking or opening a popup, and still refreshes the tray', async () => { +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 handler = controller.members.find((node) => node.name?.getText(file) === 'handleAndroidNotificationPosted'); + 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 { Harness } = evaluate(`export class Harness { ${handler.getText(file)} }`, null, { + const removed = []; + const { Harness } = evaluate(`export class Harness { ${members.join('\n')} }`, null, { ALL_NOTIFICATIONS: 0x7fffffff, - readActiveNotifications: () => [{ ...mail, key: 'key' }], + readActiveNotifications: () => active, shouldShowNotificationOnGlasses: prefs.shouldShowNotificationOnGlasses, - shell: { isScreenOn: () => false, wake: () => { wakes++; return true; }, openNotificationModal: () => popups++ }, + 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); - await instance.handleAndroidNotificationPosted('key'); - await instance.handleAndroidNotificationPosted('gone'); + instance.handleAndroidNotificationPosted('key'); + instance.handleAndroidNotificationPosted('gone'); + elapse(); assert.equal(wakes, 0); assert.equal(popups, 0); assert.equal(renders, 2); + prefs.setNotificationSourceEnabled(mail, true); - await instance.handleAndroidNotificationPosted('key'); + 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); }); diff --git a/tests/notification-modal-queue.test.cjs b/tests/notification-modal-queue.test.cjs index 2edad5e3..d639dfe2 100644 --- a/tests/notification-modal-queue.test.cjs +++ b/tests/notification-modal-queue.test.cjs @@ -102,3 +102,21 @@ test("the removal reported after a close is ignored, as are stale modals", () => assert.deepEqual(host.opened.map((modal) => modal.notificationKey), ["a", "b"]); assert.deepEqual(queue.queuedKeys(), []); }); + +test("a withdrawn notification leaves the queue; the open one is handed back to close", () => { + const host = makeHost(); + const queue = new NotificationModalQueue(host); + queue.post("a", true); + queue.post("b", false); + queue.post("c", false); + assert.equal(queue.withdrawn("b"), null); + assert.deepEqual(queue.queuedKeys(), ["c"]); + assert.equal(queue.withdrawn("unknown"), null); + const open = queue.withdrawn("a"); + assert.equal(open, host.opened[0]); + // The host closes it, which moves on to the next as a user close would. + queue.closed(open); + assert.deepEqual(host.opened.map((modal) => modal.notificationKey), ["a", "c"]); + queue.closed(queue.withdrawn("c")); + assert.equal(host.sleeps, 1, "the screen the withdrawn notification woke sleeps again"); +}); diff --git a/tests/notification-popup-delay.test.cjs b/tests/notification-popup-delay.test.cjs new file mode 100644 index 00000000..3f9791ba --- /dev/null +++ b/tests/notification-popup-delay.test.cjs @@ -0,0 +1,93 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { + FOREGROUND_SERVICE_POPUP_DELAY_MS, + NOTIFICATION_POPUP_DELAY_MS, + NotificationPopupDelay, + notificationPopupDelayMs, +} = require("../.test-build/app/ui/shell/notification-popup-delay.js"); + +/** A manual clock: schedule() queues timers that advance() fires in due order. */ +function makeClock() { + const clock = { + nowMs: 0, + timers: [], + now: () => clock.nowMs, + schedule(run, delayMs) { + const timer = { dueAtMs: clock.nowMs + delayMs, run, cancelled: false }; + clock.timers.push(timer); + return () => { timer.cancelled = true; }; + }, + advance(ms) { + const until = clock.nowMs + ms; + for (;;) { + const due = clock.timers.filter((timer) => !timer.cancelled && timer.dueAtMs <= until) + .sort((a, b) => a.dueAtMs - b.dueAtMs)[0]; + if (!due) break; + clock.nowMs = due.dueAtMs; + due.cancelled = true; + due.run(); + } + clock.nowMs = until; + }, + }; + return clock; +} + +function makeDelay() { + const clock = makeClock(); + const ready = []; + const delay = new NotificationPopupDelay((key) => ready.push(key), clock.schedule, clock.now); + return { clock, ready, delay }; +} + +test("a notification pops up once its delay passes", () => { + const { clock, ready, delay } = makeDelay(); + delay.post("a", 500); + clock.advance(499); + assert.deepEqual(ready, []); + assert.deepEqual(delay.pendingKeys(), ["a"]); + clock.advance(1); + assert.deepEqual(ready, ["a"]); + assert.deepEqual(delay.pendingKeys(), []); +}); + +test("one withdrawn while waiting never pops up; the replacement still does", () => { + const { clock, ready, delay } = makeDelay(); + // Messages: a foreground-service placeholder, the message under another key, then the placeholder goes. + delay.post("working", 5000); + clock.advance(2000); + delay.post("message", 500); + assert.equal(delay.withdraw("working"), true); + clock.advance(10000); + assert.deepEqual(ready, ["message"]); + assert.equal(delay.withdraw("working"), false); + assert.equal(delay.withdraw("message"), false, "already popped up"); +}); + +test("reposts can bring a popup forward but never push it back", () => { + const { clock, ready, delay } = makeDelay(); + delay.post("a", 500); + clock.advance(400); + delay.post("a", 500); + clock.advance(100); + assert.deepEqual(ready, ["a"], "an update does not restart the delay"); + + // Rewritten from a foreground-service placeholder into the real notification, same key. + delay.post("b", 5000); + clock.advance(1000); + delay.post("b", 500); + clock.advance(500); + assert.deepEqual(ready, ["a", "b"]); + clock.advance(10000); + assert.deepEqual(ready, ["a", "b"], "the earlier timer was cancelled"); +}); + +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); + assert.equal(notificationPopupDelayMs({ category: "call", foregroundService: true }), NOTIFICATION_POPUP_DELAY_MS); + assert.equal(notificationPopupDelayMs({ category: "alarm", foregroundService: true }), NOTIFICATION_POPUP_DELAY_MS); + assert.ok(FOREGROUND_SERVICE_POPUP_DELAY_MS > NOTIFICATION_POPUP_DELAY_MS); +}); diff --git a/tests/tsconfig.json b/tests/tsconfig.json index 671426a9..82c8b27b 100644 --- a/tests/tsconfig.json +++ b/tests/tsconfig.json @@ -35,6 +35,7 @@ "../app/g2/glasses-display-state.ts", "../app/g2/glance-state.ts", "../app/ui/shell/notification-modal-queue.ts", + "../app/ui/shell/notification-popup-delay.ts", "../app/apps/glanceboard/layout.ts", "../app/apps/files/video-layout.ts", "../app/g2/pairing-candidates.ts",