Refactor iOS version to use a bunch more shared code

This commit is contained in:
James Babcock committed 2026-09-22 21:26:51 -07:00
1 parent c3a0ba9f56
commit 4a194e37bb
40 files changed
+1874 -2605

No files matched your search

-66
View File
@@ -1,66 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { deflate } = require('pako');
const { buildBoundingBoxPayload: bbox } = require('../.test-build/app/g2/ble-image-optimizer.js');
const { applyDisplayPayload } = require('./helpers/display-payload.cjs');
const { rle4 } = require('../.test-build/app/g2/ble-protocol.js');
test('mode-3 payload matches the production Android encoder byte for byte', () => {
// Generated with javac from g2protocol/BleImageOptimizer.java, 2026-09-08.
const vectors = [
[0, 0, 0xab, '030000010134121a1b60'],
[319, 479, 0x12, '039fef01013412601112'],
[3, 5, 0xa5, '03010201013412601a15'],
];
for (const [x, y, value, expected] of vectors) {
const base = new Uint8Array(320 * 480), next = base.slice(); next[y * 320 + x] = value;
const payload = bbox(base, next, 640, 480, 0x1234);
assert.equal(Buffer.from(payload).toString('hex'), expected);
assert.deepEqual(applyDisplayPayload(base, payload), next);
}
});
test('bounding boxes include both nibbles, preserve neighboring pixels and cover all four screen edges', () => {
const base = Uint8Array.from({ length: 320 * 480 }, (_, i) => i & 255);
for (const x of [0, 1, 2, 3, 4, 637, 638, 639]) for (const y of [0, 1, 2, 477, 478, 479]) {
const next = base.slice(); next[y * 320 + (x >> 1)] ^= x % 2 ? 15 : 240;
const payload = bbox(base, next, 640, 480, 1);
assert.deepEqual([...payload.slice(1, 5)], [Math.floor(x / 4), Math.floor(y / 2), 1, 1]);
assert.deepEqual(applyDisplayPayload(base, payload), next);
}
});
test('unchanged, incompatible and full-screen boxes fall back without compressing a region', () => {
const base = new Uint8Array(320 * 480), next = base.slice(); next[0] = next[next.length - 1] = 255;
const compress = () => assert.fail('A fallback must not compress a bounding box');
assert.equal(bbox(base, base, 640, 480, 1, compress), null);
assert.equal(bbox(base, next, 640, 480, 1, compress), null);
assert.equal(bbox(null, next, 640, 480, 1, compress), null);
assert.equal(bbox(base.subarray(1), next, 640, 480, 1, compress), null);
assert.equal(bbox(base, next.subarray(1), 640, 480, 1, compress), null);
for (const [w, h] of [[0, 480], [639, 480], [640, 479], [1024, 480], [640, 512]])
assert.equal(bbox(base, next, w, h, 1, compress), null);
});
test('seeded sparse edits reconstruct exactly across successive bounding-box updates', () => {
let seed = 42;
const random = limit => { seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; return seed % limit; };
let base = Uint8Array.from({ length: 320 * 480 }, () => random(256));
for (let fid = 1; fid <= 60; fid++) {
const next = base.slice(), bx = random(280), by = random(440);
for (let n = 0; n < 20; n++) next[(by + random(40)) * 320 + bx + random(40)] ^= 0xff;
const payload = bbox(base, next, 640, 480, fid);
assert.ok(payload); assert.equal(payload[5] | (payload[6] << 8), fid);
assert.deepEqual(applyDisplayPayload(base, payload), next);
base = next;
}
});
test('a small edit encodes only its region on a busy screen', () => {
const base = Uint8Array.from({ length: 320 * 480 }, (_, i) => i & 255), next = base.slice();
next[100 * 320 + 100] ^= 255;
const payload = bbox(base, next, 640, 480, 1);
assert.ok(payload.length <= 15);
assert.ok(payload.length < (1 + rle4(next).length) / 10);
assert.deepEqual(applyDisplayPayload(base, payload), next);
});
-53
View File
@@ -1,53 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const { CfwTransport, parseCfwAcks } = require('../.test-build/app/g2/cfw-transport.js');
const { crc16, concat, MessageReceiver } = require('../.test-build/app/g2/ble-protocol.js');
const hex = value => Buffer.from(value).toString('hex');
test('iOS transport matches Android packets including persistent compression, reset, raw fallback and ATT limits', () => {
const random = new Uint8Array(65535); let seed = 42;
for (let i = 0; i < random.length; i++) { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; random[i] = seed & 255; }
const cases = [[100, 3, 185, new Uint8Array([6, 0, 0, 255, 255])],
[101, 3, 185, new Uint8Array([6, 0, 0, 255, 255])], [102, 1, 20, new Uint8Array(500).fill(42)],
'reset', [255, 3, 514, random], [103, 3, 240, new Uint8Array([11])]];
// Captured from the original Java encoder before migration; production now uses Kotlin.
const expected = require('./fixtures/cfw-java-golden.json');
const hash = value => require('node:crypto').createHash('sha256').update(value).digest('hex');
const transport = new CfwTransport(); let index = 0;
for (const c of cases) {
if (c === 'reset') { transport.reset(); continue; }
const [id, lenses, maxWrite, payload] = c, packets = transport.encode(payload, id, lenses, maxWrite);
assert.ok(packets.every(p => p.length <= maxWrite));
assert.equal(hash(packets.map(hex).join(' ')), expected[index++]);
}
});
function ackPacket(records, lens = 1, nack = false) {
const words = (id, ordinal, size, crc) => new Uint8Array([id, ordinal & 255, ordinal >>> 8, size & 255, size >>> 8, crc & 255, crc >>> 8]);
const first = words(...records[0]);
const body = concat(new Uint8Array([nack ? 3 : 1]), first.subarray(0, 3), new Uint8Array([lens]),
first.subarray(3), ...records.slice(1).map(r => words(...r)));
const crc = crc16(body);
return concat(new Uint8Array([0xaa, 0x12, 50, body.length + 2, 1, 1, 0xf0, 0]), body, new Uint8Array([crc & 255, crc >>> 8]));
}
test('redundant ACKs are validated atomically and survive split/coalesced notifications', () => {
const packet = ackPacket([[104, 0, 50, 123], [103, 0, 40, 321], [102, 0, 30, 222], [101, 0, 20, 111]], 2);
assert.deepEqual(parseCfwAcks(packet).map(a => [a.streamId, a.lens, a.size]), [[104, 2, 50], [103, 2, 40], [102, 2, 30], [101, 2, 20]]);
const receiver = new MessageReceiver();
assert.deepEqual(receiver.receive('L', packet.subarray(0, 6)), []);
const messages = receiver.receive('L', concat(packet.subarray(6), packet));
assert.equal(messages.length, 2); assert.deepEqual(parseCfwAcks(messages[0].packet), parseCfwAcks(packet));
for (let offset = 0; offset < packet.length; offset++) {
const corrupt = packet.slice(); corrupt[offset] ^= 1;
// Transport sequence byte is not covered by the ACK's CRC or identity.
if (offset !== 2) assert.equal(parseCfwAcks(corrupt), null, `offset ${offset}`);
}
assert.equal(parseCfwAcks(ackPacket([[104, 0, 50, 123]], 3)), null);
assert.equal(parseCfwAcks(ackPacket([[104, 0, 50, 123], [103, 0, 40, 321]], 1, true)), null);
assert.equal(parseCfwAcks(ackPacket([[104, 0, 0, 0]], 1, true))[0].nack, true);
});
+64 -41
View File
@@ -82,7 +82,7 @@ test('iOS host forwards hands-free capture mode to the voice bridge', async () =
const { IosPreviewController } = load('app/g2/ios-preview-controller.ts', { require: id => id === '../native/ios-voice-input'
? { iosVoiceInput: { startGlassesCapture: (_session, _log, endpointing) => captures.push(endpointing) } } : {} });
const host = Object.create(IosPreviewController.prototype);
host.session = { state: { phase: 'connected' } };
host.communicator = {}; host.state = { phase: 'connected' };
await host.startVoiceCapture(true);
await host.startVoiceCapture();
assert.deepEqual(captures, [true, false]);
@@ -207,22 +207,43 @@ test('settings-driven repaint runs after font cache invalidation, regardless of
test('background glasses input still composites frames; phone resume preserves the session; explicit stop stays stopped', async () => {
const tasks = new Map(), screenStates = [], inputs = [], frames = [], previews = [], states = [], sounds = [];
let nextTask = 0, starts = 0, stops = 0, pollStarts = 0, pollStops = 0, session;
let nextTask = 0, starts = 0, stops = 0, pollStarts = 0, pollStops = 0, bridge;
const window = { windowId: 'launcher', surfaceId: 'launcher', appId: 'launcher', title: 'Apps',
setScreenOn: on => screenStates.push(on), requestRender() {} };
const shell = { configure() {}, registerWindow() {}, wake() {}, focusWindow() {},
getWindows: () => [window], foregroundWindow: () => window, isScreenOn: () => true,
setBatteryLevels() {}, paintScene() { return new Uint8Array([0,0]); }, paintSurface() {}, underlayDim: () => 0, getFocus: () => 'app',
receiveInput: async input => { inputs.push(input); } };
class Session {
state = { phase: 'disconnected' };
constructor(_transport, onState, onInput) { session = this; this.onState = onState; this.onInput = onInput; }
async start() { starts++; this.state = { phase: 'connected' }; this.onState(this.state); }
async stop() { stops++; this.state = { phase: 'disconnected' }; this.onState(this.state); }
async setBrightness() {}
setFrame(pixels) { if (this.state.phase === 'connected') frames.push(pixels); }
playBuzzerSequence(payload) { sounds.push([...payload]); }
wake() {}
// The shared Kotlin session, as seen through the iOS bridge: frames reach it
// only while connected, callbacks come back on the JS thread.
const noop = () => () => {};
class FaceclawCommunicatorBridge {
phase = 'disconnected';
constructor() { bridge = this; }
onStateChange(fn) { this.stateListener = fn; return noop(); }
onRingEvent(fn) { this.ringListener = fn; return noop(); }
onBatteryState() { return noop(); } onFirmwareInfo() { return noop(); } onFrameMetrics() { return noop(); }
onWearState() { return noop(); } addCompassListener() { return noop(); } onAncsRelayFrame() { return noop(); }
onAncsAuthorization() { return noop(); } setRequiresAncs() {} rightWriteLimit() { return 20; } onPhoneLockSignal() {}
async writeRawToRight() {}
async start() { starts++; this.phase = 'connected'; this.stateListener({ phase: 'connected', status: 'Connected.' }); }
async disconnect() { stops++; this.phase = 'disconnected'; this.stateListener({ phase: 'disconnected', status: 'Disconnected.' }); }
async close() {}
async setBrightness() {} async enableWearDetectionAndRequestState() {}
async configureCompositorScreen() {} async configureSurface() {} async setUnderlayDim() {} async setSurfaceVisible() {}
async setScreenBlanked() {} async removeSurface() {}
async submitSurfaceFrame(_id, pixels) { if (this.phase === 'connected') frames.push(pixels); }
async submitShellScene(bytes) { if (this.phase === 'connected') frames.push(bytes); }
waitForFrameFinished() { return Promise.resolve('sent'); }
getCompositePreview() { return new Uint8Array([1, 2]); }
async playBuzzerSequence(payload) { sounds.push([...payload]); }
}
class PreviewDisplayTarget {
activate() {} release() {}
async configureCompositorScreen() {} async configureSurface() {} async setUnderlayDim() {} async setSurfaceVisible() {}
async setScreenBlanked() {} async removeSurface() {} async submitSurfaceFrame() {} async submitShellScene() {}
waitForFrameFinished() { return Promise.resolve('composited'); }
getCompositePreview() { return new Uint8Array([1, 2]); }
}
const settings = { brightnessSetting: { get: () => 'auto' }, brightnessSettingToLevel: () => null, lockScreenEnabledSetting: { get: () => true }, onAnySettingChanged: () => () => {}, previewColorSetting: { get: () => 'white' } };
const modules = {
@@ -238,22 +259,20 @@ test('background glasses input still composites frames; phone resume preserves t
'../native/compass.ios': { bindCompassSession() {}, receiveCompassEvent() {} },
'@nativescript/core': { File: { fromPath: () => ({ writeTextSync() {} }) }, knownFolders: { documents: () => ({ path: '/tmp' }) }, path },
'../native/ios-voice-input': { iosVoiceInput: { handleSessionEnded() {}, stopPhoneCapture() {} } },
'../native/ios-bluetooth': { iosBluetooth: () => ({}) }, './glasses-session': { GlassesSession: Session },
'../native/faceclaw-communicator.ios': { FaceclawCommunicatorBridge, resolveIosPeripherals: async addresses => addresses },
'../native/preview-display.ios': { PreviewDisplayTarget },
'./ancs-client': { ANCS_FIRMWARE_VERSION: 16, AncsClient: class { state = 'disconnected'; start() {} stop() {} stopCommand() { return new Uint8Array(); } receive() { return false; } } },
'../native/nightscout-bridge': { nightscoutBridge: { async start() { pollStarts++; }, async stop() { pollStops++; } } },
'./glance-host': { GlanceHost: class { dismiss() {} isVisible() { return false; } } },
'./device-addresses': { loadDeviceAddresses: () => ({}) }, './ios-peripheral-identity': { deviceAddressError: () => null },
'./glance-host': { GlanceHost: class { dismiss() {} reset() {} isVisible() { return false; } } },
'./device-addresses': { loadDeviceAddresses: () => ({ right: 'AA', left: 'BB', ring: '' }) }, './ios-peripheral-identity': { deviceAddressError: () => null },
'../apps/launcher/launcher-app': { createLauncherWindow: () => window, LAUNCHER_SURFACE_ID: 'launcher' },
'../apps/launcher': { launcherEntries: () => [] },
'../apps/all-apps': { ALL_APPS: [] }, '../ui/dashboard-settings': settings,
'../native/phone-battery': { readPhoneBatteryState: () => ({ battery: 80, charging: false }) },
'../graphics/surface-compositor': { SurfaceCompositor: class {
setShellScene() {} configureSurface() {} setSurfaceVisible() {} submitSurfaceFrame() {} setUnderlayDim() {} setScreenBlanked() {}
compositeFrame() { return { pixels: new Uint8Array([1, 2]) }; }
} },
'../graphics/plane': { flattenPlanesWithDraws: () => ({ image: { pixels: new Uint8Array([1, 2]), width: 2, height: 1 }, draws: [] }) },
'../graphics/plane': { flattenPlanesWithDraws: () => ({ image: { pixels: new Uint8Array([1, 2]), width: 2, height: 1 }, draws: [] }), planesFingerprint: () => 'fp' },
'../graphics/glyph-wire': { prepareFrameDraws: () => null },
'../native/texture-planner.ios': { IosTexturePlanner: class {} },
'../native/ios-graphics': { previewPixels: pixels => pixels },
'../graphics/image': { G2_LENS_WIDTH: 640, G2_LENS_HEIGHT: 480 },
'./lock-screen': { LOCK_SCREEN_SURFACE_ID: 'lock-screen', createLockScreenImage: () => ({ width: 1, height: 1, to8bppBuffer: () => new Uint8Array(1) }) },
'../ui/shell/shell': { shell, rawInputEventToInputEvent: input => input },
'../ui/shell/geometry': { appViewportRect: () => ({ x: 0, y: 0, width: 640, height: 480 }) },
pako: { deflate: x => x },
@@ -269,29 +288,32 @@ test('background glasses input still composites frames; phone resume preserves t
NSOperationQueue: { mainQueue: {} },
});
const flush = () => { for (const [id, fn] of [...tasks]) { if (tasks.delete(id)) fn(); } };
const settle = async () => { for (let i = 0; i < 4; i++) { flush(); await new Promise(resolve => setImmediate(resolve)); } };
const controller = new api.IosPreviewController(image => previews.push(image), assert.fail, state => states.push(state));
await controller.actions.playBuzzerSequence(new Uint8Array([5, 4, 0]));
assert.equal(sounds.length, 0);
controller.resume(); await controller.connect(); flush();
controller.resume(); await controller.connect(); await settle();
await controller.actions.playBuzzerSequence(new Uint8Array([5, 4, 0]));
assert.deepEqual(sounds, [[5, 4, 0]]);
const previewCount = previews.length, stateCount = states.length;
controller.pause(); controller.pause(); // NativeScript also unloads its root page on background entry.
assert.equal(stops, 0); assert.ok(screenStates.every(Boolean));
assert.equal(pollStarts, 1); assert.equal(pollStops, 0, 'connected glasses keep Nightscout polling in background');
session.onInput({ eventType: 3, eventSource: 1 });
await controller.inputQueue; flush();
assert.equal(inputs.length, 1); assert.ok(frames.length >= 2);
const frameCount = frames.length;
bridge.ringListener({ kind: 'sys-event', containerName: '', eventType: 3, eventSource: 1, systemExitReasonCode: 0, frameId: 0 });
await controller.inputQueue; await settle();
assert.equal(inputs.length, 1); assert.ok(frames.length > frameCount, 'background input still composites frames');
assert.equal(previews.length, previewCount); assert.equal(states.length, stateCount);
controller.resume(); flush();
controller.resume(); await settle();
assert.equal(starts, 1); assert.ok(previews.length > previewCount);
controller.pause(); await controller.disconnect(); flush();
controller.pause(); await controller.disconnect(); await settle();
assert.equal(stops, 1); assert.equal(screenStates.at(-1), false);
assert.equal(pollStops, 1);
const frameCount = frames.length;
session.onInput({ eventType: 3, eventSource: 1 }); await controller.inputQueue; flush();
assert.equal(inputs.length, 1); assert.equal(frames.length, frameCount);
controller.resume(); flush();
const stoppedFrames = frames.length;
bridge.ringListener({ kind: 'sys-event', containerName: '', eventType: 3, eventSource: 1, systemExitReasonCode: 0, frameId: 0 });
await controller.inputQueue; await settle();
assert.equal(inputs.length, 1); assert.equal(frames.length, stoppedFrames);
controller.resume(); await settle();
assert.equal(starts, 1); assert.equal(controller.connectionState.phase, 'disconnected');
assert.equal(pollStarts, 2, 'resuming the phone restarts Nightscout polling');
});
@@ -368,21 +390,22 @@ test('iOS configures an in-process surface before submitting constructor-trigger
require: name => ({
'../ui/shell/shell': { shell },
'../ui/shell/geometry': { appViewportRect: () => ({ x: 0, y: 0, width: 2, height: 1 }) },
'../graphics/plane': { flattenPlanesWithDraws: planes => ({ image: planes[0], draws: [] }) },
'../graphics/plane': { flattenPlanesWithDraws: planes => ({ image: planes[0], draws: [] }), planesFingerprint: () => 'fp' },
'../graphics/glyph-wire': { prepareFrameDraws: () => null },
})[name] ?? {},
console,
});
// Exercise the real launch method with a strict compositor boundary. App
// Exercise the real launch method with a strict display boundary. App
// construction paints synchronously, as Nightscout's tray subscription does.
const controller = Object.create(api.IosPreviewController.prototype);
controller.inProcessApps = new Map();
controller.requestShellRender = () => {};
controller.scheduleFrame = () => {};
controller.compositor = {
configureSurface(id) { surfaces.add(id); }, setSurfaceVisible() {},
removeSurface(id) { surfaces.delete(id); },
submitSurfaceFrame(id, pixels) { assert.ok(surfaces.has(id), `unconfigured ${id}`); submitted.push([...pixels]); },
controller.schedulePreviewUpdate = () => {};
controller.communicator = null;
controller.previewTarget = {
async configureSurface(id) { surfaces.add(id); }, async setSurfaceVisible() {},
async removeSurface(id) { surfaces.delete(id); },
async submitSurfaceFrame(id, pixels) { assert.ok(surfaces.has(id), `unconfigured ${id}`); submitted.push([...pixels]); },
};
let plumbing, early;
const fresh = [{ pixels: new Uint8Array([30, 40]), width: 2, height: 1 }];
@@ -453,14 +476,14 @@ test('iOS preview voice uses the phone microphone, while connected capture stays
require: id => id === '../native/ios-voice-input' ? { iosVoiceInput: bridge } : {},
});
const host = Object.create(IosPreviewController.prototype);
host.active = true; host.glassesLocked = false;
host.active = true; host.glassesLocked = false; host.communicator = null; host.state = { phase: 'disconnected' };
assert.equal(await host.prepareVoiceCapture(), true);
await host.startVoiceCapture(true);
assert.deepEqual(calls, [['prepare', true, true], ['prepare', true, true], ['phone', true]]);
calls.length = 0; host.session = { state: { phase: 'connected' } };
calls.length = 0; host.communicator = {}; host.state = { phase: 'connected' };
assert.equal(await host.prepareVoiceCapture(), true); await host.startVoiceCapture(false);
assert.deepEqual(calls, [['prepare', true, false], ['glasses', false]]);
calls.length = 0; host.active = false; host.session = null;
calls.length = 0; host.active = false; host.communicator = null; host.state = { phase: 'disconnected' };
assert.equal(await host.prepareVoiceCapture(), false); await host.startVoiceCapture();
assert.deepEqual(calls, []);
});
+18 -14
View File
@@ -77,23 +77,27 @@ for (const provider of ['openai', 'anthropic']) {
});
}
test('iOS SSE adapter invokes listeners on its polling thread and stops polling at cancellation/EOF', () => {
const timers = new Set(), instances = [], seen = [];
test('iOS SSE adapter forwards the Kotlin stream events once and stops after cancellation/EOF', () => {
const instances = [], seen = [];
const nsObject = { extend: methods => ({ new: () => ({ ...methods }) }) };
const listenerModule = loader({ NSObject: nsObject }, {})('app/native/kotlin-listener.ios.ts');
const api = loader({
setInterval: fn => { timers.add(fn); return fn; }, clearInterval: fn => timers.delete(fn),
FaceclawSseRequest: { alloc: () => ({ initWithURLBodyHeaders(url, body, headers) {
const instance = { events: [], cancelled: false, takeEvents() { const events = this.events; this.events = []; return JSON.stringify(events); }, cancel() { this.cancelled = true; } };
instances.push(instance); assert.equal(JSON.parse(headers)['User-Agent'], 'fixture'); return instance;
} }) },
}, { '../util/http': { withUserAgent: headers => ({ ...headers, 'User-Agent': 'fixture' }) } })('app/native/sse.ios.ts');
const listener = { onLine: line => seen.push(line), onComplete: () => seen.push('complete'), onHttpError() {}, onFailure: error => assert.fail(error) };
FaceclawKitIosSseRequest: { alloc: () => ({ initWithUrlBodyHeadersJsonListener(url, body, headers, listener) {
const instance = { listener, cancelled: false, cancel() { this.cancelled = true; } };
instances.push(instance); assert.equal(JSON.parse(headers)['User-Agent'], 'fixture'); assert.equal(url, 'https://fixture'); return instance;
} }) }, FaceclawKitFaceclawSseListener: {},
}, { '../util/http': { withUserAgent: headers => ({ ...headers, 'User-Agent': 'fixture' }) }, './kotlin-listener.ios': listenerModule })('app/native/sse.ios.ts');
const listener = { onLine: line => seen.push(line), onComplete: () => seen.push('complete'), onHttpError: (code, body) => seen.push(`http:${code}:${body}`), onFailure: error => seen.push(`fail:${error}`) };
const handle = api.openSseRequest('https://fixture', '{}', {}, listener);
instances[0].events.push({ kind: 'line', text: 'first' }); assert.deepEqual(seen, []);
for (const tick of timers) tick(); assert.deepEqual(seen, ['first']);
handle.cancel(); assert.equal(timers.size, 0); assert.equal(instances[0].cancelled, true);
instances[0].listener.onLineLine('first'); assert.deepEqual(seen, ['first']);
handle.cancel(); handle.cancel(); assert.equal(instances[0].cancelled, true);
instances[0].listener.onLineLine('after cancel'); instances[0].listener.onComplete(); assert.deepEqual(seen, ['first']);
api.openSseRequest('https://fixture', '{}', {}, listener);
instances[1].events.push({ kind: 'line', text: 'last' }, { kind: 'complete' });
for (const tick of [...timers]) tick(); assert.deepEqual(seen, ['first', 'last', 'complete']); assert.equal(timers.size, 0);
instances[1].listener.onLineLine('last'); instances[1].listener.onComplete(); instances[1].listener.onFailureMessage_('late');
assert.deepEqual(seen, ['first', 'last', 'complete']);
api.openSseRequest('https://fixture', '{}', {}, listener);
instances[2].listener.onHttpErrorCodeBody(429, 'slow down'); instances[2].listener.onComplete();
assert.deepEqual(seen.at(-1), 'http:429:slow down');
});
test('iOS only offers cloud assistant models and preserves old local-model conversations as Auto', () => {
-751
View File
@@ -1,751 +0,0 @@
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' },
]);
});
+73 -43
View File
@@ -6,7 +6,6 @@ const vm = require('node:vm');
const ts = require('typescript');
const images = require('../.test-build/app/graphics/image.js');
const { SurfaceCompositor } = require('../.test-build/app/graphics/surface-compositor.js');
const protocol = require('../.test-build/app/g2/ble-protocol.js');
const events = require('../.test-build/app/g2/events.js');
function load(file, modules, globals = {}) {
@@ -24,8 +23,8 @@ const timings = load('app/native/frame-timings.ts', {});
function fixture() {
const observers = new Map(), phoneState = { protectedDataAvailable: true };
let settingsChanged, remoteHost;
let now = 1000, nextTask = 0, screenOn = true, shellOptions, session;
let settingsChanged, remoteHost, controller, bridge = null;
let now = 1000, nextTask = 0, screenOn = true, shellOptions;
const tasks = new Map(), sent = [], previews = [], received = [], errors = [];
const boardStats = { starts: 0, stops: 0, paints: 0 };
const settings = { lock: true, enabled: true, tap: true, hold: true, tilt: true, duration: 3000 };
@@ -39,8 +38,10 @@ function fixture() {
'../util/render-freshness': { beginRenderPass() {}, endRenderPass: () => false },
'./glance-state': require('../.test-build/app/g2/glance-state.js'),
}, clock);
const launcherPixels = new Uint8Array(640 * 480).fill(75), fullRect = { x: 0, y: 0, width: 640, height: 480 };
const window = { windowId: 'launcher', surfaceId: 'launcher', appId: 'launcher', title: 'Apps',
requestRender() {}, setScreenOn() {} };
// The launcher repaints into whichever display target the controller has after a switch.
requestRender() { void controller?.displayReady.then(() => controller.display?.submitSurfaceFrame('launcher', launcherPixels, fullRect, 'launcher')); }, setScreenOn() {} };
const shell = {
configure: options => { shellOptions = options; }, registerWindow() {}, focusWindow() {},
wake: () => { screenOn = true; shellOptions.onScreenStateChanged(true); },
@@ -54,15 +55,43 @@ function fixture() {
if (input.type === 'display-wake' || !screenOn && input.type === 'double-click') shell.wake();
},
};
class Session {
state = { phase: 'disconnected' };
constructor(_transport, onState, onInput, _log, _activity, _compass, onWear) { session = this; this.onState = onState; this.onInput = onInput; this.onWear = onWear; }
async enableWearDetectionAndRequestState() {}
async start() { this.state = { phase: 'connected' }; this.onState(this.state); }
async stop() { this.state = { phase: 'disconnected' }; this.onState(this.state); }
async setBrightness() {}
setFrame(pixels) { if (this.state.phase === 'connected') sent.push(pixels); }
wake() {}
// Both display targets compose with the real (TypeScript reference) compositor so
// the pixel assertions below exercise real layering, blanking and lock surfaces.
class Display {
compositor = new SurfaceCompositor(640, 480);
async configureCompositorScreen() {}
async configureSurface(id, options) { this.compositor.configureSurface(id, options); }
async removeSurface(id) { this.compositor.removeSurface(id); this.changed(); }
async setSurfaceVisible(id, visible) { this.compositor.setSurfaceVisible(id, visible); this.changed(); }
async setUnderlayDim(below, factor) { this.compositor.setUnderlayDim(below, factor); this.changed(); }
async setScreenBlanked(blanked) { this.compositor.setScreenBlanked(blanked); this.changed(); }
async submitSurfaceFrame(id, pixels, rect, _fingerprint, _paintMs, _frameId, draws = null) { this.compositor.submitSurfaceFrame(id, pixels, rect, draws); this.changed(); }
async submitShellScene(bytes) { this.compositor.setShellScene(bytes); this.changed(); }
getCompositePreview() { return this.compositor.composite(); }
changed() {}
}
class PreviewDisplayTarget extends Display {
activate(fn) { this.onFrame = fn; } release() { this.onFrame = null; }
changed() { this.onFrame?.(); }
waitForFrameFinished() { return Promise.resolve('composited'); }
}
const noop = () => () => {};
class FaceclawCommunicatorBridge extends Display {
phase = 'disconnected'; listeners = {};
constructor() { super(); bridge = this; }
on(kind, fn) { this.listeners[kind] = fn; return () => { if (this.listeners[kind] === fn) delete this.listeners[kind]; }; }
onStateChange(fn) { return this.on('state', fn); } onRingEvent(fn) { return this.on('ring', fn); }
onWearState(fn) { return this.on('wear', fn); } onBatteryState() { return noop(); } onFirmwareInfo() { return noop(); }
onFrameMetrics() { return noop(); } addCompassListener() { return noop(); } onAncsRelayFrame() { return noop(); }
onAncsAuthorization() { return noop(); } setRequiresAncs() {} rightWriteLimit() { return 20; } onPhoneLockSignal() {}
async writeRawToRight() {} async setBrightness() {} async enableWearDetectionAndRequestState() {} async playBuzzerSequence() {} async close() {}
emitState(phase, status = phase) { if (phase === 'connected' || phase === 'disconnected') this.phase = phase; this.listeners.state?.({ phase, status }); }
emitRing(input) { this.listeners.ring?.(input); }
emitWear(wearing) { this.listeners.wear?.(wearing); }
async start() { this.emitState('connected', 'Connected.'); }
async disconnect() { this.emitState('disconnected', 'Disconnected.'); }
waitForFrameFinished() { return Promise.resolve('sent'); }
changed() { if (this.phase === 'connected') sent.push(this.compositor.composite()); }
}
const provider = {
isEnabled: () => settings.enabled, showOnTap: () => settings.tap,
@@ -85,13 +114,14 @@ function fixture() {
"../native/compass.ios": { bindCompassSession() {}, receiveCompassEvent() {} },
'@nativescript/core': { File: { fromPath: () => ({ writeTextSync() {} }) },
knownFolders: { documents: () => ({ path: '/tmp' }) }, path },
'../native/ios-bluetooth': { iosBluetooth: () => ({}) },
'../native/ios-voice-input': { iosVoiceInput: { handleSessionEnded() {}, stopPhoneCapture() {} } },
'./glasses-session': { GlassesSession: Session },
'../native/faceclaw-communicator.ios': { FaceclawCommunicatorBridge, resolveIosPeripherals: async addresses => addresses },
'../native/preview-display.ios': { PreviewDisplayTarget },
'./ancs-client': { ANCS_FIRMWARE_VERSION: 16, AncsClient: class { state = 'disconnected'; start() {} stop() {} stopCommand() { return new Uint8Array(); } receive() { return false; } } },
'../native/nightscout-bridge': { nightscoutBridge: { async start() {}, async stop() {} } },
'./glance-host': { GlanceHost }, './events': events,
'./lock-screen': { LOCK_SCREEN_SURFACE_ID: 'lock-screen', createLockScreenImage: () => new images.GrayImage(640, 480, 123) },
'./device-addresses': { loadDeviceAddresses: () => ({}) }, './ios-peripheral-identity': { deviceAddressError: () => null },
'./device-addresses': { loadDeviceAddresses: () => ({ right: 'AA', left: 'BB', ring: '' }) }, './ios-peripheral-identity': { deviceAddressError: () => null },
'../apps/launcher': { launcherEntries: () => [] },
'../apps/evenhub/installed-apps': {}, '../apps/evenhub/manager': {}, '../apps/evenhub/updates': {}, '../apps/evenhub': {},
'../apps/launcher/launcher-app': { createLauncherWindow: () => window, LAUNCHER_SURFACE_ID: 'launcher' },
@@ -103,9 +133,7 @@ function fixture() {
'../native/phone-battery': { readPhoneBatteryState: () => ({ battery: 80, charging: false }) },
'../apps/ios-availability': { iosAppUnavailableReason: () => null },
'../graphics/glyph-wire': { prepareFrameDraws: () => null },
'../native/texture-planner.ios': { IosTexturePlanner: class {} },
'../graphics/surface-compositor': { SurfaceCompositor }, '../graphics/plane': planes, '../graphics/image': images,
'../native/ios-graphics': { previewPixels: pixels => pixels },
'../graphics/plane': planes, '../graphics/image': images,
'../ui/gestures': { makeInputEvent: event => event }, '../ui/layers': { noopLayerActions: {} },
'../apps/files/text-viewer': {},
'../ui/shell/shell': { shell, rawInputEventToInputEvent: event => ({
@@ -124,8 +152,8 @@ function fixture() {
NSNotificationCenter: { defaultCenter: { addObserverForNameObjectQueueUsingBlock(name, _object, _queue, fn) { observers.set(name, fn); return name; }, removeObserver(name) { observers.delete(name); } } },
NSOperationQueue: { mainQueue: {} },
});
const controller = new IosPreviewController((pixels, title) => previews.push({ pixels, title }), message => errors.push(message));
controller.compositor.submitSurfaceFrame('launcher', new Uint8Array(640 * 480).fill(75), { x: 0, y: 0, width: 640, height: 480 });
controller = new IosPreviewController((pixels, title) => previews.push({ pixels, title }), message => errors.push(message));
window.requestRender();
controller.resume();
async function drain() { await controller.inputQueue; await controller.glance.queue; }
async function advance(ms) {
@@ -133,16 +161,18 @@ function fixture() {
for (const [id, task] of [...tasks]) if (task.at <= now && tasks.delete(id)) task.fn();
await drain();
}
async function render() { await drain(); await advance(33); assert.deepEqual(errors, []); }
async function render() { await drain(); await advance(33); await drain(); assert.deepEqual(errors, []); }
async function hardware(type, source = 2, ringTick) {
const payload = protocol.bytes(13, protocol.bytes(3, protocol.concat(protocol.integer(1, type), protocol.integer(2, source))));
const input = protocol.decodeGlassesInput({ sid: protocol.SID.hub, flag: 1, payload });
if (ringTick !== undefined) input.ringInput = { type: type === 3 ? 2 : 1, tick: ringTick, aux:0, speed:0 };
session.onInput(input);
const input = { kind: type === 12 ? 'display-wake' : 'sys-event', containerName: '', eventType: type, eventSource: source,
systemExitReasonCode: 0, frameId: 0 };
if (ringTick !== undefined) input.ringInput = { type: type === 3 ? 2 : 1, tick: ringTick, aux: 0, speed: 0 };
bridge.emitRing(input);
await render();
}
async function phone(type, origin = 'ring') { controller.gesture(type, origin); await render(); }
return { controller, shell, remoteHost, keyboardChanged: session => shellOptions.onKeyboardInputChanged(session), settings, phoneState, observers, wear: wearing => session.onWear(wearing), settingsChanged: () => settingsChanged(), sent, previews, received, boardStats, hardware, phone, advance, render };
async function connect() { await controller.connect(); await render(); }
return { controller, shell, remoteHost, keyboardChanged: session => shellOptions.onKeyboardInputChanged(session), settings, phoneState, observers,
get bridge() { return bridge; }, connect, wear: wearing => bridge.emitWear(wearing), settingsChanged: () => settingsChanged(), sent, previews, received, boardStats, hardware, phone, advance, render };
}
const assertBlank = pixels => assert.ok(pixels.every(p => p === 0));
const assertBoard = pixels => {
@@ -151,7 +181,7 @@ const assertBoard = pixels => {
};
test('iOS sleep tap shows the shared board; repeated tap renews timeout and hides to black', async () => {
const f = fixture(); await f.controller.connect(); f.shell.sleep(); await f.render();
const f = fixture(); await f.connect(); f.shell.sleep(); await f.render();
assertBlank(f.sent.at(-1));
await f.hardware(0); assertBoard(f.sent.at(-1)); assert.equal(f.shell.isScreenOn(), false);
assert.equal(f.previews.at(-1).title, 'Glanceboard'); assert.equal(f.received.length, 0);
@@ -165,7 +195,7 @@ test('iOS sleep tap shows the shared board; repeated tap renews timeout and hide
});
test('iOS holds and tap-then-holds last until release, including with phone backgrounded', async () => {
const f = fixture(); await f.controller.connect(); f.shell.sleep(); f.controller.pause();
const f = fixture(); await f.connect(); f.shell.sleep(); f.controller.pause();
const previews = f.previews.length;
for (const type of [9, 11]) {
await f.hardware(type, 1); assertBoard(f.sent.at(-1));
@@ -176,7 +206,7 @@ test('iOS holds and tap-then-holds last until release, including with phone back
});
test('double-tap and other shell wakes replace Glanceboard without waking it again', async () => {
const f = fixture(); await f.controller.connect(); f.shell.sleep();
const f = fixture(); await f.connect(); f.shell.sleep();
await f.hardware(9); await f.hardware(3);
assert.equal(f.shell.isScreenOn(), true); assert.equal(f.controller.glance.isVisible(), false);
assert.equal(f.sent.at(-1)[0], 80); assert.equal(f.boardStats.stops, 1);
@@ -186,14 +216,14 @@ test('double-tap and other shell wakes replace Glanceboard without waking it aga
});
test('head tilt uses Glanceboard when enabled and otherwise wakes the regular UI', async () => {
const f = fixture(); await f.controller.connect(); f.shell.sleep();
const f = fixture(); await f.connect(); f.shell.sleep();
await f.hardware(12, 1); assertBoard(f.sent.at(-1)); assert.equal(f.shell.isScreenOn(), false);
await f.hardware(3); f.shell.sleep(); f.settings.tilt = false;
await f.hardware(12, 1); assert.equal(f.shell.isScreenOn(), true); assert.equal(f.sent.at(-1)[0], 80);
});
test('disabled triggers and scrolls do not show the board; awake taps still reach the shell', async () => {
const f = fixture(); await f.controller.connect();
const f = fixture(); await f.connect();
await f.hardware(0); assert.equal(f.received.at(-1).type, 'click'); assert.equal(f.boardStats.starts, 0);
f.shell.sleep(); f.settings.tap = false; f.settings.hold = false;
for (const type of [0, 9, 11, 10, 1, 2]) await f.hardware(type);
@@ -218,7 +248,7 @@ test('phone preview gestures use Glanceboard; losing runtime cleans up holds and
test('iOS lock hides apps and Glanceboard, blocks input, and stays locked when put back on', async () => {
const f = fixture(); await f.controller.connect(); f.shell.sleep(); await f.hardware(0);
const f = fixture(); await f.connect(); f.shell.sleep(); await f.hardware(0);
f.controller.pause();
// The notification precedes the property change: do not immediately undo it.
f.observers.get('lock')(); f.wear(false); await f.render();
@@ -239,7 +269,7 @@ test('iOS lock hides apps and Glanceboard, blocks input, and stays locked when p
});
test('iOS removal before phone lock, setting changes, and observer lifetime', async () => {
const f = fixture(); await f.controller.connect(); f.wear(false); await f.render();
const f = fixture(); await f.connect(); f.wear(false); await f.render();
assert.equal(f.controller.glassesLocked, false);
f.observers.get('lock')(); await f.render();
assert.equal(f.controller.glassesLocked, true);
@@ -255,7 +285,7 @@ test('iOS removal before phone lock, setting changes, and observer lifetime', as
});
test('iOS wear notifications catch protected-data changes missed while suspended', async () => {
const f = fixture(); await f.controller.connect(); f.controller.pause();
const f = fixture(); await f.connect(); f.controller.pause();
f.phoneState.protectedDataAvailable = false; f.wear(false); await f.render();
assert.equal(f.controller.glassesLocked, true);
f.controller.resume(); await f.render();
@@ -267,7 +297,7 @@ test('iOS wear notifications catch protected-data changes missed while suspended
test('iOS locked phone controls cannot dispatch mirror, voice, or keyboard input', async () => {
const f = fixture(); await f.controller.connect(); f.wear(false);
const f = fixture(); await f.connect(); f.wear(false);
f.observers.get('lock')(); await f.render();
await f.phone('tap', 'mirror'); await f.phone('long-press', 'watch');
f.controller.startVoiceInput();
@@ -276,16 +306,16 @@ test('iOS locked phone controls cannot dispatch mirror, voice, or keyboard input
assert.equal(f.received.length, 0);
assert.equal(f.controller.glassesLocked, true);
// Locked state also survives transport recovery until a phone unlock.
f.controller.session.onState({ phase: 'retrying' });
f.controller.session.onState({ phase: 'connecting' });
f.controller.session.onState({ phase: 'connected' });
f.bridge.emitState('retrying');
f.bridge.emitState('connecting');
f.bridge.emitState('connected');
await f.render();
assert.ok(f.sent.at(-1).every(p => p === 123));
});
test('iOS deduplicates original ring ticks before apps, lock toggles and Glanceboard', async () => {
const f = fixture(); await f.controller.connect();
const f = fixture(); await f.connect();
await f.hardware(0,2,1000); await f.hardware(0,2,1050);
assert.equal(f.received.length,1);
await f.hardware(0,2,1100); assert.equal(f.received.length,2);
@@ -299,8 +329,8 @@ test('iOS deduplicates original ring ticks before apps, lock toggles and Glanceb
assert.equal(f.shell.isScreenOn(),true);
await f.hardware(3,2,2050); assert.equal(f.shell.isScreenOn(),true);
// A new transport session starts a fresh suppression window.
f.controller.session.onState({ phase:'retrying' });
f.controller.session.onState({ phase:'connected' });
f.bridge.emitState('retrying');
f.bridge.emitState('connected');
await f.hardware(3,2,2051); assert.equal(f.shell.isScreenOn(),false);
});
@@ -325,7 +355,7 @@ test('keyboard sessions cannot deliver text after the glasses lock or phone leav
test('external input shares iOS dispatch, including hold release and phone-lock gating', async () => {
const f = fixture(); await f.controller.connect(); f.wear(false);
const f = fixture(); await f.connect(); f.wear(false);
assert.equal(f.remoteHost.ready(), true);
assert.equal(f.remoteHost.locked(), false);
await f.remoteHost.input('swipe-left', 'watch');
+100 -71
View File
@@ -13,78 +13,110 @@ function load(file, modules = {}, globals = {}) {
return context.exports;
}
const flush = () => new Promise(resolve => setImmediate(resolve));
function flasherFixture({ hash = 'custom', failRole = '', backgroundRole = '' } = {}) {
const calls = [], events = new Map(), native = { idleTimerDisabled: false, applicationState: 0 };
const settle = async (rounds = 6) => { for (let i = 0; i < rounds; i++) { await flush(); await new Promise(resolve => setTimeout(resolve, 0)); } };
// The Kotlin facades (FaceclawKitIos*) deliver listener callbacks on the main queue; the
// fakes call the TypeScript listener object directly. NSObject.extend is how the wrappers
// implement Kotlin listener protocols.
const nsObject = { extend: methods => ({ new: () => ({ ...methods }) }) };
function bluetooth(identifiers = { right: 'R-ID', left: 'L-ID' }, fail = null) {
return { iosBluetooth: () => ({ resolveDevices: async addresses => {
if (fail) throw new Error(fail);
return Object.fromEntries(Object.entries(identifiers).filter(([role]) => addresses[role]));
} }) };
}
function flasherFixture({ hash = 'custom', outcome = 'success', backgroundOn = '', resolveError = null } = {}) {
const calls = [], events = new Map(), native = { idleTimerDisabled: false, applicationState: 0 }, instances = [];
const app = { suspendEvent: 'suspend', on: (e, cb) => events.set(e, cb), off: e => events.delete(e) };
class Link {
closed = false;
check() { if (this.closed) throw new Error('Cancelled'); }
async resolve() { calls.push('resolve'); }
async connect(role, ota) { this.check(); calls.push(`connect:${role}:${ota}`); }
async authenticate(role) { this.check(); calls.push(`auth:${role}`); }
disconnect(role) { calls.push(`disconnect:${role}`); }
close() { this.closed = true; calls.push('close'); }
}
const FaceclawKitIosFirmwareFlasher = { alloc: () => ({ initWithRightAddressLeftAddressFirmwarePath(right, left, path) {
const flasher = { listener: null, cancelled: false, closed: false,
setListenerListener(listener) { this.listener = listener; },
start() {
calls.push(`start:${right}:${left}:${path}`);
setTimeout(() => {
for (const lens of ['left', 'right']) {
if (this.cancelled) break;
this.listener.onStateStateDetail('connecting', lens); this.listener.onStateStateDetail('flashing', lens);
this.listener.onProgressLensComponentIndexComponentCountBlockIndexBlockCountBytesSentBytesTotal(lens, 1, 1, 1, 1, 16, 16);
if (lens === backgroundOn) events.get('suspend')();
if (outcome === 'fail' && lens === 'right') { this.listener.onCompleteSuccessDetail(false, 'END rejected'); return; }
}
if (this.cancelled) { this.listener.onCompleteSuccessDetail(false, 'Cancelled. Retry with both lenses powered on to complete installation.'); return; }
this.listener.onStateStateDetail('done', 'Both lenses flashed. Your glasses are rebooting.');
this.listener.onCompleteSuccessDetail(true, 'Both lenses flashed. Your glasses are rebooting.');
}, 0);
},
cancel() { this.cancelled = true; calls.push('cancel'); }, close() { this.closed = true; calls.push('close'); } };
instances.push(flasher); return flasher;
} }) };
const { FirmwareFlasher } = load('app/native/firmware-flasher.ios.ts', {
'@nativescript/core': { Application: app }, '../g2/stock-connection': { StockConnection: Link },
'@nativescript/core': { Application: app },
'../g2/firmware/cfw-patches': { CFW_PATCH_SET: { outputSha256: 'custom', baseSha256: 'stock' } },
'./firmware-files.ios': { readFirmwareFile: () => new Uint8Array(16), firmwareSha256: () => hash },
'./ios-bluetooth': { iosBluetooth: () => ({}) },
'../g2/firmware-ota': { validateFirmware: () => { calls.push('validate'); return []; },
flashLensImage: async (link, role) => {
calls.push(`flash:${role}`);
if (role === backgroundRole) events.get('suspend')();
link.check();
if (role === failRole) throw new Error('END rejected');
} },
}, { UIApplication: { sharedApplication: native }, UIApplicationState: { Active: 0 },
setTimeout: fn => setTimeout(fn, 0) });
'./ios-bluetooth': bluetooth({ right: 'R-ID', left: 'L-ID' }, resolveError), './kotlin-listener.ios': listenerModule,
}, { UIApplication: { sharedApplication: native }, UIApplicationState: { Active: 0 }, FaceclawKitIosFirmwareFlasher, FaceclawKitFaceclawFirmwareFlasherListener: {} });
const flasher = new FirmwareFlasher({ right: 'r', left: 'l' }, 'prepared.bin');
const states = [], progress = [];
flasher.onStateChange((state, detail) => states.push(`${state}:${detail}`)); flasher.onProgress(value => progress.push(value.lens));
const result = new Promise(resolve => flasher.onComplete((success, detail) => resolve({ success, detail })));
return { calls, events, native, flasher, result };
return { calls, events, native, flasher, result, instances, states, progress };
}
const listenerModule = load('app/native/kotlin-listener.ios.ts', {}, { NSObject: nsObject });
test('iOS flashing authenticates and verifies both lenses in order before reporting success', async () => {
test('iOS flashing checks the image hash, resolves identifiers, runs the Kotlin OTA flow and reports success', async () => {
for (const hash of ['custom', 'stock']) {
const f = flasherFixture({ hash }); f.flasher.start(); f.flasher.start();
assert.equal((await f.result).success, true);
assert.deepEqual(f.calls, ['validate', 'resolve', 'connect:left:true', 'auth:left', 'flash:left', 'disconnect:left',
'connect:right:true', 'auth:right', 'flash:right', 'disconnect:right', 'close']);
assert.deepEqual(f.calls, ['start:R-ID:L-ID:prepared.bin', 'close']);
assert.equal(f.native.idleTimerDisabled, false); assert.equal(f.events.size, 0);
await settle();
assert.deepEqual(f.states, ['validating:', 'connecting:left', 'flashing:left', 'connecting:right', 'flashing:right', 'done:Both lenses flashed. Your glasses are rebooting.']);
assert.deepEqual(f.progress, ['left', 'right']);
}
});
test('iOS flashing refuses a changed image before Bluetooth and never reports partial success', async () => {
const invalid = flasherFixture({ hash: 'changed' }); invalid.flasher.start();
assert.match((await invalid.result).detail, /SHA-256/); assert.deepEqual(invalid.calls, ['close']);
const failure = flasherFixture({ failRole: 'right' }); failure.flasher.start();
assert.match((await invalid.result).detail, /SHA-256/); assert.deepEqual(invalid.calls, []); assert.equal(invalid.native.idleTimerDisabled, false);
const unresolved = flasherFixture({ resolveError: 'Could not find the left arm.' }); unresolved.flasher.start();
assert.match((await unresolved.result).detail, /left arm/); assert.deepEqual(unresolved.calls, []);
const failure = flasherFixture({ outcome: 'fail' }); failure.flasher.start();
const result = await failure.result; assert.equal(result.success, false); assert.match(result.detail, /END rejected/);
assert.equal(failure.native.idleTimerDisabled, false); assert.equal(failure.events.size, 0);
assert.equal(failure.native.idleTimerDisabled, false); assert.equal(failure.events.size, 0); assert.equal(failure.calls.includes('close'), true);
});
test('backgrounding during iOS OTA stops the transfer and directs retry of both lenses', async () => {
const f = flasherFixture({ backgroundRole: 'left' }); f.flasher.start();
const f = flasherFixture({ backgroundOn: 'left' }); f.flasher.start();
const result = await f.result;
assert.equal(result.success, false); assert.match(result.detail, /left the foreground.*retry both lenses/);
assert.equal(f.calls.includes('flash:right'), false); assert.equal(f.native.idleTimerDisabled, false);
assert.equal(f.instances[0].cancelled, true); assert.equal(f.progress.includes('right'), false); assert.equal(f.native.idleTimerDisabled, false);
});
test('iOS firmware prompt surfaces heartbeat disconnection instead of leaving confirmation stuck', async () => {
let heartbeat;
const p = require('../.test-build/app/g2/ble-protocol.js');
class Link {
async resolve() {} async connect() {} async authenticate() {} async request() {}
onMessage() { return () => {}; } nextMagic() { return 1; } close() {}
async write() { throw new Error('Lost connection to the right lens.'); }
}
test('iOS firmware prompt maps addresses to identifiers, forwards the Kotlin flow events and surfaces its errors', async () => {
const instances = [];
const FaceclawKitIosFlashPrompt = { alloc: () => ({ initWithRightAddressLeftAddressWarningTextSkipPrompt(right, left, warning, skip) {
const prompt = { args: [right, left, warning, skip], listener: null, closed: false, started: 0,
setListenerListener(listener) { this.listener = listener; }, start() { this.started++; }, cancel() {}, close() { this.closed = true; } };
instances.push(prompt); return prompt;
} }) };
const { FlashPromptCommunicator } = load('app/native/flash-prompt-communicator.ios.ts', {
'../g2/stock-connection': { StockConnection: Link }, '../g2/flash-prompt-protocol': {}, '../g2/ble-protocol': p,
'./ios-bluetooth': { iosBluetooth: () => ({}) },
}, { setInterval: fn => { heartbeat = fn; return 1; }, clearInterval() {} });
const prompt = new FlashPromptCommunicator({ right: 'r', left: 'l' }, 'warning'), errors = [];
prompt.onStateChange((state, detail) => { if (state === 'error') errors.push(detail); });
prompt.start(); await flush(); heartbeat(); await flush();
assert.deepEqual(errors, ['Lost connection to the right lens.']); prompt.close();
'./ios-bluetooth': bluetooth(), './kotlin-listener.ios': listenerModule,
}, { FaceclawKitIosFlashPrompt, FaceclawKitFaceclawFlashPromptListener: {} });
const prompt = new FlashPromptCommunicator({ right: 'r', left: 'l' }, 'warning', { skipPrompt: true }), states = [], results = [], batteries = [];
prompt.onStateChange((state, detail) => states.push(`${state}:${detail}`)); prompt.onResult(approved => results.push(approved)); prompt.onBattery(b => batteries.push(b));
prompt.start(); prompt.start(); await settle();
assert.equal(instances.length, 1); assert.deepEqual(instances[0].args, ['R-ID', 'L-ID', 'warning', true]); assert.equal(instances[0].started, 1);
const listener = instances[0].listener;
listener.onStateStateDetail('connected', ''); listener.onBatteryRightPercentLeftPercent(88, -1); listener.onResultApproved(true);
listener.onStateStateDetail('error', 'Lost connection to the right lens.'); await settle();
assert.deepEqual(states, ['connecting:', 'connected:', 'error:Lost connection to the right lens.']);
assert.deepEqual(JSON.parse(JSON.stringify(batteries)), [{ right: 88, left: null }]); assert.deepEqual(results, [true]);
prompt.close(); assert.equal(instances[0].closed, true);
const unresolved = load('app/native/flash-prompt-communicator.ios.ts', {
'./ios-bluetooth': bluetooth({}, 'Wake the glasses.'), './kotlin-listener.ios': listenerModule,
}, { FaceclawKitIosFlashPrompt, FaceclawKitFaceclawFlashPromptListener: {} });
const failed = new unresolved.FlashPromptCommunicator({ right: 'r', left: 'l' }, 'warning'), errors = [];
failed.onStateChange((state, detail) => { if (state === 'error') errors.push(detail); });
failed.start(); await settle(); assert.deepEqual(errors, ['Wake the glasses.']); assert.equal(instances.length, 1);
});
test('iOS onboarding returns to the existing main controller, or creates it after first setup', () => {
@@ -117,37 +149,34 @@ test('pinned stock firmware reproduces the custom image, extracts fonts, and pas
'../util/hex-util': require('../.test-build/app/util/hex-util.js'), '../graphics/evenhub-font': { EvenHubFont: { invalidate() {} } },
'../native/firmware-files': { firmwareSha256: hash, writeFirmwareFile: (file, buffer) => fs.writeFileSync(file, new Uint8Array(buffer)) },
});
const { validateFirmware } = require('../.test-build/app/g2/firmware-ota.js');
const stock = await builder.buildStockFirmware(); assert.equal(stock.sha256, patches.CFW_PATCH_SET.baseSha256);
assert.equal(validateFirmware(fs.readFileSync(stock.path)).length, 6);
const custom = await builder.buildCustomFirmware(); assert.equal(hash(fs.readFileSync(custom.path)), patches.CFW_PATCH_SET.outputSha256);
assert.equal(validateFirmware(fs.readFileSync(custom.path)).length, 6);
assert.equal(builder.hasExtractedEvenHubFonts(), true);
});
for (const unsolicited of [false, true]) test(`iOS firmware probe ${unsolicited ? 'accepts a version push with device-owned magic' : 'falls back to the left lens after a silent right lens'}`, async () => {
const p = require('../.test-build/app/g2/ble-protocol.js'), calls = [];
let listener;
const str = (field, text) => p.bytes(field, new Uint8Array(Buffer.from(text)));
const version = { sid: p.SID.settings, payload: p.concat(p.bytes(4, p.concat(str(5, '2.2.9.22'), str(6, '2.2.9.22'))), str(100, 'faceclaw/13')) };
class Link {
onMessage(fn) { listener = fn; } async resolve() {} check() {} isConnected() { return true; }
async connect(role) { calls.push(`connect:${role}`); }
async authenticate(role) { calls.push(`auth:${role}`); }
async request(role, sid) {
if (sid === p.SID.launch) return {};
if (role === 'right') { if (unsolicited) listener(role, version); throw new Error('Timeout'); }
return version;
}
close() { calls.push('close'); }
}
test('iOS firmware probe resolves identifiers, runs the Kotlin flow and settles once', async () => {
const instances = [];
const FaceclawKitIosDeviceInfoProbe = { alloc: () => ({ initWithRightAddressLeftAddress(right, left) {
const probe = { args: [right, left], listener: null, closed: 0, setListenerListener(listener) { this.listener = listener; }, start() { this.started = true; }, cancel() {}, close() { this.closed++; } };
instances.push(probe); return probe;
} }) };
const { DeviceInfoProbe } = load('app/native/device-info-probe.ios.ts', {
'../g2/stock-connection': { StockConnection: Link, StockTimeout: class extends Error {} },
'../g2/ble-protocol': p, './ios-bluetooth': { iosBluetooth: () => ({}) },
});
const info = await new DeviceInfoProbe('r', 'l').run();
assert.equal(info.rightVersion, '2.2.9.22'); assert.equal(info.leftVersion, '2.2.9.22'); assert.equal(info.extension, 'faceclaw/13');
assert.deepEqual(calls, ['connect:right', 'auth:right', 'connect:left', 'auth:left', 'close']);
'./ios-bluetooth': bluetooth(), './kotlin-listener.ios': listenerModule,
}, { FaceclawKitIosDeviceInfoProbe, FaceclawKitFaceclawDeviceInfoProbeListener: {} });
const probe = new DeviceInfoProbe('r', 'l'), states = [];
probe.onStateChange((state, detail) => states.push(`${state}:${detail}`));
const pending = probe.run(); await settle();
assert.deepEqual(instances[0].args, ['R-ID', 'L-ID']); assert.equal(instances[0].started, true);
instances[0].listener.onStateStateDetail('querying', 'right');
instances[0].listener.onResultLeftVersionRightVersionExtension('2.2.9.22', '2.2.9.22', 'faceclaw/13');
instances[0].listener.onErrorMessage('late error is ignored');
const info = await pending; await settle();
assert.deepEqual(JSON.parse(JSON.stringify(info)), { leftVersion: '2.2.9.22', rightVersion: '2.2.9.22', extension: 'faceclaw/13' });
assert.deepEqual(states, ['connecting:right', 'querying:right']); assert.equal(instances[0].closed, 1);
const failing = new DeviceInfoProbe('r'); const failed = failing.run(); await settle();
assert.deepEqual(instances[1].args, ['R-ID', '']);
instances[1].listener.onErrorMessage("Connected, but couldn't read a firmware version.");
await assert.rejects(failed, /firmware version/);
});
test('iOS discovery stops pending scans on cancellation and ignores a late permission result', async () => {
-32
View File
@@ -1,32 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const protocol = require('../.test-build/app/g2/ble-protocol.js');
const decode = (payload) => protocol.decodeGlassesInput({ sid:224,flag:1,payload });
const packet = Buffer.from('08026a151a13080e1002a2060c524901010aabcd00efcdab89','hex');
test('timestamped CFW packet decodes atomically with source and original unsigned tick', () => {
const input = decode(packet);
assert.equal(input.eventType,14); assert.equal(input.eventSource,2);
assert.deepEqual(input.ringInput,{tick:0x89abcdef,type:10,aux:171,speed:205});
for (const tick of [0,1,0xffffffff]) {
const p = Buffer.from(packet); p.writeUInt32LE(tick,21);
assert.equal(decode(p).ringInput.tick,tick);
}
});
test('legacy/invalid metadata leaves input intact without inventing a clock', () => {
assert.equal(decode(Buffer.from('08026a041a02080e','hex')).ringInput,undefined);
for (const offset of [9,13,14,15,16,20]) {
const p = Buffer.from(packet); p[offset]++;
assert.equal(decode(p).ringInput,undefined);
}
});
// Firmware regression: MsgPbTxByBle sets flag 0; Thread_MsgPbNotifyByBle
// (also used by stock SysEvent) sets flag 1. Payload validity is insufficient.
test('ring input must use the notification envelope, never the reply envelope', () => {
assert.equal(protocol.decodeGlassesInput({ sid:224,flag:0,payload:packet }),null);
for (const flag of [1,6]) {
const input = protocol.decodeGlassesInput({ sid:224,flag,payload:packet });
assert.equal(input.eventType,14); assert.equal(input.ringInput.tick,0x89abcdef);
}
});
+3 -6
View File
@@ -2,7 +2,9 @@
"compilerOptions": {
"module": "commonjs",
"target": "ES2020",
"lib": ["ES2020"],
"lib": [
"ES2020"
],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
@@ -14,15 +16,10 @@
"../app/remote/protocol.ts",
"../app/remote/listeners.ts",
"../app/g2/ancs-client.ts",
"../app/g2/ble-protocol.ts",
"../app/graphics/lvgl-font.ts",
"../app/phone-ui/ble-bandwidth-meter.ts",
"../app/apps/terminal/hub-header.ts",
"../app/g2/ios-peripheral-identity.ts",
"../app/g2/glasses-session.ts",
"../app/g2/stock-connection.ts",
"../app/g2/firmware-ota.ts",
"../app/g2/flash-prompt-protocol.ts",
"../app/graphics/surface-compositor.ts",
"../app/graphics/image.ts",
"../app/graphics/plane.ts",