const test = require('node:test'); const assert = require('node:assert/strict'); const p = require('../.test-build/app/g2/ble-protocol.js'); const { identifyIosPeripheral, deviceAddressError } = require('../.test-build/app/g2/ios-peripheral-identity.js'); const { GlassesSession } = require('../.test-build/app/g2/glasses-session.js'); const { deflate, inflate } = require('pako'); const { inflateSync, constants } = require('node:zlib'); const { REQUIRED_FACECLAW_FIRMWARE_VERSION } = require('../.test-build/app/g2/firmware-compat.js'); const hex = bytes => Buffer.from(bytes).toString('hex'); const string = (field, text) => p.bytes(field, new Uint8Array(Buffer.from(text))); // Generated by compiling the existing Android BleProtocol.java/BmpUtil.java, // plus BleImageOptimizer's unchanged RLE method, with javac 25.0.2. test('iOS/shared protocol matches Android-generated wire vectors byte for byte', () => { const vectors = [ [p.authentication(101), '080410651a0408011004'], [p.prelude(), '0802109c01220a1a081206120408001000'], [p.createLayout(102), '080010661a2308011a1c0800100018c00420a0024801520964617368626f617264580162012028904e'], [p.heartbeat(103), '080c106772020800'], [p.settingsQuery(104), '0802106822020801'], [p.shutdown(105), '080910695a020801'], [p.framebufferLease(true), '08011000aa0606464301050000'], [p.framebufferLease(false), '08011000aa0606464301060000'], [p.frameMessage(p.authentication(101), 128, 0, 64)[0], 'aa21400c01018000080410651a04080110041024'], ]; for (const [actual, expected] of vectors) assert.equal(hex(actual), expected); const packed = p.packGray4(new Uint8Array([0, 1, 7, 8, 15, 16, 23, 24, 127, 128, 247, 255]), 3, 4); assert.equal(hex(packed), '0000111012808ff0'); assert.equal(hex(p.rle4(packed)), '40311011121810182f10'); }); test('negotiated-MTU framing reassembles split and coalesced notifications and rejects bad CRC', () => { const payload = p.concat(p.integer(1, 3), p.integer(2, 110), p.bytes(8, new Uint8Array(3900).fill(55))); const frames = p.frameMessage(payload, 0xe0, 0x20, 17, 185); assert.ok(frames.every(f => f.length <= 185)); const receiver = new p.MessageReceiver(), stream = p.concat(...frames); assert.deepEqual(receiver.receive('L', stream.slice(0, 7)), []); const messages = receiver.receive('L', stream.slice(7)); assert.equal(messages.length, 1); assert.deepEqual(messages[0].payload, payload); stream[stream.length - 1] ^= 1; assert.deepEqual(receiver.receive('L', stream), []); assert.throws(() => p.frameMessage(payload, 1, 0, 1, 10), /too small/); assert.throws(() => p.readBytes(new Uint8Array([0x1a, 0x7f]), 3), /Truncated/); }); test('interleaved links and missing/expired fragments cannot produce false ACKs', () => { const payload = p.concat(p.integer(1, 3), p.integer(2, 110), p.bytes(8, new Uint8Array(300))); const frames = p.frameMessage(payload, 224, 0, 17), receiver = new p.MessageReceiver(); assert.deepEqual(receiver.receive('L', frames[0], 0), []); assert.deepEqual(receiver.receive('R', frames[1], 1), []); assert.deepEqual(receiver.receive('L', frames[1], 6000), []); assert.equal(receiver.receive('L', p.concat(...frames), 6001).length, 1); }); test('full-frame RLE splits 65535-pixel runs and preserves opaque near-black', () => { const packed = p.packGray4(new Uint8Array(640 * 480).fill(1), 640, 480); assert.ok(packed.every(v => v === 0)); const encoded = p.rle4(packed); let count = 0, offset = 0; while (offset < encoded.length) { const token = encoded[offset++]; let run = token >>> 4; if (!run) { run = encoded[offset++]; if (!run) { run = encoded[offset] | (encoded[offset + 1] << 8); offset += 2; } } assert.equal(token & 15, 0); count += run; } assert.equal(count, 640 * 480); assert.deepEqual(inflate(deflate(encoded)), encoded); }); test('iOS mapping requires the full advertised MAC, never just a name suffix', () => { const raw = { identifier: '8A2DD845-B208-F292-EB77-F4645C5AC42F', name: 'Even G2_32_L_B6ECE0', manufacturerData: '4552' + Buffer.from('S211GBBC180304').toString('hex') + 'e0ecb61412e001', rssi: -45, connectable: true }; const device = identifyIosPeripheral(raw); assert.equal(device.address, 'E0:12:14:B6:EC:E0'); assert.equal(device.role, 'left'); assert.equal(device.identifier, raw.identifier); assert.equal(device.serial, 'S211GBBC180304'); assert.equal(identifyIosPeripheral({ ...raw, manufacturerData: '' }), null); assert.equal(identifyIosPeripheral({ ...raw, identifier: 'not-a-uuid' }), null); assert.match(deviceAddressError({ left: device.address, right: device.address, ring: '' }), /different/); assert.equal(deviceAddressError({ left: device.address, right: 'AA:BB:CC:DD:EE:FF', ring: '' }), null); }); test('ring and arm input decoders preserve gesture and source', () => { assert.equal(p.decodeRingInput(new Uint8Array([255, 4, 2])).eventType, 3); assert.equal(p.decodeRingInput(new Uint8Array([255, 5, 0])).eventType, 2); assert.equal(p.decodeRingInput(new Uint8Array([255, 5, 2])).eventType, 1); assert.equal(p.decodeRingInput(new Uint8Array([0, 9, 97, 0, 8, 0, 0, 0, 0, 0, 0])).eventType, 10); assert.equal(p.decodeRingInput(new Uint8Array([255, 4, 99])), null); const payload = p.bytes(13, p.bytes(3, p.concat(p.integer(1, 9), p.integer(2, 3)))); assert.equal(p.decodeGlassesInput({ sid: 224, flag: 1, payload }).eventSource, 3); assert.equal(p.decodeGlassesInput({ sid: 224, flag: 32, payload }), null); const headUp = p.bytes(13, p.bytes(3, p.concat(p.integer(1, 12), p.integer(2, 1)))); const wake = p.decodeGlassesInput({ sid: 224, flag: 1, payload: headUp }); assert.equal(wake.kind, 'display-wake'); assert.equal(wake.eventType, 12); assert.equal(wake.eventSource, 1); // The stock G2 sender omits source for dedicated Faceclaw event 14. const press = p.decodeGlassesInput({ sid: 224, flag: 1, payload: p.bytes(13, p.bytes(3, p.integer(1, 14))) }); assert.equal(press.kind, 'sys-event'); assert.equal(press.eventType, 14); assert.equal(press.eventSource, 0); }); class FakeTransport { events = new Set(); receiver = new p.MessageReceiver(); sent = []; subscriptions = []; closed = []; hold = false; held = []; stock = false; cfw = new Map(); onEvent(fn) { this.events.add(fn); return () => this.events.delete(fn); } emit(event) { for (const fn of [...this.events]) fn(event); } async resolveDevices() { return { left: 'L', right: 'R', ring: 'ring' }; } async connect(id) { return { characteristics: id === 'ring' ? p.RING_NOTIFY : [p.G2_WRITE, p.G2_NOTIFY], maxWrite: 185 }; } async subscribe(id, characteristic) { this.subscriptions.push([id, characteristic]); } disconnect(id) { this.closed.push(id); this.emit({ kind: 'disconnected', identifier: id }); } stopScan() {} ack(id, message, overrides = {}) { if (message.sid === p.SID.cfw) { for (const lens of overrides.lenses ?? [1, 2]) { const size = overrides.size ?? message.payload.length, crc = overrides.checksum ?? p.crc16(message.payload); const body = new Uint8Array([overrides.nack ? 3 : 1, overrides.magic ?? message.magic, overrides.ordinal ?? 0, 0, lens, size & 255, size >>> 8, crc & 255, crc >>> 8]); const checksum = p.crc16(body); const packet = p.concat(new Uint8Array([0xaa, 0x12, 0, 11, 1, 1, overrides.sid ?? p.SID.cfw, 0]), body, new Uint8Array([checksum & 255, checksum >>> 8])); this.emit({ kind: 'notification', identifier: overrides.identifier ?? id, characteristic: p.G2_NOTIFY, data: hex(packet) }); } return; } 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/${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))); // The right/master link also carries ACKs for image writes to L. this.emit({ kind: 'notification', identifier: overrides.identifier ?? 'R', characteristic: p.G2_NOTIFY, data }); } 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); let state = this.cfw.get(id) ?? { history: Buffer.alloc(0), decoded: 0 }; if (frame[8] & 0x80) { state.record = []; state.magic = frame[2]; } state.record.push(frame.subarray(9, -2)); this.cfw.set(id, state); if (!(frame[8] & 0x40)) return; const record = p.concat(...state.record), flags = record[0]; assert.equal(record.length - 5, record[1] | record[2] << 8); if (flags & 8) { state.history = Buffer.alloc(0); state.decoded = 0; } let payload = record.subarray(5); if (flags & 4) { state.history = Buffer.concat([state.history, payload]); const all = inflateSync(state.history, { finishFlush: constants.Z_SYNC_FLUSH }); payload = new Uint8Array(all.subarray(state.decoded)); state.decoded = all.length; } assert.equal(p.crc16(payload), record[3] | record[4] << 8); messages = [{ sid: p.SID.cfw, magic: state.magic, payload, flags, command: -1 }]; } else messages = this.receiver.receive(id, frame); for (const message of messages) { this.sent.push({ id, message }); if (!message.magic) continue; if (this.hold) this.held.push({ id, message }); else queueMicrotask(() => this.ack(id, message)); } } } const addresses = { right: 'AA:BB:CC:DD:EE:01', left: 'AA:BB:CC:DD:EE:02', ring: '' }; async function until(predicate) { for (let i = 0; i < 100; i++) { if (predicate()) return; await new Promise(resolve => setTimeout(resolve, 5)); } assert.fail('Timed out waiting for test state'); } function harness(t, transport = new FakeTransport(), textures) { const states = [], input = [], compass = [], wear = []; const session = new GlassesSession(transport, state => states.push(state), event => input.push(event), undefined, undefined, event => compass.push(event), wearing => wear.push(wearing), undefined, textures); t.after(async () => { transport.hold = false; await session.stop(); }); return { transport, session, states, input, compass, wear }; } test('session authenticates both arms, checks firmware and sends acknowledged display data to L', async t => { const h = harness(t); await h.session.start({ ...addresses, ring: 'AA:BB:CC:DD:EE:03' }); assert.equal(h.session.state.phase, 'connected'); assert.equal(h.session.state.ring, true); assert.equal(h.session.state.battery, 90); assert.equal(h.session.state.charging, false); assert.deepEqual(h.transport.sent.filter(s => s.message.sid === 128).map(s => s.id).sort(), ['L', 'R']); h.session.setFrame(new Uint8Array(640 * 480)); await until(() => h.session.state.frames === 1); const image = h.transport.sent.find(s => s.message.sid === p.SID.cfw && s.message.payload[0] === 26); assert.equal(image.id, 'L'); assert.equal(image.message.payload[0], 26); const layout = h.transport.sent.find(s => s.message.sid === p.SID.hub && s.message.command === 0); assert.equal(p.readBytes(p.readBytes(layout.message.payload, 3), 4), undefined); await h.session.stop(); assert.equal(h.session.state.phase, 'disconnected'); assert.ok(h.transport.sent.some(s => s.message.sid === p.SID.cfw && s.message.payload[0] === 11)); }); test('stock firmware is rejected before framebuffer/layout/image commands', async t => { const transport = new FakeTransport(); transport.stock = true; const h = harness(t, transport); await h.session.start(addresses); assert.equal(h.session.state.phase, 'error'); assert.match(h.session.state.status, /firmware/); assert.ok(!transport.sent.some(s => s.message.sid === p.SID.hub)); }); test('one unavailable R1 notification channel does not discard the usable channel', async t => { const transport = new FakeTransport(); const subscribe = transport.subscribe.bind(transport); transport.subscribe = async (id, uuid) => { if (uuid === p.RING_NOTIFY[0]) throw new Error('CCCD timed out'); return subscribe(id, uuid); }; const h = harness(t, transport); await h.session.start({ ...addresses, ring: 'AA:BB:CC:DD:EE:03' }); assert.equal(h.session.state.ring, true); assert.ok(transport.subscriptions.some(([id, uuid]) => id === 'ring' && uuid === p.RING_NOTIFY[1])); assert.ok(!transport.closed.includes('ring')); }); test('disconnect cancels in-flight authentication and ignores late acknowledgements', async t => { const h = harness(t); h.transport.hold = true; const start = h.session.start(addresses); await until(() => h.transport.held.length === 2); await h.session.stop(); for (const held of h.transport.held) h.transport.ack(held.id, held.message); await start; assert.equal(h.session.state.phase, 'disconnected'); assert.ok(!h.states.some(s => s.phase === 'connected')); assert.equal(h.transport.sent.length, 2); }); test('wrong peer, service or magic cannot satisfy a pending request; timeout rejects it', async t => { const h = harness(t); await h.session.start(addresses); h.transport.hold = true; const request = h.session.request('right', p.SID.hub, p.heartbeat, 'test heartbeat', 30); const rejected = assert.rejects(request, /not acknowledged/); await until(() => h.transport.held.length > 0); const held = h.transport.held[0]; h.transport.ack(held.id, held.message, { identifier: 'stranger' }); h.transport.ack(held.id, held.message, { sid: 9 }); h.transport.ack(held.id, held.message, { magic: held.message.magic + 1 }); await rejected; }); test('ring disconnect retries independently and stop cancels further retries', async t => { const h = harness(t); await h.session.start({ ...addresses, ring: 'AA:BB:CC:DD:EE:03' }); const armMessages = h.transport.sent.length; h.transport.emit({ kind: 'disconnected', identifier: 'ring', message: 'Link lost' }); assert.equal(h.session.state.phase, 'connected'); assert.equal(h.session.state.ring, false); assert.notEqual(h.session.ringRetryTimer, null); await new Promise(resolve => setTimeout(resolve, 2100)); assert.equal(h.session.state.ring, true); assert.equal(h.transport.sent.length, armMessages); assert.equal(h.transport.subscriptions.filter(([id]) => id === 'ring').length, 4); h.transport.emit({ kind: 'disconnected', identifier: 'ring' }); await h.session.stop(); assert.equal(h.session.ringRetryTimer, null); }); test('a BLE wake services overdue heartbeat and lease without waiting for a suspended poll timer', async t => { const h = harness(t); await h.session.start(addresses); clearTimeout(h.session.timer); h.session.timer = null; h.session.lastHeartbeat = Date.now() - 12_000; h.session.lastLease = Date.now() - 60_000; const before = h.transport.sent.length; const data = hex(p.concat(...p.frameMessage(p.integer(1, 6), p.SID.auth, 1, 22))); h.transport.emit({ kind: 'notification', identifier: 'L', characteristic: p.G2_NOTIFY, data }); // pump starts in the notification callback, before any timers can fire. assert.equal(h.session.pumping, true); await until(() => !h.session.pumping); const sent = h.transport.sent.slice(before); assert.equal(sent.filter(s => s.message.sid === p.SID.hub && s.message.command === 12).length, 1); assert.deepEqual(sent.filter(s => s.message.sid === p.SID.settings).map(s => s.id).sort(), ['L', 'R']); assert.equal(h.session.state.phase, 'connected'); assert.deepEqual(h.transport.closed, []); await h.session.stop(); const count = h.transport.sent.length; h.session.wake(); h.transport.emit({ kind: 'notification', identifier: 'L', characteristic: p.G2_NOTIFY, data }); assert.equal(h.transport.sent.length, count); assert.equal(h.session.state.phase, 'disconnected'); }); test('glasses mic uses Android wire control and only routes bound-arm audio during capture', async t => { assert.equal(hex(p.audioControl(101, true)), '080f10659201020801'); assert.equal(hex(p.audioControl(101, false)), '080f10659201020800'); const h = harness(t), audio = []; await h.session.start(addresses); const send = id => h.transport.emit({ kind: 'notification', identifier: id, characteristic: p.G2_RENDER_NOTIFY, data: '010203' }); send('R'); assert.equal(audio.length, 0); await h.session.setMicrophone(true, bytes => audio.push(hex(bytes))); assert.ok(h.transport.subscriptions.some(([id, c]) => id === 'R' && c === p.G2_RENDER_NOTIFY)); assert.ok(h.transport.subscriptions.some(([id, c]) => id === 'L' && c === p.G2_RENDER_NOTIFY)); send('stranger'); send('ring'); send('L'); send('R'); assert.deepEqual(audio, ['010203', '010203']); const disabling = h.session.setMicrophone(false); send('R'); assert.equal(audio.length, 2); // Immediate, before the disable ACK. await disabling; assert.deepEqual(h.transport.sent.filter(s => s.message.command === 15).map(s => [s.id, p.readInteger(p.readBytes(s.message.payload, 18), 1)]), [['R', 1], ['R', 0]]); }); test('release while microphone enable awaits ACK sends disable last and rejects further audio', async t => { const h = harness(t); await h.session.start(addresses); h.transport.hold = true; let packets = 0; const enabling = h.session.setMicrophone(true, () => packets++); await until(() => h.transport.held.some(s => s.message.command === 15)); const disabling = h.session.setMicrophone(false); h.transport.emit({ kind: 'notification', identifier: 'R', characteristic: p.G2_RENDER_NOTIFY, data: '01' }); assert.equal(packets, 0); h.transport.hold = false; for (const s of h.transport.held) h.transport.ack(s.id, s.message); await Promise.all([enabling, disabling]); const mic = h.transport.sent.filter(s => s.message.command === 15); assert.equal(p.readInteger(p.readBytes(mic.at(-1).message.payload, 18), 1), 0); }); const imageMessages = transport => transport.sent.filter(s => s.message.sid === p.SID.cfw && ![10, 11].includes(s.message.payload[0])); const imageBody = sent => sent.message.payload; const ack = (transport, sent, overrides) => transport.ack(sent.id, sent.message, overrides); const tick = () => new Promise(resolve => setImmediate(resolve)); const noisy = () => Uint8Array.from({ length: 640 * 480 }, (_, i) => (i % 2) * 255); test('resource evictions and uploads precede their frame, share ACK accounting, and coalesce pixels with draw identities', async t => { const plans = []; let resets = 0; const textures = { reset() { resets++; }, plan(previous, next, frame, firstId) { plans.push({ previous, next, frame, firstId }); return { resourceCommands: plans.length === 1 ? [new Uint8Array([22, 1]), new Uint8Array([21, 2])] : [], payload: new Uint8Array([8, plans.length]), nextFid: firstId + 2, usedBytes: 100 }; }, }; const h = harness(t, new FakeTransport(), textures); await h.session.start(addresses); h.transport.hold = true; const a = { native: { id: 'a' } }, b = { native: { id: 'b' } }, c = { native: { id: 'c' } }; h.session.setFrame(new Uint8Array(640 * 480), a); await until(() => imageMessages(h.transport).length === 3); const sent = imageMessages(h.transport); assert.deepEqual(sent.map(s => s.message.payload[0]), [22, 21, 8]); h.session.setFrame(new Uint8Array(640 * 480).fill(80), b); h.session.setFrame(new Uint8Array(640 * 480).fill(160), c); assert.equal(plans.length, 1, 'coalesced frames must not allocate textures'); ack(h.transport, sent[2]); ack(h.transport, sent[1]); await tick(); assert.equal(h.session.state.frames, 0, 'a draw ACK cannot retire an unacknowledged upload'); ack(h.transport, sent[0]); await until(() => imageMessages(h.transport).length === 4); assert.equal(h.session.state.frames, 1); assert.equal(plans.length, 2); assert.equal(plans[1].frame, c); assert.deepEqual(plans[1].previous, plans[0].next); assert.equal(plans[1].firstId, plans[0].firstId + 2); assert.ok(plans[1].next.every(value => value === 0xaa)); ack(h.transport, imageMessages(h.transport)[3]); await until(() => h.session.state.frames === 2); h.transport.hold = false; await h.session.stop(); assert.ok(resets > 0); }); test('evictions drain earlier replayable draws before resource IDs can be reused', async t => { let plans = 0; const textures = { reset() {}, plan() { return { resourceCommands: ++plans === 1 ? [] : [new Uint8Array([22]), new Uint8Array([21])], payload: new Uint8Array([8]), nextFid: 1, usedBytes: 100 }; }, }; const h = harness(t, new FakeTransport(), textures); await h.session.start(addresses); h.transport.hold = true; h.session.setFrame(new Uint8Array(640 * 480), { native: {} }); await until(() => imageMessages(h.transport).length === 1); h.session.setFrame(new Uint8Array(640 * 480).fill(80), { native: {} }); await until(() => plans === 2); await tick(); assert.equal(imageMessages(h.transport).length, 1, 'eviction cannot enter an unresolved window'); h.session.recoverCfw(); await tick(); assert.equal(imageMessages(h.transport).length, 1); ack(h.transport, imageMessages(h.transport)[0]); await until(() => imageMessages(h.transport).length === 4); assert.deepEqual(imageMessages(h.transport).map(s => s.message.payload[0]), [8, 22, 21, 8]); h.transport.hold = false; for (const sent of imageMessages(h.transport).slice(1)) ack(h.transport, sent); await until(() => h.session.state.frames === 2); }); test('a failed resource upload invalidates residency and the pipelined frame base', async t => { let resets = 0; const textures = { reset() { resets++; }, plan() { return { resourceCommands: [new Uint8Array([21])], payload: new Uint8Array([8]), nextFid: 1, usedBytes: 4 }; }, }; const h = harness(t, new FakeTransport(), textures); await h.session.start(addresses); const original = h.session.requestCfw.bind(h.session); h.session.requestCfw = (role, payload) => payload[0] === 21 ? Promise.reject(new Error('texture upload failed')) : original(role, payload); h.session.setFrame(new Uint8Array(640 * 480), { native: {} }); await until(() => h.session.state.phase === 'retrying'); assert.equal(resets, 1); assert.equal(h.session.lastEnqueued, null); assert.equal(h.session.latestTextures, null); assert.equal(h.session.state.frames, 0); }); test('resuming near framebuffer lease expiry discards cached draws before transmission', async t => { let resets = 0, plans = 0; const textures = { reset() { resets++; }, plan() { plans++; return null; } }; const h = harness(t, new FakeTransport(), textures); await h.session.start(addresses); h.session.lastLease = Date.now() - 85_000; h.session.setFrame(new Uint8Array(640 * 480), { native: {} }); await h.session.pump(); assert.equal(h.session.state.phase, 'retrying'); assert.equal(resets, 1); assert.equal(plans, 0); assert.equal(imageMessages(h.transport).length, 0); }); // Both eyes must finish; wrong ingress, size, CRC, ordinal and legacy replies do not count. test('CFW ACK identity and both-lens completion gate display metrics', async t => { const { iosBleTraffic } = require('../.test-build/app/g2/ble-traffic-counters.js'); const h = harness(t); await h.session.start(addresses); h.transport.hold = true; const before = iosBleTraffic.sample(); let written = 0; const write = h.transport.write.bind(h.transport); h.transport.write = async (...args) => { written += args[2].length; await write(...args); }; h.session.setFrame(new Uint8Array(640 * 480)); await until(() => imageMessages(h.transport).length === 2); const [draw, sent] = imageMessages(h.transport); ack(h.transport,draw); for (const wrong of [{ identifier: 'R' }, { size: 99 }, { checksum: 0 }, { ordinal: 1 }, { magic: sent.message.magic + 1 }]) ack(h.transport, sent, wrong); ack(h.transport, sent, { lenses: [1] }); await tick(); assert.equal(h.session.state.frames, 0); ack(h.transport, sent, { lenses: [2] }); await until(() => h.session.state.frames === 1); assert.equal(iosBleTraffic.sample().bytes - before.bytes, written); assert.equal(iosBleTraffic.sample().messages - before.messages, 2); assert.equal(iosBleTraffic.sample().frames - before.frames, 1); ack(h.transport, sent); await tick(); assert.equal(h.session.state.frames, 1); }); test('large frames use bounded RLE bands and ordered three-message pipelining', async t => { const { applyDisplayPayload } = require('./helpers/display-payload.cjs'); const h = harness(t); await h.session.start(addresses); h.transport.hold = true; const gray = noisy(); h.session.setFrame(gray); await until(() => imageMessages(h.transport).length === 3); const first = imageMessages(h.transport); ack(h.transport, first[2]); ack(h.transport, first[1]); await tick(); assert.equal(imageMessages(h.transport).length, 3); assert.equal(h.session.state.frames, 0); ack(h.transport, first[0]); await until(() => imageMessages(h.transport).length === 6); for (const sent of imageMessages(h.transport).slice(3)) ack(h.transport, sent); await until(() => imageMessages(h.transport).length === 9); assert.equal(h.session.state.frames, 0); for (const sent of imageMessages(h.transport).slice(6)) ack(h.transport, sent); await until(() => h.session.state.frames === 1); let shadow = new Uint8Array(320 * 480); for (const sent of imageMessages(h.transport)) { assert.ok(sent.message.payload.length <= 65535); shadow = applyDisplayPayload(shadow, sent.message.payload); } assert.deepEqual(shadow, p.packGray4(gray, 640, 480)); }); test('draw/present pairs pipeline and coalesce waiting frames', async t => { const h=harness(t);await h.session.start(addresses);h.transport.hold=true; const submit=async v=>{h.session.setFrame(new Uint8Array(640*480).fill(v));await h.session.pump();await tick();}; await submit(0);await submit(0);assert.equal(imageMessages(h.transport).length,2); await submit(255);await until(()=>imageMessages(h.transport).length===3); await submit(80);await submit(160); const first=imageMessages(h.transport);ack(h.transport,first[2]);ack(h.transport,first[1]);await tick(); assert.equal(h.session.state.frames,0);assert.equal(imageMessages(h.transport).length,3); ack(h.transport,first[0]);await until(()=>imageMessages(h.transport).length===6); for(const message of imageMessages(h.transport).slice(3)) ack(h.transport,message); await until(()=>h.session.state.frames===3); const {applyDisplayPayload}=require('./helpers/display-payload.cjs');let screen=new Uint8Array(320*480); for(const {message} of imageMessages(h.transport)) screen=applyDisplayPayload(screen,message.payload); assert.deepEqual(screen,p.packGray4(new Uint8Array(640*480).fill(160),640,480)); assert.deepEqual(imageMessages(h.transport).map(s=>s.message.payload[0]),[26,28,26,28,26,28]); }); test('NACK replays the unresolved window with fresh IDs and reset compression; stale ACKs are ignored', async t => { const h = harness(t); await h.session.start(addresses); h.transport.hold = true; for (const value of [0, 255, 0]) { h.session.setFrame(new Uint8Array(640 * 480).fill(value)); await h.session.pump(); await tick(); } await until(() => imageMessages(h.transport).length === 3); const old = imageMessages(h.transport); ack(h.transport, old[2]); ack(h.transport, old[1], { nack: true, lenses: [2] }); await until(() => imageMessages(h.transport).length === 6); const replay = imageMessages(h.transport).slice(3); for (const sent of old) ack(h.transport, sent); await tick(); assert.equal(h.session.state.frames, 0); replay.forEach((sent, i) => { assert.notEqual(sent.message.magic, old[i].message.magic); assert.ok(sent.message.flags & 8); assert.deepEqual(sent.message.payload, old[i].message.payload); ack(h.transport, sent); }); await until(() => imageMessages(h.transport).length === 9); imageMessages(h.transport).slice(6).forEach(sent=>ack(h.transport,sent)); await until(() => h.session.state.frames === 3); }); test('timeout starts after writes; missing ACK retries are bounded and invalidate the delta base', async t => { const h = harness(t); await h.session.start(addresses); h.transport.hold = true; const write = h.transport.write.bind(h.transport); let release; const blocked = new Promise(resolve => { release = resolve; }); h.transport.write = async (...args) => { if (args[0] === 'L') await blocked; await write(...args); }; h.session.setFrame(new Uint8Array(640 * 480)); await h.session.pump(); await new Promise(resolve => setTimeout(resolve, 550)); assert.equal(h.session.state.phase, 'connected'); assert.equal(imageMessages(h.transport).length, 0); release(); await until(() => imageMessages(h.transport).length === 2); await tick(); for (let i = 1; i <= 4; i++) { h.session.cfwPending.forEach(p => p.deadline = 1); h.session.recoverCfw(); if (i < 4) await until(() => imageMessages(h.transport).length === 2 * (i + 1)); } assert.equal(h.session.state.phase, 'retrying'); assert.match(h.session.state.status, /retry limit/); assert.equal(h.session.lastEnqueued, null); assert.equal(h.session.cfwPending.length, 0); for (const sent of imageMessages(h.transport)) ack(h.transport, sent); await tick(); assert.equal(h.session.state.frames, 0); }); test('failed write poisons queued display work; disconnect cleanup uses the new SID', async t => { const h = harness(t); await h.session.start(addresses); const write = h.transport.write.bind(h.transport); let attempts = 0; h.transport.write = async (...args) => { if (args[0] === 'L') { attempts++; throw new Error('test write failed'); } await write(...args); }; h.session.setFrame(noisy()); await until(() => h.session.state.phase === 'retrying'); assert.equal(attempts, 1); assert.equal(h.session.displayInFlight, 0); await h.session.stop(); h.transport.write = write; await h.session.start(addresses); h.transport.hold = true; h.session.setFrame(noisy()); await until(() => imageMessages(h.transport).length === 3); const stale = imageMessages(h.transport); h.transport.hold = false; await h.session.stop(); stale.forEach(s => ack(h.transport, s)); await tick(); assert.equal(h.session.state.phase, 'disconnected'); assert.equal(h.session.state.frames, 0); assert.equal(h.transport.sent.at(-1).message.sid, p.SID.cfw); assert.deepEqual(h.transport.sent.at(-1).message.payload, new Uint8Array([11])); }); test('full display window still services input and microphone control', async t => { const h = harness(t); await h.session.start(addresses); h.transport.hold = true; h.session.setFrame(noisy()); await until(() => imageMessages(h.transport).length === 3); const input = p.bytes(13, p.bytes(3, p.concat(p.integer(1, 9), p.integer(2, 3)))); h.transport.emit({ kind: 'notification', identifier: 'R', characteristic: p.G2_NOTIFY, data: hex(p.concat(...p.frameMessage(input, p.SID.hub, 1, 22))) }); assert.equal(h.input.length, 1); const audio = [], enabling = h.session.setMicrophone(true, packet => audio.push(hex(packet))); await until(() => h.transport.sent.some(s => s.message.command === 15)); ack(h.transport, h.transport.sent.find(s => s.message.command === 15)); await enabling; h.transport.emit({ kind: 'notification', identifier: 'L', characteristic: p.G2_RENDER_NOTIFY, data: '010203' }); assert.deepEqual(audio, ['010203']); assert.equal(h.session.displayInFlight, 3); }); test('draw updates reconstruct moving and erased pixels while present gates frame completion', async t => { const {applyDisplayPayload}=require('./helpers/display-payload.cjs'); const h=harness(t);await h.session.start(addresses);h.transport.hold=true; const base=new Uint8Array(640*480),a=base.slice(),b=base.slice();a[11*640+13]=255;b[11*640+101]=160; let screen=new Uint8Array(320*480); for(const [i,frame] of [base,a,b,base].entries()) { h.session.setFrame(frame);await h.session.pump();await until(()=>imageMessages(h.transport).length===(i+1)*2); const [draw,present]=imageMessages(h.transport).slice(i*2); assert.equal(draw.message.payload[0],26);assert.equal(present.message.payload[0],28); screen=applyDisplayPayload(screen,draw.message.payload);assert.deepEqual(screen,p.packGray4(frame,640,480)); ack(h.transport,draw);await tick();assert.equal(h.session.state.frames,i); ack(h.transport,present);await until(()=>h.session.state.frames===i+1); } assert.equal(imageMessages(h.transport)[2].message.payload[7],0); // compact bbox }); test('reconnect reseeds the screen and unified draw calls carry no legacy frame id', async t => { const h=harness(t);await h.session.start(addresses); const submit=async gray=>{const before=h.session.state.frames;h.session.setFrame(gray);await until(()=>h.session.state.frames===before+1);return imageBody(imageMessages(h.transport).at(-2));}; const base=new Uint8Array(640*480),next=base.slice();next[1234]=255; assert.equal((await submit(base))[7],1); // wide full-screen bounds const delta=await submit(next);assert.equal(delta[7],0); // compact bbox, immediately followed by RLE const count=imageMessages(h.transport).length;h.session.setFrame(next);await h.session.pump();await tick();assert.equal(imageMessages(h.transport).length,count); await h.session.stop();await h.session.start(addresses);assert.equal((await submit(next))[7],1); }); const compassMessages = transport => transport.sent.filter(s => s.message.sid === p.SID.cfw && s.message.payload[0] === 10); const buzzerMessages = transport => transport.sent.filter(s => s.message.sid === p.SID.cfw && s.message.payload[0] === 5); const buzzerPayload = () => new Uint8Array([5, 4, 2, 0xb8, 0x0b, 25, 80, 0, 1, 0, 0, 20, 0]); test('buzzer snapshots the complete Android payload and waits for both lens ACKs without counting a frame', async t => { const h = harness(t); await h.session.playBuzzerSequence(buzzerPayload()); assert.equal(h.transport.sent.length, 0); await h.session.start(addresses); await h.session.playBuzzerSequence(new Uint8Array()); assert.equal(buzzerMessages(h.transport).length, 0); h.transport.hold = true; const payload = buzzerPayload(), expected = payload.slice(); let complete = false; const playing = h.session.playBuzzerSequence(payload).then(() => { complete = true; }); payload.fill(0); await until(() => buzzerMessages(h.transport).length === 1); const sent = buzzerMessages(h.transport)[0]; assert.equal(sent.id, 'L'); assert.deepEqual(sent.message.payload, expected); h.transport.ack(sent.id, sent.message, { lenses: [1] }); await tick(); assert.equal(complete, false); h.transport.ack(sent.id, sent.message, { lenses: [2] }); await playing; assert.equal(h.session.state.frames, 0); }); test('buzzer shares display compression and ACK recovery while the frame window is full', async t => { const h = harness(t); await h.session.start(addresses); h.transport.hold = true; h.session.setFrame(noisy()); await until(() => imageMessages(h.transport).length === 3); const playing = h.session.playBuzzerSequence(buzzerPayload()); await until(() => buzzerMessages(h.transport).length === 1); const sent = buzzerMessages(h.transport)[0]; h.transport.ack(sent.id, sent.message, { nack: true }); await until(() => buzzerMessages(h.transport).length === 2); const replay = buzzerMessages(h.transport)[1]; assert.notEqual(replay.message.magic, sent.message.magic); assert.deepEqual(replay.message.payload, buzzerPayload()); h.transport.hold = false; // Subsequent bands of the large frame can finish too. for (const item of h.transport.sent.filter(s => s.message.sid === p.SID.cfw).slice(-4)) ack(h.transport, item); await playing; assert.equal(h.session.state.phase, 'connected'); await until(() => h.session.state.frames === 1); }); test('disconnect cancels queued buzzer work and does not play it on reconnect', async t => { const h = harness(t); await h.session.start(addresses); h.transport.hold = true; const playing = h.session.playBuzzerSequence(buzzerPayload()); await until(() => buzzerMessages(h.transport).length === 1); h.transport.emit({ kind: 'disconnected', identifier: 'R' }); await playing; await h.session.playBuzzerSequence(buzzerPayload()); h.transport.hold = false; await h.session.start(addresses, true); assert.equal(buzzerMessages(h.transport).length, 1); }); test('compass desired state survives connecting and reconnecting; explicit stop disables it first', async t => { const h = harness(t); h.session.setCompassEnabled(true); await h.session.start(addresses); assert.equal(compassMessages(h.transport).length, 1); assert.equal(compassMessages(h.transport)[0].id, 'L'); assert.deepEqual([...compassMessages(h.transport)[0].message.payload], [10, 2, 100, 0, 0, 0]); await h.session.stop(); assert.deepEqual([...compassMessages(h.transport).at(-1).message.payload], [10, 0]); assert.equal(h.transport.sent.at(-1).message.payload[0], 11); await h.session.start(addresses); assert.equal(compassMessages(h.transport).at(-1).message.payload[1], 2); h.transport.emit({ kind: 'disconnected', identifier: 'R' }); assert.equal(h.session.state.phase, 'retrying'); await h.session.start(addresses, true); assert.equal(compassMessages(h.transport).at(-1).message.payload[1], 2); }); test('release during pending compass enable sends disable after the enable ACK', async t => { const h = harness(t); await h.session.start(addresses); assert.deepEqual([...compassMessages(h.transport)[0].message.payload], [10, 0]); h.transport.hold = true; h.session.setCompassEnabled(true); await until(() => h.transport.held.length === 1); h.session.setCompassEnabled(false); const enabling = h.transport.held.shift(); h.transport.hold = false; h.transport.ack(enabling.id, enabling.message); await until(() => compassMessages(h.transport).length === 3); assert.deepEqual(compassMessages(h.transport).map(s => s.message.payload[1]), [0, 2, 0]); }); test('compass notifications only come from the right arm and preserve diagnostics and calibration', async t => { const h = harness(t); await h.session.start(addresses); const payload = new Uint8Array(Buffer.from('080f1000520308e702a2060c434d010302038c0098badcfe', 'hex')); const emit = (id, sid = 8, flag = 1, body = payload) => h.transport.emit({ kind: 'notification', identifier: id, characteristic: p.G2_NOTIFY, data: hex(p.concat(...p.frameMessage(body, sid, flag, 20))) }); emit('L'); emit('other'); emit('R', 9); emit('R', 8, 0x20); assert.equal(h.compass.length, 0); emit('R'); emit('R', 8, 6, new Uint8Array([8, 16, 16, 0])); emit('R', 8, 1, new Uint8Array([8, 17, 16, 0])); assert.deepEqual(h.compass, [{ command: 15, headingDegrees: 359, diagnostics: { magneticAccuracy: 3, magneticAnomalies: 2, orientationSource: 3, flags: 140, sampleTimeMs: 0xfedcba98, } }, { command: 16, headingDegrees: -1 }, { command: 17, headingDegrees: -1 }]); }); test('wear detection matches Android wire format and queries both arms on every connection', async t => { const wear = require('../.test-build/app/g2/wear-protocol.js'); assert.equal(hex(wear.enableWearDetection(42)), '0801102a1a042a020801'); assert.equal(hex(wear.queryWearState()), '08011000aa0606464301070000'); const h = harness(t); await h.session.start(addresses); const queries = () => h.transport.sent.filter(({ message }) => hex(message.payload) === hex(wear.queryWearState())); assert.deepEqual(queries().map(q => q.id).sort(), ['L', 'R']); const enable = h.transport.sent.find(({ message }) => { const body = p.readBytes(message.payload, 3); return message.sid === p.SID.settings && message.command === 1 && body && p.readBytes(body, 5); }); assert.equal(enable.id, 'R'); assert.equal(enable.message.flag, 0x20); await h.session.stop(); await h.session.start(addresses); assert.equal(queries().length, 4); }); test('wear notifications validate the event and peer and work during initial connection', async t => { const h = harness(t); const payload = state => p.concat(p.integer(1, 3), p.bytes(5, p.concat(p.integer(1, 1), p.integer(2, state)))); const emit = (id, data, sid = 0x10) => h.transport.emit({ kind: 'notification', identifier: id, characteristic: p.G2_NOTIFY, data: hex(p.concat(...p.frameMessage(data, sid, 1, 12))) }); const originalWrite = h.transport.write.bind(h.transport); h.transport.write = async (...args) => { await originalWrite(...args); if (h.transport.sent.at(-1)?.message.magic === 0) emit(args[0], payload(0)); }; await h.session.start(addresses); assert.ok(h.wear.length >= 2); assert.ok(h.wear.every(value => value === false)); h.wear.length = 0; emit('stranger', payload(0)); emit('ring', payload(0)); emit('R', payload(2)); emit('R', payload(0), p.SID.hub); emit('R', p.integer(1, 3)); assert.deepEqual(h.wear, []); emit('L', payload(0)); emit('R', payload(1)); assert.deepEqual(h.wear, [false, true]); 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 = REQUIRED_FACECLAW_FIRMWARE_VERSION; 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.equal(h.session.state.phase, 'error'); assert.match(h.session.state.status, new RegExp(`requires revision ${REQUIRED_FACECLAW_FIRMWARE_VERSION}`)); 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 = REQUIRED_FACECLAW_FIRMWARE_VERSION; 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'); } }); test('brightness sends the Android settings payload to the right temple, including explicit zero and Auto', async () => { const transport = new FakeTransport(), session = new GlassesSession(transport, () => {}, () => {}); await session.setBrightness(50); assert.equal(transport.sent.length, 0, 'preview mode must not send Bluetooth commands'); const requests = []; session.state.phase = 'connected'; session.request = async (role, sid, build) => { requests.push({ role, sid, payload: hex(build(105)) }); }; await session.setBrightness(0); await session.setBrightness(80); await session.setBrightness(null); assert.deepEqual(requests, [ { role: 'right', sid: 9, payload: '080110691a060a0408001000' }, { role: 'right', sid: 9, payload: '080110691a060a0408001050' }, { role: 'right', sid: 9, payload: '080110691a040a020801' }, ]); });