diff --git a/.gitignore b/.gitignore index 5f98a77a..3c6e0d8c 100644 --- a/.gitignore +++ b/.gitignore @@ -43,3 +43,6 @@ faceclaw_settings.xml # Developer configs build_paths.sh + +# tools/health-preview.cjs output (rendered PNGs, regenerate with the tool) +preview/ diff --git a/app/app.css b/app/app.css index d95f977e..1d3cfffd 100644 --- a/app/app.css +++ b/app/app.css @@ -698,3 +698,681 @@ Button.permissions-primary-dimmed { .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
: 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; +} diff --git a/app/app.ts b/app/app.ts index 7a2f44f9..6880e4db 100644 --- a/app/app.ts +++ b/app/app.ts @@ -13,6 +13,34 @@ installNativeUserAgent() registerShareIntentHandler() registerPhoneRotation() +import { resyncSystemAppearance } from './native/system-appearance' +import { startLiveHealthSync, startAlignedRingPull } from './health/health-live' + +installNativeUserAgent() +registerShareIntentHandler() + +// 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() + +// Live system dark/light switches while the app is running were confirmed +// (Chris, both directions, 2026-09-02) to leave the Ghost companion's Terminal +// and Doc panes white-on-white and Rich View visually dark-locked -- while a +// COLD launch in either theme renders correctly. That proves the app.css +// .ns-dark rules themselves are right and the LIVE-UPDATE signal is the gap, +// not any one pane's styling -- see system-appearance.ts for the actual fix +// and why it resyncs from two triggers instead of trusting the framework's +// own automatic recolor alone. +Application.on(Application.systemAppearanceChangedEvent, resyncSystemAppearance) +Application.on(Application.resumeEvent, resyncSystemAppearance) + Application.run({ moduleName: 'app-root' }) // Don't place any code after the application has been started diff --git a/app/apps/all-apps.ts b/app/apps/all-apps.ts index 864b8536..06f40493 100644 --- a/app/apps/all-apps.ts +++ b/app/apps/all-apps.ts @@ -7,6 +7,7 @@ import terminalApp from "./terminal"; import filesApp from "./files"; import musicApp from "./music"; import nightscoutApp from "./nightscout"; +import healthApp from "./health"; import transcribeApp from "./transcribe"; import teleprompterApp from "./teleprompter"; import microphonesApp from "./microphones"; @@ -40,6 +41,7 @@ export const ALL_APPS: readonly AppDefinition[] = [ filesApp, musicApp, nightscoutApp, + healthApp, transcribeApp, teleprompterApp, microphonesApp, diff --git a/app/apps/health/health-app.ts b/app/apps/health/health-app.ts new file mode 100644 index 00000000..904899c3 --- /dev/null +++ b/app/apps/health/health-app.ts @@ -0,0 +1,198 @@ +/** + * 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, hypnogram, 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> = {}; + private stageBands: GlanceData["stageBands"] = []; + private fixture = false; + /** Index into GLANCE_PAGES. 0 is the overview. */ + private pageIndex = 0; + private timer: ReturnType | 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> = {}; + for (const metric of SAMPLE_METRICS) { + hourly[metric] = rollupSeries(samples, { + metric, + granularity: "hour", + startMs: today, + endMs: today + DAY_MS, + }); + } + this.hourly = hourly; + const night = sessions.find((session) => session.dayStartMs === today); + this.stageBands = night ? hypnogram(night) : []; + 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; +} diff --git a/app/apps/health/index.ts b/app/apps/health/index.ts new file mode 100644 index 00000000..db4e1043 --- /dev/null +++ b/app/apps/health/index.ts @@ -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; diff --git a/app/health/health-chart.ts b/app/health/health-chart.ts new file mode 100644 index 00000000..53407055 --- /dev/null +++ b/app/health/health-chart.ts @@ -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> = { + 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 = { + 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); +} diff --git a/app/health/health-derive.ts b/app/health/health-derive.ts new file mode 100644 index 00000000..ba6235b4 --- /dev/null +++ b/app/health/health-derive.ts @@ -0,0 +1,406 @@ +/** + * 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> = { + day: 1, + week: 7, + month: 30, + quarter: 90, +}; + +export const RANGE_LABELS: Readonly> = { + 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(); + 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; +} + +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 night = sleepSessions + .filter((session) => session.dayStartMs === dayStartMs) + .sort((a, b) => b.totalSec - a.totalSec)[0]; + 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: night ? sleepSummary(night) : null, + }; +} + +// =========================================================================== +// 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 = { + 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, + }; +} + +/** + * 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. + * + * Two sessions attributed to the same day are SUMMED rather than the longest + * winning. That differs from `dailySummary`, which picks the longest because it + * is answering "how did you sleep last night" with one headline number; here + * the column is the day's total time in each stage, and dropping a nap would + * make the bar disagree with the sleep total shown beside it. + */ +export function sleepNights( + sessions: readonly SleepSession[], + startMs: number, + endMs: number, +): SleepNight[] { + const byDay = new Map(); + 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, + })); +} + +/** + * 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; +} diff --git a/app/health/health-fixtures.ts b/app/health/health-fixtures.ts new file mode 100644 index 00000000..3bae7886 --- /dev/null +++ b/app/health/health-fixtures.ts @@ -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(); + 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 = { + 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; +} diff --git a/app/health/health-glance.ts b/app/health/health-glance.ts new file mode 100644 index 00000000..1e84c441 --- /dev/null +++ b/app/health/health-glance.ts @@ -0,0 +1,507 @@ +/** + * 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>; + /** 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); + return; + case "metric": + drawMetricDetail(image, size, fonts, page.metric, data); + return; + case "sleep": + drawSleepDetail(image, size, fonts, data); + return; + } +} + +// =========================================================================== +// 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, and the sample-data badge when the data is generated. + * + * 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, + fixture: boolean, +): void { + const { small } = fonts; + const y = size.height - small.lineHeight - 2; + image.drawText(small, MARGIN, y, hint, INK.faint); + if (fixture) drawTextRight(image, small, size.width - MARGIN, y, "Sample data", 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, "", data.fixture); + 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`, data.fixture); +} + +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)}`, data.fixture); +} + +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`, data.fixture); + 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`, data.fixture); +} diff --git a/app/health/health-ingest.ts b/app/health/health-ingest.ts new file mode 100644 index 00000000..d1d93a8e --- /dev/null +++ b/app/health/health-ingest.ts @@ -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.java`'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.java` 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; +} diff --git a/app/health/health-live.ts b/app/health/health-live.ts new file mode 100644 index 00000000..d7c2d73f --- /dev/null +++ b/app/health/health-live.ts @@ -0,0 +1,582 @@ +/** + * 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 { 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; + } +} + +/** + * The ring timestamps in a frame 4 hours ahead of real time, and that is our + * own doing: the handshake sets its clock to `now + 14400s`, because that is + * what a real Even write carries (verified against six of them). Even's app + * evidently subtracts the same offset on the way back out. We were not, so + * every hourly sample landed 4 hours in the future. + * + * MEASURED, not theorised. Stored samples read 09:00/10:00/11:00 local while + * the actual time was 07:15; minus four hours gives 05:00/06:00/07:00, which + * is exactly right for a ring that had just reported the current hour. + * + * ⚠ This value is PAIRED with the offset in `sendRingHandshake()`. They must + * move together. + * + * Both were hardcoded to 14400. As of 2026-09-12 both COMPUTE it: 14400 was + * only ever right because every capture behind this work was taken in EDT, + * where 14400s is the magnitude of the UTC offset. Computing it is identical + * today and survives DST. + * + * ⚠ MIND THE SIGN. The quantity is "how far AHEAD of real time the ring's clock + * runs", which is the magnitude of a west-of-UTC offset — positive 14400 in + * EDT. `getTimezoneOffset()` is already minutes WEST of UTC (+240 in EDT), so + * it is used as-is, NOT negated. Java's `TimeZone.getOffset()` uses the + * opposite convention and is negated there; the two agree on +14400. + * + * Worth recording because the first cut of this change got the sign backwards + * on both sides at once — consistently, so they stayed "paired", and still + * wrong by 8 hours. Only the handshake's own assertion log caught it. + * + * Note this direction is the OPPOSITE of the "ring stores naive local time" + * hypothesis (which predicts `epoch + utc_offset`, i.e. 4h behind). Measured + * behaviour is 4h ahead. The hypothesis is unconfirmed; the measurement rules. + */ +function ringClockOffsetMs(atMs: number): number { + return new Date(atMs).getTimezoneOffset() * 60 * 1000; +} + +/** + * Sleep timestamps need TWICE the correction the hourly samples need. + * + * ⚠ EMPIRICAL, AND THE MECHANISM IS UNEXPLAINED. Do not read a story into the + * factor of 2. The last time this file invented a tidy explanation for a ring + * clock quirk ("the ring stores naive local time") it was falsified the next + * day, which is why the hourly comment above ends with "the measurement rules". + * The same applies here, more so: nothing about a sleep record is known to + * differ from an hourly one in how it is stamped, and yet the correction does. + * + * The evidence, 2026-09-12, the first real sleep record off the hardware: + * `start_ts` decodes raw to 10:21:01 EDT. Chris confirmed the true window two + * independent ways - he slept "straight through from around 1:30 AM to 9:30 AM", + * and separately reported seeing only the first block with "another 4 or so + * hours after that". Under -4h the block is 06:21 -> 09:25, which puts the + * missing time BEFORE it and contradicts what the device showed. Under -8h it + * is 02:21 -> 05:25, leaving 05:25 -> 09:30 (4h05m) missing AFTER it, which is + * what he saw. + * + * Expressed as twice `ringClockOffsetMs` rather than a fresh 28800 so the + * November DST change moves the hourly correction and this one together. Like + * the hourly path it is evaluated at the RAW instant, so within ~8h of a DST + * switch it can pick the wrong side by an hour - the same caveat, deliberately + * kept identical rather than special-cased here. + */ +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); + } +} + +export function syncLiveRecords(): LiveSyncResult { + 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 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 { ...EMPTY, seen: size }; + + const { samples, sleep, skipped } = convertRecords(wire); + if (samples.length === 0 && sleep.length === 0) { + return { seen: size, 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); + if (samplesWritten > 0 || sleepWritten > 0) markLiveData(); + + // 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. + 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 | 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 | 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 }; diff --git a/app/health/health-phone-chart.ts b/app/health/health-phone-chart.ts new file mode 100644 index 00000000..7d97f18c --- /dev/null +++ b/app/health/health-phone-chart.ts @@ -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; + } +} diff --git a/app/health/health-seed.ts b/app/health/health-seed.ts new file mode 100644 index 00000000..22aa041b --- /dev/null +++ b/app/health/health-seed.ts @@ -0,0 +1,137 @@ +/** + * 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 { 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 { + try { + File.fromPath(livePath()).writeTextSync(JSON.stringify({ firstAtMs: Date.now() })); + } catch (error) { + console.warn("health live marker write failed", error); + } +} + +/** + * 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) File.fromPath(entity.path).removeSync(); + } + } catch (error) { + console.warn("health fixture purge failed", error); + } + clearFixtureMarker(); +} + +/** + * 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() }); + store.ingestSamples(samples); + store.ingestSleep(sleep); + const marker: Marker = { version: FIXTURE_VERSION, seededAtMs: Date.now(), days }; + File.fromPath(markerPath()).writeTextSync(JSON.stringify(marker)); + 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 { + try { + if (File.exists(markerPath())) File.fromPath(markerPath()).removeSync(); + } catch (error) { + console.warn("health fixture marker clear failed", error); + } +} diff --git a/app/health/health-store-files.ts b/app/health/health-store-files.ts new file mode 100644 index 00000000..0d3c3bbb --- /dev/null +++ b/app/health/health-store-files.ts @@ -0,0 +1,86 @@ +/** + * 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 { + try { + // `File.fromPath` creates the file when it is missing, and + // `appendTextSync` is the durable single-call append - deliberately not + // read-modify-write, which would put every record already on disk at + // risk on every new one. + File.fromPath(pathFor(name)).appendTextSync(text, (error) => { + console.warn(`health store append failed (${name})`, error); + }); + } catch (error) { + console.warn(`health store append threw (${name})`, error); + } + } + + write(name: string, text: string): void { + try { + File.fromPath(pathFor(name)).writeTextSync(text, (error) => { + console.warn(`health store write failed (${name})`, error); + }); + } catch (error) { + console.warn(`health store write threw (${name})`, error); + } + } + + list(): string[] { + try { + return healthFolder() + .getEntitiesSync() + .map((entity) => entity.name); + } catch (error) { + console.warn("health store list failed", error); + return []; + } + } +} + +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; +} diff --git a/app/health/health-store.ts b/app/health/health-store.ts new file mode 100644 index 00000000..9b686e9e --- /dev/null +++ b/app/health/health-store.ts @@ -0,0 +1,433 @@ +/** + * 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>>; +}; + +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>(); + private sleep: SleepSession[] | null = null; + private rollups: RollupFile | null = null; + + constructor(private readonly backend: HealthStorageBackend) {} + + // ------------------------------------------------------------------------- + // 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(); + 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 existing = shard.get(key); + if (existing && sameSample(existing, sample)) continue; + shard.set(key, sample); + const pending = byShard.get(name); + if (pending) pending.push(sample); + else byShard.set(name, [sample]); + } + let written = 0; + for (const [name, list] of byShard) { + const text = list.map((sample) => `${JSON.stringify(toLine(sample))}\n`).join(""); + this.backend.append(name, text); + written += list.length; + } + if (written > 0) this.updateRollupsFor(samples); + 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(); + 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, fresh.map((s) => `${JSON.stringify(s)}\n`).join("")); + } + 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 { + const file = this.loadRollups(); + const out = new Map(); + 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>(); + 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> = {}; + 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(); + 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> = {}; + 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 { + const held = this.shards.get(name); + if (held) return held; + const shard = new Map(); + 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; + } +} diff --git a/app/health/health-types.ts b/app/health/health-types.ts new file mode 100644 index 00000000..8739d5fc --- /dev/null +++ b/app/health/health-types.ts @@ -0,0 +1,231 @@ +/** + * The health record shapes, normalised for storage and display. + * + * These mirror `RingProtocol.java`'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> = { + heartRate: "Heart rate", + spo2: "Blood oxygen", + hrv: "HRV", + steps: "Steps", + sleep: "Sleep", +}; + +export const METRIC_UNITS: Readonly> = { + 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> = { + heartRate: "Heart rate", + spo2: "Blood oxygen", + hrv: "HRV", + steps: "Steps", + calories: "Calories", +}; + +export const SAMPLE_METRIC_UNITS: Readonly> = { + 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> = { + 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}`; +} diff --git a/app/health/sleep-stages.ts b/app/health/sleep-stages.ts new file mode 100644 index 00000000..2c1c2a44 --- /dev/null +++ b/app/health/sleep-stages.ts @@ -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> = { + 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 = { + wake: "Awake", + rem: "REM", + light: "Light", + deep: "Deep", + }; + return labels[stage]; +} diff --git a/tests/health-revisions.test.cjs b/tests/health-revisions.test.cjs new file mode 100644 index 00000000..5f1913d3 --- /dev/null +++ b/tests/health-revisions.test.cjs @@ -0,0 +1,162 @@ +// The 2026-09-10 design revisions, pinned where getting them wrong would be +// silent. +// +// These are not tests of "does it draw" - a chart's appearance is checked by +// rendering it (tools/health-preview.cjs writes a PNG of every surface without +// an emulator). What is worth a test here is the handful of places where the +// revision put a SPECIFIC rule in the code that a later reader would plausibly +// undo: +// +// 1. The two sleep stage orders, which differ ON PURPOSE and therefore look +// exactly like a typo to anyone who meets one without the other. +// 2. The nightly sleep series, which the diverging chart plots - a gap has to +// stay at its own position or every later night shifts a column. +// 3. The stat rows, where "Buckets" was removed because it was an +// implementation detail on screen. +// +// Everything runs on generated fixtures. No real health data is read. + +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { buildFixtures } = require("../.test-build/app/health/health-fixtures.js"); +const { + dailySummary, + sleepNights, + sleepSummary, + stageSeconds, +} = require("../.test-build/app/health/health-derive.js"); +const { + SLEEP_LANE_ORDER, + SLEEP_STACK_ORDER, + rangeAverageText, +} = require("../.test-build/app/health/health-chart.js"); +const { GLANCE_PAGES } = require("../.test-build/app/health/health-glance.js"); +const { startOfLocalDay, DAY_MS, SAMPLE_METRICS } = require("../.test-build/app/health/health-types.js"); + +test("the two sleep stage orders are stated in opposite directions but agree on screen", () => { + // Week/month/quarter: stacked upward from zero, deep at the bottom. + assert.deepEqual([...SLEEP_STACK_ORDER], ["deep", "rem", "light"]); + // One night: lanes listed downward, awake at the top. + assert.deepEqual([...SLEEP_LANE_ORDER], ["wake", "light", "rem", "deep"]); + + // The point worth pinning. The two orders were given in opposite directions + // (one bottom-to-top, one top-to-bottom) and therefore READ as contradictory, + // which is why the brief called the difference out as deliberate. Resolve + // both to the same direction and the three sleep stages land in the SAME + // vertical order: light highest, deep lowest. The only real difference is + // where awake goes - a lane above the others, or a bar below the zero line. + const stackTopToBottom = [...SLEEP_STACK_ORDER].reverse(); + const lanesTopToBottomWithoutWake = SLEEP_LANE_ORDER.filter((stage) => stage !== "wake"); + assert.deepEqual( + stackTopToBottom, + [...lanesTopToBottomWithoutWake], + "deep sits at the bottom in both views - do not 'fix' one to disagree with the other", + ); + + // Awake is in the lanes and NOT in the upward stack - it diverges downward. + assert.ok(!SLEEP_STACK_ORDER.includes("wake")); + assert.ok(SLEEP_LANE_ORDER.includes("wake")); +}); + +test("the nightly sleep series keeps gaps in position", () => { + const now = Date.now(); + const today = startOfLocalDay(now); + const startMs = today - 6 * DAY_MS; + const { sleep } = buildFixtures({ days: 7, nowMs: now }); + + const all = sleepNights(sleep, startMs, today + DAY_MS); + assert.equal(all.length, 7, "one entry per day in the window, filled or not"); + + // Drop the middle night and check the later ones do not slide left. + const middleDay = all[3].startMs; + const thinned = sleep.filter((session) => session.dayStartMs !== middleDay); + const withGap = sleepNights(thinned, startMs, today + DAY_MS); + assert.equal(withGap.length, 7); + assert.equal(withGap[3].hasData, false, "the removed night is a gap, not a shift"); + assert.equal(withGap[3].startMs, middleDay); + assert.deepEqual( + withGap.map((night) => night.startMs), + all.map((night) => night.startMs), + "every night keeps its own day on the axis", + ); +}); + +test("two sessions on one day are summed, not deduped to the longest", () => { + const today = startOfLocalDay(Date.now()); + const night = (totalSec, wakeSec) => ({ + dayStartMs: today, + startMs: today, + endMs: today, + totalSec, + wakeSec, + remSec: totalSec * 0.2, + lightSec: totalSec * 0.6, + deepSec: totalSec * 0.2, + segments: [], + timeResolved: true, + }); + const nights = sleepNights([night(3600, 300), night(1800, 60)], today, today + DAY_MS); + assert.equal(nights.length, 1); + assert.equal(nights[0].wakeSec, 360, "a nap's wake time counts too"); + assert.ok( + Math.abs(nights[0].lightSec - (3600 + 1800) * 0.6) < 1e-6, + "stage totals add across both sessions", + ); +}); + +test("a stage's lane duration comes from the named totals", () => { + const now = Date.now(); + const { sleep } = buildFixtures({ days: 2, nowMs: now }); + const summary = sleepSummary(sleep[0]); + // The four lanes must account for the whole time in bed, which is exactly + // the property that does NOT depend on the raw stage-id mapping. + const summed = SLEEP_LANE_ORDER.reduce( + (total, stage) => total + stageSeconds(stage, summary), + 0, + ); + assert.ok( + Math.abs(summed - (summary.totalSec + summary.wakeSec)) < 1, + `lanes should sum to time in bed, got ${summed}`, + ); + assert.equal(stageSeconds("wake", summary), summary.wakeSec); +}); + +test("the glance line reads as a range and an average", () => { + assert.equal( + rangeAverageText({ min: 60, max: 98, avg: 72.6, hasData: true }, "bpm"), + "60-98 bpm, avg 73", + ); + assert.equal( + rangeAverageText({ min: 0, max: 0, avg: 0, hasData: false }, "bpm"), + "--", + "no data shows a dash, never a zero", + ); + // ASCII hyphen only: Terminus has no en dash and would render the default + // char, putting a "?" in the middle of the number. + const text = rangeAverageText({ min: 40, max: 62, avg: 51, hasData: true }, "ms"); + for (const char of text) { + assert.ok(char.codePointAt(0) < 128, `"${char}" is outside ASCII`); + } +}); + +test("HRV reached the daily summary", () => { + const now = Date.now(); + const today = startOfLocalDay(now); + const { samples, sleep } = buildFixtures({ days: 2, nowMs: now }); + const summary = dailySummary(samples, sleep, today); + assert.ok(summary.hrv, "HRV is on the glance now - Chris revised the spec"); + assert.ok(summary.hrv.hasData); + assert.ok(summary.hrv.max >= summary.hrv.min); +}); + +test("the glasses cursor walks the summary, every parameter, then sleep", () => { + assert.equal(GLANCE_PAGES[0].kind, "overview", "the glance is where it opens"); + assert.equal(GLANCE_PAGES[GLANCE_PAGES.length - 1].kind, "sleep"); + const walked = GLANCE_PAGES.filter((page) => page.kind === "metric").map((page) => page.metric); + assert.deepEqual( + [...walked].sort(), + [...SAMPLE_METRICS].sort(), + "every measured parameter is reachable by scrolling", + ); +}); diff --git a/tests/health.test.cjs b/tests/health.test.cjs new file mode 100644 index 00000000..4e0984a7 --- /dev/null +++ b/tests/health.test.cjs @@ -0,0 +1,427 @@ +// The health feature's logic, pinned where getting it wrong would be silent. +// +// The three things worth a test here are not the arithmetic - they are the +// places where a bug would quietly produce a plausible wrong answer: +// +// 1. The STORE's durability contract. A health record may be the only copy +// that will ever exist (the ring appears to discard backlog it thinks it +// delivered), so "an append never rewrites a file that already holds +// records" and "a re-sync of the same hour corrects rather than +// duplicates" are the properties the whole feature rests on. +// 2. The INGEST rules that decline to guess - an unanchored hourly page is +// dropped, and step buckets do not get invented timestamps. +// 3. SLEEP, where the percentages must come from the named totals (which +// need no stage-id mapping) while only the hypnogram depends on the ids. +// +// Everything runs on generated fixtures. No real health data is read. + +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { HealthStore } = require("../.test-build/app/health/health-store.js"); +const { buildFixtures } = require("../.test-build/app/health/health-fixtures.js"); +const { + dailySummary, + sleepSummary, + hypnogram, + rollupSeries, + bandIsMeaningful, + formatDuration, +} = require("../.test-build/app/health/health-derive.js"); +const { convertRecords, sleepIdentityHolds } = require("../.test-build/app/health/health-ingest.js"); +const { + STAGE_NAME_BY_ID, + STAGE_MAPPING_CONFIRMED, + stageNameForId, +} = require("../.test-build/app/health/sleep-stages.js"); +const { + startOfLocalDay, + DAY_MS, + HOUR_MS, + TEN_MINUTES_MS, +} = require("../.test-build/app/health/health-types.js"); + +/** An in-memory backend that also records how each file was touched. */ +function memoryBackend() { + const files = new Map(); + const ops = []; + return { + ops, + files, + exists: (name) => files.has(name), + read: (name) => files.get(name) ?? null, + append(name, text) { + ops.push({ op: "append", name }); + files.set(name, (files.get(name) ?? "") + text); + }, + write(name, text) { + ops.push({ op: "write", name }); + files.set(name, text); + }, + list: () => [...files.keys()], + }; +} + +const HOUR = 3600000; + +function sample(metric, startMs, min, max, avg, total) { + return { metric, startMs, spanMs: HOUR, min, max, avg, total: total ?? avg }; +} + +// --------------------------------------------------------------------------- +// Storage + +test("a stored sample survives a fresh store over the same files", () => { + const backend = memoryBackend(); + const first = new HealthStore(backend); + const start = startOfLocalDay(Date.now()); + first.ingestSamples([sample("heartRate", start, 55, 90, 70)]); + + const second = new HealthStore(backend); + const held = second.samplesInRange(start, start + DAY_MS); + assert.equal(held.length, 1); + assert.equal(held[0].avg, 70); +}); + +test("a sample file is only ever appended to, never rewritten", () => { + const backend = memoryBackend(); + const store = new HealthStore(backend); + const start = startOfLocalDay(Date.now()); + for (let hour = 0; hour < 6; hour += 1) { + store.ingestSamples([sample("heartRate", start + hour * HOUR, 50 + hour, 90, 70 + hour)]); + } + const sampleWrites = backend.ops.filter( + (entry) => entry.op === "write" && entry.name.startsWith("samples-"), + ); + // The rollup cache is rewritten freely - it is derived. The shards are not. + assert.equal(sampleWrites.length, 0); + assert.ok(backend.ops.some((entry) => entry.op === "append")); +}); + +test("re-storing an unchanged bucket writes nothing; a changed one corrects it", () => { + const backend = memoryBackend(); + const store = new HealthStore(backend); + const start = startOfLocalDay(Date.now()); + + assert.equal(store.ingestSamples([sample("heartRate", start, 55, 90, 70)]), 1); + // The live poller re-reads the same capped list every 30 minutes; a no-op + // here is what stops that appending a duplicate line forever. + assert.equal(store.ingestSamples([sample("heartRate", start, 55, 90, 70)]), 0); + // The current hour genuinely changes as it fills up. Later line wins. + assert.equal(store.ingestSamples([sample("heartRate", start, 55, 104, 74)]), 1); + + const reloaded = new HealthStore(backend); + const held = reloaded.samplesInRange(start, start + DAY_MS); + assert.equal(held.length, 1); + assert.equal(held[0].max, 104); +}); + +test("a corrupt rollup cache is rebuilt from the shards rather than trusted", () => { + const backend = memoryBackend(); + const store = new HealthStore(backend); + const start = startOfLocalDay(Date.now()); + store.ingestSamples([sample("heartRate", start, 55, 90, 70), sample("heartRate", start + HOUR, 60, 100, 80)]); + + backend.files.set("rollups.json", "{ not json"); + const recovered = new HealthStore(backend); + const rollups = recovered.dailyRollups("heartRate", start, start + DAY_MS); + const day = rollups.get(start); + assert.ok(day, "the day should be recovered from the raw shards"); + assert.equal(day.min, 55); + assert.equal(day.max, 100); + assert.equal(day.count, 2); +}); + +test("a single unreadable line does not cost the rest of the file", () => { + const backend = memoryBackend(); + const store = new HealthStore(backend); + const start = startOfLocalDay(Date.now()); + store.ingestSamples([sample("heartRate", start, 55, 90, 70)]); + const name = [...backend.files.keys()].find((key) => key.startsWith("samples-")); + backend.files.set(name, `${backend.files.get(name)}{ truncated\n`); + store.ingestSamples([sample("heartRate", start + HOUR, 60, 100, 80)]); + + const reloaded = new HealthStore(backend); + assert.equal(reloaded.samplesInRange(start, start + DAY_MS).length, 2); +}); + +// --------------------------------------------------------------------------- +// Ingest: the rules that decline to guess + +test("an unanchored hourly page is dropped, not dated", () => { + const result = convertRecords([ + { + kind: "hourly", + metric: "heartRate", + anchorMs: null, + groups: [{ hourIndex: 0, avg: 70, max: 90, min: 55 }], + }, + ]); + assert.equal(result.samples.length, 0); + assert.equal(result.skipped.length, 1); + assert.match(result.skipped[0].why, /anchor/); +}); + +test("an anchored hourly page dates each group from the anchor", () => { + const anchor = startOfLocalDay(Date.now()); + const result = convertRecords([ + { + kind: "hourly", + metric: "hrv", + anchorMs: anchor, + groups: [ + { hourIndex: 0, avg: 40, max: 40, min: 40 }, + { hourIndex: 5, avg: 52, max: 55, min: 50 }, + ], + }, + ]); + assert.equal(result.samples.length, 2); + assert.equal(result.samples[0].startMs, anchor); + assert.equal(result.samples[1].startMs, anchor + 5 * HOUR_MS); +}); + +// The index is cracked (2026-09-12): bucket i starts at anchor + i * 10 minutes. +// This test previously asserted the opposite - one day-span total, buckets +// deliberately discarded - which was the honest call while the index was only +// trusted as an identity. It is now the placement contract. +test("steps place each bucket at anchor + index * ten minutes", () => { + const anchor = startOfLocalDay(Date.now()); + const result = convertRecords([ + { + kind: "steps", + anchorMs: anchor, + buckets: [ + { index: 0, steps: 100, activeCalories: 4, totalCalories: 15 }, + { index: 130, steps: 260, activeCalories: 9, totalCalories: 21 }, + ], + }, + ]); + const steps = result.samples.filter((entry) => entry.metric === "steps"); + assert.equal(steps.length, 2, "one sample per bucket, not one day total"); + assert.equal(steps[0].startMs, anchor); + assert.equal(steps[0].total, 100); + assert.equal(steps[0].spanMs, TEN_MINUTES_MS); + assert.equal(steps[1].startMs, anchor + 130 * TEN_MINUTES_MS); + assert.equal(steps[1].total, 260); + + // The day total is now `sum` and ONLY `sum` - `max`/`avg` are per-bucket. + // Every reader was checked against this on 2026-09-12. + assert.equal( + steps.reduce((acc, entry) => acc + entry.total, 0), + 360, + ); + + const calories = result.samples.filter((entry) => entry.metric === "calories"); + assert.equal(calories.length, 2); + assert.equal(calories[1].startMs, anchor + 130 * TEN_MINUTES_MS); + assert.equal(calories[1].total, 21); + + // Nothing is declined any more - the buckets are placed, not discarded. + assert.equal(result.skipped.length, 0); +}); + +test("a sleep session is stored with its time marked unresolved", () => { + const result = convertRecords([ + { + kind: "sleep", + startTs: 90000, + endTs: 90000 + 21600, + totalSec: 20400, + wakeSec: 1200, + remSec: 3600, + lightSec: 12000, + deepSec: 4800, + segments: [{ stageId: 2, halfMinutes: 720 }], + receivedAtMs: Date.now(), + }, + ]); + assert.equal(result.sleep.length, 1); + assert.equal(result.sleep[0].timeResolved, false); + assert.equal(result.sleep[0].dayStartMs, startOfLocalDay(Date.now())); +}); + +// The first real sleep record off the hardware, 2026-09-12, verbatim from +// `files/health/sleep.jsonl` under com.faceclaw.app. It is here as a FROZEN +// known-good: the -8h correction was derived from Chris confirming the window +// two independent ways, and a future change that quietly makes it -4h again +// (or 0h, which is what shipped first) should fail a test rather than wait to +// be noticed in a chart. +const REAL_SLEEP_RECORD = { + kind: "sleep", + startTs: 1789222861, + endTs: 1789233931, + totalSec: 10440, + wakeSec: 630, + remSec: 1620, + lightSec: 5880, + deepSec: 2940, + segments: [ + { stageId: 0, halfMinutes: 21 }, + { stageId: 2, halfMinutes: 42 }, + { stageId: 3, halfMinutes: 36 }, + { stageId: 2, halfMinutes: 40 }, + { stageId: 1, halfMinutes: 36 }, + { stageId: 2, halfMinutes: 42 }, + { stageId: 3, halfMinutes: 62 }, + { stageId: 2, halfMinutes: 46 }, + { stageId: 1, halfMinutes: 18 }, + { stageId: 2, halfMinutes: 26 }, + ], + receivedAtMs: 1789234000000, +}; + +test("a clock correction promotes a sleep session to a real placement", () => { + const rawStartMs = REAL_SLEEP_RECORD.startTs * 1000; + // Twice the hourly ring-clock offset, computed the way health-live.ts + // computes it - so this says what the RULE is rather than restating a + // constant that would rot at the November DST change. + const correction = 2 * new Date(rawStartMs).getTimezoneOffset() * 60 * 1000; + + const result = convertRecords([{ ...REAL_SLEEP_RECORD, clockCorrectionMs: correction }]); + assert.equal(result.sleep.length, 1); + const night = result.sleep[0]; + + assert.equal(night.timeResolved, true, "a corrected session is placed, not unresolved"); + assert.equal(night.startMs, rawStartMs - correction); + assert.equal(night.endMs, REAL_SLEEP_RECORD.endTs * 1000 - correction); + // The wake-up day, not the day it happened to be received on. + assert.equal(night.dayStartMs, startOfLocalDay(night.endMs)); + // The correction must move where the night sits, never how long it was. + assert.equal(night.endMs - night.startMs, 11070 * 1000); + assert.equal(night.totalSec, 10440); +}); + +test("the real 2026-09-12 record decodes to the window Chris confirmed", (t) => { + // EDT only: the known-good is a wall-clock reading and the assertion is + // meaningless in another zone. Skipped rather than weakened elsewhere. + if (new Date(REAL_SLEEP_RECORD.startTs * 1000).getTimezoneOffset() !== 240) { + t.skip("not EDT"); + return; + } + const result = convertRecords([{ ...REAL_SLEEP_RECORD, clockCorrectionMs: 8 * 3600 * 1000 }]); + const night = result.sleep[0]; + const local = (ms) => new Date(ms).toLocaleString("sv-SE", { timeZone: "America/New_York" }); + assert.equal(local(night.startMs), "2026-09-12 02:21:01"); + assert.equal(local(night.endMs), "2026-09-12 05:25:31"); +}); + +// --------------------------------------------------------------------------- +// Sleep + +test("stage percentages come from the named totals, not from the stage ids", () => { + const session = { + dayStartMs: startOfLocalDay(Date.now()), + startMs: 0, + endMs: 0, + totalSec: 20000, + wakeSec: 1000, + remSec: 4000, + lightSec: 12000, + deepSec: 4000, + // Deliberately unmappable ids: the percentages must not care. + segments: [{ stageId: 9, halfMinutes: 700 }], + timeResolved: true, + }; + const summary = sleepSummary(session); + assert.equal(Math.round(summary.remPercent), 20); + assert.equal(Math.round(summary.lightPercent), 60); + assert.equal(Math.round(summary.deepPercent), 20); + // total / (total + wake) = 20000 / 21000 + assert.equal(Math.round(summary.efficiencyPercent), 95); + // ...while the hypnogram, which does depend on the ids, says so. + assert.equal(hypnogram(session)[0].stage, null); +}); + +test("the stage-id mapping is the one named place, and it is the derived one", () => { + assert.equal(stageNameForId(0), "wake"); + assert.equal(stageNameForId(1), "rem"); + assert.equal(stageNameForId(2), "light"); + assert.equal(stageNameForId(3), "deep"); + assert.equal(stageNameForId(4), null); + assert.equal(Object.keys(STAGE_NAME_BY_ID).length, 4); + // Pinned deliberately: flipping this is the confirmation step, and it should + // be a decision someone makes, not something that drifts. + assert.equal(STAGE_MAPPING_CONFIRMED, false); +}); + +test("no sleep-quality composite is exposed", () => { + const summary = sleepSummary({ + dayStartMs: 0, startMs: 0, endMs: 0, + totalSec: 20000, wakeSec: 1000, remSec: 4000, lightSec: 12000, deepSec: 4000, + segments: [], timeResolved: true, + }); + const invented = Object.keys(summary).filter((key) => /quality|score/i.test(key)); + assert.deepEqual(invented, []); +}); + +// --------------------------------------------------------------------------- +// Series and fixtures + +test("a range with no data comes back as gaps at the right positions", () => { + const start = startOfLocalDay(Date.now()); + const points = rollupSeries([sample("heartRate", start + 3 * HOUR, 55, 90, 70)], { + metric: "heartRate", + granularity: "hour", + startMs: start, + endMs: start + DAY_MS, + }); + assert.equal(points.length, 24); + assert.equal(points[0].count, 0); + assert.equal(points[3].count, 1); + assert.equal(points[3].avg, 70); +}); + +test("the band is drawn for heart rate and dropped for a collapsed metric", () => { + const start = startOfLocalDay(Date.now()); + const spread = []; + const flat = []; + for (let hour = 0; hour < 12; hour += 1) { + spread.push({ startMs: start + hour * HOUR, spanMs: HOUR, min: 60, max: 92, avg: 74, sum: 74, count: 1 }); + flat.push({ startMs: start + hour * HOUR, spanMs: HOUR, min: 97, max: 97, avg: 97, sum: 97, count: 1 }); + } + assert.equal(bandIsMeaningful(spread), true); + assert.equal(bandIsMeaningful(flat), false); +}); + +test("the fixtures reproduce the shapes the real export has", () => { + const now = Date.now(); + const { samples, sleep } = buildFixtures({ days: 7, nowMs: now }); + + const hourly = samples.filter((entry) => entry.metric === "heartRate"); + assert.ok(hourly.every((entry) => entry.spanMs === HOUR_MS), "heart rate is hourly"); + const stepBuckets = samples.filter((entry) => entry.metric === "steps"); + assert.ok(stepBuckets.every((entry) => entry.spanMs === 600000), "steps are ten-minute"); + + // Heart rate has a real spread; SpO2 mostly does not. Both were measured off + // the export before the generator was written. + const hrSpread = hourly.filter((entry) => entry.max > entry.min).length / hourly.length; + const spo2 = samples.filter((entry) => entry.metric === "spo2"); + const spo2Spread = spo2.filter((entry) => entry.max > entry.min).length / spo2.length; + assert.ok(hrSpread > 0.9, `heart rate should nearly always have spread, got ${hrSpread}`); + assert.ok(spo2Spread < 0.15, `SpO2 should rarely have spread, got ${spo2Spread}`); + + // Every generated night satisfies the same identity real records satisfy. + for (const night of sleep) { + assert.ok( + sleepIdentityHolds(night), + "segment run must account for exactly the time in bed", + ); + } +}); + +test("the daily summary picks last night and today's own buckets", () => { + const now = Date.now(); + const today = startOfLocalDay(now); + const { samples, sleep } = buildFixtures({ days: 3, nowMs: now }); + const summary = dailySummary(samples, sleep, today); + assert.equal(summary.dayStartMs, today); + assert.ok(summary.heartRate.hasData); + assert.ok(summary.sleep, "there should be a night attributed to today"); + assert.ok(summary.steps >= 0); +}); + +test("durations format the way the glance prints them", () => { + assert.equal(formatDuration(0), "--"); + assert.equal(formatDuration(6 * 3600 + 12 * 60), "6h 12m"); + assert.equal(formatDuration(45 * 60), "45m"); +}); diff --git a/tests/tsconfig.json b/tests/tsconfig.json index b575de39..f221361f 100644 --- a/tests/tsconfig.json +++ b/tests/tsconfig.json @@ -30,6 +30,15 @@ "../app/apps/evenhub/containers.ts", "../app/apps/timer/timer-model.ts", "../app/apps/teleprompter/script-tracker.ts", - "../app/apps/nightscout/nightscout-alerts.ts" + "../app/apps/nightscout/nightscout-alerts.ts", + "../app/health/health-types.ts", + "../app/health/health-derive.ts", + "../app/health/health-store.ts", + "../app/health/health-ingest.ts", + "../app/health/health-fixtures.ts", + "../app/health/sleep-stages.ts", + "../app/health/health-chart.ts", + "../app/health/health-glance.ts", + "../app/health/health-phone-chart.ts" ] } diff --git a/tools/health-preview.cjs b/tools/health-preview.cjs new file mode 100644 index 00000000..40157c5f --- /dev/null +++ b/tools/health-preview.cjs @@ -0,0 +1,376 @@ +#!/usr/bin/env node +/** + * Render every health surface to a PNG, under plain node, with no emulator. + * + * ## Why this exists + * + * The first pass at this feature verified its layout by building an Android + * AVD, booting it headless, installing the app and screenshotting it. That + * works, and it cost most of a three-hour dispatch to set up for a question - + * "does this layout look right?" - that never needed a device in the loop. + * + * Everything the health screens draw goes into a `GrayImage` through code that + * imports nothing from NativeScript: `health/health-chart.ts` (the primitives), + * `health/health-glance.ts` (the glasses pages) and + * `health/health-phone-chart.ts` (the phone bitmap). So this script calls the + * REAL drawing functions with fixture data and writes what comes back. The + * previews cannot drift from the app, because they are not a second + * implementation of it - they are the same functions the device calls. + * + * ## The one platform shim, and why it is honest + * + * `graphics/bdffont.ts` reads the bundled .bdf through + * `knownFolders.currentApp()`. That is the only NativeScript call anywhere + * under the drawing code, so it gets one stub backed by node:fs, pointed at the + * same `app/fonts/` files the device loads. The glyphs are the real glyphs. + * + * ⚠ FONT CAVEAT, worth knowing before reading a preview as gospel. The device's + * DEFAULT UI font is Roboto-Light at 14px, a TTF - and TTF rasterization on + * this project happens in Java (`TtfFont.load` bails unless `global.isAndroid`), + * so it cannot run here. Off Android the shipping code falls back to the + * Terminus bitmap faces, which is what these previews use. That is a real, + * user-selectable configuration rather than a preview-only invention, but it is + * not the default, and text will not be pixel-identical to a device screenshot. + * + * The layouts are written against `font.lineHeight` / `measureText` rather than + * fixed offsets, so what actually matters is whether they survive the font + * metric range. `--big` re-renders everything one bitmap size up (small 12px -> + * 16px, large 24px -> 32px) to check exactly that; the guaranteed small-font + * line-height band is 12..21 (see ui-fonts.ts), and 12 and 16 sit inside it. + * + * ## Use + * + * npx tsc -p tests/tsconfig.json # or: npm test + * node tools/health-preview.cjs [--out DIR] [--big] [--real DIR] + * + * ## --real: the same surfaces, on data pulled off the phone + * + * `--real DIR` reads a `sleep.jsonl` (and, if present, a `samples-*.jsonl`) + * copied out of `files/health/` under `com.faceclaw.app` and renders the sleep + * surfaces from THAT instead of from fixtures. Nothing about the drawing + * changes - it is the same `drawGlancePage` and `renderPhoneChart` - so the + * question it answers is only ever "what does the real data look like in the + * layout we already have", never "should the layout be different". + * + * A stored session written by a pre-correction build carries + * `timeResolved: false` and RAW ring seconds. Those are run back through the + * shipping `convertRecords()` with the real clock correction, so the preview + * shows what the phone will store after the fix rather than a hand-placed + * guess. A session already marked resolved is used as-is and not corrected + * twice. + */ + +const fs = require("node:fs"); +const path = require("node:path"); +const Module = require("node:module"); + +const ROOT = path.resolve(__dirname, ".."); +const APP = path.join(ROOT, "app"); +const BUILD = path.join(ROOT, ".test-build", "app"); + +// --- the one platform shim ------------------------------------------------- +const nsCoreStub = { + knownFolders: { + currentApp: () => ({ + getFile: (relative) => ({ + readTextSync: () => fs.readFileSync(path.join(APP, relative), "utf8"), + }), + }), + }, +}; +const realLoad = Module._load; +Module._load = function (request) { + if (request === "@nativescript/core") return nsCoreStub; + return realLoad.apply(this, arguments); +}; + +if (!fs.existsSync(BUILD)) { + console.error(`No ${path.relative(ROOT, BUILD)} - run: npx tsc -p tests/tsconfig.json`); + process.exit(1); +} + +const { GrayImage } = require(path.join(BUILD, "graphics/image.js")); +const { getFont } = require(path.join(BUILD, "graphics/bdffont.js")); +const { buildFixtures } = require(path.join(BUILD, "health/health-fixtures.js")); +const { + dailySummary, + hypnogram, + rollupSeries, + shortWeekday, + sleepNights, + sleepSummary, + stageSeconds, + formatDuration, +} = require(path.join(BUILD, "health/health-derive.js")); +const { drawGlancePage, GLANCE_PAGES } = require(path.join(BUILD, "health/health-glance.js")); +const { convertRecords } = require(path.join(BUILD, "health/health-ingest.js")); +const { HealthStore } = require(path.join(BUILD, "health/health-store.js")); +const { renderPhoneChart } = require(path.join(BUILD, "health/health-phone-chart.js")); +const { stageLabel } = require(path.join(BUILD, "health/sleep-stages.js")); +const { DAY_MS, SAMPLE_METRICS, startOfLocalDay } = require(path.join(BUILD, "health/health-types.js")); +const UPNG = require("upng-js"); + +// --- arguments ------------------------------------------------------------- +const args = process.argv.slice(2); +const big = args.includes("--big"); +const realIndex = args.indexOf("--real"); +const REAL_DIR = realIndex >= 0 && args[realIndex + 1] ? path.resolve(args[realIndex + 1]) : null; +const outIndex = args.indexOf("--out"); +const OUT = path.resolve( + outIndex >= 0 && args[outIndex + 1] ? args[outIndex + 1] : path.join(ROOT, "preview"), +); +fs.mkdirSync(OUT, { recursive: true }); + +const small = getFont(big ? "terminus16" : "terminus12"); +const large = getFont(big ? "terminus32" : "terminus24"); +const fonts = { small, large }; + +// --- real data, when asked for --------------------------------------------- +/** + * `HealthStorageBackend` over a plain directory. + * + * Reading the pulled files THROUGH the real store, rather than parsing them + * here, is the same rule the rest of this tool follows. The on-disk sample line + * is a compact seven-key shape (`{m,t,s,n,x,a,u}`) that only `health-store.ts` + * knows how to read; a hand-rolled parser for it in a preview script is exactly + * the kind of second implementation that drifts. Read-only - `append`/`write` + * throw rather than quietly doing nothing, so a preview can never mutate a + * pulled copy of real data. + */ +class DirBackend { + constructor(dir) { + this.dir = dir; + } + exists(name) { + return fs.existsSync(path.join(this.dir, name)); + } + read(name) { + return this.exists(name) ? fs.readFileSync(path.join(this.dir, name), "utf8") : null; + } + append() { + throw new Error("health-preview is read-only"); + } + write() { + throw new Error("health-preview is read-only"); + } + list() { + return fs.readdirSync(this.dir); + } +} + +/** + * Put a stored session in the frame the corrected build will store it in. + * + * The correction is NOT applied here by hand - the record is turned back into + * the wire shape and pushed through the real `convertRecords()`, so if that + * function is wrong the preview is wrong in exactly the same way the phone is, + * which is the only useful behaviour for a check like this. + */ +function resolveStoredSleep(stored) { + if (stored.timeResolved) return stored; + const startTs = Math.round(stored.startMs / 1000); + const endTs = Math.round(stored.endMs / 1000); + const correction = 2 * new Date(stored.startMs).getTimezoneOffset() * 60 * 1000; + const { sleep } = convertRecords([ + { + kind: "sleep", + startTs, + endTs, + totalSec: stored.totalSec, + wakeSec: stored.wakeSec, + remSec: stored.remSec, + lightSec: stored.lightSec, + deepSec: stored.deepSec, + segments: stored.segments, + receivedAtMs: stored.startMs, + clockCorrectionMs: correction, + }, + ]); + return sleep[0]; +} + +function loadReal(dir) { + const store = new HealthStore(new DirBackend(dir)); + const sleep = store.sleepSessions().map(resolveStoredSleep); + if (sleep.length === 0) { + console.error(`No sleep sessions in ${dir}/sleep.jsonl`); + process.exit(1); + } + // Pin the clock to mid-afternoon of the most recent night's WAKE-UP day, so + // "today" is the day that night belongs to and the glance reads like a real + // one rather than an empty day. + const latest = sleep.reduce((a, b) => (b.dayStartMs > a.dayStartMs ? b : a)); + const nowMs = latest.dayStartMs + 15 * 3600 * 1000 + 20 * 60 * 1000; + // A bounded window, not (0, MAX): samplesInRange walks a shard per MONTH, so + // an open range asks it to name a few million files and it returns nothing. + // A quarter back covers every view this tool renders. + const samples = store.samplesInRange(nowMs - 120 * DAY_MS, nowMs + DAY_MS); + console.log(`real data: ${sleep.length} sleep session(s), ${samples.length} samples`); + for (const night of sleep) { + console.log( + ` night ${new Date(night.startMs).toString()}\n` + + ` -> ${new Date(night.endMs).toString()}` + + ` total ${night.totalSec}s wake ${night.wakeSec}s` + + ` timeResolved=${night.timeResolved}`, + ); + } + return { samples, sleep, nowMs }; +} + +// --- data ------------------------------------------------------------------ +// A fixed clock so a preview is reproducible and its date caption is stable. +// Mid-afternoon, so "today so far" is a partial day like a real glance. +const real = REAL_DIR ? loadReal(REAL_DIR) : null; +const NOW = real ? real.nowMs : new Date(2026, 8, 10, 15, 20, 0).getTime(); +const TODAY = startOfLocalDay(NOW); +const fixtures = real + ? { samples: real.samples, sleep: real.sleep } + : buildFixtures({ days: 95, nowMs: NOW, seed: 0x5eed }); + +const todaySamples = fixtures.samples.filter( + (sample) => sample.startMs >= TODAY && sample.startMs < TODAY + DAY_MS, +); +const summary = dailySummary(todaySamples, fixtures.sleep, TODAY); +const lastNight = fixtures.sleep.find((session) => session.dayStartMs === TODAY); + +const hourly = {}; +for (const metric of SAMPLE_METRICS) { + hourly[metric] = rollupSeries(todaySamples, { + metric, + granularity: "hour", + startMs: TODAY, + endMs: TODAY + DAY_MS, + }); +} + +const glanceData = { + summary, + hourly, + stageBands: lastNight ? hypnogram(lastNight) : [], + nowMs: NOW, + // The badge the glasses footer draws. It must follow the DATA, or a real + // render comes out stamped "Sample data" and the preview lies about the one + // thing it exists to show. + fixture: !real, +}; + +// --- PNG out --------------------------------------------------------------- +const written = []; + +function writePng(name, image) { + const baked = image.withDrawsBaked(); + const rgba = new Uint8Array(baked.width * baked.height * 4); + for (let i = 0; i < baked.pixels.length; i += 1) { + const value = baked.pixels[i]; + rgba[i * 4] = value; + rgba[i * 4 + 1] = value; + rgba[i * 4 + 2] = value; + rgba[i * 4 + 3] = 255; + } + const file = path.join(OUT, `${REAL_DIR ? "real-" : ""}${name}${big ? "-big" : ""}.png`); + fs.writeFileSync(file, Buffer.from(UPNG.encode([rgba.buffer], baked.width, baked.height, 0))); + + // A blank canvas would otherwise be a silent pass, and a page that drew + // nothing is exactly the failure a preview is supposed to catch. + let lit = 0; + for (const value of baked.pixels) if (value > 0) lit += 1; + const inkPercent = ((lit / baked.pixels.length) * 100).toFixed(1); + written.push({ name: path.basename(file), size: `${baked.width}x${baked.height}`, ink: `${inkPercent}%` }); + if (lit === 0) console.error(` !! ${file} is entirely blank`); +} + +// --- the glasses: 640x480, the G2 lens ------------------------------------ +const LENS = { width: 640, height: 480 }; +GLANCE_PAGES.forEach((page, index) => { + const name = + page.kind === "overview" ? "overview" : page.kind === "sleep" ? "sleep" : page.metric; + const image = new GrayImage(LENS.width, LENS.height, 0); + drawGlancePage(image, LENS, fonts, page, glanceData); + writePng(`glasses-${String(index + 1).padStart(2, "0")}-${name}`, image); +}); + +// --- the phone ------------------------------------------------------------- +/** + * Two widths, both real: 411dp is the Fold 7's cover screen (the compact + * layout), 750dp its inner screen (expanded). Both are the numbers the first + * pass measured on screen in the emulator, so the previews line up with the + * readout in those screenshots. The chart renders at RENDER_SCALE 2 into a box + * of (width - 32)dp, matching health-view-model.ts. + */ +const RENDER_SCALE = 2; +const PHONE_LAYOUTS = [ + { name: "narrow", widthDp: 411, chartHeightDp: 190 }, + { name: "wide", widthDp: 750, chartHeightDp: 380 }, +]; + +function phoneChart(layout, name, content) { + const image = renderPhoneChart({ + width: Math.round((layout.widthDp - 32) * RENDER_SCALE), + height: Math.round(layout.chartHeightDp * RENDER_SCALE), + font: small, + content, + }); + writePng(`phone-${layout.name}-${name}`, image); +} + +function metricContent(metric, granularity, days) { + const startMs = TODAY - (days - 1) * DAY_MS; + const points = rollupSeries(fixtures.samples, { + metric, + granularity, + startMs, + endMs: TODAY + DAY_MS, + }); + return { + kind: "metric", + metric, + points, + mode: metric === "steps" || metric === "calories" ? "bars" : "band", + xLabel: (point) => + granularity === "hour" + ? `${new Date(point.startMs).getHours()}` + : days <= 7 + ? shortWeekday(point.startMs) + : `${new Date(point.startMs).getDate()}`, + }; +} + +function nightsContent(days) { + const startMs = TODAY - (days - 1) * DAY_MS; + return { + kind: "nights", + nights: sleepNights(fixtures.sleep, startMs, TODAY + DAY_MS), + xLabel: (night) => + days <= 7 ? shortWeekday(night.startMs) : `${new Date(night.startMs).getDate()}`, + }; +} + +function lanesContent() { + const summaryOfNight = lastNight ? sleepSummary(lastNight) : null; + return { + kind: "lanes", + bands: lastNight ? hypnogram(lastNight) : [], + laneText: (stage) => ({ + label: stageLabel(stage), + value: summaryOfNight ? formatDuration(stageSeconds(stage, summaryOfNight)) : "--", + }), + }; +} + +for (const layout of PHONE_LAYOUTS) { + phoneChart(layout, "hr-day", metricContent("heartRate", "hour", 1)); + phoneChart(layout, "hr-week", metricContent("heartRate", "day", 7)); + phoneChart(layout, "spo2-day", metricContent("spo2", "hour", 1)); + phoneChart(layout, "steps-week", metricContent("steps", "day", 7)); + phoneChart(layout, "sleep-day-lanes", lanesContent()); + phoneChart(layout, "sleep-week", nightsContent(7)); + phoneChart(layout, "sleep-month", nightsContent(30)); + phoneChart(layout, "sleep-quarter", nightsContent(90)); +} + +// --- report ---------------------------------------------------------------- +console.log(`font: small lineHeight ${small.lineHeight}, large lineHeight ${large.lineHeight}`); +console.log(`wrote ${written.length} PNGs to ${OUT}\n`); +for (const entry of written) { + console.log(` ${entry.name.padEnd(34)} ${entry.size.padEnd(10)} ink ${entry.ink}`); +}