First iteration of glanceboard

This commit is contained in:
James Babcock committed 2026-09-11 10:47:19 -07:00
1 parent a3660fac61
commit 8a340fc4ad
36 files changed
+2874 -357

No files matched your search

+356
View File
@@ -0,0 +1,356 @@
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 () => {}, 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++; } }, 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('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));
}
}
});
+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');
});
+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;
}
`);
+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), /revision 0/);
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("", "", "")), "");
});
+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;
}
}
+59
View File
@@ -0,0 +1,59 @@
// 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/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, nudge,
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; },
};
};
+59
View File
@@ -0,0 +1,59 @@
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, long-press holds, 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("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);
assert.equal(glanceEventForGesture("short-then-long-press", true), null);
});
+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 });
}
});
+169
View File
@@ -0,0 +1,169 @@
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('tilt disables awards, objective progress, saver and drain bonus', () => {
const h = worker();
h.launchBall(h.w); target(h, 0);
h.nudge(h.w); h.nudge(h.w); h.nudge(h.w);
assert.equal(h.w.tilted, true);
lane(h, 0); target(h, 1);
h.w.ballX = 121; h.w.ballY = 110; h.collideBumpers(h.w);
assert.equal(h.w.score, 150);
assert.equal(h.w.targetsDown[1], false);
assert.ok(h.w.rolloverLit.every((value) => !value));
h.ballDrained(h.w);
assert.equal(h.w.ballsLeft, 2);
assert.equal(h.w.lastBonus, 0);
assert.equal(h.w.score, 150);
});
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 });
}
});
+1
View File
@@ -17,6 +17,7 @@
"../app/g2/even-advertisement.ts",
"../app/g2/glasses-artwork.ts",
"../app/g2/glasses-display-state.ts",
"../app/g2/glance-state.ts",
"../app/g2/pairing-candidates.ts",
"../app/apps/calculator/math/*.ts",
"../app/apps/microphones/mic-protocol.ts",