Clear notification popups when they're dismissed on the phone, and avoid showing some notifications that are spurious

This commit is contained in:
James Babcock committed 2026-10-14 02:03:51 -07:00
1 parent 42c2d5cd55
commit 63e0d71e2f
16 files changed
+420 -70

No files matched your search

+2 -2
View File
@@ -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();
+4 -4
View File
@@ -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;
}
+43 -18
View File
@@ -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<void> {
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<void> {
if (this.phase !== "connected" || !this.communicator) {
return;
+4
View File
@@ -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,
+51 -16
View File
@@ -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<string, { icon: GrayImage | null; atMs: number }>
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,
+2
View File
@@ -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;
};
+5
View File
@@ -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();
+11
View File
@@ -74,6 +74,17 @@ export class NotificationModalQueue<M> {
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);
+79
View File
@@ -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<string, { dueAtMs: number; cancel: () => 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());
}
}
+33 -15
View File
@@ -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<string, { icon: GrayImage; widget?: TrayWidget }>();
private activeVoiceLayer: VoiceInputLayer | null = null;
private activeKeyboardLayer: KeyboardInputLayer | null = null;
private readonly notificationModals = new NotificationModalQueue<ShellModalLayer>({
private readonly notificationModals = new NotificationModalQueue<NotificationPopup>({
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();
}