diff --git a/api/test/vitals.test.js b/api/test/vitals.test.js index 7022f45..db17430 100644 --- a/api/test/vitals.test.js +++ b/api/test/vitals.test.js @@ -10,7 +10,7 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { parsePayload, mergeVitals, vitalsSeries, vitalsHours, dropMetric, emptyVitals, parseHaeDate, - normalizeDoc, RETENTION_DAYS, LEDGER_MS, HOURS_KEPT_DAYS + normalizeDoc, pickSource, RETENTION_DAYS, LEDGER_MS, HOURS_KEPT_DAYS } from '../vitals.js'; const NOW = Date.parse('2026-05-01T23:30:00Z'); @@ -230,6 +230,146 @@ test('workouts dedupe on name+start+end, newest first, and a re-send adds nothin assert.equal(again.doc.workouts.length, 2); }); +/* ---------- two devices, one walk ---------- + * + * Reported live: the Health app said 946 steps and the card said 1,700 — a ratio of about 1.8, which + * is the share of the day only one of the two devices was recording. HealthKit de-duplicates the + * same walk across an iPhone and an Apple Watch; a payload that carries both as separate points has + * been de-duplicated by nobody, so adding them counts the walk twice. Each bucket now keeps its + * sources apart and shows the one that reported most in it. */ + +const bySource = (name, source, points) => ({ + name, units: 'count', + data: points.map(([time, qty]) => ({ qty, date: at('2026-05-01', time), source })) +}); + +test('the same hour from two devices is counted once, not twice', () => { + const doc = merge(emptyVitals(), parsePayload({ + data: { metrics: [ + bySource('step_count', 'Apple Watch', [['08:00:00', 120], ['09:00:00', 220]]), + bySource('step_count', 'iPhone', [['08:00:00', 90], ['09:00:00', 140]]) + ] } + })).doc; + const day = doc.metrics.step_count.days['2026-05-01']; + // 946 against 1,700: the watch was on the wrist for both hours, so the day is the watch's. + assert.equal(day.f.qty.sum, 340, 'the day is one device, not the sum of two'); + assert.equal(day.n, 2); + assert.equal(day.h['08'].f.qty.sum, 120); + assert.equal(day.h['09'].f.qty.sum, 220); + assert.equal(day.src, 'Apple Watch', 'and the bucket says which device it used'); + // Both are still remembered as having reported — the footer of the sheet lists them. + assert.deepEqual(doc.metrics.step_count.sources, ['iPhone', 'Apple Watch']); +}); + +test('an hour only the phone recorded is the phone\'s hour', () => { + // The choice is per bucket, and that is what makes the disjoint case right: a walk without the + // watch is not lost, because nothing competes with it in those hours. + const doc = merge(emptyVitals(), parsePayload({ + data: { metrics: [ + bySource('step_count', 'Apple Watch', [['14:00:00', 500]]), + bySource('step_count', 'iPhone', [['09:00:00', 400], ['14:00:00', 60]]) + ] } + })).doc; + const day = doc.metrics.step_count.days['2026-05-01']; + assert.equal(day.h['09'].f.qty.sum, 400, 'the phone had that hour to itself'); + assert.equal(day.h['09'].src, 'iPhone'); + assert.equal(day.h['14'].f.qty.sum, 500, 'and the watch won the hour it shares'); + assert.equal(day.h['14'].src, 'Apple Watch'); + assert.equal(day.f.qty.sum, 900, 'so the day is both, each counted once'); +}); + +test('two day totals for one day is one day, and the larger one is the truth', () => { + // Days grouping with a point per source: replacing is what the day rule does, and picking the + // larger is what HealthKit would show — the union of both devices is not the smaller total. + const doc = merge(emptyVitals(), parsePayload({ + data: { metrics: [ + { name: 'step_count', units: 'count', data: [ + { qty: 946, date: at('2026-05-01'), source: 'Apple Watch' }, + { qty: 754, date: at('2026-05-01'), source: 'iPhone' } + ] } + ] } + })).doc; + const day = doc.metrics.step_count.days['2026-05-01']; + assert.equal(day.f.qty.sum, 946, 'not 1,700'); + assert.equal(day.src, 'Apple Watch'); + assert.equal(day.own, true); + + // A newer, larger total from either device replaces it, as a day always did. + const later = merge(doc, parsePayload({ + data: { metrics: [{ name: 'step_count', units: 'count', data: [ + { qty: 1200, date: at('2026-05-01'), source: 'Apple Watch' }, + { qty: 1300, date: at('2026-05-01'), source: 'iPhone' } + ] }] } + })).doc.metrics.step_count.days['2026-05-01']; + assert.equal(later.f.qty.sum, 1300, 'the day is one of them, never both added'); + assert.equal(later.src, 'iPhone'); +}); + +test('a payload with no source at all behaves exactly as it always did', () => { + // Every metric HAE sends without a `source` (iOS 27+ omits it for cumulative data, and older + // exports never had it) lives in one unnamed source, so one bucket is the whole story. + const doc = merge(emptyVitals(), parsePayload({ + data: { metrics: [ + bySource('step_count', undefined, [['08:00:00', 120], ['09:00:00', 220]]), + bySource('step_count', undefined, [['14:00:00', 500]]) + ] } + })).doc; + const day = doc.metrics.step_count.days['2026-05-01']; + assert.equal(day.f.qty.sum, 840, 'three samples, one device, added'); + assert.equal(day.src, null, 'no source to name'); + assert.equal(day.n, 3); +}); + +test('an hour stored before sources existed competes like any other', () => { + // An upgrade must not throw away what it already had: an aggregate with no sources is adopted as + // the unnamed source, and the two then compete on samples like any pair — the day does not silently + // become whatever the phone sent last. + // A fresh copy each time: `mergeVitals` is pure in what it *returns*, but the buckets it is given + // are the ones it writes into, so a second merge off the same object would see the first one's work. + const legacy = () => normalizeDoc({ metrics: { step_count: { units: 'count', days: { + '2026-05-01': { n: 12, lastTs: Date.parse('2026-05-01T09:00:00Z'), f: { qty: { n: 12, sum: 900, min: 1, max: 90, last: 40 } }, + h: { '08': { n: 12, lastTs: Date.parse('2026-05-01T09:00:00Z'), f: { qty: { n: 12, sum: 900, min: 1, max: 90, last: 40 } } } } } + } } } }); + const doc = merge(legacy(), parsePayload({ + data: { metrics: [{ name: 'step_count', units: 'count', data: [{ qty: 4, date: at('2026-05-01', '15:00:00'), source: 'iPhone' }] }] } + }), NOW).doc; + const day = doc.metrics.step_count.days['2026-05-01']; + assert.equal(day.h['08'].f.qty.sum, 900, 'the hour it already had is untouched'); + assert.equal(day.h['15'].f.qty.sum, 4, 'the phone\'s sample landed in its own hour'); + assert.equal(day.f.qty.sum, 904, 'the day is both hours, each counted once'); + // The day's own source is *undecided* here on purpose: a legacy day with no hours has nothing to + // attribute, so the reader reports null rather than inventing a device. + assert.equal(day.src, undefined); + + // Same hour, both sources: the one with more samples that hour wins. Three new samples do not + // outweigh an aggregate of twelve, so the hour it already had stands... + const three = merge(legacy(), parsePayload(metric('step_count', 'count', [ + { qty: 500, date: at('2026-05-01', '08:00:00'), source: 'Apple Watch' }, + { qty: 500, date: at('2026-05-01', '08:05:00'), source: 'Apple Watch' }, + { qty: 500, date: at('2026-05-01', '08:10:00'), source: 'Apple Watch' } + ]))).doc.metrics.step_count.days['2026-05-01']; + assert.equal(three.h['08'].f.qty.sum, 900, 'twelve samples beat three'); + assert.equal(three.h['08'].f.qty.n, 12); + // ...and a device that genuinely reports more of the hour does take it. + const caughtUp = merge(legacy(), parsePayload(metric('step_count', 'count', Array.from({ length: 14 }, + (_, i) => ({ qty: 60, date: at('2026-05-01', `08:${String(i * 4).padStart(2, '0')}:00`), source: 'Apple Watch' }))))).doc + .metrics.step_count.days['2026-05-01']; + assert.equal(caughtUp.h['08'].src, 'Apple Watch', 'fourteen samples against twelve'); + assert.equal(caughtUp.h['08'].f.qty.sum, 840); +}); + +test('the source a bucket shows is picked by samples, then recency, then size', () => { + const bucket = s => ({ s }); + assert.equal(pickSource(bucket({ a: { n: 2, lastTs: 1, f: {} }, b: { n: 3, lastTs: 0, f: {} } })), 'b', 'most samples'); + assert.equal(pickSource(bucket({ a: { n: 2, lastTs: 9, f: {} }, b: { n: 2, lastTs: 1, f: {} } })), 'a', 'then newest'); + assert.equal(pickSource(bucket({ + a: { n: 1, lastTs: 5, f: { qty: { n: 1, sum: 10 } } }, + b: { n: 1, lastTs: 5, f: { qty: { n: 1, sum: 99 } } } + })), 'b', 'then the larger total'); + assert.equal(pickSource({}), null); + assert.equal(pickSource({ s: {} }), null); +}); + /* ---------- hours: the detail a day total throws away ---------- */ test('an hourly payload keeps its hours, and the day is exactly their sum', () => { diff --git a/api/vitals.js b/api/vitals.js index 5839246..4c499c5 100644 --- a/api/vitals.js +++ b/api/vitals.js @@ -327,6 +327,114 @@ function hourGrouped(points) { const dayKeyOk = k => /^\d{4}-\d{2}-\d{2}$/.test(k); +/* ── Two devices, one walk ──────────────────────────────────────────────────────────────────── + * + * HealthKit de-duplicates: the same walk recorded by an iPhone and an Apple Watch is one walk in the + * Health app. A payload that carries both as separate points has been de-duplicated by nobody, so + * adding them is what turns 946 steps into 1,700 — a live report, and a ratio of about 1.8, which is + * exactly the share of the time only one of the two devices was recording. + * + * So a bucket keeps its sources *apart* and shows one of them: the source that reported most in that + * bucket, which is the device that was actually being worn. Per bucket, never per day, because that + * is what makes both cases right — an hour where only the phone recorded is the phone's hour, and an + * hour where both recorded is counted once. A metric with a single source (most people, and every + * metric whose payload has no `source` at all) behaves exactly as it did before: one sub-bucket, + * which is the bucket. + * + * The choice is deliberately not a sum, not an average, and not a "max": it is one device's own + * aggregate. A number that exists on the wrist is the number the wrist's app shows. */ + +/** This source's own aggregates inside a bucket, created on first sight. */ +function sourceBucket(bucket, source) { + const all = bucket.s || (bucket.s = {}); + const key = source || ''; + return all[key] || (all[key] = { n: 0, lastTs: 0, f: {} }); +} + +/** How much a source reports in a bucket — used only to break a tie, never to compute a value. */ +function totalOf(b) { + const sums = Object.values(b.f || {}).map(v => v.sum).filter(v => typeof v === 'number'); + return sums.length ? Math.max(...sums) : 0; +} + +/** + * The source a bucket shows: most samples, then the newest, then the largest total. Sample count + * first because it says who was actually recording (a watch taking a reading every five minutes + * against a phone that caught one); the newest next because a payload that stops mid-bucket leaves + * the other device holding the end of it; the total last, which is the only tie-break left for a + * day-level point from each device. + */ +export function pickSource(bucket) { + const all = bucket && bucket.s; + if (!all) return null; + let best = null, bestN = -1, bestTs = -1, bestTotal = -1; + for (const [key, b] of Object.entries(all)) { + const total = totalOf(b); + const better = b.n > bestN + || (b.n === bestN && b.lastTs > bestTs) + || (b.n === bestN && b.lastTs === bestTs && total > bestTotal); + if (better) { best = key; bestN = b.n; bestTs = b.lastTs; bestTotal = total; } + } + return best; +} + +/** + * A bucket written before this existed has an aggregate and no sources: it is adopted as the + * unnamed source rather than thrown away, so an upgrade never loses the day it already had — and + * the two then compete on samples like any other pair. + */ +function seedLegacy(bucket, ms) { + if (!bucket.s && bucket.f && Object.keys(bucket.f).length) { + bucket.s = { '': { n: bucket.n || 0, lastTs: bucket.lastTs || ms, f: bucket.f } }; + } +} + +/** Fold one sample into its own source's bucket, then show the winning one. */ +function addPoint(bucket, source, fields, ms) { + seedLegacy(bucket, ms); + const b = sourceBucket(bucket, source); + addFields(b, fields); + b.lastTs = Math.max(b.lastTs, ms); + return applySource(bucket); +} + +/** + * One datapoint that *is* a bucket — an hour HAE grouped itself, or a day it totalled — where that + * source's earlier report of the same bucket is superseded rather than added to (the hour in + * progress grows on every run of a five-minute automation). + * + * Only that source's sub-bucket is superseded. A device re-sending its own hour says nothing about + * the other device's, and wiping the whole bucket is how one device's report would silently delete + * the other's — which is the opposite of what this is for. + */ +function setPoint(bucket, source, fields, ms) { + seedLegacy(bucket, ms); + const b = sourceBucket(bucket, source); + b.n = 0; + b.f = {}; + b.lastTs = ms; + addFields(b, fields); + return applySource(bucket); +} + +/** What this source last reported for a bucket, whether the bucket knows about sources or not. */ +function sourceReport(bucket, source) { + if (!bucket) return null; + if (bucket.s) return bucket.s[source || ''] || null; + return bucket; +} + +/** Make the bucket show its winning source; returns the key that won (or null). */ +function applySource(bucket) { + const key = pickSource(bucket); + if (key == null) return null; + const b = bucket.s[key]; + bucket.src = key || null; + bucket.n = b.n; + bucket.f = b.f; + return key; +} + function addFields(bucket, fields) { for (const [k, v] of Object.entries(fields)) { const f = bucket.f[k] || (bucket.f[k] = { n: 0, sum: 0, min: v, max: v, last: v }); @@ -371,6 +479,18 @@ function deriveDay(day) { day.f = f; day.n = n; day.hsum = sumHours(day); + /* Which device the day is mostly made of. Each hour has already been reduced to one source (two + devices recording the same hour are one hour), so the day's answer is the device that reported + most of it — worth saying out loud on the sheet, because "the watch, mostly, plus two hours the + phone had to itself" is what the number actually is. */ + const bySrc = {}; + for (const hb of Object.values(day.h || {})) { + // `|| ''`: an hour stored before sources existed has none, and its samples are still the day's. + const key = hb.src || ''; + bySrc[key] = (bySrc[key] || 0) + (hb.n || 0); + } + const winner = Object.entries(bySrc).sort((a, b) => b[1] - a[1])[0]; + day.src = winner ? (winner[0] || null) : null; } /** @@ -429,16 +549,20 @@ export function mergeVitals(doc, payload, now = Date.now()) { } 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 + // Nothing to do when this source re-sends the value it already reported (the common case + // for every run after the first). `f` is compared as a whole because a day total and a // once-a-day gauge both live in it. - if (prev && prev.n === 1 && sameFields(prev.f, p.fields)) { stats.duplicates++; continue; } - // The hours already stored for that day ride along: the phone's own total is the better - // 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, ownAt: now }; - cur.days[key].hsum = sumHours(cur.days[key]); + const own = sourceReport(prev, p.source); + if (own && own.n === 1 && sameFields(own.f, p.fields)) { stats.duplicates++; continue; } + // The hours already stored for that day ride along, and so does any other source's total: + // the phone's own number is the better day value, but it says nothing about the shape of + // the day, and one device's total does not replace another's — the two are compared, and + // the one that reported more wins (`own` records that the day's number is a declared total + // rather than the sum of its hours; see below). + const dayBucket = prev ? { ...prev, own: true, ownAt: now } : { h: {}, own: true, ownAt: now, n: 0, lastTs: p.at.ms, f: {} }; + cur.days[key] = dayBucket; + setPoint(dayBucket, p.source, p.fields, p.at.ms); + dayBucket.hsum = sumHours(dayBucket); stats.points++; continue; } @@ -446,11 +570,13 @@ export function mergeVitals(doc, payload, now = Date.now()) { const hours = day.h || (day.h = {}); const hh = p.at.time.slice(0, 2); if (byHour) { - // An hour the phone grouped itself: replaced, never unioned, because the hour in progress - // grows on every run of a five-minute automation. - const prev = hours[hh]; + // An hour the phone grouped itself: replaced — that source's hour, never unioned, because + // the hour in progress grows on every run of a five-minute automation. Another device's + // report of the same hour is a separate sub-bucket and is not touched. + const prev = sourceReport(hours[hh], p.source); if (prev && sameFields(prev.f, p.fields)) { stats.duplicates++; continue; } - hours[hh] = bucketFrom(p.fields, p.at.ms); + const hb = hours[hh] || (hours[hh] = { n: 0, lastTs: p.at.ms, f: {} }); + setPoint(hb, p.source, p.fields, p.at.ms); // The exact datapoint is remembered anyway: a payload grouped by hour and a later one // carrying real minutes can describe the same instant — the automation was reconfigured, // or two of them write to one profile — and the union path can only see the ledger, so @@ -460,8 +586,9 @@ export function mergeVitals(doc, payload, now = Date.now()) { const id = sampleId(p); if (cur.seen[id] != null) { stats.duplicates++; continue; } cur.seen[id] = p.at.ms; - addFields(hours[hh] || (hours[hh] = { n: 0, lastTs: p.at.ms, f: {} }), p.fields); - hours[hh].lastTs = Math.max(hours[hh].lastTs, p.at.ms); + const hb = hours[hh] || (hours[hh] = { n: 0, lastTs: p.at.ms, f: {} }); + addPoint(hb, p.source, p.fields, p.at.ms); + hb.lastTs = Math.max(hb.lastTs, p.at.ms); } day.lastTs = Math.max(day.lastTs, p.at.ms); /* Recompute the day from its hours, which keeps this idempotent: the same hour arriving @@ -648,6 +775,10 @@ export function vitalsSeries(doc, { days = 90, now = Date.now() } = {}) { // `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, + // Which device the day is mostly made of, when more than one reported into it. Two devices + // recording the same hour are one hour, and saying which one won is the difference between a + // number somebody can check against their watch and a number they cannot. + source: b.src || null, hours_sum: b.hsum || null, f: projectFields(b.f) }); diff --git a/docs/HEALTH.md b/docs/HEALTH.md index a7c855d..10d80d0 100644 --- a/docs/HEALTH.md +++ b/docs/HEALTH.md @@ -69,6 +69,7 @@ configured for, so the rule is chosen per payload, from the payload's own shape: | Every datapoint sits exactly on midnight (`00:00:00`) — HAE's **Days** grouping, i.e. a **total** per day | The day it names is **replaced** by it, in full. A day total only ever supersedes another day total, so re-sending the same day all afternoon converges on the day's total instead of accumulating. | Overlapping windows, disjoint windows, manual re-exports, first sync of a year of history. | | Every datapoint sits exactly on the hour (`HH:00:00`) — HAE's **Hours** grouping, i.e. a **total** per hour | That **hour** is replaced, for the same reason: the hour in progress grows on every run. The day is then recomputed as the sum of its hours, so the day total and the hourly detail can never disagree. The hours are what the detail sheet draws (kept for 7 days; the day aggregates live on). | Overlapping windows, disjoint windows, and switching an automation from `Days` to `Hours` mid-day. | | Anything else — real sample timestamps, or Minute grouping | Each sample is identified by its **instant plus its numbers** and stored once, in its own hour. A repeat is skipped and reported back as `duplicates`; a genuinely new sample is added. | Overlapping windows (repeats detected) and disjoint ones (new samples add). | +| **Two devices in one hour** (an Apple Watch and an iPhone both recording the walk) | The hour keeps each source's aggregates apart and shows **one** of them — the source that reported most in that hour, then the newest, then the largest. Not a sum: HealthKit de-duplicates the same walk, and adding both is what turns 946 steps into 1,700. The choice is per hour, which is what makes the disjoint case right too — an hour only the phone recorded is the phone's hour, and nothing competes with it. | A metric with a single source, or one whose payload has no `source` at all, behaves exactly as it did: one source, which is the bucket. | The hour rule is decided from the **whole payload**, never from a single timestamp: a five-minute automation also produces samples that land exactly on the hour, and reading one of those as an hour @@ -234,6 +235,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, by about 1.6–1.9× | Two devices recorded the same activity and the Health app de-duplicated it. Nothing to do: the hour keeps its sources apart and shows one of them, and the metric's sheet ends with `… · Apple Watch, iPhone · using Apple Watch` so the number can be checked against the device that produced it. A ratio that *grows* through the day instead means the payload carries running totals rather than per-hour values — see the row below. | | 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. | diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index 4fff5dd..9d843c0 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -1407,6 +1407,7 @@ export default { 'Reset this measurement': 'Reiniciar esta medición', // segunda opinión (Jev) 'The server is running an older API than this screen: the numbers may not match Apple Health, and the hourly detail and the sync receipt will not appear until the api container is updated.': 'El servidor está corriendo una api más vieja que esta pantalla: los números pueden no coincidir con Apple Health, y el detalle por hora y el recibo del último envío no van a aparecer hasta que se actualice el contenedor de la api.', + 'using {0}': 'se usa {0}', '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', diff --git a/frontend/src/views/Health.jsx b/frontend/src/views/Health.jsx index 30b257e..434a2f7 100644 --- a/frontend/src/views/Health.jsx +++ b/frontend/src/views/Health.jsx @@ -233,7 +233,12 @@ function MetricSheet({ card, metric, close, onReset }) { list is only worth a section when there is more than one (heart rate's Min/Avg/Max, sleep's stages, an unknown metric's whatever-it-sent). */ const receipt = receiptRows(metric && metric.shape, { withValues: hourList.length === 0 }) - const conflict = dayConflict(metric && metric.days ? metric.days.find(d => d.day === card.day) : null) + const dayObj = metric && Array.isArray(metric.days) ? metric.days.find(d => d.day === card.day) : null + const conflict = dayConflict(dayObj) + // When two devices reported into this day, which one the number is mostly made of. It is the + // difference between a number somebody can check against their watch and one they cannot: the + // watch and the phone record the same walk, and only one of them is counted in each hour. + const usedSource = dayObj && dayObj.source && (card.sources || []).length > 1 ? dayObj.source : null const history = historyRows(card, { skip: card.day }) const val = r => fmtValue(r.value, card.dec) + (unitLabel(card.unit) ? ' ' + unitLabel(card.unit) : '') @@ -292,6 +297,7 @@ function MetricSheet({ card, metric, close, onReset }) {
{t('{0} days with data in this range', card.days)} {card.sources.length ? ' · ' + card.sources.join(', ') : ''} + {usedSource ? ' · ' + t('using {0}', usedSource) : ''}
{/* What the phone actually sent for this metric, last sync. It is here because "the number in diff --git a/frontend/src/views/Health.render.test.jsx b/frontend/src/views/Health.render.test.jsx index 51c5187..8f6d2ac 100644 --- a/frontend/src/views/Health.render.test.jsx +++ b/frontend/src/views/Health.render.test.jsx @@ -430,7 +430,7 @@ describe('the detail sheet', () => { }, 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 } } + { ...day('2026-09-03', { qty: bucket(499) }), hours: 3, own: true, hours_sum: { qty: 340 }, source: 'Apple Watch' } ] } } @@ -459,6 +459,9 @@ describe('the detail sheet', () => { // 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') + // Two devices reported into this day, so the sheet says which one the number is mostly made of: + // the difference between a number somebody can check against their watch and one they cannot. + expect(text).toContain('using Apple Watch') }) it('shows the values in the receipt when there are no hours to show them in', async () => { @@ -489,6 +492,22 @@ describe('the detail sheet', () => { expect(text).not.toContain('Hour by hour') }) + it('says which device the day came from when two reported', async () => { + const oneSource = () => ({ + ...VITALS, + metrics: { step_count: { units: 'count', sources: ['Apple Watch'], days: [ + { ...day('2026-09-03', { qty: bucket(946) }), hours: 0, source: 'Apple Watch' } + ] } } + }) + // One source: nothing to disambiguate, so the line stays as it was. + route(oneSource(), { ok: true, metric: 'step_count', day: '2026-09-03', hours: [] }) + await mountWithSheets() + openSteps() + await act(async () => {}) + expect(sheet()).toContain('Apple Watch') + expect(sheet()).not.toContain('using') + }) + it('says the automation groups by day instead of drawing an empty hour list', async () => { route(VITALS, HOURS) await mountWithSheets()