From 5c69540f62b52e4bd71431230a77e8d1cbadd15e Mon Sep 17 00:00:00 2001 From: Daniel Santillan Date: Wed, 23 Sep 2026 16:18:28 -0400 Subject: [PATCH] Salud: reset one measurement, without losing the rest MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "Podemos reiniciar los números de esas mediciones para yo enviar el de hoy." The whole-file reset already existed two taps away in the setup sheet, but it is the wrong size for the question: the four metrics he suspects are not the profile. Throwing away a month of heart rate to start steps over is not a reset, it is a tax. So a metric can now be forgotten on its own: the detail sheet has **Reset this measurement**, which deletes that metric's days (and hours) and nothing else — the other metrics, the workouts and the ingest key stay. With any Date Range wider than a day the phone re-sends that metric on its next sync, which is what makes this a reset rather than a loss: Apple Health still has the data, and a day total replaces the day it names, so the stored past is rewritten rather than duplicated. The two destructive rows are worded apart on purpose and the confirm names the metric ("¿Reiniciar Pasos?"), because the neighbouring action in the setup sheet takes every metric there is. `dropMetric()` is pure and returns how many days it took, and the route answers `metric: null` for a metric the profile does not have (or a profile with no health file at all) instead of an error — a screen that says "nothing stored" is more useful than a 404 answering a button press. Tested from both ends: the helper's purity and arithmetic, the route against a real server (one metric gone, the others and the workouts intact, the key still working, and a re-sync rebuilding it), and the sheet's flow through the real confirm. Mutation-checked: pointing the row at the whole-file delete fails it. --- CHANGELOG.md | 6 ++++ api/openapi.yaml | 18 ++++++++-- api/server.js | 13 ++++++- api/test/server-vitals.test.js | 41 +++++++++++++++++++++++ api/test/vitals.test.js | 30 +++++++++++++++-- api/vitals.js | 22 ++++++++++++ docs/HEALTH.md | 7 ++++ frontend/src/lib/audit.js | 1 + frontend/src/locales/es.js | 9 +++++ frontend/src/views/Health.jsx | 34 +++++++++++++++++-- frontend/src/views/Health.render.test.jsx | 35 +++++++++++++++++++ 11 files changed, 209 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f4eca9..04e7eae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,12 @@ the setting that decides whether history exists at all: with HAE's default `Toda never sent, which is exactly what a card frozen on a single day looks like — `Previous 7 Days` is what the setup steps now say. +A metric can also be **reset on its own** (its detail sheet → *Reset this measurement*): the days +and hours stored for that one measurement go, every other metric stays, and the next sync rebuilds +it from the phone. That is the shape of the question people actually arrive with — "these steps +look wrong, start them over" — and it is not the same as the profile-wide *Delete the health data* +two taps away in the setup sheet, which is why the two are worded apart. + Also here: the watch's workouts are shown **read-only** in Salud and deliberately kept out of the history — they carry no sets or weights, so folding them into progression, PRs and the recovery model would be inventing data. Coverage: `api/vitals.js` (19 tests), the routes against a real diff --git a/api/openapi.yaml b/api/openapi.yaml index fd7e6e9..5dabffa 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -668,10 +668,24 @@ paths: delete: tags: [health] operationId: vitalsClear - summary: Delete the caller's health data - description: >- + summary: Delete the caller's health data, or one metric of it + description: | Removes the profile's health file and nothing else: the workout history, the account and the ingest key are untouched, so a phone needs no re-configuring to sync again. + + With `?metric=` it forgets **one** measurement instead, days and hours included, and leaves + every other metric in place — the answer to "these numbers look wrong, start this one over". + It is a reset rather than a loss whenever the automation's Date Range is wider than a day: + the next sync sends that metric again from Apple Health. A metric the profile does not have + answers `200` with `metric: null`, not an error. + parameters: + - name: metric + in: query + required: false + schema: { type: string } + description: >- + The metric name exactly as HAE wrote it (`step_count`, `heart_rate`…). Omit it to clear + everything. responses: '200': description: Deleted (also when there was nothing stored). diff --git a/api/server.js b/api/server.js index 14777e9..43e8cc4 100644 --- a/api/server.js +++ b/api/server.js @@ -19,7 +19,7 @@ import { startCadence } from './coach/cadence.js'; import { startWarmup } from './coach/warmup.js'; import { dayReminderPush, restTimerPush, testPush } from './push-messages.js'; import { verifyError } from './verify-error.js'; -import { parsePayload, mergeVitals, vitalsSeries, vitalsHours, emptyVitals, RETENTION_DAYS } from './vitals.js'; +import { parsePayload, mergeVitals, vitalsSeries, vitalsHours, dropMetric, emptyVitals, RETENTION_DAYS } from './vitals.js'; import { hostAllowed, readCapped, parseMusicPage } from './music.js'; const PORT = +(process.env.PORT || 3000); @@ -1108,6 +1108,17 @@ const routes = { 'DELETE /api/vitals': async (req, res) => { const user = readSession(req); if (!user) return json(res, 401, { error: 'not signed in' }); + /* `?metric=` narrows the delete to one measurement — "reset Pasos", not "start over". The rest + of the file, the workouts and the key stay, and with any Date Range wider than a day the + phone sends that metric again on its next sync, so it comes back with Apple's numbers. */ + const metric = new URL(req.url, 'http://x').searchParams.get('metric'); + if (metric) { + const { doc, days, found } = dropMetric(readVitals(user.id), metric); + // No file, or no such metric in it: nothing to write, and the caller is told which it was. + if (doc && found) writeVitals(user.id, doc); + audit(req, 'auth.health.metric.clear', { user, msg: `${metric}:${days}` }); + return json(res, 200, { ok: true, metric: found ? metric : null, days }); + } try { fs.unlinkSync(vitalsFile(user.id)); } catch { /* nothing stored */ } audit(req, 'auth.health.clear', { user }); json(res, 200, { ok: true }); diff --git a/api/test/server-vitals.test.js b/api/test/server-vitals.test.js index 0e54f9e..a7aaf5a 100644 --- a/api/test/server-vitals.test.js +++ b/api/test/server-vitals.test.js @@ -251,6 +251,47 @@ test('GET /api/vitals/hours opens one metric\'s day, and only with a session', a assert.equal((await read('metric=nope&day=' + today)).metric, null); }); +test('DELETE /api/vitals?metric= resets one measurement and keeps everything else', async t => { + const h = await startServer(t); + const key = (await (await fetch(`${h.api}/api/vitals/key`, { method: 'POST', headers: cookie('u_h1') })).json()).key; + await ingest(h, key, payload()); + await ingest(h, key, { data: { metrics: [{ name: 'step_count', units: 'count', data: [{ qty: 9000, date: `${yday} 00:00:00 +0000` }] }] } }); + + // A session, like every other read: the ingest key cannot delete anything either. + assert.equal((await fetch(`${h.api}/api/vitals?metric=step_count`)).status, 401); + assert.equal((await fetch(`${h.api}/api/vitals?metric=step_count`, { method: 'DELETE', headers: { Authorization: `Bearer ${key}` } })).status, 401); + + const before = await (await fetch(`${h.api}/api/vitals`, { headers: cookie('u_h1') })).json(); + assert.equal(before.metrics.step_count.days.length, 2, 'two days of steps to start over from'); + + const gone = await (await fetch(`${h.api}/api/vitals?metric=step_count`, { method: 'DELETE', headers: cookie('u_h1') })).json(); + assert.deepEqual(gone, { ok: true, metric: 'step_count', days: 2 }); + + const after = await (await fetch(`${h.api}/api/vitals`, { headers: cookie('u_h1') })).json(); + assert.equal(after.metrics.step_count, undefined, 'the metric is gone'); + assert.deepEqual(Object.keys(after.metrics).sort(), ['heart_rate', 'weight_body_mass'], 'the others are not'); + assert.equal(after.workouts.length, 1, 'and the workouts are not health data'); + assert.equal(after.key, key, 'the key survives, so the phone keeps syncing'); + + // Asking again is not an error and not a surprise: it says it found nothing. + assert.deepEqual(await (await fetch(`${h.api}/api/vitals?metric=step_count`, { method: 'DELETE', headers: cookie('u_h1') })).json(), + { ok: true, metric: null, days: 0 }); + // A profile with no health file at all answers the same way rather than writing an empty one. + assert.deepEqual(await (await fetch(`${h.api}/api/vitals?metric=step_count`, { method: 'DELETE', headers: cookie('u_h2') })).json(), + { ok: true, metric: null, days: 0 }); + assert.equal((await (await fetch(`${h.api}/api/vitals`, { headers: cookie('u_h2') })).json()).metrics.step_count, undefined); + + // The phone syncs again and the metric is rebuilt from what it sends. + assert.equal((await ingest(h, key, payload())).status, 200); + const rebuilt = await (await fetch(`${h.api}/api/vitals`, { headers: cookie('u_h1') })).json(); + assert.equal(rebuilt.metrics.step_count.days.length, 1); + assert.equal(rebuilt.metrics.step_count.days[0].f.qty.sum, 8000); + + // ...and the whole-file delete still works when no metric is named. + assert.equal((await fetch(`${h.api}/api/vitals`, { method: 'DELETE', headers: cookie('u_h1') })).status, 200); + assert.deepEqual((await (await fetch(`${h.api}/api/vitals`, { headers: cookie('u_h1') })).json()).metrics, {}); +}); + test('DELETE /api/vitals wipes the health file and leaves the account, the key and the workouts alone', async t => { const h = await startServer(t); const key = (await (await fetch(`${h.api}/api/vitals/key`, { method: 'POST', headers: cookie('u_h1') })).json()).key; diff --git a/api/test/vitals.test.js b/api/test/vitals.test.js index bb28368..94bf6db 100644 --- a/api/test/vitals.test.js +++ b/api/test/vitals.test.js @@ -9,8 +9,8 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { - parsePayload, mergeVitals, vitalsSeries, vitalsHours, emptyVitals, parseHaeDate, normalizeDoc, - RETENTION_DAYS, LEDGER_MS, HOURS_KEPT_DAYS + parsePayload, mergeVitals, vitalsSeries, vitalsHours, dropMetric, emptyVitals, parseHaeDate, + normalizeDoc, RETENTION_DAYS, LEDGER_MS, HOURS_KEPT_DAYS } from '../vitals.js'; const NOW = Date.parse('2026-05-01T23:30:00Z'); @@ -385,6 +385,32 @@ test('the dedupe ledger and the day buckets are both pruned, so the file stays b assert.ok(LEDGER_MS === 72 * 3600 * 1000 && RETENTION_DAYS > 365); }); +test('dropMetric forgets one metric, days and all, and touches nothing else', () => { + const doc = merge(emptyVitals(), parsePayload({ + data: { + metrics: [ + { name: 'step_count', units: 'count', data: [{ qty: 9000, date: at('2026-05-01') }, { qty: 8000, date: at('2026-04-30') }] }, + { name: 'heart_rate', units: 'bpm', data: [{ date: at('2026-05-01', '09:00:00'), Avg: 70 }] } + ], + workouts: [{ name: 'Walking', start: at('2026-05-01', '10:00:00'), end: at('2026-05-01', '11:00:00') }] + } + }), NOW).doc; + + const gone = dropMetric(doc, 'step_count'); + assert.equal(gone.found, true); + assert.equal(gone.days, 2, 'and it says how much it took'); + assert.equal(gone.doc.metrics.step_count, undefined); + assert.ok(gone.doc.metrics.heart_rate, 'the other metric is untouched'); + assert.equal(gone.doc.workouts.length, 1, 'and a workout is not a health metric'); + // The input document is not modified: this is a pure function like the merge. + assert.ok(doc.metrics.step_count); + + // A metric that is not there, and a profile with no file at all, are both answers rather than + // errors — the screen says "nothing stored" instead of failing at the person. + assert.deepEqual(dropMetric(doc, 'never_heard_of_it'), { doc, days: 0, found: false }); + assert.deepEqual(dropMetric(null, 'step_count'), { doc: null, days: 0, found: false }); +}); + test('normalizeDoc survives a hand-edited or half-written file', () => { const d = normalizeDoc({ metrics: { step_count: null, heart_rate: { days: 'nope', units: 7, sources: 'x' } }, workouts: 'nope' }); assert.deepEqual(d.workouts, []); diff --git a/api/vitals.js b/api/vitals.js index ce9d99a..cc937b3 100644 --- a/api/vitals.js +++ b/api/vitals.js @@ -536,6 +536,28 @@ export function vitalsSeries(doc, { days = 90, now = Date.now() } = {}) { return { updatedAt: d.updatedAt, last: d.last, metrics, workouts: d.workouts }; } +/** + * Forget one metric, keeping everything else. + * + * The whole-file delete exists and is two taps, but it is the wrong size for the question people + * actually arrive with: "these numbers look wrong, let me start that one over". With a Date Range + * of a week or a month the phone re-sends the metric on its next sync, so this is a *reset* rather + * than a loss — and every other metric, the workouts and the ingest key are untouched, which is + * what makes it safe to do without thinking about the rest of the profile. + * + * @returns {{doc:object|null, days:number, found:boolean}} `doc` is null when the profile has no + * health file at all, so the caller can leave the file alone instead of writing an empty one. + */ +export function dropMetric(doc, metric) { + if (!doc || typeof doc !== 'object') return { doc: null, days: 0, found: false }; + const out = normalizeDoc(doc); + const name = String(metric || ''); + if (!Object.prototype.hasOwnProperty.call(out.metrics, name)) return { doc, days: 0, found: false }; + const days = Object.keys(out.metrics[name].days || {}).length; + delete out.metrics[name]; + return { doc: out, days, found: true }; +} + /** * One metric's hours on one day, oldest first — what the detail sheet opens. * diff --git a/docs/HEALTH.md b/docs/HEALTH.md index 15acf05..fd07d6e 100644 --- a/docs/HEALTH.md +++ b/docs/HEALTH.md @@ -141,6 +141,12 @@ Bounds, all enforced on write: **Salud → ⚙ → Delete the health data** removes this file. Your workouts, routines, account, passes and ingest key are untouched, so the phone needs no re-configuring to sync again. +To start over on **one** measurement instead — "these steps look wrong" — open the metric's card and +use **Reset this measurement**: that metric's days and hours go, everything else stays, and with a +Date Range of a week or more the next sync rebuilds it from Apple Health. Because a day total +*replaces* the day it names, a re-sync corrects the stored past as well: there is no separate +"recalculate" step to run. + --- ## 4. Security @@ -176,6 +182,7 @@ and you have backed up your health file too. | `413 body too large` | A first sync with everything selected and Summarize off. Turn Summarize Data on, group by Days or Hours, or split the metrics across two automations. Behind your own reverse proxy (Caddy, Cloudflare, a second nginx), raise its body limit for this path as well — the bundled stack already does. | | `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 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. | diff --git a/frontend/src/lib/audit.js b/frontend/src/lib/audit.js index b5b18bb..700d4d0 100644 --- a/frontend/src/lib/audit.js +++ b/frontend/src/lib/audit.js @@ -34,6 +34,7 @@ const LABELS = { 'auth.health.key.create': 'Created a health ingest key', 'auth.health.key.rotate': 'Replaced the health ingest key', 'auth.health.clear': 'Deleted their health data', + 'auth.health.metric.clear': 'Reset one health metric', 'admin.user.disable': 'Disabled an account', 'admin.user.enable': 'Re-enabled an account', 'admin.user.delete': 'Deleted an account', diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index bac937b..7e94efa 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -1403,6 +1403,15 @@ export default { 'Replace the key': 'Reemplazar la clave', 'The old one stops working immediately': 'La anterior deja de funcionar al instante', 'Delete the health data': 'Borrar los datos de salud', + // resetting one measurement, from its own detail sheet + 'Reset this measurement': 'Reiniciar esta medición', + 'Your next sync from the iPhone rebuilds it': 'El próximo envío desde el iPhone la reconstruye', + 'Resetting removes every day stored for this metric and nothing else: your other metrics, your workouts and your ingest key stay. With a Date Range of a week or more, the next sync sends it again from Apple Health.': 'Reiniciar borra todos los días guardados de esta métrica y nada más: tus otras métricas, tus entrenamientos y tu clave de ingesta se quedan. Con un rango de fechas de una semana o más, el próximo envío la manda otra vez desde Apple Health.', + 'Reset {0}?': '¿Reiniciar {0}?', + 'Every day stored for this metric is removed for this profile. Nothing else is touched, and your next sync from the iPhone sends it again.': 'Se borran todos los días guardados de esta métrica en este perfil. No se toca nada más, y tu próximo envío desde el iPhone la manda de nuevo.', + 'Reset': 'Reiniciar', + '{0} reset': '{0} reiniciada', + 'Nothing stored for {0}': 'No hay nada guardado de {0}', 'Keeps your workouts and your key': 'Conserva tus entrenamientos y tu clave', 'Replace the ingest key?': '¿Reemplazar la clave de ingesta?', 'Your iPhone stops syncing until you paste the new key into Health Auto Export. Nothing already stored is lost.': 'Tu iPhone deja de sincronizar hasta que pegues la nueva clave en Health Auto Export. No se pierde nada de lo ya guardado.', diff --git a/frontend/src/views/Health.jsx b/frontend/src/views/Health.jsx index 8523f3a..9e01dbd 100644 --- a/frontend/src/views/Health.jsx +++ b/frontend/src/views/Health.jsx @@ -104,7 +104,7 @@ function MetricCard({ card, onOpen }) { * 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 }) { +function MetricSheet({ card, metric, close, onReset }) { const rows = detailRows(card, undefined, metric) const tr = trendOf(card) const [day, setDay] = useState(card.day) @@ -176,6 +176,19 @@ function MetricSheet({ card, metric, close }) { {t('{0} days with data in this range', card.days)} {card.sources.length ? ' · ' + card.sources.join(', ') : ''} + + {/* 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. */} +

{t('Manage')}

+
+ onReset(card)} /> +
+
+ {t('Resetting removes every day stored for this metric and nothing else: your other metrics, your workouts and your ingest key stay. With a Date Range of a week or more, the next sync sends it again from Apple Health.')} +
@@ -322,8 +335,25 @@ export default function Health() { .catch(e => toast(e.message)) }) + /* One metric, back to nothing — the answer to "these numbers look wrong, start them over". The + confirm names the metric, because the neighbouring "Delete the health data" in the setup sheet + takes all of them and the two must not look alike. */ + const resetMetric = (card, close) => confirmSheet({ + title: t('Reset {0}?', card.label), + message: t('Every day stored for this metric is removed for this profile. Nothing else is touched, and your next sync from the iPhone sends it again.'), + confirmText: t('Reset'), danger: true, + onConfirm: () => api('/api/vitals?metric=' + encodeURIComponent(card.name), { method: 'DELETE' }) + .then(r => { + close() + load() + toast(r && r.metric ? t('{0} reset', card.label) : t('Nothing stored for {0}', card.label)) + }) + .catch(e => toast(e.message)) + }) + const setup = () => openSheet(close => ) - const openMetric = card => openSheet(close => ) + const openMetric = card => openSheet(close => resetMetric(c, close)} />) /* Guest mode keeps everything in this browser and never talks to a server, so there is nothing for a phone to post to. Saying so once is friendlier than a 401 the visitor cannot act on. */ diff --git a/frontend/src/views/Health.render.test.jsx b/frontend/src/views/Health.render.test.jsx index f6fb3d8..114902f 100644 --- a/frontend/src/views/Health.render.test.jsx +++ b/frontend/src/views/Health.render.test.jsx @@ -276,6 +276,41 @@ describe('the detail sheet', () => { expect(sheet()).toContain('9,000') }) + it('resets one measurement from its own sheet, and names what it is resetting', async () => { + const calls = [] + api.mockImplementation(async (path, opts) => { + calls.push([path, opts && opts.method]) + if (path.startsWith('/api/vitals/hours')) return HOURS + if (path.startsWith('/api/vitals?metric=')) return { ok: true, metric: 'step_count', days: 3 } + if (path.startsWith('/api/vitals?')) return withHours() + throw new Error('unexpected ' + path) + }) + const { confirmSheet } = await import('../sheets.jsx') + confirmSheet.mockClear() + await mountWithSheets() + openSteps() + await act(async () => {}) + + expect(sheet()).toContain('Reset this measurement') + click([...sheetEl().querySelectorAll('button')].find(b => b.textContent.includes('Reset this measurement'))) + await act(async () => {}) + + // The question names the metric. Its neighbour, "Delete the health data" in the setup sheet, + // takes every metric there is, and the two must not be mistakable for each other. + const opts = confirmSheet.mock.calls.at(-1)[0] + expect(opts.title).toContain('Steps') + expect(opts.danger).toBe(true) + expect(opts.message).toContain('Nothing else is touched') + + await act(async () => { opts.onConfirm() }) + await act(async () => {}) + // One metric, by name — never the profile's whole health file. + expect(calls).toContainEqual(['/api/vitals?metric=step_count', 'DELETE']) + expect(calls).not.toContainEqual(['/api/vitals', 'DELETE']) + // ...and the screen reloads what is left. + expect(calls.filter(([p]) => p === '/api/vitals?days=7').length).toBeGreaterThan(1) + }) + it('moves the hour list to a day that has hours when that day is tapped', async () => { const byDay = { '2026-09-03': HOURS,