Files
faceclaw/tests/ios-ble.test.cjs
T
2026-09-18 23:30:07 -07:00

514 lines
32 KiB
JavaScript

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);
});
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/${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);
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()) {
const states = [], input = [], compass = [];
const session = new GlassesSession(transport, state => states.push(state), event => input.push(event), undefined, undefined, event => compass.push(event));
t.after(async () => { transport.hold = false; await session.stop(); });
return { transport, session, states, input, compass };
}
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] === 6);
assert.equal(image.id, 'L');
assert.equal(image.message.payload[0], 6);
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);
// 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 === 1);
const sent = imageMessages(h.transport)[0];
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, 1);
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 === 8);
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('display pipelines A-B-A and coalesces newer waiting frames', async t => {
const h = harness(t); await h.session.start(addresses); h.transport.hold = true;
const submit = async value => { h.session.setFrame(new Uint8Array(640 * 480).fill(value)); await h.session.pump(); await tick(); };
await submit(0); await submit(0); assert.equal(imageMessages(h.transport).length, 1);
await submit(255); await submit(0); await until(() => imageMessages(h.transport).length === 3);
await submit(80); await submit(160);
const sent = imageMessages(h.transport);
ack(h.transport, sent[2]); ack(h.transport, sent[1]); await tick();
assert.equal(h.session.state.frames, 0); assert.equal(imageMessages(h.transport).length, 3);
ack(h.transport, sent[0]); await until(() => imageMessages(h.transport).length === 4);
assert.equal(h.session.state.frames, 3);
assert.deepEqual(imageBody(imageMessages(h.transport)[3]), p.concat(new Uint8Array([6]), p.rle4(p.packGray4(new Uint8Array(640 * 480).fill(160), 640, 480))));
ack(h.transport, imageMessages(h.transport)[3]); await until(() => h.session.state.frames === 4);
});
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(() => 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 === 1); 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 === 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('pipelined bounding boxes reconstruct moving and erased content against the last queued frame', 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;
const frames = [base, a, b];
for (let i = 0; i < frames.length; i++) {
h.session.setFrame(frames[i]); await h.session.pump();
await until(() => imageMessages(h.transport).length === i + 1);
}
const messages = imageMessages(h.transport), payloads = messages.map(m => imageBody(m));
assert.deepEqual(payloads.map(b => b[0]), [6, 3, 3]);
assert.deepEqual(payloads.slice(1).map(b => b[5] | (b[6] << 8)), [1, 2]);
assert.equal(h.session.state.frames, 0); // All three updates precede any ACK.
let shadow = new Uint8Array(320 * 480);
for (let i = 0; i < payloads.length; i++) {
shadow = applyDisplayPayload(shadow, payloads[i]);
assert.deepEqual(shadow, p.packGray4(frames[i], 640, 480));
}
// A late ACK for the old full frame must not replace the delta comparison base.
ack(h.transport, messages[0]); await until(() => h.session.state.frames === 1);
h.session.setFrame(base); await h.session.pump();
await until(() => imageMessages(h.transport).length === 4);
const clear = imageBody(imageMessages(h.transport)[3]);
assert.equal(clear[0], 3); assert.equal(clear[1], 25); // Only B's dot needs clearing.
assert.deepEqual(applyDisplayPayload(shadow, clear), p.packGray4(base, 640, 480));
for (const message of imageMessages(h.transport).slice(1)) ack(h.transport, message);
await until(() => h.session.state.frames === 4);
});
test('delta ids skip reserved values and advance only on emitted deltas; reconnect reseeds with a full frame', 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(-1));
};
const base = new Uint8Array(640 * 480), next = base.slice(); next[1234] = 255;
assert.equal((await submit(base))[0], 6);
h.session.nextImageFrameId = 0xfffe;
const delta = await submit(next); assert.equal(delta[5] | (delta[6] << 8), 0xfffe);
h.session.setFrame(next); await h.session.pump(); await tick();
assert.equal(h.session.nextImageFrameId, 1);
const full = await submit(new Uint8Array(640 * 480).fill(255)); assert.equal(full[0], 6);
assert.equal(h.session.nextImageFrameId, 1);
const clear = await submit(next); assert.equal(clear[0], 6); // Whole-screen bounding box.
const wrapped = await submit(base); assert.equal(wrapped[5] | (wrapped[6] << 8), 1);
await h.session.stop(); await h.session.start(addresses);
assert.equal((await submit(base))[0], 6); // Even the same pixels need a trusted full base.
});
const compassMessages = transport => transport.sent.filter(s => s.message.sid === p.SID.cfw && s.message.payload[0] === 10);
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 }]);
});