Merge main into ios-port and update the iOS CFW transport

This commit is contained in:
James Babcock committed 2026-09-17 23:33:51 -07:00
commit e8e144f3f2
156 files changed
+10528 -1679

No files matched your search

+5
View File
@@ -22,3 +22,8 @@ Compass diagnostics have focused UI and wire-format checks:
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`.
R1 battery field-106 decoding (valid zero, charging, unavailable/disconnected,
legacy firmware, malformed messages) uses the same C/Java golden packet:
node --test tests/ring-battery-protocol.test.cjs
+384
View File
@@ -0,0 +1,384 @@
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, deps, globals = {}) {
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, setTimeout, clearTimeout, ...globals, require(name) {
assert.ok(name in deps, `Unexpected import ${name} in ${file}`);
return deps[name];
} });
return exports;
}
const callbacks = () => ({ onTextDelta() {}, onToolActivity() {}, onTurnDone() {}, onError() {} });
const config = (model = 'terra', effort = 'low') => ({ kind: 'direct', llm: {
provider: model === 'sonnet' ? 'anthropic' : 'openai', selection: model, model, effort, apiKey: 'secret-key',
} });
function sessions() {
const turns = [];
let synchronousError = false;
const { AssistantSession } = load('app/assistant/session.ts', {
'../prompts': { ASSISTANT_SYSTEM_PROMPT_BASE: '', buildAssistantSystemPrompt: () => '', describeAssistantContext: () => '' },
'./bridge-client': { assistantBridge: {} },
'./direct-backend': { DirectAssistantBackend: class { runTurn(options) {
const turn = { ...options, cancelled: false };
turns.push(turn);
if (synchronousError) options.callbacks.onError('failed');
return { cancel() { turn.cancelled = true; } };
} } },
'./tool-registry': { toolRegistry: { listTools: () => [] } },
});
function done(text) {
const turn = turns.at(-1);
turn.messages.push({ role: 'assistant', content: text });
turn.callbacks.onTextDelta(text, text);
turn.callbacks.onTurnDone({ stopReason: 'end_turn' });
}
return { AssistantSession, turns, done, setError() { synchronousError = true; } };
}
function conversations(saved = '') {
const env = sessions();
const { AssistantConversations } = load('app/assistant/conversations.ts', {
'./session': { AssistantSession: env.AssistantSession },
'./models': { ASSISTANT_MODEL_VALUES: ['auto', 'terra', 'sonnet'] },
});
let stored = '';
const store = new AssistantConversations((model, effort) => config(model, effort), () => 'terra', (value) => { stored = value; }, saved);
return { ...env, store, saved: () => stored };
}
test('voice and chat reuse selected history; sessions isolate context and persist without credentials', () => {
const env = conversations();
const firstId = env.store.current().id;
const voice = env.store.ensureSession();
voice.sendUtterance('Remember the blue door', {}, callbacks());
assert.equal(env.store.create(), false);
env.done('I will remember.');
const chat = env.store.ensureSession();
assert.equal(chat, voice);
chat.sendUtterance('What color?', {}, callbacks());
assert.equal(env.turns.at(-1).messages[0].content, 'Remember the blue door');
assert.equal(chat.transcript[1].text, 'I will remember.');
env.done('Blue.');
assert.ok(env.store.create());
env.store.ensureSession().sendUtterance('A separate topic', {}, callbacks());
assert.equal(env.turns.at(-1).messages.length, 1);
env.done('New topic.');
assert.ok(env.store.select(firstId));
assert.equal(env.store.ensureSession(), voice);
const restored = conversations(env.saved());
assert.equal(restored.store.current().id, firstId);
assert.equal(restored.store.ensureSession().transcript.at(-1).text, 'Blue.');
assert.equal(env.saved().includes('secret-key'), false);
restored.store.ensureSession().sendUtterance('Continue after restart', {}, callbacks());
assert.equal(restored.turns.at(-1).messages[0].content, 'Remember the blue door');
});
test('model and effort changes retain transcript and apply only to the chosen session', () => {
const env = conversations();
const original = env.store.current().id;
env.store.ensureSession().sendUtterance('hello', {}, callbacks());
assert.equal(env.store.configure('sonnet', 'high'), false);
env.done('hi');
env.store.configure('sonnet', 'high');
env.store.ensureSession().sendUtterance('follow up', {}, callbacks());
assert.equal(env.turns.at(-1).provider, 'anthropic');
assert.equal(env.turns.at(-1).effort, 'high');
assert.equal(env.turns.at(-1).messages[0].content, 'hello');
env.done('still here');
env.store.create();
assert.equal(env.store.current().model, 'terra');
assert.equal(env.store.current().reasoning, 'default');
env.store.select(original);
assert.equal(env.store.current().reasoning, 'high');
});
test('cancelled tools and late callbacks cannot mutate the next turn or its history', () => {
const env = sessions();
const session = new env.AssistantSession(config());
session.sendUtterance('first', {}, callbacks());
const old = env.turns[0];
old.callbacks.onTextDelta('partial', 'partial');
session.cancel();
session.sendUtterance('second', {}, callbacks());
old.messages.push({ role: 'user', content: [{ type: 'tool_result', tool_use_id: 'old', content: 'late' }] });
old.callbacks.onTextDelta('late', 'late');
old.callbacks.onTurnDone({ stopReason: 'end_turn' });
assert.equal(session.isTurnActive(), true);
assert.equal(session.transcript[1].text, 'partial');
assert.equal(JSON.stringify(env.turns[1].messages).includes('tool_result'), false);
env.done('new answer');
assert.equal(session.isTurnActive(), false);
});
test('synchronous provider errors do not leave a permanently active turn', () => {
const env = sessions(); env.setError();
const session = new env.AssistantSession(config());
session.sendUtterance('hello', {}, callbacks());
assert.equal(session.isTurnActive(), false);
assert.equal(session.status, 'failed');
});
function draftEnv({ prepare = async () => true, start = async () => {}, stop = () => {}, initialStatus = 'Ready' } = {}) {
const transcripts = new Set(), statuses = new Set(), timers = new Map();
const sent = [];
let starts = 0, stops = 0, mic = false, timerId = 0;
const { VoiceDraft } = load('app/apps/ai-chat/voice-draft.ts', {
'../../native/voice-control': { voiceControlBridge: {
onTranscript(cb) { transcripts.add(cb); return () => transcripts.delete(cb); },
onStatus(cb) { statuses.add(cb); cb({ status: initialStatus }); return () => statuses.delete(cb); },
} },
'../../ui/shell/voice-activity': { voiceActivity: { setActive(value) { mic = value; } } },
}, {
setTimeout(cb) { timers.set(++timerId, cb); return timerId; },
clearTimeout(id) { timers.delete(id); },
});
const draft = new VoiceDraft({ startVoiceCapture: async () => { starts++; await start(); }, stopVoiceCapture: () => { stops++; return stop(); } }, prepare, () => {}, (text) => sent.push(text));
return { draft, sent, starts: () => starts, stops: () => stops, mic: () => mic,
transcript(text, isFinal = false) { for (const cb of [...transcripts]) cb({ text, isFinal }); },
status(status) { for (const cb of [...statuses]) cb({ status }); },
timeout() { for (const cb of [...timers.values()]) cb(); },
subscriptions: () => transcripts.size + statuses.size,
};
}
test('hold displays partials, release waits for final and sends exactly once', async () => {
const env = draftEnv();
await env.draft.start();
env.transcript('hello');
assert.equal(env.draft.text, 'hello');
assert.deepEqual(env.sent, []);
env.draft.release();
assert.equal(env.stops(), 1);
env.transcript('hello world', true);
env.timeout();
env.transcript('duplicate', true);
assert.deepEqual(env.sent, ['hello world']);
assert.equal(env.subscriptions(), 0);
assert.equal(env.mic(), false);
});
test('release before permission resolves never starts a microphone', async () => {
let ready;
const env = draftEnv({ prepare: () => new Promise((resolve) => { ready = resolve; }) });
const start = env.draft.start();
env.draft.release(); ready(true); await start;
assert.equal(env.starts(), 0);
assert.equal(env.draft.active, false);
assert.deepEqual(env.sent, []);
});
test('chat waits past its fallback deadline for native recognition', async () => {
let complete;
const stopped = new Promise(resolve => { complete = resolve; });
const env = draftEnv({ stop: () => stopped });
await env.draft.start();
env.transcript('first segment');
env.draft.release(); env.timeout();
assert.deepEqual(env.sent, []);
assert.equal(env.draft.phase, 'finishing');
env.transcript('first segment and the rest', true);
complete(); await stopped; env.timeout();
assert.deepEqual(env.sent, ['first segment and the rest']);
});
test('a cancelled chat capture cannot finish a newer capture when native stop resolves', async () => {
let complete;
const stopped = new Promise(resolve => { complete = resolve; });
const env = draftEnv({ stop: () => stopped });
await env.draft.start();
env.draft.release(); env.draft.cancel();
await env.draft.start();
env.transcript('new speech');
complete(); await stopped; env.timeout();
assert.deepEqual(env.sent, []);
assert.equal(env.draft.phase, 'listening');
env.draft.cancel();
});
test('release during async mic startup stops capture after it starts', async () => {
let started;
const env = draftEnv({ start: () => new Promise((resolve) => { started = resolve; }) });
const pending = env.draft.start();
await new Promise(setImmediate);
env.transcript('quick message');
env.draft.release(); started(); await pending;
assert.equal(env.stops(), 1);
env.timeout();
assert.deepEqual(env.sent, ['quick message']);
});
test('empty capture, rejection and closing never submit stale speech', async () => {
for (const cancel of ['empty', 'rejection', 'close']) {
const env = draftEnv({ initialStatus: 'old error' });
await env.draft.start();
assert.equal(env.starts(), 1);
if (cancel !== 'empty') env.transcript('should not send');
if (cancel === 'rejection') env.status('Ignored — not your enrolled voice');
if (cancel === 'close') env.draft.cancel();
env.draft.release(); env.timeout(); env.transcript('late', true);
assert.deepEqual(env.sent, []);
assert.equal(env.subscriptions(), 0);
}
});
function shellEnv() {
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 };
const timings = { spanCurrent: (_, fn) => fn(), span: (_, __, fn) => fn(), spanAsync: (_, __, fn) => fn(),
startFrame: () => 0, annotateFrame() {}, finishFrame() {}, runWithFrame: (_, fn) => fn() };
const layers = load('app/ui/layers.ts', {
'../graphics/image': images, '../graphics/plane': { dimPlanes: (planes) => planes },
'../native/frame-timings': timings, './gestures': gestures,
});
class Menu {
constructor(title, items) { this.title = title; this.items = items; this.selectedIndex = 0; }
selectItem(index) { this.selectedIndex = index; return this; }
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': {},
'../gestures': gestures, '../layers': layers, '../menu': { MenuLayer: Menu },
'./voice-input': {}, './keyboard-input': {}, './voice-activity': {}, './assistant': {},
'../../assistant/conversations': {}, '../../assistant/models': {}, '../../native/settings-store': {},
'../notifications': {}, '../dashboard-settings': settings, './ambient-cards': {},
'./chrome-layer': { ShellChromeLayer: class {} }, './modal-layer': {}, './tool-debug-layer': {},
'./brightness-picker-layer': {},
'../../assistant/tool-registry': {}, './geometry': { sidebarWidth: () => 64, minWindowTop: () => 96, TOP_BAR_HEIGHT: 28 },
});
const { createInProcessWindow } = load('app/ui/shell/in-process-window.ts', {
'../../graphics/image': images, '../../native/frame-timings': timings,
'../../util/render-freshness': { beginRenderPass() {}, endRenderPass: () => false },
'../layers': layers, '../window-menu': { WindowMenuLayer: Menu },
'./chrome-layer': { windowIcon: () => () => null }, './geometry': { appViewportSize: () => ({ width: 576, height: 260 }) },
'./shell': { shell },
});
const input = [], menus = [];
let microphone = false;
const app = createInProcessWindow({
appId: 'ai-chat', windowId: 'ai-chat', title: 'AI Chat', iconLetter: 'AI', closeable: true, holdToTalk: true,
baseLayer: { paint: () => new Image(), handleInput(event) {
input.push(event.type);
if (event.type === 'long-press') microphone = true;
if (event.type === 'long-press-release') microphone = false;
if (event.type === 'double-click') shell.yieldFocusToSidebar();
} },
menuItems: () => [{ label: 'New session', onSelect() {} }],
onAppMenuOpened() { menus.push('app'); microphone = false; },
onSystemMenuOpened() { menus.push('system'); microphone = false; },
isVoiceCapturing: () => microphone,
actions: layers.noopLayerActions, submitFrame: async () => {}, setSurfaceVisible() {},
});
shell.registerWindow(app.window);
shell.focusWindow('ai-chat');
return { shell, app, input, menus, microphone: () => microphone, event: (type) => gestures.makeInputEvent({ type }) };
}
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'));
assert.equal(env.microphone(), true);
assert.equal(env.shell.escapeMenuTimer, null);
await env.shell.receiveInput(env.event('long-press-release'));
assert.equal(env.microphone(), false);
assert.deepEqual(env.input, ['long-press', 'long-press-release']);
await env.shell.receiveInput(env.event('click'));
assert.deepEqual(env.menus, ['app']);
assert.equal(env.app.stack.isAtBase(), false);
await env.shell.receiveInput(env.event('short-then-long-press'));
assert.deepEqual(env.menus, ['app', 'system']);
assert.equal(env.app.stack.isAtBase(), true);
assert.equal(env.shell.stack.isAtBase(), false);
await env.shell.receiveInput(env.event('long-press-release'));
assert.deepEqual(env.input, ['long-press', 'long-press-release']);
env.shell.stack.clearToBase();
env.shell.focusWindow('ai-chat');
await env.shell.receiveInput(env.event('double-click'));
assert.equal(env.shell.isWindowFocused('ai-chat'), false);
});
test('ordinary apps retain long-press system menu and games retain the escape timer', async () => {
const env = shellEnv();
env.app.window.holdToTalk = false;
await env.shell.receiveInput(env.event('long-press'));
assert.deepEqual(env.menus, ['system']);
assert.deepEqual(env.input, []);
env.shell.stack.clearToBase();
env.app.window.claimsLongPress = () => true;
await env.shell.receiveInput(env.event('long-press'));
assert.notEqual(env.shell.escapeMenuTimer, null);
await env.shell.receiveInput(env.event('long-press-release'));
assert.equal(env.shell.escapeMenuTimer, null);
});
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 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', {
'../../graphics/image': graphics, '../../graphics/ui-fonts': { getDefaultSmallFont: () => font },
'../../graphics/textwrap': textwrap, '../../assistant/models': { assistantModelLabel: (s) => s },
'../../ui/dashboard-settings': { assistantBackendSetting: { get: () => 'direct' } },
'../../ui/gestures': load('app/ui/gestures.ts', {}), '../../ui/window-menu': {},
'../../ui/shell/in-process-window': { createInProcessWindow(options) {
windowOptions = options; return { requestRender() {} };
} },
'../../ui/shell/shell': { shell: { getAssistantConversations: () => env.store } },
'./voice-draft': { VoiceDraft: class { active = false; text = ''; status = ''; cancel() {} } },
});
createAiChatWindow({ actions: {}, setSurfaceVisible() {}, onClosed() {} });
const layer = windowOptions.baseLayer;
return { ...env, layer, paint: (width = 576, height = 260) => layer.paint({ stack: { getBaseSize: () => ({ width, height }) } }) };
}
test('scrollback stays anchored during streaming, follows at the bottom and resets on session switch', () => {
const env = chatLayerEnv();
const session = env.store.ensureSession();
for (let i = 0; i < 20; i++) session.transcript.push({ role: i % 2 ? 'assistant' : 'user', text: `Message ${i}: sample conversation text.` });
env.paint();
assert.ok(env.layer.maxFirstLine > 0);
env.layer.handleInput({ type: 'swipe-up' });
const first = env.layer.firstLine;
session.transcript.push({ role: 'assistant', text: 'New streamed text '.repeat(30) });
env.paint();
assert.equal(env.layer.firstLine, first);
for (let i = 0; i < 50; i++) env.layer.handleInput({ type: 'swipe-down' });
assert.equal(env.layer.firstLine, null);
env.layer.handleInput({ type: 'scroll-up' });
env.store.create(); env.paint();
assert.equal(env.layer.firstLine, null);
});
test('chat paints at both window heights with pending speech pinned beneath history', () => {
const env = chatLayerEnv();
env.store.ensureSession().transcript.push({ role: 'user', text: 'Plan my afternoon.' }, {
role: 'assistant', text: 'You have a meeting at two. There is time for a walk beforehand. '.repeat(8),
});
env.layer.draft.active = true;
env.layer.draft.status = 'Listening... release to send';
env.layer.draft.text = 'Actually, leave some time to pick up lunch on the way.';
for (const [width, height] of [[576, 260], [576, 452], [640, 452]]) {
const image = env.paint(width, height);
assert.equal(image.width, width); assert.equal(image.height, height);
assert.equal(image.to8bppBuffer().length, width * height);
if (process.env.FACECLAW_CHAT_RENDER_DIR) {
const pixels = image.to8bppBuffer();
const rgba = new Uint8Array(pixels.length * 4);
for (let i = 0; i < pixels.length; i++) rgba.set([pixels[i], pixels[i], pixels[i], 255], i * 4);
const png = require('upng-js').encode([rgba.buffer], width, height, 0);
fs.writeFileSync(path.join(process.env.FACECLAW_CHAT_RENDER_DIR, `chat-${width}x${height}.png`), Buffer.from(png));
}
}
});
+10 -11
View File
@@ -8,13 +8,13 @@ const { rle4 } = require('../.test-build/app/g2/ble-protocol.js');
test('mode-3 payload matches the production Android encoder byte for byte', () => {
// Generated with javac from g2protocol/BleImageOptimizer.java, 2026-09-08.
const vectors = [
[0, 0, 0xab, '03000001013412789c93924e000000e70096'],
[319, 479, 0x12, '039fef01013412789c4b1014020001570084'],
[3, 5, 0xa5, '03010201013412789c4b90120500016c0090'],
[0, 0, 0xab, '030000010134121a1b60'],
[319, 479, 0x12, '039fef01013412601112'],
[3, 5, 0xa5, '03010201013412601a15'],
];
for (const [x, y, value, expected] of vectors) {
const base = new Uint8Array(320 * 480), next = base.slice(); next[y * 320 + x] = value;
const payload = bbox(base, next, 640, 480, 0x1234, deflate);
const payload = bbox(base, next, 640, 480, 0x1234);
assert.equal(Buffer.from(payload).toString('hex'), expected);
assert.deepEqual(applyDisplayPayload(base, payload), next);
}
@@ -24,7 +24,7 @@ test('bounding boxes include both nibbles, preserve neighboring pixels and cover
const base = Uint8Array.from({ length: 320 * 480 }, (_, i) => i & 255);
for (const x of [0, 1, 2, 3, 4, 637, 638, 639]) for (const y of [0, 1, 2, 477, 478, 479]) {
const next = base.slice(); next[y * 320 + (x >> 1)] ^= x % 2 ? 15 : 240;
const payload = bbox(base, next, 640, 480, 1, deflate);
const payload = bbox(base, next, 640, 480, 1);
assert.deepEqual([...payload.slice(1, 5)], [Math.floor(x / 4), Math.floor(y / 2), 1, 1]);
assert.deepEqual(applyDisplayPayload(base, payload), next);
}
@@ -49,19 +49,18 @@ test('seeded sparse edits reconstruct exactly across successive bounding-box upd
for (let fid = 1; fid <= 60; fid++) {
const next = base.slice(), bx = random(280), by = random(440);
for (let n = 0; n < 20; n++) next[(by + random(40)) * 320 + bx + random(40)] ^= 0xff;
const payload = bbox(base, next, 640, 480, fid, deflate);
const payload = bbox(base, next, 640, 480, fid);
assert.ok(payload); assert.equal(payload[5] | (payload[6] << 8), fid);
assert.deepEqual(applyDisplayPayload(base, payload), next);
base = next;
}
});
test('a small edit compresses only its region and reduces bytes on a busy screen', () => {
test('a small edit encodes only its region on a busy screen', () => {
const base = Uint8Array.from({ length: 320 * 480 }, (_, i) => i & 255), next = base.slice();
next[100 * 320 + 100] ^= 255;
let compressedInputBytes = 0;
const payload = bbox(base, next, 640, 480, 1, bytes => { compressedInputBytes += bytes.length; return deflate(bytes); });
assert.ok(compressedInputBytes <= 8); // A 4x2 rectangle, at most one RLE byte per pixel.
assert.ok(payload.length < (1 + deflate(rle4(next)).length) / 10);
const payload = bbox(base, next, 640, 480, 1);
assert.ok(payload.length <= 15);
assert.ok(payload.length < (1 + rle4(next).length) / 10);
assert.deepEqual(applyDisplayPayload(base, payload), next);
});
+131
View File
@@ -0,0 +1,131 @@
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 = {}) {
const source = fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
const context = { exports: {}, require: (name) => modules[name] ?? {}, console };
vm.runInNewContext(ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, context, { filename: file });
return context.exports;
}
const textwrap = load('app/graphics/textwrap.ts');
const graphics = load('app/graphics/image.ts', { './textwrap': textwrap });
const plane = load('app/graphics/plane.ts', { './image': graphics });
const gestures = load('app/ui/gestures.ts');
const numeric = load('app/util/numeric-util.ts');
const { BdfFont } = load('app/graphics/bdffont.ts');
const font = BdfFont.parse(fs.readFileSync(path.join(__dirname, '../app/fonts/terminus/ter-u18n.bdf'), 'utf8'));
const fonts = { getDefaultSmallFont: () => font };
const layers = load('app/ui/layers.ts', {
'../graphics/image': graphics, '../graphics/plane': plane, './gestures': gestures,
'../native/frame-timings': { spanCurrent: (_name, paint) => paint() },
});
const menu = load('app/ui/menu.ts', {
'../graphics/image': graphics, '../graphics/ui-fonts': fonts, '../graphics/textwrap': textwrap,
'../util/numeric-util': numeric, './gestures': gestures, './metrics': load('app/ui/metrics.ts'),
});
function fixture(initial = '50', viewport = { x: 64, y: 124, width: 576, height: 260 }) {
let value = initial, writes = 0, closed = 0;
const settings = {
brightnessSetting: { get: () => value, set: (next) => { value = next; writes++; } },
brightnessSettingToLevel: (value) => value === 'auto' ? null : Number(value),
};
const geometry = {
appViewportRect: () => viewport, SHELL_OPAQUE_BLACK: 1,
sidebarWidth: () => viewport.x, minWindowTop: () => viewport.y - 28, TOP_BAR_HEIGHT: 28,
};
const picker = load('app/ui/shell/brightness-picker-layer.ts', {
'../../graphics/ui-fonts': fonts, '../../util/numeric-util': numeric,
'../dashboard-settings': settings, '../gestures': gestures, './geometry': geometry,
});
const base = { paint: () => new graphics.GrayImage(640, 480), handleInput() {} };
const stack = new layers.LayerStack(base, layers.noopLayerActions);
const open = () => stack.push(new picker.BrightnessPickerLayer(() => closed++));
open();
return { stack, open, settings, geometry, picker, value: () => value, writes: () => writes,
closed: () => closed, input: (type) => stack.handleInput(gestures.makeInputEvent({ type, source: 'watch' })) };
}
test('swipes change the saved level by 10, clamp at both ends, and both tap gestures confirm', async () => {
const f = fixture();
await f.input('swipe-up'); assert.equal(f.value(), '60');
await f.input('swipe-down'); assert.equal(f.value(), '50');
for (let i = 0; i < 8; i++) await f.input('scroll-up');
assert.equal(f.value(), '100'); assert.equal(f.writes(), 7);
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);
await f.input('double-click'); assert.ok(f.stack.isAtBase()); assert.equal(f.closed(), 2);
assert.equal(f.value(), '0');
});
test('enabling Auto while the picker is open prevents manual changes', async () => {
const f = fixture();
f.settings.brightnessSetting.set('auto');
await f.input('scroll-up'); await f.input('scroll-down');
assert.equal(f.value(), 'auto'); assert.equal(f.writes(), 1);
});
test('the thin bar fills upward in proportion to brightness in each viewport', () => {
for (const viewport of [
{ x: 64, y: 28, width: 576, height: 260 },
{ x: 64, y: 220, width: 576, height: 260 },
{ x: 0, y: 28, width: 640, height: 452 },
]) {
for (const level of [0, 10, 50, 100]) {
const f = fixture(String(level), viewport);
const image = f.stack.paint().at(-1).image;
const fill = [];
for (let y = 0; y < image.height; y++) {
for (let x = 0; x < image.width; x++) {
if (image.getPixel(x, y) === 255) fill.push({ x, y });
}
}
assert.equal(fill.length, 12 * level);
if (level) {
assert.equal(new Set(fill.map((p) => p.x)).size, 12);
assert.equal(new Set(fill.map((p) => p.y)).size, level);
assert.ok(fill.every((p) => p.x >= viewport.x && p.x < viewport.x + viewport.width
&& p.y >= viewport.y && p.y < viewport.y + viewport.height));
const bottom = fill.at(-1);
assert.equal(image.getPixel(bottom.x, bottom.y + 1), 1);
assert.equal(image.getPixel(bottom.x, bottom.y + 2), 150);
}
}
}
});
test('system menu hides brightness in Auto and opens its picker between Voice input and Debug', async () => {
const f = fixture('auto');
const { shell } = load('app/ui/shell/shell.ts', {
'../../graphics/image': graphics, '../layers': layers, '../menu': menu, '../gestures': gestures,
'../dashboard-settings': f.settings, './geometry': f.geometry, './brightness-picker-layer': f.picker,
'./chrome-layer': { ShellChromeLayer: class {} },
});
shell.registerWindow({ windowId: 'test', appId: 'test', closeable: true, handleInput() {} });
shell.openSystemMenu('test');
let opened = shell.stack.layers.at(-1);
assert.deepEqual(Array.from(opened.items, (item) => item.label),
['Close window', 'Focus app switcher', 'Voice input', 'Debug']);
shell.stack.clearToBase();
f.settings.brightnessSetting.set('40');
shell.openSystemMenu('test');
opened = shell.stack.layers.at(-1);
assert.deepEqual(Array.from(opened.items, (item) => item.label),
['Close window', 'Focus app switcher', 'Voice input', 'Brightness', 'Debug']);
await shell.stack.handleInput(gestures.makeInputEvent({ type: 'scroll-down' }));
await shell.stack.handleInput(gestures.makeInputEvent({ type: 'scroll-down' }));
await shell.stack.handleInput(gestures.makeInputEvent({ type: 'click', source: 'ring' }));
assert.ok(shell.stack.topMatches((layer) => layer instanceof f.picker.BrightnessPickerLayer));
await shell.stack.handleInput(gestures.makeInputEvent({ type: 'double-click', source: 'ring' }));
assert.ok(shell.stack.isAtBase());
assert.equal(shell.focus, 'sidebar');
});
+59
View File
@@ -0,0 +1,59 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const { CfwTransport, parseCfwAcks } = require('../.test-build/app/g2/cfw-transport.js');
const { crc16, concat, MessageReceiver } = require('../.test-build/app/g2/ble-protocol.js');
const hex = value => Buffer.from(value).toString('hex');
test('iOS transport matches Android packets including persistent compression, reset, raw fallback and ATT limits', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'faceclaw-cfw-java-'));
const java = name => process.env.JAVA_HOME ? path.join(process.env.JAVA_HOME, 'bin', name) : name;
const random = new Uint8Array(65535); let seed = 42;
for (let i = 0; i < random.length; i++) { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; random[i] = seed & 255; }
const cases = [[100, 3, 185, new Uint8Array([6, 0, 0, 255, 255])],
[101, 3, 185, new Uint8Array([6, 0, 0, 255, 255])], [102, 1, 20, new Uint8Array(500).fill(42)],
'reset', [255, 3, 514, random], [103, 3, 240, new Uint8Array([11])]];
try {
execFileSync(java('javac'), ['-d', dir,
path.join(__dirname, '../App_Resources/Android/src/main/java/com/faceclaw/app/g2protocol/CfwTransport.java'),
path.join(__dirname, 'fixtures/CfwTransportVectors.java')]);
const expected = execFileSync(java('java'), ['-cp', dir, 'com.faceclaw.app.CfwTransportVectors',
...cases.map(c => c === 'reset' ? c : `${c[0]}:${c[1]}:${c[2]}:${hex(c[3])}`)],
{ maxBuffer: 1024 * 1024 }).toString().trim().split('\n');
const transport = new CfwTransport(); let index = 0;
for (const c of cases) {
if (c === 'reset') { transport.reset(); continue; }
const [id, lenses, maxWrite, payload] = c, packets = transport.encode(payload, id, lenses, maxWrite);
assert.ok(packets.every(p => p.length <= maxWrite));
assert.equal(packets.map(hex).join(' '), expected[index++]);
}
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
});
function ackPacket(records, lens = 1, nack = false) {
const words = (id, ordinal, size, crc) => new Uint8Array([id, ordinal & 255, ordinal >>> 8, size & 255, size >>> 8, crc & 255, crc >>> 8]);
const first = words(...records[0]);
const body = concat(new Uint8Array([nack ? 3 : 1]), first.subarray(0, 3), new Uint8Array([lens]),
first.subarray(3), ...records.slice(1).map(r => words(...r)));
const crc = crc16(body);
return concat(new Uint8Array([0xaa, 0x12, 50, body.length + 2, 1, 1, 0xf0, 0]), body, new Uint8Array([crc & 255, crc >>> 8]));
}
test('redundant ACKs are validated atomically and survive split/coalesced notifications', () => {
const packet = ackPacket([[104, 0, 50, 123], [103, 0, 40, 321], [102, 0, 30, 222], [101, 0, 20, 111]], 2);
assert.deepEqual(parseCfwAcks(packet).map(a => [a.streamId, a.lens, a.size]), [[104, 2, 50], [103, 2, 40], [102, 2, 30], [101, 2, 20]]);
const receiver = new MessageReceiver();
assert.deepEqual(receiver.receive('L', packet.subarray(0, 6)), []);
const messages = receiver.receive('L', concat(packet.subarray(6), packet));
assert.equal(messages.length, 2); assert.deepEqual(parseCfwAcks(messages[0].packet), parseCfwAcks(packet));
for (let offset = 0; offset < packet.length; offset++) {
const corrupt = packet.slice(); corrupt[offset] ^= 1;
// Transport sequence byte is not covered by the ACK's CRC or identity.
if (offset !== 2) assert.equal(parseCfwAcks(corrupt), null, `offset ${offset}`);
}
assert.equal(parseCfwAcks(ackPacket([[104, 0, 50, 123]], 3)), null);
assert.equal(parseCfwAcks(ackPacket([[104, 0, 50, 123], [103, 0, 40, 321]], 1, true)), null);
assert.equal(parseCfwAcks(ackPacket([[104, 0, 0, 0]], 1, true))[0].nack, true);
});
+6 -1
View File
@@ -42,9 +42,14 @@ function compass(width = 576, height = 260) {
RecordingImage.prototype.clone = function () {
const image = baseClone.call(this); Object.setPrototypeOf(image, RecordingImage.prototype); image.texts = []; return image;
};
const calibration = { isCompassCalibrated: () => true, normalizeHeading: (v) => v };
const rose = load('app/apps/compass/compass-rose.ts', {
'../../graphics/image': { GrayImage: RecordingImage }, './calibration': calibration,
});
const app = load('app/apps/compass/compass-app.ts', {
'../../graphics/ui-fonts': { getDefaultSmallFont: () => small, getDefaultLargeFont: () => large },
'../../graphics/image': { GrayImage: RecordingImage }, '../../graphics/textwrap': textwrap,
'./compass-rose': rose,
'../../native/compass': { COMPASS_CHANGED: 15, COMPASS_CALIBRATION_STARTED: 16, COMPASS_CALIBRATION_COMPLETE: 17,
addCompassListener: (fn) => { listener = fn; return () => {}; }, setCompassEnabled() {} },
'../../ui/metrics': { lineStep: (font) => font.lineHeight + 2 },
@@ -55,7 +60,7 @@ function compass(width = 576, height = 260) {
},
'../../ui/shell/shell': { shell: { isWindowVisible: () => true } },
'../../g2/android-permissions': { hasLocationPermission: () => false },
'./calibration': { isCompassCalibrated: () => true, normalizeHeading: (v) => v },
'./calibration': calibration,
'./calibration-layer': {}, './declination': { onDeclinationChanged: () => () => {} },
'./heading': { getNorthReference: () => 'magnetic', resolveHeading: (v) => ({ displayDegrees: v }) },
'./debug': debug,
+4
View File
@@ -61,6 +61,10 @@ function compass({ style, width = 576, height = 260 } = {}) {
'../../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 }) },
};
+21 -7
View File
@@ -26,6 +26,14 @@ const font = (size) => BdfFont.parse(fs.readFileSync(
const small = font(12);
const large = font(24);
let viewportWidth = 576;
const calibration = { isCompassCalibrated: () => true, normalizeHeading: (n) => ((n % 360) + 360) % 360 };
// The rose renderer's private helpers are re-exported for referenceFrame.
const rose = load('app/apps/compass/compass-rose.ts', {
'../../graphics/image': graphics,
'./calibration': calibration,
}, `
export { rotatingRoseBounds, drawPlaneGrid, drawDiscWall, drawTiltedRing, drawHeadingTick };
`);
const compass = load('app/apps/compass/compass-app.ts', {
'../../graphics/ui-fonts': { getDefaultSmallFont: () => small, getDefaultLargeFont: () => large },
'../../graphics/image': graphics,
@@ -36,20 +44,26 @@ const compass = load('app/apps/compass/compass-app.ts', {
'../../ui/shell/in-process-window': {},
'../../ui/shell/shell': {},
'../../g2/android-permissions': {},
'./calibration': { isCompassCalibrated: () => true, normalizeHeading: (n) => ((n % 360) + 360) % 360 },
'./calibration': calibration,
'./calibration-layer': {},
'./compass-rose': rose,
'./debug': { compassDebugLines: () => [], isCompassDebugEnabled: () => false, setCompassDebugEnabled: () => {} },
'./declination': {},
'./heading': { getNorthReference: () => 'magnetic', resolveHeading: (n) => ({ displayDegrees: n }) },
}, `
export { CompassLayer, rotatingRoseBounds, createCompassBackground, drawCompassRose };
export { CompassLayer };
const rose_1 = require('./compass-rose');
export const rotatingRoseBounds = rose_1.rotatingRoseBounds;
export const createCompassBackground = rose_1.createCompassBackground;
export const drawCompassRose = rose_1.drawCompassRose;
export function referenceFrame(width, height, cx, cy, radius, clipY, heading) {
const image = new GrayImage(width, height, 0);
const fade = heading === null ? 0.45 : 1;
drawPlaneGrid(image, cx, cy, radius, clipY);
drawDiscWall(image, cx, cy, radius, fade);
drawTiltedRing(image, cx, cy, radius, 105 * fade);
drawCompassRose(image, cx, cy, radius, heading);
drawHeadingTick(image, cx, cy, radius, 255 * fade);
rose_1.drawPlaneGrid(image, cx, cy, radius, clipY);
rose_1.drawDiscWall(image, cx, cy, radius, fade);
rose_1.drawTiltedRing(image, cx, cy, radius, 105 * fade);
rose_1.drawCompassRose(image, cx, cy, radius, heading);
rose_1.drawHeadingTick(image, cx, cy, radius, 255 * fade);
return image;
}
`);
+19
View File
@@ -0,0 +1,19 @@
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 });
}
});
+75
View File
@@ -0,0 +1,75 @@
// Pins the firmware-extension parsing and the compatibility / onboarding
// classification that the firmware check page and the main screen share.
const test = require("node:test");
const assert = require("node:assert/strict");
const compat = require("../.test-build/app/g2/firmware-compat.js");
const REQUIRED = compat.REQUIRED_FACECLAW_FIRMWARE_VERSION;
const info = (extension, left = "2.2.9.22", right = "2.2.9.22") => ({ leftVersion: left, rightVersion: right, extension });
test("parseFirmwareExtension recognizes each slot format", () => {
assert.deepEqual(compat.parseFirmwareExtension(""), { kind: "none" });
assert.deepEqual(compat.parseFirmwareExtension(" "), { kind: "none" });
assert.deepEqual(compat.parseFirmwareExtension("Faceclaw/1"), { kind: "faceclaw", version: 1 });
assert.deepEqual(compat.parseFirmwareExtension(" Faceclaw/12 "), { kind: "faceclaw", version: 12 });
assert.deepEqual(compat.parseFirmwareExtension("EVENCFW/22 img640 imgz rle"), {
kind: "legacy-faceclaw",
text: "EVENCFW/22 img640 imgz rle",
});
assert.deepEqual(compat.parseFirmwareExtension("EVENCFW"), { kind: "legacy-faceclaw", text: "EVENCFW" });
assert.deepEqual(compat.parseFirmwareExtension("OtherCFW/3"), { kind: "other", text: "OtherCFW/3" });
// A Faceclaw prefix without a usable number is not ours.
assert.deepEqual(compat.parseFirmwareExtension("Faceclaw/x"), { kind: "other", text: "Faceclaw/x" });
});
test("the required revision and newer revisions are compatible", () => {
assert.equal(compat.hasCompatibleFirmware(info(`Faceclaw/${REQUIRED}`)), true);
assert.equal(compat.firmwareIncompatibilityMessage(info(`Faceclaw/${REQUIRED}`)), null);
assert.equal(compat.hasCompatibleFirmware(info(`Faceclaw/${REQUIRED + 5}`)), true);
assert.equal(compat.firmwareIncompatibilityMessage(info(`Faceclaw/${REQUIRED + 5}`)), null);
assert.equal(compat.classifyOnboardingFirmware(info(`Faceclaw/${REQUIRED + 5}`)).kind, "custom");
});
test("older Faceclaw revisions and legacy EVENCFW builds need a reflash", () => {
const older = info(`Faceclaw/${REQUIRED - 1}`);
assert.equal(compat.hasCompatibleFirmware(older), false);
assert.match(compat.firmwareIncompatibilityMessage(older), new RegExp(`revision ${REQUIRED - 1}`));
assert.match(compat.firmwareIncompatibilityMessage(older), new RegExp(`requires revision ${REQUIRED}`));
assert.equal(compat.classifyOnboardingFirmware(older).kind, "older-faceclaw");
const legacy = info("EVENCFW/22 img640 fbguard wearnotify");
assert.equal(compat.hasCompatibleFirmware(legacy), false);
assert.match(compat.firmwareIncompatibilityMessage(legacy), /older version of Faceclaw's custom firmware/);
const classified = compat.classifyOnboardingFirmware(legacy);
assert.equal(classified.kind, "older-faceclaw");
assert.equal(classified.version, "2.2.9.22");
assert.equal(classified.extension.kind, "legacy-faceclaw");
});
test("custom firmware from another source is flashable with its own messaging", () => {
const other = info("OtherCFW/3", "2.2.9.22", "2.2.9.22");
assert.equal(compat.hasCompatibleFirmware(other), false);
assert.match(compat.firmwareIncompatibilityMessage(other), /different source/);
assert.match(compat.firmwareIncompatibilityMessage(other), /OtherCFW\/3/);
assert.equal(compat.classifyOnboardingFirmware(other).kind, "other-custom");
assert.match(compat.describeFirmwareExtension({ kind: "other", text: "OtherCFW/3" }), /different source/);
});
test("stock firmware classifies by base version and warns on the main screen", () => {
assert.equal(compat.firmwareIncompatibilityMessage(info("", "", "")), null, "nothing reported is not a verdict");
assert.match(compat.firmwareIncompatibilityMessage(info("")), /stock firmware/);
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");
// 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");
});
test("reportedFirmwareVersion picks the higher arm", () => {
assert.equal(compat.reportedFirmwareVersion(info("", "2.2.9.22", "2.2.10.10")), "2.2.10.10");
assert.equal(compat.reportedFirmwareVersion(info("", "", "2.2.9.22")), "2.2.9.22");
assert.equal(compat.reportedFirmwareVersion(info("", "", "")), "");
});
+19
View File
@@ -0,0 +1,19 @@
package com.faceclaw.app;
/** Production Android encoder oracle for the iOS transport parity test. */
public final class CfwTransportVectors {
public static void main(String[] args) {
CfwTransport transport = new CfwTransport();
for (String line : args) {
String[] fields = line.split(":", -1);
if (fields[0].equals("reset")) { transport.reset(); continue; }
int id = Integer.parseInt(fields[0]), lenses = Integer.parseInt(fields[1]);
int maxWrite = Integer.parseInt(fields[2]);
byte[] payload = java.util.HexFormat.of().parseHex(fields[3]);
StringBuilder result = new StringBuilder();
for (byte[] packet : transport.encode(payload, id, lenses, maxWrite + 3))
result.append(java.util.HexFormat.of().formatHex(packet)).append(" ");
System.out.println(result.toString().trim());
}
}
}
+67
View File
@@ -0,0 +1,67 @@
package com.faceclaw.app;
import java.util.Arrays;
public class FaceclawGestureEventTest {
private static byte[] hex(String value) {
byte[] result = new byte[value.length() / 2];
for (int i = 0; i < result.length; ++i)
result[i] = (byte)Integer.parseInt(value.substring(i * 2, i * 2 + 2), 16);
return result;
}
private static byte[] pb(byte[] payload) {
byte[] frame = BleProtocol.framePb(payload, 9, BleProtocol.FLAG_NOTIFY, 15).get(0);
return BleProtocol.parseFrame(frame).pb;
}
/** G2SettingPackage{commandId=3, magic=0, field102=['F','C',1,event,source,0]}: the CFW's wire shape. */
private static byte[] packet(int event, int source) {
byte[] p = hex("08031000b20606464301000000");
p[10] = (byte)event; p[11] = (byte)source;
return p;
}
public static void main(String[] args) {
// Event codes map to the sys-events a live page would produce.
int[][] events = {
{2, BleProtocol.EVENT_CLICK},
{3, BleProtocol.EVENT_RING_LONG_PRESS},
{4, BleProtocol.EVENT_RING_LONG_PRESS_RELEASE},
};
int[][] sources = {
{0, BleProtocol.EVENT_SOURCE_GLASSES_L},
{1, BleProtocol.EVENT_SOURCE_GLASSES_R},
{4, BleProtocol.EVENT_SOURCE_RING},
{7, 0},
};
for (int[] e : events) for (int[] s : sources) {
BleProtocol.FaceclawGestureEvent g = BleProtocol.parseFaceclawGestureEvent(pb(packet(e[0], s[0])));
assert g != null && g.eventType == e[1] && g.eventSource == s[1] : e[0] + "/" + s[0];
}
// The double-tap wake event (1) and unknown codes are not gestures, and the
// wake parser does not mistake a gesture for a wake.
byte[] wake = packet(1, 0x34); wake[12] = 0x12;
assert BleProtocol.parseFaceclawGestureEvent(pb(wake)) == null;
assert BleProtocol.parseFaceclawWakeEvent(pb(wake)) == 0x1234;
assert BleProtocol.parseFaceclawWakeEventCode(pb(wake)) == 1;
// The head-up wake (5) shares the nonce handshake but keeps its own code.
byte[] headUp = packet(5, 0x34); headUp[12] = 0x12;
assert BleProtocol.parseFaceclawGestureEvent(pb(headUp)) == null;
assert BleProtocol.parseFaceclawWakeEvent(pb(headUp)) == 0x1234;
assert BleProtocol.parseFaceclawWakeEventCode(pb(headUp)) == BleProtocol.FACECLAW_WAKE_EVENT_HEAD_UP;
for (int code : new int[] {2, 3, 4, 6}) {
assert BleProtocol.parseFaceclawWakeEvent(pb(packet(code, 1))) == -1;
assert BleProtocol.parseFaceclawWakeEventCode(pb(packet(code, 1))) == -1;
}
for (int code : new int[] {0, 5, 6, 255})
assert BleProtocol.parseFaceclawGestureEvent(pb(packet(code, 1))) == null;
// Wrong protocol version, wrong magic letters, truncated payloads, plain settings.
byte[] bad = packet(2, 1); bad[9] = 2;
assert BleProtocol.parseFaceclawGestureEvent(pb(bad)) == null;
bad = packet(2, 1); bad[7] = 'X';
assert BleProtocol.parseFaceclawGestureEvent(pb(bad)) == null;
byte[] full = packet(2, 1);
for (int n = 0; n < full.length; ++n)
assert BleProtocol.parseFaceclawGestureEvent(pb(Arrays.copyOf(full, n))) == null : n;
assert BleProtocol.parseFaceclawGestureEvent(pb(hex("08031000"))) == null;
assert BleProtocol.parseFaceclawGestureEvent(null) == null;
System.out.println("FaceclawGestureEventTest ok");
}
}
+50
View File
@@ -0,0 +1,50 @@
package com.faceclaw.app;
import java.util.Arrays;
public class RingBatteryProtocolTest {
private static byte[] hex(String value) {
byte[] result = new byte[value.length() / 2];
for (int i = 0; i < result.length; ++i)
result[i] = (byte)Integer.parseInt(value.substring(i * 2, i * 2 + 2), 16);
return result;
}
private static BleProtocol.RingBatterySnapshot parse(byte[] payload) {
byte[] frame = BleProtocol.framePb(payload, 9, BleProtocol.FLAG_NOTIFY, 15).get(0);
return BleProtocol.parseRingBattery(BleProtocol.parseFrame(frame).pb);
}
public static void main(String[] args) {
// Same golden payload as g2flash/tests/ring_battery_test.c.
byte[] packet = hex("08031000d206055242010752");
BleProtocol.RingBatterySnapshot result = parse(packet);
assert result.battery == 82 && result.charging == 1;
packet[10] = 3;
for (int level = 0; level <= 100; ++level) {
packet[11] = (byte)level;
result = parse(packet);
assert result.battery == level && result.charging == 0;
}
for (int flags : new int[] {0, 1}) {
packet[10] = (byte)flags; packet[11] = (byte)255;
result = parse(packet);
assert result.battery == -1 && result.charging == -1;
}
packet = hex("08031000d206055242010752");
for (int n = 0; n < packet.length; ++n)
assert parse(Arrays.copyOf(packet, n)) == null;
for (int offset : new int[] {7, 8, 9, 10, 11}) {
byte previous = packet[offset]; packet[offset] = (byte)255;
assert parse(packet) == null;
packet[offset] = previous;
}
assert parse(hex("08031000")) == null; // older firmware
assert parse(hex("d206055242010252")) == null; // valid without connected
assert parse(hex("d206055242010352")).battery == 82;
assert parse(hex("d2060552420100ff")).battery == -1;
// Invalid unknown value and charging-without-valid must be rejected.
assert parse(hex("d206055242010052")) == null;
assert parse(hex("d2060552420105ff")) == null;
assert parse(hex("d206055242010364")).battery == 100;
assert parse(hex("d206055242010365")) == null;
assert BleProtocol.parseRingBattery(null) == null;
}
}
+58
View File
@@ -0,0 +1,58 @@
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;
}
}
+60
View File
@@ -0,0 +1,60 @@
// Execute the production worker, replacing only NativeScript/platform services.
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const ts = require('typescript');
const root = path.resolve(__dirname, '../..');
function load(file, modules = {}, extra = '', globals = {}) {
const context = { exports: {}, console, ...globals, require: (name) => {
if (!(name in modules)) throw new Error(`Unexpected dependency: ${name}`);
return modules[name];
} };
const source = fs.readFileSync(path.join(root, file), 'utf8');
vm.runInNewContext(ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText + extra, context, { filename: file });
return context.exports;
}
const { BdfFont } = load('app/graphics/bdffont.ts', { '@nativescript/core': {} });
const font = (size) => BdfFont.parse(fs.readFileSync(path.join(root, `app/fonts/terminus/ter-u${size}n.bdf`), 'utf8'));
const fonts = { terminus24: font(24), terminus32: font(32) };
const smallFont = font(18);
const graphics = load('app/graphics/image.ts', { './textwrap': load('app/graphics/textwrap.ts') });
module.exports = function worker() {
let now = 10000;
let highScore = '0';
const noop = () => {};
const global = { postMessage: noop };
const api = load('app/apps/pinball/pinball-app.worker.ts', {
'@nativescript/core/globals': {},
'../../graphics/image': graphics,
'../../graphics/plane': {}, '../../graphics/glyph-wire': {},
'../../graphics/bdffont': { getFont: (name) => fonts[name] },
'../../graphics/ui-fonts': { getDefaultSmallFont: () => smallFont },
'../../native/frame-timings': { finishFrame: noop, logFrame: noop },
'../../native/active-display': {},
'../../native/settings-store': { getStringSetting: () => highScore, setStringSetting: (_, value) => { highScore = value; } },
'../../ui/sound-effects': {},
'../../ui/sound-setting': { loadSoundEnabled: () => true, saveSoundEnabled: () => {} },
'../../ui/window-menu': { WindowMenu: class { open() {} } },
'../../ui/gestures': { directionalFallback: (event) => event, GESTURE_CLICK: '●', GESTURE_DOUBLE_CLICK: '●●', GESTURE_SCROLL: '↕', GESTURE_LONG_PRESS: '—' },
'../../util/numeric-util': { clamp: (v, lo, hi) => Math.max(lo, Math.min(hi, v)) },
}, `
renderAndSubmit = () => {};
playSfx = () => {};
exports.api = { windows, launchBall, ballDrained, stepPhysics, tick, flip,
checkTargets, checkRollovers, collideBumpers, resetGame, paintContent, TARGETS, ROLLOVERS };
`, { global, Date: { now: () => now }, setInterval: () => 1, clearInterval: noop }).api;
const message = (data) => global.onmessage({ data });
message({ type: 'open-window', windowId: 'test', surfaceId: 'test', title: 'Pinball', viewport: { width: 576, height: 260 } });
message({ type: 'foreground', windowId: 'test', foreground: true, focused: true });
const w = api.windows.get('test');
return { ...api, w, message, highScore: () => Number(highScore),
input: (type) => message({ type: 'input', windowId: 'test', focused: true, frameId: 1, event: { type } }),
advance: (seconds) => { for (let i = 0; i < Math.round(seconds * 120); i++) { now += 1000 / 120; api.stepPhysics(w); } },
elapse: (seconds) => { now += seconds * 1000; },
};
};
+67
View File
@@ -0,0 +1,67 @@
const test = require("node:test");
const assert = require("node:assert/strict");
const {
GLANCE_HIDDEN,
GLANCE_TIMEOUT_MS,
glanceEventForGesture,
reduceGlance,
} = require("../.test-build/app/g2/glance-state.js");
const T0 = 1_000_000;
test("a press shows the board and arms the auto-hide timer", () => {
const shown = reduceGlance(GLANCE_HIDDEN, { type: "press" }, T0);
assert.deepEqual(shown, { visible: true, holding: false, hideAtMs: T0 + GLANCE_TIMEOUT_MS });
// A timer firing early is ignored; on time it hides.
assert.equal(reduceGlance(shown, { type: "timeout" }, T0 + GLANCE_TIMEOUT_MS - 1), shown);
assert.deepEqual(reduceGlance(shown, { type: "timeout" }, T0 + GLANCE_TIMEOUT_MS), GLANCE_HIDDEN);
});
test("a further press renews the timer from the new press", () => {
const shown = reduceGlance(GLANCE_HIDDEN, { type: "press" }, T0);
const renewed = reduceGlance(shown, { type: "press" }, T0 + 2000);
assert.equal(renewed.hideAtMs, T0 + 2000 + GLANCE_TIMEOUT_MS);
assert.equal(reduceGlance(renewed, { type: "timeout" }, T0 + GLANCE_TIMEOUT_MS), renewed);
});
test("a hold shows the board without a timer and the release hides it", () => {
const held = reduceGlance(GLANCE_HIDDEN, { type: "hold" }, T0);
assert.deepEqual(held, { visible: true, holding: true, hideAtMs: null });
assert.equal(reduceGlance(held, { type: "timeout" }, T0 + 60_000), held);
// A tap mid-hold neither hides nor starts a timer.
assert.equal(reduceGlance(held, { type: "press" }, T0 + 500), held);
assert.deepEqual(reduceGlance(held, { type: "release" }, T0 + 1000), GLANCE_HIDDEN);
});
test("a release that was not holding the board is ignored", () => {
assert.equal(reduceGlance(GLANCE_HIDDEN, { type: "release" }, T0), GLANCE_HIDDEN);
const shown = reduceGlance(GLANCE_HIDDEN, { type: "press" }, T0);
assert.equal(reduceGlance(shown, { type: "release" }, T0 + 100), shown);
});
test("dismiss hides from any state", () => {
const held = reduceGlance(GLANCE_HIDDEN, { type: "hold" }, T0);
assert.deepEqual(reduceGlance(held, { type: "dismiss" }, T0), GLANCE_HIDDEN);
const shown = reduceGlance(GLANCE_HIDDEN, { type: "press" }, T0);
assert.deepEqual(reduceGlance(shown, { type: "dismiss" }, T0), GLANCE_HIDDEN);
});
test("gesture mapping: taps and head-tilt press, both long-press gestures hold, double-tap dismisses only a visible board", () => {
assert.deepEqual(glanceEventForGesture("click", false), { type: "press" });
assert.deepEqual(glanceEventForGesture("head-tilt", false), { type: "press" });
assert.deepEqual(glanceEventForGesture("long-press", false), { type: "hold" });
assert.deepEqual(glanceEventForGesture("short-then-long-press", false), { type: "hold" });
assert.deepEqual(glanceEventForGesture("short-then-long-press", true), { type: "hold" });
assert.deepEqual(glanceEventForGesture("long-press-release", true), { type: "release" });
assert.equal(glanceEventForGesture("double-click", false), null);
assert.deepEqual(glanceEventForGesture("double-click", true), { type: "dismiss" });
assert.equal(glanceEventForGesture("scroll-up", true), null);
});
test("the press timeout is the host's when supplied", () => {
const shown = reduceGlance(GLANCE_HIDDEN, { type: "press" }, T0, 10_000);
assert.equal(shown.hideAtMs, T0 + 10_000);
assert.equal(reduceGlance(shown, { type: "timeout" }, T0 + GLANCE_TIMEOUT_MS), shown);
assert.deepEqual(reduceGlance(shown, { type: "timeout" }, T0 + 10_000), GLANCE_HIDDEN);
});
+81
View File
@@ -0,0 +1,81 @@
const test = require("node:test");
const assert = require("node:assert/strict");
const { QUADRANT_LAYOUT, resolveGlanceRegions, slotsVerticallyAdjacent } = require("../.test-build/app/apps/glanceboard/layout.js");
const spans = (choice) => choice === "terminal" || choice === "calendar";
test("quadrant adjacency: left pair and right pair stack, nothing else", () => {
assert.equal(slotsVerticallyAdjacent(QUADRANT_LAYOUT, 0, 2), true);
assert.equal(slotsVerticallyAdjacent(QUADRANT_LAYOUT, 3, 1), true);
assert.equal(slotsVerticallyAdjacent(QUADRANT_LAYOUT, 0, 1), false);
assert.equal(slotsVerticallyAdjacent(QUADRANT_LAYOUT, 0, 3), false);
assert.equal(slotsVerticallyAdjacent(QUADRANT_LAYOUT, 1, 1), false);
});
test("a spanning widget in both left slots becomes one double-height region", () => {
const regions = resolveGlanceRegions(QUADRANT_LAYOUT, ["terminal", "music", "terminal", "none"], spans);
assert.deepEqual(regions, [
{ choice: "terminal", rect: { x: 0, y: 0, width: 288, height: 288 }, slots: [0, 2] },
{ choice: "music", rect: { x: 288, y: 0, width: 288, height: 144 }, slots: [1] },
]);
});
test("a spanning widget in both right slots merges too, in slot order", () => {
const regions = resolveGlanceRegions(QUADRANT_LAYOUT, ["none", "calendar", "compass", "calendar"], spans);
assert.deepEqual(regions.map((region) => [region.choice, region.slots, region.rect.height]), [
["calendar", [1, 3], 288],
["compass", [2], 144],
]);
});
test("a non-spanning duplicate and a diagonal duplicate stay separate regions", () => {
const music = resolveGlanceRegions(QUADRANT_LAYOUT, ["music", "none", "music", "none"], spans);
assert.deepEqual(music.map((region) => region.slots), [[0], [2]]);
const diagonal = resolveGlanceRegions(QUADRANT_LAYOUT, ["terminal", "none", "none", "terminal"], spans);
assert.deepEqual(diagonal.map((region) => region.slots), [[0], [3]]);
});
test("empty slots produce no region", () => {
assert.deepEqual(resolveGlanceRegions(QUADRANT_LAYOUT, ["none", "none", "none", "none"], spans), []);
});
test("dividers: left edges of the right column, top edges of the bottom row, minus merged interiors", () => {
const { slotDividers } = require("../.test-build/app/apps/glanceboard/layout.js");
const single = resolveGlanceRegions(QUADRANT_LAYOUT, ["music", "compass", "none", "none"], spans);
assert.deepEqual(slotDividers(QUADRANT_LAYOUT, single), [
{ x0: 288, y0: 0, x1: 288, y1: 143 },
{ x0: 0, y0: 144, x1: 287, y1: 144 },
{ x0: 288, y0: 144, x1: 288, y1: 287 },
{ x0: 288, y0: 144, x1: 575, y1: 144 },
]);
// A tall Terminal on the left drops the line across the left column only.
const tall = resolveGlanceRegions(QUADRANT_LAYOUT, ["terminal", "music", "terminal", "none"], spans);
assert.deepEqual(slotDividers(QUADRANT_LAYOUT, tall), [
{ x0: 288, y0: 0, x1: 288, y1: 143 },
{ x0: 288, y0: 144, x1: 288, y1: 287 },
{ x0: 288, y0: 144, x1: 575, y1: 144 },
]);
});
test("2x3 adds a bottom row without moving or resizing the first four slots", () => {
const { SIX_SLOT_LAYOUT } = require("../.test-build/app/apps/glanceboard/layout.js");
assert.equal(SIX_SLOT_LAYOUT.width, 576);
assert.equal(SIX_SLOT_LAYOUT.height, 432);
assert.deepEqual(SIX_SLOT_LAYOUT.slots.slice(0, 4).map((slot) => slot.rect), QUADRANT_LAYOUT.slots.map((slot) => slot.rect));
assert.deepEqual(SIX_SLOT_LAYOUT.slots.slice(4).map((slot) => slot.rect), [
{ x: 0, y: 288, width: 288, height: 144 },
{ x: 288, y: 288, width: 288, height: 144 },
]);
const regions = resolveGlanceRegions(SIX_SLOT_LAYOUT, ["none", "none", "terminal", "none", "terminal", "music"], spans);
assert.deepEqual(regions, [
{ choice: "terminal", rect: { x: 0, y: 144, width: 288, height: 288 }, slots: [2, 4] },
{ choice: "music", rect: { x: 288, y: 288, width: 288, height: 144 }, slots: [5] },
]);
const { slotDividers } = require("../.test-build/app/apps/glanceboard/layout.js");
const bottomDividers = slotDividers(SIX_SLOT_LAYOUT, regions).filter((line) => line.y0 === 288);
assert.deepEqual(bottomDividers, [
{ x0: 288, y0: 288, x1: 288, y1: 431 },
{ x0: 288, y0: 288, x1: 575, y1: 288 },
]);
});
+99
View File
@@ -0,0 +1,99 @@
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 layout = require('../.test-build/app/apps/glanceboard/layout.js');
function load(file, dependencies) {
const context = { exports: {}, console, require: (name) => {
assert.ok(name in dependencies, name);
return dependencies[name];
} };
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;
}
function harness() {
const values = new Map();
const listeners = new Set();
class Setting {
constructor(options) { Object.assign(this, options); }
get() { return values.get(this.storageKey) ?? this.defaultValue; }
set(value) { values.set(this.storageKey, value); }
}
const config = {
ConfigSettingBoolean: Setting, ConfigSettingEnum: Setting,
onAnySettingChanged: (listener) => { listeners.add(listener); return () => listeners.delete(listener); },
};
const widgets = {
glanceWidgetSpans: (choice) => choice === 'calendar' || choice === 'terminal',
findGlanceWidget: () => ({ create: () => ({ start() {}, stop() {}, paint() {} }) }),
};
const settings = load('app/apps/glanceboard/glanceboard-settings.ts', {
'../../ui/dashboard-settings': config, './layout': layout, './widgets': widgets,
});
class GrayImage {
constructor(width, height) { this.width = width; this.height = height; }
drawLine() {}
composeInto() {}
}
const { GlanceBoard } = load('app/apps/glanceboard/board.ts', {
'../../graphics/image': { GrayImage }, '../../ui/dashboard-settings': config,
'./glanceboard-settings': settings, './layout': layout, './widgets': widgets,
});
return { settings, GlanceBoard, values, listeners, notify: () => [...listeners].forEach((listener) => listener()) };
}
test('layout defaults to 2x2; expanding preserves stored slots and remembers the extra row', () => {
const { settings: s, values } = harness();
values.set('glanceboard.quadrants.slot.0', 'compass');
assert.equal(s.glanceLayoutSetting.get(), '2x2');
assert.equal(s.glanceLayout(), layout.QUADRANT_LAYOUT);
s.glanceLayoutSetting.set('2x3');
assert.equal(s.glanceLayout(), layout.SIX_SLOT_LAYOUT);
assert.deepEqual(Array.from(s.glanceSlotSettings(), (slot) => slot.get()),
['compass', 'calendar', 'music', 'calendar', 'none', 'none']);
s.glanceSlotSettings()[5].set('nightscout');
s.glanceLayoutSetting.set('2x2');
assert.equal(s.glanceSlotSettings().length, 4);
s.glanceLayoutSetting.set('2x3');
assert.equal(s.glanceSlotSettings()[5].get(), 'nightscout');
});
test('a spanning widget in the middle row keeps only one adjacent partner', () => {
const { settings: s } = harness();
s.glanceLayoutSetting.set('2x3');
const slots = s.glanceSlotSettings();
for (const index of [0, 2, 4]) slots[index].set('terminal');
s.clearConflictingSlots(s.glanceLayout(), 2, 'terminal');
assert.deepEqual(Array.from(slots, (slot) => slot.get()),
['terminal', 'calendar', 'terminal', 'calendar', 'none', 'none']);
slots[4].set('terminal');
s.clearConflictingSlots(s.glanceLayout(), 4, 'terminal');
assert.equal(slots[0].get(), 'none');
assert.equal(slots[2].get(), 'terminal');
});
test('an active empty board resizes and requests a frame when the layout changes', () => {
const h = harness();
for (const slot of h.settings.glanceSlotSettings(layout.SIX_SLOT_LAYOUT)) slot.set('none');
let renders = 0;
const board = new h.GlanceBoard(() => renders++);
board.start();
assert.equal(board.paint().height, 288);
h.settings.glanceLayoutSetting.set('2x3');
h.notify();
assert.equal(board.paint().width, 576);
assert.equal(board.paint().height, 432);
assert.equal(renders, 1);
h.settings.glanceLayoutSetting.set('2x2');
h.notify();
assert.equal(board.paint().height, 288);
assert.equal(renders, 2);
board.stop();
assert.equal(h.listeners.size, 0);
});
+1 -2
View File
@@ -1,5 +1,4 @@
const assert = require('node:assert/strict');
const { inflateSync } = require('node:zlib');
// Independent firmware-format decoder for reconstruction tests (not app code).
function applyDisplayPayload(base, payload, width = 640, height = 480) {
@@ -7,7 +6,7 @@ function applyDisplayPayload(base, payload, width = 640, height = 480) {
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 = inflateSync(payload.subarray(mode === 3 ? 7 : 1));
const tokens = payload.subarray(mode === 3 ? 7 : 1);
const pixels = [];
for (let i = 0; i < tokens.length;) {
const token = tokens[i++], color = token & 15;
+1 -1
View File
@@ -81,7 +81,7 @@ test('background glasses input still composites frames; phone resume preserves t
receiveInput: async input => { inputs.push(input); } };
class Session {
state = { phase: 'disconnected' };
constructor(_transport, _deflate, onState, onInput) { session = this; this.onState = onState; this.onInput = onInput; }
constructor(_transport, onState, onInput) { session = this; this.onState = onState; this.onInput = onInput; }
async start() { starts++; this.state = { phase: 'connected' }; this.onState(this.state); }
async stop() { stops++; this.state = { phase: 'disconnected' }; this.onState(this.state); }
setFrame(pixels) { if (this.state.phase === 'connected') frames.push(pixels); }
+139 -171
View File
@@ -4,6 +4,8 @@ const p = require('../.test-build/app/g2/ble-protocol.js');
const { identifyIosPeripheral, deviceAddressError } = require('../.test-build/app/g2/ios-peripheral-identity.js');
const { GlassesSession } = require('../.test-build/app/g2/glasses-session.js');
const { deflate, inflate } = require('pako');
const { inflateSync, constants } = require('node:zlib');
const { REQUIRED_FACECLAW_FIRMWARE_VERSION } = require('../.test-build/app/g2/firmware-compat.js');
const hex = bytes => Buffer.from(bytes).toString('hex');
const string = (field, text) => p.bytes(field, new Uint8Array(Buffer.from(text)));
@@ -13,13 +15,12 @@ test('iOS/shared protocol matches Android-generated wire vectors byte for byte',
const vectors = [
[p.authentication(101), '080410651a0408011004'],
[p.prelude(), '0802109c01220a1a081206120408001000'],
[p.createLayout(102), '080010661a3808021a1c0800100018c00420a0024801520964617368626f617264580162012022130800100018c00420a002280a3205696d67303028904e'],
[p.createLayout(102), '080010661a2308011a1c0800100018c00420a0024801520964617368626f617264580162012028904e'],
[p.heartbeat(103), '080c106772020800'],
[p.settingsQuery(104), '0802106822020801'],
[p.shutdown(105), '080910695a020801'],
[p.framebufferLease(true), '08011000aa0606464301050000'],
[p.framebufferLease(false), '08011000aa0606464301060000'],
[p.imageFragment(106, new Uint8Array([6, 1, 2, 3, 4]), 0), '0803106a2a1a080a1205696d673030180a200528003000380542050601020304'],
[p.frameMessage(p.authentication(101), 128, 0, 64)[0], 'aa21400c01018000080410651a04080110041024'],
];
for (const [actual, expected] of vectors) assert.equal(hex(actual), expected);
@@ -90,7 +91,7 @@ test('ring and arm input decoders preserve gesture and source', () => {
class FakeTransport {
events = new Set(); receiver = new p.MessageReceiver(); sent = []; subscriptions = []; closed = [];
hold = false; held = []; stock = false;
hold = false; held = []; stock = false; cfw = new Map();
onEvent(fn) { this.events.add(fn); return () => this.events.delete(fn); }
emit(event) { for (const fn of [...this.events]) fn(event); }
async resolveDevices() { return { left: 'L', right: 'R', ring: 'ring' }; }
@@ -99,9 +100,19 @@ class FakeTransport {
disconnect(id) { this.closed.push(id); this.emit({ kind: 'disconnected', identifier: id }); }
stopScan() {}
ack(id, message, overrides = {}) {
if (message.sid === p.SID.cfw) {
for (const lens of overrides.lenses ?? [1, 2]) {
const size = overrides.size ?? message.payload.length, crc = overrides.checksum ?? p.crc16(message.payload);
const body = new Uint8Array([overrides.nack ? 3 : 1, overrides.magic ?? message.magic, overrides.ordinal ?? 0, 0, lens, size & 255, size >>> 8, crc & 255, crc >>> 8]);
const checksum = p.crc16(body);
const packet = p.concat(new Uint8Array([0xaa, 0x12, 0, 11, 1, 1, overrides.sid ?? p.SID.cfw, 0]), body, new Uint8Array([checksum & 255, checksum >>> 8]));
this.emit({ kind: 'notification', identifier: overrides.identifier ?? id, characteristic: p.G2_NOTIFY, data: hex(packet) });
}
return;
}
let body = new Uint8Array();
if (message.sid === p.SID.auth) body = p.bytes(3, new Uint8Array());
if (message.sid === p.SID.settings) body = p.concat(p.bytes(4, p.concat(string(5, '2.2.9.22'), string(6, '2.2.9.22'), p.integer(12, 90), p.integer(13, 0))), string(100, this.stock ? '' : 'EVENCFW/18 img640 fbguard wearnotify cleanup11'));
if (message.sid === p.SID.settings) body = p.concat(p.bytes(4, p.concat(string(5, '2.2.9.22'), string(6, '2.2.9.22'), p.integer(12, 90), p.integer(13, 0))), string(100, this.stock ? '' : `Faceclaw/${REQUIRED_FACECLAW_FIRMWARE_VERSION}`));
const responseCommand = message.sid === p.SID.launch ? 1 : message.sid === p.SID.hub && message.command === 0 ? 1 : message.sid === p.SID.hub && message.command === 3 ? 4 : message.command;
const payload = p.concat(p.integer(1, responseCommand), p.integer(2, overrides.magic ?? message.magic), body);
const data = hex(p.concat(...p.frameMessage(payload, overrides.sid ?? message.sid, 0, 12)));
@@ -110,7 +121,26 @@ class FakeTransport {
}
async write(id, characteristic, frame) {
assert.equal(characteristic, p.G2_WRITE); assert.ok(frame.length <= 185);
for (const message of this.receiver.receive(id, frame)) {
let messages;
if (frame[6] === p.SID.cfw) {
assert.equal(p.crc16(frame.subarray(8, -2)), frame[frame.length - 2] | frame[frame.length - 1] << 8);
let state = this.cfw.get(id) ?? { history: Buffer.alloc(0), decoded: 0 };
if (frame[8] & 0x80) { state.record = []; state.magic = frame[2]; }
state.record.push(frame.subarray(9, -2)); this.cfw.set(id, state);
if (!(frame[8] & 0x40)) return;
const record = p.concat(...state.record), flags = record[0];
assert.equal(record.length - 5, record[1] | record[2] << 8);
if (flags & 8) { state.history = Buffer.alloc(0); state.decoded = 0; }
let payload = record.subarray(5);
if (flags & 4) {
state.history = Buffer.concat([state.history, payload]);
const all = inflateSync(state.history, { finishFlush: constants.Z_SYNC_FLUSH });
payload = new Uint8Array(all.subarray(state.decoded)); state.decoded = all.length;
}
assert.equal(p.crc16(payload), record[3] | record[4] << 8);
messages = [{ sid: p.SID.cfw, magic: state.magic, payload, flags, command: -1 }];
} else messages = this.receiver.receive(id, frame);
for (const message of messages) {
this.sent.push({ id, message });
if (!message.magic) continue;
if (this.hold) this.held.push({ id, message });
@@ -125,7 +155,7 @@ async function until(predicate) {
}
function harness(t, transport = new FakeTransport()) {
const states = [], input = [];
const session = new GlassesSession(transport, deflate, state => states.push(state), event => input.push(event));
const session = new GlassesSession(transport, state => states.push(state), event => input.push(event));
t.after(async () => { transport.hold = false; await session.stop(); });
return { transport, session, states, input };
}
@@ -136,18 +166,19 @@ test('session authenticates both arms, checks firmware and sends acknowledged di
assert.equal(h.session.state.charging, false);
assert.deepEqual(h.transport.sent.filter(s => s.message.sid === 128).map(s => s.id).sort(), ['L', 'R']);
h.session.setFrame(new Uint8Array(640 * 480)); await until(() => h.session.state.frames === 1);
const image = h.transport.sent.find(s => s.message.sid === 224 && s.message.command === 3);
const image = h.transport.sent.find(s => s.message.sid === p.SID.cfw);
assert.equal(image.id, 'L');
const fragment = p.readBytes(image.message.payload, 5), payload = p.readBytes(fragment, 8);
assert.equal(payload[0], 6); assert.ok(inflate(payload.slice(1)).length > 0);
assert.equal(image.message.payload[0], 6);
const layout = h.transport.sent.find(s => s.message.sid === p.SID.hub && s.message.command === 0);
assert.equal(p.readBytes(p.readBytes(layout.message.payload, 3), 4), undefined);
await h.session.stop();
assert.equal(h.session.state.phase, 'disconnected');
assert.ok(h.transport.sent.some(s => s.message.command === 3 && p.readBytes(p.readBytes(s.message.payload, 5), 8)[0] === 11));
assert.ok(h.transport.sent.some(s => s.message.sid === p.SID.cfw && s.message.payload[0] === 11));
});
test('stock firmware is rejected before framebuffer/layout/image commands', async t => {
const transport = new FakeTransport(); transport.stock = true;
const h = harness(t, transport); await h.session.start(addresses);
assert.equal(h.session.state.phase, 'error'); assert.match(h.session.state.status, /modified firmware/);
assert.equal(h.session.state.phase, 'error'); assert.match(h.session.state.status, /firmware/);
assert.ok(!transport.sent.some(s => s.message.sid === p.SID.hub));
});
test('one unavailable R1 notification channel does not discard the usable channel', async t => {
@@ -257,166 +288,128 @@ test('release while microphone enable awaits ACK sends disable last and rejects
assert.equal(p.readInteger(p.readBytes(mic.at(-1).message.payload, 18), 1), 0);
});
test('iOS traffic counts framed writes and logical messages, and advances fps only after the complete image ACK', async t => {
const { iosBleTraffic } = require('../.test-build/app/g2/ble-traffic-counters.js');
const h = harness(t); await h.session.start(addresses);
const before = iosBleTraffic.sample();
let writtenBytes = 0;
const write = h.transport.write.bind(h.transport);
h.transport.write = async (...args) => { await write(...args); writtenBytes += args[2].length; };
// Force multiple EvenHub messages so first-message ACK is not mistaken for a frame.
h.session.deflate = () => new Uint8Array(8000).fill(1);
h.transport.hold = true;
h.session.setFrame(new Uint8Array(640 * 480).fill(255));
await until(() => iosBleTraffic.sample().messages > before.messages);
assert.equal(iosBleTraffic.sample().frames, before.frames);
assert.equal(iosBleTraffic.sample().bytes - before.bytes, writtenBytes);
h.transport.hold = false;
for (const held of h.transport.held) h.transport.ack(held.id, held.message);
await until(() => h.session.state.frames === 1);
const after = iosBleTraffic.sample();
assert.equal(after.messages - before.messages, 3);
assert.equal(after.frames - before.frames, 1);
assert.equal(after.bytes - before.bytes, writtenBytes);
assert.ok(writtenBytes > 8001); // Includes protobuf, fragmentation headers and CRCs.
h.session.setFrame(new Uint8Array(640 * 480).fill(255));
await h.session.pump();
assert.deepEqual(iosBleTraffic.sample(), after); // Deduplicated image is not an ACKed frame.
await h.session.stop();
assert.equal(iosBleTraffic.sample().frames, after.frames); // No reset on disconnect.
});
const imageMessages = transport => transport.sent.filter(s => s.message.sid === p.SID.hub && s.message.command === 3);
const imageBody = sent => p.readBytes(sent.message.payload, 5);
const ack = (transport, sent) => transport.ack(sent.id, sent.message);
const imageMessages = transport => transport.sent.filter(s => s.message.sid === p.SID.cfw && s.message.payload[0] !== 11);
const imageBody = sent => sent.message.payload;
const ack = (transport, sent, overrides) => transport.ack(sent.id, sent.message, overrides);
const tick = () => new Promise(resolve => setImmediate(resolve));
const noisy = () => Uint8Array.from({ length: 640 * 480 }, (_, i) => (i % 2) * 255);
test('display window sends three complete messages before any ACK and refills on an out-of-order ACK', async t => {
const h = harness(t); await h.session.start(addresses);
// Five protocol messages, each split into many negotiated-MTU BLE writes.
const compressed = Uint8Array.from({ length: 16000 }, (_, i) => i & 255);
h.session.deflate = () => compressed; h.transport.hold = true;
h.session.setFrame(new Uint8Array(640 * 480).fill(255));
await until(() => imageMessages(h.transport).length === 3);
await tick(); assert.equal(imageMessages(h.transport).length, 3);
// Both eyes must finish; wrong ingress, size, CRC, ordinal and legacy replies do not count.
test('CFW ACK identity and both-lens completion gate display metrics', async t => {
const { iosBleTraffic } = require('../.test-build/app/g2/ble-traffic-counters.js');
const h = harness(t); await h.session.start(addresses); h.transport.hold = true;
const before = iosBleTraffic.sample(); let written = 0;
const write = h.transport.write.bind(h.transport);
h.transport.write = async (...args) => { written += args[2].length; await write(...args); };
h.session.setFrame(new Uint8Array(640 * 480));
await until(() => imageMessages(h.transport).length === 1);
const sent = imageMessages(h.transport)[0];
for (const wrong of [{ identifier: 'R' }, { size: 99 }, { checksum: 0 }, { ordinal: 1 }, { magic: sent.message.magic + 1 }]) ack(h.transport, sent, wrong);
ack(h.transport, sent, { lenses: [1] }); await tick();
assert.equal(h.session.state.frames, 0);
const first = imageMessages(h.transport);
ack(h.transport, first[1]); // Relayed ACKs need not arrive in submission order.
await until(() => imageMessages(h.transport).length === 4);
ack(h.transport, first[1]); // Duplicate ACK must not open another slot.
await tick(); assert.equal(imageMessages(h.transport).length, 4);
ack(h.transport, first[2]);
await until(() => imageMessages(h.transport).length === 5);
const sent = imageMessages(h.transport);
assert.deepEqual(sent.map(s => p.readInteger(imageBody(s), 6)), [0, 1, 2, 3, 4]);
assert.deepEqual(p.concat(...sent.map(s => p.readBytes(imageBody(s), 8))), p.concat(new Uint8Array([6]), compressed));
ack(h.transport, sent[4]); ack(h.transport, sent[3]);
await tick(); assert.equal(h.session.state.frames, 0); // First fragment still unacknowledged.
ack(h.transport, sent[0]);
await until(() => h.session.state.frames === 1);
assert.equal(h.session.displayInFlight, 0); assert.equal(h.session.displayFrames.length, 0);
ack(h.transport, sent, { lenses: [2] }); await until(() => h.session.state.frames === 1);
assert.equal(iosBleTraffic.sample().bytes - before.bytes, written);
assert.equal(iosBleTraffic.sample().messages - before.messages, 1);
assert.equal(iosBleTraffic.sample().frames - before.frames, 1);
ack(h.transport, sent); await tick(); assert.equal(h.session.state.frames, 1);
});
test('display pipelines across frames, deduplicates against enqueued images and coalesces to the newest waiting frame', async t => {
test('large frames use bounded RLE bands and ordered three-message pipelining', async t => {
const { applyDisplayPayload } = require('./helpers/display-payload.cjs');
const h = harness(t); await h.session.start(addresses); h.transport.hold = true;
const gray = noisy(); h.session.setFrame(gray);
await until(() => imageMessages(h.transport).length === 3);
const first = imageMessages(h.transport);
ack(h.transport, first[2]); ack(h.transport, first[1]); await tick();
assert.equal(imageMessages(h.transport).length, 3); assert.equal(h.session.state.frames, 0);
ack(h.transport, first[0]); await until(() => imageMessages(h.transport).length === 6);
for (const sent of imageMessages(h.transport).slice(3)) ack(h.transport, sent);
await until(() => imageMessages(h.transport).length === 8);
assert.equal(h.session.state.frames, 0);
for (const sent of imageMessages(h.transport).slice(6)) ack(h.transport, sent);
await until(() => h.session.state.frames === 1);
let shadow = new Uint8Array(320 * 480);
for (const sent of imageMessages(h.transport)) {
assert.ok(sent.message.payload.length <= 65535);
shadow = applyDisplayPayload(shadow, sent.message.payload);
}
assert.deepEqual(shadow, p.packGray4(gray, 640, 480));
});
test('display pipelines A-B-A and coalesces newer waiting frames', async t => {
const h = harness(t); await h.session.start(addresses); h.transport.hold = true;
const submit = async value => { h.session.setFrame(new Uint8Array(640 * 480).fill(value)); await h.session.pump(); await tick(); };
await submit(0); await until(() => imageMessages(h.transport).length === 1);
await submit(0); assert.equal(imageMessages(h.transport).length, 1); // Duplicate still in flight.
await submit(255); await submit(0); // A -> B -> A must transmit all three.
await until(() => imageMessages(h.transport).length === 3);
await submit(0); await submit(0); assert.equal(imageMessages(h.transport).length, 1);
await submit(255); await submit(0); await until(() => imageMessages(h.transport).length === 3);
await submit(80); await submit(160);
const sent = imageMessages(h.transport);
assert.deepEqual(p.readBytes(imageBody(sent[0]), 8), p.readBytes(imageBody(sent[2]), 8));
await submit(80); await submit(160); // Only the newest waiting frame survives.
assert.equal(imageMessages(h.transport).length, 3);
ack(h.transport, sent[2]); ack(h.transport, sent[1]); await tick();
assert.equal(h.session.state.frames, 0);
assert.equal(h.session.displayFrames.length, 3); // Bounded behind the missing oldest ACK.
assert.equal(imageMessages(h.transport).length, 3);
ack(h.transport, sent[0]);
await until(() => imageMessages(h.transport).length === 4);
assert.equal(h.session.state.frames, 0); assert.equal(imageMessages(h.transport).length, 3);
ack(h.transport, sent[0]); await until(() => imageMessages(h.transport).length === 4);
assert.equal(h.session.state.frames, 3);
const newest = imageMessages(h.transport)[3];
assert.deepEqual(p.readBytes(imageBody(newest), 8), p.concat(new Uint8Array([6]), deflate(p.rle4(p.packGray4(new Uint8Array(640 * 480).fill(160), 640, 480)))));
ack(h.transport, newest); await until(() => h.session.state.frames === 4);
await submit(160); assert.equal(imageMessages(h.transport).length, 4);
assert.deepEqual(imageBody(imageMessages(h.transport)[3]), p.concat(new Uint8Array([6]), p.rle4(p.packGray4(new Uint8Array(640 * 480).fill(160), 640, 480))));
ack(h.transport, imageMessages(h.transport)[3]); await until(() => h.session.state.frames === 4);
});
test('ACK timeout starts after transport writes drain; a lost display ACK flushes the whole pipeline', async t => {
const h = harness(t); await h.session.start(addresses);
const request = h.session.request.bind(h.session);
h.session.request = (role, sid, build, label, ...rest) => request(role, sid, build, label, ...(label === 'Display frame' ? [40] : rest));
const write = h.transport.write.bind(h.transport);
let release;
test('NACK replays the unresolved window with fresh IDs and reset compression; stale ACKs are ignored', async t => {
const h = harness(t); await h.session.start(addresses); h.transport.hold = true;
for (const value of [0, 255, 0]) { h.session.setFrame(new Uint8Array(640 * 480).fill(value)); await h.session.pump(); await tick(); }
await until(() => imageMessages(h.transport).length === 3);
const old = imageMessages(h.transport);
ack(h.transport, old[2]); ack(h.transport, old[1], { nack: true, lenses: [2] });
await until(() => imageMessages(h.transport).length === 6);
const replay = imageMessages(h.transport).slice(3);
for (const sent of old) ack(h.transport, sent);
await tick(); assert.equal(h.session.state.frames, 0);
replay.forEach((sent, i) => { assert.notEqual(sent.message.magic, old[i].message.magic); assert.ok(sent.message.flags & 8); assert.deepEqual(sent.message.payload, old[i].message.payload); ack(h.transport, sent); });
await until(() => h.session.state.frames === 3);
});
test('timeout starts after writes; missing ACK retries are bounded and invalidate the delta base', async t => {
const h = harness(t); await h.session.start(addresses); h.transport.hold = true;
const write = h.transport.write.bind(h.transport); let release;
const blocked = new Promise(resolve => { release = resolve; });
h.transport.write = async (...args) => { if (args[0] === 'L') await blocked; await write(...args); };
h.transport.hold = true; h.session.deflate = () => new Uint8Array(16000);
h.session.setFrame(new Uint8Array(640 * 480)); await h.session.pump();
await new Promise(resolve => setTimeout(resolve, 65));
await new Promise(resolve => setTimeout(resolve, 550));
assert.equal(h.session.state.phase, 'connected'); assert.equal(imageMessages(h.transport).length, 0);
release(); await until(() => imageMessages(h.transport).length === 3);
const stale = imageMessages(h.transport);
await until(() => h.session.state.phase === 'retrying');
assert.match(h.session.state.status, /Display frame was not acknowledged/);
assert.equal(h.session.displayInFlight, 0); assert.equal(h.session.displayFrames.length, 0);
assert.equal(h.session.lastEnqueued, null); assert.equal(h.session.pending.size, 0);
for (const sent of stale) ack(h.transport, sent);
await tick(); assert.equal(h.session.state.frames, 0); assert.equal(imageMessages(h.transport).length, 3);
// A new session must resend even the identical image; old ACKs cannot count it.
await h.session.stop(); h.transport.hold = false; await h.session.start(addresses);
h.session.deflate = deflate; h.transport.hold = true;
h.session.setFrame(new Uint8Array(640 * 480));
await until(() => imageMessages(h.transport).length === 4);
for (const sent of stale) ack(h.transport, sent);
release(); await until(() => imageMessages(h.transport).length === 1); await tick();
for (let i = 1; i <= 4; i++) {
h.session.cfwPending.forEach(p => p.deadline = 1); h.session.recoverCfw();
if (i < 4) await until(() => imageMessages(h.transport).length === i + 1);
}
assert.equal(h.session.state.phase, 'retrying'); assert.match(h.session.state.status, /retry limit/);
assert.equal(h.session.lastEnqueued, null); assert.equal(h.session.cfwPending.length, 0);
for (const sent of imageMessages(h.transport)) ack(h.transport, sent);
await tick(); assert.equal(h.session.state.frames, 0);
ack(h.transport, imageMessages(h.transport)[3]); await until(() => h.session.state.frames === 1);
});
test('failed transport write prevents queued display messages from being written', async t => {
test('failed write poisons queued display work; disconnect cleanup uses the new SID', async t => {
const h = harness(t); await h.session.start(addresses);
let attempts = 0;
const write = h.transport.write.bind(h.transport);
h.transport.write = async (...args) => {
if (args[0] === 'L') { attempts++; throw new Error('test write failed'); }
return write(...args);
};
h.session.deflate = () => new Uint8Array(16000);
h.session.setFrame(new Uint8Array(640 * 480));
await until(() => h.session.state.phase === 'retrying');
assert.equal(attempts, 1); assert.equal(h.session.pending.size, 0);
assert.equal(h.session.displayInFlight, 0); assert.equal(h.session.state.frames, 0);
});
test('disconnect cancels the display window and sends cleanup after the queued images stop', async t => {
const h = harness(t); await h.session.start(addresses);
h.transport.hold = true; h.session.deflate = () => new Uint8Array(16000);
h.session.setFrame(new Uint8Array(640 * 480));
await until(() => imageMessages(h.transport).length === 3);
const stale = imageMessages(h.transport);
h.transport.hold = false; await h.session.stop();
for (const sent of stale) ack(h.transport, sent);
await tick();
const write = h.transport.write.bind(h.transport); let attempts = 0;
h.transport.write = async (...args) => { if (args[0] === 'L') { attempts++; throw new Error('test write failed'); } await write(...args); };
h.session.setFrame(noisy()); await until(() => h.session.state.phase === 'retrying');
assert.equal(attempts, 1); assert.equal(h.session.displayInFlight, 0);
await h.session.stop(); h.transport.write = write; await h.session.start(addresses);
h.transport.hold = true; h.session.setFrame(noisy()); await until(() => imageMessages(h.transport).length === 3);
const stale = imageMessages(h.transport); h.transport.hold = false; await h.session.stop();
stale.forEach(s => ack(h.transport, s)); await tick();
assert.equal(h.session.state.phase, 'disconnected'); assert.equal(h.session.state.frames, 0);
assert.equal(h.session.displayInFlight, 0); assert.equal(h.session.displayFrames.length, 0);
const images = imageMessages(h.transport);
assert.equal(images.length, 4); assert.deepEqual(p.readBytes(imageBody(images[3]), 8), new Uint8Array([11]));
assert.equal(h.transport.sent.at(-1).message.sid, p.SID.cfw);
assert.deepEqual(h.transport.sent.at(-1).message.payload, new Uint8Array([11]));
});
test('a full display window leaves glasses input, microphone control and audio responsive', async t => {
const h = harness(t); await h.session.start(addresses);
h.transport.hold = true; h.session.deflate = () => new Uint8Array(16000);
h.session.setFrame(new Uint8Array(640 * 480));
await until(() => imageMessages(h.transport).length === 3);
test('full display window still services input and microphone control', async t => {
const h = harness(t); await h.session.start(addresses); h.transport.hold = true;
h.session.setFrame(noisy()); await until(() => imageMessages(h.transport).length === 3);
const input = p.bytes(13, p.bytes(3, p.concat(p.integer(1, 9), p.integer(2, 3))));
h.transport.emit({ kind: 'notification', identifier: 'R', characteristic: p.G2_NOTIFY,
data: hex(p.concat(...p.frameMessage(input, p.SID.hub, 1, 22))) });
assert.equal(h.input.length, 1); assert.equal(h.input[0].eventSource, 3);
h.transport.emit({ kind: 'notification', identifier: 'R', characteristic: p.G2_NOTIFY, data: hex(p.concat(...p.frameMessage(input, p.SID.hub, 1, 22))) });
assert.equal(h.input.length, 1);
const audio = [], enabling = h.session.setMicrophone(true, packet => audio.push(hex(packet)));
await until(() => h.transport.sent.some(s => s.message.command === 15));
ack(h.transport, h.transport.sent.find(s => s.message.command === 15)); await enabling;
h.transport.emit({ kind: 'notification', identifier: 'L', characteristic: p.G2_RENDER_NOTIFY, data: '010203' });
assert.deepEqual(audio, ['010203']);
assert.equal(imageMessages(h.transport).length, 3); assert.equal(h.session.state.frames, 0);
assert.equal(h.session.displayInFlight, 3);
assert.deepEqual(audio, ['010203']); assert.equal(h.session.displayInFlight, 3);
});
test('pipelined bounding boxes reconstruct moving and erased content against the last queued frame', async t => {
@@ -429,7 +422,7 @@ test('pipelined bounding boxes reconstruct moving and erased content against the
h.session.setFrame(frames[i]); await h.session.pump();
await until(() => imageMessages(h.transport).length === i + 1);
}
const messages = imageMessages(h.transport), payloads = messages.map(m => p.readBytes(imageBody(m), 8));
const messages = imageMessages(h.transport), payloads = messages.map(m => imageBody(m));
assert.deepEqual(payloads.map(b => b[0]), [6, 3, 3]);
assert.deepEqual(payloads.slice(1).map(b => b[5] | (b[6] << 8)), [1, 2]);
assert.equal(h.session.state.frames, 0); // All three updates precede any ACK.
@@ -442,7 +435,7 @@ test('pipelined bounding boxes reconstruct moving and erased content against the
ack(h.transport, messages[0]); await until(() => h.session.state.frames === 1);
h.session.setFrame(base); await h.session.pump();
await until(() => imageMessages(h.transport).length === 4);
const clear = p.readBytes(imageBody(imageMessages(h.transport)[3]), 8);
const clear = imageBody(imageMessages(h.transport)[3]);
assert.equal(clear[0], 3); assert.equal(clear[1], 25); // Only B's dot needs clearing.
assert.deepEqual(applyDisplayPayload(shadow, clear), p.packGray4(base, 640, 480));
for (const message of imageMessages(h.transport).slice(1)) ack(h.transport, message);
@@ -454,7 +447,7 @@ test('delta ids skip reserved values and advance only on emitted deltas; reconne
const submit = async gray => {
const before = h.session.state.frames; h.session.setFrame(gray);
await until(() => h.session.state.frames === before + 1);
return p.readBytes(imageBody(imageMessages(h.transport).at(-1)), 8);
return imageBody(imageMessages(h.transport).at(-1));
};
const base = new Uint8Array(640 * 480), next = base.slice(); next[1234] = 255;
assert.equal((await submit(base))[0], 6);
@@ -469,28 +462,3 @@ test('delta ids skip reserved values and advance only on emitted deltas; reconne
await h.session.stop(); await h.session.start(addresses);
assert.equal((await submit(base))[0], 6); // Even the same pixels need a trusted full base.
});
test('a lost delta ACK invalidates the queued base and late delta ACKs cannot seed a new session', async t => {
const h = harness(t); await h.session.start(addresses);
const base = new Uint8Array(640 * 480); h.session.setFrame(base);
await until(() => h.session.state.frames === 1);
const request = h.session.request.bind(h.session);
h.session.request = (role, sid, build, label, ...rest) => request(role, sid, build, label, ...(label === 'Display frame' ? [50] : rest));
h.transport.hold = true;
const a = base.slice(), b = base.slice(); a[1234] = 255; b[4321] = 255;
h.session.setFrame(a); await h.session.pump();
h.session.setFrame(b); await h.session.pump();
await until(() => imageMessages(h.transport).length === 3);
const stale = imageMessages(h.transport).slice(1);
assert.deepEqual(stale.map(m => p.readBytes(imageBody(m), 8)[0]), [3, 3]);
ack(h.transport, stale[1]); // Even a later successful delta does not rescue a hole.
await until(() => h.session.state.phase === 'retrying');
assert.equal(h.session.lastEnqueued, null); assert.equal(h.session.state.frames, 1);
await h.session.stop(); h.transport.hold = false; await h.session.start(addresses);
h.transport.hold = true; h.session.setFrame(b); await h.session.pump();
await until(() => imageMessages(h.transport).length === 4);
const reseed = imageMessages(h.transport)[3]; assert.equal(p.readBytes(imageBody(reseed), 8)[0], 6);
for (const message of stale) ack(h.transport, message);
await tick(); assert.equal(h.session.state.frames, 1);
ack(h.transport, reseed); await until(() => h.session.state.frames === 2);
});
+231
View File
@@ -0,0 +1,231 @@
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 vm = require('node:vm');
const { execFileSync } = require('node:child_process');
const ts = require('typescript');
const source = (file) => fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
function load(file, requireModule, globals = {}) {
const context = { exports: {}, require: requireModule, console, ...globals };
vm.runInNewContext(ts.transpileModule(source(file), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, context);
return context.exports;
}
function store(settings = new Map()) {
const listeners = [];
const storage = {
getStringSetting: (key, fallback) => settings.get(key) ?? fallback,
setStringSetting: (key, value) => {
settings.set(key, value);
for (const listener of listeners) listener(key);
},
onSettingsStoreChanged: (listener) => { listeners.push(listener); return () => {}; },
};
return { prefs: load('app/native/media-apps.ts', () => storage), storage };
}
const chrome = { packageName: 'com.android.chrome', appName: 'Chrome' };
const player = { packageName: 'com.player', appName: 'Player' };
test('defaults apply before discovery; explicit choices survive restart, renames and rediscovery', () => {
const settings = new Map();
let { prefs } = store(settings);
assert.equal(prefs.isMediaAppEnabled(chrome.packageName), false);
assert.equal(prefs.isMediaAppEnabled(player.packageName), true);
assert.equal(prefs.isMediaAppEnabled('com.android.chrome.music'), true);
prefs.rememberMediaApps([chrome, player, player, { packageName: '', appName: 'Invalid' }]);
assert.equal(prefs.readMediaApps().length, 2);
prefs.setMediaAppEnabled({ ...chrome, title: 'Do not store metadata' }, true);
prefs.setMediaAppEnabled(player, false);
({ prefs } = store(settings));
prefs.rememberMediaApps([{ ...player, appName: 'Renamed player' }, chrome]);
assert.equal(prefs.isMediaAppEnabled(chrome.packageName), true);
assert.equal(prefs.isMediaAppEnabled(player.packageName), false);
assert.equal(prefs.readMediaApps().find((a) => a.packageName === player.packageName).appName, 'Renamed player');
assert.ok(!Array.from(settings.values()).join('').includes('Do not store metadata'));
prefs.rememberMediaApps([]);
assert.equal(prefs.readMediaApps().length, 2);
prefs.setMediaAppEnabled(player, true);
prefs.setMediaAppEnabled(chrome, false);
assert.equal(store(settings).prefs.isMediaAppEnabled(player.packageName), true);
assert.equal(store(settings).prefs.isMediaAppEnabled(chrome.packageName), false);
});
test('malformed saved entries preserve defaults, and discovery does not freeze defaults', () => {
for (const raw of ['invalid', '{}', '[null, {}, {"packageName": 1}]',
'[{"packageName":"com.android.chrome","enabled":"true"}]']) {
const { prefs } = store(new Map([['music.apps', raw]]));
assert.equal(prefs.isMediaAppEnabled(chrome.packageName), false);
assert.equal(prefs.isMediaAppEnabled(player.packageName), true);
}
const { prefs } = store();
prefs.rememberMediaApps([chrome]);
assert.equal(prefs.readMediaApps()[0].enabled, undefined);
});
function bridges() {
const { prefs, storage } = store();
let browserListener, controllerListener, ignored, queries = 0, disconnects = 0, plays = 0;
const browsable = [chrome, player].map((app) => ({ ...app, serviceClass: `${app.packageName}.Browser` }));
class NativeBrowser {
setListener(listener) { browserListener = listener; }
listBrowsableAppsJson() { queries++; return JSON.stringify(browsable); }
connect(id) { browserListener.onConnectResult(id, true, 'root', ''); }
disconnect() { disconnects++; }
playFromMediaId() { plays++; }
}
class NativeController {
setIgnoredPackagesJson(json) { ignored = JSON.parse(json); }
setListener(listener) { controllerListener = listener; }
start() { assert.ok(ignored.includes(chrome.packageName)); }
}
const dependencies = {
'@nativescript/core': { Utils: { android: { getApplicationContext: () => ({}) } } },
'./media-apps': prefs,
'./settings-store': storage,
'../graphics/image': {},
'./image-files': {},
};
const globals = { global: { isAndroid: true }, com: { faceclaw: { app: {
FaceclawMediaBrowser: NativeBrowser,
FaceclawMediaBrowserListener: function(listener) { return listener; },
FaceclawMediaController: NativeController,
FaceclawMediaControllerListener: function(listener) { return listener; },
} } } };
const requireModule = (name) => { assert.ok(name in dependencies, name); return dependencies[name]; };
const browser = load('app/native/media-browser.ts', requireModule, globals).mediaBrowserBridge;
const controller = load('app/native/media-controller.ts', requireModule, globals).mediaControllerBridge;
return { prefs, browser, controller, browsable, queries: () => queries, disconnects: () => disconnects,
plays: () => plays, ignored: () => ignored, observed: (apps) => controllerListener.onSessionAppsChanged(JSON.stringify(apps)) };
}
test('browse discovery remembers ignored apps and cached results reflect toggles immediately', async () => {
const b = bridges();
assert.deepEqual(Array.from(b.browser.listBrowsableApps(), (a) => a.packageName), [player.packageName]);
assert.equal(b.prefs.readMediaApps().length, 2);
b.prefs.setMediaAppEnabled(chrome, true);
assert.equal(b.browser.listBrowsableApps().length, 2);
assert.equal(b.queries(), 1);
await b.browser.connect(b.browsable[0]);
b.browser.playFromMediaId('song');
assert.equal(b.plays(), 1);
b.prefs.setMediaAppEnabled(chrome, false);
assert.equal(b.disconnects(), 1);
b.browser.playFromMediaId('song');
assert.equal(b.plays(), 1);
await assert.rejects(b.browser.connect(b.browsable[0]), /ignored/);
b.prefs.setMediaAppEnabled(player, false);
assert.equal(b.browser.listBrowsableApps().length, 0);
});
test('native controller gets defaults before start and records all session owners, retaining ended sessions', async () => {
const b = bridges();
await b.controller.start();
b.observed([chrome, player]);
b.observed([]);
assert.equal(b.prefs.readMediaApps().length, 2);
b.prefs.setMediaAppEnabled(chrome, true);
b.prefs.setMediaAppEnabled(player, false);
assert.ok(!b.ignored().includes(chrome.packageName));
assert.ok(b.ignored().includes(player.packageName));
});
test('Music settings keeps toggles and selection when a new app arrives and supports back', async () => {
const { prefs } = store();
let refreshes = 0, closes = 0;
const textwrap = load('app/graphics/textwrap.ts');
const graphics = load('app/graphics/image.ts', () => textwrap);
const { BdfFont } = load('app/graphics/bdffont.ts', () => ({}));
const font = BdfFont.parse(source('app/fonts/terminus/ter-u20n.bdf'));
class RecordingImage extends graphics.GrayImage {
texts = [];
drawText(font, x, y, text, value) { this.texts.push({ x, y, text }); super.drawText(font, x, y, text, value); }
}
const deps = {
'../graphics/image': { ...graphics, GrayImage: RecordingImage },
'../graphics/textwrap': textwrap,
'../graphics/ui-fonts': { getDefaultSmallFont: () => font },
'../util/numeric-util': { clamp: (n, lo, hi) => Math.max(lo, Math.min(hi, n)) },
'./metrics': load('app/ui/metrics.ts'), './gestures': {},
};
const menu = load('app/ui/menu.ts', (name) => deps[name]);
const uiDeps = {
'../../graphics/image': deps['../graphics/image'],
'../../graphics/textwrap': textwrap,
'../../graphics/ui-fonts': deps['../graphics/ui-fonts'],
'../../native/media-apps': prefs,
'../../native/media-browser': { mediaBrowserBridge: { listBrowsableApps: (refresh) => {
assert.equal(refresh, true); refreshes++; prefs.rememberMediaApps([player]); return [];
} } },
'../../ui/menu': menu,
};
const { MusicSettingsLayer } = load('app/apps/music/music-settings.ts', (name) => uiDeps[name]);
const layer = new MusicSettingsLayer();
const ctx = { stack: { getBaseSize: () => ({ width: 540, height: 224 }), isFocused: () => true, pop: () => closes++ } };
const paint = () => layer.paint(ctx, () => new RecordingImage(540, 224));
const input = (type) => layer.handleInput({ type }, ctx);
assert.equal(refreshes, 1);
paint();
await input('click');
assert.equal(prefs.isMediaAppEnabled(player.packageName), false);
prefs.rememberMediaApps([{ packageName: 'com.alpha', appName: 'Alpha' }]);
const image = paint();
assert.ok(image.texts.some(({ text }) => text === 'Player'));
assert.ok(image.texts.some(({ text }) => text === 'Alpha'));
assert.ok(image.texts.every(({ y }) => y >= 0 && y + font.lineHeight <= image.height));
await input('click');
assert.equal(prefs.isMediaAppEnabled(player.packageName), true);
await input('double-click');
assert.equal(closes, 1);
});
test('native session selection skips ignored playing and idle apps, including the all-ignored case', () => {
// Execute the production selection method with lightweight media-session doubles.
const java = source('App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawMediaController.java');
const method = java.slice(java.indexOf(' private MediaController chooseController('),
java.indexOf(' private void emitSessionAppsLocked('));
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'faceclaw-media-java-'));
const javaBin = (name) => process.env.JAVA_HOME ? path.join(process.env.JAVA_HOME, 'bin', name) : name;
try {
const file = path.join(directory, 'MediaSelectionTest.java');
fs.writeFileSync(file, `import java.util.*;
public class MediaSelectionTest {
Set<String> ignoredPackages = new HashSet<>();
static class PlaybackState {
static final int STATE_PLAYING = 3;
int state; PlaybackState(int state) { this.state = state; } int getState() { return state; }
}
static class MediaController {
String name; PlaybackState state;
MediaController(String name, int state) { this.name = name; this.state = new PlaybackState(state); }
String getPackageName() { return name; } PlaybackState getPlaybackState() { return state; }
}
${method}
public static void main(String[] args) {
MediaSelectionTest test = new MediaSelectionTest();
MediaController ignored = new MediaController("browser", 3);
MediaController paused = new MediaController("player", 2);
MediaController playing = new MediaController("music", 3);
test.ignoredPackages.add("browser");
assert test.chooseController(Arrays.asList(ignored, paused)) == paused;
assert test.chooseController(Arrays.asList(ignored, paused, playing)) == playing;
assert test.chooseController(Arrays.asList(ignored)) == null;
ignored.state = null;
assert test.chooseController(Arrays.asList(ignored, paused)) == paused;
test.ignoredPackages.add("music");
assert test.chooseController(Arrays.asList(ignored, paused, playing)) == paused;
test.ignoredPackages.remove("browser"); ignored.state = new PlaybackState(3);
assert test.chooseController(Arrays.asList(ignored, paused)) == ignored;
assert test.chooseController(null) == null;
assert test.chooseController(Collections.emptyList()) == null;
}
}`);
execFileSync(javaBin('javac'), ['-d', directory, file], { stdio: 'pipe' });
execFileSync(javaBin('java'), ['-ea', '-cp', directory, 'MediaSelectionTest'], { stdio: 'pipe' });
} finally {
fs.rmSync(directory, { recursive: true, force: true });
}
});
+153
View File
@@ -0,0 +1,153 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const worker = require('./fixtures/pinball-worker.cjs');
function lane(h, index) {
h.w.ballX = h.ROLLOVERS[index].x;
h.w.ballY = h.ROLLOVERS[index].y;
h.checkRollovers(h.w);
h.w.ballY = 60;
h.checkRollovers(h.w);
}
function target(h, index) {
const t = h.TARGETS[index];
h.w.ballX = t.x + (index < 3 ? 7 : -7);
h.w.ballY = t.y;
h.w.ballVx = index < 3 ? -50 : 50;
h.checkTargets(h.w);
}
test('skill shot awards only the marked first lane; rollovers debounce and raise multiplier to 5x', () => {
const h = worker();
h.launchBall(h.w);
lane(h, 0);
assert.equal(h.w.score, 800);
lane(h, 0);
assert.equal(h.w.score, 800);
lane(h, 1); lane(h, 2);
assert.equal(h.w.score, 1400);
assert.equal(h.w.multiplier, 2);
for (let round = 0; round < 6; round++) for (let i = 0; i < 3; i++) lane(h, i);
assert.equal(h.w.multiplier, 5);
const missed = worker();
missed.launchBall(missed.w);
lane(missed, 1); lane(missed, 0);
assert.equal(missed.w.score, 100);
});
test('six distinct drop targets light a repeatable, escalating center jackpot', () => {
const h = worker();
h.launchBall(h.w);
for (let i = 0; i < 6; i++) { target(h, i); target(h, i); }
assert.equal(h.w.score, 1900);
assert.ok(h.w.targetsDown.every(Boolean));
h.w.ballX = 121; h.w.ballY = 110;
h.collideBumpers(h.w);
assert.equal(h.w.score, 4000);
assert.equal(h.w.jackpots, 1);
assert.ok(h.w.targetsDown.every((value) => !value));
for (let i = 0; i < 6; i++) target(h, i);
h.w.ballX = 121; h.w.ballY = 110;
h.collideBumpers(h.w);
assert.equal(h.w.score, 9000);
assert.equal(h.w.jackpots, 2);
});
test('ball saver preserves objectives once, then a drain pays multiplied bonus and resets the ball', () => {
const h = worker();
h.launchBall(h.w);
target(h, 0);
h.w.multiplier = 3;
h.ballDrained(h.w);
assert.equal(h.w.ballsLeft, 3);
assert.equal(h.w.ballState, 'ready');
assert.equal(h.w.targetsDown[0], true);
h.launchBall(h.w);
assert.equal(h.w.ballSaveRemaining, 0);
assert.equal(h.w.skillShotRemaining, 0);
h.ballDrained(h.w);
assert.equal(h.w.ballsLeft, 2);
assert.equal(h.w.lastBonus, 300);
assert.equal(h.w.score, 450);
assert.equal(h.highScore(), 450);
assert.equal(h.w.multiplier, 1);
assert.equal(h.w.skillLane, 1);
assert.ok(h.w.targetsDown.every((value) => !value));
h.launchBall(h.w);
assert.equal(h.w.ballSaveRemaining, 8);
});
test('pause, background, screen-off and menus preserve gameplay timers', () => {
for (const suspend of [
(h) => h.input('double-click'),
(h) => h.input('short-then-long-press'),
(h) => h.message({ type: 'foreground', windowId: 'test', foreground: false, focused: false }),
(h) => h.message({ type: 'screen', on: false }),
]) {
const h = worker(); h.launchBall(h.w); suspend(h);
h.elapse(60); h.tick(h.w);
assert.equal(h.w.ballSaveRemaining, 8);
assert.equal(h.w.skillShotRemaining, 8);
}
});
test('expired saver drains normally; final bonus is included in game over and restart keeps high score', () => {
const h = worker();
for (let i = 0; i < 3; i++) {
h.launchBall(h.w); target(h, 0);
h.w.ballSaveRemaining = 0;
h.ballDrained(h.w);
}
assert.equal(h.w.phase, 'game-over');
assert.equal(h.w.score, 750);
assert.equal(h.w.lastBonus, 100);
h.resetGame(h.w);
assert.equal(h.w.score, 0);
assert.equal(h.w.ballsLeft, 3);
assert.equal(h.w.lastBonus, 0);
assert.equal(h.w.highScore, 750);
});
test('live simulation consumes skill and save time; wall-clock pauses do not', () => {
const h = worker(); h.launchBall(h.w);
h.advance(0.25);
assert.ok(Math.abs(h.w.ballSaveRemaining - 7.75) < 0.001);
assert.ok(Math.abs(h.w.skillShotRemaining - 7.75) < 0.001);
h.input('double-click'); h.elapse(90); h.input('click');
h.advance(0.25);
assert.ok(Math.abs(h.w.ballSaveRemaining - 7.5) < 0.001);
assert.ok(Math.abs(h.w.skillShotRemaining - 7.5) < 0.001);
h.w.skillShotRemaining = 0;
lane(h, 0);
assert.equal(h.w.score, 50);
});
test('production physics stays finite and within the table at every launch power', () => {
for (let power = 1; power <= 5; power++) {
const h = worker(); h.w.launchPower = power; h.launchBall(h.w);
let enteredPlayfield = false;
for (let step = 0; step < 120 * 30 && h.w.ballState === 'live'; step++) {
if (h.w.ballVy > 0 && h.w.ballY > 195) for (const f of h.w.flippers) h.flip(h.w, f);
h.advance(1 / 120);
assert.ok(Number.isFinite(h.w.ballX) && Number.isFinite(h.w.ballY));
assert.ok(h.w.ballX >= 9 && h.w.ballX <= 261);
if (h.w.ballX < 226) enteredPlayfield = true;
}
assert.ok(enteredPlayfield, `power ${power} enters playfield`);
}
});
test('ready, live jackpot, paused and game-over frames render at the glasses viewport size', () => {
const h = worker();
for (const phase of ['playing', 'paused', 'game-over']) {
h.w.phase = phase;
for (const lit of [false, true]) {
h.w.targetsDown.fill(lit);
const image = h.paintContent(h.w);
assert.equal(image.width, 576);
assert.equal(image.height, 260);
assert.ok(image.withDrawsBaked().pixels.some((p) => p > 0));
}
}
});
+19
View File
@@ -0,0 +1,19 @@
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('ring battery decodes valid, unavailable, legacy, and malformed reports', () => {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'faceclaw-ring-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/RingBatteryProtocolTest.java')], { stdio: 'pipe' });
execFileSync(javaBin('java'), ['-ea', '-cp', directory, 'com.faceclaw.app.RingBatteryProtocolTest'], { stdio: 'pipe' });
} finally {
fs.rmSync(directory, { recursive: true, force: true });
}
});
+5 -1
View File
@@ -107,7 +107,11 @@ class Image {
test('cursor replaces only the prompt; marker and frame persist across cached blink phases', () => {
const renders = [];
const icons = load('app/graphics/icons.ts', { './image': { GrayImage: Image } }, {
const icons = load('app/graphics/icons.ts', { './image': { GrayImage: Image },
'../native/svg-rasterizer': { rasterizeSvg(svg, size, stroke) {
renders.push(svg); assert.equal(stroke, 2); const image = new Image(size, size); image.pixels.fill(255); return image;
} },
}, {
global: { isAndroid: true },
com: { faceclaw: { app: { IconRenderer: { renderSvgGray(svg, size, stroke) {
renders.push(svg); assert.equal(stroke, 2); return new Uint8Array(size * size).fill(255);
+23
View File
@@ -0,0 +1,23 @@
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('256 KiB cache uploads and planner draws preserve wide image and glyph offsets', () => {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'faceclaw-texture-java-'));
const javaBin = (name) => process.env.JAVA_HOME ? path.join(process.env.JAVA_HOME, 'bin', name) : name;
const root = path.join(__dirname, '../App_Resources/Android/src/main/java/com/faceclaw/app');
try {
const clock = path.join(directory, 'SystemClock.java');
const log = path.join(directory, 'Log.java');
fs.writeFileSync(clock, 'package android.os; public class SystemClock { public static long elapsedRealtime() { return 0; } }');
fs.writeFileSync(log, 'package android.util; public class Log { public static int i(String tag, String msg) { return 0; } }');
const sources = ['GlyphAtlas.java', 'ImageAtlas.java', 'FwGlyphAtlas.java', 'SurfaceCompositor.java',
'util/BmpUtil.java', 'util/CollectionUtils.java', 'g2protocol/BleProtocol.java',
'g2protocol/BleImageOptimizer.java', 'g2protocol/TextureCacheState.java', 'g2protocol/TexturePlanner.java'];
execFileSync(javaBin('javac'), ['-d', directory, ...sources.map(file => path.join(root, file)),
clock, log, path.join(__dirname, 'fixtures/TextureCacheProtocolTest.java')], { stdio: 'pipe' });
execFileSync(javaBin('java'), ['-ea', '-cp', directory, 'com.faceclaw.app.TextureCacheProtocolTest'], { stdio: 'pipe' });
} finally { fs.rmSync(directory, { recursive: true, force: true }); }
});
+1
View File
@@ -51,6 +51,7 @@ function worker() {
'../../native/active-display': {},
'../../native/settings-store': { getStringSetting: () => '0', setStringSetting: noop },
'../../ui/sound-effects': {}, '../../ui/window-menu': {},
'../../ui/sound-setting': { loadSoundEnabled: () => true, saveSoundEnabled: noop },
'../../ui/gestures': { directionalFallback: (event) => event },
'../../util/numeric-util': { clamp: (v, lo, hi) => Math.max(lo, Math.min(hi, v)) },
};
+3
View File
@@ -19,11 +19,14 @@
"../app/g2/glasses-session.ts",
"../app/graphics/surface-compositor.ts",
"../app/phone-ui/phone-gestures.ts",
"../app/g2/firmware-compat.ts",
"../app/g2/glasses-hardware-identity.ts",
"../app/g2/ble-proximity.ts",
"../app/g2/even-advertisement.ts",
"../app/g2/glasses-artwork.ts",
"../app/g2/glasses-display-state.ts",
"../app/g2/glance-state.ts",
"../app/apps/glanceboard/layout.ts",
"../app/g2/pairing-candidates.ts",
"../app/apps/calculator/math/*.ts",
"../app/apps/microphones/mic-protocol.ts",
+167
View File
@@ -0,0 +1,167 @@
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, deps, globals = {}) {
const exports = {};
vm.runInNewContext(ts.transpileModule(fs.readFileSync(path.join(__dirname, '..', file), 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, { exports, console, ...globals, require: name => deps[name] ?? {} });
return exports;
}
function dialog({ autoSend = false, deferred = true, synchronousFinal } = {}) {
const listeners = new Set(), timers = new Map(), sent = [], refinements = [];
let complete, timerId = 0, starts = 0, frame;
let completion = new Promise(resolve => { complete = resolve; });
const { VoiceInputLayer } = load('app/ui/shell/voice-input.ts', {
'../../native/voice-control': { voiceControlBridge: {
onTranscript(cb) { listeners.add(cb); return () => listeners.delete(cb); },
onStatus() { return () => {}; },
} },
'../../native/anthropic': { refineDictation(options) { refinements.push(options); return { cancel() {} }; } },
'../dashboard-settings': { anthropicApiKeySetting: { get: () => 'key' } },
'../gestures': { gestureHints: () => '' },
'./input-dialog': { paintInputDialog(_image, options) { frame = options; } },
}, {
global: { isIOS: false },
setTimeout(cb) { const id = ++timerId; timers.set(id, cb); return id; },
clearTimeout(id) { timers.delete(id); },
});
const transcript = (text, isFinal = false) => { for (const cb of [...listeners]) cb({ text, isFinal }); };
const layer = new VoiceInputLayer({ autoSend, onClosed() {}, dismiss: () => layer.onRemoved(),
actions: { requestRender() {}, startVoiceCapture() { starts++; }, stopVoiceCapture() {
if (synchronousFinal) transcript(synchronousFinal, true);
return deferred ? completion : undefined;
} },
sendTargets: [{ id: 'send', label: 'Send', onSend: text => sent.push(text) }],
});
layer.startCapture();
return { layer, sent, refinements, transcript, starts: () => starts,
input: type => layer.handleInput({ type }, {}),
frame() { layer.paint({}, () => ({})); return frame; },
timeout() { for (const [id, cb] of [...timers]) { timers.delete(id); cb(); } },
async complete() { complete(); await completion; await Promise.resolve(); },
nextCapture() { completion = new Promise(resolve => { complete = resolve; }); },
timers: () => timers.size,
};
}
for (const partial of ['', 'Set a timer']) {
test(`auto-send waits for slow native recognition with ${partial ? 'a committed segment' : 'no partial'}`, async () => {
const env = dialog({ autoSend: true });
if (partial) env.transcript(partial);
env.layer.endCapture();
env.timeout(); // well beyond the old fallback deadline
assert.deepEqual(env.sent, []);
assert.equal(env.timers(), 0);
env.transcript('Set a timer for five minutes', true);
await env.complete(); env.timeout();
assert.deepEqual(env.sent, ['Set a timer for five minutes']);
assert.equal(env.timers(), 0);
});
}
async function continuation() {
const env = dialog();
env.layer.endCapture();
env.transcript('Set a timer for five minutes', true);
await env.complete();
env.nextCapture();
env.input('scroll-down'); env.input('click'); // Continue
env.input('click'); // stop follow-up
return env;
}
test('Continue refines the complete late result instead of appending an editing instruction', async () => {
const env = await continuation();
env.timeout();
assert.equal(env.refinements.length, 0);
env.transcript('Change five to ten', true);
await env.complete(); env.timeout();
assert.equal(env.refinements.length, 1);
assert.equal(env.refinements[0].original, 'Set a timer for five minutes');
assert.equal(env.refinements[0].followup, 'Change five to ten');
});
test('Send and Continue cannot consume partial text while native recognition is pending', async () => {
const env = dialog();
env.transcript('Set a timer'); env.layer.endCapture();
assert.equal(env.frame().status, 'Finishing transcription...');
env.input('click'); env.input('scroll-down'); env.input('click');
assert.deepEqual(env.sent, []);
assert.equal(env.starts(), 1);
env.transcript('Set a timer for five minutes', true); await env.complete();
env.input('scroll-up'); env.input('click');
assert.deepEqual(env.sent, ['Set a timer for five minutes']);
});
test('cancelling a pending continuation ignores its late transcript', async () => {
const env = await continuation();
env.input('double-click');
env.transcript('Change five to ten', true); await env.complete(); env.timeout();
assert.equal(env.refinements.length, 0);
assert.equal(env.frame().text, 'Set a timer for five minutes');
});
test('closing while native recognition is pending never schedules a fallback or sends', async () => {
const env = dialog({ autoSend: true });
env.layer.endCapture(); env.layer.onRemoved();
env.transcript('late', true); await env.complete(); env.timeout();
assert.deepEqual(env.sent, []);
assert.equal(env.timers(), 0);
});
test('failed or empty native captures return to the menu without sending', async () => {
const env = dialog({ autoSend: true });
env.layer.endCapture(); await env.complete(); env.timeout();
assert.deepEqual(env.sent, []);
assert.equal(env.frame().status, 'Send, continue, or discard?');
});
test('cloud fallback and a synchronous final still send exactly once', () => {
for (const synchronousFinal of [undefined, 'complete']) {
const env = dialog({ autoSend: true, deferred: false, synchronousFinal });
env.transcript('partial'); env.layer.endCapture(); env.timeout();
assert.deepEqual(env.sent, [synchronousFinal ?? 'partial']);
}
});
test('native completion is capture-specific, follows the final, and does not wait for shared capture', async () => {
let controller;
class Controller {
constructor() { controller = this; }
setListener(listener) { this.listener = listener; }
setCommunicator() {} setUsePhoneMic() {} setSaveRecordings() {} setEndpointing() {}
setNoiseSuppression() {} setBeamFilter() {} clearSpeakerVerification() {} setOnboardModelKind() {}
start(_mode, id) { this.captureId = id; this.active = true; }
stop() { this.active = false; }
isCapturing() { return this.active; }
}
const { FaceclawVoiceControlBridge } = load('app/native/voice-control.ts', {
'@nativescript/core': { Utils: { android: { getApplicationContext: () => ({}) } } },
'./speech-pause': { SpeechPauseDetector: class { reset() {} } },
}, { global: { isAndroid: true }, com: { faceclaw: { app: {
FaceclawVoiceController: Controller,
FaceclawVoiceControllerListener: function (listener) { return listener; },
} } } });
const bridge = new FaceclawVoiceControlBridge();
const options = { provider: 'onboard-whisper' };
const events = [];
bridge.onTranscript(event => events.push(event.text));
bridge.startPushToTalk(options);
const stopped = bridge.stopPushToTalk().then(() => events.push('stopped'));
controller.listener.onStopped(0); // an older raw/cloud capture's callback
await Promise.resolve(); assert.deepEqual(events, []);
controller.listener.onTranscript('complete', true);
assert.deepEqual(events, ['complete']);
controller.listener.onStopped(controller.captureId); await stopped;
assert.deepEqual(events, ['complete', 'stopped']);
bridge.startContinuousCapture(options); bridge.startPushToTalk(options);
assert.equal(bridge.stopPushToTalk(), undefined);
assert.equal(controller.active, true);
bridge.stopContinuousCapture(); controller.listener.onStopped(controller.captureId);
});