forked from Blendman974/faceclaw
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:
1 parent
9b70880a5b
commit
070c891577
13 files changed
+566
-71
No files matched your search
@@ -1,10 +1,11 @@
|
||||
import { type AppDefinition } from "../app-definition";
|
||||
import { createNightscoutAppWindow, NIGHTSCOUT_SURFACE_ID, NIGHTSCOUT_WINDOW_ID } from "./nightscout-app";
|
||||
import { createNightscoutAppWindow, startNightscoutTrayIcon, NIGHTSCOUT_SURFACE_ID, NIGHTSCOUT_WINDOW_ID } from "./nightscout-app";
|
||||
|
||||
const nightscoutApp: AppDefinition = {
|
||||
appId: "nightscout",
|
||||
title: "Nightscout",
|
||||
icon: "nightscout",
|
||||
boot: () => startNightscoutTrayIcon(),
|
||||
launch: (ctx) => ctx.launchInProcessApp(NIGHTSCOUT_WINDOW_ID, NIGHTSCOUT_SURFACE_ID, createNightscoutAppWindow),
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
export type NightscoutAlertValues = {
|
||||
cageTimestampMs: number | null;
|
||||
reservoirUnits: number | null;
|
||||
batteryVoltage: number | null;
|
||||
loopTimestampMs: number | null;
|
||||
};
|
||||
|
||||
export type NightscoutThresholds = {
|
||||
maxCannulaAgeHours: number;
|
||||
cartridgeLowUnits: number;
|
||||
batteryLowVoltage: number;
|
||||
maxLoopAgeMinutes: number;
|
||||
};
|
||||
|
||||
/** Zero disables a threshold. Missing measurements do not imply a breach. */
|
||||
export function evaluateNightscoutAlerts(values: NightscoutAlertValues, limits: NightscoutThresholds, nowMs: number) {
|
||||
const known = (value: number | null): value is number => value !== null && Number.isFinite(value) && value >= 0;
|
||||
const enabled = (value: number): boolean => Number.isFinite(value) && value > 0;
|
||||
const tooOld = (timestamp: number | null, limit: number, unitMs: number): boolean =>
|
||||
enabled(limit) && known(timestamp) && timestamp > 0 && nowMs - timestamp > limit * unitMs;
|
||||
const tooLow = (value: number | null, limit: number): boolean => enabled(limit) && known(value) && value < limit;
|
||||
const cannula = tooOld(values.cageTimestampMs, limits.maxCannulaAgeHours, 3_600_000);
|
||||
const cartridge = tooLow(values.reservoirUnits, limits.cartridgeLowUnits);
|
||||
const battery = tooLow(values.batteryVoltage, limits.batteryLowVoltage);
|
||||
const loop = tooOld(values.loopTimestampMs, limits.maxLoopAgeMinutes, 60_000);
|
||||
return { cannula, cartridge, battery, loop, any: cannula || cartridge || battery || loop };
|
||||
}
|
||||
|
||||
export function normalizeNightscoutThreshold(value: string | null | undefined): string {
|
||||
const text = (value ?? "").trim();
|
||||
const number = Number(text);
|
||||
return /^(\d+(\.\d*)?|\.\d+)$/.test(text) && Number.isFinite(number) && number >= 0 ? String(number) : "0";
|
||||
}
|
||||
@@ -8,6 +8,8 @@ import {
|
||||
type InProcessAppOptions,
|
||||
type InProcessWindow,
|
||||
} from "../../ui/shell/in-process-window";
|
||||
import { evaluateNightscoutAlerts } from "./nightscout-alerts";
|
||||
import { loadNightscoutThresholds, nightscoutAlwaysShowInTopBarSetting, onAnySettingChanged } from "../../ui/dashboard-settings";
|
||||
import { shell } from "../../ui/shell/shell";
|
||||
|
||||
export const NIGHTSCOUT_WINDOW_ID = "nightscout";
|
||||
@@ -19,14 +21,34 @@ const TRAY_GRAPH_WIDTH = 48;
|
||||
const TRAY_STALE_MS = 15 * 60 * 1000;
|
||||
const TRAY_GRAPH_WINDOW_MS = 2 * 60 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* The Nightscout app: the full-screen glucose view (previously reached via
|
||||
* the dashboard card) in its own in-process window. While the app is running
|
||||
* it also publishes a top-bar tray icon: the latest blood-glucose value
|
||||
* (struck through when stale) plus a minimal 48px history graph.
|
||||
*/
|
||||
const windowRenders = new Set<() => void>();
|
||||
let trayStarted = false;
|
||||
let trayTick: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
function syncNightscout(): void {
|
||||
const visible = windowRenders.size > 0 || nightscoutAlwaysShowInTopBarSetting.get();
|
||||
shell.setTrayIcon(TRAY_ICON_ID, visible ? buildNightscoutTrayIcon(nightscoutBridge.snapshot()) : null);
|
||||
for (const render of windowRenders) render();
|
||||
// Age warnings and stale glucose must advance even during a stalled fetch.
|
||||
if (visible && trayTick === null) trayTick = setInterval(syncNightscout, 60_000);
|
||||
if (!visible && trayTick !== null) {
|
||||
clearInterval(trayTick);
|
||||
trayTick = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Shell-lifetime subscription so the tray can be enabled before any window opens. */
|
||||
export function startNightscoutTrayIcon(): void {
|
||||
if (trayStarted) return;
|
||||
trayStarted = true;
|
||||
nightscoutBridge.onStateChange(syncNightscout);
|
||||
onAnySettingChanged(syncNightscout);
|
||||
}
|
||||
|
||||
/** Full-screen glucose view with a shared, optionally persistent tray readout. */
|
||||
export function createNightscoutAppWindow(options: InProcessAppOptions): InProcessWindow {
|
||||
let unsubscribe: (() => void) | null = null;
|
||||
startNightscoutTrayIcon();
|
||||
const render = () => app.requestRender();
|
||||
const app = createInProcessWindow({
|
||||
appId: "nightscout",
|
||||
windowId: NIGHTSCOUT_WINDOW_ID,
|
||||
@@ -41,28 +63,25 @@ export function createNightscoutAppWindow(options: InProcessAppOptions): InProce
|
||||
setSurfaceVisible: options.setSurfaceVisible,
|
||||
removeSurface: options.removeSurface,
|
||||
onClosed: () => {
|
||||
unsubscribe?.();
|
||||
unsubscribe = null;
|
||||
shell.setTrayIcon(TRAY_ICON_ID, null);
|
||||
windowRenders.delete(render);
|
||||
syncNightscout();
|
||||
options.onClosed();
|
||||
},
|
||||
});
|
||||
// onStateChange fires immediately with the current snapshot, so this also
|
||||
// publishes the initial tray icon.
|
||||
unsubscribe = nightscoutBridge.onStateChange((state) => {
|
||||
shell.setTrayIcon(TRAY_ICON_ID, buildNightscoutTrayIcon(state));
|
||||
app.requestRender();
|
||||
});
|
||||
windowRenders.add(render);
|
||||
syncNightscout();
|
||||
return app;
|
||||
}
|
||||
|
||||
/** BG value (struck through when stale) + minimal 2-hour line graph. */
|
||||
/** BG value, 2-hour graph, then a warning triangle when any threshold is breached. */
|
||||
function buildNightscoutTrayIcon(state: NightscoutState): GrayImage {
|
||||
const font = getDefaultSmallFont();
|
||||
const nowMs = Date.now();
|
||||
const label = state.latest ? `${state.latest.sgv}` : "--";
|
||||
const labelWidth = font.measureText(label);
|
||||
const image = new GrayImage(labelWidth + 4 + TRAY_GRAPH_WIDTH, TRAY_HEIGHT, 0);
|
||||
const warning = evaluateNightscoutAlerts(state, loadNightscoutThresholds(), nowMs).any;
|
||||
const graphEnd = labelWidth + 4 + TRAY_GRAPH_WIDTH;
|
||||
const image = new GrayImage(graphEnd + (warning ? 24 : 0), TRAY_HEIGHT, 0);
|
||||
|
||||
const textY = Math.max(0, ((TRAY_HEIGHT - font.lineHeight) / 2) | 0);
|
||||
image.drawText(font, 0, textY, label, 220);
|
||||
@@ -72,6 +91,14 @@ function buildNightscoutTrayIcon(state: NightscoutState): GrayImage {
|
||||
}
|
||||
|
||||
drawTrayGraph(image, labelWidth + 4, state, nowMs);
|
||||
if (warning) {
|
||||
const x = graphEnd + 4;
|
||||
image.drawLine(x + 9, 3, x, 20, 255);
|
||||
image.drawLine(x, 20, x + 18, 20, 255);
|
||||
image.drawLine(x + 18, 20, x + 9, 3, 255);
|
||||
image.fillRect(x + 8, 9, 2, 6, 255);
|
||||
image.fillRect(x + 8, 17, 2, 2, 255);
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { evaluateNightscoutAlerts } from "./nightscout-alerts";
|
||||
import { getDefaultLargeFont, getDefaultSmallFont } from "../../graphics/ui-fonts";
|
||||
import { GrayImage, type UiFont } from "../../graphics/image";
|
||||
import { truncateText } from "../../graphics/textwrap";
|
||||
@@ -6,6 +7,13 @@ import { Layer, LayerContext } from "../../ui/layers";
|
||||
import { nightscoutBridge, type NightscoutState } from "../../native/nightscout-bridge";
|
||||
import {
|
||||
isNightscoutSettingsConfigured,
|
||||
loadNightscoutThresholds,
|
||||
nightscoutMaxCannulaAgeSetting,
|
||||
nightscoutCartridgeLowSetting,
|
||||
nightscoutBatteryLowSetting,
|
||||
nightscoutMaxLoopAgeSetting,
|
||||
nightscoutAlwaysShowInTopBarSetting,
|
||||
toggleSettingMenuItem,
|
||||
nightscoutApiTokenSetting,
|
||||
nightscoutSiteUrlSetting,
|
||||
textSettingMenuItem,
|
||||
@@ -332,21 +340,43 @@ export class NightscoutLayer implements Layer {
|
||||
|
||||
const statusX = 170;
|
||||
const statusWidth = width - 22 - statusX;
|
||||
const statusLines: { text: string; shade: number; direction?: string }[] = [
|
||||
const alerts = evaluateNightscoutAlerts(nightscout, loadNightscoutThresholds(), nowMs);
|
||||
const statusLines: { text: string; shade: number; direction?: string; fields?: { text: string; warning?: boolean }[] }[] = [
|
||||
{ text: `Delta ${formatDelta(nightscout.delta)} Trend `, shade: 180, direction: nightscout.direction },
|
||||
{
|
||||
text: `IOB ${nightscout.iob === null ? "--" : nightscout.iob.toFixed(2)} COB ${nightscout.cob === null ? "--" : formatWholeNumber(nightscout.cob)} Updated ${formatTimestamp(latest.timestampMs)}`,
|
||||
shade: 160,
|
||||
},
|
||||
{
|
||||
text: `CAGE ${formatAgeShortFromTimestamp(nightscout.cageTimestampMs, nowMs)} Loop ${nightscout.openapsStatusShort}`,
|
||||
shade: 160,
|
||||
text: "", shade: 160,
|
||||
fields: [
|
||||
{ text: `CAGE ${formatAgeShortFromTimestamp(nightscout.cageTimestampMs, nowMs)}`, warning: alerts.cannula },
|
||||
{ text: `Loop ${formatAgeShortFromTimestamp(nightscout.loopTimestampMs, nowMs)}`, warning: alerts.loop },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: "", shade: 150,
|
||||
fields: [
|
||||
{ text: "Pump" },
|
||||
{ text: nightscout.reservoirUnits === null ? "--U" : `${Math.round(nightscout.reservoirUnits)}U`, warning: alerts.cartridge },
|
||||
{ text: nightscout.batteryVoltage === null ? "--V" : `${nightscout.batteryVoltage.toFixed(2)}V`, warning: alerts.battery },
|
||||
{ text: nightscout.pumpStatus || "--" },
|
||||
],
|
||||
},
|
||||
{ text: `Pump ${nightscout.pumpStatus || "--"}`, shade: 150 },
|
||||
];
|
||||
let statusY = graphTop - 8 - statusLines.length * step;
|
||||
for (const line of statusLines) {
|
||||
if (line.direction !== undefined) {
|
||||
if (line.fields) {
|
||||
let x = statusX;
|
||||
for (const field of line.fields) {
|
||||
const text = truncateText(font, field.text, Math.max(0, statusX + statusWidth - x));
|
||||
const textWidth = font.measureText(text);
|
||||
if (field.warning && textWidth > 0) image.fillRect(x - 2, statusY - 1, textWidth + 4, font.lineHeight + 2, 230);
|
||||
image.drawText(font, x, statusY, text, field.warning ? 0 : line.shade);
|
||||
x += textWidth + font.measureText(" ");
|
||||
if (x >= statusX + statusWidth) break;
|
||||
}
|
||||
} else if (line.direction !== undefined) {
|
||||
image.drawText(font, statusX, statusY, line.text, line.shade);
|
||||
drawDirectionIndicator(image, font, statusX + font.measureText(line.text), statusY, line.direction, line.shade);
|
||||
} else {
|
||||
@@ -390,6 +420,11 @@ export function nightscoutMenuItems(): MenuItem[] {
|
||||
openSettingsSubMenu(ctx, "Nightscout settings", [
|
||||
textSettingMenuItem(nightscoutSiteUrlSetting),
|
||||
textSettingMenuItem(nightscoutApiTokenSetting),
|
||||
textSettingMenuItem(nightscoutMaxCannulaAgeSetting),
|
||||
textSettingMenuItem(nightscoutCartridgeLowSetting),
|
||||
textSettingMenuItem(nightscoutBatteryLowSetting),
|
||||
textSettingMenuItem(nightscoutMaxLoopAgeSetting),
|
||||
toggleSettingMenuItem(nightscoutAlwaysShowInTopBarSetting),
|
||||
]);
|
||||
},
|
||||
},
|
||||
|
||||
@@ -36,7 +36,7 @@ import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../../gra
|
||||
import { prepareFrameDraws } from "../../graphics/glyph-wire";
|
||||
import { getDefaultSmallFont, getTerminalFontConfig } from "../../graphics/ui-fonts";
|
||||
import { truncateText } from "../../graphics/textwrap";
|
||||
import { TERMINAL_ICON_GLYPHS } from "../../graphics/icons";
|
||||
import { TERMINAL_ICON_GLYPHS, type IconActivity } from "../../graphics/icons";
|
||||
import * as frameTimings from "../../native/frame-timings";
|
||||
import { getActiveDisplay } from "../../native/active-display";
|
||||
import { GESTURE_DOUBLE_CLICK, type InputEvent } from "../../ui/gestures";
|
||||
@@ -285,7 +285,7 @@ const sessionRecency = new Map<string, number>();
|
||||
// continues, so 5s of slack keeps the indicator lit through the gaps.
|
||||
const sessionActivity = new Map<string, number>();
|
||||
const ACTIVITY_ACTIVE_MS = 5_000;
|
||||
// Alternation period of the hub's activity indicator.
|
||||
// Alternation period shared by hub rows and sidebar cursors.
|
||||
const HUB_ANIMATION_STEP_MS = 800;
|
||||
|
||||
function recencyKey(connectionId: string, socket: string): string {
|
||||
@@ -461,6 +461,7 @@ function openWindow(windowId: string, surfaceId: string, title: string, viewport
|
||||
if (pendingView) {
|
||||
pendingViews.delete(windowId);
|
||||
windows.set(windowId, createViewWindow(windowId, surfaceId, title, viewport, pendingView));
|
||||
updateHubAnimation();
|
||||
renderHubWindows();
|
||||
return;
|
||||
}
|
||||
@@ -490,6 +491,7 @@ function openWindow(windowId: string, surfaceId: string, title: string, viewport
|
||||
if (!controlsInitialized) {
|
||||
syncControlsFromSettings();
|
||||
}
|
||||
updateHubAnimation();
|
||||
}
|
||||
|
||||
function closeWindow(windowId: string): void {
|
||||
@@ -510,6 +512,8 @@ function closeWindow(windowId: string): void {
|
||||
endAddConnection(window);
|
||||
}
|
||||
windows.delete(windowId);
|
||||
windowIconActivity.delete(windowId);
|
||||
updateHubAnimation();
|
||||
// Auto-reconnect only runs while at least one terminal window is open.
|
||||
if (windows.size === 0) {
|
||||
for (const control of controls.values()) {
|
||||
@@ -720,42 +724,47 @@ function renderHubWindows(): void {
|
||||
}
|
||||
}
|
||||
|
||||
// Hub activity animation: while a foregrounded hub lists at least one active
|
||||
// session, a timer re-renders it so the per-row indicator alternates. The
|
||||
// timer stops itself once every session's activity ages out (its final tick
|
||||
// renders the rows indicator-free) or the hub leaves the foreground.
|
||||
// One animation clock for foreground hub rows and every terminal sidebar icon.
|
||||
// Keep ticking while the sidebar can show activity, even with the hub closed.
|
||||
let hubAnimationPhase = 0;
|
||||
let hubAnimationTimer: ReturnType<typeof setInterval> | null = null;
|
||||
const windowIconActivity = new Map<string, IconActivity>();
|
||||
|
||||
function isSessionActive(connectionId: string, socket: string): boolean {
|
||||
const at = sessionActivity.get(recencyKey(connectionId, socket));
|
||||
return at !== undefined && Date.now() - at < ACTIVITY_ACTIVE_MS;
|
||||
}
|
||||
|
||||
function hubAnimationShouldRun(): boolean {
|
||||
if (!screenOn) return false;
|
||||
let hubVisible = false;
|
||||
for (const window of windows.values()) {
|
||||
if (window.kind === "hub" && window.foreground) hubVisible = true;
|
||||
}
|
||||
if (!hubVisible) return false;
|
||||
function isWindowSessionActive(window: TerminalWindow): boolean {
|
||||
if (window.kind === "view") return isSessionActive(window.connectionId, window.socket);
|
||||
const now = Date.now();
|
||||
for (const at of sessionActivity.values()) {
|
||||
if (now - at < ACTIVITY_ACTIVE_MS) return true;
|
||||
}
|
||||
return false;
|
||||
return [...sessionActivity.values()].some((at) => now - at < ACTIVITY_ACTIVE_MS);
|
||||
}
|
||||
|
||||
/** Start or stop the animation timer to match the current state. */
|
||||
function hubAnimationShouldRun(): boolean {
|
||||
return screenOn && [...windows.values()].some(isWindowSessionActive);
|
||||
}
|
||||
|
||||
function syncWindowIconActivity(): void {
|
||||
for (const window of windows.values()) {
|
||||
const activity: IconActivity = screenOn && isWindowSessionActive(window)
|
||||
? (hubAnimationPhase === 0 ? "on" : "off") : "idle";
|
||||
if ((windowIconActivity.get(window.windowId) ?? "idle") === activity) continue;
|
||||
windowIconActivity.set(window.windowId, activity);
|
||||
post({ type: "set-icon-activity", windowId: window.windowId, activity });
|
||||
}
|
||||
}
|
||||
|
||||
/** Start or stop animation and publish changed icons, including expiry/wake. */
|
||||
function updateHubAnimation(): void {
|
||||
if (hubAnimationShouldRun()) {
|
||||
const shouldRun = hubAnimationShouldRun();
|
||||
if (shouldRun && !hubAnimationTimer) hubAnimationPhase = 0;
|
||||
syncWindowIconActivity();
|
||||
if (shouldRun) {
|
||||
if (hubAnimationTimer) return;
|
||||
hubAnimationTimer = setInterval(() => {
|
||||
hubAnimationPhase = (hubAnimationPhase + 1) % 2;
|
||||
if (!hubAnimationShouldRun() && hubAnimationTimer) {
|
||||
clearInterval(hubAnimationTimer);
|
||||
hubAnimationTimer = null;
|
||||
}
|
||||
updateHubAnimation();
|
||||
// Render even on the stopping tick, to clear expired indicators.
|
||||
renderHubWindows();
|
||||
}, HUB_ANIMATION_STEP_MS);
|
||||
|
||||
+20
-7
@@ -89,9 +89,11 @@ export const ICON_SVGS = {
|
||||
} as const;
|
||||
|
||||
export type IconName = keyof typeof ICON_SVGS;
|
||||
/** Idle prompt, or the visible/hidden phases of an activity cursor. */
|
||||
export type IconActivity = "idle" | "on" | "off";
|
||||
|
||||
// The "_" element of the terminal icon, swapped out for a session glyph in
|
||||
// renderIconWithGlyph.
|
||||
// Prompt and session-marker elements replaced by renderIconWithGlyph.
|
||||
const TERMINAL_PROMPT = '<path d="m7 11 2-2-2-2"/>';
|
||||
const TERMINAL_UNDERSCORE = '<path d="M11 13h4"/>';
|
||||
|
||||
/**
|
||||
@@ -157,12 +159,23 @@ export function renderSvgIcon(cacheName: string, svg: string, size: number): Gra
|
||||
/**
|
||||
* Render an icon with a glyph character substituted in — currently only the
|
||||
* terminal icon, whose "_" becomes the glyph (">3" instead of ">_"). Falls
|
||||
* back to the plain icon for other names or unsupported characters.
|
||||
* back to the plain marker for unsupported characters. Active terminal icons
|
||||
* replace the prompt with a blinking cursor, leaving the marker in place.
|
||||
*/
|
||||
export function renderIconWithGlyph(name: IconName, glyph: string, size: number): GrayImage | null {
|
||||
const shape = name === "terminal" ? TERMINAL_GLYPH_SHAPES[glyph] : undefined;
|
||||
if (!shape) return renderIcon(name, size);
|
||||
return renderSvgCached(`${name}[${glyph}]`, ICON_SVGS.terminal.replace(TERMINAL_UNDERSCORE, shape), size);
|
||||
export function renderIconWithGlyph(name: IconName, glyph: string, size: number, activity: IconActivity = "idle"): GrayImage | null {
|
||||
if (name !== "terminal") return renderIcon(name, size);
|
||||
const shape = TERMINAL_GLYPH_SHAPES[glyph];
|
||||
if (!shape && activity === "idle") return renderIcon(name, size);
|
||||
let svg: string = ICON_SVGS.terminal;
|
||||
if (shape) svg = svg.replace(TERMINAL_UNDERSCORE, shape);
|
||||
if (activity !== "idle") {
|
||||
// IconRenderer strokes all elements at width 2; the narrow rectangle
|
||||
// therefore becomes a solid cursor without needing per-element fills.
|
||||
svg = svg.replace(TERMINAL_PROMPT, activity === "on"
|
||||
? '<rect x="7.5" y="8" width="1" height="6"/>'
|
||||
: "");
|
||||
}
|
||||
return renderSvgCached(`${name}[${shape ? glyph : ""}]:${activity}`, svg, size);
|
||||
}
|
||||
|
||||
function renderSvgCached(cacheName: string, svg: string, size: number): GrayImage | null {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { loadNightscoutSettings, nightscoutApiTokenSetting, nightscoutSiteUrlSetting } from "../ui/dashboard-settings";
|
||||
import { nightscoutApiTokenSetting, nightscoutSiteUrlSetting } from "../ui/dashboard-settings";
|
||||
import { fetchWithUserAgent } from "../util/http";
|
||||
|
||||
export type NightscoutPoint = {
|
||||
@@ -33,6 +33,10 @@ export type NightscoutState = {
|
||||
iob: number | null;
|
||||
cob: number | null;
|
||||
cageTimestampMs: number | null;
|
||||
reservoirUnits: number | null;
|
||||
batteryVoltage: number | null;
|
||||
loopTimestampMs: number | null;
|
||||
/** Pump communication age and operating state; measurements are separate. */
|
||||
pumpStatus: string;
|
||||
openapsStatusShort: string;
|
||||
carbs: NightscoutCarbEvent[];
|
||||
@@ -121,6 +125,9 @@ const DEFAULT_NIGHTSCOUT_STATE: NightscoutState = {
|
||||
iob: null,
|
||||
cob: null,
|
||||
cageTimestampMs: null,
|
||||
reservoirUnits: null,
|
||||
batteryVoltage: null,
|
||||
loopTimestampMs: null,
|
||||
pumpStatus: "",
|
||||
openapsStatusShort: "--",
|
||||
carbs: [],
|
||||
@@ -259,6 +266,9 @@ export class NightscoutBridge {
|
||||
iob: Number.isFinite(iob) ? iob : null,
|
||||
cob,
|
||||
cageTimestampMs: latestSiteChange > 0 ? latestSiteChange : null,
|
||||
reservoirUnits: firstFiniteNumber(latestDeviceStatus?.pump?.reservoir),
|
||||
batteryVoltage: firstFiniteNumber(latestDeviceStatus?.pump?.battery?.voltage),
|
||||
loopTimestampMs: loopTimestampMs > 0 ? loopTimestampMs : null,
|
||||
pumpStatus,
|
||||
openapsStatusShort: loopTimestampMs > 0 ? formatElapsedShort(nowMs - loopTimestampMs) : "--",
|
||||
carbs: parsedTreatments.carbs,
|
||||
@@ -359,6 +369,8 @@ function parseTimestampMs(value: unknown): number {
|
||||
|
||||
function firstFiniteNumber(...values: unknown[]): number | null {
|
||||
for (const value of values) {
|
||||
if (typeof value !== "number" && typeof value !== "string") continue;
|
||||
if (typeof value === "string" && !value.trim()) continue;
|
||||
const numeric = Number(value);
|
||||
if (Number.isFinite(numeric)) {
|
||||
return numeric;
|
||||
@@ -371,8 +383,6 @@ function formatPumpStatus(status: NightscoutDeviceStatusResponse | undefined, no
|
||||
if (!status?.pump) {
|
||||
return "--";
|
||||
}
|
||||
const reservoir = firstFiniteNumber(status.pump.reservoir);
|
||||
const voltage = firstFiniteNumber(status.pump.battery?.voltage);
|
||||
const commTimestampMs = Math.max(
|
||||
parseTimestampMs(status.pump.status?.timestamp),
|
||||
parseTimestampMs(status.pump.clock),
|
||||
@@ -380,12 +390,6 @@ function formatPumpStatus(status: NightscoutDeviceStatusResponse | undefined, no
|
||||
);
|
||||
const stateLabel = summarizePumpState(status);
|
||||
const parts: string[] = [];
|
||||
if (reservoir !== null) {
|
||||
parts.push(`${Math.round(reservoir)}U`);
|
||||
}
|
||||
if (voltage !== null) {
|
||||
parts.push(`${voltage.toFixed(2)}v`);
|
||||
}
|
||||
if (commTimestampMs > 0) {
|
||||
parts.push(`${formatElapsedShort(nowMs - commTimestampMs)} ago`);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { normalizeNightscoutThreshold, type NightscoutThresholds } from "../apps/nightscout/nightscout-alerts";
|
||||
import { GESTURE_DOUBLE_CLICK, InputEvent } from "./gestures";
|
||||
import {
|
||||
getBooleanSetting,
|
||||
@@ -755,6 +756,48 @@ export const nightscoutApiTokenSetting = new ConfigSettingString({
|
||||
description: "Access token for the Nightscout site's API.",
|
||||
});
|
||||
|
||||
function nightscoutThresholdSetting(id: string, label: string, unit: string, description: string): ConfigSettingString {
|
||||
return new ConfigSettingString({
|
||||
id: `nightscout-${id}`,
|
||||
label,
|
||||
storageKey: `integrations.nightscout.${id}`,
|
||||
defaultValue: "0",
|
||||
editorTitle: `${label} (${unit}; 0 = off)`,
|
||||
normalize: normalizeNightscoutThreshold,
|
||||
formatValue: (value) => Number(value) > 0 ? `${value} ${unit}` : "Off",
|
||||
description: `${description} Enter 0 to disable.`,
|
||||
});
|
||||
}
|
||||
|
||||
export const nightscoutMaxCannulaAgeSetting = nightscoutThresholdSetting(
|
||||
"max-cannula-age-hours", "Max cannula age", "h", "Warn when time since the last site change exceeds this many hours.",
|
||||
);
|
||||
export const nightscoutCartridgeLowSetting = nightscoutThresholdSetting(
|
||||
"cartridge-low-units", "Cartridge low threshold", "U", "Warn when the pump reservoir falls below this many units.",
|
||||
);
|
||||
export const nightscoutBatteryLowSetting = nightscoutThresholdSetting(
|
||||
"battery-low-voltage", "Battery voltage threshold", "V", "Warn when pump battery voltage falls below this value.",
|
||||
);
|
||||
export const nightscoutMaxLoopAgeSetting = nightscoutThresholdSetting(
|
||||
"max-loop-age-minutes", "Max time since last loop", "min", "Warn when time since the last loop exceeds this many minutes.",
|
||||
);
|
||||
export const nightscoutAlwaysShowInTopBarSetting = new ConfigSettingBoolean({
|
||||
id: "nightscout-always-show-in-top-bar",
|
||||
label: "Always show in top bar",
|
||||
storageKey: "integrations.nightscout.alwaysShowInTopBar",
|
||||
defaultValue: false,
|
||||
description: "Keep the Nightscout glucose graph and warnings in the top bar even when all Nightscout windows are closed.",
|
||||
});
|
||||
|
||||
export function loadNightscoutThresholds(): NightscoutThresholds {
|
||||
return {
|
||||
maxCannulaAgeHours: Number(nightscoutMaxCannulaAgeSetting.get()),
|
||||
cartridgeLowUnits: Number(nightscoutCartridgeLowSetting.get()),
|
||||
batteryLowVoltage: Number(nightscoutBatteryLowSetting.get()),
|
||||
maxLoopAgeMinutes: Number(nightscoutMaxLoopAgeSetting.get()),
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Navigate app: saved and recent destinations.
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import { BATTERY_ICON_WIDTH, drawBattery } from "../../graphics/battery";
|
||||
import { readActiveNotificationIcons } from "../../native/notification-icons";
|
||||
import { readPhoneBatteryState } from "../../native/phone-battery";
|
||||
import { noteStaleDataUsed, renderPassAllowsStaleData } from "../../util/render-freshness";
|
||||
import { renderIcon, renderIconWithGlyph, type IconName } from "../../graphics/icons";
|
||||
import { renderIcon, renderIconWithGlyph, type IconActivity, type IconName } from "../../graphics/icons";
|
||||
import { batteryDisplayModeSetting, timeFormatSetting } from "../dashboard-settings";
|
||||
import { Layer } from "../layers";
|
||||
import { scrollToKeepSelectionVisible } from "../menu";
|
||||
@@ -144,9 +144,9 @@ function invertedIcon(icon: GrayImage): GrayImage {
|
||||
}
|
||||
|
||||
/** Window icon rendered from an SVG (Lucide), rendered once per size and cached. */
|
||||
export function makeSvgWindowIcon(name: IconName, glyph?: string): ShellChromeWindow["drawIcon"] {
|
||||
export function makeSvgWindowIcon(name: IconName, glyph?: string, activity?: () => IconActivity): ShellChromeWindow["drawIcon"] {
|
||||
return (image, x, y, size, inverted) => {
|
||||
const icon = glyph ? renderIconWithGlyph(name, glyph, size) : renderIcon(name, size);
|
||||
const icon = glyph || activity ? renderIconWithGlyph(name, glyph ?? "", size, activity?.() ?? "idle") : renderIcon(name, size);
|
||||
if (!icon) return;
|
||||
const dx = x + Math.max(0, ((size - icon.width) / 2) | 0);
|
||||
const dy = y + Math.max(0, ((size - icon.height) / 2) | 0);
|
||||
@@ -155,8 +155,8 @@ export function makeSvgWindowIcon(name: IconName, glyph?: string): ShellChromeWi
|
||||
}
|
||||
|
||||
/** SVG icon when a name is given, else the letter placeholder. */
|
||||
export function windowIcon(icon: IconName | undefined, letter: string, glyph?: string): ShellChromeWindow["drawIcon"] {
|
||||
return icon ? makeSvgWindowIcon(icon, glyph) : makeLetterWindowIcon(letter);
|
||||
export function windowIcon(icon: IconName | undefined, letter: string, glyph?: string, activity?: () => IconActivity): ShellChromeWindow["drawIcon"] {
|
||||
return icon ? makeSvgWindowIcon(icon, glyph, activity) : makeLetterWindowIcon(letter);
|
||||
}
|
||||
|
||||
/** Window icon backed by an arbitrary cached grayscale image renderer. */
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { windowIcon } from "./chrome-layer";
|
||||
import { type IconName } from "../../graphics/icons";
|
||||
import { type IconActivity, type IconName } from "../../graphics/icons";
|
||||
import { toolRegistry, type ToolResult, type ToolSpec } from "../../assistant/tool-registry";
|
||||
import { appViewportSize, type WindowHeightMode } from "./geometry";
|
||||
import * as frameTimings from "../../native/frame-timings";
|
||||
@@ -62,6 +62,8 @@ export type WorkerAppReply =
|
||||
}
|
||||
| { type: "set-title"; windowId: string; title: string }
|
||||
| { type: "set-attention"; windowId: string; attention: boolean }
|
||||
/** App-driven animation phase for sidebar icons that support an activity cursor. */
|
||||
| { type: "set-icon-activity"; windowId: string; activity: IconActivity }
|
||||
| {
|
||||
/** Open the shell's voice dialog aimed at this window (a menu pick). */
|
||||
type: "start-voice-input";
|
||||
@@ -194,6 +196,7 @@ const TOOL_CALL_HOST_TIMEOUT_MS = 15_000;
|
||||
|
||||
export class WorkerAppHost {
|
||||
private readonly openWindows = new Set<string>();
|
||||
private readonly windowIconActivity = new Map<string, IconActivity>();
|
||||
/** Per-window gesture bindings, as last reported (see set-window-gestures). */
|
||||
private readonly windowGestures = new Map<string, { hasAppMenu: boolean; claimsLongPress: boolean }>();
|
||||
private readonly pendingToolCalls = new Map<string, PendingToolCall>();
|
||||
@@ -270,6 +273,12 @@ export class WorkerAppHost {
|
||||
shell.openSystemMenu(message.windowId);
|
||||
}
|
||||
break;
|
||||
case "set-icon-activity":
|
||||
if (this.openWindows.has(message.windowId) && this.windowIconActivity.get(message.windowId) !== message.activity) {
|
||||
this.windowIconActivity.set(message.windowId, message.activity);
|
||||
this.options.requestShellRender();
|
||||
}
|
||||
break;
|
||||
case "set-window-gestures":
|
||||
this.windowGestures.set(message.windowId, {
|
||||
hasAppMenu: message.hasAppMenu,
|
||||
@@ -358,13 +367,14 @@ export class WorkerAppHost {
|
||||
close: () => {
|
||||
this.openWindows.delete(spec.windowId);
|
||||
this.windowGestures.delete(spec.windowId);
|
||||
this.windowIconActivity.delete(spec.windowId);
|
||||
// Withdraw this window's tools and fail any in-flight calls to it.
|
||||
toolRegistry.removeAppTools(spec.windowId);
|
||||
this.failPendingToolCallsFor(spec.windowId);
|
||||
this.post({ type: "close-window", windowId: spec.windowId });
|
||||
this.options.removeSurface(surfaceId);
|
||||
},
|
||||
drawIcon: windowIcon(spec.icon, spec.iconLetter, spec.iconGlyph),
|
||||
drawIcon: windowIcon(spec.icon, spec.iconLetter, spec.iconGlyph, () => this.windowIconActivity.get(spec.windowId) ?? "idle"),
|
||||
handleInput: (event, frameId) => {
|
||||
frameTimings.logFrame(frameId, `input posted to the ${this.options.appId} worker`);
|
||||
this.post({
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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
@@ -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"
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user