Display proper app name in iOS notifications

This commit is contained in:
James Babcock committed 2026-09-19 11:46:46 -07:00
1 parent 67823f66ef
commit cef879fec0
5 files changed
+223 -33

No files matched your search

+73 -23
View File
@@ -4,6 +4,7 @@ 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 MAX_COMMAND = 80 // Firmware relay limit, including its 8-byte header.
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]
@@ -28,8 +29,19 @@ function utf8(bytes: Uint8Array): string {
}
return result
}
function fallbackAppName(identifier: string): string {
return identifier.split('.').filter(Boolean).pop() || 'Unknown app'
}
function notificationDate(value: string): number | undefined {
const parts = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})$/.exec(value)
if (!parts) return undefined
const [year,month,day,hour,minute,second] = parts.slice(1).map(Number)
const date = new Date(year,month-1,day,hour,minute,second)
return date.getFullYear() === year && date.getMonth() === month-1 && date.getDate() === day &&
date.getHours() === hour && date.getMinutes() === minute && date.getSeconds() === second ? date.getTime() : undefined
}
type Source = { flags: number; category: number; revision: number; postTime: number; popup: boolean }
type Request = { uid: number; revision: number; action?: number; labels?: boolean }
type Request = { uid: number; revision: number; action?: number; metadata?: boolean; appId?: string }
export type AncsState = 'disconnected' | 'starting' | 'ready' | 'unavailable'
/** Owns one phone/lens BLE session. Nothing is persisted. Firmware enforces
@@ -46,6 +58,8 @@ export class AncsClient {
private response: number[] = []
private sources = new Map<number, Source>()
private notifications = new Map<number, AndroidNotification>()
private appNames = new Map<string, string>()
private maxWrite = 20
private queue: Request[] = []
private acknowledged = false
private responseDone = false
@@ -62,8 +76,9 @@ export class AncsClient {
this.state = state; this.statusMessage = message; this.log(message); this.changed()
}
start(token: number): void {
start(token: number, maxWrite = 20): void {
this.stop(); this.disposed = false; this.token = token >>> 0 || 1
this.maxWrite = Math.min(MAX_COMMAND, maxWrite)
this.begin()
}
private begin(): void {
@@ -84,7 +99,7 @@ export class AncsClient {
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.timer = null; this.sources.clear(); this.notifications.clear(); this.appNames.clear(); this.queue = []
this.pending = null; this.response = []; this.fragments = []; this.packetKind = -1; this.sequence = 0
}
private recover(message = 'Notification relay interrupted. Retrying…'): void {
@@ -178,9 +193,12 @@ export class AncsClient {
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]
// Notification attributes use two requests, each fitting a 20-byte ATT
// payload. App IDs cannot be fragmented by this firmware's CP relay.
const cp = request.appId !== undefined
? [1,...Array.from(request.appId, c => c.charCodeAt(0)),0,0]
: request.action === undefined
? request.metadata ? [0,...le32(request.uid),2,128,0,4,5,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() })
@@ -192,10 +210,21 @@ export class AncsClient {
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
if (!b.length) return
const appId = this.pending.appId
let cursor: number
if (appId !== undefined) {
if (b[0] !== 1) { this.recover(); return }
const end = b.indexOf(0,1)
if (end < 0) { if (b.length > appId.length+1) this.recover(); return }
if (utf8(b.subarray(1,end)) !== appId) { this.recover(); return }
cursor = end+1
} else {
if (b.length < 5) return
if (b[0] !== 0 || read32(b,1) !== this.pending.uid) { this.recover(); return }
cursor = 5
}
const expected = appId !== undefined ? [0] : this.pending.metadata ? [2,4,5,6,7] : [0,1,3]
const attrs = new Map<number,string>()
while (cursor < b.length) {
if (cursor+3 > b.length) return
@@ -206,30 +235,51 @@ export class AncsClient {
}
if (attrs.size !== expected.length) return
const {uid,revision} = this.pending, source = this.sources.get(uid)
if (appId !== undefined) {
const displayName = attrs.get(0)!.trim()
const name = displayName && displayName !== appId ? displayName : fallbackAppName(appId)
this.appNames.set(appId,name)
while (this.appNames.size > MAX_ACTIVE) this.appNames.delete(this.appNames.keys().next().value!)
for (const notification of this.notifications.values()) {
if (notification.packageName === appId) notification.appName = name
}
}
if (source?.revision === revision) {
const key = `ancs:${this.token}:${uid}`
if (this.pending.labels) {
if (appId !== undefined) {
this.publish(uid,source)
} else if (this.pending.metadata) {
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)
if (notification) {
notification.subText = attrs.get(2)!
notification.when = notificationDate(attrs.get(5)!) ?? source.postTime
const size = attrs.get(4)!
if (/^\d+$/.test(size) && Number.isSafeInteger(Number(size))) notification.messageSize = Number(size)
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 id = notification.packageName
// Bundle IDs are ASCII. Reject embedded NULs/invalid IDs and use the
// readable fallback if the entire command cannot fit either link.
if (!this.appNames.has(id) && /^[A-Za-z0-9.-]+$/.test(id) && id.length+11 <= this.maxWrite) {
this.queue.unshift({uid,revision,appId:id})
} else this.publish(uid,source)
}
} 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,
this.notifications.set(uid,{key,packageName,appName:this.appNames.get(packageName) || fallbackAppName(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.queue.unshift({uid,revision,metadata:true}); this.changed(key,false)
}
}
this.responseDone = true
if (this.acknowledged) this.complete()
}
private publish(uid: number, source: Source): void {
const popup = source.popup; source.popup = false
this.changed(`ancs:${this.token}:${uid}`,popup)
}
private complete(): void {
if (this.timer !== null) clearTimeout(this.timer)
this.timer = null; this.pending = null; this.response = []; this.pump()
+2 -2
View File
@@ -145,7 +145,7 @@ export class GlassesSession {
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)
this.notifications.start((Date.now() ^ Math.floor(Math.random()*0xffffffff)) >>> 0, this.limits.right)
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()
@@ -327,7 +327,7 @@ export class GlassesSession {
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)
this.notifications.start((Date.now() ^ Math.floor(Math.random()*0xffffffff)) >>> 0, this.limits.right)
}
return
}
+2
View File
@@ -5,4 +5,6 @@ export type AndroidNotification = {
bigText: string; subText: string; infoText: string; summaryText: string;
category: string; lines: string[]; postTime: number; when: number;
actions: AndroidNotificationAction[]; dismissLabel?: string;
/** Full message size reported by iOS, even when the fetched text is bounded. */
messageSize?: number;
};
+113 -8
View File
@@ -2,10 +2,10 @@ 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) {
function setup(t, token=123, maxWrite=20) {
const sent=[], changed=[]
const client=new AncsClient(async b=>sent.push([...b]), (...args)=>changed.push(args))
t.after(()=>client.stop()); client.start(token)
t.after(()=>client.stop()); client.start(token,maxWrite)
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)=> {
@@ -14,15 +14,22 @@ function setup(t, token=123) {
}
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)])
const details=(uid,title='Hello',body='Private message',appId='com.example')=>feed(2,[0,...le(uid),...attr(0,appId),...attr(1,title),...attr(3,body)])
const metadata=(uid,{subtitle='',size='',date='',positive='',negative=''}={})=>feed(2,[0,...le(uid),...attr(2,subtitle),...attr(4,size),...attr(5,date),...attr(6,positive),...attr(7,negative)])
const appName=(appId,name)=>feed(2,[1,...Buffer.from(appId),0,...attr(0,name)])
const deliver=(uid,appId='com.example',meta={})=> {
source(uid);feed(3,[]);details(uid,'Hello','Private message',appId);feed(3,[]);metadata(uid,meta)
}
const restart=()=>{seq=0;client.start(token,maxWrite);feed(0,[0]);feed(0,[1])}
feed(0,[0]); feed(0,[1])
return {client,sent,changed,frame,feed,source,attr,details}
return {client,sent,changed,frame,feed,source,attr,details,metadata,appName,deliver,restart}
}
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é')
x.feed(3,[]);x.metadata(7)
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)
x.source(7,1);x.feed(3,[]);x.details(7,'Updated');x.feed(3,[]);x.metadata(7);assert.equal(x.changed.at(-1)[1],false)
x.source(8,0,4);x.feed(3,[]);x.details(8);x.feed(3,[]);x.metadata(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=>{
@@ -47,8 +54,8 @@ test('attribute overflow is rejected without allocation from untrusted lengths',
})
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')])
assert.deepEqual(x.sent.at(-1).slice(8),[0,...le(7),2,128,0,4,5,6,7]);x.feed(3,[])
x.metadata(7,{positive:'Accept',negative:'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)
@@ -91,3 +98,101 @@ test('relay errors have a distinct message and clear any displayed content', t =
assert.match(x.client.statusMessage,/reported a notification relay error/)
assert.deepEqual(x.client.read(),[])
})
test('requests every notification attribute and uses the app display name for the first popup',t=>{
const x=setup(t,123,185), id='net.superblock.Pushover'
x.deliver(7,id,{subtitle:'A subtitle',size:'1024',date:'20260919T123456'})
assert.deepEqual(x.sent[1].slice(8),[0,...le(7),0,1,128,0,3,0,2])
assert.deepEqual(x.sent[2].slice(8),[0,...le(7),2,128,0,4,5,6,7])
assert.deepEqual(x.sent.at(-1).slice(8),[1,...Buffer.from(id),0,0])
assert.equal(x.client.read()[0].appName,'Pushover')
assert.equal(x.changed.some(([,popup])=>popup),false)
// Fragment the actual ANCS Data Source response, including the app ID and UTF-8.
x.feed(3,[])
for (const byte of [1,...Buffer.from(id),0,...x.attr(0,'Pushover — 通知')]) x.feed(2,[byte])
const n=x.client.read()[0]
assert.equal(n.appName,'Pushover — 通知');assert.equal(n.packageName,id)
assert.equal(n.subText,'A subtitle');assert.equal(n.messageSize,1024)
assert.equal(n.when,new Date(2026,8,19,12,34,56).getTime())
assert.deepEqual(x.changed.at(-1),['ancs:123:7',true])
assert.equal(x.client.state,'ready')
})
test('app names are cached per session and a name update does not trigger another popup',t=>{
const x=setup(t,123,185), id='com.example'
x.deliver(1,id);x.appName(id,'Example App')
assert.equal(x.changed.filter(([,popup])=>popup).length,1)
const count=x.sent.length
x.source(2);assert.equal(x.sent.length,count) // Still waiting for app CP acknowledgement.
x.feed(3,[]);x.feed(3,[]);x.details(2);x.feed(3,[]);x.metadata(2)
assert.equal(x.sent.filter(p=>p[8]===1).length,1)
assert.ok(x.client.read().every(n=>n.appName==='Example App'))
assert.equal(x.changed.filter(([,popup])=>popup).length,2)
x.restart();x.deliver(1,id)
assert.equal(x.client.read()[0].appName,'example')
assert.equal(x.sent.filter(p=>p[8]===1).length,2)
x.feed(3,[]);x.appName(id,'New Session Name')
assert.equal(x.client.read()[0].appName,'New Session Name')
})
test('missing display names use and cache the final bundle-ID component',t=>{
for(const name of ['', ' ', 'net.superblock.Pushover']) {
const x=setup(t,123,185), id='net.superblock.Pushover'
x.deliver(1,id);x.feed(3,[]);x.appName(id,name)
assert.equal(x.client.read()[0].appName,'Pushover')
x.deliver(2,id)
assert.equal(x.sent.filter(p=>p[8]===1).length,1)
}
})
test('minimum MTU and relay command limit fall back without sending an oversized app request',t=>{
for(const [maxWrite,id,expected,canRequest] of [
[20,'net.superblock.Pushover','Pushover',false],
[20,'com.short','short',true],
[80,'a'.repeat(67)+'.X','X',true],
[185,'a'.repeat(68)+'.X','X',false],
[185,'','Unknown app',false],
[185,'com.bad\0id','bad\0id',false],
]) {
const x=setup(t,123,maxWrite);x.deliver(1,id)
assert.equal(x.client.read()[0].appName,expected)
assert.equal(x.sent.some(p=>p[8]===1),canRequest)
assert.ok(x.sent.every(p=>p.length<=Math.min(maxWrite,80)))
if(!canRequest) assert.deepEqual(x.changed.at(-1),['ancs:123:1',true])
}
})
test('app response must match the requested identifier and reject malformed attributes',t=>{
for(const response of [
x=>[1,...Buffer.from('com.wrong'),0,...x.attr(0,'Wrong')],
x=>[1,...Buffer.from('com.example'),0,0,1,2],
x=>[1,...Buffer.from('com.example'),0,...x.attr(1,'Wrong attribute')],
x=>[1,...Buffer.from('com.exampleX')],
]) {
const x=setup(t,123,185);x.deliver(1);x.feed(2,response(x))
assert.equal(x.client.state,'unavailable');assert.deepEqual(x.client.read(),[])
}
})
test('removal or modification during app lookup cannot resurrect or pop up a stale notification',t=>{
for(const event of [1,2]) {
const x=setup(t,123,185);x.deliver(1);x.source(1,event)
x.appName('com.example','Example App');x.feed(3,[])
assert.equal(x.changed.some(([,popup])=>popup),false)
if(event===2) assert.deepEqual(x.client.read(),[])
else {
x.feed(3,[]);x.details(1,'Updated');x.feed(3,[]);x.metadata(1)
assert.equal(x.client.read()[0].title,'Updated')
assert.equal(x.client.read()[0].appName,'Example App')
assert.equal(x.changed.at(-1)[1],false)
}
}
})
test('missing or invalid date and message size preserve arrival time and omit invalid size',t=>{
for(const [date,size] of [['',''],['20260230T123456','oops'],['20260919T256100','9007199254740992']]) {
const x=setup(t);x.deliver(1,'com.example',{date,size})
const n=x.client.read()[0]
assert.equal(n.when,n.postTime);assert.equal(n.messageSize,undefined)
}
})
+33
View File
@@ -576,3 +576,36 @@ test('firmware 15 requires an upgrade before starting notification relay', async
assert.match(h.session.notifications.statusMessage, /firmware 16 or newer/);
assert.equal(transport.ancs?.length ?? 0, 0);
});
test('ANCS app-name lookup uses the right-link write limit, including after reauthorization', 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 id = 'net.superblock.Pushover';
const attr = (key, value) => { const bytes = [...Buffer.from(value)]; return [key, bytes.length & 255, bytes.length >> 8, ...bytes]; };
for (let attempt = 0; attempt < 2; attempt++) {
if (attempt) {
transport.emit({kind:'ancs-authorization',identifier:'R',authorized:false});
const count = transport.ancs.length;
transport.emit({kind:'ancs-authorization',identifier:'R',authorized:true});
await until(() => transport.ancs.slice(count).some(p => p.frame[3] === 0));
}
const start = transport.ancs.filter(p => p.frame[3] === 0).at(-1);
const token = [...start.frame.subarray(4,8)];
let sequence = 0;
const feed = (kind, bytes) => transport.emit({kind:'notification',identifier:'R',characteristic:p.G2_NOTIFY,
data:hex(new Uint8Array([65,78,1,kind,...token,sequence++,0,3,...bytes]))});
const count = transport.ancs.length;
feed(0,[1]);feed(1,[0,0,1,1,7,0,0,0]);
await until(() => transport.ancs.length === count+1);
feed(3,[]);feed(2,[0,7,0,0,0,...attr(0,id),...attr(1,'Title'),...attr(3,'Message')]);
await until(() => transport.ancs.length === count+2);
feed(3,[]);feed(2,[0,7,0,0,0,...attr(2,''),...attr(4,'7'),...attr(5,''),...attr(6,''),...attr(7,'')]);
await until(() => transport.ancs.length === count+3);
const request = transport.ancs.at(-1);
assert.equal(request.id,'R');
assert.deepEqual([...request.frame.subarray(8)],[1,...Buffer.from(id),0,0]);
feed(3,[]);feed(2,[1,...Buffer.from(id),0,...attr(0,'Pushover Notifications')]);
assert.equal(h.session.notifications.read()[0].appName,'Pushover Notifications');
}
});