Implement notifications on iOS

This commit is contained in:
James Babcock committed 2026-09-19 11:07:37 -07:00
1 parent 64bf600ef9
commit 67823f66ef
19 files changed
+540 -65

No files matched your search

@@ -7,6 +7,7 @@
- (void)initializeBluetooth;
- (void)scan:(BOOL)enabled;
- (void)connect:(NSString *)identifier requestId:(NSInteger)requestId;
- (void)connect:(NSString *)identifier requiresANCS:(BOOL)requiresANCS requestId:(NSInteger)requestId;
- (void)subscribe:(NSString *)identifier characteristic:(NSString *)uuid requestId:(NSInteger)requestId;
- (void)write:(NSString *)identifier characteristic:(NSString *)uuid data:(NSData *)data requestId:(NSInteger)requestId;
- (void)disconnect:(NSString *)identifier;
+8 -1
View File
@@ -77,6 +77,9 @@
@"connectable": advertisement[CBAdvertisementDataIsConnectable] ?: @YES}];
}
- (void)connect:(NSString *)identifier requestId:(NSInteger)requestId {
[self connect:identifier requiresANCS:NO requestId:requestId];
}
- (void)connect:(NSString *)identifier requiresANCS:(BOOL)requiresANCS requestId:(NSInteger)requestId {
if (self.central.state != CBManagerStatePoweredOn) { [self complete:@(requestId) error:@"Bluetooth is not ready" details:nil]; return; }
FCBPeripheral *peer = self.peers[identifier.uppercaseString];
if (!peer) {
@@ -89,7 +92,11 @@
[self complete:@(requestId) error:@"Peripheral is already connecting or connected" details:nil]; return;
}
[peer.characteristics removeAllObjects]; peer.connectRequest = @(requestId);
[self.central connectPeripheral:peer.peripheral options:nil];
[self.central connectPeripheral:peer.peripheral options:requiresANCS ? @{CBConnectPeripheralOptionRequiresANCS: @YES} : nil];
}
- (void)centralManager:(CBCentralManager *)central didUpdateANCSAuthorizationForPeripheral:(CBPeripheral *)peripheral {
[self emit:@{@"kind": @"ancs-authorization", @"identifier": peripheral.identifier.UUIDString,
@"authorized": @(peripheral.ancsAuthorized)}];
}
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
[peripheral discoverServices:nil];
-1
View File
@@ -1,7 +1,6 @@
/** Native services still outside the current iOS app-screen milestone. */
const unavailable: Record<string, string> = {
music: 'Media-player integration is not available on iOS yet.',
notifications: 'Phone notification integration is not available on iOS yet.',
transcribe: 'Voice capture and transcription are not available on iOS yet.',
microphones: 'Glasses microphone capture is not available on iOS yet.',
calendar: 'Calendar access is not available on iOS yet.',
+237
View File
@@ -0,0 +1,237 @@
import type { AndroidNotification } from '../native/notification-types'
export const ANCS_FIRMWARE_VERSION = 16
export const ANCS_CONNECT_MESSAGE = 'Connect glasses to receive iPhone notifications.'
const MAX_ACTIVE = 128
const MAX_RESPONSE = 2048
const HEADER = 11
const read32 = (b: Uint8Array, i: number) => (b[i] | b[i+1]<<8 | b[i+2]<<16 | b[i+3]<<24) >>> 0
const le32 = (n: number) => [n & 255, n>>>8 & 255, n>>>16 & 255, n>>>24]
// NativeScript does not supply TextDecoder in every isolate.
function utf8(bytes: Uint8Array): string {
let result = ''
for (let i=0; i<bytes.length;) {
const first = bytes[i]
if (first < 128) { result += String.fromCharCode(first); i++; continue }
const count = first >= 0xc2 && first <= 0xdf ? 2 : first >= 0xe0 && first <= 0xef ? 3 : first >= 0xf0 && first <= 0xf4 ? 4 : 0
if (!count) { result += '\uFFFD'; i++; continue }
let code = first & (0x7f >> count), valid = i+count <= bytes.length
for (let j=1; j<count && valid; j++) {
if ((bytes[i+j] & 0xc0) !== 0x80) valid = false
else code = (code << 6) | (bytes[i+j] & 63)
}
if (!valid || code < (count === 2 ? 128 : count === 3 ? 2048 : 65536) ||
code > 0x10ffff || code >= 0xd800 && code <= 0xdfff) {
result += '\uFFFD'; i++; continue
}
result += String.fromCodePoint(code); i += count
}
return result
}
type Source = { flags: number; category: number; revision: number; postTime: number; popup: boolean }
type Request = { uid: number; revision: number; action?: number; labels?: boolean }
export type AncsState = 'disconnected' | 'starting' | 'ready' | 'unavailable'
/** Owns one phone/lens BLE session. Nothing is persisted. Firmware enforces
* peer ownership; token/sequence checks here additionally reject stale chunks. */
export class AncsClient {
state: AncsState = 'disconnected'
statusMessage = ANCS_CONNECT_MESSAGE
private resetReceived = false
private token = 0
private lastStartToken = 0
private sequence = 0
private packetKind = -1
private fragments: number[] = []
private response: number[] = []
private sources = new Map<number, Source>()
private notifications = new Map<number, AndroidNotification>()
private queue: Request[] = []
private acknowledged = false
private responseDone = false
private pending: Request | null = null
private timer: ReturnType<typeof setTimeout> | null = null
private retry: ReturnType<typeof setTimeout> | null = null
private revision = 0
private disposed = true
constructor(private readonly send: (packet: Uint8Array) => Promise<void>,
private readonly changed: (key?: string, popup?: boolean) => void,
private readonly log: (message: string) => void = () => {}) {}
private status(state: AncsState, message: string): void {
this.state = state; this.statusMessage = message; this.log(message); this.changed()
}
start(token: number): void {
this.stop(); this.disposed = false; this.token = token >>> 0 || 1
this.begin()
}
private begin(): void {
if (this.disposed) return
this.clear(); this.resetReceived = false
this.status('starting', 'Connecting to iPhone notifications…')
this.deadline()
const token = this.token
this.lastStartToken = token
void this.send(this.command(0)).catch(() => { if (token === this.token) this.recover() })
}
stop(message = ANCS_CONNECT_MESSAGE): void {
this.disposed = true
if (this.retry !== null) clearTimeout(this.retry)
this.retry = null; this.clear(); this.token = 0
this.status('disconnected', message)
}
stopCommand(): Uint8Array { return new Uint8Array([65,78,1,1,...le32(this.lastStartToken)]) }
private clear(): void {
if (this.timer !== null) clearTimeout(this.timer)
this.timer = null; this.sources.clear(); this.notifications.clear(); this.queue = []
this.pending = null; this.response = []; this.fragments = []; this.packetKind = -1; this.sequence = 0
}
private recover(message = 'Notification relay interrupted. Retrying…'): void {
if (this.disposed || this.retry !== null) return
this.clear(); this.status('unavailable', message)
// New token rejects every queued packet/response from the previous attempt.
this.token = (this.token + 1) >>> 0 || 1
this.retry = setTimeout(() => { this.retry = null; this.begin() }, 5000)
}
private deadline(): void {
if (this.timer !== null) clearTimeout(this.timer)
this.timer = setTimeout(() => this.recover(this.state === 'starting'
? this.resetReceived ? 'Glasses did not finish subscribing to iPhone notifications. Retrying…'
: 'No notification relay response. Check Share System Notifications on the right lens. Retrying…'
: 'Notification retrieval timed out. Retrying…'), 10000)
}
private command(op: number, payload: number[] = []): Uint8Array {
return new Uint8Array([65,78,1,op,...le32(this.token),...payload])
}
read(limit = 50): AndroidNotification[] {
return [...this.notifications.values()].sort((a,b) => b.postTime-a.postTime).slice(0, Math.max(0,limit))
.map(n => ({...n, lines: [...n.lines], actions: n.actions.map(a => ({...a}))}))
}
action(key: string, action: number): boolean {
const notification = [...this.notifications.entries()].find(([,n]) => n.key === key)
if (this.state !== 'ready' || this.queue.length >= MAX_ACTIVE || !notification || ![0,1].includes(action) ||
!notification[1].actions.some(a => a.index === action && a.enabled)) return false
const [uid] = notification, source = this.sources.get(uid)!
this.queue.push({uid, revision: source.revision, action}); this.pump(); return true
}
/** Local hide: ANCS negative action can decline a call, so Dismiss must never
* silently translate into a destructive negative action. */
dismiss(key: string): boolean {
const entry = [...this.notifications.entries()].find(([,n]) => n.key === key)
if (!entry) return false
this.notifications.delete(entry[0]); this.sources.delete(entry[0]); this.changed(); return true
}
receive(packet: Uint8Array): boolean {
if (packet[0] !== 65 || packet[1] !== 78) return false
if (this.disposed || this.state === 'unavailable' || packet.length < HEADER || packet[2] !== 1 || read32(packet,4) !== this.token) return true
const sequence = packet[8] | packet[9]<<8, flags = packet[10], kind = packet[3]
if (sequence !== this.sequence || flags > 3 || kind > 3 || packet.length > 244) { this.recover(); return true }
this.sequence = (sequence + 1) & 65535
if (flags & 1) {
if (this.packetKind !== -1) { this.recover(); return true }
this.packetKind = kind; this.fragments = []
}
if (this.packetKind !== kind || this.fragments.length + packet.length - HEADER > 512) { this.recover(); return true }
this.fragments.push(...packet.subarray(HEADER))
if (flags & 2) {
const data = new Uint8Array(this.fragments); this.fragments = []; this.packetKind = -1
if (kind === 0) {
if (data.length !== 1 || data[0] > 2) { this.recover(); return true }
if (data[0] === 2) { this.recover('Glasses reported a notification relay error. Retrying…'); return true }
if (data[0] === 0) { this.resetReceived = true; this.log('Glasses accepted notification relay START; awaiting subscription') }
if (data[0] === 1) {
if (this.timer !== null) clearTimeout(this.timer)
this.timer = null; this.status('ready', 'No current iOS notifications.'); this.pump()
}
} else if (kind === 1) this.source(data)
else if (kind === 2) this.attributes(data)
else if (this.pending) {
this.acknowledged = true
if (this.pending.action !== undefined || this.responseDone) this.complete()
}
}
return true
}
private source(data: Uint8Array): void {
if (data.length !== 8 || data[0] > 2) { this.recover(); return }
const uid = read32(data,4)
if (data[0] === 2) {
this.sources.delete(uid); this.notifications.delete(uid)
this.queue = this.queue.filter(r => r.uid !== uid); this.changed(); return
}
const old = this.sources.get(uid)
const source = {flags: data[1], category: data[2], revision: ++this.revision,
postTime: old?.postTime ?? Date.now(), popup: !old && data[0] === 0 && !(data[1] & 4)}
this.sources.set(uid, source)
while (this.sources.size > MAX_ACTIVE) {
const oldest = this.sources.keys().next().value!
this.sources.delete(oldest); this.notifications.delete(oldest)
this.queue = this.queue.filter(r => r.uid !== oldest)
}
this.queue = this.queue.filter(r => r.uid !== uid || r.action !== undefined)
this.queue.push({uid, revision: source.revision}); this.pump()
}
private pump(): void {
if (this.state !== 'ready' || this.pending) return
while (this.queue.length) {
const request = this.queue.shift()!
if (this.sources.get(request.uid)?.revision !== request.revision) continue
this.pending = request; this.response = []; this.acknowledged = this.responseDone = false; this.deadline()
// Exactly three attributes, fits even the minimum 20-byte ATT payload.
const cp = request.action === undefined
? request.labels ? [0,...le32(request.uid),6,7] : [0,...le32(request.uid),0,1,128,0,3,0,2]
: [2,...le32(request.uid),request.action]
const token = this.token
void this.send(this.command(2,cp)).catch(() => { if (token === this.token) this.recover() })
return
}
}
private attributes(data: Uint8Array): void {
if (!this.pending || this.pending.action !== undefined) return
if (this.response.length + data.length > MAX_RESPONSE) { this.recover(); return }
this.response.push(...data)
const b = new Uint8Array(this.response)
if (b.length < 5) return
if (b[0] !== 0 || read32(b,1) !== this.pending.uid) { this.recover(); return }
const expected = this.pending.labels ? [6,7] : [0,1,3]
let cursor = 5
const attrs = new Map<number,string>()
while (cursor < b.length) {
if (cursor+3 > b.length) return
const id = b[cursor], length = b[cursor+1] | b[cursor+2]<<8
if (!expected.includes(id) || attrs.has(id) || length > 512) { this.recover(); return }
if (cursor+3+length > b.length) return
attrs.set(id,utf8(b.subarray(cursor+3,cursor+3+length))); cursor += 3+length
}
if (attrs.size !== expected.length) return
const {uid,revision} = this.pending, source = this.sources.get(uid)
if (source?.revision === revision) {
const key = `ancs:${this.token}:${uid}`
if (this.pending.labels) {
const notification = this.notifications.get(uid)
if (notification) notification.actions = [
...(source.flags & 8 && attrs.get(6) ? [{index:0,title:attrs.get(6)!,enabled:true}] : []),
...(source.flags & 16 && attrs.get(7) ? [{index:1,title:attrs.get(7)!,enabled:true}] : []),
]
const popup = source.popup; source.popup = false
this.changed(key,popup)
} else {
const packageName = attrs.get(0)!, title = attrs.get(1)!, text = attrs.get(3)!
this.notifications.set(uid,{key,packageName,appName:packageName,title,text,bigText:text,
subText:'',infoText:'',summaryText:'',category:String(source.category),lines:[],postTime:source.postTime,when:source.postTime,actions:[],dismissLabel:'Hide on glasses'})
if (source.flags & 24) {
this.queue.unshift({uid,revision,labels:true}); this.changed(key,false)
} else {
const popup = source.popup; source.popup = false; this.changed(key,popup)
}
}
}
this.responseDone = true
if (this.acknowledged) this.complete()
}
private complete(): void {
if (this.timer !== null) clearTimeout(this.timer)
this.timer = null; this.pending = null; this.response = []; this.pump()
}
}
+59 -29
View File
@@ -19,30 +19,60 @@ export type FirmwarePatchSet = {
export const CFW_PATCH_SET: FirmwarePatchSet = {
"base": "g2_2.2.9.22.bin",
"baseSha256": "a03fbea9f68a9de6bc271daabb9f3a41c59053d1086622c76a4e990f829cc561",
"outputSha256": "2d72b37a6e3ac4e3e493bbc12d48566f2bf52eb62d2707c11c8da11aaaf0bb14",
"outputSha256": "b856094899d7da6e2e4446a2c11fb3f026cecfa9f8e1a4f05e61f607a63994ad",
"patches": [
{
"offset": 1422112,
"old": "15e0",
"new": "fae7",
"desc": "route ANCS write completions through relay event hook"
},
{
"offset": 1422106,
"old": "fff7cefa",
"new": "f0f246fb",
"desc": "cfw_ancs_event"
},
{
"offset": 1422134,
"old": "fef770ff",
"new": "f0f286f8",
"desc": "cfw_ancs_open"
},
{
"offset": 1422152,
"old": "fef76fff",
"new": "f0f29df8",
"desc": "cfw_ancs_close"
},
{
"offset": 1376122,
"old": "51334d00",
"new": "c1507c00",
"desc": "connection-bound ANCS EUS write callback"
},
{
"offset": 935280,
"old": "fff717f8",
"new": "64f395fb",
"new": "64f37dfd",
"desc": "bl cfw_message_bridge_received (ordered private bridge delivery before worker pool)"
},
{
"offset": 935628,
"old": "fef769ff",
"new": "64f3e7fa",
"new": "64f3cffc",
"desc": "bl cfw_message_bridge_received (ordered private bridge delivery before worker pool)"
},
{
"offset": 943818,
"old": "fcf76aff",
"new": "62f3e8fa",
"new": "62f3d0fc",
"desc": "bl cfw_message_bridge_received (ordered private bridge delivery before worker pool)"
},
{
"offset": 1415004,
"old": "fcf745f8",
"new": "eef23dfb",
"new": "eef2d5fc",
"desc": "bl cfw_receive_packet (private SID-f0 probe before TPL reassembly)"
},
{
@@ -72,145 +102,145 @@ export const CFW_PATCH_SET: FirmwarePatchSet = {
{
"offset": 1242342,
"old": "d4f790fb",
"new": "1af362fc",
"new": "1af380fe",
"desc": "bl settings_send_wrapper (append caps field 100)"
},
{
"offset": 1240038,
"old": "f5f710f9",
"new": "1af300fe",
"new": "1bf304f8",
"desc": "bl settings_decode_wrapper (Faceclaw lease field 101)"
},
{
"offset": 939336,
"old": "0bf02af9",
"new": "64f377f8",
"new": "64f37bfa",
"desc": "bl faceclaw_display_start @ 0x45f146 (fail-open wake takeover)"
},
{
"offset": 939528,
"old": "0bf0caf8",
"new": "64f3e5f8",
"new": "64f3e9fa",
"desc": "bl faceclaw_display_start_headup @ 0x45f206 (fail-open wake takeover)"
},
{
"offset": 939016,
"old": "10f096f8",
"new": "65f3bdfd",
"new": "66f311f8",
"desc": "bl headup_gate (head-up sensor event -> EvenHub sys event 12 under lease)"
},
{
"offset": 939036,
"old": "fff765fb",
"new": "64f303f8",
"new": "64f3ebf9",
"desc": "bl faceclaw_idle_input_gate (idle tap/long/release -> field-102 events 2/3/4)"
},
{
"offset": 831036,
"old": "1df057fc",
"new": "7ff399ff",
"new": "80f3edf9",
"desc": "bl gesture_press (Faceclaw lease gates event 9 vs stock UI event 8)"
},
{
"offset": 831042,
"old": "24f023f9",
"new": "80f33af8",
"new": "80f38efa",
"desc": "bl gesture_short_long (Faceclaw lease gates event 11 vs stock Menu path)"
},
{
"offset": 831800,
"old": "1df0d9fa",
"new": "7ff31ffe",
"new": "80f373f8",
"desc": "bl gesture_release (source-qualified event 10 vs stock UI event 0x4a)"
},
{
"offset": 1553752,
"old": "7fb50600",
"new": "cef217bc",
"new": "cef235be",
"desc": "even_ai_display_ctrl entry -> conditional Faceclaw lease trampoline"
},
{
"offset": 1047796,
"old": "f6f7edff",
"new": "45f32ffd",
"new": "45f377fe",
"desc": "bl display_copy_hook @ 0x4798f2 (640x480 direct framebuffer)"
},
{
"offset": 1048112,
"old": "f6f74fff",
"new": "45f391fc",
"new": "45f3d9fd",
"desc": "bl display_copy_hook @ 0x479a2e (640x480 direct framebuffer)"
},
{
"offset": 1255404,
"old": "d9f758ff",
"new": "16f31ffe",
"new": "17f307f8",
"desc": "bl faceclaw_send_wear_event @ 0x4ac3ea (outside onboarding)"
},
{
"offset": 1255504,
"old": "d9f726ff",
"new": "16f3edfd",
"new": "16f3d5ff",
"desc": "bl faceclaw_send_wear_event @ 0x4ac44e (outside onboarding)"
},
{
"offset": 1297700,
"old": "65f0affd",
"new": "0cf377f8",
"new": "0cf35ffa",
"desc": "bl compass_decode_capture (sample-matched GAF diagnostics)"
},
{
"offset": 1296176,
"old": "fff759fc",
"new": "0cf3edfb",
"new": "0cf3d5fd",
"desc": "bl compass_report_event (stock UI + heading with diagnostics over BLE)"
},
{
"offset": 1290360,
"old": "00210170",
"new": "0df3a7fe",
"new": "0ef38ff8",
"desc": "bl compass_preserve_accuracy (retain magnetic calibration under Faceclaw framebuffer lease)"
},
{
"offset": 4476518,
"old": "",
"new": "b0b581ea00039b0701d0034637e0c2b110f0030315d000f1010ca2f1010e0023cc5c9e45c45403f1010404d0634413f003032346f4d121440319121b102a14d302e00346102a10d3d1f800c0d1f804e0cc688d68103adc609d60c3f804e043f810cb0f2a01f11001eed8042a07d300bf51f8045b043a032a43f8045bf8d8002a08bfb0bd0139013b11f8015f013a03f8015ff9d1b0bd00bf884218bf002a00d1704710b50b1a38bf431a934207d288420ad281ea00039b0726d0034669e0fff79fffbde81040704781ea000300eb020c9b0701eb020e42d15fea8c732bd0a0f1010c00bf8b1813f801ec8418531e04f801ec04d0624412f003021a46f2d101eb030e00eb030c17e0830736d0a2f1010c00f1010e002300bfcc5c9c45c45403f1010404d0734413f003032346f4d1121b2144031922e01346042b0ed3aef10402acf1040152f80449043b032b41f80449f8d802f1040e01f1040c1a4653b1aef10101acf1010300bf11f80149013a03f80149f9d1bde8104070470346042a06d351f8044b043a032a43f8044bf8d8002af0d00139013b00bf11f8014f013a03f8014ff9d1e6e700bf2de9f04fa5b04ef66c6b4ff2a84416460d46ccf2ff0bc2f229044ff6ff7900274ff00108019006e048f2c731c0f24501bff32f8f8847d4f800a0bff35f8f20680321cff680710140b1f1005fbff35f8f03d10168594500f0bb804ff4377005f05ff8002800f0a1824ff62451cff6ff7142183d3182f8dc7282f8dd7282f8de7282f8df7282f8e07282f8e17282f8e27282f8e37282f8e47282f8e57282f8e67282f8e77282f8e87282f8e97282f8ea7282f8eb7282f8ec7282f8ed7282f8ee7282f8ef7282f8f07282f8f17282f8f27282f8f37282f8f47282f8f57282f8f67282f8f77282f8f87282f8f97282f8fa7282f8fb7282f8fc7282f8fd7282f8fe7282f8ff7282f8007382f8017382f8027382f8037382f8047382f8057382f8067382f8077382f8087382f8097382f80a7382f80b7382f80c7382f80d7382f80e7382f80f7382f8107382f8117382f8127382f8137382f8147382f8157382f8167382f8177382f8187382d1c0f800b080f80a80a0f81c90a0f81e90a0f82090a0f82290a0f82490a0f82690a0f82890a0f82a90a0f82c90a0f82e90a0f83090a0f83290a0f83490a0f83690a0f83890a0f83a9054e8001f51457ff436afbff35f8f44e8000121b154e8001f5145f8d02be7aa4645ea064100260127c0f8701206e048f2c731c0f24501bff32f8f88472568bff35f8f20680321cff680710140b1f1005fbff35f8f03d10168594500f0bc804ff4377004f084ff002800f0c6814ff62451cff6ff7100bf42183d3182f8dc6282f8dd6282f8de6282f8df6282f8e06282f8e16282f8e26282f8e36282f8e46282f8e56282f8e66282f8e76282f8e86282f8e96282f8ea6282f8eb6282f8ec6282f8ed6282f8ee6282f8ef6282f8f06282f8f16282f8f26282f8f36282f8f46282f8f56282f8f66282f8f76282f8f86282f8f96282f8fa6282f8fb6282f8fc6282f8fd6282f8fe6282f8ff6282f8006382f8016382f8026382f8036382f8046382f8056382f8066382f8076382f8086382f8096382f80a6382f80b6382f80c6382f80d6382f80e6382f80f6382f8106382f8116382f8126382f8136382f8146382f8156382f8166382f8176382f8186382d1c0f800b08772a0f81c90a0f81e90a0f82090a0f82290a0f82490a0f82690a0f82890a0f82a90a0f82c90a0f82e90a0f83090a0f83290a0f83490a0f83690a0f83890a0f83a9054e8001fa9427ff437afbff35f8f00bf44e8000121b154e8001fa942f8d02be7d0f8746242f6f767c0f24407002ebff35f8f00f0eb8007f19a0230464ff0ff314ff0ff379047002840f0418143f67750c0f24f00804700274ff001080397adf8107006e048f2c731c0f24501bff32f8f88472568bff35f8f20680321cff680710140b1f1005fbff35f8f03d10168594500f0e1804ff4377004f08efe002800f0d9804ff62451cff6ff7100bf42183d3182f8dc7282f8dd7282f8de7282f8df7282f8e07282f8e17282f8e27282f8e37282f8e47282f8e57282f8e67282f8e77282f8e87282f8e97282f8ea7282f8eb7282f8ec7282f8ed7282f8ee7282f8ef7282f8f07282f8f17282f8f27282f8f37282f8f47282f8f57282f8f67282f8f77282f8f87282f8f97282f8fa7282f8fb7282f8fc7282f8fd7282f8fe7282f8ff7282f8007382f8017382f8027382f8037382f8047382f8057382f8067382f8077382f8087382f8097382f80a7382f80b7382f80c7382f80d7382f80e7382f80f7382f8107382f8117382f8127382f8137382f8147382f8157382f8167382f8177382f8187382d1c0f800b080f80a80a0f81c90a0f81e90a0f82090a0f82290a0f82490a0f82690a0f82890a0f82a90a0f82c90a0f82e90a0f83090a0f83290a0f83490a0f83690a0f83890a0f83a9054e8001fa9427ff436afbff35f8f44e8000149b354e8001fa942f8d02be705460020b847b0b105f51d7151e8006f4eb9bff35f8f00bf41e8000292b151e8006f002ef8d00021bff32f8fbff35f8f21b10646f9e64ff0ff3742e007f5a9718847f2e60121f1e70020019d42f6f764002d4ff0010bc0f2440418bfbaf1000f33d10df108098046484602f07df903ab28465146012205f0d1fc9df8111007464846002918bf4ff0ff3702f0a3fabbf1000f044608d19df8100028b949f28340c0f247004c308047b8f1000f18bfc8f80c4042f6f764c0f2440404f5807130468847384625b0bde8f08f2a7802f07f01a1f1150313f1030f0bd802f07b030b2b07d002f07e02082a03d0032901d00629b7d140b149f28341c0f247010746884797f8641111b14ff0ff37d6e738464ff0000ba6e770b500284dd001684ef66c62ccf2ff02914218bf70bd90f8441090f8455046f6756c8d42c0f2510c2ad205eb8501014491f8492091f84a4091f846e091f8473091f8481042ea0424012c4ff0010298bf14466e1c054680f84560b9b164294eea032028bf6421012888bf024644f62060824228bf02460cf5e2731046984706e0002180f84410bde870406047e047286c38b142f64d42c0f244022146bde87040104770bd02464ff64b70cff6ff7042f6653c7844c0f2440c00210023604700bf2de9f04f9fb04ff2a840c2f229000668bff35f8f30466ff39600b0f1005f42d130684ef66c65ccf2ff05a8423bd196f8640130b3d6f860411cb340f6b400c2f20000076804a802f0a5f8002f00f06a8140f2030a384621464ff416320296cff6807a4ff6ff760397fff752fb4ff6245b48f2c738cff6ff7b00270124c0f245081ce096f8660170b1d6f8680140b146f68051c2f207010968401a002802f37080002086f8660140f6d100c0f247001fb0bde8f04f0047bff32f8fc0474ff2a840c2f22900d0f80090bff35f8f0Line truncated
"new": "b0b581ea00039b0701d0034637e0c2b110f0030315d000f1010ca2f1010e0023cc5c9e45c45403f1010404d0634413f003032346f4d121440319121b102a14d302e00346102a10d3d1f800c0d1f804e0cc688d68103adc609d60c3f804e043f810cb0f2a01f11001eed8042a07d300bf51f8045b043a032a43f8045bf8d8002a08bfb0bd0139013b11f8015f013a03f8015ff9d1b0bd00bf884218bf002a00d1704710b50b1a38bf431a934207d288420ad281ea00039b0726d0034669e0fff79fffbde81040704781ea000300eb020c9b0701eb020e42d15fea8c732bd0a0f1010c00bf8b1813f801ec8418531e04f801ec04d0624412f003021a46f2d101eb030e00eb030c17e0830736d0a2f1010c00f1010e002300bfcc5c9c45c45403f1010404d0734413f003032346f4d1121b2144031922e01346042b0ed3aef10402acf1040152f80449043b032b41f80449f8d802f1040e01f1040c1a4653b1aef10101acf1010300bf11f80149013a03f80149f9d1bde8104070470346042a06d351f8044b043a032a43f8044bf8d8002af0d00139013b00bf11f8014f013a03f8014ff9d1e6e700bf2de9f04fa5b04ef66c6b4ff2a84416460d46ccf2ff0bc2f229044ff6ff7900274ff00108019006e048f2c731c0f24501bff32f8f8847d4f800a0bff35f8f20680321cff680710140b1f1005fbff35f8f03d10168594500f0d7804ff4397005f07dfa002800f0f3824ff61c51cff6ff7142184a3182f8e47282f8e57282f8e67282f8e77282f8e87282f8e97282f8ea7282f8eb7282f8ec7282f8ed7282f8ee7282f8ef7282f8f07282f8f17282f8f27282f8f37282f8f47282f8f57282f8f67282f8f77282f8f87282f8f97282f8fa7282f8fb7282f8fc7282f8fd7282f8fe7282f8ff7282f8007382f8017382f8027382f8037382f8047382f8057382f8067382f8077382f8087382f8097382f80a7382f80b7382f80c7382f80d7382f80e7382f80f7382f8107382f8117382f8127382f8137382f8147382f8157382f8167382f8177382f8187382f8197382f81a7382f81b7382f81c7382f81d7382f81e7382f81f7382f8207382f8217382f8227382f8237382f8247382f8257382f8267382f8277382f8287382f8297382f82a7382f82b7382f82c7382f82d737ff468afc0f800b080f80a80a0f81c90a0f81e90a0f82090a0f82290a0f82490a0f82690a0f82890a0f82a90a0f82c90a0f82e90a0f83090a0f83290a0f83490a0f83690a0f83890a0f83a9054e8001f51457ff41bafbff35f8f00bf44e8000121b154e8001f5145f8d00fe7aa4645ea064100260127c0f8701206e048f2c731c0f24501bff32f8f88472568bff35f8f20680321cff680710140b1f1005fbff35f8f03d10168594500f0d6804ff4397005f086f9002800f0fc814ff61c51cff6ff7100bf42184a3182f8e46282f8e56282f8e66282f8e76282f8e86282f8e96282f8ea6282f8eb6282f8ec6282f8ed6282f8ee6282f8ef6282f8f06282f8f16282f8f26282f8f36282f8f46282f8f56282f8f66282f8f76282f8f86282f8f96282f8fa6282f8fb6282f8fc6282f8fd6282f8fe6282f8ff6282f8006382f8016382f8026382f8036382f8046382f8056382f8066382f8076382f8086382f8096382f80a6382f80b6382f80c6382f80d6382f80e6382f80f6382f8106382f8116382f8126382f8136382f8146382f8156382f8166382f8176382f8186382f8196382f81a6382f81b6382f81c6382f81d6382f81e6382f81f6382f8206382f8216382f8226382f8236382f8246382f8256382f8266382f8276382f8286382f8296382f82a6382f82b6382f82c6382f82d637ff468afc0f800b08772a0f81c90a0f81e90a0f82090a0f82290a0f82490a0f82690a0f82890a0f82a90a0f82c90a0f82e90a0f83090a0f83290a0f83490a0f83690a0f83890a0f83a9054e8001fa9427ff41cafbff35f8f44e8000121b154e8001fa942f8d011e7d0f8746242f6f767c0f24407002ebff35f8f00f0078107f19a0230464ff0ff314ff0ff379047002840f05d8143f67750c0f24f00804700274ff001080397adf8107006e048f2c731c0f24501bff32f8f88472568bff35f8f20680321cff680710140b1f1005fbff35f8f03d10168594500f0fd804ff4397005f076f8002800f0f5804ff61c51cff6ff7100bf42184a3182f8e47282f8e57282f8e67282f8e77282f8e87282f8e97282f8ea7282f8eb7282f8ec7282f8ed7282f8ee7282f8ef7282f8f07282f8f17282f8f27282f8f37282f8f47282f8f57282f8f67282f8f77282f8f87282f8f97282f8fa7282f8fb7282f8fc7282f8fd7282f8fe7282f8ff7282f8007382f8017382f8027382f8037382f8047382f8057382f8067382f8077382f8087382f8097382f80a7382f80b7382f80c7382f80d7382f80e7382f80f7382f8107382f8117382f8127382f8137382f8147382f8157382f8167382f8177382f8187382f8197382f81a7382f81b7382f81c7382f81d7382f81e7382f81f7382f8207382f8217382f8227382f8237382f8247382f8257382f8267382f8277382f8287382f8297382f82a7382f82b7382f82c7382f82d737ff468afc0f800b080f80a80a0f81c90a0f81e90a0f82090a0f82290a0f82490a0f82690a0f82890a0f82a90a0f82c90a0f82e90a0f83090a0f83290a0f83490a0f83690a0f83890a0f83a9054e8001fa9427ff41bafbff35f8f00bf44e8000149b354e8001fa942f8d00fe705460020b847b0b105f51d7151e8006f4eb9bff35f8f00bf41e8000292b151e8006f002ef8d00021bff32f8fbff35f8f21b10646dde64ff0ff3742e007f5a9718847d6e60121f1e70020019d42f6f764002d4ff0010bc0f2440418bfbaf1000f33d10df108098046484602f08ffa03ab28465146012206f097fa9df8111007464846002918bf4ff0ff3702f0cffbbbf1000f044608d19df8100028b949f28340c0f247004c308047b8f1000f18bfc8f80c4042f6f764c0f2440404f5807130468847384625b0bde8f08f2a7802f07f01a1f1150313f1030f0bd802f07b030b2b07d002f07e02082a03d0032901d00629b7d140b149f28341c0f247010746884797f8641111b14ff0ff37d6e738464ff0000ba6e72de9f04f81b04ef66c6b4ff2a8454ff61c5848f2c73accf2ff0bc2f229054ff6ff76cff6ff7800274ff00109c0f2450a03e000bfbff32f8fd0472c68bff35f8f2868bff35f8f01466ff39601b1f1005f03d10168594500f0c6804ff4397004f0e7fe002800f0be80414600bf42184a3182f8e47282f8e57282f8e67282f8e77282f8e87282f8e97282f8ea7282f8eb7282f8ec7282f8ed7282f8ee7282f8ef7282f8f07282f8f17282f8f27282f8f37282f8f47282f8f57282f8f67282f8f77282f8f87282f8f97282f8fa7282f8fb7282f8fc7282f8fd7282f8fe7282f8ff7282f8007382f801738Line truncated
"desc": "append injected blobs to main-app payload"
},
{
"offset": 779114,
"old": "846a3800",
"new": "c81b3900",
"new": "d8293900",
"desc": "main-app subheader payload size (ps)"
},
{
"offset": 152,
"old": "046b3800",
"new": "481c3900",
"new": "582a3900",
"desc": "main-app TOC entry size (ps + 128)"
},
{
"offset": 779234,
"old": "846a3804",
"new": "c81b3904",
"new": "d8293904",
"desc": "main-app preamble length (low 24 bits)"
},
{
"offset": 779238,
"old": "85c355a2",
"new": "5ba18044",
"new": "c485abc8",
"desc": "[5] ota/s200_firmware_ota.bin preamble crc32"
},
{
"offset": 156,
"old": "ed292ee4",
"new": "c88dcd16",
"new": "c48d32fe",
"desc": "[5] ota/s200_firmware_ota.bin component crc32c (TOC)"
},
{
"offset": 779118,
"old": "ed292ee4",
"new": "c88dcd16",
"new": "c48d32fe",
"desc": "[5] ota/s200_firmware_ota.bin component crc32c (subheader)"
}
]
+27 -4
View File
@@ -1,3 +1,4 @@
import { AncsClient, ANCS_FIRMWARE_VERSION } from './ancs-client'
import { type CompassEvent } from '../native/compass-types'
import * as protocol from './ble-protocol'
import { iosBleTraffic } from './ble-traffic-counters'
@@ -11,11 +12,11 @@ import { decodeWearState, enableWearDetection, queryWearState } from './wear-pro
declare function setTimeout(callback: () => void, ms: number): number
declare function clearTimeout(id: number): void
export type SessionAddresses = { left: string; right: string; ring: string }
export type TransportEvent = { kind: string; identifier?: string; characteristic?: string; data?: string; message?: string; state?: number }
export type TransportEvent = { kind: string; identifier?: string; characteristic?: string; data?: string; message?: string; state?: number; authorized?: boolean }
export interface SessionTransport {
onEvent(listener: (event: TransportEvent) => void): () => void
resolveDevices(addresses: SessionAddresses): Promise<Record<string, string>>
connect(identifier: string): Promise<{ characteristics: string[]; maxWrite: number }>
connect(identifier: string, requiresANCS?: boolean): Promise<{ characteristics: string[]; maxWrite: number }>
subscribe(identifier: string, characteristic: string): Promise<void>
write(identifier: string, characteristic: string, bytes: Uint8Array): Promise<void>
disconnect(identifier: string): void
@@ -37,6 +38,7 @@ type DisplayFrame = { packed: Uint8Array; commands: Uint8Array[]; offset: number
export class GlassesSession {
state: SessionState = { phase: 'disconnected', status: 'Preview only', battery: null, charging: null, ring: false,
frames: 0, capabilities: '', leftVersion: '', rightVersion: '' }
readonly notifications: AncsClient
private generation = 0
private ids: Record<string, string> = {}
private limits: Record<string, number> = {}
@@ -86,7 +88,9 @@ export class GlassesSession {
private readonly log: (message: string) => void = () => {},
private readonly onActivity: () => void = () => {},
private readonly onCompass: (event: CompassEvent) => void = () => {},
private readonly onWearState: (wearing: boolean) => void = () => {}) {
private readonly onWearState: (wearing: boolean) => void = () => {},
onNotificationsChanged: (key?: string, popup?: boolean) => void = () => {}) {
this.notifications = new AncsClient(packet => this.writePackets('right', () => [packet]), onNotificationsChanged, message => this.log('ANCS: ' + message))
this.off = transport.onEvent(event => this.receive(event))
}
private update(phase: SessionState['phase'], status: string): void {
@@ -107,7 +111,7 @@ export class GlassesSession {
this.ids = ids
for (const role of ['right', 'left']) {
this.update('connecting', `Connecting ${role} arm…`)
const details = await this.transport.connect(ids[role]); this.check(generation)
const details = await this.transport.connect(ids[role], role === 'right'); this.check(generation)
this.limits[role] = details.maxWrite
if (!details.characteristics.includes(protocol.G2_WRITE) || !details.characteristics.includes(protocol.G2_NOTIFY)) throw new Error(`${role} arm is missing G2 communication characteristics.`)
await this.transport.subscribe(ids[role], protocol.G2_NOTIFY); this.check(generation)
@@ -140,6 +144,9 @@ export class GlassesSession {
this.lastHeartbeat = this.lastLease = this.lastSettings = Date.now()
this.displayed = null; this.retryCount = 0
this.update('connected', 'Glasses connected')
if (/^Faceclaw\/(\d+)/.test(this.state.capabilities) && Number(this.state.capabilities.split('/')[1]) >= ANCS_FIRMWARE_VERSION)
this.notifications.start((Date.now() ^ Math.floor(Math.random()*0xffffffff)) >>> 0)
else this.notifications.stop(`Update glasses to Faceclaw firmware ${ANCS_FIRMWARE_VERSION} or newer for iPhone notifications.`)
await this.syncCompass(); this.check(generation)
this.schedule()
if (addresses.ring && ids.ring) await this.connectRing(generation)
@@ -313,6 +320,17 @@ export class GlassesSession {
}
private receive(event: TransportEvent): void {
if (!Object.values(this.ids).includes(event.identifier ?? '')) return
if (event.kind === 'ancs-authorization' && event.identifier === this.ids.right) {
if (event.authorized === false) {
const active = this.notifications.state !== 'disconnected'
const command = this.notifications.stopCommand()
this.notifications.stop('Enable Share System Notifications in iPhone Settings → Bluetooth → right lens.')
if (active && this.state.phase === 'connected') void this.writePackets('right', () => [command]).catch(() => {})
} else if (this.state.phase === 'connected' && /^Faceclaw\/(\d+)/.test(this.state.capabilities) && Number(this.state.capabilities.split('/')[1]) >= ANCS_FIRMWARE_VERSION) {
this.notifications.start((Date.now() ^ Math.floor(Math.random()*0xffffffff)) >>> 0)
}
return
}
if (event.kind === 'disconnected') {
if (event.identifier === this.ids.ring) {
this.state.ring = false
@@ -340,6 +358,7 @@ export class GlassesSession {
if (input) { this.log(`Direct R1 gesture ${input.eventType}`); this.onInput(input) }
return
}
if (event.identifier === this.ids.right && this.notifications.receive(data)) return
for (const message of this.receiver.receive(event.identifier!, data)) {
this.log(`RX ${event.identifier === this.ids.left ? 'L' : 'R'} sid=${message.sid.toString(16)} flag=${message.flag.toString(16)} cmd=${message.command} magic=${message.magic}`)
if (message.sid === protocol.SID.cfw) {
@@ -523,6 +542,7 @@ export class GlassesSession {
finally { if (generation === this.generation) { this.pumping = false; this.schedule(this.canSendDisplay() ? 0 : 1000) } }
}
private reset(): void {
this.notifications.stop()
++this.generation
this.compassSent = null; this.compassWork = Promise.resolve()
++this.microphoneToken; this.audioListener = null; this.microphoneEnabled = false
@@ -568,6 +588,9 @@ export class GlassesSession {
if (this.audioListener || this.microphoneEnabled) {
try { await this.setMicrophone(false) } catch (error) { this.log(`Microphone cleanup: ${this.message(error)}`) }
}
if (this.notifications.state !== 'disconnected') {
try { await this.writePackets('right', () => [this.notifications.stopCommand()]) } catch {}
}
const cleanup = this.layoutCreated && this.state.phase === 'connected'
this.update('disconnecting', 'Disconnecting…'); this.reset()
try {
+14 -1
View File
@@ -1,3 +1,6 @@
import { bindIosNotifications, iosNotificationsChanged, onIosNotificationPopup } from '../native/notification-icons.ios'
import { shouldShowNotificationOnGlasses } from '../native/notification-sources'
import { readActiveNotifications } from '../native/notification-icons.ios'
import { launcherEntries } from '../apps/launcher'
import { getInstalledEvenHubAppById, installedEvenHubPackageId, uninstallEvenHubPackage } from '../apps/evenhub/installed-apps'
import { isInstalledPackagePresent } from '../apps/evenhub/updates'
@@ -146,6 +149,13 @@ export class IosPreviewController {
shell.registerWindow(launcher)
shell.wake('window')
shell.focusWindow(launcher.windowId)
onIosNotificationPopup(key => {
const notification = readActiveNotifications(128).find(n => n.key === key)
if (this.glassesLocked || !notification || !shouldShowNotificationOnGlasses(notification.packageName)) return
const woke = !shell.isScreenOn() && shell.wake('sidebar')
shell.openNotificationModal(key, woke)
this.requestShellRender()
})
registerSystemTools()
registerWindowTools({ apps: ALL_APPS.filter(app => !iosAppUnavailableReason(app.appId)),
launchApp: id => this.launchApp(id), requestShellRender: () => this.requestShellRender() })
@@ -498,7 +508,10 @@ export class IosPreviewController {
}, message => this.logBluetooth(message), () => {
if (!UIApplication.sharedApplication.protectedDataAvailable) this.handlePhoneLockState(true)
this.refreshClock()
}, receiveCompassEvent, wearing => this.handleWearState(wearing))
}, receiveCompassEvent, wearing => this.handleWearState(wearing), (key, popup) => {
iosNotificationsChanged(key, popup); this.requestShellRender()
})
bindIosNotifications(this.session.notifications)
bindCompassSession(this.session)
}
await this.session.start(addresses)
+1 -1
View File
@@ -134,7 +134,7 @@ export class IosBluetooth {
try { call(id) } catch (error) { clearTimeout(timer); this.pending.delete(id); reject(error) }
})
}
connect(identifier: string): Promise<ConnectionDetails> { return this.operation(identifier, id => this.native.connectRequestId(identifier, id), 20_000) }
connect(identifier: string, requiresANCS = false): Promise<ConnectionDetails> { return this.operation(identifier, id => this.native.connectRequiresANCSRequestId(identifier, requiresANCS, id), 20_000) }
async subscribe(identifier: string, characteristic: string): Promise<void> {
// R1 exposes two notification channels; one may never complete its CCCD
// request. Keep the link alive so the other channel can still be tried.
+4
View File
@@ -0,0 +1,4 @@
import { iosNotificationState, iosNotificationMessage } from './notification-icons.ios'
export function isNotificationListenerEnabled(): boolean { return iosNotificationState() === 'ready' }
export function requestNotificationListenerAccess(): void { /* iOS exposes no deep link to this Bluetooth setting. */ }
export function notificationEmptyMessage(): string { return iosNotificationMessage() }
+5
View File
@@ -31,3 +31,8 @@ export function requestNotificationListenerAccess(): void {
if (!context) return;
com.faceclaw.app.FaceclawEvenAppDetector.openNotificationAccessSettings(context);
}
export function notificationEmptyMessage(): string {
return isNotificationListenerEnabled() ? "No current Android notifications."
: "Grant permission on your phone to view notifications on the glasses.";
}
+44
View File
@@ -0,0 +1,44 @@
import { GrayImage } from '../graphics/image'
import { AncsClient, ANCS_CONNECT_MESSAGE, type AncsState } from '../g2/ancs-client'
import { rememberNotificationSources } from './notification-sources'
export type { AndroidNotification, AndroidNotificationAction } from './notification-types'
export type { NotificationIconsResult, NotificationIconResult } from './notification-icons'
export const ALL_NOTIFICATIONS = 0x7fffffff
let active: AncsClient | null = null
const listeners = new Set<(key: string) => void>()
const popups = new Set<(key: string) => void>()
export function bindIosNotifications(client: AncsClient): void { active = client }
export function iosNotificationsChanged(key?: string, popup = false): void {
const current = active
if (current) rememberNotificationSources(current.read(ALL_NOTIFICATIONS))
for (const listener of listeners) listener(key ?? '')
if (popup && key) for (const listener of popups) listener(key)
}
export function onIosNotificationPopup(listener: (key: string) => void): () => void {
popups.add(listener); return () => { popups.delete(listener) }
}
export function iosNotificationMessage(): string { return active?.statusMessage ?? ANCS_CONNECT_MESSAGE }
export function iosNotificationState(): AncsState { return active?.state ?? 'disconnected' }
export function readActiveNotifications(maxNotifications = 50) { return active?.read(maxNotifications) ?? [] }
export function invokeNotificationAction(key: string, index: number): boolean { return active?.action(key,index) ?? false }
export function dismissNotification(key: string): boolean { return active?.dismiss(key) ?? false }
export function onAndroidNotificationPosted(listener: (key: string) => void): () => void {
listeners.add(listener); return () => { listeners.delete(listener) }
}
// ANCS does not provide app icons. Use a local bell; never fetch notification
// sources or content from a third-party icon service.
function bell(): GrayImage {
const image = new GrayImage(24,24,0)
image.fillRoundedRect(6,5,12,13,220,5)
image.fillRect(4,17,16,2,220)
image.fillRect(10,20,4,2,220)
return image
}
export function readActiveNotificationIcons(maxIcons: number, _allowStale: boolean) {
const sources = new Set(readActiveNotifications(ALL_NOTIFICATIONS).map(n => n.packageName))
return {icons: Array.from(sources).slice(0,Math.max(0,maxIcons)).map(() => bell()),stale:false}
}
export function readNotificationIconByKey(key: string, _allowStale: boolean) {
return {icon: readActiveNotifications(ALL_NOTIFICATIONS).some(n => n.key === key) ? bell() : null,stale:false}
}
+2 -22
View File
@@ -28,28 +28,8 @@ function invalidateIconCaches(): void {
keyedIconCache.clear();
}
export type AndroidNotificationAction = {
index: number;
title: string;
enabled: boolean;
};
export type AndroidNotification = {
key: string;
packageName: string;
appName: string;
title: string;
text: string;
bigText: string;
subText: string;
infoText: string;
summaryText: string;
category: string;
lines: string[];
postTime: number;
when: number;
actions: AndroidNotificationAction[];
};
import type { AndroidNotification, AndroidNotificationAction } from "./notification-types";
export type { AndroidNotification, AndroidNotificationAction } from "./notification-types";
export type NotificationIconsResult = {
icons: GrayImage[];
+8
View File
@@ -0,0 +1,8 @@
/** Shared notification model; Android names are retained for existing callers. */
export type AndroidNotificationAction = { index: number; title: string; enabled: boolean };
export type AndroidNotification = {
key: string; packageName: string; appName: string; title: string; text: string;
bigText: string; subText: string; infoText: string; summaryText: string;
category: string; lines: string[]; postTime: number; when: number;
actions: AndroidNotificationAction[]; dismissLabel?: string;
};
+3 -5
View File
@@ -15,7 +15,7 @@ import {
type AndroidNotificationAction,
} from "../native/notification-icons";
import { setNotificationSourceEnabled } from "../native/notification-sources";
import { isNotificationListenerEnabled } from "../native/notification-access";
import { notificationEmptyMessage } from "../native/notification-access";
import { noteStaleDataUsed, renderPassAllowsStaleData } from "../util/render-freshness";
import { type InputEvent } from "./gestures";
import { type Layer, type LayerContext, type PaintBelow } from "./layers";
@@ -88,9 +88,7 @@ export class NotificationsListLayer implements Layer {
if (!notifications.length) {
image.drawText(font, TITLE_X, TITLE_Y, "Notifications", 220);
const message = isNotificationListenerEnabled()
? "No current Android notifications."
: "Grant permission on your phone to view notifications on the glasses.";
const message = notificationEmptyMessage();
const messageLines = wrapText(font, message, width - 48);
for (let index = 0; index < messageLines.length; index++) {
image.drawText(font, 24, 72 + index * lineStep(font), messageLines[index]!, 190);
@@ -445,7 +443,7 @@ function buildDetailMenu(notification: AndroidNotification, origin: SingleNotifi
label: action.enabled ? action.title : `${action.title} (unavailable)`,
action,
})),
{ kind: "dismiss", label: "Dismiss" },
{ kind: "dismiss", label: notification.dismissLabel || "Dismiss" },
...(origin === "new-notification-modal" && notification.packageName
? [{ kind: "disable-source" as const, label: "Don't show on glasses again" }] : []),
];
+93
View File
@@ -0,0 +1,93 @@
const test = require('node:test')
const assert = require('node:assert/strict')
const { AncsClient } = require('../.test-build/app/g2/ancs-client.js')
const le = n => [n&255,n>>>8&255,n>>>16&255,n>>>24]
function setup(t, token=123) {
const sent=[], changed=[]
const client=new AncsClient(async b=>sent.push([...b]), (...args)=>changed.push(args))
t.after(()=>client.stop()); client.start(token)
let seq=0
const frame=(kind,bytes,flags=3,sequence=seq++,nonce=token)=>new Uint8Array([65,78,1,kind,...le(nonce),sequence&255,sequence>>8,flags,...bytes])
const feed=(kind,bytes)=> {
if (!bytes.length) return client.receive(frame(kind,[]))
for(let i=0;i<bytes.length;i+=9) client.receive(frame(kind,bytes.slice(i,i+9),(i===0?1:0)|(i+9>=bytes.length?2:0)))
}
const source=(uid,event=0,flags=0)=>feed(1,[event,flags,1,1,...le(uid)])
const attr=(id,text)=> {const b=[...Buffer.from(text)];return [id,b.length&255,b.length>>8,...b]}
const details=(uid,title='Hello',body='Private message')=>feed(2,[0,...le(uid),...attr(0,'com.example'),...attr(1,title),...attr(3,body)])
feed(0,[0]); feed(0,[1])
return {client,sent,changed,frame,feed,source,attr,details}
}
test('receives fragmented UTF-8 notifications; pre-existing and modified items do not pop up',t=>{
const x=setup(t); x.source(7); x.feed(3,[]); x.details(7,'Hi 👓','Message café')
assert.equal(x.client.read()[0].text,'Message café');assert.deepEqual(x.changed.at(-1),['ancs:123:7',true])
x.source(7,1);x.feed(3,[]);x.details(7,'Updated');assert.equal(x.changed.at(-1)[1],false)
x.source(8,0,4);x.feed(3,[]);x.details(8);assert.equal(x.changed.at(-1)[1],false)
assert.ok(x.sent.every(p=>p.length<=20))
})
test('removal during retrieval cannot resurrect notification',t=>{
const x=setup(t);x.source(7);x.source(7,2);x.details(7);x.feed(3,[])
assert.deepEqual(x.client.read(),[])
})
test('modification during retrieval ignores old text then retrieves new revision',t=>{
const x=setup(t);x.source(7);x.source(7,1);x.details(7,'Old');x.feed(3,[])
assert.deepEqual(x.client.read(),[]);x.feed(3,[]);x.details(7,'New');assert.equal(x.client.read()[0].title,'New')
})
test('disconnect, reused UID and delayed old-token packets cannot expose old content',t=>{
const x=setup(t);x.source(7);x.feed(3,[]);x.details(7);const key=x.client.read()[0].key
x.client.stop();assert.deepEqual(x.client.read(),[]);assert.equal(x.client.action(key,1),false)
x.client.start(456);x.client.receive(x.frame(1,[0,0,1,1,...le(7)],3,0,123));assert.deepEqual(x.client.read(),[])
assert.equal(x.client.state,'starting')
})
test('sequence gaps and oversized attributes fail closed and erase partial state',t=>{
const x=setup(t);x.source(7);x.client.receive(x.frame(2,[0,...le(7),0,255,255],3,33));assert.equal(x.client.state,'unavailable');assert.deepEqual(x.client.read(),[])
})
test('attribute overflow is rejected without allocation from untrusted lengths',t=>{
const x=setup(t);x.source(7);x.feed(2,[0,...le(7),0,255,255]);assert.equal(x.client.state,'unavailable')
})
test('actions use supplied labels; local Dismiss never sends negative action',t=>{
const x=setup(t);x.source(7,0,24);x.details(7);x.feed(3,[])
assert.deepEqual(x.sent.at(-1).slice(8),[0,...le(7),6,7]);x.feed(3,[])
x.feed(2,[0,...le(7),...x.attr(6,'Accept'),...x.attr(7,'Decline')])
const n=x.client.read()[0];assert.deepEqual(n.actions.map(a=>a.title),['Accept','Decline'])
assert.equal(x.client.action(n.key,0),true);assert.deepEqual(x.sent.at(-1).slice(8),[2,...le(7),0]);x.feed(3,[])
const count=x.sent.length;assert.equal(x.client.dismiss(n.key),true);assert.equal(x.sent.length,count)
})
test('does not start next CP transaction before previous write response',t=>{
const x=setup(t);x.source(1);x.source(2);x.details(1);assert.equal(x.sent.length,2)
x.feed(3,[]);assert.equal(x.sent.length,3)
})
test('active notifications and pending work are bounded',t=>{
const x=setup(t);for(let i=0;i<150;i++) x.source(i)
assert.ok(x.client.sources.size<=128);assert.ok(x.client.queue.length<=128)
})
test('stop during retry uses the firmware token actually sent, not the next attempt token',t=>{
const x=setup(t);x.client.receive(x.frame(1,[0,0,1,1,...le(7)],3,99))
assert.equal(x.client.state,'unavailable');assert.deepEqual([...x.client.stopCommand().slice(4)],le(123))
})
test('malformed UTF-8 preserves the valid text prefix',t=>{
const x=setup(t);x.source(7);x.feed(3,[])
x.feed(2,[0,...le(7),...x.attr(0,'com.example'),...x.attr(1,'Hello'),3,3,0,65,66,0xc3])
assert.equal(x.client.read()[0].text,'AB�')
})
test('startup diagnostics distinguish missing reply from an incomplete subscription', t => {
t.mock.timers.enable({apis:['setTimeout']})
const logs=[]; const client=new AncsClient(async()=>{},()=>{},message=>logs.push(message))
t.after(()=>client.stop());client.start(123)
t.mock.timers.tick(10000)
assert.equal(client.state,'unavailable');assert.match(client.statusMessage,/No notification relay response/)
t.mock.timers.tick(5000)
client.receive(new Uint8Array([65,78,1,0,...le(124),0,0,3,0]))
t.mock.timers.tick(10000)
assert.equal(client.state,'unavailable');assert.match(client.statusMessage,/did not finish subscribing/)
assert.ok(logs.some(message=>message.includes('accepted notification relay START')))
})
test('relay errors have a distinct message and clear any displayed content', t => {
const x=setup(t);x.source(7);x.feed(3,[]);x.details(7)
x.feed(0,[2]);assert.equal(x.client.state,'unavailable')
assert.match(x.client.statusMessage,/reported a notification relay error/)
assert.deepEqual(x.client.read(),[])
})
+4
View File
@@ -194,6 +194,8 @@ test('background glasses input still composites frames; phone resume preserves t
'../assistant/navigate-tools': { registerNavigateTools() {} },
'../assistant/roam-tools': { registerRoamTools() {} },
"../native/ios-navigation-sensors": {},
'../native/notification-icons.ios': { bindIosNotifications() {}, iosNotificationsChanged() {}, onIosNotificationPopup: () => () => {}, readActiveNotifications: () => [] },
'../native/notification-sources': { shouldShowNotificationOnGlasses: () => true },
'../native/compass.ios': { bindCompassSession() {}, receiveCompassEvent() {} },
'@nativescript/core': { File: { fromPath: () => ({ writeTextSync() {} }) }, knownFolders: { documents: () => ({ path: '/tmp' }) }, path },
'../native/ios-voice-input': { iosVoiceInput: { handleSessionEnded() {} } },
@@ -269,6 +271,8 @@ test('iOS bandwidth footer toggles live, polls only in foreground and resets its
'../assistant/navigate-tools': { registerNavigateTools() {} },
'../assistant/roam-tools': { registerRoamTools() {} },
"../native/ios-navigation-sensors": {},
'../native/notification-icons.ios': { bindIosNotifications() {}, iosNotificationsChanged() {}, onIosNotificationPopup: () => () => {}, readActiveNotifications: () => [] },
'../native/notification-sources': { shouldShowNotificationOnGlasses: () => true },
'../native/compass.ios': { bindCompassSession() {}, receiveCompassEvent() {} },
'@nativescript/core': core,
'../apps/launcher': { launcherEntries: () => [] },
+27 -1
View File
@@ -117,7 +117,7 @@ class FakeTransport {
}
let body = new Uint8Array();
if (message.sid === p.SID.auth) body = p.bytes(3, new Uint8Array());
if (message.sid === p.SID.settings) body = p.concat(p.bytes(4, p.concat(string(5, '2.2.9.22'), string(6, '2.2.9.22'), p.integer(12, 90), p.integer(13, 0))), string(100, this.stock ? '' : `Faceclaw/${REQUIRED_FACECLAW_FIRMWARE_VERSION}`));
if (message.sid === p.SID.settings) body = p.concat(p.bytes(4, p.concat(string(5, '2.2.9.22'), string(6, '2.2.9.22'), p.integer(12, 90), p.integer(13, 0))), string(100, this.stock ? '' : `Faceclaw/${this.firmware ?? REQUIRED_FACECLAW_FIRMWARE_VERSION}`));
const responseCommand = message.sid === p.SID.launch ? 1 : message.sid === p.SID.hub && message.command === 0 ? 1 : message.sid === p.SID.hub && message.command === 3 ? 4 : message.command;
const payload = p.concat(p.integer(1, responseCommand), p.integer(2, overrides.magic ?? message.magic), body);
const data = hex(p.concat(...p.frameMessage(payload, overrides.sid ?? message.sid, 0, 12)));
@@ -126,6 +126,7 @@ class FakeTransport {
}
async write(id, characteristic, frame) {
assert.equal(characteristic, p.G2_WRITE); assert.ok(frame.length <= 185);
if (frame[0] === 65 && frame[1] === 78) { (this.ancs ??= []).push({ id, frame: new Uint8Array(frame) }); return; }
let messages;
if (frame[6] === p.SID.cfw) {
assert.equal(p.crc16(frame.subarray(8, -2)), frame[frame.length - 2] | frame[frame.length - 1] << 8);
@@ -550,3 +551,28 @@ test('wear notifications validate the event and peer and work during initial con
await h.session.stop(); emit('R', payload(0));
assert.deepEqual(h.wear, [false, true]);
});
test('ANCS packets are scoped to the right link and cleared on disconnect and authorization revocation', async t => {
const transport = new FakeTransport(); transport.firmware = 16;
const h = harness(t, transport); await h.session.start(addresses);
await until(() => transport.ancs?.length);
const token = Array.from(transport.ancs[0].frame.subarray(4,8));
assert.equal(transport.ancs[0].id, 'R');
const frame = new Uint8Array([65,78,1,0,...token,0,0,3,1]);
const emit = id => transport.emit({kind:'notification',identifier:id,characteristic:p.G2_NOTIFY,data:hex(frame)});
emit('L'); assert.equal(h.session.notifications.state, 'starting');
emit('R'); assert.equal(h.session.notifications.state, 'ready');
transport.emit({kind:'ancs-authorization',identifier:'R',authorized:false});
assert.equal(h.session.notifications.state,'disconnected');
emit('R'); assert.equal(h.session.notifications.state,'disconnected');
await h.session.stop(); assert.deepEqual(h.session.notifications.read(),[]);
});
test('firmware 15 requires an upgrade before starting notification relay', async t => {
const transport = new FakeTransport(); transport.firmware = 15;
const h = harness(t, transport); await h.session.start(addresses);
assert.equal(h.session.notifications.state, 'disconnected');
assert.match(h.session.notifications.statusMessage, /firmware 16 or newer/);
assert.equal(transport.ancs?.length ?? 0, 0);
});
+2
View File
@@ -76,6 +76,8 @@ function fixture() {
'../assistant/navigate-tools': { registerNavigateTools() {} },
'../assistant/roam-tools': { registerRoamTools() {} },
"../native/ios-navigation-sensors": {},
'../native/notification-icons.ios': { bindIosNotifications() {}, iosNotificationsChanged() {}, onIosNotificationPopup: () => () => {}, readActiveNotifications: () => [] },
'../native/notification-sources': { shouldShowNotificationOnGlasses: () => true },
"../native/compass.ios": { bindCompassSession() {}, receiveCompassEvent() {} },
'@nativescript/core': { File: { fromPath: () => ({ writeTextSync() {} }) },
knownFolders: { documents: () => ({ path: '/tmp' }) }, path },
+1
View File
@@ -11,6 +11,7 @@
"outDir": "../.test-build"
},
"include": [
"../app/g2/ancs-client.ts",
"../app/g2/ble-protocol.ts",
"../app/graphics/lvgl-font.ts",
"../app/phone-ui/ble-bandwidth-meter.ts",