forked from Blendman974/faceclaw
Porting onboarding/flashing flow io iOS
This commit is contained in:
1 parent
68b459751e
commit
64bf600ef9
46 files changed
+1419
-211
No files matched your search
@@ -281,6 +281,8 @@ test('iOS bandwidth footer toggles live, polls only in foreground and resets its
|
||||
onAnySettingChanged: fn => { settingListeners.add(fn); return () => settingListeners.delete(fn); } },
|
||||
'../g2/device-addresses': { loadDeviceAddresses: () => ({}) },
|
||||
'../g2/ios-peripheral-identity': { deviceAddressError: () => 'no test devices' },
|
||||
'./onboarding-state': { isPreviewOnlyMode: () => false },
|
||||
'../g2/reconnect-policy': { isAutoReconnectSuppressed: () => false },
|
||||
};
|
||||
const { createMainPage } = load('app/phone-ui/main-page.ios.ts', {
|
||||
require: id => modules[id] ?? {}, Date: { now: () => atMs },
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const p = require('../.test-build/app/g2/ble-protocol.js');
|
||||
const { StockConnection, OTA_WRITE, OTA_NOTIFY, decodeOtaAcks } = require('../.test-build/app/g2/stock-connection.js');
|
||||
const { firmwareCrc, validateFirmware, flashLensImage } = require('../.test-build/app/g2/firmware-ota.js');
|
||||
const { createFlashPrompt, flashPromptSelection } = require('../.test-build/app/g2/flash-prompt-protocol.js');
|
||||
const hex = bytes => Buffer.from(bytes).toString('hex');
|
||||
function fixture() {
|
||||
const sizes = [9000, 20, 20, 20, 20], image = new Uint8Array(0x40 + 5 * 16 + sizes.reduce((n, size) => n + size + 128, 0));
|
||||
const view = new DataView(image.buffer), u32 = (off, value) => view.setUint32(off, value, true);
|
||||
u32(8, 5); let offset = 0x40 + 5 * 16;
|
||||
sizes.forEach((size, index) => {
|
||||
u32(0x40 + index * 16 + 4, offset); u32(offset + 8, size);
|
||||
image.set(Buffer.from(index ? `ota/part${index}.bin` : 'ota/s200_firmware_ota.bin'), offset + 48);
|
||||
image.fill(index + 1, offset + 128, offset + 128 + size);
|
||||
if (!index) { u32(offset + 128, size); u32(offset + 128 + 0x14, 0x00438000); }
|
||||
const crc = firmwareCrc(image.subarray(offset + 128, offset + 128 + size));
|
||||
u32(offset + 12, crc); u32(0x40 + index * 16 + 12, crc); offset += size + 128;
|
||||
});
|
||||
return image;
|
||||
}
|
||||
class Transport {
|
||||
listeners = new Set(); writes = []; messages = []; chunks = []; seq = 0; held = false; respond = null; closed = [];
|
||||
onEvent(fn) { this.listeners.add(fn); return () => this.listeners.delete(fn); }
|
||||
emit(event) { for (const fn of this.listeners) fn(event); }
|
||||
async resolveDevices() { return { left: 'L', right: 'R' }; }
|
||||
async connect() { return { characteristics: [p.G2_WRITE, p.G2_NOTIFY, OTA_WRITE, OTA_NOTIFY], maxWrite: 60 }; }
|
||||
async subscribe() {}
|
||||
stopScan() {}
|
||||
disconnect(id) { this.closed.push(id); this.emit({ kind: 'disconnected', identifier: id }); }
|
||||
notify(id, sid, payload, characteristic = p.G2_NOTIFY, flag = 0) {
|
||||
this.emit({ kind: 'notification', identifier: id, characteristic, data: hex(p.concat(...p.frameMessage(payload, sid, flag, 10))) });
|
||||
}
|
||||
async write(id, characteristic, bytes) {
|
||||
this.writes.push({ id, characteristic, bytes });
|
||||
if (bytes[5] === 1) this.chunks = [];
|
||||
this.chunks.push(bytes.subarray(8));
|
||||
if (bytes[5] !== bytes[4]) return;
|
||||
const all = p.concat(...this.chunks), payload = all.slice(0, -2);
|
||||
assert.equal(p.crc16(payload), all.at(-2) | all.at(-1) << 8);
|
||||
const message = { id, characteristic, sid: bytes[6], seq: bytes[2], payload };
|
||||
this.messages.push(message);
|
||||
if (this.respond) return this.respond(message);
|
||||
if (this.held) return;
|
||||
if (characteristic === OTA_WRITE) {
|
||||
if (message.sid === 0xc0 && payload[0] === 2) { this.seq = message.seq; return; }
|
||||
if (message.sid === 0xc1) assert.equal(message.seq, this.seq, 'marker/data sequence must match');
|
||||
this.notify(id, 0xc0, new Uint8Array([message.sid === 0xc1 ? 2 : payload[0], 0]), OTA_NOTIFY);
|
||||
} else {
|
||||
this.notify(id, message.sid, p.concat(p.integer(1, p.readInteger(payload, 1)), p.integer(2, p.readInteger(payload, 2)), p.bytes(3, new Uint8Array())));
|
||||
}
|
||||
}
|
||||
}
|
||||
async function connection(t, transport = new Transport()) {
|
||||
const link = new StockConnection(transport); t.after(() => link.close());
|
||||
await link.resolve({ left: 'a', right: 'b', ring: '' }); await link.connect('left', true);
|
||||
return { link, transport };
|
||||
}
|
||||
|
||||
test('OTA validator checks CRCs, bounds, overlap and the main-app preamble before transfer', () => {
|
||||
const image = fixture(), segments = validateFirmware(image);
|
||||
assert.equal(segments.length, 5);
|
||||
const corrupt = image.slice(); corrupt[segments[0].offset + 200] ^= 1;
|
||||
assert.throws(() => validateFirmware(corrupt), /CRC32C/);
|
||||
assert.throws(() => validateFirmware(image.slice(0, -1)), /truncated/);
|
||||
const bad = image.slice(), view = new DataView(bad.buffer);
|
||||
view.setUint32(0x44, 0xfffffff0, true); assert.throws(() => validateFirmware(bad), /bounds/);
|
||||
const overlap = image.slice(); new DataView(overlap.buffer).setUint32(0x54, segments[0].offset, true);
|
||||
assert.throws(() => validateFirmware(overlap), /overlap/);
|
||||
const wrongLoad = image.slice(), w = new DataView(wrongLoad.buffer), main = segments[0];
|
||||
w.setUint32(main.offset + 128 + 0x14, 0, true);
|
||||
const crc = firmwareCrc(wrongLoad.subarray(main.offset + 128, main.offset + 128 + main.size));
|
||||
w.setUint32(main.offset + 12, crc, true); w.setUint32(0x4c, crc, true);
|
||||
assert.throws(() => validateFirmware(wrongLoad), /preamble/);
|
||||
});
|
||||
|
||||
test('OTA framing streams every verified byte in 4KB blocks with shared marker/data sequences', async t => {
|
||||
const { link, transport } = await connection(t); await link.authenticate('left');
|
||||
const image = fixture(), segments = validateFirmware(image), progress = [];
|
||||
await flashLensImage(link, 'left', image, segments, value => progress.push(value), () => {}, async () => {});
|
||||
const controls = transport.messages.filter(m => m.sid === 0xc0);
|
||||
assert.equal(controls[0].payload[0], 0);
|
||||
assert.equal(controls.filter(m => m.payload[0] === 1).length, 5);
|
||||
assert.equal(controls.filter(m => m.payload[0] === 3).length, 5);
|
||||
const streamed = p.concat(...transport.messages.filter(m => m.sid === 0xc1).map(m => m.payload));
|
||||
assert.deepEqual(streamed, p.concat(...segments.map(s => image.slice(s.offset + 128, s.offset + 128 + s.size))));
|
||||
assert.equal(progress.at(-1).bytesSent, progress.at(-1).bytesTotal);
|
||||
assert.ok(transport.writes.every(w => w.bytes.length <= 60));
|
||||
});
|
||||
|
||||
test('OTA retries NAKed blocks and failed END verification, but never accepts a rejected FILE_CHECK', async () => {
|
||||
const image = fixture(), segments = validateFirmware(image); let blockAttempts = 0, endAttempts = 0, checks = 0;
|
||||
const fake = { check() {}, async exchange(_role, _sid, payload, _match, _timeout, _write, _notify, _flag, _seq, data) {
|
||||
const op = payload[0]; let status = 0;
|
||||
if (op === 1) checks++;
|
||||
if (op === 2 && ++blockAttempts === 1) status = 1;
|
||||
if (op === 3 && ++endAttempts === 1) status = 2;
|
||||
return { payload: new Uint8Array([op, status]) };
|
||||
} };
|
||||
await flashLensImage(fake, 'left', image, segments, () => {}, () => {}, async () => {});
|
||||
assert.equal(checks, 6); assert.equal(blockAttempts, 11);
|
||||
let dataWrites = 0;
|
||||
fake.exchange = async (_role, _sid, payload, ...args) => { if (args.at(-1)) dataWrites++; return { payload: new Uint8Array([payload[0], payload[0] === 1 ? 4 : 0]) }; };
|
||||
await assert.rejects(flashLensImage(fake, 'left', image, segments, () => {}, () => {}, async () => {}), /failed after 3 attempts/);
|
||||
assert.equal(dataWrites, 0);
|
||||
});
|
||||
|
||||
test('onboarding requests ignore wrong peers, magic and pre-encryption authentication failures', async t => {
|
||||
const { link, transport } = await connection(t); let resolved = false;
|
||||
transport.respond = message => {
|
||||
const magic = p.readInteger(message.payload, 2);
|
||||
const good = p.concat(p.integer(1, 4), p.integer(2, magic), p.bytes(3, new Uint8Array()));
|
||||
transport.notify('stranger', p.SID.auth, good);
|
||||
transport.notify('R', p.SID.auth, good);
|
||||
transport.notify('L', p.SID.auth, p.concat(p.integer(1, 4), p.integer(2, magic), p.bytes(3, p.integer(1, 1))));
|
||||
transport.notify('L', p.SID.auth, p.concat(p.integer(1, 4), p.integer(2, magic + 1), p.bytes(3, new Uint8Array())));
|
||||
setImmediate(() => { assert.equal(resolved, false); transport.notify('L', p.SID.auth, good); });
|
||||
};
|
||||
await link.authenticate('left'); resolved = true;
|
||||
});
|
||||
|
||||
test('OTA ACK parsing rejects bad CRC and truncation; cancellation rejects an outstanding transaction', async t => {
|
||||
const { link, transport } = await connection(t); transport.held = true;
|
||||
const payload = new Uint8Array([2, 0]), packet = p.frameMessage(payload, 0xc0, 0, 1)[0];
|
||||
assert.equal(decodeOtaAcks(packet)[0].payload[1], 0);
|
||||
assert.deepEqual(decodeOtaAcks(packet.slice(0, -1)), []);
|
||||
packet[8] ^= 1; assert.deepEqual(decodeOtaAcks(packet), []);
|
||||
const pending = link.exchange('left', 0xc0, new Uint8Array([0]), m => m.command === 0, 8000, OTA_WRITE, OTA_NOTIFY, 0);
|
||||
link.close(); await assert.rejects(pending, /Cancelled/);
|
||||
assert.equal(transport.listeners.size, 0);
|
||||
});
|
||||
|
||||
test('stock confirmation keeps No first and accepts only a confirmed flashmenu selection', () => {
|
||||
const page = createFlashPrompt(42, 'Warning'); const body = p.readBytes(page, 3);
|
||||
const list = p.readBytes(body, 2), label = p.readBytes(body, 3);
|
||||
assert.equal(p.readInteger(list, 3), 280); assert.equal(p.readInteger(label, 4), 130);
|
||||
assert.equal(p.readString(list, 10), 'flashmenu'); assert.equal(p.readString(label, 12), 'Warning');
|
||||
const event = (index, type = 0, name = 'flashmenu') => ({ sid: 0xe0, flag: 1,
|
||||
payload: p.bytes(13, p.bytes(1, p.concat(p.bytes(2, new Uint8Array(Buffer.from(name))), p.integer(4, index), p.integer(5, type)))) });
|
||||
assert.equal(flashPromptSelection(event(0)), false); assert.equal(flashPromptSelection(event(1)), true);
|
||||
assert.equal(flashPromptSelection(event(1, 1)), null); assert.equal(flashPromptSelection(event(1, 0, 'other')), null);
|
||||
});
|
||||
@@ -0,0 +1,164 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs'), vm = require('node:vm'), ts = require('typescript');
|
||||
const crypto = require('node:crypto'), os = require('node:os'), path = require('node:path');
|
||||
function load(file, modules = {}, globals = {}) {
|
||||
const context = { exports: {}, require: name => {
|
||||
if (!(name in modules)) throw new Error(`Missing mock: ${name} in ${file}`);
|
||||
return modules[name];
|
||||
}, Uint8Array, ArrayBuffer, DataView, setTimeout, clearTimeout, setInterval, clearInterval, ...globals };
|
||||
vm.runInNewContext(ts.transpileModule(fs.readFileSync(file, 'utf8'), {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
|
||||
}).outputText, context);
|
||||
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 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 { FirmwareFlasher } = load('app/native/firmware-flasher.ios.ts', {
|
||||
'@nativescript/core': { Application: app }, '../g2/stock-connection': { StockConnection: Link },
|
||||
'../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) });
|
||||
const flasher = new FirmwareFlasher({ right: 'r', left: 'l' }, 'prepared.bin');
|
||||
const result = new Promise(resolve => flasher.onComplete((success, detail) => resolve({ success, detail })));
|
||||
return { calls, events, native, flasher, result };
|
||||
}
|
||||
|
||||
test('iOS flashing authenticates and verifies both lenses in order before reporting 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.equal(f.native.idleTimerDisabled, false); assert.equal(f.events.size, 0);
|
||||
}
|
||||
});
|
||||
|
||||
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();
|
||||
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);
|
||||
});
|
||||
|
||||
test('backgrounding during iOS OTA stops the transfer and directs retry of both lenses', async () => {
|
||||
const f = flasherFixture({ backgroundRole: '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);
|
||||
});
|
||||
|
||||
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.'); }
|
||||
}
|
||||
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();
|
||||
});
|
||||
|
||||
test('iOS onboarding returns to the existing main controller, or creates it after first setup', () => {
|
||||
const calls = [], main = { entry: { moduleName: 'phone-ui/main-page' } }, stack = [main];
|
||||
const { finishOnboardingNavigation } = load('app/phone-ui/onboarding-navigation.ts', {
|
||||
'@nativescript/core': { Frame: { topmost: () => ({ backStack: stack, goBack: entry => calls.push(entry), navigate: entry => calls.push(entry) }) } },
|
||||
}, { global: { isIOS: true } });
|
||||
finishOnboardingNavigation(); assert.equal(calls[0], main);
|
||||
stack.length = 0; finishOnboardingNavigation();
|
||||
assert.equal(calls[1].moduleName, 'phone-ui/main-page'); assert.equal(calls[1].clearHistory, true);
|
||||
});
|
||||
|
||||
test('pinned stock firmware reproduces the custom image, extracts fonts, and passes OTA validation', {
|
||||
skip: !process.env.FACECLAW_TEST_STOCK_FIRMWARE && 'Set FACECLAW_TEST_STOCK_FIRMWARE to the pinned stock .bin',
|
||||
}, async t => {
|
||||
const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'faceclaw-firmware-test-'));
|
||||
t.after(() => fs.rmSync(temp, { recursive: true, force: true }));
|
||||
const base = fs.readFileSync(process.env.FACECLAW_TEST_STOCK_FIRMWARE);
|
||||
const hash = buffer => crypto.createHash('sha256').update(new Uint8Array(buffer)).digest('hex');
|
||||
const patches = load('app/g2/firmware/cfw-patches.ts'), fonts = load('app/g2/firmware-fonts.ts');
|
||||
const builder = load('app/g2/firmware-builder.ts', {
|
||||
'@nativescript/core': { File: { exists: fs.existsSync, fromPath: file => ({ readTextSync: () => fs.readFileSync(file, 'utf8') }) },
|
||||
knownFolders: { documents: () => ({ path: temp, getFile: name => ({ writeTextSync: text => fs.writeFileSync(path.join(temp, name), text) }) }) } },
|
||||
'./firmware/cfw-patches': patches, './firmware-fonts': fonts,
|
||||
'../util/http': { fetchWithUserAgent: async () => ({ ok: true, arrayBuffer: async () => Uint8Array.from(base).buffer }) },
|
||||
'../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'); }
|
||||
}
|
||||
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']);
|
||||
});
|
||||
|
||||
test('iOS discovery stops pending scans on cancellation and ignores a late permission result', async () => {
|
||||
const listeners = new Set(); let ready = async () => {}, starts = 0, stops = 0;
|
||||
const ble = { state: 5, scanning: false, devices: new Map(),
|
||||
ensureReady: () => ready(), onEvent: fn => { listeners.add(fn); return () => listeners.delete(fn); },
|
||||
startScan: async () => { starts++; }, stopScan: () => { stops++; },
|
||||
};
|
||||
const { DeviceDiscoveryBridge } = load('app/native/device-discovery.ios.ts', {
|
||||
'./ios-bluetooth': { iosBluetooth: () => ble }, './device-discovery-common': {},
|
||||
});
|
||||
const discovery = new DeviceDiscoveryBridge();
|
||||
const pending = discovery.scanCandidates(60_000); await flush(); discovery.stopScan();
|
||||
await assert.rejects(pending, /cancelled/); assert.equal(listeners.size, 0); assert.equal(starts, 1);
|
||||
let release; ready = () => new Promise(resolve => { release = resolve; });
|
||||
const waiting = discovery.scanCandidates(); discovery.stopScan(); release();
|
||||
await assert.rejects(waiting, /cancelled/); assert.equal(starts, 1); assert.equal(stops, 1);
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs'), vm = require('node:vm'), ts = require('typescript');
|
||||
function load(file, modules = {}, globals = {}) {
|
||||
const context = { exports: {}, require: name => modules[name] ?? {}, ...globals };
|
||||
vm.runInNewContext(ts.transpileModule(fs.readFileSync(file, 'utf8'), {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
|
||||
}).outputText, context);
|
||||
return context.exports;
|
||||
}
|
||||
function scanner() {
|
||||
const instances = [];
|
||||
const api = load('app/native/qr-scan.ios.ts', {}, { FaceclawQrScanner: {
|
||||
isAvailable: () => true,
|
||||
new: () => {
|
||||
const native = { startWithCompletion(done) { this.done = done; }, cancel() { this.cancelled = true; this.done(null, null); } };
|
||||
instances.push(native); return native;
|
||||
},
|
||||
} });
|
||||
return { api, instances };
|
||||
}
|
||||
const flush = () => new Promise(resolve => setImmediate(resolve));
|
||||
function layerFixture() {
|
||||
const { api, instances } = scanner();
|
||||
let available = true, pops = 0, renders = 0, launch = async () => {};
|
||||
const saved = [], launched = [], logs = [];
|
||||
const manager = load('app/apps/evenhub/manager.ts');
|
||||
const { LoadAppFromQrLayer } = load('app/apps/developer/load-app.ts', {
|
||||
'../../native/qr-scan': { ...api, isQrScannerAvailable: () => available },
|
||||
'../../ui/dashboard-settings': { developerAppUrlSetting: { set: url => saved.push(url) } },
|
||||
'../evenhub': { isLoadableAppUrl: url => manager.normalizeAppUrl(url) !== null,
|
||||
openEvenHubUrl: async (_ctx, url) => { launched.push(url); await launch(); } },
|
||||
}, { global: { isIOS: true } });
|
||||
const layer = new LoadAppFromQrLayer({ appendLog: text => logs.push(text) });
|
||||
const ctx = { actions: { requestRender: () => renders++ }, stack: { pop: () => { pops++; layer.onRemoved(); } } };
|
||||
return { layer, ctx, instances, saved, launched, logs, get pops() { return pops; }, get renders() { return renders; },
|
||||
available: value => { available = value; }, launch: fn => { launch = fn; } };
|
||||
}
|
||||
|
||||
test('iOS scanner delivers one result, prevents overlapping cameras, and allows a later scan', async () => {
|
||||
const { api, instances } = scanner();
|
||||
assert.equal(api.isQrScannerAvailable(), true);
|
||||
const first = api.scanQrCode();
|
||||
await assert.rejects(api.scanQrCode(), /already open/);
|
||||
instances[0].done('https://example.com/app', null);
|
||||
instances[0].done('https://late.example/app', null);
|
||||
assert.equal(await first, 'https://example.com/app');
|
||||
const second = api.scanQrCode(); api.cancelQrScan();
|
||||
assert.equal(await second, null); assert.equal(instances[1].cancelled, true);
|
||||
});
|
||||
|
||||
test('iOS scanner reports permission/native errors and releases its active scan', async () => {
|
||||
const { api, instances } = scanner();
|
||||
const first = api.scanQrCode(); instances[0].done(null, 'Allow Camera in Settings');
|
||||
await assert.rejects(first, /Allow Camera/);
|
||||
const retry = api.scanQrCode(); instances[1].done('http://dev.local:5173/?key=a%2Fb#app', null);
|
||||
assert.equal(await retry, 'http://dev.local:5173/?key=a%2Fb#app');
|
||||
});
|
||||
|
||||
test('Developer QR saves and launches an app URL exactly once, preserving port/query/fragment', async () => {
|
||||
const f = layerFixture(); f.layer.open(f.ctx); f.layer.open(f.ctx);
|
||||
const url = 'http://dev.local:5173/?key=a%2Fb#app';
|
||||
f.instances[0].done(url, null); await flush();
|
||||
assert.deepEqual(f.saved, [url]); assert.deepEqual(f.launched, [url]);
|
||||
assert.equal(f.pops, 1); assert.equal(f.instances.length, 1);
|
||||
});
|
||||
|
||||
test('Developer QR cancellation, invalid content and permission failure can all be retried', async () => {
|
||||
const f = layerFixture(); f.layer.open(f.ctx); f.instances[0].done(null, null); await flush();
|
||||
assert.match(f.layer.status, /cancelled/);
|
||||
f.layer.handleInput({ type: 'click' }, f.ctx); f.instances[1].done('file:///private/test', null); await flush();
|
||||
assert.match(f.layer.status, /Not a URL/);
|
||||
f.layer.handleInput({ type: 'click' }, f.ctx); f.instances[2].done(null, 'Camera denied'); await flush();
|
||||
assert.match(f.layer.status, /Camera denied/);
|
||||
assert.deepEqual(f.saved, []); assert.deepEqual(f.launched, []); assert.equal(f.pops, 0);
|
||||
f.layer.handleInput({ type: 'click' }, f.ctx); f.instances[3].done('https://example.com/', null); await flush();
|
||||
assert.equal(f.pops, 1);
|
||||
});
|
||||
|
||||
test('leaving Developer QR cancels the camera and suppresses late results', async () => {
|
||||
const f = layerFixture(); f.layer.open(f.ctx);
|
||||
f.layer.handleInput({ type: 'double-click' }, f.ctx);
|
||||
const renders = f.renders;
|
||||
f.instances[0].done('https://example.com/', null); await flush();
|
||||
assert.equal(f.instances[0].cancelled, true);
|
||||
assert.deepEqual(f.saved, []); assert.deepEqual(f.launched, []);
|
||||
assert.equal(f.renders, renders); assert.equal(f.pops, 1);
|
||||
});
|
||||
|
||||
test('leaving while an app launches cannot pop a replacement page or repaint the removed layer', async () => {
|
||||
const f = layerFixture(); let finish;
|
||||
f.launch(() => new Promise(resolve => { finish = resolve; }));
|
||||
f.layer.open(f.ctx); f.instances[0].done('https://example.com/', null); await flush();
|
||||
f.ctx.stack.pop(); const renders = f.renders;
|
||||
finish(); await flush();
|
||||
assert.equal(f.pops, 1); assert.equal(f.renders, renders);
|
||||
});
|
||||
|
||||
test('iOS without a camera explains availability and can retry when available', async () => {
|
||||
const f = layerFixture(); f.available(false); f.layer.open(f.ctx);
|
||||
assert.match(f.layer.status, /physical iPhone/); assert.equal(f.instances.length, 0);
|
||||
f.available(true); f.layer.handleInput({ type: 'click' }, f.ctx);
|
||||
assert.equal(f.instances.length, 1); f.layer.onRemoved(); await flush();
|
||||
});
|
||||
|
||||
test('Developer QR menu is enabled on iOS and pushes then opens its layer', () => {
|
||||
let menu, options; const calls = [];
|
||||
const { createDeveloperAppWindow } = load('app/apps/developer/developer-app.ts', {
|
||||
'../../ui/menu': { MenuLayer: class { constructor(_title, items) { menu = items; } } },
|
||||
'../../ui/shell/geometry': { appViewportSize: () => ({ height: 480 }) },
|
||||
'../../ui/shell/in-process-window': { YieldAtRootLayer: class {}, createInProcessWindow: value => { options = value; return {}; } },
|
||||
'./load-app': { LoadAppFromQrLayer: class { open() { calls.push('open'); } } },
|
||||
}, { global: { isIOS: true } });
|
||||
createDeveloperAppWindow({}, {});
|
||||
const qr = menu.find(item => item.label === 'Load app from QR code');
|
||||
assert.ok(!qr.disabled); qr.onSelect({ stack: { push: () => calls.push('push') } });
|
||||
assert.deepEqual(calls, ['push', 'open']);
|
||||
});
|
||||
@@ -17,6 +17,9 @@
|
||||
"../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/phone-ui/phone-gestures.ts",
|
||||
|
||||
Reference in new issue
Block a user