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

This commit is contained in:
James Babcock committed 2026-10-06 13:32:49 -07:00
commit e12cfaaf38
309 files changed
+15906 -3352

No files matched your search

+6 -2
View File
@@ -260,8 +260,12 @@ function shellEnv({ wakeAction = 'voice-input', skipConfirmation = false } = {})
'../../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 },
'./brightness-picker-layer': {}, './notification-modal-queue': load('app/ui/shell/notification-modal-queue.ts', {}),
'../../native/notification-icons': {}, '../../native/notification-sources': {},
'../../assistant/tool-registry': {}, './geometry': {
sidebarWidth: () => 64, minWindowTop: () => 96, switcherPosition: () => 'left', uiDepth: () => 0,
appViewportRect: () => ({ x: 64, y: 124, width: 576, height: 260 }),
},
});
const { createInProcessWindow } = load('app/ui/shell/in-process-window.ts', {
'../../graphics/image': images, '../../native/frame-timings': timings,
+475 -11
View File
@@ -14,6 +14,8 @@ function geometry() {
displayModeSetting: '576x288', verticalPositionSetting: 'middle',
navigateDisplayModeSetting: 'global', navigateVerticalPositionSetting: 'global',
terminalDisplayModeSetting: 'default', terminalVerticalPositionSetting: 'global',
appSwitcherPositionSetting: 'left', uiDepthSetting: '0', statusBarPositionSetting: 'top',
statusBarVisibilitySetting: 'always', windowBorderSetting: true,
}).map(([name, value]) => [name, { value, get() { return this.value; } }]));
const context = { exports: {}, require: (name) => {
if (name === '../../graphics/image') return { G2_LENS_WIDTH: 640, G2_LENS_HEIGHT: 480 };
@@ -65,23 +67,485 @@ test('Terminal can disable its tall default, inherit position or override both d
test('all explicit size/position combinations stay within the display and align content below the bar', () => {
const g = geometry();
for (const globalMode of ['576x288', '576x480', '640x480']) {
g.settings.displayModeSetting.value = globalMode;
for (const appId of ['navigate', 'terminal']) {
for (const mode of ['global', '576x288', '576x480', '640x480']) {
g.settings[`${appId}DisplayModeSetting`].value = mode;
for (const position of ['global', 'top', 'upper', 'middle', 'lower', 'bottom']) {
g.settings[`${appId}VerticalPositionSetting`].value = position;
const rect = g.rect('max', appId);
assert.equal(rect.x + rect.width, 640);
assert.equal(rect.y, g.windowTop('max', appId) + g.TOP_BAR_HEIGHT);
assert.ok(rect.y >= 28 && rect.y + rect.height <= 480);
const combos = [['left', 'top'], ['right', 'top'], ['bottom', 'top'], ['bottom', 'bottom'], ['left', 'bottom']];
for (const statusBar of ['top', 'bottom']) {
for (const visibility of ['always', 'switcher']) {
for (const border of [true, false]) combos.push(['popup', statusBar, visibility, border]);
}
}
for (const [switcher, statusBar, visibility = 'always', border = true] of combos) {
g.settings.appSwitcherPositionSetting.value = switcher;
g.settings.statusBarPositionSetting.value = statusBar;
g.settings.statusBarVisibilitySetting.value = visibility;
g.settings.windowBorderSetting.value = border;
for (const globalMode of ['576x288', '576x480', '640x480']) {
g.settings.displayModeSetting.value = globalMode;
for (const appId of ['navigate', 'terminal']) {
for (const mode of ['global', '576x288', '576x480', '640x480']) {
g.settings[`${appId}DisplayModeSetting`].value = mode;
for (const position of ['global', 'top', 'upper', 'middle', 'lower', 'bottom']) {
g.settings[`${appId}VerticalPositionSetting`].value = position;
for (const heightMode of ['min', 'medium', 'max']) {
const rect = g.rect(heightMode, appId);
const fullPanel = g.displayMode(appId) === '640x480';
assert.equal(rect.x + rect.width, fullPanel ? 640 : { left: 640, right: 576, bottom: 608, popup: 608 }[switcher]);
const header = g.windowHeaderHeight(appId), footer = g.windowFooterHeight(appId);
assert.equal(g.statusInSwitcherRow(appId), statusBar === 'bottom' && g.switcherRowHeight(appId) > 0);
if (switcher === 'popup') {
// Each edge has the status bar's rows (unless it only
// overlays), else the frame's side, else nothing.
assert.equal(g.windowFramed(appId), border && !fullPanel);
const edge = (side) => visibility === 'always' && statusBar === side ? g.TOP_BAR_HEIGHT : g.windowFramed(appId) ? 1 : 0;
assert.deepEqual([header, footer], [edge('top'), edge('bottom')]);
// The status bar's rows lie within the band, at its edge.
const top = g.windowTop(heightMode, appId), band = g.windowBandHeight(heightMode, appId);
assert.equal(g.statusBarTop(heightMode, appId), statusBar === 'top' ? top : top + band - g.TOP_BAR_HEIGHT);
} else {
assert.deepEqual([header, footer], [g.statusInSwitcherRow(appId) ? 1 : g.TOP_BAR_HEIGHT, 0]);
}
assert.equal(rect.y, g.windowTop(heightMode, appId) + header);
assert.equal(rect.height + header + footer, g.windowBandHeight(heightMode, appId));
assert.ok(rect.y >= header && rect.y + rect.height + footer <= 480 - g.switcherRowHeight(appId));
const row = g.switcherRect(heightMode, appId);
assert.ok(row.y + row.height <= 480);
// A reserved bottom row hangs right under the window, as wide as it.
if (g.switcherRowHeight(appId)) assert.deepEqual([row.x, row.y, row.width], [rect.x, rect.y + rect.height, rect.width]);
// The frame's sides, just outside the window, survive the
// deepest shift (±62 moves each lens 31px).
if (g.windowFramed(appId)) assert.ok(rect.x - 1 - 31 >= 0 && rect.x + rect.width + 31 < 640);
}
}
}
}
}
}
});
test('the app switcher can sit on the right edge', () => {
const g = geometry();
g.settings.appSwitcherPositionSetting.value = 'right';
assert.deepEqual(g.rect('min'), { x: 0, y: 124, width: 576, height: 260 });
assert.deepEqual({ ...g.switcherRect('max') }, { x: 576, y: 96, width: 64, height: 288 });
assert.equal(g.screenCenterInViewportX(), 320);
assert.equal(g.isOnSwitcherEdge(600, 10, 'min'), true);
assert.equal(g.isOnSwitcherEdge(10, 200, 'min'), false);
assert.equal(g.windowFramed(), false);
// Depth needs the bottom row's side margins.
g.settings.uiDepthSetting.value = '32';
assert.equal(g.uiDepth(), 0);
g.settings.displayModeSetting.value = '640x480';
assert.deepEqual(g.rect('max'), { x: 0, y: 28, width: 640, height: 452 });
});
test('a popup app switcher centres 576-wide windows, whose edges the status bar and frame decide', () => {
const g = geometry();
g.settings.appSwitcherPositionSetting.value = 'popup';
// Nothing is reserved for the switcher: it shows only while focused, and
// is modal while it does.
assert.equal(g.sidebarStripVisible('window'), false);
assert.equal(g.sidebarStripVisible('sidebar'), true);
assert.equal(g.isOnSwitcherEdge(5, 5, 'min'), true);
assert.equal(g.screenCenterInViewportX(), 288);
g.settings.uiDepthSetting.value = '-48';
assert.equal(g.uiDepth(), -48);
// The top bar above the content and the frame's bottom side below it.
assert.equal(g.windowFramed(), true);
assert.deepEqual(g.rect('min'), { x: 32, y: 124, width: 576, height: 259 });
assert.deepEqual(g.rect('medium'), { x: 32, y: 110, width: 576, height: 288 });
assert.deepEqual(g.rect('max', 'terminal'), { x: 32, y: 28, width: 576, height: 451 });
// At the bottom, the bar takes the band's last rows, and the frame's top a row of its own.
g.settings.statusBarPositionSetting.value = 'bottom';
assert.deepEqual(g.rect('min'), { x: 32, y: 97, width: 576, height: 259 });
assert.equal(g.statusBarTop('min'), 356);
// Shown only in the switcher, the bar overlays the content, which grows into its rows.
g.settings.statusBarVisibilitySetting.value = 'switcher';
assert.deepEqual(g.rect('min'), { x: 32, y: 97, width: 576, height: 286 });
assert.deepEqual(g.rect('max', 'terminal'), { x: 32, y: 1, width: 576, height: 478 });
assert.equal(g.statusBarTop('min'), 356);
// Without the frame too, windows have no chrome rows at all.
g.settings.windowBorderSetting.value = false;
assert.equal(g.windowFramed(), false);
assert.deepEqual(g.rect('max', 'terminal'), { x: 32, y: 0, width: 576, height: 480 });
assert.deepEqual(g.rect('medium'), { x: 32, y: 96, width: 576, height: 288 });
// Full panel: the status bar keeps its edge, but there's no room for a frame.
g.settings.windowBorderSetting.value = true;
g.settings.statusBarVisibilitySetting.value = 'always';
g.settings.displayModeSetting.value = '640x480';
assert.equal(g.windowFramed(), false);
assert.deepEqual(g.rect('max'), { x: 0, y: 0, width: 640, height: 452 });
assert.equal(g.statusBarTop('max'), 452);
});
test('a bottom app switcher centres 576-wide windows and hangs one tall tab under them', () => {
const g = geometry();
g.settings.appSwitcherPositionSetting.value = 'bottom';
assert.equal(g.SWITCHER_ROW_HEIGHT, 36);
assert.deepEqual(g.rect('max', 'terminal'), { x: 32, y: 28, width: 576, height: 416 });
assert.deepEqual({ ...g.switcherRect('max', 'terminal') }, { x: 32, y: 444, width: 576, height: 36 });
// Band and row share the slack: no gap under a band shorter than the screen.
assert.deepEqual(g.rect('min'), { x: 32, y: 106, width: 576, height: 260 });
assert.deepEqual({ ...g.switcherRect('min') }, { x: 32, y: 366, width: 576, height: 36 });
assert.equal(g.isOnSwitcherEdge(10, 370, 'min'), true);
assert.equal(g.isOnSwitcherEdge(10, 360, 'min'), false);
g.settings.verticalPositionSetting.value = 'bottom';
assert.equal(g.switcherRect('min').y, 444);
// The true centre is the viewport's own with the window centred.
assert.equal(g.screenCenterInViewportX(), 288);
// Depth applies only here, as does the window frame.
g.settings.uiDepthSetting.value = '-48';
assert.equal(g.uiDepth(), -48);
assert.equal(g.windowFramed(), true);
// Full panel: windows fill the panel and the row overlays the bottom edge while focused.
g.settings.displayModeSetting.value = '640x480';
assert.deepEqual(g.rect('max'), { x: 0, y: 28, width: 640, height: 452 });
assert.deepEqual({ ...g.switcherRect('max') }, { x: 0, y: 444, width: 640, height: 36 });
assert.equal(g.sidebarStripVisible('window'), false);
assert.equal(g.sidebarStripVisible('sidebar'), true);
assert.equal(g.windowFramed(), false);
});
// The real chrome layer over the given geometry, with platform pieces stubbed:
// a 4px-per-character font that paints each character as a 2x6 block, up to
// `notifications` 24px notification icons (keyed n0, n1, ...), and a phone
// battery at 80%.
const graphics = require('../.test-build/app/graphics/image.js');
const shellScene = require('../.test-build/app/graphics/shell-scene.js');
const displayList = require('../.test-build/app/graphics/display-list.js');
function chromeLayer(g, { notifications = 0, phoneBattery = null, windows = 1, trayIcons = [] } = {}) {
const font = { lineHeight: 12, ascent: 10, measureText: (text) => text.length * 4,
drawText: (image, x, y, text, value) => { for (let i = 0; i < text.length; i++) image.fillRect(x + i * 4, y + 2, 2, 6, value); } };
let nextKey = 100;
const requested = [];
const settings = { get: () => 'always' };
const modules = {
'../../graphics/shell-scene': shellScene, '../../graphics/image': graphics,
'../../graphics/display-list': displayList, '../../graphics/ui-fonts': { getDefaultSmallFont: () => font, getDefaultMediumFont: () => font },
'../../graphics/textwrap': require('../.test-build/app/graphics/textwrap.js'),
'../../graphics/battery': require('../.test-build/app/graphics/battery.js'),
'./ambient-cards': { activeAmbientCards: () => [] },
'../../native/notification-icons': { readActiveNotificationIcons: (max) => {
requested.push(max);
const count = Math.min(max, notifications);
return { icons: Array.from({ length: count }, () => new graphics.GrayImage(24, 24, 200)),
keys: Array.from({ length: count }, (_, index) => `n${index}`), stale: false };
} },
'../../native/phone-battery': { readPhoneBatteryState: () => ({ battery: phoneBattery, charging: false }) },
'../../util/render-freshness': { renderPassAllowsStaleData: () => false },
'../dashboard-settings': { batteryDisplayModeSetting: { get: () => 'icon' }, phoneBatteryVisibilitySetting: settings,
batteryIndicatorVisible: () => true },
'../clock-format': { formatClockDate: () => 'Thu Oct 2', formatClockTime: () => '9:41' },
'../layers': { LayerStack: { allocateShellKey: () => nextKey++ } },
// As in menu.ts.
'../menu': { scrollToKeepSelectionVisible: (scroll, selected, visible, count) => Math.min(Math.max(0, count - visible),
Math.max(0, selected < scroll ? selected : selected >= scroll + visible ? selected - visible + 1 : scroll)) },
'./geometry': g,
};
const context = { exports: {}, require: (name) => modules[name] ?? {} };
vm.runInNewContext(js(read('app/ui/shell/chrome-layer.ts')), context);
const state = {
windows: Array.from({ length: windows }, (_, i) => ({ title: `Window ${i}`, attention: false,
drawIcon: (image, x, y, size) => image.fillRect(x, y, size, size, 120) })),
selectedIndex: 0, focus: 'window', foregroundHeightMode: 'min',
battery: { headset: null, ring: null, watch: null }, trayIcons,
};
return { chrome: new context.exports.ShellChromeLayer(() => state), state, requested };
}
test('a bottom app switcher frames the foreground window\'s content in a rounded border', () => {
const g = geometry();
g.settings.appSwitcherPositionSetting.value = 'bottom';
g.settings.uiDepthSetting.value = '62';
// The second window is selected: the first's (see the launcher test below)
// would square the bottom-left corner.
const { chrome, state } = chromeLayer(g, { windows: 2 });
state.selectedIndex = 1;
const parts = chrome.paintParts();
// Just the top bar and then the row: the frame is no surface of its own.
const part = (key) => parts.find((p) => p.shellKey === key);
const [bar, strip] = [part(2), part(1)];
assert.deepEqual(Array.from(parts, (p) => p.shellKey), [2, 1]);
// The min band's content spans y=106..365, between the bar's bottom row
// (the frame's top) at 105 and the row's top edge (its bottom) at 366. The
// frame is one rounded rect riding on the row, replayed after the bar.
const frames = (image) => image.draws.filter((d) => d.presentation?.displayList);
const [frame] = frames(strip.image);
assert.deepEqual([strip.x + frame.x, strip.y + frame.y, frame.source.width, frame.source.height, frame.presentation.depth], [31, 105, 578, 262, 0]);
assert.deepEqual(JSON.parse(JSON.stringify(frame.presentation.displayList.calls)), [{ op: displayList.DrawOp.ROUNDED_RECT, x: 0, y: 0, width: 578, height: 262,
radius: 8, background: 0, border: 3, outside: 0, clip: { x: 0, y: 0, width: 578, height: 261 } }]);
// Over a lit screen: the sides just outside the window, the top along the
// bar's bottom row, the content's corners cut black, its interior left
// alone, and the bottom row left to the separator.
const lit = new Uint8Array(640 * 480).fill(255);
displayList.paintDisplayList(lit, lit.slice(), 640, 480, { displayList: frame.presentation.displayList,
x: strip.x + frame.x, y: strip.y + frame.y, width: 578, height: 262, depth: 0 });
const px = (x, y) => lit[y * 640 + x];
assert.deepEqual([px(31, 200), px(608, 200), px(300, 105)], [48, 48, 48]);
assert.deepEqual([px(31, 105), px(32, 106), px(32, 365), px(607, 365)], [0, 0, 0, 0]);
assert.deepEqual([px(36, 105), px(300, 200), px(300, 366), px(36, 366)], [48, 255, 255, 255]);
const at = (p, x, y) => p.image.pixels[(y - p.y) * p.image.width + x - p.x];
// The separator is the bottom side, starting where the corner's curve ends.
assert.deepEqual([at(strip, 35, 366), at(strip, 36, 366), at(strip, 603, 366), at(strip, 604, 366)], [1, 40, 40, 1]);
// The bar's own divider gives way to the frame's top.
assert.equal(at(bar, 300, 105), 1);
shellScene.encodeShellScene(parts, g.uiDepth());
// The flat paint carries the same frame.
const image = chrome.paint();
assert.deepEqual(frames(image).map((d) => [d.x, d.y]), [[31, 105]]);
// No frame in the full-panel mode.
g.settings.displayModeSetting.value = '640x480';
assert.equal(chrome.paintParts().flatMap((p) => frames(p.image)).length, 0);
});
test('the launcher\'s tab lines up with the window frame, whose corner squares to meet it', () => {
const g = geometry();
g.settings.appSwitcherPositionSetting.value = 'bottom';
const paint = (chrome) => {
const [, strip] = chrome.paintParts();
const [frame] = strip.image.draws.filter((d) => d.presentation?.displayList);
const lit = new Uint8Array(640 * 480).fill(255);
displayList.paintDisplayList(lit, lit.slice(), 640, 480, { displayList: frame.presentation.displayList,
x: strip.x + frame.x, y: strip.y + frame.y, width: frame.source.width, height: frame.source.height, depth: 0 });
return { strip, px: (x, y) => lit[y * 640 + x], at: (x, y) => strip.image.pixels[(y - strip.y) * strip.image.width + x - strip.x] };
};
const { chrome, state } = chromeLayer(g, { windows: 3 });
// The first cell starts at the frame's left side (x=31), one pixel outside
// the window, so the row's surface spans the frame.
let { strip, px, at } = paint(chrome);
assert.deepEqual([strip.x, strip.image.width], [31, 578]);
assert.deepEqual([chrome.windowIndexAt(31, 380, 3), chrome.windowIndexAt(30, 380, 3), chrome.windowIndexAt(71, 380, 3)], [0, null, 1]);
// Selected, its tab's outline continues the frame's left side straight
// down: the corner is square and the content's corner whole.
assert.deepEqual([px(31, 360), px(31, 365), px(32, 365)], [48, 48, 255]);
assert.deepEqual([at(31, 366), at(31, 370)], [150, 150]);
// Focused, the tab fills from the side.
state.focus = 'sidebar';
({ at } = paint(chrome));
assert.equal(at(31, 370), 255);
// With another window selected the corner rounds again, and the separator
// starts where its curve ends; the launcher's cell stays at the side.
state.focus = 'window'; state.selectedIndex = 1;
({ px, at } = paint(chrome));
assert.deepEqual([px(31, 365), px(32, 365), at(35, 366), at(36, 366)], [0, 0, 1, 40]);
assert.equal(chrome.windowIndexAt(31, 380, 3), 0);
// Scrolled past the launcher, the cells keep the left chevron's margin.
const scrolled = chromeLayer(g, { windows: 20 });
scrolled.state.selectedIndex = 19;
({ px } = paint(scrolled.chrome));
assert.equal(scrolled.chrome.windowIndexAt(35, 380, 20), null);
assert.notEqual(scrolled.chrome.windowIndexAt(41, 380, 20), null);
assert.equal(px(31, 365), 0);
});
test('the status bar can join a bottom app switcher, and windows grow into the top bar', () => {
const g = geometry();
g.settings.statusBarPositionSetting.value = 'bottom';
// Only beside a reserved bottom row.
assert.equal(g.statusInSwitcherRow(), false);
g.settings.appSwitcherPositionSetting.value = 'bottom';
assert.equal(g.statusInSwitcherRow(), true);
// A one-row header (the frame's top) replaces the 28px top bar; medium
// windows keep a 288px (EvenHub) content area.
assert.equal(g.windowHeaderHeight(), 1);
assert.deepEqual(g.rect('min'), { x: 32, y: 79, width: 576, height: 287 });
assert.deepEqual(g.rect('medium'), { x: 32, y: 79, width: 576, height: 288 });
assert.deepEqual(g.rect('max', 'terminal'), { x: 32, y: 1, width: 576, height: 443 });
assert.deepEqual({ ...g.switcherRect('min') }, { x: 32, y: 366, width: 576, height: 36 });
// The full-panel mode keeps the top bar: its row shows only while focused.
g.settings.displayModeSetting.value = '640x480';
assert.equal(g.statusInSwitcherRow(), false);
assert.deepEqual(g.rect('max'), { x: 0, y: 28, width: 640, height: 452 });
});
test('the switcher row lays out windows, free space, notifications, widgets, batteries and the clock', () => {
const g = geometry();
g.settings.appSwitcherPositionSetting.value = 'bottom';
g.settings.statusBarPositionSetting.value = 'bottom';
const tray = new graphics.GrayImage(30, 20, 180);
const { chrome, requested } = chromeLayer(g, { notifications: 2, phoneBattery: 80, trayIcons: [tray] });
const parts = chrome.paintParts();
// No top bar: the row, then the status bar on the top bar's surface and depth.
assert.deepEqual(Array.from(parts, (p) => [p.shellKey, p.depth ?? 0]), [[1, 0], [2, -2]]);
const [row, status] = parts;
// Right to left from the row's end (x=608), centred under its separator
// line (y=366): "Thu Oct 2 9:41" (56px) flush with it; the battery block (label
// 20 + gap 5 + gauge 21) 16px before it; the 30px widget 10px before that;
// then the two notification icons, 8px clear of the widget. The surface
// starts 2px before them, room for a selection box round the first.
const clockX = 608 - 56, batteryLeft = clockX - 16 - 46, trayLeft = batteryLeft - 40, iconsLeft = trayLeft - 8 - 56 + 4;
assert.deepEqual([status.x, status.y, status.image.width, status.image.height], [iconsLeft - 2, 367, 608 - iconsLeft + 2, 35]);
const at = (p, x, y) => p.image.withDrawsBaked().pixels[(y - p.y) * p.image.width + x - p.x];
// The clock's text runs 8 rows down the top bar's layout, which sits 5 rows into the row.
assert.deepEqual([at(status, clockX, 366 + 5 + 8 + 2), at(status, trayLeft, 366 + 5 + 4), at(status, iconsLeft, 366 + 5 + 2)], [210, 180, 200]);
assert.equal(at(status, batteryLeft, 366 + 5 + 8 + 2), 150, 'battery label');
// Windows take what the status bar leaves; the rest is free space.
assert.equal(at(row, 40 + 2, 366 + 2), 120, 'first window icon');
assert.equal(chrome.windowIndexAt(45, 380, 1), 0);
assert.equal(chrome.windowIndexAt(iconsLeft + 2, 380, 1), null);
// Notification icons stop short of the one window slot's room (with the
// row's margins and the gap to the status bar).
assert.equal(requested.at(-1), Math.floor((trayLeft - 8 - (32 + 20 + 40 - 8 + 8) + 4) / 28));
// No top bar, but the frame is still there, its top one row above the content.
const [frame] = row.image.draws.filter((d) => d.presentation?.displayList);
assert.deepEqual([row.x + frame.x, row.y + frame.y, frame.source.height], [31, 78, 289]);
shellScene.encodeShellScene(parts, g.uiDepth());
});
test('many windows scroll in what the notification icons leave them', () => {
const g = geometry();
g.settings.appSwitcherPositionSetting.value = 'bottom';
g.settings.statusBarPositionSetting.value = 'bottom';
const { chrome, requested } = chromeLayer(g, { notifications: 40, windows: 12 });
const [row, status] = chrome.paintParts();
// Clock only (no batteries or widgets): notifications end 8px before its
// 8px lead-in, and stop where three window slots plus margins remain.
const trayLeft = 608 - 56 - 8, floor = 32 + 20 + 3 * 40 - 8 + 8;
const max = Math.floor((trayLeft - 8 - floor + 4) / 28);
assert.equal(requested.at(-1), max);
const iconsLeft = trayLeft - 8 - max * 28 + 4;
assert.equal(status.x, iconsLeft - 2);
// Three windows fit before the status bar's gap; the rest scroll, with the
// chevron at the end of the windows rather than of the row.
assert.equal(chrome.windowIndexAt(32 + 10 + 2 * 40 + 4, 380, 12), 2);
assert.equal(chrome.windowIndexAt(32 + 10 + 3 * 40 + 4, 380, 12), null);
const windowsRight = iconsLeft - 8;
const chevron = row.image.pixels.findIndex((v, i) => v === 140);
assert.equal(chevron % row.image.width + row.x, windowsRight - 6);
});
test('a popup app switcher shows a box of window icons over the dimmed window while focused', () => {
const g = geometry();
g.settings.appSwitcherPositionSetting.value = 'popup';
const { chrome, state } = chromeLayer(g, { windows: 3 });
const summary = (parts) => Array.from(parts, (p) => [p.shellKey, p.depth ?? 0, p.dimUnderneath ?? 1]);
const at = (p, x, y) => p.image.pixels[(y - p.y) * p.image.width + x - p.x];
// In the window: the top bar, then the frame, which rides on a pixel of
// its own at its top-left corner (outside its curve).
let parts = chrome.paintParts();
assert.deepEqual(summary(parts), [[2, -2, 1], [1, 0, 1]]);
const [bar, carrier] = parts;
assert.deepEqual([carrier.x, carrier.y, carrier.image.width, carrier.image.height], [31, 123, 1, 1]);
// The whole rounded rect, from the bar's last row (in place of its
// divider) round the content (32,124 576×259) to the footer row under it.
const [frame] = carrier.image.draws.filter((d) => d.presentation?.displayList);
assert.deepEqual([carrier.x + frame.x, carrier.y + frame.y, frame.presentation.depth], [31, 123, 0]);
assert.deepEqual(JSON.parse(JSON.stringify(frame.presentation.displayList.calls)), [{ op: displayList.DrawOp.ROUNDED_RECT,
x: 0, y: 0, width: 578, height: 261, radius: 8, background: 0, border: 3, outside: 0 }]);
assert.equal(at(bar, 300, 123), 1);
// Focused: the box, nearer than the window, last. Its dim rides on the
// first part, so it dims the windows and none of the chrome.
state.focus = 'sidebar';
parts = chrome.paintParts();
assert.deepEqual(summary(parts), [[2, -2, 0.5], [1, 0, 1], [100, 4, 1]]);
const encoded = shellScene.encodeShellScene(parts, g.uiDepth());
assert.equal(new DataView(encoded.buffer).getUint16(12, true), 128, 'first layer dims to half');
// Three 44px cells 4px apart, in the minimum 272px width, centred over the
// content; 12px padding round the cells and the 12px title line under them.
let popup = parts[2];
assert.deepEqual([popup.x, popup.y, popup.image.width, popup.image.height], [184, 210, 272, 86]);
assert.equal(at(popup, 184, 210), 72, 'border');
// The selected (first) cell is filled white around its icon; the others'
// icons are depth images of their own over the black box.
assert.deepEqual([at(popup, 252, 240), at(popup, 260, 240), at(popup, 310, 240)], [255, 120, 1]);
assert.deepEqual(popup.image.draws.filter((d) => d.presentation).map((d) => [popup.x + d.x, popup.y + d.y]), [[304, 227], [352, 227]]);
// The selected window's title, centred under the icons.
assert.equal(at(popup, 184 + (272 - 32) / 2, 222 + 44 + 6 + 2), 210);
assert.deepEqual([chrome.windowIndexAt(260, 240, 3), chrome.windowIndexAt(300, 240, 3), chrome.windowIndexAt(296, 240, 3),
chrome.windowIndexAt(10, 10, 3)], [0, 1, null, null]);
// The flat paint shows it too.
assert.equal(chrome.paint().pixels[210 * 640 + 184], 72);
// Many windows scroll, with a chevron at either end of the icons.
const many = chromeLayer(g, { windows: 20 });
many.state.focus = 'sidebar';
many.state.selectedIndex = 15;
popup = many.chrome.paintParts()[2];
assert.deepEqual([popup.x, popup.image.width], [58, 524]);
assert.equal(many.chrome.windowIndexAt(90, 240, 20), 6);
assert.deepEqual([at(popup, 74, 244), at(popup, 565, 244)], [140, 140]);
});
test('a popup switcher\'s status bar can sit at the bottom, show only in the switcher, or go without the frame', () => {
const g = geometry();
g.settings.appSwitcherPositionSetting.value = 'popup';
g.settings.statusBarVisibilitySetting.value = 'switcher';
const { chrome, state } = chromeLayer(g);
const at = (p, x, y) => p.image.pixels[(y - p.y) * p.image.width + x - p.x];
// Outside the switcher there's only the frame.
assert.deepEqual(Array.from(chrome.paintParts(), (p) => p.shellKey), [1]);
// In it, the bar overlays the content's top inside the frame, whose top
// runs along the bar's first row, so it keeps its divider on its last.
state.focus = 'sidebar';
let [bar, carrier] = chrome.paintParts();
assert.deepEqual([bar.x, bar.y, bar.image.width, bar.image.height, carrier.y], [32, 96, 576, 28, 96]);
assert.equal(at(bar, 300, 123), 40);
// At the bottom, its divider is its first row, and the frame's bottom its last.
g.settings.statusBarPositionSetting.value = 'bottom';
[bar] = chrome.paintParts();
assert.deepEqual([bar.y, at(bar, 300, 356), at(bar, 300, 383)], [356, 40, 1]);
// Always shown without a frame, a divider still separates bar and window.
g.settings.statusBarVisibilitySetting.value = 'always';
g.settings.windowBorderSetting.value = false;
state.focus = 'window';
const parts = chrome.paintParts();
assert.deepEqual(Array.from(parts, (p) => p.shellKey), [2]);
assert.deepEqual([parts[0].y, at(parts[0], 300, 356)], [356, 40]);
g.settings.statusBarPositionSetting.value = 'top';
[bar] = chrome.paintParts();
assert.deepEqual([bar.y, at(bar, 300, 123)], [96, 40]);
});
test('a notification the switcher selects sits in a box, filled with its icon inverted while the switcher has focus', () => {
const g = geometry();
g.settings.appSwitcherPositionSetting.value = 'bottom';
g.settings.statusBarPositionSetting.value = 'bottom';
const { chrome, state } = chromeLayer(g, { notifications: 3, windows: 2 });
Object.assign(state, { selectedIndex: -1, selectedNotificationKey: 'n1', focus: 'sidebar' });
let [row, status] = chrome.paintParts();
assert.deepEqual(Array.from(chrome.notificationKeys()), ['n0', 'n1', 'n2']);
// Clock only: the icons end 8px before its 8px lead-in, 28px apart, each
// 7 rows into the row (the top bar's layout, 5 rows down).
const iconsLeft = 608 - 56 - 8 - 8 - 3 * 28 + 4, iconY = 366 + 7, n1 = iconsLeft + 28;
const at = (p, x, y) => p.image.withDrawsBaked().pixels[(y - p.y) * p.image.width + x - p.x];
// The box: 2px either side of the icon, 1px above and below, white; the
// icon inside it inverted; its neighbours as ever.
assert.deepEqual([at(status, n1 - 2, iconY + 12), at(status, n1 + 25, iconY + 12), at(status, n1 + 12, iconY - 1)], [255, 255, 255]);
assert.equal(at(status, n1 + 12, iconY - 2), 1);
assert.deepEqual([at(status, n1 + 5, iconY + 5), at(status, iconsLeft + 5, iconY + 5)], [55, 200]);
// No window is selected: the separator runs unbroken over the windows.
assert.equal(at(row, 50, 366), 40);
// Mirror touches find the icons by their boxes, which tile the icons' run.
assert.deepEqual([chrome.notificationKeyAt(n1 + 5, 380), chrome.notificationKeyAt(n1 - 3, 380),
chrome.notificationKeyAt(iconsLeft - 3, 380), chrome.notificationKeyAt(n1 + 5, 400)], ['n1', 'n0', null, null]);
// With its detail view focused instead, the box is an outline round the plain icon.
state.focus = 'window';
[, status] = chrome.paintParts();
assert.deepEqual([at(status, n1 - 2, iconY + 12), at(status, n1 - 1, iconY + 12), at(status, n1 + 5, iconY + 5)], [150, 1, 200]);
// The first icon's box fits the status bar's surface.
state.selectedNotificationKey = 'n0';
[, status] = chrome.paintParts();
assert.equal(at(status, iconsLeft - 2, iconY + 12), 150);
// In the top bar (the status bar's default place) likewise; barTop=78.
g.settings.statusBarPositionSetting.value = 'top';
const [bar] = chrome.paintParts();
const barIconsLeft = 32 + 10 + 56 + 16;
assert.deepEqual(Array.from(chrome.notificationKeys()), ['n0', 'n1', 'n2']);
assert.deepEqual([at(bar, barIconsLeft - 2, 78 + 14), at(bar, barIconsLeft + 5, 78 + 7)], [150, 200]);
assert.equal(chrome.notificationKeyAt(barIconsLeft + 30, 78 + 10), 'n1');
});
test('with the selection out on a notification, the windows stay scrolled as they were', () => {
const g = geometry();
g.settings.appSwitcherPositionSetting.value = 'bottom';
const { chrome, state } = chromeLayer(g, { notifications: 2, windows: 20 });
state.selectedIndex = 19;
chrome.paintParts();
const last = 32 + 10 + 2 * 40 + 4;
const before = chrome.windowIndexAt(last, 380, 20);
assert.ok(before > 2);
Object.assign(state, { selectedIndex: -1, selectedNotificationKey: 'n0' });
chrome.paintParts();
assert.equal(chrome.windowIndexAt(last, 380, 20), before);
});
// Exercise the real worker message handler with platform work stubbed out.
function resizeHandler(file, globals) {
const source = ts.createSourceFile(file, read(file), ts.ScriptTarget.Latest, true);
+19
View File
@@ -0,0 +1,19 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { imageFromAsciiArt } = require('../.test-build/app/graphics/image.js');
test('imageFromAsciiArt maps characters through the palette', () => {
const image = imageFromAsciiArt(['#/.', ' _#'], { '#': 255, '/': 128, '_': 64 });
assert.equal(image.width, 3);
assert.equal(image.height, 2);
assert.deepEqual([...image.pixels], [255, 128, 0, 0, 64, 255]);
});
test('imageFromAsciiArt pads short lines and lets the palette override the background', () => {
const image = imageFromAsciiArt(['.#', '.'], { '#': 300, '.': 10 });
assert.deepEqual([...image.pixels], [10, 255, 10, 0]);
});
test('imageFromAsciiArt rejects characters missing from the palette', () => {
assert.throws(() => imageFromAsciiArt(['#x'], { '#': 255 }), /"x"/);
});
+4 -3
View File
@@ -25,6 +25,7 @@ function settingsFixture(store = new Map()) {
getBooleanSetting: (k, d) => store.get(k) ?? d, setBooleanSetting: (k, v) => store.set(k, v),
};
if (id.includes('brightness-curve')) return require('../.test-build/app/g2/brightness-curve.js');
if (id.includes('animation-speed')) return require('../.test-build/app/ui/animation-speed.js');
return { Layer: class {}, ASSISTANT_MODEL_CHOICES: [] };
}};
vm.runInNewContext(ts.transpileModule(fs.readFileSync('app/ui/dashboard-settings.ts', 'utf8'), {
@@ -36,11 +37,11 @@ test('auto minimum defaults to 20 and preserves a saved preference', () => {
assert.equal(settingsFixture().getBrightnessPreferences().minimum, 20);
assert.equal(settingsFixture(new Map([['display.autoBrightnessMin', '25']])).getBrightnessPreferences().minimum, 25);
});
test('the screen fade setting switches the on/off fade between 280 ms and instant', () => {
test('the screen fade speed scales the 280 ms on/off fade, or makes it instant', () => {
const api = settingsFixture();
assert.equal(api.getBrightnessPreferences().fadeMs, 280);
api.screenFadeSetting.set(false);
assert.equal(api.getBrightnessPreferences().fadeMs, 0);
const fadeAt = (speed) => { api.screenFadeSetting.set(speed); return api.getBrightnessPreferences().fadeMs; };
assert.deepEqual(['very-fast', 'fast', 'normal', 'slow', 'disabled'].map(fadeAt), [56, 140, 280, 560, 0]);
});
test('curve drafts preview exactly while brightness keeps the previous valid saved curve', () => {
const store = new Map([['display.autoBrightnessCurve', '0:0,2:50,8:100']]);
+2 -1
View File
@@ -27,7 +27,7 @@ const layers = load('app/ui/layers.ts', {
'../native/frame-timings': { spanCurrent: (_name, paint) => paint() },
});
const menu = load('app/ui/menu.ts', {
'./menu-animation-pref': require('../.test-build/app/ui/menu-animation-pref.js'), '../native/settings-store': { getBooleanSetting: (_key, fallback) => fallback },
'./menu-animation-pref': require('../.test-build/app/ui/menu-animation-pref.js'), './animation-speed': require('../.test-build/app/ui/animation-speed.js'), '../native/settings-store': { getStringSetting: (_key, fallback) => fallback },
'./menu-highlight-motion': require('../.test-build/app/ui/menu-highlight-motion.js'), '../graphics/menu-scroll-list': require('../.test-build/app/graphics/menu-scroll-list.js'), './menu-scroll-motion': require('../.test-build/app/ui/menu-scroll-motion.js'), '../graphics/draw-expression': require('../.test-build/app/graphics/draw-expression.js'),
'../graphics/image': graphics, '../graphics/ui-fonts': fonts, '../graphics/textwrap': textwrap,
'../util/numeric-util': numeric, './gestures': gestures, './metrics': load('app/ui/metrics.ts'),
@@ -114,6 +114,7 @@ test('system menu hides brightness in Auto and opens its picker between Voice in
'../../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 {} },
'./notification-modal-queue': load('app/ui/shell/notification-modal-queue.ts'),
});
shell.registerWindow({ windowId: 'test', appId: 'test', closeable: true, handleInput() {} });
shell.openSystemMenu('test');
+87
View File
@@ -0,0 +1,87 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { GrayImage } = require('../.test-build/app/graphics/image.js');
const {
BATTERY_ICON_WIDTH,
DENSE_BATTERY_BLOCK_HEIGHT,
drawBattery,
drawDenseBatteries,
} = require('../.test-build/app/graphics/battery.js');
const RIGHT = 120;
const TOP = 4;
const LOWER_ROW = DENSE_BATTERY_BLOCK_HEIGHT - drawBattery(0, false).height;
/** Every top-left position where exactly this gauge was drawn. */
function findGauges(image, percent, charging) {
const gauge = drawBattery(percent, charging);
const found = [];
for (let y = 0; y + gauge.height <= image.height; y++) {
for (let x = 0; x + gauge.width <= image.width; x++) {
let match = true;
for (let gy = 0; match && gy < gauge.height; gy++) {
for (let gx = 0; match && gx < gauge.width; gx++) {
match = image.pixels[(y + gy) * image.width + x + gx] === gauge.pixels[gy * gauge.width + gx];
}
}
if (match) found.push({ x, y });
}
}
return found;
}
function hasInk(image, x0, x1, y0, y1) {
for (let y = y0; y < y1; y++) {
for (let x = x0; x < x1; x++) {
if (image.pixels[y * image.width + x] > 0) return true;
}
}
return false;
}
function gaugeAt(image, percent, charging = false) {
const found = findGauges(image, percent, charging);
assert.equal(found.length, 1, `one ${percent}% gauge`);
return found[0];
}
test('dense batteries stack two per column, right-aligned', () => {
const image = new GrayImage(RIGHT + 8, 32, 0);
const left = drawDenseBatteries(image, [
{ device: 'phone', percent: 80, charging: false },
{ device: 'watch', percent: 35, charging: true },
{ device: 'glasses', percent: 60, charging: false },
{ device: 'ring', percent: 100, charging: false },
], RIGHT, TOP);
const phone = gaugeAt(image, 80);
const watch = gaugeAt(image, 35, true);
const glasses = gaugeAt(image, 60);
const ring = gaugeAt(image, 100);
assert.deepEqual(glasses, { x: RIGHT - BATTERY_ICON_WIDTH, y: TOP });
assert.deepEqual(ring, { x: RIGHT - BATTERY_ICON_WIDTH, y: TOP + LOWER_ROW });
assert.equal(phone.y, TOP);
assert.deepEqual(watch, { x: phone.x, y: TOP + LOWER_ROW });
// Each gauge has its device icon to its left.
assert.ok(hasInk(image, left, phone.x, TOP, TOP + 10));
assert.ok(hasInk(image, left, watch.x, TOP + LOWER_ROW, TOP + LOWER_ROW + 10));
assert.ok(hasInk(image, phone.x + BATTERY_ICON_WIDTH, glasses.x, TOP, TOP + 10));
assert.ok(hasInk(image, watch.x + BATTERY_ICON_WIDTH, ring.x, TOP + LOWER_ROW, TOP + LOWER_ROW + 10));
});
test('an odd count leaves the first indicator alone, vertically centered', () => {
const image = new GrayImage(RIGHT + 8, 32, 0);
drawDenseBatteries(image, [
{ device: 'phone', percent: 80, charging: false },
{ device: 'glasses', percent: 60, charging: false },
{ device: 'ring', percent: 20, charging: false },
], RIGHT, TOP);
assert.equal(gaugeAt(image, 80).y, TOP + LOWER_ROW / 2);
assert.deepEqual(gaugeAt(image, 60), { x: RIGHT - BATTERY_ICON_WIDTH, y: TOP });
assert.deepEqual(gaugeAt(image, 20), { x: RIGHT - BATTERY_ICON_WIDTH, y: TOP + LOWER_ROW });
});
test('no indicators draws nothing', () => {
const image = new GrayImage(RIGHT + 8, 32, 0);
assert.equal(drawDenseBatteries(image, [], RIGHT, TOP), RIGHT);
assert.ok(image.pixels.every((value) => value === 0));
});
+26 -2
View File
@@ -5,7 +5,7 @@ const { DrawOp, SCREEN, encodeDisplayList, readDisplayList, paintDisplayList } =
const { GrayImage } = require('../.test-build/app/graphics/image.js');
const { encodePresentation } = require('../.test-build/app/graphics/presentation-wire.js');
// Also consumed by FrameDisplayListTest.kt: bridge bytes, not independently rebuilt native calls.
const MENU = '077e0000000300020002000200022a00000096000000010002000200ffffffff0200080000ff24017e30020000000001812c8001812c1611010017328001812c16103001812c3023414031ff24017c30020000000001812c8001812c1611010017328001812c16103001812c302341403102000200010001030400000000000000001f';
const MENU = '077f0000000300020002000200022a00000096000000010002000200ffffffff0200080000ff24017e30020000000001812c8001812c1611010017328001812c16103001812c3023414031ff24017c30020000000001812c8001812c1611010017328001812c16103001812c30234140310200020001000103100400000000000000001f';
const MULTI = '0744000000030002000400010002000000000000000002000200010000ff010001006003000400000000000000001f0200000100000001000100020002feffffff7f00010001007f00';
test('extended integers agree with firmware widths and sign extension', () => {
@@ -90,9 +90,33 @@ test('frame submission supports resource-free lists and plain PRESENT-relative t
// the font and image ids it registers: a clipped clear, a clipped rounded rect,
// and replayed glyph + icon draws clipped while sliding up. REPLAY_PIXELS is
// what the list paints over a nibble-1 screen, 16x8 at 4 bits per pixel.
const REPLAY = '0780000000020003000800040000070000006400000000000300890000000000000600040002880000010001000200020000000400030000000510a00000000000000600040000ff2502000080c002000000000180c8800180c8161101001732800180c81610300180c830234031020000efbe4100000000000000ff01bebafeca04000100';
const REPLAY = '078100000002000300080004000007000000640000000000030089000000000000060004000288000001000100020002000000040003000000051010a00000000000000600040000ff2502000080c002000000000180c8800180c8161101001732800180c81610300180c830234031020000efbe4100000000000000ff01bebafeca04000100';
const REPLAY_PIXELS = '11111111111111111111111111111111111111111111111111fff28f111111111125522211111111112552221111111111222222111111111111111111111111';
// Also consumed by FrameDisplayListTest.kt: a window-frame rounded rect with no
// fill, a border of 3 and black outside the curve (revision 36), clipped short
// of its bottom row, and what it paints over a nibble-9 12x8 screen.
const FRAME = '072b00000002000100080006000000000000000000000000010088000000000000080005000000080006000300000300';
const FRAME_PIXELS = '999999999999990333333099993399993399993999999399993999999399993399993399999999999999999999999999';
test('a rounded rect outside color encodes, decodes and paints over the corners', () => {
const placed = { x: 2, y: 1, width: 8, height: 6, depth: 0, displayList: { resources: [], calls: [
{ op: DrawOp.ROUNDED_RECT, x: 0, y: 0, width: 8, height: 6, radius: 3, background: 0, border: 3, outside: 0, clip: { x: 0, y: 0, width: 8, height: 5 } },
] } };
assert.equal(Buffer.from(encodeDisplayList(placed, 0)).toString('hex'), FRAME);
const output = new Uint8Array(12 * 8).fill(9 * 16);
paintDisplayList(output, output.slice(), 12, 8, placed, false, 0);
assert.equal(Array.from(output, (v) => (v >> 4).toString(16)).join(''), FRAME_PIXELS);
const [rect] = readDisplayList(Buffer.from(FRAME, 'hex'), 0, 0).placed.displayList.calls;
assert.equal(rect.outside, 0);
// Without one, the call decodes without it and leaves the corners alone.
const plain = { ...placed, displayList: { resources: [], calls: [{ ...placed.displayList.calls[0], outside: undefined }] } };
assert.equal('outside' in readDisplayList(encodeDisplayList(plain, 0), 0, 0).placed.displayList.calls[0], false);
const corners = new Uint8Array(12 * 8).fill(9 * 16);
paintDisplayList(corners, corners.slice(), 12, 8, plain, false, 0);
assert.deepEqual([corners[12 + 2] >> 4, corners[12 + 5] >> 4], [9, 3]);
});
function replayList() {
// 'A' is 3x2 ink one row below a 4px line top; the icon is 2x2.
const font = { fingerprintId: 9001, atlasKey: 'stub-font', ascent: 3, lineHeight: 4 };
-15
View File
@@ -42,21 +42,6 @@ function paint(container, now, focused = true) {
const displayLists = (image) => image.draws.map((draw) => draw.presentation?.displayList).filter(Boolean);
const pixel = (image, x, y) => image.withDrawsBaked().pixels[y * image.width + x];
test("rows are padded 6px around the text; unselected text is at level 2/15", () => {
const rowHeight = listRowHeight(font);
assert.equal(rowHeight, 32);
const container = list(["ab", "cd"], 100);
const image = paint(container, 1000);
const textX = LIST_ITEM_PADDING_X, textY = LIST_ITEM_PADDING_Y + 4;
assert.equal(pixel(image, textX, textY), 255, "selected text is full brightness");
assert.equal(pixel(image, textX, rowHeight + textY), DESELECTED_TEXT, "unselected text is 2/15");
assert.equal(DESELECTED_TEXT + 8 >> 4, 2);
// The outline hugs the text plus padding, not the row width.
const outlineRight = 2 * 10 + 2 * LIST_ITEM_PADDING_X - 1;
assert.equal(pixel(image, outlineRight, rowHeight / 2), 255);
assert.equal(pixel(image, outlineRight + 2, rowHeight / 2), 0);
});
test("the unfocused outline is dimmer", () => {
const image = paint(list(["ab"], 100), 1000, false);
assert.equal(pixel(image, 0, 16), 130);
+77
View File
@@ -0,0 +1,77 @@
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 source = fs.readFileSync(path.join(__dirname, '../app/apps/evenhub/session.ts'), 'utf8');
const shim = source.match(/export const EVENHUB_BRIDGE_INJECT_SCRIPT = `([\s\S]*?)`;/)[1];
function page() {
const state = { now: 1000, wakes: 0, log: [] };
const win = {
Date: { now: () => state.now }, console, Map, Array, Math,
__faceclawEvenHub: { postMessage() {}, wakeTimers() { state.wakes++; } },
};
win.window = win;
win.performance = { now: () => state.now };
vm.createContext(win);
vm.runInContext(shim, win);
state.win = win;
state.tick = () => vm.runInContext('__fcTick()', win);
return state;
}
test('an idle page asks for no ticks, and its first timer wakes the host once', () => {
const p = page();
assert.equal(p.tick(), -1);
p.win.setTimeout(() => p.log.push('a'), 100);
p.win.setTimeout(() => p.log.push('b'), 200);
assert.equal(p.wakes, 1);
p.now += 5;
assert.equal(p.tick(), 95);
p.now += 95;
assert.equal(p.tick(), 100);
assert.deepEqual(p.log, ['a']);
p.now += 100;
assert.equal(p.tick(), -1);
assert.deepEqual(p.log, ['a', 'b']);
});
test('work due before the scheduled tick wakes the host; work added during a tick does not', () => {
const p = page();
p.win.setTimeout(() => {}, 500);
p.tick();
const wakes = p.wakes;
p.win.setTimeout(() => { p.win.setTimeout(() => p.log.push('inner'), 0); }, 10);
assert.equal(p.wakes, wakes + 1);
p.now += 10;
assert.equal(p.tick(), 16, 'the inner zero-delay timer runs next frame');
assert.equal(p.wakes, wakes + 1);
p.now += 16;
p.tick();
assert.deepEqual(p.log, ['inner']);
});
test('an animation-frame loop keeps the host at frame rate until it stops', () => {
const p = page();
let frames = 0;
const loop = () => { if (++frames < 3) p.win.requestAnimationFrame(loop); };
p.win.requestAnimationFrame(loop);
p.now += 16; assert.equal(p.tick(), 16);
p.now += 16; assert.equal(p.tick(), 16);
p.now += 16; assert.equal(p.tick(), -1);
assert.equal(frames, 3);
});
test('intervals keep cadence and the fixed-rate entry points still work', () => {
const p = page();
const id = p.win.setInterval(() => p.log.push('iv'), 50);
p.now += 50; assert.equal(p.tick(), 50);
p.now += 50; p.tick();
p.win.clearInterval(id);
assert.equal(p.tick(), -1);
p.win.setTimeout(() => p.log.push('legacy'), 0);
vm.runInContext('__fcTimerTick(); __fcRafTick()', p.win);
assert.deepEqual(p.log, ['iv', 'iv', 'legacy']);
});
-1
View File
@@ -65,7 +65,6 @@ test("stock firmware classifies by base version and warns on the main screen", (
assert.equal(compat.classifyOnboardingFirmware(info("", "2.2.10.10", "2.2.10.10")).kind, "flashable-stock");
assert.equal(compat.classifyOnboardingFirmware(info("", "2.3.0.1", "2.3.0.1")).kind, "flashable-stock");
assert.equal(compat.classifyOnboardingFirmware(info("", "2.3.0.24", "2.3.0.24")).kind, "flashable-stock");
assert.equal(compat.classifyOnboardingFirmware(info("", "2.3.0.24", "2.3.0.25")).kind, "newer-stock-unvalidated");
// Faceclaw firmware on a newer base is still judged by its revision, not the base.
assert.equal(compat.classifyOnboardingFirmware(info(`Faceclaw/${REQUIRED}`, "2.3.0.1", "2.3.0.1")).kind, "custom");
});
+16 -1
View File
@@ -63,7 +63,8 @@ function loadIconGrid({ lastInputWasWatch = false } = {}) {
const menu = load('app/ui/menu.ts', {
...common, './layers': {},
'./menu-animation-pref': build('ui/menu-animation-pref'),
'../native/settings-store': { getBooleanSetting: (_key, fallback) => fallback },
'./animation-speed': build('ui/animation-speed'),
'../native/settings-store': { getStringSetting: (_key, fallback) => fallback },
});
const grid = load('app/ui/icon-grid.ts', {
...common,
@@ -122,6 +123,20 @@ function shown(image, at) {
return withClock(at, () => Array.from(image.withDrawsBaked().pixels, (v) => Math.min(15, (v + 8) >> 4)));
}
test('a box topped at the band inset less the highlight inset pads the first row band evenly', () => {
// The launcher's root grid (launcher-app.ts ROOT_GRID_TOP) relies on this.
const { grid } = makeGrid();
const { ICON_GRID_BAND_INSET_X: insetX, ICON_GRID_HIGHLIGHT_INSET_Y: insetY } = loadIconGrid();
const image = paint(grid, 1000, { x: 0, y: insetX - insetY, width: 500, height: 190 });
const stroke = build('ui/menu-core').MENU_HIGHLIGHT_STROKE;
let left = 500, right = -1, top = 200;
image.pixels.forEach((v, i) => {
if (v !== stroke) return;
left = Math.min(left, i % 500); right = Math.max(right, i % 500); top = Math.min(top, (i / 500) | 0);
});
assert.deepEqual([top, left, 500 - 1 - right], [insetX, insetX, insetX]);
});
test('rows keep their content height instead of stretching, and the next row peeks clipped', () => {
assert.equal(metrics.iconGridMinRowHeight({ lineHeight: LINE_HEIGHT }, 44, 2), ROW_H);
const { grid } = makeGrid({ items: Array.from({ length: 15 }, (_, i) => `item${i}`) });
+20
View File
@@ -40,6 +40,9 @@ test('new SysEvent decodes independently of click, double-tap, hold and release'
const decoded = d.rawInputEventToPayload({ kind: 'sys-event', eventType: 14, eventSource: source });
assert.equal(decoded.type, 'ring-press'); assert.equal(decoded.source, 'ring');
}
// Synthetic watch touch-down (TOUCH_EVENT_FROM_WATCH, never sent by firmware).
const watch = d.rawInputEventToPayload({ kind: 'sys-event', eventType: 14, eventSource: 4 });
assert.equal(watch.type, 'ring-press'); assert.equal(watch.source, 'watch');
for (const source of [1, 3, 99, undefined]) {
assert.equal(d.rawInputEventToPayload({ kind: 'sys-event', eventType: 14, eventSource: source }).type, 'unknown');
}
@@ -192,3 +195,20 @@ test('debug history retains both clocks and uses unsigned gaps across counter wr
assert.equal(log.entries[0].filtered,true);
log.clear(); log.add(ring(1,500)); assert.equal(log.entries[0].ringGapTicks,null);
});
test('PressTracker pairs each gesture with the touch-down that began it', () => {
const { PressTracker } = load('app/ui/gestures.ts');
const t = new PressTracker();
const ev = (type, source) => ({ type, source, timestampMs: 0 });
assert.equal(t.followsPress(ev('ring-press', 'watch')), false);
assert.equal(t.followsPress(ev('click', 'watch')), true);
// Input with no touch-down of its own (finger-pinch tap, crown, older watch app) still acts.
assert.equal(t.followsPress(ev('click', 'watch')), false);
// A press pairs only with the next event, and only from its own source.
t.followsPress(ev('ring-press', 'watch'));
assert.equal(t.followsPress(ev('click', 'left-arm')), false);
assert.equal(t.followsPress(ev('click', 'watch')), false);
// Stock ring scroll notifications omit their source.
t.followsPress(ev('ring-press', 'ring'));
assert.equal(t.followsPress({ type: 'scroll-up', timestampMs: 0 }), true);
});
-171
View File
@@ -88,63 +88,6 @@ test('iOS host forwards hands-free capture mode to the voice bridge', async () =
assert.deepEqual(captures, [true, false]);
});
for (const isIOS of [true, false]) {
test(`${isIOS ? 'iOS' : 'Android'} Assistant settings expose supported controls and usable model choices`, () => {
const store = new Map();
let picker;
const models = load('app/assistant/models.ts', { global: { isIOS }, require: () => ({
LOCAL_MODEL: { label: 'Qwen', id: 'qwen' }, isLocalModelReady: () => false,
}) });
const settings = load('app/ui/dashboard-settings.ts', { global: { isIOS }, require: id => {
if (id.includes('settings-store')) return {
onSettingsStoreChanged() {},
getStringSetting: (key, fallback) => store.get(key) ?? fallback,
setStringSetting: (key, value) => store.set(key, value),
getBooleanSetting: (key, fallback) => store.get(key) ?? fallback,
setBooleanSetting: (key, value) => store.set(key, value),
};
if (id === '~/assistant/models') return models;
return { Layer: class {}, isLocalModelReady: () => false,
openModalMenu: (_ctx, _title, items) => { picker = items; } };
} });
const menus = load('app/ui/dashboard/settings-menus.ts', { global: { isIOS }, require: id => {
if (id === '../dashboard-settings') return settings;
if (id === './remote-input-menu') return { remoteInputMenuItem: () => ({ label: 'Input tokens' }) };
if (id === './settings-panel') return { SettingsPanelLayer: class { constructor(sections) { this.sections = sections; } } };
return { LOCAL_MODEL: { sizeBytes: 1000 }, ASR_MODELS: { moonshine: {}, 'whisper-base-en': {} },
uiFontPickerMenuItem: () => ({ label: 'Font' }), terminalFontPickerMenuItem: () => ({ label: 'Terminal font' }) };
} });
const sections = menus.createSettingsPanelLayer().sections;
assert.ok(sections.find(section => section.label === 'Display').items.some(item => item.label === settings.lockScreenEnabledSetting.label));
const assistant = sections.find(section => section.label === 'Assistant');
assert.equal(assistant.items.some(item => item.disabled === true), false);
const ctx = { stack: { pop() {} }, actions: { requestRender() {} } };
const row = setting => assistant.items.find(item => item.label === setting.label);
row(settings.assistantBackendSetting).onSelect(ctx);
assert.deepEqual(Array.from(picker, item => item.label), isIOS ? ['Cloud API'] : ['On-phone', 'My own agent (bridge)']);
assert.equal(assistant.items.some(item => item.label === 'On-phone model'), !isIOS);
assert.equal(!!row(settings.assistantBridgeHostSetting), !isIOS);
assert.equal(!!row(settings.assistantAllowProactiveSetting), !isIOS);
row(settings.assistantModelSetting).onSelect(ctx);
assert.equal(picker.some(item => item.label.includes('Qwen')), !isIOS);
const terra = picker.find(item => item.label === 'Terra');
assert.equal(terra.disabled(), true);
const keys = sections.find(section => section.label === 'API Keys').items;
assert.ok(keys.some(item => item.label === settings.openAiApiKeySetting.label));
assert.ok(keys.some(item => item.label === settings.anthropicApiKeySetting.label));
settings.openAiApiKeySetting.set('fixture-key');
assert.equal(terra.disabled(), false);
terra.onSelect(ctx);
assert.equal(settings.assistantModelSetting.get(), 'terra');
assert.equal(models.resolveAssistantModel(settings.assistantModelSetting.get(), {
openai: settings.openAiApiKeySetting.get(), anthropic: '',
}).provider, 'openai');
row(settings.assistantSkipConfirmationSetting).onSelect(ctx);
assert.equal(settings.assistantSkipConfirmationSetting.get(), true);
assert.ok(sections.find(section => section.label === 'Voice').items.some(item => item.label === settings.wakeWordActionSetting.label));
});
}
test('iOS phone battery distinguishes unknown, charging, full and unplugged readings', () => {
const device = { batteryLevel: -1, batteryState: 0 };
const api = load('app/native/phone-battery.ts', { require: () => ({}), global: { isIOS: true },
@@ -205,119 +148,6 @@ test('settings-driven repaint runs after font cache invalidation, regardless of
assert.deepEqual(painted, ['Bold']);
});
test('background glasses input still composites frames; phone resume preserves the session; explicit stop stays stopped', async () => {
const tasks = new Map(), screenStates = [], inputs = [], frames = [], previews = [], states = [], sounds = [];
let nextTask = 0, starts = 0, stops = 0, pollStarts = 0, pollStops = 0, bridge;
const window = { windowId: 'launcher', surfaceId: 'launcher', appId: 'launcher', title: 'Apps',
setScreenOn: on => screenStates.push(on), requestRender() {} };
const shell = { configure() {}, registerWindow() {}, wake() {}, focusWindow() {},
getWindows: () => [window], foregroundWindow: () => window, isScreenOn: () => true,
setBatteryLevels() {}, paintScene() { return new Uint8Array([0,0]); }, paintSurface() {}, underlayDim: () => 0, getFocus: () => 'app',
receiveInput: async input => { inputs.push(input); } };
// The shared Kotlin session, as seen through the iOS bridge: frames reach it
// only while connected, callbacks come back on the JS thread.
const noop = () => () => {};
class FaceclawCommunicatorBridge {
phase = 'disconnected';
constructor() { bridge = this; }
onStateChange(fn) { this.stateListener = fn; return noop(); }
onRingEvent(fn) { this.ringListener = fn; return noop(); }
onBatteryState() { return noop(); } onFirmwareInfo() { return noop(); } onFrameMetrics() { return noop(); }
onWearState() { return noop(); } addCompassListener() { return noop(); } onAncsRelayFrame() { return noop(); }
onAncsAuthorization() { return noop(); } setRequiresAncs() {} rightWriteLimit() { return 20; } onPhoneLockSignal() {}
async writeRawToRight() {}
async start() { starts++; this.phase = 'connected'; this.stateListener({ phase: 'connected', status: 'Connected.' }); }
async disconnect() { stops++; this.phase = 'disconnected'; this.stateListener({ phase: 'disconnected', status: 'Disconnected.' }); }
async close() {}
async configureBrightness() {} async setBrightness() {} async enableWearDetectionAndRequestState() {}
async configureCompositorScreen() {} async configureSurface() {} async setUnderlayDim() {} async setSurfaceVisible() {}
async setScreenBlanked() {} async removeSurface() {}
async submitSurfaceFrame(_id, pixels) { if (this.phase === 'connected') frames.push(pixels); }
async submitShellScene(bytes) { if (this.phase === 'connected') frames.push(bytes); }
waitForFrameFinished() { return Promise.resolve('sent'); }
getCompositePreview() { return new Uint8Array([1, 2]); }
async playBuzzerSequence(payload) { sounds.push([...payload]); }
}
class PreviewDisplayTarget {
activate() {} release() {}
async configureCompositorScreen() {} async configureSurface() {} async setUnderlayDim() {} async setSurfaceVisible() {}
async setScreenBlanked() {} async removeSurface() {} async submitSurfaceFrame() {} async submitShellScene() {}
waitForFrameFinished() { return Promise.resolve('composited'); }
getCompositePreview() { return new Uint8Array([1, 2]); }
}
const settings = { brightnessSetting: { get: () => 'auto' }, brightnessSettingToLevel: () => null, getBrightnessPreferences: () => ({ auto: true, level: 50, minimum: 2, maximum: 100, curve: '0:0,1000:100', fadeMs: 280 }), lockScreenEnabledSetting: { get: () => true }, onAnySettingChanged: () => () => {}, previewColorSetting: { get: () => 'white' } };
const modules = {
"../ui/input-monitor": load("app/ui/input-monitor.ts", {}),
'../remote/service': { startRemoteInput() {} },
'../assistant/system-tools': { registerSystemTools() {} },
'../assistant/window-tools': { registerWindowTools() {} },
'../assistant/navigate-tools': { registerNavigateTools() {} },
'../assistant/roam-tools': { registerRoamTools() {} },
"../native/ios-navigation-sensors": {},
'../native/notification-icons.ios': { bindIosNotifications() {}, iosNotificationsChanged() {}, onIosNotificationPopup: () => () => {}, readActiveNotifications: () => [] },
'../native/notification-sources': { shouldShowNotificationOnGlasses: () => true },
'../native/compass.ios': { bindCompassSession() {}, receiveCompassEvent() {} },
'@nativescript/core': { File: { fromPath: () => ({ writeTextSync() {} }) }, knownFolders: { documents: () => ({ path: '/tmp' }) }, path },
'../native/ios-voice-input': { iosVoiceInput: { handleSessionEnded() {}, stopPhoneCapture() {} } },
'../native/faceclaw-communicator.ios': { FaceclawCommunicatorBridge, resolveIosPeripherals: async addresses => addresses },
'../native/preview-display.ios': { PreviewDisplayTarget },
'./ancs-client': { ANCS_FIRMWARE_VERSION: 16, AncsClient: class { state = 'disconnected'; start() {} stop() {} stopCommand() { return new Uint8Array(); } receive() { return false; } } },
'../native/nightscout-bridge': { nightscoutBridge: { async start() { pollStarts++; }, async stop() { pollStops++; } } },
'./glance-host': { GlanceHost: class { dismiss() {} reset() {} isVisible() { return false; } } },
'./device-addresses': { loadDeviceAddresses: () => ({ right: 'AA', left: 'BB', ring: '' }) }, './ios-peripheral-identity': { deviceAddressError: () => null },
'../apps/launcher/launcher-app': { createLauncherWindow: () => window, LAUNCHER_SURFACE_ID: 'launcher' },
'../apps/launcher': { launcherEntries: () => [] },
'../apps/all-apps': { ALL_APPS: [] }, '../ui/dashboard-settings': settings,
'../native/phone-battery': { readPhoneBatteryState: () => ({ battery: 80, charging: false }) },
'../graphics/plane': { flattenPlanesWithDraws: () => ({ image: { pixels: new Uint8Array([1, 2]), width: 2, height: 1 }, draws: [] }), planesFingerprint: () => 'fp' },
'../graphics/glyph-wire': { prepareFrameDraws: () => null },
'../graphics/image': { G2_LENS_WIDTH: 640, G2_LENS_HEIGHT: 480 },
'./lock-screen': { LOCK_SCREEN_SURFACE_ID: 'lock-screen', createLockScreenImage: () => ({ width: 1, height: 1, to8bppBuffer: () => new Uint8Array(1) }) },
'../ui/shell/shell': { shell, rawInputEventToInputEvent: input => input },
'../ui/shell/geometry': { appViewportRect: () => ({ x: 0, y: 0, width: 640, height: 480 }) },
pako: { deflate: x => x },
};
const api = load('app/g2/ios-preview-controller.ts', {
require: id => modules[id] ?? {}, console: { log() {}, warn() {}, error() {} },
setTimeout: fn => { tasks.set(++nextTask, fn); return nextTask; }, clearTimeout: id => tasks.delete(id),
setInterval: () => ++nextTask, clearInterval() {},
UIDevice: { currentDevice: {} }, UIApplication: { sharedApplication: { protectedDataAvailable: true } },
UIApplicationProtectedDataWillBecomeUnavailable: 'lock', UIApplicationProtectedDataDidBecomeAvailable: 'unlock',
UIDeviceBatteryLevelDidChangeNotification: 'level', UIDeviceBatteryStateDidChangeNotification: 'state',
NSNotificationCenter: { defaultCenter: { addObserverForNameObjectQueueUsingBlock() {}, removeObserver() {} } },
NSOperationQueue: { mainQueue: {} },
});
const flush = () => { for (const [id, fn] of [...tasks]) { if (tasks.delete(id)) fn(); } };
const settle = async () => { for (let i = 0; i < 4; i++) { flush(); await new Promise(resolve => setImmediate(resolve)); } };
const controller = new api.IosPreviewController(image => previews.push(image), assert.fail, state => states.push(state));
await controller.actions.playBuzzerSequence(new Uint8Array([5, 4, 0]));
assert.equal(sounds.length, 0);
controller.resume(); await controller.connect(); await settle();
await controller.actions.playBuzzerSequence(new Uint8Array([5, 4, 0]));
assert.deepEqual(sounds, [[5, 4, 0]]);
const previewCount = previews.length, stateCount = states.length;
controller.pause(); controller.pause(); // NativeScript also unloads its root page on background entry.
assert.equal(stops, 0); assert.ok(screenStates.every(Boolean));
assert.equal(pollStarts, 1); assert.equal(pollStops, 0, 'connected glasses keep Nightscout polling in background');
const frameCount = frames.length;
bridge.ringListener({ kind: 'sys-event', containerName: '', eventType: 3, eventSource: 1, systemExitReasonCode: 0, frameId: 0 });
await controller.inputQueue; await settle();
assert.equal(inputs.length, 1); assert.ok(frames.length > frameCount, 'background input still composites frames');
assert.equal(previews.length, previewCount); assert.equal(states.length, stateCount);
controller.resume(); await settle();
assert.equal(starts, 1); assert.ok(previews.length > previewCount);
controller.pause(); await controller.disconnect(); await settle();
assert.equal(stops, 1); assert.equal(screenStates.at(-1), false);
assert.equal(pollStops, 1);
const stoppedFrames = frames.length;
bridge.ringListener({ kind: 'sys-event', containerName: '', eventType: 3, eventSource: 1, systemExitReasonCode: 0, frameId: 0 });
await controller.inputQueue; await settle();
assert.equal(inputs.length, 1); assert.equal(frames.length, stoppedFrames);
controller.resume(); await settle();
assert.equal(starts, 1); assert.equal(controller.connectionState.phase, 'disconnected');
assert.equal(pollStarts, 2, 'resuming the phone restarts Nightscout polling');
});
test('iOS bandwidth footer toggles live, polls only in foreground and resets its rate window on resume', () => {
const views = [], intervals = new Map(), appEvents = new Map(), settingListeners = new Set();
let enabled = false, atMs = 0, totals = { messages: 0, bytes: 0, frames: 0 }, nextId = 0;
@@ -439,7 +269,6 @@ test('iOS compositor rejects missing and removed surfaces before crossing into K
assert.equal(nativeSubmissions, 1);
});
test('iOS welcome sound waits for a new acknowledged frame and is consumed once', async () => {
let pending = true;
const played = [], sounds = load('app/ui/sound-effects.ts', { require: name => { assert.equal(name, '../g2/cfw-message-type'); return load('app/g2/cfw-message-type.ts', {}); } });
+1 -22
View File
@@ -15,7 +15,6 @@ function load(file, modules = {}, globals = {}) {
}).outputText, sandbox);
return sandbox.exports;
}
const flush = () => new Promise(resolve => setImmediate(resolve));
function provider() {
let now = 1000000, granted = true;
@@ -166,6 +165,7 @@ function screenFixture() {
const calendar = load('app/apps/calendar/calendar.ts', modules('../../'));
const widget = load('app/apps/glanceboard/widgets/calendar-widget.ts', {
...modules('../../../'), '../../calendar/calendar': calendar,
'../glance-font': { glanceFont: { small: () => font, medium: () => font } },
}, { ...f.clock, setInterval: fn => { timers.set(++nextTimer, fn); return nextTimer; }, clearInterval: id => timers.delete(id) });
return { ...f, ...calendar, ...widget, timers, Image };
}
@@ -206,27 +206,6 @@ test('Calendar window subscribes, refreshes periodically, and cleans up on close
options.onClosed(); assert.equal(unsubscribed, 1); assert.equal(cleared, 1); assert.equal(closed, 1);
});
test('iOS Calendar is launchable and its permission remains optional during onboarding', async () => {
const availability = load('app/apps/ios-availability.ts');
assert.equal(availability.iosAppUnavailableReason('calendar'), null);
const f = permissionFixture(); let resumed;
const { PermissionsViewModel } = load('app/phone-ui/permissions-view-model.ts', {
'@nativescript/core': { Observable: class { notifyPropertyChange() {} },
Application: { on: (_event, fn) => { resumed = fn; }, off() {} } },
'../native/ios-bluetooth': { iosBluetooth: () => ({ state: 5 }) },
'../native/calendar-permissions': f.api,
'../g2/android-permissions': {}, '../native/battery-optimization': {}, '../native/notification-access': {},
}, { global: { isIOS: true } });
const model = new PermissionsViewModel({ onboarding: true }); model.onPageLoaded();
const card = () => model.cards.find(item => item.id === 'calendar');
assert.equal(card().optionalVisibility, 'visible'); assert.equal(card().checkVisibility, 'collapse');
assert.equal(model.primaryClass, '-primary');
model.onCardTap({ object: { bindingContext: card() } }); assert.equal(f.requests.length, 1);
f.status('granted'); f.requests[0](true, null); await flush();
assert.equal(card().checkVisibility, 'visible');
f.status('denied'); resumed(); assert.equal(card().checkVisibility, 'collapse');
});
test('awaited calendar reads do not replace the display cache and reject failures or revoked access', async () => {
const f = provider(); f.api.readUpcomingEvents();
const awaited = f.api.readUpcomingEventsAsync(10, 3600000);
+3 -23
View File
@@ -1,10 +1,8 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs'), vm = require('node:vm');
const { createHash } = require('node:crypto');
const { zstdCompressSync } = require('node:zlib');
const { loader } = require('./helpers/load-typescript.cjs');
const { LvglFont } = require('../.test-build/app/graphics/lvgl-font.js');
function pack(files) {
const key = Buffer.from('EVEN REALITIES');
@@ -17,27 +15,6 @@ function pack(files) {
})]);
}
test('iOS LVGL reader loads the bundled font including CJK and game symbols', () => {
const bytes = new Uint8Array(fs.readFileSync('app/fonts/source-han-sans/SourceHanSansSC-Light-20.lvgl.bin'));
const font = new LvglFont(bytes);
// Metrics and full glyph SHA-256 vectors from production Java LvglFontFile.
assert.deepEqual([...font.metrics], [25, 19]);
const vectors = [
[0x25a6, 'b08ecb603fd059b0a00ba3088f18b79185c421e73049797cd3cb0828e1e5cd04'],
[0x25c6, 'c176d5dcdb5f7e3a7220455528efde3760672c40cee39b422fc3f5ad20df66dd'],
[0x4e2d, '9bde2c8f1ffcf7afc598f4d0350c9ff262484816aa0c9b46d31f0c3c09613003'],
[0xff21, '0074f96299a75b86912282416e47e0823790e091352aec852eff49b89b2e719d'],
];
for (const [cp, hash] of vectors) {
const glyph = font.glyph(cp);
const w = glyph[0] | glyph[1] << 8, h = glyph[2] | glyph[3] << 8;
assert.ok(w > 0 && h > 0); assert.equal(glyph.length, 8 + (Math.floor(w / 2) + 1) * h);
assert.equal(createHash('sha256').update(glyph).digest('hex'), hash);
}
assert.equal(font.glyph(0x10ffff).length, 0);
assert.throws(() => new LvglFont(bytes.subarray(0, 80)), /bounds|Truncated/);
});
test('EHPK entrypoints and extraction paths cannot escape their package directory', () => {
const load = loader({}, { fzstd: require('fzstd') });
const api = load('app/apps/evenhub/ehpk.ts');
@@ -56,6 +33,7 @@ test('Files on iOS exposes Run app for EHPKs and passes the selected local path'
const load = loader({ global: { isIOS: true } }, {
'../../native/file-access': {}, '../../native/font-files': { isFontFile: () => false },
'../../graphics/installed-fonts': {}, '../../native/image-files': { isDecodableImageFile: () => false },
'../../native/video-player': { isPlayableVideoFile: () => true },
'../evenhub/installed-apps': { readEvenHubPackageManifest: () => null }, '../evenhub/permission-dialog': {},
'./file-browser': { FileBrowserLayer: class { constructor(options) { browserOptions = options; } } },
'./file-info-dialog': { FileInfoDialogLayer: class { constructor(entry, value) { actions = value; } } },
@@ -64,6 +42,8 @@ test('Files on iOS exposes Run app for EHPKs and passes the selected local path'
});
load('app/apps/files/files-app.ts').createFilesAppWindow({ openEhpkApp: path => { opened = path; }, installEhpkApp: path => { installed = path; } });
assert.equal(browserOptions.isSupportedFile('test.EHPK'), true);
// Video playback is Android-only for now.
assert.equal(browserOptions.isSupportedFile('clip.mp4'), false);
const ctx = { stack: { push() {}, pop() {} } };
browserOptions.onFilePicked({ name: 'test.ehpk', path: '/Documents/test.ehpk' }, ctx);
assert.deepEqual(Array.from(actions, a => a.label), ['Run app', 'Install']);
+40 -183
View File
@@ -5,7 +5,6 @@ const path = require('node:path');
const vm = require('node:vm');
const ts = require('typescript');
const images = require('../.test-build/app/graphics/image.js');
const { SurfaceCompositor } = require('../.test-build/app/graphics/surface-compositor.js');
const events = require('../.test-build/app/g2/events.js');
function load(file, modules, globals = {}) {
@@ -20,6 +19,7 @@ function load(file, modules, globals = {}) {
}
const planes = load('app/graphics/plane.ts', { './image': images });
const timings = load('app/native/frame-timings.ts', {});
const LAUNCHER_GRAY = 75;
function fixture() {
const observers = new Map(), phoneState = { protectedDataAvailable: true };
@@ -38,7 +38,7 @@ function fixture() {
'../util/render-freshness': { beginRenderPass() {}, endRenderPass: () => false },
'./glance-state': require('../.test-build/app/g2/glance-state.js'),
}, clock);
const launcherPixels = new Uint8Array(640 * 480).fill(75), fullRect = { x: 0, y: 0, width: 640, height: 480 };
const launcherPixels = new Uint8Array(640 * 480).fill(LAUNCHER_GRAY), fullRect = { x: 0, y: 0, width: 640, height: 480 };
const window = { windowId: 'launcher', surfaceId: 'launcher', appId: 'launcher', title: 'Apps',
// The launcher repaints into whichever display target the controller has after a switch.
requestRender() { void controller?.displayReady.then(() => controller.display?.submitSurfaceFrame('launcher', launcherPixels, fullRect, 'launcher')); }, setScreenOn() {} };
@@ -55,21 +55,43 @@ function fixture() {
if (input.type === 'display-wake' || !screenOn && input.type === 'double-click') shell.wake();
},
};
// Both display targets compose with the real (TypeScript reference) compositor so
// the pixel assertions below exercise real layering, blanking and lock surfaces.
// Both display targets share a minimal compositor (z-ordered opaque and
// color-keyed surfaces, visibility, blanking) so the pixel assertions below
// exercise layering, blanking and lock surfaces.
class Display {
compositor = new SurfaceCompositor(640, 480);
surfaces = new Map(); blanked = false; depths = [];
async configureCompositorScreen() {}
async configureSurface(id, options) { this.compositor.configureSurface(id, options); }
async removeSurface(id) { this.compositor.removeSurface(id); this.changed(); }
async setSurfaceVisible(id, visible) { this.compositor.setSurfaceVisible(id, visible); this.changed(); }
depths = [];
async setSurfaceDepth(id, depth) { this.depths.push([id, depth]); this.compositor.setSurfaceDepth(id, depth); }
async setUnderlayDim(below, factor) { this.compositor.setUnderlayDim(below, factor); this.changed(); }
async setScreenBlanked(blanked) { this.compositor.setScreenBlanked(blanked); this.changed(); }
async submitSurfaceFrame(id, pixels, rect, _fingerprint, _paintMs, _frameId, draws = null) { this.compositor.submitSurfaceFrame(id, pixels, rect, draws); this.changed(); }
async submitShellScene(bytes) { this.compositor.setShellScene(bytes); this.changed(); }
getCompositePreview() { return this.compositor.composite(); }
async configureSurface(id, options) {
const previous = this.surfaces.get(id);
const pixels = previous?.width === options.width && previous.height === options.height
? previous.pixels : new Uint8Array(options.width * options.height);
this.surfaces.set(id, { ...options, pixels, visible: previous?.visible ?? true });
}
async removeSurface(id) { this.surfaces.delete(id); this.changed(); }
async setSurfaceVisible(id, visible) { const surface = this.surfaces.get(id); if (surface) surface.visible = visible; this.changed(); }
async setSurfaceDepth(id, depth) { this.depths.push([id, depth]); }
async setUnderlayDim() { this.changed(); }
async setScreenBlanked(blanked) { this.blanked = blanked; this.changed(); }
async submitSurfaceFrame(id, pixels, rect) {
const surface = this.surfaces.get(id);
if (!surface) throw new Error(`Unknown surface: ${id}`);
for (let y = 0; y < rect.height; y++) {
surface.pixels.set(pixels.subarray(y * rect.width, (y + 1) * rect.width), (rect.y + y) * surface.width + rect.x);
}
this.changed();
}
async submitShellScene() { this.changed(); }
getCompositePreview() {
const output = new Uint8Array(640 * 480);
if (this.blanked) return output;
for (const s of [...this.surfaces.values()].filter(s => s.visible).sort((a, b) => a.zOrder - b.zOrder)) {
for (let y = 0; y < s.height; y++) for (let x = 0; x < s.width; x++) {
const value = s.pixels[y * s.width + x];
if (s.transparency !== 'color-key' || value) output[(s.y + y) * 640 + s.x + x] = value;
}
}
return output;
}
changed() {}
}
class PreviewDisplayTarget extends Display {
@@ -93,7 +115,7 @@ function fixture() {
async start() { this.emitState('connected', 'Connected.'); }
async disconnect() { this.emitState('disconnected', 'Disconnected.'); }
waitForFrameFinished() { return Promise.resolve('sent'); }
changed() { if (this.phase === 'connected') sent.push(this.compositor.composite()); }
changed() { if (this.phase === 'connected') sent.push(this.getCompositePreview()); }
}
const provider = {
isEnabled: () => settings.enabled, showOnTap: () => settings.tap,
@@ -121,9 +143,11 @@ function fixture() {
'../native/preview-display.ios': { PreviewDisplayTarget },
'./ancs-client': { ANCS_FIRMWARE_VERSION: 16, AncsClient: class { state = 'disconnected'; start() {} stop() {} stopCommand() { return new Uint8Array(); } receive() { return false; } } },
'../native/nightscout-bridge': { nightscoutBridge: { async start() {}, async stop() {} } },
'../native/weather': { weatherBridge: { setSessionActive() {} } },
'./glance-host': { GlanceHost }, './events': events,
'./lock-screen': { LOCK_SCREEN_SURFACE_ID: 'lock-screen', createLockScreenImage: () => new images.GrayImage(640, 480, 123) },
'./device-addresses': { loadDeviceAddresses: () => ({ right: 'AA', left: 'BB', ring: '' }) }, './ios-peripheral-identity': { deviceAddressError: () => null },
'./firmware-compat': load('app/g2/firmware-compat.ts', {}), './reconnect-policy': load('app/g2/reconnect-policy.ts', {}),
'../apps/launcher': { launcherEntries: () => [] },
'../apps/evenhub/installed-apps': {}, '../apps/evenhub/manager': {}, '../apps/evenhub/updates': {}, '../apps/evenhub': {},
'../apps/launcher/launcher-app': { createLauncherWindow: () => window, LAUNCHER_SURFACE_ID: 'launcher' },
@@ -182,70 +206,6 @@ const assertBoard = pixels => {
assert.equal(pixels[0], 0, 'opaque Glanceboard hides the retained app and shell');
};
test('iOS sleep tap shows the shared board; repeated tap renews timeout and hides to black', async () => {
const f = fixture(); await f.connect(); f.shell.sleep(); await f.render();
assertBlank(f.sent.at(-1));
await f.hardware(0); assertBoard(f.sent.at(-1)); assert.equal(f.shell.isScreenOn(), false);
assert.equal(f.previews.at(-1).title, 'Glanceboard'); assert.equal(f.received.length, 0);
await f.advance(2000); await f.hardware(0); await f.advance(1100);
assert.equal(f.controller.glance.isVisible(), true);
const offset = f.sent.length;
await f.advance(2000); await f.render();
assert.equal(f.controller.glance.isVisible(), false);
for (const pixels of f.sent.slice(offset)) assertBlank(pixels);
assert.equal(f.boardStats.starts, 1); assert.equal(f.boardStats.stops, 1);
});
test('Glanceboard applies its depth setting to its surface only when it changes', async () => {
const f = fixture(); await f.connect(); f.shell.sleep(); await f.render();
f.settings.depth = 32; await f.hardware(0); assertBoard(f.sent.at(-1));
await f.advance(3100); await f.render(); assert.equal(f.controller.glance.isVisible(), false);
await f.hardware(0); assert.equal(f.controller.glance.isVisible(), true);
await f.advance(3100); await f.render();
f.settings.depth = 0; await f.hardware(0);
assert.deepEqual(f.controller.display.depths, [['glance', 32], ['glance', 0]]);
});
test('iOS holds and tap-then-holds last until release, including with phone backgrounded', async () => {
const f = fixture(); await f.connect(); f.shell.sleep(); f.controller.pause();
const previews = f.previews.length;
for (const type of [9, 11]) {
await f.hardware(type, 1); assertBoard(f.sent.at(-1));
await f.advance(10000); assert.equal(f.controller.glance.isVisible(), true);
await f.hardware(10, 1); assertBlank(f.sent.at(-1));
}
assert.equal(f.previews.length, previews); assert.equal(f.received.length, 0);
});
test('double-tap and other shell wakes replace Glanceboard without waking it again', async () => {
const f = fixture(); await f.connect(); f.shell.sleep();
await f.hardware(9); await f.hardware(3);
assert.equal(f.shell.isScreenOn(), true); assert.equal(f.controller.glance.isVisible(), false);
assert.equal(f.sent.at(-1)[0], 80); assert.equal(f.boardStats.stops, 1);
f.shell.sleep(); await f.hardware(0); f.shell.wake(); await f.render();
assert.equal(f.controller.glance.isVisible(), false); assert.equal(f.sent.at(-1)[0], 80);
await f.advance(5000); await f.render(); assert.equal(f.sent.at(-1)[0], 80);
});
test('head tilt uses Glanceboard when enabled and otherwise wakes the regular UI', async () => {
const f = fixture(); await f.connect(); f.shell.sleep();
await f.hardware(12, 1); assertBoard(f.sent.at(-1)); assert.equal(f.shell.isScreenOn(), false);
await f.hardware(3); f.shell.sleep(); f.settings.tilt = false;
await f.hardware(12, 1); assert.equal(f.shell.isScreenOn(), true); assert.equal(f.sent.at(-1)[0], 80);
});
test('disabled triggers and scrolls do not show the board; awake taps still reach the shell', async () => {
const f = fixture(); await f.connect();
await f.hardware(0); assert.equal(f.received.at(-1).type, 'click'); assert.equal(f.boardStats.starts, 0);
f.shell.sleep(); f.settings.tap = false; f.settings.hold = false;
for (const type of [0, 9, 11, 10, 1, 2]) await f.hardware(type);
assert.equal(f.boardStats.starts, 0); assertBlank(f.sent.at(-1));
f.settings.enabled = false; f.settings.tap = f.settings.hold = true;
for (const type of [0, 9, 11]) await f.hardware(type);
assert.equal(f.boardStats.starts, 0);
await f.hardware(3); assert.equal(f.shell.isScreenOn(), true);
});
test('phone preview gestures use Glanceboard; losing runtime cleans up holds and timers', async () => {
const f = fixture(); f.shell.sleep();
await f.phone('tap', 'mirror'); assertBoard(f.previews.at(-1).pixels);
@@ -258,94 +218,6 @@ test('phone preview gestures use Glanceboard; losing runtime cleans up holds and
assert.equal(f.boardStats.starts, f.boardStats.stops);
});
test('iOS lock hides apps and Glanceboard, blocks input, and stays locked when put back on', async () => {
const f = fixture(); await f.connect(); f.shell.sleep(); await f.hardware(0);
f.controller.pause();
// The notification precedes the property change: do not immediately undo it.
f.observers.get('lock')(); f.wear(false); await f.render();
assert.equal(f.controller.glassesLocked, true);
assert.equal(f.controller.glance.isVisible(), false);
await f.hardware(3); // wake the lock screen
assert.ok(f.sent.at(-1).every(p => p === 123));
for (const type of [0, 1, 2, 9, 11]) await f.hardware(type);
f.wear(true); await f.render();
assert.equal(f.received.length, 0);
assert.ok(f.sent.at(-1).every(p => p === 123));
await f.hardware(3); assertBlank(f.sent.at(-1));
await f.hardware(12, 1); assert.ok(f.sent.at(-1).every(p => p === 123));
f.observers.get('unlock')(); await f.render();
assert.equal(f.controller.glassesLocked, false);
assert.equal(f.sent.at(-1)[0], 80);
await f.hardware(0); assert.equal(f.received.length, 1);
});
test('iOS removal before phone lock, setting changes, and observer lifetime', async () => {
const f = fixture(); await f.connect(); f.wear(false); await f.render();
assert.equal(f.controller.glassesLocked, false);
f.observers.get('lock')(); await f.render();
assert.equal(f.controller.glassesLocked, true);
f.settings.lock = false; f.settingsChanged(); await f.render();
assert.equal(f.controller.glassesLocked, false);
f.settings.lock = true; f.settingsChanged(); await f.render();
assert.equal(f.controller.glassesLocked, true);
f.controller.pause(); assert.ok(f.observers.has('unlock'));
await f.controller.disconnect(); assert.equal(f.observers.has('unlock'), false);
f.controller.resume(); await f.render();
assert.equal(f.controller.glassesLocked, false);
assert.equal(f.observers.size, 4);
});
test('iOS wear notifications catch protected-data changes missed while suspended', async () => {
const f = fixture(); await f.connect(); f.controller.pause();
f.phoneState.protectedDataAvailable = false; f.wear(false); await f.render();
assert.equal(f.controller.glassesLocked, true);
f.controller.resume(); await f.render();
assert.equal(f.controller.glassesLocked, true);
f.controller.pause(); f.phoneState.protectedDataAvailable = true;
f.controller.resume(); await f.render();
assert.equal(f.controller.glassesLocked, false);
});
test('iOS locked phone controls cannot dispatch mirror, voice, or keyboard input', async () => {
const f = fixture(); await f.connect(); f.wear(false);
f.observers.get('lock')(); await f.render();
await f.phone('tap', 'mirror'); await f.phone('long-press', 'watch');
f.controller.startVoiceInput();
assert.equal(await f.controller.prepareVoiceCapture(), false);
await f.controller.startVoiceCapture(); await f.controller.typeIntoApp();
assert.equal(f.received.length, 0);
assert.equal(f.controller.glassesLocked, true);
// Locked state also survives transport recovery until a phone unlock.
f.bridge.emitState('retrying');
f.bridge.emitState('connecting');
f.bridge.emitState('connected');
await f.render();
assert.ok(f.sent.at(-1).every(p => p === 123));
});
test('iOS deduplicates original ring ticks before apps, lock toggles and Glanceboard', async () => {
const f = fixture(); await f.connect();
await f.hardware(0,2,1000); await f.hardware(0,2,1050);
assert.equal(f.received.length,1);
await f.hardware(0,2,1100); assert.equal(f.received.length,2);
// A filtered click cannot open a sleep-time board.
f.shell.sleep(); await f.hardware(0,2,1150);
assert.equal(f.controller.glance.isVisible(),false);
await f.hardware(0,2,1200); assert.equal(f.controller.glance.isVisible(),true);
// A duplicated double tap must not wake and immediately re-sleep a lock screen.
f.observers.get('lock')(); f.wear(false); await f.render();
f.shell.sleep(); await f.hardware(3,2,2000);
assert.equal(f.shell.isScreenOn(),true);
await f.hardware(3,2,2050); assert.equal(f.shell.isScreenOn(),true);
// A new transport session starts a fresh suppression window.
f.bridge.emitState('retrying');
f.bridge.emitState('connected');
await f.hardware(3,2,2051); assert.equal(f.shell.isScreenOn(),false);
});
test('keyboard sessions cannot deliver text after the glasses lock or phone leaves the foreground', () => {
const f = fixture();
let editor;
@@ -365,18 +237,3 @@ test('keyboard sessions cannot deliver text after the glasses lock or phone leav
editor.discard(); assert.deepEqual(calls.at(-1), ['discard']);
});
test('external input shares iOS dispatch, including hold release and phone-lock gating', async () => {
const f = fixture(); await f.connect(); f.wear(false);
assert.equal(f.remoteHost.ready(), true);
assert.equal(f.remoteHost.locked(), false);
await f.remoteHost.input('swipe-left', 'watch');
await f.remoteHost.input('long-press', 'ring');
assert.deepEqual(f.received.map(e => [e.type, e.source]), [
['swipe-left', 'watch'], ['long-press', 'ring'], ['long-press-release', 'ring'],
]);
f.observers.get('lock')();
assert.equal(f.remoteHost.locked(), true);
await f.remoteHost.input('click', 'watch');
assert.equal(f.received.length, 3);
});
+5 -1
View File
@@ -93,8 +93,9 @@ test('Navigate host releases GPS and compass together and ignores an old stream
test('Weather uses the portable location provider and preserves NWS parsing', async () => {
const requests = [], timers = new Set(); let permission = true;
const period = { name: 'Today', temperature: 70, temperatureUnit: 'F', shortForecast: 'Sunny', windSpeed: '5 mph', windDirection: 'W' };
const api = loader({ setTimeout, clearTimeout, setInterval: fn => { timers.add(fn); return fn; }, clearInterval: fn => timers.delete(fn) }, {
const api = loader({ setTimeout: fn => { timers.add(fn); return fn; }, clearTimeout: fn => timers.delete(fn) }, {
'./location-permissions': { hasLocationPermission: () => permission },
'./settings-store': { getStringSetting: (_key, fallback) => fallback, setStringSetting() {} },
'./location': { getCurrentLocation: async () => fix },
'../version': { USER_AGENT: 'test' },
'../util/http': { fetchWithUserAgent: async url => { requests.push(url); return { ok: true, json: async () =>
@@ -115,6 +116,9 @@ test('closing Weather during permission prompt cannot restart polling', async ()
'../../native/location-permissions': { hasLocationPermission: () => false, ensureLocationPermission: () => new Promise(resolve => { granted = resolve; }) },
'../../native/weather': { weatherBridge: { start() { starts++; }, stop() { stops++; }, onStateChange: () => () => {}, snapshot() {} } },
'./weather': { WeatherLayer: class {} },
'./weather-settings': {},
'../../ui/dashboard-settings': { toggleSettingMenuItem: () => ({}) },
'../../ui/dashboard/settings-panel': { openSettingsSubMenu() {} },
'../../ui/shell/in-process-window': { YieldAtRootLayer: class {}, createInProcessWindow: opts => { options = opts; return { requestRender() {} }; } },
})('app/apps/weather/weather-app.ts');
api.createWeatherAppWindow({ onClosed() {} }); options.onClosed(); granted(true); await flush();
-13
View File
@@ -103,16 +103,3 @@ test('iOS without a camera explains availability and can retry when available',
assert.equal(f.instances.length, 1); f.layer.onRemoved(); await flush();
});
test('Developer QR menu is enabled on iOS and pushes then opens its layer', () => {
let menu, options; const calls = [];
const { createDeveloperAppWindow } = load('app/apps/developer/developer-app.ts', {
'../../ui/menu': { MenuLayer: class { constructor(_title, items) { menu = items; } } },
'../../ui/shell/geometry': { appViewportSize: () => ({ height: 480 }) },
'../../ui/shell/in-process-window': { YieldAtRootLayer: class {}, createInProcessWindow: value => { options = value; return {}; } },
'./load-app': { LoadAppFromQrLayer: class { open() { calls.push('open'); } } },
}, { global: { isIOS: true } });
createDeveloperAppWindow({}, {});
const qr = menu.find(item => item.label === 'Load app from QR code');
assert.ok(!qr.disabled); qr.onSelect({ stack: { push: () => calls.push('push') } });
assert.deepEqual(calls, ['push', 'open']);
});
+8 -1
View File
@@ -7,13 +7,20 @@ plugins {
// Compile the production sources without building NativeScript or touching BLE.
kotlin {
// Match native/kotlin/shared/build.gradle.kts.
compilerOptions {
freeCompilerArgs.add("-Xexpect-actual-classes")
allWarningsAsErrors.set(true)
}
android {
namespace = "com.faceclaw.protocoltests"
compileSdk = 35
minSdk = 24
withJava()
compilerOptions { jvmTarget.set(JvmTarget.JVM_17) }
withHostTestBuilder {}.configure {}
// Production code logs through android.util.Log, which the host-test android.jar
// stubs to throw; a throw on the session worker turns into a spurious reconnect.
withHostTestBuilder {}.configure { isReturnDefaultValues = true }
}
iosArm64()
iosSimulatorArm64()
@@ -0,0 +1,44 @@
package com.faceclaw.app
import java.util.Collections
import kotlin.test.*
/**
* The phone mirror pulls previews only when told to, while the compositor's player advances an
* animated display list on its own timer. It needs a notification after every redraw, the
* settled one included, or it keeps a mid-slide frame. Host-only: it runs the real redraw thread.
*/
class PreviewAnimationListenerTest {
// FrameDisplayListTest's menu golden (a 2x2 highlight sliding in to rest at (3, 2)),
// restarted at 0 of its 240 ms so the slide is still in flight at the first pull.
private val menu = "077f0000000300020002000200022a00000096000000010002000200ffffffff0200080000ff24017e30020000000001812c8001812c1611010017328001812c16103001812c3023414031ff24017c30020000000001812c8001812c1611010017328001812c16103001812c30234140310200020001000103100400000000000000001f"
.chunked(2).map { it.toInt(16).toByte() }.toByteArray().also { it.fill(0, 18, 22) }
private fun settledPreview(): ByteArray {
val reader = ArrayByteReader(menu)
assertEquals(DrawRecordKind.DISPLAY_LIST, reader.get().toInt())
val list = FrameDisplayList.read(reader, drawAnimationTimeMs() - 10_000)
return ShellScene(emptyList(), listOf(list)).preview(ByteArray(64), 8, 8)
}
@Test fun mirrorIsNotifiedOfEachRedrawThroughTheSettledFrame() {
val c = SurfaceCompositor()
c.configureScreen(8, 8)
c.configureSurface("app", 0, 0, 8, 8, 0, 0)
val pulled = Collections.synchronizedList(ArrayList<ByteArray>())
c.setPreviewAnimationListener { pulled.add(assertNotNull(c.previewComposite()).gray) }
c.submitSurface("app", ArrayByteReader(ByteArray(64)), 0, 0, 8, 8, "menu", ArrayByteReader(menu))
val settled = settledPreview()
assertFalse(assertNotNull(c.previewComposite()).gray.contentEquals(settled), "the first pull is mid-slide")
// Redraws are 45 ms apart; 150 ms without one means the player has stopped.
val deadline = System.nanoTime() + 2_000_000_000L
var count = -1
while (System.nanoTime() < deadline && pulled.size != count) {
count = pulled.size
Thread.sleep(150)
}
assertEquals(count, pulled.size, "the player stops once the slide's timeline ends")
assertTrue(pulled.size >= 2, "one notification per redraw")
assertContentEquals(settled, pulled.last(), "the last notification's pull is the settled frame")
}
}
@@ -36,6 +36,46 @@ class DisplayListTest {
renderer.render(DrawProtocol.SCREEN, DisplayListRenderer.Target(source,640,480), DisplayListRenderer.Target(destination,640,480))
assertContentEquals(source, destination)
}
@Test fun rectCopyMatchesPerPixelReferenceWithShiftsClipsAndAliasing() {
val random = Random(7)
repeat(4000) { case ->
val width = random.nextInt(1, 20); val height = random.nextInt(1, 6)
val offset = random.nextInt(3); val shift = random.nextInt(-4, 5)
val clip = if (random.nextBoolean()) null else {
val left = random.nextInt(-3, width + 1); val top = random.nextInt(-2, height + 1)
intArrayOf(left, top, left + random.nextInt(0, width + 3), top + random.nextInt(0, height + 2))
}
// Screen as a separate array, the target's own array at another offset, or the target itself.
val mode = random.nextInt(3)
val screenWidth = random.nextInt(1, 20); val screenHeight = random.nextInt(1, 6)
val screenOffset = random.nextInt(3)
val targetSize = offset + (width + 1) / 2 * height
val screenSize = screenOffset + (screenWidth + 1) / 2 * screenHeight
val bytes = random.nextBytes(maxOf(targetSize, if (mode == 1) screenSize else 0) + 2)
val screenBytes = if (mode == 0) random.nextBytes(screenSize + 1) else bytes
val sourceId = if (mode == 2) DrawProtocol.CURRENT else DrawProtocol.SCREEN
val sourceWidth = if (mode == 2) width else screenWidth
val sourceHeight = if (mode == 2) height else screenHeight
val w = random.nextInt(1, sourceWidth + 1); val h = random.nextInt(1, sourceHeight + 1)
val x = random.nextInt(sourceWidth - w + 1); val y = random.nextInt(sourceHeight - h + 1)
val dx = random.nextInt(-w - 5, width + 5); val dy = random.nextInt(-h - 2, height + 2)
val expected = bytes.copyOf()
val expectedScreen = if (mode == 0) screenBytes.copyOf() else expected
val referenceTarget = DisplayListRenderer.Target(expected, width, height, offset, shift, clip)
val referenceSource = if (mode == 2) referenceTarget
else DisplayListRenderer.Target(expectedScreen, screenWidth, screenHeight, screenOffset)
val snapshot = IntArray(w * h) { referenceSource.get(x + it % w, y + it / w) }
for (i in snapshot.indices) referenceTarget.put(dx + i % w, dy + i / w, snapshot[i])
val target = DisplayListRenderer.Target(bytes, width, height, offset, shift, clip)
val screen = if (mode == 2) target else DisplayListRenderer.Target(screenBytes, screenWidth, screenHeight, screenOffset)
DisplayListRenderer(emptyMap()).execute(
DrawProtocol.sequence(listOf(DrawProtocol.rectCopy(sourceId, x, y, w, h, dx, dy))), target, screen)
assertContentEquals(expected, bytes, "case $case")
if (mode == 0) assertContentEquals(expectedScreen, screenBytes, "case $case screen")
}
}
@Test fun invalidGraphDoesNotCopyScreenIntoComposition() {
val screen = hex("12345678"); val composition = hex("9abcdef0")
val resources = mapOf(1 to DrawProtocol.displayList(listOf(byteArrayOf(99,0))))
@@ -259,6 +299,79 @@ class DisplayListTest {
assertEquals(0, output.get(if (right) 639 else 0, 240)) // cleared, not stale
}
}
@Test fun addedDepthJoinsOrInsertsTheDepthField() {
val copy = DrawProtocol.rectCopy(DrawProtocol.SCREEN, 0, 0, 4, 4, 0, 0)
assertContentEquals(DrawProtocol.rectCopy(DrawProtocol.SCREEN, 0, 0, 4, 4, 0, 0, depth = 8), DrawProtocol.withAddedDepth(copy, 8))
val targeted = DrawProtocol.image(3, 1, 2, target = 5, depth = -2)
assertContentEquals(DrawProtocol.image(3, 1, 2, target = 5, depth = 6), DrawProtocol.withAddedDepth(targeted, 8))
assertSame(copy, DrawProtocol.withAddedDepth(copy, 0))
assertContentEquals(DrawProtocol.image(3, 1, 2, depth = 127), DrawProtocol.withAddedDepth(DrawProtocol.image(3, 1, 2, depth = 120), 16))
}
/** The bottom switcher's Depth setting: the shell scene's depth moves the screen, shell layers and selections together. */
@Test fun shellSceneDepthShiftsTheWholePresentationButNotDimming() {
val c = SurfaceCompositor()
c.configureScreen(640, 480)
c.configureSurface("app", 32, 0, 576, 480, 0, 0)
c.submitSurface("app", ArrayByteReader(ByteArray(576 * 480) { if (it % 576 in 100 until 110) 255.toByte() else 0 }),
0, 0, 576, 480, "stripe")
// One white 2x1 shell layer at (200, 10), dimming what is under it, at layer depth -2; scene depth 8.
val header = listOf(1, 1, 200, 10, 2, 1, 128, 0, -2).flatMap { listOf(it.toByte(), (it shr 8).toByte()) }.toByteArray()
c.setShellScene(ArrayByteReader(header + byteArrayOf(-1, -1) + DrawProtocol.word(8)))
val composite = c.composite()
assertEquals(8, composite.shellScene.screenDepth)
val calls = composite.shellScene.calls(640, 480, intArrayOf(1), IntArray(0))
assertTrue(calls.any { it.contentEquals(DrawProtocol.lut(640, 480, 128)) }) // the dim stays whole-screen
val screen = BmpUtil.pack4bppFromGray8(composite.screenGray, 640, 480)
for (right in listOf(false, true)) {
val glasses = Glasses(right)
glasses.apply(ScenePlanner(ResourceCacheState()).plan(screen, 640, 480, null, composite.shellScene, 1).commands)
val output = DisplayListRenderer.Target(glasses.composition, 640, 480)
// Screen: half of 8 per lens. Layer: depth -2 + 8, so one pixel less than the screen's shift on each lens.
val shift = if (right) -4 else 4
val layerShift = if (right) -3 else 3
assertEquals(0, output.get(131 + shift, 200)); assertTrue(output.get(132 + shift, 200) > 0)
assertTrue(output.get(141 + shift, 200) > 0); assertEquals(0, output.get(142 + shift, 200))
assertEquals(15, output.get(200 + layerShift, 10)); assertEquals(15, output.get(201 + layerShift, 10))
}
// The phone mirror shows the scene unshifted, so touches land where they look.
val preview = assertNotNull(c.previewComposite()).gray
assertEquals(0, preview[131].toInt() and 255); assertTrue((preview[132].toInt() and 255) > 0)
// A covering surface's own depth still wins over the scene's.
c.configureSurface("glance", 0, 0, 640, 480, 900, 0)
c.setSurfaceDepth("glance", -16)
assertEquals(-16, c.composite().shellScene.screenDepth)
}
/** #42: stacked modal-sized layers overflow the cache, so the frame bakes the bottom ones instead of throwing. */
@Test fun shellOverTheResourceBudgetBakesBottomLayersAndRecovers() {
val cache = ResourceCacheState(); val planner = ScenePlanner(cache)
val gray = ByteArray(640 * 480) { 48 }; val app = BmpUtil.pack4bppFromGray8(gray, 640, 480)
fun layer(key: Int, y: Int, h: Int, nibble: Int, depth: Int = 0) =
ShellScene.Layer(key, 14, y, 612, h, 256, ByteArray(306 * h) { (nibble * 17).toByte() }, depth = depth)
// Each 612x214 layer is just under the 64 KiB resource cap; three exceed the arena on their own.
fun chrome(depth: Int) = layer(1, 444, 36, 7, depth)
val modals = listOf(layer(2, 10, 214, 9), layer(3, 120, 214, 11), layer(4, 230, 214, 13, depth = 4))
val overflow = ShellScene(listOf(chrome(6)) + modals)
val plan = planner.plan(app, 640, 480, null, overflow, 1)
assertEquals(2, plan.bakedLayers); assertFalse(plan.bakedSelections)
assertTrue(plan.commands.all { it.size <= 65535 })
assertTrue(cache.usedBytes() <= ResourceCacheState.CACHE_SIZE)
// Baked layers lose their stereo depth; the live ones keep it.
val expected = ShellScene(listOf(chrome(0)) + modals)
val lenses = listOf(Glasses(), Glasses(true))
for (glasses in lenses) {
glasses.apply(plan.commands)
assertContentEquals(BmpUtil.pack4bppFromGray8(expected.preview(gray, 640, 480, glasses.right), 640, 480), glasses.composition)
}
// Once the shell fits again, the next frame is fully live and the screen is the app's again.
val fits = ShellScene(listOf(chrome(0), modals[2]))
val next = planner.plan(app, 640, 480, null, fits, plan.nextFid)
assertEquals(0, next.bakedLayers)
for (glasses in lenses) {
glasses.apply(next.commands)
assertContentEquals(app, glasses.screen)
assertContentEquals(BmpUtil.pack4bppFromGray8(fits.preview(gray, 640, 480, glasses.right), 640, 480), glasses.composition)
}
}
@Test fun noisyFramesRemainBoundedAndResourceBudgetIs192KiB() {
val cache=ResourceCacheState();val planner=ScenePlanner(cache);val glasses=Glasses()
val app=ByteArray(640*480/2){(it*37).toByte()}
@@ -96,7 +96,9 @@ class DrawWireTest {
renderer.execute(DrawProtocol.sequence(listOf(call)), target)
screen.fill(0x12)
val savedResources = resources.mapValues { it.value.copyOf() }
val malformed = (0 until call.size).map { call.copyOf(it) } + listOf(call + byteArrayOf(0))
// A rounded rect may end in one outside-color byte (revision 36), but not one past 15.
val overlong = if (call[0].toInt() == DRAW_OP_ROUNDED_RECT) byteArrayOf(16) else byteArrayOf(0)
val malformed = (0 until call.size).map { call.copyOf(it) } + listOf(call + overlong, call + byteArrayOf(0, 0))
for (bad in malformed) {
assertFails { renderer.execute(DrawProtocol.sequence(listOf(valid, bad, valid)), target) }
assertContentEquals(ByteArray(16) { 0x12 }, screen)
@@ -4,13 +4,13 @@ import kotlin.test.*
class FrameDisplayListTest {
// Golden records emitted by display-list-authoring.test.cjs.
private val menu = "077e0000000300020002000200022a00000096000000010002000200ffffffff0200080000ff24017e30020000000001812c8001812c1611010017328001812c16103001812c3023414031ff24017c30020000000001812c8001812c1611010017328001812c16103001812c302341403102000200010001030400000000000000001f"
private val menu = "077f0000000300020002000200022a00000096000000010002000200ffffffff0200080000ff24017e30020000000001812c8001812c1611010017328001812c16103001812c3023414031ff24017c30020000000001812c8001812c1611010017328001812c16103001812c30234140310200020001000103100400000000000000001f"
private val multi = "0744000000030002000400010002000000000000000002000200010000ff010001006003000400000000000000001f0200000100000001000100020002feffffff7f00010001007f00"
private val scroll = "078a000000030002000400020000070000009600000001000200040011223344556677880200020000000000ff250100300102300180f0800180f0161101001732800180f01610300180f0302341403101001102000200010008000000ff280101300100300180f0800180f0161101001732800180f01610300180f030234140310100170100160400020000000103"
private val scroll = "078b000000030002000400020000070000009600000001000200040011223344556677880200020000000000ff250100300102300180f0800180f0161101001732800180f01610300180f0302341403101001102000200010008000000ff280101300100300180f0800180f0161101001732800180f01610300180f03023414031010017010016040002000000010310"
// Clipped clear, clipped rounded rect, and replayed glyph + icon records with
// placeholder atlas ids 0xbeef / 0xcafebabe, plus what they paint over a
// nibble-1 16x8 screen (display-list-authoring.test.cjs).
private val replay = "0780000000020003000800040000070000006400000000000300890000000000000600040002880000010001000200020000000400030000000510a00000000000000600040000ff2502000080c002000000000180c8800180c8161101001732800180c81610300180c830234031020000efbe4100000000000000ff01bebafeca04000100"
private val replay = "078100000002000300080004000007000000640000000000030089000000000000060004000288000001000100020002000000040003000000051010a00000000000000600040000ff2502000080c002000000000180c8800180c8161101001732800180c81610300180c830234031020000efbe4100000000000000ff01bebafeca04000100"
private val replayPixels = "11111111111111111111111111111111111111111111111111fff28f111111111125522211111111112552221111111111222222111111111111111111111111"
private fun hex(s: String) = s.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
private fun read(bytes: ByteArray, now: Long = 1150): FrameDisplayList {
@@ -43,7 +43,8 @@ class FrameDisplayListTest {
}
@Test fun animatedCopySourcesRebindOnPresentAndDestinationsTranslate() {
// Emitted by menu-scroll-animation.test.cjs: a menu strip scrolling from row 0 to row 2.
// Recorded from a since-removed menu-scroll-animation.test.cjs case (240ms slides):
// a menu strip scrolling from row 0 to row 2.
val list = read(hex(scroll)).translated(10, 10)
fun copy(elapsed: Long): List<Int> {
val call = DrawReader(list.calls(intArrayOf(5), 1150).first())
@@ -98,7 +99,7 @@ class FrameDisplayListTest {
// One opaque 1x1 shell layer, with one generic list after its pixels.
val layer = DrawProtocol.word(1) + DrawProtocol.word(1) + DrawProtocol.word(0) + DrawProtocol.word(0) +
DrawProtocol.word(1) + DrawProtocol.word(1) + DrawProtocol.word(256) + DrawProtocol.word(1) +
DrawProtocol.word(0) + byteArrayOf(32) + hex(multi)
DrawProtocol.word(0) + byteArrayOf(32) + hex(multi) + DrawProtocol.word(0)
val shell = ShellScene.decode(ArrayByteReader(layer))
assertEquals(2, shell.retainedResources.size)
assertEquals(240, shell.preview(ByteArray(64) { 32 }, 8, 8)[21].toInt() and 255)
@@ -141,6 +142,28 @@ class FrameDisplayListTest {
assertEquals(replayPixels, nibbles)
}
// A window-frame rounded rect (display-list-authoring.test.cjs): no fill, a
// border of 3, black outside the curve (revision 36), clipped short of its
// bottom row, over a nibble-9 12x8 screen.
private val frame = "072b00000002000100080006000000000000000000000000010088000000000000080005000000080006000300000300"
private val framePixels = "999999999999990333333099993399993399993999999399993999999399993399993399999999999999999999999999"
@Test fun roundedRectOutsideColorBridgesToTheTrailingByteAndPaintsLikeTheSoftwareRenderer() {
val call = read(hex(frame)).calls(IntArray(0), 0).single()
val plain = DrawProtocol.roundedRect(DrawValue.Integer(2), DrawValue.Integer(1), 8, 6, 3, 0, 3,
depth = 0, clip = DrawClip(2, 1, 8, 5))
assertContentEquals(plain + byteArrayOf(0), call)
val target = DisplayListRenderer.Target(ByteArray(48) { 0x99.toByte() }, 12, 8)
DisplayListRenderer(emptyMap()).execute(DrawProtocol.sequence(listOf(call)), target)
assertEquals(framePixels, (0 until 96).joinToString("") { target.get(it % 12, it / 12).toString(16) })
// Without the trailing byte the corners keep what was there; a color past 15 is rejected.
val corners = DisplayListRenderer.Target(ByteArray(48) { 0x99.toByte() }, 12, 8)
DisplayListRenderer(emptyMap()).execute(DrawProtocol.sequence(listOf(plain)), corners)
assertEquals(9, corners.get(2, 1)); assertEquals(3, corners.get(5, 1))
assertFails { DisplayListRenderer(emptyMap()).execute(DrawProtocol.sequence(listOf(plain + byteArrayOf(16))), corners) }
assertFails { DrawProtocol.roundedRect(DrawValue.Integer(0), DrawValue.Integer(0), 8, 6, 3, 0, 3, outside = 16) }
}
@Test fun replayWithAnUnknownRecordDrawsNothing() {
val list = read(registeredReplay(imageKnown = false), 1100)
assertTrue(list.resources.isEmpty())
@@ -10,6 +10,7 @@ import kotlin.test.assertTrue
private const val RIGHT = "AA:00:00:00:00:01"
private const val LEFT = "AA:00:00:00:00:02"
private const val STOCK_VERSION = "2.3.0.24"
/** The test platform with a clock the tests can jump forward (the real waits keep real time). */
private class ClockPlatform(private val base: ProtocolPlatform) : ProtocolPlatform by base {
@@ -62,6 +63,14 @@ private class FakeLink(private val platform: ProtocolPlatform) : SessionLink {
val connected = HashSet<String>()
val disconnected = ArrayList<String>()
@Volatile var closed = false
/** An address whose connection attempts fail, like an arm that isn't advertising. */
@Volatile var unreachable: String? = null
/**
* The firmware-extension string settings READ acks report alongside [STOCK_VERSION] on both
* arms ("" is stock firmware, which omits the field), or null for an ack without firmware info.
*/
@Volatile var firmwareExtension: String? = null
@Volatile var connects = 0
var seq = 0
val writes: List<Write>
@@ -71,10 +80,14 @@ private class FakeLink(private val platform: ProtocolPlatform) : SessionLink {
fun cfwMessages(): List<ByteArray> = writes.filter { it.sid == CfwTransport.SID && it.kind == "image" }.mapNotNull { it.message }
override fun connect(address: String, timeoutMs: Int): Boolean {
connected.add(address)
connects++
if (address == unreachable) return false
lock.withLock { connected.add(address) }
return true
}
override fun isConnected(address: String): Boolean = lock.withLock { address in connected }
override fun requestHighPriority(address: String) {}
override fun requestMtu(address: String, mtu: Int, timeoutMs: Int): Boolean = true
@@ -100,23 +113,32 @@ private class FakeLink(private val platform: ProtocolPlatform) : SessionLink {
if (sid == CfwTransport.SID) {
for (lens in 1..2) core.onNotification(address, BleProtocol.NOTIFY_CHAR_UUID, cfwAck(magic, lens, inFlight.message.size, inFlight.cfwChecksum))
} else {
core.onNotification(address, BleProtocol.NOTIFY_CHAR_UUID, ackFrame(sid, magic, pb))
core.onNotification(address, BleProtocol.NOTIFY_CHAR_UUID, ackFrame(sid, magic, inFlight.kind))
}
}
return true
}
private fun ackFrame(sid: Int, magic: Int, request: ByteArray): ByteArray {
private fun ackFrame(sid: Int, magic: Int, kind: String?): ByteArray {
val extension = firmwareExtension
val body = if (sid == BleProtocol.SID_SECURITY_AUTH)
BleProtocol.encodeVarintField(1, 4) + BleProtocol.encodeVarintField(2, magic) + byteArrayOf(0x1a, 0x00)
else if (kind == "battery" && extension != null)
BleProtocol.encodeVarintField(1, 1) + BleProtocol.encodeVarintField(2, magic) +
BleProtocol.encodeBytesField(4,
BleProtocol.encodeBytesField(5, STOCK_VERSION.encodeToByteArray()) +
BleProtocol.encodeBytesField(6, STOCK_VERSION.encodeToByteArray())) +
(if (extension.isEmpty()) ByteArray(0) else BleProtocol.encodeBytesField(100, extension.encodeToByteArray()))
else
BleProtocol.encodeVarintField(1, 1) + BleProtocol.encodeVarintField(2, magic)
return BleProtocol.framePb(body, sid, 0x00, seq++)[0]
}
override fun disconnect(address: String) {
disconnected.add(address)
connected.remove(address)
lock.withLock {
disconnected.add(address)
connected.remove(address)
}
}
override fun close() {
@@ -196,12 +218,15 @@ private class FakeHost(private val platform: ProtocolPlatform) : SessionHost {
private class FakeListener : FaceclawBleCommunicatorListener {
val phases = ArrayList<String>()
@Volatile var lastStatus = ""
val events = ArrayList<String>()
val finished = ArrayList<String>()
val batteries = ArrayList<String>()
val firmware = ArrayList<String>()
override fun onStateChange(phase: String?, status: String?) {
phases.add(phase ?: "")
lastStatus = status ?: ""
}
override fun onRingEvent(kind: String?, containerName: String?, eventType: Int, eventSource: Int, systemExitReasonCode: Int, frameId: Int, ringTick: Long, ringType: Int, ringAux: Int, ringSpeed: Int) {
@@ -226,7 +251,9 @@ private class FakeListener : FaceclawBleCommunicatorListener {
finished.add("$frameId:$outcome")
}
override fun onFirmwareInfo(leftVersion: String?, rightVersion: String?, extension: String?) {}
override fun onFirmwareInfo(leftVersion: String?, rightVersion: String?, extension: String?) {
firmware.add("$leftVersion|$rightVersion|$extension")
}
}
private class Session {
@@ -454,4 +481,214 @@ class GlassesSessionCoreTest {
assertContentEquals(first.message, second.message)
s.core.disconnect()
}
@Test
fun aCfwAckSlowerThanHalfASecondIsNotReplayed() {
val s = Session()
s.link.muted.add("image")
s.startAndAwaitLayout()
s.core.configureCompositorScreen(64, 32)
s.core.configureSurface("s", 0, 0, 64, 32, 0, SurfaceCompositor.TRANSPARENCY_OPAQUE)
try {
s.submitFrame(3, 0x20, 1)
assertTrue(waitUntil(5_000) { s.link.cfwMessages().size == 1 })
// Well past the old 500 ms deadline, but inside the 3 s ack window.
s.platform.offsetMs += 1_500
sleepMs(400)
assertFalse(s.host.hasLog("CFW recovery"), s.host.logs().takeLast(10).toString())
assertEquals(1, s.link.cfwMessages().size)
// The late ack still completes the frame.
val first = s.link.writes.first { it.sid == CfwTransport.SID && it.kind == "image" }
val message = assertNotNull(s.core.monitor.withLock { s.core.inFlightMessages.firstOrNull { it.magic == first.magic } })
for (lens in 1..2) {
s.core.onNotification(LEFT, BleProtocol.NOTIFY_CHAR_UUID, cfwAck(first.magic, lens, message.message.size, message.cfwChecksum))
}
assertTrue(waitUntil(3_000) { s.displayedMatchesDesired() })
} finally {
s.core.close()
}
}
@Test
fun cfwAckDeadlinesFollowTheirOwnArmsWritesAndAcks() {
val core = Session().core
fun cfw(magic: Int, leftArm: Boolean) = OutboundMessage(
"image", "m$magic", CfwTransport.SID, 0, magic, byteArrayOf(1), CfwMessageWindow.ACK_STALL_MS, 0, leftArm)
val left = cfw(1, true)
val right = cfw(2, false)
core.monitor.withLock {
for (message in listOf(left, right)) {
message.sentAtMs = 1_000
message.ackDeadlineAtMs = 4_000
core.inFlightMessages.addLast(message)
}
core.lastArmCfwAckAtMs[0] = 2_000
core.lastArmWriteAtMs[1] = 5_000
core.refreshCfwAckDeadlinesLocked()
}
assertEquals(5_000L, left.ackDeadlineAtMs)
assertEquals(5_500L, right.ackDeadlineAtMs)
// Any CFW ack from an arm counts as that arm's progress, matched or not.
val before = core.now()
core.onNotification(LEFT, BleProtocol.NOTIFY_CHAR_UUID, cfwAck(77, 1, 1, 0))
assertTrue(core.monitor.withLock { core.lastArmCfwAckAtMs[0] } >= before)
assertEquals(0L, core.monitor.withLock { core.lastArmCfwAckAtMs[1] })
}
@Test
fun reconnectBackoffGrowsAndRestartsAfterAStableSession() {
val core = Session().core
core.monitor.withLock {
assertEquals(2_000L, core.scheduleReconnectLocked(false))
assertEquals(6_000L, core.scheduleReconnectLocked(false))
assertEquals(10_000L, core.scheduleReconnectLocked(false))
assertEquals(10_000L, core.scheduleReconnectLocked(false))
// A session that dies soon after coming up keeps backing off...
core.lastSessionReadyAtMs = core.now() - 1_000
assertEquals(10_000L, core.scheduleReconnectLocked(true))
// ...one that stayed up starts the schedule over.
core.lastSessionReadyAtMs = core.now() - ConnectionOptions.STABLE_SESSION_MS
assertEquals(2_000L, core.scheduleReconnectLocked(true))
assertEquals(6_000L, core.scheduleReconnectLocked(false))
}
}
@Test
fun unreachableArmIsNamedAndRetriedWithBackoff() {
val s = Session()
s.link.unreachable = LEFT
fun retryDelayMs() = s.core.monitor.withLock { s.core.reconnectAfterMs } - s.platform.elapsedRealtimeMs()
fun attempts() = s.core.monitor.withLock { s.core.consecutiveReconnects }
try {
assertTrue(s.core.start())
assertTrue(waitUntil(5_000) { attempts() == 1 }, s.host.logs().takeLast(10).toString())
assertTrue(s.host.hasLog("Transport failure: left arm not found"))
assertTrue(s.listener.lastStatus.startsWith("Can't reach the left arm"), s.listener.lastStatus)
assertTrue(retryDelayMs() in 1_000L..2_000L)
// Both arms are torn down, so the right arm doesn't sit connected on its own.
assertTrue(s.link.disconnected.containsAll(listOf(RIGHT, LEFT)))
s.platform.offsetMs += 2_000
assertTrue(waitUntil(5_000) { attempts() == 2 })
assertTrue(retryDelayMs() in 5_000L..6_000L)
s.platform.offsetMs += 6_000
assertTrue(waitUntil(5_000) { attempts() == 3 })
assertTrue(retryDelayMs() in 9_000L..10_000L)
// Once the arm answers again, the session comes up.
s.link.unreachable = null
s.platform.offsetMs += 10_000
assertTrue(waitUntil(5_000) { s.layoutCreated() }, s.host.logs().takeLast(10).toString())
} finally {
s.core.close()
}
}
@Test
fun stockFirmwareHaltsTheSessionBeforeAnyCustomFirmwareTraffic() {
val s = Session()
s.core.setRequiredFirmwareRevision(36)
s.link.firmwareExtension = ""
try {
assertTrue(s.core.start())
assertTrue(waitUntil(5_000) { s.listener.phases.contains("incompatible-firmware") }, s.host.logs().takeLast(10).toString())
assertEquals(listOf("$STOCK_VERSION|$STOCK_VERSION|"), s.listener.firmware)
assertTrue(s.host.hasLog("incompatible firmware"), s.host.logs().takeLast(10).toString())
// The settings reply precedes the layout, so stock never sees a private-stream message.
assertEquals(0, s.link.writes.count { it.kind == "create-layout" })
assertEquals(0, s.link.writes.count { it.sid == CfwTransport.SID })
assertTrue(s.link.disconnected.containsAll(listOf(RIGHT, LEFT)))
assertFalse(s.core.isSessionReady())
// Parked rather than retrying: no redial even well past the backoff schedule.
val connects = s.link.connects
s.platform.offsetMs += 60_000
s.core.interruptibleSleep.interrupt()
sleepMs(300)
assertEquals(connects, s.link.connects)
assertEquals("incompatible-firmware", s.listener.phases.last())
assertFalse(s.listener.phases.contains("retrying"))
} finally {
s.core.close()
}
}
@Test
fun anOlderFaceclawRevisionAlsoHalts() {
val s = Session()
s.core.setRequiredFirmwareRevision(36)
s.link.firmwareExtension = "Faceclaw/35"
try {
assertTrue(s.core.start())
assertTrue(waitUntil(5_000) { s.listener.phases.contains("incompatible-firmware") }, s.host.logs().takeLast(10).toString())
assertEquals(0, s.link.writes.count { it.kind == "create-layout" })
} finally {
s.core.close()
}
}
@Test
fun compatibleFirmwareIsCheckedAgainOnEverySession() {
val s = Session()
s.core.setRequiredFirmwareRevision(36)
s.link.firmwareExtension = "Faceclaw/36"
try {
s.startAndAwaitLayout()
assertTrue(s.core.monitor.withLock { s.core.customFirmwareDetected })
assertFalse(s.listener.phases.contains("incompatible-firmware"))
// The glasses come back on stock firmware (reflashed while the link was down):
// the new session's own settings query catches it before the layout.
s.link.firmwareExtension = ""
s.core.handleTransportFailure("test drop")
s.platform.offsetMs += 10_000
s.core.interruptibleSleep.interrupt()
assertTrue(waitUntil(5_000) { s.listener.phases.contains("incompatible-firmware") }, s.host.logs().takeLast(10).toString())
assertEquals(2, s.link.writes.count { it.kind == "battery" })
assertEquals(1, s.link.writes.count { it.kind == "enter-evenhub" })
assertEquals(0, s.link.writes.count { it.kind == "create-layout" })
} finally {
s.core.close()
}
}
@Test
fun customFirmwareEntersEvenHubOnEverySessionInsteadOfCreatingTheLayout() {
val s = Session()
s.core.setRequiredFirmwareRevision(37)
s.link.firmwareExtension = "Faceclaw/37"
try {
s.startAndAwaitLayout()
fun enters() = s.link.writes.filter { it.kind == "enter-evenhub" }
assertEquals(1, enters().size)
assertEquals(CfwTransport.SID, enters()[0].sid)
assertContentEquals(byteArrayOf(CFW_MSG_ENTER_EVENHUB.toByte()), enters()[0].message)
// The settings reply that identifies the firmware comes first.
assertTrue(s.link.writes.indexOfFirst { it.kind == "battery" } < s.link.writes.indexOf(enters()[0]))
// A reconnect may find the previous session's page still up. Mode 31
// ACKs in that state, so the session is entered the same way again.
s.core.handleTransportFailure("test drop")
assertTrue(waitUntil(5_000) { !s.layoutCreated() })
s.platform.offsetMs += 10_000
s.core.interruptibleSleep.interrupt()
assertTrue(waitUntil(5_000) { s.layoutCreated() && enters().size == 2 }, s.host.logs().takeLast(10).toString())
assertEquals(0, s.link.writes.count { it.kind == "create-layout" })
} finally {
s.core.close()
}
}
@Test
fun firmwareCompatibilityFollowsTheRevisionString() {
fun info(extension: String) = BleProtocol.FirmwareInfo(STOCK_VERSION, STOCK_VERSION, extension)
assertEquals(-1, info("").faceclawRevision())
assertEquals(-1, info("EVENCFW/22 img640").faceclawRevision())
assertEquals(-1, info("Faceclaw/abc").faceclawRevision())
assertEquals(-1, info("OtherCFW/36").faceclawRevision())
assertEquals(36, info(" Faceclaw/36 ").faceclawRevision())
assertFalse(info("").isCompatible(36))
assertFalse(info("Faceclaw/35").isCompatible(36))
assertTrue(info("Faceclaw/36").isCompatible(36))
assertTrue(info("Faceclaw/40").isCompatible(36))
assertTrue(info("Faceclaw/1").isCompatible(0))
assertFalse(info("EVENCFW/22").isCompatible(0))
}
}
@@ -43,7 +43,7 @@ class PreviewPackingTest {
compositor.configureSurface("app", 0, 0, 3, 2, 0, SurfaceCompositor.TRANSPARENCY_OPAQUE)
// One white 2x1 shell layer at (0,0), with no dimming or selection.
val header = listOf(1, 1, 0, 0, 2, 1, 256, 0, 0).flatMap { listOf(it.toByte(), (it shr 8).toByte()) }.toByteArray()
compositor.setShellScene(ArrayByteReader(header + byteArrayOf(-16, -16)))
compositor.setShellScene(ArrayByteReader(header + byteArrayOf(-16, -16) + DrawProtocol.word(0)))
val wire = compositor.applyAndComposite("app", ArrayByteReader(ByteArray(6) { 32 }), 0, 0, 3, 2, "first")
assertSame(wire.screenGray, wire.gray) // ShellScene.preview allocates its own pixels.
assertContentEquals(ByteArray(6) { 32 }, wire.screenGray)
@@ -212,6 +212,18 @@ class ProtocolTest {
assertTrue(CfwMessageWindow.canSend(listOf(eviction), upload))
}
@Test
fun cfwAckDeadlineWaitsWhileEitherWritesOrAcksProgress() {
// Sent at 1000 into an idle arm: 3 s from the send.
assertEquals(4_000L, CfwMessageWindow.ackDeadline(1_000, 1_000, 0))
// An ack from the arm restarts the 3 s ack window.
assertEquals(5_500L, CfwMessageWindow.ackDeadline(1_000, 1_000, 2_500))
// Writes still completing keep it waiting past the ack window, 500 ms at a time.
assertEquals(6_700L, CfwMessageWindow.ackDeadline(1_000, 6_200, 2_500))
// An ack from before the send doesn't shorten anything.
assertEquals(4_000L, CfwMessageWindow.ackDeadline(1_000, 1_000, 900))
}
@Test
fun orderedCompletionAndWholeWindowRecovery() {
val head = message()
@@ -97,6 +97,46 @@ class SharedGraphicsTest {
assertContentEquals(byteArrayOf(-56, -56, 0, -56, -56, 0), c.composite().gray)
}
@Test
fun surfaceIsCurrentOnlyAfterItsContentAndEveryChangeWasComposited() {
val c = SurfaceCompositor()
c.configureScreen(3, 2)
c.configureSurface("app", 0, 0, 3, 2, 0, 0)
assertFalse(c.isSurfaceCurrent("app", ""))
c.applyAndComposite("app", ArrayByteReader(ByteArray(6) { 200.toByte() }), 0, 0, 3, 2, "a")
assertTrue(c.isSurfaceCurrent("app", "a"))
assertFalse(c.isSurfaceCurrent("app", "b"))
assertFalse(c.isSurfaceCurrent("missing", "a"))
// A preview composite is not kept, so it does not apply pending changes.
c.setUnderlayDim(1, 128)
assertFalse(c.isSurfaceCurrent("app", "a"))
c.previewComposite()
assertFalse(c.isSurfaceCurrent("app", "a"))
c.composite()
assertTrue(c.isSurfaceCurrent("app", "a"))
for (change in listOf<() -> Unit>(
{ c.configureSurface("app", 1, 0, 3, 2, 0, 0) },
{ c.setSurfaceVisible("app", false) },
{ c.setSurfaceDepth("app", 2) },
{ c.setBlanked(false) },
{ c.removeSurface("other") },
)) {
change()
assertFalse(c.isSurfaceCurrent("app", "a"))
c.composite()
assertTrue(c.isSurfaceCurrent("app", "a"))
}
// Submitting without compositing retains the content but leaves it unapplied.
c.submitSurface("app", ArrayByteReader(ByteArray(6)), 0, 0, 3, 2, "b")
assertFalse(c.isSurfaceCurrent("app", "b"))
c.composite()
assertTrue(c.isSurfaceCurrent("app", "b"))
// A resize discards the retained content.
c.configureSurface("app", 0, 0, 2, 2, 0, 0)
c.composite()
assertFalse(c.isSurfaceCurrent("app", "b"))
}
@Test
fun pngChunksAndPixels() {
val png = SharedScreenshots.encode4BitGrayPng(byteArrayOf(0, 16, -1, 32, 48, 64), 3, 2)
@@ -0,0 +1,75 @@
package com.faceclaw.app
import kotlin.test.*
class VideoFrameScalerTest {
private val identity = ByteArray(256) { it.toByte() }
private fun scale(scaler: VideoFrameScaler, luma: ByteArray, lut: ByteArray = identity): IntArray {
val out = ByteArray(scaler.outputWidth * scaler.outputHeight)
scaler.scale(luma, 0, scaler.sourceWidth, 1, lut, out)
return IntArray(out.size) { out[it].toInt() and 0xff }
}
@Test fun twoToOneDownscaleAveragesEachBox() {
// 4x2 source -> 2x1: each output is the mean of a 2x2 box.
val luma = byteArrayOf(0, 100, 200.toByte(), 200.toByte(), 20, 80, 100, 100)
val scaler = VideoFrameScaler(4, 2, 0, 2, 1)
assertContentEquals(intArrayOf(50, 150), scale(scaler, luma))
}
@Test fun largeDownscaleStaysWithinTheTapBudget() {
// 100:1 horizontally still averages only MAX_TAPS samples, spread across the box.
val luma = ByteArray(200) { (if (it % 100 < 50) 0 else 200).toByte() }
val scaler = VideoFrameScaler(200, 1, 0, 2, 1)
assertContentEquals(intArrayOf(100, 100), scale(scaler, luma))
}
@Test fun upscaleIsNearestNeighbor() {
val scaler = VideoFrameScaler(2, 1, 0, 4, 2)
assertContentEquals(intArrayOf(10, 10, 90, 90, 10, 10, 90, 90), scale(scaler, byteArrayOf(10, 90)))
}
@Test fun offsetAndStridesSelectTheVisiblePlane() {
// A 2x2 visible crop at (1, 1) of a 4-wide plane, with interleaved samples (pixelStride 2).
val plane = ByteArray(40)
fun put(x: Int, y: Int, v: Int) { plane[(1 + y) * 10 + 1 + x * 2] = v.toByte() }
put(0, 0, 11); put(1, 0, 22); put(0, 1, 33); put(1, 1, 44)
val scaler = VideoFrameScaler(2, 2, 0, 2, 2)
val out = ByteArray(4)
scaler.scale(plane, 11, 10, 2, identity, out)
assertContentEquals(byteArrayOf(11, 22, 33, 44), out)
}
@Test fun rotationsMatchTheContainerClockwiseConvention() {
// Coded 3x2: 1 2 3
// 4 5 6
val luma = byteArrayOf(1, 2, 3, 4, 5, 6)
assertContentEquals(intArrayOf(4, 1, 5, 2, 6, 3), scale(VideoFrameScaler(3, 2, 90, 2, 3), luma))
assertContentEquals(intArrayOf(6, 5, 4, 3, 2, 1), scale(VideoFrameScaler(3, 2, 180, 3, 2), luma))
assertContentEquals(intArrayOf(3, 6, 2, 5, 1, 4), scale(VideoFrameScaler(3, 2, 270, 2, 3), luma))
}
@Test fun normalizeRotationSnapsToQuarterTurns() {
assertEquals(0, VideoFrameScaler.normalizeRotation(0))
assertEquals(90, VideoFrameScaler.normalizeRotation(90))
assertEquals(270, VideoFrameScaler.normalizeRotation(-90))
assertEquals(180, VideoFrameScaler.normalizeRotation(540))
assertEquals(0, VideoFrameScaler.normalizeRotation(359))
}
@Test fun limitedRangeStretchesAndMonochromeThresholds() {
val gray = VideoFrameScaler.toneLut(limitedRange = true, gamma = 1f, monochrome = false)
assertEquals(0, gray[16].toInt() and 0xff)
assertEquals(0, gray[0].toInt() and 0xff)
assertEquals(255, gray[235].toInt() and 0xff)
assertEquals(255, gray[255].toInt() and 0xff)
val mono = VideoFrameScaler.toneLut(limitedRange = false, gamma = 2.2f, monochrome = true)
assertEquals(0, mono[127].toInt() and 0xff)
assertEquals(255, mono[128].toInt() and 0xff)
// Gamma darkens midtones but leaves the ends alone.
val photo = VideoFrameScaler.toneLut(limitedRange = false, gamma = 2.2f, monochrome = false)
assertTrue((photo[128].toInt() and 0xff) < 64)
assertEquals(255, photo[255].toInt() and 0xff)
}
}
+18 -33
View File
@@ -7,7 +7,6 @@ const graphics=require('../.test-build/app/graphics/image.js');
const planes=require('../.test-build/app/graphics/plane.js');
const wire=require('../.test-build/app/graphics/presentation-wire.js');
const {encodeShellScene}=require('../.test-build/app/graphics/shell-scene.js');
const {SurfaceCompositor}=require('../.test-build/app/graphics/surface-compositor.js');
function load(file,modules) {
const context={exports:{},require:name=>{assert.ok(name in modules, name);return modules[name];}};
vm.runInNewContext(ts.transpileModule(fs.readFileSync(file,'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2020}}).outputText,context);
@@ -19,7 +18,7 @@ const menuCore=load('app/ui/menu-core.ts',{
'../graphics/image':graphics,'./menu-highlight-motion': require('../.test-build/app/ui/menu-highlight-motion.js'), '../graphics/menu-scroll-list': require('../.test-build/app/graphics/menu-scroll-list.js'), './menu-scroll-motion': require('../.test-build/app/ui/menu-scroll-motion.js'), '../graphics/draw-expression': require('../.test-build/app/graphics/draw-expression.js'),
});
const {MenuLayer}=load('app/ui/menu.ts',{
'./menu-animation-pref': require('../.test-build/app/ui/menu-animation-pref.js'), '../native/settings-store': { getBooleanSetting: (_key, fallback) => fallback },
'./menu-animation-pref': require('../.test-build/app/ui/menu-animation-pref.js'), './animation-speed': require('../.test-build/app/ui/animation-speed.js'), '../native/settings-store': { getStringSetting: (_key, fallback) => fallback },
'../graphics/image':graphics,'../graphics/textwrap':{},'../graphics/ui-fonts':{getDefaultSmallFont:()=>font},
'../util/numeric-util':{clamp:(n,a,b)=>Math.max(a,Math.min(b,n))},'./gestures':{},
'./menu-highlight-motion': require('../.test-build/app/ui/menu-highlight-motion.js'), '../graphics/menu-scroll-list': require('../.test-build/app/graphics/menu-scroll-list.js'), './menu-scroll-motion': require('../.test-build/app/ui/menu-scroll-motion.js'), '../graphics/draw-expression': require('../.test-build/app/graphics/draw-expression.js'),
@@ -37,27 +36,17 @@ test('menu retains the selected text and rounded highlight on the menu plane',as
assert.ok(row.source.pixels.some(v=>v===255));assert.ok(!image.withDrawsBaked(false).pixels.some(v=>v===255));
const flat=planes.flattenPlanesWithDraws([{image,x:0,y:0}]);
const records=wire.presentationRecords(prepareFrameDraws(flat.draws));assert.equal(records.length,1);
const c=new SurfaceCompositor(80,80);c.configureSurface('app',{x:0,y:0,width:80,height:80,zOrder:0,transparency:'opaque'});
c.submitSurfaceFrame('app',flat.image.pixels,{x:0,y:0,width:80,height:80},prepareFrameDraws(flat.draws));
const screen=flat.image.pixels.slice(),preview=c.composite();
assert.ok(preview.some(v=>v===240));assert.deepEqual(flat.image.pixels,screen);
await m.layer.handleInput({type:'scroll-down'},m.context);
const next=m.paint().draws.find(d=>d.presentation);assert.ok(next.y>row.y);assert.equal(next.presentation.depth,0);
});
test('shell menu selection survives serialization and is not baked into its surface',()=>{
test('shell menu selection survives serialization',()=>{
const image=menu().paint(),bytes=encodeShellScene([{image,x:0,y:0,shellKey:7}]);
assert.equal(new DataView(bytes.buffer).getUint16(14,true),1);
const c=new SurfaceCompositor(80,80);c.setShellScene(bytes);assert.ok(c.composite().some(v=>v===240));
});
test('later opaque planes occlude a replayed selection without erasing its visible part',()=>{
test('later opaque planes add an occlusion to a replayed selection',()=>{
const image=menu().paint(),row=image.draws.find(d=>d.presentation),cover=new graphics.GrayImage(10,8,1);
const flat=planes.flattenPlanesWithDraws([{image,x:0,y:0},{image:cover,x:row.x+10,y:row.y+2}]);
const records=wire.presentationRecords(prepareFrameDraws(flat.draws));assert.ok(records[0].displayList.calls.some(c => c.op === 2 && c.resource === 65535));
const c=new SurfaceCompositor(80,80);c.configureSurface('app',{x:0,y:0,width:80,height:80,zOrder:0,transparency:'opaque'});
c.submitSurfaceFrame('app',flat.image.pixels,{x:0,y:0,width:80,height:80},prepareFrameDraws(flat.draws));
const preview=c.composite();
for(let y=row.y+2;y<row.y+10;y++) for(let x=row.x+10;x<row.x+20;x++) assert.equal(preview[y*80+x],0);
assert.ok(preview.some(v=>v===240));
});
const {LayerStack,noopLayerActions}=load('app/ui/layers.ts',{
@@ -71,45 +60,37 @@ test('context menu surface and selected row both use +4 without changing the app
assert.deepEqual(frame.image.pixels,base.pixels);
const records=wire.presentationRecords(prepareFrameDraws(frame.draws));
assert.deepEqual(records.map(r=>r.depth),[4,4]);assert.equal(records[0].mode,'masked-image');
const c=new SurfaceCompositor(100,90);c.configureSurface('app',{x:0,y:0,width:100,height:90,zOrder:0,transparency:'opaque'});
c.submitSurfaceFrame('app',frame.image.pixels,{x:0,y:0,width:100,height:90},prepareFrameDraws(frame.draws));
const preview=c.composite();
assert.equal(preview[45*100+10],96); // old left edge has no baked menu
assert.equal(preview[45*100+13],0); // shifted opaque black interior
assert.equal(preview[8*100+12],96); // transparent rounded corner
assert.ok(preview.some(v=>v===240));
stack.pop();const closed=planes.flattenPlanesWithDraws(stack.paint());
c.submitSurfaceFrame('app',closed.image.pixels,{x:0,y:0,width:100,height:90},prepareFrameDraws(closed.draws));
assert.deepEqual(c.composite(),base.pixels);
assert.deepEqual(closed.image.pixels,base.pixels);
assert.deepEqual(wire.presentationRecords(prepareFrameDraws(closed.draws)),[]);
});
test('system menu bridge shifts its surface and selected row together by +4',()=>{
const image=menu().paint(),bytes=encodeShellScene([{image,x:8,y:0,shellKey:7,depth:4}]);
const view=new DataView(bytes.buffer),w=view.getUint16(8,true),h=view.getUint16(10,true);
assert.equal(view.getInt16(16,true),4);
assert.equal(wire.readPresentation(bytes,18+w*h).selection.depth,4);
const c=new SurfaceCompositor(100,80);c.setShellScene(bytes);const preview=c.composite();
assert.equal(preview[40*100+8],0);assert.equal(preview[40*100+10],80);
});
test('unselected sidebar icons retain -2 depth through shell cropping, including attention badges',()=>{
const shellScene=require('../.test-build/app/graphics/shell-scene.js');
const {ShellChromeLayer}=load('app/ui/shell/chrome-layer.ts',{
'../../graphics/shell-scene':shellScene,'../../graphics/image':graphics,
'../../graphics/shell-scene':shellScene,'../../graphics/image':graphics,'../../graphics/display-list':require('../.test-build/app/graphics/display-list.js'),
'../../graphics/ui-fonts':{getDefaultSmallFont:()=>font,getDefaultMediumFont:()=>font},
'../../graphics/textwrap':{},'./ambient-cards':{},'../../graphics/battery':{},
'../../native/notification-icons':{},'../../native/phone-battery':{},'../../util/render-freshness':{},
'../../graphics/icons':{},'../dashboard-settings':{},'../clock-format':{},'../../graphics/bdffont':{},
'../layers':{LayerStack},'../menu':{scrollToKeepSelectionVisible:()=>0},'../metrics':{},
'./geometry':{MIN_WINDOW_HEIGHT:280,minWindowTop:()=>0,windowTop:()=>0,SHELL_OPAQUE_BLACK:1,SIDEBAR_WIDTH:64,TOP_BAR_HEIGHT:24},
'./geometry':{MIN_WINDOW_HEIGHT:280,minWindowTop:()=>0,windowTop:()=>0,SHELL_OPAQUE_BLACK:1,SIDEBAR_WIDTH:64,TOP_BAR_HEIGHT:24,
SWITCHER_ROW_HEIGHT:36,switcherPosition:()=>'left',switcherRect:()=>({x:0,y:0,width:64,height:280})},
});
const state={selectedIndex:0,focus:'sidebar',windows:[0,1,2].map(n=>({attention:n===1,drawIcon:(image,x,y)=>image.fillRect(x,y,4,4,240)}))};
const chrome=new ShellChromeLayer(()=>state),image=new graphics.GrayImage(640,480);
chrome.drawSidebar(image,state);
assert.deepEqual(Array.from(image.draws.filter(d=>d.presentation),d=>d.presentation.depth),[-2,-2]);
const crop=shellScene.shellCrop(image,0,0,64,280,1),bytes=encodeShellScene([crop]);
const c=new SurfaceCompositor(640,480);c.setShellScene(bytes);const preview=c.composite();
assert.equal(preview[34*640+30],240); // selected icon stays at its original x
assert.equal(preview[74*640+29],240); // unselected icon moves left by one
assert.equal(preview[74*640+33],0); // no baked copy at the original right edge
const view=new DataView(bytes.buffer),w=view.getUint16(8,true),h=view.getUint16(10,true);
assert.equal(view.getUint16(14,true),2);
const first=wire.readPresentation(bytes,18+w*h),second=wire.readPresentation(bytes,first.end);
assert.deepEqual([first.selection.depth,second.selection.depth],[-2,-2]);
state.selectedIndex=1;const next=new graphics.GrayImage(640,480);chrome.drawSidebar(next,state);
assert.equal(next.draws.filter(d=>d.presentation).length,2);
});
@@ -128,6 +109,10 @@ test('shell modal carries its inner menu highlight animation instead of baking i
const image=paint(),row=image.draws.find(d=>d.presentation);
assert.ok(row.y>before.y);assert.ok(row.presentation.displayList.timeline,'the slide stays a timed display list');
assert.ok(!image.withDrawsBaked(false).pixels.some(v=>v===255),'selected text is not baked into the modal surface');
const c=new SurfaceCompositor(200,200);c.setShellScene(encodeShellScene([{image,x:0,y:0,shellKey:9}]));
assert.ok(c.composite().some(v=>v===240));
});
test('shell crop widens a fractional rect (TTF-measured status bar) to whole pixels',()=>{
const {shellCrop}=require('../.test-build/app/graphics/shell-scene.js'),image=new graphics.GrayImage(576,288,7);
const crop=shellCrop(image,400.5,250,175.5,15,2);
assert.deepEqual([crop.x,crop.y,crop.image.width,crop.image.height],[400,250,176,15]);
assert.ok(crop.image.pixels.every(v=>v===7));
});
+22 -44
View File
@@ -1,17 +1,12 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { Menu } = require('../.test-build/app/ui/menu-core.js');
const { MENU_HIGHLIGHT_DURATION_MS } = require('../.test-build/app/ui/menu-highlight-motion.js');
const { MenuHighlightMotion, MENU_HIGHLIGHT_DURATION_MS } = require('../.test-build/app/ui/menu-highlight-motion.js');
const { GrayImage } = require('../.test-build/app/graphics/image.js');
const { DrawOp, encodeDisplayList, readDisplayList } = require('../.test-build/app/graphics/display-list.js');
const { DrawOp } = require('../.test-build/app/graphics/display-list.js');
const { evaluate } = require('../.test-build/app/graphics/draw-expression.js');
const { DrawExpression: E } = require('../.test-build/app/graphics/draw-expression.js');
const { menuScrollList, slidingHighlightY } = require('../.test-build/app/graphics/menu-scroll-list.js');
const { MENU_BOUNCE_DURATION_MS, scrollOffsetExpression } = require('../.test-build/app/ui/menu-scroll-motion.js');
const { encodePresentation } = require('../.test-build/app/graphics/presentation-wire.js');
const { MenuScrollMotion, MENU_BOUNCE_DURATION_MS } = require('../.test-build/app/ui/menu-scroll-motion.js');
const { setMenuAnimationReader } = require('../.test-build/app/ui/menu-animation-pref.js');
// Also consumed by FrameDisplayListTest.kt.
const SCROLL = '078a000000030002000400020000070000009600000001000200040011223344556677880200020000000000ff250100300102300180f0800180f0161101001732800180f01610300180f0302341403101001102000200010008000000ff280101300100300180f0800180f0161101001732800180f01610300180f030234140310100170100160400020000000103';
const BOX = { x: 10, y: 5, width: 40, height: 60 };
const ITEMS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
@@ -182,24 +177,9 @@ test('an end without wrap or exit callback bounces, carrying the highlight with
assert.equal(scrollLists(paint(exiting, 2000)).length, 0, 'an exit callback replaces the bounce');
});
test('a bounce during a scroll starts from the offset on screen', () => {
const menu = inkMenu();
menu.select(4);
paint(menu, 1000);
menu.moveSelection(1);
paint(menu, 2000); // 60 -> 80, the end
menu.moveSelection(1);
paint(menu, 2060); // the highlight moves to the last row; no further scroll
assert.equal(menu.selectedIndex, 6);
menu.moveSelection(1);
const [list] = scrollLists(paint(menu, 2120));
const offsets = [0, MENU_BOUNCE_DURATION_MS].map((ms) => evaluate(list.calls[0].y, ms, 0).value);
assert.ok(offsets[0] < offsets[1], 'it starts where the scroll had got to, above its settled offset');
});
test('with menu animation off, scrolls, slides and bounces snap', (t) => {
setMenuAnimationReader(() => false);
t.after(() => setMenuAnimationReader(() => true));
test('with menu animation disabled, scrolls, slides and bounces snap', (t) => {
setMenuAnimationReader(() => 'disabled');
t.after(() => setMenuAnimationReader(() => 'normal'));
const timed = (image) => image.draws.filter((draw) => draw.presentation?.displayList?.timeline);
const menu = inkMenu();
paint(menu, 1000);
@@ -217,22 +197,20 @@ test('with menu animation off, scrolls, slides and bounces snap', (t) => {
assert.equal(timed(paint(menu, 5000)).length, 0, 'no bounce');
});
test('scroll lists survive the bridge with animated copy coordinates', () => {
const strip = { width: 2, height: 4, pixels: Uint8Array.of(17, 34, 51, 68, 85, 102, 119, 136) };
const timeline = { from: 0, to: 2, startedAt: 1000, token: 7, durationMs: MENU_HIGHLIGHT_DURATION_MS };
const y = slidingHighlightY(0, { dx: 0, dy: 1, startedAt: 1000, token: 7, durationMs: MENU_HIGHLIGHT_DURATION_MS }, 1000);
const list = menuScrollList(strip, 1, 2, timeline, scrollOffsetExpression(timeline).sub(E.i32(0)),
{ y, width: 4, height: 2, radius: 0, background: 15, border: 45 });
const bytes = encodeDisplayList({ displayList: list, x: 3, y: 2, width: 4, height: 2, depth: 0 }, 1150);
assert.equal(Buffer.from(bytes).toString('hex'), SCROLL);
const { placed } = readDisplayList(bytes, 0, 1150);
const [copy, box] = placed.displayList.calls;
assert.equal(evaluate(copy.y, 150, 0).value, 1);
assert.deepEqual(evaluate(copy.y, 150, 90), { value: 2, pending: false });
assert.equal(copy.dx, 1);
assert.equal(evaluate(box.y, 0, 0).value, 0, 'the highlight is clamped inside the viewport');
const image = new GrayImage(8, 8);
image.drawDisplayList(list, 3, 2, 4, 2);
assert.ok(encodePresentation(image.draws[0]).length > 0);
test('menu animation speed scales slide, scroll and bounce durations', (t) => {
t.after(() => setMenuAnimationReader(() => 'normal'));
for (const [speed, factor] of [['very-fast', 5], ['fast', 2], ['normal', 1], ['slow', 0.5]]) {
setMenuAnimationReader(() => speed);
const highlight = new MenuHighlightMotion();
highlight.paint(0, 0, 10, 20, 100, 20, 0);
highlight.navigate(0, false);
assert.equal(highlight.paint(1, 0, 10, 40, 100, 20, 100).durationMs, MENU_HIGHLIGHT_DURATION_MS / factor, speed);
const scroll = new MenuScrollMotion();
scroll.paint(0, BOX, 0);
scroll.navigate(false);
assert.equal(scroll.paint(20, BOX, 100).durationMs, MENU_HIGHLIGHT_DURATION_MS / factor, speed);
scroll.bounce(8);
assert.equal(scroll.paint(20, BOX, 1000).durationMs, MENU_BOUNCE_DURATION_MS / factor, speed);
}
});
+7 -6
View File
@@ -1,7 +1,7 @@
// Pins the mic_control wire codec against the firmware contract in g2flash's
// patches/mic_control.c (microphone-configurations branch): field-103 control
// records, the 21-byte field-104 status, and the 21-byte 'SM' stream header
// with concatenated (not interleaved) channel payloads.
// with interleaved PCM16 channel payloads.
const test = require("node:test");
const assert = require("node:assert/strict");
@@ -13,7 +13,7 @@ const {
encodeMicControl,
decodeMicStatus,
decodeMicStreamFrame,
splitConcatenatedPcm16,
splitInterleavedPcm16,
defaultMicConfig,
micEnabled,
setMicEnabled,
@@ -154,12 +154,13 @@ function buildSmFrame({ channels = 2, samplesPerChannel = 4, angle = -30, ssr =
data[18] = ssr >> 8;
data[19] = payLen & 0xff;
data[20] = payLen >> 8;
// Channel blocks are CONCATENATED: channel 0 all-1000s, channel 1 all-(-2000)s.
// Channels are INTERLEAVED (ch0, ch1, ch0, ch1, ...): channel 0 all-1000s,
// channel 1 all-(-2000)s.
for (let c = 0; c < channels; c++) {
const value = c === 0 ? 1000 : -2000;
const unsigned = value < 0 ? value + 0x10000 : value;
for (let s = 0; s < samplesPerChannel; s++) {
const base = SM_HEADER_BYTES + c * samplesPerChannel * 2 + s * 2;
const base = SM_HEADER_BYTES + (s * channels + c) * 2;
data[base] = unsigned & 0xff;
data[base + 1] = unsigned >> 8;
}
@@ -182,9 +183,9 @@ test("SM frame decode: header fields and negative angle", () => {
assert.equal(decodeMicStreamFrame(buildSmFrame({ truncated: true })).truncated, true);
});
test("SM payload splits as concatenated channel blocks", () => {
test("SM payload deinterleaves into per-channel samples", () => {
const frame = decodeMicStreamFrame(buildSmFrame({ samplesPerChannel: 3 }));
const channels = splitConcatenatedPcm16(frame);
const channels = splitInterleavedPcm16(frame);
assert.ok(channels);
assert.equal(channels.length, 2);
assert.equal(channels[0].length, 3);
+1 -1
View File
@@ -155,7 +155,7 @@ test('Music settings keeps toggles and selection when a new app arrives and supp
'../util/numeric-util': { clamp: (n, lo, hi) => Math.max(lo, Math.min(hi, n)) },
'./menu-highlight-motion': require('../.test-build/app/ui/menu-highlight-motion.js'), '../graphics/menu-scroll-list': require('../.test-build/app/graphics/menu-scroll-list.js'), './menu-scroll-motion': require('../.test-build/app/ui/menu-scroll-motion.js'), '../graphics/draw-expression': require('../.test-build/app/graphics/draw-expression.js'),
'./metrics': load('app/ui/metrics.ts'), './gestures': {},
'./menu-animation-pref': require('../.test-build/app/ui/menu-animation-pref.js'), '../native/settings-store': { getBooleanSetting: (_key, fallback) => fallback },
'./menu-animation-pref': require('../.test-build/app/ui/menu-animation-pref.js'), './animation-speed': require('../.test-build/app/ui/animation-speed.js'), '../native/settings-store': { getStringSetting: (_key, fallback) => fallback },
};
deps['./menu-core'] = load('app/ui/menu-core.ts', (name) => deps[name]);
const menu = load('app/ui/menu.ts', (name) => deps[name]);
+7
View File
@@ -66,6 +66,13 @@ int main(int argc, char **argv) { @autoreleasepool {
for (NSUInteger i=10; i<light.length; i++) { Check(l[i] >= d[i], @"gamma monotonic"); if (l[i] > 0 && l[i] < 255) antialiased = YES; }
Check(antialiased, @"antialias coverage");
Check([FaceclawFontRenderer renderGlyphCell:font size:32 codePoint:0x1f642 gamma:1].length > 10, @"non-BMP fallback glyph");
// macOS falls back to Apple Color Emoji for ⌚ (as iOS does for ▶), whose
// alpha-only raster is a bare silhouette 1.3125em wide; a text font has it.
NSData *watch = [FaceclawFontRenderer renderGlyphCell:font size:32 codePoint:0x231a gamma:1];
double watchAdvance = U16(watch.bytes) / 64.0;
Check(watch.length > 10 && watchAdvance < 32, @"text presentation preferred over color emoji fallback");
Check(fabs(watchAdvance - [FaceclawFontRenderer measureTextExact:font text:@"⌚" size:32]) <= 1.0/128, @"text-presentation advance agrees");
Check(fabs([FaceclawFontRenderer measureTextExact:font text:@"A⌚" size:32] - a - watchAdvance) < 0.01, @"text-presentation pair measure agrees");
NSString *sample = @"AgjÉ 0123456789 — AV fi ffi";
SavePGM([FaceclawFontRenderer renderText:font text:sample size:32 gamma:1], [outDir stringByAppendingPathComponent:@"line.pgm"]);
NSString *paragraph = @"The quick brown fox jumps over the lazy dog.\nCafé déjà vu — 23°C. ALongWordWithoutSpacesToExerciseWrapping. More text for truncation.";
+3 -3
View File
@@ -73,7 +73,7 @@ function paintWidget(smallHeight, largeHeight, height = 144, measurements = {})
};
const { NightscoutWidget } = load('app/apps/glanceboard/widgets/nightscout-widget.ts', {
'../../../graphics/image': { GrayImage },
'../../../graphics/ui-fonts': { getDefaultSmallFont: () => small, getDefaultLargeFont: () => ({ ...small, lineHeight: largeHeight }) },
'../glance-font': { glanceFont: { small: () => small, large: () => ({ ...small, lineHeight: largeHeight }) } },
'../../../graphics/textwrap': require('../.test-build/app/graphics/textwrap.js'),
'../../../native/nightscout-bridge': { nightscoutBridge: { snapshot: () => state } },
'../../../ui/dashboard-settings': { isNightscoutSettingsConfigured: () => true, loadNightscoutThresholds: () => limits },
@@ -206,7 +206,7 @@ test('bridge exposes numeric measurements and treats absent values as unknown',
let pump = { reservoir: '10.5', battery: { voltage: '1.15' } };
const module = load('app/native/nightscout-bridge.ts', {
'../ui/dashboard-settings': { nightscoutSiteUrlSetting: { get: () => 'https://example.test' }, nightscoutApiTokenSetting: { get: () => 'test' } },
'../util/http': { async fetchWithUserAgent(url) {
'../util/http': { async fetchTextWithUserAgent(url) {
const body = url.includes('/entries.') ? [{ date: now, sgv: 100 }] : url.includes('/devicestatus.') ? [{ pump, openaps: { suggested: { mills: now - 60_000 } } }] : url.includes('/status.') ? {} : [];
return { ok: true, json: async () => body };
} },
@@ -231,7 +231,7 @@ test('polling starts once and stops even while the initial HTTP request is pendi
const timers = new Map();
const module = load('app/native/nightscout-bridge.ts', {
'../ui/dashboard-settings': { nightscoutSiteUrlSetting: { get: () => 'https://example.test' }, nightscoutApiTokenSetting: { get: () => 'test' } },
'../util/http': { async fetchWithUserAgent() {
'../util/http': { async fetchTextWithUserAgent() {
calls++;
await pending;
return { ok: true, json: async () => [] };
+31 -5
View File
@@ -86,7 +86,7 @@ function ui(fontSize = 12) {
'../util/render-freshness': { renderPassAllowsStaleData: () => false },
'./menu-highlight-motion': require('../.test-build/app/ui/menu-highlight-motion.js'), '../graphics/menu-scroll-list': require('../.test-build/app/graphics/menu-scroll-list.js'), './menu-scroll-motion': require('../.test-build/app/ui/menu-scroll-motion.js'), '../graphics/draw-expression': require('../.test-build/app/graphics/draw-expression.js'),
'./metrics': load('app/ui/metrics.ts'),
'./menu-animation-pref': require('../.test-build/app/ui/menu-animation-pref.js'), '../native/settings-store': { getBooleanSetting: (_key, fallback) => fallback },
'./menu-animation-pref': require('../.test-build/app/ui/menu-animation-pref.js'), './animation-speed': require('../.test-build/app/ui/animation-speed.js'), '../native/settings-store': { getStringSetting: (_key, fallback) => fallback },
'./gestures': {},
};
const requireModule = (name) => {
@@ -98,14 +98,40 @@ function ui(fontSize = 12) {
const { SingleNotificationLayer } = load('app/ui/notifications.ts', requireModule);
const { NotificationFilterLayer } = load('app/ui/notification-filter.ts', requireModule);
const ctx = { stack: { getBaseSize: () => ({ width: 540, height: 224 }), isFocused: () => true, pop: () => closes++ } };
const popup = new SingleNotificationLayer('key', { origin: 'new-notification-modal', closeModal: () => closes++ });
const popup = new SingleNotificationLayer('key', { origin: 'new-notification-modal', onClose: () => closes++ });
const trayCloses = [];
const tray = new SingleNotificationLayer('key', { origin: 'notification-tray', onClose: (_ctx, gone) => trayCloses.push(gone) });
const filter = new NotificationFilterLayer();
const paint = (layer) => layer.paint(ctx, () => new RecordingImage(540, 224));
let paintedBelow = 0;
const paint = (layer) => layer.paint(ctx, () => { paintedBelow++; return new RecordingImage(540, 224); });
const input = (layer, type) => layer.handleInput({ type }, ctx);
return { prefs, popup, filter, paint, input, active: (value) => { active = value; },
dismissals: () => dismissals, closes: () => closes };
return { prefs, popup, tray, filter, paint, input, active: (value) => { active = value; },
dismissals: () => dismissals, closes: () => closes, trayCloses, paintedBelow: () => paintedBelow };
}
test('a notification the switcher selected reports back and dismissal to it, and repeats its last frame once gone', async () => {
const app = ui();
const labels = (image) => image.texts.map(({ text }) => text);
assert.ok(labels(app.paint(app.tray)).includes('Back'));
assert.ok(!labels(app.paint(app.tray)).some((text) => text.includes("Don't show")));
await app.input(app.tray, 'double-click');
await app.input(app.tray, 'click');
assert.deepEqual(app.trayCloses, [false, false]);
await app.input(app.tray, 'scroll-down');
const last = app.paint(app.tray);
await app.input(app.tray, 'click');
assert.equal(app.dismissals(), 1);
assert.deepEqual(app.trayCloses, [false, false, true]);
// The switcher swaps in a neighbour after the paint; until then the paint
// holds what was showing rather than the list below.
const again = app.paint(app.tray);
assert.deepEqual(app.trayCloses, [false, false, true, true]);
assert.equal(app.paintedBelow(), 0);
// (Compared unbaked: the menu highlight's draws animate with the clock.)
assert.deepEqual(Buffer.from(again.pixels), Buffer.from(last.pixels));
assert.deepEqual(again.drawList, last.drawList);
});
test('popup dismisses before confirmation; confirming disables the source even after the notification disappears', async () => {
const app = ui();
await app.input(app.popup, 'scroll-down');
+104
View File
@@ -0,0 +1,104 @@
const test = require("node:test");
const assert = require("node:assert/strict");
const { NotificationModalQueue } = require("../.test-build/app/ui/shell/notification-modal-queue.js");
/** A host that records opened modals (one handle object each) and sleeps. */
function makeHost(unavailable = new Set()) {
const host = {
opened: [],
sleeps: 0,
open(notificationKey) {
const modal = { notificationKey };
host.opened.push(modal);
return modal;
},
isAvailable: (notificationKey) => !unavailable.has(notificationKey),
sleep() { host.sleeps++; },
};
return host;
}
test("only one modal is open; later notifications wait and open as each closes", () => {
const host = makeHost();
const queue = new NotificationModalQueue(host);
queue.post("a", false);
queue.post("b", false);
queue.post("c", false);
assert.deepEqual(host.opened.map((modal) => modal.notificationKey), ["a"]);
assert.deepEqual(queue.queuedKeys(), ["b", "c"]);
queue.closed(host.opened[0]);
assert.deepEqual(host.opened.map((modal) => modal.notificationKey), ["a", "b"]);
queue.closed(host.opened[1]);
queue.closed(host.opened[2]);
assert.deepEqual(host.opened.map((modal) => modal.notificationKey), ["a", "b", "c"]);
assert.equal(host.sleeps, 0);
// With nothing open, the next notification opens at once.
queue.post("d", false);
assert.equal(host.opened.length, 4);
});
test("reposts of the open or a queued notification are not duplicated", () => {
const host = makeHost();
const queue = new NotificationModalQueue(host);
queue.post("a", false);
queue.post("a", false);
queue.post("b", false);
queue.post("b", false);
assert.equal(host.opened.length, 1);
assert.deepEqual(queue.queuedKeys(), ["b"]);
});
test("queued notifications that went away are skipped", () => {
const unavailable = new Set(["b"]);
const host = makeHost(unavailable);
const queue = new NotificationModalQueue(host);
queue.post("a", false);
queue.post("b", false);
queue.post("c", false);
queue.closed(host.opened[0]);
assert.deepEqual(host.opened.map((modal) => modal.notificationKey), ["a", "c"]);
});
test("a screen woken by a notification sleeps again once the last modal closes", () => {
const host = makeHost();
const queue = new NotificationModalQueue(host);
queue.post("a", true);
queue.post("b", false);
queue.closed(host.opened[0]);
assert.equal(host.sleeps, 0, "the next notification opens instead of sleeping");
queue.closed(host.opened[1]);
assert.equal(host.sleeps, 1);
// A modal opened with the screen already on doesn't sleep when closed.
queue.post("c", false);
queue.closed(host.opened[2]);
assert.equal(host.sleeps, 1);
});
test("sleep drops the queue; another removal opens the next without sleeping", () => {
const host = makeHost();
const queue = new NotificationModalQueue(host);
queue.post("a", true);
queue.post("b", false);
queue.removed(host.opened[0], false);
assert.deepEqual(queue.queuedKeys(), []);
assert.equal(host.opened.length, 1);
queue.post("c", false);
queue.post("d", false);
queue.removed(host.opened[1], true);
assert.deepEqual(host.opened.map((modal) => modal.notificationKey), ["a", "c", "d"]);
assert.equal(host.sleeps, 0);
});
test("the removal reported after a close is ignored, as are stale modals", () => {
const host = makeHost();
const queue = new NotificationModalQueue(host);
queue.post("a", false);
queue.post("b", false);
const first = host.opened[0];
queue.closed(first);
queue.removed(first, true);
queue.closed(first);
assert.deepEqual(host.opened.map((modal) => modal.notificationKey), ["a", "b"]);
assert.deepEqual(queue.queuedKeys(), []);
});
+14 -9
View File
@@ -20,37 +20,42 @@ function setup() {
}
test('single tap retains mirror coordinates and waits to disambiguate double tap', () => {
const s = setup(); s.touch('down'); s.touch('up');
assert.deepEqual(s.types(), []); s.advance(280);
assert.deepEqual(s.events, [{ type: 'tap', x: 20, y: 30 }]);
assert.deepEqual(s.types(), ['press']); s.advance(280);
assert.deepEqual(s.events, [{ type: 'press', x: 20, y: 30 }, { type: 'tap', x: 20, y: 30 }]);
});
test('every first-finger touch-down presses; a far second touch flushes the pending tap first', () => {
const s = setup(); s.touch('down'); s.touch('up'); s.advance(100);
s.touch('down', 200, 30); s.touch('down', 201, 30, 2); s.touch('up', 201, 30, 2); s.touch('up', 200, 30); s.advance(1000);
assert.deepEqual(s.types(), ['press', 'tap', 'press', 'double-tap']);
});
test('double tap emits back without accidental selection', () => {
const s = setup(); s.touch('down'); s.touch('up'); s.advance(150);
s.touch('down'); s.touch('up'); s.advance(1000);
assert.deepEqual(s.types(), ['double-tap']);
assert.deepEqual(s.types(), ['press', 'press', 'double-tap']);
});
test('a hold emits a press and release, never a tap', () => {
const s = setup(); s.touch('down'); s.advance(500); s.touch('up'); s.advance(1000);
assert.deepEqual(s.types(), ['long-press', 'long-press-release']);
assert.deepEqual(s.types(), ['press', 'long-press', 'long-press-release']);
});
test('tap then hold emits the app-menu gesture without an earlier selection', () => {
const s = setup(); s.touch('down'); s.touch('up'); s.advance(100);
s.touch('down'); s.advance(500); s.touch('up'); s.advance(1000);
assert.deepEqual(s.types(), ['short-then-long-press', 'long-press-release']);
assert.deepEqual(s.types(), ['press', 'press', 'short-then-long-press', 'long-press-release']);
});
test('four directional swipes cancel pending holds and taps', () => {
for (const [x, y, expected] of [[80, 30, 'swipe-right'], [-40, 30, 'swipe-left'], [20, 90, 'swipe-down'], [20, -30, 'swipe-up']]) {
const s = setup(); s.touch('down'); s.touch('move', x, y); s.advance(500); s.touch('up', x, y); s.advance(500);
assert.deepEqual(s.types(), [expected]);
assert.deepEqual(s.types(), ['press', expected]);
}
});
test('two fingers send back exactly once and cancel the long-press timer', () => {
const s = setup(); s.touch('down'); s.touch('down', 21, 30, 2); s.advance(500);
s.touch('up', 21, 30, 2); s.touch('up'); s.advance(1000);
assert.deepEqual(s.types(), ['double-tap']);
assert.deepEqual(s.types(), ['press', 'double-tap']);
});
test('cancellation prevents delayed selections and releases active holds', () => {
const s = setup(); s.touch('down'); s.touch('up'); s.r.cancel(); s.advance(1000);
assert.deepEqual(s.types(), []);
assert.deepEqual(s.types(), ['press']);
s.touch('down'); s.advance(500); s.touch('cancel'); s.advance(1000);
assert.deepEqual(s.types(), ['long-press', 'long-press-release']);
assert.deepEqual(s.types(), ['press', 'press', 'long-press', 'long-press-release']);
});
+1 -1
View File
@@ -22,7 +22,7 @@ const font = BdfFont.parse(fs.readFileSync(path.join(__dirname, '../app/fonts/te
const textwrap = load('app/graphics/textwrap.ts', {});
const fonts = { getDefaultSmallFont: () => font };
const menu = load('app/ui/menu.ts', {
'./menu-animation-pref': require('../.test-build/app/ui/menu-animation-pref.js'), '../native/settings-store': { getBooleanSetting: (_key, fallback) => fallback },
'./menu-animation-pref': require('../.test-build/app/ui/menu-animation-pref.js'), './animation-speed': require('../.test-build/app/ui/animation-speed.js'), '../native/settings-store': { getStringSetting: (_key, fallback) => fallback },
'../graphics/image': graphics, '../graphics/textwrap': textwrap, '../graphics/ui-fonts': fonts,
'../util/numeric-util': { clamp: (n, lo, hi) => Math.max(lo, Math.min(hi, n)) }, './gestures': {},
'./metrics': metrics, './menu-core': menuCore,
-49
View File
@@ -1,49 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { SurfaceCompositor } = require('../.test-build/app/graphics/surface-compositor.js');
const rect = (x, y, width, height) => ({ x, y, width, height });
function surface(c, id, box, values, zOrder = 0, transparency = 'opaque') {
c.configureSurface(id, { ...box, zOrder, transparency });
c.submitSurfaceFrame(id, Uint8Array.from(values), rect(0, 0, box.width, box.height));
}
test('shell color key preserves underlying text while opaque black covers it', () => {
const c = new SurfaceCompositor(3, 2);
surface(c, 'app', rect(0, 0, 3, 2), [200, 200, 200, 200, 200, 200]);
surface(c, 'shell', rect(0, 0, 3, 2), [0, 1, 255, 0, 0, 0], 1, 'color-key');
c.setUnderlayDim(1, 0.5);
assert.deepEqual([...c.composite()], [100, 1, 255, 100, 100, 100]);
c.setSurfaceVisible('shell', false);
assert.deepEqual([...c.composite()], [100, 100, 100, 100, 100, 100]);
surface(c, 'opaque', rect(1, 0, 1, 2), [0, 0], 2);
assert.deepEqual([...c.composite()], [100, 0, 100, 100, 0, 100]);
});
test('partial frames clip in surface coordinates, then surfaces clip to the screen', () => {
const c = new SurfaceCompositor(3, 2);
surface(c, 'app', rect(-1, 0, 3, 2), [1, 2, 3, 4, 5, 6]);
const source = Uint8Array.from([99, 10, 20, 99, 30, 40, 99]);
c.submitSurfaceFrame('app', source.subarray(1, 5), rect(1, 1, 2, 2));
source.fill(0);
assert.deepEqual([...c.composite()], [2, 3, 0, 10, 20, 0]);
c.submitSurfaceFrame('app', Uint8Array.from([50, 60, 70, 80]), rect(-1, -1, 2, 2));
// The clipped update changed the offscreen column, leaving visible pixels intact.
assert.deepEqual([...c.composite()], [2, 3, 0, 10, 20, 0]);
});
test('moving a surface retains its frame; resizing clears it; blanking is reversible', () => {
const c = new SurfaceCompositor(3, 1);
surface(c, 'app', rect(0, 0, 2, 1), [7, 9]);
c.configureSurface('app', { ...rect(1, 0, 2, 1), zOrder: 0, transparency: 'opaque' });
assert.deepEqual([...c.composite()], [0, 7, 9]);
c.setScreenBlanked(true); assert.deepEqual([...c.composite()], [0, 0, 0]);
c.setScreenBlanked(false); assert.deepEqual([...c.composite()], [0, 7, 9]);
c.configureSurface('app', { ...rect(0, 0, 3, 1), zOrder: 0, transparency: 'opaque' });
assert.deepEqual([...c.composite()], [0, 0, 0]);
});
test('layer order is independent of creation order; removal reveals lower surfaces', () => {
const c = new SurfaceCompositor(1, 1);
surface(c, 'top', rect(0, 0, 1, 1), [20], 10);
surface(c, 'bottom', rect(0, 0, 1, 1), [80], -1);
assert.equal(c.composite()[0], 20);
c.removeSurface('top'); assert.equal(c.composite()[0], 80);
assert.throws(() => c.submitSurfaceFrame('missing', new Uint8Array(1), rect(0, 0, 1, 1)));
assert.throws(() => c.submitSurfaceFrame('bottom', new Uint8Array(2), rect(0, 0, 1, 1)));
});
+71
View File
@@ -0,0 +1,71 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { buildGlanceSnapshot, glanceSummary } = require('../.test-build/app/apps/t3code/t3-glance.js');
const { threadMarker } = require('../.test-build/app/apps/t3code/t3-model.js');
const NOW = Date.parse('2026-10-04T12:00:00.000Z');
const iso = (offsetMs) => new Date(NOW + offsetMs).toISOString();
function thread(id, extra = {}) {
return {
id, projectId: 'p1', title: `Thread ${id}`, status: 'completed', latestRunId: 'r', activeProviderThreadId: 'x',
pendingBackgroundTasks: [], latestUserMessageAt: iso(-60_000), updatedAt: iso(-60_000), createdAt: iso(-86_400_000),
lineage: {}, ...extra,
};
}
const env = (id, threads, extra = {}) => ({ id, ready: true, phase: 'connected', enabled: true, threads, ...extra });
test('rows: needs-you, then working, then recent, across environments; settled and snoozed left out', () => {
const snapshot = buildGlanceSnapshot([
env('a', [
thread('recent', { latestUserMessageAt: iso(-120_000) }),
thread('approve', { status: 'running', pendingRuntimeRequest: { id: 'q1', kind: 'file-change', createdAt: iso(-1000) } }),
thread('done', { settledOverride: 'settled', settledAt: iso(-1000) }),
]),
env('b', [
thread('busy', { status: 'running', latestUserAuthoredMessageAt: iso(-30_000) }),
thread('nap', { snoozedUntil: iso(3_600_000), snoozedAt: iso(-1000) }),
thread('new', { latestRunCompletedAt: iso(-5000), lastVisitedAt: iso(-50_000), latestUserMessageAt: iso(-10_000) }),
]),
], NOW);
assert.deepEqual(snapshot.rows.map((row) => row.key), ['a:approve', 'b:busy', 'b:new', 'a:recent']);
assert.deepEqual(snapshot.rows.map((row) => row.status), ['approval', 'working', 'ready', 'ready']);
assert.equal(snapshot.rows[0].requestKind, 'file-change');
assert.equal(snapshot.rows[2].unread, true);
assert.equal(snapshot.needsYou, 1);
assert.equal(snapshot.working, 1);
assert.equal(snapshot.more, 0);
assert.equal(snapshot.status, '');
assert.equal(glanceSummary(snapshot), '1 needs you · 1 working');
// It crosses postMessage: plain JSON only.
assert.deepEqual(JSON.parse(JSON.stringify(snapshot)), snapshot);
});
test('caps rows and counts the rest', () => {
const threads = Array.from({ length: 30 }, (_, index) => thread(`t${index}`, { latestUserMessageAt: iso(-index * 1000) }));
const snapshot = buildGlanceSnapshot([env('a', threads)], NOW);
assert.equal(snapshot.rows.length, 24);
assert.equal(snapshot.more, 6);
});
test('status when nothing is connected', () => {
assert.deepEqual(buildGlanceSnapshot([], NOW), { configured: false, status: '', needsYou: 0, working: 0, rows: [], more: 0 });
const status = (environments) => buildGlanceSnapshot(environments, NOW).status;
assert.equal(status([env('a', [], { ready: false, phase: 'connecting' })]), 'Connecting…');
assert.equal(status([env('a', [], { ready: false, phase: 'retrying' })]), "Can't reach T3 Code");
assert.equal(status([env('a', [], { ready: false, phase: 'auth-failed' })]), 'Pair again in the T3 Code app');
assert.equal(status([env('a', [], { ready: false, phase: 'idle', enabled: false })]), 'Disconnected');
// One connected environment is enough to show threads.
assert.equal(status([env('a', [], { ready: false, phase: 'retrying' }), env('b', [])]), '');
});
test('status marks', () => {
assert.deepEqual(threadMarker('approval'), { marker: '!', value: 255 });
assert.deepEqual(threadMarker('input'), { marker: '?', value: 255 });
assert.equal(threadMarker('working').marker, '…');
assert.equal(threadMarker('ready', { unread: true }).marker, '●');
assert.equal(threadMarker('ready', { settled: true, unread: true }).marker, '✓');
assert.equal(threadMarker('ready').marker, '');
assert.equal(threadMarker('failed', { unread: true }).marker, 'x');
});
+242
View File
@@ -0,0 +1,242 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const model = require('../.test-build/app/apps/t3code/t3-model.js');
const { TranscriptLayout } = require('../.test-build/app/apps/t3code/t3-transcript.js');
const NOW = Date.parse('2026-10-04T12:00:00.000Z');
const iso = (offsetMs) => new Date(NOW + offsetMs).toISOString();
function shellThread(overrides = {}) {
return {
id: 't1', projectId: 'p1', title: 'Fix the flaky test',
status: 'completed', activityRunStatus: null, latestRunId: 'r1', activeProviderThreadId: 'pt1',
pendingRuntimeRequest: null, pendingBackgroundTasks: [], lastError: null, lastErrorClass: null,
latestUserMessageAt: iso(-60_000), latestUserAuthoredMessageAt: iso(-60_000), updatedAt: iso(-30_000), createdAt: iso(-3_600_000),
archivedAt: null, deletedAt: null, settledOverride: null, settledAt: null, snoozedUntil: null, snoozedAt: null,
lineage: { relationshipToParent: null },
...overrides,
};
}
test('shell reducer: snapshot, metadata-only snapshot, deltas, dedupe, archive', () => {
const shell = new model.ShellModel();
shell.apply({ kind: 'snapshot', snapshot: { snapshotSequence: 10, projects: [{ id: 'p1', title: 'faceclaw' }], threads: [shellThread()] } });
assert.equal(shell.sequence, 10);
assert.equal(shell.threads.size, 1);
// Repository-identity refresh frames carry threads: [] and must not wipe the list.
assert.equal(shell.apply({ kind: 'snapshot', resolvedRepositoryIdentityRoots: ['/x'], snapshot: { snapshotSequence: 99, projects: [], threads: [] } }), false);
assert.equal(shell.threads.size, 1);
assert.equal(shell.sequence, 10);
shell.apply({ kind: 'thread.updated', sequence: 11, location: 'active', thread: shellThread({ id: 't2', title: 'Second' }) });
assert.equal(shell.threads.size, 2);
assert.equal(shell.apply({ kind: 'thread.updated', sequence: 11, location: 'active', thread: shellThread({ id: 't3' }) }), false, 'replayed sequence is ignored');
shell.apply({ kind: 'thread.updated', sequence: 12, location: 'archive', thread: shellThread({ id: 't2' }) });
assert.deepEqual([...shell.threads.keys()], ['t1']);
shell.apply({ kind: 'thread.removed', sequence: 13, location: 'active', threadId: 't1' });
assert.equal(shell.threads.size, 0);
assert.equal(shell.sequence, 13);
shell.apply({ kind: 'synchronized' });
assert.equal(shell.synchronized, true);
});
test('thread status follows T3 mobile', () => {
assert.equal(model.threadStatus(shellThread({ pendingRuntimeRequest: { id: 'q', kind: 'command' } })), 'approval');
assert.equal(model.threadStatus(shellThread({ pendingRuntimeRequest: { id: 'q', kind: 'user_input' } })), 'input');
assert.equal(model.threadStatus(shellThread({ pendingRuntimeRequest: { id: 'q', kind: 'auth_refresh' }, status: 'running' })), 'working');
assert.equal(model.threadStatus(shellThread({ activityRunStatus: 'waiting', status: 'waiting' })), 'working', 'run "waiting" is finalization, not approval');
assert.equal(model.threadStatus(shellThread({ status: 'completed', pendingBackgroundTasks: [{ kind: 'subagent' }] })), 'waiting');
assert.equal(model.threadStatus(shellThread({ status: 'failed', lastErrorClass: 'usage_limit' })), 'limited');
assert.equal(model.threadStatus(shellThread({ status: 'failed' })), 'failed');
assert.equal(model.threadStatus(shellThread({ latestRunId: null, activeProviderThreadId: null, status: 'idle' })), 'ready');
});
test('sections: needs-you first, working by send time, hidden subagents, snoozed and settled apart', () => {
const threads = [
shellThread({ id: 'recent-old', updatedAt: iso(-90_000), latestUserMessageAt: iso(-90_000) }),
shellThread({ id: 'recent-new', latestUserMessageAt: iso(-10_000) }),
shellThread({ id: 'asks', pendingRuntimeRequest: { id: 'q', kind: 'user_input', createdAt: iso(-5_000) } }),
shellThread({ id: 'work-a', status: 'running', latestUserAuthoredMessageAt: iso(-50_000) }),
shellThread({ id: 'work-b', status: 'running', latestUserAuthoredMessageAt: iso(-20_000) }),
shellThread({ id: 'sub', lineage: { relationshipToParent: 'subagent' } }),
shellThread({ id: 'done', settledOverride: 'settled', settledAt: iso(-1000) }),
shellThread({ id: 'zz', snoozedUntil: iso(3_600_000), snoozedAt: iso(-1000), latestRunCompletedAt: iso(-5000) }),
];
const sections = model.sectionThreads(threads, NOW);
const ids = (list) => list.map((thread) => thread.id);
assert.deepEqual(ids(sections.attention), ['asks']);
assert.deepEqual(ids(sections.working), ['work-b', 'work-a']);
assert.deepEqual(ids(sections.recent), ['recent-new', 'recent-old']);
assert.deepEqual(ids(sections.settled), ['done']);
assert.deepEqual(ids(sections.snoozed), ['zz']);
// A run finishing after the snooze raises its hand.
assert.equal(model.isThreadSnoozed(shellThread({ snoozedUntil: iso(3_600_000), snoozedAt: iso(-10_000), latestRunCompletedAt: iso(-1000) }), NOW), false);
});
test('unread means a run finished after the last visit (never visited reads as read)', () => {
assert.equal(model.isThreadUnread(shellThread({ latestRunCompletedAt: iso(-1000), lastVisitedAt: iso(-5000) })), true);
assert.equal(model.isThreadUnread(shellThread({ latestRunCompletedAt: iso(-5000), lastVisitedAt: iso(-1000) })), false);
assert.equal(model.isThreadUnread(shellThread({ latestRunCompletedAt: iso(-1000), lastVisitedAt: null })), false);
});
function item(id, ordinal, type, extra = {}) {
return { id, threadId: 't1', runId: 'r1', nodeId: null, ordinal, status: 'completed', title: null, type, ...extra };
}
function detailWithSnapshot(extra = {}) {
const detail = new model.ThreadDetailModel('t1');
detail.apply({
kind: 'snapshot',
snapshotSequence: 100,
hasMoreHistory: false,
historyCursor: null,
latestLocalTurnOrdinal: 3,
projection: {
thread: { id: 't1', title: 'Fix the flaky test', latestRunId: 'r1' },
runs: [{ id: 'r1', status: 'running', requestedAt: iso(-10_000) }],
attempts: [], messages: [], plans: [],
runtimeRequests: [],
visibleTurnItems: [
{ visibility: 'inherited', item: { ...item('parent-1', 1, 'user_message', { text: 'from the parent' }), threadId: 'parent' } },
{ visibility: 'local', item: item('u1', 2, 'user_message', { text: 'Please fix it', inputIntent: 'turn_start' }) },
{ visibility: 'local', item: item('c1', 3, 'command_execution', { input: "bash -lc 'npm test'", status: 'running' }) },
],
...extra,
},
});
return detail;
}
test('thread detail: snapshot, streaming text replaces, sequence dedupe', () => {
const detail = detailWithSnapshot();
assert.deepEqual(detail.timeline().map((row) => row.id), ['parent-1', 'u1', 'c1']);
const streaming = (seq, text, streamingFlag) => detail.apply({
kind: 'event', sequence: seq,
event: { type: 'turn-item.updated', payload: item('a1', 4, 'assistant_message', { text, streaming: streamingFlag, status: streamingFlag ? 'running' : 'completed' }) },
});
assert.equal(streaming(101, 'I found the race.\n\n', true), true);
assert.equal(streaming(102, 'I found the race.\n\nThe test awaits login() first.', false), true);
assert.equal(streaming(102, 'stale replay', false), false);
const entries = model.timelineEntries(detail);
assert.deepEqual(entries.map((entry) => entry.kind), ['user', 'user', 'activity', 'assistant']);
assert.equal(entries[3].text, 'I found the race.\n\nThe test awaits login() first.');
assert.equal(entries[3].streaming, false);
assert.equal(entries[2].label, 'npm test', 'bash -lc wrapper unwrapped');
assert.equal(entries[2].state, 'running');
assert.equal(detail.activeRunId(), 'r1');
});
test('thread detail: bounded windows drop updates to unloaded history', () => {
const detail = detailWithSnapshot();
detail.hasMoreHistory = true;
detail.apply({ kind: 'event', sequence: 101, event: { type: 'turn-item.updated', payload: item('old', 1, 'assistant_message', { text: 'ancient' }) } });
assert.equal(detail.items.has('old'), false);
detail.apply({ kind: 'event', sequence: 102, event: { type: 'turn-item.updated', payload: item('new', 9, 'assistant_message', { text: 'fresh' }) } });
assert.equal(detail.items.has('new'), true);
});
test('thread detail: rolled-back runs and cancelled queued turns are hidden', () => {
const detail = detailWithSnapshot();
detail.apply({ kind: 'event', sequence: 101, event: { type: 'run.updated', payload: { id: 'r1', status: 'rolled_back' } } });
assert.deepEqual(detail.timeline().map((row) => row.id), ['parent-1']);
});
test('pending approval and question pair with their timeline rows', () => {
const detail = detailWithSnapshot({
runtimeRequests: [
{ id: 'req-a', kind: 'command', status: 'pending', responseCapability: { type: 'live' } },
{ id: 'req-q', kind: 'user_input', status: 'pending', responseCapability: { type: 'message' } },
{ id: 'req-old', kind: 'command', status: 'resolved' },
],
});
detail.apply({ kind: 'event', sequence: 101, event: { type: 'turn-item.updated', payload: item('ap', 4, 'approval_request', { status: 'waiting', requestId: 'req-a', requestKind: 'command', prompt: 'rm -rf build' }) } });
detail.apply({ kind: 'event', sequence: 102, event: { type: 'turn-item.updated', payload: item('qu', 5, 'user_input_request', { status: 'waiting', requestId: 'req-q', responseMode: 'message', questions: [{ id: 'Which DB?', question: 'Which DB?', options: [{ label: 'Postgres' }, { label: 'SQLite', value: 'sqlite' }] }] }) } });
const pending = detail.pendingRequests();
assert.deepEqual(pending.map((request) => [request.kind, request.item.id, request.answerable, request.messageMode]), [
['approval', 'ap', true, false],
['question', 'qu', true, true],
]);
assert.deepEqual(model.approvalOptions(pending[0].item).map((option) => option.decision), ['accept', 'acceptForSession', 'decline']);
assert.equal(model.optionAnswer(pending[1].item.questions[0].options[1]), 'sqlite');
const command = model.approvalResponseCommand('t1', 'req-a', 'accept');
assert.equal(command.type, 'runtime-request.respond');
assert.match(command.commandId, /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
const entries = model.timelineEntries(detail);
assert.deepEqual(entries.filter((entry) => entry.kind === 'request').map((entry) => [entry.label, entry.detail, entry.resolved]), [
['Approve command', 'rm -rf build', false],
['Question', 'Which DB?', false],
]);
});
test('queued follow-ups come from queued runs and their messages', () => {
const detail = detailWithSnapshot({
runs: [
{ id: 'r1', status: 'running', requestedAt: iso(-10_000) },
{ id: 'r2', status: 'queued', userMessageId: 'm2', queuePosition: 1 },
{ id: 'r3', status: 'queued', userMessageId: 'm3', queuePosition: 0 },
],
messages: [{ id: 'm2', role: 'user', text: 'then this' }, { id: 'm3', role: 'user', text: 'first this' }],
});
assert.deepEqual(detail.queuedMessages(), ['first this', 'then this']);
const queued = model.timelineEntries(detail).filter((entry) => entry.queued);
assert.deepEqual(queued.map((entry) => entry.text), ['first this', 'then this']);
});
test('activity summaries', () => {
assert.equal(model.summarizeActivity(item('x', 1, 'command_execution', { input: 'Preparing workspace' })), null);
assert.deepEqual(model.summarizeActivity(item('x', 1, 'file_change', { fileName: 'src/app/foo.ts', additions: 3, deletions: 1 })), { label: 'Changed foo.ts', detail: '+3/-1' });
assert.deepEqual(model.summarizeActivity(item('x', 1, 'dynamic_tool', { title: 'read src/foo.ts', toolName: 'Read' })), { label: 'Read src/foo.ts', detail: '' });
assert.equal(model.summarizeActivity(item('x', 1, 'reasoning', { status: 'running' })).label, 'Thinking');
assert.equal(model.summarizeActivity(item('x', 1, 'error', { failure: { class: 'usage_limit', message: 'resets at 5pm' } })).label, 'Usage limit reached');
assert.equal(model.summarizeActivity(item('x', 1, 'todo_list')), null);
assert.equal(model.commandDisplayText("/bin/zsh -lc \"git status\""), 'git status');
});
test('plainMarkdown cleans up for the glasses', () => {
assert.equal(
model.plainMarkdown('## Plan\n\n- **Fix** the [race](http://x)\n- run `npm test`\n\n```ts\nconst a = 1;\n```\n\n\n\nDone.'),
'Plan\n\n· Fix the race\n· run npm test\n\nconst a = 1;\n\nDone.',
);
});
test('default model selection mirrors mobile', () => {
const providers = [
{ instanceId: 'codex', enabled: true, installed: true, auth: { status: 'unauthenticated' }, models: [{ slug: 'gpt-5', isDefault: true }] },
{ instanceId: 'claudeAgent', enabled: true, installed: true, auth: { status: 'authenticated' }, models: [{ slug: 'old', isLegacy: true, isDefault: true }, { slug: 'claude-sonnet-5' }, { slug: 'claude-opus-5', isDefault: true }] },
];
const project = { id: 'p1', title: 'faceclaw' };
assert.deepEqual(model.defaultModelSelection(null, providers, project), { instanceId: 'claudeAgent', model: 'claude-opus-5' });
const settings = { defaultModelSelection: { instanceId: 'codex', model: 'gpt-5' }, projectSettingsOverrides: { p1: { defaultModelSelection: { instanceId: 'claudeAgent', model: 'claude-sonnet-5' } } } };
assert.deepEqual(model.defaultModelSelection(settings, providers, project), { instanceId: 'claudeAgent', model: 'claude-sonnet-5' });
assert.equal(model.defaultModelSelection({ defaultModelSelection: { instanceId: 'codex', model: 'gpt-5' } }, providers.slice(0, 1), project), null, 'unauthenticated providers are skipped');
const payload = model.launchThreadPayload(project, ' Fix the login test ', { instanceId: 'claudeAgent', model: 'claude-opus-5' }, null);
assert.equal(payload.title, 'Fix the login test');
assert.equal(payload.runtimeMode, 'full-access');
assert.deepEqual(payload.workspaceStrategy, { type: 'root' });
});
test('formatAge', () => {
assert.equal(model.formatAge(NOW - 20_000, NOW), 'now');
assert.equal(model.formatAge(NOW - 5 * 60_000, NOW), '5m');
assert.equal(model.formatAge(NOW - 3 * 3_600_000, NOW), '3h');
assert.equal(model.formatAge(NOW - 2 * 86_400_000, NOW), '2d');
assert.equal(model.formatAge(0, NOW), '');
});
test('transcript layout collapses long tool runs and wraps messages', () => {
const font = { measureText: (text) => text.length * 6, getGlyph: () => ({ dwidthX: 6 }) };
const activities = Array.from({ length: 6 }, (_, index) => ({ kind: 'activity', id: `a${index}`, label: `step ${index}`, detail: '', state: index === 5 ? 'running' : 'done' }));
const entries = [
{ kind: 'user', id: 'u', text: 'please do the thing' },
...activities,
{ kind: 'assistant', id: 'm', text: 'All done, the thing is fixed now.', streaming: false },
];
const layout = new TranscriptLayout();
const lines = layout.layout(entries, font, 120).map((line) => line.text);
assert.deepEqual(lines, [
'You: please do the', 'thing',
'',
'· 4 earlier steps', '· step 4', '· step 5 …',
'',
'All done, the thing', 'is fixed now.',
]);
});
+48
View File
@@ -0,0 +1,48 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { parsePairingInput, baseUrlLabel } = require('../.test-build/app/apps/t3code/t3-pairing.js');
function target(input) {
const result = parsePairingInput(input);
assert.ok(result.ok, result.error);
return result.target;
}
test('direct pairing link from t3 pair', () => {
assert.deepEqual(target('http://192.168.1.20:3773/pair#token=7JBMA3AYC28V'), {
credential: '7JBMA3AYC28V', label: '',
httpBaseUrl: 'http://192.168.1.20:3773/', wsBaseUrl: 'ws://192.168.1.20:3773/',
});
assert.equal(target(' https://Mac.tail1234.ts.net:443/pair?token=ABCDEFGH2345 ').httpBaseUrl, 'https://mac.tail1234.ts.net/');
assert.equal(target('https://mac.tail1234.ts.net/pair#token=ABCDEFGH2345').wsBaseUrl, 'wss://mac.tail1234.ts.net/');
});
test('hosted app.t3.codes link uses the host param', () => {
const parsed = target('https://app.t3.codes/pair?host=https%3A%2F%2Fmy-mac.tail1234.ts.net%2F&label=My+Mac#token=7JBMA3AYC28V');
assert.deepEqual(parsed, {
credential: '7JBMA3AYC28V', label: 'My Mac',
httpBaseUrl: 'https://my-mac.tail1234.ts.net/', wsBaseUrl: 'wss://my-mac.tail1234.ts.net/',
});
// A schemeless host defaults to https.
assert.equal(target('https://app.t3.codes/pair?host=box.example.com:8443#token=ABCDEFGH2345').httpBaseUrl, 'https://box.example.com:8443/');
});
test('mobile QR payload and hand-typed host + code', () => {
const inner = encodeURIComponent('http://10.0.0.5:3773/pair#token=ZZZZ22223333');
assert.equal(target(`t3code://pair?pairingUrl=${inner}`).httpBaseUrl, 'http://10.0.0.5:3773/');
assert.deepEqual(target('10.0.0.5:3773 ABCDEFGH2345'), {
credential: 'ABCDEFGH2345', label: '', httpBaseUrl: 'http://10.0.0.5:3773/', wsBaseUrl: 'ws://10.0.0.5:3773/',
});
assert.equal(target('mac.tail1234.ts.net ABCDEFGH2345').httpBaseUrl, 'https://mac.tail1234.ts.net/');
});
test('rejects links without a token or of the wrong kind', () => {
assert.equal(parsePairingInput('').ok, false);
assert.match(parsePairingInput('http://10.0.0.5:3773/pair').error, /no pairing token/);
assert.match(parsePairingInput('ftp://10.0.0.5/pair#token=X').error, /Unsupported/);
assert.equal(parsePairingInput('hello there').ok, false);
});
test('baseUrlLabel drops the scheme', () => {
assert.equal(baseUrlLabel('http://10.0.0.5:3773/'), '10.0.0.5:3773');
});
+128
View File
@@ -0,0 +1,128 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { T3RpcConnection, causeToError } = require('../.test-build/app/apps/t3code/t3-rpc.js');
// Every connection made here, closed at the end so their ping timers don't keep Node alive.
const connections = [];
test.after(() => { for (const connection of connections) connection.close(); });
/** A connection over a scripted fake socket; `sent` collects parsed outgoing frames. */
function connect(options = {}) {
const sent = [];
let handlers = null;
let closed = 0;
const connection = new T3RpcConnection({
url: 'ws://test/ws',
pingIntervalMs: 1_000_000,
openTimeoutMs: 1_000_000,
...options,
openSocket: (_url, h) => {
handlers = h;
return { send: (text) => sent.push(JSON.parse(text)), close: () => { closed++; } };
},
});
connections.push(connection);
return {
connection, sent,
open: () => handlers.onOpen(),
receive: (message) => handlers.onMessage(JSON.stringify(message)),
drop: (reason) => handlers.onClose(reason),
closedCount: () => closed,
};
}
test('requests made while connecting are sent once the socket opens', async () => {
const t = connect();
const result = t.connection.call('server.probe', {});
assert.equal(t.sent.length, 0);
t.open();
assert.deepEqual(t.sent, [{ _tag: 'Request', id: 0, tag: 'server.probe', payload: {}, headers: [] }]);
t.receive({ _tag: 'Exit', requestId: 0, exit: { _tag: 'Success', value: { ok: 1 } } });
assert.deepEqual(await result, { ok: 1 });
});
test('every chunk is acked and delivered; interrupt cancels', () => {
const t = connect();
t.open();
const values = [];
let ended = 'not yet';
const sub = t.connection.subscribe('orchestration.subscribeShell', { requestCompletionMarker: true },
(v) => values.push(...v), (error) => { ended = error; });
t.receive({ _tag: 'Chunk', requestId: 0, values: [{ kind: 'snapshot' }] });
t.receive({ _tag: 'Chunk', requestId: 0, values: [{ kind: 'synchronized' }, { kind: 'thread.updated' }] });
assert.deepEqual(values.map((v) => v.kind), ['snapshot', 'synchronized', 'thread.updated']);
assert.deepEqual(t.sent.slice(1), [{ _tag: 'Ack', requestId: 0 }, { _tag: 'Ack', requestId: 0 }]);
sub.cancel();
assert.deepEqual(t.sent.at(-1), { _tag: 'Interrupt', requestId: 0 });
t.receive({ _tag: 'Exit', requestId: 0, exit: { _tag: 'Failure', cause: [{ _tag: 'Interrupt', fiberId: 1 }] } });
assert.equal(ended, 'not yet', 'a cancelled stream reports nothing more');
});
test('typed failures, defects and batched frames', async () => {
const t = connect();
t.open();
const failing = t.connection.call('subscribeAuthAccess', {});
const dying = t.connection.call('no.such.method', {});
t.receive([
{ _tag: 'Pong' },
{ _tag: 'Exit', requestId: 0, exit: { _tag: 'Failure', cause: [{ _tag: 'Fail', error: { _tag: 'EnvironmentAuthorizationError', message: 'missing scope' } }] } },
{ _tag: 'Exit', requestId: 1, exit: { _tag: 'Failure', cause: [{ _tag: 'Die', defect: 'Unknown request tag: no.such.method' }] } },
]);
await assert.rejects(failing, (error) => error.kind === 'fail' && error.errorTag === 'EnvironmentAuthorizationError' && error.message === 'missing scope');
await assert.rejects(dying, (error) => error.kind === 'die' && /Unknown request tag/.test(error.message));
});
test('a connection-level defect fails everything pending', async () => {
const t = connect();
t.open();
const call = t.connection.call('server.getConfig', {});
let streamError = null;
t.connection.subscribe('subscribeServerConfig', {}, () => {}, (error) => { streamError = error; });
t.receive({ _tag: 'Defect', defect: { name: 'SyntaxError', message: 'bad json' } });
await assert.rejects(call, (error) => error.kind === 'die');
assert.equal(streamError.kind, 'die');
});
test('dropping the socket fails pending work as disconnected', async () => {
const t = connect();
t.open();
const states = [];
t.connection.onStateChange((state, reason) => states.push([state, reason]));
const call = t.connection.call('server.probe', {});
let streamError = null;
t.connection.subscribe('orchestration.subscribeThread', { threadId: 'x' }, () => {}, (error) => { streamError = error; });
t.drop('network gone');
await assert.rejects(call, (error) => error.kind === 'disconnected' && error.message === 'network gone');
assert.equal(streamError.kind, 'disconnected');
assert.deepEqual(states, [['closed', 'network gone']]);
await assert.rejects(t.connection.call('server.probe'), (error) => error.kind === 'disconnected');
});
test('unanswered pings close the connection', () => {
const realSetInterval = global.setInterval;
let tick = null;
global.setInterval = (fn) => { tick = fn; return 1; };
try {
const t = connect({ maxMissedPongs: 2 });
t.open();
tick();
tick();
assert.equal(t.sent.filter((m) => m._tag === 'Ping').length, 2);
t.receive({ _tag: 'Pong' });
tick();
tick();
assert.equal(t.connection.getState(), 'open', 'a pong resets the count');
tick();
assert.equal(t.connection.getState(), 'closed');
assert.equal(t.closedCount(), 1);
} finally {
global.setInterval = realSetInterval;
}
});
test('causeToError prefers typed failures', () => {
const error = causeToError([{ _tag: 'Interrupt' }, { _tag: 'Fail', error: { _tag: 'X', detail: 'why' } }]);
assert.equal(error.kind, 'fail');
assert.equal(error.message, 'why');
assert.equal(causeToError([{ _tag: 'Interrupt' }]).kind, 'interrupt');
});
+5 -5
View File
@@ -1,10 +1,10 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { layoutHubHeader } = require('../.test-build/app/apps/terminal/hub-header.js');
const { HUB_TITLE_X, layoutHubHeader } = require('../.test-build/app/apps/terminal/hub-header.js');
const font = size => ({ measureText: text => [...text].length * size, getGlyph: () => ({ dwidthX: size }) });
test('terminal short status stays inline; exact-fit status does not move the list', () => {
const f = font(7), title = 'Terminal', status = 'Connected.';
const width = 18 + f.measureText(title) + 16 + f.measureText(status) + 12;
const width = HUB_TITLE_X + f.measureText(title) + 16 + f.measureText(status) + 12;
const header = layoutHubHeader(f, title, status, width, 18);
assert.equal(header.y, 10); assert.equal(header.listTop, 34); assert.deepEqual(header.lines, [status]);
assert.equal(layoutHubHeader(f, title, status, width - 1, 18).y, 28);
@@ -14,16 +14,16 @@ test('terminal long error wraps in full-width block and moves menu below all lin
for (const size of [5, 7, 12, 20]) for (const width of [320, 576, 640]) {
const f = font(size), step = size * 2;
const header = layoutHubHeader(f, 'Terminal - Connections', status, width, step);
assert.equal(header.x, 18); assert.equal(header.y, 10 + step);
assert.equal(header.x, HUB_TITLE_X); assert.equal(header.y, 10 + step);
assert.equal(header.lines.join(' '), status);
assert.ok(header.lines.every(line => f.measureText(line) <= width - 30));
assert.ok(header.lines.every(line => f.measureText(line) <= width - HUB_TITLE_X - 12));
assert.ok(header.listTop >= header.y + header.lines.length * step);
assert.equal(header.listTop, 16 + step * (1 + header.lines.length));
}
});
test('terminal explicit newlines and long unbroken messages remain complete', () => {
const h = layoutHubHeader(font(7), 'Terminal', 'First\nSecond', 640, 18);
assert.equal(h.x, 18); assert.deepEqual(h.lines, ['First', 'Second']);
assert.equal(h.x, HUB_TITLE_X); assert.deepEqual(h.lines, ['First', 'Second']);
const word = 'x'.repeat(200);
const wrapped = layoutHubHeader(font(7), 'Terminal', word, 320, 18);
assert.equal(wrapped.lines.join(''), word);
+71
View File
@@ -0,0 +1,71 @@
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');
// Run the worker's actual hub session-list builder with its collaborators stubbed.
function hub({ presets = [] } = {}) {
const file = 'app/apps/terminal/terminal-app.worker.ts';
const source = ts.createSourceFile(file, fs.readFileSync(path.join(__dirname, '..', file), 'utf8'), ts.ScriptTarget.Latest, true);
const functions = new Set(['hubSessionItems', 'isControlConnected', 'controlStatusWord', 'orderedSessions', 'recencyKey', 'sessionLabel']);
const selected = source.statements.filter((s) => ts.isFunctionDeclaration(s) && functions.has(s.name?.text));
const connected = [];
const context = {
controls: new Map(), sessionRecency: new Map(),
launchPresetNames: () => presets,
connectionDisplayName: (config) => config.name,
clientOptionsFor: (config) => (config.url === 'bad' ? null : {}),
isSessionActive: () => false, viewGlyphForSocket: () => null, viewWindowIdForSocket: () => null,
connectControl: (control) => connected.push(control.config.name),
};
vm.runInNewContext(ts.transpileModule(selected.map((s) => s.getText(source)).join('\n'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, context);
const window = { sessionOrder: [] };
return {
connected,
add(name, { enabled = true, phase = null, sessions = [], retrying = false, url = 'ok' } = {}) {
context.controls.set(name, {
config: { id: name, name, url, enabled },
state: phase && { phase, sessions: sessions.map((title) => ({ socket: title, title, command: title })) },
reconnectTimer: retrying ? 1 : null,
});
},
items: () => context.hubSessionItems(window).slice(2), // past Manage Connections + Settings
};
}
// Array.from: the items are arrays from the vm realm.
const rows = (items) => Array.from(items, (item) => `${item.heading ? '# ' : ''}${item.label}${item.onSelect ? '' : ' [x]'}`);
test('every configured host gets a heading in stored order, whatever its state', () => {
const h = hub();
h.add('alpha', { phase: 'connecting' });
h.add('beta', { phase: 'connected', sessions: ['vim'] });
h.add('gamma', { phase: 'failed', retrying: true });
h.add('delta', { enabled: false });
h.add('epsilon', { url: 'bad' });
assert.deepEqual(rows(h.items()), [
'# alpha (connecting) [x]',
'# beta [x]',
'vim',
'# gamma (retrying) [x]',
'Connect now',
'# delta (off) [x]',
'Connect',
'# epsilon (bad connection string) [x]',
]);
h.items().find((item) => item.label === 'Connect').onSelect();
assert.deepEqual(h.connected, ['delta']);
});
test('a lone host still shows its heading; connected headings launch when presets exist', () => {
const h = hub({ presets: ['shell'] });
h.add('solo', { phase: 'connected' });
assert.deepEqual(rows(h.items()), ['# solo', '(no live sessions; run g2mirror <command>)']);
const lone = hub();
lone.add('solo', { phase: 'connecting' });
assert.deepEqual(rows(lone.items()), ['# solo (connecting) [x]']);
});
+11 -3
View File
@@ -16,12 +16,11 @@
"../app/remote/protocol.ts",
"../app/remote/listeners.ts",
"../app/g2/ancs-client.ts",
"../app/graphics/lvgl-font.ts",
"../app/phone-ui/ble-bandwidth-meter.ts",
"../app/apps/terminal/hub-header.ts",
"../app/g2/ios-peripheral-identity.ts",
"../app/graphics/surface-compositor.ts",
"../app/graphics/image.ts",
"../app/graphics/battery.ts",
"../app/graphics/plane.ts",
"../app/graphics/shell-scene.ts",
"../app/ui/metrics.ts",
@@ -35,7 +34,9 @@
"../app/g2/glasses-artwork.ts",
"../app/g2/glasses-display-state.ts",
"../app/g2/glance-state.ts",
"../app/ui/shell/notification-modal-queue.ts",
"../app/apps/glanceboard/layout.ts",
"../app/apps/files/video-layout.ts",
"../app/g2/pairing-candidates.ts",
"../app/apps/calculator/math/*.ts",
"../app/apps/microphones/mic-protocol.ts",
@@ -60,6 +61,13 @@
"../app/health/health-card.ts",
"../app/health/health-phone-chart.ts",
"../app/g2/brightness-curve.ts",
"../app/g2/events.ts"
"../app/g2/events.ts",
"../app/apps/t3code/t3-rpc.ts",
"../app/apps/t3code/t3-pairing.ts",
"../app/apps/t3code/t3-model.ts",
"../app/apps/t3code/t3-auth.ts",
"../app/apps/t3code/t3-client.ts",
"../app/apps/t3code/t3-transcript.ts",
"../app/apps/t3code/t3-glance.ts"
]
}
+57
View File
@@ -0,0 +1,57 @@
const test = require("node:test");
const assert = require("node:assert/strict");
const {
fitVideo,
formatMediaTime,
videoHeightMode,
videoRect,
} = require("../.test-build/app/apps/files/video-layout.js");
const WINDOW = { width: 576, height: 260 };
const TALL_WINDOW = { width: 576, height: 452 };
// ../g2flash/demos/badapple.mp4
const BAD_APPLE = { width: 1444, height: 1080 };
test("fixed sizes fit their box and keep the aspect ratio", () => {
assert.deepEqual(videoRect("small", BAD_APPLE, WINDOW), { x: 208, y: 70, width: 160, height: 120 });
assert.deepEqual(videoRect("medium", BAD_APPLE, WINDOW), { x: 168, y: 40, width: 240, height: 180 });
const wide = videoRect("small", { width: 1920, height: 1080 }, WINDOW);
assert.equal(wide.width, 160);
assert.equal(wide.height, 90);
});
test("large fills the window height; full screen fills the tall window's width", () => {
assert.deepEqual(videoRect("large", BAD_APPLE, WINDOW), { x: 112, y: 0, width: 348, height: 260 });
assert.deepEqual(videoRect("full", BAD_APPLE, TALL_WINDOW), { x: 0, y: 10, width: 576, height: 430 });
assert.equal(videoHeightMode("full"), "max");
assert.equal(videoHeightMode("large"), "min");
});
test("rects are aligned for the delta encoder and stay inside the viewport", () => {
for (const size of ["small", "medium", "large", "full"]) {
for (const video of [BAD_APPLE, { width: 1080, height: 1920 }, { width: 100, height: 20 }, { width: 7, height: 5 }]) {
for (const viewport of [WINDOW, TALL_WINDOW, { width: 150, height: 100 }]) {
const rect = videoRect(size, video, viewport);
const where = `${size} ${video.width}x${video.height} in ${viewport.width}x${viewport.height}`;
assert.equal(rect.x % 4, 0, where);
assert.equal(rect.y % 2, 0, where);
assert.equal(rect.width % 2, 0, where);
assert.equal(rect.height % 2, 0, where);
assert.ok(rect.width >= 2 && rect.height >= 2, where);
assert.ok(rect.x + rect.width <= viewport.width, where);
assert.ok(rect.y + rect.height <= viewport.height, where);
}
}
}
});
test("a tiny video is scaled up to the chosen size", () => {
assert.deepEqual(fitVideo({ width: 80, height: 60 }, { width: 240, height: 180 }), { width: 240, height: 180 });
});
test("media times", () => {
assert.equal(formatMediaTime(0), "0:00");
assert.equal(formatMediaTime(232_130), "3:52");
assert.equal(formatMediaTime(3_723_000), "1:02:03");
});
+199
View File
@@ -0,0 +1,199 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { loader } = require('./helpers/load-typescript.cjs');
const HOUR_MS = 60 * 60 * 1000;
const fix = { latitude: 37.7, longitude: -122.4, accuracyMeters: 8, timestampMs: 1234 };
/** weather.ts with fake timers, settings store and NWS responses. */
function weatherHarness({ periods, observation = null, store = new Map(), permission = () => true }) {
const timers = new Map(), requests = [];
let nextTimer = 1;
const api = loader({
setTimeout: (fn, ms) => { const id = nextTimer++; timers.set(id, { fn: () => { timers.delete(id); fn(); }, ms }); return id; },
clearTimeout: id => timers.delete(id),
}, {
'./location-permissions': { hasLocationPermission: permission },
'./location': { getCurrentLocation: async () => fix },
'./settings-store': { getStringSetting: (key, fallback) => store.get(key) ?? fallback, setStringSetting: (key, value) => store.set(key, value) },
'../version': { USER_AGENT: 'test' },
'../util/http': { fetchWithUserAgent: async url => {
requests.push(url);
let body;
if (url.includes('/points/')) {
body = { properties: {
forecast: 'https://fixture/forecast',
observationStations: observation ? 'https://fixture/stations' : undefined,
relativeLocation: { properties: { city: 'San Francisco', state: 'CA' } },
} };
} else if (url === 'https://fixture/stations') {
body = { features: [{ id: 'https://fixture/station' }] };
} else if (url.endsWith('/observations/latest')) {
body = { properties: observation };
} else {
body = { properties: { periods } };
}
return { ok: true, json: async () => body };
} },
})('app/native/weather.ts');
// Only the bridge's refresh timer outlives a refresh (fetch timeouts are cleared).
const refreshTimer = () => {
assert.ok(timers.size <= 1, `expected at most one timer, got ${timers.size}`);
return [...timers.values()][0] ?? null;
};
return { api, store, requests, refreshTimer };
}
const sunny = { name: 'Today', temperature: 70, temperatureUnit: 'F', shortForecast: 'Sunny', isDaytime: true };
test('Weather takes the condition from the NWS icon, falling back to the text', async () => {
const h = weatherHarness({
periods: [
{ ...sunny, icon: 'https://api.weather.gov/icons/land/night/snow,60/rain,20?size=medium' },
{ ...sunny, name: 'Tonight', shortForecast: 'Chance Rain Showers', isDaytime: false },
{ ...sunny, name: 'Monday', shortForecast: 'Mostly Cloudy' },
],
observation: {
textDescription: 'Thunderstorms', icon: 'https://api.weather.gov/icons/land/day/tsra?size=medium',
temperature: { value: 20, unitCode: 'wmoUnit:degC' },
},
});
const bridge = new h.api.WeatherBridge();
await bridge.refreshNow();
const { current, forecast } = bridge.snapshot();
assert.equal(current.condition, 'thunderstorm');
assert.equal(current.isDaytime, true);
assert.equal(current.temperatureF, 68);
// The first code of a two-part icon, and its day/night segment.
assert.equal(forecast[0].condition, 'snow');
assert.equal(forecast[0].isDaytime, false);
assert.equal(forecast[1].condition, 'showers');
assert.equal(forecast[2].condition, 'cloudy');
});
test('Weather without an observation takes the condition from the first forecast period', async () => {
const h = weatherHarness({ periods: [{ ...sunny, icon: 'https://api.weather.gov/icons/land/day/few?size=medium' }] });
const bridge = new h.api.WeatherBridge();
await bridge.refreshNow();
assert.equal(bridge.snapshot().current.condition, 'partly-cloudy');
assert.equal(bridge.snapshot().current.observed, false);
});
test('Weather restores its cache on restart and refreshes hourly only during a session with an indicator on', async () => {
const first = weatherHarness({ periods: [sunny] });
const bridge = new first.api.WeatherBridge();
await bridge.refreshNow();
assert.ok(first.store.get('weather.cache'));
// A restart shows the cached reading without fetching.
const h = weatherHarness({ periods: [sunny], store: first.store });
const restarted = new h.api.WeatherBridge();
assert.equal(restarted.snapshot().phase, 'ready');
assert.equal(restarted.snapshot().current.temperatureF, 70);
assert.equal(h.requests.length, 0);
restarted.setBackgroundRefresh(true);
assert.equal(h.refreshTimer(), null, 'no refreshes outside a glasses session');
restarted.setSessionActive(true);
const timer = h.refreshTimer();
assert.ok(timer.ms > HOUR_MS - 60_000 && timer.ms <= HOUR_MS, `fresh cache waits out the hour (${timer.ms})`);
restarted.setBackgroundRefresh(false);
assert.equal(h.refreshTimer(), null);
restarted.setBackgroundRefresh(true);
restarted.setSessionActive(false);
assert.equal(h.refreshTimer(), null);
});
test('Weather refreshes a stale cache at once and backs off after a failure', async () => {
const store = new Map([['weather.cache', JSON.stringify({
version: 1, locationName: 'Old', current: null, forecast: [], lastUpdatedMs: Date.now() - 2 * HOUR_MS,
})]]);
let permission = true;
const h = weatherHarness({ periods: [sunny], store, permission: () => permission });
const bridge = new h.api.WeatherBridge();
bridge.setBackgroundRefresh(true);
bridge.setSessionActive(true);
assert.equal(h.refreshTimer().ms, 0);
h.refreshTimer().fn();
await bridge.refreshNow();
assert.equal(bridge.snapshot().locationName, 'San Francisco, CA');
assert.ok(h.refreshTimer().ms > HOUR_MS - 60_000);
// Without permission the attempt fails; the next one waits the retry delay, not zero.
permission = false;
await bridge.refreshNow();
assert.equal(bridge.snapshot().phase, 'permission-required');
const retry = h.refreshTimer().ms;
assert.ok(retry > 9 * 60_000 && retry <= 10 * 60_000, `retry delay ${retry}`);
});
/** weather-indicators.ts with a fake shell, settings and bridge. */
function indicatorHarness() {
const settings = new Map(), settingListeners = new Set(), stateListeners = new Set(), trays = [];
const background = [];
let state = { phase: 'ready', current: null, forecast: [], lastUpdatedMs: null };
class GrayImage {
constructor(width, height) { this.width = width; this.height = height; this.draws = []; }
drawImage(_source, x, y) { this.draws.push(['image', x, y]); }
drawText(_font, x, y, text) { this.draws.push(['text', x, y, text]); }
withDrawsBaked() { return this; }
}
const font = { lineHeight: 12, measureText: text => text.length * 6 };
class Setting {
constructor(options) { Object.assign(this, options); }
get() { return settings.get(this.storageKey) ?? this.defaultValue; }
}
const api = loader({}, {
'../../graphics/image': { GrayImage },
'../../graphics/ui-fonts': { getDefaultSmallFont: () => font },
'../../graphics/icons': { renderSvgIcon: (_name, _svg, size) => new GrayImage(size, size) },
'../../native/weather': { weatherBridge: {
onStateChange: listener => { stateListeners.add(listener); listener(state); return () => stateListeners.delete(listener); },
snapshot: () => state,
setBackgroundRefresh: enabled => background.push(enabled),
} },
'../../ui/dashboard-settings': {
ConfigSettingBoolean: Setting,
onAnySettingChanged: listener => { settingListeners.add(listener); return () => settingListeners.delete(listener); },
},
'../../ui/shell/shell': { shell: { setTrayIcon: (id, icon) => trays.push([id, icon]) } },
})('app/apps/weather/weather-indicators.ts');
return {
api, trays, background,
setSetting(key, value) { settings.set(key, value); for (const listener of settingListeners) listener(); },
setState(next) { state = next; for (const listener of stateListeners) listener(state); },
};
}
test('Weather tray icon follows the status-bar setting and hides a stale reading', () => {
const h = indicatorHarness();
h.api.startWeatherIndicators();
assert.deepEqual(h.background, [false]);
assert.equal(h.trays.length, 0, 'nothing shown, nothing to clear');
h.setSetting('weather.showOnSystemCard', true);
assert.equal(h.background.at(-1), true, 'the system card alone keeps refreshes running');
assert.equal(h.trays.length, 0);
h.setSetting('weather.showInStatusBar', true);
const current = { temperatureF: 71.6, condition: 'rain', isDaytime: true };
h.setState({ phase: 'ready', current, forecast: [], lastUpdatedMs: Date.now() });
const [id, icon] = h.trays.at(-1);
assert.equal(id, 'weather');
assert.equal(icon.height, 24);
assert.deepEqual(icon.draws.map(draw => draw[0]), ['image', 'text']);
assert.equal(icon.draws[1][3], '72°');
// An unchanged reading does not rebuild the icon.
const count = h.trays.length;
h.setState({ phase: 'loading', current, forecast: [], lastUpdatedMs: Date.now() });
assert.equal(h.trays.length, count);
h.setState({ phase: 'error', current, forecast: [], lastUpdatedMs: Date.now() - 4 * HOUR_MS });
assert.deepEqual(h.trays.at(-1), ['weather', null]);
h.setSetting('weather.showOnSystemCard', false);
h.setSetting('weather.showInStatusBar', false);
assert.equal(h.background.at(-1), false);
});