Merge branch 'main' of https://github.com/jimrandomh/faceclaw into ring-health-fixes

This commit is contained in:
James Babcock committed 2026-09-25 23:12:20 -07:00
commit a2166c6a6c
822 files changed
+79614 -30124

No files matched your search

+18 -8
View File
@@ -15,15 +15,25 @@ That compiles the pure modules with the project's TypeScript into
dependencies are needed — the tests are plain `.test.cjs` files that use
`node:test` and `node:assert`.
Compass diagnostics have focused UI and wire-format checks:
The shared Kotlin suite runs separately from the Node tests:
node --test tests/compass-debug.test.cjs tests/compass-protocol.test.cjs
npm run test:kotlin
npm run test:kotlin:ios
The protocol check also compiles the production Java parser, so it needs a
JDK (`JAVA_HOME`, or `javac` and `java` on `PATH`). Its golden packet is shared
with the firmware encoder test in `g2flash/tests/compass_diagnostics_test.c`.
It includes the migrated compass, R1 battery, gesture and texture Java fixtures,
which now call the Kotlin implementation from Android host tests. Common tests
also run as native iOS simulator binaries. See [the Kotlin README](../native/kotlin/README.md)
for SDK requirements, source layout and coverage. The compass and battery
fixtures retain the golden packets shared with firmware tests.
R1 battery field-106 decoding (valid zero, charging, unavailable/disconnected,
legacy firmware, malformed messages) uses the same C/Java golden packet:
The native iOS EvenHub probe runs separately on a booted simulator:
node --test tests/ring-battery-protocol.test.cjs
node tests/ios-evenhub-native.cjs <simulator-UUID>
It compiles the production WKWebView host into an isolated app and checks local
and remote loading, document-start injection, assets, storage and navigation.
It then opens Safari to background the probe and verifies that injected timeouts,
intervals and animation callbacks still fire, and cancelled timers stay cancelled.
A short UIKit background task keeps the test process running without glasses.
This covers the ticker's background behavior; sustained execution with BLE and a
locked physical phone still requires device testing.
+39 -8
View File
@@ -46,7 +46,7 @@ function conversations(saved = '') {
const env = sessions();
const { AssistantConversations } = load('app/assistant/conversations.ts', {
'./session': { AssistantSession: env.AssistantSession },
'./models': { ASSISTANT_MODEL_VALUES: ['auto', 'terra', 'sonnet'] },
'./models': { supportedAssistantModel: value => value, ASSISTANT_MODEL_VALUES: ['auto', 'terra', 'sonnet'] },
});
let stored = '';
const store = new AssistantConversations((model, effort) => config(model, effort), () => 'terra', (value) => { stored = value; }, saved);
@@ -228,7 +228,7 @@ test('empty capture, rejection and closing never submit stale speech', async ()
}
});
function shellEnv() {
function shellEnv({ wakeAction = 'voice-input', skipConfirmation = false } = {}) {
const gestures = load('app/ui/gestures.ts', {});
class Image { constructor(width = 576, height = 260) { this.width = width; this.height = height; } }
const images = { GrayImage: Image, G2_LENS_WIDTH: 640, G2_LENS_HEIGHT: 480 };
@@ -244,11 +244,19 @@ function shellEnv() {
paint(_ctx, below) { return below(); }
handleInput(event, ctx) { if (event.type === 'double-click') ctx.stack.pop(); }
}
const settings = { wakeWordActionSetting: { get: () => 'voice-input' }, brightnessSetting: { get: () => 'auto' } };
const { shell } = load('app/ui/shell/shell.ts', {
'../../graphics/image': images, '../../graphics/plane': {}, '../../graphics/ui-fonts': {}, '../../g2/events': {},
const voiceDialogs = [];
const settings = { wakeWordActionSetting: { get: () => wakeAction }, brightnessSetting: { get: () => 'auto' },
assistantSkipConfirmationSetting: { get: () => skipConfirmation } };
const { shell, rawInputEventToInputEvent } = load('app/ui/shell/shell.ts', {
'../../graphics/shell-scene': { encodeShellScene: () => new Uint8Array([0, 0]) },
'../../graphics/image': images, '../../graphics/plane': {}, '../../graphics/ui-fonts': {}, '../../g2/events': load('app/g2/events.ts', {}),
'../gestures': gestures, '../layers': layers, '../menu': { MenuLayer: Menu },
'./voice-input': {}, './keyboard-input': {}, './voice-activity': {}, './assistant': {},
'../input-monitor': load('app/ui/input-monitor.ts', {}),
'./voice-input': { VoiceInputLayer: class {
constructor(options) { this.options = options; voiceDialogs.push(options); }
startCapture() {}
onRemoved() { this.options.onClosed(); }
} }, './keyboard-input': {}, './voice-activity': { voiceActivity: { setActive() {} } }, './assistant': {},
'../../assistant/conversations': {}, '../../assistant/models': {}, '../../native/settings-store': {},
'../notifications': {}, '../dashboard-settings': settings, './ambient-cards': {},
'./chrome-layer': { ShellChromeLayer: class {} }, './modal-layer': {}, './tool-debug-layer': {},
@@ -280,9 +288,32 @@ function shellEnv() {
});
shell.registerWindow(app.window);
shell.focusWindow('ai-chat');
return { shell, app, input, menus, microphone: () => microphone, event: (type) => gestures.makeInputEvent({ type }) };
return { shell, app, input, menus, voiceDialogs, rawInputEventToInputEvent, microphone: () => microphone, event: (type) => gestures.makeInputEvent({ type }) };
}
test('wakeword wakes the shared shell, respects its action, and opens only one hands-free assistant dialog', async () => {
for (const wakeAction of ['off', 'turn-screen-on', 'voice-input']) {
const env = shellEnv({ wakeAction, skipConfirmation: true });
env.shell.isAssistantAvailable = () => true;
env.shell.sleep();
const event = env.rawInputEventToInputEvent({ kind: 'even-ai', eventType: 1, eventSource: 0 });
assert.equal(event.type, 'wakeword');
await env.shell.receiveInput(event);
await new Promise(resolve => setImmediate(resolve));
assert.equal(env.shell.isScreenOn(), wakeAction !== 'off');
assert.equal(env.voiceDialogs.length, wakeAction === 'voice-input' ? 1 : 0);
if (wakeAction === 'voice-input') {
const options = env.voiceDialogs[0];
assert.equal(options.handsFree, true);
assert.equal(options.autoSend, true);
assert.equal(options.sendTargets[options.defaultTargetIndex].id, 'assistant');
await env.shell.receiveInput(event);
assert.equal(env.voiceDialogs.length, 1);
}
env.shell.stack.clearToBase();
}
});
test('chat holds bypass the escape timer; release, menus and double tap follow the requested routing', async () => {
const env = shellEnv();
await env.shell.receiveInput(env.event('long-press'));
@@ -324,7 +355,7 @@ function chatLayerEnv() {
const env = conversations();
const textwrap = load('app/graphics/textwrap.ts', {});
const { BdfFont } = load('app/graphics/bdffont.ts', { '@nativescript/core': {} });
const graphics = load('app/graphics/image.ts', { './textwrap': textwrap });
const graphics = require('../.test-build/app/graphics/image.js');
const font = BdfFont.parse(fs.readFileSync(path.join(__dirname, '../app/fonts/terminus/ter-u12n.bdf'), 'utf8'));
let windowOptions;
const { createAiChatWindow } = load('app/apps/ai-chat/ai-chat-app.ts', {
+198
View File
@@ -0,0 +1,198 @@
const test = require('node:test')
const assert = require('node:assert/strict')
const { AncsClient } = require('../.test-build/app/g2/ancs-client.js')
const le = n => [n&255,n>>>8&255,n>>>16&255,n>>>24]
function setup(t, token=123, maxWrite=20) {
const sent=[], changed=[]
const client=new AncsClient(async b=>sent.push([...b]), (...args)=>changed.push(args))
t.after(()=>client.stop()); client.start(token,maxWrite)
let seq=0
const frame=(kind,bytes,flags=3,sequence=seq++,nonce=token)=>new Uint8Array([65,78,1,kind,...le(nonce),sequence&255,sequence>>8,flags,...bytes])
const feed=(kind,bytes)=> {
if (!bytes.length) return client.receive(frame(kind,[]))
for(let i=0;i<bytes.length;i+=9) client.receive(frame(kind,bytes.slice(i,i+9),(i===0?1:0)|(i+9>=bytes.length?2:0)))
}
const source=(uid,event=0,flags=0)=>feed(1,[event,flags,1,1,...le(uid)])
const attr=(id,text)=> {const b=[...Buffer.from(text)];return [id,b.length&255,b.length>>8,...b]}
const details=(uid,title='Hello',body='Private message',appId='com.example')=>feed(2,[0,...le(uid),...attr(0,appId),...attr(1,title),...attr(3,body)])
const metadata=(uid,{subtitle='',size='',date='',positive='',negative=''}={})=>feed(2,[0,...le(uid),...attr(2,subtitle),...attr(4,size),...attr(5,date),...attr(6,positive),...attr(7,negative)])
const appName=(appId,name)=>feed(2,[1,...Buffer.from(appId),0,...attr(0,name)])
const deliver=(uid,appId='com.example',meta={})=> {
source(uid);feed(3,[]);details(uid,'Hello','Private message',appId);feed(3,[]);metadata(uid,meta)
}
const restart=()=>{seq=0;client.start(token,maxWrite);feed(0,[0]);feed(0,[1])}
feed(0,[0]); feed(0,[1])
return {client,sent,changed,frame,feed,source,attr,details,metadata,appName,deliver,restart}
}
test('receives fragmented UTF-8 notifications; pre-existing and modified items do not pop up',t=>{
const x=setup(t); x.source(7); x.feed(3,[]); x.details(7,'Hi 👓','Message café')
x.feed(3,[]);x.metadata(7)
assert.equal(x.client.read()[0].text,'Message café');assert.deepEqual(x.changed.at(-1),['ancs:123:7',true])
x.source(7,1);x.feed(3,[]);x.details(7,'Updated');x.feed(3,[]);x.metadata(7);assert.equal(x.changed.at(-1)[1],false)
x.source(8,0,4);x.feed(3,[]);x.details(8);x.feed(3,[]);x.metadata(8);assert.equal(x.changed.at(-1)[1],false)
assert.ok(x.sent.every(p=>p.length<=20))
})
test('removal during retrieval cannot resurrect notification',t=>{
const x=setup(t);x.source(7);x.source(7,2);x.details(7);x.feed(3,[])
assert.deepEqual(x.client.read(),[])
})
test('modification during retrieval ignores old text then retrieves new revision',t=>{
const x=setup(t);x.source(7);x.source(7,1);x.details(7,'Old');x.feed(3,[])
assert.deepEqual(x.client.read(),[]);x.feed(3,[]);x.details(7,'New');assert.equal(x.client.read()[0].title,'New')
})
test('disconnect, reused UID and delayed old-token packets cannot expose old content',t=>{
const x=setup(t);x.source(7);x.feed(3,[]);x.details(7);const key=x.client.read()[0].key
x.client.stop();assert.deepEqual(x.client.read(),[]);assert.equal(x.client.action(key,1),false)
x.client.start(456);x.client.receive(x.frame(1,[0,0,1,1,...le(7)],3,0,123));assert.deepEqual(x.client.read(),[])
assert.equal(x.client.state,'starting')
})
test('sequence gaps and oversized attributes fail closed and erase partial state',t=>{
const x=setup(t);x.source(7);x.client.receive(x.frame(2,[0,...le(7),0,255,255],3,33));assert.equal(x.client.state,'unavailable');assert.deepEqual(x.client.read(),[])
})
test('attribute overflow is rejected without allocation from untrusted lengths',t=>{
const x=setup(t);x.source(7);x.feed(2,[0,...le(7),0,255,255]);assert.equal(x.client.state,'unavailable')
})
test('actions use supplied labels; local Dismiss never sends negative action',t=>{
const x=setup(t);x.source(7,0,24);x.details(7);x.feed(3,[])
assert.deepEqual(x.sent.at(-1).slice(8),[0,...le(7),2,128,0,4,5,6,7]);x.feed(3,[])
x.metadata(7,{positive:'Accept',negative:'Decline'})
const n=x.client.read()[0];assert.deepEqual(n.actions.map(a=>a.title),['Accept','Decline'])
assert.equal(x.client.action(n.key,0),true);assert.deepEqual(x.sent.at(-1).slice(8),[2,...le(7),0]);x.feed(3,[])
const count=x.sent.length;assert.equal(x.client.dismiss(n.key),true);assert.equal(x.sent.length,count)
})
test('does not start next CP transaction before previous write response',t=>{
const x=setup(t);x.source(1);x.source(2);x.details(1);assert.equal(x.sent.length,2)
x.feed(3,[]);assert.equal(x.sent.length,3)
})
test('active notifications and pending work are bounded',t=>{
const x=setup(t);for(let i=0;i<150;i++) x.source(i)
assert.ok(x.client.sources.size<=128);assert.ok(x.client.queue.length<=128)
})
test('stop during retry uses the firmware token actually sent, not the next attempt token',t=>{
const x=setup(t);x.client.receive(x.frame(1,[0,0,1,1,...le(7)],3,99))
assert.equal(x.client.state,'unavailable');assert.deepEqual([...x.client.stopCommand().slice(4)],le(123))
})
test('malformed UTF-8 preserves the valid text prefix',t=>{
const x=setup(t);x.source(7);x.feed(3,[])
x.feed(2,[0,...le(7),...x.attr(0,'com.example'),...x.attr(1,'Hello'),3,3,0,65,66,0xc3])
assert.equal(x.client.read()[0].text,'AB�')
})
test('startup diagnostics distinguish missing reply from an incomplete subscription', t => {
t.mock.timers.enable({apis:['setTimeout']})
const logs=[]; const client=new AncsClient(async()=>{},()=>{},message=>logs.push(message))
t.after(()=>client.stop());client.start(123)
t.mock.timers.tick(10000)
assert.equal(client.state,'unavailable');assert.match(client.statusMessage,/No notification relay response/)
t.mock.timers.tick(5000)
client.receive(new Uint8Array([65,78,1,0,...le(124),0,0,3,0]))
t.mock.timers.tick(10000)
assert.equal(client.state,'unavailable');assert.match(client.statusMessage,/did not finish subscribing/)
assert.ok(logs.some(message=>message.includes('accepted notification relay START')))
})
test('relay errors have a distinct message and clear any displayed content', t => {
const x=setup(t);x.source(7);x.feed(3,[]);x.details(7)
x.feed(0,[2]);assert.equal(x.client.state,'unavailable')
assert.match(x.client.statusMessage,/reported a notification relay error/)
assert.deepEqual(x.client.read(),[])
})
test('requests every notification attribute and uses the app display name for the first popup',t=>{
const x=setup(t,123,185), id='net.superblock.Pushover'
x.deliver(7,id,{subtitle:'A subtitle',size:'1024',date:'20260919T123456'})
assert.deepEqual(x.sent[1].slice(8),[0,...le(7),0,1,128,0,3,0,2])
assert.deepEqual(x.sent[2].slice(8),[0,...le(7),2,128,0,4,5,6,7])
assert.deepEqual(x.sent.at(-1).slice(8),[1,...Buffer.from(id),0,0])
assert.equal(x.client.read()[0].appName,'Pushover')
assert.equal(x.changed.some(([,popup])=>popup),false)
// Fragment the actual ANCS Data Source response, including the app ID and UTF-8.
x.feed(3,[])
for (const byte of [1,...Buffer.from(id),0,...x.attr(0,'Pushover — 通知')]) x.feed(2,[byte])
const n=x.client.read()[0]
assert.equal(n.appName,'Pushover — 通知');assert.equal(n.packageName,id)
assert.equal(n.subText,'A subtitle');assert.equal(n.messageSize,1024)
assert.equal(n.when,new Date(2026,8,19,12,34,56).getTime())
assert.deepEqual(x.changed.at(-1),['ancs:123:7',true])
assert.equal(x.client.state,'ready')
})
test('app names are cached per session and a name update does not trigger another popup',t=>{
const x=setup(t,123,185), id='com.example'
x.deliver(1,id);x.appName(id,'Example App')
assert.equal(x.changed.filter(([,popup])=>popup).length,1)
const count=x.sent.length
x.source(2);assert.equal(x.sent.length,count) // Still waiting for app CP acknowledgement.
x.feed(3,[]);x.feed(3,[]);x.details(2);x.feed(3,[]);x.metadata(2)
assert.equal(x.sent.filter(p=>p[8]===1).length,1)
assert.ok(x.client.read().every(n=>n.appName==='Example App'))
assert.equal(x.changed.filter(([,popup])=>popup).length,2)
x.restart();x.deliver(1,id)
assert.equal(x.client.read()[0].appName,'example')
assert.equal(x.sent.filter(p=>p[8]===1).length,2)
x.feed(3,[]);x.appName(id,'New Session Name')
assert.equal(x.client.read()[0].appName,'New Session Name')
})
test('missing display names use and cache the final bundle-ID component',t=>{
for(const name of ['', ' ', 'net.superblock.Pushover']) {
const x=setup(t,123,185), id='net.superblock.Pushover'
x.deliver(1,id);x.feed(3,[]);x.appName(id,name)
assert.equal(x.client.read()[0].appName,'Pushover')
x.deliver(2,id)
assert.equal(x.sent.filter(p=>p[8]===1).length,1)
}
})
test('minimum MTU and relay command limit fall back without sending an oversized app request',t=>{
for(const [maxWrite,id,expected,canRequest] of [
[20,'net.superblock.Pushover','Pushover',false],
[20,'com.short','short',true],
[80,'a'.repeat(67)+'.X','X',true],
[185,'a'.repeat(68)+'.X','X',false],
[185,'','Unknown app',false],
[185,'com.bad\0id','bad\0id',false],
]) {
const x=setup(t,123,maxWrite);x.deliver(1,id)
assert.equal(x.client.read()[0].appName,expected)
assert.equal(x.sent.some(p=>p[8]===1),canRequest)
assert.ok(x.sent.every(p=>p.length<=Math.min(maxWrite,80)))
if(!canRequest) assert.deepEqual(x.changed.at(-1),['ancs:123:1',true])
}
})
test('app response must match the requested identifier and reject malformed attributes',t=>{
for(const response of [
x=>[1,...Buffer.from('com.wrong'),0,...x.attr(0,'Wrong')],
x=>[1,...Buffer.from('com.example'),0,0,1,2],
x=>[1,...Buffer.from('com.example'),0,...x.attr(1,'Wrong attribute')],
x=>[1,...Buffer.from('com.exampleX')],
]) {
const x=setup(t,123,185);x.deliver(1);x.feed(2,response(x))
assert.equal(x.client.state,'unavailable');assert.deepEqual(x.client.read(),[])
}
})
test('removal or modification during app lookup cannot resurrect or pop up a stale notification',t=>{
for(const event of [1,2]) {
const x=setup(t,123,185);x.deliver(1);x.source(1,event)
x.appName('com.example','Example App');x.feed(3,[])
assert.equal(x.changed.some(([,popup])=>popup),false)
if(event===2) assert.deepEqual(x.client.read(),[])
else {
x.feed(3,[]);x.details(1,'Updated');x.feed(3,[]);x.metadata(1)
assert.equal(x.client.read()[0].title,'Updated')
assert.equal(x.client.read()[0].appName,'Example App')
assert.equal(x.changed.at(-1)[1],false)
}
}
})
test('missing or invalid date and message size preserve arrival time and omit invalid size',t=>{
for(const [date,size] of [['',''],['20260230T123456','oops'],['20260919T256100','9007199254740992']]) {
const x=setup(t);x.deliver(1,'com.example',{date,size})
const n=x.client.read()[0]
assert.equal(n.when,n.postTime);assert.equal(n.messageSize,undefined)
}
})
+4 -1
View File
@@ -100,7 +100,7 @@ test('Navigate resize preserves its active route and window, and remeasures an o
menu: { resize: (size) => { menuSize = size; } }, lastSubmittedFingerprint: 'old' };
const route = { destination: 'Home' };
const resize = resizeHandler('app/apps/navigate/navigate-app.worker.ts', {
window, route, render: () => { paints++; },
window, route, phase: 'navigating', render: () => { paints++; },
});
resize({ width: 576, height: 260 });
assert.equal(window.viewportHeight, 260);
@@ -148,6 +148,9 @@ test('resizing a terminal reconnects with the new grid and ignores callbacks fro
},
} } },
};
const socketContext = { exports: {}, com: context.com };
vm.runInNewContext(js(read('app/native/socket.ts')), socketContext);
context.require = name => name === './socket' ? socketContext.exports : {};
vm.runInNewContext(js(read('app/native/g2mirror-client.ts')), context);
const client = new context.exports.G2MirrorClient({ host: 'localhost', port: 1234, cols: 72, rows: 28 });
client.start();
+24
View File
@@ -0,0 +1,24 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { BleBandwidthMeter } = require('../.test-build/app/phone-ui/ble-bandwidth-meter.js');
test('bandwidth meter matches Android units, includes control bytes and counts acknowledged frames', () => {
const meter = new BleBandwidthMeter();
assert.equal(meter.sample({ messages: 10, bytes: 1000, frames: 2 }, 0), 'BLE sent: 10 messages, 1,000 bytes');
assert.equal(meter.sample({ messages: 13, bytes: 4000, frames: 4 }, 1000),
'BLE sent: 13 messages, 4,000 bytes · 3.0 kB/s, 2.0 fps, 1,500 B/frame');
meter.reset();
meter.sample({ messages: 0, bytes: 0, frames: 0 }, 0);
assert.equal(meter.sample({ messages: 1, bytes: 20, frames: 0 }, 1000), 'BLE sent: 1 messages, 20 bytes · 20 B/s, 0.0 fps');
});
test('bandwidth rates decay to zero at idle and reset over suspend/toggle/counter resets', () => {
const meter = new BleBandwidthMeter();
meter.sample({ messages: 0, bytes: 0, frames: 0 }, 0);
for (let second = 1; second <= 6; second++) {
const label = meter.sample({ messages: 10, bytes: 5000, frames: 5 }, second * 1000);
if (second === 6) assert.match(label, /0 B\/s, 0.0 fps$/);
}
meter.reset();
assert.doesNotMatch(meter.sample({ messages: 20, bytes: 9000, frames: 10 }, 20000), /fps/);
assert.doesNotMatch(meter.sample({ messages: 0, bytes: 0, frames: 0 }, 21000), /fps/);
assert.doesNotMatch(meter.sample({ messages: 1, bytes: 10, frames: 0 }, 30000), /fps/);
});
+53
View File
@@ -0,0 +1,53 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const { normalizeBrightnessCurve, brightnessCurveError, DEFAULT_BRIGHTNESS_CURVE } = require('../.test-build/app/g2/brightness-curve.js');
test('brightness curve accepts monotone knots and canonicalizes spacing', () => {
assert.equal(normalizeBrightnessCurve(' 0:0, 2.5:20,1000:100 '), '0:0,2.5:20,1000:100');
});
test('invalid brightness drafts survive editing and report an error', () => {
for (const text of ['', '0:0', '1:0,100:100', '0:0,1:80,2:50,3:100', '0:0,0:100', '0:0,NaN:100', '0:0,1:99', '0:0,1e9:100', ':0,1:100']) {
assert.equal(normalizeBrightnessCurve(text), text);
assert.ok(brightnessCurveError(text), text);
}
});
test('only the previous default migrates to the calibrated curve', () => {
assert.equal(normalizeBrightnessCurve('0:0,1:10,10:30,100:65,1000:100'), DEFAULT_BRIGHTNESS_CURVE);
assert.equal(normalizeBrightnessCurve('0:0,3:50,10:100'), '0:0,3:50,10:100');
});
const fs = require('node:fs'), vm = require('node:vm'), ts = require('typescript');
function settingsFixture(store = new Map()) {
const context = { exports: {}, global: { isIOS: false }, require: id => {
if (id.includes('settings-store')) return {
onSettingsStoreChanged() {}, getStringSetting: (k, d) => store.get(k) ?? d,
setStringSetting: (k, v) => store.set(k, v),
};
if (id.includes('brightness-curve')) return require('../.test-build/app/g2/brightness-curve.js');
return { Layer: class {}, ASSISTANT_MODEL_CHOICES: [] };
}};
vm.runInNewContext(ts.transpileModule(fs.readFileSync('app/ui/dashboard-settings.ts', 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, context);
return context.exports;
}
test('auto minimum defaults to 20 and preserves a saved preference', () => {
assert.equal(settingsFixture().getBrightnessPreferences().minimum, 20);
assert.equal(settingsFixture(new Map([['display.autoBrightnessMin', '25']])).getBrightnessPreferences().minimum, 25);
});
test('curve drafts preview exactly while brightness keeps the previous valid saved curve', () => {
const store = new Map([['display.autoBrightnessCurve', '0:0,2:50,8:100']]);
let api = settingsFixture(store), curve = api.autoBrightnessCurveSetting;
assert.equal(api.getBrightnessPreferences().minimum, 20);
curve.set('0:0,2:50,8:');
assert.equal(curve.get(), '0:0,2:50,8:');
assert.ok(curve.validationError());
assert.equal(api.getBrightnessPreferences().curve, '0:0,2:50,8:100');
// Restart keeps the draft and the last accepted curve separate.
api = settingsFixture(store); curve = api.autoBrightnessCurveSetting;
assert.equal(curve.get(), '0:0,2:50,8:');
assert.equal(api.getBrightnessPreferences().curve, '0:0,2:50,8:100');
curve.set('0:0,2:50,6:100');
assert.equal(curve.validationError(), null);
assert.equal(api.getBrightnessPreferences().curve, '0:0,2:50,6:100');
});
+7 -3
View File
@@ -15,7 +15,7 @@ function load(file, modules = {}) {
}
const textwrap = load('app/graphics/textwrap.ts');
const graphics = load('app/graphics/image.ts', { './textwrap': textwrap });
const graphics = require('../.test-build/app/graphics/image.js');
const plane = load('app/graphics/plane.ts', { './image': graphics });
const gestures = load('app/ui/gestures.ts');
const numeric = load('app/util/numeric-util.ts');
@@ -27,8 +27,12 @@ const layers = load('app/ui/layers.ts', {
'../native/frame-timings': { spanCurrent: (_name, paint) => paint() },
});
const menu = load('app/ui/menu.ts', {
'./menu-highlight-motion': require('../.test-build/app/ui/menu-highlight-motion.js'), '../graphics/menu-scroll-list': require('../.test-build/app/graphics/menu-scroll-list.js'), './menu-scroll-motion': require('../.test-build/app/ui/menu-scroll-motion.js'), '../graphics/draw-expression': require('../.test-build/app/graphics/draw-expression.js'),
'../graphics/image': graphics, '../graphics/ui-fonts': fonts, '../graphics/textwrap': textwrap,
'../util/numeric-util': numeric, './gestures': gestures, './metrics': load('app/ui/metrics.ts'),
'./menu-core': load('app/ui/menu-core.ts', {
'../graphics/image': graphics, './menu-highlight-motion': require('../.test-build/app/ui/menu-highlight-motion.js'), '../graphics/menu-scroll-list': require('../.test-build/app/graphics/menu-scroll-list.js'), './menu-scroll-motion': require('../.test-build/app/ui/menu-scroll-motion.js'), '../graphics/draw-expression': require('../.test-build/app/graphics/draw-expression.js'),
}),
});
function fixture(initial = '50', viewport = { x: 64, y: 124, width: 576, height: 260 }) {
@@ -62,9 +66,9 @@ test('swipes change the saved level by 10, clamp at both ends, and both tap gest
await f.input('click'); assert.ok(f.stack.isAtBase()); assert.equal(f.closed(), 1);
f.open();
for (let i = 0; i < 12; i++) await f.input('scroll-down');
assert.equal(f.value(), '0'); assert.equal(f.writes(), 17);
assert.equal(f.value(), '2'); assert.equal(f.writes(), 17);
await f.input('double-click'); assert.ok(f.stack.isAtBase()); assert.equal(f.closed(), 2);
assert.equal(f.value(), '0');
assert.equal(f.value(), '2');
});
test('enabling Auto while the picker is open prevents manual changes', async () => {
+44
View File
@@ -0,0 +1,44 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { loader } = require('./helpers/load-typescript.cjs');
const payload = new Uint8Array([5, 4, 1, 0xb8, 0x0b, 25, 80, 0]);
test('iOS game worker forwards an immutable byte payload through its host and ignores closed windows', async () => {
const played = [], worker = { postMessage() {} };
const load = loader({ global: { isIOS: true, postMessage: data => worker.onmessage({ data }) } }, {
'../../graphics/image': {}, './chrome-layer': { windowIcon() {} },
'../../assistant/tool-registry': { toolRegistry: { removeAppTools() {} } },
'./geometry': { appViewportSize: () => ({ width: 576, height: 260 }) },
'../../native/frame-timings': {}, './worker-state': {},
'./shell': { shell: { registerWindow() {} } },
});
const { WorkerAppHost } = load('app/ui/shell/worker-window.ts');
const bridge = load('app/native/worker-buzzer.ts');
const host = new WorkerAppHost({ appId: 'blocks', worker, configureSurface: async () => {},
requestShellRender() {}, removeSurface() {}, playBuzzerSequence: bytes => played.push(bytes) });
bridge.playWorkerBuzzerSequence(payload);
assert.equal(played.length, 0);
const window = host.openWindow({ windowId: 'blocks', title: 'Blocks' });
const backing = new Uint8Array(payload.length + 2); backing.set(payload, 1);
bridge.playWorkerBuzzerSequence(backing.subarray(1, -1)); backing.fill(0);
assert.deepEqual(played, [payload]);
window.close(); bridge.playWorkerBuzzerSequence(payload);
assert.equal(played.length, 1);
});
test('Android game bridge retains direct native playback and skips a missing communicator', () => {
let active = null;
const played = [];
// Stands in for the reused Java direct buffer: the payload reaches Java as a
// copy, never as the caller's own ArrayBuffer.
const directBuffer = { JavaDirectBuffer: class { load(bytes) { return { bytes: bytes.slice() }; } } };
const bridge = loader({ global: { isIOS: false },
com: { faceclaw: { app: { FaceclawBleCommunicator: { getActive: () => active } } } } },
{ './java-direct-buffer': directBuffer })('app/native/worker-buzzer.ts');
bridge.playWorkerBuzzerSequence(payload);
active = { playBuzzerSequence: buffer => played.push(buffer.bytes) };
const backing = new Uint8Array(payload.length + 2); backing.set(payload, 1);
bridge.playWorkerBuzzerSequence(backing.subarray(1, -1)); backing.fill(0);
assert.deepEqual(played, [payload]);
});
+195
View File
@@ -0,0 +1,195 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { loader } = require('./helpers/load-typescript.cjs');
function harness(provider = 'elevenlabs', continuous = true) {
const timers = new Map();
let timerId = 0;
const sockets = [];
const events = [], statuses = [], errors = [];
const load = loader({
setTimeout(fn, delay) { const id = ++timerId; timers.set(id, { fn, delay }); return id; },
clearTimeout(id) { timers.delete(id); },
console: { log() {}, warn() {} },
com: { faceclaw: { app: {
FaceclawWebSocketListener: function(callbacks) { return callbacks; },
FaceclawWebSocket: class {
constructor(url, listener) { Object.assign(this, { url, listener, sent: [], closed: false, reject: false }); sockets.push(this); }
sendText(text) { if (this.reject) return false; this.sent.push(text); return true; }
sendBinary(bytes) { if (this.reject) return false; this.sent.push(bytes); return true; }
close() { this.closed = true; }
}, } }, },
}, {
'./cloud-stt': {
CLOUD_STT_SAMPLE_RATE: 16000,
encodeBase64: bytes => Buffer.from(bytes).toString('base64'),
toJavaBytes: bytes => bytes,
},
});
const names = { elevenlabs: 'ElevenLabsSttClient', openai: 'OpenAiRealtimeSttClient', soniox: 'SonioxSttClient' };
const Provider = load(`app/native/${provider}-stt.ts`)[names[provider]];
const { ReconnectingSttClient } = load('app/native/reconnecting-stt.ts');
const client = new ReconnectingSttClient(options => new Provider(options), {
apiKey: 'test', onTranscript: event => events.push(event),
onStatus: status => statuses.push(status), onError: error => errors.push(error),
}, () => continuous);
client.start();
return { client, sockets, events, statuses, errors, timers,
open() { sockets.at(-1).listener.onOpen(); },
message(message, socket = sockets.at(-1)) { socket.listener.onTextMessage(JSON.stringify(message)); },
tick() { const [id, timer] = timers.entries().next().value; timers.delete(id); timer.fn(); return timer.delay; },
};
}
function pcm(amplitude, ms = 50) {
const bytes = new Uint8Array(ms * 32);
for (let i = 0; i < bytes.length; i += 2) { bytes[i] = amplitude & 255; bytes[i + 1] = amplitude >> 8; }
return bytes;
}
for (const provider of ['elevenlabs', 'openai', 'soniox']) {
test(`${provider}: failure and close reconnect, stale callbacks are ignored, stop cancels retry`, () => {
const h = harness(provider);
h.open();
const old = h.sockets[0];
old.listener.onFailure('network unavailable');
old.listener.onClosed(); // Both callbacks must schedule only one retry.
assert.equal(h.timers.size, 1);
assert.equal(old.closed, true);
h.client.acceptPcm(pcm(2000));
assert.equal(h.tick(), 1000);
assert.equal(h.sockets.length, 2);
h.open();
assert.ok(h.sockets[1].sent.length > 0);
const eventCount = h.events.length;
old.listener.onTextMessage(JSON.stringify({ message_type: 'partial_transcript', text: 'stale' }));
old.listener.onOpen();
assert.equal(h.events.length, eventCount);
h.sockets[1].listener.onClosed();
assert.equal(h.timers.size, 1);
h.client.stop();
assert.equal(h.timers.size, 0);
});
test(`${provider}: rejected audio send triggers recovery and requeues the packet`, () => {
const h = harness(provider);
h.open();
h.sockets[0].reject = true;
h.client.acceptPcm(pcm(2000));
assert.equal(h.timers.size, 1);
h.tick(); h.open();
assert.ok(h.sockets[1].sent.length > (provider === 'elevenlabs' ? 0 : 1));
h.client.stop();
});
test(`${provider}: auth failure stops instead of retrying indefinitely`, () => {
const h = harness(provider);
h.sockets[0].listener.onFailure("Expected HTTP 101 response but was '401 Unauthorized'");
assert.equal(h.timers.size, 0);
assert.equal(h.errors.length, 1);
});
}
test('reconnect preserves visible partials once and does not replay already-sent audio', () => {
const h = harness(); h.open();
h.client.acceptPcm(pcm(2000));
h.message({ message_type: 'partial_transcript', text: 'Before outage' });
h.sockets[0].listener.onFailure('offline');
assert.equal(h.events.at(-1).text, 'Before outage');
assert.equal(h.events.at(-1).isFinal, true);
h.tick(); h.open();
assert.equal(h.sockets[1].sent.length, 0);
h.message({ message_type: 'partial_transcript', text: 'After outage' });
assert.equal(h.events.at(-1).text, 'After outage');
h.client.stop();
});
test('pending audio is bounded to ten seconds and backoff is capped', () => {
const h = harness();
for (let i = 0; i < 20; i++) h.client.acceptPcm(pcm(i, 1000));
h.open();
const sentBytes = h.sockets[0].sent.reduce((sum, text) => sum + Buffer.from(JSON.parse(text).audio_base_64, 'base64').length, 0);
assert.equal(sentBytes, 320000);
for (const delay of [1000, 2000, 4000, 8000, 16000, 30000, 30000]) {
h.sockets.at(-1).listener.onFailure('offline');
assert.equal(h.tick(), delay);
}
h.client.stop();
});
test('finishing while disconnected cancels retries; finishing on an open socket times out cleanly', () => {
const h = harness(); h.open();
h.sockets[0].listener.onClosed();
h.client.finish();
assert.equal(h.timers.size, 0);
const live = harness(); live.open();
live.client.finish();
assert.equal(live.tick(), 5000);
assert.equal(live.sockets[0].closed, true);
live.sockets[0].listener.onFailure('late');
assert.equal(live.timers.size, 0);
});
test('only continuous capture commits at pauses, keeping ElevenLabs connected', () => {
for (const continuous of [false, true]) {
const h = harness('elevenlabs', continuous); h.open();
h.client.acceptPcm(pcm(3000));
h.client.acceptPcm(pcm(0, 1500));
const commits = h.sockets[0].sent.map(JSON.parse).filter(m => m.commit);
assert.equal(commits.length, continuous ? 1 : 0);
if (continuous) {
h.message({ message_type: 'committed_transcript', text: 'First.' });
h.message({ message_type: 'committed_transcript_with_timestamps', text: 'First.' });
assert.equal(h.events.length, 1);
assert.equal(h.events[0].paragraphBreakAfter, true);
assert.equal(h.sockets[0].closed, false);
}
h.client.stop();
}
});
test('OpenAI keeps successive items separate and drains out-of-order completions in audio order', () => {
const h = harness('openai'); h.open();
h.client.acceptPcm(pcm(3000)); h.client.acceptPcm(pcm(0, 1500));
h.message({ type: 'input_audio_buffer.committed', item_id: 'a' });
h.message({ type: 'conversation.item.input_audio_transcription.delta', item_id: 'a', delta: 'Fir' });
h.client.acceptPcm(pcm(3000)); h.client.acceptPcm(pcm(0, 1500));
h.message({ type: 'input_audio_buffer.committed', item_id: 'b' });
h.message({ type: 'conversation.item.input_audio_transcription.completed', item_id: 'b', transcript: 'Second.' });
assert.equal(h.events.some(e => e.isFinal), false);
h.message({ type: 'conversation.item.input_audio_transcription.completed', item_id: 'a', transcript: 'First.' });
assert.deepEqual(h.events.filter(e => e.isFinal).map(e => e.text), ['First.', 'Second.']);
assert.equal(h.sockets[0].closed, false);
h.message({ type: 'conversation.item.input_audio_transcription.delta', item_id: 'c', delta: 'Third.' });
assert.equal(h.events.at(-1).text, 'Third.');
h.client.stop();
});
test('Soniox speaker and pause formatting remains separate from dictation text and resets on finalize', () => {
const h = harness('soniox'); h.open();
h.message({ tokens: [
{ text: 'Hello.', start_ms: 0, end_ms: 500, speaker: '1', is_final: true },
{ text: ' Hi.', start_ms: 550, end_ms: 800, speaker: '2', is_final: false },
] });
assert.equal(h.events.at(-1).text, 'Hello. Hi.');
assert.equal(h.events.at(-1).transcribeText, 'Hello.\nHi.');
h.message({ tokens: [
{ text: ' Yes.', start_ms: 550, end_ms: 800, speaker: '2', is_final: true },
{ text: '<fin>', is_final: true },
] });
assert.equal(h.events.find(e => e.isFinal).transcribeText, 'Hello.\nYes.');
h.message({ tokens: [{ text: 'New.', start_ms: 3000, end_ms: 3400, speaker: '2', is_final: false }] });
assert.equal(h.events.at(-1).text, 'New.');
h.client.stop();
});
test('an unsolicited Soniox session end finalizes visible text and reconnects', () => {
const h = harness('soniox'); h.open();
h.message({ tokens: [{ text: 'Before expiry.', is_final: true }], finished: true });
assert.equal(h.events.at(-1).isFinal, true);
assert.equal(h.events.at(-1).text, 'Before expiry.');
assert.equal(h.timers.size, 1);
h.tick(); h.open();
assert.equal(h.sockets.length, 2);
h.client.stop();
});
-19
View File
@@ -1,19 +0,0 @@
const test = require('node:test');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
test('compass diagnostics decode with legacy and malformed-extension fallback', () => {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'faceclaw-compass-java-'));
const javaBin = (name) => process.env.JAVA_HOME ? path.join(process.env.JAVA_HOME, 'bin', name) : name;
try {
execFileSync(javaBin('javac'), ['-d', directory,
path.join(__dirname, '../App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/BleProtocol.java'),
path.join(__dirname, '../App_Resources/Android/src/main/java/com/faceclaw/app/util/CollectionUtils.java'),
path.join(__dirname, 'fixtures/CompassProtocolTest.java')], { stdio: 'pipe' });
execFileSync(javaBin('java'), ['-ea', '-cp', directory, 'com.faceclaw.app.CompassProtocolTest'], { stdio: 'pipe' });
} finally {
fs.rmSync(directory, { recursive: true, force: true });
}
});
@@ -17,19 +17,14 @@ function load(file, modules = {}, globals = {}) {
return context.exports;
}
const textwrap = load('app/graphics/textwrap.ts');
const graphics = load('app/graphics/image.ts', { './textwrap': textwrap });
const graphics = require('../.test-build/app/graphics/image.js');
const { BdfFont } = load('app/graphics/bdffont.ts', { '@nativescript/core': {} });
const font = (size) => BdfFont.parse(fs.readFileSync(path.join(__dirname, `../app/fonts/terminus/ter-u${size}n.bdf`), 'utf8'));
const small = font(18), large = font(32);
const diagnostics = { magneticAccuracy: 3, magneticAnomalies: 2, orientationSource: 3, flags: 0x8c, sampleTimeMs: 1234 };
function compass(width = 576, height = 260) {
const settings = new Map();
const debug = load('app/apps/compass/debug.ts', { '../../native/settings-store': {
getBooleanSetting: (key, fallback) => settings.get(key) ?? fallback,
setBooleanSetting: (key, value) => settings.set(key, value),
} });
let listener, window, renders = 0, pops = 0;
let listener, window;
class RecordingImage extends graphics.GrayImage {
texts = [];
drawText(font, x, y, text, value) {
@@ -56,64 +51,62 @@ function compass(width = 576, height = 260) {
'../../ui/shell/geometry': { screenCenterInViewportX: () => width / 2 - 32 },
'../../ui/shell/in-process-window': {
YieldAtRootLayer: class { constructor(layer) { return layer; } },
createInProcessWindow: (options) => { window = options; return { requestRender: () => ++renders }; },
createInProcessWindow: (options) => { window = options; return { requestRender() {} }; },
},
'../../ui/shell/shell': { shell: { isWindowVisible: () => true } },
'../../g2/android-permissions': { hasLocationPermission: () => false },
'../../native/location-permissions': { hasLocationPermission: () => false },
'./calibration': calibration,
'./calibration-layer': {}, './declination': { onDeclinationChanged: () => () => {} },
'./heading': { getNorthReference: () => 'magnetic', resolveHeading: (v) => ({ displayDegrees: v }) },
'./debug': debug,
}, { setInterval: () => 1, clearInterval() {} });
const ctx = { stack: { getBaseSize: () => ({ width, height }), pop: () => ++pops } };
const open = () => app.createCompassAppWindow({ onClosed() {} }); open();
return { open, debug, settings, menu: () => window.menuItems(),
toggle: () => window.menuItems().find((item) => item.label.startsWith('Debug information:')).onSelect(ctx),
const ctx = { stack: { getBaseSize: () => ({ width, height }), pop() {} } };
app.createCompassAppWindow({ onClosed() {} });
return { menu: () => window.menuItems(),
paint: () => window.baseLayer.paint(ctx),
heading: (info) => listener({ command: 15, headingDegrees: 359, diagnostics: info }),
renders: () => renders, pops: () => pops };
heading: (info) => listener({ command: 15, headingDegrees: 359, diagnostics: info }) };
}
test('debug toggle defaults off, repaints, closes menu and survives reopening', () => {
const app = compass(); app.heading(diagnostics);
assert.equal(app.debug.isCompassDebugEnabled(), false);
assert.ok(!app.paint().texts.some((t) => t.text.startsWith('Mag:')));
const before = app.renders(); app.toggle();
assert.equal(app.debug.isCompassDebugEnabled(), true);
assert.ok(app.renders() > before && app.pops() === 1);
app.open(); assert.equal(app.debug.isCompassDebugEnabled(), true);
app.toggle(); assert.equal(app.debug.isCompassDebugEnabled(), false);
const calibrationText = (image) => image.texts.find((t) => t.text.startsWith('Calibration:'));
const overlaps = (a, b) => a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height;
test('calibration readiness is always shown and the debug toggle is gone', () => {
const app = compass();
assert.ok(!app.menu().some((item) => item.label.startsWith('Debug information')));
assert.equal(calibrationText(app.paint()).text, 'Calibration: --');
app.heading(diagnostics);
assert.equal(calibrationText(app.paint()).text, 'Calibration: ●●●');
assert.ok(!app.paint().texts.some((t) => /^(Mag|Anom|Src):/.test(t.text)));
});
test('diagnostics sit to the right of the heading without overlap or clipping', () => {
for (const width of [240, 320, 576, 640]) {
const app = compass(width); app.toggle(); app.heading(diagnostics);
test('calibration dots track firmware magnetic accuracy and never go stale', () => {
const app = compass();
for (const [accuracy, dots] of [[0, '○○○'], [1, '●○○'], [2, '●●○'], [3, '●●●'], [4, '●●●'], [-1, '--']]) {
app.heading({ ...diagnostics, magneticAccuracy: accuracy });
assert.equal(calibrationText(app.paint()).text, `Calibration: ${dots}`, `accuracy ${accuracy}`);
}
app.heading(diagnostics);
// Legacy samples (no 0x80 flag) and missing diagnostics must replace the old value.
app.heading({ ...diagnostics, flags: 0 });
assert.equal(calibrationText(app.paint()).text, 'Calibration: --');
app.heading(diagnostics);
app.heading(undefined);
assert.equal(calibrationText(app.paint()).text, 'Calibration: --');
});
test('calibration readout fits the viewport without overlapping the heading or status', () => {
for (const [width, height] of [[240, 260], [320, 260], [576, 260], [640, 260], [576, 288], [576, 140]]) {
const app = compass(width, height); app.heading({ ...diagnostics, magneticAccuracy: 2 });
const image = app.paint();
const heading = image.texts.find((t) => t.text === '359° N');
for (const text of ['Mag: 3/3', 'Anom: 2', 'Src: RV']) {
const label = image.texts.find((t) => t.text === text);
assert.ok(label, text);
assert.ok(label.x > heading.x + heading.width);
assert.ok(label.x + label.width <= width && label.y + label.height <= image.height);
const label = calibrationText(image);
assert.ok(label.x >= 0 && label.y >= 0, `${width}x${height}`);
assert.ok(label.x + label.width <= width && label.y + label.height <= image.height, `${width}x${height}`);
for (const other of image.texts.filter((t) => t !== label)) {
assert.ok(!overlaps(label, other), `${width}x${height}: overlaps "${other.text}"`);
}
const status = image.texts.find((t) => t.text === 'Magnetic heading');
assert.ok(image.texts.filter((t) => t.text.startsWith('Src:')).every((t) => t.y + t.height < status.y));
if (process.env.COMPASS_PREVIEW && width === 576) {
if (process.env.COMPASS_PREVIEW && width === 576 && height === 260) {
fs.writeFileSync(process.env.COMPASS_PREVIEW, Buffer.concat([
Buffer.from(`P5\n${image.width} ${image.height}\n255\n`), Buffer.from(image.withDrawsBaked().pixels),
]));
}
}
});
test('legacy and missing samples replace diagnostics instead of leaving stale values', () => {
const app = compass(); app.toggle(); app.heading(diagnostics);
assert.ok(app.paint().texts.some((t) => t.text === 'Mag: 3/3'));
app.heading(undefined);
assert.ok(app.paint().texts.some((t) => t.text === 'unavailable'));
assert.ok(!app.paint().texts.some((t) => t.text === 'Mag: 3/3'));
assert.deepEqual(Array.from(app.debug.compassDebugLines({ ...diagnostics, flags: 0 })), ['Sample data', 'unavailable']);
for (const [source, name] of [[1, 'GRV'], [2, 'GMRV'], [3, 'RV']]) {
assert.equal(app.debug.compassDebugLines({ ...diagnostics, orientationSource: source })[2], `Src: ${name}`);
}
});
-154
View File
@@ -1,154 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const ts = require('typescript');
function load(file, requireModule, globals = {}) {
const source = fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
const js = ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText;
const context = { exports: {}, require: requireModule, ...globals };
vm.runInNewContext(js, context, { filename: file });
return context.exports;
}
const textwrap = load('app/graphics/textwrap.ts');
const graphics = load('app/graphics/image.ts', () => textwrap);
const { BdfFont } = load('app/graphics/bdffont.ts', () => ({}));
const font = (size) => BdfFont.parse(fs.readFileSync(
path.join(__dirname, `../app/fonts/terminus/ter-u${size}n.bdf`), 'utf8'));
const small = font(12);
const large = font(24);
function compass({ style, width = 576, height = 260 } = {}) {
const settings = new Map(style === undefined ? [] : [['compass.style', style]]);
let listener;
let window;
let renders = 0;
let pops = 0;
class RecordingImage extends graphics.GrayImage {
lines = [];
texts = [];
drawLine(...args) { this.lines.push(args); super.drawLine(...args); }
drawText(font, x, y, text, value) {
this.texts.push({ x, y, text, value });
super.drawText(font, x, y, text, value);
}
}
const modules = {
'../../graphics/ui-fonts': { getDefaultSmallFont: () => small, getDefaultLargeFont: () => large },
'../../graphics/image': { ...graphics, GrayImage: RecordingImage },
'../../graphics/textwrap': textwrap,
'../../native/settings-store': {
getStringSetting: (key, fallback) => settings.get(key) ?? fallback,
setStringSetting: (key, value) => settings.set(key, value),
},
'../../native/compass': {
COMPASS_CHANGED: 1, COMPASS_CALIBRATION_STARTED: 2, COMPASS_CALIBRATION_COMPLETE: 3,
addCompassListener: (fn) => { listener = fn; return () => {}; },
setCompassEnabled() {},
},
'../../ui/metrics': { lineStep: (font) => font.lineHeight + 2 },
'../../ui/shell/geometry': { screenCenterInViewportX: () => width - 320 },
'../../ui/shell/in-process-window': {
YieldAtRootLayer: class { constructor(layer) { return layer; } },
createInProcessWindow: (options) => { window = options; return { requestRender: () => renders++ }; },
},
'../../ui/shell/shell': { shell: { isWindowVisible: () => true } },
'../../g2/android-permissions': { hasLocationPermission: () => false },
'./calibration': { isCompassCalibrated: () => true, normalizeHeading: (n) => ((n % 360) + 360) % 360 },
'./calibration-layer': {},
'./compass-rose': load('app/apps/compass/compass-rose.ts', {
'../../graphics/image': { ...graphics, GrayImage: RecordingImage },
'./calibration': { normalizeHeading: (n) => ((n % 360) + 360) % 360 },
}),
'./declination': { onDeclinationChanged: () => () => {} },
'./heading': { getNorthReference: () => 'magnetic', resolveHeading: (n) => ({ displayDegrees: n }) },
};
const app = load('app/apps/compass/compass-app.ts', (name) => {
assert.ok(name in modules, `Unexpected dependency: ${name}`);
return modules[name];
}, { setInterval: () => 1, clearInterval() {} });
const ctx = { stack: { getBaseSize: () => ({ width, height }), pop: () => pops++ } };
const open = () => app.createCompassAppWindow({ onClosed() {} });
open();
return {
settings, open,
menu: () => window.menuItems(),
toggle: () => window.menuItems().find((item) => item.label.startsWith('Style:')).onSelect(ctx),
paint: () => window.baseLayer.paint(ctx),
heading: (degrees) => listener({ command: 1, headingDegrees: degrees }),
renders: () => renders,
pops: () => pops,
};
}
test('Circle is the default; the context menu switches, repaints and remembers the style', () => {
const app = compass();
assert.equal(app.menu()[0].label, 'Style: Circle');
const before = app.renders();
app.toggle();
assert.equal(app.menu()[0].label, 'Style: Strip');
assert.equal(app.settings.get('compass.style'), 'strip');
assert.equal(app.renders(), before + 1);
assert.equal(app.pops(), 1);
app.open();
assert.equal(app.menu()[0].label, 'Style: Strip');
app.toggle();
assert.equal(app.menu()[0].label, 'Style: Circle');
assert.equal(compass({ style: 'unknown' }).menu()[0].label, 'Style: Circle');
});
test('switching styles preserves the numeric readout and status at every display size', () => {
for (const [width, height] of [[576, 260], [576, 452], [640, 452]]) {
const app = compass({ width, height });
app.heading(82);
const circle = app.paint();
app.toggle();
const strip = app.paint();
assert.deepEqual(strip.texts.slice(0, 2), circle.texts);
assert.deepEqual(circle.texts.map((item) => item.text), ['82° E', 'Magnetic heading']);
}
});
test('strip ticks are 5 degrees apart on the full-display 23 degree scale', () => {
for (const width of [576, 640]) {
const app = compass({ style: 'strip', width });
app.heading(90);
const image = app.paint();
const top = image.lines[0][1];
const ticks = image.lines.filter(([x0, y0, x1]) => x0 === x1 && y0 === top);
assert.deepEqual(ticks.map(([x]) => x), [80, 85, 90, 95, 100]
.map((bearing) => Math.round(width - 320 + (bearing - 90) * 640 / 23))
.filter((x) => x >= 0 && x < width));
assert.equal(image.lines[0][0], 0);
assert.equal(image.lines[0][2], width - 1);
assert.equal(image.lines[1][1], image.height - 4);
assert.ok(image.texts.some(({ text }) => text === 'E'));
}
});
test('bearings scroll continuously through north with wrapped labels', () => {
const app = compass({ style: 'strip' });
const northX = (heading) => {
app.heading(heading);
const image = app.paint();
const north = image.texts.find(({ text }) => text === 'N');
assert.ok(north);
assert.ok(image.texts.some(({ text }) => text === '355°'));
assert.ok(image.texts.some(({ text }) => text === '5°'));
return north.x;
};
assert.ok(Math.abs(northX(359.9) - northX(0.1) - 0.2 * 640 / 23) <= 1);
});
test('a strip waiting for sensor data shows the rails without invented bearings', () => {
const app = compass({ style: 'strip' });
const image = app.paint();
assert.deepEqual(image.texts.map(({ text }) => text), ['--°', 'Waiting for compass data…']);
assert.equal(image.lines.length, 2);
assert.ok(image.lines[0][4] < 105);
});
+5 -5
View File
@@ -19,7 +19,7 @@ function load(file, modules = {}, extra = '', globals = {}) {
const textwrap = load('app/graphics/textwrap.ts');
const { BdfFont } = load('app/graphics/bdffont.ts', { '@nativescript/core': {} });
const graphics = load('app/graphics/image.ts', { './textwrap': textwrap });
const graphics = require('../.test-build/app/graphics/image.js');
const { GrayImage } = graphics;
const font = (size) => BdfFont.parse(fs.readFileSync(
path.join(__dirname, `../app/fonts/terminus/ter-u${size}n.bdf`), 'utf8'));
@@ -43,11 +43,10 @@ const compass = load('app/apps/compass/compass-app.ts', {
'../../ui/shell/geometry': { screenCenterInViewportX: () => viewportWidth - 320 },
'../../ui/shell/in-process-window': {},
'../../ui/shell/shell': {},
'../../g2/android-permissions': {},
'../../native/location-permissions': {},
'./calibration': calibration,
'./calibration-layer': {},
'./compass-rose': rose,
'./debug': { compassDebugLines: () => [], isCompassDebugEnabled: () => false, setCompassDebugEnabled: () => {} },
'./declination': {},
'./heading': { getNorthReference: () => 'magnetic', resolveHeading: (n) => ({ displayDegrees: n }) },
}, `
@@ -149,13 +148,14 @@ test('heading updates reuse the texture; brightness, layout and clipping changes
test('the background registers once and uses a nine-byte image reference on later frames', () => {
const registered = [];
const { prepareFrameDraws } = load('app/graphics/glyph-wire.ts', {}, '', {
const atlas = load('app/native/texture-atlas.ts', { './java-direct-buffer': { copyToJavaByteBuffer: (bytes) => bytes } }, '', {
global: { isAndroid: true },
com: { faceclaw: { app: { ImageAtlas: { ensure: (...args) => {
com: { faceclaw: { app: { AndroidByteReader: class { constructor(buffer) { this.buffer = buffer; } }, ImageAtlas: { ensure: (...args) => {
registered.push(args);
return 1;
} } } } },
});
const { prepareFrameDraws } = load('app/graphics/glyph-wire.ts', { '../native/texture-atlas': atlas, './presentation-wire': require('../.test-build/app/graphics/presentation-wire.js') });
const background = compass.createCompassBackground(576, 260, 256, 193.25, 98, 140, 1);
for (const heading of [0, 1, 2, 45, 90]) {
const image = background.clone();
+129
View File
@@ -0,0 +1,129 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { DrawExpression: E, ExprOp, varint, DrawBytes, evaluate } = require('../.test-build/app/graphics/draw-expression.js');
const { DrawOp, SCREEN, encodeDisplayList, readDisplayList, paintDisplayList } = require('../.test-build/app/graphics/display-list.js');
const { GrayImage } = require('../.test-build/app/graphics/image.js');
const { encodePresentation } = require('../.test-build/app/graphics/presentation-wire.js');
// Also consumed by FrameDisplayListTest.kt: bridge bytes, not independently rebuilt native calls.
const MENU = '077e0000000300020002000200022a00000096000000010002000200ffffffff0200080000ff24017e30020000000001812c8001812c1611010017328001812c16103001812c3023414031ff24017c30020000000001812c8001812c1611010017328001812c16103001812c302341403102000200010001030400000000000000001f';
const MULTI = '0744000000030002000400010002000000000000000002000200010000ff010001006003000400000000000000001f0200000100000001000100020002feffffff7f00010001007f00';
test('extended integers agree with firmware widths and sign extension', () => {
const vectors = [[63,'3f'],[-64,'40'],[64,'8040'],[-65,'bfbf'],[8191,'9fff'],[-8192,'a000'],[8192,'c02000'],[-8193,'dfdfff'],[1048575,'cfffff'],[-1048576,'d00000'],[1048576,'e0100000'],[-1048577,'efefffff'],[134217727,'e7ffffff'],[-134217728,'e8000000'],[134217728,'f008000000'],[2147483647,'f07fffffff'],[-2147483648,'f080000000']];
for (const [value, hex] of vectors) {
assert.equal(Buffer.from(varint(value)).toString('hex'), hex);
assert.equal(new DrawBytes(Buffer.from(hex, 'hex')).variable(), value);
}
for (const n of [0,127,128,16383,16384,2097151,2097152,268435455,268435456,4294967295]) assert.equal(new DrawBytes(Uint8Array.from(varint(n,false))).variable(false), n);
assert.throws(() => E.i32(2147483648));
assert.throws(() => E.f32(Infinity));
});
test('typed expressions follow i32/f32 arithmetic, easing, time and error semantics', () => {
assert.equal(evaluate(E.i32(2147483647).add(E.i32(1)),0).value, -2147483648);
assert.equal(evaluate(E.i32(7).neg().div(E.i32(2)),0).value, -3);
assert.equal(evaluate(E.i32(-2147483648).div(E.i32(-1)),0).value, -2147483648);
assert.equal(evaluate(E.f32(1.5).mul(E.f32(2)).toInt(),0).value, 3);
for (let op = ExprOp.SMOOTHSTEP; op <= ExprOp.EASE_IN_OUT_CUBIC; op++) {
assert.equal(evaluate(E.f32(0).ease(op),0).value, 0);
assert.equal(evaluate(E.f32(1).ease(op),0).value, 1);
}
assert.deepEqual(evaluate(E.i32(300).time(),0,150), {value:150,pending:true});
assert.deepEqual(evaluate(E.i32(300).time(),0,300), {value:300,pending:false});
assert.deepEqual(evaluate(E.i32(300).time().div(E.i32(0)),0,150), {value:0,pending:false});
assert.deepEqual(evaluate(E.decode(Uint8Array.of(ExprOp.IADD)),0), {value:0,pending:false});
// Delayed timelines: a later start holds at 0, an earlier one continues, a finished one is constant.
const pct = (d, delay, elapsed) => evaluate(E.progress(d, delay).mul(E.f32(100)).toInt(), elapsed).value;
assert.deepEqual([pct(200, 100, 50), pct(200, 100, 200), pct(200, -50, 0), pct(200, -50, 150), pct(200, -300, 0)], [0, 50, 25, 100, 100]);
assert.equal(Buffer.from(E.progress(300, 0).code).toString('hex'), Buffer.from(E.progress(300).code).toString('hex'));
});
test('menu authors the golden generic list and stable timeline identity', () => {
const original = Date.now; Date.now = () => 1150;
try {
const image = new GrayImage(8,4);
image.drawMenuSelection(new GrayImage(2,2,255),3,2,16,48,1,2,{dx:-2,dy:-4,startedAt:1000,token:42,durationMs:300});
assert.equal(Buffer.from(encodePresentation(image.draws[0])).toString('hex'), MENU);
const before = image.fingerprint(); Date.now = () => 1250;
assert.equal(image.fingerprint(), before, 'wall time does not change frame identity');
const decoded = readDisplayList(Buffer.from(MENU,'hex'),0,1150).placed;
const y = decoded.displayList.calls[0].y;
assert.deepEqual(evaluate(y,150,0), {value:-2,pending:true});
assert.deepEqual(evaluate(y,150,150), {value:0,pending:false});
assert.deepEqual(evaluate(y,300,0), {value:0,pending:false});
} finally { Date.now = original; }
});
test('local resources, relative placement, stereo and screen restoration round-trip', () => {
const list = { resources:[{width:2,height:1,pixels:Uint8Array.of(0,255)},{width:1,height:1,pixels:Uint8Array.of(96)}], calls:[
{op:DrawOp.IMAGE,resource:0,x:0,y:0,transparent:true},
{op:DrawOp.RECT_COPY,resource:1,x:0,y:0,width:1,height:1,dx:2,dy:0},
{op:DrawOp.RECT_COPY,resource:SCREEN,x:-1,y:0,width:1,height:1,dx:-1,dy:0,depth:-2},
] };
const bytes = encodeDisplayList({displayList:list,x:3,y:2,width:4,height:1,depth:2});
assert.equal(Buffer.from(bytes).toString('hex'), MULTI);
const {placed,end} = readDisplayList(bytes,0);
assert.equal(end,bytes.length);
for (const right of [false,true]) {
const screen = new Uint8Array(64).fill(32), output = screen.slice();
paintDisplayList(output,screen,8,8,placed,right);
assert.equal(output[2*8+(right?3:5)],240);
assert.equal(output[2*8+(right?4:6)],96);
assert.equal(output[2*8+2],32);
}
for (let i=0;i<bytes.length;i++) assert.throws(() => readDisplayList(bytes.slice(0,i),0));
const invalid = {...list, calls:[{op:DrawOp.IMAGE,resource:2,x:0,y:0,transparent:true}]};
assert.throws(() => encodeDisplayList({displayList:invalid,x:0,y:0,width:4,height:1,depth:0}));
});
test('frame submission supports resource-free lists and plain PRESENT-relative time', () => {
const image = new GrayImage(8,8);
image.drawDisplayList({resources:[],calls:[{op:DrawOp.ROUNDED_RECT,x:E.i32(4).time(),y:0,width:2,height:2,radius:0,background:15,border:16}]},0,0,8,8);
const bytes = encodePresentation(image.draws[0]);
const {placed} = readDisplayList(bytes,0,1000);
const output = new Uint8Array(64), screen = output.slice();
paintDisplayList(output,screen,8,8,placed,false,1002);
assert.equal(output[2],240); assert.equal(output[0],0);
});
// Also consumed by FrameDisplayListTest.kt, with 0xbeef / 0xcafebabe replaced by
// the font and image ids it registers: a clipped clear, a clipped rounded rect,
// and replayed glyph + icon draws clipped while sliding up. REPLAY_PIXELS is
// what the list paints over a nibble-1 screen, 16x8 at 4 bits per pixel.
const REPLAY = '0780000000020003000800040000070000006400000000000300890000000000000600040002880000010001000200020000000400030000000510a00000000000000600040000ff2502000080c002000000000180c8800180c8161101001732800180c81610300180c830234031020000efbe4100000000000000ff01bebafeca04000100';
const REPLAY_PIXELS = '11111111111111111111111111111111111111111111111111fff28f111111111125522211111111112552221111111111222222111111111111111111111111';
function replayList() {
// 'A' is 3x2 ink one row below a 4px line top; the icon is 2x2.
const font = { fingerprintId: 9001, atlasKey: 'stub-font', ascent: 3, lineHeight: 4 };
const glyph = { encoding: 65, bbxWidth: 3, bbxHeight: 2, bbxX: 0, bbxY: 0, bitmapRows: [0xa0, 0xe0] };
const icon = new GrayImage(2, 2); icon.pixels.set([255, 0, 128, 255]);
const source = new GrayImage(8, 4);
source.drawGlyph(font, glyph, 0, 0, 255);
source.drawImage(icon, 4, 1);
const records = Uint8Array.from([0, 0xef, 0xbe, 65, 0, 0, 0, 0, 0, 0, 0, 255, 1, 0xbe, 0xba, 0xfe, 0xca, 4, 0, 1, 0]);
const clip = { x: 0, y: 0, width: 6, height: 4 };
return { x: 2, y: 3, width: 8, height: 4, depth: 0, displayList: { resources: [], timeline: { token: 7, startedAt: 1000 }, calls: [
{ op: DrawOp.CLEAR, color: 2, clip },
{ op: DrawOp.ROUNDED_RECT, x: 0, y: 0, width: 4, height: 3, radius: 0, background: 5, border: 16, clip: { x: 1, y: 1, width: 2, height: 2 } },
{ op: DrawOp.DRAWS, x: 0, y: E.progress(200).lerp(E.f32(-4), E.f32(0)).toInt(), records, count: 2, source, clip },
] } };
}
test('clipped clears, rects and replayed draws encode, decode and paint', () => {
const placed = replayList();
const hex = Buffer.from(encodeDisplayList(placed, 1100)).toString('hex');
const output = new Uint8Array(16 * 8).fill(16);
paintDisplayList(output, output.slice(), 16, 8, placed, false, 1100);
const nibbles = Array.from(output, (v) => (Math.min(15, (v + 8) >> 4)).toString(16)).join('');
assert.equal(hex, REPLAY);
assert.equal(nibbles, REPLAY_PIXELS);
const decoded = readDisplayList(Buffer.from(REPLAY, 'hex'), 0, 1100).placed;
const [clear, rect, draws] = decoded.displayList.calls;
assert.deepEqual([clear.op, clear.color, clear.clip], [DrawOp.CLEAR, 2, { x: 0, y: 0, width: 6, height: 4 }]);
assert.deepEqual(rect.clip, { x: 1, y: 1, width: 2, height: 2 });
assert.equal(draws.count, 2);
assert.deepEqual(Array.from(draws.records), Array.from(placed.displayList.calls[2].records));
assert.equal(draws.source, undefined, 'decoded draws have no software source');
assert.throws(() => readDisplayList(Buffer.from(REPLAY.replace('01bebafeca', '05bebafeca'), 'hex'), 0, 1100), /draw record/);
});
+109
View File
@@ -0,0 +1,109 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { zstdCompressSync } = require('node:zlib');
const { loader } = require('./helpers/load-typescript.cjs');
const flush = () => new Promise(resolve => setImmediate(resolve));
function pack(files) {
const key = Buffer.from('EVEN REALITIES'), xor = b => Buffer.from(b.map((v, i) => v ^ key[i % key.length]));
const header = Buffer.alloc(20); header.write('EHPK'); header.writeUInt32LE(20, 8);
return Buffer.concat([header, ...Object.entries(files).map(([name, value]) => {
const raw = Buffer.from(value), body = zstdCompressSync(raw), path = Buffer.from(name), h = Buffer.alloc(16);
h.writeUInt32LE(0xbaa9bae4); h.writeUInt32LE(body.length, 4); h.writeUInt32LE(raw.length, 8); h.writeUInt16LE(path.length, 14);
return Buffer.concat([h, xor(path), xor(body)]);
})]);
}
function packageFixture() {
const expanded = [], files = new Map(), settings = new Map();
const bytes = pack({ 'app.json': JSON.stringify({ package_id: 'test.large', name: 'Large', permissions: [{ name: 'network' }] }),
'dist/index.html': '<html>Test</html>', 'dist/icon.svg': '<svg/>', 'dist/engine.wasm': 'abcdef'.repeat(2_000_000) });
const load = loader({ global: { isIOS: true } }, {
fzstd: { decompress: (input, output) => { expanded.push(output.length); return require('fzstd').decompress(input, output); } },
'../../native/file-access': { readBinaryFile: path => files.get(path) ?? null, readTextFile() {}, appFilesDirPath: () => '/app',
writeBinaryFile: (path, bytes) => { files.set(path, bytes); return true; },
deletePathRecursively: path => { for (const key of files.keys()) if (key.startsWith(path + '/')) files.delete(key); } },
'../../native/settings-store': { getStringSetting: (key, fallback) => settings.get(key) ?? fallback, setStringSetting: (key, value) => settings.set(key, value) },
'../../native/icon-image': {}, '../../graphics/icons': {}, '../../graphics/image': {},
});
files.set('/source.ehpk', bytes);
return { load, bytes, expanded, files };
}
test('permission inspection and installation never decompress the large app engine; extraction expands it once', () => {
const h = packageFixture(), installed = h.load('app/apps/evenhub/installed-apps.ts');
assert.equal(installed.readEvenHubPackageManifestBytes(h.bytes).packageId, 'test.large');
assert.equal(h.expanded.length, 1);
installed.installEvenHubPackageBytes(h.bytes);
assert.ok(h.expanded.every(size => size < 1024), 'Only manifest, HTML and icon are needed to install');
h.load('app/apps/evenhub/package-extraction.ts').extractPackage('/source.ehpk', '/runtime');
assert.equal(h.expanded.filter(size => size === 12_000_000).length, 1);
assert.equal(h.files.get('/runtime/dist/engine.wasm').length, 12_000_000);
});
test('store install releases serialized input before download and permission approval finish', async () => {
let completeDownload, dialog, installed = false, launched = false;
const download = new Promise(resolve => { completeDownload = resolve; });
const manifest = { name: 'Test', packageId: 'test', permissions: [{ name: 'network' }], privacyPolicyUrl: '' };
const load = loader({}, {
'../../graphics/ui-fonts': {}, '../../graphics/image': {}, '../../graphics/textwrap': {}, '../../ui/menu-core': require('../.test-build/app/ui/menu-core.js'), '../files/text-viewer': {}, '../../ui/metrics': {},
'./even-api': { evenHubApi: { getStoreAppDetail: async () => null, downloadApp: () => download } },
'./installed-apps': { getInstalledEvenHubApp: () => null, readEvenHubPackageManifestBytes: () => manifest,
readEvenHubPackageManifest: () => null, installedEvenHubPackagePath: () => '', installedEvenHubAppId: id => id,
installEvenHubPackageBytes: () => { installed = true; return { packageId: 'test', version: '1' }; } },
'./manager': { closeRunningPackage() {} }, './updates': {},
'./permission-dialog': { EvenHubPermissionDialogLayer: class {
constructor(_name, _permissions, _policy, allow) { this.allow = allow; }
handleInput() { this.allow(); }
} },
});
const { EvenHubStoreDetailLayer } = load('app/apps/evenhub/store-detail-layer.ts');
const layer = new EvenHubStoreDetailLayer({ packageId: 'test', name: 'Test' }, { appendLog() {}, launchApp: () => { launched = true; } });
const ctx = { actions: { requestRender() {} }, stack: { push: value => { dialog = value; } } };
let queue = Promise.resolve(), returned = false;
queue = queue.then(() => layer.handleInput({ type: 'click' }, ctx)).then(() => { returned = true; });
await flush(); assert.equal(returned, true, 'Input must return even while download is unresolved');
completeDownload({ bytes: new Uint8Array(20), privacyPolicyUrl: '' });
await flush(); assert.ok(dialog); assert.equal(installed, false);
queue = queue.then(() => dialog.handleInput({ type: 'click' }, ctx));
await queue; await flush();
assert.equal(installed, true); assert.equal(launched, true);
});
test('iOS extraction sends paths to a worker, leaves main responsive, and terminates on success or failure', async () => {
const workers = [], timers = new Map(); let serial = 0;
class Worker {
constructor() { workers.push(this); } postMessage(value) { this.request = value; } terminate() { this.terminated = true; }
}
const { unpackRuntime } = loader({ Worker, setTimeout: fn => { timers.set(++serial, fn); return serial; }, clearTimeout: id => timers.delete(id) })('app/apps/evenhub/unpack-runtime.ios.ts');
const work = unpackRuntime('/source.ehpk', '/runtime');
assert.deepEqual(JSON.parse(JSON.stringify(workers[0].request)), { path: '/source.ehpk', directory: '/runtime' });
await flush(); // The JS loop remains runnable while extraction is outstanding.
workers[0].onmessage({ data: { manifest: { packageId: 'test' } } });
assert.equal((await work).packageId, 'test'); assert.equal(workers[0].terminated, true); assert.equal(timers.size, 0);
const failed = unpackRuntime('/bad.ehpk', '/runtime');
workers[1].onerror({ message: 'fixture failure' });
await assert.rejects(failed, /fixture failure/); assert.equal(workers[1].terminated, true);
});
test('installed raster icons use the iOS decoder and retain decoded dimensions', () => {
const calls = [];
const iconLoader = loader({ global: { isIOS: true }, FaceclawGraphics: {
decodeImageFileMaxWidthMaxHeight: (path, width, height) => {
calls.push({ path, width, height });
return path.endsWith('missing.png') ? null : new Uint8Array([2, 0, 1, 0, 80, 255]);
},
} }, { './kotlin-data': { fromData: data => data } })('app/native/icon-image.ios.ts');
const installed = loader({}, {
'../../native/icon-image': iconLoader,
'../../native/file-access': { appFilesDirPath: () => '/app' },
'../../native/settings-store': {}, '../../graphics/icons': {}, fzstd: require('fzstd'),
})('app/apps/evenhub/installed-apps.ts');
const record = { packageId: 'test', installedAt: 'today', iconFile: 'icon.png' };
const image = installed.renderInstalledEvenHubIcon('test', 32, record);
assert.equal(image.width, 2); assert.equal(image.height, 1);
assert.deepEqual([...image.pixels], [80, 255]);
assert.equal(calls[0].path, '/app/evenhub-installed/test/icon.png');
assert.equal(calls[0].width, 32);
assert.equal(installed.renderInstalledEvenHubIcon('test', 32, record), image);
assert.equal(calls.length, 1);
assert.equal(iconLoader.loadIconImage('/missing.png', 32, 32), null);
});
+203
View File
@@ -0,0 +1,203 @@
// The EvenHub sign-in form's open/close contract, which is what made it
// impossible to get rid of: it used to open itself on the store layer's first
// paint (which includes the restore of a still-open EvenHub at startup), and
// submitting an untouched form reopened it, so with no Cancel control on the
// panel there was no way out.
//
// The real store layer runs here with its dependencies mocked, so these assert
// the layer's actual behavior rather than a reimplementation of it.
const test = require('node:test');
const assert = require('node:assert/strict');
const { loader } = require('./helpers/load-typescript.cjs');
const setting = (initial = '') => {
let value = initial;
return { get: () => value, set: (next) => { value = next; } };
};
class AuthError extends Error {}
/**
* Load the store layer, by default with a signed-out account and no stored
* credentials. `api` overrides evenHubApi methods; text the layer paints is
* collected in `drawn`, and the options each app page is opened with in
* `detailOptions`.
*/
const loadStoreLayer = ({ configured = false, api = {} } = {}) => {
const email = setting('');
const password = setting('');
const drawn = [];
const detailOptions = [];
const font = { lineHeight: 10, measureText: (text) => text.length * 6 };
const load = loader({}, {
'../../graphics/ui-fonts': { getDefaultSmallFont: () => font },
'../../graphics/image': { GrayImage: class { drawText(_f, _x, _y, text) { drawn.push(text); } fillRect() {} } },
'../../graphics/textwrap': { truncateText: (_f, text) => text, wrapText: (_f, text) => [text] },
'../../util/numeric-util': { clamp: (v, lo, hi) => Math.min(hi, Math.max(lo, v)) },
'../../ui/gestures': { GESTURE_CLICK: 'click' },
'../../ui/menu': { drawSelectionHighlight() {} },
'../../ui/menu-core': require('../.test-build/app/ui/menu-core.js'),
'../../ui/shell/shell': { shell: { yieldFocusToSidebar() {} } },
'../../ui/metrics': { lineStep: () => 12 },
'../../ui/dashboard-settings': {
ConfigSettingString: class { constructor(options) { this.value = options.defaultValue ?? ''; }
get() { return this.value; } set(next) { this.value = next; } },
},
'./even-api': {
evenHubApi: { signIn: async () => {}, ...api },
EvenHubAuthenticationError: AuthError,
isEvenHubStoreConfigured: () => configured,
},
'./credentials': {
evenHubLoginEmailSetting: email,
evenHubLoginPasswordSetting: password,
evenHubRememberMeSetting: { get: () => true, set() {} },
clearEvenHubLoginForm() { email.set(''); password.set(''); },
resetEvenHubLoginForm() { email.set(''); password.set(''); },
clearEvenHubSession() {}, clearTransientEvenHubSession() {},
},
'./installed-apps': { getInstalledEvenHubApps: () => [], uninstallEvenHubPackage: async () => {} },
'./store-detail-layer': { EvenHubStoreDetailLayer: class { constructor(_app, options) { detailOptions.push(options); } } },
'./store-install': { cleanError: (error) => String(error?.message ?? error), installStoreApp: async () => {} },
'./updates': { checkForEvenHubUpdates: async () => [], describeUpdate: () => '' },
});
const { EvenHubStoreLayer } = load('app/apps/evenhub/store-layer.ts');
return { EvenHubStoreLayer, email, password, drawn, detailOptions };
};
/** A LayerContext that records every editor the layer asks the phone to open. */
const makeCtx = () => {
const opened = [];
const stack = {
cleared: 0,
pushed: [],
getBaseSize: () => ({ width: 576, height: 136 }),
isFocused: () => true,
clearToBase() { stack.cleared++; stack.pushed.length = 0; },
push(layer) { stack.pushed.push(layer); },
};
return {
opened,
stack,
actions: {
requestRender() {},
endTextSettingEdit() {},
startTextSettingsEdit(settings, title, onFinish, toggle, onCancel) {
opened.push({ title, onFinish, onCancel });
},
},
};
};
const newLayer = () => {
const { EvenHubStoreLayer } = loadStoreLayer();
return new EvenHubStoreLayer({ launchApp: async () => {}, appendLog: () => {} });
};
const settle = () => new Promise((resolve) => setImmediate(resolve));
test('painting the signed-out store does not open the phone sign-in form by itself', () => {
const layer = newLayer(), ctx = makeCtx();
layer.paint(ctx);
layer.paint(ctx);
assert.deepEqual(ctx.opened, [], 'first paint runs on app-start restore too, so it must not open the editor');
});
test('a click on the login pane opens the sign-in form', () => {
const layer = newLayer(), ctx = makeCtx();
layer.paint(ctx);
layer.handleInput({ type: 'click' }, ctx);
assert.equal(ctx.opened.length, 1);
assert.equal(ctx.opened[0].title, 'Sign in to EvenHub');
assert.equal(typeof ctx.opened[0].onCancel, 'function', 'the editor must hand back a way to close it');
});
test('submitting an untouched sign-in form closes it instead of reopening it', async () => {
const layer = newLayer(), ctx = makeCtx();
layer.paint(ctx);
layer.handleInput({ type: 'click' }, ctx);
ctx.opened[0].onFinish();
await settle();
assert.equal(ctx.opened.length, 1, 'an empty submission is the only way out, so it must not reopen the editor');
});
test('a half-filled sign-in form is a mistake and reopens with the reason', async () => {
const { EvenHubStoreLayer, email } = loadStoreLayer();
const layer = new EvenHubStoreLayer({ launchApp: async () => {}, appendLog: () => {} });
const ctx = makeCtx();
layer.paint(ctx);
layer.handleInput({ type: 'click' }, ctx);
email.set('someone@example.com');
ctx.opened[0].onFinish();
await settle();
assert.equal(ctx.opened.length, 2);
assert.equal(ctx.opened[1].title, 'Sign in to EvenHub');
});
test('cancelling the sign-in form leaves it reopenable', () => {
const layer = newLayer(), ctx = makeCtx();
layer.paint(ctx);
layer.handleInput({ type: 'click' }, ctx);
ctx.opened[0].onCancel();
layer.handleInput({ type: 'click' }, ctx);
assert.equal(ctx.opened.length, 2, 'a dropped onCancel latches the guard and no later open is allowed');
});
test('an expired session drops the store back to the logged-out pane', async () => {
const { EvenHubStoreLayer, drawn } = loadStoreLayer({
configured: true,
api: { listApps: async () => { throw new AuthError('Your login is expired'); } },
});
const layer = new EvenHubStoreLayer({ launchApp: async () => {}, appendLog: () => {} });
const ctx = makeCtx();
layer.paint(ctx);
await settle();
assert.equal(layer.buildMenuItems().length, 0, 'the signed-in menu (Refresh, Log Out) is gone');
assert.equal(ctx.stack.cleared, 1, 'pages above the list needed the session too');
assert.deepEqual(ctx.opened, [], 'this can happen on a startup restore, so the form must not pop up by itself');
drawn.length = 0;
layer.paint(ctx);
assert.ok(drawn.includes('Signed out: Your login is expired'), `painted: ${JSON.stringify(drawn)}`);
layer.handleInput({ type: 'click' }, ctx);
assert.equal(ctx.opened.length, 1, 'a click on the pane opens the sign-in form');
});
test('an expired session on an app page drops the store back to the logged-out pane', () => {
const { EvenHubStoreLayer, detailOptions } = loadStoreLayer({
configured: true,
api: { listApps: () => new Promise(() => {}) },
});
const layer = new EvenHubStoreLayer({ launchApp: async () => {}, appendLog: () => {} });
const ctx = makeCtx();
layer.paint(ctx);
layer.showInstalledPackage(ctx.stack, { packageId: 'com.example.app', name: 'Example' });
assert.equal(ctx.stack.pushed.length, 1);
const { onAuthError } = detailOptions[0];
assert.equal(onAuthError(ctx, new Error('network down')), false, 'other failures stay on the page');
assert.ok(layer.buildMenuItems().length > 0);
assert.equal(onAuthError(ctx, new AuthError('Your login is expired')), true);
assert.equal(ctx.stack.pushed.length, 0, 'the app page is closed');
assert.equal(layer.buildMenuItems().length, 0);
});
test('an API envelope with code 401 is a rejected session and forgets the token', async () => {
let token = 'stale-token';
let invalidated = 0;
const api = loader({ setTimeout, clearTimeout }, {
'./even-platform': { getPhoneOpenUdid: () => 'fixture-terminal', hmacSha256Base64: () => 'fixture-signature' },
'./credentials': {
getEvenHubToken: () => token, hasEvenHubCredentials: () => !!token,
saveEvenHubSession() {}, invalidateEvenHubToken() { invalidated++; token = ''; },
},
'../../util/http': {
fetchWithUserAgent: async () => ({ status: 200, json: async () => ({ code: 401, msg: 'Your login is expired' }) }),
},
})('app/apps/evenhub/even-api.ts');
await assert.rejects(api.evenHubApi.listApps(), (error) => {
assert.ok(error instanceof api.EvenHubAuthenticationError, `got ${error}`);
assert.equal(error.message, 'Your login is expired');
return true;
});
assert.equal(invalidated, 1);
assert.equal(api.isEvenHubStoreConfigured(), false);
});
-19
View File
@@ -1,19 +0,0 @@
const test = require('node:test');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
test('CFW idle-gesture events decode to sys-event types and sources; wake and junk do not', () => {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'faceclaw-gesture-java-'));
const javaBin = (name) => process.env.JAVA_HOME ? path.join(process.env.JAVA_HOME, 'bin', name) : name;
try {
execFileSync(javaBin('javac'), ['-d', directory,
path.join(__dirname, '../App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/BleProtocol.java'),
path.join(__dirname, '../App_Resources/Android/src/main/java/com/faceclaw/app/util/CollectionUtils.java'),
path.join(__dirname, 'fixtures/FaceclawGestureEventTest.java')], { stdio: 'pipe' });
execFileSync(javaBin('java'), ['-ea', '-cp', directory, 'com.faceclaw.app.FaceclawGestureEventTest'], { stdio: 'pipe' });
} finally {
fs.rmSync(directory, { recursive: true, force: true });
}
});
+4 -2
View File
@@ -62,8 +62,10 @@ test("stock firmware classifies by base version and warns on the main screen", (
assert.equal(compat.classifyOnboardingFirmware(info("", "", "")).kind, "unknown");
assert.equal(compat.classifyOnboardingFirmware(info("", "2.2.9.22", "2.2.9.22")).kind, "flashable-stock");
assert.equal(compat.classifyOnboardingFirmware(info("", "2.2.4.34", "")).kind, "flashable-stock");
assert.equal(compat.classifyOnboardingFirmware(info("", "2.2.10.10", "2.2.10.10")).kind, "newer-stock-validated");
assert.equal(compat.classifyOnboardingFirmware(info("", "2.3.0.1", "2.3.0.1")).kind, "newer-stock-unvalidated");
assert.equal(compat.classifyOnboardingFirmware(info("", "2.2.10.10", "2.2.10.10")).kind, "flashable-stock");
assert.equal(compat.classifyOnboardingFirmware(info("", "2.3.0.1", "2.3.0.1")).kind, "flashable-stock");
assert.equal(compat.classifyOnboardingFirmware(info("", "2.3.0.24", "2.3.0.24")).kind, "flashable-stock");
assert.equal(compat.classifyOnboardingFirmware(info("", "2.3.0.24", "2.3.0.25")).kind, "newer-stock-unvalidated");
// Faceclaw firmware on a newer base is still judged by its revision, not the base.
assert.equal(compat.classifyOnboardingFirmware(info(`Faceclaw/${REQUIRED}`, "2.3.0.1", "2.3.0.1")).kind, "custom");
});
-137
View File
@@ -1,137 +0,0 @@
package com.faceclaw.app;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.CountDownLatch;
public final class RingHealthTransferTest implements AutoCloseable {
private final Object lock = new Object();
private final ArrayDeque<byte[]> ringOutbound = new ArrayDeque<>();
private final ScheduledExecutorService callbacks = Executors.newSingleThreadScheduledExecutor();
private final List<String> writes = new ArrayList<>();
private volatile boolean running = true;
private boolean ringConnected = true;
private boolean ringNotificationsReady = true;
private boolean ringHealthRspSeen;
private int ringHealthPageCounter;
private int seq;
private boolean failAck;
private boolean answer = true;
private boolean delayRsp;
private boolean pullRequested = true;
private final CountDownLatch requestStarted = new CountDownLatch(1);
private final String ringAddress = "ring";
private long ringReconnectAfterMs;
private static class ConnectionOptions { static final int RING_RECONNECT_DELAY_MS = 1000; }
private static class BleManager { void disconnect(String address) {} }
private final BleManager bleManager = new BleManager();
private static String safeMessage(Throwable t) { return t.getMessage(); }
private boolean shouldAttemptRingConnect() { return false; }
private void tryConnectRing(String reason) { throw new AssertionError("unexpected connect"); }
private void runRequestedRingHealthPull() {
if (pullRequested) { pullRequested = false; requestRingHealth(); }
}
private void resumeAbortedRingHealthPull() {}
private static final long RING_HEALTH_RSP_TIMEOUT_MS = 500;
private static final long RING_HEALTH_DATA_IDLE_MS = 100;
private static final int[] RING_DEVICE_PING_CMD_LO = {10, 1, 2, 11};
private static class SystemClock {
static long elapsedRealtime() { return System.nanoTime() / 1_000_000; }
}
private int nextRingSeqLocked() { return ++seq; }
private int nextRingNonceLocked() { return seq; }
private void logLine(String message) {}
private void sendRingDevicePing(int command) {}
private void page(int id) {
synchronized (lock) {
ringOutbound.add(new byte[] {(byte) id});
ringHealthPageCounter++;
lock.notifyAll();
}
}
private boolean writeRingFrame(byte[] frame, String what) {
if (Thread.holdsLock(lock)) throw new AssertionError("GATT write under session lock");
if (what.equals("page ack")) {
if (failAck) return false;
int pageId = frame[0] & 0xff;
writes.add("ack:" + pageId);
// Exercise a write longer than the idle timeout. Page two arrives
// only after page one's ACK has actually completed.
try { Thread.sleep(130); } catch (InterruptedException e) { throw new AssertionError(e); }
if (pageId % 10 == 1) callbacks.schedule(() -> page(pageId + 1), 5, TimeUnit.MILLISECONDS);
} else {
requestStarted.countDown();
int command = RingProtocol.parse(frame).cmdHi;
writes.add("req:" + command);
if (answer) {
page(command * 10 + 1);
if (delayRsp) {
callbacks.schedule(() -> {
synchronized (lock) { ringHealthRspSeen = true; lock.notifyAll(); }
}, 20, TimeUnit.MILLISECONDS);
} else {
synchronized (lock) { ringHealthRspSeen = true; lock.notifyAll(); }
}
}
}
return true;
}
// TRANSFER_METHODS
@Override public void close() { callbacks.shutdownNow(); }
public static void main(String[] args) throws Exception {
try (RingHealthTransferTest transfer = new RingHealthTransferTest()) {
transfer.answer = false;
Thread worker = new Thread(transfer::runRingWorker);
worker.start();
if (!transfer.requestStarted.await(1, TimeUnit.SECONDS)) throw new AssertionError("no request");
// The glasses sender can still take the session lock while the
// ring is waiting on its RSP. Shutdown must cancel that wait too.
long start = SystemClock.elapsedRealtime();
synchronized (transfer.lock) { transfer.running = false; transfer.lock.notifyAll(); }
worker.interrupt();
worker.join(300);
if (worker.isAlive()) throw new AssertionError("ring worker did not stop");
if (SystemClock.elapsedRealtime() - start >= 300) throw new AssertionError("session lock blocked");
}
try (RingHealthTransferTest transfer = new RingHealthTransferTest()) {
transfer.delayRsp = true;
if (!transfer.requestRingHealth()) throw new AssertionError("pull failed");
List<String> expected = new ArrayList<>();
for (int command : RingProtocol.HEALTH_COMMANDS) {
expected.add("req:" + command);
expected.add("ack:" + (command * 10 + 1));
expected.add("ack:" + (command * 10 + 2));
}
if (!transfer.writes.equals(expected)) throw new AssertionError("premature next type: " + transfer.writes);
}
try (RingHealthTransferTest transfer = new RingHealthTransferTest()) {
transfer.failAck = true;
if (transfer.requestRingHealth()) throw new AssertionError("failed ACK completed pull");
if (transfer.writes.size() != 1) throw new AssertionError("advanced after failed ACK");
if (transfer.ringOutbound.size() != 1) throw new AssertionError("failed ACK was discarded");
transfer.failAck = false;
if (!transfer.awaitRingHealthDataIdle(RING_HEALTH_DATA_IDLE_MS)) throw new AssertionError("retry failed");
if (!transfer.ringOutbound.isEmpty()) throw new AssertionError("retry did not drain ACKs");
}
try (RingHealthTransferTest transfer = new RingHealthTransferTest()) {
transfer.answer = false;
if (transfer.requestRingHealth()) throw new AssertionError("missing RSP completed pull");
if (transfer.writes.size() != 1) throw new AssertionError("advanced without RSP");
}
try (RingHealthTransferTest transfer = new RingHealthTransferTest()) {
transfer.ringConnected = false;
if (transfer.awaitRingHealthDataIdle(100)) throw new AssertionError("disconnect completed transfer");
}
}
}
-58
View File
@@ -1,58 +0,0 @@
package com.faceclaw.app;
import java.lang.reflect.*;
import java.util.*;
public class TextureCacheProtocolTest {
static int u16(byte[] b, int p) { return (b[p]&255) | (b[p+1]&255)<<8; }
static int u32(byte[] b, int p) { return u16(b,p) | u16(b,p+2)<<16; }
public static void main(String[] args) throws Exception {
TextureCacheState cache = new TextureCacheState();
byte[] pixels = new byte[255*255];
for (int i=0;i<pixels.length;i++) pixels[i]=(byte)(i%15+1);
ImageAtlas.Entry big = new ImageAtlas.Entry(255,255,pixels);
for (int i=0;i<3;i++) assert cache.ensureImage(i,big)>=0;
ImageAtlas.Entry tiny = new ImageAtlas.Entry(1,1,new byte[]{15});
int imageOffset = cache.ensureImage(100,tiny);
assert imageOffset>65535;
GlyphAtlas.Glyph glyph = new GlyphAtlas.Glyph(1,1,0,1,0,null,new byte[]{15});
int glyphOffset = cache.ensureGlyph(42,'A',glyph);
int table = cache.fontTableOffset(42);
assert table>65535 && glyphOffset==table+96*4;
byte[] memory = new byte[262144];
for (byte[] upload: cache.drainUploadPayloads(3600)) {
assert upload[0]==18;
int pos=1;
while (pos<upload.length) {
int offset=u32(upload,pos), n=u16(upload,pos+4);
System.arraycopy(upload,pos+6,memory,offset,n); pos+=6+n;
}
assert pos==upload.length;
}
assert memory[imageOffset]==1 && memory[imageOffset+2]==0x1f;
assert u32(memory,table+('A'-32)*4)==glyphOffset;
assert !cache.hasPendingUploads();
// Exercise the production planner encoders with offsets above 64 KiB.
Class<?> selected=Class.forName("com.faceclaw.app.TexturePlanner$Selected");
Constructor<?> ctor=selected.getDeclaredConstructors()[0]; ctor.setAccessible(true);
Object image=ctor.newInstance(SurfaceCompositor.ScreenDraw.image(100,321,123),null,tiny,321,15);
Method encode=TexturePlanner.class.getDeclaredMethod("encodeImageDraw",TextureCacheState.class,selected);
encode.setAccessible(true);
byte[] draw=(byte[])encode.invoke(null,cache,image);
assert draw.length==10 && draw[0]==19 && u32(draw,1)==imageOffset;
assert u16(draw,5)==321 && u16(draw,7)==123 && draw[9]==31;
Object letter=ctor.newInstance(SurfaceCompositor.ScreenDraw.glyph(42,'A',321,123,255),glyph,null,321,15);
Method runs=TexturePlanner.class.getDeclaredMethod("buildRuns",TextureCacheState.class,List.class,List.class);
runs.setAccessible(true); List<byte[]> out=new ArrayList<>();
runs.invoke(null,cache,Collections.singletonList(letter),out);
byte[] run=out.get(0);
assert run.length==12 && run[0]==20 && u32(run,1)==table;
assert u16(run,5)==321 && u16(run,7)==123 && run[9]==31 && run[10]==1 && run[11]=='A';
int id=200;
while (cache.ensureImage(id++,big)>=0) {}
int before=cache.usedBytes();
assert cache.ensureImage(id,big)==-1 && cache.usedBytes()==before;
cache.reset(); assert cache.usedBytes()==0 && !cache.hasPendingUploads();
assert cache.ensureImage(id,tiny)==0;
}
}
+7
View File
@@ -0,0 +1,7 @@
[
"d73e76bae77dd09f6af2f9483b8d24b7ebb79dca266ace5f062dea936c181219",
"60afd64152c40d6a0b4a70437d3636a36b41f690fe7fa43a44c1fff1accb0845",
"8f4ce275c048001ef30da8b9d93e63c15d3fb49bc643d3f5fd6908b0adaf2292",
"50a45b6816d4f0669d09958ef2dd32ab3d162b6959b6252a940d3ec1180bd80e",
"5e53d5665b33cd46cb868f8063cda22ee6cce4584e5e28123803e41642f5563f"
]
+1
View File
@@ -36,6 +36,7 @@ module.exports = function worker() {
'../../graphics/ui-fonts': { getDefaultSmallFont: () => smallFont },
'../../native/frame-timings': { finishFrame: noop, logFrame: noop },
'../../native/active-display': {},
'../../native/worker-buzzer': { playWorkerBuzzerSequence() {} },
'../../native/settings-store': { getStringSetting: () => highScore, setStringSetting: (_, value) => { highScore = value; } },
'../../ui/sound-effects': {},
'../../ui/sound-setting': { loadSoundEnabled: () => true, saveSoundEnabled: () => {} },
+39
View File
@@ -0,0 +1,39 @@
const assert = require('node:assert/strict');
// Independent firmware-format decoder for reconstruction tests (not app code).
function applyDisplayPayload(base, payload, width = 640, height = 480) {
const mode = payload[0];
if (mode === 28) return base;
if (mode === 26) {
const word = i => payload[i] | payload[i+1] << 8;
let pos=3, out=base;
for(let n=0;n<word(1);n++) {
const length=word(pos);pos+=2;const call=payload.subarray(pos,pos+length);pos+=length;
assert.equal(call[0],1);assert.equal(call[1],0);
let legacy;
if(call[2]===0) legacy=Uint8Array.from([3,...call.subarray(3,7),0,0,...call.subarray(7)]);
else { assert.deepEqual([...call.subarray(3,11)],[0,0,0,0,width&255,width>>8,height&255,height>>8]);legacy=Uint8Array.from([6,...call.subarray(11)]); }
out=applyDisplayPayload(out,legacy,width,height);
}
assert.equal(pos,payload.length);return out;
}
assert.ok(mode === 3 || mode === 6);
const [left, top, w, h] = mode === 3
? [payload[1] * 4, payload[2] * 2, payload[3] * 4, payload[4] * 2] : [0, 0, width, height];
assert.ok(w > 0 && h > 0 && left + w <= width && top + h <= height);
const tokens = payload.subarray(mode === 3 ? 7 : 1);
const pixels = [];
for (let i = 0; i < tokens.length;) {
const token = tokens[i++], color = token & 15;
let count = token >>> 4;
if (!count) { count = tokens[i++]; if (!count) { count = tokens[i] | (tokens[i + 1] << 8); i += 2; } }
assert.ok(count > 0 && pixels.length + count <= w * h);
for (let n = 0; n < count; n++) pixels.push(color);
}
assert.equal(pixels.length, w * h);
const out = base.slice();
for (let y = 0; y < h; y++) for (let x = 0; x < w; x += 2)
out[(top + y) * (width / 2) + (left + x) / 2] = (pixels[y * w + x] << 4) | pixels[y * w + x + 1];
return out;
}
module.exports = { applyDisplayPayload };
+28
View File
@@ -0,0 +1,28 @@
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const ts = require('typescript');
// Execute production TypeScript with only the native boundary and clock stubbed.
exports.loader = (globals = {}, mocks = {}) => {
const cache = new Map();
function load(file) {
file = path.resolve(__dirname, '../..', file);
if (cache.has(file)) return cache.get(file);
const output = {};
cache.set(file, output);
const source = ts.transpileModule(fs.readFileSync(file, 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText;
vm.runInNewContext(source, {
exports: output, console, Uint8Array, ...globals,
require(name) {
if (name in mocks) return mocks[name];
if (!name.startsWith('.')) throw new Error(`Unmocked module: ${name}`);
return load(path.resolve(path.dirname(file), name + '.ts'));
},
}, { filename: file });
return output;
}
return load;
};
+300
View File
@@ -0,0 +1,300 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const ts = require('typescript');
const build = (name) => require(`../.test-build/app/${name}.js`);
const metrics = build('ui/metrics');
const { GrayImage } = build('graphics/image');
const { DrawOp } = build('graphics/display-list');
const { MENU_HIGHLIGHT_DURATION_MS } = build('ui/menu-highlight-motion');
const { MENU_BOUNCE_DURATION_MS } = build('ui/menu-scroll-motion');
const LINE_HEIGHT = 21;
// icon 44 + label gap 2 + line 21 + 8 breathing room.
const ROW_H = 75;
/** A font whose every glyph is a 4x6 block, drawn as deferred glyph draws like a real atlas font. */
function stubFont() {
const glyphs = new Map();
const glyph = (cp) => {
if (!glyphs.has(cp)) glyphs.set(cp, { encoding: cp, bbxWidth: 4, bbxHeight: 6, bbxX: 0, bbxY: 0, bitmapRows: Array(6).fill(0xf0) });
return glyphs.get(cp);
};
const font = {
fingerprintId: 77, atlasKey: 'stub', ascent: 15, descent: 6, lineHeight: LINE_HEIGHT,
measureText: (text) => text.length * 6,
getGlyph: glyph,
hasGlyph: () => true,
drawText(image, x, y, text, value) {
let pen = x;
for (const ch of text) { image.drawGlyph(font, glyph(ch.codePointAt(0)), pen, y, value); pen += 6; }
},
};
return font;
}
/** Transpile one module with its imports resolved from `deps`. */
function load(file, deps) {
const exports = {};
const source = fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
vm.runInNewContext(ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, { exports, console, Date, require(name) {
assert.ok(name in deps, `Unexpected import ${name} in ${file}`);
return deps[name];
} });
return exports;
}
function loadIconGrid({ lastInputWasWatch = false } = {}) {
const font = stubFont();
const state = { replayable: true };
const common = {
'../graphics/image': build('graphics/image'),
'../graphics/textwrap': build('graphics/textwrap'),
'../graphics/ui-fonts': { getDefaultSmallFont: () => font },
'../util/numeric-util': build('util/numeric-util'),
'./gestures': build('ui/gestures'),
'./menu-core': build('ui/menu-core'),
'./metrics': metrics,
};
const menu = load('app/ui/menu.ts', { ...common, './layers': {} });
const grid = load('app/ui/icon-grid.ts', {
...common,
'../graphics/draw-expression': build('graphics/draw-expression'),
'../graphics/display-list': build('graphics/display-list'),
// Registration is native; any draws are replayable unless a test says not.
'../graphics/glyph-wire': { encodeReplayDraws: (draws) => state.replayable ? { records: new Uint8Array(0), count: draws.length } : null },
'../graphics/menu-scroll-list': build('graphics/menu-scroll-list'),
'./menu': menu,
'./menu-highlight-motion': build('ui/menu-highlight-motion'),
'./menu-scroll-motion': build('ui/menu-scroll-motion'),
'./shell/shell': { shell: { lastInputWasWatch: () => lastInputWasWatch } },
'./layers': {},
});
return { ...grid, state };
}
const ICON = new GrayImage(44, 44);
ICON.fillRect(10, 10, 24, 24, 200);
const ring = (type) => ({ type });
const watch = (type) => ({ type, source: 'watch' });
const BOX = { x: 0, y: 10, width: 500, height: 180 };
function makeGrid({ items = Array.from({ length: 12 }, (_, i) => `item${i}`), isWide, onActivate, onBack, watchLast } = {}) {
const { IconGrid, state } = loadIconGrid({ lastInputWasWatch: watchLast });
const log = { activated: [], backs: 0 };
const data = { items };
const grid = new IconGrid({
items: () => data.items,
isWide,
describe: (item) => ({ label: item, icon: ICON }),
onActivate: onActivate ?? ((item, index) => { log.activated.push({ item, index }); }),
onBack: onBack ?? (() => { log.backs++; return false; }),
});
return { grid, log, data, state };
}
function withClock(now, fn) {
const original = Date.now;
Date.now = () => now;
try { return fn(); } finally { Date.now = original; }
}
function paint(grid, now, box = BOX) {
return withClock(now, () => {
const image = new GrayImage(500, 200);
grid.paint(image, box, true);
return image;
});
}
const animation = (image) => image.draws.find((draw) => draw.presentation?.displayList)?.presentation.displayList;
/** What the glasses show at `at`, as 4-bit values. */
function shown(image, at) {
return withClock(at, () => Array.from(image.withDrawsBaked().pixels, (v) => Math.min(15, (v + 8) >> 4)));
}
test('rows keep their content height instead of stretching, and the next row peeks clipped', () => {
assert.equal(metrics.iconGridMinRowHeight({ lineHeight: LINE_HEIGHT }, 44, 2), ROW_H);
const { grid } = makeGrid({ items: Array.from({ length: 15 }, (_, i) => `item${i}`) });
const image = paint(grid, 1000);
const iconYs = [...new Set(image.draws.filter((d) => d.kind === 'image' && !d.presentation).map((d) => d.y))];
assert.deepEqual(iconYs, [14, 14 + ROW_H], 'full rows are deferred draws at the natural pitch');
const glyphYs = [...new Set(image.draws.filter((d) => d.kind === 'glyph').map((d) => d.y))];
assert.deepEqual(glyphYs, [60, 60 + ROW_H], 'labels of full rows only');
// The third row's top is baked into the raster, cut off at the box bottom (y 190).
const peekTop = 14 + 2 * ROW_H;
assert.ok(image.pixels[(peekTop + 15) * 500 + 60] > 0, 'the peeking icon shows');
for (let y = 190; y < 200; y++) for (let x = 0; x < 500; x++) assert.equal(image.pixels[y * 500 + x], 0, `nothing below the box at (${x}, ${y})`);
assert.equal(animation(image), undefined, 'a first paint does not animate');
});
test('the pitch only changes with the font, not with how many rows fit', () => {
const { grid } = makeGrid();
for (const height of [150, 180, 224]) {
const image = paint(grid, 1000, { x: 0, y: 0, width: 500, height });
const ys = [...new Set(image.draws.filter((d) => d.kind === 'image').map((d) => d.y))];
for (let i = 1; i < ys.length; i++) assert.equal(ys[i] - ys[i - 1], ROW_H, `height ${height}`);
}
});
test('scrolling rows into view animates from the old paint to the new one', async () => {
const { grid } = makeGrid({ items: Array.from({ length: 15 }, (_, i) => `item${i}`) });
paint(grid, 500);
await grid.handleInput(ring('scroll-down'), null);
const before = paint(grid, 1000);
assert.equal(animation(before) !== undefined, true, 'moving the band animates its slide');
const settledBefore = paint(grid, 2000);
await grid.handleInput(ring('scroll-down'), null);
const moving = paint(grid, 3000);
const list = animation(moving);
assert.ok(list, 'the scroll is retained as a display list');
assert.deepEqual(Array.from(list.calls, (c) => c.op), [DrawOp.CLEAR, DrawOp.ROUNDED_RECT, DrawOp.DRAWS]);
assert.ok(list.calls.every((c) => c.clip && c.clip.width === 500 && c.clip.height === 180), 'every call is clipped to the box');
// First and last frames match the static paints on either side.
assert.deepEqual(shown(moving, 3000), shown(settledBefore, 2000));
const end = 3000 + MENU_HIGHLIGHT_DURATION_MS;
const settled = paint(grid, end);
assert.equal(animation(settled), undefined, 'the static paint takes over once the animation ends');
assert.deepEqual(shown(moving, end), shown(settled, end));
const middle = shown(moving, 3000 + MENU_HIGHLIGHT_DURATION_MS / 2);
assert.notDeepEqual(middle, shown(settled, end));
assert.notDeepEqual(middle, shown(settledBefore, 2000));
});
test('item selection slides the highlight between cells without redrawing past the scrollbar gutter', async () => {
const { IconGrid } = loadIconGrid();
const grid = new IconGrid({
items: () => Array.from({ length: 30 }, (_, i) => `item${i}`),
describe: (item) => ({ label: item, icon: ICON }), onActivate: () => {}, onBack: () => false, scrollbar: true,
});
paint(grid, 500);
await grid.handleInput(ring('click'), null);
const before = paint(grid, 1000);
assert.equal(animation(before), undefined, 'entering item mode snaps');
await grid.handleInput(ring('scroll-down'), null);
const moving = paint(grid, 2000);
const list = animation(moving);
assert.ok(list);
assert.equal(list.calls[0].clip.width, 495, 'the scrollbar gutter is left to the static paint');
const rect = list.calls[1];
const { evaluate } = build('graphics/draw-expression');
assert.equal(evaluate(rect.x, 0).value, 200 + 6, 'starts on the middle cell');
assert.equal(evaluate(rect.x, MENU_HIGHLIGHT_DURATION_MS).value, 300 + 6, 'rests on the next cell');
assert.deepEqual(shown(moving, 2000), shown(before, 1000));
const end = 2000 + MENU_HIGHLIGHT_DURATION_MS;
assert.deepEqual(shown(moving, end), shown(paint(grid, end), end));
});
test('navigating past an end bounces and comes back', async () => {
const { grid } = makeGrid();
const rest = paint(grid, 1000);
await grid.handleInput(ring('scroll-up'), null);
const bouncing = paint(grid, 2000);
const list = animation(bouncing);
assert.ok(list, 'a bounce at the top is animated');
assert.deepEqual(shown(bouncing, 2000), shown(rest, 1000));
const peak = shown(bouncing, 2000 + Math.round(MENU_BOUNCE_DURATION_MS * 0.35));
assert.notDeepEqual(peak, shown(rest, 1000), 'the rows move down past the top');
// The first icon row moved 24px down (0.4 of a row, capped); the highlight moved with it.
// Column 0's icon ink spans x 38..61 at 4-bit level 13.
const iconTop = (image) => { for (let y = 10; y < 200; y++) if (image[y * 500 + 50] === 13) return y; };
assert.equal(iconTop(peak) - iconTop(shown(rest, 1000)), 24);
assert.deepEqual(shown(bouncing, 2000 + MENU_BOUNCE_DURATION_MS), shown(rest, 1000));
});
test('unreplayable rows, host navigation and taps snap', async () => {
const { grid, state } = makeGrid({ onBack: () => { grid.resetSelection(); return false; } });
paint(grid, 1000);
state.replayable = false;
await grid.handleInput(ring('scroll-down'), null);
assert.equal(animation(paint(grid, 2000)), undefined, 'rows that cannot be replayed snap');
state.replayable = true;
assert.equal(animation(paint(grid, 2100)), undefined, 'the cancelled motion does not resume');
await grid.handleInput(ring('double-click'), null);
assert.equal(animation(paint(grid, 3000)), undefined, 'a host reset is not navigation');
await grid.hitTest(250, 20 + ROW_H, null);
assert.equal(animation(paint(grid, 4000)), undefined, 'a tap selects without sliding');
});
test('ring: row mode, then item mode at the middle column, linear traversal, back out', async () => {
const { grid, log } = makeGrid();
assert.equal(grid.selectedItem, null, 'row mode pins no item');
await grid.handleInput(ring('click'), null);
assert.equal(grid.selectedItem, 'item2', 'click enters item mode at the middle column');
await grid.handleInput(ring('scroll-down'), null);
await grid.handleInput(ring('scroll-down'), null);
await grid.handleInput(ring('scroll-down'), null);
assert.equal(grid.selectedItem, 'item5', 'item scrolling continues onto the next row');
await grid.handleInput(ring('scroll-up'), null);
assert.equal(grid.selectedItem, 'item4', 'and back onto the previous row at its end');
await grid.handleInput(ring('click'), null);
assert.deepEqual(log.activated, [{ item: 'item4', index: 4 }]);
await grid.handleInput(ring('double-click'), null);
assert.equal(grid.selectedItem, null, 'double-click drops to row mode');
assert.equal(log.backs, 0);
await grid.handleInput(ring('double-click'), null);
assert.equal(log.backs, 1, 'double-click in row mode backs out');
});
test('watch: four-way cells, left from the first column backs out and stays in item mode', async () => {
const { grid, log, data } = makeGrid({
onBack: () => { log.backs++; grid.resetSelection(); return false; },
});
await grid.handleInput(watch('swipe-down'), null);
await grid.handleInput(watch('swipe-right'), null);
assert.equal(grid.selectedItem, 'item6', 'row 1, column 1');
await grid.handleInput(watch('swipe-down'), null);
assert.equal(grid.selectedItem, 'item11', 'a shorter row clamps the column');
await grid.handleInput(watch('swipe-left'), null);
assert.equal(grid.selectedItem, 'item10');
assert.equal(log.backs, 0);
await grid.handleInput(watch('swipe-left'), null);
assert.equal(log.backs, 1);
assert.equal(grid.selectedItem, 'item0', 'the host reset the selection, and the watch keeps a cell selected');
data.items = ['only'];
await grid.handleInput(watch('click'), null);
assert.deepEqual(log.activated, [{ item: 'only', index: 0 }]);
});
test('activating or backing out of the grid returns it to row mode', async () => {
const { grid } = makeGrid({ onActivate: async () => true, onBack: () => true });
await grid.handleInput(watch('swipe-right'), null);
await grid.handleInput(watch('click'), null);
assert.equal(grid.selectedItem, null, 'a launch leaves row mode behind');
await grid.handleInput(ring('click'), null);
assert.notEqual(grid.selectedItem, null);
await grid.handleInput(watch('double-click'), null);
assert.equal(grid.selectedItem, null, 'leaving via the watch restores row mode too');
});
test('wide items take their own row and count as one item', async () => {
const items = ['notice', 'a', 'b', 'c', 'd', 'e', 'f'];
const { grid, log } = makeGrid({ items, isWide: (item) => item === 'notice' });
assert.equal(grid.selectedItem, 'notice', 'a wide row is selected as a whole even in row mode');
await grid.handleInput(ring('click'), null);
assert.deepEqual(log.activated, [{ item: 'notice', index: 0 }], 'one click opens a wide row');
grid.selectIndex(6);
assert.equal(grid.cursorIndex, 6);
assert.equal(grid.selectedItem, null, 'selectIndex keeps row mode');
await grid.handleInput(ring('click'), null);
assert.equal(grid.selectedItem, 'f', 'the one-item row clamps the middle column');
await grid.handleInput(ring('scroll-up'), null);
assert.equal(grid.selectedItem, 'e', 'item traversal walks back through the full row');
for (let i = 0; i < 5; i++) await grid.handleInput(ring('scroll-up'), null);
assert.equal(grid.selectedItem, 'notice');
});
test('hitTest opens the cell under the touch, including the peeking row', async () => {
const { grid, log } = makeGrid();
paint(grid, 1000);
assert.equal(await grid.hitTest(50, 10 + 2 * ROW_H + 5, null), true);
assert.deepEqual(log.activated, [{ item: 'item10', index: 10 }]);
assert.equal(grid.selectedItem, 'item10', 'the touched cell becomes the selection');
assert.equal(await grid.hitTest(250, 5, null), false, 'above the box');
assert.equal(await grid.hitTest(250, 10 + 2 * ROW_H + 5, null), false, 'past the last cell of a short row');
});
+194
View File
@@ -0,0 +1,194 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const ts = require('typescript');
const read = (file) => fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
const js = (source) => ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText;
function load(file, modules = {}) {
const context = { exports: {}, console, require(name) {
assert.ok(name in modules, name); return modules[name];
} };
vm.runInNewContext(js(read(file)), context);
return context.exports;
}
const monitor = load('app/ui/input-monitor.ts');
const event = (type, timestampMs = 1000) => ({ type, source: 'ring', timestampMs });
function shellDeclarations() {
const source = ts.createSourceFile('shell.ts', read('app/ui/shell/shell.ts'), ts.ScriptTarget.Latest, true);
const names = new Set(['rawInputEventToInputEvent', 'rawInputEventToPayload', 'eventSourceToString', 'scrollEvent']);
const declarations = source.statements.filter((s) => ts.isFunctionDeclaration(s) && names.has(s.name?.text));
assert.equal(declarations.length, names.size);
const shell = source.statements.find((s) => ts.isClassDeclaration(s) && s.name?.text === 'Shell');
const methods = shell.members.filter((s) => ['receiveInput', 'routeInput'].includes(s.name?.getText(source)));
const context = { exports: {}, acceptInput: monitor.acceptInput,
makeInputEvent: (payload) => ({ ...payload, timestampMs: 12345678 }),
...load('app/g2/events.ts') };
vm.createContext(context);
vm.runInContext(js(declarations.map((s) => s.getText(source)).join('\n') +
'\nexport class Shell {\n' + methods.map((s) => s.getText(source)).join('\n') + '\n}'), context);
return context;
}
test('new SysEvent decodes independently of click, double-tap, hold and release', () => {
const d = shellDeclarations();
for (const source of [0, 2]) {
const decoded = d.rawInputEventToPayload({ kind: 'sys-event', eventType: 14, eventSource: source });
assert.equal(decoded.type, 'ring-press'); assert.equal(decoded.source, 'ring');
}
for (const source of [1, 3, 99, undefined]) {
assert.equal(d.rawInputEventToPayload({ kind: 'sys-event', eventType: 14, eventSource: source }).type, 'unknown');
}
for (const [id, type] of [[0,'click'],[3,'double-click'],[9,'long-press'],[10,'long-press-release'],[11,'short-then-long-press']]) {
assert.equal(d.rawInputEventToPayload({ kind: 'sys-event', eventType: id, eventSource: 2 }).type, type);
}
});
test('press is observed before routing and does not wake, operate shell menus or replace hold state', async () => {
const { exports: { Shell } } = shellDeclarations();
for (const screenOn of [true, false]) for (const focus of ['window', 'sidebar']) for (const atBase of [true, false]) {
const s = new Shell(), seen = [], delivered = [];
const unsubscribe = monitor.addInputListener((e) => seen.push(e));
Object.assign(s, { screenOn, focus, stack: { isAtBase: () => atBase },
foregroundWindow: () => ({ handleInput(e) { assert.equal(seen.length, 1); delivered.push(e); } }),
syncInputFocus() {}, lastInput: event('long-press'), lastInputAtMs: 123 });
try {
const result = await s.receiveInput(event('ring-press'));
assert.equal(result.shell, false);
assert.equal(delivered.length, Number(screenOn && focus === 'window' && atBase));
assert.equal(seen.length, 1);
assert.equal(s.lastInput.type, 'long-press'); assert.equal(s.lastInputAtMs, 123);
} finally { unsubscribe(); }
}
});
test('bounded history preserves equal-time events, snapshots and arrival gaps; pause and clear work', () => {
const log = new monitor.InputEventLog();
const first = event('ring-press'); log.add(first); first.type = 'unknown';
log.add(event('click')); log.add(event('double-click', 1250));
assert.equal(log.entries[2].event.type, 'ring-press');
assert.equal(log.entries[2].gapMs, null); assert.equal(log.entries[1].gapMs, 0);
assert.equal(log.entries[0].gapMs, 250);
log.paused = true; log.add(event('click')); assert.equal(log.count, 3);
log.paused = false;
for (let i = 0; i < 210; i++) log.add(event('click', 2000 + i));
assert.equal(log.entries.length, 200); assert.equal(log.count, 213);
log.clear(); log.add(event('ring-press')); assert.equal(log.count, 1); assert.equal(log.entries[0].gapMs, null);
assert.equal(monitor.inputTimestamp(new Date(2026, 0, 2, 3, 4, 5, 6).getTime()), '03:04:05.006');
});
test('Input events captures while visible, pauses for history, and unsubscribes on removal', () => {
const textwrap = load('app/graphics/textwrap.ts');
const graphics = require('../.test-build/app/graphics/image.js');
const { BdfFont } = load('app/graphics/bdffont.ts', { '@nativescript/core': {} });
const font = BdfFont.parse(read('app/fonts/terminus/ter-u18n.bdf'));
class RecordingImage extends graphics.GrayImage {
texts = [];
drawText(font, x, y, text, value) {
this.texts.push({ x, y, text, width: font.measureText(text), height: font.lineHeight });
super.drawText(font, x, y, text, value);
}
}
const { InputEventsLayer } = load('app/apps/developer/input-events.ts', {
'../../graphics/ui-fonts': { getDefaultSmallFont: () => font },
'../../graphics/image': { GrayImage: RecordingImage }, '../../graphics/textwrap': textwrap,
'../../ui/input-monitor': monitor, '../../ui/menu': { drawListScrollbar() {} },
});
let visible = true, renders = 0, removed = 0, pops = 0;
const layer = new InputEventsLayer(() => renders++, () => visible, () => removed++);
const ctx = { stack: { getBaseSize: () => ({ width: 576, height: 260 }),
pop: () => pops++, popThrough: (page) => { assert.equal(page, layer); page.onRemoved(); } } };
try {
for (const type of ['ring-press','click','ring-press','ring-press','double-click','long-press','long-press-release','short-then-long-press']) {
const e = { ...event(type, 1000 + renders * 75), ringInput: { tick: 4294967200 + renders, type: 1, aux:0, speed:0 } };
monitor.notifyInputListeners(e, renders > 0); layer.handleInput(e);
}
assert.equal(renders, 8); assert.equal(layer.log.count, 8); assert.equal(pops, 0);
visible = false; monitor.notifyInputListeners(event('click')); assert.equal(renders, 8); visible = true;
const image = layer.paint(ctx);
assert.ok(image.texts.some(t => t.text.startsWith("R4294967")));
assert.ok(image.texts.some(t => t.text.startsWith("*")));
layer.menuItems()[2].onSelect(ctx);
assert.ok(layer.paint(ctx).texts.some(t => t.text.startsWith("Phone receive time")));
for (const text of image.texts) {
assert.ok(text.x >= 0 && text.x + text.width <= image.width, text.text);
assert.ok(text.y >= 0 && text.y + text.height <= image.height, text.text);
}
if (process.env.INPUT_EVENTS_PREVIEW) fs.writeFileSync(process.env.INPUT_EVENTS_PREVIEW, Buffer.concat([
Buffer.from(`P5\n${image.width} ${image.height}\n255\n`), Buffer.from(image.withDrawsBaked().pixels),
]));
layer.menuItems()[0].onSelect(ctx); monitor.notifyInputListeners(event('click'));
assert.equal(layer.log.count, 8); assert.equal(layer.menuItems()[0].label, 'Resume capture');
layer.menuItems()[1].onSelect(ctx); assert.equal(layer.log.count, 0);
layer.menuItems()[0].onSelect(ctx); monitor.notifyInputListeners(event('ring-press'));
assert.equal(layer.log.count, 1);
layer.menuItems()[3].onSelect(ctx); monitor.notifyInputListeners(event('click'));
assert.equal(removed, 1); assert.equal(layer.log.count, 1);
} finally { layer.onRemoved(); }
});
const ring = (type, tick, received = 1000) => ({ ...event('click', received),
ringInput: { type, tick, aux: 17, speed: 29 } });
test('filter matches stock timing boundaries, exemptions, wrap, reset and zero sentinel', () => {
const f = new monitor.RingInputFilter();
for (const [type, tick, accepted] of [
[1,1000,true], [1,1099,false], [10,1099,true], [1,1100,true],
[8,1101,true], [2,1200,false], [2,1201,true], [2,1201,false],
[10,1201,true], [10,1202,true], [9,1301,true],
]) assert.equal(f.accept(ring(type, tick)), accepted, `${type}@${tick}`);
f.reset(); assert.equal(f.accept(ring(1,1)), true);
f.reset(); assert.equal(f.accept(ring(1,0xffffffd0)),true);
assert.equal(f.accept(ring(1,0x33)),false); assert.equal(f.accept(ring(1,0x34)),true);
// Backward timestamps / ring restart pass using unsigned subtraction.
assert.equal(f.accept(ring(1,5)),true);
f.reset(); assert.equal(f.accept(ring(1,0)),true); assert.equal(f.accept(ring(1,1)),true);
assert.equal(f.accept(event('click')),true);
assert.equal(f.accept({ ...event('click'), source: 'watch' }),true);
// Host scheduling does not affect decisions; filtered events do not extend the window.
f.reset(); assert.equal(f.accept(ring(4,1000,100000)),true);
assert.equal(f.accept(ring(4,1050,999999)),false);
assert.equal(f.accept(ring(4,1100,999999)),true);
f.reset(); assert.equal(f.accept(ring(99,2000)),true);
assert.equal(f.accept(ring(1,2050)),false);
});
test('raw debug observer sees suppressed reports once before app routing', async () => {
monitor.resetRingInputFilter();
const { exports: { Shell } } = shellDeclarations(), s = new Shell(), seen = [], routed = [];
s.routeInput = async (e) => { routed.push(e); return { shell:false,window:true }; };
s.syncInputFocus = () => {};
const off = monitor.addInputListener((e, filtered) => seen.push([e, filtered]));
try {
const first = ring(1,1000), second = ring(1,1050);
assert.equal(monitor.acceptInput(first),true); await s.receiveInput(first);
assert.equal(monitor.acceptInput(second),false); await s.receiveInput(second);
assert.equal(seen.length,2); assert.equal(routed.length,1);
assert.deepEqual(seen.map((e) => e[1]),[false,true]);
assert.equal(seen[1][0].ringInput.tick,1050);
assert.equal(Object.isFrozen(seen[1][0].ringInput),true);
} finally { off(); monitor.resetRingInputFilter(); }
});
test('raw-to-app conversion retains the unsigned ring clock and explicit scroll source', () => {
const d = shellDeclarations();
for (const [wire,eventType,direction] of [[4,1,'scroll-up'],[5,2,'scroll-down']]) {
const raw = { kind:'sys-event', eventType, eventSource:2, ringInput: ring(wire,0xffffffff).ringInput };
const input = d.exports.rawInputEventToInputEvent(raw);
assert.equal(input.type,direction); assert.equal(input.source,'ring');
assert.equal(input.timestampMs,12345678); assert.equal(input.ringInput.tick,0xffffffff);
assert.notEqual(input.ringInput,raw.ringInput);
}
});
test('debug history retains both clocks and uses unsigned gaps across counter wrap', () => {
const log = new monitor.InputEventLog();
log.add(ring(1,0xfffffff0,5000)); log.add(ring(1,0x10,5001),true);
assert.equal(log.entries[0].gapMs,1); assert.equal(log.entries[0].ringGapTicks,32);
assert.equal(log.entries[0].filtered,true);
log.clear(); log.add(ring(1,500)); assert.equal(log.entries[0].ringGapTicks,null);
});
+515
View File
@@ -0,0 +1,515 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const ts = require('typescript');
const path = require('node:path');
function load(file, context) {
const sandbox = { exports: {}, ...context };
const source = fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
vm.runInNewContext(ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 } }).outputText, sandbox);
return sandbox.exports;
}
test('iOS worker replies keep cached draw references paired with their baked pixels', () => {
const replies = [], received = [];
const wrap = buffer => ({ length: buffer.byteLength, buffer,
base64EncodedStringWithOptions: () => Buffer.from(buffer).toString('base64') });
const NSData = {
dataWithBytesLength: buffer => wrap(buffer),
alloc: () => ({ initWithBase64EncodedStringOptions: text => {
const bytes = Uint8Array.from(Buffer.from(text, 'base64')); return wrap(bytes.buffer);
} }),
};
const interop = { handleof: buffer => buffer, bufferFromData: data => data.buffer };
const display = load('app/native/active-display.ios.ts', {
NSData, interop, global: { postMessage: message => replies.push(message) },
}).getActiveDisplay();
const pixels = new Uint8Array([255, 0, 0, 255]), draws = new Uint8Array([1, 7, 0, 0, 0, 0, 0, 0, 0]);
display.submitSurfaceFrame(pixels.buffer, 'window:test', 0, 0, 2, 2, 'frame', 0, 1, draws.buffer);
const worker = {};
const { WorkerAppHost } = load('app/ui/shell/worker-window.ts', {
require: () => ({}), global: { isIOS: true }, NSData, interop,
});
const host = new WorkerAppHost({ appId: 'test', worker, submitPixels: (...args) => received.push(args) });
host.openWindows.add('test');
worker.onmessage({ data: replies[0] });
assert.equal(received.length, 1);
assert.deepEqual([...received[0][1]], [...pixels]);
assert.deepEqual([...new Uint8Array(received[0][4])], [...draws]);
display.submitSurfaceFrame(pixels.buffer, 'window:test', 0, 0, 2, 2);
worker.onmessage({ data: replies[1] });
assert.equal(received[1][4], null, 'a pixel-only update must clear previous draw identities');
host.openWindows.clear(); worker.onmessage({ data: replies[0] });
assert.equal(received.length, 2, 'closed windows cannot deliver stale cached draws');
});
test('iOS installed apps launch, recover missing packages, and close before uninstall', async () => {
const calls = [], app = { packageId: 'test.app', name: 'Test' };
let present = true;
const modules = {
"../ui/input-monitor": load("app/ui/input-monitor.ts", {}),
'../apps/all-apps': { ALL_APPS: [{ appId: 'evenhub' }] },
'../apps/evenhub/installed-apps': { getInstalledEvenHubAppById: id => id === 'installed' ? app : null,
installedEvenHubPackageId: id => id === 'installed' ? app.packageId : null,
uninstallEvenHubPackage: id => calls.push(['uninstall', id]) },
'../apps/evenhub/updates': { isInstalledPackagePresent: () => present },
'../apps/evenhub': { openEvenHubStoreForPackage: (_ctx, value) => calls.push(['reinstall', value.packageId]) },
'../apps/evenhub/manager': { launchInstalledPackage: (ctx, value) => calls.push(['launch', ctx.appId, value.packageId]),
closeRunningPackage: id => calls.push(['close', id]) },
};
const { IosPreviewController } = load('app/g2/ios-preview-controller.ts', { require: id => modules[id] ?? {} });
const host = Object.create(IosPreviewController.prototype);
host.buildAppContext = app => app; host.fail = assert.fail; host.requestShellRender = () => {};
await host.launchApp('installed'); present = false; await host.launchApp('installed');
await host.uninstallApp('installed');
assert.deepEqual(calls, [['launch', 'installed', 'test.app'], ['reinstall', 'test.app'], ['close', 'test.app'], ['uninstall', 'test.app']]);
});
test('iOS settings prompts honor password input and report cancellation', async () => {
const prompts = [], writes = [];
const { IosPreviewController } = load('app/g2/ios-preview-controller.ts', { require: id => id === '@nativescript/core' ? {
Dialogs: { prompt: async options => { prompts.push(options); return { result: false, text: 'discarded' }; } },
} : {} });
const host = Object.create(IosPreviewController.prototype); host.active = true;
const accepted = await host.editSetting({ editorTitle: 'Password', inputKind: 'password', get: () => '', set: value => writes.push(value) });
assert.equal(prompts[0].inputType, 'password');
assert.equal(accepted, false); assert.deepEqual(writes, []);
});
test('iOS host forwards hands-free capture mode to the voice bridge', async () => {
const captures = [];
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.communicator = {}; host.state = { phase: 'connected' };
await host.startVoiceCapture(true);
await host.startVoiceCapture();
assert.deepEqual(captures, [true, false]);
});
for (const isIOS of [true, false]) {
test(`${isIOS ? 'iOS' : 'Android'} Assistant settings expose supported controls and usable model choices`, () => {
const store = new Map();
let picker;
const models = load('app/assistant/models.ts', { global: { isIOS }, require: () => ({
LOCAL_MODEL: { label: 'Qwen', id: 'qwen' }, isLocalModelReady: () => false,
}) });
const settings = load('app/ui/dashboard-settings.ts', { global: { isIOS }, require: id => {
if (id.includes('settings-store')) return {
onSettingsStoreChanged() {},
getStringSetting: (key, fallback) => store.get(key) ?? fallback,
setStringSetting: (key, value) => store.set(key, value),
getBooleanSetting: (key, fallback) => store.get(key) ?? fallback,
setBooleanSetting: (key, value) => store.set(key, value),
};
if (id === '~/assistant/models') return models;
return { Layer: class {}, isLocalModelReady: () => false,
openModalMenu: (_ctx, _title, items) => { picker = items; } };
} });
const menus = load('app/ui/dashboard/settings-menus.ts', { global: { isIOS }, require: id => {
if (id === '../dashboard-settings') return settings;
if (id === './remote-input-menu') return { remoteInputMenuItem: () => ({ label: 'Input tokens' }) };
if (id === './settings-panel') return { SettingsPanelLayer: class { constructor(sections) { this.sections = sections; } } };
return { LOCAL_MODEL: { sizeBytes: 1000 }, ASR_MODELS: { moonshine: {}, 'whisper-base-en': {} },
uiFontPickerMenuItem: () => ({ label: 'Font' }), terminalFontPickerMenuItem: () => ({ label: 'Terminal font' }) };
} });
const sections = menus.createSettingsPanelLayer().sections;
assert.ok(sections.find(section => section.label === 'Display').items.some(item => item.label === settings.lockScreenEnabledSetting.label));
const assistant = sections.find(section => section.label === 'Assistant');
assert.equal(assistant.items.some(item => item.disabled === true), false);
const ctx = { stack: { pop() {} }, actions: { requestRender() {} } };
const row = setting => assistant.items.find(item => item.label === setting.label);
row(settings.assistantBackendSetting).onSelect(ctx);
assert.deepEqual(Array.from(picker, item => item.label), isIOS ? ['Cloud API'] : ['On-phone', 'My own agent (bridge)']);
assert.equal(assistant.items.some(item => item.label === 'On-phone model'), !isIOS);
assert.equal(!!row(settings.assistantBridgeHostSetting), !isIOS);
assert.equal(!!row(settings.assistantAllowProactiveSetting), !isIOS);
row(settings.assistantModelSetting).onSelect(ctx);
assert.equal(picker.some(item => item.label.includes('Qwen')), !isIOS);
const terra = picker.find(item => item.label === 'Terra');
assert.equal(terra.disabled(), true);
const keys = sections.find(section => section.label === 'API Keys').items;
assert.ok(keys.some(item => item.label === settings.openAiApiKeySetting.label));
assert.ok(keys.some(item => item.label === settings.anthropicApiKeySetting.label));
settings.openAiApiKeySetting.set('fixture-key');
assert.equal(terra.disabled(), false);
terra.onSelect(ctx);
assert.equal(settings.assistantModelSetting.get(), 'terra');
assert.equal(models.resolveAssistantModel(settings.assistantModelSetting.get(), {
openai: settings.openAiApiKeySetting.get(), anthropic: '',
}).provider, 'openai');
row(settings.assistantSkipConfirmationSetting).onSelect(ctx);
assert.equal(settings.assistantSkipConfirmationSetting.get(), true);
assert.ok(sections.find(section => section.label === 'Voice').items.some(item => item.label === settings.wakeWordActionSetting.label));
});
}
test('iOS phone battery distinguishes unknown, charging, full and unplugged readings', () => {
const device = { batteryLevel: -1, batteryState: 0 };
const api = load('app/native/phone-battery.ts', { require: () => ({}), global: { isIOS: true },
UIDevice: { currentDevice: device }, UIDeviceBatteryState: { Unknown: 0, Unplugged: 1, Charging: 2, Full: 3 } });
assert.deepEqual({ ...api.readPhoneBatteryState() }, { battery: null, charging: null });
device.batteryLevel = 0.726; device.batteryState = 2;
assert.deepEqual({ ...api.readPhoneBatteryState() }, { battery: 73, charging: true });
device.batteryLevel = 1; device.batteryState = 3;
assert.deepEqual({ ...api.readPhoneBatteryState() }, { battery: 100, charging: true });
device.batteryLevel = 0; device.batteryState = 1;
assert.deepEqual({ ...api.readPhoneBatteryState() }, { battery: 0, charging: false });
});
test('settings changes propagate between iOS worker isolates once, including after a getter read', () => {
const store = new Map(), ticks = new Set(), tasks = [];
const ApplicationSettings = { getString: (k, d) => store.get(k) ?? d, getBoolean: (k, d) => store.get(k) ?? d,
setString: (k, v) => store.set(k, v), setBoolean: (k, v) => store.set(k, v), hasKey: k => store.has(k) };
const context = { require: () => ({ ApplicationSettings }), setTimeout: fn => tasks.push(fn),
setInterval: fn => { ticks.add(fn); return fn; }, clearInterval: fn => ticks.delete(fn) };
const main = load('app/native/settings-store.ios.ts', context), worker = load('app/native/settings-store.ios.ts', context);
const seenMain = [], seenWorker = [];
const offMain = main.onSettingsStoreChanged(k => seenMain.push(k));
const offWorker = worker.onSettingsStoreChanged(k => seenWorker.push(k));
main.getStringSetting('terminal.connections', '[]'); worker.getStringSetting('terminal.connections', '[]');
main.setStringSetting('terminal.connections', '["test"]');
assert.equal(worker.getStringSetting('terminal.connections', '[]'), '["test"]');
const flush = () => { for (const tick of ticks) tick(); while (tasks.length) tasks.shift()(); };
flush(); flush();
assert.deepEqual(seenMain, ['terminal.connections']); assert.deepEqual(seenWorker, ['terminal.connections']);
main.getBooleanSetting('sound', true); worker.getBooleanSetting('sound', true);
worker.setBooleanSetting('sound', false); flush();
assert.equal(main.getBooleanSetting('sound', true), false);
assert.deepEqual(seenMain, ['terminal.connections', 'sound']);
offWorker(); offMain(); assert.equal(ticks.size, 0);
});
test('iOS worker frames preserve baked grayscale bytes through the message boundary', () => {
const messages = [];
const api = load('app/native/active-display.ios.ts', { global: { postMessage: m => messages.push(m) },
interop: { handleof: b => b }, NSData: { dataWithBytesLength: (b, n) => ({ base64EncodedStringWithOptions: () => Buffer.from(b, 0, n).toString('base64') }) } });
const pixels = new Uint8Array([0, 1, 15, 127, 254, 255]);
api.getActiveDisplay().submitSurfaceFrame(pixels.buffer, 'window:blocks:main', 0, 0, 3, 2);
assert.equal(messages[0].surfaceId, 'window:blocks:main');
assert.equal(messages[0].width, 3); assert.equal(messages[0].height, 2);
assert.deepEqual(Buffer.from(messages[0].pixels, 'base64'), Buffer.from(pixels));
});
test('settings-driven repaint runs after font cache invalidation, regardless of subscription order', () => {
const listeners = [], tasks = [], painted = [];
let cachedFont = 'Light';
const api = load('app/ui/dashboard-settings.ts', { global: { isIOS: true },
require: id => id.includes('settings-store') ? { onSettingsStoreChanged: fn => listeners.push(fn) }
: { Layer: class {}, ASSISTANT_MODEL_CHOICES: [] },
setTimeout: fn => tasks.push(fn),
});
api.onAnySettingChanged(() => painted.push(cachedFont));
listeners.push(() => { cachedFont = 'Bold'; });
for (const listener of listeners) listener('display.uiFont2');
while (tasks.length) tasks.shift()();
assert.deepEqual(painted, ['Bold']);
});
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, 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); } };
// 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 configureBrightness() {} 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, getBrightnessPreferences: () => ({ auto: true, level: 50, minimum: 2, maximum: 100, curve: '0:0,1000:100', fadeMs: 280 }), lockScreenEnabledSetting: { get: () => true }, onAnySettingChanged: () => () => {}, previewColorSetting: { get: () => 'white' } };
const modules = {
"../ui/input-monitor": load("app/ui/input-monitor.ts", {}),
'../remote/service': { startRemoteInput() {} },
'../assistant/system-tools': { registerSystemTools() {} },
'../assistant/window-tools': { registerWindowTools() {} },
'../assistant/navigate-tools': { registerNavigateTools() {} },
'../assistant/roam-tools': { registerRoamTools() {} },
"../native/ios-navigation-sensors": {},
'../native/notification-icons.ios': { bindIosNotifications() {}, iosNotificationsChanged() {}, onIosNotificationPopup: () => () => {}, readActiveNotifications: () => [] },
'../native/notification-sources': { shouldShowNotificationOnGlasses: () => true },
'../native/compass.ios': { bindCompassSession() {}, receiveCompassEvent() {} },
'@nativescript/core': { File: { fromPath: () => ({ writeTextSync() {} }) }, knownFolders: { documents: () => ({ path: '/tmp' }) }, path },
'../native/ios-voice-input': { iosVoiceInput: { handleSessionEnded() {}, stopPhoneCapture() {} } },
'../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() {} 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/plane': { flattenPlanesWithDraws: () => ({ image: { pixels: new Uint8Array([1, 2]), width: 2, height: 1 }, draws: [] }), planesFingerprint: () => 'fp' },
'../graphics/glyph-wire': { prepareFrameDraws: () => null },
'../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 },
};
const api = load('app/g2/ios-preview-controller.ts', {
require: id => modules[id] ?? {}, console: { log() {}, warn() {}, error() {} },
setTimeout: fn => { tasks.set(++nextTask, fn); return nextTask; }, clearTimeout: id => tasks.delete(id),
setInterval: () => ++nextTask, clearInterval() {},
UIDevice: { currentDevice: {} }, UIApplication: { sharedApplication: { protectedDataAvailable: true } },
UIApplicationProtectedDataWillBecomeUnavailable: 'lock', UIApplicationProtectedDataDidBecomeAvailable: 'unlock',
UIDeviceBatteryLevelDidChangeNotification: 'level', UIDeviceBatteryStateDidChangeNotification: 'state',
NSNotificationCenter: { defaultCenter: { addObserverForNameObjectQueueUsingBlock() {}, removeObserver() {} } },
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(); 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');
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(); await settle();
assert.equal(starts, 1); assert.ok(previews.length > previewCount);
controller.pause(); await controller.disconnect(); await settle();
assert.equal(stops, 1); assert.equal(screenStates.at(-1), false);
assert.equal(pollStops, 1);
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');
});
test('iOS bandwidth footer toggles live, polls only in foreground and resets its rate window on resume', () => {
const views = [], intervals = new Map(), appEvents = new Map(), settingListeners = new Set();
let enabled = false, atMs = 0, totals = { messages: 0, bytes: 0, frames: 0 }, nextId = 0;
class View {
events = new Map(); children = [];
constructor() { views.push(this); }
on(event, fn) { this.events.set(event, fn); }
addChild(view) { this.children.push(view); }
set(key, value) { this[key] = value; }
notifyPropertyChange() {}
getActualSize() { return { width: 0, height: 0 }; }
getViewById() { return null; }
static setRow() {} static setColumn() {}
}
const core = { Application: { suspendEvent: 'suspend', resumeEvent: 'resume',
on: (key, fn) => appEvents.set(key, fn), off: key => appEvents.delete(key) },
Builder: { load: () => new View() }, Observable: View, Button: View, Color: class {}, Dialogs: {}, GridLayout: View, Image: View, Label: View, Page: View, StackLayout: View };
const modules = {
"../ui/input-monitor": load("app/ui/input-monitor.ts", {}),
'../assistant/system-tools': { registerSystemTools() {} },
'../assistant/window-tools': { registerWindowTools() {} },
'../assistant/navigate-tools': { registerNavigateTools() {} },
'../assistant/roam-tools': { registerRoamTools() {} },
"../native/ios-navigation-sensors": {},
'../native/notification-icons.ios': { bindIosNotifications() {}, iosNotificationsChanged() {}, onIosNotificationPopup: () => () => {}, readActiveNotifications: () => [] },
'../native/notification-sources': { shouldShowNotificationOnGlasses: () => true },
'../native/compass.ios': { bindCompassSession() {}, receiveCompassEvent() {} },
'@nativescript/core': core,
'../apps/launcher': { launcherEntries: () => [] },
'../apps/all-apps': { ALL_APPS: [] },
'../g2/ios-preview-controller': { IosPreviewController: class { resume() {} pause() {} } },
'./phone-gestures': { PhoneGestureRecognizer: class { cancel() {} } },
'./ble-bandwidth-meter': require('../.test-build/app/phone-ui/ble-bandwidth-meter.js'),
'../native/ble-traffic': { sampleBleTraffic: () => totals },
'../ui/dashboard-settings': { brightnessSetting: { get: () => 'auto' }, displayModeSetting: { get: () => 'full' }, displayModeLabel: () => 'Full', showBleBandwidthSetting: { get: () => enabled },
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 },
};
modules['./keyboard-input-view-model'] = load('app/phone-ui/keyboard-input-view-model.ts', { require: id => modules[id] });
modules['./remote-controls-view-model'] = load('app/phone-ui/remote-controls-view-model.ts', { require: id => modules[id] });
const { createMainPage } = load('app/phone-ui/main-page.ios.ts', {
require: id => modules[id] ?? {}, Date: { now: () => atMs },
NSNotificationCenter: { defaultCenter: { addObserverForNameObjectQueueUsingBlock: () => ({}), removeObserver() {} } },
UIKeyboardWillChangeFrameNotification: 'keyboard', NSOperationQueue: { mainQueue: {} },
setInterval: fn => { const id = ++nextId; intervals.set(id, fn); return id; }, clearInterval: id => intervals.delete(id),
setTimeout: () => 1, clearTimeout() {},
});
const page = createMainPage(), footer = views.find(v => v.accessibilityIdentifier === 'ble-bandwidth-indicator');
page.events.get('loaded')(); assert.equal(intervals.size, 0); assert.equal(footer.visibility, 'collapse');
enabled = true; for (const fn of settingListeners) fn();
assert.equal(intervals.size, 1); assert.equal(footer.visibility, 'visible');
totals = { messages: 4, bytes: 2000, frames: 2 }; atMs = 1000; for (const fn of intervals.values()) fn();
assert.match(footer.text, /2.0 fps, 1,000 B\/frame/);
appEvents.get('suspend')(); assert.equal(intervals.size, 0);
const previousText = footer.text;
totals = { messages: 40, bytes: 20000, frames: 20 }; atMs = 20000;
for (const fn of settingListeners) fn(); assert.equal(footer.text, previousText); assert.equal(intervals.size, 0);
appEvents.get('resume')(); assert.equal(intervals.size, 1); assert.doesNotMatch(footer.text, /fps/);
enabled = false; for (const fn of settingListeners) fn(); assert.equal(footer.visibility, 'collapse'); assert.equal(intervals.size, 0);
page.events.get('unloaded')(); assert.equal(appEvents.size, 0); assert.equal(settingListeners.size, 0);
});
test('iOS configures an in-process surface before submitting constructor-triggered frames', async () => {
const submitted = [], surfaces = new Set();
const shell = { getWindows: () => [], configure() {}, registerWindow() {}, focusWindow() {}, foregroundWindow: () => null };
const api = load('app/g2/ios-preview-controller.ts', {
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: [] }), planesFingerprint: () => 'fp' },
'../graphics/glyph-wire': { prepareFrameDraws: () => null },
})[name] ?? {},
console,
});
// 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.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 }];
await controller.launchInProcessApp('nightscout', 'window:nightscout', options => {
plumbing = options;
early = options.submitFrame([{ pixels: new Uint8Array([10, 20]), width: 2, height: 1 }]);
return { window: { windowId: 'nightscout', surfaceId: 'window:nightscout', appId: 'nightscout' },
requestRender: () => options.submitFrame(fresh) };
});
await early;
assert.deepEqual(submitted, [[30, 40]]);
plumbing.removeSurface();
await plumbing.submitFrame(fresh);
assert.deepEqual(submitted, [[30, 40]], 'late callbacks cannot submit to a removed surface');
});
test('iOS compositor rejects missing and removed surfaces before crossing into Kotlin', () => {
let nativeSubmissions = 0;
const native = { configureIdXYWidthHeightZOrderTransparent() {}, removeId() {}, submitDrawsIdDataXYWidthHeightDraws() { nativeSubmissions++; } };
const api = load('app/graphics/surface-compositor.ios.ts', {
require: () => ({ toData: data => data }),
FaceclawKitIosSurfaceCompositor: { alloc: () => ({ initWithWidthHeight: () => native }) },
});
const c = new api.SurfaceCompositor(2, 1), pixels = new Uint8Array([1, 2]);
const rect = { x: 0, y: 0, width: 2, height: 1 };
assert.throws(() => c.submitSurfaceFrame('nightscout', pixels, rect), /Unknown surface/);
c.configureSurface('nightscout', { ...rect, zOrder: 0, transparency: 'opaque' });
c.submitSurfaceFrame('nightscout', pixels, rect);
c.removeSurface('nightscout');
assert.throws(() => c.submitSurfaceFrame('nightscout', pixels, rect), /Unknown surface/);
assert.equal(nativeSubmissions, 1);
});
test('iOS welcome sound waits for a new acknowledged frame and is consumed once', async () => {
let pending = true;
const played = [], sounds = load('app/ui/sound-effects.ts', { require: name => { assert.equal(name, '../g2/cfw-message-type'); return load('app/g2/cfw-message-type.ts', {}); } });
const { IosPreviewController } = load('app/g2/ios-preview-controller.ts', {
require: id => ({
'../phone-ui/onboarding-state': { isWelcomeSoundPending: () => pending, setWelcomeSoundPending: value => { pending = value; } },
'../ui/sound-effects': sounds,
})[id] ?? {},
setTimeout: fn => { fn(); return 1; },
});
const host = Object.create(IosPreviewController.prototype);
host.acknowledgedFrames = 0;
host.actions = { playBuzzerSequence: bytes => played.push([...bytes]) };
host.logBluetooth = assert.fail;
host.maybePlayWelcomeSound({ phase: 'connecting', frames: 0 });
host.maybePlayWelcomeSound({ phase: 'connected', frames: 0 });
assert.equal(pending, true); assert.equal(played.length, 0);
host.maybePlayWelcomeSound({ phase: 'connected', frames: 1 });
assert.equal(pending, false);
await new Promise(resolve => setImmediate(resolve));
assert.ok(played.length > 0);
const count = played.length;
host.maybePlayWelcomeSound({ phase: 'connected', frames: 1 });
host.maybePlayWelcomeSound({ phase: 'connected', frames: 2 });
assert.equal(played.length, count);
});
test('iOS preview voice uses the phone microphone, while connected capture stays on glasses', async () => {
const calls = [];
const bridge = { prepare: async (foreground, phone) => { calls.push(['prepare', foreground, phone]); return true; },
startPhoneCapture: async (_log, endpointing) => calls.push(['phone', endpointing]),
startGlassesCapture: async (_session, _log, endpointing) => calls.push(['glasses', endpointing]) };
const { IosPreviewController } = load('app/g2/ios-preview-controller.ts', {
require: id => id === '../native/ios-voice-input' ? { iosVoiceInput: bridge } : {},
});
const host = Object.create(IosPreviewController.prototype);
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.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.communicator = null; host.state = { phase: 'disconnected' };
assert.equal(await host.prepareVoiceCapture(), false); await host.startVoiceCapture();
assert.deepEqual(calls, []);
});
test('iOS keyboard action opens the shared destination session and remains blocked while locked', () => {
let opened = 0;
const { IosPreviewController } = load('app/g2/ios-preview-controller.ts', {
require: id => id === '../ui/shell/shell' ? { shell: { startKeyboardInput: () => opened++ } } : {},
});
const host = Object.create(IosPreviewController.prototype);
host.active = true; host.glassesLocked = false; host.typeIntoApp(); assert.equal(opened, 1);
host.glassesLocked = true; host.typeIntoApp(); assert.equal(opened, 1);
host.glassesLocked = false; host.active = false; host.typeIntoApp(); assert.equal(opened, 1);
});
test('iOS curve editor retains invalid draft and retries Save with a validation message', async () => {
const prompts = [], errors = [], saved = [];
const answers = [{ result: true, text: '0:0,5:' }, { result: true, text: '0:0,5:100' }];
const { IosPreviewController } = load('app/g2/ios-preview-controller.ts', { require: id => id === '@nativescript/core'
? { Dialogs: { prompt: async options => { prompts.push(options.defaultText); return answers.shift(); }, alert: async options => errors.push(options.message) } }
: {} });
const host = Object.create(IosPreviewController.prototype); host.active = true;
const curve = require('../.test-build/app/g2/brightness-curve.js');
assert.equal(await host.editSetting({ editorTitle: 'Auto light curve', get: () => '0:0,8:100',
set: value => saved.push(value), validationError: curve.brightnessCurveError }), true);
assert.deepEqual(prompts, ['0:0,8:100', '0:0,5:']);
assert.equal(errors.length, 1);
assert.deepEqual(saved, ['0:0,5:100']);
});
+133
View File
@@ -0,0 +1,133 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { loader } = require('./helpers/load-typescript.cjs');
const flush = () => new Promise(resolve => setImmediate(resolve));
function assistant(provider) {
const requests = [], calls = [], deltas = [], errors = [], done = [];
const registry = { listTools: () => [{ name: 'timer.set', description: 'Set a timer', inputSchema: { type: 'object' } }],
callTool: async (name, args) => { calls.push({ name, args }); return { ok: true, content: 'Timer set' }; } };
const load = loader({ global: { isIOS: true, isAndroid: false }, setTimeout, clearTimeout }, {
'./sse': { openSseRequest: (url, body, headers, listener) => {
const request = { url, body: JSON.parse(body), headers, listener, cancelled: false };
requests.push(request); return { cancel: () => { request.cancelled = true; } };
} },
'../native/llama': { streamLocalQwen: () => assert.fail('iOS must not invoke a local LLM') },
'./bridge-client': { assistantBridge: {} }, './tool-registry': { toolRegistry: registry },
'../prompts': { ASSISTANT_SYSTEM_PROMPT_BASE: 'test', buildAssistantSystemPrompt: () => 'test', describeAssistantContext: () => '' },
});
const { AssistantSession } = load('app/assistant/session.ts');
const session = new AssistantSession({ kind: 'direct', llm: { selection: 'auto', provider, model: 'fixture-model', apiKey: 'fixture-key', effort: 'low' } }, registry);
const send = text => session.sendUtterance(text, {}, { onTextDelta: (_delta, full) => deltas.push(full),
onToolActivity() {}, onError: error => errors.push(error), onTurnDone: result => done.push(result) });
const event = (request, event) => request.listener.onLine('data: ' + JSON.stringify(event));
function text(request, value) {
if (provider === 'anthropic') {
event(request, { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } });
event(request, { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: value } });
} else event(request, { type: 'response.output_text.delta', output_index: 0, delta: value });
}
function finish(request, tool = false) {
if (provider === 'anthropic') {
event(request, { type: 'message_delta', delta: { stop_reason: tool ? 'tool_use' : 'end_turn' } });
event(request, { type: 'message_stop' });
} else event(request, { type: 'response.completed' });
}
function tool(request) {
if (provider === 'anthropic') {
event(request, { type: 'content_block_start', index: 1, content_block: { type: 'tool_use', id: 'tool-1', name: 'timer_set' } });
event(request, { type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: '{"seconds":' } });
event(request, { type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: '60}' } });
} else {
event(request, { type: 'response.output_item.done', output_index: 1, item: { type: 'reasoning', id: 'reason', encrypted_content: 'opaque-fixture' } });
event(request, { type: 'response.output_item.added', output_index: 2, item: { type: 'function_call', call_id: 'tool-1', id: 'item-1', name: 'timer_set', arguments: '' } });
event(request, { type: 'response.function_call_arguments.delta', output_index: 2, delta: '{"seconds":' });
event(request, { type: 'response.function_call_arguments.delta', output_index: 2, delta: '60}' });
}
}
return { load, session, send, event, text, finish, tool, requests, calls, deltas, errors, done };
}
for (const provider of ['openai', 'anthropic']) {
test(`iOS ${provider} streams, calls shared tools, continues with results, and preserves follow-up history`, async () => {
const h = assistant(provider); h.send('Set a one-minute timer');
const first = h.requests[0]; assert.equal(first.body.stream, true);
if (provider === 'openai') { assert.equal(first.headers.Authorization, 'Bearer fixture-key'); assert.equal(first.body.store, false); }
else assert.equal(first.headers['x-api-key'], 'fixture-key');
h.text(first, 'Setting π 👓'); h.tool(first); h.finish(first, true); await flush();
assert.equal(first.cancelled, true); assert.equal(h.calls[0].name, 'timer.set'); assert.equal(h.calls[0].args.seconds, 60);
assert.equal(h.requests.length, 2);
const second = h.requests[1];
assert.match(JSON.stringify(second.body), /Timer set/);
if (provider === 'openai') assert.match(JSON.stringify(second.body), /opaque-fixture/);
h.text(second, 'Your timer is running.'); h.finish(second);
assert.equal(h.session.isTurnActive(), false); assert.equal(h.done.length, 1); assert.equal(h.errors.length, 0);
h.send('What did you set?');
assert.match(JSON.stringify(h.requests[2].body), /Your timer is running/);
h.session.cancel(); assert.equal(h.requests[2].cancelled, true);
});
test(`iOS ${provider} cancellation, HTTP errors and premature EOF never execute incomplete tools`, async () => {
const h = assistant(provider); h.send('test'); const first = h.requests[0]; h.session.cancel();
h.text(first, 'late'); h.tool(first); h.finish(first, true); await flush();
assert.equal(h.calls.length, 0); assert.equal(h.deltas.length, 0);
h.send('retry'); h.requests[1].listener.onHttpError(401, '{"error":{"message":"Invalid API key"}}');
assert.equal(h.session.isTurnActive(), false); assert.match(h.errors[0], /key/i);
h.send('retry'); const third = h.requests[2]; h.text(third, 'Partial'); h.tool(third); third.listener.onComplete(); await flush();
assert.match(h.errors.at(-1), /before.*completed/); assert.equal(h.calls.length, 0); assert.equal(third.cancelled, true);
});
}
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({
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].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].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', () => {
const api = loader({ global: { isIOS: true } }, { '../native/llama': { LOCAL_MODEL: { label: 'Qwen', id: 'qwen' }, isLocalModelReady: () => false } })('app/assistant/models.ts');
assert.equal(api.ASSISTANT_MODEL_CHOICES.includes('qwen'), false);
assert.equal(api.supportedAssistantModel('qwen'), 'auto');
assert.equal(api.resolveAssistantModel('auto', { openai: 'key', anthropic: '' }).provider, 'openai');
assert.equal(api.resolveAssistantModel('auto', { openai: '', anthropic: 'key' }).provider, 'anthropic');
assert.equal(api.resolveAssistantModel('auto', { openai: '', anthropic: '' }), null);
const { AssistantConversations } = loader({}, { './models': api, './session': {} })('app/assistant/conversations.ts');
const history = { messages: [], transcript: [{ role: 'user', text: 'Keep this conversation' }] };
const saved = JSON.stringify({ selectedId: 'old', conversations: [{ id: 'old', model: 'qwen', reasoning: 'default', history }] });
const conversations = new AssistantConversations(() => null, () => 'auto', () => {}, saved);
assert.equal(conversations.current().model, 'auto'); assert.equal(conversations.title(), 'Keep this conversation');
});
test('cancelling during a tool prevents subsequent tool side effects and a stalled turn times out', async () => {
let stream, completeTool, deadline;
const calls = [], failures = [];
const { DirectAssistantBackend } = loader({ setTimeout: fn => { deadline = fn; return 1; }, clearTimeout() {} }, {
'../native/openai': { streamOpenAiResponse: options => { stream = options; return { cancel() {} }; } },
'../native/anthropic': {}, '../native/llama': {},
})('app/assistant/direct-backend.ts');
const backend = new DirectAssistantBackend();
const options = { provider: 'openai', messages: [], buildTools: () => [], resolveToolName: name => name,
registry: { callTool: name => { calls.push(name); return new Promise(resolve => { completeTool = resolve; }); } },
callbacks: { onTextDelta() {}, onToolActivity() {}, onTurnDone() {}, onError: message => failures.push(message) } };
const handle = backend.runTurn(options);
stream.onDone({ text: '', stopReason: 'tool_use', content: [1, 2].map(id => ({ type: 'tool_use', id: String(id), name: 'tool' + id, input: {} })) });
handle.cancel(); completeTool({ ok: true, content: 'done' }); await flush();
assert.deepEqual(calls, ['tool1']);
backend.runTurn({ ...options, messages: [] }); deadline(); assert.match(failures[0], /too long/);
});
+265
View File
@@ -0,0 +1,265 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const ts = require('typescript');
function load(file, modules = {}, globals = {}) {
const sandbox = { exports: {}, require: id => {
if (!(id in modules)) throw new Error(`Unstubbed import: ${id}`);
return modules[id];
}, ...globals };
vm.runInNewContext(ts.transpileModule(fs.readFileSync(path.join(__dirname, '..', file), 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, sandbox);
return sandbox.exports;
}
const flush = () => new Promise(resolve => setImmediate(resolve));
function provider() {
let now = 1000000, granted = true;
const reads = [];
const bridge = { readUpcomingEventsWindowMsCompletion: (max, window, done) => reads.push({ max, window, done }) };
const permissions = { hasCalendarPermission: () => granted };
const clock = { Date: class extends Date { static now() { return now; } } };
const api = load('app/native/calendar.ios.ts', { './calendar-permissions': permissions }, {
FaceclawCalendar: { shared: () => bridge }, ...clock,
});
const event = (id, extra = {}) => ({ id, title: 'Meeting', startMs: now + 10000, endMs: now + 60000,
allDay: false, location: 'Office', calendarName: 'Work', ...extra });
return { api, bridge, reads, permissions, event, clock, advance: ms => { now += ms; }, permission: value => { granted = value; } };
}
test('iOS calendar reads asynchronously, shares pending work, caches, and expires ended events', () => {
const f = provider(); let changes = 0;
f.api.onCalendarChanged(() => changes++);
assert.equal(f.api.readUpcomingEvents().length, 0);
assert.equal(f.api.getCalendarReadState(), 'loading');
f.api.readUpcomingEvents(); assert.equal(f.reads.length, 1);
assert.equal(f.reads[0].max, 50); assert.equal(f.reads[0].window, 14 * 86400000);
f.reads[0].done(JSON.stringify([f.event('one')]), null);
assert.equal(changes, 1); assert.equal(f.api.getCalendarReadState(), 'ready');
assert.equal(f.api.readUpcomingEvents()[0].id, 'one'); assert.equal(f.reads.length, 1);
f.advance(30000); assert.equal(f.api.readUpcomingEvents()[0].id, 'one');
f.api.readUpcomingEvents(); assert.equal(f.reads.length, 2);
f.advance(30001); assert.equal(f.api.readUpcomingEvents().length, 0, 'ended events disappear even during refresh');
});
test('iOS calendar preserves recurrence occurrences, all-day fields and overlapping events, and sorts before limiting', () => {
const f = provider(); f.api.readUpcomingEvents(3, 100000);
f.reads[0].done(JSON.stringify([
f.event('series', { startMs: 1080000, endMs: 1090000 }),
f.event('later', { startMs: 1090000, endMs: 1095000 }),
f.event('series', { startMs: 1030000, endMs: 1040000 }),
f.event('all-day', { startMs: 900000, allDay: true, location: '', calendarName: 'Personal' }),
f.event('ended', { startMs: 900000, endMs: 999999 }),
f.event('outside', { startMs: 1100000, endMs: 1110000 }),
f.event('bad', { startMs: null }), f.event('bad-end', { endMs: 'invalid' }), null,
]), null);
const rows = f.api.readUpcomingEvents(3, 100000);
assert.deepEqual(Array.from(rows, e => e.id), ['all-day', 'series', 'series']);
assert.equal(rows[0].allDay, true); assert.equal(rows[0].calendarName, 'Personal');
assert.equal(rows[0].startMs, 900000); assert.equal(rows[0].location, '');
});
test('event-store changes invalidate pending reads and notify only active subscribers', () => {
const f = provider(); let changes = 0;
const off = f.api.onCalendarChanged(() => changes++);
f.api.readUpcomingEvents(); const old = f.reads[0];
f.bridge.changeHandler(); assert.equal(changes, 1);
f.api.readUpcomingEvents(); old.done(JSON.stringify([f.event('stale')]), null);
assert.equal(f.api.getCalendarReadState(), 'loading'); assert.equal(changes, 1);
f.reads[1].done(JSON.stringify([f.event('fresh')]), null);
assert.equal(f.api.readUpcomingEvents()[0].id, 'fresh'); assert.equal(changes, 2);
off(); f.bridge.changeHandler(); assert.equal(changes, 2);
});
test('permission revocation prevents cached and in-flight calendar data from resurfacing', () => {
const f = provider(); f.api.readUpcomingEvents();
f.reads[0].done(JSON.stringify([f.event('private')]), null);
f.permission(false); assert.equal(f.api.readUpcomingEvents().length, 0);
f.permission(true); f.api.readUpcomingEvents();
f.permission(false); f.reads[1].done(JSON.stringify([f.event('private')]), null);
assert.equal(f.api.readUpcomingEvents().length, 0);
f.permission(true); assert.equal(f.api.readUpcomingEvents().length, 0);
assert.equal(f.reads.length, 3);
});
test('calendar read failures have a distinct state and retry after the cache interval', () => {
for (const [json, error] of [['[]', 'Unavailable'], ['bad json', null], ['{}', null]]) {
const f = provider(); f.api.readUpcomingEvents(); f.reads[0].done(json, error);
assert.equal(f.api.getCalendarReadState(), 'error');
assert.equal(f.api.readUpcomingEvents().length, 0); assert.equal(f.reads.length, 1);
f.advance(30000); f.api.readUpcomingEvents();
f.reads[1].done('[]', null); assert.equal(f.api.getCalendarReadState(), 'ready');
}
});
test('calendar input bounds, query changes and force refresh do not reuse the wrong result', () => {
const f = provider();
for (const value of [0, -1, NaN, Infinity]) assert.equal(f.api.readUpcomingEvents(value).length, 0);
f.api.readUpcomingEvents(5, 0); f.api.readUpcomingEvents(5, NaN); assert.equal(f.reads.length, 0);
f.api.readUpcomingEvents(999, Number.MAX_VALUE);
assert.equal(f.reads[0].max, 200); assert.equal(f.reads[0].window, 366 * 86400000);
f.api.readUpcomingEvents(); f.reads[0].done(JSON.stringify([f.event('wrong-query')]), null);
assert.equal(f.api.readUpcomingEvents().length, 0);
f.reads[1].done(JSON.stringify([f.event('right-query')]), null);
assert.equal(f.api.readUpcomingEvents(50, 14 * 86400000, true)[0].id, 'right-query');
assert.equal(f.reads.length, 3);
});
function permissionFixture(initial = 'not-determined') {
let status = initial, confirm = true;
const requests = [], dialogs = [], opened = [];
const api = load('app/native/calendar-permissions.ios.ts', {
'@nativescript/core': {
Dialogs: { confirm: async options => { dialogs.push(options); return confirm; }, alert: async options => { dialogs.push(options); } },
Utils: { openUrl: async url => opened.push(url) },
},
}, { FaceclawCalendar: { shared: () => ({ hasPermission: () => status === 'granted',
permissionStatus: () => status, requestPermission: done => requests.push(done) }) } });
return { api, requests, dialogs, opened, status: value => { status = value; }, confirm: value => { confirm = value; } };
}
test('calendar permission requests coalesce, allow write-only upgrades, and propagate failures', async () => {
for (const status of ['not-determined', 'write-only']) {
const f = permissionFixture(status);
assert.equal(f.api.hasCalendarPermission(), false);
const first = f.api.ensureCalendarPermission(); assert.equal(f.api.ensureCalendarPermission(), first);
assert.equal(f.requests.length, 1); f.requests[0](false, null); assert.equal(await first, false);
const retry = f.api.ensureCalendarPermission(); f.requests[1](false, 'Native failure');
await assert.rejects(retry, /Native failure/);
const grant = f.api.ensureCalendarPermission(); f.status('granted'); f.requests[2](true, null);
assert.equal(await grant, true); assert.equal(await f.api.ensureCalendarPermission(), true);
assert.equal(f.requests.length, 3);
}
});
test('denied calendar access offers Settings; restricted access explains the restriction', async () => {
const denied = permissionFixture('denied');
denied.confirm(false); assert.equal(await denied.api.ensureCalendarPermission(), false);
assert.equal(denied.opened.length, 0);
denied.confirm(true); await denied.api.ensureCalendarPermission();
assert.deepEqual(denied.opened, ['app-settings:']); assert.equal(denied.requests.length, 0);
const restricted = permissionFixture('restricted'); await restricted.api.ensureCalendarPermission();
assert.match(restricted.dialogs[0].title, /Restricted/);
assert.equal(restricted.requests.length, 0); assert.equal(restricted.opened.length, 0);
});
function screenFixture() {
const f = provider(), timers = new Map(); let nextTimer = 0;
const font = { lineHeight: 12, measureText: text => text.length * 6 };
class Image {
constructor(width = 300, height = 288) { this.width = width; this.height = height; this.text = []; }
drawText(_font, _x, _y, text) { this.text.push(text); }
fillRoundedRect() {} drawRoundedRect() {}
}
const common = {
'graphics/image': { GrayImage: Image }, 'graphics/ui-fonts': { getDefaultSmallFont: () => font, getDefaultMediumFont: () => font },
'graphics/textwrap': { truncateText: (_font, text) => text, wrapText: (_font, text) => [text] },
'native/calendar': f.api, 'native/calendar-permissions': f.permissions, 'ui/metrics': { lineStep: () => 14 },
'ui/dashboard-settings': { timeFormatSetting: { get: () => '24h' } }, 'ui/gestures': { GESTURE_CLICK: 'Tap' },
'util/numeric-util': { clamp: (n, min, max) => Math.max(min, Math.min(max, n)) },
};
const modules = depth => Object.fromEntries(Object.entries(common).map(([key, value]) => [depth + key, value]));
const calendar = load('app/apps/calendar/calendar.ts', modules('../../'));
const widget = load('app/apps/glanceboard/widgets/calendar-widget.ts', {
...modules('../../../'), '../../calendar/calendar': calendar,
}, { ...f.clock, setInterval: fn => { timers.set(++nextTimer, fn); return nextTimer; }, clearInterval: id => timers.delete(id) });
return { ...f, ...calendar, ...widget, timers, Image };
}
test('Calendar and Glanceboard show permission, loading, error and event states with widget cleanup', () => {
const f = screenFixture(); let renders = 0, requests = 0;
const widget = new f.CalendarWidget(), layer = new f.CalendarLayer(() => requests++);
const ctx = { stack: { getBaseSize: () => ({ width: 300, height: 288 }) } };
const paintWidget = () => { const image = new f.Image(); widget.paint(image); return image.text.join(' '); };
widget.start(() => renders++); widget.start(() => renders++); assert.equal(f.timers.size, 1);
f.permission(false); assert.match(layer.paint(ctx).text.join(' '), /Grant calendar permission/);
assert.match(paintWidget(), /permission needed/);
layer.handleInput({ type: 'click' }); assert.equal(requests, 1); assert.equal(f.reads.length, 0);
f.permission(true); assert.match(layer.paint(ctx).text.join(' '), /Loading/);
assert.match(paintWidget(), /Loading/);
f.reads[0].done('[]', 'Unavailable'); assert.match(layer.paint(ctx).text.join(' '), /unavailable/);
assert.match(paintWidget(), /unavailable/);
f.api.invalidateCalendarCache(); layer.paint(ctx);
f.reads[1].done(JSON.stringify([f.event('event')]), null);
assert.match(layer.paint(ctx).text.join(' '), /Meeting/);
assert.match(paintWidget(), /Meeting/);
widget.stop(); const before = renders; f.bridge.changeHandler();
assert.equal(renders, before); assert.equal(f.timers.size, 0);
});
test('Calendar window subscribes, refreshes periodically, and cleans up on close', async () => {
let options, listener, tick, unsubscribed = 0, cleared = 0, closed = 0, renders = 0;
const app = { requestRender: () => renders++ };
const { createCalendarAppWindow } = load('app/apps/calendar/calendar-app.ts', {
'../../native/calendar-permissions': { hasCalendarPermission: () => true },
'../../native/calendar': { onCalendarChanged: fn => { listener = fn; return () => unsubscribed++; } },
'../../ui/shell/chrome-layer': { makeImageWindowIcon() {}, windowIcon() {} },
'./calendar': { CalendarLayer: class {} }, './calendar-icon': {},
'../../ui/shell/in-process-window': { YieldAtRootLayer: class {}, createInProcessWindow: value => { options = value; return app; } },
}, { setInterval: fn => { tick = fn; return 1; }, clearInterval: () => cleared++ });
createCalendarAppWindow({ onClosed: () => closed++ });
listener(); tick(); assert.equal(renders, 2);
options.onClosed(); assert.equal(unsubscribed, 1); assert.equal(cleared, 1); assert.equal(closed, 1);
});
test('iOS Calendar is launchable and its permission remains optional during onboarding', async () => {
const availability = load('app/apps/ios-availability.ts');
assert.equal(availability.iosAppUnavailableReason('calendar'), null);
const f = permissionFixture(); let resumed;
const { PermissionsViewModel } = load('app/phone-ui/permissions-view-model.ts', {
'@nativescript/core': { Observable: class { notifyPropertyChange() {} },
Application: { on: (_event, fn) => { resumed = fn; }, off() {} } },
'../native/ios-bluetooth': { iosBluetooth: () => ({ state: 5 }) },
'../native/calendar-permissions': f.api,
'../g2/android-permissions': {}, '../native/battery-optimization': {}, '../native/notification-access': {},
}, { global: { isIOS: true } });
const model = new PermissionsViewModel({ onboarding: true }); model.onPageLoaded();
const card = () => model.cards.find(item => item.id === 'calendar');
assert.equal(card().optionalVisibility, 'visible'); assert.equal(card().checkVisibility, 'collapse');
assert.equal(model.primaryClass, '-primary');
model.onCardTap({ object: { bindingContext: card() } }); assert.equal(f.requests.length, 1);
f.status('granted'); f.requests[0](true, null); await flush();
assert.equal(card().checkVisibility, 'visible');
f.status('denied'); resumed(); assert.equal(card().checkVisibility, 'collapse');
});
test('awaited calendar reads do not replace the display cache and reject failures or revoked access', async () => {
const f = provider(); f.api.readUpcomingEvents();
const awaited = f.api.readUpcomingEventsAsync(10, 3600000);
assert.equal(f.reads[1].max, 10); assert.equal(f.reads[1].window, 3600000);
f.reads[1].done(JSON.stringify([f.event('assistant')]), null);
assert.equal((await awaited)[0].id, 'assistant');
assert.equal(f.api.getCalendarReadState(), 'loading');
f.reads[0].done(JSON.stringify([f.event('display')]), null);
assert.equal(f.api.readUpcomingEvents()[0].id, 'display');
const failed = f.api.readUpcomingEventsAsync(); f.reads[2].done('[]', 'Unavailable');
await assert.rejects(failed, /Unavailable/);
const revoked = f.api.readUpcomingEventsAsync(); f.permission(false);
f.reads[3].done(JSON.stringify([f.event('private')]), null);
await assert.rejects(revoked, /permission/);
await assert.rejects(f.api.readUpcomingEventsAsync(), /permission/);
assert.equal(f.reads.length, 4);
});
test('iOS assistant calendar tool awaits events, reports denied access and failures, and leaves unsupported tools hidden', async () => {
const f = provider(), registered = new Map();
const { registerSystemTools } = load('app/assistant/system-tools.ts', {
'../native/calendar': f.api, '../native/calendar-permissions': f.permissions,
'../native/media-controller': {}, '../native/notification-icons': {}, '../ui/shell/shell': {}, './tool-registry': {},
}, { global: { isIOS: true } });
registerSystemTools({ registerSystemTool: (definition, handler) => registered.set(definition.name, handler) });
assert.deepEqual([...registered.keys()], ['glasses.get_state', 'glasses.show_alert', 'calendar.list_events']);
const list = registered.get('calendar.list_events');
const result = list({ within_hours: 2, max_events: 3 });
assert.equal(f.reads[0].max, 3); assert.equal(f.reads[0].window, 7200000);
f.reads[0].done(JSON.stringify([f.event('one')]), null);
assert.match((await result).content, /Meeting.*Office/);
const empty = list({}); f.reads[1].done('[]', null);
assert.match((await empty).content, /No upcoming/);
const failed = list({}); f.reads[2].done('[]', 'Failed'); assert.equal((await failed).ok, false);
f.permission(false); assert.equal((await list({})).ok, false); assert.equal(f.reads.length, 3);
});
+86
View File
@@ -0,0 +1,86 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const ts = require('typescript');
const path = require('node:path');
function load(file, context = {}) {
const sandbox = { exports: {}, console, ...context };
vm.runInNewContext(ts.transpileModule(fs.readFileSync(path.join(__dirname, '..', file), 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, sandbox);
return sandbox.exports;
}
test('iOS compass owners and listeners work before connection and across session replacement', () => {
const api = load('app/native/compass.ios.ts', { require: () => ({}) });
const states = [], nextStates = [], events = [];
const off = api.addCompassListener(event => events.push(event));
api.setCompassEnabled(true, 'compass');
api.setCompassEnabled(true, 'glanceboard');
api.bindCompassSession({ setCompassEnabled: enabled => states.push(enabled) });
api.setCompassEnabled(false, 'compass');
assert.deepEqual(states, [true, true]);
api.bindCompassSession({ setCompassEnabled: enabled => nextStates.push(enabled) });
assert.equal(states.at(-1), false);
api.setCompassEnabled(false, 'glanceboard');
assert.deepEqual(nextStates, [true, false]);
api.receiveCompassEvent({ command: 15, headingDegrees: 271 });
off(); api.receiveCompassEvent({ command: 15, headingDegrees: 90 });
assert.deepEqual(events, [{ command: 15, headingDegrees: 271 }]);
});
test('shared declination cache handles iOS fixes, persisted corrections and unavailable sensors', async () => {
const store = new Map(), listeners = [];
let permission = false, lookups = 0, fail = false;
let now = 1_800_000_000_000;
const ios = load('app/native/declination.ios.ts');
const context = {
Date: { now: () => now }, console: { warn() {} },
require: id => ({
'../../native/location-permissions': { hasLocationPermission: () => permission },
'../../native/declination': { restoreDeclination: ios.restoreDeclination, getCurrentDeclination: async () => {
lookups++; if (fail) throw new Error('No heading sensor');
return { latitude: 37.7, longitude: -122.4, degrees: 12.5 };
} },
'../../native/settings-store': { getStringSetting: (key, fallback) => store.get(key) ?? fallback,
setStringSetting: (key, value) => store.set(key, value) },
})[id],
};
const api = load('app/apps/compass/declination.ts', context);
api.onDeclinationChanged(() => listeners.push(api.getDeclinationDegrees()));
assert.equal(api.getDeclinationAvailability(), 'no-permission');
api.refreshDeclination(); assert.equal(lookups, 0);
permission = true;
assert.equal(api.getDeclinationAvailability(), 'no-fix');
api.refreshDeclination(); api.refreshDeclination();
await new Promise(resolve => setImmediate(resolve));
assert.equal(lookups, 1); assert.deepEqual(listeners, [12.5]);
assert.equal(api.getDeclinationAvailability(), 'available');
const restarted = load('app/apps/compass/declination.ts', context);
assert.equal(restarted.getDeclinationDegrees(), 12.5);
restarted.refreshDeclination(); assert.equal(lookups, 1);
now += 25 * 60 * 60 * 1000; fail = true;
restarted.refreshDeclination(); await new Promise(resolve => setImmediate(resolve));
assert.equal(restarted.getDeclinationDegrees(), 12.5);
restarted.refreshDeclination(); assert.equal(lookups, 2);
// Existing Android preferences have coordinates but no cached correction.
store.delete('compass.declination.degrees'); fail = false;
store.set('compass.declination.locatedAtMs', String(now));
const migrated = load('app/apps/compass/declination.ts', context);
assert.equal(migrated.getDeclinationDegrees(), null);
migrated.refreshDeclination(); await new Promise(resolve => setImmediate(resolve));
assert.equal(migrated.getDeclinationDegrees(), 12.5);
});
test('iOS native correction callbacks resolve values or propagate unavailable errors', async () => {
let unavailable = false;
const api = load('app/native/declination.ios.ts', { FaceclawLocation: { shared: () => ({
requestDeclination: callback => callback(-8.25, 51, 0, unavailable ? 'Heading unavailable' : ''),
}) } });
assert.deepEqual({ ...await api.getCurrentDeclination() }, { latitude: 51, longitude: 0, degrees: -8.25 });
unavailable = true;
await assert.rejects(api.getCurrentDeclination(), /Heading unavailable/);
assert.equal(api.restoreDeclination(0, 0, NaN), null);
assert.equal(api.restoreDeclination(0, 0, 360), null);
});
+10
View File
@@ -0,0 +1,10 @@
const { execFileSync } = require('node:child_process');
const { mkdtempSync, rmSync } = require('node:fs');
const { tmpdir } = require('node:os');
const { join, resolve } = require('node:path');
const root = resolve(__dirname, '..'), dir = mkdtempSync(join(tmpdir(), 'faceclaw-config-'));
try {
execFileSync('xcrun', ['clang', '-fobjc-arc', '-framework', 'Foundation', '-I', 'App_Resources/iOS/src',
'tests/native/ios-config-test.m', 'App_Resources/iOS/src/FaceclawConfigPort.m', '-o', join(dir, 'config-test')], { cwd: root, stdio: 'inherit' });
execFileSync(join(dir, 'config-test'), [dir], { stdio: 'inherit' });
} finally { rmSync(dir, { recursive: true, force: true }); }
+21
View File
@@ -0,0 +1,21 @@
const test = require('node:test');
const { execFileSync } = require('node:child_process');
test('iOS config codec preserves Android XML and JSON types and rejects malformed imports', () => {
execFileSync('python3', ['-c', `
import importlib.util, pathlib, tempfile
spec = importlib.util.spec_from_file_location('config', 'scripts/ios_config.py')
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
values = {'terminal.connections': '[{"url":"g2mirror://test@host"}]', 'flag': True, 'empty': '', 'number': 42, 'ratio': 0.25, 'unicode': 'π & < 🔋\\nnext'}
with tempfile.TemporaryDirectory() as d:
p = pathlib.Path(d) / 'settings'
for xml in [False, True]:
m.atomic_write(p, m.encode_config(values, xml))
assert m.read_config(p) == values
assert p.stat().st_mode & 0o777 == 0o600
for invalid in [b'{}', b'<map><set name="x"/></map>', b'<map><boolean name="x" value="maybe"/></map>', b'<map><string name="x">a</string><string name="x">b</string></map>', b'{"schema":1,"settings":{"x":null}}', b'{"schema":1,"settings":{"x":NaN}}', b'<map><string name="x">oops']:
p.write_bytes(invalid)
try: m.read_config(p)
except (ValueError, m.ET.ParseError): pass
else: raise AssertionError('accepted invalid config')
`], { stdio: 'inherit' });
});
+70
View File
@@ -0,0 +1,70 @@
// Run the production WKWebView host in an isolated simulator app, no glasses.
const http = require('node:http');
const { execFileSync } = require('node:child_process');
const fs = require('node:fs'), path = require('node:path'), os = require('node:os');
const { loader } = require('./helpers/load-typescript.cjs');
const root = path.resolve(__dirname, '..'), work = fs.mkdtempSync(path.join(os.tmpdir(), 'faceclaw-evenhub-probe-'));
const bundle = path.join(work, 'EvenHubProbe.app'), dist = path.join(bundle, 'dist');
fs.mkdirSync(dist, { recursive: true });
const source = fs.readFileSync(path.join(root, 'app/apps/evenhub/session.ts'), 'utf8');
const shim = source.match(/export const EVENHUB_BRIDGE_INJECT_SCRIPT = `([\s\S]*?)`;/)[1];
const adapter = loader({}, { './session': {}, '../../version': {} })('app/apps/evenhub/webview.ios.ts').IOS_EVENHUB_TRANSPORT_SCRIPT;
fs.writeFileSync(path.join(bundle, 'bridge.js'), adapter + shim);
fs.writeFileSync(path.join(bundle, 'secret.txt'), 'must not be served');
fs.writeFileSync(path.join(dist, 'index.html'), `<script>flutter_inappwebview.callHandler('early')</script><script type="module" src="/app.js"></script>`);
fs.writeFileSync(path.join(dist, 'app.js'), `
import { value } from './module.js';
const call = name => flutter_inappwebview.callHandler(name);
if (value === 42) await call('module');
const previous = localStorage.getItem('probe'); localStorage.setItem('probe','saved'); await call(previous === 'saved' ? 'restored' : 'stored');
if ((await (await fetch('/data.json')).json()).ok) await call('fetch');
const image = new Image(); image.onload = () => call('image'); image.src = '/pixel.png';
setTimeout(() => call('timer'), 40); requestAnimationFrame(() => call('raf'));
await WebAssembly.instantiate(new Uint8Array([0,97,115,109,1,0,0,0])); await call('wasm');
if (!(await fetch('/%2e%2e/secret.txt')).ok) await call('traversal');
`);
fs.writeFileSync(path.join(dist, 'module.js'), 'export const value = 42;');
fs.writeFileSync(path.join(dist, 'data.json'), '{"ok":true}');
fs.writeFileSync(path.join(dist, 'pixel.png'), Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aBVkAAAAASUVORK5CYII=', 'base64'));
fs.writeFileSync(path.join(bundle, 'Info.plist'), `<?xml version="1.0"?><plist version="1.0"><dict><key>CFBundleIdentifier</key><string>com.faceclaw.evenhub-probe</string><key>CFBundleExecutable</key><string>EvenHubProbe</string><key>CFBundleName</key><string>EvenHubProbe</string><key>CFBundlePackageType</key><string>APPL</string><key>CFBundleVersion</key><string>1</string><key>CFBundleShortVersionString</key><string>1</string><key>NSAppTransportSecurity</key><dict><key>NSAllowsLocalNetworking</key><true/></dict><key>UILaunchScreen</key><dict/><key>LSRequiresIPhoneOS</key><true/></dict></plist>`);
const sdk = execFileSync('xcrun', ['--sdk', 'iphonesimulator', '--show-sdk-path'], { encoding: 'utf8' }).trim();
execFileSync('xcrun', ['clang', '-fobjc-arc', '-target', `${process.arch === 'arm64' ? 'arm64' : 'x86_64'}-apple-ios15.1-simulator`, '-isysroot', sdk,
'-framework', 'UIKit', '-framework', 'Foundation', '-framework', 'CoreGraphics', '-framework', 'WebKit', '-framework', 'UniformTypeIdentifiers',
'-I', 'App_Resources/iOS/src', 'tests/native/ios-evenhub-test.m', 'App_Resources/iOS/src/FaceclawEvenHubWebView.m', 'App_Resources/iOS/src/FaceclawCrypto.m', '-o', path.join(bundle, 'EvenHubProbe')], { cwd: root, stdio: 'inherit' });
const server = http.createServer((request, response) => {
if (request.url === '/redirect') { response.writeHead(302, { Location: `http://localhost:${server.address().port}/untrusted` }); response.end(); return; }
if (request.url === '/untrusted') { response.end("<script>webkit.messageHandlers.faceclaw.postMessage({kind:'call', name:'UNTRUSTED', args:'[]', id:0})</script>"); return; }
const file = path.join(dist, request.url === '/' ? 'index.html' : request.url.slice(1));
if (!file.startsWith(dist + path.sep) || !fs.existsSync(file)) { response.writeHead(404); response.end(); return; }
response.setHeader('Content-Type', file.endsWith('.js') ? 'text/javascript' : file.endsWith('.json') ? 'application/json' : file.endsWith('.png') ? 'image/png' : 'text/html');
response.end(fs.readFileSync(file));
});
server.listen(0, '127.0.0.1', async () => {
try {
fs.writeFileSync(path.join(bundle, 'remote.txt'), `http://127.0.0.1:${server.address().port}/`);
const device = process.argv[2] || 'booted';
execFileSync('xcrun', ['simctl', 'install', device, bundle], { stdio: 'inherit' });
const container = execFileSync('xcrun', ['simctl', 'get_app_container', device, 'com.faceclaw.evenhub-probe', 'data'], { encoding: 'utf8' }).trim();
const resultFile = path.join(container, 'Documents/result.json');
const readyFile = path.join(container, 'Documents/background-ready.json');
for (const file of [resultFile, readyFile]) fs.rmSync(file, { force: true });
execFileSync('xcrun', ['simctl', 'launch', '--terminate-running-process', device, 'com.faceclaw.evenhub-probe'], { stdio: 'inherit' });
let backgrounded = false;
const deadline = Date.now() + 50000;
while (!fs.existsSync(resultFile)) {
if (Date.now() > deadline) throw new Error(`EvenHub probe timed out (backgrounded=${backgrounded}); artifacts: ${work}`);
if (!backgrounded && fs.existsSync(readyFile)) {
execFileSync('xcrun', ['simctl', 'launch', device, 'com.apple.mobilesafari'], { stdio: 'inherit' });
backgrounded = true;
}
await new Promise(resolve => setTimeout(resolve, 100));
}
const result = JSON.parse(fs.readFileSync(resultFile, 'utf8'));
console.log(JSON.stringify({ work, ...result }));
if (!result.passed) process.exitCode = 1;
} catch (error) {
console.error(error); process.exitCode = 1;
} finally {
server.closeAllConnections(); server.close();
}
});
+236
View File
@@ -0,0 +1,236 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs'), vm = require('node:vm');
const { createHash } = require('node:crypto');
const { zstdCompressSync } = require('node:zlib');
const { loader } = require('./helpers/load-typescript.cjs');
const { LvglFont } = require('../.test-build/app/graphics/lvgl-font.js');
function pack(files) {
const key = Buffer.from('EVEN REALITIES');
const xor = b => Buffer.from(b.map((v, i) => v ^ key[i % key.length]));
const header = Buffer.alloc(20); header.write('EHPK'); header.writeUInt32LE(20, 8);
return Buffer.concat([header, ...Object.entries(files).map(([name, value]) => {
const text = Buffer.from(value), body = zstdCompressSync(text), path = Buffer.from(name), record = Buffer.alloc(16);
record.writeUInt32LE(0xbaa9bae4); record.writeUInt32LE(body.length, 4); record.writeUInt32LE(text.length, 8); record.writeUInt16LE(path.length, 14);
return Buffer.concat([record, xor(path), xor(body)]);
})]);
}
test('iOS LVGL reader loads the bundled font including CJK and game symbols', () => {
const bytes = new Uint8Array(fs.readFileSync('app/fonts/source-han-sans/SourceHanSansSC-Light-20.lvgl.bin'));
const font = new LvglFont(bytes);
// Metrics and full glyph SHA-256 vectors from production Java LvglFontFile.
assert.deepEqual([...font.metrics], [25, 19]);
const vectors = [
[0x25a6, 'b08ecb603fd059b0a00ba3088f18b79185c421e73049797cd3cb0828e1e5cd04'],
[0x25c6, 'c176d5dcdb5f7e3a7220455528efde3760672c40cee39b422fc3f5ad20df66dd'],
[0x4e2d, '9bde2c8f1ffcf7afc598f4d0350c9ff262484816aa0c9b46d31f0c3c09613003'],
[0xff21, '0074f96299a75b86912282416e47e0823790e091352aec852eff49b89b2e719d'],
];
for (const [cp, hash] of vectors) {
const glyph = font.glyph(cp);
const w = glyph[0] | glyph[1] << 8, h = glyph[2] | glyph[3] << 8;
assert.ok(w > 0 && h > 0); assert.equal(glyph.length, 8 + (Math.floor(w / 2) + 1) * h);
assert.equal(createHash('sha256').update(glyph).digest('hex'), hash);
}
assert.equal(font.glyph(0x10ffff).length, 0);
assert.throws(() => new LvglFont(bytes.subarray(0, 80)), /bounds|Truncated/);
});
test('EHPK entrypoints and extraction paths cannot escape their package directory', () => {
const load = loader({}, { fzstd: require('fzstd') });
const api = load('app/apps/evenhub/ehpk.ts');
assert.equal(api.safeEhpkPath('dist/assets/game.js'), true);
for (const path of ['../settings.json', '/private/file', 'dist/../../file', 'dist\\file', 'dist//x', '.', '..', 'x\0y', 'https://host/app']) {
assert.equal(api.safeEhpkPath(path), false);
assert.throws(() => api.parseManifest(JSON.stringify({ entrypoint: path })), /entrypoint/);
assert.throws(() => api.parseEhpk(pack({ [path]: 'test' })), /invalid file path/);
}
const archive = api.parseEhpk(pack({ 'app.json': '{"package_id":"test.app"}', 'dist/index.html': '<html>test</html>' }));
assert.ok(archive.files.has('dist/index.html'));
});
test('Files on iOS exposes Run app for EHPKs and passes the selected local path', () => {
let browserOptions, actions, opened, installed;
const load = loader({ global: { isIOS: true } }, {
'../../native/file-access': {}, '../../native/font-files': { isFontFile: () => false },
'../../graphics/installed-fonts': {}, '../../native/image-files': { isDecodableImageFile: () => false },
'../evenhub/installed-apps': { readEvenHubPackageManifest: () => null }, '../evenhub/permission-dialog': {},
'./file-browser': { FileBrowserLayer: class { constructor(options) { browserOptions = options; } } },
'./file-info-dialog': { FileInfoDialogLayer: class { constructor(entry, value) { actions = value; } } },
'./font-previewer': {}, './image-viewer': {}, './text-viewer': {},
'../../ui/shell/in-process-window': { createInProcessWindow: () => ({}) }, '../../ui/shell/shell': {},
});
load('app/apps/files/files-app.ts').createFilesAppWindow({ openEhpkApp: path => { opened = path; }, installEhpkApp: path => { installed = path; } });
assert.equal(browserOptions.isSupportedFile('test.EHPK'), true);
const ctx = { stack: { push() {}, pop() {} } };
browserOptions.onFilePicked({ name: 'test.ehpk', path: '/Documents/test.ehpk' }, ctx);
assert.deepEqual(Array.from(actions, a => a.label), ['Run app', 'Install']);
actions[0].onSelect(ctx); assert.equal(opened, '/Documents/test.ehpk');
actions[1].onSelect(ctx); assert.equal(installed, '/Documents/test.ehpk');
});
test('local package runtimes unpack independently and clean up after closing or a failed launch', async () => {
const files = new Map(), sessions = [];
const manifest = { package_id: 'test.app', name: 'Test' };
let archive = pack({ 'app.json': JSON.stringify(manifest), 'dist/index.html': '<html>test</html>' });
class Session { constructor(manifest, distDir) { this.manifest = manifest; this.distDir = distDir; sessions.push(this); } attachWebView(handle) { this.handle = handle; } close() { this.handle.destroy(); } }
const load = loader({ global: { isIOS: true } }, {
'@nativescript/core': { Application: {} }, fzstd: require('fzstd'),
'../../native/file-access': { appFilesDirPath: () => '/private/app', readBinaryFile: () => archive,
writeBinaryFile: (path, bytes) => { files.set(path, bytes); return true; },
deletePathRecursively: path => { for (const key of files.keys()) if (key.startsWith(path + '/')) files.delete(key); } },
'./session': { EvenHubSession: Session }, './evenhub-window': { createEvenHubWindow: () => ({}) },
'./webview': { createEvenHubWebView: () => ({ evaluateJs() {}, destroy() {} }) },
'../../ui/shell/shell': {}, './installed-apps': { readEvenHubPackageManifest: () => ({ packageId: 'test.app' }) },
});
const manager = load('app/apps/evenhub/manager.ts'), ctx = { appendLog() {}, launchInProcessApp: async () => {} };
await manager.launchPackage(ctx, '/test.ehpk'); await manager.launchPackage(ctx, '/test.ehpk');
assert.notEqual(sessions[0].distDir, sessions[1].distDir); assert.equal(manager.runningAppCount(), 2);
sessions[0].close(); assert.equal(manager.runningAppCount(), 1);
assert.ok(files.has(sessions[1].distDir + '/index.html')); assert.ok(!files.has(sessions[0].distDir + '/index.html'));
sessions[1].close(); assert.equal(files.size, 0);
await assert.rejects(manager.launchPackage({ ...ctx, launchInProcessApp: async () => { throw new Error('test launch failed'); } }, '/test.ehpk'), /test launch failed/);
assert.equal(files.size, 0); assert.equal(manager.runningAppCount(), 0);
archive = pack({ 'app.json': JSON.stringify(manifest) });
await assert.rejects(manager.launchPackage(ctx, '/bad.ehpk'), /entrypoint is missing/);
assert.equal(files.size, 0);
});
function sessionHarness(overrides = {}, playBuzzer = () => {}) {
const settings = new Map(), logs = [], renders = [];
const load = loader({ global: { isIOS: true }, setTimeout, clearTimeout, Promise }, {
'@nativescript/core': { ApplicationSettings: { getString: (k, d) => settings.get(k) ?? d, setString: (k, v) => settings.set(k, v) } },
'upng-js': require('upng-js'),
'../../graphics/evenhub-font': { EvenHubFont: { get: () => ({ drawText() {}, drawTextWrapped() {}, lineHeight: 20 }) } },
'../../ui/dashboard-settings': {}, '../../ui/sound-effects': {}, './api-key-dialog': {},
'./mic-router': { evenHubMicRouter: {} }, './imu-router': { evenHubImuRouter: {} },
'./compass-router': { evenHubCompassRouter: {} }, '../../assistant/tool-registry': {},
'../../native/location': {}, '../../native/location-tracker': {}, '../../native/location-permissions': {}, ...overrides,
});
const api = load('app/apps/evenhub/session.ts');
const session = new api.EvenHubSession({ name: 'Probe', packageId: 'test.probe', permissions: [] }, '/test/dist', line => logs.push(line), '', playBuzzer);
session.attachWindow({ requestRender: () => renders.push(1), windowId: 'probe', closeWindow() {} });
const web = vm.createContext({ Promise, Map, Date, console });
web.window = web;
web.__faceclawEvenHub = { postMessage: (name, args, id) => session.handleBridgeCall(name, args, id) };
let destroyed = false;
session.attachWebView({ evaluateJs: script => vm.runInContext(script, web), destroy: () => { destroyed = true; } });
vm.runInContext(api.EVENHUB_BRIDGE_INJECT_SCRIPT, web);
const call = (method, data = {}) => web.flutter_inappwebview.callHandler('evenAppMessage', JSON.stringify({ method, data }));
return { session, call, web, logs, renders, destroyed: () => destroyed };
}
test('injected EvenHub RPC creates, updates and composites an image page with no Android globals', async () => {
const h = sessionHarness();
assert.equal(await h.call('createStartUpPageContainer', { containerTotalNum: 1,
imageObject: [{ containerID: 1, containerName: 'board', xPosition: 0, yPosition: 0, width: 2, height: 2 }] }), 0);
assert.equal(await h.call('updateImageRawData', { containerID: 1, containerName: 'board', imageData: [0, 80, 160, 255] }), 0);
const painted = h.session.paint({ width: 576, height: 288 }, true);
assert.deepEqual([painted.pixels[0], painted.pixels[1], painted.pixels[576], painted.pixels[577]], [0, 80, 160, 255]);
assert.equal(await h.call('setLocalStorage', { key: 'score', value: '42' }), true);
assert.equal(await h.call('getLocalStorage', { key: 'score' }), '42');
const events = [];
h.web._listenEvenAppMessage = value => events.push(typeof value === 'string' ? JSON.parse(value) : value);
h.session.handleGesture({ type: 'click', source: 'ring' });
assert.ok(events.some(e => e.method === 'evenHubEvent'));
assert.equal(await h.call('audioControl', { isOpen: true }), false);
assert.equal(await h.call('imuControl', { isOpen: true }), false);
assert.equal(await h.call('getAppLocation'), null);
h.session.close(); await new Promise(resolve => setTimeout(resolve, 120)); assert.equal(h.destroyed(), true);
});
test('iOS webview adapter defers loading until handles attach and destroys a not-yet-loaded app', () => {
const timers = new Map(), calls = [];
const native = { startEntrypointScript: (...args) => calls.push(args), startURLScript: (...args) => calls.push(args), destroy: () => calls.push('destroy') };
const load = loader({ FaceclawEvenHubWebView: { new: () => native },
setTimeout: fn => { timers.set(1, fn); return 1; }, clearTimeout: id => timers.delete(id) }, {
'./session': { EVENHUB_BRIDGE_INJECT_SCRIPT: 'BRIDGE', buildFaceclawExtensionsScript: () => 'EXT' }, '../../version': { FACECLAW_VERSION: 'test' },
});
const { createEvenHubWebView } = load('app/apps/evenhub/webview.ios.ts');
const session = { manifest: { name: 'Probe', entrypoint: 'index.html' }, distDir: '/app/dist' };
const host = createEvenHubWebView(session); assert.equal(calls.length, 0);
timers.get(1)(); assert.equal(calls[0][0], '/app/dist'); assert.match(calls[0][2], /postMessage/); assert.match(calls[0][2], /BRIDGEEXT$/);
host.destroy(); assert.equal(timers.size, 0); assert.equal(calls.at(-1), 'destroy');
const remote = createEvenHubWebView({ ...session, remoteUrl: 'https://example.test' });
timers.get(1)(); assert.equal(calls.at(-1)[0], 'https://example.test');
remote.destroy();
});
test('EvenHub location uses the platform boundary and closes its subscription', async () => {
let permission = true, callback, starts = 0, stops = 0;
const fix = { latitude: 12, longitude: 34, accuracyMeters: 5, timestampMs: 1234 };
const h = sessionHarness({
'../../native/location-permissions': { ensureFineLocationPermission: async () => permission },
'../../native/location': { getCurrentLocation: async () => fix },
'../../native/location-tracker': { LocationTracker: class {
constructor(value) { callback = value; } start() { starts++; } stop() { stops++; }
} },
});
assert.equal(await h.call('getAppLocation'), null); // No manifest permission.
h.session.manifest.permissions.push({ name: 'location' });
assert.deepEqual(JSON.parse(JSON.stringify(await h.call('getAppLocation'))), {
latitude: 12, longitude: 34, accuracy: 5, timestamp: 1234,
});
permission = false;
assert.equal(await h.call('startAppLocationUpdates'), false);
permission = true;
assert.equal(await h.call('startAppLocationUpdates'), true);
assert.equal(starts, 1);
const events = [];
h.web._listenEvenAppMessage = value => events.push(typeof value === 'string' ? JSON.parse(value) : value);
callback.onLocation(fix);
assert.equal(events.at(-1).method, 'appLocationChanged');
h.session.close();
assert.equal(stops, 1);
});
test('iOS store terminal identity persists and signing crosses the native boundary', () => {
const settings = new Map();
const api = loader({ NSUUID: { UUID: () => ({ UUIDString: '12345678-1234-5678-90AB-123456789ABC' }) },
FaceclawCrypto: { hmacSha256Message: (key, body) => require('node:crypto').createHmac('sha256', key).update(body).digest('base64') },
}, { '../../native/settings-store': {
getStringSetting: (key, fallback) => settings.get(key) ?? fallback,
setStringSetting: (key, value) => settings.set(key, value),
} })('app/apps/evenhub/even-platform.ios.ts');
assert.equal(api.getPhoneOpenUdid(), '1234567812345678');
assert.equal(api.getPhoneOpenUdid(), '1234567812345678');
assert.equal(settings.size, 1);
assert.equal(api.hmacSha256Base64('key', 'The quick brown fox jumps over the lazy dog'), '97yD9DBThCSxMpjmqm+xQ+9NWaFJRhdZl0edvC0aPNg=');
});
test('store login and catalog requests use platform signing with the shared wire format', async () => {
const requests = [], signatures = [];
let token = '';
const api = loader({ setTimeout, clearTimeout }, {
'./even-platform': { getPhoneOpenUdid: () => 'fixture-terminal', hmacSha256Base64: (_key, value) => { signatures.push(value); return 'fixture-signature'; } },
'./credentials': { getEvenHubToken: () => token, hasEvenHubCredentials: () => !!token,
saveEvenHubSession: (_email, value) => { token = value; }, invalidateEvenHubToken() {} },
'../../util/http': { fetchWithUserAgent: async (url, init) => {
requests.push({ url, ...init });
return { status: 200, json: async () => ({ code: 0, data: url.endsWith('/login') ? { token: 'fixture-token' } : { list: [], total: 0 } }) };
} },
})('app/apps/evenhub/even-api.ts');
await api.evenHubApi.signIn('test@example.invalid', 'fixture-password', false);
await api.evenHubApi.listApps();
assert.equal(requests.length, 2);
assert.match(requests[0].headers.common, /openUdid=fixture-terminal/);
assert.equal(requests[1].headers.token, 'fixture-token');
assert.equal(requests[1].headers.sign, 'fixture-signature');
assert.equal(signatures[0], api.signingParts('POST', '/v2/g/login', requests[0].headers.common, '', '', requests[0].body));
});
test('EvenHub buzzer RPC uses the host action on iOS and chunks and paces long sequences', async () => {
const sounds = loader()('app/ui/sound-effects.ts'), played = [];
const h = sessionHarness({ '../../ui/sound-effects': sounds }, bytes => played.push([...bytes]));
const steps = Array.from({ length: 49 }, () => ({ freq: 3000, ms: 1, duty: 25 }));
await h.session.dispatchExtension('playBuzzer', [steps]);
assert.equal(played.length, 2);
assert.deepEqual(played[0], [...sounds.buildSoundSequencePayload(steps.slice(0, 48))]);
assert.deepEqual(played[1], [...sounds.buildSoundSequencePayload(steps.slice(48))]);
await h.session.dispatchExtension('playBuzzer', [[null, { freq: 'bad', ms: 10 }]]);
assert.equal(played.length, 2);
h.session.close();
});
+10
View File
@@ -0,0 +1,10 @@
// Runs the production Core Text renderer on macOS, without UIKit or a simulator.
const { execFileSync } = require('node:child_process');
const { mkdtempSync } = require('node:fs');
const { tmpdir } = require('node:os');
const { join, resolve } = require('node:path');
const root = resolve(__dirname, '..'), dir = mkdtempSync(join(tmpdir(), 'faceclaw-font-'));
execFileSync('xcrun', ['clang', '-fobjc-arc', '-Wall', '-Wextra', '-framework', 'Foundation', '-framework', 'CoreText', '-framework', 'CoreGraphics',
'-I', 'App_Resources/iOS/src', 'tests/native/ios-font-test.m', 'App_Resources/iOS/src/FaceclawFontRenderer.m', '-o', join(dir, 'font-test')], { cwd: root, stdio: 'inherit' });
execFileSync(join(dir, 'font-test'), [join(root, 'app/fonts/ttf'), dir], { stdio: 'inherit' });
console.log(`Font test artifacts: ${dir}`);
+382
View File
@@ -0,0 +1,382 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
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 events = require('../.test-build/app/g2/events.js');
function load(file, modules, globals = {}) {
const context = { exports: {}, require: id => {
if (!(id in modules)) throw new Error(`Unstubbed import: ${id}`);
return modules[id];
}, ...globals };
vm.runInNewContext(ts.transpileModule(fs.readFileSync(path.join(__dirname, '..', file), 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, context);
return context.exports;
}
const planes = load('app/graphics/plane.ts', { './image': images });
const timings = load('app/native/frame-timings.ts', {});
function fixture() {
const observers = new Map(), phoneState = { protectedDataAvailable: true };
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, depth: 0 };
const clock = { Date: class extends Date { static now() { return now; } },
setTimeout: (fn, ms) => { tasks.set(++nextTask, { fn, at: now + ms }); return nextTask; },
clearTimeout: id => tasks.delete(id), setInterval: () => ++nextTask, clearInterval() {} };
const { GlanceHost } = load('app/g2/glance-host.ts', {
'../graphics/image': images, '../graphics/plane': planes,
'../graphics/glyph-wire': { prepareFrameDraws: () => null }, '../native/frame-timings': timings,
'../ui/shell/geometry': { minWindowTop: () => 48 },
'../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',
// 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); },
sleep: () => { screenOn = false; shellOptions.onScreenStateChanged(false); },
isScreenOn: () => screenOn, getWindows: () => [window], foregroundWindow: () => window,
setBatteryLevels() {}, underlayDim: () => 1, getFocus: () => 'app', hasOverlay: () => false,
describeInputTarget: () => 'test app',
paintScene: () => new Uint8Array([0, 0]), paintSurface: () => [{ image: new images.GrayImage(640, 480, 0), x: 0, y: 0 }],
receiveInput: async input => {
received.push(input);
if (input.type === 'display-wake' || !screenOn && input.type === 'double-click') shell.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(); }
depths = [];
async setSurfaceDepth(id, depth) { this.depths.push([id, depth]); this.compositor.setSurfaceDepth(id, depth); }
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 configureBrightness() {} 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,
showOnLongPress: () => settings.hold, showOnHeadTilt: () => settings.tilt,
tapTimeoutMs: () => settings.duration, depth: () => settings.depth,
createBoard: () => ({ start: () => boardStats.starts++, stop: () => boardStats.stops++,
paint: () => { boardStats.paints++; return new images.GrayImage(100, 80, 200); } }),
};
const inputMonitor = load("app/ui/input-monitor.ts", {});
const modules = {
"../ui/input-monitor": inputMonitor,
'../remote/service': { startRemoteInput(host) { remoteHost = host; } },
'../assistant/system-tools': { registerSystemTools() {} },
'../assistant/window-tools': { registerWindowTools() {} },
'../assistant/navigate-tools': { registerNavigateTools() {} },
'../assistant/roam-tools': { registerRoamTools() {} },
"../native/ios-navigation-sensors": {},
'../native/notification-icons.ios': { bindIosNotifications() {}, iosNotificationsChanged() {}, onIosNotificationPopup: () => () => {}, readActiveNotifications: () => [] },
'../native/notification-sources': { shouldShowNotificationOnGlasses: () => true },
"../native/compass.ios": { bindCompassSession() {}, receiveCompassEvent() {} },
'@nativescript/core': { File: { fromPath: () => ({ writeTextSync() {} }) },
knownFolders: { documents: () => ({ path: '/tmp' }) }, path },
'../native/ios-voice-input': { iosVoiceInput: { handleSessionEnded() {}, stopPhoneCapture() {} } },
'../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: () => ({ 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' },
'../apps/all-apps': { ALL_APPS: [{ appId: 'glanceboard', glanceboard: provider }] },
'../phone-ui/onboarding-state': { isWelcomeSoundPending: () => false },
'../ui/sound-effects': {},
'../ui/shell/worker-window': {}, '../ui/shell/in-process-window': {},
'../ui/dashboard-settings': { brightnessSetting: { get: () => 'auto' }, brightnessSettingToLevel: () => null, getBrightnessPreferences: () => ({ auto: true, level: 50, minimum: 2, maximum: 100, curve: '0:0,1000:100', fadeMs: 280 }), lockScreenEnabledSetting: { get: () => settings.lock }, onAnySettingChanged: fn => { settingsChanged = fn; return () => {}; }, previewColorSetting: { get: () => 'white' } },
'../native/phone-battery': { readPhoneBatteryState: () => ({ battery: 80, charging: false }) },
'../apps/ios-availability': { iosAppUnavailableReason: () => null },
'../graphics/glyph-wire': { prepareFrameDraws: () => null },
'../graphics/plane': planes, '../graphics/image': images,
'../ui/gestures': { makeInputEvent: event => event }, '../ui/layers': { noopLayerActions: {} },
'../apps/files/text-viewer': {},
'../ui/shell/shell': { shell, rawInputEventToInputEvent: event => ({
ringInput: event.ringInput, timestampMs: now,
type: event.kind === 'display-wake' ? 'display-wake'
: ({ 0: 'click', 1: 'scroll-up', 2: 'scroll-down', 3: 'double-click', 9: 'long-press',
10: 'long-press-release', 11: 'short-then-long-press' })[event.eventType] ?? 'unknown', source: 'ring',
}) },
'../ui/shell/geometry': { appViewportRect: () => ({ x: 0, y: 0, width: 640, height: 480 }) },
};
const { IosPreviewController } = load('app/g2/ios-preview-controller.ts', modules, {
...clock, console: { log() {}, warn() {}, error: text => errors.push(text) },
UIDevice: { currentDevice: {} }, UIApplication: { sharedApplication: phoneState },
UIApplicationProtectedDataWillBecomeUnavailable: 'lock', UIApplicationProtectedDataDidBecomeAvailable: 'unlock',
UIDeviceBatteryLevelDidChangeNotification: 'level', UIDeviceBatteryStateDidChangeNotification: 'state',
NSNotificationCenter: { defaultCenter: { addObserverForNameObjectQueueUsingBlock(name, _object, _queue, fn) { observers.set(name, fn); return name; }, removeObserver(name) { observers.delete(name); } } },
NSOperationQueue: { mainQueue: {} },
});
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) {
now += ms;
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); await drain(); assert.deepEqual(errors, []); }
async function hardware(type, source = 2, ringTick) {
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(); }
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 => {
assert.equal(pixels[48 * 640 + 270], 200);
assert.equal(pixels[0], 0, 'opaque Glanceboard hides the retained app and shell');
};
test('iOS sleep tap shows the shared board; repeated tap renews timeout and hides to black', async () => {
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);
await f.advance(2000); await f.hardware(0); await f.advance(1100);
assert.equal(f.controller.glance.isVisible(), true);
const offset = f.sent.length;
await f.advance(2000); await f.render();
assert.equal(f.controller.glance.isVisible(), false);
for (const pixels of f.sent.slice(offset)) assertBlank(pixels);
assert.equal(f.boardStats.starts, 1); assert.equal(f.boardStats.stops, 1);
});
test('Glanceboard applies its depth setting to its surface only when it changes', async () => {
const f = fixture(); await f.connect(); f.shell.sleep(); await f.render();
f.settings.depth = 32; await f.hardware(0); assertBoard(f.sent.at(-1));
await f.advance(3100); await f.render(); assert.equal(f.controller.glance.isVisible(), false);
await f.hardware(0); assert.equal(f.controller.glance.isVisible(), true);
await f.advance(3100); await f.render();
f.settings.depth = 0; await f.hardware(0);
assert.deepEqual(f.controller.display.depths, [['glance', 32], ['glance', 0]]);
});
test('iOS holds and tap-then-holds last until release, including with phone backgrounded', async () => {
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));
await f.advance(10000); assert.equal(f.controller.glance.isVisible(), true);
await f.hardware(10, 1); assertBlank(f.sent.at(-1));
}
assert.equal(f.previews.length, previews); assert.equal(f.received.length, 0);
});
test('double-tap and other shell wakes replace Glanceboard without waking it again', async () => {
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);
f.shell.sleep(); await f.hardware(0); f.shell.wake(); await f.render();
assert.equal(f.controller.glance.isVisible(), false); assert.equal(f.sent.at(-1)[0], 80);
await f.advance(5000); await f.render(); assert.equal(f.sent.at(-1)[0], 80);
});
test('head tilt uses Glanceboard when enabled and otherwise wakes the regular UI', async () => {
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.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);
assert.equal(f.boardStats.starts, 0); assertBlank(f.sent.at(-1));
f.settings.enabled = false; f.settings.tap = f.settings.hold = true;
for (const type of [0, 9, 11]) await f.hardware(type);
assert.equal(f.boardStats.starts, 0);
await f.hardware(3); assert.equal(f.shell.isScreenOn(), true);
});
test('phone preview gestures use Glanceboard; losing runtime cleans up holds and timers', async () => {
const f = fixture(); f.shell.sleep();
await f.phone('tap', 'mirror'); assertBoard(f.previews.at(-1).pixels);
await f.phone('double-tap', 'mirror'); assert.equal(f.shell.isScreenOn(), true);
f.shell.sleep(); await f.phone('long-press', 'ring');
await f.phone('long-press-release', 'ring'); assertBlank(f.previews.at(-1).pixels);
await f.phone('short-then-long-press', 'ring'); assert.equal(f.controller.glance.isVisible(), true);
f.controller.pause(); await f.render(); assert.equal(f.controller.glance.isVisible(), false);
f.controller.resume(); await f.render(); assertBlank(f.previews.at(-1).pixels);
assert.equal(f.boardStats.starts, f.boardStats.stops);
});
test('iOS lock hides apps and Glanceboard, blocks input, and stays locked when put back on', async () => {
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();
assert.equal(f.controller.glassesLocked, true);
assert.equal(f.controller.glance.isVisible(), false);
await f.hardware(3); // wake the lock screen
assert.ok(f.sent.at(-1).every(p => p === 123));
for (const type of [0, 1, 2, 9, 11]) await f.hardware(type);
f.wear(true); await f.render();
assert.equal(f.received.length, 0);
assert.ok(f.sent.at(-1).every(p => p === 123));
await f.hardware(3); assertBlank(f.sent.at(-1));
await f.hardware(12, 1); assert.ok(f.sent.at(-1).every(p => p === 123));
f.observers.get('unlock')(); await f.render();
assert.equal(f.controller.glassesLocked, false);
assert.equal(f.sent.at(-1)[0], 80);
await f.hardware(0); assert.equal(f.received.length, 1);
});
test('iOS removal before phone lock, setting changes, and observer lifetime', async () => {
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);
f.settings.lock = false; f.settingsChanged(); await f.render();
assert.equal(f.controller.glassesLocked, false);
f.settings.lock = true; f.settingsChanged(); await f.render();
assert.equal(f.controller.glassesLocked, true);
f.controller.pause(); assert.ok(f.observers.has('unlock'));
await f.controller.disconnect(); assert.equal(f.observers.has('unlock'), false);
f.controller.resume(); await f.render();
assert.equal(f.controller.glassesLocked, false);
assert.equal(f.observers.size, 4);
});
test('iOS wear notifications catch protected-data changes missed while suspended', async () => {
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();
assert.equal(f.controller.glassesLocked, true);
f.controller.pause(); f.phoneState.protectedDataAvailable = true;
f.controller.resume(); await f.render();
assert.equal(f.controller.glassesLocked, false);
});
test('iOS locked phone controls cannot dispatch mirror, voice, or keyboard input', async () => {
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();
assert.equal(await f.controller.prepareVoiceCapture(), false);
await f.controller.startVoiceCapture(); await f.controller.typeIntoApp();
assert.equal(f.received.length, 0);
assert.equal(f.controller.glassesLocked, true);
// Locked state also survives transport recovery until a phone unlock.
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.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);
// A filtered click cannot open a sleep-time board.
f.shell.sleep(); await f.hardware(0,2,1150);
assert.equal(f.controller.glance.isVisible(),false);
await f.hardware(0,2,1200); assert.equal(f.controller.glance.isVisible(),true);
// A duplicated double tap must not wake and immediately re-sleep a lock screen.
f.observers.get('lock')(); f.wear(false); await f.render();
f.shell.sleep(); await f.hardware(3,2,2000);
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.bridge.emitState('retrying');
f.bridge.emitState('connected');
await f.hardware(3,2,2051); assert.equal(f.shell.isScreenOn(),false);
});
test('keyboard sessions cannot deliver text after the glasses lock or phone leaves the foreground', () => {
const f = fixture();
let editor;
f.controller.onKeyboardInputChanged = session => { editor = session; };
const calls = [];
f.keyboardChanged({ targets: [{ id: 'app', label: 'Type into App' }],
setText: text => calls.push(['text', text]), send: () => calls.push(['send']),
sendTo: id => calls.push(['target', id]), discard: () => calls.push(['discard']) });
editor.setText('hello'); editor.sendTo('app');
assert.deepEqual(calls, [['text', 'hello'], ['target', 'app']]);
f.controller.glassesLocked = true;
editor.setText('locked'); editor.send(); editor.sendTo('app');
assert.equal(calls.length, 2);
f.controller.glassesLocked = false; f.controller.pause();
editor.setText('background'); editor.sendTo('app');
assert.equal(calls.length, 2);
editor.discard(); assert.deepEqual(calls.at(-1), ['discard']);
});
test('external input shares iOS dispatch, including hold release and phone-lock gating', async () => {
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');
await f.remoteHost.input('long-press', 'ring');
assert.deepEqual(f.received.map(e => [e.type, e.source]), [
['swipe-left', 'watch'], ['long-press', 'ring'], ['long-press-release', 'ring'],
]);
f.observers.get('lock')();
assert.equal(f.remoteHost.locked(), true);
await f.remoteHost.input('click', 'watch');
assert.equal(f.received.length, 3);
});
+11
View File
@@ -0,0 +1,11 @@
// Exercise the actual decoder with stock G2 packet framing and encoded PCM.
const { execFileSync } = require('node:child_process');
const { mkdtempSync, readdirSync } = require('node:fs');
const { tmpdir } = require('node:os');
const { join, resolve } = require('node:path');
const root = resolve(__dirname, '..'), dir = mkdtempSync(join(tmpdir(), 'faceclaw-lc3-'));
const src = 'App_Resources/iOS/src';
const files = readdirSync(join(root, src, 'lc3')).filter(f => f.endsWith('.c')).map(f => `${src}/lc3/${f}`);
execFileSync('xcrun', ['clang', '-fobjc-arc', '-O2', '-framework', 'Foundation', '-I', src, '-I', `${src}/lc3`,
'tests/native/ios-lc3-test.m', `${src}/FaceclawLc3Decoder.m`, ...files, '-o', join(dir, 'lc3-test')], { cwd: root, stdio: 'inherit' });
execFileSync(join(dir, 'lc3-test'), [], { stdio: 'inherit' });
+122
View File
@@ -0,0 +1,122 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { loader } = require('./helpers/load-typescript.cjs');
const flush = () => new Promise(resolve => setImmediate(resolve));
function nativeLocation() {
const instances = [];
const FaceclawLocationUpdates = { new() {
const value = { stopped: 0, startOnce() { this.once = true; }, startTracking(ms) { this.interval = ms; },
stop() { this.stopped++; this.eventHandler = null; } };
instances.push(value); return value;
} };
return { instances, load: loader({ FaceclawLocationUpdates }) };
}
const fix = { latitude: 37.7, longitude: -122.4, accuracyMeters: 8, bearingDeg: null, speedMps: null, timestampMs: 1234 };
test('iOS one-shot location resolves a fix, rejects native errors, and releases each provider', async () => {
const h = nativeLocation(), api = h.load('app/native/location.ios.ts');
const result = api.getCurrentLocation(), native = h.instances[0];
assert.equal(native.once, true);
native.eventHandler(JSON.stringify(fix));
assert.deepEqual({ ...await result }, fix); assert.ok(native.stopped);
const denied = api.getCurrentLocation();
h.instances[1].eventHandler(JSON.stringify({ error: 'Permission denied' }));
await assert.rejects(denied, /Permission denied/);
assert.ok(h.instances[1].stopped);
});
test('iOS tracking preserves unavailable course/speed and ignores callbacks after stop or restart', () => {
const h = nativeLocation(), api = h.load('app/native/location-tracker.ios.ts'), fixes = [], errors = [];
const tracker = new api.LocationTracker({ onLocation: fix => fixes.push(fix), onError: error => errors.push(error) });
tracker.start(1000); tracker.start(1000);
assert.equal(h.instances.length, 1); assert.equal(h.instances[0].interval, 1000);
const old = h.instances[0].eventHandler;
old(JSON.stringify(fix)); tracker.stop(); old(JSON.stringify(fix)); tracker.start(); old(JSON.stringify(fix));
assert.equal(fixes.length, 1); assert.equal(fixes[0].bearingDeg, null);
h.instances[1].eventHandler(JSON.stringify({ error: 'Location disabled' }));
assert.equal(tracker.isRunning(), false); assert.deepEqual(errors, ['Location disabled']);
});
test('Navigate worker routes sensor callbacks by stream id and receives true-north correction', () => {
const messages = [], fixes = [], headings = [];
const api = loader({ global: { postMessage: message => messages.push(message) } })('app/apps/navigate/navigation-sensors.ios.ts');
const tracker = new api.LocationTracker({ onLocation: fix => fixes.push(fix), onError() {} });
tracker.start(); const first = messages.at(-1).request.id;
tracker.stop(); tracker.start(); const second = messages.at(-1).request.id;
api.handleNavigationSensorEvent({ kind: 'location', id: first, location: fix });
api.handleNavigationSensorEvent({ kind: 'location', id: second, location: fix });
assert.equal(fixes.length, 1);
const off = api.addCompassListener(event => headings.push(event));
api.handleNavigationSensorEvent({ kind: 'compass', event: { command: 15, headingDegrees: 123 }, declination: 12 });
assert.equal(api.magneticDeclinationDegrees(37.7, -122.4), 12);
off(); api.handleNavigationSensorEvent({ kind: 'compass', event: {}, declination: null });
assert.equal(headings.length, 1); tracker.stop();
});
function sensorHost() {
const pending = [], trackers = [], holds = [], replies = [];
let compass;
class Tracker {
constructor(callbacks) { this.callbacks = callbacks; trackers.push(this); }
start() { this.started = true; }
stop() { this.stopped = true; }
}
const api = loader({}, {
'./location-tracker.ios': { LocationTracker: Tracker },
'./location-permissions.ios': { ensureFineLocationPermission: () => new Promise(resolve => pending.push(resolve)) },
'./compass.ios': { setCompassEnabled: (on, owner) => holds.push([on, owner]),
addCompassListener: fn => { compass = fn; return () => { compass = null; }; } },
'../apps/compass/declination': { refreshDeclination() {}, getDeclinationDegrees: () => 12.5 },
})('app/native/ios-navigation-sensors.ts');
return { host: new api.IosNavigationSensors(event => replies.push(event)), pending, trackers, holds, replies,
heading: () => compass?.({ command: 15, headingDegrees: 90 }) };
}
test('closing Navigate while precise permission is pending cannot start GPS later', async () => {
const h = sensorHost(); h.host.handle({ action: 'start', id: 1, intervalMs: 1000 });
h.host.stop(); h.pending.shift()(true); await flush();
assert.equal(h.trackers.length, 0); assert.equal(h.replies.length, 0);
h.host.handle({ action: 'start', id: 2, intervalMs: 1000 }); h.pending.shift()(false); await flush();
assert.equal(h.replies[0].kind, 'error'); assert.equal(h.replies[0].id, 2);
});
test('Navigate host releases GPS and compass together and ignores an old stream error', async () => {
const h = sensorHost(); h.host.handle({ action: 'start', id: 1, intervalMs: 1000 });
h.pending.shift()(true); await flush();
h.host.handle({ action: 'compass', enabled: true }); h.heading();
assert.equal(h.replies[0].declination, 12.5);
h.trackers[0].callbacks.onLocation(fix); assert.equal(h.replies[1].kind, 'location');
h.host.stop(); h.trackers[0].callbacks.onError('late error'); h.heading();
assert.equal(h.replies.length, 2); assert.equal(h.trackers[0].stopped, true);
assert.deepEqual(h.holds.at(-1), [false, 'worker:navigate']);
});
test('Weather uses the portable location provider and preserves NWS parsing', async () => {
const requests = [], timers = new Set(); let permission = true;
const period = { name: 'Today', temperature: 70, temperatureUnit: 'F', shortForecast: 'Sunny', windSpeed: '5 mph', windDirection: 'W' };
const api = loader({ setTimeout, clearTimeout, setInterval: fn => { timers.add(fn); return fn; }, clearInterval: fn => timers.delete(fn) }, {
'./location-permissions': { hasLocationPermission: () => permission },
'./location': { getCurrentLocation: async () => fix },
'../version': { USER_AGENT: 'test' },
'../util/http': { fetchWithUserAgent: async url => { requests.push(url); return { ok: true, json: async () =>
url.includes('/points/') ? { properties: { forecast: 'https://fixture/forecast', relativeLocation: { properties: { city: 'San Francisco', state: 'CA' } } } }
: { properties: { periods: [period] } } }; } },
})('app/native/weather.ts');
const bridge = new api.WeatherBridge(); bridge.start(); await bridge.refreshNow();
assert.equal(bridge.snapshot().phase, 'ready'); assert.equal(bridge.snapshot().current.temperatureF, 70);
assert.equal(bridge.snapshot().locationName, 'San Francisco, CA');
assert.match(requests[0], /37\.7000,-122\.4000/);
bridge.stop(); assert.equal(timers.size, 0);
permission = false; await bridge.refreshNow(); assert.equal(bridge.snapshot().phase, 'permission-required');
});
test('closing Weather during permission prompt cannot restart polling', async () => {
let granted, options, starts = 0, stops = 0;
const api = loader({}, {
'../../native/location-permissions': { hasLocationPermission: () => false, ensureLocationPermission: () => new Promise(resolve => { granted = resolve; }) },
'../../native/weather': { weatherBridge: { start() { starts++; }, stop() { stops++; }, onStateChange: () => () => {}, snapshot() {} } },
'./weather': { WeatherLayer: class {} },
'../../ui/shell/in-process-window': { YieldAtRootLayer: class {}, createInProcessWindow: opts => { options = opts; return { requestRender() {} }; } },
})('app/apps/weather/weather-app.ts');
api.createWeatherAppWindow({ onClosed() {} }); options.onClosed(); granted(true); await flush();
assert.equal(starts, 0); assert.equal(stops, 1);
});
+197
View File
@@ -0,0 +1,197 @@
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));
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) };
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/firmware/cfw-patches': { CFW_PATCH_SET: { outputSha256: 'custom', baseSha256: 'stock' } },
'./firmware-files.ios': { readFirmwareFile: () => new Uint8Array(16), firmwareSha256: () => hash },
'./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, instances, states, progress };
}
const listenerModule = load('app/native/kotlin-listener.ios.ts', {}, { NSObject: nsObject });
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, ['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, []); 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.calls.includes('close'), true);
});
test('backgrounding during iOS OTA stops the transfer and directs retry of both lenses', async () => {
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.instances[0].cancelled, true); assert.equal(f.progress.includes('right'), false); assert.equal(f.native.idleTimerDisabled, false);
});
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', {
'./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', () => {
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 (url) => {
const md5 = crypto.createHash('md5').update(base).digest('hex');
assert.equal(url, `https://cdn.evenreal.co/firmware/${md5}.bin`);
return { 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 stock = await builder.buildStockFirmware(); assert.equal(stock.sha256, patches.CFW_PATCH_SET.baseSha256);
const custom = await builder.buildCustomFirmware(); assert.equal(hash(fs.readFileSync(custom.path)), patches.CFW_PATCH_SET.outputSha256);
assert.equal(builder.hasExtractedEvenHubFonts(), true);
});
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', {
'./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 () => {
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);
});
+118
View File
@@ -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']);
});
+15
View File
@@ -0,0 +1,15 @@
// macOS integration test for the same NSURLSession transport compiled into iOS.
const { Server: WebSocketServer } = require('ws');
const { spawn, execFileSync } = require('node:child_process');
const { mkdtempSync, rmSync } = require('node:fs');
const { tmpdir } = require('node:os');
const { join, resolve } = require('node:path');
const root = resolve(__dirname, '..'), dir = mkdtempSync(join(tmpdir(), 'faceclaw-socket-'));
execFileSync('xcrun', ['clang', '-fobjc-arc', '-framework', 'Foundation', '-I', 'App_Resources/iOS/src',
'tests/native/ios-socket-test.m', 'App_Resources/iOS/src/FaceclawSocket.m', '-o', join(dir, 'socket-test')], { cwd: root, stdio: 'inherit' });
const server = new WebSocketServer({ host: '127.0.0.1', port: 0 });
server.on('connection', socket => socket.on('message', data => socket.send(data.toString(), () => socket.close(1000, 'done'))));
server.on('listening', () => {
const child = spawn(join(dir, 'socket-test'), [`ws://127.0.0.1:${server.address().port}`], { stdio: 'inherit' });
child.on('exit', code => { server.close(); rmSync(dir, { recursive: true, force: true }); process.exitCode = code ?? 1; });
});
+10
View File
@@ -0,0 +1,10 @@
const { execFileSync } = require('node:child_process');
const { mkdtempSync, rmSync } = require('node:fs');
const { tmpdir } = require('node:os');
const { join } = require('node:path');
const dir = mkdtempSync(join(tmpdir(), 'faceclaw-transcript-'));
try {
execFileSync('xcrun', ['clang', '-fobjc-arc', '-framework', 'Foundation', '-I', 'App_Resources/iOS/src',
'tests/native/ios-speech-transcript-test.m', 'App_Resources/iOS/src/FaceclawSpeechTranscript.m', '-o', join(dir, 'test')], { stdio: 'inherit' });
execFileSync(join(dir, 'test'), [], { stdio: 'inherit' });
} finally { rmSync(dir, { recursive: true, force: true }); }
+45
View File
@@ -0,0 +1,45 @@
const { execFileSync, spawn } = require('node:child_process');
const { mkdtempSync, rmSync } = require('node:fs');
const { tmpdir } = require('node:os');
const { join, resolve } = require('node:path');
const http = require('node:http');
const assert = require('node:assert/strict');
const root = resolve(__dirname, '..'), dir = mkdtempSync(join(tmpdir(), 'faceclaw-sse-'));
execFileSync('xcrun', ['clang', '-fobjc-arc', '-framework', 'Foundation', '-I', 'App_Resources/iOS/src',
'tests/native/ios-sse-test.m', 'App_Resources/iOS/src/FaceclawSseRequest.m', '-o', join(dir, 'sse-test')], { cwd: root, stdio: 'inherit' });
const server = http.createServer(async (request, response) => {
assert.notEqual(request.url, '/redirected', 'Credentials must not follow redirects');
assert.equal(request.headers.authorization, 'Bearer fixture-key');
assert.equal(request.headers['user-agent'], 'Faceclaw-test');
assert.equal(request.method, 'POST');
const chunks = []; for await (const chunk of request) chunks.push(chunk);
assert.deepEqual(JSON.parse(Buffer.concat(chunks)), { test: true });
if (request.url === '/error') { response.writeHead(401); response.end('{"error":{"type":"invalid_api_key"}}'); return; }
if (request.url === '/redirect') { response.writeHead(302, { Location: '/redirected' }); response.end(); return; }
response.writeHead(200, { 'Content-Type': 'text/event-stream', ...(request.url === '/disconnect' ? { 'Content-Length': '1000' } : {}) });
if (request.url === '/overflow') { response.end('x'.repeat(2 * 1024 * 1024 + 1)); return; }
if (request.url === '/disconnect') {
response.write('data: partial'); setTimeout(() => response.destroy(), 50); return;
}
if (request.url === '/cancel') {
response.write('data: first\n'); const timer = setTimeout(() => response.end('data: late\n'), 200);
response.on('close', () => clearTimeout(timer)); return;
}
// Split UTF-8 characters and CRLF boundaries across individual network writes.
const bytes = Buffer.from('\uFEFFdata: π 👓\r\n\r\n: ping\rdata: last');
let index = 0;
const timer = setInterval(() => {
if (index === bytes.length) { clearInterval(timer); response.end(); }
else response.write(bytes.subarray(index, ++index));
}, 2);
response.on('close', () => clearInterval(timer));
});
server.listen(0, '127.0.0.1', async () => {
try {
for (const mode of ['stream', 'error', 'redirect', 'cancel', 'overflow', 'disconnect']) await new Promise((resolve, reject) => {
const child = spawn(join(dir, 'sse-test'), [`http://127.0.0.1:${server.address().port}/${mode}`, mode], { stdio: 'inherit' });
child.on('error', reject); child.on('exit', code => code === 0 ? resolve() : reject(new Error(`${mode}: exit ${code}`)));
});
} catch (error) { console.error(error); process.exitCode = 1; }
finally { server.closeAllConnections(); server.close(); rmSync(dir, { recursive: true, force: true }); }
});
+29
View File
@@ -0,0 +1,29 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { loader } = require('./helpers/load-typescript.cjs');
function renderSource(svg) {
let source;
const { rasterizeSvg } = loader({}, { './ios-graphics': {
rasterizeSvg: (value, size) => { source = value; assert.equal(size, 32); return 'rendered'; },
} })('app/native/svg-rasterizer.ios.ts');
assert.equal(rasterizeSvg(svg, 32, 2), 'rendered');
return source;
}
test('EvenHub currentColor SVG fills are resolved before handing them to SVGKit', () => {
// Same document shape as the Snake and Weather store icons copied from the phone.
const source = renderSource('<svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" fill="currentColor"><path d="M4 1h10v2h-10Z"/></svg>');
assert.match(source, /fill="#ffffff"/);
assert.doesNotMatch(source, /currentColor/i);
assert.equal((source.match(/fill=/g) || []).length, 1);
assert.match(source, /viewBox="0 0 24 24"/);
});
test('currentColor strokes/styles resolve without filling open Lucide shapes', () => {
const source = renderSource('<svg fill="none" stroke="currentColor"><path style="stroke:currentColor" d="M2 2L8 8"/></svg>');
assert.match(source, /fill="none"/);
assert.match(source, /stroke="#ffffff"/);
assert.match(source, /style="stroke:#ffffff"/);
assert.match(source, /stroke-linecap="round"/);
});
+46
View File
@@ -0,0 +1,46 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const ts = require('typescript');
const { Menu } = require('../.test-build/app/ui/menu-core.js');
function load(file, context) {
const sandbox = { exports: {}, ...context };
vm.runInNewContext(ts.transpileModule(fs.readFileSync(file, 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 } }).outputText, sandbox);
return sandbox.exports;
}
test('iOS Type Into App submits UTF-8 terminal text and delays Enter at the byte boundary without Java', () => {
const sent = [];
const { G2MirrorClient } = load('app/native/g2mirror-client.ts', {
require: () => ({}), global: { isIOS: true }, NSUTF8StringEncoding: 4,
NSString: { stringWithString: text => ({
lengthOfBytesUsingEncoding: () => Buffer.byteLength(text, 'utf8'),
dataUsingEncoding: () => ({ base64EncodedStringWithOptions: () => Buffer.from(text).toString('base64') }),
}) },
});
const client = new G2MirrorClient({});
client.ws = { sendText: json => sent.push(JSON.parse(json)) };
client.handleMessage(JSON.stringify({ type: 'connect', command: 'test' }));
const { VoiceInputLayer } = load('app/ui/shell/voice-input.ts', {
require: id => id.includes('voice-control') ? { voiceControlBridge: { stop() {} } }
: id.includes('dashboard-settings') ? { anthropicApiKeySetting: { get: () => '' } }
: id.includes('input-dialog') ? { createInputDialogMenu: (items, selectedIndex) =>
new Menu({ items, selectedIndex, wrap: true, getHeight: () => 1, draw() {} }) } : {},
global: { isIOS: true },
});
for (const text of ['hello terminal', 'café π 🔋', 'line one\n第二行', '']) {
let closed = false;
const layer = new VoiceInputLayer({ actions: { requestRender() {} }, onClosed() {},
dismiss() { closed = true; layer.onRemoved(); }, sendTargets: [{ id: 'app', label: 'Type Into App', onSend: value => client.submitInput(value) }] });
layer.onTranscript({ text, isFinal: true });
const count = sent.length;
layer.menuRows()[0].onSelect();
assert.equal(closed, true);
if (!text) { assert.equal(sent.length, count); continue; }
const message = sent.at(-1);
assert.equal(message.type, 'input');
assert.equal(Buffer.from(message.data, 'base64').toString('utf8'), text + '\r');
assert.deepEqual(message.delays, [{ at: Buffer.byteLength(text), ms: 150 }]);
}
});
+138
View File
@@ -0,0 +1,138 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const ts = require('typescript');
function harness() {
const native = { startWithEndpointing(endpointing) { this.endpointing = endpointing; return ''; }, startPhoneWithEndpointing(endpointing) { this.endpointing = endpointing; this.phone = true; return this.error ?? ''; }, cancel() { this.cancels++; }, cancels: 0, finish() { this.finished = true; }, acceptPacket: p => audio.push(p) };
const audio = [], timers = new Map(), commands = [], text = [];
let authorization = 3, microphoneAuthorization = 3, microphoneRequests = 0, permissionRequests = 0, release;
const sandbox = { exports: {}, FaceclawSpeech: { new: () => native, authorizationStatus: () => authorization,
requestAuthorization: done => { permissionRequests++; done(3); },
microphoneAuthorizationStatus: () => microphoneAuthorization,
requestMicrophoneAuthorization: done => { microphoneRequests++; done(3); } },
setTimeout: fn => { timers.set(fn, fn); return fn; }, clearTimeout: fn => timers.delete(fn),
NSData: { dataWithBytesLength: (b, n) => Buffer.from(b, 0, n) }, interop: { handleof: b => b } };
vm.runInNewContext(ts.transpileModule(fs.readFileSync('app/native/voice-control.ios.ts', 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 } }).outputText, sandbox);
const bridge = new sandbox.exports.IosVoiceControlBridge();
bridge.onTranscript(event => text.push({ ...event }));
const session = { setMicrophone(enabled, fn) {
commands.push(enabled);
if (enabled) { this.packet = fn; return new Promise(resolve => { release = resolve; }); }
return Promise.resolve();
} };
return { bridge, native, session, audio, commands, text, timers, release: () => release(),
microphoneAuthorization: value => { microphoneAuthorization = value; }, microphoneRequests: () => microphoneRequests,
authorization: value => { authorization = value; }, permissionRequests: () => permissionRequests,
event: event => native.eventHandler(JSON.stringify(event)) };
}
test('iOS speech permission is requested only in foreground and denial stays actionable', async () => {
const h = harness(); h.authorization(0);
assert.equal(await h.bridge.prepare(false), false); assert.equal(h.permissionRequests(), 0);
assert.equal(await h.bridge.prepare(true), true); assert.equal(h.permissionRequests(), 1);
h.authorization(2); assert.equal(await h.bridge.prepare(true), false);
assert.match(h.bridge.statusText, /Settings/);
});
test('glasses speech sends PCM-source packets, replaces partials, and drains final text after manual release', async () => {
const h = harness(); const start = h.bridge.startGlassesCapture(h.session, () => {});
h.session.packet(new Uint8Array([1, 2, 3])); assert.deepEqual([...h.audio[0]], [1, 2, 3]);
h.release(); await start;
h.event({ kind: 'transcript', text: 'hello', final: false });
h.event({ kind: 'transcript', text: 'hello world', final: false });
h.bridge.stopPushToTalk(); assert.deepEqual(h.commands, [true, false]); assert.equal(h.native.finished, true);
h.session.packet(new Uint8Array([4])); assert.equal(h.audio.length, 1);
h.event({ kind: 'transcript', text: 'Hello world.', final: true });
h.event({ kind: 'ended', message: 'Ready to send' });
assert.deepEqual(h.text, [{ text: 'hello', isFinal: false }, { text: 'hello world', isFinal: false }, { text: 'Hello world.', isFinal: true }]);
h.event({ kind: 'transcript', text: 'stale', final: true }); assert.equal(h.text.length, 3);
assert.equal(h.timers.size, 0);
});
test('cancel and disconnect during enable cannot resurrect capture or leave its microphone listener active', async () => {
for (const stop of ['stop', 'handleSessionEnded']) {
const h = harness(); let ends = 0; h.bridge.onSpeechEnd(() => ends++);
const start = h.bridge.startGlassesCapture(h.session, () => {});
h.bridge[stop](); h.release(); await start;
h.session.packet(new Uint8Array([9]));
h.event({ kind: 'transcript', text: 'stale', final: true });
assert.deepEqual(h.commands, [true, false]); assert.equal(h.audio.length, 0); assert.equal(h.text.length, 0);
assert.equal(h.timers.size, 0); assert.equal(ends, stop === 'stop' ? 0 : 1);
}
});
test('missing microphone data ends the session and disables the mic with an actionable status', async () => {
const h = harness(); const start = h.bridge.startGlassesCapture(h.session, () => {}); h.release(); await start;
for (const fn of h.timers.values()) fn();
assert.deepEqual(h.commands, [true, false]); assert.match(h.bridge.statusText, /No microphone audio/);
});
test('hands-free endpointing releases the microphone and waits for the final transcript before completing', async () => {
const h = harness(); let ends = 0, completed = false;
h.bridge.onSpeechEnd(() => ends++);
const start = h.bridge.startGlassesCapture(h.session, () => {}, true); h.release(); await start;
assert.equal(h.native.endpointing, true);
h.event({ kind: 'transcript', text: 'Set a timer', final: false });
h.event({ kind: 'finishing' });
const completion = h.bridge.stopPushToTalk().then(() => { completed = true; });
await Promise.resolve();
assert.equal(completed, false); assert.equal(ends, 1);
assert.deepEqual(h.commands, [true, false]);
h.event({ kind: 'transcript', text: 'Set a timer for five minutes.', final: true });
h.event({ kind: 'ended' }); await completion;
assert.equal(completed, true);
assert.equal(h.text.at(-1).text, 'Set a timer for five minutes.');
const manual = h.bridge.startGlassesCapture(h.session, () => {}); h.release(); await manual;
assert.equal(h.native.endpointing, false);
const cancelled = h.bridge.stopPushToTalk(); h.bridge.stop(); await cancelled;
});
test('phone microphone permission is requested only for foreground preview capture', async () => {
const h = harness(); h.microphoneAuthorization(0);
assert.equal(await h.bridge.prepare(true), true);
assert.equal(h.microphoneRequests(), 0, 'glasses input does not need phone microphone permission');
assert.equal(await h.bridge.prepare(false, true), false);
assert.equal(h.microphoneRequests(), 0);
assert.equal(await h.bridge.prepare(true, true), true);
assert.equal(h.microphoneRequests(), 1);
h.microphoneAuthorization(2);
assert.equal(await h.bridge.prepare(true, true), false);
assert.match(h.bridge.statusText, /Microphone.*Settings/);
});
test('phone capture forwards endpointing and drains final text without touching Bluetooth', async () => {
const h = harness();
await h.bridge.startPhoneCapture(() => {}, true);
assert.equal(h.native.phone, true); assert.equal(h.native.endpointing, true);
h.bridge.handleSessionEnded();
h.event({ kind: 'transcript', text: 'First line\nSecond line', final: false });
assert.equal(h.text.length, 1, 'BLE state changes must not stop phone capture');
h.event({ kind: 'finishing' });
let finished = false;
const completion = h.bridge.stopPushToTalk().then(() => { finished = true; });
await Promise.resolve(); assert.equal(finished, false);
h.bridge.handleSessionEnded();
h.event({ kind: 'transcript', text: 'First line\nSecond line.', final: true });
h.event({ kind: 'ended' }); await completion;
assert.equal(h.text.at(-1).text, 'First line\nSecond line.');
assert.deepEqual(h.commands, []);
});
test('background cleanup stops phone capture but preserves glasses capture', async () => {
const h = harness(); let ends = 0; h.bridge.onSpeechEnd(() => ends++);
await h.bridge.startPhoneCapture(() => {});
h.bridge.stopPhoneCapture();
assert.equal(ends, 1);
h.event({ kind: 'transcript', text: 'stale', final: true }); assert.equal(h.text.length, 0);
const start = h.bridge.startGlassesCapture(h.session, () => {}); h.release(); await start;
h.bridge.stopPhoneCapture();
h.event({ kind: 'transcript', text: 'on glasses', final: false });
assert.equal(h.text.at(-1).text, 'on glasses');
h.bridge.stop();
});
test('phone microphone startup errors end capture with an actionable status', async () => {
const h = harness(); let ends = 0; h.bridge.onSpeechEnd(() => ends++);
h.native.error = 'No phone microphone is available.';
await h.bridge.startPhoneCapture(() => {});
assert.equal(ends, 1); assert.match(h.bridge.statusText, /No phone microphone/);
await h.bridge.stopPushToTalk();
});
+122
View File
@@ -0,0 +1,122 @@
const test = require("node:test");
const assert = require("node:assert/strict");
const { JavaDirectBuffer, copyToJavaByteBuffer } = require("../.test-build/app/native/java-direct-buffer.js");
/**
* A stand-in for java.nio.ByteBuffer.allocateDirect: fixed capacity, a
* position and a limit, and the relative bulk get() SurfaceCompositor uses.
* viewOf() plays ArrayBuffer.from: a view over the same memory, not a copy.
*/
function fakeBackend() {
const allocated = [];
return {
allocated,
allocateDirect(capacity) {
const memory = new Uint8Array(capacity);
const buffer = {
memory,
position: 0,
limitValue: capacity,
clear() {
this.position = 0;
this.limitValue = capacity;
return this;
},
limit(newLimit) {
if (newLimit > capacity) throw new Error("limit past capacity");
this.limitValue = newLimit;
if (this.position > newLimit) this.position = newLimit;
return this;
},
remaining() {
return this.limitValue - this.position;
},
get(dst, offset, length) {
if (length > this.remaining()) throw new Error("BufferUnderflowException");
dst.set(memory.subarray(this.position, this.position + length), offset);
this.position += length;
return this;
},
};
allocated.push(buffer);
return buffer;
},
viewOf(buffer) {
return buffer.memory;
},
};
}
/** Consume the way SurfaceCompositor.applyAndComposite does: exact remaining(), then drain. */
function consume(buffer, expectedBytes) {
assert.equal(buffer.remaining(), expectedBytes);
const out = new Uint8Array(expectedBytes);
buffer.get(out, 0, expectedBytes);
return out;
}
function frame(length, seed) {
const bytes = new Uint8Array(length);
for (let i = 0; i < length; i++) bytes[i] = (i * 31 + seed) & 0xff;
return bytes;
}
test("a loaded buffer exposes exactly the payload bytes to a Java-style reader", () => {
const backend = fakeBackend();
const pool = new JavaDirectBuffer(640 * 480, backend);
const shell = frame(640 * 480, 1);
assert.deepEqual(consume(pool.load(shell), shell.length), shell);
});
test("successive frames reuse one Java buffer, including smaller ones", () => {
const backend = fakeBackend();
const pool = new JavaDirectBuffer(640 * 480, backend);
for (let i = 0; i < 50; i++) {
const size = i % 2 === 0 ? 640 * 480 : 640 * 452;
const bytes = frame(size, i);
assert.deepEqual(consume(pool.load(bytes), size), bytes);
}
assert.equal(pool.allocations, 1);
assert.equal(backend.allocated.length, 1);
});
test("a payload larger than the buffer allocates once more, then reuses", () => {
const backend = fakeBackend();
const pool = new JavaDirectBuffer(0, backend);
consume(pool.load(frame(10, 0)), 10);
consume(pool.load(frame(9000, 0)), 9000);
consume(pool.load(frame(8000, 0)), 8000);
consume(pool.load(frame(9000, 0)), 9000);
assert.equal(pool.allocations, 2);
});
test("loadOptional passes null through and loads a draw list", () => {
const backend = fakeBackend();
const pool = new JavaDirectBuffer(0, backend);
assert.equal(pool.loadOptional(null), null);
assert.equal(pool.loadOptional(undefined), null);
assert.equal(pool.loadOptional(new ArrayBuffer(0)), null);
assert.equal(backend.allocated.length, 0);
const draws = frame(36, 7);
assert.deepEqual(consume(pool.loadOptional(draws.buffer), 36), draws);
});
test("a view on a larger buffer contributes only its own bytes", () => {
const backend = fakeBackend();
const pool = new JavaDirectBuffer(0, backend);
const whole = frame(100, 3);
const view = whole.subarray(10, 30);
assert.deepEqual(consume(pool.load(view), 20), whole.slice(10, 30));
});
test("copyToJavaByteBuffer gives each crossing its own exact-length buffer", () => {
const backend = fakeBackend();
const whole = frame(100, 5);
const first = copyToJavaByteBuffer(whole.subarray(10, 30), backend);
const second = copyToJavaByteBuffer(frame(7, 1), backend);
assert.notEqual(first, second);
assert.deepEqual(consume(first, 20), whole.slice(10, 30));
assert.deepEqual(consume(second, 7), frame(7, 1));
assert.equal(consume(copyToJavaByteBuffer(new Uint8Array(0), backend), 0).length, 0);
});
+32
View File
@@ -0,0 +1,32 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { loader } = require('./helpers/load-typescript.cjs');
function fixture() {
class Observable { get(key) { return this[key]; } notifyPropertyChange() {} }
const { KeyboardInputViewModel } = loader({}, { '@nativescript/core': { Observable } })('app/phone-ui/keyboard-input-view-model.ts');
const model = new KeyboardInputViewModel(), sent = [], text = [];
const session = { targets: [{ id: 'assistant', label: 'Send to Assistant' }, { id: 'app', label: 'Type Into App' }],
setText: value => text.push(value), sendTo: id => sent.push(id), discard: () => model.setSession(null) };
model.setSession(session);
return { model, session, sent, text };
}
test('multiline keyboard editor routes Agent and App buttons to distinct shell destinations', () => {
const h = fixture();
assert.equal(h.model.keyboardInputPrimaryTargetLabel, 'Send to Agent');
assert.equal(h.model.keyboardInputSecondaryTargetLabel, 'Type into App');
h.model.onKeyboardInputTextChange({ object: { text: 'First line\nSecond line' } });
h.model.onKeyboardInputPrimarySendTap();
h.model.onKeyboardInputSecondarySendTap();
assert.deepEqual(h.sent, ['assistant', 'app']);
assert.equal(h.text.at(-1), 'First line\nSecond line');
});
test('discard and shell-side closure reset the editor; unsupported destinations stay hidden', () => {
const h = fixture();
h.model.keyboardInputText = 'draft'; h.model.onKeyboardInputDiscardTap();
assert.equal(h.model.keyboardInputText, '');
assert.equal(h.model.keyboardInputVisibility, 'collapse');
h.model.setSession({ ...h.session, targets: [{ id: 'assistant', label: 'Send' }] });
assert.equal(h.model.keyboardInputPrimaryTargetLabel, 'Send to Agent');
assert.equal(h.model.keyboardInputSecondaryTargetVisibility, 'collapse');
h.model.onKeyboardInputSecondarySendTap(); assert.deepEqual(h.sent, []);
});
+43
View File
@@ -0,0 +1,43 @@
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 { checkAndroidRuntime } = require('../scripts/kotlin-build.cjs');
test('Android preparation rejects a stale metadata generator but allows fresh and matching platforms', () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'faceclaw-kotlin-build-'));
try {
const installed = path.join(root, 'node_modules/@nativescript/android/framework/build-tools/android-metadata-generator.jar');
const generated = path.join(root, 'platforms/android/build-tools/android-metadata-generator.jar');
fs.mkdirSync(path.dirname(installed), { recursive: true });
fs.writeFileSync(installed, 'current metadata generator');
assert.doesNotThrow(() => checkAndroidRuntime(root));
fs.mkdirSync(path.dirname(generated), { recursive: true });
fs.writeFileSync(generated, 'old metadata generator');
assert.throws(() => checkAndroidRuntime(root), /ns platform clean android/);
fs.copyFileSync(installed, generated);
assert.doesNotThrow(() => checkAndroidRuntime(root));
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
test('every remaining Java source has an explicit Android boundary and every migration has one replacement', () => {
const root = path.resolve(__dirname, '..');
const java = path.join(root, 'App_Resources/Android/src/main/java');
const list = directory => fs.readdirSync(directory, { withFileTypes: true }).flatMap(entry => {
const file = path.join(directory, entry.name);
return entry.isDirectory() ? list(file) : file.endsWith('.java') ? [path.relative(java, file)] : [];
});
const boundaries = require('../native/kotlin/android-java-boundaries.json');
const retained = boundaries.flatMap(group => { assert.ok(group.reason.length > 20); return group.files; });
assert.deepEqual(list(java).sort(), retained.sort());
assert.equal(new Set(retained).size, retained.length);
const migrated = require('../native/kotlin/migrated-java-sources.json');
assert.equal(new Set(migrated.map(entry => entry.java)).size, migrated.length);
for (const entry of migrated) {
assert.equal(fs.existsSync(path.join(java, entry.java)), false, entry.java);
assert.ok(fs.existsSync(path.join(root, entry.kotlin)), entry.kotlin);
}
});
+40
View File
@@ -0,0 +1,40 @@
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
plugins {
kotlin("multiplatform") version "2.4.20"
id("com.android.kotlin.multiplatform.library") version "8.13.2"
}
// Compile the production sources without building NativeScript or touching BLE.
kotlin {
android {
namespace = "com.faceclaw.protocoltests"
compileSdk = 35
minSdk = 24
withJava()
compilerOptions { jvmTarget.set(JvmTarget.JVM_17) }
withHostTestBuilder {}.configure {}
}
iosArm64()
iosSimulatorArm64()
sourceSets {
commonMain { kotlin.srcDir("../../native/kotlin/shared/src/commonMain/kotlin") }
androidMain { kotlin.srcDir("../../native/kotlin/shared/src/androidMain/kotlin") }
iosMain { kotlin.srcDir("../../native/kotlin/shared/src/iosMain/kotlin") }
commonTest.dependencies { implementation(kotlin("test")) }
}
}
// The font is already shipped in the app; avoid copying megabytes into test fixtures.
val generateFixturePaths = tasks.register("generateFixturePaths") {
val output = layout.buildDirectory.file("generated/fixtures/com/faceclaw/app/FixturePaths.kt")
outputs.dir(layout.buildDirectory.dir("generated/fixtures"))
doLast {
val font = file("../../app/fonts/source-han-sans/SourceHanSansSC-Light-20.lvgl.bin").canonicalPath
output.get().asFile.apply {
parentFile.mkdirs()
writeText("package com.faceclaw.app\ninternal const val TEST_FONT_PATH = \"${font.replace("\\", "\\\\").replace("\"", "\\\"")}\"\n")
}
}
}
kotlin.sourceSets.commonTest { kotlin.srcDir(generateFixturePaths) }
+3
View File
@@ -0,0 +1,3 @@
pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }
dependencyResolutionManagement { repositories { google(); mavenCentral() } }
rootProject.name = "FaceclawProtocolTests"
@@ -0,0 +1,20 @@
package com.faceclaw.app;
import java.util.*;
/** Android's Java communicator and iOS share the same resource API and wire commands. */
public class ResourceCacheProtocolTest {
public static void main(String[] args) {
ResourceCacheState cache = new ResourceCacheState();
CachedResource image = new CachedResource(new byte[]{1, 1, 31});
assert cache.prepare(Collections.singletonList(image))[0] == 0;
List<byte[]> commands = cache.drainCommands(3600);
assert commands.size() == 2 && commands.get(0)[0] == 22;
assert Arrays.equals(commands.get(1), new byte[]{21,1,0,0,0,3,0,0,0,0,0,3,0,1,1,31});
assert cache.prepare(Collections.singletonList(image))[0] == 0;
assert cache.drainCommands(3600).isEmpty();
cache.reset();
assert cache.prepare(Collections.singletonList(image))[0] == 0;
assert cache.drainCommands(3600).get(0)[0] == 22;
}
}
@@ -0,0 +1,530 @@
package com.faceclaw.app;
import java.util.Arrays;
import java.util.List;
/**
* Standalone self-test for {@link RingProtocol}. No Android APIs and no
* hardware: every byte-manipulation path is exercised against either frames
* copied from the reference capture or synthetic bodies built from the spec's
* field layout.
*
* <p>Run through JavaCompatibilityTest ({@code npm run test:kotlin}), which
* also checks that the Kotlin port keeps the Java-facing API the TypeScript
* health ingest reads.
*
* <p>The captured frames reproduced below are requests and page-ACKs only.
* Those carry a nonce, a command id and a sequence number — no biometric
* values. No captured DATA page appears here, deliberately.
*/
public final class RingProtocolSelfTest {
private static int checks;
private static int failures;
public static void main(String[] args) {
testCrcAndRequestRoundTrip();
testFiveHealthRequests();
testPageAckAgainstCapture();
testParseRejectsGarbage();
testFragmentReassembly();
testHourlyDecode();
testStepsDecode();
testSleepDecodeAndIdentities();
testDailyWireLayouts();
testDeviceStatus();
System.out.println();
System.out.println(failures == 0
? "PASS: all " + checks + " checks"
: "FAIL: " + failures + " of " + checks + " checks");
if (failures != 0) {
throw new AssertionError(failures + " of " + checks + " ring protocol checks failed");
}
}
// ------------------------------------------------------------------
/**
* Rebuild captured request pkt 9166 from its decoded fields alone. If the
* CRC-32C parameters or the header layout are wrong by even one bit this
* cannot reproduce the captured bytes.
*/
private static void testCrcAndRequestRoundTrip() {
section("CRC + request round-trip (captured pkt 9166)");
byte[] built = RingProtocol.buildRequest(
RingProtocol.CHAN_HEALTH,
RingProtocol.CMD_HI_HEART_RATE,
RingProtocol.CMD_LO_HEALTH,
0x06,
0x08ca);
expectHex("pkt 9166", "00db64265a64026406000001010c00ca08", built);
RingProtocol.Frame frame = RingProtocol.parse(built);
expect("parses back", frame != null && frame.crcOk);
expect("chan", frame.chan == RingProtocol.CHAN_HEALTH);
expect("kind REQ", frame.kind == RingProtocol.KIND_REQ);
expect("seq", frame.seq == 0x06);
expect("cmd 01:01", frame.cmdHi == 0x01 && frame.cmdLo == 0x01);
expect("payload is the 2-byte nonce", frame.payload.length == 2);
// A single flipped payload bit must invalidate the CRC.
byte[] tampered = built.clone();
tampered[15] ^= 0x01;
RingProtocol.Frame bad = RingProtocol.parse(tampered);
expect("tampered frame fails CRC", bad != null && !bad.crcOk);
}
/** The five ready-to-send health requests, seq=1, nonce=0. */
private static void testFiveHealthRequests() {
section("five health requests (spec section 9)");
String[][] expected = {
{"heart rate", "00450fe48f64026401000001010c000000"},
{"SpO2", "000d3fd33364026401000002010c000000"},
{"HRV", "00dc30615564026401000004010c000000"},
{"steps", "00e4208c3e64026401000005010c000000"},
{"sleep", "00ac10bb8264026401000006010c000000"},
};
int[] commands = {
RingProtocol.CMD_HI_HEART_RATE,
RingProtocol.CMD_HI_SPO2,
RingProtocol.CMD_HI_HRV,
RingProtocol.CMD_HI_STEPS,
RingProtocol.CMD_HI_SLEEP,
};
for (int i = 0; i < commands.length; i++) {
byte[] built = RingProtocol.buildHealthRequest(commands[i], 0x01, 0x0000);
expectHex(expected[i][0], expected[i][1], built);
}
// The convenience burst builder must produce the same first frame and
// then advance the shared sequence counter by one per frame.
List<byte[]> burst = RingProtocol.buildHealthRequestBurst(0x01, 0x0000);
expect("burst has five frames", burst.size() == 5);
expectHex("burst[0] == heart rate", expected[0][1], burst.get(0));
boolean seqRuns = true;
for (int i = 0; i < burst.size(); i++) {
RingProtocol.Frame f = RingProtocol.parse(burst.get(i));
if (f == null || !f.crcOk || f.seq != 0x01 + i) {
seqRuns = false;
}
}
expect("burst sequence numbers run 1..5 and all CRCs are valid", seqRuns);
}
/**
* Rebuild real captured page-ACKs. This is what pins down the two things
* the prose spec got wrong: the payload begins with the usual nonce (so the
* echoed page seq is at offset 6, not 4), and the frame's own SEQ is the
* phone's shared counter rather than the echoed page seq.
*/
private static void testPageAckAgainstCapture() {
section("page ACK 00:7E rebuilt from captured frames");
// seq, nonce, ackedCmdHi, ackedCmdLo, pageSeq, expected hex
Object[][] cases = {
{0x0d, 0x5f49, 0x01, 0x01, 0x03, "005e55d80b6401640d0001007e1600495f02010100030000000000"},
{0x13, 0xdc10, 0x04, 0x01, 0x07, "00a2bae3c4640164130001007e160010dc02040100070000000000"},
{0x17, 0x86e9, 0x02, 0x01, 0x09, "002c006c61640164170001007e1600e98602020100090000000000"},
{0x23, 0x634c, 0x06, 0x01, 0x13, "00b96c8823640164230001007e16004c6302060100130000000000"},
{0x25, 0x46f2, 0x05, 0x01, 0x14, "00474ee8b8640164250001007e1600f24602050100140000000000"},
{0x14, 0x7bc3, 0x05, 0x01, 0x3b, "00f3a5a917640164140001007e1600c37b020501003b0000000000"},
};
for (Object[] c : cases) {
byte[] built = RingProtocol.buildPageAck(
(Integer) c[0], (Integer) c[1], (Integer) c[2], (Integer) c[3], (Integer) c[4]);
expectHex("ack for cmd " + hex2((Integer) c[2]) + ":" + hex2((Integer) c[3])
+ " page seq " + hex2((Integer) c[4]), (String) c[5], built);
}
RingProtocol.Frame f = RingProtocol.parse(RingProtocol.buildPageAck(0x0d, 0x5f49, 0x01, 0x01, 0x03));
expect("ack rides the DEVICE channel", f.chan == RingProtocol.CHAN_DEVICE);
expect("ack kind is ACK", f.kind == RingProtocol.KIND_ACK);
expect("ack command is 00:7e", f.cmdHi == 0x00 && f.cmdLo == 0x7e);
expect("ack header seq differs from echoed page seq", f.seq != (f.payload[6] & 0xff));
expect("echoed page seq is at payload[6]", (f.payload[6] & 0xff) == 0x03);
}
private static void testParseRejectsGarbage() {
section("parser rejects non-frames");
expect("null", RingProtocol.parse(null) == null);
expect("too short", RingProtocol.parse(new byte[8]) == null);
expect("no magic", RingProtocol.parse(new byte[20]) == null);
// A 3-byte ring gesture frame must not look like a header.
expect("gesture frame is not a header",
!RingProtocol.looksLikeHeader(new byte[] {(byte) 0xff, 0x04, 0x01}));
// A frame whose PLEN disagrees with its actual length is rejected.
byte[] frame = RingProtocol.buildHealthRequest(RingProtocol.CMD_HI_HRV, 1, 0);
byte[] truncated = Arrays.copyOf(frame, frame.length - 1);
expect("length/PLEN mismatch rejected", RingProtocol.parse(truncated) == null);
}
/**
* Fragmentation, reproducing the shape the capture actually shows: an
* oversized frame split into a 244-byte FLAG=0x01 head and a headerless
* continuation, with an unrelated complete frame arriving in between.
*/
private static void testFragmentReassembly() {
section("fragment reassembly");
// Build a 252-byte steps-shaped frame: 15 header + 237 payload.
byte[] payload = new byte[237];
for (int i = 0; i < payload.length; i++) {
payload[i] = (byte) (i * 7 + 3);
}
byte[] whole = RingProtocol.buildFrame(
RingProtocol.CHAN_HEALTH, RingProtocol.KIND_DATA,
RingProtocol.CMD_HI_STEPS, RingProtocol.CMD_LO_HEALTH, 0x15, payload);
expect("test frame is 252 bytes", whole.length == 252);
byte[] head = Arrays.copyOf(whole, 244);
head[0] = (byte) RingProtocol.FLAG_FRAGMENTED;
byte[] continuation = new byte[RingProtocol.CONTINUATION_PREFIX_LEN + (whole.length - 244)];
System.arraycopy(whole, 244, continuation, RingProtocol.CONTINUATION_PREFIX_LEN, whole.length - 244);
expect("continuation is 5 + remaining bytes", continuation.length == 13);
byte[] interleaved = RingProtocol.buildFrame(
RingProtocol.CHAN_DEVICE, RingProtocol.KIND_DATA, 0x00, 0x01, 0x16, new byte[9]);
RingProtocol.Reassembler reassembler = new RingProtocol.Reassembler();
RingProtocol.Intake first = reassembler.accept(head);
expect("head consumed", first.consumed && first.frame == null);
expect("fragment outstanding", reassembler.hasPending());
RingProtocol.Intake middle = reassembler.accept(interleaved);
expect("interleaved frame still parses while a fragment is pending",
middle.consumed && middle.frame != null && middle.frame.crcOk);
expect("fragment survives the interleaved frame", reassembler.hasPending());
RingProtocol.Intake done = reassembler.accept(continuation);
expect("continuation completes the frame", done.consumed && done.frame != null);
expect("reassembled frame passes CRC", done.frame.crcOk);
expect("reassembled bytes are exact",
Arrays.equals(done.frame.raw, headJoined(head, whole)));
expect("no fragment left outstanding", !reassembler.hasPending());
expect("reassembled payload is intact", Arrays.equals(done.frame.payload, payload));
// Non-protocol traffic must pass straight through untouched.
RingProtocol.Intake gesture = reassembler.accept(new byte[] {(byte) 0xff, 0x04, 0x01});
expect("gesture frame is not consumed", !gesture.consumed);
}
private static byte[] headJoined(byte[] head, byte[] whole) {
byte[] expected = whole.clone();
expected[0] = head[0];
return expected;
}
// ------------------------------------------------------------------
// Synthetic record bodies, built directly from the spec's field layout.
// ------------------------------------------------------------------
private static void testHourlyDecode() {
section("hourly decode (heart rate W=1, HRV W=2, backlog page)");
// Anchored heart-rate page, W=1, three groups.
long anchor = 1788926400L; // 2026-09-09 00:00 local, the capture's anchor
int[][] groups = {{0, 61, 88, 55}, {1, 58, 71, 52}, {2, 63, 90, 57}};
byte[] body = hourlyBody(3, anchor, 12345L, 64, 1, groups);
RingProtocol.Frame frame = dataFrame(RingProtocol.CMD_HI_HEART_RATE, body);
RingProtocol.HourlyRecord hr = RingProtocol.decodeHourly(frame, 0L);
expect("HR decodes", hr != null);
expect("HR width resolved to 1", hr.valueWidth == 1);
expect("HR group count", hr.groups.length == 3);
expect("HR anchor", hr.anchorUnixSeconds == anchor);
expect("HR not backlog", !hr.isBacklog());
expect("HR current", hr.current == 64);
boolean values = true;
for (int i = 0; i < groups.length; i++) {
RingProtocol.HourlyGroup g = hr.groups[i];
values &= g.hourIndex == groups[i][0] && g.avg == groups[i][1]
&& g.max == groups[i][2] && g.min == groups[i][3]
&& g.unixSeconds == anchor + groups[i][0] * 3600L;
}
expect("HR values and hour timestamps round-trip", values);
// HRV uses two-byte values; the width must be resolved, not assumed.
int[][] hrvGroups = {{8, 300, 420, 210}, {9, 275, 380, 190}, {10, 512, 640, 400}};
byte[] hrvBody = hourlyBody(3, anchor, 22222L, 333, 2, hrvGroups);
RingProtocol.HourlyRecord hrv =
RingProtocol.decodeHourly(dataFrame(RingProtocol.CMD_HI_HRV, hrvBody), 0L);
expect("HRV decodes", hrv != null);
expect("HRV width resolved to 2", hrv.valueWidth == 2);
expect("HRV current", hrv.current == 333);
expect("HRV holds values above 255", hrv.groups[2].max == 640);
// Backlog page: anchor absent. The hour index must survive; the absolute
// time must NOT be invented.
byte[] backlogBody = hourlyBody(3, RingProtocol.UNKNOWN_TIME, 77777L, 60, 1, groups);
RingProtocol.HourlyRecord backlog =
RingProtocol.decodeHourly(dataFrame(RingProtocol.CMD_HI_HEART_RATE, backlogBody), 0L);
expect("backlog decodes", backlog != null);
expect("backlog flagged", backlog.isBacklog());
expect("backlog anchor unknown", backlog.anchorUnixSeconds == RingProtocol.UNKNOWN_TIME);
boolean noInventedTime = true;
for (RingProtocol.HourlyGroup g : backlog.groups) {
noInventedTime &= g.unixSeconds == RingProtocol.UNKNOWN_TIME;
}
expect("backlog groups carry no invented absolute time", noInventedTime);
expect("backlog keeps raw hour indices",
backlog.groups[0].hourIndex == 0 && backlog.groups[2].hourIndex == 2);
expect("backlog still decodes values", backlog.groups[1].avg == 58);
}
private static void testStepsDecode() {
section("steps decode");
long anchor = 1788926400L;
int[][] buckets = {{0, 120, 4, 16}, {3, 0, 0, 12}, {130, 45, 2, 14}};
byte[] body = stepsBody(anchor, buckets);
RingProtocol.StepsRecord steps =
RingProtocol.decodeSteps(dataFrame(RingProtocol.CMD_HI_STEPS, body), 0L);
expect("steps decode", steps != null);
expect("bucket count", steps.buckets.length == 3);
expect("total steps", steps.totalSteps() == 165);
expect("raw index preserved, including the 130+ jump",
steps.buckets[2].index == 130);
expect("v2/v3 kept as unconfirmed calorie-shaped fields",
steps.buckets[0].calorieLike2 == 4 && steps.buckets[0].calorieLike3 == 16);
expect("steps anchor", steps.anchorUnixSeconds == anchor);
// Length must be exact: a truncated body is a decode failure, not a guess.
byte[] shortBody = Arrays.copyOf(body, body.length - 1);
expect("truncated steps body rejected",
RingProtocol.decodeSteps(dataFrame(RingProtocol.CMD_HI_STEPS, shortBody), 0L) == null);
}
private static void testSleepDecodeAndIdentities() {
section("sleep decode + the spec's arithmetic identities");
// segments: (stage, halfMinutes). Stage sums: 0->10, 1->20, 2->70, 3->25.
int[][] segments = {{0, 4}, {1, 20}, {2, 40}, {0, 6}, {2, 30}, {3, 25}};
int totalHalfMinutes = 125;
int seconds = totalHalfMinutes * 30; // 3750
int wake = 10 * 30; // 300, stage 0
int rem = 20 * 30; // 600, stage 1
int light = 70 * 30; // 2100, stage 2
int deep = 25 * 30; // 750, stage 3
int total = seconds - wake; // 3450
long start = 100000L;
long end = start + seconds;
byte[] body = sleepBody(1, start, end, total, wake, rem, light, deep, segments);
RingProtocol.SleepRecord sleep =
RingProtocol.decodeSleep(dataFrame(RingProtocol.CMD_HI_SLEEP, body), 0L);
expect("sleep decodes", sleep != null);
expect("real record", sleep.isRealRecord());
expect("segment count", sleep.segments.length == segments.length);
expect("segment stages and durations round-trip",
sleep.segments[2].stage == 2 && sleep.segments[2].halfMinutes == 40);
expect("identity: sum(half_minutes) x 30 == total_time + wake_time",
sleep.totalHalfMinutes() * 30 == sleep.totalTime + sleep.wakeTime);
expect("identity: sum(half_minutes) x 30 == end_ts - start_ts",
sleep.totalHalfMinutes() * 30 == (int) (sleep.endTs - sleep.startTs));
expect("identity: per-stage sums match the four stage totals",
sleep.halfMinutesForStage(0) * 30 == wake
&& sleep.halfMinutesForStage(1) * 30 == rem
&& sleep.halfMinutesForStage(2) * 30 == light
&& sleep.halfMinutesForStage(3) * 30 == deep);
expect("identitiesHold() agrees", sleep.identitiesHold());
expect("uncracked 6-byte field stored raw, not interpreted",
sleep.unknownPrefix.length == 6);
expect("relative timestamps kept as sent",
sleep.startTs == start && sleep.endTs == end);
// The empty end-of-list marker must decode without inventing a session.
byte[] marker = new byte[] {0x11, 0x22, 0x02};
RingProtocol.SleepRecord empty =
RingProtocol.decodeSleep(dataFrame(RingProtocol.CMD_HI_SLEEP, marker), 0L);
expect("RECSTATE=2 marker decodes", empty != null && !empty.isRealRecord());
expect("marker has no segments", empty.segments.length == 0);
// A declared segment count that does not fill the body is a parse failure.
byte[] broken = body.clone();
broken[32] = (byte) (segments.length + 1);
expect("segment-count mismatch rejected",
RingProtocol.decodeSleep(dataFrame(RingProtocol.CMD_HI_SLEEP, broken), 0L) == null);
}
// ------------------------------------------------------------------
private static void testDailyWireLayouts() {
section("footer-free daily layouts and timezone anchors");
long anchor = 1789700400L;
byte[] hr = hourlyBody(2, anchor, anchor + 3600, 70, 1,
new int[][] {{0, 70, 80, 60}, {1, 72, 82, 62}});
expect("two-hour HR frame is 37 bytes", dataFrame(1, hr).raw.length == 37);
for (int timezone : new int[] {-420, -240, 0, 330, 840}) {
putLe(hr, 3, timezone, 2);
RingProtocol.HourlyRecord decoded = RingProtocol.decodeHourly(dataFrame(1, hr), 0);
expect("anchor works at timezone " + timezone,
decoded != null && decoded.anchorUnixSeconds == anchor && decoded.groups.length == 2);
}
byte[] spo2 = hourlyBody(1, anchor, anchor, 98, 1, new int[][] {{0, 98, 99, 97}});
expect("one-hour SpO2 frame is 33 bytes", dataFrame(2, spo2).raw.length == 33);
expect("SpO2 decodes without footer", RingProtocol.decodeHourly(dataFrame(2, spo2), 0).groups[0].avg == 98);
byte[] hrv = hourlyBody(1, anchor, anchor, 51, 2, new int[][] {{3, 51, 300, 40}});
RingProtocol.HourlyRecord variability = RingProtocol.decodeHourly(dataFrame(4, hrv), 0);
expect("one-hour HRV retains two-byte values", variability.valueWidth == 2
&& variability.groups[0].hourIndex == 3 && variability.groups[0].max == 300);
// Offline daily pages omit the five-byte latest-reading prefix.
byte[] offline = new byte[9 + 8];
System.arraycopy(hr, 0, offline, 0, 9);
System.arraycopy(hr, 14, offline, 9, 8);
RingProtocol.HourlyRecord past = RingProtocol.decodeHourly(dataFrame(1, offline), 0);
expect("daily page without latest sample decodes", past != null
&& past.current == -1 && past.groups[1].avg == 72);
putLe(offline, 5, 0, 4);
expect("zero day remains unresolved", RingProtocol.anchorUnixSeconds(offline) == RingProtocol.UNKNOWN_TIME);
int[][] buckets = new int[8][4];
for (int i = 0; i < buckets.length; i++) buckets[i] = new int[] {i, i * 10, 1, 2};
byte[] activity = stepsBody(anchor, buckets);
expect("eight-bucket activity frame is 80 bytes", dataFrame(5, activity).raw.length == 80);
expect("activity decodes without footer", RingProtocol.decodeSteps(dataFrame(5, activity), 0).buckets.length == 8);
expect("trailing garbage rejected", RingProtocol.decodeSteps(dataFrame(5,
Arrays.copyOf(activity, activity.length + 4)), 0) == null);
}
private static void testDeviceStatus() {
section("direct device status battery");
byte[] payload = {0x11, 0x22, 82, 2, 1, 0, 0, 0, 0};
for (int charge = 0; charge <= 3; charge++) {
payload[3] = (byte) charge;
RingProtocol.Frame frame = RingProtocol.parse(RingProtocol.buildFrame(
RingProtocol.CHAN_DEVICE, RingProtocol.KIND_RSP, 0, 1, 1, payload));
RingProtocol.DeviceStatus status = RingProtocol.decodeDeviceStatus(frame);
expect("battery and charge enum " + charge, status != null && status.battery == 82
&& status.charging == (charge == 0 ? -1 : charge == 2 ? 0 : 1));
}
payload[2] = (byte) 255;
expect("invalid battery rejected", RingProtocol.decodeDeviceStatus(RingProtocol.parse(
RingProtocol.buildFrame(1, 3, 0, 1, 1, payload))) == null);
expect("wrong channel rejected", RingProtocol.decodeDeviceStatus(dataFrame(1, payload)) == null);
expect("short response rejected", RingProtocol.decodeDeviceStatus(RingProtocol.parse(
RingProtocol.buildFrame(1, 3, 0, 1, 1, new byte[2]))) == null);
}
// Synthetic body builders matching the recovered R1 serializers.
// ------------------------------------------------------------------
private static byte[] hourlyBody(int count, long anchor, long tag, int current,
int width, int[][] groups) {
byte[] body = new byte[13 + width + count * (1 + 3 * width)];
body[0] = 0x11;
body[1] = 0x22;
body[2] = (byte) count;
writeAnchor(body, anchor);
putLe(body, 9, tag, 4);
putLe(body, 13, current, width);
int offset = 13 + width;
for (int[] g : groups) {
body[offset++] = (byte) g[0];
putLe(body, offset, g[1], width);
offset += width;
putLe(body, offset, g[2], width);
offset += width;
putLe(body, offset, g[3], width);
offset += width;
}
return body;
}
private static byte[] stepsBody(long anchor, int[][] buckets) {
byte[] body = new byte[9 + buckets.length * 7];
body[0] = 0x33;
body[1] = 0x44;
body[2] = (byte) buckets.length;
writeAnchor(body, anchor);
int offset = 9;
for (int[] b : buckets) {
body[offset] = (byte) b[0];
putLe(body, offset + 1, b[1], 2);
putLe(body, offset + 3, b[2], 2);
putLe(body, offset + 5, b[3], 2);
offset += 7;
}
return body;
}
private static byte[] sleepBody(int recordState, long start, long end, int total, int wake,
int rem, int light, int deep, int[][] segments) {
byte[] body = new byte[34 + segments.length * 3];
body[0] = 0x55;
body[1] = 0x66;
body[2] = (byte) recordState;
for (int i = 3; i < 9; i++) {
body[i] = (byte) (0xA0 + i); // the uncracked 6-byte field
}
putLe(body, 9, 90210L, 4); // the uncracked u32 tag
body[13] = 0x00;
putLe(body, 14, start, 4);
putLe(body, 18, end, 4);
putLe(body, 22, total, 2);
putLe(body, 24, wake, 2);
putLe(body, 26, rem, 2);
putLe(body, 28, light, 2);
putLe(body, 30, deep, 2);
body[32] = (byte) segments.length;
body[33] = 0x00;
int offset = 34;
for (int[] s : segments) {
body[offset] = (byte) s[0];
putLe(body, offset + 1, s[1], 2);
offset += 3;
}
return body;
}
private static void writeAnchor(byte[] body, long anchor) {
if (anchor == RingProtocol.UNKNOWN_TIME) {
return; // six zero bytes = backlog page
}
body[3] = 0x10;
body[4] = (byte) 0xFF;
putLe(body, 5, anchor, 4);
}
private static void putLe(byte[] out, int offset, long value, int width) {
for (int i = 0; i < width; i++) {
out[offset + i] = (byte) ((value >>> (8 * i)) & 0xff);
}
}
private static RingProtocol.Frame dataFrame(int cmdHi, byte[] body) {
byte[] frame = RingProtocol.buildFrame(
RingProtocol.CHAN_HEALTH, RingProtocol.KIND_DATA, cmdHi,
RingProtocol.CMD_LO_HEALTH, 0x20, body);
return RingProtocol.parse(frame);
}
// ------------------------------------------------------------------
private static void section(String name) {
System.out.println();
System.out.println("-- " + name);
}
private static void expect(String what, boolean ok) {
checks++;
if (!ok) {
failures++;
}
System.out.println(" " + (ok ? "ok " : "FAIL") + " " + what);
}
private static void expectHex(String what, String expectedHex, byte[] actual) {
String actualHex = RingProtocol.hex(actual);
boolean ok = expectedHex.equals(actualHex);
checks++;
if (!ok) {
failures++;
System.out.println(" FAIL " + what);
System.out.println(" expected " + expectedHex);
System.out.println(" actual " + actualHex);
return;
}
System.out.println(" ok " + what + " " + actualHex);
}
private static String hex2(int value) {
return String.format(java.util.Locale.US, "%02x", value & 0xff);
}
}
@@ -0,0 +1,117 @@
package com.faceclaw.app
import java.io.ByteArrayOutputStream
import java.util.Collections
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.zip.Inflater
import kotlin.test.*
// Host tests have no Android clock; all other services use the production adapter.
internal actual fun testPlatform(): ProtocolPlatform =
object : ProtocolPlatform by AndroidProtocolPlatform {
override fun elapsedRealtimeMs() = System.nanoTime() / 1_000_000
}
internal actual fun inflateRecords(records: List<ByteArray>): List<ByteArray> {
val inflater = Inflater()
try {
return records.map { record ->
if (record[0].toInt() and CfwTransport.RESET_CONTEXT != 0) inflater.reset()
val body = record.copyOfRange(5, record.size)
if (record[0].toInt() and CfwTransport.COMPRESSED == 0) body
else {
inflater.setInput(body)
val out = ByteArrayOutputStream()
val buffer = ByteArray(4096)
do {
val count = inflater.inflate(buffer)
out.write(buffer, 0, count)
} while (!inflater.needsInput())
out.toByteArray()
}
}
} finally {
inflater.end()
}
}
class AndroidProtocolTest {
@Test
fun javaGoldenCorpus() {
// SHA-256 of packets emitted by the pre-migration Java implementation.
val raw = java.security.MessageDigest.getInstance("SHA-256")
val compressed = java.security.MessageDigest.getInstance("SHA-256")
val transport = CfwTransport(testPlatform())
var state = 123456789
try {
repeat(120) { i ->
val size = intArrayOf(0, 1, 4, 247, 248, 252, 4095, 4096, 8192, 65535)[i % 10]
val data =
ByteArray(size) {
state = state xor (state shl 13)
state = state xor (state ushr 17)
state = state xor (state shl 5)
state.toByte()
}
if (i % 3 == 0) data.fill((i % 7).toByte())
val id = (i * 37) and 255
val lenses = 1 + (i / 7) % 3
val mtu = intArrayOf(23, 247, 512, 517)[i % 4]
if (i % 13 == 0) transport.reset()
CfwTransport.frame(data, id, lenses, mtu).forEach { raw.update(it) }
transport.encode(data, id, lenses, mtu).forEach { compressed.update(it) }
}
assertEquals(
"d0efdb99ac71763dd29b70fbd0021b80e1cfe514dfc8a60e2a8424892b16c9f5",
raw.digest().toHexString(),
)
assertEquals(
"eb5ce0cc6e41b8e84f0d9455f98f3f666b20be0643c3756c5f7aa9d9a66085e2",
compressed.digest().toHexString(),
)
} finally {
transport.close()
}
}
@Test
fun writeModeMapping() {
assertEquals(
android.bluetooth.BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT,
AndroidProtocolPlatform.writeType(GattWriteMode.WITH_RESPONSE),
)
assertEquals(
android.bluetooth.BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE,
AndroidProtocolPlatform.writeType(ConnectionOptions.WRITE_MODE),
)
}
@Test
fun concurrentAllocationNeverDuplicatesAnInUseId() {
val pool = BleMagicPool(testPlatform())
val inUse = Collections.synchronizedSet(mutableSetOf<Int>())
val executor = Executors.newFixedThreadPool(8)
try {
val jobs =
List(8) {
executor.submit {
repeat(2000) {
val id = pool.allocate()
assertTrue(inUse.add(id))
Thread.yield()
assertTrue(inUse.remove(id))
pool.release(1, id, null, null)
}
}
}
jobs.forEach { it.get(30, TimeUnit.SECONDS) }
assertEquals(156, List(156) { pool.allocate() }.toSet().size)
} finally {
executor.shutdownNow()
}
}
}
internal actual fun digest(bytes: ByteArray): String =
BinaryEncoding.bytesToHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes))
@@ -0,0 +1,33 @@
package com.faceclaw.app
import java.util.Locale
import kotlin.test.Test
import kotlin.test.assertEquals
/** The shared export must match what the Java-era String.format("%+7d") produced. */
class FrameTimingsFormatTest {
private class FakeClock : ProtocolPlatform by AndroidProtocolPlatform {
var nowMs = 5_000L
override fun elapsedRealtimeMs(): Long = nowMs
}
@Test
fun lineOffsetsMatchJavaFormat() {
val clock = FakeClock()
val core = FrameTimingsCore(clock, wallClockMs = { 0L }, threadName = { "worker" }, formatWallClock = { "w" }, logInfo = {}, logWarn = {})
val offsets = listOf(-1_234_567L, -12L, -1L, 0L, 1L, 42L, 999L, 1_000L, 12_345L, 1_234_567L, 12_345_678L)
val root = core.startFrame("input:fmt")
for (offset in offsets) {
clock.nowMs = 5_000L + offset
core.log(root, "o=$offset")
}
clock.nowMs = 5_000L
core.finishFrame(root, "sent")
val export = core.buildExport()
for (offset in offsets) {
val javaLine = String.format(Locale.US, " %+7dms [%s] %s", offset, "worker", "o=$offset")
assert(export.contains("\n$javaLine\n")) { "missing <$javaLine> in\n$export" }
}
assertEquals(2, export.split("\n").count { it.contains("finished: sent") })
}
}
@@ -0,0 +1,29 @@
package com.faceclaw.app
import kotlin.test.Test
/** Existing wire fixtures also verify the Java API retained by the Kotlin port. */
class JavaCompatibilityTest {
@Test fun compass() = CompassProtocolTest.main(emptyArray())
@Test fun ringBattery() = RingBatteryProtocolTest.main(emptyArray())
@Test fun gestures() = FaceclawGestureEventTest.main(emptyArray())
@Test fun resourceCache() = ResourceCacheProtocolTest.main(emptyArray())
@Test fun ringHealthProtocol() = RingProtocolSelfTest.main(emptyArray())
}
class AndroidByteReaderTest {
@Test fun repeatedBridgeCrossingsHaveIndependentCursors() {
val buffer = java.nio.ByteBuffer.wrap(byteArrayOf(10, 20, 30))
val first = AndroidByteReader(buffer)
kotlin.test.assertEquals(10, first.get().toInt())
kotlin.test.assertEquals(0, buffer.position())
val second = AndroidByteReader(buffer)
kotlin.test.assertEquals(3, second.remaining())
kotlin.test.assertEquals(10, second.get().toInt())
kotlin.test.assertEquals(20, first.get().toInt())
}
}
@@ -0,0 +1,123 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
private class FakeScheduler : AlarmScheduler {
val pending = LinkedHashMap<Any, Pair<Long, () -> Unit>>()
override fun postDelayed(token: Any, delayMs: Long, action: () -> Unit) { pending[token] = delayMs to action }
override fun cancel(token: Any) { pending.remove(token) }
override fun cancelAll() { pending.clear() }
fun fire(token: Any) { val entry = pending.remove(token) ?: error("no timer $token"); entry.second() }
}
private class FakeSink : RingingSink {
val events = ArrayList<String>()
var sounding = false
override fun showNotification(item: RingingItem) { events.add("notify ${item.id} " + (if (item.silenced) "silenced" else if (item.escalated) "ringing" else "glasses")) }
override fun itemRemoved(item: RingingItem) { events.add("removed ${item.id}") }
override fun ringingStarted() { events.add("wake") }
override fun startSound() { if (!sounding) { sounding = true; events.add("sound on") } }
override fun stopSound() { if (sounding) { sounding = false; events.add("sound off") } }
override fun reschedule(item: RingingItem, atMs: Long, minutes: Int) { events.add("reschedule ${item.id} $atMs $minutes") }
override fun cancelSchedule(id: Long) { events.add("cancel $id") }
override fun recordPhoneAction(id: Long, action: String, minutes: Int) { events.add("action $id $action $minutes") }
override fun log(line: String) { events.add("log $line") }
}
class AlarmRingingPolicyTest {
private var now = 5_000_000L
private val gate = GlassesStatusGate { now }
private val scheduler = FakeScheduler()
private val sink = FakeSink()
private val policy = AlarmRingingPolicy(gate, { now }, testPlatform()).also { it.attach(scheduler, sink) }
private fun item(id: Long, kind: String = AlarmSchedule.KIND_ALARM) = RingingItem(id, "Wake", "", kind, 9, now)
@Test
fun glassesUnavailableEscalatesImmediately() {
policy.ring(item(1))
assertEquals(listOf("log ring alarm 1 (no glasses status)", "wake", "notify 1 glasses", "log phone sound for 1: no glasses status", "notify 1 ringing", "sound on"), sink.events)
assertTrue(policy.isRinging(1))
assertEquals(setOf<Any>("silence:1"), scheduler.pending.keys)
scheduler.fire("silence:1")
assertEquals(listOf("log auto-silenced 1", "notify 1 silenced", "sound off"), sink.events.drop(6))
}
@Test
fun deliveryAndAcknowledgementTimersEscalate() {
gate.set(connected = true, worn = true, charging = false)
policy.ring(item(2))
assertEquals(listOf("log ring alarm 2 (glasses worn)", "wake", "notify 2 glasses"), sink.events)
assertEquals(setOf<Any>("delivery:2"), scheduler.pending.keys)
policy.markDelivered(2)
assertEquals("log delivered 2 to glasses", sink.events.last())
assertEquals(setOf<Any>("delivery:2", "ack:2"), scheduler.pending.keys)
scheduler.fire("delivery:2") // delivered in time: no escalation
assertFalse(policy.snapshot().single().escalated)
scheduler.fire("ack:2")
assertTrue(policy.snapshot().single().escalated)
assertTrue(sink.sounding)
// Acknowledged on the glasses afterwards: quiet stop, sound off.
policy.stopQuietly(2, "acknowledged")
assertEquals(listOf("log acknowledged 2", "removed 2", "sound off"), sink.events.takeLast(3))
assertFalse(policy.isAnythingRinging())
}
@Test
fun undeliveredRingEscalatesAfterDeliveryWait() {
gate.set(connected = true, worn = true, charging = false)
policy.ring(item(3))
scheduler.fire("delivery:3")
assertEquals("log phone sound for 3: not delivered to the glasses", sink.events[3])
assertTrue(sink.sounding)
}
@Test
fun snoozeAndDismissRecordActionsAndRearm() {
policy.ring(item(4, AlarmSchedule.KIND_TIMER))
policy.snooze(4)
assertEquals(listOf("action 4 snooze 9", "removed 4", "sound off", "reschedule 4 ${now + 9 * 60_000L} 9"), sink.events.takeLast(4))
policy.ring(item(5))
policy.dismiss(5)
assertEquals(listOf("action 5 dismiss 0", "removed 5", "sound off", "cancel 5"), sink.events.takeLast(4))
policy.dismiss(99) // unknown: no-op
assertEquals("cancel 5", sink.events.last())
}
@Test
fun earlySignalsAreConsumedOrExpire() {
gate.set(connected = true, worn = true, charging = false)
assertFalse(policy.deliveredOrDefer(6))
policy.ring(item(6))
assertEquals("log delivered 6 to glasses", sink.events.last())
assertEquals(setOf<Any>("ack:6"), scheduler.pending.keys)
assertFalse(policy.stopOrDefer(7))
policy.ring(item(7))
assertEquals("log ring 7 already acknowledged", sink.events.last())
assertFalse(policy.isRinging(7))
assertFalse(policy.stopOrDefer(8))
now += AlarmRingingPolicy.EARLY_SIGNAL_MAX_AGE_MS + 1
policy.ring(item(8))
assertTrue(policy.isRinging(8))
assertTrue(policy.stopOrDefer(8))
assertTrue(policy.deliveredOrDefer(8))
}
@Test
fun duplicateRingOnlyRefreshesNotificationAndDetachDropsTimers() {
policy.ring(item(9))
val before = sink.events.size
policy.ring(item(9))
assertEquals(listOf("notify 9 ringing"), sink.events.drop(before))
assertEquals(1, policy.snapshot().size)
policy.detach()
assertTrue(scheduler.pending.isEmpty())
policy.ring(item(10)) // no host: ignored
assertFalse(policy.isRinging(10))
}
}
@@ -0,0 +1,109 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
private class MemoryStore : AlarmStore {
val values = HashMap<String, String?>()
override fun read(key: String): String? = values[key]
override fun write(key: String, value: String?) { values[key] = value }
}
class AlarmScheduleTest {
private val store = MemoryStore()
private var now = 1_700_000_000_000L
private val schedule = AlarmSchedule(store, { now }, testPlatform())
@Test
fun persistsEntriesAsJsonAndReplacesById() {
schedule.put(AlarmEntry(7, now + 60_000, "Tea", "steep", AlarmSchedule.KIND_TIMER, 5))
schedule.put(AlarmEntry(8, now + 120_000, null, null, null, 10))
assertEquals("""[{"id":7,"at":${now + 60_000},"title":"Tea","text":"steep","kind":"timer","snoozeMinutes":5},{"id":8,"at":${now + 120_000},"title":"","text":"","kind":"alarm","snoozeMinutes":10}]""", store.values[AlarmSchedule.KEY_SCHEDULED])
schedule.put(AlarmEntry(7, now + 90_000, "Tea", "steep", AlarmSchedule.KIND_TIMER, 5))
assertEquals(listOf(8L, 7L), schedule.entries().map { it.id })
assertEquals(now + 90_000, schedule.find(7)?.at)
schedule.remove(8)
assertNull(schedule.find(8))
// A corrupt file reads as empty rather than failing.
store.values[AlarmSchedule.KEY_SCHEDULED] = "{nope"
assertTrue(schedule.entries().isEmpty())
}
@Test
fun replayRingsRecentDropsMissedArmsFuture() {
schedule.put(AlarmEntry(1, now - 60_000, "recent", "", null, 10))
schedule.put(AlarmEntry(2, now - AlarmSchedule.LATE_GRACE_MS - 1, "old", "", AlarmSchedule.KIND_TIMER, 10))
schedule.put(AlarmEntry(3, now + 60_000, "future", "", null, 10))
val rang = ArrayList<Long>()
val armed = ArrayList<Long>()
schedule.replay("boot", { rang.add(it.id) }, { armed.add(it.id) })
assertEquals(listOf(1L), rang)
assertEquals(listOf(3L), armed)
assertEquals(listOf(1L, 3L), schedule.entries().map { it.id })
val log = schedule.readLog()
assertTrue(log.contains("$now missed timer 2 (boot)"), log)
assertTrue(log.endsWith("$now rescheduled 1 (boot)"), log)
}
@Test
fun stalenessComparesSoonestPendingWithSystemAlarm() {
assertFalse(schedule.looksStale(null))
schedule.put(AlarmEntry(1, now - 1, "past", "", null, 10))
assertNull(schedule.soonestPendingAt())
schedule.put(AlarmEntry(2, now + 50_000, "", "", null, 10))
schedule.put(AlarmEntry(3, now + 20_000, "", "", null, 10))
assertEquals(now + 20_000, schedule.soonestPendingAt())
assertTrue(schedule.looksStale(null))
assertTrue(schedule.looksStale(now + 30_000))
assertFalse(schedule.looksStale(now + 20_500))
assertFalse(schedule.looksStale(now + 5_000))
}
@Test
fun journalAppendsAndDrains() {
schedule.appendJournal(5, "snooze", 10)
now += 1000
schedule.appendJournal(6, "dismiss", 0)
assertEquals("""[{"id":5,"action":"snooze","minutes":10,"at":${now - 1000}},{"id":6,"action":"dismiss","minutes":0,"at":$now}]""", schedule.drainJournal())
assertEquals("[]", schedule.drainJournal())
val log = schedule.readLog().lines()
assertEquals("${now - 1000} phone snooze 5 (10 min)", log[0])
assertEquals("$now phone dismiss 6", log[1])
}
@Test
fun logKeepsOnlyTheLastLines() {
for (index in 0 until AlarmSchedule.LOG_LINES + 5) schedule.log("line $index")
val lines = schedule.readLog().lines()
assertEquals(AlarmSchedule.LOG_LINES, lines.size)
assertEquals("$now line 5", lines.first())
assertEquals("$now line ${AlarmSchedule.LOG_LINES + 4}", lines.last())
}
@Test
fun glassesGateRequiresFreshWornConnectedNotCharging() {
var clock = 10_000L
val gate = GlassesStatusGate { clock }
assertFalse(gate.canCarryAlarm())
assertEquals("no glasses status", gate.description())
gate.set(connected = true, worn = true, charging = false)
assertTrue(gate.canCarryAlarm())
assertEquals("glasses worn", gate.description())
gate.set(connected = true, worn = false, charging = false)
assertEquals("glasses not worn", gate.description())
gate.set(connected = true, worn = true, charging = true)
assertEquals("glasses charging", gate.description())
gate.set(connected = false, worn = true, charging = false)
assertEquals("glasses not connected", gate.description())
gate.set(connected = true, worn = true, charging = false)
clock += GlassesStatusGate.MAX_AGE_MS + 1
assertFalse(gate.canCarryAlarm())
assertEquals("glasses status stale", gate.description())
assertEquals(0x7fffffff and (0x1_0000_0002L xor 1L).toInt(), AlarmSchedule.requestCode(0x1_0000_0002L))
assertNotNull(AlarmEntry.fromJson(Json.parse("""{"id":1,"at":2}""")))
}
}
@@ -0,0 +1,130 @@
package com.faceclaw.app
import kotlin.math.abs
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
class AudioHelpersTest {
@Test
fun cutPointLandsInQuietestWindowForFloatsAndShorts() {
// 1000 loud samples with a silent gap at 700..760; search the last 500 with a 40 window.
val floats = FloatArray(1000) { if (it in 700 until 760) 0f else 0.5f }
val cut = AudioSegmentation.quietestCutPoint(floats, floats.size, 500, 40)
assertTrue(cut in 700..760, "cut=$cut")
val shorts = ShortArray(1100) { if (it - 100 in 700 until 760) 0 else 16000 }
assertEquals(cut, AudioSegmentation.quietestCutPoint(shorts, 100, 1000, 500, 40))
// Too short to search: returns the length unchanged.
assertEquals(30, AudioSegmentation.quietestCutPoint(FloatArray(30) { 0.1f }, 30, 500, 40))
}
@Test
fun normalizePeakScalesUpButNeverDown() {
val quiet = floatArrayOf(0.01f, -0.02f, 0.005f)
AudioSegmentation.normalizePeak(quiet, 0.9f, 30f)
assertTrue(abs(quiet[1] + 0.6f) < 1e-6f, "capped at maxGain 30: ${quiet[1]}")
val loud = floatArrayOf(0.95f, -0.5f)
AudioSegmentation.normalizePeak(loud, 0.9f, 30f)
assertEquals(0.95f, loud[0])
val silent = FloatArray(4)
AudioSegmentation.normalizePeak(silent, 0.9f, 30f)
assertEquals(0f, AudioSegmentation.peakAmplitude(silent))
}
@Test
fun pcmConversionsRoundTrip() {
val samples = shortArrayOf(0, 1, -1, 32767, -32768, 256)
val le = AudioSegmentation.pcm16ToLittleEndian(samples, 0, samples.size)
assertEquals(listOf(0, 0, 1, 0, 0xff, 0xff, 0xff, 0x7f, 0, 0x80, 0, 1), le.map { it.toInt() and 0xff })
val floats = AudioSegmentation.pcm16leToFloat(le)
assertEquals(AudioSegmentation.pcm16ToFloat(samples, 0, samples.size).toList(), floats.toList())
assertEquals(32767 / 32768.0f, floats[3])
assertEquals(-1f, floats[4])
assertEquals(2.0, AudioSegmentation.rms(shortArrayOf(2, -2, 2, -2), 0, 4))
}
@Test
fun voicePrintMathAndBlobCodec() {
val v = floatArrayOf(3f, 4f)
VoicePrint.l2Normalize(v)
assertEquals(listOf(0.6f, 0.8f), v.toList())
assertTrue(abs(VoicePrint.dot(v, v) - 1.0) < 1e-6)
assertNull(VoicePrint.l2Normalize(null))
assertTrue(VoicePrint.isLongEnoughToEmbed(16000, 16000))
assertTrue(!VoicePrint.isLongEnoughToEmbed(15999, 16000))
val blob = SpeakerEmbeddings.floatsToBlob(floatArrayOf(1.5f, -2f))
assertEquals(listOf(0, 0, 0xc0, 0x3f, 0, 0, 0, 0xc0), blob.map { it.toInt() and 0xff })
assertEquals(listOf(1.5f, -2f), SpeakerEmbeddings.blobToFloats(blob)!!.toList())
assertNull(SpeakerEmbeddings.blobToFloats(byteArrayOf(1, 2, 3)))
assertNull(SpeakerEmbeddings.blobToFloats(null))
}
@Test
fun centroidUpdatesAndBlends() {
val first = SpeakerEmbeddings.runningMean(null, 0, floatArrayOf(1f, 0f), 5)
assertEquals(1, first.count)
assertEquals(listOf(1f, 0f), first.embedding.toList())
val second = SpeakerEmbeddings.runningMean(first.embedding, first.count, floatArrayOf(0f, 1f), 5)
assertEquals(2, second.count)
assertTrue(abs(second.embedding[0] - second.embedding[1]) < 1e-6f)
assertTrue(abs(VoicePrint.dot(second.embedding, second.embedding) - 1.0) < 1e-6)
// The cap limits the existing weight: count 100 capped at 1 behaves like an equal blend.
val capped = SpeakerEmbeddings.runningMean(floatArrayOf(1f, 0f), 100, floatArrayOf(0f, 1f), 1)
assertTrue(abs(capped.embedding[0] - capped.embedding[1]) < 1e-6f)
assertEquals(101, capped.count)
// Mismatched sizes restart the centroid.
assertEquals(1, SpeakerEmbeddings.runningMean(floatArrayOf(1f), 4, floatArrayOf(0f, 1f), 5).count)
val blended = SpeakerEmbeddings.blend(floatArrayOf(1f, 0f), 1, floatArrayOf(0f, 1f), 3)
assertNotNull(blended)
assertTrue(blended[1] > blended[0])
assertEquals(listOf(0f, 1f), SpeakerEmbeddings.blend(null, 0, floatArrayOf(0f, 1f), 3)!!.toList())
assertEquals(listOf(1f, 0f), SpeakerEmbeddings.blend(floatArrayOf(1f, 0f), 2, null, 0)!!.toList())
assertNull(SpeakerEmbeddings.blend(null, 0, null, 0))
assertTrue(SpeakerEmbeddings.shouldAdoptInsights(targetHasInsights = false, sourceHasInsights = true))
assertTrue(!SpeakerEmbeddings.shouldAdoptInsights(targetHasInsights = true, sourceHasInsights = true))
}
private fun wav(dataSize: Int, extraChunk: Boolean = false, channels: Int = 1, bits: Int = 16, format: Int = 1): ByteArray {
val out = ByteSink()
fun u16(v: Int) { out.write(v); out.write(v ushr 8) }
fun u32(v: Int) { u16(v); u16(v ushr 16) }
out.write("RIFF".encodeToByteArray()); u32(0); out.write("WAVE".encodeToByteArray())
if (extraChunk) { out.write("LIST".encodeToByteArray()); u32(4); u32(0) }
out.write("fmt ".encodeToByteArray()); u32(18)
u16(format); u16(channels); u32(16000); u32(16000 * channels * 2); u16(channels * 2); u16(bits); u16(0)
out.write("data".encodeToByteArray()); u32(dataSize)
return out.toByteArray()
}
@Test
fun wavHeaderParsesChunksAndRecoversZeroSize() {
val header = wav(4000)
val info = WavPcmReader.parseHeader(header, header.size + 4000L)
assertEquals(16000, info.sampleRate)
assertEquals(1, info.channels)
assertEquals(16, info.bitsPerSample)
assertEquals(header.size.toLong(), info.dataOffset)
assertEquals(4000L, info.dataBytes)
val withList = wav(100, extraChunk = true)
assertEquals(withList.size.toLong(), WavPcmReader.parseHeader(withList, withList.size + 100L).dataOffset)
val unpatched = wav(0)
assertEquals(1234L, WavPcmReader.parseHeader(unpatched, unpatched.size + 1234L).dataBytes)
assertFailsWith<IllegalArgumentException> { WavPcmReader.parseHeader("RIFX".encodeToByteArray() + ByteArray(20), 24) }
assertFailsWith<IllegalArgumentException> { WavPcmReader.parseHeader(wav(10, bits = 8), 100) }
assertFailsWith<IllegalArgumentException> { WavPcmReader.parseHeader(wav(10, format = 3), 100) }
assertFailsWith<IllegalArgumentException> { WavPcmReader.parseHeader(wav(10).copyOf(20), 100) }
// The shared header matches the shared writer.
val written = BinaryEncoding.wavHeader(640, 16000, 1)
val parsed = WavPcmReader.parseHeader(written, 44 + 640L)
assertEquals(44L, parsed.dataOffset)
assertEquals(640L, parsed.dataBytes)
}
}
@@ -0,0 +1,44 @@
package com.faceclaw.app
import kotlin.test.*
internal expect fun digest(bytes: ByteArray): String
class AudioRecordingTest {
@Test
fun javaNoiseSuppressionGoldenAcrossChunksAndReset() {
val suppressor = FaceclawNoiseSuppressor(16000)
val output = ByteSink()
for (round in 0 until 80) {
val input = ByteArray(if (round % 7 == 0) 514 else 640)
for (i in 0 until input.size / 2) {
val value = ((round * 317 + i * 773) % 48000) - 24000
input[i * 2] = value.toByte()
input[i * 2 + 1] = (value shr 8).toByte()
}
if (round == 41) suppressor.reset()
output.write(assertNotNull(suppressor.process(input)))
}
// SHA-256 from the original Java DSP, including warmup and irregular chunks.
assertEquals(
"4a7e86b70d61d683b17c7051dbd6666f5ea62427fdd7fdb1d4c9a1772a1eb8ef",
digest(output.toByteArray()),
)
}
@Test
fun javaGifGoldenIncludingDedupAndLzwCodeGrowth() {
val recorder = SharedGifScreenRecorder()
assertTrue(recorder.encode().isEmpty())
for (round in 0 until 7) {
val pixels = ByteArray(33 * 17) { ((it * 73 + round * 117) % 256).toByte() }
recorder.addFrame(pixels, 33, 17, round * 133L)
recorder.addFrame(pixels, 33, 17, round * 133L + 10)
}
assertFalse(recorder.isOverflowed())
assertEquals(
"8c5dcb98fa03653972f7f7d5ddaaacff323dd633578905bc252ebe21f9d82780",
digest(recorder.encode()),
)
}
}
@@ -0,0 +1,108 @@
package com.faceclaw.app
import kotlin.test.*
class BrightnessPolicyTest {
private fun report(lux: Int, reason: Int = 2, flags: Int = 11): ByteArray {
val b = ByteArray(24)
b[0] = 65; b[1] = 76; b[2] = 1; b[3] = reason.toByte(); b[4] = flags.toByte()
val raw = lux * 10
for (i in 0..3) b[6+i] = (raw ushr (8*i)).toByte()
return b
}
@Test fun defaultMatchesMeasuredLightingPreferences() {
val p = BrightnessPolicy()
for ((raw, expected) in listOf(0 to 20, 2 to 26, 15 to 46, 50 to 100, 500 to 100)) {
val b = report(0)
b[6] = raw.toByte(); b[7] = (raw shr 8).toByte()
p.resetSamples(); p.sample(b, 1000)
assertEquals(expected, p.target, "raw ALS=$raw")
}
}
@Test fun curveUsesConfiguredBoundsAndLogInterpolation() {
val p = BrightnessPolicy()
p.configure(true, 50, 10, 90, "0:0,99:100", 280)
p.sample(report(9), 1000)
assertEquals(50, p.target) // log(10) / log(100) = 1/2
p.resetSamples(); p.sample(report(0), 2000); assertEquals(10, p.target)
p.resetSamples(); p.sample(report(10000), 3000); assertEquals(90, p.target)
}
@Test fun onlySuccessfulPassivePollsDriveAuto() {
val p = BrightnessPolicy()
val initial = p.target
for (reason in listOf(0, 1, 3, 4)) assertFalse(p.sample(report(0, reason), 1000))
for (flags in listOf(0, 1, 3, 9, 10)) assertFalse(p.sample(report(0, flags = flags), 1000))
assertFalse(p.sample(byteArrayOf(), 1000))
assertEquals(initial, p.target)
assertTrue(p.sample(report(0), 1000)); assertEquals(20, p.target)
}
@Test fun manualPersistsAcrossSamplesAndModeChangesUseLatestLight() {
val p = BrightnessPolicy()
p.configure(false, 70, 2, 80, "0:0,100:100", 450)
p.sample(report(100), 1000); assertEquals(70, p.target)
p.setMode(true, 50); assertEquals(80, p.target)
p.setMode(false, 0); assertEquals(2, p.target)
assertEquals(450, p.fadeMs)
}
@Test fun brightensFasterThanItDimsAndResetsStaleSamples() {
val up = BrightnessPolicy(); val down = BrightnessPolicy()
for (p in listOf(up, down)) p.configure(true, 50, 2, 100, "0:0,100:100", 280)
up.sample(report(0), 1000); up.sample(report(100), 1500)
down.sample(report(100), 1000); down.sample(report(0), 1500)
assertTrue(up.target - 2 > 100 - down.target)
down.sample(report(0), 20000); assertEquals(2, down.target)
}
@Test fun autoHoldsSmallChangesUntilTheyAccumulateToFivePoints() {
val p = BrightnessPolicy()
p.configure(true, 50, 20, 40, "0:0,1:20,2:25,3:45,4:50,5:100", 280)
var now = 1000L
fun sample(lux: Int, changed: Boolean, target: Int) {
// Space readings beyond the smoothing window to isolate the deadband.
now += 11000
assertEquals(changed, p.sample(report(lux), now), "lux=$lux")
assertEquals(target, p.target, "lux=$lux")
}
sample(0, true, 20)
repeat(5) { sample(1, false, 20) } // Desired 24 stays suppressed.
sample(2, true, 25) // Exact five-point increase is accepted.
sample(3, false, 25) // Desired 29.
sample(4, true, 30)
sample(2, true, 25) // Exact five-point decrease is accepted too.
sample(1, false, 25)
sample(0, true, 20)
}
@Test fun boundsDoNotBypassDeadbandButExplicitChangesDo() {
for ((initial, lux) in listOf(24 to 0, 36 to 5)) {
val p = BrightnessPolicy()
p.configure(false, initial, 20, 40, "0:0,5:100", 280)
p.setMode(true, initial)
assertFalse(p.sample(report(lux), 1000))
assertEquals(initial, p.target)
p.setMode(false, initial + 1)
assertEquals(initial + 1, p.target) // Small manual changes remain exact.
p.setMode(true, initial)
assertEquals(if (lux == 0) 20 else 40, p.target)
}
val p = BrightnessPolicy()
p.sample(report(0), 1000)
p.configure(true, 50, 21, 100, BrightnessPolicy.DEFAULT_CURVE, 280)
assertEquals(21, p.target) // An explicit bounds edit applies immediately.
}
@Test fun invalidCurveDoesNotPartiallyChangeLivePolicy() {
val p = BrightnessPolicy()
for (curve in listOf("", "0:0", "1:0,100:100", "0:0,1:80,2:50,3:100", "0:0,0:100", "0:0,NaN:100", "0:0,1:99")) {
assertFailsWith<IllegalArgumentException> { p.configure(false, 90, 20, 80, curve, 0) }
assertTrue(p.automatic); assertEquals(280, p.fadeMs)
}
p.configure(true, 50, 80, 20, "0:0,100:100", 0)
p.sample(report(0), 1000); assertEquals(80, p.target)
}
}
@@ -0,0 +1,127 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
class CaptionEngineCoreTest {
private class Sink : CaptionSegmentSink {
val starts = mutableListOf<Long>()
val utterances = mutableListOf<List<Any>>()
override fun onSpeechStart(startMs: Long) { starts.add(startMs) }
override fun onUtterance(samples: ShortArray, length: Int, startMs: Long, endMs: Long, peakRms: Double) {
utterances.add(listOf(length, startMs, endMs, samples[0].toInt()))
}
}
private fun chunk(amplitude: Int, samples: Int = 800): ShortArray =
ShortArray(samples) { if (it % 2 == 0) amplitude.toShort() else (-amplitude).toShort() }
@Test
fun segmenterUsesPreRollOnsetReleaseAndSilence() {
val sink = Sink()
val segmenter = CaptionSegmenter(sink)
repeat(10) { segmenter.processChunk(chunk(100), 800) } // 500 ms idle, noise floor ~100 -> threshold 220
repeat(10) { segmenter.processChunk(chunk(3000), 800) } // 500 ms speech
assertEquals(listOf(100L), sink.starts) // 500 ms - 400 ms pre-roll
repeat(15) { segmenter.processChunk(chunk(100), 800) } // 750 ms < 800 ms silence: still open
assertTrue(sink.utterances.isEmpty())
segmenter.processChunk(chunk(100), 800) // 800 ms of silence closes it
assertEquals(1, sink.utterances.size)
val (length, startMs, endMs, first) = sink.utterances[0]
assertEquals(100L, startMs)
assertEquals(6400 + 10 * 800 + 16 * 800, length) // pre-roll + speech + trailing silence
assertEquals(startMs as Long + (length as Int) * 1000L / 16000, endMs)
assertEquals(100, first) // the pre-roll audio leads the utterance
assertTrue(segmenter.isInUtterance.not())
}
@Test
fun segmenterDropsTooShortUtterancesAndCapsLength() {
val sink = Sink()
val segmenter = CaptionSegmenter(sink)
segmenter.silenceMs = 100 // clamps to 200
segmenter.processChunk(chunk(10), 800) // seeds the noise floor; becomes the 50 ms pre-roll
segmenter.processChunk(chunk(3000), 800) // onset
repeat(4) { segmenter.processChunk(chunk(0), 800) } // 200 ms silence
assertEquals(1, sink.starts.size)
assertTrue(sink.utterances.isEmpty()) // 300 ms < 350 ms minimum
repeat(400) { segmenter.processChunk(chunk(3000), 800) } // 20 s of speech: capped at 15 s
assertEquals(1, sink.utterances.size)
assertEquals(16000 * 15, sink.utterances[0][0])
segmenter.flush()
assertEquals(2, sink.utterances.size) // the remainder is flushed on stop
}
@Test
fun utteranceDecoderSplitsLongAudioAndEmbedsTenSeconds() {
val calls = mutableListOf<Int>()
val transcriber = object : OfflineTranscriber {
override fun recognize(samples: FloatArray, count: Int): String { calls.add(count); return if (calls.size == 2) ", b" else "a" }
override fun release() {}
}
var embedded = 0
val embedder = object : SpeakerEmbedder {
override fun embed(pcm16le: ByteArray, sampleRate: Int): FloatArray? { embedded = pcm16le.size; return floatArrayOf(1f) }
override fun release() {}
}
val decoder = UtteranceDecoder(transcriber, embedder)
val utterance = ShortArray(16000 * 12) { if (it % 2 == 0) 2000 else -2000 }
assertEquals("a, b", decoder.recognize(utterance, utterance.size))
assertEquals(2, calls.size)
assertTrue(calls[0] <= UtteranceDecoder.DECODE_SEGMENT_MAX_SAMPLES)
assertEquals(utterance.size, calls.sum())
assertNotNull(decoder.embed(utterance, utterance.size))
assertEquals(16000 * 10 * 2, embedded)
assertEquals("", UtteranceDecoder(null, null).recognize(utterance, utterance.size))
assertNull(UtteranceDecoder(null, null).embed(utterance, utterance.size))
}
@Test
fun captionSessionRunsQueueThroughSegmenterAndDecoder() {
val startLatch = Latch(1, testPlatform())
val utteranceLatch = Latch(1, testPlatform())
val events = mutableListOf<String>()
val listener = object : FaceclawCaptionEngineListener {
override fun onUtterance(text: String?, embedding: FloatArray?, startMs: Long, endMs: Long, peakRms: Double) {
events.add("utterance:$text:${embedding?.size}:$startMs"); utteranceLatch.countDown()
}
override fun onSpeechStart(startMs: Long) { events.add("start:$startMs"); startLatch.countDown() }
override fun onStatus(status: String?) { events.add("status:$status") }
}
val host = object : CaptionHost {
override val dispatcher = CallbackDispatcher { it() }
override fun loadTranscriber(modelDir: String): OfflineTranscriber? = if (modelDir == "models") object : OfflineTranscriber {
override fun recognize(samples: FloatArray, count: Int): String = "hi"
override fun release() {}
} else null
override fun loadEmbedder(modelPath: String): SpeakerEmbedder? = object : SpeakerEmbedder {
override fun embed(pcm16le: ByteArray, sampleRate: Int): FloatArray? = floatArrayOf(0.5f, 0.5f)
override fun release() {}
}
}
val session = CaptionSession(host, testPlatform(), "caption-test") { m, e -> error("$m: $e") }
session.setListener(listener)
session.setAsrModelDir("models")
session.setSpeakerModelPath("speaker")
session.setSilenceMs(300)
session.acceptPcm(ByteArray(1600)) // ignored before start
session.start()
val loud = AudioSegmentation.pcm16ToLittleEndian(chunk(3000), 0, 800)
val quiet = AudioSegmentation.pcm16ToLittleEndian(chunk(0), 0, 800)
val idle = AudioSegmentation.pcm16ToLittleEndian(chunk(10), 0, 800)
repeat(2) { session.acceptPcm(idle) } // seeds the noise floor and fills 100 ms of pre-roll
repeat(10) { session.acceptPcm(loud) }
assertTrue(startLatch.await(5000))
repeat(8) { session.acceptPcm(quiet) }
assertTrue(utteranceLatch.await(5000))
session.stop()
session.stop() // idempotent
assertEquals("status:Loading caption model...", events[0])
assertEquals("status:Captions listening...", events[1])
assertEquals("start:0", events[2])
assertEquals("utterance:hi:2:0", events[3])
}
}
@@ -0,0 +1,40 @@
package com.faceclaw.app
import kotlin.test.*
class CompassTest {
private fun hex(text: String) = text.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
@Test
fun receiverPayloadAndAndroidFrameDecodeTheSameCompassSample() {
val payload = hex("080f1000520308e702a2060c434d010302038c0098badcfe")
for (flag in listOf(1, 6)) {
val frame = BleProtocol.framePb(payload, 8, flag, 15).single()
val received = MessageReceiver().receive("R", frame, 0).single()
val shared = assertNotNull(BleProtocol.parseCompassPayload(received.sid, received.flag, received.payload))
val android = assertNotNull(BleProtocol.parseCompassEvent(BleProtocol.parseFrame(frame)))
assertEquals(359, shared.headingDegrees)
assertEquals(15, shared.command)
assertEquals(3, shared.magneticAccuracy)
assertEquals(2, shared.magneticAnomalies)
assertEquals(3, shared.orientationSource)
assertEquals(0x8c, shared.diagnosticFlags)
assertEquals(0xfedcba98L, shared.sampleTimeMs)
assertEquals(android.sampleTimeMs, shared.sampleTimeMs)
}
assertNull(BleProtocol.parseCompassPayload(9, 1, payload))
assertNull(BleProtocol.parseCompassPayload(8, 0x20, payload))
assertNull(BleProtocol.parseCompassPayload(8, 1, hex("080f1000520308e802")))
assertNull(BleProtocol.parseCompassPayload(8, 1, byteArrayOf()))
for (size in 9 until payload.size) {
val legacy = assertNotNull(BleProtocol.parseCompassPayload(8, 1, payload.copyOf(size)))
assertEquals(359, legacy.headingDegrees)
assertEquals(-1, legacy.diagnosticFlags)
}
for (command in listOf(16, 17)) {
val calibration = assertNotNull(BleProtocol.parseCompassPayload(8, 1, byteArrayOf(8, command.toByte(), 16, 0)))
assertEquals(command, calibration.command)
assertEquals(-1, calibration.headingDegrees)
}
}
}
@@ -0,0 +1,54 @@
package com.faceclaw.app
import kotlin.test.*
class DimDitherTest {
@Test fun contextMenuDimHalftonesLevelsThatWouldRoundAway() {
// CONTEXT_MENU_DIM = 0.25: level 1 becomes a 1/0 halftone instead of black or 1.
val (even, odd) = DimDither.tables(64)
assertContentEquals(intArrayOf(0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4), even)
assertContentEquals(intArrayOf(0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4), odd)
}
@Test fun everyFactorGivesMonotonicAdjacentPairsThatKeepVisiblePixels() {
for (factor in 0..256) {
val (even, odd) = DimDither.tables(factor)
assertEquals(0, even[0])
assertEquals(0, odd[0])
for (level in 1..15) {
val halfSteps = even[level] + odd[level]
assertTrue(even[level] - odd[level] in 0..1, "factor=$factor level=$level")
assertTrue(halfSteps in 1..2 * level, "factor=$factor level=$level")
assertTrue(halfSteps >= even[level - 1] + odd[level - 1], "factor=$factor level=$level")
}
}
val (even, odd) = DimDither.tables(256)
assertContentEquals(IntArray(16) { it }, even)
assertContentEquals(IntArray(16) { it }, odd)
}
@Test fun remapUsesTheEvenTableWhereShiftedXPlusYIsEven() {
val even = IntArray(16) { 15 - it }
val odd = IntArray(16) { it / 2 }
val call = DrawProtocol.remapColors(0, 0, 3, 2, even, odd)
assertContentEquals(byteArrayOf(DRAW_OP_REMAP_COLORS.toByte(), 0, 0, 0, 0, 0, 3, 0, 2, 0,
0xfe.toByte(), 0xdc.toByte(), 0xba.toByte(), 0x98.toByte(), 0x76, 0x54, 0x32, 0x10,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77), call)
for (shift in listOf(0, 1)) {
// Rows of 4 pixels: 4, 5, 6, 7 then 8, 9, 10, 11.
val pixels = byteArrayOf(0x45, 0x67, 0x89.toByte(), 0xab.toByte())
DisplayListRenderer(emptyMap()).execute(DrawProtocol.sequence(listOf(call)),
DisplayListRenderer.Target(pixels, 4, 2).shifted(shift))
val target = DisplayListRenderer.Target(pixels, 4, 2)
for (y in 0..1) for (x in 0..3) {
val source = 4 + y * 4 + x
val expected = when {
x !in shift until shift + 3 -> source
(x + y) % 2 == 0 -> even[source]
else -> odd[source]
}
assertEquals(expected, target.get(x, y), "shift=$shift x=$x y=$y")
}
}
}
}
@@ -0,0 +1,304 @@
package com.faceclaw.app
import kotlin.test.*
import kotlin.random.Random
class DisplayListTest {
private fun hex(s: String) = s.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
@Test fun screenCopyPreservesOffsetsClippingPaddingAndAliasing() {
val random = Random(42)
val renderer = DisplayListRenderer(emptyMap())
for (sourceWidth in listOf(1, 2, 3, 7, 8, 640)) for (destinationWidth in listOf(1, 2, 3, 7, 8, 640)) {
for (shared in listOf(false, true)) for (shift in listOf(-3, 0, 2)) {
val sourceHeight = random.nextInt(1, 5); val destinationHeight = random.nextInt(1, 5)
val sourceOffset = random.nextInt(4); val destinationOffset = random.nextInt(4)
val size = maxOf(sourceOffset + (sourceWidth + 1) / 2 * sourceHeight,
destinationOffset + (destinationWidth + 1) / 2 * destinationHeight) + 3
val source = random.nextBytes(size)
val destination = if (shared) source else random.nextBytes(size)
val expectedSource = source.copyOf()
val expectedDestination = if (shared) expectedSource else destination.copyOf()
// Original per-pixel semantics, including cascading writes when
// views alias and ignoring shiftX when reading the source.
val referenceSource = DisplayListRenderer.Target(expectedSource, sourceWidth, sourceHeight, sourceOffset, 5)
val referenceDestination = DisplayListRenderer.Target(expectedDestination, destinationWidth, destinationHeight, destinationOffset, shift)
for (y in 0 until sourceHeight) for (x in 0 until sourceWidth)
referenceDestination.put(x, y, referenceSource.get(x, y))
assertEquals(emptySet(), renderer.render(DrawProtocol.SCREEN,
DisplayListRenderer.Target(source, sourceWidth, sourceHeight, sourceOffset, 5),
DisplayListRenderer.Target(destination, destinationWidth, destinationHeight, destinationOffset, shift)))
assertContentEquals(expectedDestination, destination, "$sourceWidth/$destinationWidth shared=$shared shift=$shift")
assertContentEquals(expectedSource, source)
}
}
val source = random.nextBytes(640 * 480 / 2)
val destination = ByteArray(source.size)
renderer.render(DrawProtocol.SCREEN, DisplayListRenderer.Target(source,640,480), DisplayListRenderer.Target(destination,640,480))
assertContentEquals(source, destination)
}
@Test fun invalidGraphDoesNotCopyScreenIntoComposition() {
val screen = hex("12345678"); val composition = hex("9abcdef0")
val resources = mapOf(1 to DrawProtocol.displayList(listOf(byteArrayOf(99,0))))
assertFails { DisplayListRenderer(resources).render(1, DisplayListRenderer.Target(screen,8,1), DisplayListRenderer.Target(composition,8,1)) }
assertContentEquals(hex("9abcdef0"), composition)
}
@Test fun oddPixelsRawRleClippingFontsNestedListsAndLut() {
val raw = DrawProtocol.rawImage(3, 3, hex("123045607890"))
val font = ByteArray(197); font[0]=1; font[67]=193.toByte(); hex("0801011f").copyInto(font,193)
val resources = mutableMapOf(10 to raw, 11 to hex("0802024f"), 12 to font)
val nested = listOf(DrawProtocol.image(11, -1, 0), DrawProtocol.bbox(hex("0c000000"), 2, 1, 0, 1, 1, 10))
resources[20]=DrawProtocol.displayList(nested)
val calls = listOf(DrawProtocol.call(DRAW_OP_DISPLAY_LIST,DrawProtocol.word(20)), DrawProtocol.image(10,3,1),
DrawProtocol.call(DRAW_OP_TEXT,hex("0c0007030f0141")), DrawProtocol.lut(8,4,128))
resources[21]=DrawProtocol.displayList(calls)
// Like the C harness, seed composition with the screen: this list has no screen copy.
val screen=hex("123456789abcdef0123456789abcdef0"); val output=screen.copyOf()
val renderer=DisplayListRenderer(resources)
assertEquals(setOf(10,11,12,20,21),renderer.render(21,DisplayListRenderer.Target(screen,8,4),DisplayListRenderer.Target(output,8,4)))
// Shared with the C sanitizer harness: signed clipping, resource target override, font and LUT.
assertContentEquals(hex("81223344755162701122334445544578"),output)
val first=output.copyOf(); screen.copyInto(output); renderer.render(21,DisplayListRenderer.Target(screen,8,4),DisplayListRenderer.Target(output,8,4))
assertContentEquals(first,output)
assertContentEquals(hex("123456789abcdef0123456789abcdef0"),screen)
}
@Test fun rootListsComposeTheScreenCopyAndClearBeforeDepthShifts() {
val screen = ByteArray(640 * 480 / 2) { (0x12 + it * 0x22).toByte() }
val sourceTarget = DisplayListRenderer.Target(screen, 640, 480)
// Without a copy, a root presents only what it draws.
val empty = mapOf(1 to DrawProtocol.displayList(emptyList()))
val composition = ByteArray(screen.size) { 0x55 }
DisplayListRenderer(empty).render(1, sourceTarget, DisplayListRenderer.Target(composition, 640, 480))
assertTrue(composition.all { it == 0x55.toByte() })
for (depth in listOf(-64, -17, 0, 1, 32)) for (right in listOf(false, true)) {
val resources = mapOf(1 to DrawProtocol.displayList(DrawProtocol.screenCopy(640, 480, depth)))
val output = ByteArray(screen.size) { -1 }
val target = DisplayListRenderer.Target(output, 640, 480)
DisplayListRenderer(resources, rightLens = right).render(1, sourceTarget, target)
val shift = DrawProtocol.depthOffset(depth, right)
for (y in listOf(0, 479)) for (x in 0 until 640) {
val sx = x - shift
assertEquals(if (sx in 0 until 640) sourceTarget.get(sx, y) else 0, target.get(x, y), "depth=$depth right=$right x=$x")
}
}
// Clear fills the whole resource target, padding included, and ignores depth.
val raw = DrawProtocol.rawImage(3, 2, hex("1234ab12"))
DisplayListRenderer(mapOf(5 to raw)).execute(DrawProtocol.sequence(listOf(DrawProtocol.clear(7, target = 5))),
DisplayListRenderer.Target(ByteArray(1), 1, 1))
assertContentEquals(DrawProtocol.rawImage(3, 2, hex("77777777")), raw)
val rejected = DrawProtocol.call(DRAW_OP_CLEAR, hex("10"))
assertFails { DisplayListRenderer(emptyMap()).execute(DrawProtocol.sequence(listOf(rejected)), DisplayListRenderer.Target(ByteArray(1), 1, 1)) }
}
@Test fun graphValidationPrecedesMutationAndCopyPreservesOverlap() {
val screen=hex("12345678"); val target=DisplayListRenderer.Target(screen,8,1)
val copy=DrawProtocol.call(DRAW_OP_RECT_COPY,hex("feff0000060001000200"))
DisplayListRenderer(emptyMap()).execute(DrawProtocol.sequence(listOf(copy)),target)
assertContentEquals(hex("12123456"),screen)
// Revision 29: an animated source row scrolls a raw strip; source bounds are checked each frame.
val strip=mapOf(9 to DrawProtocol.rawImage(2,4,hex("11223344")))
val scroll=DrawProtocol.rectCopy(9,DrawValue.Integer(0),DrawValue.animate(0,2,100),2,2,DrawValue.Integer(0),DrawValue.Integer(0))
for ((elapsed,rows) in listOf(0L to "1122",100L to "3344",500L to "3344")) {
val window=DisplayListRenderer.Target(ByteArray(2),2,2)
val renderer=DisplayListRenderer(strip)
renderer.execute(DrawProtocol.sequence(listOf(scroll)),window,elapsedMs=elapsed)
assertContentEquals(hex(rows),window.bytes); assertEquals(elapsed<100,renderer.animationPending)
}
val past=DrawProtocol.rectCopy(9,0,3,2,2,0,0)
assertFails { DisplayListRenderer(strip).execute(DrawProtocol.sequence(listOf(past)),DisplayListRenderer.Target(ByteArray(2),2,2)) }
val valid=DrawProtocol.bbox(hex("ffffffff"),4,0,0,8,1)
assertFails { DisplayListRenderer(emptyMap()).execute(DrawProtocol.sequence(listOf(valid,byteArrayOf(99,0))),target) }
assertContentEquals(hex("12123456"),screen)
val cyclic=mapOf(1 to DrawProtocol.displayList(listOf(DrawProtocol.call(DRAW_OP_DISPLAY_LIST,DrawProtocol.word(2)))),
2 to DrawProtocol.displayList(listOf(DrawProtocol.call(DRAW_OP_DISPLAY_LIST,DrawProtocol.word(1)))))
assertFails { DisplayListRenderer(cyclic).render(1,target,target) }
}
@Test fun roundedRectsAndNestedOddNegativeDepthMatchFirmwareOnBothLenses() {
val resources = mapOf(
40 to hex("0404000200f00f0ff0"),
41 to hex("0202000d0008020201010c0008000300040a0800040202280005041f"),
42 to hex("02010005000702fd2900"))
val screen = hex("012345601234560112345601234560122345601234560123345601234560123445601234560123455601234f60123456601234560123456001234560123456011234560123456012234560123456012334560123456012344560123456012345")
val expected = listOf("01234560123456011aaaaaaaaaa56012aa45644444aa0123a4564444456a1234a564f44f564a2345a6444fff644a3456a4444456444a4560aa44456444aa56011aaaaaaaaaa56012234560123456012334560123456012344560123456012345", "012345601234560112aaaaaaaaaa60122aa56444445aa1233a5644444564a2344a644f44f644a3455a4444ff6444a4566a4444564444a5600aa44564444aa60112aaaaaaaaaa6012234560123456012334560123456012344560123456012345")
for (right in listOf(false, true)) {
val output = screen.copyOf() // the shared vector's list has no screen copy
DisplayListRenderer(resources, rightLens = right).render(42, DisplayListRenderer.Target(screen,16,12), DisplayListRenderer.Target(output,16,12))
assertContentEquals(hex(expected[if(right) 1 else 0]), output)
}
for (depth in -128..127) {
assertEquals(kotlin.math.floor(depth / 2.0).toInt(), DrawProtocol.depthOffset(depth, false))
assertEquals(-kotlin.math.floor((depth + 1) / 2.0).toInt(), DrawProtocol.depthOffset(depth, true))
}
}
@Test fun roundedFillPreservesBrighterTextAndDepthClipsWithoutNibbleDamage() {
val pixels = ByteArray(32) { 0x11 }; pixels[13] = 0xf1.toByte()
val target = DisplayListRenderer.Target(pixels,8,8)
val fill = DrawProtocol.roundedRect(-1,0,8,8,2,6,16,2)
DisplayListRenderer(emptyMap()).execute(DrawProtocol.sequence(listOf(fill)),target)
assertEquals(15,target.get(2,3)); assertEquals(6,target.get(3,3)); assertEquals(1,target.get(0,0))
val bbox = DrawProtocol.call(DRAW_OP_BOUNDING_BOX,hex("00000002010f10"),depth=-1)
DisplayListRenderer(emptyMap()).execute(DrawProtocol.sequence(listOf(bbox)),target)
assertEquals(15,target.get(0,0));assertEquals(1,target.get(7,0))
val before=pixels.copyOf()
assertFails { DisplayListRenderer(emptyMap()).execute(DrawProtocol.sequence(listOf(byteArrayOf(8,2))),target) }
assertContentEquals(before,pixels)
}
@Test fun selectedMenuResourcesStayOutOfScreenAndReplayAtDepthTwo() {
val planner=ScenePlanner(ResourceCacheState()); val left=Glasses(); val right=Glasses(true)
val app=ByteArray(640*480/2) { 0x11 }
fun row(x:Int) = MenuSelection(x,8,8,4,1,4,9,2,hex("00ff0000000000000000000000000000"))
val scene=ShellScene(emptyList(),listOf(row(10)))
val first=planner.plan(app,640,480,null,scene,1);left.apply(first.commands);right.apply(first.commands)
assertContentEquals(app,left.screen);assertContentEquals(app,right.screen)
val l=DisplayListRenderer.Target(left.composition,640,480);val r=DisplayListRenderer.Target(right.composition,640,480)
assertEquals(15,l.get(13,8));assertEquals(15,r.get(11,8));assertEquals(1,l.get(9,8))
val moved=planner.plan(app,640,480,null,ShellScene(emptyList(),listOf(row(20))),1)
assertFalse(moved.commands.any { it[0].toInt()==26 || it[0].toInt()==29 })
left.apply(moved.commands);assertContentEquals(app,left.screen)
left.apply(planner.plan(app,640,480,null,ShellScene.EMPTY,1).commands)
assertContentEquals(app,left.composition)
}
@Test fun contextMenusAndSidebarDepthReplayOnBothLensesWithoutBakedCopies() {
fun record(kind: Int, x: Int, y: Int, w: Int, h: Int, depth: Int, gray: ByteArray): MenuSelection {
val bytes = DrawProtocol.word(x) + DrawProtocol.word(y) + DrawProtocol.word(w) + DrawProtocol.word(h) +
DrawProtocol.word(0) + byteArrayOf(16, 48, depth.toByte()) + DrawProtocol.word(0) + gray
return MenuSelection.read(ArrayByteReader(bytes), kind)
}
val menu = record(5, 10, 10, 8, 8, 4, ByteArray(64) { if (it == 0) 0 else 1 })
val selected = record(3, 12, 12, 4, 2, 6, ByteArray(8) { -1 })
val icon = record(4, 30, 10, 2, 2, -2, ByteArray(4) { -1 })
val app = ByteArray(640 * 480 / 2) { 0x66 }
val planner = ScenePlanner(ResourceCacheState())
val scene = ShellScene(emptyList(), listOf(menu, selected, icon))
val plan = planner.plan(app, 640, 480, null, scene, 1)
for (right in listOf(false, true)) {
val glasses = Glasses(right); glasses.apply(plan.commands)
assertContentEquals(app, glasses.screen)
val output = DisplayListRenderer.Target(glasses.composition,640,480)
val shift = if (right) -2 else 2
assertEquals(6, output.get(10 + shift,10)) // transparent corner
assertEquals(0, output.get(11 + shift,10)) // opaque black stays opaque
assertEquals(15, output.get(12 + (if (right) -3 else 3),12))
assertEquals(15, output.get(30 + (if (right) 1 else -1),10))
assertEquals(6, output.get(if (right) 30 else 31,10)) // no unshifted icon
val preview = scene.preview(ByteArray(640*480) { 96 },640,480,right)
assertContentEquals(glasses.composition, BmpUtil.pack4bppFromGray8(preview,640,480))
}
// The shell uses an independently owned surface with its own depth.
val shell = ShellScene(listOf(ShellScene.Layer(1,10,10,8,8,256,ByteArray(32),listOf(selected),4)))
val left = shell.preview(ByteArray(640*480) { 96 },640,480)
val right = shell.preview(ByteArray(640*480) { 96 },640,480,true)
assertEquals(0,left[10*640+12].toInt()); assertEquals(96,left[10*640+10].toInt())
assertEquals(0,right[10*640+8].toInt()); assertEquals(96,right[10*640+16].toInt())
}
private class Glasses(val right: Boolean = false) {
val resources=mutableMapOf<Int,ByteArray>(); val screen=ByteArray(640*480/2);val composition=ByteArray(screen.size)
var root=65535
fun apply(commands: List<ByteArray>) {
for(b in commands) when(b[0].toInt()) {
21 -> { var p=3;repeat(DrawProtocol.u16(b,1)) {
val id=DrawProtocol.u16(b,p); val total=DrawProtocol.u16(b,p+2) or (DrawProtocol.u16(b,p+4) shl 16)
val offset=DrawProtocol.u16(b,p+6);val n=DrawProtocol.u16(b,p+8)
b.copyInto(resources.getOrPut(id){ByteArray(total)},offset,p+10,p+10+n);p+=10+n
} }
22 -> repeat(DrawProtocol.u16(b,1)) { resources.remove(DrawProtocol.u16(b,3+it*2)) }
29 -> repeat(DrawProtocol.u16(b,1)) { val p=3+it*6;resources.getOrPut(DrawProtocol.u16(b,p)) { DrawProtocol.rawImage(DrawProtocol.u16(b,p+2),DrawProtocol.u16(b,p+4)) } }
26 -> DisplayListRenderer(resources, rightLens = right).execute(b.copyOfRange(1,b.size),DisplayListRenderer.Target(screen,640,480))
27 -> root=DrawProtocol.u16(b,1)
28 -> DisplayListRenderer(resources, rightLens = right).render(root,DisplayListRenderer.Target(screen,640,480),DisplayListRenderer.Target(composition,640,480))
else -> error("legacy command ${b[0]}")
}
}
}
@Test fun persistentShellUpdatesDoNotPolluteScreenAndClosingRevealsCurrentApp() {
val cache=ResourceCacheState();val planner=ScenePlanner(cache);val glasses=Glasses()
val app=ByteArray(640*480/2){0x99.toByte()}
val overlay=ShellScene(listOf(ShellScene.Layer(1,0,0,3,3,128,hex("fff0fff0fff0"))))
val first=planner.plan(app,640,480,null,overlay,1);glasses.apply(first.commands)
assertContentEquals(app,glasses.screen);assertEquals(255,glasses.composition[0].toInt() and 255)
// Half of level 9 is a 5/4 checkerboard; x=200 on row 0 is an even pixel.
assertEquals(0x54,glasses.composition[100].toInt() and 255)
val changed=ShellScene(listOf(ShellScene.Layer(1,0,0,3,3,128,hex("111011101110"))))
val repaint=planner.plan(app,640,480,null,changed,1)
assertFalse(repaint.commands.any { it[0].toInt() in listOf(21,22,29) })
glasses.apply(repaint.commands);assertContentEquals(app,glasses.screen)
val newer=app.copyOf();newer[0]=0x22
glasses.apply(planner.plan(newer,640,480,null,changed,1).commands)
glasses.apply(planner.plan(newer,640,480,null,ShellScene.EMPTY,1).commands)
assertContentEquals(newer,glasses.composition)
cache.reset();val reconnect=planner.plan(newer,640,480,null,changed,1)
assertTrue(reconnect.commands.any { it[0].toInt()==29 });glasses.apply(reconnect.commands)
assertContentEquals(newer,glasses.screen)
}
@Test fun fullScreenSurfaceDepthShiftsThePresentedScreenPerLens() {
val c = SurfaceCompositor()
c.configureScreen(640, 480)
c.configureSurface("app", 0, 0, 640, 480, 0, 0)
c.configureSurface("glance", 0, 0, 640, 480, 900, 0)
val board = ByteArray(640 * 480) { if (it % 640 in 100 until 110) 255.toByte() else 0 }
c.submitSurface("glance", ArrayByteReader(board), 0, 0, 640, 480, "board")
c.setSurfaceDepth("glance", 32)
assertEquals(32, c.composite().shellScene.screenDepth)
// Only the topmost visible surface counts, and only when it opaquely covers the screen.
c.configureSurface("partial", 0, 0, 10, 10, 950, 0)
assertEquals(0, c.composite().shellScene.screenDepth)
c.setSurfaceVisible("partial", false)
c.setSurfaceVisible("glance", false)
assertEquals(0, c.composite().shellScene.screenDepth)
c.setSurfaceVisible("glance", true)
val composite = c.composite()
val screen = BmpUtil.pack4bppFromGray8(composite.screenGray, 640, 480)
for (right in listOf(false, true)) {
val glasses = Glasses(right)
glasses.composition.fill(-1) // stale pixels from an earlier frame
glasses.apply(ScenePlanner(ResourceCacheState()).plan(screen, 640, 480, null, composite.shellScene, 1).commands)
assertContentEquals(screen, glasses.screen)
val output = DisplayListRenderer.Target(glasses.composition, 640, 480)
val shift = if (right) -16 else 16
assertEquals(15, output.get(100 + shift, 0)); assertEquals(0, output.get(99 + shift, 0))
assertEquals(15, output.get(109 + shift, 479)); assertEquals(0, output.get(110 + shift, 479))
assertEquals(0, output.get(if (right) 639 else 0, 240)) // cleared, not stale
}
}
@Test fun noisyFramesRemainBoundedAndResourceBudgetIs192KiB() {
val cache=ResourceCacheState();val planner=ScenePlanner(cache);val glasses=Glasses()
val app=ByteArray(640*480/2){(it*37).toByte()}
val plan=planner.plan(app,640,480,null,ShellScene.EMPTY,1)
assertTrue(plan.commands.all { it.size<=65535 });glasses.apply(plan.commands)
assertContentEquals(app,glasses.screen);assertContentEquals(app,glasses.composition)
assertEquals(196608,ResourceCacheState.CACHE_SIZE)
}
/** Revision 35. Same calls and expectations as ClipTest in g2flash/tests/test_display_list.py. */
@Test fun clipRectsNarrowEveryOpNestThroughListsAndMoveWithDepth() {
val font = ByteArray(198); font[0] = 1; font[1 + 33 * 2] = 193.toByte(); hex("000202ffff").copyInto(font, 193)
val resources = mutableMapOf(1 to hex("000404ffffffffffffffff"), 3 to font,
5 to hex("0202000700" + "0400010000000f" + "0f00" + "04040900000002000200010008000f"),
6 to hex("00040200000000"), 7 to hex("0201000e00080106000000040002000000" + "0f10"))
fun draw(call: String, right: Boolean = false): DisplayListRenderer.Target {
val target = DisplayListRenderer.Target(ByteArray(64) { 0x11 }, 16, 8)
DisplayListRenderer(resources, rightLens = right).execute(DrawProtocol.sequence(listOf(hex(call))), target)
return target
}
fun expect(target: DisplayListRenderer.Target, color: Int, inside: (Int, Int) -> Boolean) {
for (y in 0 until 8) for (x in 0 until 16) assertEquals(if (inside(x, y)) color else 1, target.get(x, y), "($x, $y)")
}
expect(draw("040403000200" + "0a000a00" + "0100" + "0201" + "0f"), 15) { x, y -> x in 3..5 && y in 2..4 }
expect(draw("0400" + "0100" + "ff020105" + "00" + "0f"), 15) { x, y -> x in 5..8 && y < 4 }
expect(draw("0504" + "0100000002000100" + "0300" + "0000" + "0f" + "02" + "4141"), 15) { x, y -> y == 0 && x in 1..2 }
expect(draw("0804" + "0400040004000200" + "0000" + "1000" + "0800" + "0000" + "0f10"), 15) { x, y -> x in 4..7 && y in 4..5 }
expect(draw("0904" + "fefffeff04000400" + "09"), 9) { x, y -> x < 2 && y < 2 }
expect(draw("0904" + "0300050003000100" + "09"), 9) { x, y -> y == 5 && x in 3..5 }
expect(draw("0604" + "0100010001000600" + "0000000010000800" + "77".repeat(16)), 7) { x, y -> x == 1 && y in 1..6 }
expect(draw("0204" + "0200020001000100" + "0100" + "0000" + "04000400" + "0000"), 15) { x, y -> x == 2 && y == 2 }
expect(draw("0104" + "0100010002000100" + "00" + "000001" + "01" + "8f"), 15) { x, y -> y == 1 && x in 1..2 }
expect(draw("0704" + "000000000a000300" + "0500"), 15) { x, y -> (x < 4 && y < 3) || (x == 9 && y < 2) }
val deep = "0806" + "02" + "0000000004000400" + "0000" + "1000" + "0800" + "0000" + "0f10"
expect(draw(deep), 15) { x, y -> x in 1..4 && y < 4 }
expect(draw(deep, right = true), 15) { x, y -> x < 3 && y < 4 }
// A target override starts unclipped: the whole resource fills, the screen stays.
expect(draw("0704" + "0000000001000100" + "0700"), 15) { _, _ -> false }
assertContentEquals(hex("000402ffffffff"), resources.getValue(6))
expect(draw("0804" + "0400040000000000" + "0000" + "1000" + "0800" + "0000" + "0f10"), 15) { _, _ -> false }
// Unknown flag bits, a truncated clip header, and the old s16 image layout all reject.
for (bad in listOf("090800", "0904000000000100", "04000100020001000f")) assertFails(bad) { draw(bad) }
}
}
@@ -0,0 +1,113 @@
package com.faceclaw.app
import kotlin.test.*
class DrawExpressionTest {
private fun hex(s: String) = s.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
private fun evaluate(code: ByteArray, elapsed: Long = 0): Pair<Int, Boolean> {
val frame = DrawEvaluation(elapsed)
return DrawExpression.evaluate(DrawReader(code), frame) to frame.animationPending
}
@Test fun integerWidthsSignExtensionAndReservedPrefixes() {
val signed = mapOf(
0 to "00", 63 to "3f", -64 to "40", -1 to "7f", 64 to "8040", -65 to "bfbf",
8191 to "9fff", -8192 to "a000", 8192 to "c02000", -8193 to "dfdfff",
1048575 to "cfffff", -1048576 to "d00000", 1048576 to "e0100000",
-1048577 to "efefffff", 134217727 to "e7ffffff", -134217728 to "e8000000",
134217728 to "f008000000", Int.MAX_VALUE to "f07fffffff", Int.MIN_VALUE to "f080000000",
)
for ((number, bytes) in signed) {
assertContentEquals(hex(bytes), ExtendedVarint.signed(number))
assertEquals(number, ExtendedVarint.read(DrawReader(hex(bytes)), true))
}
for (value in listOf(0u, 127u, 128u, 16383u, 16384u, 2097151u, 2097152u, 268435455u, 268435456u, UInt.MAX_VALUE)) {
val bytes = ExtendedVarint.unsigned(value)
assertEquals(value, ExtendedVarint.read(DrawReader(bytes), false).toUInt())
for (n in 0 until bytes.size) assertFails { ExtendedVarint.read(DrawReader(bytes.copyOf(n)), false) }
}
for (prefix in 0xf1..0xff) assertFails { ExtendedVarint.read(DrawReader(byteArrayOf(prefix.toByte())), true) }
assertEquals(-1, ExtendedVarint.read(DrawReader(hex("bfff")), true)) // valid non-minimal form
assertFails { ExtendedVarint.evaluate(DrawReader(hex("ff05")), DrawEvaluation(0)) }
}
@Test fun arithmeticTypesStackErrorsAndTimeTracking() {
val vectors = listOf(
"0107010510" to 12, "0107010511" to 2, "0107010512" to 35,
"0179010213" to -3, "0179010214" to -1, "017915" to 7,
"0107010516" to 5, "0107010517" to 7, "01010109" to 9,
"01040310" to 8, "010401070504" to 7,
"010430010230202431" to -6,
"020000c03f02000000402231" to 3,
"01003001806430020000003f4031" to 50,
"01f07fffffff010110" to Int.MIN_VALUE,
"01f080000000017f13" to Int.MIN_VALUE,
"01f080000000017f14" to 0,
)
for ((code, expected) in vectors) assertEquals(expected to false, evaluate(hex(code)), code)
for (bad in listOf("", "10", "0101010013", "010130010110", "020000807f", "ff", "0180", "01013210")) {
assertEquals(0 to false, evaluate(hex(bad)), bad)
}
assertEquals(0 to false, evaluate(ByteArray(66) { if (it % 2 == 0) 1 else 0 })) // stack overflow
assertEquals(0 to false, evaluate(ByteArray(1025)))
for (op in DrawExpression.SMOOTHSTEP..DrawExpression.EASE_IN_OUT_CUBIC) {
assertEquals(0 to false, evaluate(hex("0200000000") + byteArrayOf(op.toByte(), 49)))
assertEquals(1 to false, evaluate(hex("020000803f") + byteArrayOf(op.toByte(), 49)))
}
assertEquals(499 to true, evaluate(hex("0181f432"), 499))
assertEquals(500 to false, evaluate(hex("0181f432"), 500))
assertEquals(500 to false, evaluate(hex("0181f432"), 900))
assertEquals(0 to false, evaluate(hex("0181f432ff"), 250)) // errors discard pending time
}
@Test fun smoothstepCoordinatesMatchFirmwareAndSurvivePresentTimeReset() {
val value = DrawValue.animate(10, 110, 500) as DrawValue.Expression
val code = "010a3001806e300181f432010010300181f43023414031"
assertContentEquals(hex(code), value.program)
for ((time, expected) in listOf(0L to 10, 125L to 25, 250L to 60, 375L to 94, 500L to 110, 900L to 110)) {
assertEquals(expected to (time < 500), evaluate(value.program, time))
}
val continued = DrawValue.animate(10, 110, 500, elapsedMs = 250) as DrawValue.Expression
assertEquals(60 to true, evaluate(continued.program, 0))
assertEquals(110 to false, evaluate(continued.program, 250))
}
@Test fun playerSchedulesOnlyUnfinishedFramesAndCancelsStaleCallbacks() {
val call = DrawProtocol.roundedRect(DrawValue.Integer(0), DrawValue.animate(0, 4, 300), 2, 2, 0, 15)
val renderer = DisplayListRenderer(mapOf(1 to DrawProtocol.displayList(DrawProtocol.screenCopy(4, 8) + call)))
val screen = DisplayListRenderer.Target(ByteArray(16), 4, 8)
val output = DisplayListRenderer.Target(ByteArray(16), 4, 8)
var now = 1000L
val queued = mutableListOf<() -> Unit>()
var cancelled = 0
var displayed = 0
val player = DisplayListPlayer(renderer, screen, output, { now }, { delay, callback ->
assertEquals(45, delay)
queued.add(callback);
{ cancelled++ }
}, { displayed++ })
player.present(1)
assertEquals(15, output.get(0, 0))
val first = queued.removeAt(0)
now += 150
first()
assertEquals(15, output.get(0, 2))
assertEquals(0, output.get(0, 0))
val stale = queued.removeAt(0)
player.present(1)
assertEquals(15, output.get(0, 0))
stale()
assertEquals(3, displayed)
now += 300
queued.removeAt(0)()
assertEquals(15, output.get(0, 4))
assertFalse(renderer.animationPending)
assertTrue(queued.isEmpty())
player.present(1)
val stopped = queued.removeAt(0)
player.stop()
stopped()
assertEquals(5, displayed)
assertTrue(cancelled >= 2)
}
}
@@ -0,0 +1,139 @@
package com.faceclaw.app
import kotlin.test.*
class DrawWireTest {
private fun hex(value: String) = value.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
@Test fun encodersUseRevision35CoordinatesAndPreserveOtherWireBytes() {
// Literal vectors pin the firmware grammar independently of the reader.
val calls = listOf(
DrawProtocol.image(0x1234, -32768, 32767, 0x1f, target = 511, depth = -128) to
"0403ff01803412df8000c07fff1f",
DrawProtocol.rectCopy(DrawProtocol.CURRENT, 1, 2, 3, 4, -5, -6) to
"0200feff0102030004007b7a",
DrawProtocol.stockText(-1, 2, 15, hex("41c3a9")) to "0300ffff02000f0341c3a9",
DrawProtocol.text(511, -2, 3, 31, hex("01417f")) to "0500ff017e031f0301417f",
DrawProtocol.playList(511, depth = 127) to "07027fff01",
DrawProtocol.roundedRect(-1, 2, 640, 480, 65535, 15, 16) to
"08007f028002e001ffff0f10",
DrawProtocol.lut(640, 480, 256) to "0600000000008002e0010123456789abcdef0123456789abcdef",
DrawProtocol.bbox(hex("ffffffffffffffff"), 4, 0, 0, 8, 2) to "010000000002010f10",
DrawProtocol.bbox(hex("0f"), 1, 1, 0, 1, 1) to "01000101000000010001001f",
DrawProtocol.clear(15, target = 511) to "0901ff010f",
// Revision 35: the clip rect follows target and depth.
DrawProtocol.clear(3, target = 511, clip = DrawClip(-1, 2, 3, 4)) to "0905ff01ffff02000300040003",
DrawProtocol.image(7, 1, 2, depth = 2, clip = DrawClip(0, 0, 640, 480)) to "040602000000008002e001070001020f",
)
for ((call, expected) in calls) assertContentEquals(hex(expected), call)
assertContentEquals(hex("0100050007027fff01"), DrawProtocol.sequence(listOf(calls[4].first)))
assertContentEquals(hex("1a0100050007027fff01"), DrawProtocol.message(listOf(calls[4].first)))
assertContentEquals(hex("020100050007027fff01"), DrawProtocol.displayList(listOf(calls[4].first)))
assertContentEquals(hex("1bffff"), DrawProtocol.root(DrawProtocol.SCREEN))
val flat = DrawProtocol.screenCopy(640, 352)
assertEquals(1, flat.size)
assertContentEquals(hex("0200ffff0000800260010000"), flat[0])
val shifted = DrawProtocol.screenCopy(640, 352, -32)
assertEquals(2, shifted.size)
assertContentEquals(hex("090000"), shifted[0])
assertContentEquals(hex("0202e0ffff0000800260010000"), shifted[1])
}
@Test fun optimizerFieldsAreReencodedAndOpaqueBytesArePreserved() {
val records = listOf(
"1300020080ff7f1f" to "04000002df8000c07fff1f",
"14ff01ffff02000f0341017f" to "0500ff017f020f0341017f",
"0fffff02001f0341c3a9" to "0300ffff02001f0341c3a9",
"030001020134120f10" to "010000000102010f10",
"060f10" to "01000100000000080002000f10",
"090100020003000400fbfffaff" to "0200feff0102030004007b7a",
)
for ((record, expected) in records) {
val calls = DrawProtocol.fromOptimized(hex(record), 8, 2)
assertEquals(1, calls.size)
assertContentEquals(hex(expected), calls.single(), record)
}
val nested = hex("0802") + records.take(2).fold(byteArrayOf()) { bytes, (record, _) ->
val payload = hex(record)
bytes + DrawProtocol.word(payload.size) + payload
}
val calls = DrawProtocol.fromOptimized(nested)
assertEquals(2, calls.size)
for (i in calls.indices) assertContentEquals(hex(records[i].second), calls[i])
assertFails { DrawProtocol.fromOptimized(hex("1300020080ff7f")) }
assertFails { DrawProtocol.fromOptimized(hex("1300020080ff7f1f00")) }
assertFails { DrawProtocol.fromOptimized(hex("0fffff02001f0441c3a9")) }
}
@Test fun everyTruncatedOrOverlongCallIsRejectedBeforeMutation() {
val font = ByteArray(197)
font[0] = 1
font[67] = 193.toByte() // Glyph A.
hex("0801011f").copyInto(font, 193)
val resources = mapOf(
1 to hex("0401000100f0"),
2 to font,
3 to DrawProtocol.displayList(emptyList()),
)
val renderer = DisplayListRenderer(resources, builtin = { _, _ ->
DisplayListRenderer.BuiltinGlyph(hex("0801011f"), 1)
})
val calls = listOf(
DrawProtocol.image(1, 0, 0, target = 1, depth = -1),
DrawProtocol.rectCopy(DrawProtocol.CURRENT, 0, 0, 2, 2, 1, 1),
DrawProtocol.stockText(0, 0, 15, hex("41")),
DrawProtocol.text(2, 0, 0, 15, hex("41")),
DrawProtocol.playList(3),
DrawProtocol.roundedRect(0, 0, 4, 4, 1, 15),
DrawProtocol.lut(8, 4, 128),
DrawProtocol.bbox(ByteArray(16) { -1 }, 4, 0, 0, 8, 4),
)
val screen = ByteArray(16) { 0x12 }
val target = DisplayListRenderer.Target(screen, 8, 4)
val valid = DrawProtocol.roundedRect(0, 0, 4, 4, 0, 15)
for (call in calls) {
// Establish that each fixture is valid before testing malformed forms.
renderer.execute(DrawProtocol.sequence(listOf(call)), target)
screen.fill(0x12)
val savedResources = resources.mapValues { it.value.copyOf() }
val malformed = (0 until call.size).map { call.copyOf(it) } + listOf(call + byteArrayOf(0))
for (bad in malformed) {
assertFails { renderer.execute(DrawProtocol.sequence(listOf(valid, bad, valid)), target) }
assertContentEquals(ByteArray(16) { 0x12 }, screen)
for ((id, bytes) in savedResources) assertContentEquals(bytes, resources[id])
}
}
val sequence = DrawProtocol.sequence(listOf(valid))
for (length in 0 until sequence.size) {
assertFails { renderer.execute(sequence.copyOf(length), target) }
assertContentEquals(ByteArray(16) { 0x12 }, screen)
}
assertFails { renderer.execute(sequence + byteArrayOf(0), target) }
assertContentEquals(ByteArray(16) { 0x12 }, screen)
}
@Test fun batchesRespectEncodedLengthsAndCallBudget() {
val call = DrawProtocol.playList(511)
val messages = DrawProtocol.messages(List(3) { call }, maxBytes = 15)
assertEquals(listOf(15, 9), messages.map { it.size })
assertContentEquals(hex("1a020004000700ff0104000700ff01"), messages[0])
assertFails { DrawProtocol.messages(listOf(call), maxBytes = 8) }
val many = DrawProtocol.messages(List(4097) { call })
assertEquals(listOf(4096, 1), many.map { DrawProtocol.u16(it, 1) })
assertTrue(DrawProtocol.messages(emptyList()).isEmpty())
}
@Test fun resourceReaderViewsUseRelativeOffsetsAndCannotEscapeTheirBounds() {
val reader = ArrayByteReader(hex("ff123456ee"), 1, 4)
assertEquals(0x12.toByte(), reader.get(0))
assertEquals(0x3412.toShort(), reader.getShort())
assertEquals(1, reader.remaining())
assertFails { reader.get(ByteArray(2)) }
assertEquals(0x56.toByte(), reader.get())
assertEquals(0, reader.remaining())
assertFails { reader.get() }
assertFails { reader.get(3) }
assertFails { reader.get(-1) }
assertFails { ArrayByteReader(byteArrayOf(1), 1, 2) }
}
}
@@ -0,0 +1,47 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
class EvenHubAssetServerTest {
@Test
fun resolvesPathsWithIndexDefaultAndEscapeChecks() {
assertEquals("index.html", EvenHubAssetServer.resolve(null)!!.relativePath)
assertEquals("index.html", EvenHubAssetServer.resolve("")!!.relativePath)
assertEquals("index.html", EvenHubAssetServer.resolve("/")!!.relativePath)
assertEquals("assets/app.js", EvenHubAssetServer.resolve("/assets/app.js")!!.relativePath)
assertEquals("assets/app.js", EvenHubAssetServer.resolve("/assets/./x/../app.js")!!.relativePath)
assertNull(EvenHubAssetServer.resolve("/../secret"))
assertNull(EvenHubAssetServer.resolve("/a/../../secret"))
assertNull(EvenHubAssetServer.resolve("/.."))
assertTrue(EvenHubAssetServer.resolve("/index.html")!!.isHtml)
assertTrue(EvenHubAssetServer.isInsideRoot("/apps/x", "/apps/x/index.html"))
assertTrue(EvenHubAssetServer.isInsideRoot("/apps/x/", "/apps/x/a/b"))
assertEquals(false, EvenHubAssetServer.isInsideRoot("/apps/x", "/apps/xy/index.html"))
assertEquals(false, EvenHubAssetServer.isInsideRoot("/apps/x", "/apps/index.html"))
}
@Test
fun mimeTableCoversBothPlatformsTables() {
assertEquals("text/html", EvenHubAssetServer.mimeTypeFor("Index.HTM"))
assertEquals("text/javascript", EvenHubAssetServer.mimeTypeFor("bundle.mjs"))
assertEquals("application/wasm", EvenHubAssetServer.mimeTypeFor("core.wasm"))
assertEquals("font/woff2", EvenHubAssetServer.mimeTypeFor("a.woff2"))
assertEquals("image/svg+xml", EvenHubAssetServer.mimeTypeFor("icon.svg"))
assertEquals("text/plain", EvenHubAssetServer.mimeTypeFor("bundle.js.map"))
assertEquals("application/octet-stream", EvenHubAssetServer.mimeTypeFor("blob"))
assertEquals("application/octet-stream", EvenHubAssetServer.mimeTypeFor("weird.xyz"))
}
@Test
fun injectsShimAfterHeadOrAtStart() {
assertEquals(
"<!doctype html><HEAD lang=\"x\"><script>S</script><title>t</title></HEAD>",
EvenHubAssetServer.injectIntoHtml("<!doctype html><HEAD lang=\"x\"><title>t</title></HEAD>", "S"),
)
assertEquals("<script>S</script><body>x</body>", EvenHubAssetServer.injectIntoHtml("<body>x</body>", "S"))
assertEquals("<script>S</script><head", EvenHubAssetServer.injectIntoHtml("<head", "S"), "unterminated head tag")
}
}
@@ -0,0 +1,118 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
class FirmwareImageTest {
private fun putU32(buf: ByteArray, offset: Int, value: Long) {
for (i in 0 until 4) buf[offset + i] = ((value ushr (8 * i)) and 0xff).toByte()
}
private class Component(val name: String, val payload: ByteArray)
/** Builds a checksum-fixed container; [tamper] runs before the CRCs are recorded. */
private fun container(components: List<Component>, tamper: (ByteArray) -> Unit = {}): ByteArray {
val count = components.size
val toc = FirmwareImage.HEADER_SIZE + count * FirmwareImage.TOC_ENTRY_SIZE
var offset = toc
val offsets = components.map { c -> offset.also { offset += FirmwareImage.SUBHEADER_SIZE + c.payload.size } }
val img = ByteArray(offset)
putU32(img, 8, count.toLong())
components.forEachIndexed { i, c ->
val off = offsets[i]
putU32(img, FirmwareImage.HEADER_SIZE + i * 16 + 4, off.toLong())
putU32(img, off + 8, c.payload.size.toLong())
c.name.encodeToByteArray().copyInto(img, off + FirmwareImage.NAME_OFFSET)
c.payload.copyInto(img, off + FirmwareImage.SUBHEADER_SIZE)
}
tamper(img)
components.forEachIndexed { i, c ->
val off = offsets[i]
val crc = FirmwareImage.crc32cUnsigned(img, off + FirmwareImage.SUBHEADER_SIZE, c.payload.size)
putU32(img, FirmwareImage.HEADER_SIZE + i * 16 + 12, crc)
putU32(img, off + 12, crc)
}
return img
}
private fun mainApp(size: Int): ByteArray {
val payload = ByteArray(size) { (it * 7).toByte() }
putU32(payload, 0, size.toLong())
putU32(payload, 0x14, FirmwareImage.APP_LOAD_ADDR)
return payload
}
private fun validComponents(): List<Component> =
listOf(
Component("ota/bootloader.bin", ByteArray(300) { it.toByte() }),
Component("ota/a.bin", ByteArray(64) { 1 }),
Component("ota/b.bin", ByteArray(128) { 2 }),
Component("ota/c.bin", ByteArray(32) { 3 }),
Component(FirmwareImage.REQUIRED_SEGMENT, mainApp(600)),
)
@Test
fun crc32cMatchesKnownVector() {
// Castagnoli polynomial, MSB-first, init 0, no reflection or final xor (g2flash.py
// crc32c_msb); vectors from an independent Python implementation of that definition.
assertEquals(0xc052a8c8L, FirmwareImage.crc32cUnsigned("123456789".encodeToByteArray()))
assertEquals(0xd7b91914L, FirmwareImage.crc32cUnsigned(ByteArray(256) { it.toByte() }))
assertEquals(0L, FirmwareImage.crc32cUnsigned(ByteArray(0)))
assertEquals(FirmwareImage.crc32cUnsigned("23456789".encodeToByteArray()), FirmwareImage.crc32cUnsigned("123456789".encodeToByteArray(), 1, 8))
}
@Test
fun validImageParsesAllComponents() {
val segs = FirmwareImage.validate(container(validComponents()))
assertEquals(5, segs.size)
assertEquals(listOf(300, 64, 128, 32, 600), segs.map { it.ps })
assertEquals(FirmwareImage.REQUIRED_SEGMENT, segs[4].name)
assertTrue(segs.zipWithNext().all { (a, b) -> a.end <= b.off })
}
@Test
fun rejectsStaleCrc() {
val img = container(validComponents())
img[img.size - 1] = (img[img.size - 1] + 1).toByte()
assertTrue(assertFailsWith<IllegalStateException> { FirmwareImage.validate(img) }.message!!.contains("CRC32C"))
}
@Test
fun rejectsOverlappingComponents() {
val img = container(validComponents()) { buf ->
// Point component 1's TOC entry at component 0, so both claim the same bytes.
val off0 = FirmwareImage.readU32(buf, FirmwareImage.HEADER_SIZE + 4)
putU32(buf, FirmwareImage.HEADER_SIZE + 16 + 4, off0)
}
assertTrue(assertFailsWith<IllegalStateException> { FirmwareImage.parseSegments(img) }.message!!.contains("overlap"))
}
@Test
fun rejectsTruncatedPayload() {
val img = container(validComponents())
val truncated = img.copyOf(img.size - 10)
assertTrue(assertFailsWith<IllegalStateException> { FirmwareImage.parseSegments(truncated) }.message!!.contains("truncated"))
assertFailsWith<IllegalStateException> { FirmwareImage.parseSegments(ByteArray(0x10)) }
}
@Test
fun rejectsWrongComponentCountAndMissingMain() {
val four = validComponents().dropLast(1)
assertTrue(assertFailsWith<IllegalStateException> { FirmwareImage.validate(container(four)) }.message!!.contains("components"))
val noMain = validComponents().dropLast(1) + Component("ota/other.bin", ByteArray(40))
assertTrue(assertFailsWith<IllegalStateException> { FirmwareImage.validate(container(noMain)) }.message!!.contains("not found"))
}
@Test
fun rejectsMainAppBeyondMramCeiling() {
val ceiling = (FirmwareImage.APP_MAX_END - FirmwareImage.APP_LOAD_ADDR + FirmwareImage.APP_PREAMBLE).toInt()
val fits = validComponents().dropLast(1) + Component(FirmwareImage.REQUIRED_SEGMENT, mainApp(ceiling))
FirmwareImage.validate(container(fits))
val tooBig = validComponents().dropLast(1) + Component(FirmwareImage.REQUIRED_SEGMENT, mainApp(ceiling + 1))
assertTrue(assertFailsWith<IllegalStateException> { FirmwareImage.validate(container(tooBig)) }.message!!.contains("MRAM"))
val badAddr = validComponents().dropLast(1) + Component(FirmwareImage.REQUIRED_SEGMENT, mainApp(600).also { putU32(it, 0x14, 0x1234L) })
assertTrue(assertFailsWith<IllegalStateException> { FirmwareImage.validate(container(badAddr)) }.message!!.contains("load address"))
}
}
@@ -0,0 +1,22 @@
package com.faceclaw.app
import kotlin.test.*
class FontTest {
@Test
fun bundledFontMatchesJavaMetricsAndGlyphs() {
assertContentEquals(byteArrayOf(25, 19), LvglFontFile.getMetrics(TEST_FONT_PATH))
val vectors =
mapOf(
0x25a6 to "b08ecb603fd059b0a00ba3088f18b79185c421e73049797cd3cb0828e1e5cd04",
0x25c6 to "c176d5dcdb5f7e3a7220455528efde3760672c40cee39b422fc3f5ad20df66dd",
0x4e2d to "9bde2c8f1ffcf7afc598f4d0350c9ff262484816aa0c9b46d31f0c3c09613003",
0xff21 to "0074f96299a75b86912282416e47e0823790e091352aec852eff49b89b2e719d",
)
vectors.forEach { (codePoint, expected) ->
assertEquals(expected, digest(LvglFontFile.getGlyph(TEST_FONT_PATH, codePoint)))
}
assertTrue(LvglFontFile.getGlyph(TEST_FONT_PATH, 0x10ffff).isEmpty())
assertTrue(LvglFontFile.getMetrics("/nonexistent/faceclaw-font").isEmpty())
}
}
@@ -0,0 +1,69 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
class FoundationTest {
@Test
fun jsonRoundTripsObjectsArraysAndNumbers() {
val text = """{"a":1,"b":[true,null,"x\ny"],"c":{"d":2.5,"e":-3}}"""
val value = Json.parseObject(text)
assertEquals(1, value["a"].asInt())
assertEquals(listOf(true, null, "x\ny"), value["b"].asArray())
assertEquals(2.5, value["c"].asObject()!!["d"].asDouble())
assertEquals(-3L, value["c"].asObject()!!["e"].asLong())
assertEquals(text, Json.write(value))
assertEquals("[1,2,\"q\\\"\"]", Json.write(listOf(1, 2L, "q\"")))
assertEquals("1", JsonNumber.of(1.0).text)
assertEquals("1.5", JsonNumber.of(1.5).text)
assertNull("x".asInt())
}
@Test
fun sha256MatchesKnownVector() {
assertEquals("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", sha256Hex("abc".encodeToByteArray()))
val incremental = Sha256Digest()
incremental.update("a".encodeToByteArray())
incremental.update("bc".encodeToByteArray())
assertEquals(sha256("abc".encodeToByteArray()).toList(), incremental.digest().toList())
}
@Test
fun latchAndQueueHandOffAcrossThreads() {
val platform = testPlatform()
val latch = Latch(1, platform)
val queue = BlockingQueue<String>(platform)
assertFalse(latch.await(20))
startThread("foundation-test", true) {
sleepMs(20)
queue.put("hello")
latch.countDown()
}
assertEquals("hello", queue.poll(2000))
assertTrue(latch.await(2000))
assertNull(queue.poll(10))
}
@Test
fun interruptibleSleepConsumesEarlyInterrupt() {
val platform = testPlatform()
val sleep = InterruptibleSleep(platform)
sleep.interrupt()
val start = platform.elapsedRealtimeMs()
assertFalse(sleep.sleep(500))
assertTrue(platform.elapsedRealtimeMs() - start < 400)
assertTrue(sleep.sleep(5))
startThread("foundation-wake", true) { sleepMs(30); sleep.interrupt() }
assertFalse(sleep.sleep(5000))
}
@Test
fun wallClockFormatsPattern() {
val text = formatLocalTime(0L, "yyyy")
assertTrue(text == "1970" || text == "1969", text)
assertTrue(currentTimeMillis() > 1_600_000_000_000L)
}
}
@@ -0,0 +1,149 @@
package com.faceclaw.app
import kotlin.test.*
class FrameDisplayListTest {
// Golden records emitted by display-list-authoring.test.cjs.
private val menu = "077e0000000300020002000200022a00000096000000010002000200ffffffff0200080000ff24017e30020000000001812c8001812c1611010017328001812c16103001812c3023414031ff24017c30020000000001812c8001812c1611010017328001812c16103001812c302341403102000200010001030400000000000000001f"
private val multi = "0744000000030002000400010002000000000000000002000200010000ff010001006003000400000000000000001f0200000100000001000100020002feffffff7f00010001007f00"
private val scroll = "078a000000030002000400020000070000009600000001000200040011223344556677880200020000000000ff250100300102300180f0800180f0161101001732800180f01610300180f0302341403101001102000200010008000000ff280101300100300180f0800180f0161101001732800180f01610300180f030234140310100170100160400020000000103"
// Clipped clear, clipped rounded rect, and replayed glyph + icon records with
// placeholder atlas ids 0xbeef / 0xcafebabe, plus what they paint over a
// nibble-1 16x8 screen (display-list-authoring.test.cjs).
private val replay = "0780000000020003000800040000070000006400000000000300890000000000000600040002880000010001000200020000000400030000000510a00000000000000600040000ff2502000080c002000000000180c8800180c8161101001732800180c81610300180c830234031020000efbe4100000000000000ff01bebafeca04000100"
private val replayPixels = "11111111111111111111111111111111111111111111111111fff28f111111111125522211111111112552221111111111222222111111111111111111111111"
private fun hex(s: String) = s.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
private fun read(bytes: ByteArray, now: Long = 1150): FrameDisplayList {
val reader = ArrayByteReader(bytes)
assertEquals(DrawRecordKind.DISPLAY_LIST, reader.get().toInt())
return FrameDisplayList.read(reader, now).also { assertEquals(0, reader.remaining()) }
}
@Test fun authoredExpressionsRebindOnPresentAndTranslateWithTheSurface() {
val row = read(hex(menu)).translated(10, 10)
assertEquals(1, row.resources.size)
fun coordinates(now: Long, elapsed: Long): Triple<Int, Int, Boolean> {
val call = DrawReader(row.calls(intArrayOf(7), now).first())
assertEquals(DRAW_OP_ROUNDED_RECT, call.readU8())
assertEquals(DRAW_FLAG_DEPTH, call.readU8())
assertEquals(2, call.readS8())
val frame = DrawEvaluation(elapsed)
val x = ExtendedVarint.evaluate(call, frame)
val y = ExtendedVarint.evaluate(call, frame)
return Triple(x, y, frame.animationPending)
}
assertEquals(Triple(12, 10, true), coordinates(1150, 0))
assertEquals(Triple(13, 12, false), coordinates(1150, 150))
assertEquals(coordinates(1150, 75), coordinates(1225, 0), "another PRESENT preserves progress")
assertEquals(Triple(13, 12, false), coordinates(1400, 0))
val later = hex(menu).also { it[18] = 200.toByte() } // envelope 5 + elapsed offset 13
assertEquals(read(hex(menu)).fingerprint, read(later).fingerprint)
val other = hex(menu).also { it[14] = 43 } // timeline token
assertNotEquals(read(hex(menu)).fingerprint, read(other).fingerprint)
}
@Test fun animatedCopySourcesRebindOnPresentAndDestinationsTranslate() {
// Emitted by menu-scroll-animation.test.cjs: a menu strip scrolling from row 0 to row 2.
val list = read(hex(scroll)).translated(10, 10)
fun copy(elapsed: Long): List<Int> {
val call = DrawReader(list.calls(intArrayOf(5), 1150).first())
assertEquals(DRAW_OP_RECT_COPY, call.readU8())
assertEquals(DRAW_FLAG_DEPTH, call.readU8())
assertEquals(0, call.readS8())
val frame = DrawEvaluation(elapsed)
val values = listOf(call.readU16(), ExtendedVarint.evaluate(call, frame), ExtendedVarint.evaluate(call, frame),
call.readU16(), call.readU16(), ExtendedVarint.evaluate(call, frame), ExtendedVarint.evaluate(call, frame))
call.requireDone()
return values + if (frame.animationPending) 1 else 0
}
// 150 of 240 ms elapsed before this PRESENT; the source row is not translated with the surface.
assertEquals(listOf(5, 0, 1, 2, 2, 14, 12, 1), copy(0))
assertEquals(listOf(5, 0, 2, 2, 2, 14, 12, 0), copy(90))
}
@Test fun localResourceIdsAreResolvedAndScreenCopiesStayAtScreenDepth() {
val list = read(hex(multi)).translated(10, 10)
val calls = list.calls(intArrayOf(41, 42), 1150)
assertContentEquals(DrawProtocol.image(41, 13, 12, 31, depth = 2), calls[0])
assertContentEquals(DrawProtocol.rectCopy(42, 0, 0, 1, 1, 15, 12, depth = 2), calls[1])
assertContentEquals(DrawProtocol.rectCopy(DrawProtocol.SCREEN, 12, 12, 1, 1, 12, 12, depth = 0), calls[2])
val scene = ShellScene(emptyList(), listOf(read(hex(multi))))
assertEquals(2, scene.retainedResources.size)
for (right in listOf(false, true)) {
val pixels = scene.preview(ByteArray(64) { 32 }, 8, 8, right)
assertEquals(240, pixels[16 + if (right) 3 else 5].toInt() and 255)
assertEquals(96, pixels[16 + if (right) 4 else 6].toInt() and 255)
assertEquals(32, pixels[18].toInt() and 255)
}
val cache = ResourceCacheState()
val planner = ScenePlanner(cache)
val screen = ByteArray(32) { 0x22 }
planner.plan(screen, 8, 8, null, scene, 1)
val ids = scene.retainedResources.map { cache.resourceId(it) }
assertTrue(ids.all { it >= 0 }); assertNotEquals(ids[0], ids[1])
planner.plan(screen, 8, 8, null, scene, 1)
assertEquals(ids, scene.retainedResources.map { cache.resourceId(it) })
}
@Test fun frameAndShellSubmissionUseTheSameGenericDecoder() {
val c = SurfaceCompositor()
c.configureScreen(8, 8)
c.configureSurface("app", 0, 0, 8, 8, 0, 0)
c.submitSurface("app", ArrayByteReader(ByteArray(64) { 32 }), 0, 0, 8, 8, "list",
ArrayByteReader(hex(multi)))
val frame = c.composite()
assertEquals(2, frame.shellScene.retainedResources.size)
assertEquals(240, frame.gray[21].toInt() and 255)
assertTrue(frame.screenGray.all { it.toInt() == 32 })
// One opaque 1x1 shell layer, with one generic list after its pixels.
val layer = DrawProtocol.word(1) + DrawProtocol.word(1) + DrawProtocol.word(0) + DrawProtocol.word(0) +
DrawProtocol.word(1) + DrawProtocol.word(1) + DrawProtocol.word(256) + DrawProtocol.word(1) +
DrawProtocol.word(0) + byteArrayOf(32) + hex(multi)
val shell = ShellScene.decode(ArrayByteReader(layer))
assertEquals(2, shell.retainedResources.size)
assertEquals(240, shell.preview(ByteArray(64) { 32 }, 8, 8)[21].toInt() and 255)
}
@Test fun rejectsTruncationBadResourcesAndTrailingData() {
val bytes = hex(multi)
for (end in 1 until bytes.size) assertFails { read(bytes.copyOf(end)) }
assertFails { read(bytes.copyOf().also { it[40] = 9 }) } // first image's local resource
val trailing = bytes + byteArrayOf(0)
trailing[1] = (trailing[1] + 1).toByte()
assertFails { read(trailing) }
}
/** The TS golden's placeholder ids, replaced by ids registered in this process. */
private fun registeredReplay(imageKnown: Boolean = true): ByteArray {
val key = "stub-font".encodeToByteArray()
val glyph = byteArrayOf(key.size.toByte()) + key + byteArrayOf(4, 1, 0, 65, 0, 0, 0, 0, 1, 3, 2) +
byteArrayOf(0xa0.toByte(), 0, 0, 0, 0xe0.toByte(), 0, 0, 0)
GlyphAtlas.register(ArrayByteReader(glyph))
val fontId = GlyphAtlas.fontId("stub-font")
val imageId = if (imageKnown) ImageAtlas.ensure("stub-replay-icon", 2, 2,
ArrayByteReader(byteArrayOf(255.toByte(), 0, 128.toByte(), 255.toByte()))) else 0x7fffffff
fun le(value: Int, bytes: Int) = (0 until bytes).joinToString("") { ((value ushr (8 * it)) and 255).toString(16).padStart(2, '0') }
return hex(replay.replace("efbe", le(fontId, 2)).replace("bebafeca", le(imageId, 4)))
}
@Test fun replayedDrawsCompileToClippedImageAndTextCallsThatPaintLikeTheSoftwareRenderer() {
val list = read(registeredReplay(), 1100)
assertEquals(2, list.resources.size, "the icon and a font snapshot")
val ids = intArrayOf(1, 2)
val calls = list.calls(ids, 1100)
assertEquals(listOf(DRAW_OP_CLEAR, DRAW_OP_ROUNDED_RECT, DRAW_OP_IMAGE, DRAW_OP_TEXT), calls.map { it[0].toInt() })
assertTrue(calls.all { it[1].toInt() and DRAW_FLAG_CLIP != 0 })
val resources = list.resources.withIndex().associate { (i, resource) -> ids[i] to resource.bytes }
val screen = ByteArray(64) { 0x11 }
val target = DisplayListRenderer.Target(screen, 16, 8)
DisplayListRenderer(resources).execute(DrawProtocol.sequence(calls), target)
val nibbles = (0 until 128).joinToString("") { target.get(it % 16, it / 16).toString(16) }
assertEquals(replayPixels, nibbles)
}
@Test fun replayWithAnUnknownRecordDrawsNothing() {
val list = read(registeredReplay(imageKnown = false), 1100)
assertTrue(list.resources.isEmpty())
assertTrue(list.calls(IntArray(0), 1100).isEmpty())
}
}
@@ -0,0 +1,139 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class FrameTimingsCoreTest {
private class FakeClock : ProtocolPlatform by testPlatform() {
var nowMs = 1_000L
override fun elapsedRealtimeMs(): Long = nowMs
}
private fun core(clock: FakeClock, logs: MutableList<String> = ArrayList()) = FrameTimingsCore(
platform = clock,
wallClockMs = { 1_700_000_000_000L + clock.nowMs },
threadName = { "t" },
formatWallClock = { "wall@$it" },
logInfo = { logs.add("I $it") },
logWarn = { logs.add("W $it") },
)
@Test
fun exportRendersTreeAgainstRootClockByteForByte() {
val clock = FakeClock()
val logs = ArrayList<String>()
val core = core(clock, logs)
val root = core.startFrame("input:sys-event type=0")
clock.nowMs += 5
core.annotate(root, "fg=terminal")
core.log(root, "input event received on JS side")
clock.nowMs += 1
core.spanStart(root, "handle-input")
clock.nowMs += 10
val child = core.startFrame("render:shell", root)
clock.nowMs += 4
core.spanEnd(root, "handle-input")
core.spanEnd(root, "missing")
core.spanStart(child, "paint")
clock.nowMs += 30
core.finishFrame(child, "discarded: superseded")
clock.nowMs += 50
core.finishFrame(root, "sent")
core.finishFrame(root, "sent") // ignored: first finish wins
core.log(root, "late line is dropped")
clock.nowMs += 100
assertEquals(listOf(
"I frame#2 [render:shell] -> discarded: superseded in 34ms",
"I frame#1 [input:sys-event type=0 fg=terminal] -> sent in 100ms",
), logs)
assertEquals("frames started=2 sent=1 discarded=1 timeout=0 | input-to-display p50=100ms p90=100ms p99=100ms max=100ms", core.statsSummary())
val expected = """
|FrameTimings export at wall@1700000001200
|frames started=2 sent=1 discarded=1 timeout=0 open=0
|input-to-display latency (last 1): p50=100ms p90=100ms p99=100ms max=100ms
|
|Frames are trees: an input event's own frame is the root, and the renders it
|caused are indented under it with offsets measured from the root's start.
|
|=== slowest frames that reached the glasses ===
|frame#1 [input:sys-event type=0 fg=terminal] started wall@1700000001000 duration 100ms (tree 100ms) outcome sent
| +5ms [t] input event received on JS side
| +6ms [t] span handle-input start
| +16ms [t] spawned frame#2 (render:shell)
| +20ms [t] span handle-input end (14ms)
| +20ms [t] span missing end (start not recorded)
| +100ms [t] finished: sent
| frame#2 [render:shell] started +16ms duration 34ms outcome discarded: superseded
| +20ms [t] span paint start
| +50ms [t] span paint never ended (started at +4ms)
| +50ms [t] finished: discarded: superseded
|=== recent frames (oldest first) ===
|frame#1 [input:sys-event type=0 fg=terminal] started wall@1700000001000 duration 100ms (tree 100ms) outcome sent
| +5ms [t] input event received on JS side
| +6ms [t] span handle-input start
| +16ms [t] spawned frame#2 (render:shell)
| +20ms [t] span handle-input end (14ms)
| +20ms [t] span missing end (start not recorded)
| +100ms [t] finished: sent
| frame#2 [render:shell] started +16ms duration 34ms outcome discarded: superseded
| +20ms [t] span paint start
| +50ms [t] span paint never ended (started at +4ms)
| +50ms [t] finished: discarded: superseded
|""".trimMargin()
assertTrue(core.isExportDirty)
assertEquals(expected, core.takeExport())
assertFalse(core.isExportDirty)
assertEquals(null, core.takeExport())
assertEquals(expected, core.buildExport())
}
@Test
fun sweepFinishesStaleFramesAsTimeoutsAndIgnoresZeroAndUnknownIds() {
val clock = FakeClock()
val logs = ArrayList<String>()
val core = core(clock, logs)
val stale = core.startFrame("render:app")
clock.nowMs += FrameTimingsCore.FRAME_TIMEOUT_MS - 1
val fresh = core.startFrame("render:late")
assertEquals(0, core.sweepTimedOut())
clock.nowMs += 1
assertEquals(1, core.sweepTimedOut())
assertEquals(listOf("W frame#$stale [render:app] timed out after 30000ms without being finished"), logs)
core.log(0, "ignored")
core.log(999, "ignored")
core.spanStart(0, "x")
core.finishFrame(0, "sent")
core.finishFrame(fresh, "sent")
assertEquals("frames started=2 sent=1 discarded=0 timeout=1", core.statsSummary())
val export = core.buildExport()
assertTrue(export.contains("frame#$stale [render:app] started wall@"))
assertTrue(export.contains("outcome timeout: never reported finished\n"))
assertTrue(export.contains("render-to-display latency (last 1): p50=1ms p90=1ms p99=1ms max=1ms"))
assertTrue(export.contains("open=0"))
}
@Test
fun lineCapAndNegativeOffsetsFormatLikeJava() {
val clock = FakeClock()
val core = core(clock)
val root = core.startFrame("input:x")
clock.nowMs -= 12 // a line stamped before the root's start still formats with a sign
core.log(root, "early")
clock.nowMs += 12
repeat(250) { core.log(root, "line $it") }
core.finishFrame(root, "sent")
val export = core.buildExport()
assertTrue(export.contains("\n -12ms [t] early\n"), export)
// Printed once under "slowest" and once under "recent".
assertEquals(2, Regex("\\.\\.\\. line cap reached").findAll(export).count())
assertTrue(export.contains("line 198"))
assertFalse(export.contains("line 199"))
// Like the Java original, lines past the cap (including the finish line) are dropped.
assertFalse(export.contains("finished: sent"))
assertTrue(export.contains("outcome sent\n"))
}
}
@@ -0,0 +1,457 @@
package com.faceclaw.app
import kotlin.concurrent.Volatile
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
private const val RIGHT = "AA:00:00:00:00:01"
private const val LEFT = "AA:00:00:00:00:02"
/** The test platform with a clock the tests can jump forward (the real waits keep real time). */
private class ClockPlatform(private val base: ProtocolPlatform) : ProtocolPlatform by base {
@Volatile var offsetMs = 0L
override fun elapsedRealtimeMs(): Long = base.elapsedRealtimeMs() + offsetMs
}
private fun waitUntil(timeoutMs: Long, condition: () -> Boolean): Boolean {
val platform = testPlatform()
val deadline = platform.elapsedRealtimeMs() + timeoutMs
while (platform.elapsedRealtimeMs() < deadline) {
if (condition()) return true
sleepMs(10)
}
return condition()
}
private fun ByteArray.containsSequence(needle: ByteArray): Boolean {
if (needle.isEmpty() || size < needle.size) return false
outer@ for (start in 0..size - needle.size) {
for (i in needle.indices) if (this[start + i] != needle[i]) continue@outer
return true
}
return false
}
/** One logical write as the fake link saw it: the frames, the decoded pb, and the in-flight message (if any). */
private class Write(
val address: String,
val sid: Int,
val frames: List<ByteArray>,
val pb: ByteArray,
val kind: String?,
val label: String?,
val magic: Int,
val message: ByteArray?,
)
/**
* A GATT link that records every write and, unless a kind is muted, answers it the way the
* firmware would: EvenHub/settings/auth requests get a matching ack frame, CFW stream
* messages get one ACK per lens.
*/
private class FakeLink(private val platform: ProtocolPlatform) : SessionLink {
lateinit var core: GlassesSessionCore
private val lock = platform.createLock()
private val writesList = ArrayList<Write>()
val muted = HashSet<String>()
val connected = HashSet<String>()
val disconnected = ArrayList<String>()
@Volatile var closed = false
var seq = 0
val writes: List<Write>
get() = lock.withLock { writesList.toList() }
/** Decoded CFW image messages (the drive loop's debug-flags control rides the same stream and is excluded). */
fun cfwMessages(): List<ByteArray> = writes.filter { it.sid == CfwTransport.SID && it.kind == "image" }.mapNotNull { it.message }
override fun connect(address: String, timeoutMs: Int): Boolean {
connected.add(address)
return true
}
override fun requestHighPriority(address: String) {}
override fun requestMtu(address: String, mtu: Int, timeoutMs: Int): Boolean = true
override fun negotiatedMtu(address: String): Int = 247
override fun discoverServices(address: String, timeoutMs: Int): Boolean = true
override fun enableNotifications(address: String, characteristicUuid: String, enable: Boolean, timeoutMs: Int): Boolean = true
override fun writeFrames(address: String, characteristicUuid: String, frames: List<ByteArray>, mode: GattWriteMode, timeoutMs: Int): Boolean {
val sid = frames[0][6].toInt() and 255
val magic = if (sid == CfwTransport.SID) frames[0][2].toInt() and 255 else BleProtocol.parseFrame(frames[0]).msgSeq
// The in-flight entry gives the label/kind and the decoded CFW message.
val inFlight = core.monitor.withLock { core.inFlightMessages.firstOrNull { it.sid == sid && it.magic == magic && magic != 0 } }
val pb = if (sid == CfwTransport.SID) ByteArray(0) else {
val joined = frames.flatMap { frame -> frame.slice(8 until 8 + (frame[3].toInt() and 255)) }.toByteArray()
joined.copyOf(maxOf(0, joined.size - 2))
}
val write = Write(address, sid, frames, pb, inFlight?.kind, inFlight?.label, magic, inFlight?.message?.copyOf())
lock.withLock { writesList.add(write) }
if (inFlight != null && inFlight.kind !in muted) {
if (sid == CfwTransport.SID) {
for (lens in 1..2) core.onNotification(address, BleProtocol.NOTIFY_CHAR_UUID, cfwAck(magic, lens, inFlight.message.size, inFlight.cfwChecksum))
} else {
core.onNotification(address, BleProtocol.NOTIFY_CHAR_UUID, ackFrame(sid, magic, pb))
}
}
return true
}
private fun ackFrame(sid: Int, magic: Int, request: ByteArray): ByteArray {
val body = if (sid == BleProtocol.SID_SECURITY_AUTH)
BleProtocol.encodeVarintField(1, 4) + BleProtocol.encodeVarintField(2, magic) + byteArrayOf(0x1a, 0x00)
else
BleProtocol.encodeVarintField(1, 1) + BleProtocol.encodeVarintField(2, magic)
return BleProtocol.framePb(body, sid, 0x00, seq++)[0]
}
override fun disconnect(address: String) {
disconnected.add(address)
connected.remove(address)
}
override fun close() {
closed = true
}
override fun isBonded(address: String): Boolean = true
override fun prepareBenchmarkLink(address: String, mode: Int) {}
override fun recordDisplayFrameSent() {}
}
private fun cfwAck(streamId: Int, lens: Int, size: Int, checksum: Int): ByteArray {
val packet = ByteArray(19)
packet[0] = 0xaa.toByte()
packet[1] = 0x12
packet[3] = 11
packet[4] = 1
packet[5] = 1
packet[6] = CfwTransport.SID.toByte()
packet[8] = 1
packet[9] = streamId.toByte()
packet[12] = lens.toByte()
packet[13] = size.toByte()
packet[14] = (size ushr 8).toByte()
packet[15] = checksum.toByte()
packet[16] = (checksum ushr 8).toByte()
val crc = CfwTransport.crc(packet.copyOfRange(8, 17))
packet[17] = crc.toByte()
packet[18] = (crc ushr 8).toByte()
return packet
}
private class FakeHost(private val platform: ProtocolPlatform) : SessionHost {
private val lock = platform.createLock()
private val lines = ArrayList<String>()
private var done: Latch? = null
var wakeLock = false
fun logs(): List<String> = lock.withLock { lines.toList() }
fun hasLog(fragment: String): Boolean = logs().any { it.contains(fragment) }
override fun postToMain(action: () -> Unit) = action()
override fun currentThreadDispatcher(): SessionDispatcher = SessionDispatcher { it() }
override fun isPhoneLocked(): Boolean = false
override fun setScreenWakeLock(on: Boolean) {
wakeLock = on
}
override fun isEvenAppActive(): Boolean = false
override fun startWorker(body: () -> Unit) {
val latch = Latch(1, platform)
done = latch
startThread("test-session", true) {
try {
body()
} finally {
latch.countDown()
}
}
}
override fun joinWorker(timeoutMs: Long) {
done?.await(timeoutMs)
}
override fun log(level: SessionLogLevel, tag: String, message: String, error: Throwable?) {
lock.withLock { lines.add("$level $tag: $message") }
}
}
private class FakeListener : FaceclawBleCommunicatorListener {
val phases = ArrayList<String>()
val events = ArrayList<String>()
val finished = ArrayList<String>()
val batteries = ArrayList<String>()
override fun onStateChange(phase: String?, status: String?) {
phases.add(phase ?: "")
}
override fun onRingEvent(kind: String?, containerName: String?, eventType: Int, eventSource: Int, systemExitReasonCode: Int, frameId: Int, ringTick: Long, ringType: Int, ringAux: Int, ringSpeed: Int) {
events.add("$kind:$eventType")
}
override fun onBatteryState(headsetBattery: Int, headsetCharging: Int, ringBattery: Int, ringCharging: Int) {
batteries.add("$headsetBattery/$headsetCharging/$ringBattery/$ringCharging")
}
override fun onSilentMode(silent: Boolean) {}
override fun onWearState(wearing: Boolean) {}
override fun onPhoneLockState(locked: Boolean) {}
override fun onEvenAppConflict(message: String?) {}
override fun onFrameMetrics(paintMs: Int, transmitMs: Int, tileCount: Int) {}
override fun onFrameFinished(frameId: Int, outcome: String?) {
finished.add("$frameId:$outcome")
}
override fun onFirmwareInfo(leftVersion: String?, rightVersion: String?, extension: String?) {}
}
private class Session {
val platform = ClockPlatform(testPlatform())
val link = FakeLink(platform)
val host = FakeHost(platform)
val listener = FakeListener()
val frameTimings = FrameTimingsCore(platform)
val core = GlassesSessionCore(link, host, frameTimings, platform, RIGHT, LEFT, "")
init {
link.core = core
core.setListener(listener)
}
fun layoutCreated(): Boolean = core.monitor.withLock { core.fixedLayoutCreated }
fun startAndAwaitLayout() {
assertTrue(core.start())
assertTrue(waitUntil(5_000) { layoutCreated() }, "layout never created; logs=${host.logs().takeLast(20)}")
}
/** A 64x32 surface frame with a marker byte at [marker]; returns the expected composite fingerprint. */
fun submitFrame(marker: Int, value: Byte, frameId: Int): Unit {
val pixels = ByteArray(64 * 32)
pixels[marker] = value
core.submitSurfaceFrame(ArrayByteReader(pixels), "s", 0, 0, 64, 32, "content-$marker-$value", 0, frameId, null)
}
fun displayedMatchesDesired(): Boolean = core.monitor.withLock {
core.desiredTilesLock.locked { core.desiredFingerprint.isNotEmpty() && core.desiredFingerprint == core.displayedFingerprint }
}
}
class GlassesSessionCoreTest {
@Test fun brightnessConfigPrecedesFirstFrameAndSleepWakeFollowsComposites() {
val s = Session()
s.core.configureBrightness(false, 70, 2, 100, "0:0,1000:100", 280)
s.core.configureCompositorScreen(640, 480)
s.core.configureSurface("s", 0, 0, 64, 32, 0, SurfaceCompositor.TRANSPARENCY_OPAQUE)
s.startAndAwaitLayout()
s.core.monitor.withLock { s.core.customFirmwareDetected = true }
try {
s.submitFrame(1, 0x70, 1)
assertTrue(waitUntil(5000) { s.displayedMatchesDesired() })
fun outputs() = s.link.writes.filter { it.address == LEFT && it.kind == "brightness-output" }
assertTrue(waitUntil(5000) { outputs().isNotEmpty() })
val first = outputs().first().message!!
assertContentEquals(byteArrayOf(30, 1, 70, 1, 24, 1), first)
val writes = s.link.writes.filter { it.address == LEFT }
assertTrue(writes.indexOfFirst { it.kind == "als-control" } < writes.indexOfFirst { it.kind == "brightness-output" })
assertTrue(writes.indexOfFirst { it.kind == "brightness-output" } < writes.indexOfFirst { it.message?.firstOrNull() == 28.toByte() })
s.core.setScreenBlanked(true)
assertTrue(waitUntil(5000) { s.displayedMatchesDesired() && outputs().last().message!![3] == 0.toByte() })
s.core.setScreenBlanked(false)
assertTrue(waitUntil(5000) { s.displayedMatchesDesired() && outputs().last().message!![3] == 1.toByte() })
// The ordered CFW window may replay accepted commands; those must
// retain the same brightness and visibility, without an extra toggle.
val visibility = outputs().map { it.message!![3].toInt() }
val transitions = visibility.filterIndexed { i, v -> i == 0 || visibility[i-1] != v }
assertEquals(listOf(1, 0, 1), transitions)
assertTrue(outputs().all { it.message!![2] == 70.toByte() })
// The demo cannot restore the stock adjuster while Faceclaw owns brightness.
s.core.setAmbientLightPolling(false, 250, 0, 1000, true)
s.platform.offsetMs += 3000
s.core.interruptibleSleep.interrupt()
assertTrue(waitUntil(5000) { s.link.writes.count { it.address == LEFT && it.kind == "als-control" } >= 2 })
assertTrue(s.link.writes.filter { it.kind == "als-control" }.all { it.message!![1] == 1.toByte() })
} finally { s.core.close() }
}
@Test
fun connectsAuthenticatesPreludesAndCreatesTheLayout() {
val s = Session()
s.startAndAwaitLayout()
val writes = s.link.writes
assertEquals(setOf(RIGHT, LEFT), writes.filter { it.sid == BleProtocol.SID_SECURITY_AUTH }.map { it.address }.toSet())
assertTrue(s.host.hasLog("security auth R=ok L=ok"), s.host.logs().toString())
assertEquals(1, writes.count { it.kind == "prelude" })
// The framebuffer lease is acquired on both arms (fire-and-forget settings writes, magic 0).
val fbAcquire = byteArrayOf(70, 67, 1, BleProtocol.FACECLAW_FB_OP_ACQUIRE.toByte())
assertEquals(setOf(RIGHT, LEFT), writes.filter { it.sid == BleProtocol.SID_UI_SETTING && it.pb.containsSequence(fbAcquire) }.map { it.address }.toSet())
assertEquals(1, writes.count { it.kind == "battery" }, "settings query for firmware info")
assertEquals(1, writes.count { it.kind == "create-layout" })
assertTrue(s.core.isSessionReady())
assertEquals(listOf("disconnected", "connecting", "connected"), s.listener.phases.distinct())
s.core.disconnect()
assertFalse(s.core.isSessionReady())
assertEquals("disconnected", s.listener.phases.last())
assertTrue(s.listener.phases.contains("disconnecting"))
assertTrue(s.link.closed)
assertEquals(listOf(RIGHT, LEFT), s.link.disconnected.takeLast(2))
assertFalse(s.host.wakeLock)
assertTrue(s.host.hasLog("communicator stop"))
}
@Test
fun imagePipelineSendsAKeyframeThenABoundingBoxDelta() {
val s = Session()
s.startAndAwaitLayout()
s.core.configureCompositorScreen(64, 32)
s.core.configureSurface("s", 0, 0, 64, 32, 0, SurfaceCompositor.TRANSPARENCY_OPAQUE)
s.submitFrame(100, 0x80.toByte(), 1)
assertTrue(waitUntil(5_000) { s.link.cfwMessages().size >= 1 && s.displayedMatchesDesired() }, s.host.logs().takeLast(20).toString())
assertTrue(s.listener.finished.contains("1:sent"), s.listener.finished.toString())
s.submitFrame(101, 0x80.toByte(), 2)
assertTrue(waitUntil(5_000) { s.link.cfwMessages().size >= 2 && s.displayedMatchesDesired() }, s.host.logs().takeLast(20).toString())
val messages = s.link.cfwMessages()
assertEquals(CFW_MSG_FULL_FRAME, messages[0][0].toInt() and CFW_MSG_TYPE_MASK, "first frame is a keyframe")
assertEquals(CFW_MSG_BOUNDING_BOX, messages[1][0].toInt() and CFW_MSG_TYPE_MASK, "second frame is a delta")
assertTrue(s.listener.finished.contains("2:sent"))
// Identical content again: nothing is sent and the frame is finished as a no-change.
s.submitFrame(101, 0x80.toByte(), 3)
assertTrue(waitUntil(2_000) { s.listener.finished.any { it.startsWith("3:") } })
assertTrue(s.listener.finished.any { it == "3:discarded: no change from displayed image" }, s.listener.finished.toString())
assertEquals(2, s.link.cfwMessages().size)
s.core.disconnect()
}
@Test
fun heartbeatAndLeaseRenewalFollowTheClock() {
val s = Session()
s.startAndAwaitLayout()
// The first heartbeat follows the layout at once (nothing has been acked yet); the
// next one waits for HEARTBEAT_READY_MS since that ack.
assertTrue(waitUntil(3_000) { s.link.writes.count { it.kind == "heartbeat" } == 1 }, s.host.logs().takeLast(10).toString())
assertTrue(s.host.hasLog("Got ACK for heartbeat"))
sleepMs(300)
assertEquals(1, s.link.writes.count { it.kind == "heartbeat" })
s.platform.offsetMs += ConnectionOptions.HEARTBEAT_READY_MS + 100L
s.core.interruptibleSleep.interrupt()
assertTrue(waitUntil(3_000) { s.link.writes.count { it.kind == "heartbeat" } == 2 }, s.host.logs().takeLast(10).toString())
val leaseWritesBefore = s.link.writes.count { it.sid == BleProtocol.SID_UI_SETTING && it.pb.containsSequence(byteArrayOf(70, 67, 1, BleProtocol.FACECLAW_FB_OP_ACQUIRE.toByte())) }
s.platform.offsetMs += GlassesSessionCore.FACECLAW_WAKE_LEASE_RENEW_MS + 100L
s.core.interruptibleSleep.interrupt()
assertTrue(waitUntil(3_000) {
s.link.writes.count { it.sid == BleProtocol.SID_UI_SETTING && it.pb.containsSequence(byteArrayOf(70, 67, 1, BleProtocol.FACECLAW_FB_OP_ACQUIRE.toByte())) } == leaseWritesBefore + 2
}, "framebuffer lease renewed on both arms")
s.core.disconnect()
}
@Test
fun deferredWakeIsClaimedAndReadyIsSentAfterResume() {
val s = Session()
s.startAndAwaitLayout()
s.core.configureCompositorScreen(64, 32)
s.core.configureSurface("s", 0, 0, 64, 32, 0, SurfaceCompositor.TRANSPARENCY_OPAQUE)
s.submitFrame(7, 0x40, 1)
assertTrue(waitUntil(5_000) { s.displayedMatchesDesired() })
assertTrue(s.core.suspendEvenHubSession())
assertTrue(s.core.monitor.withLock { s.core.shutdownRequested })
assertEquals(1, s.link.writes.count { it.kind == "shutdown" })
// CFW deferred double-tap wake on the right arm: field 102 [F,C,ver,event=1,nonce LE16].
val nonce = 0x1234
val event = byteArrayOf(70, 67, 1, 1, (nonce and 0xff).toByte(), (nonce ushr 8).toByte())
val pb = BleProtocol.encodeVarintField(1, 1) + BleProtocol.encodeVarintField(2, 0) + BleProtocol.encodeBytesField(BleProtocol.FACECLAW_WAKE_EVENT_FIELD, event)
s.core.onNotification(RIGHT, BleProtocol.NOTIFY_CHAR_UUID, BleProtocol.framePb(pb, BleProtocol.SID_UI_SETTING, BleProtocol.FLAG_NOTIFY, 9)[0])
assertTrue(s.listener.events.contains("display-wake:${BleProtocol.EVENT_DOUBLE_CLICK}"), s.listener.events.toString())
val claim = byteArrayOf(70, 67, 1, BleProtocol.FACECLAW_WAKE_OP_CLAIM.toByte(), (nonce and 0xff).toByte(), (nonce ushr 8).toByte())
assertTrue(waitUntil(3_000) { s.link.writes.count { it.pb.containsSequence(claim) } == 2 }, "CLAIM written to both arms")
assertEquals(RIGHT, s.link.writes.first { it.pb.containsSequence(claim) }.address, "right arm first")
assertTrue(s.core.resumeEvenHubSession())
assertEquals(2, s.link.writes.count { it.kind == "prelude" })
assertTrue(waitUntil(5_000) { s.layoutCreated() && s.displayedMatchesDesired() }, s.host.logs().takeLast(20).toString())
assertTrue(s.core.awaitEvenHubSessionReady(5_000))
val ready = byteArrayOf(70, 67, 1, BleProtocol.FACECLAW_WAKE_OP_READY.toByte(), (nonce and 0xff).toByte(), (nonce ushr 8).toByte())
assertEquals(2, s.link.writes.count { it.pb.containsSequence(ready) }, "READY written to both arms")
s.core.disconnect()
}
@Test
fun unexpectedAndDuplicateAcksAreLoggedNotApplied() {
val s = Session()
s.startAndAwaitLayout()
val unknown = BleProtocol.framePb(BleProtocol.encodeVarintField(1, 1) + BleProtocol.encodeVarintField(2, 150), BleProtocol.SID_EVENHUB, 0, 5)[0]
s.core.onNotification(RIGHT, BleProtocol.NOTIFY_CHAR_UUID, unknown)
assertTrue(s.host.hasLog("unexpected ACK sid=${BleProtocol.SID_EVENHUB} magic=150"), s.host.logs().takeLast(5).toString())
val layout = s.link.writes.first { it.kind == "create-layout" }
val duplicate = BleProtocol.framePb(BleProtocol.encodeVarintField(1, 1) + BleProtocol.encodeVarintField(2, layout.magic), layout.sid, 0, 6)[0]
s.core.onNotification(RIGHT, BleProtocol.NOTIFY_CHAR_UUID, duplicate)
assertTrue(s.host.hasLog("duplicate ACK for already-acked message sid=${layout.sid} magic=${layout.magic}"), s.host.logs().takeLast(5).toString())
assertTrue(s.layoutCreated())
s.core.disconnect()
}
@Test
fun ackTimeoutOnTheLayoutReconnects() {
val s = Session()
s.link.muted.add("create-layout")
assertTrue(s.core.start())
assertTrue(waitUntil(5_000) { s.link.writes.any { it.kind == "create-layout" } })
assertFalse(s.layoutCreated())
s.platform.offsetMs += ConnectionOptions.ACK_TIMEOUT_MS + ConnectionOptions.WRITE_TIMEOUT_MS + 1_000L
s.core.interruptibleSleep.interrupt()
assertTrue(waitUntil(3_000) { s.listener.phases.contains("retrying") }, s.host.logs().takeLast(10).toString())
assertTrue(s.host.hasLog("message timed out: create-layout"))
assertTrue(s.host.hasLog("Transport failure: ack timeout"))
assertTrue(s.link.disconnected.containsAll(listOf(RIGHT, LEFT)))
s.core.disconnect()
assertEquals("disconnected", s.listener.phases.last())
}
@Test
fun cfwNackTriggersReplayWithAFreshStreamId() {
val s = Session()
s.link.muted.add("image")
s.startAndAwaitLayout()
s.core.configureCompositorScreen(64, 32)
s.core.configureSurface("s", 0, 0, 64, 32, 0, SurfaceCompositor.TRANSPARENCY_OPAQUE)
s.submitFrame(3, 0x20, 1)
assertTrue(waitUntil(5_000) { s.link.cfwMessages().size == 1 })
val first = s.link.writes.first { it.sid == CfwTransport.SID && it.kind == "image" }
val message = assertNotNull(s.core.monitor.withLock { s.core.inFlightMessages.firstOrNull { it.magic == first.magic } })
// A NACK from lens 1 marks the message for replay; the window re-sends it under a new id.
val nack = cfwAck(first.magic, 1, 0, 0).also { it[8] = 3; val crc = CfwTransport.crc(it.copyOfRange(8, 17)); it[17] = crc.toByte(); it[18] = (crc ushr 8).toByte() }
s.core.onNotification(LEFT, BleProtocol.NOTIFY_CHAR_UUID, nack)
assertTrue(waitUntil(3_000) { s.link.cfwMessages().size == 2 }, s.host.logs().takeLast(10).toString())
assertTrue(s.host.hasLog("CFW replay id=${first.magic}"))
val second = s.link.writes.filter { it.sid == CfwTransport.SID && it.kind == "image" }[1]
assertTrue(second.magic != first.magic)
assertEquals(1, message.cfwRetries)
assertContentEquals(first.message, second.message)
s.core.disconnect()
}
}
@@ -0,0 +1,128 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
class GlyphAndIconSourceTest {
private fun u16(bytes: ByteArray, at: Int) = (bytes[at].toInt() and 0xff) or ((bytes[at + 1].toInt() and 0xff) shl 8)
private fun s16(bytes: ByteArray, at: Int) = u16(bytes, at).toShort().toInt()
// 6x4 raster: ink in columns 2..4, rows 1..2, one 128 edge pixel.
private val raster = byteArrayOf(
0, 0, 0, 0, 0, 0,
0, 0, -1, -1, 0, 0,
0, 0, 0, -1, 0x7f, 0,
0, 0, 0, 0, 0, 0,
)
@Test
fun gammaLutIsIdentityAtOneAndDarkensAboveOne() {
val linear = GlyphPacket.gammaLut(1.0)
for (i in 0 until 256) assertEquals(i, linear[i].toInt() and 0xff)
assertContentEquals(linear, GlyphPacket.gammaLut(0.0))
val squared = GlyphPacket.gammaLut(2.0)
assertEquals(64, squared[128].toInt() and 0xff)
assertEquals(255, squared[255].toInt() and 0xff)
}
@Test
fun inkScansFindPaintedBoxes() {
assertContentEquals(intArrayOf(2, 4), GlyphPacket.paintedColumnRange(raster, 6, 4))
assertContentEquals(intArrayOf(2, 1, 4, 2), GlyphPacket.inkBounds(raster, 6, 4))
assertNull(GlyphPacket.paintedColumnRange(ByteArray(12), 4, 3))
assertNull(GlyphPacket.inkBounds(ByteArray(12), 4, 3))
}
@Test
fun imagePacketsCarryLittleEndianHeaderAndGammaMappedRegion() {
val whole = GlyphPacket.packImage(raster, 6, 4, 1.0)
assertEquals(4 + 24, whole.size)
assertEquals(6, u16(whole, 0))
assertEquals(4, u16(whole, 2))
assertContentEquals(raster, whole.copyOfRange(4, whole.size))
val region = GlyphPacket.packImageRegion(raster, 6, 2, 1, 3, 2, 2.0)
assertEquals(3, u16(region, 0))
assertEquals(2, u16(region, 2))
assertContentEquals(byteArrayOf(-1, -1, 0, 0, -1, 63), region.copyOfRange(4, region.size))
}
@Test
fun glyphCellPacketsCropToInkAndEncodeSignedOffsets() {
val cell = GlyphPacket.packGlyphCell(GlyphPacket.advanceFixed(5.5), raster, 6, 4, penX = 3, baselineY = 3, ascent = 10, gamma = 1.0)
assertEquals(352, u16(cell, 0))
assertEquals(-1, s16(cell, 2)) // ink starts one pixel left of the pen
assertEquals(8, s16(cell, 4)) // ascent 10, ink top two rows above the baseline
assertEquals(3, u16(cell, 6))
assertEquals(2, u16(cell, 8))
assertContentEquals(byteArrayOf(-1, -1, 0, 0, -1, 0x7f), cell.copyOfRange(10, cell.size))
val empty = GlyphPacket.packGlyphCell(64, ByteArray(12), 4, 3, 0, 0, 10, 1.0)
assertContentEquals(byteArrayOf(64, 0, 0, 0, 0, 0, 0, 0, 0, 0), empty)
assertEquals(0xffff, GlyphPacket.advanceFixed(5000.0))
}
private fun nameTable(vararg records: Triple<Int, Int, String>): ByteArray {
// records: (platformId, nameId, value); platform 1 stored Latin-1, others UTF-16BE
val strings = ArrayList<ByteArray>()
for ((platform, _, value) in records) {
strings.add(if (platform == 1) ByteArray(value.length) { value[it].code.toByte() }
else ByteArray(value.length * 2) { if (it % 2 == 0) (value[it / 2].code shr 8).toByte() else value[it / 2].code.toByte() })
}
val out = ByteSink()
fun u16(v: Int) { out.write(v ushr 8); out.write(v) }
fun u32(v: Int) { u16(v ushr 16); u16(v and 0xffff) }
val nameOffset = 12 + 16
val nameLength = 6 + records.size * 12 + strings.sumOf { it.size }
u32(0x00010000); u16(1); u16(0); u16(0); u16(0) // offset table, 1 table
u32(0x6e616d65); u32(0); u32(nameOffset); u32(nameLength) // 'name' record
u16(0); u16(records.size); u16(6 + records.size * 12)
var offset = 0
for ((i, record) in records.withIndex()) {
u16(record.first); u16(0); u16(0); u16(record.second); u16(strings[i].size); u16(offset)
offset += strings[i].size
}
for (s in strings) out.write(s)
return out.toByteArray()
}
@Test
fun openTypeNamesPreferTypographicFamilyAndStyle() {
assertEquals("Roboto\nLight", OpenTypeNames.parse(nameTable(Triple(3, 1, "Roboto Light"), Triple(3, 2, "Regular"), Triple(3, 16, "Roboto"), Triple(1, 17, "Light"))))
assertEquals("Mono\n", OpenTypeNames.parse(nameTable(Triple(1, 1, " Mono "))))
assertEquals("", OpenTypeNames.parse(nameTable(Triple(3, 2, "Bold"))))
assertEquals("", OpenTypeNames.parse(ByteArray(8)))
}
@Test
fun svgIconsParseShapesStrokeRuleAndPlacement() {
val svg = """<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><rect x="3" y="3" width="18" height="18" rx="2"/>
<circle cx="12" cy="12" r="0"/><circle cx="12" cy="12" r="3"/><path d="M4 4h16"/><polygon points="1,2 3 4 5"/><line x1="0" y1="0" x2="1" y2="1"/></svg>"""
val icon = SvgIconSource.parse(svg)!!
assertTrue(icon.stroked)
assertEquals(listOf("Rect", "Circle", "PathData", "Polyline", "Line"), icon.shapes.map { it::class.simpleName })
val rect = icon.shapes[0] as SvgShape.Rect
assertEquals(2f, rect.rx); assertEquals(2f, rect.ry)
assertEquals(3f, (icon.shapes[1] as SvgShape.Circle).r)
assertEquals("M4 4h16", (icon.shapes[2] as SvgShape.PathData).d)
val polygon = icon.shapes[3] as SvgShape.Polyline
assertContentEquals(floatArrayOf(1f, 2f, 3f, 4f), polygon.points)
assertTrue(polygon.closed)
assertContentEquals(floatArrayOf(0f, 0f, 2f), icon.placement(48))
val filled = SvgIconSource.parse("""<svg viewBox="-2 0 40 20"><rect width="4" height="2"/></svg>""")!!
assertTrue(!filled.stroked)
assertContentEquals(floatArrayOf(0f, 5f, 0.5f), filled.placement(20))
assertEquals(-2f, filled.minX)
assertNull(SvgIconSource.parse("""<svg><circle r="0"/><rect width="0" height="3"/></svg>"""))
}
@Test
fun coverageQuantizesToThreeLevels() {
assertEquals(0, SvgIconSource.quantizeCoverage(63))
assertEquals(128, SvgIconSource.quantizeCoverage(64))
assertEquals(128, SvgIconSource.quantizeCoverage(191))
assertEquals(255, SvgIconSource.quantizeCoverage(192))
assertContentEquals(byteArrayOf(0, -128, -1), SvgIconSource.quantizeArgb(intArrayOf(0x10ffffff, 0x80000000.toInt(), 0xff000000.toInt())))
}
}
@@ -0,0 +1,99 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertSame
import kotlin.test.assertTrue
class GraphicsCoresTest {
private fun checksum(bytes: ByteArray): Long {
var sum = 7L
for (b in bytes) sum = sum * 31 + (b.toInt() and 0xff)
return sum
}
@Test
fun grayPacketHeaderAndFlatConversion() {
// 3x2: opaque white, opaque mid, transparent white, half-alpha red, opaque black, opaque green
val pixels = intArrayOf(
0xffffffff.toInt(), 0xff808080.toInt(), 0x00ffffff,
0x80ff0000.toInt(), 0xff000000.toInt(), 0xff00ff00.toInt(),
)
val packet = GrayPacket.fromArgb(pixels, 3, 2, 1f, false)
assertEquals(4 + 6, packet.size)
assertContentEquals(byteArrayOf(3, 0, 2, 0), packet.copyOfRange(0, 4))
assertEquals(255, packet[4].toInt() and 0xff)
assertEquals(128, packet[5].toInt() and 0xff)
assertEquals(0, packet[6].toInt() and 0xff) // alpha 0 darkens to black
assertEquals(76 * 128 / 255, packet[7].toInt() and 0xff) // luma 76 at half alpha
assertEquals(0, packet[8].toInt() and 0xff)
assertEquals(149, packet[9].toInt() and 0xff)
val wide = GrayPacket.fromArgb(IntArray(300 * 2), 300, 2, 1f, false)
assertContentEquals(byteArrayOf(0x2c, 1, 2, 0), wide.copyOfRange(0, 4))
}
@Test
fun toneCurveDarkensMidtones() {
val identity = GrayPacket.toneCurve(1f)
assertEquals((0..255).toList(), identity.toList())
val curve = GrayPacket.toneCurve(2.2f)
assertEquals(0, curve[0])
assertEquals(255, curve[255])
assertEquals(56, curve[128])
assertTrue(curve.toList() == curve.sorted())
}
@Test
fun ditherIsDeterministicAndQuantized() {
// A horizontal ramp over 16x4 so the diffusion has somewhere to go.
val pixels = IntArray(16 * 4) { i -> val v = (i % 16) * 17; 0xff000000.toInt() or (v shl 16) or (v shl 8) or v }
val a = GrayPacket.fromArgb(pixels, 16, 4, 1f, true)
val b = GrayPacket.fromArgb(pixels, 16, 4, 1f, true)
assertContentEquals(a, b)
for (i in 4 until a.size) {
val v = a[i].toInt() and 0xff
assertTrue(v == 1 || (v % 16 == 0 && v in 16..240), "byte $i = $v")
}
// Mid-gray flat area dithers to a mix of two adjacent levels, never a solid.
val flat = GrayPacket.fromArgb(IntArray(8 * 8) { 0xff7f7f7f.toInt() }, 8, 8, 1f, true)
val levels = flat.drop(4).map { it.toInt() and 0xff }.toSet()
assertEquals(setOf(112, 128), levels)
assertEquals(2001783152304756847L, checksum(a))
}
@Test
fun previewPaletteValues() {
assertEquals(0xff000000.toInt(), PreviewPalette.argb(0, 0.7, false))
assertEquals(0xffffffff.toInt(), PreviewPalette.argb(255, 0.7, false))
assertEquals(0xff00ff00.toInt(), PreviewPalette.argb(255, 0.7, true))
val gray = PreviewPalette.argb(128, 0.7, false)
val v = gray and 0xff
assertEquals(157, v)
assertEquals(0xff000000.toInt() or (v shl 16) or (v shl 8) or v, gray)
assertEquals(0xff000000.toInt() or (v shl 8), PreviewPalette.argb(128, 0.7, true))
assertEquals(0xff808080.toInt(), PreviewPalette.argb(128, 1.0, false))
val lut = PreviewPalette.lookupTable(0.7, false)
assertSame(lut, PreviewPalette.lookupTable(0.7, false))
assertEquals(256, lut.size)
val expanded = PreviewPalette.expand(byteArrayOf(0, 0x80.toByte(), 0xff.toByte()), 0, 3, 0.7, false)
assertContentEquals(intArrayOf(lut[0], lut[128], lut[255]), expanded)
}
@Test
fun statusIconsAreStable() {
val wifi = StatusIconArt.wifi(4)
val cell = StatusIconArt.cell(2)
val hotspot = StatusIconArt.hotspot()
for (icon in listOf(wifi, cell, hotspot)) {
assertEquals(24 * 24, icon.size)
assertTrue(icon.any { it.toInt() != 0 })
}
assertTrue(StatusIconArt.wifi(0).count { it.toInt() != 0 } < wifi.count { it.toInt() != 0 })
assertEquals(StatusIconArt.wifi(2).toList(), StatusIconArt.wifi(2).toList())
assertEquals(listOf(-7515428168691714401L, -7643893777543336767L, 7675840471157348143L), listOf(checksum(wifi), checksum(cell), checksum(hotspot)))
val scaled = StatusIconArt.scale(wifi, 12)
assertEquals(144, scaled.size)
assertSame(wifi, StatusIconArt.scale(wifi, 24))
}
}
@@ -0,0 +1,67 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class Lc3PacketFramerTest {
private class FakeCodec(var fail: Boolean = false) : Lc3Codec {
var calls = 0
override fun decodeFrames(packet: ByteArray, offset: Int, length: Int, pcmOut: ShortArray): Int {
calls++
assertEquals(0, offset)
assertEquals(Lc3PacketFramer.LC3_BYTES, length)
return if (fail) -1 else Lc3PacketFramer.SAMPLES_PER_PACKET
}
}
private fun packet(counter: Int, ssr: Int = 0, angle: Int = 0): ByteArray {
val p = ByteArray(Lc3PacketFramer.PACKET_BYTES)
p[Lc3PacketFramer.COUNTER_OFFSET] = counter.toByte()
p[Lc3PacketFramer.SSR_OFFSET] = (ssr and 0xff).toByte()
p[Lc3PacketFramer.SSR_OFFSET + 1] = ((ssr shr 8) and 0xff).toByte()
p[Lc3PacketFramer.ANGLE_OFFSET] = (angle and 0xff).toByte()
p[Lc3PacketFramer.ANGLE_OFFSET + 1] = ((angle shr 8) and 0xff).toByte()
return p
}
@Test
fun countsRealDuplicateLateAndMissingPackets() {
val codec = FakeCodec()
val framer = Lc3PacketFramer(codec)
val pcm = ShortArray(Lc3PacketFramer.SAMPLES_PER_PACKET)
assertEquals(800, framer.decodePacket(packet(250), pcm))
assertEquals(800, framer.decodePacket(packet(251), pcm))
assertEquals(0, framer.decodePacket(packet(251), pcm)) // relayed by the other arm
assertEquals(0, framer.decodePacket(packet(250), pcm)) // late copy (gap 255)
assertEquals(800, framer.decodePacket(packet(254), pcm)) // 252, 253 lost
assertEquals(800, framer.decodePacket(packet(1), pcm)) // wraps past 255 -> 0; 255, 0 lost
assertEquals(0, framer.decodePacket(packet(129), pcm)) // gap 128 is late, not 127 losses
assertEquals(4, framer.realPackets)
assertEquals(3, framer.duplicatePackets)
assertEquals(4, framer.missingPackets)
assertEquals(0, framer.decodeErrors)
assertEquals(4, codec.calls)
}
@Test
fun parsesSignedTrailerAndRejectsBadInput() {
val codec = FakeCodec()
val framer = Lc3PacketFramer(codec)
val pcm = ShortArray(Lc3PacketFramer.SAMPLES_PER_PACKET)
framer.decodePacket(packet(7, ssr = -1234, angle = -45), pcm)
assertEquals(-1234, framer.lastSsr)
assertEquals(-45, framer.lastAngleDegrees)
assertEquals(0, framer.decodePacket(ByteArray(10), pcm))
assertEquals(0, framer.decodePacket(null, pcm))
assertEquals(2, framer.decodeErrors)
assertFailsWith<IllegalArgumentException> { framer.decodePacket(packet(8), ShortArray(10)) }
codec.fail = true
assertEquals(0, framer.decodePacket(packet(8), pcm))
assertEquals(3, framer.decodeErrors)
// A failed decode does not advance the counter, so 8 is still accepted afterwards.
codec.fail = false
assertEquals(800, framer.decodePacket(packet(8), pcm))
assertEquals(2, framer.realPackets)
}
}
@@ -0,0 +1,67 @@
package com.faceclaw.app
import kotlin.test.*
class PreviewPackingTest {
private fun level(value: Byte): Int = minOf(15, ((value.toInt() and 255) + 8) / 16)
@Test
fun everyPairOfGrayValuesHasTheSameWireEncoding() {
val pixels = ByteArray(65536 * 2) { if (it % 2 == 0) (it / 512).toByte() else (it / 2).toByte() }
val packed = BmpUtil.pack4bppFromGray8(pixels, 512, 256)
for (i in packed.indices) {
assertEquals((level(pixels[i * 2]) * 16 + level(pixels[i * 2 + 1])).toByte(), packed[i], "pair $i")
}
for (v in 0..255) assertEquals(level(v.toByte()), BmpUtil.nibbleForGray(v))
}
@Test
fun oddWidthsPadEveryRowAndIgnoreTrailingInput() {
for (width in listOf(1, 3, 5, 639, 641)) {
val height = 7
val pixels = ByteArray(width * height + 13) { (it * 73 + 19).toByte() }
val stride = (width + 1) / 2
val packed = BmpUtil.pack4bppFromGray8(pixels, width, height)
assertEquals(stride * height, packed.size)
for (y in 0 until height) {
for (x in 0 until width) {
val byte = packed[y * stride + x / 2].toInt() and 255
assertEquals(level(pixels[y * width + x]), if (x % 2 == 0) byte / 16 else byte % 16)
}
assertEquals(0, packed[(y + 1) * stride - 1].toInt() and 15)
}
}
assertContentEquals(ByteArray(4), BmpUtil.pack4bppFromGray8(null, 3, 2))
assertContentEquals(ByteArray(4), BmpUtil.pack4bppFromGray8(ByteArray(5) { -1 }, 3, 2))
assertTrue(BmpUtil.pack4bppFromGray8(null, 0, 2).isEmpty())
}
@Test
fun wireFramesSkipPreviewButExplicitReadbackIncludesLatestShellAndPixels() {
val compositor = SurfaceCompositor(false)
compositor.configureScreen(3, 2)
compositor.configureSurface("app", 0, 0, 3, 2, 0, SurfaceCompositor.TRANSPARENCY_OPAQUE)
// One white 2x1 shell layer at (0,0), with no dimming or selection.
val header = listOf(1, 1, 0, 0, 2, 1, 256, 0, 0).flatMap { listOf(it.toByte(), (it shr 8).toByte()) }.toByteArray()
compositor.setShellScene(ArrayByteReader(header + byteArrayOf(-16, -16)))
val wire = compositor.applyAndComposite("app", ArrayByteReader(ByteArray(6) { 32 }), 0, 0, 3, 2, "first")
assertSame(wire.screenGray, wire.gray) // ShellScene.preview allocates its own pixels.
assertContentEquals(ByteArray(6) { 32 }, wire.screenGray)
assertEquals(1, wire.shellScene.layers.size)
val preview = assertNotNull(compositor.previewComposite())
assertContentEquals(byteArrayOf(-16, -16, 32, 32, 32, 32), preview.gray)
assertEquals(wire.fingerprint, preview.fingerprint)
assertContentEquals(wire.screenGray, preview.screenGray)
// Updates while hidden retain the newest frame. Preview reads don't
// consume the wire sequence or affect the next submitted frame.
val newer = compositor.applyAndComposite("app", ArrayByteReader(ByteArray(6) { 64 }), 0, 0, 3, 2, "second")
assertEquals(wire.seq + 1, newer.seq)
assertSame(newer.screenGray, newer.gray)
assertContentEquals(byteArrayOf(-16, -16, 64, 64, 64, 64), compositor.previewComposite()!!.gray)
compositor.setBlanked(true)
assertContentEquals(ByteArray(6), compositor.previewComposite()!!.gray)
compositor.setBlanked(false)
assertContentEquals(byteArrayOf(-16, -16, 64, 64, 64, 64), compositor.previewComposite()!!.gray)
}
}
@@ -0,0 +1,297 @@
package com.faceclaw.app
import kotlin.random.Random
import kotlin.test.*
internal expect fun testPlatform(): ProtocolPlatform
internal expect fun inflateRecords(records: List<ByteArray>): List<ByteArray>
internal fun record(packets: List<ByteArray>): ByteArray =
packets.flatMap { it.slice(9 until it.size - 2) }.toByteArray()
private fun hex(value: String) = value.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
private fun u16(bytes: ByteArray, offset: Int) =
(bytes[offset].toInt() and 255) or ((bytes[offset + 1].toInt() and 255) shl 8)
class ProtocolTest {
@Test
fun javaGoldenPacketsAndCrc() {
assertEquals(0x29b1, CfwTransport.crc("123456789".encodeToByteArray()))
assertEquals(0xffff, CfwTransport.crc(byteArrayOf()))
// Captured from the Java implementation before migration, including sequence wrap.
val expected =
listOf(
"aa21ff0c0101f000830b0f0078c331323334862b",
"aa21000c0101f000033536373839616263648c7b",
"aa2101050101f000436566de70",
)
val actual = CfwTransport.frame("123456789abcdef".encodeToByteArray(), 255, 3, 23)
assertEquals(expected.size, actual.size)
expected.zip(actual).forEach { (a, b) -> assertContentEquals(hex(a), b) }
}
@Test
fun framingBoundariesAndValidation() {
for (size in listOf(0, 1, 247, 252, 253, 65535)) {
val data = ByteArray(size) { it.toByte() }
for (mtu in listOf(23, 247, 512, 517)) {
val packets = CfwTransport.frame(data, 255, 2, mtu)
packets.forEachIndexed { i, packet ->
assertTrue(packet.size <= mtu - 3)
assertEquals((255 + i) and 255, packet[2].toInt() and 255)
assertEquals(packet.size - 8, packet[3].toInt() and 255)
assertEquals(
2 or (if (i == 0) 128 else 0) or (if (i == packets.lastIndex) 64 else 0),
packet[8].toInt() and 255,
)
assertEquals(
CfwTransport.crc(packet.copyOfRange(8, packet.size - 2)),
u16(packet, packet.size - 2),
)
}
val stream = record(packets)
assertEquals(size, u16(stream, 1))
assertEquals(CfwTransport.crc(data), u16(stream, 3))
assertContentEquals(data, stream.copyOfRange(5, stream.size))
}
}
for (invalid in listOf<ByteArray?>(null, ByteArray(65536))) assertFailsWith<
IllegalArgumentException
> {
CfwTransport.frame(invalid, 0, 3, 23)
}
for (stream in listOf(-1, 256)) assertFailsWith<IllegalArgumentException> {
CfwTransport.frame(byteArrayOf(), stream, 3, 23)
}
for (lens in listOf(0, 4)) assertFailsWith<IllegalArgumentException> {
CfwTransport.frame(byteArrayOf(), 0, lens, 23)
}
for (mtu in listOf(22, 518)) assertFailsWith<IllegalArgumentException> {
CfwTransport.frame(byteArrayOf(), 0, 3, mtu)
}
}
@Test
fun streamingCompressionRoundTripsAndResets() {
val transport = CfwTransport(testPlatform())
try {
val text = "shared history 👓 ".repeat(300).encodeToByteArray()
val inputs = listOf(text, text, byteArrayOf(), byteArrayOf(), text, text)
val records = inputs.mapIndexed { i, data ->
if (i == 5) transport.reset()
record(transport.encode(data, i, if (i < 4) 3 else 1, 247))
}
assertTrue(records[1].size < records[0].size)
assertTrue(records[0][0].toInt() and CfwTransport.RESET_CONTEXT != 0)
assertEquals(0, records[1][0].toInt() and CfwTransport.RESET_CONTEXT)
assertTrue(records[4][0].toInt() and CfwTransport.RESET_CONTEXT != 0)
assertTrue(records[5][0].toInt() and CfwTransport.RESET_CONTEXT != 0)
inputs.zip(inflateRecords(records)).forEach { (a, b) -> assertContentEquals(a, b) }
transport.close()
transport.close()
val reopened = record(transport.encode(text, 10, 1, 512))
assertTrue(reopened[0].toInt() and CfwTransport.RESET_CONTEXT != 0)
assertContentEquals(text, inflateRecords(listOf(reopened)).single())
} finally {
transport.close()
}
}
@Test
fun incompressibleMaximumFallsBackWithoutPoisoningHistory() {
val transport = CfwTransport(testPlatform())
try {
val data = Random(42).nextBytes(65535)
val raw = record(transport.encode(data, 255, 3, 517))
assertEquals(3 or CfwTransport.RESET_CONTEXT, raw[0].toInt())
val next = record(transport.encode(data.copyOf(1000), 0, 3, 517))
assertTrue(next[0].toInt() and CfwTransport.RESET_CONTEXT != 0)
val decoded = inflateRecords(listOf(raw, next))
assertContentEquals(data, decoded[0])
assertContentEquals(data.copyOf(1000), decoded[1])
} finally {
transport.close()
}
}
@Test
fun ackBatchesAndMalformedPackets() {
for (count in 1..4) {
val packet = ackPacket(count)
val acks = assertNotNull(CfwTransport.parseAcks(packet))
assertEquals(count, acks.size)
acks.forEachIndexed { i, ack ->
assertFalse(ack.nack)
assertEquals(255 - i, ack.streamId)
assertEquals(0x1234 + i, ack.messageId)
assertEquals(2, ack.lens)
assertEquals(0x4567 + i, ack.size)
assertEquals(0xabcd + i, ack.checksum)
}
assertEquals(255, assertNotNull(CfwTransport.parseAck(packet)).streamId)
// Every bit of the payload (including ACK trailers and CRC) is protected.
for (i in 8 until packet.size) {
val corrupt = packet.copyOf()
corrupt[i] = (corrupt[i].toInt() xor 1).toByte()
assertNull(CfwTransport.parseAcks(corrupt))
}
}
assertTrue(assertNotNull(CfwTransport.parseAck(ackPacket(1, 3))).nack)
assertNull(CfwTransport.parseAcks(ackPacket(2, 3)))
assertNull(CfwTransport.parseAcks(ackPacket(5)))
assertNull(CfwTransport.parseAcks(ackPacket(1, 2)))
for (index in listOf(0, 1, 3, 4, 5, 6, 7)) {
val corrupt = ackPacket(1)
corrupt[index] = (corrupt[index].toInt() xor 1).toByte()
assertNull(CfwTransport.parseAcks(corrupt))
}
val wrongLens = ackPacket(1)
wrongLens[12] = 3
sealAck(wrongLens)
assertNull(CfwTransport.parseAcks(wrongLens))
for (size in 0..18) assertNull(CfwTransport.parseAcks(ByteArray(size)))
assertNull(CfwTransport.parseAcks(null))
}
@Test
fun ackMatchingAndReplay() {
val input = byteArrayOf(1, 2, 3)
val message = message(input = input)
input[0] = 99
assertContentEquals(byteArrayOf(1, 2, 3), message.message)
fun ack(
lens: Int,
stream: Int = 100,
nack: Boolean = false,
size: Int = 3,
checksum: Int = message.cfwChecksum,
id: Int = 0,
) = CfwTransport.Ack(nack, stream, id, lens, size, checksum)
assertFalse(message.acceptCfwAck(null))
assertFalse(message.acceptCfwAck(ack(1, stream = 99)))
assertFalse(message.acceptCfwAck(ack(1, size = 4)))
assertFalse(message.acceptCfwAck(ack(1, checksum = 0)))
assertFalse(message.acceptCfwAck(ack(3)))
assertFalse(message.acceptCfwAck(ack(1, id = 1)))
assertEquals(0, message.cfwAckLenses)
assertFalse(message.acceptCfwAck(ack(1)))
assertFalse(message.acceptCfwAck(ack(1)))
assertTrue(message.acceptCfwAck(ack(2)))
assertFalse(message.acceptCfwAck(ack(1, nack = true, size = 0, checksum = 0)))
assertFalse(message.acceptCfwAck(ack(2)))
message.ackDeadlineAtMs = 500
message.ackPayload = byteArrayOf(1)
message.prepareCfwReplay(101)
assertEquals(1, message.cfwRetries)
assertFalse(message.cfwRetryPending)
assertEquals(0, message.cfwAckLenses)
assertEquals(0L, message.ackDeadlineAtMs)
assertTrue(message.ackPayload.isEmpty())
assertFalse(message.acceptCfwAck(ack(1)))
assertFalse(message.acceptCfwAck(ack(1, stream = 101)))
assertTrue(message.acceptCfwAck(ack(2, stream = 101)))
var callbacks = 0
message.onAck = MessageCallback { callbacks++ }
message.onAck!!.run()
assertEquals(1, callbacks)
}
@Test
fun evictionWaitsForAllEarlierReplayableCommands() {
val earlier = message(input = byteArrayOf(19, 0, 0))
val eviction = message(input = byteArrayOf(22, 1, 0, 0, 0))
val upload = message(input = byteArrayOf(21, 1, 0))
assertFalse(CfwMessageWindow.canSend(listOf(earlier), eviction))
earlier.cfwAckLenses = 3 // Still retained behind an unresolved window head.
assertFalse(CfwMessageWindow.canSend(listOf(earlier), eviction))
assertTrue(CfwMessageWindow.canSend(emptyList(), eviction))
assertTrue(CfwMessageWindow.canSend(listOf(message(sid = 1)), eviction))
assertTrue(CfwMessageWindow.canSend(listOf(earlier), upload))
assertTrue(CfwMessageWindow.canSend(listOf(eviction), upload))
}
@Test
fun orderedCompletionAndWholeWindowRecovery() {
val head = message()
val tail = message()
val stock = message(sid = 1)
val window = listOf(stock, head, tail)
tail.cfwAckLenses = 3
assertNull(CfwMessageWindow.acknowledgedHead(window))
assertTrue(CfwMessageWindow.replayWindow(window, 100).isEmpty())
head.ackDeadlineAtMs = 100
assertTrue(CfwMessageWindow.replayWindow(window, 99).isEmpty())
assertEquals(listOf(head, tail), CfwMessageWindow.replayWindow(window, 100))
head.cfwAckLenses = 3
assertSame(head, CfwMessageWindow.acknowledgedHead(window))
assertTrue(CfwMessageWindow.replayWindow(window, 100).isEmpty())
tail.cfwRetryPending = true
assertEquals(listOf(head, tail), CfwMessageWindow.replayWindow(window, 100))
head.cfwRetryPending = true
assertNull(CfwMessageWindow.acknowledgedHead(window))
}
@Test
fun magicPoolExhaustionLruAndReleaseRecords() {
var now = 123L
val platform =
object : ProtocolPlatform by testPlatform() {
override fun elapsedRealtimeMs() = now
}
val pool = BleMagicPool(platform)
assertEquals((100..255).toList(), List(156) { pool.allocate() })
assertFailsWith<IllegalStateException> { pool.allocate() }
pool.release(1, 101, "first", "ack")
pool.release(1, 100, null, null)
now = 456
pool.release(2, 101, "other", "timeout") // duplicate release must not allocate twice
assertEquals(101, pool.allocate())
assertEquals(100, pool.allocate())
assertFailsWith<IllegalStateException> { pool.allocate() }
val first = assertNotNull(pool.getReleaseRecord(1, 101))
assertEquals(123L, first.releasedAtMs)
assertEquals("first", first.label)
assertEquals(456L, assertNotNull(pool.getReleaseRecord(2, 101)).releasedAtMs)
assertEquals("", assertNotNull(pool.getReleaseRecord(1, 100)).reason)
for (invalid in listOf(-1, 99, 256)) {
pool.release(1, invalid, "bad", "bad")
assertNull(pool.getReleaseRecord(1, invalid))
}
}
}
private fun message(sid: Int = CfwTransport.SID, input: ByteArray = byteArrayOf(1, 2, 3)) =
OutboundMessage("test", "test", sid, 0, 100, input, 500, 0, false)
private fun ackPacket(count: Int, kind: Int = 1): ByteArray {
val packet = ByteArray(19 + (count - 1) * 7)
packet[0] = 0xaa.toByte()
packet[1] = 0x12
packet[3] = (packet.size - 8).toByte()
packet[4] = 1
packet[5] = 1
packet[6] = 0xf0.toByte()
packet[8] = kind.toByte()
packet[12] = 2
fun put16(offset: Int, value: Int) {
packet[offset] = value.toByte()
packet[offset + 1] = (value ushr 8).toByte()
}
for (i in 0 until count) {
val offset = if (i == 0) 9 else 17 + (i - 1) * 7
packet[offset] = (255 - i).toByte()
put16(offset + 1, 0x1234 + i)
put16(offset + (if (i == 0) 4 else 3), 0x4567 + i)
put16(offset + (if (i == 0) 6 else 5), 0xabcd + i)
}
sealAck(packet)
return packet
}
private fun sealAck(packet: ByteArray) {
val crc = CfwTransport.crc(packet.copyOfRange(8, packet.size - 2))
packet[packet.size - 2] = crc.toByte()
packet[packet.size - 1] = (crc ushr 8).toByte()
}
@@ -0,0 +1,178 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
private class FakeConnection(input: String, private val bytesOverride: ByteArray? = null) : RemoteInputConnection {
private val bytes = bytesOverride ?: input.encodeToByteArray()
private var index = 0
private val written = ByteSink()
var closed = false
val output: String get() = written.toByteArray().decodeToString()
override fun readByte(timeoutMs: Long): Int = if (index < bytes.size) bytes[index++].toInt() and 255 else -1
override fun write(bytes: ByteArray) = written.write(bytes)
override fun close() { closed = true }
}
private class FakePort(platform: ProtocolPlatform) : LocalServerPort {
val connections = BlockingQueue<FakeConnection>(platform)
var localAddresses = setOf("127.0.0.1", "192.168.1.5")
var bindFails = false
var listener: FakeListener? = null
inner class FakeListener : RemoteInputListener {
override var isClosed = false
override fun accept(): RemoteInputConnection? {
while (!isClosed) {
val next = connections.poll(20)
if (next != null) return next
}
return null
}
override fun close() { isClosed = true }
}
override fun isLocalUnicastAddress(address: String): Boolean = address in localAddresses
override fun bind(address: String, port: Int): RemoteInputListener {
if (bindFails) throw IllegalStateException("in use")
return FakeListener().also { listener = it }
}
}
private fun waitFor(timeoutMs: Long = 3000, condition: () -> Boolean): Boolean {
val platform = testPlatform()
val deadline = platform.elapsedRealtimeMs() + timeoutMs
while (platform.elapsedRealtimeMs() < deadline) {
if (condition()) return true
sleepMs(5)
}
return condition()
}
class RemoteInputSessionTest {
private val platform = testPlatform()
private val random = object : RandomSource { override fun nextBytes(count: Int) = ByteArray(count) { it.toByte() } }
private fun dispatchOnThread(action: () -> Unit) = startThread("remote-input-dispatch", true, action)
private fun session(port: FakePort, requestTimeoutMs: Long = 5000, readTimeoutMs: Long = 5000) =
RemoteInputSession(port, random, ::dispatchOnThread, platform, requestTimeoutMs = requestTimeoutMs, readTimeoutMs = readTimeoutMs)
@Test
fun startValidatesAddressesAndBindFailures() {
val port = FakePort(platform)
val session = session(port)
assertEquals("Invalid local address.", session.start(7000, "localhost"))
assertEquals("Address is not assigned to a local interface.", session.start(7000, "10.0.0.9"))
port.bindFails = true
assertEquals("Could not open local input port 7000.", session.start(7000, "127.0.0.1"))
port.bindFails = false
assertEquals("", session.start(7000, "127.0.0.1"))
assertEquals("", session.start(7000, "127.0.0.1"), "second start is a no-op")
session.stop()
assertTrue(waitFor { port.listener!!.isClosed })
assertTrue(RemoteInputSession.isNumericLocalAddress("fe80::1%en0"))
assertFalse(RemoteInputSession.isNumericLocalAddress("example.com"))
}
@Test
fun requestIsPublishedAnsweredAndWrittenBack() {
val port = FakePort(platform)
val session = session(port)
var notified = 0
session.setRequestListener { notified++ }
assertEquals("", session.start(7000, "127.0.0.1"))
val connection = FakeConnection("{\"token\":\"t\",\"text\":\"hi\"}\n")
port.connections.put(connection)
assertTrue(waitFor { notified == 1 })
val pending = Json.parseObject(session.nextRequest()!!)
assertEquals(1L, pending["id"].asLong())
assertEquals("{\"token\":\"t\",\"text\":\"hi\"}", pending["body"].asString())
assertTrue(pending["expiresAt"].asLong()!! > currentTimeMillis())
assertNull(session.nextRequest(), "consumed once")
session.complete(99L, "{\"ok\":false}")
assertFalse(waitFor(100) { connection.output.isNotEmpty() }, "wrong id is ignored")
session.complete(1L, "{\"ok\":true}")
assertTrue(waitFor { connection.output == "{\"ok\":true}\n" })
assertTrue(waitFor { connection.closed })
session.stop()
}
@Test
fun timeoutRepliesWithTheTimeoutResponse() {
val port = FakePort(platform)
val session = session(port, requestTimeoutMs = 150)
assertEquals("", session.start(7000, "127.0.0.1"))
val connection = FakeConnection("slow\n")
port.connections.put(connection)
assertTrue(waitFor { connection.output == RemoteInputSession.TIMEOUT_RESPONSE + "\n" })
assertNull(session.nextRequest(), "expired request is dropped")
session.stop()
}
@Test
fun oversizedAndIncompleteFramesGetNoReply() {
val port = FakePort(platform)
val session = session(port)
var notified = 0
session.setRequestListener { notified++ }
assertEquals("", session.start(7000, "127.0.0.1"))
val huge = FakeConnection("", ByteArray(RemoteInputSession.MAX_FRAME_BYTES + 2) { 'a'.code.toByte() }.also { it[it.size - 1] = '\n'.code.toByte() })
port.connections.put(huge)
assertTrue(waitFor { huge.closed })
assertEquals("", huge.output)
val partial = FakeConnection("no newline")
port.connections.put(partial)
assertTrue(waitFor { partial.closed })
assertEquals("", partial.output)
val invalidUtf8 = FakeConnection("", byteArrayOf(0xff.toByte(), 0xfe.toByte(), '\n'.code.toByte()))
port.connections.put(invalidUtf8)
assertTrue(waitFor { invalidUtf8.closed })
assertEquals("", invalidUtf8.output)
assertEquals(0, notified)
assertNull(session.nextRequest())
session.stop()
}
@Test
fun stopWhilePendingReleasesTheServingThread() {
val port = FakePort(platform)
val session = session(port)
var notified = 0
session.setRequestListener { notified++ }
assertEquals("", session.start(7000, "127.0.0.1"))
val connection = FakeConnection("pending\n")
port.connections.put(connection)
assertTrue(waitFor { notified == 1 })
session.stop()
assertTrue(waitFor { connection.closed })
assertNull(session.nextRequest())
assertEquals("", session.start(7001, "127.0.0.1"), "restart after stop")
session.stop()
}
@Test
fun helpersFilterInterfacesAndHashTokens() {
val all = listOf(
InterfaceAddress("lo0", "127.0.0.1", up = true, pointToPoint = false, loopback = true, linkLocal = false, anyLocal = false),
InterfaceAddress("wlan0", "192.168.1.5", up = true, pointToPoint = false, loopback = false, linkLocal = false, anyLocal = false),
InterfaceAddress("wlan0", "fe80::1%wlan0", up = true, pointToPoint = false, loopback = false, linkLocal = true, anyLocal = false),
InterfaceAddress("tun0", "100.64.0.2", up = true, pointToPoint = true, loopback = false, linkLocal = false, anyLocal = false),
InterfaceAddress("eth0", "10.0.0.2", up = false, pointToPoint = false, loopback = false, linkLocal = false, anyLocal = false),
InterfaceAddress("any", "0.0.0.0", up = true, pointToPoint = false, loopback = false, linkLocal = false, anyLocal = true),
)
assertEquals(
"[{\"name\":\"wlan0\",\"address\":\"192.168.1.5\",\"pointToPoint\":false},{\"name\":\"tun0\",\"address\":\"100.64.0.2\",\"pointToPoint\":true}]",
RemoteInputSession.interfacesJson(all),
)
assertEquals("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", RemoteInputSession.tokenHash("abc"))
val session = session(FakePort(platform))
assertEquals("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", session.randomSecret())
}
}
@@ -0,0 +1,211 @@
package com.faceclaw.app
import kotlin.test.*
class ResourceCacheTest {
private fun resource(size: Int, value: Int) = CachedResource(ByteArray(size) { value.toByte() })
private fun u16(bytes: ByteArray, offset: Int) = (bytes[offset].toInt() and 255) or ((bytes[offset + 1].toInt() and 255) shl 8)
private fun u32(bytes: ByteArray, offset: Int) = u16(bytes, offset) or (u16(bytes, offset + 2) shl 16)
private fun uploaded(commands: List<ByteArray>): Map<Int, ByteArray> {
val resources = HashMap<Int, ByteArray>()
val received = HashMap<Int, Int>()
for (command in commands) {
assertTrue(command.size <= 3600)
if (command[0].toInt() != 21) continue
var pos = 3
val seen = HashSet<Int>()
repeat(u16(command, 1)) {
val id = u16(command, pos)
assertTrue(id in 0..511 && seen.add(id))
val total = u32(command, pos + 2)
val offset = u16(command, pos + 6)
val length = u16(command, pos + 8)
assertEquals(received[id] ?: 0, offset)
val bytes = resources.getOrPut(id) { ByteArray(total) }
command.copyInto(bytes, offset, pos + 10, pos + 10 + length)
received[id] = offset + length
pos += 10 + length
}
assertEquals(command.size, pos)
}
resources.forEach { (id, data) -> assertEquals(data.size, received[id]) }
return resources
}
@Test fun contentAddressingAndWireVector() {
val cache = ResourceCacheState()
val image = CachedResource(byteArrayOf(1, 1, 31))
val ids = cache.prepare(listOf(image, CachedResource(image.bytes)))
assertContentEquals(intArrayOf(0, 0), ids)
val commands = cache.drainCommands(3600)
assertEquals(22, commands.first()[0].toInt())
assertEquals(512, u16(commands.first(), 1))
assertEquals(511, u16(commands.first(), 1025))
assertContentEquals(byteArrayOf(21, 1, 0, 0, 0, 3, 0, 0, 0, 0, 0, 3, 0, 1, 1, 31), commands.last())
assertContentEquals(image.bytes, uploaded(commands).getValue(0))
assertEquals(2068, cache.usedBytes())
assertEquals(0, cache.prepare(listOf(image))[0])
assertTrue(cache.drainCommands(3600).isEmpty())
cache.reset(); cache.prepare(listOf(image))
assertEquals(22, cache.drainCommands(3600).first()[0].toInt())
}
@Test fun exactly64KiBUploadsInBoundedContiguousChunks() {
val cache = ResourceCacheState()
val data = CachedResource(ByteArray(65536) { (it * 37).toByte() })
assertEquals(0, cache.prepare(listOf(data))[0])
val commands = cache.drainCommands(3600)
assertTrue(commands.count { it[0].toInt() == 21 } > 1)
assertContentEquals(data.bytes, uploaded(commands).getValue(0))
assertEquals(-1, cache.prepare(listOf(resource(65537, 1)))[0])
assertTrue(cache.drainCommands(3600).isEmpty())
assertEquals(0, cache.resourceId(data))
}
@Test fun lruEvictsByBytesAndProtectsAllCurrentFrameHits() {
val cache = ResourceCacheState()
val a = resource(60000, 1); val b = resource(60000, 2); val c = resource(60000, 3); val d = resource(60000, 4)
assertContentEquals(intArrayOf(0, 1, 2), cache.prepare(listOf(a, b, c)))
cache.drainCommands(3600)
cache.prepare(listOf(a)); cache.drainCommands(3600) // b is oldest now.
assertContentEquals(intArrayOf(1, 2), cache.prepare(listOf(d, c))) // protect later hit c before d.
val commands = cache.drainCommands(3600)
assertContentEquals(byteArrayOf(22, 1, 0, 1, 0), commands.first())
assertEquals(-1, cache.resourceId(b))
assertEquals(0, cache.resourceId(a)); assertEquals(2, cache.resourceId(c))
assertEquals(1, cache.resourceId(d))
assertContentEquals(d.bytes, uploaded(commands).getValue(1))
val tooLarge = cache.prepare(listOf(a, c, d, b))
assertEquals(-1, tooLarge.last())
assertTrue(cache.drainCommands(3600).isEmpty())
assertEquals(3, cache.residentCount())
}
@Test fun idPressureUsesLruEvenWhenBytesAreAvailable() {
val cache = ResourceCacheState()
val resources = (0..512).map { CachedResource(byteArrayOf(it.toByte(), (it ushr 8).toByte())) }
assertContentEquals(IntArray(512) { it }, cache.prepare(resources.take(512)))
cache.drainCommands(3600)
cache.prepare(listOf(resources[0])); cache.drainCommands(3600)
assertEquals(1, cache.prepare(listOf(resources[512]))[0])
val commands = cache.drainCommands(3600)
assertContentEquals(byteArrayOf(22, 1, 0, 1, 0), commands.first())
assertEquals(0, cache.resourceId(resources[0]))
assertEquals(-1, cache.resourceId(resources[1]))
}
@Test fun rejectedPlansRestoreResidencyAndLru() {
val cache = ResourceCacheState()
val resources = (0..3).map { resource(65536, it) }
cache.prepare(resources.take(3)); cache.drainCommands(3600)
val rollback = cache.checkpoint()
cache.prepare(listOf(resources[3]))
assertEquals(-1, cache.resourceId(resources[0]))
rollback()
assertEquals(0, cache.resourceId(resources[0])); assertEquals(-1, cache.resourceId(resources[3]))
assertTrue(cache.drainCommands(3600).isEmpty())
cache.prepare(listOf(resources[3]))
assertContentEquals(byteArrayOf(22, 1, 0, 0, 0), cache.drainCommands(3600).first())
}
@Test fun imagePlannerEmitsResourceIdsAndReusesResidency() {
val cache = ResourceCacheState()
val id = ImageAtlas.ensure("resource-test-white", 2, 2, ArrayByteReader(ByteArray(4) { -1 }))
val pixels = ByteArray(8 * 4)
for (y in 0..1) for (x in 0..1) pixels[y * 8 + x] = -1
val packed = BmpUtil.pack4bppFromGray8(pixels, 8, 4)
val draws = arrayOf(SurfaceCompositor.ScreenDraw.image(id, 0, 0))
fun plan() = assertNotNull(TexturePlanner.plan(null, packed, 8, 4, draws, cache, 1, true, 8, testPlatform()))
val cold = plan()
assertEquals(1, cold.drawnImages)
assertContentEquals(byteArrayOf(19, 0, 0, 0, 0, 0, 0, 31), cold.payload.takeLast(8).toByteArray())
assertTrue(cold.resourceCommands.isNotEmpty())
val warm = plan()
assertTrue(warm.resourceCommands.isEmpty()); assertContentEquals(cold.payload, warm.payload)
cache.reset(); assertTrue(plan().resourceCommands.isNotEmpty())
assertNull(TexturePlanner.plan(null, ByteArray(packed.size), 8, 4, draws, cache, 1, true, 8, testPlatform()))
}
@Test fun imagePixelLoopsPreserveClippingTransparencyAndNeighborNibbles() {
val width = 12
val height = 8
for (imageWidth in listOf(3, 4, 5, 9)) {
val imageHeight = 5
val pixels = ByteArray(imageWidth * imageHeight) { i ->
if (i % 3 == 0) 0 else (((i % 15) + 1) * 16).toByte()
}
val id = ImageAtlas.ensure("pixel-loop-$imageWidth", imageWidth, imageHeight, ArrayByteReader(pixels))
for (left in listOf(-1, 0, 1, 2, 10, 11, 14)) for (top in listOf(-1, 0, 1, 7, 9)) {
val gray = ByteArray(width * height) { ((it % 15 + 1) * 16).toByte() }
val visibleInk = ArrayList<Int>()
for (row in 0 until imageHeight) for (col in 0 until imageWidth) {
val x = left + col; val y = top + row; val value = pixels[row * imageWidth + col]
if (x in 0 until width && y in 0 until height && value.toInt() != 0) {
gray[y * width + x] = value
visibleInk.add(y * width + x)
}
}
val expected = BmpUtil.pack4bppFromGray8(gray, width, height)
val draws = arrayOf(SurfaceCompositor.ScreenDraw.image(id, left, top))
val plan = TexturePlanner.plan(null, expected, width, height, draws, ResourceCacheState(), 1, true, 8, testPlatform())
if (left < 0 || top < 0 || left >= width || top >= height) {
assertNull(plan) // The wire format cannot replay negative image origins.
continue
}
val result = assertNotNull(plan, "$imageWidth at $left,$top")
assertEquals(1, result.drawnImages)
val actual = ByteArray(expected.size) { 0x55 }
DisplayListRenderer(uploaded(result.resourceCommands)).execute(
DrawProtocol.sequence(DrawProtocol.fromOptimized(result.payload, width, height)),
DisplayListRenderer.Target(actual, width, height))
assertContentEquals(expected, actual, "$imageWidth at $left,$top")
// A conflicting visible ink pixel must reject the cached draw.
if (visibleInk.isNotEmpty()) {
val offset = visibleInk.first()
gray[offset] = 0
assertNull(TexturePlanner.plan(null, BmpUtil.pack4bppFromGray8(gray, width, height),
width, height, draws, ResourceCacheState(), 1, true, 8, testPlatform()))
}
}
}
}
private fun registerFont(key: String, encodings: List<Int>, size: Int = 2): Int {
val out = ByteSink(); val name = key.encodeToByteArray()
out.write(name.size); out.write(name, 0, name.size); out.write(size)
out.write(encodings.size); out.write(0)
for (encoding in encodings) {
out.write(encoding); repeat(3) { out.write(0) }
out.write(0); out.write(0); out.write(size); out.write(size)
repeat(size * ((size + 1) / 2)) { out.write(0x12) }
}
GlyphAtlas.registerAa(ArrayByteReader(out.toByteArray()))
return GlyphAtlas.fontId(key)
}
@Test fun fontTablesUseRelativeU16OffsetsAndGrowOnDemand() {
val id = registerFont("resource-font-relative", listOf(65, 66))
val first = FontResourceAtlas.get(id, setOf(65))
assertEquals(193, u16(first.resource.bytes, 1 + (65 - 32) * 2))
assertEquals(0, u16(first.resource.bytes, 1 + (66 - 32) * 2))
assertSame(first, FontResourceAtlas.get(id, setOf(65)))
val second = FontResourceAtlas.get(id, setOf(66))
assertTrue(second.encodings.containsAll(setOf(65, 66)))
assertEquals(193 + GlyphAtlas.get(id, 65)!!.cachedBytes.size, u16(second.resource.bytes, 1 + (66 - 32) * 2))
val cache = ResourceCacheState()
cache.prepare(listOf(second.resource)); val commands = cache.drainCommands(3600)
assertContentEquals(second.resource.bytes, uploaded(commands).getValue(0))
}
@Test fun oversizedFontsPrioritizeTheCurrentFrameWithin64KiB() {
val id = registerFont("resource-font-limit", listOf(65, 66), 255)
val a = FontResourceAtlas.get(id, setOf(65))
assertEquals(setOf(65), a.encodings)
val b = FontResourceAtlas.get(id, setOf(66))
assertEquals(setOf(66), b.encodings)
assertTrue(b.resource.bytes.size <= 65536)
assertEquals(0, u16(b.resource.bytes, 1 + (65 - 32) * 2))
assertEquals(193, u16(b.resource.bytes, 1 + (66 - 32) * 2))
}
}
@@ -0,0 +1,149 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
class ResumableDownloadTest {
private class Storage : DownloadStorage {
val files = HashMap<String, ByteArray>()
override fun length(path: String): Long = files[path]?.size?.toLong() ?: -1L
override fun prepareParent(path: String) {}
override fun openWrite(path: String, append: Boolean): FileSink {
if (!append) files[path] = ByteArray(0)
return object : FileSink {
override fun write(bytes: ByteArray, offset: Int, length: Int) {
files[path] = (files[path] ?: ByteArray(0)) + bytes.copyOfRange(offset, offset + length)
}
override fun close() {}
}
}
override fun readAll(path: String, consumer: (ByteArray, Int) -> Boolean): Long {
val data = files[path] ?: return 0
var at = 0L
for (chunk in data.toList().chunked(7)) {
val bytes = chunk.toByteArray()
if (!consumer(bytes, bytes.size)) break
at += bytes.size
}
return at
}
override fun rename(from: String, to: String): Boolean { files[to] = files.remove(from) ?: return false; return true }
override fun delete(path: String): Boolean = files.remove(path) != null
}
private class Transport(val content: ByteArray, val honorRange: Boolean = true, val truncateAt: Int = -1) : DownloadTransport {
var lastRange = -1L
override fun open(url: String, rangeFrom: Long): DownloadResponse {
lastRange = rangeFrom
val start = if (honorRange) rangeFrom.toInt() else 0
val end = if (truncateAt >= 0) minOf(truncateAt, content.size) else content.size
val body = content.copyOfRange(start, end)
var at = 0
return object : DownloadResponse {
override val code: Int = if (honorRange && rangeFrom > 0) 206 else 200
override val contentLength: Long = body.size.toLong()
override fun read(buffer: ByteArray): Int {
if (at >= body.size) return -1
val n = minOf(5, body.size - at)
body.copyInto(buffer, 0, at, at + n)
at += n
return n
}
override fun close() {}
}
}
}
private class Events : FaceclawModelDownloaderListener {
val progress = ArrayList<Pair<Long, Long>>()
var done: String? = null
var error: String? = null
override fun onProgress(bytesDownloaded: Long, totalBytes: Long) { progress.add(bytesDownloaded to totalBytes) }
override fun onDone(path: String?) { done = path }
override fun onError(message: String?) { error = message }
}
private val content = ByteArray(40) { (it * 3).toByte() }
private val sha = sha256Hex(content)
private fun run(storage: Storage, transport: Transport, expectedSha: String? = sha, total: Long = content.size.toLong()): Events {
val events = Events()
var clock = 0L
ResumableDownload("http://x/m", "/dest/model", expectedSha, total, transport, storage, events) { clock += 600; clock }.run()
return events
}
@Test
fun freshDownloadVerifiesAndRenames() {
val storage = Storage()
val transport = Transport(content)
val events = run(storage, transport)
assertNull(events.error)
assertEquals("/dest/model", events.done)
assertEquals(content.toList(), storage.files["/dest/model"]!!.toList())
assertEquals(0L, transport.lastRange)
assertTrue(events.progress.isNotEmpty() && events.progress.last().second == 40L)
val again = run(storage, transport)
assertEquals("/dest/model", again.done)
}
@Test
fun resumesFromPartWhenServerHonorsRange() {
val storage = Storage()
storage.files["/dest/model.part"] = content.copyOfRange(0, 17)
val transport = Transport(content)
val events = run(storage, transport)
assertEquals(17L, transport.lastRange)
assertNull(events.error)
assertEquals(content.toList(), storage.files["/dest/model"]!!.toList())
}
@Test
fun restartsWhenServerIgnoresRange() {
val storage = Storage()
storage.files["/dest/model.part"] = ByteArray(17) { 1 }
val transport = Transport(content, honorRange = false)
val events = run(storage, transport)
assertEquals(17L, transport.lastRange)
assertNull(events.error)
assertEquals(content.toList(), storage.files["/dest/model"]!!.toList())
}
@Test
fun checksumMismatchDeletesPart() {
val storage = Storage()
val events = run(storage, Transport(content), expectedSha = "00".repeat(32))
assertEquals("Model download was corrupted (checksum mismatch); download it again", events.error)
assertNull(storage.files["/dest/model.part"])
assertNull(storage.files["/dest/model"])
}
@Test
fun shortBodyKeepsPartForResume() {
val storage = Storage()
val events = run(storage, Transport(content, truncateAt = 30))
assertEquals("Model download ended early (30 of 40 bytes); try again to resume", events.error)
assertEquals(30, storage.files["/dest/model.part"]!!.size)
val resumed = run(storage, Transport(content))
assertNull(resumed.error)
assertEquals(content.toList(), storage.files["/dest/model"]!!.toList())
}
@Test
fun httpErrorIsReported() {
val storage = Storage()
val transport = object : DownloadTransport {
override fun open(url: String, rangeFrom: Long): DownloadResponse = object : DownloadResponse {
override val code = 404
override val contentLength = -1L
override fun read(buffer: ByteArray) = -1
override fun close() {}
}
}
val events = Events()
ResumableDownload("u", "/dest/model", null, 0, transport, storage, events).run()
assertEquals("Model download failed: HTTP 404", events.error)
}
}
@@ -0,0 +1,240 @@
package com.faceclaw.app
import kotlin.concurrent.Volatile
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
private const val RING = "CC:00:00:00:00:03"
/**
* A ring that answers health requests through the session's real notification
* path: each REQ gets DATA page `cmd*10+1`, then its RSP; the ACK for a page
* ending in 1 triggers page `+1`, so the transfer is ACK-paced like the real
* ring's backlog.
*/
private class FakeRingLink(private val platform: ProtocolPlatform) : SessionLink {
lateinit var core: GlassesSessionCore
private val lock = platform.createLock()
private val writesList = ArrayList<String>()
@Volatile var failAck = false
@Volatile var answer = true
@Volatile var delayRsp = false
@Volatile var requestStarted = false
val writes: List<String>
get() = lock.withLock { writesList.toList() }
private fun deliver(frame: ByteArray) = core.onNotification(RING, BleProtocol.R1_NOTIFY_CHAR_UUID, frame)
private fun page(cmdHi: Int, pageSeq: Int) =
deliver(RingProtocol.buildFrame(RingProtocol.CHAN_HEALTH, RingProtocol.KIND_DATA, cmdHi,
RingProtocol.CMD_LO_HEALTH, pageSeq, byteArrayOf(0, 0)))
private fun rsp(cmdHi: Int) =
deliver(RingProtocol.buildFrame(RingProtocol.CHAN_HEALTH, RingProtocol.KIND_RSP, cmdHi,
RingProtocol.CMD_LO_HEALTH, 0, byteArrayOf(0, 0)))
override fun writeFrames(address: String, characteristicUuid: String, frames: List<ByteArray>, mode: GattWriteMode, timeoutMs: Int): Boolean {
assertEquals(RING, address)
assertEquals(BleProtocol.R1_WRITE_CHAR_UUID, characteristicUuid)
val frame = RingProtocol.parse(frames.single())!!
if (frame.kind == RingProtocol.KIND_ACK) {
if (failAck) return false
val pageSeq = frame.payload[6].toInt() and 0xff
val cmdHi = frame.payload[3].toInt() and 0xff
lock.withLock { writesList.add("ack:$pageSeq") }
// A write longer than the idle timeout: page two arrives only
// after page one's ACK has actually completed.
sleepMs(130)
if (pageSeq % 10 == 1) {
startThread("ring-page", true) {
sleepMs(5)
page(cmdHi, pageSeq + 1)
}
}
} else if (frame.chan == RingProtocol.CHAN_HEALTH && frame.kind == RingProtocol.KIND_REQ) {
requestStarted = true
lock.withLock { writesList.add("req:" + frame.cmdHi) }
if (answer) {
page(frame.cmdHi, frame.cmdHi * 10 + 1)
if (delayRsp) {
startThread("ring-rsp", true) {
sleepMs(20)
rsp(frame.cmdHi)
}
} else {
rsp(frame.cmdHi)
}
}
}
// Device-channel pings between health types are not answered.
return true
}
override fun connect(address: String, timeoutMs: Int): Boolean = true
override fun requestHighPriority(address: String) {}
override fun requestMtu(address: String, mtu: Int, timeoutMs: Int): Boolean = true
override fun negotiatedMtu(address: String): Int = 247
override fun discoverServices(address: String, timeoutMs: Int): Boolean = true
override fun enableNotifications(address: String, characteristicUuid: String, enable: Boolean, timeoutMs: Int): Boolean = true
override fun disconnect(address: String) {}
override fun close() {}
override fun isBonded(address: String): Boolean = true
override fun prepareBenchmarkLink(address: String, mode: Int) {}
override fun recordDisplayFrameSent() {}
}
private class RingHost : SessionHost {
@Volatile var journalFails = false
val journal = ArrayList<String>()
override fun postToMain(action: () -> Unit) = action()
override fun currentThreadDispatcher(): SessionDispatcher = SessionDispatcher { it() }
override fun isPhoneLocked(): Boolean = false
override fun setScreenWakeLock(on: Boolean) {}
override fun isEvenAppActive(): Boolean = false
override fun startWorker(body: () -> Unit) {}
override fun joinWorker(timeoutMs: Long) {}
override fun supportsRingHealth(): Boolean = true
override fun appendRingFrameJournal(line: String) {
if (journalFails) throw IllegalStateException("disk full")
synchronizedAdd(line)
}
private val lock = testPlatform().createLock()
private fun synchronizedAdd(line: String) = lock.withLock { journal.add(line) }
override fun log(level: SessionLogLevel, tag: String, message: String, error: Throwable?) {}
}
/** A core whose ring link is up, without running the glasses worker. */
private class RingSession {
val platform = testPlatform()
val link = FakeRingLink(platform)
val host = RingHost()
val core = GlassesSessionCore(link, host, FrameTimingsCore(platform), platform,
"AA:00:00:00:00:01", "AA:00:00:00:00:02", RING)
init {
link.core = core
core.ringHealthRspTimeoutMs = 500
core.ringHealthDataIdleMs = 100
core.monitor.withLock {
core.running = true
core.ringConnected = true
core.ringNotificationsReady = true
}
}
fun outboundSize(): Int = core.monitor.withLock { core.ringOutbound.size }
}
class RingHealthTransferTest {
@Test fun shutdownCancelsAnRspWait() {
val s = RingSession()
s.link.answer = false
s.core.ringHealthRspTimeoutMs = 10_000
val done = Latch(1, s.platform)
startThread("ring-pull", true) {
s.core.requestRingHealth()
done.countDown()
}
val deadline = s.platform.elapsedRealtimeMs() + 1000
while (!s.link.requestStarted && s.platform.elapsedRealtimeMs() < deadline) sleepMs(5)
assertTrue(s.link.requestStarted, "no request")
val start = s.platform.elapsedRealtimeMs()
s.core.monitor.withLock {
s.core.running = false
s.core.monitor.signalAll()
}
assertTrue(done.await(300), "ring pull did not stop")
assertTrue(s.platform.elapsedRealtimeMs() - start < 300, "session lock blocked")
}
@Test fun ackPacedPagesDrainBeforeTheNextType() {
val s = RingSession()
s.link.delayRsp = true
assertTrue(s.core.requestRingHealth(), "pull failed")
val expected = RingProtocol.HEALTH_COMMANDS.flatMap { command ->
listOf("req:$command", "ack:" + (command * 10 + 1), "ack:" + (command * 10 + 2))
}
assertEquals(expected, s.link.writes, "premature next type")
// Every intact frame (each page and each RSP) was journaled.
assertEquals(expected.count { it.startsWith("ack:") } + RingProtocol.HEALTH_COMMANDS.size, s.host.journal.size)
}
@Test fun failedAckAbortsAndStaysQueuedForRetry() {
val s = RingSession()
s.link.failAck = true
assertFalse(s.core.requestRingHealth(), "failed ACK completed pull")
assertEquals(1, s.link.writes.size, "advanced after failed ACK")
assertEquals(1, s.outboundSize(), "failed ACK was discarded")
s.link.failAck = false
assertTrue(s.core.awaitRingHealthDataIdle(s.core.ringHealthDataIdleMs), "retry failed")
assertEquals(0, s.outboundSize(), "retry did not drain ACKs")
}
@Test fun missingRspAbortsWithoutAdvancing() {
val s = RingSession()
s.link.answer = false
assertFalse(s.core.requestRingHealth(), "missing RSP completed pull")
assertEquals(1, s.link.writes.size, "advanced without RSP")
}
@Test fun disconnectFailsTheDataWait() {
val s = RingSession()
s.core.monitor.withLock { s.core.ringConnected = false }
assertFalse(s.core.awaitRingHealthDataIdle(100), "disconnect completed transfer")
}
@Test fun unjournaledPageIsNotAcknowledged() {
val s = RingSession()
s.host.journalFails = true
s.core.onNotification(RING, BleProtocol.R1_NOTIFY_CHAR_UUID,
RingProtocol.buildFrame(RingProtocol.CHAN_HEALTH, RingProtocol.KIND_DATA, RingProtocol.CMD_HI_HEART_RATE,
RingProtocol.CMD_LO_HEALTH, 7, byteArrayOf(0, 0)))
assertEquals(0, s.outboundSize())
}
@Test fun batchWatermarkOnlyClearsWhatWasTaken() {
val s = RingSession()
// A decodable one-group heart-rate page: count 1, tz 0, anchor 1000, then [hour][avg][max][min].
val payload = byteArrayOf(0, 0, 1, 0, 0, 0xe8.toByte(), 0x03, 0, 0, 2, 60, 70, 50)
fun deliver(seq: Int) = s.core.onNotification(RING, BleProtocol.R1_NOTIFY_CHAR_UUID,
RingProtocol.buildFrame(RingProtocol.CHAN_HEALTH, RingProtocol.KIND_DATA, RingProtocol.CMD_HI_HEART_RATE,
RingProtocol.CMD_LO_HEALTH, seq, payload))
deliver(1)
deliver(2)
val batch = s.core.takeRingHealthBatch()
assertEquals(2, batch.records.size)
assertEquals(2L, batch.watermark)
deliver(3)
assertEquals(2, s.core.clearRingHealthRecordsBelow(batch.watermark))
val rest = s.core.getRingHealthRecords()
assertEquals(1, rest.size)
val record = rest.single() as RingProtocol.HourlyRecord
assertEquals(60, record.groups.single().avg)
assertEquals(1000L + 2 * 3600L, record.groups.single().unixSeconds)
}
}
@@ -0,0 +1,37 @@
package com.faceclaw.app
import kotlin.test.*
class RingInputTest {
private fun hex(value: String) = value.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
// Exact packet emitted by the emulated CFW receiver, including a tick > INT_MAX.
private val packet = hex("08026a151a13080e1002a2060c524901010aabcd00efcdab89")
@Test fun preservesOriginalClockAndRawFieldsThroughTheNativeDecoder() {
val decoded = assertNotNull(G2Event.decodePayload(224, packet))
assertEquals("sys-event", decoded.kind)
assertEquals(14, decoded.eventType)
assertEquals(2, decoded.eventSource)
assertEquals(0x89abcdefL, decoded.ringTick)
assertEquals(10, decoded.ringType)
assertEquals(171, decoded.ringAux)
assertEquals(205, decoded.ringSpeed)
// Exercise framing and CRC removal too (Android's entry point).
val frame = BleProtocol.framePb(packet, 224, 1, 1).single()
val native = assertNotNull(G2Event.decode(BleProtocol.parseFrame(frame)))
assertEquals(decoded.ringTick, native.ringTick)
}
@Test fun legacyAndInvalidExtensionsNeverInventATimestamp() {
assertEquals(-1L, assertNotNull(G2Event.decodePayload(224, hex("08026a041a02080e"))).ringTick)
for (offset in listOf(9,13,14,15,16,20)) {
val bad = packet.copyOf(); bad[offset] = (bad[offset].toInt() + 1).toByte()
assertEquals(-1L, assertNotNull(G2Event.decodePayload(224, bad)).ringTick)
}
for (tick in listOf(0L,1L,0xffffffffL)) {
val p = packet.copyOf()
for (i in 0..3) p[21+i] = (tick shr (i*8)).toByte()
assertEquals(tick, assertNotNull(G2Event.decodePayload(224,p)).ringTick)
}
}
}
@@ -0,0 +1,65 @@
package com.faceclaw.app
import kotlin.random.Random
import kotlin.test.*
class RleEncoderTest {
/** Deliberately simple per-pixel reference, independent of the byte scan. */
private fun reference(packed: ByteArray): ByteArray {
val output = ArrayList<Byte>()
var color = -1
var count = 0
fun flush() {
while (count > 0) {
val n = minOf(count, 65535)
when {
n <= 15 -> output.add((n * 16 + color).toByte())
n <= 255 -> { output.add(color.toByte()); output.add(n.toByte()) }
else -> { output.add(color.toByte()); output.add(0); output.add(n.toByte()); output.add((n / 256).toByte()) }
}
count -= n
}
}
for (byte in packed) for (pixel in listOf((byte.toInt() and 255) / 16, byte.toInt() and 15)) {
if (pixel != color) { flush(); color = pixel }
count++
}
flush()
return output.toByteArray()
}
@Test fun allTwoByteInputsPreserveExactTokensAcrossNibbleBoundaries() {
for (value in 0..65535) {
val packed = byteArrayOf((value / 256).toByte(), value.toByte())
assertContentEquals(reference(packed), BleImageOptimizer.rleEncode(packed), "input $value")
}
assertContentEquals(ByteArray(0), BleImageOptimizer.rleEncode(ByteArray(0)))
}
@Test fun longRunsAndEveryTokenBoundaryAtBothNibbleAlignments() {
for (length in listOf(1, 2, 14, 15, 16, 254, 255, 256, 65534, 65535, 65536, 131070, 131071)) {
for (prefix in 0..1) for (color in listOf(0, 7, 15)) {
val values = List(prefix) { (color + 1) % 16 } + List(length) { color } + listOf((color + 2) % 16)
val packed = ByteArray((values.size + 1) / 2) { i ->
(values[i * 2] * 16 + (values.getOrNull(i * 2 + 1) ?: 0)).toByte()
}
assertContentEquals(reference(packed), BleImageOptimizer.rleEncode(packed), "$prefix/$length/$color")
}
}
}
@Test fun noiseAndMixedRunsPreserveExactWireOutput() {
val random = Random(123)
repeat(100) {
val data = random.nextBytes(random.nextInt(1, 4096))
assertContentEquals(reference(data), BleImageOptimizer.rleEncode(data))
repeat(20) {
val start = random.nextInt(data.size)
data.fill((random.nextInt(16) * 17).toByte(), start, minOf(data.size, start + random.nextInt(1, 200)))
}
assertContentEquals(reference(data), BleImageOptimizer.rleEncode(data))
}
val screen = ByteArray(640 * 480 / 2) { 0x77 }
assertContentEquals(reference(screen), BleImageOptimizer.rleEncode(screen))
}
}
@@ -0,0 +1,46 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class SettingsChangeHubTest {
private class MemorySettings : SettingsStorage {
val values = HashMap<String?, Any?>()
override fun getString(key: String?, defaultValue: String?): String? = values[key] as? String ?: defaultValue
override fun putString(key: String?, value: String?) { values[key] = value }
override fun getBoolean(key: String?, defaultValue: Boolean): Boolean = values[key] as? Boolean ?: defaultValue
override fun putBoolean(key: String?, value: Boolean) { values[key] = value }
}
@Test
fun writesNotifyEachListenerThroughItsOwnDispatcher() {
val warnings = ArrayList<String>()
val hub = SettingsChangeHub(MemorySettings(), { warnings.add(it) }, testPlatform())
val queued = ArrayList<() -> Unit>()
val seen = ArrayList<String?>()
val listener = object : FaceclawSettingsListener { override fun onSettingChanged(key: String?) { seen.add(key) } }
hub.register(listener) { queued.add(it) }
val silent = object : FaceclawSettingsListener { override fun onSettingChanged(key: String?) { seen.add("silent") } }
hub.register(silent, null)
assertEquals(1, warnings.size)
hub.setString("font", "Inter")
hub.setBoolean("dark", true)
assertEquals("Inter", hub.getString("font", null))
assertTrue(hub.getBoolean("dark", false))
assertTrue(seen.isEmpty()) // delivered only when the dispatcher runs
queued.forEach { it() }
assertEquals(listOf<String?>("font", "dark"), seen)
val failing = object : FaceclawSettingsListener { override fun onSettingChanged(key: String?) { throw IllegalStateException("boom") } }
hub.register(failing) { it() }
hub.setString("x", null)
assertTrue(warnings.last().contains("boom"))
hub.unregister(listener)
hub.unregister(failing)
queued.clear()
hub.setBoolean("dark", false)
assertTrue(queued.isEmpty())
}
}
@@ -0,0 +1,136 @@
package com.faceclaw.app
import kotlin.test.*
class SharedGraphicsTest {
private fun hex(value: String) = value.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
@Test
fun androidWireVectorsAndGrayQuantization() {
val vectors =
listOf(
BleProtocol.buildAuthenticationRequest(101) to "080410651a0408011004",
BleProtocol.PRELUDE_F5872_PAYLOAD to "0802109c01220a1a081206120408001000",
BleProtocol.buildCreateInputPage(102) to
"080010661a2308011a1c0800100018c00420a0024801520964617368626f617264580162012028904e",
BleProtocol.buildHeartbeat(103) to "080c106772020800",
BleProtocol.buildSettingsQuery(104) to "0802106822020801",
BleProtocol.buildShutdown(105, 1) to "080910695a020801",
BleProtocol.buildFaceclawWakeControl(5, 0) to "08011000aa0606464301050000",
)
vectors.forEach { (actual, expected) -> assertContentEquals(hex(expected), actual) }
val packed =
BmpUtil.pack4bppFromGray8(
byteArrayOf(0, 1, 7, 8, 15, 16, 23, 24, 127, -128, -9, -1),
3,
4,
)
assertContentEquals(hex("0000111012808ff0"), packed)
assertContentEquals(hex("40311011121810182f10"), BleImageOptimizer.rleEncode(packed))
assertContentEquals(
hex("aa21400c01018000080410651a04080110041024"),
BleProtocol.framePb(vectors.first().first, 128, 0, 64).single(),
)
}
@Test
fun splitStreamsExpiryAndCorruption() {
val payload =
BleProtocol.encodeVarintField(1, 3) +
BleProtocol.encodeVarintField(2, 110) +
BleProtocol.encodeBytesField(8, ByteArray(3900) { 55 })
val frames = BleProtocol.framePb(payload, 224, 32, 17, 185)
assertTrue(frames.all { it.size <= 185 })
val stream = frames.reduce { a, b -> a + b }
val receiver = MessageReceiver()
assertTrue(receiver.receive("L", stream.copyOf(7), 0).isEmpty())
val message = receiver.receive("L", stream.copyOfRange(7, stream.size), 1).single()
assertContentEquals(payload, message.payload)
assertEquals(3, message.command)
assertEquals(110, message.magic)
stream[stream.lastIndex] = (stream.last().toInt() xor 1).toByte()
assertTrue(receiver.receive("L", stream, 2).isEmpty())
receiver.receive("L", frames.first(), 10)
assertTrue(receiver.receive("R", frames.drop(1).reduce { a, b -> a + b }, 11).isEmpty())
assertTrue(receiver.receive("L", frames.drop(1).reduce { a, b -> a + b }, 5011).isEmpty())
assertFailsWith<IllegalArgumentException> { BleProtocol.framePb(payload, 1, 0, 1, 10) }
assertFailsWith<IllegalArgumentException> { BleProtocol.framePb(ByteArray(60000), 1, 0, 1) }
val invalid = BleProtocol.framePb(byteArrayOf(0x1a, 0x7f), 224, 0, 2).single()
assertTrue(receiver.receive("L", invalid, 6000).isEmpty())
}
@Test
fun eventDecodeAcceptsValidatedPayloadWithoutStrippingAgain() {
val event = BleProtocol.encodeVarintField(1, 12) + BleProtocol.encodeVarintField(2, 2)
val payload = BleProtocol.encodeBytesField(13, BleProtocol.encodeBytesField(3, event))
val received =
MessageReceiver()
.receive("L", BleProtocol.framePb(payload, 224, 1, 1).single(), 0)
.single()
val decoded = assertNotNull(G2Event.decodePayload(received.sid, received.payload))
assertEquals("sys-event", decoded.kind)
assertEquals(12, decoded.eventType)
assertEquals(2, decoded.eventSource)
}
@Test
fun retainedCompositionClippingDimmingAndBlanking() {
val c = SurfaceCompositor()
c.configureScreen(3, 2)
c.configureSurface("app", 0, 0, 3, 2, 0, 0)
c.submitSurface("app", ArrayByteReader(ByteArray(6) { 200.toByte() }), 0, 0, 3, 2, "1")
c.configureSurface("shell", 0, 0, 3, 2, 1, 1)
c.submitSurface("shell", ArrayByteReader(byteArrayOf(0, 1, -1, 0, 0, 0)), 0, 0, 3, 2, "2")
c.setUnderlayDim(1, 128)
assertContentEquals(byteArrayOf(100, 1, -1, 100, 100, 100), c.composite().gray)
c.setSurfaceVisible("shell", false)
assertContentEquals(ByteArray(6) { 100 }, c.composite().gray)
c.configureSurface("opaque", 1, 0, 1, 2, 2, 0)
c.submitSurface("opaque", ArrayByteReader(byteArrayOf(0, 0)), 0, 0, 1, 2, "3")
assertContentEquals(byteArrayOf(100, 0, 100, 100, 0, 100), c.composite().gray)
c.setBlanked(true)
assertContentEquals(ByteArray(6), c.composite().gray)
c.setBlanked(false)
c.removeSurface("opaque")
c.configureSurface("app", -1, 0, 3, 2, 0, 0)
c.setUnderlayDim(0, 256)
assertContentEquals(byteArrayOf(-56, -56, 0, -56, -56, 0), c.composite().gray)
}
@Test
fun pngChunksAndPixels() {
val png = SharedScreenshots.encode4BitGrayPng(byteArrayOf(0, 16, -1, 32, 48, 64), 3, 2)
assertContentEquals(hex("89504e470d0a1a0a"), png.copyOf(8))
fun intAt(offset: Int): Int =
(0..3).fold(0) { n, i -> (n shl 8) or (png[offset + i].toInt() and 255) }
var offset = 8
val types = mutableListOf<String>()
var compressed = ByteArray(0)
while (offset < png.size) {
val size = intAt(offset)
val type = png.copyOfRange(offset + 4, offset + 8).decodeToString()
types.add(type)
if (type == "IHDR") {
assertEquals(3, intAt(offset + 8))
assertEquals(2, intAt(offset + 12))
assertEquals(4, png[offset + 16].toInt())
assertEquals(0, png[offset + 17].toInt())
}
if (type == "IDAT") compressed += png.copyOfRange(offset + 8, offset + 8 + size)
offset += size + 12
}
assertEquals(listOf("IHDR", "IDAT", "IEND"), types)
assertContentEquals(hex("0001f0002340"), inflateData(compressed, 6))
}
@Test
fun wavHeaderAndHex() {
assertEquals("007f80ff", BinaryEncoding.bytesToHex(byteArrayOf(0, 127, -128, -1)))
assertContentEquals(
hex(
"524946462804000057415645666d74201000000001000100803e0000007d0000020010006461746104040000"
),
BinaryEncoding.wavHeader(1028, 16000, 1),
)
}
}
@@ -0,0 +1,87 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class SseStreamTest {
private fun feed(stream: SseStream, vararg chunks: String) {
for (chunk in chunks) {
val bytes = chunk.encodeToByteArray()
stream.onChunk(bytes, 0, bytes.size)
}
}
@Test
fun splitsLinesAcrossChunksWithBomAndCrlf() {
val stream = SseStream()
stream.onStatus(200)
feed(stream, "event: a\r", "\ndata: {\"x\":1}\n\nda", "ta: tail")
assertEquals(listOf(SseEvent.Line("event: a"), SseEvent.Line("data: {\"x\":1}"), SseEvent.Line("")), stream.takeEvents())
stream.onComplete()
assertEquals(listOf(SseEvent.Line("data: tail"), SseEvent.Complete), stream.takeEvents())
assertTrue(stream.isFinished)
feed(stream, "late\n")
assertEquals(emptyList(), stream.takeEvents())
}
@Test
fun errorBodyIsBufferedAndCapped() {
val stream = SseStream()
stream.onStatus(429)
feed(stream, "{\"error\":", "\"slow down\"}\n")
assertEquals(emptyList(), stream.takeEvents())
stream.onComplete()
assertEquals(listOf(SseEvent.HttpError(429, "{\"error\":\"slow down\"}\n")), stream.takeEvents())
val capped = SseStream()
capped.onStatus(500)
val big = ByteArray(SseStream.ERROR_BODY_LIMIT + 100) { 'x'.code.toByte() }
capped.onChunk(big, 0, big.size)
capped.onComplete()
val event = capped.takeEvents().single() as SseEvent.HttpError
assertEquals(SseStream.ERROR_BODY_LIMIT, event.body.length)
}
@Test
fun queueOverflowAndOversizedLinesFail() {
val stream = SseStream()
stream.onStatus(200)
val line = "x".repeat(1023) + "\n"
val block = line.repeat(64).encodeToByteArray()
var fed = 0L
while (fed <= SseStream.QUEUE_BYTE_LIMIT + block.size) {
stream.onChunk(block, 0, block.size)
fed += block.size
}
val events = stream.takeEvents()
assertEquals(SseEvent.Failure("Streaming response queue overflow"), events.single())
val long = SseStream()
long.onStatus(200)
val huge = ByteArray(SseStream.LINE_LIMIT + 1) { 'y'.code.toByte() }
long.onChunk(huge, 0, huge.size)
assertEquals(SseEvent.Failure("Streaming response line too large"), long.takeEvents().single())
}
@Test
fun failureAndCancelAreTerminal() {
val stream = SseStream()
stream.onStatus(200)
feed(stream, "a\n")
stream.onFailure("boom")
assertEquals(listOf(SseEvent.Line("a"), SseEvent.Failure("boom")), stream.takeEvents())
val cancelled = SseStream()
cancelled.onStatus(200)
feed(cancelled, "a\n")
cancelled.cancel()
cancelled.onComplete()
assertEquals(emptyList(), cancelled.takeEvents())
}
@Test
fun unpacksFlatHeaderArrays() {
assertEquals(listOf("A" to "1", "C" to "3"), SseStream.unpackHeaders(arrayOf("A", "1", "", "2", "C", "3", "D")))
assertEquals(emptyList(), SseStream.unpackHeaders(null))
}
}
@@ -0,0 +1,420 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertContains
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
/** A stock-firmware lens pair behind the StockLink port; replies are scripted per written message. */
private class FakeStockLink : StockLink {
class Written(val address: String, val uuid: String, val sid: Int, val flag: Int, val seq: Int, val pb: ByteArray) {
/** Protobuf magic (field 2) of a control message; -1 for OTA payloads. */
val magic: Int get() = if (sid == 0xc0 || sid == 0xc1) -1 else BleProtocol.readVarintFieldValue(BleProtocol.stripTrailingCrc(pb), 2, -1)
}
var inbound: StockLinkListener? = null
val connected = HashSet<String>()
val bond = HashMap<String, BondState>()
val writes = ArrayList<Written>()
var connectResult: (String) -> Boolean = { true }
var responder: (Written) -> Unit = {}
var closed = false
override fun setListener(listener: StockLinkListener?) { inbound = listener }
override fun connect(address: String, timeoutMs: Int): Boolean = connectResult(address).also { if (it) connected.add(address) }
override fun prepareLink(address: String, desiredMtu: Int, timeoutMs: Int) {}
override fun discoverServices(address: String, timeoutMs: Int): Boolean = address in connected
override fun enableNotifications(address: String, characteristicUuid: String, timeoutMs: Int): Boolean = address in connected
override fun writeFrames(address: String, characteristicUuid: String, frames: List<ByteArray>, mode: GattWriteMode, timeoutMs: Int): Boolean {
if (address !in connected) throw IllegalStateException("Not connected: $address")
val head = frames.first()
val body = ByteArray(frames.sumOf { it.size - 8 })
var at = 0
for (f in frames) { f.copyInto(body, at, 8); at += f.size - 8 }
val written = Written(address, characteristicUuid, head[6].toInt() and 0xff, head[7].toInt() and 0xff, head[2].toInt() and 0xff, body)
writes.add(written)
responder(written)
return true
}
override fun isConnected(address: String): Boolean = address in connected
override fun bondState(address: String): BondState = bond[address] ?: BondState.BONDED
override fun disconnect(address: String) { connected.remove(address) }
override fun close() { closed = true; connected.clear() }
/** Deliver a lens frame on the control notify characteristic. */
fun notify(address: String, pb: ByteArray, sid: Int, flag: Int = 0) {
for (frame in BleProtocol.framePb(pb, sid, flag, 7)) inbound!!.onNotification(address, BleProtocol.NOTIFY_CHAR_UUID, frame)
}
fun otaAck(address: String, op: Int, status: Int) {
inbound!!.onNotification(address, BleProtocol.OTA_DATA_NOTIFY_UUID, BleProtocol.framePb(byteArrayOf(op.toByte(), status.toByte()), 0xc1, 0, 1).single())
}
fun drop(address: String) { connected.remove(address); inbound!!.onConnectionStateChange(address, false) }
}
private fun varint(value: Int): ByteArray { var v = value; val out = ArrayList<Byte>(); do { var b = v and 0x7f; v = v ushr 7; if (v != 0) b = b or 0x80; out.add(b.toByte()) } while (v != 0); return out.toByteArray() }
private fun field(number: Int, bytes: ByteArray): ByteArray = varint((number shl 3) or 2) + varint(bytes.size) + bytes
private fun field(number: Int, text: String): ByteArray = field(number, text.encodeToByteArray())
private fun authSuccess(magic: Int) = BleProtocol.encodeVarintField(1, 4) + BleProtocol.encodeVarintField(2, magic) + field(3, ByteArray(0))
private fun authPending(magic: Int) = BleProtocol.encodeVarintField(1, 4) + BleProtocol.encodeVarintField(2, magic) + field(3, BleProtocol.encodeVarintField(1, 1))
private fun ack(magic: Int) = BleProtocol.encodeVarintField(1, 1) + BleProtocol.encodeVarintField(2, magic)
private fun settingsAck(magic: Int, battery: Int = -1, left: String = "", right: String = "", extension: String = "", silentMode: Int = -1): ByteArray {
var request = ByteArray(0)
if (left.isNotEmpty()) request += field(5, left)
if (right.isNotEmpty()) request += field(6, right)
if (battery >= 0) request += BleProtocol.encodeVarintField(12, battery)
if (silentMode >= 0) request += BleProtocol.encodeVarintField(14, silentMode)
var pb = BleProtocol.encodeVarintField(1, 2) + BleProtocol.encodeVarintField(2, magic) + field(4, request)
if (extension.isNotEmpty()) pb += field(100, extension)
return pb
}
private fun listSelection(container: String, item: String, index: Int, eventType: Int): ByteArray =
field(13, field(1, field(2, container) + field(3, item) + BleProtocol.encodeVarintField(4, index) + BleProtocol.encodeVarintField(5, eventType)))
private val fast = StockFlowTimings(
securityAuthTimeoutMs = 300, securityAuthSoftTimeoutMs = 100, pairingWaitCapMs = 2_000, postBondGraceMs = 20, pollMs = 5,
armRetryDelayMs = 5, queryTimeoutMs = 40, preludeTimeoutMs = 40, heartbeatIntervalMs = 15, selectionTimeoutMs = 80, createAckTimeoutMs = 40,
batteryAckTimeoutMs = 40, blockAckTimeoutMs = 60, ctrlAckTimeoutMs = 60, firstLensConnectWindowMs = 200, secondLensConnectWindowMs = 200,
rebootSettleMs = 5, notifySettleMs = 5, otaRetryDelayMs = 5, componentRetryDelayMs = 5,
)
private const val R = "AA:00:00:00:00:01"
private const val L = "AA:00:00:00:00:02"
private class ProbeEvents : FaceclawDeviceInfoProbeListener {
val logs = ArrayList<String>(); val states = ArrayList<String>(); var result: List<String>? = null; var error: String? = null
override fun onLog(line: String?) { logs.add(line ?: "") }
override fun onState(state: String?, detail: String?) { states.add("$state:$detail") }
override fun onResult(leftVersion: String?, rightVersion: String?, extension: String?) { result = listOf(leftVersion ?: "", rightVersion ?: "", extension ?: "") }
override fun onError(message: String?) { error = message }
}
/** Standard lens behaviour: auth succeeds, prelude and settings are acked with the given versions/battery. */
private fun stockResponder(link: FakeStockLink, left: String = "2.2.9", right: String = "2.2.9", extension: String = "", battery: Int = 85): (FakeStockLink.Written) -> Unit = { w ->
when (w.sid) {
BleProtocol.SID_SECURITY_AUTH -> link.notify(w.address, authSuccess(w.magic), w.sid)
BleProtocol.PRELUDE_ACK_SID -> link.notify(w.address, ack(BleProtocol.PRELUDE_ACK_MAGIC), w.sid)
BleProtocol.SID_UI_SETTING -> link.notify(w.address, settingsAck(w.magic, battery, left, right, extension), w.sid)
BleProtocol.SID_EVENHUB -> link.notify(w.address, ack(w.magic), w.sid)
}
}
class StockFlowsTest {
@Test
fun probeAuthenticatesBothArmsThenReadsVersions() {
val link = FakeStockLink()
link.responder = stockResponder(link, "L1", "R1", "Faceclaw/3")
val events = ProbeEvents()
DeviceInfoProbeFlow(link, R, L, events, fast, testPlatform()).run()
assertEquals(listOf("L1", "R1", "Faceclaw/3"), events.result)
assertEquals(null, events.error)
assertEquals(listOf("connecting:right", "authenticating:right", "connecting:left", "authenticating:left", "querying:right"), events.states)
// Right arm then left arm auth, then prelude + one settings read on the right arm only.
assertEquals(listOf(R, L), link.writes.filter { it.sid == BleProtocol.SID_SECURITY_AUTH }.map { it.address })
assertEquals(listOf(R), link.writes.filter { it.sid == BleProtocol.SID_UI_SETTING }.map { it.address })
assertTrue(link.closed)
}
@Test
fun probeUsesUnsolicitedSettingsPushAndFallsBackToLeftLens() {
// Right lens: auth ok, but the settings read is never acked; instead a push on a
// device-chosen magic carries the versions.
val pushed = FakeStockLink()
pushed.responder = { w ->
when (w.sid) {
BleProtocol.SID_SECURITY_AUTH -> pushed.notify(w.address, authSuccess(w.magic), w.sid)
BleProtocol.PRELUDE_ACK_SID -> pushed.notify(w.address, ack(BleProtocol.PRELUDE_ACK_MAGIC), w.sid)
BleProtocol.SID_UI_SETTING -> pushed.notify(w.address, settingsAck(250, -1, "P1", "P2", ""), w.sid)
}
}
var events = ProbeEvents()
DeviceInfoProbeFlow(pushed, R, "", events, fast, testPlatform()).run()
assertEquals(listOf("P1", "P2", ""), events.result)
assertTrue(events.logs.any { it.contains("unsolicited settings push") })
// Right lens silent on settings (both attempts); the left lens answers.
val silentRight = FakeStockLink()
silentRight.responder = { w ->
when (w.sid) {
BleProtocol.SID_SECURITY_AUTH -> silentRight.notify(w.address, authSuccess(w.magic), w.sid)
BleProtocol.PRELUDE_ACK_SID -> silentRight.notify(w.address, ack(BleProtocol.PRELUDE_ACK_MAGIC), w.sid)
BleProtocol.SID_UI_SETTING -> if (w.address == L) silentRight.notify(w.address, settingsAck(w.magic, -1, "LL", "RR", ""), w.sid)
}
}
events = ProbeEvents()
DeviceInfoProbeFlow(silentRight, R, L, events, fast, testPlatform()).run()
assertEquals(listOf("LL", "RR", ""), events.result)
assertTrue(events.logs.any { it.contains("probing the left lens") })
assertEquals(2, silentRight.writes.count { it.sid == BleProtocol.SID_UI_SETTING && it.address == R })
assertContains(events.states, "querying:left")
}
@Test
fun probeWaitsThroughPairingAndResendsAfterBond() {
// Unbonded phone: the first auth request is answered with the pre-encryption
// non-success result, the OS then pairs (no writes while BONDING), and once bonded the
// request is re-sent after the grace period and finally succeeds.
val link = FakeStockLink()
link.bond[R] = BondState.NONE
val authReplies = ArrayList<Int>()
link.responder = { w ->
when (w.sid) {
BleProtocol.SID_SECURITY_AUTH -> { authReplies.add(w.magic); link.notify(w.address, if (authReplies.size == 1) authPending(w.magic) else authSuccess(w.magic), w.sid) }
BleProtocol.PRELUDE_ACK_SID -> link.notify(w.address, ack(BleProtocol.PRELUDE_ACK_MAGIC), w.sid)
BleProtocol.SID_UI_SETTING -> link.notify(w.address, settingsAck(w.magic, -1, "a", "b", ""), w.sid)
}
}
startThread("bond-flip", true) { sleepMs(20); link.bond[R] = BondState.BONDING; sleepMs(40); link.bond[R] = BondState.BONDED }
val events = ProbeEvents()
DeviceInfoProbeFlow(link, R, "", events, fast, testPlatform()).run()
assertEquals(listOf("a", "b", ""), events.result, events.logs.joinToString("\n"))
assertTrue(events.logs.any { it.contains("is not the success result") })
assertTrue(events.logs.any { it.contains("is pairing with the right lens") })
assertTrue(events.logs.any { it.contains("bond established") })
assertTrue(events.logs.any { it.contains("re-sending the auth request after pairing") })
assertEquals(2, authReplies.size)
assertTrue(events.logs.any { it.contains("security auth complete: right lens") })
}
@Test
fun probeReportsUnreachableArmAndCancel() {
val link = FakeStockLink()
link.connectResult = { false }
val events = ProbeEvents()
DeviceInfoProbeFlow(link, R, L, events, fast, testPlatform()).run()
assertNotNull(events.error).let { assertTrue(it.contains("could not connect to the right lens"), it) }
assertEquals(3, events.states.count { it == "connecting:right" })
val cancelled = FakeStockLink()
cancelled.responder = { w -> if (w.sid == BleProtocol.SID_SECURITY_AUTH) cancelled.notify(w.address, authPending(w.magic), w.sid) }
val slow = StockFlowTimings(securityAuthTimeoutMs = 5_000, pollMs = 5)
val flow = DeviceInfoProbeFlow(cancelled, R, "", ProbeEvents().also { events.logs.clear() }, slow, testPlatform())
startThread("cancel", true) { sleepMs(30); flow.cancel() }
val start = testPlatform().elapsedRealtimeMs()
flow.run()
assertTrue(testPlatform().elapsedRealtimeMs() - start < 2_000)
assertTrue(flow.cancelled)
}
private class PromptEvents : FaceclawFlashPromptListener {
val logs = ArrayList<String>(); val states = ArrayList<String>(); var battery: Pair<Int, Int>? = null; var result: Boolean? = null
override fun onLog(line: String?) { logs.add(line ?: "") }
override fun onState(state: String?, detail: String?) { states.add("$state:$detail") }
override fun onBattery(rightPercent: Int, leftPercent: Int) { battery = rightPercent to leftPercent }
override fun onResult(approved: Boolean) { result = approved }
}
private fun promptResponder(link: FakeStockLink, selection: Int?, batteries: Map<String, Int>, silentMode: Int = -1): (FakeStockLink.Written) -> Unit = { w ->
when (w.sid) {
BleProtocol.SID_SECURITY_AUTH -> link.notify(w.address, authSuccess(w.magic), w.sid)
BleProtocol.PRELUDE_ACK_SID -> link.notify(w.address, ack(BleProtocol.PRELUDE_ACK_MAGIC), w.sid)
BleProtocol.SID_UI_SETTING -> link.notify(w.address, settingsAck(w.magic, batteries[w.address] ?: -1, silentMode = silentMode), w.sid)
BleProtocol.SID_EVENHUB -> {
val cmd = BleProtocol.readVarintFieldValue(BleProtocol.stripTrailingCrc(w.pb), 1, -1)
link.notify(w.address, ack(w.magic), w.sid)
// Cmd 0 = create page: the user taps a row right away (a scroll first, which must be ignored).
if (cmd == 0 && selection != null) {
link.notify(w.address, listSelection(FlashPromptFlow.LIST_NAME, "other", 0, BleProtocol.EVENT_SCROLL_TOP), BleProtocol.SID_EVENHUB, BleProtocol.FLAG_NOTIFY)
link.notify(w.address, listSelection(FlashPromptFlow.LIST_NAME, FlashPromptFlow.ITEMS[selection], selection, BleProtocol.EVENT_CLICK), BleProtocol.SID_EVENHUB, BleProtocol.FLAG_NOTIFY)
}
}
}
}
@Test
fun promptApprovalReadsBothBatteriesAndShutsDown() {
val link = FakeStockLink()
link.responder = promptResponder(link, 1, mapOf(R to 85, L to 70))
val events = PromptEvents()
FlashPromptFlow(link, R, L, "warning", false, events, fast, testPlatform()).run()
assertEquals(true, events.result, events.logs.joinToString("\n"))
assertEquals(85 to 70, events.battery)
assertEquals(listOf("connecting:", "connected:", "prompting:", "battery:", "result:approved"), events.states)
val hub = link.writes.filter { it.sid == BleProtocol.SID_EVENHUB }.map { BleProtocol.readVarintFieldValue(BleProtocol.stripTrailingCrc(it.pb), 1, -1) }
assertEquals(0, hub.first()) // create page
assertEquals(9, hub.last()) // shutdown
assertTrue(link.writes.all { it.sid != BleProtocol.SID_EVENHUB || it.address == R })
assertTrue(link.closed)
}
@Test
fun promptDeclineTimeoutAndSkip() {
val declined = FakeStockLink()
declined.responder = promptResponder(declined, 0, mapOf())
var events = PromptEvents()
FlashPromptFlow(declined, R, "", "w", false, events, fast, testPlatform()).run()
assertEquals(false, events.result)
assertEquals("result:declined", events.states.last())
assertEquals(null, events.battery)
val silent = FakeStockLink()
silent.responder = promptResponder(silent, null, mapOf())
events = PromptEvents()
FlashPromptFlow(silent, R, "", "w", false, events, fast, testPlatform()).run()
assertEquals(null, events.result)
assertEquals("timeout:No response from the glasses.", events.states.last())
// Heartbeats (EvenHub cmd 12) kept the page alive while waiting (interval 15 ms, wait 80 ms).
assertTrue(silent.writes.count { it.sid == BleProtocol.SID_EVENHUB && BleProtocol.readVarintFieldValue(BleProtocol.stripTrailingCrc(it.pb), 1, -1) == 12 } >= 2)
val skipped = FakeStockLink()
skipped.responder = promptResponder(skipped, null, mapOf(R to 50))
events = PromptEvents()
FlashPromptFlow(skipped, R, L, "w", true, events, fast, testPlatform()).run()
assertEquals(true, events.result)
assertEquals(50 to -1, events.battery)
assertFalse(skipped.writes.any { it.sid == BleProtocol.SID_EVENHUB })
val lost = FakeStockLink()
lost.responder = { w ->
promptResponder(lost, null, mapOf())(w)
if (w.sid == BleProtocol.SID_EVENHUB) lost.drop(R)
}
events = PromptEvents()
FlashPromptFlow(lost, R, "", "w", false, events, fast, testPlatform()).run()
assertEquals("disconnected:Lost connection to the glasses.", events.states.last())
}
@Test
fun promptRefusesOnlyWhenTheLensReportsSilentMode() {
// Silent mode on: refused with the way out, before any page is written.
val silentOn = FakeStockLink()
silentOn.responder = promptResponder(silentOn, 1, mapOf(R to 85), silentMode = 1)
var events = PromptEvents()
FlashPromptFlow(silentOn, R, "", "w", false, events, fast, testPlatform()).run()
assertEquals(null, events.result)
assertEquals("error:${FlashPromptFlow.SILENT_MODE_MESSAGE}", events.states.last())
assertTrue(events.logs.any { it == "silent mode before prompt: on" })
assertFalse(silentOn.writes.any { it.sid == BleProtocol.SID_EVENHUB })
assertTrue(silentOn.closed)
// Silent mode off: the prompt is shown and answered as usual.
val silentOff = FakeStockLink()
silentOff.responder = promptResponder(silentOff, 1, mapOf(R to 85), silentMode = 0)
events = PromptEvents()
FlashPromptFlow(silentOff, R, "", "w", false, events, fast, testPlatform()).run()
assertEquals(true, events.result, events.logs.joinToString("\n"))
assertTrue(events.logs.any { it == "silent mode before prompt: off" })
// Firmware whose ack omits the field: unknown is not a refusal.
val omitted = FakeStockLink()
omitted.responder = promptResponder(omitted, 1, mapOf(R to 85))
events = PromptEvents()
FlashPromptFlow(omitted, R, "", "w", false, events, fast, testPlatform()).run()
assertEquals(true, events.result, events.logs.joinToString("\n"))
assertTrue(events.logs.any { it == "silent mode before prompt: unknown (ack omits the field)" })
// skipPrompt re-checks the battery only; silent mode does not block it.
val skipped = FakeStockLink()
skipped.responder = promptResponder(skipped, null, mapOf(R to 85), silentMode = 1)
events = PromptEvents()
FlashPromptFlow(skipped, R, "", "w", true, events, fast, testPlatform()).run()
assertEquals(true, events.result)
}
// ---- OTA ---------------------------------------------------------------
private fun putU32(buf: ByteArray, offset: Int, value: Long) { for (i in 0 until 4) buf[offset + i] = ((value ushr (8 * i)) and 0xff).toByte() }
private fun container(): ByteArray {
val mainApp = ByteArray(6000) { (it * 7).toByte() }.also { putU32(it, 0, 6000L); putU32(it, 0x14, FirmwareImage.APP_LOAD_ADDR) }
val components = listOf("ota/bootloader.bin" to ByteArray(300) { it.toByte() }, "ota/a.bin" to ByteArray(64) { 1 }, "ota/b.bin" to ByteArray(128) { 2 }, "ota/c.bin" to ByteArray(32) { 3 }, FirmwareImage.REQUIRED_SEGMENT to mainApp)
val toc = FirmwareImage.HEADER_SIZE + components.size * FirmwareImage.TOC_ENTRY_SIZE
var offset = toc
val offsets = components.map { c -> offset.also { offset += FirmwareImage.SUBHEADER_SIZE + c.second.size } }
val img = ByteArray(offset)
putU32(img, 8, components.size.toLong())
components.forEachIndexed { i, c ->
val off = offsets[i]
putU32(img, FirmwareImage.HEADER_SIZE + i * 16 + 4, off.toLong())
putU32(img, off + 8, c.second.size.toLong())
c.first.encodeToByteArray().copyInto(img, off + FirmwareImage.NAME_OFFSET)
c.second.copyInto(img, off + FirmwareImage.SUBHEADER_SIZE)
val crc = FirmwareImage.crc32cUnsigned(c.second)
putU32(img, FirmwareImage.HEADER_SIZE + i * 16 + 12, crc)
putU32(img, off + 12, crc)
}
return img
}
private class FlashEvents : FaceclawFirmwareFlasherListener {
val logs = ArrayList<String>(); val states = ArrayList<String>(); val progress = ArrayList<String>(); var complete: Pair<Boolean, String>? = null
override fun onLog(line: String?) { logs.add(line ?: "") }
override fun onProgress(lens: String?, componentIndex: Int, componentCount: Int, blockIndex: Int, blockCount: Int, bytesSent: Long, bytesTotal: Long) { progress.add("$lens $componentIndex/$componentCount $blockIndex/$blockCount $bytesSent/$bytesTotal") }
override fun onState(state: String?, detail: String?) { states.add("$state:$detail") }
override fun onComplete(success: Boolean, detail: String?) { complete = success to (detail ?: "") }
}
/** OTA lens: NAKs one block once and fails one END once, exercising both retry paths. */
private class OtaLens(val link: FakeStockLink) {
val received = HashMap<String, ByteArray>()
var nakOnce = true
var failEndOnce = true
var component = ByteArray(0)
fun respond(w: FakeStockLink.Written) {
when (w.sid) {
BleProtocol.SID_SECURITY_AUTH -> link.notify(w.address, authSuccess(w.magic), w.sid)
OtaFlashFlow.SID_CTRL -> {
val pb = BleProtocol.stripTrailingCrc(w.pb)
when (pb[0].toInt()) {
OtaFlashFlow.OP_BEGIN -> link.otaAck(w.address, OtaFlashFlow.OP_BEGIN, 0)
OtaFlashFlow.OP_FILE_CHECK -> { component = ByteArray(0); link.otaAck(w.address, OtaFlashFlow.OP_FILE_CHECK, 0) }
OtaFlashFlow.OP_END -> {
val status = if (failEndOnce) { failEndOnce = false; 5 } else { received[w.address] = (received[w.address] ?: ByteArray(0)) + component; 9 }
link.otaAck(w.address, OtaFlashFlow.OP_END, status)
}
OtaFlashFlow.OP_BLOCK -> {}
}
}
OtaFlashFlow.SID_DATA -> {
val block = BleProtocol.stripTrailingCrc(w.pb)
if (nakOnce) { nakOnce = false; link.otaAck(w.address, OtaFlashFlow.OP_BLOCK, 1) } else { component += block; link.otaAck(w.address, OtaFlashFlow.OP_BLOCK, 0) }
}
}
}
}
@Test
fun otaFlashesBothLensesWithBlockNakAndEndRetry() {
val img = container()
val segs = FirmwareImage.validate(img)
val link = FakeStockLink()
val lens = OtaLens(link)
link.responder = lens::respond
val events = FlashEvents()
OtaFlashFlow(link, R, L, "fw.bin", events, fast, testPlatform()) { img }.run()
assertEquals(true to "Both lenses flashed. The glasses are rebooting into the custom firmware.", events.complete, events.logs.joinToString("\n"))
assertEquals(listOf("validating:", "connecting:left", "flashing:left", "rebooting:Left lens done. Both lenses reboot briefly; reconnecting for the right lens.", "connecting:right", "flashing:right", "done:"), events.states)
// Every component payload arrived intact on both lenses, in order.
val expected = segs.fold(ByteArray(0)) { acc, s -> acc + img.copyOfRange(s.payloadStart, s.payloadStart + s.ps) }
assertContentEquals(expected, lens.received[L]!!)
assertContentEquals(expected, lens.received[R]!!)
assertTrue(events.logs.any { it.contains("NAK=1 resend 1/3") })
assertTrue(events.logs.any { it.contains("END verify FAILED (status 5)") })
assertTrue(events.logs.any { it.contains("re-flash attempt 2/3") })
assertEquals("left 5/5 2/2 6524/6524", events.progress.first { it.startsWith("left 5/5 2") })
// Marker + data share one envelope seq; the OTA stream restarts at 1 per lens.
val leftOta = link.writes.filter { it.address == L && it.uuid == BleProtocol.OTA_DATA_WRITE_UUID }
assertEquals(1, leftOta.first().seq)
val firstBlock = leftOta.indexOfFirst { it.sid == OtaFlashFlow.SID_DATA }
assertEquals(leftOta[firstBlock - 1].seq, leftOta[firstBlock].seq)
assertEquals(setOf(BleProtocol.WRITE_CHAR_UUID), link.writes.filter { it.sid == BleProtocol.SID_SECURITY_AUTH }.map { it.uuid }.toSet())
}
@Test
fun otaGivesUpWhenLensConnectWindowExpires() {
val link = FakeStockLink()
link.connectResult = { false }
val events = FlashEvents()
OtaFlashFlow(link, R, L, "fw.bin", events, fast, testPlatform()) { container() }.run()
assertEquals(false to "could not reach left lens: connect/discover incomplete", events.complete)
assertEquals("error:could not reach left lens: connect/discover incomplete", events.states.last())
assertTrue(events.logs.count { it.contains("left connect attempt") } >= 2)
assertTrue(link.closed)
val unreadable = FlashEvents()
OtaFlashFlow(FakeStockLink(), R, L, "/nonexistent/fw.bin", unreadable, fast, testPlatform()).run()
assertTrue(unreadable.complete!!.second.startsWith("could not read firmware"), unreadable.complete!!.second)
}
}
@@ -0,0 +1,273 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
class VoiceCaptureSessionTest {
/** Real clock plus an offset the test can advance to force decode cadences. */
private class ShiftedPlatform(private val base: ProtocolPlatform) : ProtocolPlatform by base {
var offsetMs = 0L
override fun elapsedRealtimeMs(): Long = base.elapsedRealtimeMs() + offsetMs
}
private class Events : FaceclawVoiceControllerListener {
val statuses = mutableListOf<String?>()
val transcripts = mutableListOf<Pair<String?, Boolean>>()
val pcmChunks = mutableListOf<ByteArray>()
val frameMeta = mutableListOf<Pair<Int, Int>>()
var speechEnds = 0
var verified: Pair<Boolean, Float>? = null
val stopped = mutableListOf<Int>()
val stoppedLatch = Latch(1, testPlatform())
override fun onStatus(status: String?) { statuses.add(status) }
override fun onTranscript(text: String?, isFinal: Boolean) { transcripts.add(text to isFinal) }
override fun onStopped(captureId: Int) { stopped.add(captureId); stoppedLatch.countDown() }
override fun onPcm(pcm16le: ByteArray?) { pcmChunks.add(pcm16le!!) }
override fun onFrameMeta(angleDegrees: Int, ssr: Int) { frameMeta.add(angleDegrees to ssr) }
override fun onSpeechEnd() { speechEnds++ }
override fun onSpeakerVerified(isWearer: Boolean, similarity: Float) { verified = isWearer to similarity }
}
/** Scripted phone mic: each entry is a chunk amplitude; after the script the read fails (-1). */
private class ScriptedMic(private val amplitudes: List<Int>, private val onRead: () -> Unit = {}) : PcmAudioSource {
var index = 0
var closed = false
override fun read(pcm: ShortArray): Int {
onRead()
if (index >= amplitudes.size) return -1
val amplitude = amplitudes[index++]
for (i in pcm.indices) pcm[i] = (if (i % 2 == 0) amplitude else -amplitude).toShort()
return pcm.size
}
override fun close() { closed = true }
}
private class FakeTranscriber(private val text: (Int) -> String) : OfflineTranscriber {
val calls = mutableListOf<Int>()
var released = false
override fun recognize(samples: FloatArray, count: Int): String { calls.add(count); return text(count) }
override fun release() { released = true }
}
private class FakeHost(
val platform: ProtocolPlatform,
var mic: PcmAudioSource? = null,
var transcriber: OfflineTranscriber? = null,
var hasModel: Boolean = true,
var embedding: FloatArray? = null,
var g2Ready: Boolean = false,
) : VoiceCaptureHost {
override val dispatcher = CallbackDispatcher { it() }
var packetListener: FaceclawAudioPacketListener? = null
var g2Stops = 0
val recordings = mutableListOf<ByteArray>()
override fun onSessionStarting() {}
override fun isG2SessionReady(): Boolean = g2Ready
override fun isG2AudioCaptureActive(): Boolean = packetListener != null
override fun g2AudioSource(): PacketAudioSource? = if (!g2Ready) null else object : PacketAudioSource {
override fun start(listener: FaceclawAudioPacketListener): Boolean { packetListener = listener; return true }
override fun stop() { g2Stops++ }
override fun isActive(): Boolean = packetListener != null
}
override fun createPacketDecoder(): AudioPacketDecoder = object : AudioPacketDecoder {
override fun decodePacket(packet: ByteArray?, pcmOut: ShortArray?): Int {
if (packet == null || packet.size != Lc3PacketFramer.PACKET_BYTES) return 0
pcmOut!!.fill(packet[0].toShort())
lastAngleDegrees = Lc3PacketFramer.readTrailerS16(packet, Lc3PacketFramer.ANGLE_OFFSET)
lastSsr = Lc3PacketFramer.readTrailerS16(packet, Lc3PacketFramer.SSR_OFFSET)
realPackets++
return Lc3PacketFramer.SAMPLES_PER_PACKET
}
override var lastAngleDegrees = 0
override var lastSsr = 0
override var realPackets = 0L
override val duplicatePackets = 0L
override val missingPackets = 0L
override val decodeErrors = 0L
override fun close() {}
}
override fun openPhoneMic(): PcmAudioSource? = mic
override fun hasTranscriberModel(kind: VoiceModelKind): Boolean = hasModel
override fun loadTranscriber(kind: VoiceModelKind): OfflineTranscriber = transcriber ?: error("no transcriber")
override fun speakerEmbedder(modelPath: String): SpeakerEmbedder = object : SpeakerEmbedder {
override fun embed(pcm16le: ByteArray, sampleRate: Int): FloatArray? = embedding
override fun release() {}
}
override fun recordingSink(): RecordingSink = RecordingSink { bytes, _ -> recordings.add(bytes) }
}
private val logs = mutableListOf<String>()
private fun session(host: VoiceCaptureHost, platform: ProtocolPlatform, name: String) =
VoiceCaptureSession(host, platform, name, { logs.add("I $it") }, { logs.add("W $it") }, { m, e -> logs.add("E $m ${e.message}") })
private fun packet(value: Int, angle: Int, ssr: Int): ByteArray {
val bytes = ByteArray(Lc3PacketFramer.PACKET_BYTES)
bytes[0] = value.toByte()
bytes[Lc3PacketFramer.SSR_OFFSET] = (ssr and 0xff).toByte()
bytes[Lc3PacketFramer.SSR_OFFSET + 1] = (ssr shr 8).toByte()
bytes[Lc3PacketFramer.ANGLE_OFFSET] = (angle and 0xff).toByte()
bytes[Lc3PacketFramer.ANGLE_OFFSET + 1] = (angle shr 8).toByte()
return bytes
}
@Test
fun beamGateWrapsAroundAndClampsHalfWidth() {
val session = session(FakeHost(testPlatform()), testPlatform(), "voice-test-beam")
session.setBeamFilter(true, 170, 30)
assertTrue(session.withinBeam(170))
assertTrue(session.withinBeam(-170)) // 20 degrees away across the wrap
assertFalse(session.withinBeam(120))
session.setBeamFilter(true, 0, 1) // clamps to 5
assertTrue(session.withinBeam(5))
assertFalse(session.withinBeam(6))
}
@Test
fun droppingQueueKeepsNewestAndCountsDrops() {
val queue = DroppingPacketQueue<Int>(3, testPlatform())
for (i in 1..5) queue.put(i)
assertEquals(2L, queue.droppedCount)
assertEquals(3, queue.take(10) { true })
assertEquals(4, queue.take(10) { true })
assertEquals(5, queue.take(10) { true })
assertNull(queue.take(10, { true }))
assertNull(queue.take(10, { false }))
}
@Test
fun g2PacketsAreCountedGatedAndForwarded() {
val platform = ShiftedPlatform(testPlatform())
val host = FakeHost(platform, g2Ready = true)
val events = Events()
val session = session(host, platform, "voice-test-g2")
session.setListener(events)
session.setBeamFilter(true, 0, 30)
session.start("cloud", 7)
val deadline = platform.elapsedRealtimeMs() + 3000
while (host.packetListener == null && platform.elapsedRealtimeMs() < deadline) sleepMs(5)
val listener = host.packetListener!!
listener.onAudioPacket(packet(1, 10, 5), "L", 1000)
listener.onAudioPacket(packet(2, 90, 5), "L", 1050) // outside the beam: meta only
listener.onAudioPacket(packet(3, 0, 0), "R", 1200) // wrong arm, late (150 ms gap), ssr 0 passes the gate
listener.onAudioPacket(ByteArray(3), "L", 1230) // bad length: dropped by the decoder
val waitUntil = platform.elapsedRealtimeMs() + 3000
while (events.pcmChunks.size < 2 && platform.elapsedRealtimeMs() < waitUntil) sleepMs(5)
session.stop()
assertTrue(events.stoppedLatch.await(3000))
val stats = session.audioStats()
assertEquals(4L, stats.queuedPackets)
assertEquals(1L, stats.wrongArmPackets)
assertEquals(1L, stats.latePackets)
assertEquals(150L, stats.maxInterPacketMs)
assertEquals(2, events.pcmChunks.size)
assertEquals(Lc3PacketFramer.SAMPLES_PER_PACKET * 2, events.pcmChunks[0].size)
assertEquals(listOf(10 to 5, 90 to 5, 0 to 0), events.frameMeta)
assertEquals(listOf(7), events.stopped)
assertTrue(host.g2Stops >= 1)
assertTrue(events.statuses.contains("Listening (cloud)..."))
assertTrue(events.transcripts.isEmpty())
assertTrue(logs.any { it.startsWith("I G2 mic packets=4 decoded=3") && it.contains("wrongArm=1") }, logs.toString())
}
@Test
fun startRefusesWithoutGlassesAndWhenAlreadyRunning() {
val host = FakeHost(testPlatform(), g2Ready = false)
val events = Events()
val session = session(host, testPlatform(), "voice-test-refuse")
session.setListener(events)
session.start("onboard", 3)
assertEquals<List<String?>>(listOf("Voice control needs an active G2 connection."), events.statuses)
assertEquals(listOf(3), events.stopped)
assertFalse(session.isCapturing())
}
@Test
fun onboardTranscriptCommitsSegmentsAndFinalizesWithReplaceSemantics() {
val platform = ShiftedPlatform(testPlatform())
// 170 chunks of 800 samples = 8.5 s: one 8 s segment commit plus a tail.
val mic = ScriptedMic(List(170) { 3000 }) { platform.offsetMs += 1000 }
val transcriber = FakeTranscriber { "x" }
val host = FakeHost(platform, mic = mic, transcriber = transcriber)
val events = Events()
val session = session(host, platform, "voice-test-onboard")
session.setListener(events)
session.setUsePhoneMic(true)
session.setSaveRecordings(true)
session.start("onboard", 1)
assertTrue(events.stoppedLatch.await(10000))
assertTrue(mic.closed)
assertTrue(transcriber.released)
assertEquals("Loading transcription model...", events.statuses[0])
assertEquals("Listening...", events.statuses[1])
val finals = events.transcripts.filter { it.second }
assertEquals(1, finals.size)
assertEquals("x x", finals.single().first)
assertEquals("x" to false, events.transcripts.first())
assertTrue(events.transcripts.any { it == ("x x" to false) })
// Every segment handed to the model is at most 8 s and was peak-normalized.
assertTrue(transcriber.calls.all { it in 1..VoiceCaptureSession.TRANSCRIPT_SEGMENT_MAX_SAMPLES })
assertTrue(logs.any { it.startsWith("I Moonshine decode final=true") }, logs.toString())
assertEquals(1, host.recordings.size)
assertEquals(170 * 800 * 2, host.recordings[0].size)
assertEquals(170, events.pcmChunks.size)
assertEquals("x x", VoiceCaptureSession.joinTranscript("x", "x"))
assertEquals("x, y", VoiceCaptureSession.joinTranscript("x", ", y"))
}
@Test
fun endpointingFiresOnceAfterSpeechThenSilence() {
val platform = ShiftedPlatform(testPlatform())
val script = List(8) { 0 } + List(10) { 3000 } + List(24) { 0 }
val host = FakeHost(platform, mic = ScriptedMic(script))
val events = Events()
val session = session(host, platform, "voice-test-endpoint")
session.setListener(events)
session.setUsePhoneMic(true)
session.setEndpointing(true)
session.start("cloud", 2)
assertTrue(events.stoppedLatch.await(10000))
assertEquals(1, events.speechEnds)
assertNull(events.verified)
}
@Test
fun speakerVerificationFailsOpenAndComparesEmbeddings() {
fun run(embedding: FloatArray?, chunks: Int): Pair<Boolean, Float>? {
val platform = ShiftedPlatform(testPlatform())
val host = FakeHost(platform, mic = ScriptedMic(List(chunks) { 1000 }), embedding = embedding)
val events = Events()
val session = session(host, platform, "voice-test-verify")
session.setListener(events)
session.setUsePhoneMic(true)
session.setSpeakerVerification("model", floatArrayOf(1f, 0f), 0.8f)
session.start("cloud", 4)
assertTrue(events.stoppedLatch.await(10000))
return events.verified
}
assertEquals<Pair<Boolean, Float>?>(true to 0f, run(floatArrayOf(1f, 0f), 10)) // under 1 s: too short, fails open
assertEquals<Pair<Boolean, Float>?>(true to 0f, run(null, 30)) // no embedding: fails open
assertEquals<Pair<Boolean, Float>?>(true to 0f, run(floatArrayOf(1f), 30)) // dimension mismatch: fails open
assertEquals<Pair<Boolean, Float>?>(true to 1f, run(floatArrayOf(1f, 0f), 30))
assertEquals<Pair<Boolean, Float>?>(false to 0f, run(floatArrayOf(0f, 1f), 30))
}
@Test
fun missingModelReportsAndStops() {
val host = FakeHost(testPlatform(), mic = ScriptedMic(emptyList()), hasModel = false)
val events = Events()
val session = session(host, testPlatform(), "voice-test-nomodel")
session.setListener(events)
session.setUsePhoneMic(true)
session.start("onboard", 9)
assertTrue(events.stoppedLatch.await(5000))
assertEquals<List<String?>>(listOf("Voice model not downloaded (see Settings > Voice)."), events.statuses)
assertEquals(listOf(9), events.stopped)
assertEquals("1.50", formatFixed(1.5, 2))
assertEquals("-0.333", formatFixed(-1.0 / 3, 3))
assertEquals("0", formatFixed(0.4, 0))
}
}
@@ -0,0 +1,42 @@
package com.faceclaw.app
import kotlin.test.*
class VoiceEndpointDetectorTest {
@Test fun silenceEndsOnlyAfterSpeechAndFiresOnce() {
val detector = VoiceEndpointDetector()
repeat(6) { assertFalse(detector.acceptLevel(100.0, 800)) }
repeat(10) { assertFalse(detector.accept(ShortArray(800) { 2000 }, 800)) }
repeat(17) { assertFalse(detector.acceptLevel(100.0, 800)) }
assertTrue(detector.acceptLevel(100.0, 800))
assertFalse(detector.acceptLevel(100.0, 800))
detector.reset()
assertFalse(detector.acceptLevel(100.0, 800))
}
@Test fun pausesResetWhenSpeechResumesAndContinuousSpeechIsBounded() {
val detector = VoiceEndpointDetector()
repeat(6) { assertFalse(detector.acceptLevel(0.0, 800)) }
assertFalse(detector.acceptLevel(2000.0, 800))
repeat(17) { assertFalse(detector.acceptLevel(0.0, 800)) }
assertFalse(detector.acceptLevel(2000.0, 800))
repeat(17) { assertFalse(detector.acceptLevel(0.0, 800)) }
assertTrue(detector.acceptLevel(0.0, 800))
detector.reset()
repeat(6) { assertFalse(detector.acceptLevel(0.0, 800)) }
repeat(593) { assertFalse(detector.acceptLevel(2000.0, 800)) }
assertTrue(detector.acceptLevel(2000.0, 800))
}
@Test fun quietRoomTimesOutOnSampleClockAndNoiseCalibrationIsRelative() {
val detector = VoiceEndpointDetector()
repeat(119) { assertFalse(detector.acceptLevel(0.0, 800)) }
assertTrue(detector.acceptLevel(0.0, 800))
detector.reset()
repeat(6) { assertFalse(detector.acceptLevel(1000.0, 800)) }
repeat(20) { assertFalse(detector.acceptLevel(2000.0, 800)) }
assertFalse(detector.acceptLevel(4000.0, 800))
repeat(17) { assertFalse(detector.acceptLevel(1000.0, 800)) }
assertTrue(detector.acceptLevel(1000.0, 800))
}
}
@@ -0,0 +1,36 @@
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertTrue
import platform.Foundation.NSDate
import platform.Foundation.NSDefaultRunLoopMode
import platform.Foundation.NSRunLoop
import platform.Foundation.NSThread
import platform.Foundation.dateWithTimeIntervalSinceNow
import platform.Foundation.runMode
class IosBleCentralTest {
/** Registering a state listener must create the central and report a state without any scan. */
@Test
fun scanListenerAloneReceivesABluetoothStateReport() {
val central = IosBleCentral(IosProtocolPlatform)
val states = ArrayList<Int>()
var offMain = 0
central.setScanListener(object : IosBleScanListener {
override fun onBluetoothState(state: Int, authorization: Int) {
if (!NSThread.isMainThread) offMain++
states.add(state)
}
override fun onAdvertisement(identifier: String, name: String, manufacturerDataHex: String, rssi: Int, connectable: Boolean) {}
})
val deadline = IosProtocolPlatform.elapsedRealtimeMs() + 5_000
while (IosProtocolPlatform.elapsedRealtimeMs() < deadline && states.none { it != 0 }) {
NSRunLoop.mainRunLoop.runMode(NSDefaultRunLoopMode, NSDate.dateWithTimeIntervalSinceNow(0.02))
}
// The simulator reports unsupported/powered-off; a real phone powered-on. Any non-unknown state proves the central exists.
assertTrue(states.any { it != 0 }, "no CBManagerState reported: $states")
assertTrue(offMain == 0, "state reports must arrive on the main queue")
central.close()
}
}
@@ -0,0 +1,46 @@
package com.faceclaw.app
import kotlin.test.*
class IosNativeApiTest {
@Test
fun binaryFacadeRoundTripsAndSlices() {
val bytes = byteArrayOf(0, -1, 2, -128)
assertContentEquals(bytes, bytes.data().byteArray())
assertTrue(byteArrayOf().data().byteArray().isEmpty())
val reader = IosByteReader(bytes.data())
assertEquals(0, reader.get().toInt())
val target = ByteArray(5)
reader.get(target, 1, 3)
assertContentEquals(byteArrayOf(0, -1, 2, -128, 0), target)
assertEquals(0, reader.remaining())
val protocol = IosProtocol()
val auth = protocol.authentication(101)
val frames = protocol.frame(auth, 128, 0, 64, 185)
val result = IosMessageReceiver().receive("L", frames.single(), 0).single()
assertEquals(101, result.magic)
assertContentEquals(auth.byteArray(), result.payload.byteArray())
}
@Test
fun compassFacadePreservesTheEndOfTheCrcFreePayload() {
val protocol = IosProtocol()
val payload = byteArrayOf(8, 15, 16, 0, 82, 3, 8, -25, 2).data()
assertEquals(359, protocol.compassInput(payload, 8, 1)?.headingDegrees)
assertNull(protocol.compassInput(payload, 8, 0))
}
@Test
fun nativeCompositorClipsPartialUpdatesBeforeCoalescing() {
val compositor = IosSurfaceCompositor(3, 2)
compositor.configure("app", 0, 0, 3, 2, 0, false)
compositor.submit("app", byteArrayOf(10, 20, 30, 40, 50, 60).data(), -1, 0, 3, 2)
assertContentEquals(byteArrayOf(20, 30, 0, 50, 60, 0), compositor.composite().byteArray())
compositor.submit("app", byteArrayOf(99).data(), 2, 1, 1, 1)
assertContentEquals(byteArrayOf(20, 30, 0, 50, 60, 99), compositor.composite().byteArray())
compositor.blank(true)
assertContentEquals(ByteArray(6), compositor.composite().byteArray())
compositor.blank(false)
assertEquals(99, compositor.composite().byteArray().last().toInt())
}
}
@@ -0,0 +1,314 @@
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
package com.faceclaw.app
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.cinterop.ByteVar
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.alloc
import kotlinx.cinterop.allocPointerTo
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.pointed
import kotlinx.cinterop.ptr
import kotlinx.cinterop.usePinned
import kotlinx.cinterop.value
import platform.Foundation.NSTemporaryDirectory
import platform.posix.AI_NUMERICHOST
import platform.posix.AI_NUMERICSERV
import platform.posix.SOCK_STREAM
import platform.posix.addrinfo
import platform.posix.close
import platform.posix.connect
import platform.posix.freeaddrinfo
import platform.posix.getaddrinfo
import platform.posix.recv
import platform.posix.send
import platform.posix.socket
private var nextPort = 43000 + (currentTimeMillis() % 9000).toInt()
/** Binds the next free loopback port; returns the listener and its port. */
private fun bindFreePort(): Pair<RemoteInputListener, Int> {
repeat(50) {
val port = nextPort++
val listener = runCatching { IosLocalServerPort.bind("127.0.0.1", port) }.getOrNull() ?: return@repeat
return listener to port
}
error("no free loopback port")
}
/** Blocking POSIX client: connects to loopback, sends [request], reads until the peer closes. */
private fun loopbackExchange(port: Int, request: ByteArray, readTimeoutMs: Int = 8000): ByteArray = memScoped {
val hints = alloc<addrinfo>()
hints.ai_flags = AI_NUMERICHOST or AI_NUMERICSERV
hints.ai_socktype = SOCK_STREAM
val resolved = allocPointerTo<addrinfo>()
check(getaddrinfo("127.0.0.1", port.toString(), hints.ptr, resolved.ptr) == 0)
val info = resolved.value!!.pointed
val fd = socket(info.ai_family, SOCK_STREAM, 0)
check(fd >= 0)
try {
check(connect(fd, info.ai_addr, info.ai_addrlen) == 0) { "connect failed" }
request.usePinned { check(send(fd, it.addressOf(0), request.size.toULong(), 0) == request.size.toLong()) }
val out = ByteSink()
val buffer = ByteArray(4096)
val deadline = IosProtocolPlatform.elapsedRealtimeMs() + readTimeoutMs
while (IosProtocolPlatform.elapsedRealtimeMs() < deadline) {
val n = buffer.usePinned { recv(fd, it.addressOf(0), buffer.size.toULong(), 0) }
if (n <= 0L) break
out.write(buffer, 0, n.toInt())
if (out.toByteArray().last() == '\n'.code.toByte()) break
}
out.toByteArray()
} finally {
freeaddrinfo(resolved.value)
close(fd)
}
}
/** Minimal loopback HTTP/1.1 server for the NSURLSession facades; one request per connection. */
private class LoopbackHttpServer(private val handler: (path: String, headers: Map<String, String>) -> Reply) {
class Reply(val status: Int, val headers: List<Pair<String, String>>, val pieces: List<ByteArray>, val pieceDelayMs: Long = 0)
private val listener: RemoteInputListener
val port: Int
val requests = ArrayList<Map<String, String>>()
private val lock = IosProtocolPlatform.createLock()
init {
val bound = bindFreePort()
listener = bound.first
port = bound.second
startThread("loopback-http", true) {
while (!listener.isClosed) {
val connection = listener.accept() ?: continue
startThread("loopback-http-conn", true) { serve(connection) }
}
}
}
fun url(path: String) = "http://127.0.0.1:$port$path"
fun close() = listener.close()
fun requestsFor(path: String): List<Map<String, String>> = lock.withLock { requests.filter { it["path"] == path } }
private fun serve(connection: RemoteInputConnection) {
try {
val head = ByteSink()
while (true) {
val b = connection.readByte(5000)
if (b < 0) return
head.write(b)
val bytes = head.toByteArray()
val n = bytes.size
if (n >= 4 && bytes[n - 4] == '\r'.code.toByte() && bytes[n - 3] == '\n'.code.toByte() &&
bytes[n - 2] == '\r'.code.toByte() && bytes[n - 1] == '\n'.code.toByte()) break
}
val lines = head.toByteArray().decodeToString().split("\r\n").filter { it.isNotEmpty() }
val path = lines.first().split(' ')[1]
val headers = lines.drop(1).associate { it.substringBefore(':').trim().lowercase() to it.substringAfter(':').trim() }
val bodyLength = headers["content-length"]?.toIntOrNull() ?: 0
repeat(bodyLength) { connection.readByte(5000) }
lock.withLock { requests.add(headers + ("path" to path)) }
val reply = handler(path, headers)
val total = reply.pieces.sumOf { it.size }
val response = buildString {
append("HTTP/1.1 ${reply.status} X\r\n")
for ((name, value) in reply.headers) append("$name: $value\r\n")
append("Content-Length: $total\r\nConnection: close\r\n\r\n")
}
connection.write(response.encodeToByteArray())
for (piece in reply.pieces) {
connection.write(piece)
if (reply.pieceDelayMs > 0) sleepMs(reply.pieceDelayMs)
}
} catch (ignored: Exception) {
} finally {
connection.close()
}
}
}
private fun waitUntil(timeoutMs: Long, condition: () -> Boolean): Boolean {
val deadline = IosProtocolPlatform.elapsedRealtimeMs() + timeoutMs
while (IosProtocolPlatform.elapsedRealtimeMs() < deadline) {
if (condition()) return true
sleepMs(20)
}
return condition()
}
private class RecordingSseListener : FaceclawSseListener {
private val lock = IosProtocolPlatform.createLock()
val lines = ArrayList<String>()
var httpError: Pair<Int, String>? = null
var failure: String? = null
var completed = false
val finished: Boolean get() = lock.withLock { completed || httpError != null || failure != null }
override fun onLine(line: String?) { lock.withLock { lines.add(line ?: "") } }
override fun onHttpError(code: Int, body: String?) { lock.withLock { httpError = code to (body ?: "") } }
override fun onComplete() { lock.withLock { completed = true } }
override fun onFailure(message: String?) { lock.withLock { failure = message ?: "" } }
}
private class RecordingDownloadListener : FaceclawModelDownloaderListener {
private val lock = IosProtocolPlatform.createLock()
var progress = 0
var done: String? = null
var error: String? = null
val finished: Boolean get() = lock.withLock { done != null || error != null }
override fun onProgress(bytesDownloaded: Long, totalBytes: Long) { lock.withLock { progress++ } }
override fun onDone(path: String?) { lock.withLock { done = path } }
override fun onError(message: String?) { lock.withLock { error = message } }
}
class IosNetworkingTest {
private val immediate: (() -> Unit) -> Unit = { it() }
/** Like the main queue: never runs on the caller's thread, so the session's lock is not re-entered. */
private val hop: (() -> Unit) -> Unit = { action -> startThread("test-dispatch", true, action) }
@Test
fun remoteInputRoundTripsOverLoopbackAndTimesOut() {
val (probe, port) = bindFreePort()
probe.close()
val remote = IosRemoteInput(hop, requestTimeoutMs = 1200)
val ready = BlockingQueue<String>(IosProtocolPlatform)
remote.setRequestListener { ready.put("ready") }
assertEquals("Invalid local address.", remote.startAddress(port, "example.com"))
assertEquals("Address is not assigned to a local interface.", remote.startAddress(port, "0.0.0.0"))
assertEquals("", remote.startAddress(port, "127.0.0.1"))
try {
val replies = BlockingQueue<ByteArray>(IosProtocolPlatform)
startThread("remote-client", true) { replies.put(loopbackExchange(port, "hello world\n".encodeToByteArray())) }
assertEquals("ready", ready.poll(5000))
val request = Json.parseObject(assertNotNull(remote.nextRequest()))
assertEquals("hello world", request["body"].asString())
assertNull(remote.nextRequest())
remote.complete(request["id"].asLong()!!, "{\"ok\":true}")
assertEquals("{\"ok\":true}\n", assertNotNull(replies.poll(5000)).decodeToString())
startThread("remote-client-2", true) { replies.put(loopbackExchange(port, "later\n".encodeToByteArray())) }
assertEquals("ready", ready.poll(5000))
assertNotNull(remote.nextRequest())
assertEquals(RemoteInputSession.TIMEOUT_RESPONSE + "\n", assertNotNull(replies.poll(8000)).decodeToString())
assertEquals(64, remote.randomSecret().length)
assertEquals(RemoteInputSession.tokenHash("abc"), remote.tokenDigest("abc"))
val all = iosInterfaceAddresses()
assertTrue(all.any { it.loopback && it.address == "127.0.0.1" }, all.toString())
assertTrue(Json.parseArray(remote.interfaces()).none { it.asObject()!!["address"].asString() == "127.0.0.1" })
assertTrue(IosLocalServerPort.isLocalUnicastAddress("::1"))
assertFalse(IosLocalServerPort.isLocalUnicastAddress("224.0.0.1"))
} finally {
remote.stop()
}
}
@Test
fun sseStreamsLinesRefusesRedirectsAndReportsErrors() {
val body = "event: a\r\ndata: one\n\ndata: two\r\n".encodeToByteArray()
val server = LoopbackHttpServer { path, _ ->
when (path) {
"/sse" -> LoopbackHttpServer.Reply(200, listOf("Content-Type" to "text/event-stream"),
listOf(body.copyOfRange(0, 13), body.copyOfRange(13, body.size)), pieceDelayMs = 50)
"/limited" -> LoopbackHttpServer.Reply(429, listOf("Content-Type" to "text/plain"), listOf("slow down".encodeToByteArray()))
else -> LoopbackHttpServer.Reply(302, listOf("Location" to "http://127.0.0.1:1/never"), listOf(ByteArray(0)))
}
}
try {
val ok = RecordingSseListener()
IosSseRequest(server.url("/sse"), "{\"q\":1}", "{\"X-Test\":\"yes\"}", ok, immediate, false)
assertTrue(waitUntil(10_000) { ok.finished }, "sse did not finish: ${ok.failure}")
assertEquals(listOf("event: a", "data: one", "", "data: two"), ok.lines)
assertTrue(ok.completed)
val request = server.requestsFor("/sse").single()
assertEquals("yes", request["x-test"])
assertEquals("text/event-stream", request["accept"])
assertTrue(request["user-agent"]!!.isNotEmpty())
val limited = RecordingSseListener()
IosSseRequest(server.url("/limited"), "{}", null, limited, immediate, false)
assertTrue(waitUntil(10_000) { limited.finished })
assertEquals(429 to "slow down", limited.httpError)
val redirected = RecordingSseListener()
IosSseRequest(server.url("/moved"), "{}", "{}", redirected, immediate, false)
assertTrue(waitUntil(10_000) { redirected.finished })
assertEquals(302, redirected.httpError?.first)
assertTrue(server.requestsFor("/never").isEmpty())
} finally {
server.close()
}
}
@Test
fun downloaderFetchesAndResumesWithRange() {
val payload = ByteArray(200_000) { (it * 31 + it / 977).toByte() }
val sha = sha256Hex(payload)
val server = LoopbackHttpServer { _, headers ->
val range = headers["range"]
if (range != null && range.startsWith("bytes=")) {
val from = range.removePrefix("bytes=").removeSuffix("-").toInt()
LoopbackHttpServer.Reply(206, listOf("Content-Range" to "bytes $from-${payload.size - 1}/${payload.size}"),
listOf(payload.copyOfRange(from, payload.size)))
} else LoopbackHttpServer.Reply(200, emptyList(), listOf(payload.copyOfRange(0, 70_000), payload.copyOfRange(70_000, payload.size)), pieceDelayMs = 30)
}
val dir = NSTemporaryDirectory().trimEnd('/') + "/faceclaw-dl-" + currentTimeMillis()
val dest = "$dir/model.bin"
try {
val first = RecordingDownloadListener()
IosModelDownloader(server.url("/model.bin"), dest, sha, payload.size.toLong(), first, immediate).start()
assertTrue(waitUntil(20_000) { first.finished }, "download did not finish: ${first.error}")
assertEquals(dest, first.done, first.error)
assertContentEquals(payload, readFileData(dest))
assertTrue(first.progress >= 1)
assertNull(server.requestsFor("/model.bin").single()["range"])
deleteFile(dest)
writeFileData("$dest.part", payload.copyOfRange(0, 50_000))
val second = RecordingDownloadListener()
IosModelDownloader(server.url("/model.bin"), dest, sha, payload.size.toLong(), second, immediate).start()
assertTrue(waitUntil(20_000) { second.finished }, "resume did not finish: ${second.error}")
assertEquals(dest, second.done, second.error)
assertContentEquals(payload, readFileData(dest))
assertEquals("bytes=50000-", server.requestsFor("/model.bin").last()["range"])
assertEquals(-1L, fileLength("$dest.part"))
} finally {
server.close()
deleteFile(dest)
deleteFile("$dest.part")
}
}
@Test
fun frameTimingsExportsToAFile() {
val dir = NSTemporaryDirectory().trimEnd('/') + "/faceclaw-ft-" + currentTimeMillis()
platform.Foundation.NSFileManager.defaultManager.createDirectoryAtPath(dir, true, null, null)
val timings = IosFrameTimings(IosProtocolPlatform)
assertNull(timings.exportNow())
timings.startExport(dir)
val frame = timings.startFrame("test:frame")
timings.spanStart(frame, "work")
timings.log(frame, "hello")
timings.spanEnd(frame, "work")
timings.finishFrame(frame, "sent")
val path = assertNotNull(timings.exportNow())
assertEquals("$dir/${IosFrameTimings.EXPORT_FILE_NAME}", path)
val text = readFileData(path).decodeToString()
assertTrue(text.contains("test:frame"), text)
assertTrue(text.contains("hello"), text)
assertNull(timings.exportNow())
assertTrue(timings.statsSummary().isNotEmpty())
deleteFile(path)
}
}
@@ -0,0 +1,97 @@
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
package com.faceclaw.app
import kotlin.test.*
import kotlinx.cinterop.*
import platform.CoreBluetooth.*
import platform.posix.memset
import platform.zlib.*
internal actual fun testPlatform(): ProtocolPlatform = IosProtocolPlatform
internal actual fun inflateRecords(records: List<ByteArray>): List<ByteArray> = memScoped {
val stream = alloc<z_stream>()
memset(stream.ptr, 0, sizeOf<z_stream>().convert())
check(inflateInit(stream.ptr) == Z_OK)
try {
records.map { record ->
if (record[0].toInt() and CfwTransport.RESET_CONTEXT != 0)
check(inflateReset(stream.ptr) == Z_OK)
val body = record.copyOfRange(5, record.size)
if (record[0].toInt() and CfwTransport.COMPRESSED == 0) body
else {
val output = mutableListOf<Byte>()
val buffer = ByteArray(4096)
body.usePinned { input ->
stream.next_in = input.addressOf(0).reinterpret()
stream.avail_in = body.size.toUInt()
buffer.usePinned { destination ->
do {
stream.next_out = destination.addressOf(0).reinterpret()
stream.avail_out = buffer.size.toUInt()
val status = inflate(stream.ptr, Z_SYNC_FLUSH)
check(status == Z_OK || status == Z_BUF_ERROR)
output.addAll(buffer.take(buffer.size - stream.avail_out.toInt()))
} while (stream.avail_in > 0u || stream.avail_out == 0u)
}
}
stream.next_in = null
stream.next_out = null
output.toByteArray()
}
}
} finally {
inflateEnd(stream.ptr)
}
}
class IosProtocolTest {
@Test
fun wakewordPacketsReachTheSharedEventDecoder() {
val api = IosProtocol()
val ctrl = BleProtocol.encodeVarintField(1, 1) // EVEN_AI_WAKE_UP
val payload = (BleProtocol.encodeVarintField(1, BleProtocol.EVEN_AI_CMD_CTRL) +
BleProtocol.encodeBytesField(3, ctrl)).data()
for (flag in listOf(1, 6)) {
val event = assertNotNull(api.glassesInput(payload, BleProtocol.SID_EVEN_AI, flag))
assertEquals("even-ai", event.kind)
assertEquals(1, event.eventType)
}
assertNull(api.glassesInput(payload, BleProtocol.SID_EVEN_AI, 2))
assertNull(api.glassesInput(payload, 0xff, 1))
assertNull(api.glassesInput(byteArrayOf().data(), BleProtocol.SID_EVEN_AI, 1))
}
@Test
fun platformClockAndWriteModes() {
val before = IosProtocolPlatform.elapsedRealtimeMs()
assertTrue(before > 0)
assertTrue(IosProtocolPlatform.elapsedRealtimeMs() >= before)
assertEquals(
CBCharacteristicWriteWithResponse,
IosProtocolPlatform.writeType(GattWriteMode.WITH_RESPONSE),
)
assertEquals(
CBCharacteristicWriteWithoutResponse,
IosProtocolPlatform.writeType(ConnectionOptions.WRITE_MODE),
)
}
}
internal actual fun digest(bytes: ByteArray): String {
val result = ByteArray(32)
result.usePinned { output ->
if (bytes.isEmpty())
platform.CoreCrypto.CC_SHA256(null, 0u, output.addressOf(0).reinterpret())
else
bytes.usePinned { input ->
platform.CoreCrypto.CC_SHA256(
input.addressOf(0),
bytes.size.toUInt(),
output.addressOf(0).reinterpret(),
)
}
}
return BinaryEncoding.bytesToHex(result)
}
@@ -0,0 +1,228 @@
package com.faceclaw.app
import kotlin.concurrent.Volatile
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import platform.Foundation.NSDate
import platform.Foundation.NSDefaultRunLoopMode
import platform.Foundation.NSRunLoop
import platform.Foundation.NSThread
import platform.Foundation.dateWithTimeIntervalSinceNow
import platform.Foundation.runMode
private const val RIGHT = "11111111-2222-3333-4444-555555555501"
private const val LEFT = "11111111-2222-3333-4444-555555555502"
/** Pump the main run loop (which drains the main dispatch queue) until [condition] or timeout. */
private fun pumpMainUntil(timeoutMs: Long, condition: () -> Boolean): Boolean {
val deadline = IosProtocolPlatform.elapsedRealtimeMs() + timeoutMs
while (IosProtocolPlatform.elapsedRealtimeMs() < deadline) {
if (condition()) return true
NSRunLoop.mainRunLoop.runMode(NSDefaultRunLoopMode, NSDate.dateWithTimeIntervalSinceNow(0.02))
}
return condition()
}
/** A GATT link that acks EvenHub/settings/auth requests and CFW stream messages like the firmware. */
private class FakeIosLink : SessionLink {
lateinit var core: GlassesSessionCore
private val lock = IosProtocolPlatform.createLock()
val connected = HashSet<String>()
val disconnected = ArrayList<String>()
@Volatile var closed = false
@Volatile var writes = 0
private var seq = 0
override fun connect(address: String, timeoutMs: Int): Boolean {
connected.add(address)
return true
}
override fun requestHighPriority(address: String) {}
override fun requestMtu(address: String, mtu: Int, timeoutMs: Int): Boolean = true
override fun negotiatedMtu(address: String): Int = 247
override fun discoverServices(address: String, timeoutMs: Int): Boolean = true
override fun enableNotifications(address: String, characteristicUuid: String, enable: Boolean, timeoutMs: Int): Boolean = true
override fun writeFrames(address: String, characteristicUuid: String, frames: List<ByteArray>, mode: GattWriteMode, timeoutMs: Int): Boolean {
writes++
val sid = frames[0][6].toInt() and 255
val magic = if (sid == CfwTransport.SID) frames[0][2].toInt() and 255 else BleProtocol.parseFrame(frames[0]).msgSeq
val inFlight = core.monitor.withLock { core.inFlightMessages.firstOrNull { it.sid == sid && it.magic == magic && magic != 0 } }
if (inFlight != null) {
if (sid == CfwTransport.SID) {
for (lens in 1..2) core.onNotification(address, BleProtocol.NOTIFY_CHAR_UUID, cfwAck(magic, lens, inFlight.message.size, inFlight.cfwChecksum))
} else {
val joined = frames.flatMap { frame -> frame.slice(8 until 8 + (frame[3].toInt() and 255)) }.toByteArray()
val pb = joined.copyOf(maxOf(0, joined.size - 2))
core.onNotification(address, BleProtocol.NOTIFY_CHAR_UUID, ackFrame(sid, magic, pb))
}
}
return true
}
private fun ackFrame(sid: Int, magic: Int, request: ByteArray): ByteArray {
val body = if (sid == BleProtocol.SID_SECURITY_AUTH)
BleProtocol.encodeVarintField(1, 4) + BleProtocol.encodeVarintField(2, magic) + byteArrayOf(0x1a, 0x00)
else
BleProtocol.encodeVarintField(1, 1) + BleProtocol.encodeVarintField(2, magic)
return lock.withLock { BleProtocol.framePb(body, sid, 0x00, seq++)[0] }
}
private fun cfwAck(streamId: Int, lens: Int, size: Int, checksum: Int): ByteArray {
val packet = ByteArray(19)
packet[0] = 0xaa.toByte()
packet[1] = 0x12
packet[3] = 11
packet[4] = 1
packet[5] = 1
packet[6] = CfwTransport.SID.toByte()
packet[8] = 1
packet[9] = streamId.toByte()
packet[12] = lens.toByte()
packet[13] = size.toByte()
packet[14] = (size ushr 8).toByte()
packet[15] = checksum.toByte()
packet[16] = (checksum ushr 8).toByte()
val crc = CfwTransport.crc(packet.copyOfRange(8, 17))
packet[17] = crc.toByte()
packet[18] = (crc ushr 8).toByte()
return packet
}
override fun disconnect(address: String) {
disconnected.add(address)
connected.remove(address)
}
override fun close() {
closed = true
}
override fun isBonded(address: String): Boolean = true
override fun prepareBenchmarkLink(address: String, mode: Int) {}
override fun recordDisplayFrameSent() {}
}
private class MainThreadListener : FaceclawBleCommunicatorListener {
val phases = ArrayList<String>()
var offMainCallbacks = 0
private fun record(phase: String) {
if (!NSThread.isMainThread) offMainCallbacks++
phases.add(phase)
}
override fun onStateChange(phase: String?, status: String?) = record(phase ?: "")
override fun onRingEvent(kind: String?, containerName: String?, eventType: Int, eventSource: Int, systemExitReasonCode: Int, frameId: Int, ringTick: Long, ringType: Int, ringAux: Int, ringSpeed: Int) {}
override fun onBatteryState(headsetBattery: Int, headsetCharging: Int, ringBattery: Int, ringCharging: Int) {
if (!NSThread.isMainThread) offMainCallbacks++
}
override fun onSilentMode(silent: Boolean) {}
override fun onWearState(wearing: Boolean) {}
override fun onPhoneLockState(locked: Boolean) {}
override fun onEvenAppConflict(message: String?) {}
override fun onFrameMetrics(paintMs: Int, transmitMs: Int, tileCount: Int) {}
override fun onFrameFinished(frameId: Int, outcome: String?) {}
override fun onFirmwareInfo(leftVersion: String?, rightVersion: String?, extension: String?) {}
}
class IosSessionFacadeTest {
@Test
fun facadeSessionConnectsOverAnInjectedLinkAndReportsOnTheMainQueue() {
assertTrue(NSThread.isMainThread, "tests drive the main run loop")
val link = FakeIosLink()
val host = IosSessionHost(threadName = "test-session")
val session = IosGlassesSession(link, null, host, RIGHT, LEFT, "", IosProtocolPlatform)
link.core = session.coreForTests()
val listener = MainThreadListener()
session.setListener(listener)
assertTrue(session.start())
assertFalse(session.start(), "already running")
assertTrue(pumpMainUntil(5_000) { listener.phases.contains("connected") }, "phases=${listener.phases}")
assertTrue(session.isSessionReady())
assertEquals(0, listener.offMainCallbacks, "listener callbacks must arrive on the main queue")
assertTrue(pumpMainUntil(5_000) { link.writes > 3 }, "auth, prelude, settings and layout writes (saw ${link.writes})")
session.disconnect()
assertTrue(pumpMainUntil(2_000) { listener.phases.lastOrNull() == "disconnected" }, "phases=${listener.phases}")
assertFalse(session.isSessionReady())
assertTrue(link.closed)
assertEquals(listOf(RIGHT, LEFT), link.disconnected.takeLast(2))
assertEquals(0, listener.offMainCallbacks)
}
@Test
fun relayFramesReachTheAncsListenerOnMainAndOtherFramesDoNot() {
val link = FakeIosLink()
val host = IosSessionHost(threadName = "test-session-ancs")
val session = IosGlassesSession(link, null, host, RIGHT, LEFT, "", IosProtocolPlatform)
val core = session.coreForTests()
link.core = core
val relayed = ArrayList<ByteArray>()
var offMain = 0
session.setAncsListener(object : IosAncsListener {
override fun onAncsAuthorization(authorized: Boolean) {}
override fun onRelayFrame(data: platform.Foundation.NSData) {
if (!NSThread.isMainThread) offMain++
relayed.add(data.byteArray())
}
})
val relay = byteArrayOf(65, 78, 1, 0, 9, 9, 9, 9, 0, 0, 0)
core.onNotification(RIGHT, BleProtocol.NOTIFY_CHAR_UUID, relay)
core.onNotification(LEFT, BleProtocol.NOTIFY_CHAR_UUID, relay) // wrong arm: ignored by the tap
assertTrue(pumpMainUntil(2_000) { relayed.size == 1 })
assertEquals(relay.toList(), relayed[0].toList())
assertEquals(0, offMain)
session.setAncsListener(null)
core.onNotification(RIGHT, BleProtocol.NOTIFY_CHAR_UUID, relay)
assertFalse(pumpMainUntil(200) { relayed.size > 1 })
}
@Test
fun hostDispatchesToTheCallingQueueAndRunsTheWorker() {
val host = IosSessionHost(threadName = "test-host")
var onMain = false
host.currentThreadDispatcher().post { onMain = NSThread.isMainThread }
assertTrue(pumpMainUntil(1_000) { onMain })
var workerThread = ""
host.startWorker { workerThread = NSThread.currentThread.name ?: "" }
host.joinWorker(2_000)
assertEquals("test-host", workerThread)
var posted = false
host.postToMain { posted = NSThread.isMainThread }
assertTrue(pumpMainUntil(1_000) { posted })
assertFalse(host.isEvenAppActive())
}
@Test
fun stockFlowFacadesConstructWithoutBluetooth() {
// No CoreBluetooth on the simulator; construction and cancel/close must still be safe.
val probe = IosDeviceInfoProbe(RIGHT, LEFT)
probe.setListener(null)
probe.close()
val prompt = IosFlashPrompt(RIGHT, LEFT, "warn", true)
prompt.close()
val flasher = IosFirmwareFlasher(RIGHT, LEFT, "/nonexistent.bin")
flasher.close()
assertNotNull(IosFrameTimings.shared.core.buildExport())
}
}
@@ -0,0 +1,90 @@
package com.faceclaw.app
import kotlin.test.*
class IosTextureApiTest {
private fun imageDraw(id: Int): ByteArray = byteArrayOf(
1, id.toByte(), (id shr 8).toByte(), (id shr 16).toByte(), (id shr 24).toByte(), 0, 0, 0, 0,
)
@Test
fun nativeSnapshotsPreserveDrawsAcrossCoalescingAndSessionResets() {
val atlas = IosTextureAtlas()
val white = ByteArray(4) { -1 }.data()
val id = atlas.imageId("ios-texture-api-white", 2, 2, white)
assertEquals(id, IosTextureAtlas().imageId("ios-texture-api-white", 2, 2, white))
val compositor = IosSurfaceCompositor(8, 4)
compositor.configure("app", 2, 0, 2, 2, 0, false)
compositor.submitDraws("app", white, 0, 0, 2, 2, imageDraw(id).data())
val frame = compositor.compositeFrame()
assertEquals(2, frame.composite.draws!!.single().x)
// A later update must not change the previously submitted snapshot.
compositor.submit("app", ByteArray(4).data(), 0, 0, 2, 2)
assertTrue(compositor.compositeFrame().composite.draws!!.isEmpty())
val next = IosProtocol().pack(frame.pixels, 8, 4)
val planner = IosTexturePlanner()
val cold = assertNotNull(planner.plan(null, next, frame, 1))
assertEquals(27, cold.resourceCommands.first().byteArray()[0].toInt())
assertTrue(cold.resourceCommands.any { it.byteArray()[0].toInt() == 21 })
assertEquals(28, cold.payload.byteArray()[0].toInt())
val warm = assertNotNull(planner.plan(null, next, frame, 1))
assertTrue(warm.resourceCommands.isEmpty())
assertContentEquals(cold.payload.byteArray(), warm.payload.byteArray())
planner.reset()
assertTrue(assertNotNull(planner.plan(null, next, frame, 1)).resourceCommands.isNotEmpty())
// A partial update clears identities even if the caller supplies stale draws.
compositor.submitDraws("app", byteArrayOf(-1).data(), 0, 0, 1, 1, imageDraw(id).data())
assertTrue(compositor.compositeFrame().composite.draws!!.isEmpty())
}
@Test
fun glyphRegistrationAndDrawingUseTheSharedAsciiTable() {
val atlas = IosTextureAtlas()
val key = "ios-aa-texture-test"
val bytes = key.encodeToByteArray()
atlas.registerAaGlyphs((byteArrayOf(bytes.size.toByte()) + bytes +
byteArrayOf(2, 1, 0, 65, 0, 0, 0, 0, 0, 2, 2, -1, -1)).data())
val font = atlas.fontId(key)
val draws = byteArrayOf(0, font.toByte(), (font shr 8).toByte(), 65, 0, 0, 0, 0, 0, 0, 0, -1)
val compositor = IosSurfaceCompositor(4, 2)
compositor.configure("text", 0, 0, 2, 2, 0, false)
compositor.submitDraws("text", ByteArray(4) { -1 }.data(), 0, 0, 2, 2, draws.data())
val frame = compositor.compositeFrame()
val plan = assertNotNull(IosTexturePlanner().plan(null, IosProtocol().pack(frame.pixels, 4, 2), frame, 1))
assertTrue(plan.usedBytes > 2048 + 192)
assertEquals(28, plan.payload.byteArray()[0].toInt())
assertTrue(plan.resourceCommands.any { command ->
val bytes = command.byteArray()
bytes[0].toInt() == 26 && bytes.last().toInt() == 65
})
}
@Test
fun oversizedPlanDiscardsUnsentResidencyBeforePixelFallback() {
val atlas = IosTextureAtlas()
val white = ByteArray(4) { -1 }.data()
val id = atlas.imageId("ios-oversized-plan", 2, 2, white)
var random = 12345
val gray = ByteArray(640 * 480) {
random = random xor (random shl 13)
random = random xor (random ushr 17)
random = random xor (random shl 5)
random.toByte()
}
gray[0] = -1; gray[1] = -1; gray[640] = -1; gray[641] = -1
val compositor = IosSurfaceCompositor(640, 480)
compositor.configure("noise", 0, 0, 640, 480, 0, false)
compositor.submitDraws("noise", gray.data(), 0, 0, 640, 480, imageDraw(id).data())
val frame = compositor.compositeFrame()
val planner = IosTexturePlanner()
val noisy = assertNotNull(planner.plan(null, IosProtocol().pack(frame.pixels, 640, 480), frame, 1))
assertTrue(noisy.resourceCommands.all { it.length <= 65535uL })
planner.reset()
val small = IosSurfaceCompositor(4, 2)
small.configure("icon", 0, 0, 2, 2, 0, false)
small.submitDraws("icon", white, 0, 0, 2, 2, imageDraw(id).data())
val next = small.compositeFrame()
val retry = assertNotNull(planner.plan(null, IosProtocol().pack(next.pixels, 4, 2), next, 1))
assertTrue(retry.resourceCommands.isNotEmpty(), "the rejected plan's image was never uploaded")
}
}
Loaded 100 of 822 files, more files were not shown because too many files have changed in this diff. Show more