diff --git a/api/test/vitals.test.js b/api/test/vitals.test.js index 94bf6db..7022f45 100644 --- a/api/test/vitals.test.js +++ b/api/test/vitals.test.js @@ -282,7 +282,7 @@ test('a raw sample that happens to sit on the hour does not wipe that hour', () assert.equal(again.doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1000); }); -test('a day total and an hour total for the same day agree on which number is the day', () => { +test('the phone\'s own day total is the day, and hours never get added to it', () => { const hours = metric('step_count', 'count', [ { qty: 500, date: at('2026-05-01', '08:00:00') }, { qty: 900, date: at('2026-05-01', '09:00:00') } @@ -290,22 +290,31 @@ test('a day total and an hour total for the same day agree on which number is th let doc = merge(emptyVitals(), parsePayload(hours)).doc; assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1400); - // A second automation grouped by Days sends the day itself: it is the better day number, and - // the hours are a shape the total cannot contradict, so they stay for the sheet to draw. + // A second automation grouped by Days sends the day itself: it is the number the Health app + // shows, so it becomes the day — and the hours stay for the sheet to draw. const total = merge(doc, parsePayload(metric('step_count', 'count', [{ qty: 1500, date: at('2026-05-01') }]))); doc = total.doc; assert.equal(total.stats.points, 1); assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1500); assert.equal(Object.keys(doc.metrics.step_count.days['2026-05-01'].h).length, 2, 'the hours rode along'); - // Then the hourly automation sends the next hour: it re-sends the whole day, so from here the - // day is the hours again — the two rules converge instead of drifting apart. + // Then hour points arrive for the same day. The day does NOT become their sum: the declared total + // already contains the hours below it, and adding them is exactly how 499 steps became 840. The + // sum rides beside it instead, so a disagreement between the two is visible rather than silent. doc = merge(doc, parsePayload(metric('step_count', 'count', [ { qty: 500, date: at('2026-05-01', '08:00:00') }, { qty: 900, date: at('2026-05-01', '09:00:00') }, { qty: 200, date: at('2026-05-01', '10:00:00') } ]))).doc; - assert.equal(doc.metrics.step_count.days['2026-05-01'].f.qty.sum, 1600); + const day = doc.metrics.step_count.days['2026-05-01']; + assert.equal(day.f.qty.sum, 1500, 'the phone\'s total is still the day'); + assert.equal(day.own, true); + assert.equal(Object.keys(day.h).length, 3, 'and the hours still landed'); + assert.equal(day.hsum.qty, 1600, 'with their sum beside them, for the screen to compare'); + + // A newer total replaces it, as it always did. + assert.equal(merge(doc, parsePayload(metric('step_count', 'count', [{ qty: 1700, date: at('2026-05-01') }]))).doc + .metrics.step_count.days['2026-05-01'].f.qty.sum, 1700); }); test('a day stored before hours existed keeps its samples when the first hour arrives', () => { @@ -344,6 +353,76 @@ test('vitalsHours answers for one metric and one day, and invents nothing', () = assert.equal(vitalsHours(emptyVitals(), { metric: 'step_count', day: '2026-05-01' }).metric, null); }); +test('a midnight total inside an hourly payload is the day, not hour zero', () => { + // The shape that produced "the watch says 499 and the app says 840": HAE sends the day's total + // stamped at midnight *and* the hours, in one payload. Read as hour 00, the total is added to the + // hours and the day doubles; read as what it is, the day is 499 and the hours are its shape. + const p = (qty, time) => ({ qty, date: at('2026-05-01', time) }); + const payload = metric('step_count', 'count', [ + p(499, '00:00:00'), // the day's own total, stamped at midnight + p(120, '08:00:00'), p(220, '09:00:00') // and two hours of it + ]); + const doc = merge(emptyVitals(), parsePayload(payload)).doc; + const day = doc.metrics.step_count.days['2026-05-01']; + assert.equal(day.f.qty.sum, 499, 'the day is the total, not 499 + 340'); + assert.equal(day.own, true); + assert.equal(day.h['00'], undefined, 'and the midnight point did not become hour 00'); + assert.deepEqual(Object.keys(day.h).sort(), ['08', '09']); + assert.equal(day.hsum.qty, 340, 'the sum of the hours is kept beside it'); + + // The same payload again is a no-op on the day, and the hours converge. + const grew = merge(doc, parsePayload(metric('step_count', 'count', [ + p(499, '00:00:00'), p(120, '08:00:00'), p(260, '09:00:00') + ]))).doc.metrics.step_count.days['2026-05-01']; + assert.equal(grew.f.qty.sum, 499); + assert.equal(grew.h['09'].f.qty.sum, 260); + + // A genuine 00:00 bucket — a handful of steps, less than the rest of the day — stays hour 00. + const small = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [ + p(3, '00:00:00'), p(300, '08:00:00'), p(400, '09:00:00') + ]))).doc.metrics.step_count.days['2026-05-01']; + assert.equal(small.f.qty.sum, 703, 'a real first hour is summed like any other'); + assert.equal(small.h['00'].f.qty.sum, 3); + assert.equal(small.own, undefined); +}); + +test('the receipt records what arrived, so a wrong number can be explained', () => { + const doc = merge(emptyVitals(), parsePayload({ + data: { metrics: [ + { name: 'step_count', units: 'count', data: [ + { qty: 120, date: at('2026-05-01', '08:00:00'), source: 'Apple Watch' }, + { qty: 220, date: at('2026-05-01', '09:00:00'), source: 'Apple Watch' }, + { qty: 90, date: at('2026-05-01', '09:30:00'), source: 'iPhone' } + ] } + ] } + }), NOW).doc; + const r = doc.shape.step_count; + assert.equal(r.points, 3); + assert.equal(r.stamps, 'mixed', 'a payload with an hour and a real instant says so'); + assert.equal(r.field, 'qty'); + assert.deepEqual(r.sources, ['Apple Watch', 'iPhone']); + assert.equal(r.sum, 430); + assert.equal(r.newest.value, 90); + assert.equal(r.tail.length, 3); + assert.equal(r.head.length, 3); + assert.equal(r.at, NOW); + + // Hour-stamped and day-stamped payloads are labelled too, because that is the question the + // receipt exists to answer. + const hourly = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [ + { qty: 120, date: at('2026-05-01', '08:00:00') }, { qty: 220, date: at('2026-05-01', '09:00:00') } + ]))).doc; + assert.equal(hourly.shape.step_count.stamps, 'hour'); + const dayly = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [{ qty: 499, date: at('2026-05-01') }]))).doc; + assert.equal(dayly.shape.step_count.stamps, 'day'); + // Replaced on every sync, never accumulated. + const again = merge(dayly, parsePayload(metric('heart_rate', 'bpm', [{ Avg: 62, date: at('2026-05-01', '09:00:00') }]))).doc; + assert.equal(again.shape.step_count.points, 1, 'the metric that did not arrive keeps its receipt'); + assert.equal(again.shape.heart_rate.field, 'Avg'); + // It survives a reload of the file, and it is not read by anything that computes a number. + assert.equal(normalizeDoc(JSON.parse(JSON.stringify(again))).shape.step_count.points, 1); +}); + test('the hourly detail is pruned after a week while the day aggregates live on', () => { const start = Date.parse('2026-05-06T12:00:00Z'); const doc = merge(emptyVitals(), parsePayload(metric('step_count', 'count', [ diff --git a/api/vitals.js b/api/vitals.js index cc937b3..5839246 100644 --- a/api/vitals.js +++ b/api/vitals.js @@ -94,6 +94,13 @@ export const MAX_WORKOUTS = 300; * survive this and live RETENTION_DAYS. */ export const HOURS_KEPT_DAYS = 7; +/** + * How long a day the phone totalled itself stays the day's number while hours keep arriving. In the + * shape this exists for the total is re-sent on every sync, so it never goes stale; an automation + * that was reconfigured to hours only stops sending it, and after this the sum of the hours takes + * over instead of the number freezing for the rest of the day. + */ +export const DECLARED_STALE_MS = 6 * 3600 * 1000; /** Sources remembered per metric — decorative, but it answers "which watch sent this?" */ const MAX_SOURCES = 4; const MAX_LEDGER_KEYS = 20000; // hard ceiling; the time-based prune is the real bound @@ -110,7 +117,10 @@ export function normalizeDoc(doc) { updatedAt: Number(d.updatedAt) || 0, last: d.last && typeof d.last === 'object' ? d.last : null, metrics: {}, - workouts: Array.isArray(d.workouts) ? d.workouts.filter(w => w && typeof w === 'object') : [] + workouts: Array.isArray(d.workouts) ? d.workouts.filter(w => w && typeof w === 'object') : [], + // The last sync's receipt per metric (see receiptFor): replaced every time, never read by + // anything that computes a number. + shape: d.shape && typeof d.shape === 'object' && !Array.isArray(d.shape) ? d.shape : {} }; const metrics = d.metrics && typeof d.metrics === 'object' && !Array.isArray(d.metrics) ? d.metrics : {}; for (const [name, m] of Object.entries(metrics)) { @@ -276,6 +286,25 @@ function hrMax(samples) { /* ---------- merging ---------- */ +/** + * A midnight-stamped datapoint that carries more than everything else in its payload put together + * is the day's own total, not hour 00: an hour cannot hold more than the day it belongs to. Returns + * the day keys it applies to, so the loop can treat exactly those points as day totals. + */ +function declaredDay(points) { + const rest = points.filter(p => !isMidnight(p.at)) + .map(p => headline(p.fields)) + .filter(Boolean) + .reduce((n, h) => n + h.value, 0); + const keys = new Set(); + for (const p of points) { + if (!isMidnight(p.at)) continue; + const h = headline(p.fields); + if (h && h.value > rest) keys.add(p.at.day); + } + return keys; +} + /** Does this metric payload look like HAE's own day-by-day grouping? */ function dayGrouped(points) { return points.length > 0 && points.every(p => isMidnight(p.at)); @@ -341,6 +370,21 @@ function deriveDay(day) { } day.f = f; day.n = n; + day.hsum = sumHours(day); +} + +/** + * What a day's hours add up to, per field — kept beside the day whether or not the day's own number + * came from them. When the phone also declares a total the two can disagree, and that disagreement + * is the most useful thing there is to show: "the hours add up to 840 and the newest one says 499" + * explains a wrong number, where the wrong number alone explains nothing. + */ +function sumHours(day) { + const out = {}; + for (const hb of Object.values(day.h || {})) { + for (const [k, v] of Object.entries(hb.f || {})) out[k] = Math.round(((out[k] || 0) + (v.sum || 0)) * 100) / 100; + } + return out; } /** @@ -365,13 +409,25 @@ export function mergeVitals(doc, payload, now = Date.now()) { // re-sent by the next automation run — anything older is pruned and can no longer be a repeat. pruneLedger(cur.seen, now); + // The receipt is written once per metric, from the payload as it arrived. + out.shape[m.name] = receiptFor(m.points, now); + + /* A midnight-stamped datapoint inside a payload that also carries hours is the day's own total, + not hour 00 of it — an hour cannot hold more than the day does. Reading it as an hour is what + turns "499 today" into 840, so when its value exceeds everything else in the payload added + together, it is taken as the day. Anything smaller is left where it is: a genuine 00:00 bucket + is a handful of steps, never more than the rest of the day. */ + // A Set, and empty is not "yes": `declared.has(day)` is what the loop asks, because a truthy + // empty Set would turn every midnight point into a day total. + const declared = replace ? null : declaredDay(m.points); + for (const p of m.points) { const key = p.at.day; if (!dayKeyOk(key)) continue; if (p.source && !cur.sources.includes(p.source)) { cur.sources = [p.source, ...cur.sources].slice(0, MAX_SOURCES); } - if (replace) { + if (replace || (declared && declared.has(p.at.day) && isMidnight(p.at))) { const prev = cur.days[key]; // Nothing to do when the phone re-sends the value we already have (the common case for // every run after the first). `f` is compared as a whole because a day total and a @@ -381,7 +437,8 @@ export function mergeVitals(doc, payload, now = Date.now()) { // day number, but it says nothing about the shape of the day and the hourly view is // built from what does. `own` records exactly that — this day's number is the phone's, // not the sum of its hours (see below). - cur.days[key] = { ...bucketFrom(p.fields, p.at.ms), h: prev?.h || {}, own: true }; + cur.days[key] = { ...bucketFrom(p.fields, p.at.ms), h: prev?.h || {}, own: true, ownAt: now }; + cur.days[key].hsum = sumHours(cur.days[key]); stats.points++; continue; } @@ -409,16 +466,27 @@ export function mergeVitals(doc, payload, now = Date.now()) { day.lastTs = Math.max(day.lastTs, p.at.ms); /* Recompute the day from its hours, which keeps this idempotent: the same hour arriving three times, or a partial hour replaced by a fuller one, leaves the same number behind. - Two days are the exceptions, and both are days whose aggregate is not "the hours so far": - own — the phone totalled this day itself (Days grouping). The hourly automation that - then takes over re-sends the whole day, so its hours supersede the total and - the day is derived from here on. + Three days are the exceptions, and all three are days whose aggregate is not "the hours so + far": + own — the phone totalled this day itself. Its total is the number the Health app shows, + and hours were re-folded into it once already (that is the bug this replaced: + 499 declared plus 341 of hours became 840). So the total stays the day, and the + hours stay the shape of it. The escape hatch is time: if no fresh total has + arrived for six hours while hours keep coming, the automation was clearly + reconfigured to hours only, and the day goes back to the sum of them. !hc — a day stored by an older version of this file, whose samples have no hour attribution. Summing its (empty, or partly filled) hours would delete what is already there, so the new sample is added to the day the old way and the hours beside it stay what they honestly are: the part that has a time of its own. */ - if (day.own || day.hc || day.n === 0) { - delete day.own; + const declaredStale = day.own && now - (day.ownAt || 0) > DECLARED_STALE_MS; + if (declaredStale) { delete day.own; delete day.ownAt; day.hc = true; } + if (day.own) { + /* The phone declared this day, so its number *is* the day: adding the hour to it would + count the morning twice, which is the whole failure this branch exists to prevent. The + hours still move — they are the shape of the day and the detail sheet draws them — and + the sum beside them moves with them so the two can be compared. */ + day.hsum = sumHours(day); + } else if (day.hc || day.n === 0) { day.hc = true; deriveDay(day); } else { @@ -495,6 +563,48 @@ function pruneDays(doc, now) { } } +/* ---------- the receipt: what actually arrived ---------- + * + * One entry per metric, replaced on every sync: how many datapoints came, how they were stamped + * (a day total, an hour, or a real instant), from which sources, what they add up to, and the first + * and last few values as the phone wrote them. It exists because "the number in the app does not + * match the Health app" is unanswerable from the number alone, and the answer is always in the + * shape of what arrived: hourly values that are really running totals add up to more than the day, + * and two devices recording the same walk add up to more than either. + * + * Bounded on purpose (three values at each end), and it is a *receipt*, not a reading: the headline + * field is picked by a fixed order rather than by the metric's meaning, because this module does not + * have the catalogue. Nothing here is used to compute a day. */ + +/** The field a receipt quotes for a point: the one a person would read if they had to pick one. */ +const HEADLINE_FIELDS = ['qty', 'Avg', 'avg', 'value', 'asleep', 'totalSleep', 'systolic']; +function headline(fields) { + for (const k of HEADLINE_FIELDS) if (typeof fields[k] === 'number') return { field: k, value: fields[k] }; + for (const [k, v] of Object.entries(fields)) if (typeof v === 'number') return { field: k, value: v }; + return null; +} + +const stampKind = t => (isMidnight(t) ? 'day' : onTheHour(t) ? 'hour' : 'sample'); + +function receiptFor(points, now) { + const kinds = new Set(points.map(p => stampKind(p.at))); + const valued = points.map(p => ({ at: p.at, h: headline(p.fields) })).filter(x => x.h); + const sum = valued.reduce((n, x) => n + x.h.value, 0); + const last = valued.length ? valued[valued.length - 1] : null; + const pair = x => [x.at.raw, x.h.value]; + return { + at: now, + points: points.length, + field: valued.length ? valued[0].h.field : null, + stamps: kinds.size > 1 ? 'mixed' : [...kinds][0], + sources: [...new Set(points.map(p => p.source).filter(Boolean))].slice(0, MAX_SOURCES), + sum: Math.round(sum * 100) / 100, + newest: last ? { stamp: last.at.raw, value: last.h.value, ms: last.at.ms } : null, + head: valued.slice(0, 3).map(pair), + tail: valued.slice(-3).map(pair) + }; +} + /* ---------- reading ---------- */ /** One bucket's fields, as the client wants them: the count, the total, and the mean it implies. */ @@ -529,9 +639,20 @@ export function vitalsSeries(doc, { days = 90, now = Date.now() } = {}) { for (const day of Object.keys(m.days).sort()) { if (day < from) continue; const b = m.days[day]; - out.push({ day, n: b.n, lastTs: b.lastTs, hours: Object.keys(b.h || {}).length, f: projectFields(b.f) }); + out.push({ + day, + n: b.n, + lastTs: b.lastTs, + hours: Object.keys(b.h || {}).length, + // `own`: this day's number is the total the phone declared, not the sum of its hours. + // `hours_sum`: what its hours add up to, so a disagreement between the two is visible + // instead of hidden — the screen shows it, and so does anybody debugging a wrong number. + own: !!b.own, + hours_sum: b.hsum || null, + f: projectFields(b.f) + }); } - if (out.length) metrics[name] = { units: m.units, sources: m.sources, days: out }; + if (out.length) metrics[name] = { units: m.units, sources: m.sources, days: out, shape: d.shape[name] || null }; } return { updatedAt: d.updatedAt, last: d.last, metrics, workouts: d.workouts }; } diff --git a/docs/HEALTH.md b/docs/HEALTH.md index 9205588..a7c855d 100644 --- a/docs/HEALTH.md +++ b/docs/HEALTH.md @@ -234,6 +234,7 @@ and you have backed up your health file too. | `200` with `received.points: 0` every time | Working, with nothing to add: bring your phone to Health Auto Export → Manual Sync → Export, and check Date Range covers a day that has data. | | Nothing on the screen | Salud fetches 30 days by default — widen the range. A metric HAE has no samples for is skipped rather than shown as a zero. | | Numbers that look doubled (steps, above all) | The export can carry the same walking twice — once from the Apple Watch and once from the iPhone. Apple Health de-duplicates that; [an export of individual samples does not](https://developer.apple.com/forums/thread/759709). A day total from HAE's own aggregation is the number the Health app shows, so `Time Grouping: Days` is the setting that keeps a card honest; grouping by Hours or Minutes reads the samples instead. | +| A card's number is bigger than the Health app's (steps above all) | Open the metric's card: **What arrived last** lists how the last payload was stamped, from which sources, what it adds up to and its newest values. A run of *rising* numbers is the tell — those are running totals, not one hour each, and adding them inflates the day. The fix that covers both shapes is already in: a day total the phone declares is the day, and hours are only ever the shape of it (the sheet says so when the two differ). If the receipt shows **one total a day**, the export is already sending what the Health app shows. | | A card shows one day, and its sheet has nothing before it | The automation's **Date Range** is `Today`, so yesterday was never sent. Set it to `Previous 7 Days`; the past cannot be invented server-side. | | The detail sheet says "arrived as one total a day", with no hour list | **Time Grouping** is `Days`: the payload has one number per day and no hours to draw. Set it to `Hours` — the day stays the sum of its hours, so nothing is double-counted, and the hour list appears from the next sync on. | | Steps look half a day behind | HAE cannot read Health while the phone is locked. Open the app (or tap the Automations widget) and the day fills in. | @@ -242,7 +243,7 @@ and you have backed up your health file too. ## 6. For developers -- `api/vitals.js` — parsing, the merge rules of §2, retention. Pure; tests in `api/test/vitals.test.js` +- `api/vitals.js` — parsing, the merge rules of §2, the per-metric receipt of what arrived, retention. Pure; tests in `api/test/vitals.test.js` cover the merge under overlapping, disjoint, day-grouped, hour-grouped, raw, heart-rate, sleep and blood-pressure payloads, plus pruning (days and hours), the day-from-hours projection and timezone handling. diff --git a/frontend/src/index.css b/frontend/src/index.css index 321b48c..3e7295b 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -1369,6 +1369,11 @@ body.chips-dragging *{cursor:inherit} /* The receipt line under the range control: dimmer and closer to the caption above it than to the cards, because it is an answer to "why has nothing moved", not a measurement. */ .vh-sync{margin:-6px 2px 12px;line-height:1.45} +/* A day whose hours and total disagree, said in words. Amber rather than red: nothing is broken — + the two numbers are both real, and one of them is the day. */ +.vh-note{margin:10px 0 0;padding:9px 11px;border-radius:var(--r-sm);font-size:12.5px;line-height:1.5; + color:var(--label-2);background:color-mix(in srgb,var(--orange) 12%,transparent); + border:var(--hair) solid color-mix(in srgb,var(--orange) 30%,transparent)} .ins-card{--tint:var(--acc);padding:12px 14px 14px;margin-bottom:12px} .ins-hd{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:4px} .ins-t{display:flex;align-items:center;gap:6px;font-size:14px;font-weight:600;color:var(--tint)} diff --git a/frontend/src/lib/vitals-view.js b/frontend/src/lib/vitals-view.js index 51c1a9a..d65e590 100644 --- a/frontend/src/lib/vitals-view.js +++ b/frontend/src/lib/vitals-view.js @@ -380,6 +380,48 @@ export function detailRows(card, day, m) { })) } +/* ---------- the receipt: what the phone actually sent ---------- */ + +/* The shape of the last payload for a metric, as words. This is the screen's answer to "the number + does not match the Health app", which is a question no number can answer about itself: hourly + values that are really running totals add up to more than the day, and two devices recording the + same walk add up to more than either. The receipt says which of those it is looking at. */ +const STAMP_LABEL = { day: 'one total a day', hour: 'one total an hour', sample: 'individual samples', mixed: 'mixed stamps' } +export const stampLabel = kind => (STAMP_LABEL[kind] ? t(STAMP_LABEL[kind]) : String(kind || '')) + +/** The receipt as rows: how it was stamped, where it came from, what it adds up to. */ +export function receiptRows(shape) { + if (!shape || !shape.points) return [] + const rows = [ + { key: 'points', label: t('Datapoints in the last sync'), value: fmtValue(shape.points) }, + { key: 'stamps', label: t('How they were stamped'), value: stampLabel(shape.stamps) }, + { key: 'sources', label: t('Sources'), value: (shape.sources || []).join(', ') || t('not reported') } + ] + if (shape.sum != null && shape.field) rows.push({ key: 'sum', label: t('{0} adds up to', shape.field), value: fmtValue(shape.sum, 0) }) + if (shape.newest) rows.push({ key: 'newest', label: t('Newest value'), value: fmtValue(shape.newest.value, 0) }) + // The three newest values, oldest first: a run of rising numbers is the tell that they are running + // totals rather than one hour each, and it is the difference between 499 and 840. + if (Array.isArray(shape.tail) && shape.tail.length > 1) { + rows.push({ key: 'tail', label: t('Latest values, oldest first'), value: shape.tail.map(([, v]) => fmtValue(v, 0)).join(' → ') }) + } + return rows +} + +/** + * Whether the day we are showing disagrees with the sum of its own hours — the single most useful + * comparison on this screen, because a day total and a sum of hours that do not match is a number + * somebody has to explain, and both numbers are right there. + */ +export function dayConflict(day) { + if (!day || !day.hours_sum || !day.f) return null + const sums = Object.entries(day.hours_sum).filter(([, v]) => Number.isFinite(v)) + if (sums.length !== 1) return null + const [field, sum] = sums[0] + const shown = day.f[field] && day.f[field].sum + if (!Number.isFinite(shown) || !Number.isFinite(sum) || shown === sum) return null + return { field, shown, sum, declared: !!day.own } +} + /* ---------- the hours behind a day, and the days behind a card ---------- */ /** diff --git a/frontend/src/lib/vitals-view.test.js b/frontend/src/lib/vitals-view.test.js index 34c11f2..2ead4e6 100644 --- a/frontend/src/lib/vitals-view.test.js +++ b/frontend/src/lib/vitals-view.test.js @@ -3,7 +3,7 @@ import { METRICS, specOf, humanize, valueOfDay, metricCards, sortCards, groupedCards, trendOf, chartPoints, workoutRows, hasVitals, activeDays, ingestUrl, unitLabel, fmtValue, agoLabel, detailRows, workoutIcon, GROUP_ORDER, tintOf, dayLabel, - hourRows, hourChartPoints, historyRows + hourRows, hourChartPoints, historyRows, receiptRows, dayConflict, stampLabel } from './vitals-view.js' /* The mapping from HAE's metric names to what a card shows. Worth testing because it is the one @@ -353,6 +353,44 @@ describe('days, units and captions', () => { expect(historyRows(cards[0]).every(r => r.hours === 0)).toBe(true) }) + /* The receipt and the day-conflict line: the two things that explain a number nobody can explain + from the number itself. Worth testing because they are *sentences about data* — the place where + "the hours add up to 840" quietly becomes "the day is 840" if nobody is looking. */ + it('turns the sync receipt into rows a person can read', () => { + const rows = receiptRows({ + at: 1, points: 720, field: 'qty', stamps: 'hour', sources: ['Apple Watch', 'iPhone'], + sum: 840, newest: { stamp: '2026-09-23 14:00:00 +0000', value: 499 }, + head: [['2026-09-23 08:00:00 +0000', 120]], tail: [['2026-09-23 12:00:00 +0000', 340], ['2026-09-23 13:00:00 +0000', 420], ['2026-09-23 14:00:00 +0000', 499]] + }) + const get = k => rows.find(r => r.key === k)?.value + expect(get('points')).toBe('720') + expect(get('stamps')).toBe('one total an hour') + expect(get('sources')).toBe('Apple Watch, iPhone') + expect(get('sum')).toBe('840') + expect(get('newest')).toBe('499') + // A run of rising numbers is the tell that they are running totals, not one hour each. + expect(get('tail')).toBe('340 → 420 → 499') + expect(receiptRows(null)).toEqual([]) + expect(receiptRows({ points: 0 })).toEqual([]) + // Nothing reported is said as nothing, not as an empty join. + expect(receiptRows({ points: 2, stamps: 'day', field: 'qty', sum: 10 }).find(r => r.key === 'sources').value).toBe('not reported') + }) + + it('sees when a day disagrees with the sum of its own hours', () => { + const day = { day: '2026-09-23', f: { qty: bucket(499) }, hours_sum: { qty: 340 }, own: true } + expect(dayConflict(day)).toEqual({ field: 'qty', shown: 499, sum: 340, declared: true }) + // Agreement is not a conflict, and neither is a day with no hours behind it. + expect(dayConflict({ ...day, hours_sum: { qty: 499 } })).toBe(null) + expect(dayConflict({ day: '2026-09-23', f: { qty: bucket(499) } })).toBe(null) + expect(dayConflict(null)).toBe(null) + // A sum that is not the day's own is still a conflict worth saying out loud. + expect(dayConflict({ f: { qty: bucket(840) }, hours_sum: { qty: 840 } , own: false })).toBe(null) + expect(dayConflict({ f: { qty: bucket(840) }, hours_sum: { qty: 340 }, own: false })) + .toEqual({ field: 'qty', shown: 840, sum: 340, declared: false }) + // Several fields at once is not something to guess about. + expect(dayConflict({ f: { qty: bucket(1) }, hours_sum: { qty: 2, Avg: 3 } })).toBe(null) + }) + 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') diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index 39d379f..5a88b77 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -1406,6 +1406,20 @@ export default { // resetting one measurement, from its own detail sheet 'Reset this measurement': 'Reiniciar esta medición', // segunda opinión (Jev) + 'What arrived last': 'Qué llegó en el último envío', + 'Datapoints in the last sync': 'Datos en el último envío', + 'How they were stamped': 'Cómo vienen marcados', + 'Sources': 'Fuentes', + 'not reported': 'sin informar', + 'Newest value': 'Valor más nuevo', + 'Latest values, oldest first': 'Últimos valores, del más viejo al más nuevo', + '{0} adds up to': '{0} suma', + 'one total a day': 'un total por día', + 'one total an hour': 'un total por hora', + 'individual samples': 'muestras individuales', + 'mixed stamps': 'marcas mezcladas', + 'The phone declared {0} for this day, and its hours add up to {1}. The declared total is the one shown — the hours are how the day was shaped, not a second number to add.': 'El teléfono declaró {0} para este día, y sus horas suman {1}. El número que se muestra es el total declarado: las horas son la forma del día, no un segundo número para sumar.', + 'This day\'s hours add up to {0} but the day shows {1}, which means the phone sent a total for the day as well as its hours.': 'Las horas de este día suman {0} pero el día muestra {1}: el teléfono mandó también un total del día además de sus horas.', 'Second opinion': 'Segunda opinión', 'Second opinion updated': 'Segunda opinión actualizada', 'What is sent': 'Qué se envía', diff --git a/frontend/src/views/Health.jsx b/frontend/src/views/Health.jsx index 229bfc2..dbc415f 100644 --- a/frontend/src/views/Health.jsx +++ b/frontend/src/views/Health.jsx @@ -30,6 +30,7 @@ import { hourRows, hourChartPoints, historyRows } from '../lib/vitals-view.js' import { insightView, sentRows, pct } from '../lib/insight-view.js' +import { receiptRows, dayConflict } from '../lib/vitals-view.js' /* The period filter, "Today" first and by default: a card's headline is always the newest reading, and "is that right now?" is the question a five-minute cadence exists to answer. The @@ -225,6 +226,8 @@ function MetricSheet({ card, metric, close, onReset }) { return () => { live = false } }, [card.name, day, dayHours]) + const receipt = receiptRows(metric && metric.shape) + const conflict = dayConflict(metric && metric.days ? metric.days.find(d => d.day === card.day) : null) const hourList = hourRows(hours, card) const history = historyRows(card) const val = r => fmtValue(r.value, card.dec) + (unitLabel(card.unit) ? ' ' + unitLabel(card.unit) : '') @@ -258,6 +261,12 @@ function MetricSheet({ card, metric, close, onReset }) { {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.')} } + {conflict &&
+ {conflict.declared + ? t('The phone declared {0} for this day, and its hours add up to {1}. The declared total is the one shown — the hours are how the day was shaped, not a second number to add.', fmtValue(conflict.shown, card.dec), fmtValue(conflict.sum, card.dec)) + : t('This day\'s hours add up to {0} but the day shows {1}, which means the phone sent a total for the day as well as its hours.', fmtValue(conflict.sum, card.dec), fmtValue(conflict.shown, card.dec))} +
} + {history.length > 1 && <>

{t('Day by day')}

@@ -280,6 +289,14 @@ function MetricSheet({ card, metric, close, onReset }) { {card.sources.length ? ' · ' + card.sources.join(', ') : ''}
+ {/* What the phone actually sent for this metric, last sync. It is here because "the number in + the app does not match the Health app" cannot be answered by the number itself: the shape of + what arrived is the answer. */} + {receipt.length > 0 && <> +

{t('What arrived last')}

+
{receipt.map(r => )}
+ } + {/* Starting one measurement over, not the whole profile. The two rows that can delete health data are worded so they cannot be confused: this one names the metric it resets, and the one in the setup sheet says it takes everything. */} diff --git a/frontend/src/views/Health.render.test.jsx b/frontend/src/views/Health.render.test.jsx index 65ce23e..f136c45 100644 --- a/frontend/src/views/Health.render.test.jsx +++ b/frontend/src/views/Health.render.test.jsx @@ -394,6 +394,43 @@ describe('the detail sheet', () => { expect(sheet()).not.toContain('This metric arrived as one total a day') }) + /* The sheet has to be able to explain a number that does not match the Health app, because the + number cannot explain itself: what arrived, how it was stamped, and — when the day and its own + hours disagree — which of the two is being shown. */ + it('shows what arrived, and says so when a day disagrees with its own hours', async () => { + const withReceipt = () => ({ + ...VITALS, + metrics: { + step_count: { + units: 'count', sources: ['Apple Watch', 'iPhone'], + shape: { + at: Date.now(), points: 720, field: 'qty', stamps: 'hour', sources: ['Apple Watch', 'iPhone'], + sum: 840, newest: { stamp: '2026-09-23 14:00:00 +0000', value: 499, ms: 1 }, + head: [['2026-09-23 08:00:00 +0000', 120]], + tail: [['2026-09-23 12:00:00 +0000', 340], ['2026-09-23 13:00:00 +0000', 420], ['2026-09-23 14:00:00 +0000', 499]] + }, + days: [ + { ...day('2026-09-02', { qty: bucket(11000) }), hours: 24, own: false, hours_sum: { qty: 11000 } }, + { ...day('2026-09-03', { qty: bucket(499) }), hours: 3, own: true, hours_sum: { qty: 340 } } + ] + } + } + }) + route(withReceipt(), HOURS) + await mountWithSheets() + openSteps() + await act(async () => {}) + + const text = sheet() + expect(text).toContain('What arrived last') + expect(text).toContain('one total an hour') + expect(text).toContain('Apple Watch, iPhone') + expect(text).toContain('340 → 420 → 499') + // The day keeps the phone's total, and the sheet says why the two numbers differ instead of + // leaving whoever noticed to guess. + expect(text).toContain('The phone declared 499 for this day, and its hours add up to 340') + }) + it('says the automation groups by day instead of drawing an empty hour list', async () => { route(VITALS, HOURS) await mountWithSheets()