Salud: a card opens onto the day, hour by hour, and onto the days before it
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s

Reported as "le doy a cualquier actividad y solo me presenta los pasos de hoy… debiera
presentarme una medida por hora, y no me da el histórico". Two separate things, and only one
of them was the app's fault.

**The history was the automation's setting.** With Date Range on its default (`Today`) every
sync carries today and nothing else, so there is exactly one day in the file to draw. That is
why a card looked frozen: not a rendering bug, a range that was never sent. The setup steps
now say `Previous 7 Days` and say why.

**The hours were thrown away by us.** Even when the phone sends 288 readings a day, the
receiver folded every one of them into a single day aggregate, so "8,123 steps today" was all
there could ever be — a number you cannot look into. Worse, the recommended setting was Time
Grouping `Days`, which sends one point per metric per day: the intraday detail never arrived
in the first place. The recommendation is now `Hours`, and the storage keeps the hours.

The merge rule for them is the same shape as the day rule, for the same reason: a payload
whose datapoints all sit on the hour is HAE's own hour grouping, and the hour *in progress*
grows on every run of a five-minute automation, so it is replaced and never unioned — 500 +
900 + 1,340 steps in one hour is a number no watch recorded. The day is then recomputed as
the sum of its hours, which is what keeps the card and the detail from ever disagreeing, and
which also makes switching an automation from Days to Hours mid-day converge instead of
double-count. Raw samples (real timestamps) still union by instant plus numbers, and they now
land in their own hour, which is where intraday detail comes from when nothing is grouped.

Three things that would have been silent bugs, caught while writing it:

- The hour rule is decided from the **whole payload**, never from one timestamp. A five-minute
  automation produces samples that sit exactly on the hour, and reading one of those as an hour
  total wipes the hour it belongs to. There is a test with a 09:00:00 and a 09:05:00 sample in
  one payload, and it fails against the per-point version of the rule.
- A day that arrived as a day total keeps its hours beside it, and a day stored before this
  existed keeps its aggregate when the first hour shows up — recomputing it from hours it does
  not have would delete 2,000 steps. Both are mutation-checked (removing either guard fails a
  test).
- A payload grouped by hour writes the ledger row anyway, because a later payload with real
  minutes can describe the same instant and the union path can only see the ledger. Without it
  the raw-sample route test double-counts a single sample.

The hours are the bulky part of this data, so they are kept for a week (the day aggregates
still live the full 400 days), pruned when the night's file is written, and fetched one metric
and one day at a time — `GET /api/vitals/hours`. A screen listing forty cards downloads none
of them; the day view carries only a count per day, which is what tells the sheet whether it
is worth asking. The sheet draws the hours, the days before it (tapping one moves the hour
list to that day), and every field the watch sent; when the automation groups by Days it says
so instead of leaving a gap where a chart should be.

Coverage: 6 new tests in `api/test/vitals.test.js` (19 total) and a route test in
`api/test/server-vitals.test.js` (5), the hour/history model in `vitals-view.test.js` (31),
three render tests through the real sheet, the route documented in `api/openapi.yaml` and
`website/api.html`, and `docs/HEALTH.md` with the settings, the new merge row and the two
symptoms now in Troubleshooting.
This commit is contained in:
dsantillan committed 2026-09-23 13:28:58 -04:00
1 parent 34d28fa5c5
commit aa6ec8ef22
14 files changed
+839 -63

No files matched your search

+70 -9
View File
@@ -162,27 +162,32 @@ export function specOf(name) {
}
/**
* One day's number for one metric.
* The number to show for one set of per-field aggregates.
*
* A known metric uses its catalogue rule. An unknown one shows the field with the most samples
* that day — the number the watch actually measured most often — falling back to whichever field
* is there, so nothing is hidden just because nobody wrote a rule for it.
*/
export function valueOfDay(day, s) {
const f = (day && day.f) || {}
const keys = Object.keys(f)
export function valueOfFields(f, s) {
const src = f || {}
const keys = Object.keys(src)
if (!keys.length) return null
if (s.fields) {
const field = s.fields.find(k => f[k] && (AGG[s.agg] || AGG.sum)(f[k]) != null)
if (field) return (AGG[s.agg] || AGG.sum)(f[field])
const field = s.fields.find(k => src[k] && (AGG[s.agg] || AGG.sum)(src[k]) != null)
if (field) return (AGG[s.agg] || AGG.sum)(src[field])
}
if (s.unknown) {
const best = keys.slice().sort((a, b) => (f[b].n || 0) - (f[a].n || 0))[0]
return f[best].avg ?? f[best].last ?? f[best].sum ?? null
const best = keys.slice().sort((a, b) => (src[b].n || 0) - (src[a].n || 0))[0]
return src[best].avg ?? src[best].last ?? src[best].sum ?? null
}
return null
}
/** One day's number for one metric. */
export function valueOfDay(day, s) {
return valueOfFields((day && day.f) || {}, s)
}
/** How many days of samples a metric's series covers, for the "n days" captions. */
const pointsOf = series => series.reduce((n, p) => n + (p.n || 0), 0)
@@ -200,7 +205,7 @@ export function metricCards(data, { days = 90 } = {}) {
for (const [name, m] of Object.entries(metrics)) {
const s = specOf(name)
const series = ((m && m.days) || [])
.map(d => ({ day: d.day, v: valueOfDay(d, s), n: d.n || 0, lastTs: d.lastTs || null }))
.map(d => ({ day: d.day, v: valueOfDay(d, s), n: d.n || 0, lastTs: d.lastTs || null, hours: d.hours || 0 }))
.filter(p => p.v != null && Number.isFinite(p.v))
if (!series.length) continue
const latest = series[series.length - 1]
@@ -221,6 +226,10 @@ export function metricCards(data, { days = 90 } = {}) {
// When the newest reading actually landed. The phone pushes every few minutes, so this is
// what makes "today's number" verifiable rather than a claim: a card can say "hace 12 min".
lastTs: latest.lastTs,
/* Whether the newest day has hours behind it. 0 or 1 means the automation grouped by day:
there is one number for the day and nothing finer was ever sent, which the detail sheet
says out loud instead of drawing an empty hour list. */
hours: latest.hours || 0,
delta: mean != null && mean !== 0 ? (latest.v - mean) / Math.abs(mean) : null,
avg: mean,
trendDays: prior.length,
@@ -392,6 +401,58 @@ export function detailRows(card, day, m) {
}))
}
/* ---------- the hours behind a day, and the days behind a card ---------- */
/**
* A metric's hours on one day, as the rows the detail sheet draws.
*
* `payload` is what `GET /api/vitals/hours` answers — one metric, one day — so this is never the
* whole document: the hours are the bulky part of health data and they are fetched when somebody
* taps a card, not when the screen loads forty of them.
*
* The value per hour uses the metric's own rule, exactly as a day does, so an hourly heart rate
* reads as an average and an hourly step count reads as a total. A row with no readable value is
* dropped rather than shown as a dash: an hour HAE sent without one of the fields a card needs is
* not a reading, and a list of dashes is worse than a shorter list.
*/
export function hourRows(payload, card) {
const s = specOf(card.name)
return ((payload && payload.hours) || [])
.map(h => ({
key: h.h,
h: h.h,
label: h.h + ':00',
value: valueOfFields(h.f, s),
n: h.n || 0,
ts: h.ts || null
}))
.filter(r => r.value != null && Number.isFinite(r.value))
}
/** The hour rows as chart points: x is that hour on the day the phone wrote. */
export function hourChartPoints(day, rows) {
return (rows || []).map(r => ({ t: Date.parse(`${day}T${r.h}:00:00`), y: r.value, d: day }))
}
/**
* A card's own history, newest day first — what the detail sheet lists under the chart.
*
* The chart shows a shape; this shows the numbers the shape is made of, which is the difference
* between "it went up" and "it went up on Tuesday". `hours` rides along so a row can say whether
* that day can be opened hour by hour.
*/
export function historyRows(card, { limit = 14 } = {}) {
const series = (card && card.series) || []
return series.slice(-limit).reverse().map(p => ({
key: p.day,
day: p.day,
label: dayLabel(p.day),
value: p.v,
n: p.n || 0,
hours: p.hours || 0
}))
}
/* ---------- workouts ---------- */
// HAE names the activity the way Apple does, in Title Case and sometimes with a long tail.
+78 -1
View File
@@ -2,7 +2,8 @@ import { describe, it, expect } from 'vitest'
import {
METRICS, specOf, humanize, valueOfDay, metricCards, sortCards, groupedCards, trendOf,
chartPoints, workoutRows, hasVitals, activeDays, ingestUrl, unitLabel, fmtValue, agoLabel,
detailRows, workoutIcon, GROUP_ORDER, tintOf, dayLabel, trendCards, seriesStats
detailRows, workoutIcon, GROUP_ORDER, tintOf, dayLabel, trendCards, seriesStats,
hourRows, hourChartPoints, historyRows
} from './vitals-view.js'
/* The mapping from HAE's metric names to what a card shows. Worth testing because it is the one
@@ -290,6 +291,82 @@ describe('days, units and captions', () => {
expect(agoLabel(0, now)).toBe('')
})
/* The hours. A card's number is a day; these are the rows that make the day readable, and the
only thing that decides which of a metric's fields becomes one number an hour. */
describe('the hours behind a day', () => {
const card = name => metricCards(doc).find(c => c.name === name)
const payload = hours => ({ ok: true, metric: 'step_count', day: '2026-05-03', hours })
it('reads one value per hour using the metric\'s own rule', () => {
const steps = card('step_count')
const rows = hourRows(payload([
{ h: '08', n: 12, ts: 1, f: { qty: { n: 12, sum: 512, min: 1, max: 90, last: 40, avg: 42.6 } } },
{ h: '09', n: 12, ts: 2, f: { qty: { n: 12, sum: 1340, min: 2, max: 300, last: 80, avg: 111.6 } } }
]), steps)
expect(rows.map(r => r.label)).toEqual(['08:00', '09:00'])
// Steps are a counter: the hour is its total, not its average — the same rule a day uses.
expect(rows.map(r => r.value)).toEqual([512, 1340])
expect(rows[0].n).toBe(12)
})
it('averages an hourly rate instead of adding it up', () => {
const hr = card('heart_rate')
const rows = hourRows({ hours: [{ h: '14', n: 60, ts: 1, f: { Avg: { n: 60, sum: 4200, min: 60, max: 90, last: 75, avg: 70 } } }] }, hr)
expect(rows[0].value).toBe(70)
})
it('drops an hour with nothing readable in it rather than showing a dash', () => {
const steps = card('step_count')
expect(hourRows(payload([{ h: '08', n: 1, ts: 1, f: { distance: bucket(2) } }]), steps)).toEqual([])
expect(hourRows(null, steps)).toEqual([])
expect(hourRows({ hours: [] }, steps)).toEqual([])
})
it('charts the hours on the day the phone wrote them', () => {
const rows = hourRows(payload([
{ h: '08', n: 1, ts: 1, f: { qty: bucket(512) } },
{ h: '09', n: 1, ts: 2, f: { qty: bucket(1340) } }
]), card('step_count'))
const pts = hourChartPoints('2026-05-03', rows)
expect(pts.map(p => p.y)).toEqual([512, 1340])
expect(new Date(pts[0].t).getHours()).toBe(8)
expect(new Date(pts[1].t).getHours()).toBe(9)
expect(hourChartPoints('2026-05-03', [])).toEqual([])
})
})
it('lists a card\'s own history newest first, and says which days can be opened by the hour', () => {
const withHours = {
metrics: {
step_count: {
units: 'count',
days: [
{ ...day('2026-05-01', { qty: bucket(5000) }), hours: 0 },
{ ...day('2026-05-02', { qty: bucket(7000) }), hours: 24 },
{ ...day('2026-05-03', { qty: bucket(12000) }), hours: 5 }
]
}
}
}
const c = metricCards(withHours)[0]
expect(c.hours).toBe(5, 'the card carries the newest day\'s hours, so the sheet knows to ask')
const rows = historyRows(c)
expect(rows.map(r => r.day)).toEqual(['2026-05-03', '2026-05-02', '2026-05-01'])
expect(rows.map(r => r.value)).toEqual([12000, 7000, 5000])
expect(rows.map(r => r.hours)).toEqual([5, 24, 0])
expect(rows[0].label).toBeTruthy()
// A limit keeps the sheet short on a metric with a year of history: the newest days win.
expect(historyRows(c, { limit: 2 }).map(r => r.day)).toEqual(['2026-05-03', '2026-05-02'])
expect(historyRows({ series: [] })).toEqual([])
})
it('reports no hours at all when the document does not carry them', () => {
// What an older server (or an automation grouping by Day) produces: no `hours` key anywhere.
const cards = metricCards(doc)
expect(cards.every(c => c.hours === 0)).toBe(true)
expect(historyRows(cards[0]).every(r => r.hours === 0)).toBe(true)
})
it('builds an absolute ingest URL that survives a subpath deployment', () => {
expect(ingestUrl({ origin: 'https://gym.example.com', pathname: '/' })).toBe('https://gym.example.com/api/vitals/ingest')
expect(ingestUrl({ origin: 'https://example.com', pathname: '/gym/' })).toBe('https://example.com/gym/api/vitals/ingest')
+6 -1
View File
@@ -1367,6 +1367,9 @@ export default {
'Read-only on purpose: these carry no sets or weights, so they stay out of your progression, your PRs and the recovery model.': 'Solo lectura a propósito: no traen series ni pesos, así que quedan fuera de tu progresión, tus PRs y el modelo de recuperación.',
'vs your average': 'frente a tu media',
'What the watch sent': 'Lo que envió el reloj',
'Hour by hour': 'Hora por hora',
'Day by day': 'Día por día',
'This metric arrived as one total a day. Health Auto Export keeps the hours if you set Time grouping to Hours, and then this sheet draws the day hour by hour — the day total is the sum of them, so nothing is counted twice.': 'Esta métrica llegó como un solo total al día. Health Auto Export conserva las horas si pones Agrupación temporal en Horas, y entonces esta hoja dibuja el día hora por hora: el total del día es la suma de ellas, así que nada se cuenta dos veces.',
'{0} samples': '{0} muestras',
'{0} days with data in this range': '{0} días con datos en este rango',
// setup
@@ -1389,10 +1392,12 @@ export default {
'Summarize data': 'Resumir datos',
'Time grouping': 'Agrupación temporal',
'Days': 'Días',
'Hours': 'Horas',
'Date range': 'Rango de fechas',
'Previous 7 Days': 'Últimos 7 días',
'Health Auto Export runs an automation on your iPhone and posts to this profile. The key below only works for your account, and only for this: it can add health data and cannot read anything back.': 'Health Auto Export ejecuta una automatización en tu iPhone y envía los datos a este perfil. La clave de aquí abajo solo funciona para tu cuenta y solo para esto: puede añadir datos de salud y no puede leer nada.',
'Grouping by days is what makes a five-minute cadence safe: each sync carries the day\'s total and replaces the previous one, so nothing is ever counted twice. Raw samples work too — they are de-duplicated instead.': 'Agrupar por días es lo que hace segura una cadencia de cinco minutos: cada envío trae el total del día y reemplaza al anterior, así que nada se cuenta dos veces. Las muestras crudas también funcionan: esas se deduplican.',
'Hours is the grouping that keeps the shape of a day: each hour arrives as its own total, the day is their sum, and a card can be read hour by hour. Days sends one number a day instead — exact, and with nothing behind it to look into. Either way a five-minute cadence is safe: a total replaces the total before it, it is never added to it.': 'Horas es la agrupación que conserva la forma del día: cada hora llega como su propio total, el día es la suma de ellas y una tarjeta se puede leer hora por hora. Días envía un solo número al día: exacto, pero sin nada detrás que mirar. En los dos casos una cadencia de cinco minutos es segura: un total reemplaza al total anterior, nunca se le suma.',
'Date range decides how much history exists at all. With Today — the default — every sync carries today and yesterday is never in the file. Previous 7 Days carries the last week every time, and those hours land on the ones already stored instead of adding to them.': 'El rango de fechas decide cuánto histórico existe. Con Hoy —el valor por defecto— cada envío trae el día de hoy y ayer nunca está en el archivo. Últimos 7 días trae la última semana cada vez, y esas horas caen sobre las ya guardadas en lugar de sumarse.',
'Pick a cadence that suits you — every 5 minutes, hourly, or once a day all land the same way.': 'Elige la cadencia que te sirva: cada 5 minutos, cada hora o una vez al día llegan igual de bien.',
'Manage': 'Gestionar',
'Replace the key': 'Reemplazar la clave',
+63 -3
View File
@@ -26,7 +26,8 @@ import LineChart from '../components/LineChart.jsx'
import { todayISO } from '../lib/format.js'
import {
groupedCards, metricCards, trendOf, chartPoints, workoutRows, hasVitals,
fmtValue, unitLabel, agoLabel, ingestUrl, detailRows, dayLabel, trendCards, seriesStats
fmtValue, unitLabel, agoLabel, ingestUrl, detailRows, dayLabel, trendCards, seriesStats,
hourRows, hourChartPoints, historyRows
} from '../lib/vitals-view.js'
/* The period filter, "Today" first and by default: a card's headline is always the newest
@@ -118,9 +119,38 @@ function TrendSection({ cards, windowLabel, onOpen }) {
* is what makes an unknown metric legible — the numbers under the names HAE used, rather than a
* card that says "91" and nothing about what 91 was.
*/
/**
* The detail sheet: the day's chart, the day hour by hour when the phone sent hours, the days
* before it, and every field HAE sent for the newest day.
*
* The hour list is the reason this sheet is worth opening at all: "8,123 steps today" is a number,
* and "08:00 → 512, 09:00 → 1,340" is a morning you can recognise. It is a second request, made
* only when the day actually has hours (`hours` comes down with the card), so a profile whose
* automation groups by Day never pays for it — and the sheet says why the list is missing instead
* of leaving a gap where a chart should be.
*/
function MetricSheet({ card, metric, close }) {
const rows = detailRows(card, undefined, metric)
const tr = trendOf(card)
const [day, setDay] = useState(card.day)
const [hours, setHours] = useState(null)
// Tapping a day in the history moves the hour list to that day, so the whole week the server
// still keeps hours for can be read without leaving the sheet.
const dayHours = (card.series || []).find(p => p.day === day)?.hours || 0
useEffect(() => {
if (dayHours < 2) { setHours(null); return }
let live = true
api('/api/vitals/hours?metric=' + encodeURIComponent(card.name) + '&day=' + encodeURIComponent(day))
.then(r => { if (live) setHours(r) })
.catch(() => { if (live) setHours(null) })
return () => { live = false }
}, [card.name, day, dayHours])
const hourList = hourRows(hours, card)
const history = historyRows(card)
const val = r => fmtValue(r.value, card.dec) + (unitLabel(card.unit) ? ' ' + unitLabel(card.unit) : '')
return <>
<h3>{card.label}</h3>
<div className="vh-sheet-top" style={{ '--tint': card.tint }}>
@@ -134,6 +164,33 @@ function MetricSheet({ card, metric, close }) {
</div>
</div>
<div className="card vh-chart"><LineChart points={chartPoints(card)} h={160} unit={unitLabel(card.unit)} color={card.tint} /></div>
{hourList.length > 1 && <>
<h4 className="sec">{t('Hour by hour')}<span className="vh-window"> · {dayLabel(day)}</span></h4>
<div className="card vh-chart">
<LineChart points={hourChartPoints(day, hourList)} h={120} unit={unitLabel(card.unit)} color={card.tint} />
</div>
<div className="list">
{hourList.map(r => <Row key={r.key} title={r.label}
subtitle={r.n > 1 ? t('{0} samples', r.n) : null} value={val(r)} />)}
</div>
</>}
{!(card.hours > 1) && <div className="small dim" style={{ marginTop: 10, lineHeight: 1.5 }}>
{t('This metric arrived as one total a day. Health Auto Export keeps the hours if you set Time grouping to Hours, and then this sheet draws the day hour by hour — the day total is the sum of them, so nothing is counted twice.')}
</div>}
{history.length > 1 && <>
<h4 className="sec">{t('Day by day')}</h4>
<div className="list">
{history.map(r => <Row key={r.key} title={r.label}
subtitle={r.n > 1 ? t('{0} samples', r.n) : null}
value={val(r)}
accessory={r.hours > 1 ? 'chevron' : null}
onClick={r.hours > 1 ? () => setDay(r.day) : null} />)}
</div>
</>}
{rows.length > 0 && <>
<h4 className="sec">{t('What the watch sent')}</h4>
<div className="list">{rows.map(r => <Row key={r.key} title={r.label}
@@ -192,11 +249,14 @@ function SetupSheet({ initialKey, onKey, onRotate, onDelete, close }) {
<Row icon="calendar" title={t('Export format')} value="JSON" />
<Row icon="list" title={t('Export version')} value="2" />
<Row icon="check" title={t('Summarize data')} value={t('On')} />
<Row icon="clock" title={t('Time grouping')} value={t('Days')} />
<Row icon="clock" title={t('Time grouping')} value={t('Hours')} />
<Row icon="history" title={t('Date range')} value={t('Previous 7 Days')} />
</div>
<div className="small dim" style={{ marginTop: 10, lineHeight: 1.5 }}>
{t('Grouping by days is what makes a five-minute cadence safe: each sync carries the day\'s total and replaces the previous one, so nothing is ever counted twice. Raw samples work too — they are de-duplicated instead.')}
{t('Hours is the grouping that keeps the shape of a day: each hour arrives as its own total, the day is their sum, and a card can be read hour by hour. Days sends one number a day instead — exact, and with nothing behind it to look into. Either way a five-minute cadence is safe: a total replaces the total before it, it is never added to it.')}
</div>
<div className="small dim" style={{ marginTop: 8, lineHeight: 1.5 }}>
{t('Date range decides how much history exists at all. With Today — the default — every sync carries today and yesterday is never in the file. Previous 7 Days carries the last week every time, and those hours land on the ones already stored instead of adding to them.')}
</div>
<div className="small dim" style={{ marginTop: 8, lineHeight: 1.5 }}>
{t('Pick a cadence that suits you — every 5 minutes, hourly, or once a day all land the same way.')}
+113 -1
View File
@@ -9,6 +9,7 @@ import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
const api = vi.fn()
vi.mock('../lib/api.js', () => ({ api: (...args) => api(...args) }))
@@ -50,7 +51,10 @@ beforeEach(() => {
localStorage.removeItem('gym_guest')
useStore.setState({ user: { id: 'u1', name: 'Test' } })
})
afterEach(() => { act(() => root.unmount()); host.remove() })
/* A sheet lives in the UI store, not in the screen, so it outlives the screen's root: without
clearing it the next test remounts yesterday's sheet, which is both a stray element in the DOM
and a request nobody asked for. Tests are independent or they are not tests. */
afterEach(() => { act(() => { useUI.setState({ sheets: [] }); root.unmount() }); host.remove() })
const mount = async () => {
await act(async () => { root.render(<Health />) })
@@ -171,6 +175,114 @@ describe('the Today filter', () => {
})
})
/* The detail sheet is where a number becomes a day. Tapping a card has to show the hours the
phone actually sent, and it has to say so plainly when it sent none — a card whose automation
groups by Day has no hours anywhere, and an empty chart there would read as a bug. The hours
are a second request on purpose (a profile with forty cards should not download 24 buckets ×
forty metrics to draw a grid), so this checks both the fetch and the drawing. */
describe('the detail sheet', () => {
const mountWithSheets = async () => {
await act(async () => { root.render(<><Health /><Modals /></>) })
await act(async () => {})
}
const click = el => act(() => { el.dispatchEvent(new MouseEvent('click', { bubbles: true })) })
// The sheet that is open right now: a previous test's sheet is still in the DOM (the Modals host
// outlives the screen's root), so reading document.body would read somebody else's day.
const sheetEl = () => [...document.querySelectorAll('.sheet')].pop()
const sheet = () => sheetEl()?.textContent || ''
const openSteps = () => click(entries().find(e => (e.querySelector('.l, .vh-tchart-t') || {}).textContent === 'Steps'))
const withHours = () => ({
...VITALS,
metrics: {
step_count: {
units: 'count', sources: ['Apple Watch'],
days: [
{ ...day('2026-09-02', { qty: bucket(11000) }), hours: 24 },
{ ...day('2026-09-03', { qty: bucket(12481) }), hours: 3 }
]
}
}
})
const HOURS = {
ok: true, metric: 'step_count', day: '2026-09-03', units: 'count',
hours: [
{ h: '08', n: 1, ts: 1, f: { qty: bucket(512) } },
{ h: '09', n: 1, ts: 2, f: { qty: bucket(1340) } },
{ h: '10', n: 1, ts: 3, f: { qty: bucket(900) } }
]
}
const route = (doc, hours) => api.mockImplementation(async path => {
if (path.startsWith('/api/vitals/hours')) return hours
if (path.startsWith('/api/vitals?')) return doc
throw new Error('unexpected ' + path)
})
it('draws the day hour by hour, and the days before it, when the phone sent hours', async () => {
route(withHours(), HOURS)
await mountWithSheets()
openSteps()
await act(async () => {})
// One metric, one day: never the whole document.
expect(api).toHaveBeenCalledWith('/api/vitals/hours?metric=step_count&day=2026-09-03')
expect(sheet()).toContain('Hour by hour')
expect(sheet()).toContain('08:00')
expect(sheet()).toContain('512')
expect(sheet()).toContain('1,340')
// The history the card is built from, so "it went up" can be read as "it went up on Tuesday".
expect(sheet()).toContain('Day by day')
expect(sheet()).toContain('11,000')
expect(sheet()).toContain('12,481')
expect(sheet()).not.toContain('This metric arrived as one total a day')
})
it('says the automation groups by day instead of drawing an empty hour list', async () => {
route(VITALS, HOURS)
await mountWithSheets()
openSteps()
await act(async () => {})
expect(sheet()).toContain('This metric arrived as one total a day')
expect(sheet()).not.toContain('Hour by hour')
// ...and it never asks for hours it knows do not exist: the card said so.
expect(api.mock.calls.map(c => c[0]).filter(p => p.startsWith('/api/vitals/hours'))).toEqual([])
// The history is drawn anyway: three days of step totals are three rows.
expect(sheet()).toContain('Day by day')
expect(sheet()).toContain('9,000')
})
it('moves the hour list to a day that has hours when that day is tapped', async () => {
const byDay = {
'2026-09-03': HOURS,
'2026-09-02': { ...HOURS, day: '2026-09-02', hours: [
{ h: '06', n: 1, ts: 1, f: { qty: bucket(500) } },
{ h: '07', n: 1, ts: 2, f: { qty: bucket(777) } }
] }
}
api.mockImplementation(async path => {
if (path.startsWith('/api/vitals/hours')) return byDay[path.split('day=')[1]]
if (path.startsWith('/api/vitals?')) return withHours()
throw new Error('unexpected ' + path)
})
await mountWithSheets()
openSteps()
await act(async () => {})
expect(sheet()).toContain('08:00')
// The row for the day before carries the chevron that says it can be opened.
const row = [...sheetEl().querySelectorAll('button')].find(b => b.textContent.includes('11,000'))
expect(row).toBeTruthy()
click(row)
await act(async () => {})
expect(api).toHaveBeenCalledWith('/api/vitals/hours?metric=step_count&day=2026-09-02')
expect(sheet()).toContain('07:00')
expect(sheet()).toContain('777')
expect(sheet()).not.toContain('08:00')
})
})
/* The setup sheet is rendered from an element captured when it was opened (useUI.openSheet keeps
the JSX), so anything it reads off the screen's state is frozen at that moment. The first
version keyed the whole "2. The header" block off the screen's `key`, which meant clicking