Merge remote-tracking branch 'origin/main' into g2-case-battery

# Conflicts:
#	native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionCore.kt
This commit is contained in:
Om Alve committed 2026-11-02 12:02:53 +05:30
commit 046454e8c0
67 files changed
+11373 -155

No files matched your search

+678
View File
@@ -407,3 +407,681 @@ Button.-primary {
.ns-dark .transcript-play {
color: #7da7f5;
}
/*
* The cover screen (phone-ui/cover-glance.xml): what the phone shows while the
* Fold is shut. It reuses .home-card and .home-section-title wholesale — the
* cover screen is the same product, laid out for a glance, not a second visual
* language — and adds only what a one-screenful layout needs.
*/
.cover-glance {
padding: 12 12 16 12;
}
.cover-glance-card {
vertical-align: center;
margin-top: 0;
}
.cover-glance-app {
font-size: 20;
font-weight: bold;
color: #222222;
}
.cover-glance-text {
font-size: 15;
color: #444444;
margin-top: 6;
}
.cover-glance-hint {
font-size: 12;
color: #888888;
text-align: center;
margin-top: 12;
}
.ns-dark .cover-glance-app {
color: #f0f0f0;
}
.ns-dark .cover-glance-text {
color: #cfcfcf;
}
.ns-dark .cover-glance-hint {
color: #909090;
}
/*
* Ghost's companion (phone-ui/ghost-companion.xml). The pilot's own palette is
* deliberately NOT ported: it was a black OLED mockup with phosphor-green
* accents standing in for a whole OS shell, and this screen lives inside the
* Faceclaw app, whose light/dark surfaces every other page already uses. What
* carries over is the structure — header, tab bar, one pane, docked compose —
* and the monospace treatment of the raw views, which is load-bearing.
*/
.ghost-app {
background-color: #ffffff;
}
/* The one header row every companion view shares — phone-ui/exocortex-header
* .xml. One line, and it replaces BOTH the app-switch bar and the per-app
* wordmark/status header that used to stack above the content. */
.exocortex-header {
padding: 5 14;
background-color: #f4f4f4;
border-bottom-width: 1;
border-bottom-color: #dddddd;
}
/* The tap target back to the hub, so it is coloured like the link it is. */
.exocortex-header-home {
font-family: monospace;
font-size: 12;
letter-spacing: 0.12;
color: #3b6fd6;
}
.exocortex-header-sep {
font-size: 12;
color: #aaaaaa;
margin-left: 6;
margin-right: 6;
}
/* The star column: the app name takes the slack and truncates before it
* pushes the connection status off the row. */
.exocortex-header-app {
font-size: 13;
font-weight: bold;
color: #222222;
}
.exocortex-header-status {
font-size: 12;
color: #666666;
}
/* The two segments that came down from the ActionBar when main-page lost it
* (round 3). Both are collapsed-width by default in the grid, so they cost
* nothing horizontally until they are drawn — and nothing vertically ever,
* since the row was already there. The padding is the tap target: these are
* Labels, so without it the hit box is the glyph. */
/* The emoji brings its own yellow. Collapsed unless a warning is live. */
.exocortex-header-warning {
font-size: 14;
padding: 2 4;
margin-left: 6;
}
/* Coloured like the link it is, matching the "Exocortex" tap target at the
* other end of the row. */
.exocortex-header-settings {
font-size: 15;
color: #3b6fd6;
padding: 2 4;
margin-left: 8;
}
.ghost-tab-bar {
padding: 2 8 3 8;
}
/* SHORTER, still four real buttons (Chris, round 2: "shrink the four pane-nav
* buttons - still functional, just shorter"). An Android Button carries a
* 48dp minimum height from the platform theme, so the explicit height is what
* actually shrinks it; padding alone would not. */
.ghost-tab {
font-size: 12;
height: 30;
padding: 3 0;
margin: 0 2;
border-radius: 6;
background-color: #e2e2e2;
color: #333333;
}
.ghost-tab-active {
background-color: #424242;
color: #ffffff;
}
/* The explicit background is LOAD-BEARING, not decoration. Rich view used to
* survive the live-theme-switch bug (the app reads the system theme once at
* launch and never re-subscribes, so a mid-session switch leaves foreground
* and background disagreeing — Terminal and Doc go white-on-white) purely
* because every turn was a card carrying its own background colour. Removing
* those cards to fix the turn-grouping bug would have removed that immunity
* with them. Painting the pane body instead keeps background and text driven
* by the SAME .ns-dark state, at the container rather than per row. */
.ghost-pane-body {
padding: 8 16 16 16;
background-color: #ffffff;
}
.ghost-empty {
font-size: 14;
color: #666666;
padding: 24 0;
text-align: center;
}
/* Rich view renders one logical TURN as a continuous block: consecutive prose
* runs together at one weight, and tool activity collapses to small muted
* marker lines BETWEEN the prose. Deliberately NOT a card per row — round 4
* gave every transcript entry the same bordered box with a bold 16pt
* headline, so a one-line `Read foo.ts` marker outweighed the reply it sat
* inside. Same convention cc-web's own rich view already proves
* (apps/claude-code-web/src/public/style.css, `.rich-tool-lines`): "muted so
* prose stays primary." */
.ghost-seg {
padding-left: 2;
padding-right: 2;
}
/* The separator lives at the END of a logical turn, not between its own
* segments — that is what makes one reply read as one block. */
.ghost-seg-end {
padding-bottom: 14;
margin-bottom: 14;
border-bottom-width: 1;
border-bottom-color: #e2e2e2;
}
/* The segment the LENS has under its cursor. The phone and the glasses are
* two views of one session, so the phone says where the wearer is rather than
* keeping a cursor of its own. A left rule rather than a box, so marking it
* cannot reintroduce the per-segment card this pass removed. */
.ghost-seg-current {
border-left-width: 3;
border-left-color: #3b6fd6;
padding-left: 9;
}
.ghost-seg-who {
font-size: 11;
text-transform: uppercase;
letter-spacing: 0.08;
color: #666666;
margin-bottom: 3;
}
/* Prose is the content. One weight, no headline split — splitHeadlineBody()
* is the glasses digest's convention and does not belong on a full reply. */
.ghost-seg-prose {
font-size: 16;
color: #222222;
margin-top: 2;
margin-bottom: 2;
}
/* Tool markers: small, monospace, muted, and almost no vertical space. */
.ghost-seg-tool {
font-family: monospace;
font-size: 11;
color: #8a8a8a;
margin-top: 3;
margin-bottom: 3;
}
/* Surfaced AskUserQuestion turns — a side channel, tinted so they do not read
* as something Ghost said mid-sentence. Must stay AFTER .ghost-seg-prose:
* both classes are applied to the same Label. */
.ghost-seg-question {
border-left-width: 3;
border-left-color: #a371f7;
padding-left: 10;
}
.ghost-seg-answer {
border-left-width: 3;
border-left-color: #3fb950;
padding-left: 10;
}
/* Not a live terminal — the undigested feed. Monospace because the alignment
* is the point: this pane exists for the moment Rich view looks wrong. */
.ghost-terminal {
font-family: monospace;
font-size: 12;
color: #222222;
padding: 12 16;
}
.ghost-doc-bar {
padding: 10 16;
background-color: #f4f4f4;
border-bottom-width: 1;
border-bottom-color: #dddddd;
}
.ghost-doc-path {
font-size: 13;
color: #666666;
}
.ghost-doc-close {
font-size: 16;
color: #666666;
padding: 0 8;
background-color: transparent;
}
/* The container the rendered markdown blocks sit in. `color` and `font-size`
* are inheritable in NativeScript, so every .doc-md Label below picks its body
* text up from here and only overrides what it actually changes. The explicit
* background is the same load-bearing one .ghost-pane-body carries: without it
* this pane goes white-on-white after a live theme switch. */
.ghost-doc-body {
font-size: 15;
color: #222222;
background-color: #ffffff;
padding: 14 16 24 16;
}
/* ── Doc viewer: rendered markdown (2026-09-03) ─────────────────────────────
* One Label per parsed block (phone-ui/markdown-render.ts). Block-level
* treatment lives here; the inline runs (bold / italic / code / link) are
* spans built in ghost-companion-view-model.ts, because a Span's weight and
* family cannot be reached from CSS. */
.doc-md {
margin-bottom: 8;
}
.doc-md-h1 {
font-size: 21;
margin-top: 14;
margin-bottom: 6;
}
.doc-md-h2 {
font-size: 18;
margin-top: 14;
margin-bottom: 6;
}
.doc-md-h3 {
font-size: 16;
margin-top: 12;
margin-bottom: 4;
}
.doc-md-h4 {
font-size: 15;
margin-top: 12;
margin-bottom: 4;
}
.doc-md-li {
margin-bottom: 4;
}
/* Nesting depth, clamped at three by the parser so a deep list cannot indent
* itself off the side of a phone. */
.doc-md-li-d0 {
margin-left: 4;
}
.doc-md-li-d1 {
margin-left: 20;
}
.doc-md-li-d2 {
margin-left: 36;
}
.doc-md-li-d3 {
margin-left: 52;
}
.doc-md-code {
font-family: monospace;
font-size: 13;
color: #333333;
background-color: #f2f2f2;
border-radius: 6;
padding: 8 10;
}
.doc-md-quote {
border-left-width: 3;
border-left-color: #c8c8c8;
padding-left: 10;
color: #555555;
}
/* An empty Label doing the job of an <hr>: the block carries no text, so its
* height and colour are the whole rule. */
.doc-md-rule {
height: 1;
margin: 12 0;
background-color: #dddddd;
}
.ghost-setting {
padding: 10 12;
margin-bottom: 8;
border-radius: 10;
border-width: 1;
border-color: #dddddd;
background-color: #f4f4f4;
}
.ghost-setting-label {
font-size: 15;
font-weight: bold;
color: #222222;
}
.ghost-setting-desc {
font-size: 12;
color: #666666;
margin-top: 2;
}
.ghost-setting-field {
font-size: 14;
color: #222222;
background-color: #ffffff;
margin-top: 6;
}
/* The one thing this screen does that the lens cannot, so it is docked rather
* than reached for. */
.ghost-compose {
padding: 8 12 12 12;
border-top-width: 1;
border-top-color: #dddddd;
background-color: #f4f4f4;
}
/* 48, not the 88 it was. CHECKED, not assumed: NativeScript core has a
* minHeightProperty but NO max-height, so letting this auto-size would grow
* the docked bar without a ceiling as you type and push the panes off screen.
* A fixed height scrolls internally instead, which is the right behaviour for
* a bar docked under the content it is about. */
.ghost-compose-input {
height: 48;
font-size: 15;
color: #222222;
background-color: #ffffff;
border-radius: 8;
padding: 8;
}
.ghost-send {
margin-left: 8;
}
.ghost-compose-status {
font-size: 12;
color: #a04040;
margin-top: 4;
}
.ns-dark .ghost-app {
background-color: #1c1c1c;
}
.ns-dark .exocortex-header,
.ns-dark .ghost-doc-bar,
.ns-dark .ghost-compose {
border-bottom-color: #4a4a4a;
border-top-color: #4a4a4a;
}
.ns-dark .exocortex-header,
.ns-dark .ghost-doc-bar,
.ns-dark .ghost-compose {
background-color: #2e2e2e;
}
.ns-dark .exocortex-header-app,
.ns-dark .ghost-seg-prose,
.ns-dark .ghost-terminal,
.ns-dark .ghost-doc-body,
.ns-dark .ghost-setting-label {
color: #f0f0f0;
}
.ns-dark .exocortex-header-status,
.ns-dark .ghost-empty,
.ns-dark .ghost-seg-who,
.ns-dark .ghost-doc-path,
.ns-dark .ghost-setting-desc {
color: #a0a0a0;
}
.ns-dark .exocortex-header-sep {
color: #6a6a6a;
}
.ns-dark .ghost-seg-tool {
color: #909090;
}
/* See .ghost-pane-body's own comment: this pairing is what keeps Rich view
* readable now that it no longer boxes every segment. */
.ns-dark .ghost-pane-body {
background-color: #1e1e1e;
}
.ns-dark .ghost-seg-end {
border-bottom-color: #3d3d3d;
}
.ns-dark .exocortex-header-home,
.ns-dark .exocortex-header-settings {
color: #8ab0ff;
}
.ns-dark .ghost-setting {
background-color: #2e2e2e;
border-color: #4a4a4a;
}
.ns-dark .ghost-seg-current {
border-left-color: #8ab0ff;
}
.ns-dark .ghost-setting-field,
.ns-dark .ghost-compose-input {
color: #f0f0f0;
background-color: #1c1c1c;
}
.ns-dark .ghost-tab {
background-color: #3a3a3a;
color: #e0e0e0;
}
.ns-dark .ghost-tab-active {
background-color: #8ab0ff;
color: #101010;
}
.ns-dark .ghost-compose-status {
color: #ff9a8a;
}
/* Exocortex's own phone settings screens (Settings, Notification sources,
* Apps on the glasses). Card rows rather than the flat `.settings-row` used
* by the mirror page's controls: these are a list you read down, and a
* comfortable thumb target matters more here than density. */
.exo-row {
background-color: #f4f4f4;
border-color: #dddddd;
border-width: 1;
border-radius: 10;
padding: 12 14;
margin-bottom: 8;
}
.settings-value {
font-size: 14;
color: #3b6fd6;
margin-left: 12;
}
.app-order-button {
font-size: 18;
width: 40;
padding: 0;
margin: 0 0 0 4;
background-color: transparent;
color: #3b6fd6;
}
.ns-dark .exo-row {
background-color: #2e2e2e;
border-color: #4a4a4a;
}
.ns-dark .settings-value,
.ns-dark .app-order-button {
color: #8ab0ff;
}
/* Doc viewer's rendered markdown, dark. Only what actually differs: the body
* text colour already comes from .ns-dark .ghost-doc-body above. */
.ns-dark .ghost-doc-body {
background-color: #1c1c1c;
}
.ns-dark .doc-md-code {
color: #d8d8d8;
background-color: #262626;
}
.ns-dark .doc-md-quote {
border-left-color: #4a4a4a;
color: #b0b0b0;
}
.ns-dark .doc-md-rule {
background-color: #3a3a3a;
}
/* The app list's own container paints its own background (2026-09-03). The
* real cause of "the ghost app rendered on the app grid's background" was the
* broken visibility binding fixed in main-page.xml, not a transparent view —
* but the two bodies share one grid cell, so whichever is up must own its
* backdrop rather than depending on the other being gone. Belt as well as
* braces: the same class of bug (a view not painting its own background) is
* what the live-theme-switch failure was made of too. */
.exocortex-home-body {
background-color: #ffffff;
}
.ns-dark .exocortex-home-body {
background-color: #1c1c1c;
}
/* ------------------------------------------------------------------------
* HEALTH (phone-ui/health-page.xml)
*
* The chart is a grayscale bitmap produced by the same GrayImage renderer the
* glasses use, so it arrives as light-on-black whatever the phone theme is.
* Rather than fight that, the chart gets an explicit dark plate in BOTH
* themes - it reads as an instrument panel inset into the page, which is the
* one place a fixed dark surface is defensible in a light-themed app. The
* chrome around it (chips, stat rows) follows the theme normally.
*/
.health-chart {
background-color: #101010;
border-radius: 10;
margin: 10 0 6 0;
}
.health-chip {
font-size: 13;
color: #444444;
background-color: #f0f0f0;
border-color: #dddddd;
border-width: 1;
border-radius: 14;
padding: 6 12;
margin: 2 6 2 0;
}
.health-chip-on {
color: #ffffff;
background-color: #222222;
border-color: #222222;
}
.health-chip-scroll {
margin-top: 4;
}
.health-stat-row {
padding: 7 2;
}
.health-stat-label {
font-size: 13;
color: #666666;
}
.health-stat-value {
font-size: 15;
font-weight: bold;
color: #222222;
}
.health-stat-panel {
margin-left: 16;
}
.health-badge {
font-size: 11;
color: #8a6d00;
background-color: #fff3cd;
border-color: #ffe08a;
border-width: 1;
border-radius: 8;
padding: 3 8;
}
/* Not debug leftover - see health-page.xml's header. */
.health-layout-meta {
font-size: 11;
color: #999999;
margin-top: 14;
}
.ns-dark .health-chip {
color: #cccccc;
background-color: #2a2a2a;
border-color: #3a3a3a;
}
.ns-dark .health-chip-on {
color: #111111;
background-color: #e8e8e8;
border-color: #e8e8e8;
}
.ns-dark .health-stat-label {
color: #999999;
}
.ns-dark .health-stat-value {
color: #f0f0f0;
}
.ns-dark .health-badge {
color: #ffd97a;
background-color: #3a3320;
border-color: #5a4c1f;
}
.ns-dark .health-layout-meta {
color: #777777;
}
+2
View File
@@ -8,6 +8,7 @@ import t3codeApp from "./t3code";
import filesApp from "./files";
import musicApp from "./music";
import nightscoutApp from "./nightscout";
import healthApp from "./health";
import transcribeApp from "./transcribe";
import translateApp from "./translate";
import teleprompterApp from "./teleprompter";
@@ -44,6 +45,7 @@ export const ALL_APPS: readonly AppDefinition[] = [
filesApp,
musicApp,
nightscoutApp,
healthApp,
transcribeApp,
translateApp,
teleprompterApp,
+9
View File
@@ -8,6 +8,7 @@ import { BandwidthBenchmarkLayer } from "./bandwidth-benchmark";
import { LightSensorDemoLayer } from "./light-sensor-demo";
import { MicrophonesMonitorLayer } from "./microphones-monitor";
import { ResourceUsageLayer } from "./resource-usage";
import { RingStatusLayer } from "./ring-status";
import { LoadAppFromQrLayer, LoadAppFromUrlLayer } from "./load-app";
import { unicodeTestMenu } from "./unicode-test";
import { type AppContext } from "../app-definition";
@@ -66,6 +67,14 @@ function debugTestsMenu(openInputEvents: OpenPage, openMicrophones: OpenPage): M
ctx.stack.push(new LightSensorDemoLayer(DEVELOPER_WINDOW_ID, ctx.actions.requestRender));
},
},
{
label: "Ring status",
disabled: global.isIOS,
description: global.isIOS ? "Not available on iOS yet." : undefined,
onSelect: (ctx) => {
ctx.stack.push(new RingStatusLayer(DEVELOPER_WINDOW_ID, ctx.actions.requestRender));
},
},
{
label: "Microphones",
onSelect: openMicrophones,
+302
View File
@@ -0,0 +1,302 @@
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
import { GrayImage } from "../../graphics/image";
import { type InputEvent } from "../../ui/gestures";
import { Layer, type LayerContext } from "../../ui/layers";
import { shell } from "../../ui/shell/shell";
import { MenuLayer, type MenuItem } from "../../ui/menu";
import { ringConnectionModeSetting } from "../../ui/dashboard-settings";
import { loadDeviceAddresses } from "../../g2/device-addresses";
import {
getRingSessionStatus,
getRingSystemBluetoothState,
sendRingConfigCommand,
setGlassesRingLink,
type GlassesRingLinkAction,
type RingConfigAction,
type RingSessionStatus,
type RingSystemBluetoothState,
} from "../../native/ring-status";
const POLL_INTERVAL_MS = 1_000;
const LEFT_X = 16;
const VALUE_X = 130;
const BUTTON_GAP = 8;
type Row = { label: string; value: string; dim?: boolean };
type Button = "glasses" | "ring" | "mode";
const BUTTONS: readonly Button[] = ["glasses", "ring", "mode"];
/** Glasses-side commands (sid 0x80 pair manager). */
const GLASSES_ACTIONS: readonly { label: string; action: GlassesRingLinkAction }[] = [
{ label: "Disconnect ring", action: "disconnect" },
{ label: "Release ring", action: "release" },
{ label: "Unpair ring", action: "unpair" },
{ label: "Connect ring", action: "connect" },
];
/** Ring-side commands over the direct link, and the combined flows. */
const RING_ACTIONS: readonly { label: string; action: RingConfigAction }[] = [
{ label: "Bind to these glasses", action: "bind" },
{ label: "Unbind from glasses", action: "unbind" },
{ label: "Targets: these glasses", action: "targets-glasses" },
{ label: "Targets: clear (any)", action: "targets-clear" },
{ label: "Remove ring notify", action: "remove-ring" },
{ label: "Touch source on", action: "touch-on" },
{ label: "Touch source off", action: "touch-off" },
{ label: "Pair auth (phone role)", action: "pair-auth" },
];
const ACTION_MENU_LAYOUT = { x: "center" as const, y: 8, width: 300, dimUnderneath: 0.35 };
/**
* Where R1 ring input is coming from: the phone's own Bluetooth link to the
* ring, the direct-link session state, and when input last arrived directly
* versus relayed by the glasses. The ring sends gestures only to whichever
* link holds its glasses role, so the two "input" rows are the quickest way
* to see which path is live.
*
* Everything below is EXPERIMENTAL (see GlassesSessionRing.kt and
* notes/ring-link-control.md). "Glasses..." sends sid 0x80 ring-link commands
* to the glasses; "Ring..." sends binding commands to the ring over the
* direct link (Mode must be direct and the link up), including Bind/Unbind,
* which do both halves in the official app's order. Mode flips the Developer
* "Ring connection" setting (applies on the next glasses connection). In
* Direct mode the session does the setup on its own (see
* GlassesSessionRing.runRingGlassesSetup); the menus are for experiments.
*/
export class RingStatusLayer implements Layer {
private session: RingSessionStatus | null = null;
private system: RingSystemBluetoothState | null = null;
private timer: ReturnType<typeof setInterval> | null = null;
private selected = 0;
private notice = "";
constructor(
private readonly windowId: string,
private readonly requestRender: () => void,
) {
this.poll();
this.timer = setInterval(() => {
this.poll();
if (shell.isWindowVisible(this.windowId)) this.requestRender();
}, POLL_INTERVAL_MS);
}
onRemoved(): void {
if (this.timer !== null) {
clearInterval(this.timer);
this.timer = null;
}
}
private ringAddress(): string {
return this.session?.ringAddress || loadDeviceAddresses().ring;
}
private poll(): void {
this.session = getRingSessionStatus();
const address = this.ringAddress();
this.system = address ? getRingSystemBluetoothState(address) : null;
}
paint(ctx: LayerContext): GrayImage {
const font = getDefaultSmallFont();
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
const lineStep = font.lineHeight + 2;
const buttonHeight = font.lineHeight + 8;
const buttonTop = height - buttonHeight - 6;
image.drawText(font, 18, 10, "Ring status", 230);
let y = 10 + lineStep + 4;
const rows = this.rows();
if (this.notice) rows.push({ label: "", value: this.notice });
for (const row of rows) {
if (y + font.lineHeight > buttonTop - 4) break;
image.drawText(font, LEFT_X, y, row.label, row.dim ? 100 : 150);
image.drawText(font, VALUE_X, y, row.value, row.dim ? 120 : 220);
y += lineStep;
}
const buttonWidth = Math.floor((width - 2 * LEFT_X - BUTTON_GAP * (BUTTONS.length - 1)) / BUTTONS.length);
BUTTONS.forEach((button, index) => {
const x = LEFT_X + index * (buttonWidth + BUTTON_GAP);
const selected = index === this.selected;
if (selected) image.fillRoundedRect(x, buttonTop, buttonWidth, buttonHeight, 40, 4);
image.drawRoundedRect(x, buttonTop, buttonWidth, buttonHeight, selected ? 200 : 70, 4);
const text = buttonLabel(button);
image.drawText(font, x + Math.max(0, Math.floor((buttonWidth - font.measureText(text)) / 2)),
buttonTop + 4, text, selected ? 255 : 170);
});
return image;
}
private rows(): Row[] {
const s = this.session;
const address = this.ringAddress();
const rows: Row[] = [
{ label: "Ring", value: address || "none paired" },
{ label: "Phone BT", value: describeSystem(this.system) },
];
if (!s) {
rows.push({ label: "Session", value: "not connected to glasses", dim: true });
return rows;
}
if (!s.directEnabled) {
const pending = ringConnectionModeSetting.get() !== "glasses";
rows.push({ label: "Direct link", value: pending ? "on after glasses reconnect" : "off (only via glasses)", dim: true });
} else {
const state = s.directNotificationsReady ? "subscribed"
: s.directConnected ? "connected, subscribing"
: "not connected";
const since = s.directStateAgeMs >= 0 ? ` ${formatAge(s.directStateAgeMs)}` : "";
const battery = s.directBattery >= 0 ? `, ${s.directBattery}%` : "";
rows.push({
label: "Direct link",
value: `${state}${since}, role ${s.directRole}, ${s.directConnectCount} connects${battery}`,
});
}
if (s.directEnabled && s.directRole === "glasses") {
rows.push({
label: "Direct auth",
value: s.directGlassesAuth ? `${s.directGlassesAuth} ${formatAge(s.directGlassesAuthAgeMs)} ago` : "not sent yet",
});
}
if (s.directEnabled) {
const pull = s.healthWindowActive ? "pulling now (phone role)"
: s.lastHealthPull ? `${s.lastHealthPull} ${formatAge(s.lastHealthPullAgeMs)} ago`
: "no pull yet";
const held = s.heldHealthRecords > 0 ? `, ${s.heldHealthRecords} records unstored` : "";
rows.push({ label: "Health sync", value: pull + held });
}
rows.push({ label: "Direct input", value: describeInput(s.lastDirectInputAgeMs, s.lastDirectInput) });
if (s.directEnabled) {
rows.push({ label: "Direct pkts", value: describeAge(s.lastDirectNotifyAgeMs) });
if (s.lastDirectRaw) {
rows.push({ label: "Direct raw", value: `${formatAge(s.lastDirectRawAgeMs)} ago: ${s.lastDirectRaw}` });
}
}
rows.push({ label: "Glasses input", value: describeInput(s.lastGlassesInputAgeMs, s.lastGlassesInput) });
rows.push({
label: "Glasses ring",
value: (s.glassesRingBatteryAgeMs < 0 ? "battery not reported"
: `${s.glassesRingBattery >= 0 ? `battery ${s.glassesRingBattery}%` : "no battery"} ${formatAge(s.glassesRingBatteryAgeMs)} ago`)
+ (s.glassesRingMac ? `, mac ${s.glassesRingMac}` : ""),
});
if (s.lastGlassesReport) {
rows.push({ label: "Glasses said", value: `${s.lastGlassesReport} (${formatAge(s.lastGlassesReportAgeMs)} ago)` });
}
if (s.lastRingCommand) {
rows.push({
label: "Ring cmd",
value: `${s.lastRingCommand} ${formatAge(s.lastRingCommandAgeMs)} ago: ${s.lastRingCommandResult}`,
});
}
if (s.lastCommand) {
rows.push({ label: "Glasses cmd", value: `${s.lastCommand} ${formatAge(s.lastCommandAgeMs)} ago` });
rows.push({ label: "Glasses ack", value: `R ${s.lastCommandResultR}; L ${s.lastCommandResultL}` });
}
if (s.lastDirectError) rows.push({ label: "Direct error", value: s.lastDirectError, dim: true });
return rows;
}
private activate(ctx: LayerContext): void {
switch (BUTTONS[this.selected]!) {
case "glasses":
ctx.stack.push(this.actionMenu("Glasses ring link", GLASSES_ACTIONS.map(({ label, action }) => ({
label,
onSelect: (menuCtx) => {
this.runGlassesAction(label, action);
menuCtx.stack.pop();
},
}))));
return;
case "ring":
ctx.stack.push(this.actionMenu("Ring binding", RING_ACTIONS.map(({ label, action }) => ({
label,
onSelect: (menuCtx) => {
this.notice = `${label}: ${sendRingConfigCommand(action, this.ringAddress(), this.system?.name ?? "")}`;
this.poll();
menuCtx.stack.pop();
},
}))));
return;
case "mode": {
const next = ringConnectionModeSetting.set(ringConnectionModeSetting.next());
this.notice = `Ring connection set to ${ringConnectionModeSetting.displayValue(next)}; applies on next glasses connection`;
return;
}
}
}
private actionMenu(title: string, items: MenuItem[]): MenuLayer {
return new MenuLayer(title, items, ACTION_MENU_LAYOUT);
}
private runGlassesAction(label: string, action: GlassesRingLinkAction): void {
this.notice = setGlassesRingLink(action, this.ringAddress(), this.system?.name ?? "")
? `${label} sent (experimental)`
: `${label} not sent (no session or no ring address)`;
this.poll();
}
handleInput(event: InputEvent, ctx: LayerContext): void {
switch (event.type) {
case "scroll-up":
this.selected = (this.selected + BUTTONS.length - 1) % BUTTONS.length;
return;
case "scroll-down":
this.selected = (this.selected + 1) % BUTTONS.length;
return;
case "click":
this.activate(ctx);
return;
case "double-click":
ctx.stack.pop();
return;
default:
return;
}
}
}
function buttonLabel(button: Button): string {
switch (button) {
case "glasses":
return "Glasses...";
case "ring":
return "Ring...";
case "mode":
return `Mode: ${ringConnectionModeSetting.get()}`;
}
}
function describeSystem(sys: RingSystemBluetoothState | null): string {
if (!sys) return "unknown";
if (sys.error) return `error: ${sys.error}`;
if (sys.bonded === undefined) return "unknown";
const parts = [sys.bonded ? "bonded" : "not bonded"];
if (sys.gattConnected !== undefined) parts.push(sys.gattConnected ? "GATT up" : "no GATT");
if (sys.aclConnected !== undefined) parts.push(sys.aclConnected ? "link up" : "no link");
return parts.join(", ");
}
function describeInput(ageMs: number, label: string): string {
if (ageMs < 0) return "never";
return label ? `${formatAge(ageMs)} ago: ${label}` : `${formatAge(ageMs)} ago`;
}
function describeAge(ageMs: number): string {
return ageMs < 0 ? "never" : `${formatAge(ageMs)} ago`;
}
function formatAge(ageMs: number): string {
const seconds = Math.floor(ageMs / 1000);
if (seconds < 60) return `${seconds}s`;
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes}m ${seconds % 60}s`;
return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
}
+2 -1
View File
@@ -5,7 +5,7 @@ import { glanceWidgetSpans } from "./widgets";
export type GlanceSlotChoice = GlanceWidgetId | "none";
const SLOT_CHOICES: readonly GlanceSlotChoice[] = ["none", "system-card", "calendar", "terminal", "t3code", "nightscout", "compass", "music"];
const SLOT_CHOICES: readonly GlanceSlotChoice[] = ["none", "system-card", "calendar", "terminal", "t3code", "nightscout", "compass", "music", "health"];
const SLOT_CHOICE_LABELS: Record<GlanceSlotChoice, string> = {
none: "Empty",
@@ -16,6 +16,7 @@ const SLOT_CHOICE_LABELS: Record<GlanceSlotChoice, string> = {
nightscout: "Nightscout",
compass: "Compass",
music: "Music",
health: "Health",
};
export function glanceSlotChoiceLabel(choice: GlanceSlotChoice): string {
+1 -1
View File
@@ -28,7 +28,7 @@ export interface GlanceWidget {
paint(image: GrayImage): void;
}
export type GlanceWidgetId = "system-card" | "nightscout" | "compass" | "music" | "calendar" | "terminal" | "t3code";
export type GlanceWidgetId = "system-card" | "nightscout" | "compass" | "music" | "calendar" | "terminal" | "t3code" | "health";
export type GlanceWidgetDefinition = {
id: GlanceWidgetId;
@@ -0,0 +1,56 @@
import { type GrayImage } from "../../../graphics/image";
import { getDefaultMediumFont, getDefaultSmallFont } from "../../../graphics/ui-fonts";
import { dailySummary, nextBucketStart } from "../../../health/health-derive";
import { drawHealthCard, type HealthCardData } from "../../../health/health-card";
import { syncLiveRecords } from "../../../health/health-live";
import { isFixtureData } from "../../../health/health-seed";
import { healthStore } from "../../../health/health-store-files";
import { startOfLocalDay } from "../../../health/health-types";
import { type GlanceWidget } from "../widget";
/** Saved daily metrics, refreshed while visible without extra BLE polling. */
export class HealthWidget implements GlanceWidget {
private data: HealthCardData = { kind: "empty" };
private timer: ReturnType<typeof setInterval> | null = null;
start(requestRender: () => void): void {
this.stop();
const refresh = (): void => {
this.refresh();
requestRender();
};
refresh();
this.timer = setInterval(refresh, 60_000);
}
stop(): void {
if (this.timer !== null) clearInterval(this.timer);
this.timer = null;
}
private refresh(): void {
try {
syncLiveRecords();
if (isFixtureData()) {
this.data = { kind: "fixture" };
return;
}
const today = startOfLocalDay(Date.now());
const store = healthStore();
const samples = store.samplesInRange(today, nextBucketStart(today, "day"));
const summary = dailySummary(samples, store.sleepSessions(), today);
this.data = samples.length || summary.sleep
? { kind: "live", summary,
hasSteps: samples.some((sample) => sample.metric === "steps"),
hasCalories: samples.some((sample) => sample.metric === "calories") }
: { kind: "empty" };
} catch (error) {
console.warn("health widget refresh failed", error);
this.data = { kind: "error" };
}
}
paint(image: GrayImage): void {
drawHealthCard(image, this.data, getDefaultSmallFont(), getDefaultMediumFont());
}
}
+2
View File
@@ -6,6 +6,7 @@ import { NightscoutWidget } from "./nightscout-widget";
import { SystemCardWidget, systemCardSettingsMenuItems } from "./system-card";
import { T3CodeWidget } from "./t3code-widget";
import { TerminalWidget } from "./terminal-widget";
import { HealthWidget } from "./health-widget";
/** Every widget a board slot can hold. */
export const GLANCE_WIDGETS: readonly GlanceWidgetDefinition[] = [
@@ -16,6 +17,7 @@ export const GLANCE_WIDGETS: readonly GlanceWidgetDefinition[] = [
{ id: "nightscout", label: "Nightscout", create: () => new NightscoutWidget() },
{ id: "compass", label: "Compass", create: () => new CompassWidget() },
{ id: "music", label: "Music", settingsMenuItems: musicSettingsMenuItems, create: () => new MusicWidget() },
{ id: "health", label: "Health", create: () => new HealthWidget() },
];
export function findGlanceWidget(id: GlanceWidgetId | (string & {})): GlanceWidgetDefinition | null {
+197
View File
@@ -0,0 +1,197 @@
/**
* HEALTH - the glasses status page.
*
* This file is now PLUMBING ONLY: the store reads, the refresh timer, the
* scroll cursor, the window lifecycle. Every pixel is drawn by
* `health/health-glance.ts`, which has no NativeScript imports and therefore
* renders under plain node - see `tools/health-preview.cjs`, which produces a
* PNG of each page below without an emulator. The first pass drew and plumbed
* in one file and could only be looked at by booting an AVD; that is the
* difference this split buys, and it is the reason to keep the two apart.
*
* ## The surface, after Chris's 2026-09-10 review
*
* The overview is a SUMMARY - text only, no charts - and scrolling walks a
* cursor through a detail page per parameter, ending at sleep's own view.
* `GLANCE_PAGES` in `health-glance.ts` is the page list, and the doc comment
* there carries the reasoning for the carousel (including which parts of it are
* interpretation rather than spec).
*/
import { getDefaultLargeFont, getDefaultSmallFont } from "../../graphics/ui-fonts";
import { GrayImage } from "../../graphics/image";
import { type InputEvent } from "../../ui/gestures";
import { type Layer, type LayerContext } from "../../ui/layers";
import {
createInProcessWindow,
YieldAtRootLayer,
type InProcessAppOptions,
type InProcessWindow,
} from "../../ui/shell/in-process-window";
import { dailySummary, dailyHypnogram, rollupSeries, type DailySummary } from "../../health/health-derive";
import {
drawGlancePage,
GLANCE_PAGES,
type GlanceData,
} from "../../health/health-glance";
import { healthStore } from "../../health/health-store-files";
import { requestFreshPull, syncLiveRecords } from "../../health/health-live";
import { isFixtureData, seedFixturesIfNeeded } from "../../health/health-seed";
import {
DAY_MS,
SAMPLE_METRICS,
startOfLocalDay,
type RollupPoint,
type SampleMetric,
} from "../../health/health-types";
export const HEALTH_WINDOW_ID = "health";
export const HEALTH_SURFACE_ID = "window:health";
/** Cheap enough to re-read on a timer; the store is a few hundred rows a day. */
const REFRESH_INTERVAL_MS = 60_000;
class HealthLayer implements Layer {
private summary: DailySummary | null = null;
/** Today by hour, per metric - what the drill-down pages plot. */
private hourly: Partial<Record<SampleMetric, RollupPoint[]>> = {};
private stageBands: GlanceData["stageBands"] = [];
private fixture = false;
/** Index into GLANCE_PAGES. 0 is the overview. */
private pageIndex = 0;
private timer: ReturnType<typeof setInterval> | null = null;
private removed = false;
constructor(private readonly requestRender: () => void) {}
start(): void {
// Live data first: if the ring has been pulled this session, this stores it
// and wipes any fixtures out of the way. Only if that leaves us with
// nothing does seeding fill the screen, and seeding refuses outright once
// real data has ever landed.
syncLiveRecords();
// Ask for something current rather than showing whatever the last
// automatic 30-minute pull happened to catch. Returns immediately; the
// pull takes ~15s and lands via the refresh tick below.
requestFreshPull();
seedFixturesIfNeeded();
this.reload();
this.timer = setInterval(() => this.reload(), REFRESH_INTERVAL_MS);
}
stop(): void {
if (this.removed) return;
this.removed = true;
if (this.timer !== null) clearInterval(this.timer);
this.timer = null;
}
onRemoved(): void {
this.stop();
}
private reload(): void {
if (this.removed) return;
// Cheap on every tick: a no-op when the communicator has nothing new, and
// the store dedupes when it does, so a 30-minute pull shows up here within
// one refresh instead of waiting for the app to be reopened.
syncLiveRecords();
try {
const store = healthStore();
const today = startOfLocalDay(Date.now());
const samples = store.samplesInRange(today, today + DAY_MS);
const sessions = store.sleepSessions();
this.summary = dailySummary(samples, sessions, today);
// One pass per metric over a day's samples - a few hundred rows, and the
// drill-down has to be instant when the cursor lands on it.
const hourly: Partial<Record<SampleMetric, RollupPoint[]>> = {};
for (const metric of SAMPLE_METRICS) {
hourly[metric] = rollupSeries(samples, {
metric,
granularity: "hour",
startMs: today,
endMs: today + DAY_MS,
});
}
this.hourly = hourly;
this.stageBands = dailyHypnogram(sessions, today);
this.fixture = isFixtureData();
} catch (error) {
console.warn("health glance reload failed", error);
}
this.requestRender();
}
paint(ctx: LayerContext): GrayImage {
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
drawGlancePage(
image,
{ width, height },
{ small: getDefaultSmallFont(), large: getDefaultLargeFont() },
GLANCE_PAGES[this.pageIndex] ?? GLANCE_PAGES[0]!,
{
summary: this.summary,
hourly: this.hourly,
stageBands: this.stageBands,
nowMs: Date.now(),
fixture: this.fixture,
},
);
return image;
}
/**
* Scrolling moves between the overview and the per-parameter detail pages.
*
* The cursor WRAPS. With seven pages and no back gesture available
* (`YieldAtRootLayer` takes double-click for back-out-to-home), wrapping is
* what guarantees the overview is always reachable by holding one direction -
* a user who has scrolled to the end never has to work out which way is back.
* Click advances too, so the drill-down is reachable without ever scrolling.
*/
handleInput(event: InputEvent, _ctx: LayerContext): void {
switch (event.type) {
case "scroll-down":
case "click":
this.movePage(1);
return;
case "scroll-up":
this.movePage(-1);
return;
default:
return;
}
}
private movePage(delta: number): void {
const count = GLANCE_PAGES.length;
this.pageIndex = (this.pageIndex + delta + count) % count;
this.requestRender();
}
}
export function createHealthAppWindow(options: InProcessAppOptions): InProcessWindow {
let requestRender = () => {};
const layer = new HealthLayer(() => requestRender());
const app = createInProcessWindow({
appId: "health",
windowId: HEALTH_WINDOW_ID,
title: "Health",
iconLetter: "H",
icon: "activity",
closeable: true,
actions: options.actions,
baseLayer: new YieldAtRootLayer(layer),
submitFrame: options.submitFrame,
setSurfaceVisible: options.setSurfaceVisible,
removeSurface: options.removeSurface,
onClosed: () => {
layer.stop();
options.onClosed();
},
});
requestRender = app.requestRender;
layer.start();
return app;
}
+11
View File
@@ -0,0 +1,11 @@
import { type AppDefinition } from "../app-definition";
import { createHealthAppWindow, HEALTH_SURFACE_ID, HEALTH_WINDOW_ID } from "./health-app";
const healthApp: AppDefinition = {
appId: "health",
title: "Health",
icon: "activity",
launch: (ctx) => ctx.launchInProcessApp(HEALTH_WINDOW_ID, HEALTH_SURFACE_ID, createHealthAppWindow),
};
export default healthApp;
+12
View File
@@ -2,6 +2,7 @@ import { Application } from '@nativescript/core'
import { registerShareIntentHandler } from './native/share-intents'
import { installNativeUserAgent } from './util/http'
import { registerPhoneRotation } from './native/phone-rotation'
import { startLiveHealthSync, startAlignedRingPull } from './health/health-live'
installNativeUserAgent()
registerShareIntentHandler()
@@ -12,4 +13,15 @@ Application.on(Application.launchEvent, () => {
setTimeout(() => require('./analytics/analytics-sources').startAppAnalytics(), 0)
})
// Ring health records live only in the communicator's memory until something
// stores them. Both health surfaces store on open, but a pull that lands while
// they are closed would be lost if the process restarted first, so this keeps
// them reaching disk regardless. No-op when there is nothing new.
startLiveHealthSync()
// Collect from the ring on a wall-clock cadence (:01 and :31). Without this
// nothing drives a pull on a timer at all - only onRingReady() on reconnect -
// so a ring that stays connected is never read.
startAlignedRingPull()
Application.run({ moduleName: 'app-root' })
+40 -5
View File
@@ -19,6 +19,8 @@ import { ALL_NOTIFICATIONS, onAndroidNotificationPosted, onAndroidNotificationRe
import { shouldShowNotificationOnGlasses } from "../native/notification-sources";
import { watchNotificationListenerBinding } from "../native/notification-access";
import { openEvenAppSettings, readEvenAppNotificationState } from "../native/even-app-conflict";
import { defaultRingName, setGlassesRingLink } from "../native/ring-status";
import { getBooleanSetting, setBooleanSetting } from "../native/settings-store";
import { grayImageToPreviewSource } from "../native/gray-image-preview";
import { firmwareIncompatibilityMessage, hasCompatibleFirmware } from "./firmware-compat";
import { hasExtractedEvenHubFonts } from "./firmware-builder";
@@ -76,7 +78,7 @@ import { loadPersistedOpenApps, savePersistedOpenApps } from "../ui/shell/open-a
import { appViewportRect, isOnSwitcherEdge, sidebarStripVisible, type ScreenRect, type WindowHeightMode } from "../ui/shell/geometry";
import { type ContinuousCaptureOptions, type LayerActions, type TextSettingsEditToggle, type TranscriptionChoice } from "../ui/layers";
import { type KeyboardInputSession } from "../ui/shell/keyboard-input";
import { appSwitcherPositionSetting, statusBarPositionSetting, statusBarVisibilitySetting, windowBorderSetting, assistantAllowProactiveSetting, assistantBackendSetting, assistantBridgeHostSetting, assistantBridgePortSetting, assistantBridgeTokenSetting, getBrightnessPreferences, displayLayoutSetting, navigateDisplayLayoutSetting, terminalDisplayLayoutSetting, elevenLabsApiKeySetting, getStringSettingById, openAiApiKeySetting, nightscoutApiTokenSetting, firmwareDebugFlagsSetting, whisperServerApiKeySetting, whisperServerLanguageSetting, whisperServerModelSetting, whisperServerUrlSetting, lockScreenEnabledSetting, nightscoutSiteUrlSetting, onAnySettingChanged, previewColorSetting, ringConnectionModeSetting, saveVoiceRecordingsSetting, sonioxApiKeySetting, screenTimeoutSetting, screenTimeoutSettingToMs, suspendEvenHubWhenScreenOffSetting, voiceProviderSetting, wakeWordActionSetting, type ConfigSettingString } from "../ui/dashboard-settings";
import { appSwitcherPositionSetting, statusBarPositionSetting, statusBarVisibilitySetting, windowBorderSetting, assistantAllowProactiveSetting, assistantBackendSetting, assistantBridgeHostSetting, assistantBridgePortSetting, assistantBridgeTokenSetting, getBrightnessPreferences, displayLayoutSetting, navigateDisplayLayoutSetting, terminalDisplayLayoutSetting, elevenLabsApiKeySetting, getStringSettingById, openAiApiKeySetting, nightscoutApiTokenSetting, firmwareDebugFlagsSetting, whisperServerApiKeySetting, whisperServerLanguageSetting, whisperServerModelSetting, whisperServerUrlSetting, lockScreenEnabledSetting, nightscoutSiteUrlSetting, onAnySettingChanged, previewColorSetting, ringConnectionModeSetting, type RingConnectionMode, saveVoiceRecordingsSetting, sonioxApiKeySetting, screenTimeoutSetting, screenTimeoutSettingToMs, suspendEvenHubWhenScreenOffSetting, voiceProviderSetting, wakeWordActionSetting, type ConfigSettingString } from "../ui/dashboard-settings";
import { isIgnoringBatteryOptimizations, requestIgnoreBatteryOptimizations } from "../native/battery-optimization";
import {
getInstalledEvenHubAppById,
@@ -247,6 +249,9 @@ function sourceName(eventSource: number): string {
return EventSourceTypeName[eventSource] ?? `SOURCE_${eventSource}`;
}
/** Set while a Direct ring session may have taken the R1 from the glasses; see handRingBackToGlassesIfNeeded. */
const RING_TAKEN_FROM_GLASSES_KEY = "developer.ringTakenFromGlasses";
class DashboardController {
private phase: ConnectionPhase = "disconnected";
private status = "Disconnected.";
@@ -323,6 +328,8 @@ class DashboardController {
/** Faceclaw's firmware at the required revision reported in; its extensions can be used. */
private customFirmwareConfirmed = false;
private faceclawWakeLeaseState: boolean | null = null;
/** Ring connection mode the current session was started with (it applies per connection). */
private ringModeAtConnect: RingConnectionMode = "glasses";
private glassesWorn: boolean | null = null;
/** Put on while charging: Java reconnects on that, and the wake waits for the new session. */
private wakeAfterChargingReconnect = false;
@@ -1027,6 +1034,25 @@ class DashboardController {
this.evenHubSuspendTimer = null;
}
/**
* A Direct-mode session may have unpaired the R1 from the glasses (see
* GlassesSessionRing.releaseRingFromGlassesLocked). The first session in
* another mode asks the glasses to connect to it again; the ring's own
* glasses targets were cleared, so it accepts them. Called on connect.
*/
private handRingBackToGlassesIfNeeded(): void {
if (this.ringModeAtConnect === "direct" || !getBooleanSetting(RING_TAKEN_FROM_GLASSES_KEY, false)) return;
const ring = loadDeviceAddresses().ring;
if (!ring) {
setBooleanSetting(RING_TAKEN_FROM_GLASSES_KEY, false);
return;
}
if (setGlassesRingLink("connect", ring, defaultRingName(ring))) {
setBooleanSetting(RING_TAKEN_FROM_GLASSES_KEY, false);
this.appendLog(`Handing the R1 ring ${ring} back to the glasses`);
}
}
private pushFirmwareDebugFlags(): void {
if (!this.communicator) return;
void this.communicator
@@ -1453,10 +1479,14 @@ class DashboardController {
this.setPhase("connecting");
this.setStatus("Connecting to the glasses...");
// "Only via glasses" (the default) means the phone never opens its own
// link to the ring: the glasses relay its gestures to us anyway, and the
// direct link is currently unreliable. An empty address disables every
// direct-ring code path in the communicator.
const ringAddress = ringConnectionModeSetting.get() === "direct" ? addresses.ring : "";
// link to the ring: the glasses relay its gestures to us anyway. An empty
// address disables every direct-ring code path in the communicator.
const ringMode = ringConnectionModeSetting.get();
this.ringModeAtConnect = ringMode;
const ringAddress = ringMode !== "glasses" ? addresses.ring : "";
// Direct mode may unpair the ring from the glasses; remember to hand it
// back once a later session runs in another mode.
if (ringMode === "direct" && ringAddress) setBooleanSetting(RING_TAKEN_FROM_GLASSES_KEY, true);
this.appendLog(
`Using configured arms: R=${addresses.right} L=${addresses.left}${ringAddress ? ` ring=${ringAddress}` : ""}`,
);
@@ -1476,6 +1506,10 @@ class DashboardController {
right: addresses.right,
left: addresses.left,
ring: ringAddress,
// Direct mode acts as the ring's glasses (gestures, battery). Health
// sync needs the phone role, which the session borrows briefly for
// each pull (GlassesSessionRing.beginRingHealthWindowLocked).
ringRole: ringMode === "direct" ? "glasses" : "phone",
});
this.communicator = communicator;
// Size the compositor before anything else is awaited: windows opened
@@ -1522,6 +1556,7 @@ class DashboardController {
// mode-7 control message once the dashboard container is warmed up.
this.pushFirmwareDebugFlags();
this.pushBrightness(true);
this.handRingBackToGlassesIfNeeded();
}
if (mappedPhase !== "connected" && mappedPhase !== "charging") {
// A wear snapshot is session-scoped. CFW reports a fresh value when
+55
View File
@@ -0,0 +1,55 @@
import { type GrayImage, type UiFont } from "../graphics/image";
import { truncateText } from "../graphics/textwrap";
import { formatDuration, type DailySummary, type MetricSummary } from "./health-derive";
export type HealthCardData =
| { kind: "live"; summary: DailySummary; hasSteps: boolean; hasCalories: boolean }
| { kind: "fixture" | "empty" | "error" };
const PAD = 8;
/** Three columns keep all six metrics legible in a 288 x 144 board slot. */
export function drawHealthCard(image: GrayImage, data: HealthCardData, small: UiFont, medium: UiFont): void {
image.drawText(small, PAD, PAD, "Health", 180);
const today = "Today";
image.drawText(small, image.width - PAD - small.measureText(today), PAD, today, 130);
const top = PAD + small.lineHeight + 6;
if (data.kind !== "live") {
const title = data.kind === "fixture" ? "Sample data"
: data.kind === "error" ? "Health unavailable" : "No health data today";
const subtitle = data.kind === "fixture" ? "Open Health for details"
: data.kind === "error" ? "Open Health to retry" : "Open Health to sync";
const font = medium.measureText(title) <= image.width - PAD * 2 ? medium : small;
const y = Math.round(top + (image.height - PAD - top - font.lineHeight - small.lineHeight - 6) / 2);
const text = truncateText(font, title, image.width - PAD * 2);
image.drawText(font, Math.round((image.width - font.measureText(text)) / 2), y, text, 240);
const hint = truncateText(small, subtitle, image.width - PAD * 2);
image.drawText(small, Math.round((image.width - small.measureText(hint)) / 2), y + font.lineHeight + 6, hint, 150);
return;
}
const average = (metric: MetricSummary, units: string): string =>
metric.hasData ? `${Math.round(metric.avg)}${units}` : "--";
const { summary } = data;
const cells: [string, string][] = [
["HR avg", average(summary.heartRate, " bpm")],
["HRV avg", average(summary.hrv, " ms")],
["SpO2 avg", average(summary.spo2, "%")],
["Steps", data.hasSteps ? String(summary.steps) : "--"],
["Cal (kcal)", data.hasCalories ? String(summary.calories) : "--"],
["Sleep", summary.sleep ? formatDuration(summary.sleep.totalSec) : "--"],
];
const columnWidth = (image.width - PAD * 2) / 3;
const rowHeight = (image.height - PAD - top) / 2;
cells.forEach(([label, value], index) => {
const left = PAD + Math.floor((index % 3) * columnWidth);
const y = top + Math.floor(Math.floor(index / 3) * rowHeight);
const width = Math.floor(columnWidth) - 6;
const font = medium.measureText(value) <= width
&& small.lineHeight + 2 + medium.lineHeight <= rowHeight - 2 ? medium : small;
const fittedLabel = label === "Cal (kcal)" && small.measureText(label) > width ? "kcal" : label;
image.drawText(small, left, y, truncateText(small, fittedLabel, width), 140);
image.drawText(font, left, y + small.lineHeight + 2, truncateText(font, value, width), 235);
});
}
+684
View File
@@ -0,0 +1,684 @@
/**
* The chart renderer, shared by both surfaces.
*
* Both the glasses glance and the phone graphs draw into a `GrayImage`, and
* the phone converts its one through `grayImageToPreviewSource()` - the same
* already-shipping path the glasses mirror uses to put a rendered frame on the
* phone screen. That is a deliberate reuse rather than a shortcut: it means
* one drawing implementation covers both surfaces, no new native code exists
* for the phone side, and the two screens cannot drift apart visually.
*
* ⚠ DESIGN CHOICE, not a spec (Chris said only "the Even app wasn't bad for
* this, I liked their summaries, but we can't copy it, we have to make our
* own"): the phone charts are MONOCHROME, because that is what
* `PreviewBitmapUtil.fromGray` produces and adding colour would mean new
* Kotlin. It lands somewhere deliberate rather than accidental - the phone
* already shows the glasses' grey mirror, so the health screens read as part
* of the same instrument - but colour is a real option later and would be a
* contained change: a second bitmap builder plus a palette here.
*
* Nothing in this file imports NativeScript, and that is load-bearing rather
* than incidental: `tools/health-preview.cjs` renders these functions under
* plain node and writes PNGs, so a layout can be looked at without an Android
* emulator in the loop. Keep it that way - the fonts arrive as `UiFont`
* arguments precisely so no drawing code ever has to reach for the platform.
*/
import { GrayImage } from "../graphics/image";
import { type UiFont } from "../graphics/image";
import {
type RollupPoint,
type SampleMetric,
type SleepNight,
isCumulative,
} from "./health-types";
import { bandIsMeaningful, formatValue, primaryValue } from "./health-derive";
import { STAGE_MAPPING_CONFIRMED, type SleepStageName } from "./sleep-stages";
/**
* The grey ramp. Everything drawn here uses one of these.
*
* ⚠ RAISED FOR CONTRAST, 2026-09-10 (Chris, reviewing the first pass): "the
* chart axis labels/gridlines are too low-contrast - dark grey on black, hard
* to read". The old ramp put gridlines at 42 and axis labels at 148 on a black
* plate, which on the phone's dark chart surface left the gridlines essentially
* invisible and the numbers a squint. Gridlines, the axis line and label text
* all moved up.
*
* `faint` is new and is where the things that were DELIBERATELY quiet went -
* the sample-data badge, the column divider, an unmapped hypnogram block. They
* used to share `grid`'s value, so raising `grid` for legibility would have
* dragged them up too; splitting the token is what lets the chart get brighter
* without the furniture shouting.
*/
export const INK = {
background: 0,
/** Deliberately quiet furniture - badges, dividers, unmapped blocks. */
faint: 46,
grid: 100,
axis: 145,
band: 82,
bar: 168,
line: 250,
label: 205,
title: 255,
dim: 125,
} as const;
export type ChartRect = { x: number; y: number; width: number; height: number };
export type ChartOptions = {
/** Only used to pick the default mode and to read `avg` vs `sum`. */
metric: SampleMetric;
points: readonly RollupPoint[];
font: UiFont;
/** Formats a point's x-axis label; return "" to leave a tick unlabelled. */
xLabel: (point: RollupPoint, index: number) => string;
/**
* `band` draws a min/max band with the average through it; `bars` draws a
* column per bucket from zero. Defaults to bars for the cumulative metrics.
*/
mode?: "band" | "bars";
};
/**
* A min/max band with the average tracked through it, or bars for the
* cumulative metrics.
*
* Gaps are drawn as gaps. A ring is taken off to charge, so missing hours are
* the normal case, not an edge case, and a line that joins across them claims
* a continuity the data does not have.
*/
export function drawMetricChart(image: GrayImage, rect: ChartRect, options: ChartOptions): void {
const { metric, points, font } = options;
const labelWidth = Math.max(34, font.measureText("8888") + 6);
const labelHeight = font.lineHeight + 2;
const plot: ChartRect = {
x: rect.x + labelWidth,
y: rect.y,
width: Math.max(8, rect.width - labelWidth),
height: Math.max(8, rect.height - labelHeight),
};
const withData = points.filter((point) => point.count > 0);
if (withData.length === 0) {
drawNoData(image, rect, font);
return;
}
const bars = options.mode ? options.mode === "bars" : isCumulative(metric);
const scale = valueScale(withData, bars);
const showBand = !bars && bandIsMeaningful(points);
drawGrid(image, plot, scale, font, rect.x);
const slotWidth = plot.width / points.length;
const yFor = (value: number): number =>
plot.y + plot.height - ((value - scale.low) / scale.span) * plot.height;
if (bars) {
const barWidth = Math.max(1, Math.floor(slotWidth * 0.62));
for (let index = 0; index < points.length; index += 1) {
const point = points[index]!;
if (point.count === 0) continue;
const top = yFor(point.sum);
const left = Math.round(plot.x + index * slotWidth + (slotWidth - barWidth) / 2);
const height = Math.max(1, Math.round(plot.y + plot.height - top));
image.fillRect(left, Math.round(top), barWidth, height, INK.bar);
}
} else {
if (showBand) {
for (let index = 0; index < points.length; index += 1) {
const point = points[index]!;
if (point.count === 0) continue;
const left = Math.round(plot.x + index * slotWidth);
const width = Math.max(1, Math.round(slotWidth));
const top = Math.round(yFor(point.max));
const bottom = Math.round(yFor(point.min));
image.fillRect(left, top, width, Math.max(1, bottom - top), INK.band);
}
}
// The average line, drawn only between adjacent points that both have
// data, so a gap stays a gap.
let previous: { x: number; y: number } | null = null;
for (let index = 0; index < points.length; index += 1) {
const point = points[index]!;
if (point.count === 0) {
previous = null;
continue;
}
const cx = plot.x + index * slotWidth + slotWidth / 2;
const cy = yFor(primaryValue(point, metric));
if (previous) image.drawLine(previous.x, previous.y, cx, cy, INK.line);
else image.fillRect(Math.round(cx), Math.round(cy), 1, 1, INK.line);
previous = { x: cx, y: cy };
}
}
drawXLabels(image, plot, points, font, rect, options.xLabel);
}
function drawNoData(image: GrayImage, rect: ChartRect, font: UiFont): void {
const message = "No data for this range";
image.drawText(
font,
rect.x + Math.round((rect.width - font.measureText(message)) / 2),
rect.y + Math.round(rect.height / 2) - font.lineHeight,
message,
INK.dim,
);
}
/** X labels along the bottom of a plot, thinned so they never collide. */
function drawXLabels(
image: GrayImage,
plot: ChartRect,
points: readonly { startMs: number }[],
font: UiFont,
clip: ChartRect,
xLabel: (point: never, index: number) => string,
): void {
const slotWidth = plot.width / Math.max(1, points.length);
const step = Math.max(1, Math.ceil(46 / Math.max(1, slotWidth)));
const labelY = plot.y + plot.height + 2;
for (let index = 0; index < points.length; index += step) {
const text = xLabel(points[index]! as never, index);
if (!text) continue;
const cx = plot.x + index * slotWidth + slotWidth / 2;
const x = Math.round(cx - font.measureText(text) / 2);
if (x < clip.x || x + font.measureText(text) > clip.x + clip.width) continue;
image.drawText(font, x, labelY, text, INK.label);
}
}
type Scale = { low: number; high: number; span: number };
function valueScale(points: readonly RollupPoint[], bars: boolean): Scale {
let low = Number.POSITIVE_INFINITY;
let high = Number.NEGATIVE_INFINITY;
for (const point of points) {
const top = bars ? point.sum : point.max;
const bottom = bars ? 0 : point.min;
if (bottom < low) low = bottom;
if (top > high) high = top;
}
if (!Number.isFinite(low) || !Number.isFinite(high)) return { low: 0, high: 1, span: 1 };
if (bars) low = 0;
if (high - low < 1) {
// A flat series still needs somewhere to sit; centre it rather than
// letting it collapse onto the axis.
low -= 1;
high += 1;
}
// Bars are measured from zero, so only the top gets breathing room - padding
// the bottom too would put a negative tick under a count that cannot go
// negative, and float the bars off their own baseline.
const pad = (high - low) * 0.08;
const scale = { low: bars ? low : low - pad, high: high + pad, span: 0 };
scale.span = scale.high - scale.low || 1;
return scale;
}
function drawGrid(
image: GrayImage,
plot: ChartRect,
scale: Scale,
font: UiFont,
labelX: number,
): void {
const lines = 3;
for (let index = 0; index < lines; index += 1) {
const fraction = index / (lines - 1);
const value = scale.high - fraction * scale.span;
const y = Math.round(plot.y + fraction * plot.height);
image.drawLine(plot.x, y, plot.x + plot.width, y, INK.grid);
const text = `${Math.round(value)}`;
const textY = Math.min(
plot.y + plot.height - font.lineHeight,
Math.max(plot.y, y - Math.round(font.lineHeight / 2)),
);
image.drawText(font, labelX, textY, text, INK.label);
}
image.drawLine(plot.x, plot.y, plot.x, plot.y + plot.height, INK.axis);
}
// ===========================================================================
// Sleep
/**
* Stage inks.
*
* ⚠ RAISED AND REORDERED, 2026-09-10, alongside the diverging sleep chart.
* Within the upward stack the ramp descends with height - deep (bottom) is the
* brightest, light (top) the dimmest - so the three read as one column with a
* clear internal order rather than three similar greys.
*
* `wake` is deliberately NOT the dimmest any more, which looks wrong in a list
* and is right on the chart: awake time is drawn BELOW the zero line, so it is
* separated from the stack spatially rather than by brightness. That frees it
* to be legible (Chris's contrast note applies to it as much as to the axes)
* without it reading as part of the sleep stack.
*/
const STAGE_INK: Readonly<Record<SleepStageName, number>> = {
wake: 150,
rem: 180,
light: 112,
deep: 250,
};
export function stageInk(stage: SleepStageName): number {
return STAGE_INK[stage];
}
/**
* The night as a run of stage blocks.
*
* This is the ONE thing on either surface that depends on the raw stage-id
* mapping, so while `STAGE_MAPPING_CONFIRMED` is false the caller is expected
* to caption it as unconfirmed - `hypnogramCaption()` supplies the wording.
*/
export function drawHypnogram(
image: GrayImage,
rect: ChartRect,
bands: readonly { stage: SleepStageName | null; seconds: number }[],
): void {
let total = 0;
for (const band of bands) total += band.seconds;
if (total <= 0) return;
let x = rect.x;
for (const band of bands) {
const width = (band.seconds / total) * rect.width;
const drawn = Math.max(1, Math.round(width));
// An unmapped stage id is drawn as a hatch-dim block rather than being
// dropped: the time happened, we just cannot name it.
const ink = band.stage ? STAGE_INK[band.stage] : INK.faint;
image.fillRect(Math.round(x), rect.y, drawn, rect.height, ink);
x += width;
}
image.drawRect(rect.x, rect.y, rect.width, rect.height, INK.axis);
}
export function hypnogramCaption(): string {
return STAGE_MAPPING_CONFIRMED
? "Sleep stages through the night"
: "Stage pattern - labels not yet confirmed on live data";
}
/** The same caption for the glasses, where the line is 300-odd pixels wide. */
export function hypnogramCaptionShort(): string {
return STAGE_MAPPING_CONFIRMED ? "Stages through the night" : "Stages - labels unconfirmed";
}
// ===========================================================================
// The diverging nightly sleep chart (week / month / 3 months)
/**
* A night as a DIVERGING stacked bar - Chris's design, 2026-09-10.
*
* Sleep stacks upward from zero in the order deep (bottom), REM (middle),
* light (top). Awake time stacks DOWNWARD, below the zero line, as its own
* segment.
*
* The divergence is the whole idea and it is a claim about the data, not a
* styling choice: awake time is not a kind of sleep, so stacking it with the
* others would make a restless night's column look like a long one. Putting it
* below the line means the upward height is always "how much you slept" and
* can be compared across nights at a glance, while the downward tail says what
* it cost. A legend names the four, because a monochrome stack is not
* self-describing.
*
* ⚠ The stage ORDER is specified (deep/REM/light bottom-to-top, awake below);
* the axis ticks, the 1px separators and the legend placement are mine.
*/
/**
* The upward stack, BOTTOM TO TOP. Deep is the foundation of the column.
*
* See `SLEEP_LANE_ORDER` for why this and the lane order only look like they
* disagree.
*/
export const SLEEP_STACK_ORDER: readonly SleepStageName[] = ["deep", "rem", "light"];
/**
* The one-night detail's lanes, TOP TO BOTTOM.
*
* ⚠ THESE TWO ORDERS LOOK CONTRADICTORY AND ARE NOT. Chris gave both in the
* same review, in opposite directions: the week/month chart stacks "Deep
* (bottom), REM (middle), light (top)" upward with awake below zero, and the
* one-day view lists "Awake, light, REM, Deep" downward. Stated that way they
* read as a conflict, which is why the brief flagged the difference as
* deliberate rather than a typo.
*
* Resolve both to the same direction and the conflict disappears. Top to
* bottom, the stack is light / REM / deep; top to bottom, the lanes are awake /
* light / REM / deep. The three sleep stages are in the SAME vertical order in
* both views - deep at the bottom, light nearest the top - so a reader who
* learns the arrangement on one screen reads the other correctly without
* relearning it.
*
* The one genuine difference is where awake goes: its own lane above the
* others here, its own bar below the zero line there. That follows from what
* each view is: a timeline has to show awake in sequence with everything else,
* and a stacked total must not add it to the sleep it interrupted.
*
* A test pins the agreement, so "fixing" either order breaks it loudly.
*/
export const SLEEP_LANE_ORDER: readonly SleepStageName[] = ["wake", "light", "rem", "deep"];
/** Descending "nice" ticks for the awake axis, in hours: 4h..5m. */
const DOWN_TICK_HOURS = [4, 2, 1, 0.5, 0.25, 1 / 6, 1 / 12];
/** "2" for whole hours, "30m" below one - the awake side is usually minutes. */
function formatHourTick(hours: number): string {
return hours >= 1 ? `${hours}` : `${Math.round(hours * 60)}m`;
}
export function drawSleepStackChart(
image: GrayImage,
rect: ChartRect,
options: {
nights: readonly SleepNight[];
font: UiFont;
xLabel: (night: SleepNight, index: number) => string;
},
): void {
const { nights, font } = options;
const labelWidth = Math.max(34, font.measureText("-88m") + 6);
const legendHeight = font.lineHeight + 4;
const labelHeight = font.lineHeight + 2;
const plot: ChartRect = {
x: rect.x + labelWidth,
y: rect.y + legendHeight,
width: Math.max(8, rect.width - labelWidth),
height: Math.max(8, rect.height - labelHeight - legendHeight),
};
drawStageLegend(image, rect.x, rect.y, rect.width, font);
const withData = nights.filter((night) => night.hasData);
if (withData.length === 0) {
drawNoData(image, rect, font);
return;
}
const hours = (seconds: number): number => seconds / 3600;
let maxUp = 0;
let maxDown = 0;
for (const night of withData) {
const up = hours(night.deepSec + night.remSec + night.lightSec);
const down = hours(night.wakeSec);
if (up > maxUp) maxUp = up;
if (down > maxDown) maxDown = down;
}
// Headroom above, and a floor under the awake band so a night with almost no
// wake time still leaves the zero line off the bottom edge.
maxUp = Math.max(1, maxUp * 1.08);
maxDown = Math.max(0.5, maxDown * 1.15);
const span = maxUp + maxDown;
const zeroY = Math.round(plot.y + (maxUp / span) * plot.height);
const pxPerHour = plot.height / span;
// Gridlines: whole hours above zero, and one below for the awake side.
const upStep = maxUp > 9 ? 4 : maxUp > 4 ? 2 : 1;
for (let hour = upStep; hour <= maxUp; hour += upStep) {
const y = Math.round(zeroY - hour * pxPerHour);
if (y < plot.y) break;
image.drawLine(plot.x, y, plot.x + plot.width, y, INK.grid);
image.drawText(font, rect.x, y - Math.round(font.lineHeight / 2), `${hour}`, INK.label);
}
// The awake side needs its own tick ladder, not the hour steps used above.
// A typical night is six hours of sleep against ten or twenty minutes awake,
// so a whole-hour tick below zero falls off the bottom of the chart and the
// downward axis ends up unlabelled - which is what the first cut of this did.
const downTick = DOWN_TICK_HOURS.find((hours) => hours <= maxDown * 0.95);
if (downTick !== undefined) {
const downY = Math.round(zeroY + downTick * pxPerHour);
if (downY <= plot.y + plot.height) {
image.drawLine(plot.x, downY, plot.x + plot.width, downY, INK.grid);
image.drawText(
font,
rect.x,
downY - Math.round(font.lineHeight / 2),
`-${formatHourTick(downTick)}`,
INK.label,
);
}
}
const slotWidth = plot.width / nights.length;
const barWidth = Math.max(1, Math.floor(slotWidth * 0.68));
for (let index = 0; index < nights.length; index += 1) {
const night = nights[index]!;
if (!night.hasData) continue;
const left = Math.round(plot.x + index * slotWidth + (slotWidth - barWidth) / 2);
// Upward: deep at the bottom, then REM, then light. Drawn from the zero
// line outward so rounding never opens a gap at the baseline.
let cursor = zeroY;
const secondsByStage: Record<SleepStageName, number> = {
deep: night.deepSec,
rem: night.remSec,
light: night.lightSec,
wake: night.wakeSec,
};
const upward: [number, number][] = SLEEP_STACK_ORDER.map((stage) => [
secondsByStage[stage],
STAGE_INK[stage],
]);
for (const [seconds, ink] of upward) {
if (seconds <= 0) continue;
const height = Math.max(1, Math.round(hours(seconds) * pxPerHour));
const top = Math.max(plot.y, cursor - height);
image.fillRect(left, top, barWidth, Math.max(1, cursor - top), ink);
cursor = top;
// A 1px unlit separator so two adjacent greys stay two segments. Only
// worth it when the bar is tall enough to still read as a block.
if (cursor > plot.y + 1 && height > 3) {
image.fillRect(left, cursor, barWidth, 1, INK.background);
}
}
// Downward: awake, below the line.
if (night.wakeSec > 0) {
const height = Math.max(1, Math.round(hours(night.wakeSec) * pxPerHour));
const bottom = Math.min(plot.y + plot.height, zeroY + 1 + height);
image.fillRect(left, zeroY + 1, barWidth, Math.max(1, bottom - zeroY - 1), STAGE_INK.wake);
}
}
// The zero line last, so it sits on top of every bar that touches it - it is
// the reference the whole chart is read against.
image.drawLine(plot.x, zeroY, plot.x + plot.width, zeroY, INK.axis);
image.drawText(font, rect.x, zeroY - Math.round(font.lineHeight / 2), "0", INK.label);
image.drawLine(plot.x, plot.y, plot.x, plot.y + plot.height, INK.axis);
drawXLabels(
image,
{ ...plot, y: plot.y, height: plot.height },
nights,
font,
{ ...rect, y: plot.y, height: plot.height },
((night: SleepNight, index: number) => options.xLabel(night, index)) as never,
);
}
/**
* The four stages as swatch + name, on one line.
*
* Awake is listed last and marked, because its bar goes the other way and a
* legend that reads deep/REM/light/awake in a row would imply they stack
* together.
*/
export function drawStageLegend(
image: GrayImage,
x: number,
y: number,
width: number,
font: UiFont,
): void {
const entries: [string, number][] = [
["Deep", STAGE_INK.deep],
["REM", STAGE_INK.rem],
["Light", STAGE_INK.light],
["Awake v", STAGE_INK.wake],
];
const swatch = Math.max(6, font.lineHeight - 4);
let cursor = x;
for (const [label, ink] of entries) {
const textWidth = font.measureText(label);
const entryWidth = swatch + 4 + textWidth + 12;
if (cursor + entryWidth > x + width) break;
image.fillRect(cursor, y + 2, swatch, swatch, ink);
image.drawRect(cursor, y + 2, swatch, swatch, INK.axis);
image.drawText(font, cursor + swatch + 4, y, label, INK.label);
cursor += entryWidth;
}
}
// ===========================================================================
// The one-night sleep detail (the glasses drill-down)
/**
* One night as four horizontal LANES, stacked top to bottom in the order
* Awake, Light, REM, Deep - Chris's ordering, 2026-09-10. It is stated in the
* opposite direction from the week chart's and therefore reads as a conflict
* with it; it is not one, and `SLEEP_LANE_ORDER` explains why. Both views put
* deep at the bottom.
*
* ⚠ PROPORTIONS ARE A DESIGN CALL. The stage order and the top-to-bottom
* orientation are specified; "exactly what arranged vertically should look
* like pixel-for-pixel wasn't specified further than that ordering". So: four
* equal-height lanes across the full width of the night, each lane's blocks
* filled where the sleeper was in that stage, with the lane's name and its
* total on the left. Equal heights rather than height-proportional-to-duration,
* because the lane's JOB is to show when that stage happened, and a 4%-of-night
* deep lane squeezed to a few pixels would show nothing.
*/
export function drawSleepLanes(
image: GrayImage,
rect: ChartRect,
options: {
bands: readonly { stage: SleepStageName | null; seconds: number }[];
font: UiFont;
/** Left-column label + total for each lane, in lane order. */
laneText: (stage: SleepStageName) => { label: string; value: string };
},
): void {
const { bands, font } = options;
const LANE_ORDER = SLEEP_LANE_ORDER;
let total = 0;
for (const band of bands) total += band.seconds;
if (total <= 0) {
drawNoData(image, rect, font);
return;
}
// The left column has to fit "Awake" plus its duration; measure rather than
// guess, so a larger UI font does not overrun the lanes.
let gutter = 0;
for (const stage of LANE_ORDER) {
const text = options.laneText(stage);
gutter = Math.max(gutter, font.measureText(text.label), font.measureText(text.value));
}
gutter += 10;
const laneX = rect.x + gutter;
const laneWidth = Math.max(8, rect.width - gutter);
const axisHeight = font.lineHeight + 2;
const laneGap = 4;
const laneHeight = Math.max(
6,
Math.floor((rect.height - axisHeight - laneGap * (LANE_ORDER.length - 1)) / LANE_ORDER.length),
);
for (let index = 0; index < LANE_ORDER.length; index += 1) {
const stage = LANE_ORDER[index]!;
const top = rect.y + index * (laneHeight + laneGap);
const text = options.laneText(stage);
// The lane's own track, so an empty stretch still reads as a lane rather
// than as nothing.
image.drawRect(laneX, top, laneWidth, laneHeight, INK.faint);
let cursor = laneX;
for (const band of bands) {
const width = (band.seconds / total) * laneWidth;
if (band.stage === stage) {
image.fillRect(Math.round(cursor), top, Math.max(1, Math.round(width)), laneHeight, STAGE_INK[stage]);
}
cursor += width;
}
// Name above its own duration, both in the gutter, vertically centred on
// the lane when there is room for two lines.
const twoLines = laneHeight >= font.lineHeight * 2;
const textTop = twoLines
? top + Math.round((laneHeight - font.lineHeight * 2) / 2)
: top + Math.round((laneHeight - font.lineHeight) / 2);
image.drawText(font, rect.x, textTop, text.label, INK.label);
if (twoLines) image.drawText(font, rect.x, textTop + font.lineHeight, text.value, INK.line);
}
// A time axis under the lanes: the night runs left to right, so mark its
// ends. Without this the lanes are a proportion with no anchor.
const axisY = rect.y + LANE_ORDER.length * (laneHeight + laneGap);
image.drawLine(laneX, axisY, laneX + laneWidth, axisY, INK.axis);
}
// ===========================================================================
// Small shared pieces
/**
* A "min / avg / max" readout, the shape both surfaces use for a metric.
*
* `whole` rounds all three. The glance passes it: an average heart rate
* printed as 72.7 reads as precision the measurement does not have, and on a
* screen you glance at rather than study, the tenth is noise. The phone's stat
* panel keeps the decimal, where comparing two averages is the point.
*/
export function tripleText(
summary: { min: number; max: number; avg: number; hasData: boolean },
metric: SampleMetric,
options?: { whole?: boolean },
): string {
if (!summary.hasData) return "--";
const show = (value: number): string =>
options?.whole ? `${Math.round(value)}` : formatValue(value, metric);
return `${show(summary.min)} / ${show(summary.avg)} / ${show(summary.max)}`;
}
/**
* "60-98 bpm, avg 73" - the glance's metric line.
*
* ⚠ REPLACES the min/avg/max triple on the glasses overview, Chris 2026-09-10:
* three bare numbers under a "min / avg / max" legend made the reader do the
* decoding. A range and an average is the same information said in the shape a
* person would say it in, and it needs no legend line underneath.
*
* The separator is an ASCII hyphen, not an en dash: the glasses render through
* Terminus, and a codepoint the face does not carry comes back as the default
* char - a "?" in the middle of the number - rather than failing loudly.
*/
export function rangeAverageText(
summary: { min: number; max: number; avg: number; hasData: boolean },
unit: string,
): string {
if (!summary.hasData) return "--";
const whole = (value: number): string => `${Math.round(value)}`;
const range = `${whole(summary.min)}-${whole(summary.max)}`;
return unit ? `${range} ${unit}, avg ${whole(summary.avg)}` : `${range}, avg ${whole(summary.avg)}`;
}
/** A right-aligned draw, for readouts that should line up on their last digit. */
export function drawTextRight(
image: GrayImage,
font: UiFont,
right: number,
y: number,
text: string,
value: number,
): void {
image.drawText(font, Math.round(right - font.measureText(text)), y, text, value);
}
+437
View File
@@ -0,0 +1,437 @@
/**
* Every derived number the two health surfaces show, in one place, with no
* NativeScript imports so it runs under plain node in `tests/`.
*
* The rule this file follows throughout: show what the ring actually said, or
* say we do not know. Nothing here invents a value to fill a gap, and the one
* composite score a health app is expected to have - a 0-100 "sleep quality" -
* is deliberately absent. See `sleepSummary` for why.
*/
import {
DAY_MS,
HOUR_MS,
type HealthSample,
type Rollup,
type RollupPoint,
type SampleMetric,
type SleepNight,
type SleepSession,
isCumulative,
rollupOf,
startOfLocalDay,
startOfLocalHour,
} from "./health-types";
import { STAGE_DISPLAY_ORDER, type SleepStageName, stageNameForId } from "./sleep-stages";
export type Granularity = "hour" | "day";
/** How far back a chart looks. Hour granularity only makes sense within a day. */
export type RangeKey = "day" | "week" | "month" | "quarter";
export const RANGE_DAYS: Readonly<Record<RangeKey, number>> = {
day: 1,
week: 7,
month: 30,
quarter: 90,
};
export const RANGE_LABELS: Readonly<Record<RangeKey, string>> = {
day: "Day",
week: "Week",
month: "Month",
quarter: "3 months",
};
/**
* Bucket samples into a series of rollups on a fixed grid.
*
* The grid is built first and then filled, so a window with no data comes back
* as a gap (`count === 0`) at its real position rather than being silently
* dropped - a chart that closes over its gaps lies about continuity, which for
* a ring that is taken off to charge is the common case, not an edge case.
*/
export function rollupSeries(
samples: readonly HealthSample[],
options: {
metric: SampleMetric;
granularity: Granularity;
/** Inclusive local start of the plotted window. */
startMs: number;
/** Exclusive local end. */
endMs: number;
},
): RollupPoint[] {
const { metric, granularity, startMs, endMs } = options;
const spanMs = granularity === "hour" ? HOUR_MS : DAY_MS;
const align = granularity === "hour" ? startOfLocalHour : startOfLocalDay;
const buckets = new Map<number, HealthSample[]>();
for (const sample of samples) {
if (sample.metric !== metric) continue;
if (sample.startMs < startMs || sample.startMs >= endMs) continue;
const key = align(sample.startMs);
const list = buckets.get(key);
if (list) list.push(sample);
else buckets.set(key, [sample]);
}
const points: RollupPoint[] = [];
// Walk by calendar step rather than adding spanMs, so a DST change does not
// shift every later bucket by an hour.
let cursor = align(startMs);
let guard = 0;
while (cursor < endMs && guard < 4000) {
guard += 1;
const inBucket = buckets.get(cursor) ?? [];
const rolled = rollupOf(inBucket);
points.push({
startMs: cursor,
spanMs,
...(rolled ?? { min: 0, max: 0, avg: 0, sum: 0, count: 0 }),
});
cursor = nextBucketStart(cursor, granularity);
}
return points;
}
export function nextBucketStart(startMs: number, granularity: Granularity): number {
const date = new Date(startMs);
if (granularity === "hour") date.setHours(date.getHours() + 1, 0, 0, 0);
else date.setDate(date.getDate() + 1);
return date.getTime();
}
/** The value a chart plots as "the" line for a metric. */
export function primaryValue(point: Rollup, metric: SampleMetric): number {
return isCumulative(metric) ? point.sum : point.avg;
}
// ===========================================================================
// The glasses status page's numbers
export type MetricSummary = {
min: number;
max: number;
avg: number;
/** False when nothing was recorded - the UI shows a dash, not a zero. */
hasData: boolean;
};
export type DailySummary = {
dayStartMs: number;
steps: number;
calories: number;
heartRate: MetricSummary;
spo2: MetricSummary;
/**
* ⚠ ADDED 2026-09-10. The first pass left HRV off the glance because Chris's
* original spec listed steps/calories/HR/SpO2/sleep and nothing else, and the
* return doc flagged the absence as deliberate rather than an oversight. He
* revised the spec on review: HRV gets a line alongside the others.
*/
hrv: MetricSummary;
sleep: SleepSummary | null;
};
const NO_DATA: MetricSummary = { min: 0, max: 0, avg: 0, hasData: false };
function summarise(samples: readonly HealthSample[], metric: SampleMetric): MetricSummary {
const rolled = rollupOf(samples.filter((sample) => sample.metric === metric));
if (!rolled) return NO_DATA;
return { min: rolled.min, max: rolled.max, avg: rolled.avg, hasData: true };
}
function sumOf(samples: readonly HealthSample[], metric: SampleMetric): number {
let total = 0;
for (const sample of samples) if (sample.metric === metric) total += sample.total;
return total;
}
/**
* Everything the glasses glance shows, for one local day.
*
* `sleepSessions` is searched for the night that ENDED on this day - the
* "last night's sleep" a morning glance means. A session is attributed to its
* wake-up day on ingest (`SleepSession.dayStartMs`), so this is a lookup, not
* a heuristic applied here.
*/
export function dailySummary(
samples: readonly HealthSample[],
sleepSessions: readonly SleepSession[],
dayStartMs: number,
): DailySummary {
const dayEndMs = nextBucketStart(dayStartMs, "day");
const inDay = samples.filter(
(sample) => sample.startMs >= dayStartMs && sample.startMs < dayEndMs,
);
const nights = sleepSessions.filter((session) => session.dayStartMs === dayStartMs);
return {
dayStartMs,
steps: Math.round(sumOf(inDay, "steps")),
calories: Math.round(sumOf(inDay, "calories")),
heartRate: summarise(inDay, "heartRate"),
spo2: summarise(inDay, "spo2"),
hrv: summarise(inDay, "hrv"),
sleep: combinedSleepSummary(nights),
};
}
// ===========================================================================
// Sleep
export type SleepSummary = {
totalSec: number;
/** Whole hours and remaining minutes of `totalSec`, for "6h 42m". */
hours: number;
minutes: number;
wakeSec: number;
/** Percentages OF TOTAL SLEEP TIME, from the record's named totals. */
remPercent: number;
lightPercent: number;
deepPercent: number;
/**
* `total_time / (total_time + wake_time)`, as a percentage.
*
* This is sleep efficiency as the AASM's actigraphy scoring defines it -
* time asleep over time in bed - and it is a decades-old published standard,
* not something invented here. It is the one number added beyond Chris's
* stated spec, and it is included precisely because it is the opposite of
* the thing that was ruled out: it has a definition anyone can look up.
*
* Deliberately NOT here: a single 0-100 "sleep quality" score. Every
* consumer wearable has one, none of them publish the blend, and there is no
* generally-accepted formula - so it would be a number with the authority of
* a measurement and the content of an opinion. Stage percentages and
* efficiency are shown as themselves instead.
*/
efficiencyPercent: number;
/** Hypnogram bands, in display order. Empty when the record had no segments. */
stageBands: readonly SleepStageBand[];
/** False when the session could not be anchored to real wall-clock time. */
timeResolved: boolean;
};
export type SleepStageBand = {
stage: SleepStageName;
seconds: number;
/** Share of total-time-in-bed (sleep + wake), so the bands sum to 100%. */
percentOfBed: number;
};
export function sleepSummary(session: SleepSession): SleepSummary {
const total = Math.max(0, session.totalSec);
const wake = Math.max(0, session.wakeSec);
const inBed = total + wake;
const pctOfSleep = (value: number): number => (total > 0 ? (value / total) * 100 : 0);
const bedSeconds: Record<SleepStageName, number> = {
wake,
rem: Math.max(0, session.remSec),
light: Math.max(0, session.lightSec),
deep: Math.max(0, session.deepSec),
};
return {
totalSec: total,
hours: Math.floor(total / 3600),
minutes: Math.round((total % 3600) / 60),
wakeSec: wake,
remPercent: pctOfSleep(session.remSec),
lightPercent: pctOfSleep(session.lightSec),
deepPercent: pctOfSleep(session.deepSec),
efficiencyPercent: inBed > 0 ? (total / inBed) * 100 : 0,
stageBands: STAGE_DISPLAY_ORDER.map((stage) => ({
stage,
seconds: bedSeconds[stage],
percentOfBed: inBed > 0 ? (bedSeconds[stage] / inBed) * 100 : 0,
})),
timeResolved: session.timeResolved,
};
}
/** Every recorded block attributed to the day contributes to its headline. */
export function combinedSleepSummary(sessions: readonly SleepSession[]): SleepSummary | null {
if (sessions.length === 0) return null;
const combined: SleepSession = {
...sessions[0], totalSec: 0, wakeSec: 0, remSec: 0, lightSec: 0, deepSec: 0,
timeResolved: sessions.every((session) => session.timeResolved),
};
for (const session of sessions) {
for (const field of ["totalSec", "wakeSec", "remSec", "lightSec", "deepSec"] as const) {
combined[field] += Math.max(0, session[field]);
}
}
return sleepSummary(combined);
}
/**
* One stage's seconds, from the summary's own bands.
*
* Both surfaces label a stage lane with its duration, and both must take that
* number from the record's NAMED per-stage fields (which `sleepSummary` already
* resolved into `stageBands`) rather than by summing the hypnogram's blocks.
* The two should agree; when they do not it is the segment array that is
* suspect, because summing blocks depends on the stage-id mapping and the named
* fields do not. See `sleep-stages.ts`.
*/
export function stageSeconds(stage: SleepStageName, summary: SleepSummary): number {
return summary.stageBands.find((band) => band.stage === stage)?.seconds ?? 0;
}
/**
* One entry per day in the window, carrying that night's four stage totals.
*
* Built for the diverging nightly chart (deep/REM/light stacked up, awake
* down). Like `rollupSeries`, the grid is laid out first and then filled, so a
* night with no record comes back as `hasData: false` at its real position
* rather than shifting every later night one column left.
*
* Sessions attributed to the same day are summed, as in `dailySummary`.
*/
export function sleepNights(
sessions: readonly SleepSession[],
startMs: number,
endMs: number,
): SleepNight[] {
const byDay = new Map<number, SleepNight>();
for (const session of sessions) {
if (session.dayStartMs < startMs || session.dayStartMs >= endMs) continue;
const entry = byDay.get(session.dayStartMs) ?? {
startMs: session.dayStartMs,
hasData: true,
deepSec: 0,
remSec: 0,
lightSec: 0,
wakeSec: 0,
};
entry.deepSec += Math.max(0, session.deepSec);
entry.remSec += Math.max(0, session.remSec);
entry.lightSec += Math.max(0, session.lightSec);
entry.wakeSec += Math.max(0, session.wakeSec);
byDay.set(session.dayStartMs, entry);
}
const nights: SleepNight[] = [];
let cursor = startOfLocalDay(startMs);
let guard = 0;
while (cursor < endMs && guard < 4000) {
guard += 1;
nights.push(
byDay.get(cursor) ?? {
startMs: cursor,
hasData: false,
deepSec: 0,
remSec: 0,
lightSec: 0,
wakeSec: 0,
},
);
cursor = nextBucketStart(cursor, "day");
}
return nights;
}
/**
* The hypnogram: the night as a run of stage blocks, in order.
*
* This is the ONE thing that depends on the raw stage-id mapping, which is why
* it is separated from `sleepSummary`'s percentages (those come from named
* fields and are unaffected). A segment whose id is not in the mapping is
* returned with `stage: null` rather than dropped or guessed at.
*/
export function hypnogram(session: SleepSession): { stage: SleepStageName | null; seconds: number }[] {
return session.segments.map((segment) => ({
stage: stageNameForId(segment.stageId),
seconds: segment.halfMinutes * 30,
}));
}
/** Chronological blocks, with unrecorded intervals left as unknown gaps. */
export function dailyHypnogram(sessions: readonly SleepSession[], dayStartMs: number): ReturnType<typeof hypnogram> {
const result: ReturnType<typeof hypnogram> = [];
let previousEnd: number | null = null;
for (const session of sessions.filter((s) => s.dayStartMs === dayStartMs)
.sort((a, b) => a.startMs - b.startMs)) {
if (previousEnd !== null && session.timeResolved && session.startMs > previousEnd) {
result.push({ stage: null, seconds: (session.startMs - previousEnd) / 1000 });
}
const bands = hypnogram(session);
result.push(...bands);
// A session without stage data still occupies its recorded interval.
const covered = bands.reduce((total, band) => total + band.seconds, 0);
const duration = session.timeResolved
? Math.max(0, (session.endMs - session.startMs) / 1000)
: session.totalSec + session.wakeSec;
if (duration > covered) result.push({ stage: null, seconds: duration - covered });
previousEnd = session.timeResolved ? Math.max(previousEnd ?? 0, session.endMs) : null;
}
return result;
}
/**
* Date formatting, done by hand.
*
* ⚠ MEASURED, not a preference: `toLocaleDateString(undefined, { weekday:
* "short" })` in this NativeScript Android runtime IGNORES the options bag and
* returns the full `Fri Sep 04 2026`. It is the usual cause - a JS engine
* built without full ICU quietly falls back instead of failing - and it turned
* a week chart's axis into seven overlapping full dates. Anything that needs a
* specific date shape has to build it, so these are the only date formatters
* either surface uses.
*
* The cost is that they are English-only. That is a real limitation and the
* right place to fix it is the runtime's ICU, not here.
*/
const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] as const;
const MONTHS = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
] as const;
/** "Fri". */
export function shortWeekday(ms: number): string {
return WEEKDAYS[new Date(ms).getDay()] ?? "";
}
/** "Thu 10 Sep". */
export function shortDate(ms: number): string {
const date = new Date(ms);
return `${WEEKDAYS[date.getDay()]} ${date.getDate()} ${MONTHS[date.getMonth()]}`;
}
/** "6h 42m", or "--" when there is nothing to show. */
export function formatDuration(seconds: number): string {
if (!Number.isFinite(seconds) || seconds <= 0) return "--";
const hours = Math.floor(seconds / 3600);
const minutes = Math.round((seconds % 3600) / 60);
return hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`;
}
/** One decimal at most, and never a trailing ".0". */
export function formatValue(value: number, metric: SampleMetric): string {
if (!Number.isFinite(value)) return "--";
if (isCumulative(metric)) return `${Math.round(value)}`;
const rounded = Math.round(value * 10) / 10;
return Number.isInteger(rounded) ? `${rounded}` : rounded.toFixed(1);
}
/**
* Whether a metric's min/max band is worth drawing.
*
* Measured against the real export before this was written: heart rate's
* hourly min and max differ in 98% of buckets, but SpO2's and HRV's are
* IDENTICAL in 97% of them - the ring reports what amounts to a single reading
* per hour for those two. Drawing a band there produces a hairline that reads
* as a rendering fault rather than as "there is no spread", so the charts drop
* to a plain line when the spread is degenerate across the window.
*/
export function bandIsMeaningful(points: readonly RollupPoint[]): boolean {
let withData = 0;
let withSpread = 0;
for (const point of points) {
if (point.count === 0) continue;
withData += 1;
if (point.max > point.min) withSpread += 1;
}
if (withData === 0) return false;
return withSpread / withData >= 0.25;
}
+246
View File
@@ -0,0 +1,246 @@
/**
* SAMPLE DATA. Not a capture, not anybody's health history.
*
* Every number below is generated from a seeded PRNG against hand-written
* ranges. Nothing here was copied out of an export. What WAS taken from the
* real export - by reading it, which is all this needed - is the *shape*:
*
* - heart rate, SpO2 and HRV arrive as HOURLY buckets carrying (avg, max,
* min); steps and calories as TEN-MINUTE buckets; sleep once per session.
* - heart rate's hourly min and max genuinely differ (they were equal in
* about 2% of real buckets), but SpO2's and HRV's are equal in about 97%
* of theirs - the ring effectively reports one reading an hour for those
* two. The generator reproduces that, because a chart that assumes a
* spread everywhere looks broken on the two metrics that do not have one.
* - roughly a third of a day's ten-minute step buckets are non-zero; the
* rest are flat, because people sit still.
* - a night is a handful of hours with a majority in light sleep, a smaller
* REM share, a smaller deep share again, and a short wake total.
*
* The ranges are round numbers chosen to sit in the same neighbourhood as
* those shapes, not measured constants, and the seed is fixed so a screenshot
* taken today matches one taken next week.
*
* `seedFixtures()` also drops a marker file, and both surfaces show a "Sample
* data" badge whenever it is present - so a screenshot of this can never be
* mistaken later for a screenshot of a real sync.
*/
import {
DAY_MS,
HOUR_MS,
TEN_MINUTES_MS,
type HealthSample,
type SleepSession,
type SleepSegment,
startOfLocalDay,
} from "./health-types";
/** Bumped whenever the generator changes, so a reseed replaces old fixtures. */
export const FIXTURE_VERSION = 1;
/** Deterministic, tiny, and good enough for plausible-looking noise. */
function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function between(random: () => number, low: number, high: number): number {
return low + random() * (high - low);
}
/**
* A daily activity curve: near-nothing overnight, a morning rise, a dip after
* lunch, an evening peak. Returns roughly 0..1 for an hour of the day.
*/
function activityCurve(hour: number): number {
if (hour < 6) return 0.03;
if (hour < 9) return 0.45;
if (hour < 12) return 0.7;
if (hour < 14) return 0.5;
if (hour < 18) return 0.75;
if (hour < 21) return 0.9;
return 0.25;
}
export type Fixtures = {
samples: HealthSample[];
sleep: SleepSession[];
};
/**
* Generate `days` days of sample data ending with today (partially filled up
* to `nowMs`, so "today so far" looks like a day in progress rather than a
* complete one).
*/
export function buildFixtures(options: { days: number; nowMs: number; seed?: number }): Fixtures {
const { days, nowMs } = options;
const random = mulberry32(options.seed ?? 0x5eed);
const samples: HealthSample[] = [];
const sleep: SleepSession[] = [];
const today = startOfLocalDay(nowMs);
for (let dayOffset = days - 1; dayOffset >= 0; dayOffset -= 1) {
const dayStart = startOfLocalDay(today - dayOffset * DAY_MS);
// A per-day baseline so consecutive days are not interchangeable.
const restingBase = between(random, 56, 66);
const hrvBase = between(random, 32, 55);
const spo2Base = between(random, 96, 98);
for (let hour = 0; hour < 24; hour += 1) {
const bucketStart = dayStart + hour * HOUR_MS;
if (bucketStart > nowMs) break;
const effort = activityCurve(hour);
// Heart rate: a real spread every hour.
const avg = restingBase + effort * between(random, 10, 34);
const spread = 4 + effort * between(random, 6, 26);
samples.push({
metric: "heartRate",
startMs: bucketStart,
spanMs: HOUR_MS,
min: Math.round(avg - spread * between(random, 0.35, 0.6)),
max: Math.round(avg + spread * between(random, 0.5, 0.9)),
avg: Math.round(avg),
total: Math.round(avg),
});
// SpO2 and HRV: one reading an hour most of the time, so min == max.
const spo2 = Math.round(spo2Base + between(random, -2, 1.4));
const spo2Flat = random() < 0.97;
samples.push({
metric: "spo2",
startMs: bucketStart,
spanMs: HOUR_MS,
min: spo2Flat ? spo2 : spo2 - 1,
max: spo2Flat ? spo2 : spo2 + 1,
avg: spo2,
total: spo2,
});
const hrv = Math.round(Math.max(6, hrvBase + between(random, -14, 18) - effort * 8));
const hrvFlat = random() < 0.97;
samples.push({
metric: "hrv",
startMs: bucketStart,
spanMs: HOUR_MS,
min: hrvFlat ? hrv : Math.max(2, hrv - 4),
max: hrvFlat ? hrv : hrv + 5,
avg: hrv,
total: hrv,
});
// Steps and calories: six ten-minute buckets inside this hour.
for (let slot = 0; slot < 6; slot += 1) {
const bucket = bucketStart + slot * TEN_MINUTES_MS;
if (bucket > nowMs) break;
const moving = random() < effort * 0.55;
const steps = moving ? Math.round(between(random, 20, 430) * effort) : 0;
const resting = Math.round(between(random, 10, 13));
const active = Math.round(steps * between(random, 0.03, 0.05));
samples.push({
metric: "steps",
startMs: bucket,
spanMs: TEN_MINUTES_MS,
min: steps,
max: steps,
avg: steps,
total: steps,
});
samples.push({
metric: "calories",
startMs: bucket,
spanMs: TEN_MINUTES_MS,
min: resting + active,
max: resting + active,
avg: resting + active,
total: resting + active,
});
}
}
sleep.push(buildNight(random, dayStart));
}
return { samples, sleep };
}
/**
* One night, attributed to the morning it ended on (`dayStart`).
*
* Built SEGMENTS FIRST, then the five duration totals summed out of them -
* the same direction a real record is consistent in. The decode found four
* arithmetic identities holding exactly on every real session, including
* `sum(half_minutes) * 30 == total_time + wake_time` and a per-stage sum
* matching each named total. Generating the totals first and the segments
* afterwards cannot satisfy those exactly once rounding is involved, so this
* goes the other way and the identities hold by construction.
*/
function buildNight(random: () => number, dayStart: number): SleepSession {
const inBedHalfMinutes = Math.round(between(random, 4.4, 6.6) * 120);
const bedMs = dayStart - inBedHalfMinutes * 30 * 1000;
const segments = buildSegments(random, inBedHalfMinutes);
const perStage = new Map<number, number>();
for (const segment of segments) {
perStage.set(segment.stageId, (perStage.get(segment.stageId) ?? 0) + segment.halfMinutes);
}
const seconds = (stageId: number): number => (perStage.get(stageId) ?? 0) * 30;
const wakeSec = seconds(0);
const remSec = seconds(1);
const lightSec = seconds(2);
const deepSec = seconds(3);
const totalSec = remSec + lightSec + deepSec;
return {
dayStartMs: dayStart,
startMs: bedMs,
endMs: bedMs + (totalSec + wakeSec) * 1000,
totalSec,
wakeSec,
remSec,
lightSec,
deepSec,
segments,
timeResolved: true,
};
}
/**
* A segment run filling exactly `inBedHalfMinutes`, cycling through the stages
* the way a night does: light, deep, light, REM, and the occasional wake block.
*
* Stage ids are the RAW ring ids (0 wake, 1 REM, 2 light, 3 deep). The fixture
* deliberately emits ids rather than friendly names, so anything downstream
* that forgets to resolve them through `stageNameForId` is wrong here too.
*
* The per-stage weights are what produce a plausible mix - light dominant,
* then deep, then REM, with a small wake share - matching the ordering the
* real export shows without reproducing its numbers.
*/
function buildSegments(random: () => number, inBedHalfMinutes: number): SleepSegment[] {
const cycle = [2, 3, 2, 1, 2, 0];
const typicalLength: Record<number, [number, number]> = {
0: [1, 6],
1: [8, 26],
2: [14, 40],
3: [10, 30],
};
const segments: SleepSegment[] = [];
let remaining = inBedHalfMinutes;
let index = 0;
while (remaining > 0) {
const stage = cycle[index % cycle.length]!;
index += 1;
const [low, high] = typicalLength[stage]!;
const take = Math.min(remaining, Math.max(1, Math.round(between(random, low, high))));
segments.push({ stageId: stage, halfMinutes: take });
remaining -= take;
}
return segments;
}
+528
View File
@@ -0,0 +1,528 @@
/**
* HEALTH, the glasses surface - all of its DRAWING, and none of its plumbing.
*
* ## Why this is a separate file from `apps/health/health-app.ts`
*
* The app file owns the things only a running app can do: reading the store,
* the refresh timer, the input cursor, the window lifecycle. All of that needs
* NativeScript. The drawing needs nothing but a `GrayImage` and two fonts.
*
* Splitting them the way `health-store.ts` is split from `health-store-files.ts`
* buys the same thing it bought there: this file runs under plain node. That is
* what lets `tools/health-preview.cjs` render every one of these pages to a PNG
* with no emulator, no AVD and no device - the previews come out of the REAL
* paint code, so they cannot drift from what the glasses show the way a
* separate mockup can. The first pass verified its layout by booting a full
* Android emulator; this file is the reason that is no longer necessary.
*
* So the rule for this file: fonts and data arrive as arguments, nothing is
* imported from `native/` or `@nativescript/core`, and nothing reaches for a
* clock except through `data.nowMs`.
*/
import { GrayImage, type UiFont } from "../graphics/image";
import { lineStep } from "../ui/metrics";
import { GESTURE_SCROLL } from "../ui/gestures";
import {
drawSleepLanes,
drawMetricChart,
drawTextRight,
hypnogramCaptionShort,
INK,
rangeAverageText,
} from "./health-chart";
import {
formatDuration,
shortDate,
stageSeconds,
type DailySummary,
type MetricSummary,
} from "./health-derive";
import {
SAMPLE_METRIC_LABELS,
SAMPLE_METRIC_SHORT_LABELS,
SAMPLE_METRIC_UNITS,
type RollupPoint,
type SampleMetric,
} from "./health-types";
import { stageLabel, type SleepStageName } from "./sleep-stages";
const MARGIN = 10;
const GUTTER = 14;
/** Below this the two columns stack instead. */
const TWO_COLUMN_MIN_WIDTH = 380;
export type GlanceFonts = { small: UiFont; large: UiFont };
/**
* One page of the glasses surface.
*
* ⚠ THE DRILL-DOWN IS A SCROLL CAROUSEL, AND THAT IS AN INTERPRETATION.
* Chris, 2026-09-10: "Scrolling to a parameter on the glasses overview should
* open that parameter's today/by-hour detail view... whichever line the user
* has scrolled to." Read literally, the act of scrolling to a parameter is what
* opens it - so scrolling walks a cursor through these pages and the page you
* land on IS the detail view, rather than scrolling moving a highlight that a
* second click then opens.
*
* Two things recommend the literal reading beyond its being literal. It costs
* one gesture instead of two, which matches the direction of every other note
* in that review (less on the glasses, not more). And it needs no back gesture:
* the shell already takes double-click for "back out to home"
* (`YieldAtRootLayer`), so a drill-down that needed its own back would have had
* to invent one out of the ring's three remaining gestures. Scrolling up to
* leave a page you scrolled down into needs nothing.
*
* Click is wired to advance as well, so a user who only ever clicks still gets
* round. Recorded as a call, not a spec.
*/
export type GlancePage =
| { kind: "overview" }
| { kind: "metric"; metric: SampleMetric }
| { kind: "sleep" };
/**
* The cursor's order. Overview first, then the five measured parameters in the
* order the overview lists them, then sleep - so scrolling down walks the
* summary top to bottom and falls off the end into last night, which is where
* the overview's right-hand column already pointed.
*/
export const GLANCE_PAGES: readonly GlancePage[] = [
{ kind: "overview" },
{ kind: "metric", metric: "heartRate" },
{ kind: "metric", metric: "spo2" },
{ kind: "metric", metric: "hrv" },
{ kind: "metric", metric: "steps" },
{ kind: "metric", metric: "calories" },
{ kind: "sleep" },
];
export type GlanceData = {
summary: DailySummary | null;
/** Today's by-hour series, per metric. Only the drill-down pages use it. */
hourly: Partial<Record<SampleMetric, readonly RollupPoint[]>>;
/** Last night as a run of stage blocks, for the sleep detail lanes. */
stageBands: readonly { stage: SleepStageName | null; seconds: number }[];
/** Wall clock, passed in rather than read, so a preview can pin the date. */
nowMs: number;
fixture: boolean;
};
export type GlanceSize = { width: number; height: number };
/** Paint whichever page the cursor is on. */
export function drawGlancePage(
image: GrayImage,
size: GlanceSize,
fonts: GlanceFonts,
page: GlancePage,
data: GlanceData,
): void {
switch (page.kind) {
case "overview":
drawOverview(image, size, fonts, data);
break;
case "metric":
drawMetricDetail(image, size, fonts, page.metric, data);
break;
case "sleep":
drawSleepDetail(image, size, fonts, data);
break;
}
if (data.fixture) drawSampleDataModal(image, size, fonts);
}
/** Keep example measurements unmistakable on every page until live data lands. */
function drawSampleDataModal(image: GrayImage, size: GlanceSize, fonts: GlanceFonts): void {
const title = "Sample data";
const lines = ["These are example measurements.", "No ring measurements saved yet."];
const { small, large } = fonts;
const width = Math.min(size.width - 20,
Math.max(large.measureText(title), ...lines.map((line) => small.measureText(line))) + 40);
const height = large.lineHeight + 2 * lineStep(small) + 40;
const x = Math.round((size.width - width) / 2);
const y = Math.round((size.height - height) / 2);
// Bake before masking so deferred chart labels cannot appear above the box.
image.bakeDeferredDrawsInPlace();
for (let i = 0; i < image.pixels.length; i++) image.pixels[i] = Math.round(image.pixels[i]! * 0.18);
image.fillRoundedRect(x, y, width, height, INK.background, 8);
image.drawRoundedRect(x, y, width, height, INK.title, 8);
image.drawText(large, Math.round((size.width - large.measureText(title)) / 2), y + 14, title, INK.title);
lines.forEach((line, index) => {
image.drawText(small, Math.round((size.width - small.measureText(line)) / 2),
y + 24 + large.lineHeight + index * lineStep(small), line, INK.title);
});
}
// ===========================================================================
// Header and footer, shared by every page
function drawHeader(
image: GrayImage,
size: GlanceSize,
fonts: GlanceFonts,
title: string,
right: string,
): number {
const { small } = fonts;
image.drawText(small, MARGIN, MARGIN, title, INK.title);
drawTextRight(image, small, size.width - MARGIN, MARGIN, right, INK.label);
const bottom = MARGIN + small.lineHeight + 3;
image.drawLine(MARGIN, bottom, size.width - MARGIN, bottom, INK.axis);
return bottom;
}
/**
* The scroll hint.
*
* The hint is not decoration: the drill-down has no on-screen affordance
* otherwise - a page that opens on a scroll looks identical to a page that does
* nothing until you try it.
*/
function drawFooter(
image: GrayImage,
size: GlanceSize,
fonts: GlanceFonts,
hint: string,
): void {
const { small } = fonts;
const y = size.height - small.lineHeight - 2;
image.drawText(small, MARGIN, y, hint, INK.faint);
}
// ===========================================================================
// 1. The overview - a summary, and nothing but
/**
* ⚠ CUT DOWN 2026-09-10 on Chris's review. What left this page and why:
*
* - The heart-rate trace chart. It was filling the left column's spare
* height and it is the single biggest thing on the page; "I think it just
* needs to be a summary".
* - The hypnogram strip under last night's stats, for the same reason.
* - The min/avg/max triple, replaced by range-and-average
* (`rangeAverageText`), which drops the "min / avg / max" legend line that
* existed only to decode the triple.
*
* What arrived: an HRV line, revising the first pass's spec.
*
* The net is that this page is now TEXT ONLY - no charts, no graphics. The
* charts did not die, they moved: the trace is the heart-rate drill-down page
* one scroll away, and the hypnogram became the sleep detail's four lanes.
* That is the actual shape of the revision - the glance got smaller because the
* drill-down gave its contents somewhere better to live.
*/
function drawOverview(
image: GrayImage,
size: GlanceSize,
fonts: GlanceFonts,
data: GlanceData,
): void {
const { small, large } = fonts;
const step = lineStep(small);
const headerBottom = drawHeader(image, size, fonts, "HEALTH", shortDate(data.nowMs));
const summary = data.summary;
if (!summary) {
image.drawText(small, MARGIN, headerBottom + step, "Waiting for ring data...", INK.dim);
drawFooter(image, size, fonts, "");
return;
}
const twoColumn = size.width >= TWO_COLUMN_MIN_WIDTH;
const columnWidth = twoColumn
? Math.floor((size.width - MARGIN * 2 - GUTTER) / 2)
: size.width - MARGIN * 2;
const rightX = twoColumn ? MARGIN + columnWidth + GUTTER : MARGIN;
const top = headerBottom + 6;
const todayBottom = drawTodayColumn(image, summary, {
x: MARGIN,
y: top,
width: columnWidth,
fonts,
step,
});
const nightTop = twoColumn ? top : todayBottom + 8;
const nightBottom = drawNightColumn(image, summary, {
x: rightX,
y: nightTop,
width: columnWidth,
fonts,
step,
});
if (twoColumn) {
// The divider stops at the taller column rather than running to the footer.
// Now that the page is text-only the columns fill about a third of the
// height, and a rule continuing 300px past the last row reads as a drawing
// artefact instead of as structure. It also matters more than it looks: on
// the glasses an unlit pixel is TRANSPARENT, so every line drawn past the
// content is one more thing between the wearer and the world.
const divider = MARGIN + columnWidth + Math.floor(GUTTER / 2);
image.drawLine(divider, top, divider, Math.max(todayBottom, nightBottom), INK.faint);
}
void large;
drawFooter(image, size, fonts, `${GESTURE_SCROLL} detail`);
}
type ColumnLayout = {
x: number;
y: number;
width: number;
fonts: GlanceFonts;
step: number;
};
function drawTodayColumn(image: GrayImage, summary: DailySummary, layout: ColumnLayout): number {
const { x, width, fonts, step } = layout;
const { small, large } = fonts;
let y = layout.y;
image.drawText(small, x, y, "TODAY", INK.label);
y += step;
// Steps get the large font: it is the number a glance is most often for.
const stepsText = summary.steps > 0 ? summary.steps.toLocaleString() : "--";
image.drawText(large, x, y, stepsText, INK.title);
const stepsWidth = large.measureText(stepsText);
image.drawText(
small,
x + stepsWidth + 6,
y + large.lineHeight - small.lineHeight - 1,
"steps",
INK.label,
);
y += large.lineHeight + 4;
const caloriesText = summary.calories > 0 ? `${summary.calories.toLocaleString()} kcal` : "-- kcal";
image.drawText(small, x, y, caloriesText, INK.bar);
y += step + 4;
// Range and average, one line each, no legend line underneath.
const rows: [string, MetricSummary, string][] = [
["HR", summary.heartRate, SAMPLE_METRIC_UNITS.heartRate],
["SpO2", summary.spo2, SAMPLE_METRIC_UNITS.spo2],
["HRV", summary.hrv, SAMPLE_METRIC_UNITS.hrv],
];
for (const [label, metricSummary, unit] of rows) {
image.drawText(small, x, y, label, INK.label);
drawTextRight(image, small, x + width, y, rangeAverageText(metricSummary, unit), INK.line);
y += step;
}
return y;
}
function drawNightColumn(image: GrayImage, summary: DailySummary, layout: ColumnLayout): number {
const { x, width, fonts, step } = layout;
const { small, large } = fonts;
let y = layout.y;
image.drawText(small, x, y, "LAST NIGHT", INK.label);
y += step;
const sleep = summary.sleep;
if (!sleep) {
image.drawText(small, x, y, "No sleep record", INK.dim);
return y + step;
}
image.drawText(large, x, y, formatDuration(sleep.totalSec), INK.title);
y += large.lineHeight + 4;
image.drawText(small, x, y, "Efficiency", INK.label);
drawTextRight(image, small, x + width, y, `${Math.round(sleep.efficiencyPercent)}%`, INK.line);
y += step + 3;
// The three stage shares Chris named, as percentages of time asleep. These
// come from the record's own named totals, so they are unaffected by the
// unconfirmed stage-id mapping the sleep detail's lanes depend on.
const rows: [string, number][] = [
["REM", sleep.remPercent],
["Deep", sleep.deepPercent],
["Light", sleep.lightPercent],
];
for (const [label, percent] of rows) {
image.drawText(small, x, y, label, INK.label);
drawTextRight(image, small, x + width, y, `${Math.round(percent)}%`, INK.line);
y += step;
}
return y;
}
// ===========================================================================
// 4. The drill-down: one parameter, today, by hour
/**
* What the phone's Day view shows for this metric, on the glasses.
*
* The headline repeats the overview's range-and-average line at full size, so
* the page answers the glance's question before the chart is read at all; the
* chart then says WHEN. That ordering is the point of the drill-down - "74 avg"
* and "and it was 130 at five o'clock" are different facts.
*/
function drawMetricDetail(
image: GrayImage,
size: GlanceSize,
fonts: GlanceFonts,
metric: SampleMetric,
data: GlanceData,
): void {
const { small, large } = fonts;
const step = lineStep(small);
const headerBottom = drawHeader(
image,
size,
fonts,
SAMPLE_METRIC_LABELS[metric].toUpperCase(),
"today, by hour",
);
let y = headerBottom + 6;
const summary = summaryFor(metric, data.summary);
const unit = SAMPLE_METRIC_UNITS[metric];
if (isCumulativeMetric(metric)) {
// Steps and calories are totals, not measurements with a spread, so the
// headline is the day's total rather than a range.
const total = metric === "steps" ? data.summary?.steps ?? 0 : data.summary?.calories ?? 0;
const text = total > 0 ? total.toLocaleString() : "--";
image.drawText(large, MARGIN, y, text, INK.title);
const width = large.measureText(text);
if (unit) {
image.drawText(
small,
MARGIN + width + 6,
y + large.lineHeight - small.lineHeight - 1,
unit,
INK.label,
);
}
y += large.lineHeight + 6;
} else {
image.drawText(small, MARGIN, y, rangeAverageText(summary, unit), INK.line);
y += step + 4;
}
const points = data.hourly[metric] ?? [];
const footerHeight = small.lineHeight + 8;
const chartHeight = size.height - y - MARGIN - footerHeight;
if (chartHeight >= 40) {
drawMetricChart(
image,
{ x: MARGIN, y, width: size.width - MARGIN * 2, height: chartHeight },
{
metric,
points,
font: small,
// Just format the hour - `drawMetricChart` already thins labels to
// whatever the column width fits. Thinning here as well multiplies the
// two and leaves a single label at midnight.
xLabel: (point) => `${new Date(point.startMs).getHours()}`,
},
);
}
drawFooter(image, size, fonts, `${GESTURE_SCROLL} ${pageHint(metric)}`);
}
function summaryFor(metric: SampleMetric, summary: DailySummary | null): MetricSummary {
const empty: MetricSummary = { min: 0, max: 0, avg: 0, hasData: false };
if (!summary) return empty;
if (metric === "heartRate") return summary.heartRate;
if (metric === "spo2") return summary.spo2;
if (metric === "hrv") return summary.hrv;
return empty;
}
function isCumulativeMetric(metric: SampleMetric): boolean {
return metric === "steps" || metric === "calories";
}
/** "SpO2 · HRV" - what scrolling either way from here reaches. */
function pageHint(metric: SampleMetric): string {
const index = GLANCE_PAGES.findIndex(
(page) => page.kind === "metric" && page.metric === metric,
);
const previous = GLANCE_PAGES[index - 1];
const next = GLANCE_PAGES[index + 1];
return [pageName(previous), pageName(next)].filter(Boolean).join(" · ");
}
function pageName(page: GlancePage | undefined): string {
if (!page) return "";
if (page.kind === "overview") return "Summary";
if (page.kind === "sleep") return "Sleep";
return SAMPLE_METRIC_SHORT_LABELS[page.metric];
}
// ===========================================================================
// 4b. The drill-down's special case: one night, four lanes
/**
* Sleep's own detail page: the four categories arranged vertically, top to
* bottom as Awake, Light, REM, Deep.
*
* The ordering is Chris's and is deliberately not the week chart's - see
* `drawSleepLanes`, which owns the drawing and carries the reasoning and the
* flagged proportions call.
*
* The unconfirmed-mapping caption rides along because this page IS the
* hypnogram: lanes are the only thing on either surface that depends on the raw
* stage ids, so it is the only place that has to hedge. The overview's
* percentages come from named totals and say so by not carrying this caption.
*/
function drawSleepDetail(
image: GrayImage,
size: GlanceSize,
fonts: GlanceFonts,
data: GlanceData,
): void {
const { small, large } = fonts;
const step = lineStep(small);
const sleep = data.summary?.sleep ?? null;
const headerBottom = drawHeader(image, size, fonts, "SLEEP", "last night");
let y = headerBottom + 6;
if (!sleep) {
image.drawText(small, MARGIN, y, "No sleep record", INK.dim);
drawFooter(image, size, fonts, `${GESTURE_SCROLL} Calories · Summary`);
return;
}
// Total and efficiency on one line, so the lanes get the height.
const totalText = formatDuration(sleep.totalSec);
image.drawText(large, MARGIN, y, totalText, INK.title);
drawTextRight(
image,
small,
size.width - MARGIN,
y + large.lineHeight - small.lineHeight - 1,
`${Math.round(sleep.efficiencyPercent)}% efficiency`,
INK.label,
);
y += large.lineHeight + 6;
const footerHeight = small.lineHeight + 8;
const captionHeight = step;
const laneHeight = size.height - y - MARGIN - footerHeight - captionHeight;
if (laneHeight >= 40) {
drawSleepLanes(
image,
{ x: MARGIN, y, width: size.width - MARGIN * 2, height: laneHeight },
{
bands: data.stageBands,
font: small,
laneText: (stage) => ({
label: stageLabel(stage),
value: formatDuration(stageSeconds(stage, sleep)),
}),
},
);
y += laneHeight;
}
image.drawText(small, MARGIN, y, hypnogramCaptionShort(), INK.faint);
drawFooter(image, size, fonts, `${GESTURE_SCROLL} Calories · Summary`);
}
+311
View File
@@ -0,0 +1,311 @@
/**
* Wire records -> stored samples. The one place that knows what the ring's
* decoded records mean in wall-clock terms.
*
* ## This is written but NOT wired up, on purpose
*
* The live BLE path lives on the `ring-health-protocol` branch, which this one
* deliberately does not touch. What is here is the whole conversion - the part
* with the judgement calls in it - written against a structural description of
* `RingProtocol.kt`'s record types rather than an import of them, so that
* branch and this one can be joined later without either having been built
* around the other.
*
* ## WHERE THE LIVE WIRING GOES - the follow-up, in full
*
* ⚠ HISTORICAL. This section is the plan, and it has since been built:
* `health-live.ts` is the caller. One detail of it is now WRONG - the live path
* must NOT use `getRingHealthRecords()`, which is a pure copy and left the
* Java-side buffer growing forever. It uses `takeRingHealthBatch()` and hands
* the records back with `clearRingHealthRecordsBelow()` once the store write
* has succeeded. Kept below for the reasoning, not as instructions.
*
* `FaceclawBleCommunicator` already accumulates decoded records into a capped
* in-memory list with a `getRingHealthRecords()` getter (implement-return,
* section 2). The bridge already exposes the native object to TypeScript:
* `FaceclawCommunicatorBridge.getNativeCommunicator()`. So the follow-up is:
*
* 1. In `dashboard-controller.ts`, after `connect()` succeeds, poll
* `communicator.getNativeCommunicator().getRingHealthRecords()` on the
* same 30-minute cadence the Java side already throttles health pulls to.
* 2. Map each Java record onto the `Wire*` shapes below - a field-for-field
* copy; the names were chosen to match.
* 3. Hand the result to `convertRecords()` and pass its `samples`/`sleep`
* straight to `healthStore().ingestSamples()` / `.ingestSleep()`.
*
* Doing it as a poll rather than a callback is what keeps it a small change:
* adding a method to `FaceclawBleCommunicatorListener` forces an edit on every
* implementer, which is exactly the reasoning that put the records in a getter
* in the first place.
*
* A note for whoever does it: ingest is idempotent (`HealthStore` dedupes on
* metric + bucket start), so re-reading the same capped list every poll is
* correct and costs one no-op per record. Do NOT drain the list on read - it
* is the only copy until this store has written it.
*
* No NativeScript imports here, so it runs under plain node in `tests/`.
*/
import {
HOUR_MS,
TEN_MINUTES_MS,
type HealthSample,
type SleepSession,
type SleepSegment,
startOfLocalDay,
} from "./health-types";
/** `RingProtocol.HourlyRecord`, for heart rate (`01:01`), SpO2 (`02:01`), HRV (`04:01`). */
export type WireHourlyRecord = {
kind: "hourly";
metric: "heartRate" | "spo2" | "hrv";
/**
* Absolute local ms the page's group index 0 refers to, from the record's
* own six-byte ANCHOR field, or null on a backlog page that carried six
* zero bytes instead.
*/
anchorMs: number | null;
groups: readonly { hourIndex: number; avg: number; max: number; min: number }[];
};
/** `RingProtocol.StepsRecord` (`05:01`). */
export type WireStepsRecord = {
kind: "steps";
/** The day anchor. Steps pages always carried one in the capture. */
anchorMs: number | null;
/** Raw buckets. `index` is the ring's own, whose meaning is NOT known. */
buckets: readonly { index: number; steps: number; activeCalories: number; totalCalories: number }[];
};
/** `RingProtocol.SleepRecord` (`06:01`). */
export type WireSleepRecord = {
kind: "sleep";
/**
* The ring's own `start_ts`/`end_ts`, in seconds.
*
* These were documented here as "ring-relative seconds - NOT Unix time",
* because nothing in the offline capture proved otherwise. The first real
* record off the hardware (2026-09-12) falsified that: `start_ts` decodes to
* a plain Unix timestamp kept on the RING'S clock, which runs ahead of real
* time. `clockCorrectionMs` is how a caller says by how much.
*
* Left as raw seconds here rather than corrected upstream so a caller with
* no correction to offer (an offline capture, a fixture) still gets the old,
* honestly-unresolved behaviour instead of a confidently wrong date.
*/
startTs: number;
endTs: number;
totalSec: number;
wakeSec: number;
remSec: number;
lightSec: number;
deepSec: number;
segments: readonly SleepSegment[];
/** Wall-clock ms the record was received; the only real time in it. */
receivedAtMs: number;
/**
* How far AHEAD of real wall-clock time `startTs`/`endTs` run, in ms, or
* omitted when the caller cannot say. Supplying it is what promotes the
* session from `timeResolved: false` to a real placement - see
* `convertSleep`. The value itself is the producer's problem, not this
* module's: see `sleepClockCorrectionMs` in `health-live.ts`.
*/
clockCorrectionMs?: number;
};
export type WireRecord = WireHourlyRecord | WireStepsRecord | WireSleepRecord;
export type ConversionResult = {
samples: HealthSample[];
sleep: SleepSession[];
/** Every record or group deliberately not stored, with the reason. */
skipped: { what: string; why: string }[];
};
export function convertRecords(records: readonly WireRecord[]): ConversionResult {
const result: ConversionResult = { samples: [], sleep: [], skipped: [] };
for (const record of records) {
if (record.kind === "hourly") convertHourly(record, result);
else if (record.kind === "steps") convertSteps(record, result);
else convertSleep(record, result);
}
return result;
}
/**
* Hourly pages. An ANCHORED page dates itself exactly: group `i` is
* `anchor + i hours`, which the decode verified against every group that had a
* row to check against.
*
* An UNANCHORED (backlog) page is dropped rather than placed. The decode did
* solve where one such page landed, but explicitly could not derive the rule
* that produced it and warned that a future page anchored elsewhere would
* break it. `RingProtocol.kt` already made the matching call - it hands
* backlog groups out with `UNKNOWN_TIME` rather than an invented time - and a
* health chart is exactly the wrong place to be the first component that
* guesses. Dropping loses a page; guessing corrupts the history silently.
*/
function convertHourly(record: WireHourlyRecord, result: ConversionResult): void {
if (record.anchorMs === null) {
result.skipped.push({
what: `${record.metric} page, ${record.groups.length} groups`,
why: "backlog page with no anchor - no verified rule for dating it",
});
return;
}
for (const group of record.groups) {
const startMs = record.anchorMs + group.hourIndex * HOUR_MS;
result.samples.push({
metric: record.metric,
startMs,
spanMs: HOUR_MS,
min: group.min,
max: group.max,
avg: group.avg,
total: group.avg,
});
}
}
/**
* Steps and calories, at TEN-MINUTE resolution.
*
* ## The index is cracked (2026-09-12)
*
* This used to emit one day-span sample holding the day's total, because the
* bucket index was only trusted as an identity, not as a time. It now resolves:
* **bucket `i` starts at `anchor + i * 10 minutes`**, with the anchor read
* offset-corrected like every other record type.
*
* Confirmed twice. The decisive check: a live ledger held 25 contiguous buckets
* (1-25) under a corrected anchor of 20:00, while the file's mtime was 00:18
* local - and `20:00 + 25 * 10min` is 00:10-00:20, which is the window that was
* actually being filled. The older "index runs 0-34 then jumps to 130-132"
* observation came from an offline capture spanning more than one ring-day;
* indices are per-record and contiguous within one.
*
* ## What this changes downstream
*
* The day total is no longer readable off any field of a day's rollup - it is
* `sum`, and only `sum`, because `count` is now ~144 rather than 1. Checked on
* 2026-09-12: every steps/calories reader already uses the summing path
* (`dailySummary` -> `sumOf` -> `sample.total`; `rollupSeries` -> `rollupOf` ->
* `sum`; the phone view model's steps branch reads `point.sum`), so nothing had
* to change for this. Do not add a reader that takes `max` or `avg` for a step
* total.
*
* A ring-day starts at 20:00 local (the ring's clock runs 4h fast, so its
* midnight is our 20:00), which means one record's buckets straddle two
* calendar days. That is correct and is the reason the day figure moves when
* this lands: the evening buckets stop being filed under tomorrow.
*/
function convertSteps(record: WireStepsRecord, result: ConversionResult): void {
if (record.anchorMs === null) {
result.skipped.push({
what: `steps page, ${record.buckets.length} buckets`,
why: "no anchor - cannot date the buckets",
});
return;
}
const anchorMs = record.anchorMs;
for (const bucket of record.buckets) {
const startMs = anchorMs + bucket.index * TEN_MINUTES_MS;
result.samples.push({
metric: "steps",
startMs,
spanMs: TEN_MINUTES_MS,
min: bucket.steps,
max: bucket.steps,
avg: bucket.steps,
total: bucket.steps,
});
result.samples.push({
metric: "calories",
startMs,
spanMs: TEN_MINUTES_MS,
min: bucket.totalCalories,
max: bucket.totalCalories,
avg: bucket.totalCalories,
total: bucket.totalCalories,
});
}
}
/**
* Sleep sessions.
*
* The durations are exact and need no anchoring - they come from named byte
* offsets and the decode reproduced a whole exported row from them. The
* SESSION TIME is the problem: `start_ts`/`end_ts` are ring-relative seconds,
* nothing in the record carries an absolute date, and the two unidentified
* fields that might have carried one were not cracked. Even's own app gets
* this wrong - one exported row is stamped 1979.
*
* RESOLVED, 2026-09-12, by the first real record off the hardware rather than
* by cracking `pay[3:9]`: `start_ts` is already a Unix timestamp, just kept on
* the ring's own clock. A caller that knows how far that clock runs ahead
* passes `clockCorrectionMs` and gets a genuinely placed session.
*
* ⚠ THE OLD FLAGGED GUESS SURVIVES for callers that do NOT pass it (offline
* captures, fixtures): the session is attributed to the local day it was
* RECEIVED on and `timeResolved` is false to say so. That guess is made rather
* than avoided because "last night's sleep" is half of what the glasses glance
* is for, and a record with no day at all cannot appear there. It is right
* whenever the ring is synced the same day it is worn and wrong for a backlog
* session pulled days later - which is why the UI never prints a date for an
* unresolved session, only "last night", and shows the unresolved marker.
*/
function convertSleep(record: WireSleepRecord, result: ConversionResult): void {
const durationSec = Math.max(0, record.endTs - record.startTs);
const common = {
totalSec: record.totalSec,
wakeSec: record.wakeSec,
remSec: record.remSec,
lightSec: record.lightSec,
deepSec: record.deepSec,
segments: record.segments,
};
if (typeof record.clockCorrectionMs === "number") {
const startMs = record.startTs * 1000 - record.clockCorrectionMs;
const endMs = (record.startTs + durationSec) * 1000 - record.clockCorrectionMs;
result.sleep.push({
// The WAKE-UP day, which is what `dailySummary` looks a night up by, and
// what the old receivedAtMs guess was approximating. Taken from the end
// of the session so a night that starts before midnight still belongs to
// the morning it ends on.
dayStartMs: startOfLocalDay(endMs),
startMs,
endMs,
...common,
timeResolved: true,
});
return;
}
result.sleep.push({
dayStartMs: startOfLocalDay(record.receivedAtMs),
// Raw seconds are kept as-is so the pair still describes the night's
// length and ordering; `timeResolved` is what says not to read them as
// wall-clock time.
startMs: record.startTs * 1000,
endMs: (record.startTs + durationSec) * 1000,
...common,
timeResolved: false,
});
}
/**
* The consistency check the decode found holds on every real record: the
* segment run must account for exactly the time in bed. Worth running on
* ingest - a record that fails it is a decode fault, not a strange night.
*/
export function sleepIdentityHolds(record: {
totalSec: number;
wakeSec: number;
segments: readonly SleepSegment[];
}): boolean {
let half = 0;
for (const segment of record.segments) half += segment.halfMinutes;
return half * 30 === record.totalSec + record.wakeSec;
}
+639
View File
@@ -0,0 +1,639 @@
/**
* Live ring → store. The producer side of `health-ingest.ts`.
*
* `health-ingest.ts` was built with a complete wire→domain conversion and no
* caller; this is the caller. It reads whatever `FaceclawBleCommunicator` has
* decoded off the ring this session, marshals the Java records into the
* `WireRecord` shapes that module already expects, and writes the result
* through the store's own deduping ingest.
*
* Three things worth knowing:
*
* 1. **It pulls, it does not subscribe, and it CONSUMES.** There is no push
* event for health records, so both surfaces call this when they open and on
* their existing refresh tick. `takeRingHealthBatch()` hands over what the
* communicator is holding together with a watermark, and once the store
* write has succeeded `clearRingHealthRecordsBelow()` hands that much back
* as consumed. Cut and paste, not copy paste.
*
* It used to be a pure copy, and nothing ever cleared the Java-side list, so
* every 60s tick re-processed the whole session's history. Measured
* 2026-09-12: `samples-2026-09.jsonl` grew 22,505 -> 28,552 lines in eight
* hours, the buffer climbing 12 -> 24 records and samples-written-per-cycle
* 8 -> 14. The store's dedupe kept the DATA right the whole time; it was the
* work and the file that grew without bound.
*
* 2. **Fixtures are purged, not just unlabelled, before the first real write.**
* `clearFixtureMarker()` only drops the badge; the 45 days of generated
* samples would stay in the store and become indistinguishable from real
* data the moment the badge went away. That is precisely the artefact
* `health-seed.ts`' own header warns about, so the first genuine record
* wipes the store files outright.
*
* 3. **Records the decode could not date are dropped, not placed.**
* `RingProtocol` hands out `UNKNOWN_TIME` (-1) for an unanchored backlog
* page rather than inventing a time; that maps to `anchorMs: null` here and
* `convertRecords` skips it with a reason. Do not "fix" this by substituting
* now() — a health chart is the wrong place to guess a timestamp.
*/
import {
convertRecords,
type WireHourlyRecord,
type WireRecord,
type WireSleepRecord,
type WireStepsRecord,
} from "./health-ingest";
import { markLiveData, purgeFixtureData } from "./health-seed";
import { checkedFileOperation, healthStore } from "./health-store-files";
import { startOfLocalDay, type SleepSegment } from "./health-types";
import { File, knownFolders } from "@nativescript/core";
/** `RingProtocol.UNKNOWN_TIME` — the decoder's "I will not guess" sentinel. */
const UNKNOWN_TIME = -1;
/** `RingProtocol.CMD_HI_*`. */
const CMD_HEART_RATE = 0x01;
const CMD_SPO2 = 0x02;
const CMD_HRV = 0x04;
const CMD_STEPS = 0x05;
const CMD_SLEEP = 0x06;
/** `SleepRecord.recordState`: 2 is the empty end-of-list marker, not a night. */
const SLEEP_STATE_EMPTY = 2;
const HOURLY_METRIC: { [cmdHi: number]: WireHourlyRecord["metric"] } = {
[CMD_HEART_RATE]: "heartRate",
[CMD_SPO2]: "spo2",
[CMD_HRV]: "hrv",
};
function activeCommunicator(): any {
try {
return (com as any).faceclaw.app.FaceclawBleCommunicator.getActive() ?? null;
} catch {
return null;
}
}
/**
* Legacy compensation for the incorrect extra timezone shift sent by the
* handshake. This is not a ring protocol requirement. Fresh HR timestamps on
* the PDT test ring run seven hours ahead, but older values and daily anchors
* do not share that shift. Keep this paired with the existing handshake until
* a controlled UTC migration; do not apply it retrospectively to raw history.
* See notes/ring-health-live-validation.md.
*/
function ringClockOffsetMs(atMs: number): number {
return new Date(atMs).getTimezoneOffset() * 60 * 1000;
}
/**
* Inherited sleep-specific heuristic, still unvalidated on this ring (no sleep
* DATA page received yet). Firmware describes UTC timestamps, not a double
* timezone offset. Remove alongside the controlled clock migration, then
* validate against a recorded night; it is not evidence of correct placement.
*/
function sleepClockOffsetMs(atMs: number): number {
return 2 * ringClockOffsetMs(atMs);
}
function anchorToMs(anchorUnixSeconds: number, applyClockOffset: boolean): number | null {
if (anchorUnixSeconds === UNKNOWN_TIME) return null;
const ms = anchorUnixSeconds * 1000;
return applyClockOffset ? ms - ringClockOffsetMs(ms) : ms;
}
/**
* Per-day step-bucket ledger.
*
* **Why this has to exist.** The ring does not resend the whole day: a pull
* delivers only the buckets new since the last successful one, the same
* watermark model every other record type uses. Measured 2026-09-11:
* 25 buckets / 222 steps, then 3 / 0, then 2 / 0, then 2 / 70. A cumulative
* day total cannot go 222 → 0 → 70.
*
* `convertSteps()` sums the buckets it is handed and emits that as the day's
* total, which was right for the offline captures it was written against —
* there, one sync carried everything. Live, it means each pull overwrites the
* day with just that pull's increment, so the step count reads as "since the
* last pull" and lurches downward. So this keeps the day's buckets and hands
* `convertSteps()` the accumulated set, leaving that function pure.
*
* **Merge is max-by-index, not addition and not last-write-wins.** A bucket is
* a time window's own total, so a window redelivered later carries a larger
* value, not an increment to add — addition would double-count every open
* window. Taking the max rather than the last value makes the merge
* ORDER-INDEPENDENT, which matters because a single sync pass merges several
* records that overlap: measured 2026-09-12, four steps records in one pass
* agreed on every bucket's step count but disagreed on its calorie fields, so
* last-write-wins made the day's calorie total ping-pong 643 ↔ 671 forever,
* appending two lines to the sample shard every cycle. Max is consistent with
* the documented model (a window's total only grows as it fills) and settles.
*
* **The ledger holds MANY days, not one.** It used to hold exactly one, and
* kept it only while the incoming day matched — so the moment a record from
* another ring-day arrived, the whole accumulated day was discarded and
* rebuilt from that one pull. With `syncLiveRecords()` re-processing the
* communicator's entire record history every 60s, that produced a repeating
* cycle of partial sums, each written to the store as a genuine day total
* (measured: a 12-state cycle, repeated 132 times, 22k lines in a day).
* Holding every day makes the replay idempotent instead of destructive — and
* no theory about WHY records replay is needed for that to hold.
*
* The day key is `startOfLocalDay(corrected anchor)`, which is the ring's own
* day start, not calendar midnight — the ring's day begins at 20:00 local
* because its clock runs 4h fast. That is fine: the key is an identity, and
* the per-bucket timestamps carry the real wall-clock placement.
*/
type StepDayBuckets = { [index: string]: { steps: number; active: number; total: number } };
type StepBucketLedger = {
/** `dayStartMs` (as a string key) -> that day's buckets. */
days: { [dayStartMs: string]: StepDayBuckets };
};
/** The pre-2026-09-12 single-day shape, migrated on read rather than dropped. */
type LegacyStepBucketLedger = { dayStartMs: number; buckets: StepDayBuckets };
/** How many ring-days to keep. Enough for a weekly chart, bounded on disk. */
const LEDGER_DAYS_KEPT = 7;
function ledgerPath(): string {
return `${knownFolders.documents().getFolder("health").path}/steps-ledger.json`;
}
function readLedger(): StepBucketLedger | null {
try {
if (!File.exists(ledgerPath())) return null;
const parsed = JSON.parse(File.fromPath(ledgerPath()).readTextSync()) as
| StepBucketLedger
| LegacyStepBucketLedger;
if (parsed && (parsed as StepBucketLedger).days) return parsed as StepBucketLedger;
// Migrate the single-day shape rather than discarding it: the file on the
// phone holds real step data the ring may not re-deliver.
//
// ⚠ RE-KEY IT. The legacy `dayStartMs` was `startOfLocalDay(RAW anchor)`,
// computed before the anchor was offset-corrected, so carrying it across
// verbatim files the day 4h too late — under a key the corrected code will
// never write to again. The accumulated buckets would sit there stranded
// while the same ring-day restarted empty beside them. Measured doing
// exactly that on 2026-09-12: a ledger with "2 days" that were one day.
const legacy = parsed as LegacyStepBucketLedger;
if (typeof legacy?.dayStartMs === "number" && legacy.buckets) {
const corrected = legacy.dayStartMs - ringClockOffsetMs(legacy.dayStartMs);
return { days: { [String(startOfLocalDay(corrected))]: legacy.buckets } };
}
return null;
} catch {
return null;
}
}
/** Keep the ledger bounded. Newest `LEDGER_DAYS_KEPT` days survive. */
function pruneLedger(ledger: StepBucketLedger): void {
const keys = Object.keys(ledger.days).sort((a, b) => Number(b) - Number(a));
for (const key of keys.slice(LEDGER_DAYS_KEPT)) delete ledger.days[key];
}
function writeLedger(ledger: StepBucketLedger): void {
try {
File.fromPath(ledgerPath()).writeTextSync(JSON.stringify(ledger));
} catch (error) {
console.warn("health live: steps ledger write failed", error);
}
}
/** Merge this pull's buckets into that ring-day's ledger and return its full set. */
function accumulateStepBuckets(
dayStartMs: number,
delivered: readonly { index: number; steps: number; activeCalories: number; totalCalories: number }[],
): { index: number; steps: number; activeCalories: number; totalCalories: number }[] {
const ledger: StepBucketLedger = readLedger() ?? { days: {} };
const dayKey = String(dayStartMs);
const day: StepDayBuckets = ledger.days[dayKey] ?? {};
ledger.days[dayKey] = day;
for (const bucket of delivered) {
const existing = day[String(bucket.index)];
// Max, not overwrite — see the type's header. Keeps the merge order-independent.
day[String(bucket.index)] = {
steps: Math.max(existing?.steps ?? 0, bucket.steps),
active: Math.max(existing?.active ?? 0, bucket.activeCalories),
total: Math.max(existing?.total ?? 0, bucket.totalCalories),
};
}
pruneLedger(ledger);
writeLedger(ledger);
const merged = Object.keys(day).map((key) => ({
index: Number(key),
steps: day[key]!.steps,
activeCalories: day[key]!.active,
totalCalories: day[key]!.total,
}));
const steps = merged.reduce((acc, b) => acc + b.steps, 0);
const calories = merged.reduce((acc, b) => acc + b.totalCalories, 0);
console.log(
`health live: steps ledger +${delivered.length} delivered -> ${merged.length} buckets held ` +
`for ring-day ${new Date(dayStartMs).toISOString()}, ${steps} steps / ${calories} cal, ` +
`${Object.keys(ledger.days).length} days in ledger`,
);
return merged;
}
function toWire(record: any): WireRecord | null {
const cmdHi = Number(record.cmdHi);
const metric = HOURLY_METRIC[cmdHi];
if (metric) {
const groups: { hourIndex: number; avg: number; max: number; min: number }[] = [];
const raw = record.groups;
for (let i = 0; i < raw.length; i++) {
const group = raw[i];
groups.push({
hourIndex: Number(group.hourIndex),
avg: Number(group.avg),
max: Number(group.max),
min: Number(group.min),
});
}
return { kind: "hourly", metric, anchorMs: anchorToMs(Number(record.anchorUnixSeconds), true), groups };
}
if (cmdHi === CMD_STEPS) {
const buckets: { index: number; steps: number; activeCalories: number; totalCalories: number }[] = [];
const raw = record.buckets;
for (let i = 0; i < raw.length; i++) {
const bucket = raw[i];
buckets.push({
index: Number(bucket.index),
steps: Number(bucket.steps),
// UNVERIFIED MAPPING. The decode never resolved which of the record's
// two calorie-like fields is active vs total burn, which is why the
// Java side names them calorieLike2/calorieLike3 rather than committing.
// convertSteps() sums totalCalories, so if the daily calorie figure
// reads wrong against Even's own export, swap these two — that is the
// whole fix, and it is the only thing here resting on a guess.
activeCalories: Number(bucket.calorieLike2),
totalCalories: Number(bucket.calorieLike3),
});
}
// Offset-corrected like every other record type, as of 2026-09-12.
//
// This used to pass `false`, and the reasoning was that flooring the raw
// anchor to the local day "absorbed" the 4h shift and landed on the right
// date, where subtracting would push the day boundary back to 20:00 the
// previous evening. That was solving the wrong problem. The anchor was
// being asked to carry the DATE LABEL for a single day-blob sample, so it
// had to be bent until the label came out right.
//
// With the bucket index cracked (bucket i starts at anchor + i*10min), the
// anchor no longer carries a date at all — it is the true start instant of
// bucket 0, and each bucket now dates itself. So the anchor must simply be
// correct, and correct means offset-corrected: measured 2026-09-12 00:36,
// the raw anchor read 00:00 today while the record's own 25 buckets place
// the series start at 20:00 the previous evening, which is exactly the 4h.
//
// The ring's day really does begin at 20:00 local, because its clock runs
// 4h fast and its day starts at ITS midnight. A ring-day therefore straddles
// two calendar days, and the buckets land on whichever real day they fall
// in — which is the point.
const anchorMs = anchorToMs(Number(record.anchorUnixSeconds), true);
if (anchorMs === null) return { kind: "steps", anchorMs: null, buckets };
// Hand convertSteps() the whole day, not just this pull's increment.
const accumulated = accumulateStepBuckets(startOfLocalDay(anchorMs), buckets);
return { kind: "steps", anchorMs, buckets: accumulated };
}
if (cmdHi === CMD_SLEEP) {
if (Number(record.recordState) === SLEEP_STATE_EMPTY) return null;
const segments: SleepSegment[] = [];
const raw = record.segments;
for (let i = 0; i < raw.length; i++) {
const segment = raw[i];
// Java calls it `stage`, the domain type calls it `stageId` - both are
// the same raw 0-3 ring id, deliberately unresolved here (see sleep-stages.ts).
segments.push({ stageId: Number(segment.stage), halfMinutes: Number(segment.halfMinutes) });
}
const startTs = Number(record.startTs);
const endTs = Number(record.endTs);
const correction = sleepClockOffsetMs(startTs * 1000);
// The assertion log for the -8h correction. One sleep record a night makes
// this cheap, and a wrong clock frame is otherwise invisible until someone
// reads a chart and disbelieves it.
console.log(
`health live: sleep raw ${new Date(startTs * 1000).toString()} -> corrected ` +
`${new Date(startTs * 1000 - correction).toString()} .. ` +
`${new Date(endTs * 1000 - correction).toString()} (-${correction / 3600000}h)`,
);
return {
kind: "sleep",
startTs,
endTs,
clockCorrectionMs: correction,
totalSec: Number(record.totalTime),
wakeSec: Number(record.wakeTime),
remSec: Number(record.remTime),
lightSec: Number(record.lightTime),
deepSec: Number(record.deepTime),
segments,
receivedAtMs: Number(record.receivedAtMs),
};
}
return null;
}
export type LiveSyncResult = {
/** Records the communicator was holding. 0 means no pull has landed yet. */
seen: number;
/** Samples genuinely new to the store. */
samplesWritten: number;
/** Sleep sessions genuinely new to the store. */
sleepWritten: number;
/** Conversions deliberately declined, with reasons, from `convertRecords`. */
skipped: { what: string; why: string }[];
};
const EMPTY: LiveSyncResult = { seen: 0, samplesWritten: 0, sleepWritten: 0, skipped: [] };
/**
* Read the communicator's decoded records into the durable store.
*
* Safe to call on every open and every refresh: the store dedupes, and an
* absent communicator (no glasses process, preview build) is a no-op rather
* than an error.
*/
/**
* Tell the communicator the snapshot is durably stored and may be dropped.
*
* Deliberately swallows its own failure: a clear that does not happen costs a
* little growth, and there is nothing useful to do about it here. The bias runs
* one way throughout - under-clearing is cheap, over-clearing loses data.
*/
function consumeUpTo(communicator: any, watermark: number): void {
try {
const dropped = Number(communicator.clearRingHealthRecordsBelow(watermark));
if (dropped > 0) {
console.log(`health live: consumed ${dropped} records (watermark ${watermark})`);
}
} catch (error) {
console.warn("health live: could not clear consumed records", error);
}
}
/** The communicator's `java.util.List` of `RingProtocol.HealthRecord`s. */
type JavaRecordList = { size(): number; get(index: number): any };
type StoreResult = Omit<LiveSyncResult, "seen">;
/**
* Convert decoded records and store them durably. Throws if a store write
* fails, so the caller keeps whatever it would otherwise mark as consumed.
* Shared by the live batch and the journal replay.
*/
function storeRecords(records: JavaRecordList): StoreResult {
const wire: WireRecord[] = [];
const size = records.size();
for (let i = 0; i < size; i++) {
try {
const converted = toWire(records.get(i));
if (converted) wire.push(converted);
} catch (error) {
console.warn("health live: skipped an undecodable record", error);
}
}
if (wire.length === 0) return { samplesWritten: 0, sleepWritten: 0, skipped: [] };
const { samples, sleep, skipped } = convertRecords(wire);
if (samples.length === 0 && sleep.length === 0) {
return { samplesWritten: 0, sleepWritten: 0, skipped };
}
// First real data wins the store outright — see the header.
purgeFixtureData();
const store = healthStore();
const samplesWritten = store.ingestSamples(samples);
const sleepWritten = store.ingestSleep(sleep);
// Also mark on a retry whose samples were already appended before a later
// write failed. Otherwise opening Health could seed fixtures over real data.
markLiveData();
return { samplesWritten, sleepWritten, skipped };
}
/**
* Bump when the Kotlin decoders learn a layout they used to reject. The
* replay cursor records the version it ran under, and a cursor from an older
* decoder replays the whole journal: the frames it skipped are only on disk.
*
* 2: R1 firmware 2.3.x's four-byte page trailer (2026-11-01). Before it,
* every page that firmware sent was journaled, acknowledged and dropped.
*/
const JOURNAL_DECODER_VERSION = 2;
type ReplayCursor = { version: number; throughReceivedAtMs: number };
function healthFilePath(name: string): string {
return `${knownFolders.documents().getFolder("health").path}/${name}`;
}
function readReplayCursor(): ReplayCursor | null {
try {
const path = healthFilePath("journal-replay.json");
if (!File.exists(path)) return null;
const parsed = JSON.parse(File.fromPath(path).readTextSync()) as ReplayCursor;
return typeof parsed?.version === "number" && typeof parsed.throughReceivedAtMs === "number" ? parsed : null;
} catch {
return null;
}
}
let journalReplayed = false;
/**
* Store the health pages in the communicator's frame journal
* (`ring-frames.jsonl`, written before each page is acknowledged) that have
* not been replayed under the current decoder. Once per process, before any
* live batch, so pages land oldest first and a newer live value is never
* overwritten by an older replayed one.
*
* The ring counts an acknowledged page as synced and does not send it again,
* so a page the decoder could not read at the time exists nowhere else. The
* store and the steps ledger are idempotent, so re-storing a page that was
* already ingested live is a no-op.
*/
function replayFrameJournalOnce(): void {
if (journalReplayed) return;
let ringProtocol: any;
try {
ringProtocol = (com as any).faceclaw.app.RingProtocol;
} catch {
ringProtocol = null;
}
const journalPath = healthFilePath("ring-frames.jsonl");
if (!ringProtocol || !File.exists(journalPath)) {
journalReplayed = true;
return;
}
const cursor = readReplayCursor();
const after = cursor?.version === JOURNAL_DECODER_VERSION ? cursor.throughReceivedAtMs : 0;
const records: JavaRecordList = ringProtocol.decodeFrameJournal(File.fromPath(journalPath).readTextSync(), after);
const size = records.size();
if (size > 0) {
const result = storeRecords(records);
let through = after;
for (let i = 0; i < size; i++) through = Math.max(through, Number(records.get(i).receivedAtMs));
const next: ReplayCursor = { version: JOURNAL_DECODER_VERSION, throughReceivedAtMs: through };
checkedFileOperation((onError) =>
File.fromPath(healthFilePath("journal-replay.json")).writeTextSync(JSON.stringify(next), onError),
);
console.log(
`health live: replayed ${size} journaled pages -> ${result.samplesWritten} samples, ` +
`${result.sleepWritten} sleep` + (result.skipped.length ? `, ${result.skipped.length} skipped` : ""),
);
}
journalReplayed = true;
}
export function syncLiveRecords(): LiveSyncResult {
try {
replayFrameJournalOnce();
} catch (error) {
// Not marked done: the next sync retries it, ahead of the live batch.
console.warn("health live: frame journal replay failed", error);
}
const communicator = activeCommunicator();
if (!communicator) return EMPTY;
let batch: any;
try {
batch = communicator.takeRingHealthBatch();
} catch (error) {
console.warn("health live: could not read ring records", error);
return EMPTY;
}
if (!batch) return EMPTY;
const records = batch.getRecords();
// Identifies exactly this snapshot. Anything the ring pushes from here on is
// numbered above it and therefore cannot be cleared by this pass - which is
// what keeps a page landing mid-ingest from being dropped.
const watermark = Number(batch.getWatermark());
if (!records || !records.size || records.size() === 0) return EMPTY;
const size = records.size();
const { samplesWritten, sleepWritten, skipped } = storeRecords(records);
// ONLY here. Both store writes have returned, so the records are durable.
// If either threw, or the process died above this line, nothing is cleared
// and the same records arrive again next tick - which costs one repeated
// ingest (a no-op, the store refuses identical re-writes) instead of losing
// a night. Note `samplesWritten === 0` is NOT a failure: it means the store
// already held all of it, which is the steady state this change creates.
// Records that converted to nothing are consumed too: holding them would
// only re-run the same conversion every tick.
consumeUpTo(communicator, watermark);
console.log(
`health live: ${size} records -> ${samplesWritten} samples, ${sleepWritten} sleep` +
(skipped.length ? `, ${skipped.length} skipped` : ""),
);
return { seen: size, samplesWritten, sleepWritten, skipped };
}
/**
* Ask the ring for a fresh pull now, rather than waiting out the automatic
* 30-minute cycle. Returns immediately; the pull itself takes ~15s on the
* communicator's worker thread and lands through the next `syncLiveRecords()`.
*
* Throttled communicator-side to one a minute — see
* `requestRingHealthNow()`. Calling it on every open is fine.
*/
export function requestFreshPull(): void {
const communicator = activeCommunicator();
if (!communicator) return;
try {
communicator.requestRingHealthNow();
} catch (error) {
console.warn("health live: on-demand pull request failed", error);
}
}
/**
* Keep decoded records reaching disk whether or not a surface is open.
*
* Without this, records live only in the communicator's memory until the
* health app or phone page is opened, so a pull that lands while both are
* closed is lost if the process restarts first. The store dedupes, so this is
* a no-op whenever there is nothing new.
*
* Called once from `app.ts`. Idempotent.
*/
const BACKGROUND_SYNC_INTERVAL_MS = 60 * 1000;
let backgroundSyncTimer: ReturnType<typeof setInterval> | null = null;
export function startLiveHealthSync(): void {
if (backgroundSyncTimer) return;
backgroundSyncTimer = setInterval(() => {
try {
syncLiveRecords();
} catch (error) {
console.warn("health live: background sync failed", error);
}
}, BACKGROUND_SYNC_INTERVAL_MS);
}
/**
* Pull the ring on a wall-clock-aligned cadence: :01 and :31, every hour.
*
* Chris, 2026-09-12: *"I think we should be polling the ring on the 30 minute
* cycle (that was my intent, not a floor honestly)."* The 30-minute value in
* `RING_HEALTH_MIN_PULL_INTERVAL_MS` was always meant as a collection rhythm
* and got built as a throttle, so a connected, stable ring pulled never —
* nothing in the system drives a pull on a timer at all.
*
* Two reasons this is aligned to the wall clock rather than a plain interval:
*
* 1. **The ring's own step buckets close on 10-minute boundaries.** Pulling on
* the boundary collects a just-closed bucket instead of a half-formed one.
* 2. **An elapsed timer drifts.** A pull at :07 sets the next at :37, then :07,
* wandering away from the boundary it is supposed to track. Re-arming
* against the clock each time cannot drift.
*
* The **one-minute offset is deliberate**: firing exactly at :00 risks catching
* the ring before it has finalised that bucket.
*
* This only *requests* a pull. The communicator still applies its own anti-spam
* floor, so an extra call here can never hammer the ring.
*/
const ALIGNED_PULL_MINUTES = [1, 31];
let alignedPullTimer: ReturnType<typeof setTimeout> | null = null;
function msUntilNextAlignedPull(now: Date): number {
const minutes = now.getMinutes();
const withinHour = ALIGNED_PULL_MINUTES.filter((m) => m > minutes);
// Next slot this hour, or the first slot of the next hour.
const target = withinHour.length ? withinHour[0] : ALIGNED_PULL_MINUTES[0] + 60;
const msIntoMinute = now.getSeconds() * 1000 + now.getMilliseconds();
return (target - minutes) * 60 * 1000 - msIntoMinute;
}
export function startAlignedRingPull(): void {
if (alignedPullTimer) return;
const arm = () => {
const delay = msUntilNextAlignedPull(new Date());
alignedPullTimer = setTimeout(() => {
alignedPullTimer = null;
try {
requestFreshPull();
} catch (error) {
console.warn("health live: aligned ring pull failed", error);
}
arm(); // re-arm against the clock, never the elapsed time
}, delay);
};
arm();
}
/** Exported for tests — the scheduling arithmetic, with no timer attached. */
export const __alignedPullInternals = { msUntilNextAlignedPull, ALIGNED_PULL_MINUTES };
+101
View File
@@ -0,0 +1,101 @@
/**
* The phone graph view's BITMAP, built without touching the phone.
*
* Same split, and for the same reason, as `health-glance.ts` is split out of
* the glasses app: `health-view-model.ts` owns the store reads, the measured
* box, the fold class and the `ImageSource` conversion - all NativeScript - and
* hands this file a size, a font and some already-selected data. What comes
* back is a `GrayImage`.
*
* The payoff is that `tools/health-preview.cjs` can render the phone chart at
* any width under plain node, which is how the narrow/wide layouts get checked
* without an emulator. It also means the chart the preview shows is built by
* the same function the phone calls, not a reimplementation of it.
*/
import { GrayImage, type UiFont } from "../graphics/image";
import {
drawMetricChart,
drawSleepLanes,
drawSleepStackChart,
INK,
} from "./health-chart";
import type { RollupPoint, SampleMetric, SleepNight } from "./health-types";
import type { SleepStageName } from "./sleep-stages";
/**
* What to draw. Three shapes, because the redesign gave sleep two charts of
* its own that are not "a series of numbers over time":
*
* - `metric` the five measured types, banded or barred (unchanged)
* - `nights` sleep over a week/month/quarter: the diverging stacked bar
* - `lanes` sleep over ONE day: the four stage lanes, which is the same
* view the glasses drill-down shows, so the two surfaces agree
* about what "sleep, today" looks like
*/
export type PhoneChartContent =
| {
kind: "metric";
metric: SampleMetric;
points: readonly RollupPoint[];
mode: "band" | "bars";
xLabel: (point: RollupPoint, index: number) => string;
}
| {
kind: "nights";
nights: readonly SleepNight[];
xLabel: (night: SleepNight, index: number) => string;
}
| {
kind: "lanes";
bands: readonly { stage: SleepStageName | null; seconds: number }[];
laneText: (stage: SleepStageName) => { label: string; value: string };
};
export type PhoneChartRequest = {
/** Pixels, already scaled by RENDER_SCALE. */
width: number;
height: number;
font: UiFont;
content: PhoneChartContent;
};
/** The inset between the bitmap's edge and the plot. */
const INSET = 8;
export function renderPhoneChart(request: PhoneChartRequest): GrayImage {
const { width, height, font, content } = request;
const image = new GrayImage(width, height, INK.background);
const rect = {
x: INSET,
y: INSET,
width: Math.max(8, width - INSET * 2),
height: Math.max(8, height - INSET * 2),
};
switch (content.kind) {
case "metric":
drawMetricChart(image, rect, {
metric: content.metric,
points: content.points,
font,
mode: content.mode,
xLabel: content.xLabel,
});
return image;
case "nights":
drawSleepStackChart(image, rect, {
nights: content.nights,
font,
xLabel: content.xLabel,
});
return image;
case "lanes":
drawSleepLanes(image, rect, {
bands: content.bands,
font,
laneText: content.laneText,
});
return image;
}
}
+143
View File
@@ -0,0 +1,143 @@
/**
* Seeding the store with sample data, and the marker that keeps a screenshot
* of it honest.
*
* Without live ring hardware there is nothing in the store, and two empty
* screens prove nothing. So the preview build seeds `health-fixtures.ts`'
* generated data and drops `fixture-marker.json` beside it; both surfaces read
* `isFixtureData()` and show a "Sample data" badge whenever it is there.
*
* The badge is the point. A health screen full of plausible numbers with no
* provenance is the one artefact from this work that could be mistaken for a
* real capture later, so the marker travels with the data rather than living
* in someone's memory of how a screenshot was taken.
*
* Real ingest never writes the marker, so the first genuine sync leaves it
* exactly as it was - which is why `clearFixtures()` exists and why the live
* wiring should call it before its first write.
*/
import { File, knownFolders } from "@nativescript/core";
import { buildFixtures, FIXTURE_VERSION } from "./health-fixtures";
import { checkedFileOperation, healthStore } from "./health-store-files";
const MARKER_FILE = "fixture-marker.json";
function markerPath(): string {
return `${knownFolders.documents().getFolder("health").path}/${MARKER_FILE}`;
}
type Marker = { version: number; seededAtMs: number; days: number };
function readMarker(): Marker | null {
try {
if (!File.exists(markerPath())) return null;
const parsed = JSON.parse(File.fromPath(markerPath()).readTextSync()) as Marker;
return typeof parsed?.version === "number" ? parsed : null;
} catch {
return null;
}
}
/** True when the store currently holds generated sample data. */
export function isFixtureData(): boolean {
return readMarker() !== null;
}
/** Written by `health-live.ts` the first time real ring data lands. */
const LIVE_FILE = "live-marker.json";
function livePath(): string {
return `${knownFolders.documents().getFolder("health").path}/${LIVE_FILE}`;
}
/** True once this install has ever stored a record decoded off the ring. */
export function hasLiveData(): boolean {
try {
return File.exists(livePath());
} catch {
return false;
}
}
/** Record that real data has been stored. Called by the live ingest path. */
export function markLiveData(): void {
if (hasLiveData()) return;
checkedFileOperation((onError) =>
File.fromPath(livePath()).writeTextSync(JSON.stringify({ firstAtMs: Date.now() }), onError),
);
}
/**
* Delete every stored sample, session and rollup, and the fixture badge with
* them. Called before the first genuine ingest.
*
* `clearFixtureMarker()` is not enough on its own and never was: dropping the
* badge while leaving 45 days of generated samples in the store produces
* exactly the artefact this file's header warns about — plausible numbers with
* no provenance, now unlabelled. Real data gets a clean store or none.
*/
export function purgeFixtureData(): void {
if (!isFixtureData()) return;
try {
const folder = knownFolders.documents().getFolder("health");
for (const entity of folder.getEntitiesSync()) {
const name = entity.name;
const isStoreFile =
(name.startsWith("samples-") && name.endsWith(".jsonl")) ||
name === "sleep.jsonl" ||
name === "rollups.json";
if (isStoreFile) {
checkedFileOperation((onError) => File.fromPath(entity.path).removeSync(onError));
}
}
// Keep the badge until every fixture file is gone. A failed purge must
// stop live ingest so it cannot mix real records with remaining fixtures.
clearFixtureMarker();
} finally {
// Also invalidate after a partial purge; cached rows no longer match disk.
healthStore().resetCache();
}
}
/**
* Seed sample data if none is present, or if the generator has changed since
* the last seed. A no-op once seeded, so it is safe to call on every launch.
*
* Refuses outright once real ring data has ever been stored — otherwise a
* version bump to the generator would inject fixtures back on top of a real
* history, which is worse than an empty screen.
*/
export function seedFixturesIfNeeded(days = 45): boolean {
if (hasLiveData()) return false;
const marker = readMarker();
if (marker && marker.version === FIXTURE_VERSION && marker.days >= days) return false;
return seedFixtures(days);
}
export function seedFixtures(days = 45): boolean {
try {
const store = healthStore();
const { samples, sleep } = buildFixtures({ days, nowMs: Date.now() });
// Label before the first append so a failed seed remains identifiable and
// can be purged before real data is ingested.
const marker: Marker = { version: FIXTURE_VERSION, seededAtMs: Date.now(), days };
checkedFileOperation((onError) =>
File.fromPath(markerPath()).writeTextSync(JSON.stringify(marker), onError),
);
store.ingestSamples(samples);
store.ingestSleep(sleep);
return true;
} catch (error) {
console.warn("health fixture seed failed", error);
return false;
}
}
/** Drop the marker. Call before the first real ingest. */
export function clearFixtureMarker(): void {
if (File.exists(markerPath())) {
checkedFileOperation((onError) => File.fromPath(markerPath()).removeSync(onError));
}
}
+81
View File
@@ -0,0 +1,81 @@
/**
* The real, on-device backing for `HealthStore`: files under the app's
* documents folder, using the same `@nativescript/core` File API that
* `open-apps-persistence.ts` already uses for the open-window list.
*
* Split out from `health-store.ts` purely so that module can stay free of
* NativeScript imports and run under plain node in `tests/`; all the logic
* worth testing is over there.
*/
import { File, Folder, knownFolders } from "@nativescript/core";
import { HealthStore, type HealthStorageBackend } from "./health-store";
const FOLDER_NAME = "health";
function healthFolder(): Folder {
return knownFolders.documents().getFolder(FOLDER_NAME);
}
function pathFor(name: string): string {
return `${healthFolder().path}/${name}`;
}
class FileBackend implements HealthStorageBackend {
exists(name: string): boolean {
try {
return File.exists(pathFor(name));
} catch {
return false;
}
}
read(name: string): string | null {
try {
if (!File.exists(pathFor(name))) return null;
return File.fromPath(pathFor(name)).readTextSync();
} catch (error) {
console.warn(`health store read failed (${name})`, error);
return null;
}
}
append(name: string, text: string): void {
// NativeScript reports IO failures through callbacks as well as throws.
// Propagate both so the caller retains the unconsumed ring batch.
checkedFileOperation((onError) => File.fromPath(pathFor(name)).appendTextSync(text, onError));
}
write(name: string, text: string): void {
checkedFileOperation((onError) => File.fromPath(pathFor(name)).writeTextSync(text, onError));
}
list(): string[] {
try {
return healthFolder()
.getEntitiesSync()
.map((entity) => entity.name);
} catch (error) {
console.warn("health store list failed", error);
return [];
}
}
}
/** Convert a synchronous NativeScript error callback into a thrown failure. */
export function checkedFileOperation(operation: (onError: (error: any) => void) => void): void {
let failure: Error | undefined;
operation((error) => {
failure = error instanceof Error ? error : new Error(error?.message ?? String(error));
});
if (failure) throw failure;
}
let store: HealthStore | null = null;
/** The app's one health store. Created on first use. */
export function healthStore(): HealthStore {
if (!store) store = new HealthStore(new FileBackend());
return store;
}
+453
View File
@@ -0,0 +1,453 @@
/**
* Durable local storage for decoded ring health records.
*
* ## Why this exists at all, and why it is not a cache
*
* Live testing on 2026-09-10 found that the ring appears to advance its own
* delivery watermark when it sends the RSP to a health request, whether or not
* the DATA page that should follow ever arrives - so a request that loses the
* race can PERMANENTLY DISCARD backlog, silently, with no error anywhere in
* the protocol (implement-return, section 11). The practical consequence:
* the moment a record is successfully decoded may be the only moment it is
* ever available. It has to hit durable storage right then.
*
* The existing `ringHealthRecords` list on `FaceclawBleCommunicator` is
* explicitly a capped, ephemeral ring buffer (256 records, oldest dropped) and
* is not a store. This is the store.
*
* ## The layout, and why it is shaped this way
*
* health/samples-YYYY-MM.jsonl append-only, one JSON object per line
* health/sleep.jsonl append-only, one session per line
* health/rollups.json DERIVED daily rollups - a rebuildable cache
*
* The raw shards are the truth and are never rewritten in place, only appended
* to. That is the property the paragraph above demands: a crash, a bad parse,
* or a bug in the rollup code can never destroy a record that was once
* received, because nothing ever rewrites the file that holds it.
*
* `rollups.json` is the answer to "pre-aggregate on write, or aggregate on
* render?" - and the answer is BOTH, at different layers, because they are
* asked by different screens:
*
* - The glasses glance and the by-hour charts want one day at fine
* resolution. That comes from raw shards, aggregated on render. At ~360
* samples a day the work is trivial, and it stays exact.
* - The by-day charts want weeks or months. Aggregating those on render
* means parsing every shard in the range - about 9 MB a year of JSONL, and
* growing without bound. So daily rollups are maintained on write and
* served straight from this one small file, and a quarter-long chart never
* opens a shard at all.
*
* Because the rollup file is derived, it carries no risk: if it is missing,
* corrupt, or written by an older version, `rebuildRollups()` regenerates it
* from the shards. Deleting it is always safe.
*
* ## No new dependency
*
* SQLite is not a dependency of this project and adding one for this would be
* the largest change in the feature. Everything the phone view needs is a
* key-ordered scan over a few tens of thousands of rows, which is what the
* above does with the `File` API already used by `open-apps-persistence.ts`
* for the same kind of job.
*
* This module has NO NativeScript imports - the filesystem arrives through
* `HealthStorageBackend` - so its durability and dedupe semantics run under
* plain node in `tests/health-store.test.cjs`. The real backend is
* `health-store-files.ts`.
*/
import {
type HealthSample,
type Rollup,
type SampleMetric,
type SleepSession,
SAMPLE_METRICS,
monthKey,
rollupOf,
startOfLocalDay,
} from "./health-types";
export interface HealthStorageBackend {
exists(name: string): boolean;
read(name: string): string | null;
/** Must create the file if absent. Durable before returning. */
append(name: string, text: string): void;
write(name: string, text: string): void;
/** Every file in the health folder. Used to rebuild the rollup cache. */
list(): string[];
}
const SAMPLE_PREFIX = "samples-";
const SAMPLE_SUFFIX = ".jsonl";
const SLEEP_FILE = "sleep.jsonl";
const ROLLUP_FILE = "rollups.json";
const ROLLUP_VERSION = 1;
/** On-disk sample line. Short keys: this is the file that grows. */
type SampleLine = {
m: SampleMetric;
t: number;
s: number;
n: number;
x: number;
a: number;
u: number;
};
type RollupFile = {
version: number;
/** `YYYY-MM-DD` -> metric -> rollup. */
days: Record<string, Partial<Record<SampleMetric, Rollup>>>;
};
function sampleKey(sample: { metric: SampleMetric; startMs: number; spanMs: number }): string {
return `${sample.metric}|${sample.startMs}|${sample.spanMs}`;
}
function dayKey(ms: number): string {
const date = new Date(startOfLocalDay(ms));
const month = `${date.getMonth() + 1}`.padStart(2, "0");
const day = `${date.getDate()}`.padStart(2, "0");
return `${date.getFullYear()}-${month}-${day}`;
}
function shardName(ms: number): string {
return `${SAMPLE_PREFIX}${monthKey(ms)}${SAMPLE_SUFFIX}`;
}
export class HealthStore {
/** Shard name -> dedupe key -> sample. Loaded lazily, per shard. */
private readonly shards = new Map<string, Map<string, HealthSample>>();
private sleep: SleepSession[] | null = null;
private rollups: RollupFile | null = null;
private rollupsDirty = false;
constructor(private readonly backend: HealthStorageBackend) {}
/** Forget cached data after the backing files have been purged. */
resetCache(): void {
this.shards.clear();
this.sleep = null;
this.rollups = null;
this.rollupsDirty = false;
}
// -------------------------------------------------------------------------
// Writing
/**
* Store decoded samples. Durable before this returns.
*
* Returns how many were genuinely new or changed. Re-storing a bucket that
* is already held is a no-op on disk, which matters because the live poller
* re-requests the current hour every 30 minutes and would otherwise append a
* duplicate line each time.
*
* ## This no-op is real, and it is the ONLY place it needs to be
*
* Re-checked 2026-09-12 while chasing a shard that reached 22k lines in a
* day. The suspicion was that identical re-writes were being appended; they
* were not. `sameSample` below compares every stored field, `spanMs` is part
* of the key, and an unchanged sample never reaches `append`.
*
* What was actually appending was a genuinely CHANGING value: the steps
* ledger merged overlapping records with last-write-wins, and those records
* disagreed about each bucket's calorie fields, so one day's calorie total
* ping-ponged 643 <-> 671 and wrote two new lines every sync cycle. An
* append-only store recording a value that really does flip-flop is correct
* behaviour; the fix belonged upstream, in `health-live.ts`' merge, and is
* there now (max-by-index, order-independent).
*
* So: do NOT add a second dedupe layer at a caller or in the file backend.
* If the shard grows again, the value is changing and the question is why.
*/
ingestSamples(samples: readonly HealthSample[]): number {
const byShard = new Map<string, Map<string, HealthSample>>();
for (const sample of samples) {
if (!Number.isFinite(sample.startMs) || sample.spanMs <= 0) continue;
const name = shardName(sample.startMs);
const shard = this.loadShard(name);
const key = sampleKey(sample);
const pending = byShard.get(name) ?? new Map<string, HealthSample>();
const existing = pending.get(key) ?? shard.get(key);
if (existing && sameSample(existing, sample)) continue;
pending.set(key, sample);
byShard.set(name, pending);
}
let written = 0;
for (const [name, pending] of byShard) {
const list = [...pending.values()];
const text = list.map((sample) => `${JSON.stringify(toLine(sample))}\n`).join("");
// A failed append can leave an incomplete final line. Start each batch
// on a fresh line so retrying cannot concatenate a valid record onto it.
this.backend.append(name, `\n${text}`);
this.rollupsDirty = true;
// Only durable values participate in deduplication. If another shard
// fails, a retry skips this successful append and retries the rest.
const shard = this.loadShard(name);
for (const [key, sample] of pending) shard.set(key, sample);
written += list.length;
}
if (this.rollupsDirty) {
this.updateRollupsFor(samples);
this.rollupsDirty = false;
}
return written;
}
/**
* Store sleep sessions. Durable before this returns.
*
* Deduped on the session's own start time, so a night re-delivered by a
* later sync replaces rather than duplicates.
*/
ingestSleep(sessions: readonly SleepSession[]): number {
const held = this.loadSleep().slice();
const fresh: SleepSession[] = [];
for (const session of sessions) {
const index = held.findIndex(
(candidate) =>
candidate.startMs === session.startMs && candidate.timeResolved === session.timeResolved,
);
if (index >= 0) {
if (JSON.stringify(held[index]) === JSON.stringify(session)) continue;
held[index] = session;
} else {
held.push(session);
}
fresh.push(session);
}
if (fresh.length > 0) {
this.backend.append(SLEEP_FILE, "\n" + fresh.map((s) => `${JSON.stringify(s)}\n`).join(""));
this.sleep = held;
}
return fresh.length;
}
// -------------------------------------------------------------------------
// Reading
/** Every stored sample overlapping [startMs, endMs). Exact - reads shards. */
samplesInRange(startMs: number, endMs: number): HealthSample[] {
const out: HealthSample[] = [];
for (const name of this.shardNamesInRange(startMs, endMs)) {
for (const sample of this.loadShard(name).values()) {
if (sample.startMs >= startMs && sample.startMs < endMs) out.push(sample);
}
}
out.sort((a, b) => a.startMs - b.startMs);
return out;
}
/** Sleep sessions, newest first. */
sleepSessions(): SleepSession[] {
return this.loadSleep().slice().sort((a, b) => b.startMs - a.startMs);
}
/**
* Daily rollups over a range, served from the derived cache.
*
* This is the path a month- or quarter-long chart takes, and it deliberately
* never opens a sample shard. A day with no entry comes back absent, and the
* caller renders a gap.
*/
dailyRollups(metric: SampleMetric, startMs: number, endMs: number): Map<number, Rollup> {
const file = this.loadRollups();
const out = new Map<number, Rollup>();
let cursor = startOfLocalDay(startMs);
let guard = 0;
while (cursor < endMs && guard < 2000) {
guard += 1;
const entry = file.days[dayKey(cursor)]?.[metric];
if (entry) out.set(cursor, entry);
const next = new Date(cursor);
next.setDate(next.getDate() + 1);
cursor = next.getTime();
}
return out;
}
/** Local midnight of the earliest day with any stored data, or null. */
earliestDayMs(): number | null {
const file = this.loadRollups();
const keys = Object.keys(file.days).sort();
if (keys.length === 0) return null;
const parts = keys[0]!.split("-").map(Number);
return new Date(parts[0]!, parts[1]! - 1, parts[2]!).getTime();
}
/** How many sample rows are held, across every loaded shard. */
loadedSampleCount(): number {
let total = 0;
for (const shard of this.shards.values()) total += shard.size;
return total;
}
// -------------------------------------------------------------------------
// The derived cache
/**
* Rebuild `rollups.json` from the raw shards. Safe to call at any time; the
* recovery path when the cache is missing, corrupt or from an older version.
*/
rebuildRollups(): void {
const days: RollupFile["days"] = {};
const perDay = new Map<string, Map<SampleMetric, HealthSample[]>>();
for (const name of this.backend.list()) {
if (!name.startsWith(SAMPLE_PREFIX) || !name.endsWith(SAMPLE_SUFFIX)) continue;
for (const sample of this.loadShard(name).values()) {
const key = dayKey(sample.startMs);
let byMetric = perDay.get(key);
if (!byMetric) {
byMetric = new Map();
perDay.set(key, byMetric);
}
const list = byMetric.get(sample.metric);
if (list) list.push(sample);
else byMetric.set(sample.metric, [sample]);
}
}
for (const [key, byMetric] of perDay) {
const entry: Partial<Record<SampleMetric, Rollup>> = {};
for (const metric of SAMPLE_METRICS) {
const rolled = rollupOf(byMetric.get(metric) ?? []);
if (rolled) entry[metric] = rolled;
}
days[key] = entry;
}
this.rollups = { version: ROLLUP_VERSION, days };
this.persistRollups();
}
private updateRollupsFor(samples: readonly HealthSample[]): void {
const file = this.loadRollups();
const touched = new Set<string>();
for (const sample of samples) touched.add(dayKey(sample.startMs));
for (const key of touched) {
const parts = key.split("-").map(Number);
const dayStart = new Date(parts[0]!, parts[1]! - 1, parts[2]!).getTime();
const dayEnd = new Date(parts[0]!, parts[1]! - 1, parts[2]! + 1).getTime();
const inDay = this.samplesInRange(dayStart, dayEnd);
const entry: Partial<Record<SampleMetric, Rollup>> = {};
for (const metric of SAMPLE_METRICS) {
const rolled = rollupOf(inDay.filter((sample) => sample.metric === metric));
if (rolled) entry[metric] = rolled;
}
file.days[key] = entry;
}
this.persistRollups();
}
private persistRollups(): void {
if (!this.rollups) return;
this.backend.write(ROLLUP_FILE, JSON.stringify(this.rollups));
}
// -------------------------------------------------------------------------
// Loading
private shardNamesInRange(startMs: number, endMs: number): string[] {
const names: string[] = [];
const cursor = new Date(startOfLocalDay(startMs));
cursor.setDate(1);
let guard = 0;
while (cursor.getTime() < endMs && guard < 240) {
guard += 1;
names.push(`${SAMPLE_PREFIX}${monthKey(cursor.getTime())}${SAMPLE_SUFFIX}`);
cursor.setMonth(cursor.getMonth() + 1);
}
return names;
}
private loadShard(name: string): Map<string, HealthSample> {
const held = this.shards.get(name);
if (held) return held;
const shard = new Map<string, HealthSample>();
this.shards.set(name, shard);
const text = this.backend.exists(name) ? this.backend.read(name) : null;
if (!text) return shard;
for (const line of text.split("\n")) {
if (line.length === 0) continue;
const sample = fromLine(line);
// Later lines win: an append is how a re-synced bucket is corrected.
if (sample) shard.set(sampleKey(sample), sample);
}
return shard;
}
private loadSleep(): SleepSession[] {
if (this.sleep) return this.sleep;
const sessions: SleepSession[] = [];
const text = this.backend.exists(SLEEP_FILE) ? this.backend.read(SLEEP_FILE) : null;
if (text) {
for (const line of text.split("\n")) {
if (line.length === 0) continue;
try {
const parsed = JSON.parse(line) as SleepSession;
if (typeof parsed?.startMs !== "number") continue;
const index = sessions.findIndex((s) => s.startMs === parsed.startMs);
if (index >= 0) sessions[index] = parsed;
else sessions.push(parsed);
} catch {
// One unreadable line must not cost the rest of the file.
}
}
}
this.sleep = sessions;
return sessions;
}
private loadRollups(): RollupFile {
if (this.rollups) return this.rollups;
const text = this.backend.exists(ROLLUP_FILE) ? this.backend.read(ROLLUP_FILE) : null;
if (text) {
try {
const parsed = JSON.parse(text) as RollupFile;
if (parsed?.version === ROLLUP_VERSION && parsed.days) {
this.rollups = parsed;
return parsed;
}
} catch {
// Falls through to a rebuild - the cache is always reconstructible.
}
}
this.rollups = { version: ROLLUP_VERSION, days: {} };
this.rebuildRollups();
return this.rollups;
}
}
function sameSample(a: HealthSample, b: HealthSample): boolean {
return a.min === b.min && a.max === b.max && a.avg === b.avg && a.total === b.total;
}
function toLine(sample: HealthSample): SampleLine {
return {
m: sample.metric,
t: sample.startMs,
s: sample.spanMs,
n: sample.min,
x: sample.max,
a: sample.avg,
u: sample.total,
};
}
function fromLine(line: string): HealthSample | null {
try {
const parsed = JSON.parse(line) as SampleLine;
if (typeof parsed?.t !== "number" || typeof parsed?.m !== "string") return null;
return {
metric: parsed.m,
startMs: parsed.t,
spanMs: parsed.s,
min: parsed.n,
max: parsed.x,
avg: parsed.a,
total: parsed.u,
};
} catch {
return null;
}
}
+231
View File
@@ -0,0 +1,231 @@
/**
* The health record shapes, normalised for storage and display.
*
* These mirror `RingProtocol.kt`'s `HourlyRecord` / `StepsRecord` /
* `SleepRecord` (on the `ring-health-protocol` branch) but deliberately are
* NOT the same types: the Java types are wire-shaped - raw hour indices, raw
* stage ids, ring-relative timestamps, a per-page anchor that may be absent.
* Everything here is already resolved into wall-clock time, or explicitly
* marked as not resolvable. The conversion is `fromRingRecords()` in
* `health-ingest.ts`, which is the only place that has to know about the wire.
*
* Keeping the two apart is what lets this app's storage and UI be built and
* tested with no BLE anywhere near them.
*/
/** The five metrics the phone view can graph. */
export type SeriesMetric = "heartRate" | "spo2" | "hrv" | "steps" | "sleep";
/** Metrics stored as bucketed samples. Sleep is per-session and excluded. */
export type SampleMetric = "heartRate" | "spo2" | "hrv" | "steps" | "calories";
export const SAMPLE_METRICS: readonly SampleMetric[] = [
"heartRate",
"spo2",
"hrv",
"steps",
"calories",
];
/** Metrics whose bucket value is a SUM over the bucket, not a measurement. */
export const CUMULATIVE_METRICS: readonly SampleMetric[] = ["steps", "calories"];
export function isCumulative(metric: SampleMetric): boolean {
return CUMULATIVE_METRICS.includes(metric);
}
export const HOUR_MS = 3_600_000;
export const TEN_MINUTES_MS = 600_000;
export const DAY_MS = 86_400_000;
/**
* One stored bucket.
*
* `min`/`max`/`avg` are what the ring reports for the physiological metrics.
* For the cumulative ones (steps, calories) the ring reports a single count
* per bucket, so all three carry that count and `total` carries it as well -
* which keeps one shape for everything and lets a rollup sum `total` while
* banding `min`/`max` without special-casing the reader.
*
* `startMs` is the LOCAL wall-clock start of the bucket. A record whose time
* could not be resolved (a backlog page with no anchor; see the decode doc's
* section 4) is not stored at all rather than stored with an invented time -
* see `health-ingest.ts`.
*/
export type HealthSample = {
metric: SampleMetric;
startMs: number;
spanMs: number;
min: number;
max: number;
avg: number;
total: number;
};
/**
* One sleep session.
*
* All five duration fields come from NAMED byte offsets in the record and need
* no stage-id mapping (see `sleep-stages.ts`). `segments` is the hypnogram and
* carries RAW stage ids - resolve them through `stageNameForId`, never inline.
*
* `timeResolved` matters and is not decoration: the decode found that the
* ring's `start_ts`/`end_ts` are ring-relative seconds, not Unix time, and
* that nothing in the record dates the session (decode section 6, "genuinely
* unresolved"). Even's own app gets this wrong - one exported row is stamped
* 1979. When we cannot anchor a session we say so rather than plotting it at a
* time we made up.
*/
export type SleepSession = {
/** Local midnight of the day the session is attributed to (the wake-up day). */
dayStartMs: number;
startMs: number;
endMs: number;
totalSec: number;
wakeSec: number;
remSec: number;
lightSec: number;
deepSec: number;
segments: readonly SleepSegment[];
/** False when startMs/endMs are ring-relative and could not be anchored. */
timeResolved: boolean;
};
export type SleepSegment = {
/** RAW ring stage id, 0-3. Resolve via `stageNameForId`. */
stageId: number;
halfMinutes: number;
};
/**
* One night's stage breakdown, in seconds, positioned on the day axis.
*
* This is what the diverging nightly sleep chart plots (week / month / 3
* months). It is a separate shape from `RollupPoint` because a night is not a
* rollup of anything - it has four named parts that stack, three up and one
* down, and flattening it to a single `sum` is exactly the information the
* redesigned chart exists to stop throwing away.
*/
export type SleepNight = {
/** Local midnight of the day the session is attributed to (the wake-up day). */
startMs: number;
/** False when no session was recorded for this day - drawn as a gap. */
hasData: boolean;
deepSec: number;
remSec: number;
lightSec: number;
wakeSec: number;
};
/** A min/max/avg/sum rollup over some window. `count` is buckets contributing. */
export type Rollup = {
min: number;
max: number;
avg: number;
sum: number;
count: number;
};
/** A rollup positioned on the time axis - what the charts actually plot. */
export type RollupPoint = Rollup & {
/** Local wall-clock start of the window this rollup covers. */
startMs: number;
spanMs: number;
};
export function emptyRollup(): Rollup {
return { min: 0, max: 0, avg: 0, sum: 0, count: 0 };
}
/** Combine samples into one rollup. Returns null when nothing contributed. */
export function rollupOf(samples: readonly HealthSample[]): Rollup | null {
if (samples.length === 0) return null;
let min = Number.POSITIVE_INFINITY;
let max = Number.NEGATIVE_INFINITY;
let sum = 0;
let weighted = 0;
for (const sample of samples) {
if (sample.min < min) min = sample.min;
if (sample.max > max) max = sample.max;
sum += sample.total;
weighted += sample.avg;
}
return {
min,
max,
avg: weighted / samples.length,
sum,
count: samples.length,
};
}
export const METRIC_LABELS: Readonly<Record<SeriesMetric, string>> = {
heartRate: "Heart rate",
spo2: "Blood oxygen",
hrv: "HRV",
steps: "Steps",
sleep: "Sleep",
};
export const METRIC_UNITS: Readonly<Record<SeriesMetric, string>> = {
heartRate: "bpm",
spo2: "%",
hrv: "ms",
steps: "",
sleep: "h",
};
/**
* The same two maps over SampleMetric rather than SeriesMetric.
*
* These exist because the two enums differ at both ends: the phone GRAPHS
* sleep (which is not a sample metric) and the glasses drill-down walks
* calories (which is not a series metric, because the phone never got a
* calories chart). A screen that iterates the sample metrics needs a label for
* all five, so it gets its own map instead of special-casing the missing one.
*/
export const SAMPLE_METRIC_LABELS: Readonly<Record<SampleMetric, string>> = {
heartRate: "Heart rate",
spo2: "Blood oxygen",
hrv: "HRV",
steps: "Steps",
calories: "Calories",
};
export const SAMPLE_METRIC_UNITS: Readonly<Record<SampleMetric, string>> = {
heartRate: "bpm",
spo2: "%",
hrv: "ms",
steps: "",
calories: "kcal",
};
/** The short form the glance uses, where a column is ~300px wide. */
export const SAMPLE_METRIC_SHORT_LABELS: Readonly<Record<SampleMetric, string>> = {
heartRate: "HR",
spo2: "SpO2",
hrv: "HRV",
steps: "Steps",
calories: "Calories",
};
/** Local midnight of the day containing `ms`. */
export function startOfLocalDay(ms: number): number {
const date = new Date(ms);
date.setHours(0, 0, 0, 0);
return date.getTime();
}
/** Local top-of-hour containing `ms`. */
export function startOfLocalHour(ms: number): number {
const date = new Date(ms);
date.setMinutes(0, 0, 0);
return date.getTime();
}
/** `YYYY-MM`, in local time - the storage shard key. */
export function monthKey(ms: number): string {
const date = new Date(ms);
const month = `${date.getMonth() + 1}`.padStart(2, "0");
return `${date.getFullYear()}-${month}`;
}
+93
View File
@@ -0,0 +1,93 @@
/**
* THE RING'S SLEEP STAGE-TYPE IDS — the single place the 0-3 -> stage mapping
* is decided. If this ever turns out wrong, this file is the whole fix.
*
* ## What the ring sends
*
* A `06:01` sleep record carries two independent descriptions of the same
* night (see the protocol decode, section 6):
*
* 1. Five NAMED per-stage totals at fixed byte offsets - `total_time`,
* `wake_time`, `rem_time`, `light_time`, `deep_time`. These are named,
* not guessed: the decode reproduced a whole exported row byte-for-byte
* from them, so a percentage computed from these fields needs no mapping
* at all and is not affected by anything in this file.
*
* 2. A segment array of `[stage_type, half_minutes]` pairs - the hypnogram,
* the shape of the night. `stage_type` is a raw 0-3 id, and *which* id is
* which stage was the open question this file answers.
*
* So: STAGE PERCENTAGES DO NOT DEPEND ON THIS MAPPING. Only the hypnogram
* strip does. `health-derive.ts` computes percentages from the named totals
* and never consults `STAGE_NAME_BY_ID` for them.
*
* ## How the mapping was determined
*
* The implementation return doc listed this as guess #3 - "never cracked",
* expected to need a live-hardware comparison against Even's own app after a
* night's sleep. It did not, because that comparison was already sitting in
* the exported history: the export IS Even's app's own report, and its
* `rem_time`/`light_time`/`deep_time`/`wake_time` columns are Even's own
* labels for the same night whose raw segment array sits in the same row.
*
* Cross-check performed 2026-09-10 over all 34 exported sessions: for each
* session, sum `half_minutes * 30` per stage id and ask which named total it
* equals.
*
* stage id 0 -> wake_time 34/34 sessions, no other total matched
* stage id 1 -> rem_time 34/34 sessions, no other total matched
* stage id 2 -> light_time 34/34 sessions, no other total matched
* stage id 3 -> deep_time 34/34 sessions, no other total matched
*
* Not one session produced an ambiguous match (an id equalling two totals) or
* an unmatched id, and the decode's own sum identity
* (`sum(half_minutes) * 30 == total_time + wake_time`) held in all 34.
*
* ## Why it is still marked unconfirmed
*
* `STAGE_MAPPING_CONFIRMED` stays `false` until the same result is seen on a
* record faceclaw decoded off the wire ITSELF, rather than one Even's app
* exported. The arithmetic above is strong evidence about what the *ids mean*,
* but every session it was computed from reached the CSV through Even's app,
* so it cannot rule out that the app relabels ids on the way in. That is a
* narrow doubt, and the live check Chris planned still closes it in one night.
*
* While this is `false` the UI labels the hypnogram as unconfirmed rather than
* asserting "this band is REM"; see `health-chart.ts`. Flipping it to `true`
* is the whole of the change once a live record agrees.
*/
export type SleepStageName = "wake" | "rem" | "light" | "deep";
/** Raw `stage_type` id -> stage. See this file's header for the evidence. */
export const STAGE_NAME_BY_ID: Readonly<Record<number, SleepStageName>> = {
0: "wake",
1: "rem",
2: "light",
3: "deep",
};
/**
* False until a record faceclaw decoded off the wire itself confirms the
* mapping above. Read by the UI, which softens its stage labels while it is
* false. Flip to `true` after a live cross-check agrees.
*/
export const STAGE_MAPPING_CONFIRMED = false;
/** The order stages are stacked/listed in, deepest sleep last. */
export const STAGE_DISPLAY_ORDER: readonly SleepStageName[] = ["wake", "rem", "light", "deep"];
export function stageNameForId(stageId: number): SleepStageName | null {
return STAGE_NAME_BY_ID[stageId] ?? null;
}
/** Human label for a stage, hedged while the mapping is unconfirmed. */
export function stageLabel(stage: SleepStageName): string {
const labels: Record<SleepStageName, string> = {
wake: "Awake",
rem: "REM",
light: "Light",
deep: "Deep",
};
return labels[stage];
}
+5 -1
View File
@@ -248,7 +248,7 @@ export class FaceclawCommunicatorBridge {
return FaceclawCommunicatorBridge.active;
}
constructor(addresses: { right: string; left: string; ring?: string }) {
constructor(addresses: { right: string; left: string; ring?: string; ringRole?: string }) {
this.communicator = FaceclawKitIosGlassesSession.alloc().initWithRightAddressLeftAddressRingAddress(
String(addresses.right ?? "").toUpperCase(),
String(addresses.left ?? "").toUpperCase(),
@@ -256,6 +256,10 @@ export class FaceclawCommunicatorBridge {
);
// The shared session halts on any other firmware ("incompatible-firmware").
this.communicator.setRequiredFirmwareRevisionRevision(REQUIRED_FACECLAW_FIRMWARE_VERSION);
// Guarded: an older framework build may not export it yet.
if (addresses.ringRole && typeof this.communicator.setDirectRingRoleRole === "function") {
this.communicator.setDirectRingRoleRole(addresses.ringRole);
}
this.listenerProxy = SessionListener.new() as SessionListener;
this.listenerProxy.bridge = this;
this.communicator.setListenerListener(this.listenerProxy);
+3 -1
View File
@@ -169,7 +169,7 @@ export class FaceclawCommunicatorBridge {
private readonly firmwareInfoListeners = new Set<(info: FirmwareInfo) => void>();
private readonly previewAnimationListeners = new Set<() => void>();
constructor(addresses: { right: string; left: string; ring?: string }) {
constructor(addresses: { right: string; left: string; ring?: string; ringRole?: string }) {
const context = Utils.android.getApplicationContext();
if (!context) throw new Error("Android application context unavailable");
@@ -181,6 +181,8 @@ export class FaceclawCommunicatorBridge {
);
// The shared session halts on any other firmware ("incompatible-firmware").
this.communicator.setRequiredFirmwareRevision(REQUIRED_FACECLAW_FIRMWARE_VERSION);
// Which R1 role the direct ring link claims; only matters with a ring address.
if (addresses.ringRole) this.communicator.setDirectRingRole(addresses.ringRole);
this.listenerProxy = new com.faceclaw.app.FaceclawBleCommunicatorListener({
onStateChange: (phase: string, status: string) => {
const state = {
+158
View File
@@ -0,0 +1,158 @@
import { Utils } from "@nativescript/core";
declare const com: any;
/**
* R1 ring diagnostics (Developer > Debug tests > Ring status). Session-side
* state comes from the active communicator; the phone's own Bluetooth view of
* the ring (bond, GATT/ACL link) is queried separately so it is available
* even with no session or with the direct ring link disabled.
*/
/** GlassesSessionCore.getRingStatus. Ages are ms before now, -1 = never. */
export type RingSessionStatus = {
directEnabled: boolean;
ringAddress: string;
glassesConnected: boolean;
sessionReady: boolean;
directConnected: boolean;
directNotificationsReady: boolean;
directConnectCount: number;
directStateAgeMs: number;
directBattery: number;
lastDirectNotifyAgeMs: number;
lastDirectInputAgeMs: number;
lastDirectInput: string;
glassesRingBattery: number;
glassesRingBatteryAgeMs: number;
lastGlassesInputAgeMs: number;
lastGlassesInput: string;
lastDirectError: string;
/** Ring MAC as the glasses reported it (wire byte order, hex), "" if not yet seen. */
glassesRingMac: string;
glassesRingName: string;
lastGlassesReport: string;
lastGlassesReportAgeMs: number;
lastCommand: string;
lastCommandAgeMs: number;
lastCommandResultR: string;
lastCommandResultL: string;
/** Which ring role the direct link claims: "phone" or "glasses". */
directRole: string;
/** Glasses role only: the link is temporarily in the phone role for a health pull. */
healthWindowActive: boolean;
/** Outcome of the last health pull ("completed, 12 pages", "aborted, 0 pages", ...), "" if none. */
lastHealthPull: string;
lastHealthPullAgeMs: number;
/** Decoded health records not yet stored by the TypeScript ingest. */
heldHealthRecords: number;
/** Glasses role only: what the ring made of our legacy pair-auth this connection ("" = not sent). */
directGlassesAuth: string;
directGlassesAuthAgeMs: number;
lastRingCommand: string;
lastRingCommandAgeMs: number;
lastRingCommandResult: string;
/** Last direct-link notification nothing decoded: characteristic prefix and hex. */
lastDirectRaw: string;
lastDirectRawAgeMs: number;
};
/**
* EXPERIMENTAL glasses-side ring link control (sid 0x80 pair manager):
* "disconnect" drops the glasses' ring link, "release" also clears their
* connect mode (may hold off auto-reconnect), "unpair" makes them forget the
* ring, "connect" hands the ring back.
*/
export type GlassesRingLinkAction = "disconnect" | "release" | "unpair" | "connect";
/**
* EXPERIMENTAL ring-side binding commands over the direct link (see
* GlassesSessionCore.sendRingConfigCommand). "bind" and "unbind" combine the
* ring and glasses halves in the official app's order.
*/
export type RingConfigAction =
| "bind"
| "unbind"
| "pair-auth"
| "targets-glasses"
| "targets-clear"
| "touch-on"
| "touch-off"
| "remove-ring";
export type RingSystemBluetoothState = {
address: string;
bonded?: boolean;
gattConnected?: boolean;
aclConnected?: boolean;
name?: string | null;
error?: string;
};
function activeCommunicator(): any {
if (!global.isAndroid) return null;
try {
return com.faceclaw.app.FaceclawBleCommunicator.getActive();
} catch {
return null;
}
}
/** Null when there is no active glasses session (or on iOS). */
export function getRingSessionStatus(): RingSessionStatus | null {
const active = activeCommunicator();
if (!active) return null;
try {
return JSON.parse(String(active.getRingStatus())) as RingSessionStatus;
} catch (error) {
console.warn(`getRingStatus failed: ${error}`);
return null;
}
}
/** Null on iOS or when the query itself fails. */
export function getRingSystemBluetoothState(address: string): RingSystemBluetoothState | null {
if (!global.isAndroid) return null;
try {
const json = com.faceclaw.app.FaceclawBleCommunicator.getSystemBluetoothStateJson(
Utils.android.getApplicationContext(), address);
return JSON.parse(String(json)) as RingSystemBluetoothState;
} catch (error) {
console.warn(`getSystemBluetoothStateJson failed: ${error}`);
return null;
}
}
/** False when there is no session or the command could not be queued. */
export function setGlassesRingLink(action: GlassesRingLinkAction, fallbackAddress: string, fallbackName: string): boolean {
const active = activeCommunicator();
if (!active) return false;
try {
return Boolean(active.setGlassesRingLink(action, fallbackAddress, fallbackName));
} catch (error) {
console.warn(`setGlassesRingLink failed: ${error}`);
return false;
}
}
/** A one-line outcome for the UI. */
export function sendRingConfigCommand(action: RingConfigAction, fallbackAddress: string, fallbackName: string): string {
const active = activeCommunicator();
if (!active) return "not sent: no glasses session";
try {
return String(active.sendRingConfigCommand(action, fallbackAddress, fallbackName));
} catch (error) {
console.warn(`sendRingConfigCommand failed: ${error}`);
return `failed: ${error}`;
}
}
/**
* The R1's advertised name, "EVEN R1_" plus the last three address bytes
* (e.g. FF:AA:F1:F6:7E:28 -> "EVEN R1_F67E28"). The glasses store it with the
* ring's MAC when told to connect.
*/
export function defaultRingName(address: string): string {
const hex = address.replace(/[^0-9a-fA-F]/g, "").toUpperCase();
return hex.length === 12 ? `EVEN R1_${hex.slice(6)}` : "";
}
+11 -4
View File
@@ -834,17 +834,24 @@ export const showBleBandwidthSetting = new ConfigSettingBoolean({
"Show Bluetooth messages and bytes sent, throughput, acknowledged display fps, and bytes per frame at the bottom of the phone screen. Rates use a five-second window; bytes include control traffic and protocol framing.",
});
export type RingConnectionMode = "glasses" | "direct";
/**
* How the phone talks to the R1. The ring has one phone role (health sync) and
* one glasses role (gestures, battery pushes), so "health" and "direct" are
* the two ways a phone link can be useful; see
* GlassesSessionCore.setDirectRingRole and notes/ring-link-control.md.
*/
export type RingConnectionMode = "glasses" | "health" | "direct";
export const ringConnectionModeSetting = new ConfigSettingEnum<RingConnectionMode>({
id: "ring-connection-mode",
label: "Ring connection",
storageKey: "developer.ringConnectionMode",
defaultValue: "glasses",
values: ["glasses", "direct"],
formatValue: (value) => (value === "direct" ? "Direct" : "Only via glasses"),
values: ["glasses", "health", "direct"],
formatValue: (value) =>
value === "direct" ? "Direct to phone" : value === "health" ? "Via glasses + health sync" : "Only via glasses",
description:
"How R1 ring input reaches the phone. Only via glasses: the ring's own link to the glasses carries its gestures, and the phone never opens a Bluetooth connection to the ring. Direct: also connect to the ring from the phone (currently unreliable). Takes effect on the next connection to the glasses.",
"How the R1 ring reaches the phone. Only via glasses: the glasses relay the ring's gestures and the phone never connects to it. Via glasses + health sync: the same, plus the phone connects to the ring to sync health data. Direct to phone (experimental): the phone takes the ring over from the glasses and gets its gestures and battery itself; the glasses lose ring input. Health still syncs, but each sync (on opening Health, and at :01 and :31) pauses ring gestures for up to a minute while the phone briefly reconnects to the ring in its health role. Leaving Direct hands the ring back to the glasses. Takes effect on the next connection to the glasses.",
});
// "whisper" (no "onboard-" prefix) is OpenAI's CLOUD realtime model
+2 -2
View File
@@ -222,8 +222,8 @@ function settingsSections(): SettingsSection[] {
{
label: "Developer",
items: [
// Whether the phone opens its own BLE link to the R1 ring; the
// glasses relay ring gestures either way. Applied at connect time.
// Whether and how the phone opens its own BLE link to the R1 ring.
// Applied at connect time.
enumSettingMenuItem(ringConnectionModeSetting),
toggleSettingMenuItem(saveVoiceRecordingsSetting),
toggleSettingMenuItem(firmwareDebugFlagsSetting),
+1 -1
View File
@@ -1,2 +1,2 @@
export const FACECLAW_VERSION = "0.8.6-pre";
export const FACECLAW_VERSION = "0.8.6";
export const USER_AGENT = "Faceclaw/"+FACECLAW_VERSION;