Enhancements to Nightscout and Terminal apps

Nightscout app: Alert thresholds for canula age, cartridge volume, pump
battery, time since last loop, shown in top bar. Option to always show
in top bar when window is closed.

Terminal app: Activity indicators in the app-switcher sidebar.
</details>
This commit is contained in:
James Babcock committed 2026-09-08 13:58:47 -07:00
1 parent 9b70880a5b
commit 070c891577
13 files changed
+566 -71

No files matched your search

+156
View File
@@ -0,0 +1,156 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const ts = require('typescript');
const alerts = require('../.test-build/app/apps/nightscout/nightscout-alerts.js');
const now = 1_800_000_000_000;
const limits = { maxCannulaAgeHours: 72, cartridgeLowUnits: 20, batteryLowVoltage: 1.2, maxLoopAgeMinutes: 15 };
const healthy = { cageTimestampMs: now, reservoirUnits: 100, batteryVoltage: 1.5, loopTimestampMs: now };
function load(file, dependencies, globals = {}) {
const source = fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
const context = { exports: {}, require(name) { assert.ok(name in dependencies, name); return dependencies[name]; }, ...globals };
vm.runInNewContext(ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
}).outputText, context);
return context.exports;
}
test('each threshold breaches independently, with strict boundaries and zero disabling it', () => {
const cases = [
['cageTimestampMs', 'maxCannulaAgeHours', 'cannula', now - 72 * 3_600_000, -1],
['reservoirUnits', 'cartridgeLowUnits', 'cartridge', 20, -0.01],
['batteryVoltage', 'batteryLowVoltage', 'battery', 1.2, -0.01],
['loopTimestampMs', 'maxLoopAgeMinutes', 'loop', now - 15 * 60_000, -1],
];
for (const [field, threshold, warning, boundary, delta] of cases) {
assert.equal(alerts.evaluateNightscoutAlerts({ ...healthy, [field]: boundary }, limits, now).any, false);
const result = alerts.evaluateNightscoutAlerts({ ...healthy, [field]: boundary + delta }, limits, now);
assert.equal(result[warning], true);
assert.equal(result.any, true);
assert.equal(Object.values(result).filter(Boolean).length, 2);
assert.equal(alerts.evaluateNightscoutAlerts({ ...healthy, [field]: boundary + delta }, { ...limits, [threshold]: 0 }, now).any, false);
}
});
test('missing/invalid measurements do not alert; real empty reservoirs do', () => {
for (const value of [null, NaN, -1, Infinity]) {
const values = Object.fromEntries(Object.keys(healthy).map(key => [key, value]));
assert.equal(alerts.evaluateNightscoutAlerts(values, limits, now).any, false);
}
assert.equal(alerts.evaluateNightscoutAlerts({ ...healthy, reservoirUnits: 0 }, limits, now).cartridge, true);
assert.equal(alerts.evaluateNightscoutAlerts({ ...healthy, loopTimestampMs: now + 60_000 }, limits, now).loop, false);
for (const value of ['', '-2', 'NaN', 'Infinity', '12abc', null]) assert.equal(alerts.normalizeNightscoutThreshold(value), '0');
assert.equal(alerts.normalizeNightscoutThreshold(' 1.25 '), '1.25');
assert.equal(alerts.normalizeNightscoutThreshold('.5'), '0.5');
});
class Image {
constructor(width, height) { this.width = width; this.height = height; this.draws = []; }
drawText(font, ...args) { this.draws.push(['text', ...args]); }
drawLine(...args) { this.draws.push(['line', ...args]); }
fillRect(...args) { this.draws.push(['rect', ...args]); }
}
const font = { measureText: text => text.length * 6, lineHeight: 12, hasGlyph: () => true };
function fixture(always = false) {
let time = now, icon, tick, changed, notify, renders = 0;
const state = { ...healthy, available: true, latest: { sgv: 100, timestampMs: now }, history: [], units: 'mg/dL', delta: 0, direction: '', iob: 1, cob: 0, pumpStatus: '0m ago', configurationMissing: false };
const bridge = { snapshot: () => state, onStateChange(fn) { notify = fn; fn(state); } };
const settings = { loadNightscoutThresholds: () => limits, nightscoutAlwaysShowInTopBarSetting: { get: () => always }, onAnySettingChanged(fn) { changed = fn; }, isNightscoutSettingsConfigured: () => true };
const deps = {
'../../graphics/image': { GrayImage: Image },
'../../graphics/ui-fonts': { getDefaultSmallFont: () => font, getDefaultLargeFont: () => font },
'../../native/nightscout-bridge': { nightscoutBridge: bridge },
'../../ui/dashboard-settings': settings,
'./nightscout-alerts': alerts,
};
const app = load('app/apps/nightscout/nightscout-app.ts', {
...deps,
'./nightscout': { NightscoutLayer: class {}, nightscoutMenuItems() {} },
'../../ui/shell/shell': { shell: { setTrayIcon(id, value) { icon = value; } } },
'../../ui/shell/in-process-window': { YieldAtRootLayer: class {}, createInProcessWindow: options => ({ close: options.onClosed, requestRender() { renders++; } }) },
}, { Date: { now: () => time }, setInterval(fn) { tick = fn; return 1; }, clearInterval() { tick = null; } });
return { app, deps, state, icon: () => icon, tick: () => tick?.(), advance(ms) { time += ms; }, notify: () => notify(), toggle(value) { always = value; changed(); }, renders: () => renders };
}
test('tray boots without a window, persists on close, and responds to settings and elapsed time', () => {
const f = fixture(true);
f.app.startNightscoutTrayIcon();
assert.ok(f.icon());
const width = f.icon().width;
f.advance(16 * 60_000); f.tick();
assert.equal(f.icon().width, width + 24);
const triangle = f.icon().draws.filter(d => d[0] === 'line' && d.at(-1) === 255);
assert.equal(triangle.length, 3);
assert.ok(triangle.every(d => d[1] > width && d[3] > width));
f.toggle(false); assert.equal(f.icon(), null);
const window = f.app.createNightscoutAppWindow({ onClosed() {} });
assert.ok(f.icon());
f.toggle(true); window.close(); assert.ok(f.icon());
const renders = f.renders(); f.notify(); assert.equal(f.renders(), renders);
f.toggle(false); assert.equal(f.icon(), null);
const reopened = f.app.createNightscoutAppWindow({ onClosed() {} });
reopened.close(); assert.equal(f.icon(), null);
});
test('tray is hidden by default and clears recovered measurement warnings immediately', () => {
const f = fixture();
f.app.startNightscoutTrayIcon();
assert.equal(f.icon(), null);
const first = f.app.createNightscoutAppWindow({ onClosed() {} });
const width = f.icon().width;
f.state.batteryVoltage = 1;
f.notify(); assert.equal(f.icon().width, width + 24);
f.state.batteryVoltage = 1.5;
f.notify(); assert.equal(f.icon().width, width);
const second = f.app.createNightscoutAppWindow({ onClosed() {} });
first.close(); assert.ok(f.icon());
second.close(); assert.equal(f.icon(), null);
});
test('main page highlights only the breached field and removes highlights on recovery', () => {
const f = fixture();
const page = load('app/apps/nightscout/nightscout.ts', {
...f.deps,
'../../graphics/textwrap': { truncateText: (font, text) => text },
'../../ui/gestures': {}, '../../ui/layers': {}, '../../ui/menu': {},
'../../ui/dashboard/settings-panel': {}, '../../ui/metrics': { lineStep: () => 16 },
'~/util/date-util': { formatAgeShortFromTimestamp: () => '1m', formatTimestamp: () => '12:00' },
}, { Date: { now: () => now } });
const layer = new page.NightscoutLayer();
const paint = () => layer.paint({ stack: { getBaseSize: () => ({ width: 576, height: 260 }) } });
for (const [field, value, label] of [['reservoirUnits', 10, '10U'], ['batteryVoltage', 1, '1.00V'], ['cageTimestampMs', now - 73 * 3_600_000, 'CAGE 1m'], ['loopTimestampMs', now - 16 * 60_000, 'Loop 1m']]) {
f.state[field] = value;
const image = paint();
const highlighted = image.draws.filter(d => d[0] === 'text' && d.at(-1) === 0);
assert.equal(highlighted.length, 1);
assert.equal(highlighted[0][3], label);
f.state[field] = healthy[field];
assert.equal(paint().draws.filter(d => d[0] === 'text' && d.at(-1) === 0).length, 0);
}
});
test('bridge exposes numeric measurements and treats absent values as unknown', async () => {
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) {
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 };
} },
}, { Date, console });
const bridge = new module.NightscoutBridge();
await bridge.refreshNow();
assert.equal(bridge.snapshot().reservoirUnits, 10.5);
assert.equal(bridge.snapshot().batteryVoltage, 1.15);
assert.equal(bridge.snapshot().loopTimestampMs, now - 60_000);
pump = { reservoir: null, battery: { voltage: '' } };
await bridge.refreshNow();
assert.equal(bridge.snapshot().reservoirUnits, null);
assert.equal(bridge.snapshot().batteryVoltage, null);
pump = { reservoir: 0, battery: { voltage: 0 } };
await bridge.refreshNow();
assert.equal(bridge.snapshot().reservoirUnits, 0);
});
+163
View File
@@ -0,0 +1,163 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const ts = require('typescript');
const read = file => fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
const js = source => ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText;
// Run the worker's actual activity and lifecycle code with platform work stubbed.
function worker() {
let now = 100_000, timer, renderCount = 0;
const messages = [];
const file = 'app/apps/terminal/terminal-app.worker.ts';
const source = ts.createSourceFile(file, read(file), ts.ScriptTarget.Latest, true);
const functions = new Set(['recencyKey', 'post', 'renderHubWindows', 'isSessionActive', 'isWindowSessionActive', 'hubAnimationShouldRun', 'syncWindowIconActivity', 'updateHubAnimation', 'noteSessionActivity', 'openWindow', 'closeWindow']);
const variables = new Set(['windows', 'pendingViews', 'activeViewId', 'sessionRecency', 'sessionActivity', 'ACTIVITY_ACTIVE_MS', 'HUB_ANIMATION_STEP_MS', 'hubAnimationPhase', 'hubAnimationTimer', 'windowIconActivity', 'screenOn']);
const selected = source.statements.filter(s =>
ts.isFunctionDeclaration(s) && functions.has(s.name?.text) ||
ts.isVariableStatement(s) && s.declarationList.declarations.some(d => variables.has(d.name.getText(source))) ||
ts.isExpressionStatement(s) && ts.isBinaryExpression(s.expression) && s.expression.left.getText(source) === 'global.onmessage');
const context = {
exports: {}, Date: { now: () => now },
setInterval(fn, ms) { assert.equal(ms, 800); assert.equal(timer, undefined); timer = fn; return 1; },
clearInterval() { timer = undefined; },
global: { postMessage: message => messages.push(message) },
scheduleRender() { renderCount++; }, renderAndSubmit() {}, maybeReconnectView() {},
controlsInitialized: true, controls: new Map(), TERMINAL_TOOLS: [],
getTerminalFontConfig: () => ({ cellWidth: 6, cellHeight: 12 }),
};
vm.runInNewContext(js(selected.map(s => s.getText(source)).join('\n')) + '\nexports.windows = windows;', context);
const message = data => context.global.onmessage({ data });
return {
messages, windows: context.exports.windows,
activity: (connection = 'host1', socket = 'a') => context.noteSessionActivity(connection, socket),
openHub() { context.openWindow('hub', 'surface:hub', 'Terminal', { width: 576, height: 260 }); },
addView(id, connectionId = 'host1', socket = 'a') {
context.exports.windows.set(id, { windowId: id, kind: 'view', connectionId, socket, foreground: false, unsubscribers: [], client: { stop() {} } });
context.updateHubAnimation();
},
close: id => context.closeWindow(id),
screen: on => message({ type: 'screen', on }),
advance(ms) { now += ms; timer?.(); },
running: () => !!timer,
phase(id) { return messages.filter(m => m.type === 'set-icon-activity' && m.windowId === id).at(-1)?.activity ?? 'idle'; },
};
}
test('background hub aggregates activity; session icons match both host and socket', () => {
const w = worker();
w.openHub(); w.addView('a'); w.addView('b', 'host1', 'b'); w.addView('other-host', 'host2', 'a');
assert.equal(w.running(), false);
w.activity();
assert.equal(w.phase('hub'), 'on'); assert.equal(w.phase('a'), 'on');
assert.equal(w.phase('b'), 'idle'); assert.equal(w.phase('other-host'), 'idle');
w.advance(800);
assert.equal(w.phase('hub'), 'off'); assert.equal(w.phase('a'), 'off');
w.advance(800); assert.equal(w.phase('a'), 'on');
w.activity('host2', 'a'); assert.equal(w.phase('other-host'), 'on');
w.advance(3400);
assert.equal(w.phase('a'), 'idle'); assert.notEqual(w.phase('hub'), 'idle');
w.advance(1600);
assert.equal(w.phase('hub'), 'idle'); assert.equal(w.phase('other-host'), 'idle');
assert.equal(w.running(), false);
});
test('animation continues with hub closed and stops after the final window closes', () => {
const w = worker();
w.openHub(); w.addView('a'); w.activity(); w.close('hub');
w.advance(800); assert.equal(w.phase('a'), 'off'); assert.equal(w.running(), true);
w.close('a'); assert.equal(w.running(), false);
w.activity(); assert.equal(w.running(), false);
w.openHub(); assert.equal(w.phase('hub'), 'on'); assert.equal(w.running(), true);
});
test('screen off pauses animation; wake recalculates fresh and expired activity', () => {
const w = worker();
w.addView('a'); w.activity(); w.screen(false);
assert.equal(w.running(), false);
w.advance(1000); w.screen(true);
assert.equal(w.phase('a'), 'on'); assert.equal(w.running(), true);
w.screen(false); w.advance(5000); w.screen(true);
assert.equal(w.phase('a'), 'idle'); assert.equal(w.running(), false);
});
test('unopened sessions activate the hub and repeated pushes extend activity without duplicate messages', () => {
const w = worker();
w.openHub(); w.activity('host2', 'unopened');
assert.equal(w.phase('hub'), 'on');
const count = w.messages.length; w.activity('host2', 'unopened'); assert.equal(w.messages.length, count);
w.advance(4000); w.activity('host2', 'unopened'); w.advance(2000);
assert.notEqual(w.phase('hub'), 'idle');
w.advance(3000); assert.equal(w.phase('hub'), 'idle');
});
function load(file, deps, globals = {}) {
const context = { exports: {}, require(name) { assert.ok(name in deps, name); return deps[name]; }, ...globals };
vm.runInNewContext(js(read(file)), context);
return context.exports;
}
class Image {
constructor(width, height) { this.width = width; this.height = height; this.pixels = new Uint8Array(width * height); }
}
test('cursor replaces only the prompt; marker and frame persist across cached blink phases', () => {
const renders = [];
const icons = load('app/graphics/icons.ts', { './image': { GrayImage: Image } }, {
global: { isAndroid: true },
com: { faceclaw: { app: { IconRenderer: { renderSvgGray(svg, size, stroke) {
renders.push(svg); assert.equal(stroke, 2); return new Uint8Array(size * size).fill(255);
} } } } },
});
for (const glyph of ['', '1', '3', 'A']) {
const idle = icons.renderIconWithGlyph('terminal', glyph, 24, 'idle');
const idleSvg = renders.at(-1);
const on = icons.renderIconWithGlyph('terminal', glyph, 24, 'on');
const onSvg = renders.at(-1);
const off = icons.renderIconWithGlyph('terminal', glyph, 24, 'off');
const offSvg = renders.at(-1);
const prompt = '<path d="m7 11 2-2-2-2"/>';
const cursor = '<rect x="7.5" y="8" width="1" height="6"/>';
assert.ok(idleSvg.includes(prompt)); assert.ok(onSvg.includes(cursor));
assert.equal(onSvg.includes(prompt), false); assert.equal(offSvg.includes(prompt), false);
assert.equal(idleSvg.replace(prompt, ''), offSvg);
assert.equal(onSvg.replace(cursor, ''), offSvg);
assert.notEqual(on, off); assert.notEqual(idle, on);
const count = renders.length;
assert.equal(icons.renderIconWithGlyph('terminal', glyph, 24, 'on'), on);
assert.equal(renders.length, count);
}
assert.equal(icons.renderIconWithGlyph('timer', '', 24, 'on'), icons.renderIcon('timer', 24));
});
test('host applies activity only to its own open windows and cleans up on close', async () => {
let paints = 0;
const worker = { postMessage() {} };
const shellWindows = new Map();
const { WorkerAppHost } = load('app/ui/shell/worker-window.ts', {
'../../graphics/image': { GrayImage: Image },
'./chrome-layer': { windowIcon: (icon, letter, glyph, phase) => phase },
'../../assistant/tool-registry': { toolRegistry: { removeAppTools() {} } },
'./geometry': { appViewportSize: () => ({ width: 576, height: 260 }) },
'../../native/frame-timings': {},
'./shell': { shell: { registerWindow: w => shellWindows.set(w.windowId, w) } },
});
const host = new WorkerAppHost({ appId: 'terminal', worker, configureSurface: async () => {}, requestShellRender() { paints++; }, removeSurface() {} });
const spec = { windowId: 'a', title: 'A', icon: 'terminal', iconGlyph: '1' };
const window = host.openWindow(spec);
await Promise.resolve();
const send = (windowId, activity) => worker.onmessage({ data: { type: 'set-icon-activity', windowId, activity } });
assert.equal(window.drawIcon(), 'idle');
let count = paints; send('unknown', 'on'); assert.equal(paints, count);
send('a', 'on'); assert.equal(window.drawIcon(), 'on'); assert.equal(paints, count + 1);
count = paints; send('a', 'on'); assert.equal(paints, count);
send('a', 'off'); assert.equal(window.drawIcon(), 'off');
send('a', 'idle'); assert.equal(window.drawIcon(), 'idle');
send('a', 'on'); window.close(); count = paints;
send('a', 'off'); assert.equal(paints, count);
const reopened = host.openWindow(spec); assert.equal(reopened.drawIcon(), 'idle');
});
+2 -1
View File
@@ -26,6 +26,7 @@
"../app/apps/microphones/name-guess.ts",
"../app/apps/evenhub/containers.ts",
"../app/apps/timer/timer-model.ts",
"../app/apps/teleprompter/script-tracker.ts"
"../app/apps/teleprompter/script-tracker.ts",
"../app/apps/nightscout/nightscout-alerts.ts"
]
}