Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

Health: read heart rate per set and weigh-ins back from Health Connect and Apple Health (#544, #127)

Duarte Santosf9c03474f38c
diff --git a/api/test/sync-hr.test.js b/api/test/sync-hr.test.js
index 14573ff5e..7cc179269 100644
--- a/api/test/sync-hr.test.js
+++ b/api/test/sync-hr.test.js
@@ -35,3 +35,31 @@ test('an older app editing another workout leaves these alone', () => {
const out = stampPut(clone(cur), next, { stamped: false, overRead: false, now: 20 });
assert.deepEqual(out.workouts.find(w => w.id === 'w1').entries[0].sets, hrSets);
});
+
+// v1.4.3: the heart rate read back from Health Connect / Apple Health adds the session's reading
+// (`w.hr` with its source) and marks weigh-ins read from there (`bodyweight[].src`). Both ride
+// along through every kind of writer, like the set fields above.
+const docHub = () => ({
+ _ts: 10, unit: 'kg',
+ workouts: [{ id: 'w1', d: '2026-10-15', _ts: 5, hr: { avg: 131, max: 162, src: 'hc', n: 601 }, entries: [{ id: '0025', sets: hrSets }] }],
+ bodyweight: [{ d: '2026-10-14', w: 81, t: 3 }, { d: '2026-10-15', w: 80.4, t: 4, src: 'hc' }],
+ routines: [],
+});
+
+test('the session heart rate and the imported weigh-in mark stay through every writer', () => {
+ const cur = docHub();
+ for (const stamped of [true, false]) {
+ const out = stampPut(clone(cur), clone(cur), { stamped, overRead: false, now: 20 });
+ assert.deepEqual(out.workouts[0].hr, cur.workouts[0].hr);
+ assert.deepEqual(out.bodyweight, cur.bodyweight);
+ }
+});
+
+test('an older app that drops the session heart rate on another edit gets it put back', () => {
+ const cur = docHub();
+ const next = clone(cur);
+ delete next.workouts[0].hr;
+ next.workouts[0].name = 'Push';
+ const out = stampPut(clone(cur), next, { stamped: false, overRead: false, now: 20 });
+ assert.deepEqual(out.workouts[0].hr, cur.workouts[0].hr);
+});
diff --git a/docs/MOBILE.md b/docs/MOBILE.md
index c283d4b0c..69ca30e0e 100644
--- a/docs/MOBILE.md
+++ b/docs/MOBILE.md
@@ -191,8 +191,9 @@ that.
Each weigh-in as a weight record, in kilograms. A workout without a real start and end is left
out rather than given made-up times. `src/lib/health-connect.js` works this out; its tests
pin it.
-- **Write-only.** The manifest declares `WRITE_EXERCISE` and `WRITE_WEIGHT` and nothing else, and
- openGym reads nothing back.
+- **Permissions.** The manifest declares `WRITE_EXERCISE`, `WRITE_WEIGHT` and, since v1.4.3,
+ `READ_HEART_RATE` and `READ_WEIGHT` (see "Reading back" below). Each is asked for only when its
+ switch is turned on. No background and no history permission.
- **No duplicates.** Every record carries openGym's own id as its `clientRecordId`
(`opengym-w-<workout id>`, `opengym-bw-<day>`), so writing it again replaces it. An edited workout
or weigh-in is written again; a deleted one is removed from Health Connect.
@@ -208,16 +209,56 @@ that.
- **Where it shows:** Android 14 and later have Health Connect built in. On Android 9–13 it is an
app of its own, and the card offers its store page until it is installed. Below Android 9 (the
app supports Android 6) Health Connect does not exist and the card is not shown.
-- **The library:** `androidx.health.connect:connect-client` 1.1.0-alpha12, called from Java
- (`HealthConnectPlugin.java`) through `runBlocking` on a worker thread, so the Android project stays
- Java-only. 1.1.0 stable needs compileSdk 36 and AGP 8.9.1, a toolchain bump left for its own
- change. The library asks for minSdk 26; `tools:overrideLibrary` keeps the app at 23 and the plugin
- checks the version before touching it.
+- **The library:** `androidx.health.connect:connect-client` 1.1.0 (stable, `variables.gradle`),
+ called from Java (`HealthConnectPlugin.java`) through `runBlocking` on a worker thread, so the
+ Android project stays Java-only. The library asks for minSdk 26; `tools:overrideLibrary` keeps the
+ app at 23 and the plugin checks the version before touching it.
+- **Privacy link.** Health Connect's "why does this app ask?" link opens the app through the two
+ activity-aliases in the manifest; `MainActivity` then opens https://opengym.ch/privacy, the same
+ policy the Play listing names (Play requires that).
Worth checking on a real device after changes here: turning it on shows Health Connect's own
permission screen; a finished workout appears in Health Connect within a few seconds; deleting it
in openGym removes it there; turning it off with "remove" leaves no openGym record behind.
+#### Reading back: heart rate and weigh-ins (v1.4.3, #544, #127)
+
+Two more switches in the same card (Android: Health Connect, iPhone: Apple Health), each off by
+default, each independent of writing and of the other:
+
+- **Heart rate from your watch.** For each workout finished in the last 24 hours, the heart-rate
+ samples between its start and end (+5 min) are read: `HC.readHeartRate({ from, to })` →
+ `{ samples: [[ms, bpm]] }`. `lib/heart-rate.js` `hrFromSamples` splits them over the sets: a set
+ ends at its tick (`at`) and lasts as long as its reps (3 s each, 15-120 s), seconds or minutes
+ take, never starting before the previous tick (the same estimate as the .fit export); its rest
+ runs to the next set. A set gets `hr` / `restHr` (`{ avg, max }`, the Apple Watch fields) only
+ when it has none yet, so the Apple Watch's live reading is never replaced. Sparse sources (median
+ gap over 20 s, a band that saves once a minute) and workouts without ticks get only the session's
+ reading, `w.hr = { avg, max, src: 'hc' | 'ah', n }`, replaced later only by a fuller read from
+ the same hub (Garmin and Fitbit sync late) and never when `src` is `'watch'`. Re-read at most
+ every 10 minutes (2 after coming back to the foreground) until the 24 hours are over.
+- **Weigh-ins from other apps.** `HC.readWeights({ since })` → `{ records: [{ t, kg, id, origin,
+ clientId }] }`: 30 days back the first time (what Health Connect gives without the history
+ permission), afterwards from the newest seen minus two days. `lib/health-read.js` `mergeWeighIns`
+ takes the latest of each day, skips openGym's own records (`clientRecordId` `opengym-*`, origin
+ `ch.duartesantos.opengym*`), keeps a day that has a weigh-in typed into openGym, does not bring
+ back one deleted in openGym after it was measured, and converts to lb for an lb profile. Imported
+ entries carry `src` and are never written back (`healthRecords` leaves them out), and in a sync
+ merge a typed weigh-in beats an imported one of the same day whichever is newer
+ (`mergeBodyweight`); typing over an imported one makes it a typed one.
+- **Foreground only.** Reads run at launch, on resume and after saves, never in the background.
+ No `READ_HEALTH_DATA_IN_BACKGROUND`, no `READ_HEALTH_DATA_HISTORY`; old workouts are not filled in.
+- **Device-local state** in `opengym-health.json`: `readHr`, `readWeight`, `wCursor`, `seen` (what
+ was imported per day), `hrTried` (when each recent workout was last read), `readError`.
+- **iPhone:** `AppleHealthPlugin.swift` `readHeartRate` / `readWeights` through `HKSampleQuery`;
+ the plain-value conversion is `WatchCore/Sources/WatchCore/HealthReadCore.swift` (compiled into
+ the app, tested by `swift test`). Apple Health never says whether reading was allowed, so a
+ refusal reads nothing. The usage string (`NSHealthShareUsageDescription`) says what is read.
+- **Synced fields:** `set.hr`, `set.restHr`, `w.hr`, `bodyweight[].src` are plain optional fields;
+ the server keeps them through every writer (`api/test/sync-hr.test.js`).
+- **Emulator check:** Google's Health Connect Toolbox can insert heart-rate and weight records on an
+ API 34+ emulator; see the v1.4.3 notes for the run.
+
### Animation quality and the animation packs (store apps)
Settings → Workout → **Animation quality**, in the store apps only (the web and a self-hosted
diff --git a/frontend/android/app/src/main/AndroidManifest.xml b/frontend/android/app/src/main/AndroidManifest.xml
index a63377cb0..a6feae311 100644
--- a/frontend/android/app/src/main/AndroidManifest.xml
+++ b/frontend/android/app/src/main/AndroidManifest.xml
@@ -120,10 +120,14 @@
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<!-- Gym check-in: scanning a membership QR/barcode with the camera. -->
<uses-permission android:name="android.permission.CAMERA" />
- <!-- Health Connect (#200): write-only, asked for only when the user turns it on in Settings.
- openGym writes finished workouts and weigh-ins and reads nothing back. -->
+ <!-- Health Connect (#200): each asked for only when the user turns its switch on in Settings.
+ openGym writes finished workouts and weigh-ins, and since v1.4.3 can read back the heart
+ rate during a workout and weigh-ins from other apps (#544). Foreground only: no
+ background or history read permission. -->
<uses-permission android:name="android.permission.health.WRITE_EXERCISE" />
<uses-permission android:name="android.permission.health.WRITE_WEIGHT" />
+ <uses-permission android:name="android.permission.health.READ_HEART_RATE" />
+ <uses-permission android:name="android.permission.health.READ_WEIGHT" />
<!-- Whether the Health Connect app is there, on Android 13 and lower. -->
<queries>
diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/HealthConnectPlugin.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/HealthConnectPlugin.java
index 8c9f1736f..94b5091dd 100644
--- a/frontend/android/app/src/main/java/ch/duartesantos/opengym/HealthConnectPlugin.java
+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/HealthConnectPlugin.java
@@ -8,9 +8,13 @@ import androidx.activity.result.contract.ActivityResultContract;
import androidx.health.connect.client.HealthConnectClient;
import androidx.health.connect.client.PermissionController;
import androidx.health.connect.client.records.ExerciseSessionRecord;
+import androidx.health.connect.client.records.HeartRateRecord;
import androidx.health.connect.client.records.Record;
import androidx.health.connect.client.records.WeightRecord;
import androidx.health.connect.client.records.metadata.Metadata;
+import androidx.health.connect.client.request.ReadRecordsRequest;
+import androidx.health.connect.client.response.ReadRecordsResponse;
+import androidx.health.connect.client.time.TimeRangeFilter;
import androidx.health.connect.client.units.Mass;
import com.getcapacitor.JSArray;
import com.getcapacitor.JSObject;
@@ -59,6 +63,13 @@ import org.json.JSONObject;
* await HC.write({ sessions: [...], weights: [...] });
* await HC.remove({ sessions: [ids], weights: [ids] });
* await HC.openSettings(); // Health Connect's data screen, or its store page
+ *
+ * Reading back (v1.4.3), each only after the user turned it on and granted that one permission:
+ * await HC.requestPermissions({ read: ['heartRate'], write: [] }); // { granted, read: { heartRate, weight } }
+ * await HC.readHeartRate({ from, to }); // { samples: [[ms, bpm]], origins: [package] }
+ * await HC.readWeights({ since }); // { records: [{ t, kg, id, origin, clientId }] }
+ * Foreground only: no READ_HEALTH_DATA_IN_BACKGROUND, no READ_HEALTH_DATA_HISTORY (Health Connect
+ * then gives 30 days back from the first grant, plenty for the workout just done).
*/
@CapacitorPlugin(name = "HealthConnect")
public class HealthConnectPlugin extends Plugin {
@@ -67,6 +78,11 @@ public class HealthConnectPlugin extends Plugin {
// The literal permission names, as declared in AndroidManifest.xml.
private static final String WRITE_EXERCISE = "android.permission.health.WRITE_EXERCISE";
private static final String WRITE_WEIGHT = "android.permission.health.WRITE_WEIGHT";
+ private static final String READ_HEART_RATE = "android.permission.health.READ_HEART_RATE";
+ private static final String READ_WEIGHT = "android.permission.health.READ_WEIGHT";
+ // Records per page when reading, and pages at most: a few hours of heart rate fit easily.
+ private static final int PAGE = 1000;
+ private static final int MAX_PAGES = 50;
// Health Connect takes at most this many records in one insert.
private static final int CHUNK = 500;
@@ -118,7 +134,9 @@ public class HealthConnectPlugin extends Plugin {
try {
JSObject r = new JSObject();
r.put("status", status);
- r.put("granted", granted().containsAll(permissions()));
+ Set<String> got = granted();
+ r.put("granted", got.containsAll(permissions()));
+ r.put("read", readState(got));
call.resolve(r);
} catch (Exception e) {
call.reject(e.getMessage(), "failed");
@@ -132,8 +150,15 @@ public class HealthConnectPlugin extends Plugin {
call.reject("Health Connect is not available", "unavailable");
return;
}
+ Set<String> asked;
+ try {
+ asked = asked(call);
+ } catch (JSONException e) {
+ call.reject(e.getMessage(), "failed");
+ return;
+ }
ActivityResultContract<Set<String>, Set<String>> contract = PermissionController.createRequestPermissionResultContract(PROVIDER);
- Intent intent = contract.createIntent(getContext(), permissions());
+ Intent intent = contract.createIntent(getContext(), asked);
startActivityForResult(call, intent, "permissionsResult");
}
@@ -146,8 +171,11 @@ public class HealthConnectPlugin extends Plugin {
// user may also have granted one of the two and not the other.
worker.execute(() -> {
try {
+ Set<String> now = new HashSet<>(granted());
+ if (got != null) now.addAll(got);
JSObject r = new JSObject();
- r.put("granted", (got != null && got.containsAll(permissions())) || granted().containsAll(permissions()));
+ r.put("granted", now.containsAll(permissions()));
+ r.put("read", readState(now));
call.resolve(r);
} catch (Exception e) {
call.reject(e.getMessage(), "failed");
@@ -203,6 +231,119 @@ public class HealthConnectPlugin extends Plugin {
});
}
+ @PluginMethod
+ public void readHeartRate(PluginCall call) {
+ if (!"available".equals(sdkStatus())) {
+ call.reject("Health Connect is not available", "unavailable");
+ return;
+ }
+ Long from = millis(call, "from"), to = millis(call, "to");
+ if (from == null || to == null || to <= from) {
+ call.reject("from and to are needed", "failed");
+ return;
+ }
+ worker.execute(() -> {
+ try {
+ List<HeartRateRecord> recs = read(HeartRateRecord.class,
+ TimeRangeFilter.between(Instant.ofEpochMilli(from), Instant.ofEpochMilli(to)));
+ JSArray samples = new JSArray();
+ for (long[] s : HealthRead.samples(recs, from, to)) samples.put(new JSArray().put(s[0]).put(s[1]));
+ Set<String> origins = new HashSet<>();
+ for (HeartRateRecord r : recs) origins.add(r.getMetadata().getDataOrigin().getPackageName());
+ JSObject out = new JSObject();
+ out.put("samples", samples);
+ out.put("origins", new JSArray(origins));
+ call.resolve(out);
+ } catch (SecurityException e) {
+ call.reject(e.getMessage(), "permission");
+ } catch (Exception e) {
+ call.reject(e.getMessage(), "failed");
+ }
+ });
+ }
+
+ @PluginMethod
+ public void readWeights(PluginCall call) {
+ if (!"available".equals(sdkStatus())) {
+ call.reject("Health Connect is not available", "unavailable");
+ return;
+ }
+ Long since = millis(call, "since");
+ if (since == null) {
+ call.reject("since is needed", "failed");
+ return;
+ }
+ worker.execute(() -> {
+ try {
+ List<WeightRecord> recs = read(WeightRecord.class, TimeRangeFilter.after(Instant.ofEpochMilli(since)));
+ JSArray records = new JSArray();
+ for (HealthRead.Weight w : HealthRead.weights(recs)) {
+ JSObject o = new JSObject();
+ o.put("t", w.t);
+ o.put("kg", w.kg);
+ o.put("id", w.id);
+ o.put("origin", w.origin);
+ o.put("clientId", w.clientId);
+ records.put(o);
+ }
+ JSObject out = new JSObject();
+ out.put("records", records);
+ call.resolve(out);
+ } catch (SecurityException e) {
+ call.reject(e.getMessage(), "permission");
+ } catch (Exception e) {
+ call.reject(e.getMessage(), "failed");
+ }
+ });
+ }
+
+ // Every page of one record type in the window, oldest first.
+ @SuppressWarnings("unchecked")
+ private <T extends Record> List<T> read(Class<T> type, TimeRangeFilter range) throws InterruptedException {
+ List<T> out = new ArrayList<>();
+ String token = null;
+ for (int page = 0; page < MAX_PAGES; page++) {
+ ReadRecordsRequest<T> req = new ReadRecordsRequest<>(JvmClassMappingKt.getKotlinClass(type), range,
+ Collections.emptySet(), true, PAGE, token);
+ ReadRecordsResponse<T> res = (ReadRecordsResponse<T>) BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE,
+ (scope, cont) -> client().readRecords(req, cont));
+ out.addAll(res.getRecords());
+ token = res.getPageToken();
+ if (token == null || token.isEmpty()) break;
+ }
+ return out;
+ }
+
+ // What was asked for: { read: ['heartRate', 'weight'], write: ['exercise', 'weight'] }, each
+ // optional. Without either, the two write permissions, as before v1.4.3.
+ private static Set<String> asked(PluginCall call) throws JSONException {
+ JSArray read = call.getArray("read", null), write = call.getArray("write", null);
+ if (read == null && write == null) return permissions();
+ Set<String> out = new HashSet<>();
+ if (read != null) for (int i = 0; i < read.length(); i++) {
+ String p = HealthRead.readPermission(read.getString(i));
+ if (p != null) out.add(p);
+ }
+ if (write != null) for (int i = 0; i < write.length(); i++) {
+ String p = HealthRead.writePermission(write.getString(i));
+ if (p != null) out.add(p);
+ }
+ return out;
+ }
+
+ // A time from JS: a number that may arrive as an Integer, Long or Double (getLong takes only Long).
+ private static Long millis(PluginCall call, String name) {
+ Object v = call.getData().opt(name);
+ return v instanceof Number ? ((Number) v).longValue() : null;
+ }
+
+ private static JSObject readState(Set<String> granted) {
+ JSObject r = new JSObject();
+ r.put("heartRate", granted.contains(READ_HEART_RATE));
+ r.put("weight", granted.contains(READ_WEIGHT));
+ return r;
+ }
+
// Health Connect's own screen for the data apps wrote, where the user can look at and delete
// what openGym wrote. Without Health Connect (Android 13 and lower), its store page instead.
@PluginMethod
diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/HealthRead.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/HealthRead.java
new file mode 100644
index 000000000..b2fa83696
--- /dev/null
+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/HealthRead.java
@@ -0,0 +1,80 @@
+package ch.duartesantos.opengym;
+
+import androidx.health.connect.client.records.HeartRateRecord;
+import androidx.health.connect.client.records.WeightRecord;
+import androidx.health.connect.client.records.metadata.Metadata;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * What HealthConnectPlugin hands to JS when it reads (v1.4.3): plain values, no Android classes,
+ * so it is tested on the JVM (HealthReadTest). Heart rate as [ms, bpm] pairs inside the window
+ * asked for; weigh-ins as { t, kg, id, origin, clientId }. Which of them openGym takes, and how,
+ * is decided in JS (lib/health-read.js), which also skips openGym's own records.
+ */
+final class HealthRead {
+ private HealthRead() {}
+
+ // Beyond this no reading is plausible; lib/heart-rate.js applies the same bounds again.
+ static final long BPM_MIN = 25;
+ static final long BPM_MAX = 250;
+ // A workout of a few hours at one sample a second is well under this.
+ static final int MAX_SAMPLES = 50000;
+
+ /** The samples of these records that lie in [from, to], oldest first. */
+ static List<long[]> samples(List<HeartRateRecord> records, long from, long to) {
+ List<long[]> out = new ArrayList<>();
+ for (HeartRateRecord r : records) {
+ for (HeartRateRecord.Sample s : r.getSamples()) {
+ long t = s.getTime().toEpochMilli();
+ long bpm = s.getBeatsPerMinute();
+ if (t < from || t > to || bpm < BPM_MIN || bpm > BPM_MAX) continue;
+ out.add(new long[] { t, bpm });
+ if (out.size() >= MAX_SAMPLES) break;
+ }
+ if (out.size() >= MAX_SAMPLES) break;
+ }
+ out.sort((a, b) -> Long.compare(a[0], b[0]));
+ return out;
+ }
+
+ /** One weigh-in as JS gets it. */
+ static final class Weight {
+ final long t;
+ final double kg;
+ final String id, origin, clientId;
+
+ Weight(long t, double kg, String id, String origin, String clientId) {
+ this.t = t; this.kg = kg; this.id = id; this.origin = origin; this.clientId = clientId;
+ }
+ }
+
+ static List<Weight> weights(List<WeightRecord> records) {
+ List<Weight> out = new ArrayList<>();
+ for (WeightRecord r : records) {
+ Metadata m = r.getMetadata();
+ double kg = r.getWeight().getKilograms();
+ if (!(kg > 0)) continue;
+ out.add(new Weight(r.getTime().toEpochMilli(), kg, m.getId(),
+ m.getDataOrigin().getPackageName(), m.getClientRecordId()));
+ }
+ return out;
+ }
+
+ /** The JS names of the read permissions, as the manifest declares them. */
+ static String readPermission(String name) {
+ switch (name) {
+ case "heartRate": return "android.permission.health.READ_HEART_RATE";
+ case "weight": return "android.permission.health.READ_WEIGHT";
+ default: return null;
+ }
+ }
+
+ static String writePermission(String name) {
+ switch (name) {
+ case "exercise": return "android.permission.health.WRITE_EXERCISE";
+ case "weight": return "android.permission.health.WRITE_WEIGHT";
+ default: return null;
+ }
+ }
+}
diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/MainActivity.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/MainActivity.java
index c15a57d9c..91fdafdc4 100644
--- a/frontend/android/app/src/main/java/ch/duartesantos/opengym/MainActivity.java
+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/MainActivity.java
@@ -1,5 +1,7 @@
package ch.duartesantos.opengym;
+import android.content.Intent;
+import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
@@ -37,6 +39,29 @@ public class MainActivity extends BridgeActivity {
passSystemBarsToPage();
}
+ @Override
+ protected void onNewIntent(Intent intent) {
+ super.onNewIntent(intent);
+ showHealthPrivacy(intent);
+ }
+
+ // Health Connect's "why does this app ask?" link (the two activity-aliases in the manifest)
+ // must show the privacy policy, the same one the Play listing names: opened in the browser.
+ static final String PRIVACY_URL = "https://opengym.ch/privacy";
+ static boolean isHealthRationale(String action) {
+ return "androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE".equals(action)
+ || "android.intent.action.VIEW_PERMISSION_USAGE".equals(action);
+ }
+
+ private void showHealthPrivacy(Intent intent) {
+ if (intent == null || !isHealthRationale(intent.getAction())) return;
+ try {
+ startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(PRIVACY_URL)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
+ } catch (Exception e) {
+ // No browser: the app itself opens, as before.
+ }
+ }
+
/** For FlavorPlugins: registerPlugin is protected in BridgeActivity. */
void registerFlavorPlugin(Class<? extends com.getcapacitor.Plugin> plugin) {
registerPlugin(plugin);
diff --git a/frontend/android/app/src/test/java/ch/duartesantos/opengym/HealthReadTest.java b/frontend/android/app/src/test/java/ch/duartesantos/opengym/HealthReadTest.java
new file mode 100644
index 000000000..19ec62aa5
--- /dev/null
+++ b/frontend/android/app/src/test/java/ch/duartesantos/opengym/HealthReadTest.java
@@ -0,0 +1,73 @@
+package ch.duartesantos.opengym;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+import androidx.health.connect.client.records.HeartRateRecord;
+import androidx.health.connect.client.records.WeightRecord;
+import androidx.health.connect.client.records.metadata.DataOrigin;
+import androidx.health.connect.client.records.metadata.Metadata;
+import androidx.health.connect.client.units.Mass;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import org.junit.Test;
+
+// v1.4.3: what HealthConnectPlugin hands to JS when it reads heart rate and weigh-ins back.
+public class HealthReadTest {
+
+ private static HeartRateRecord hr(long start, long end, long[][] samples) {
+ HeartRateRecord.Sample[] s = new HeartRateRecord.Sample[samples.length];
+ for (int i = 0; i < samples.length; i++) s[i] = new HeartRateRecord.Sample(Instant.ofEpochMilli(samples[i][0]), samples[i][1]);
+ return new HeartRateRecord(Instant.ofEpochMilli(start), ZoneOffset.UTC, Instant.ofEpochMilli(end), ZoneOffset.UTC,
+ Arrays.asList(s), Metadata.unknownRecordingMethod());
+ }
+
+ @Test
+ public void samplesInsideTheWindowOldestFirst() {
+ HeartRateRecord a = hr(10_000, 20_000, new long[][] { { 10_000, 120 }, { 15_000, 130 }, { 20_000, 140 } });
+ HeartRateRecord b = hr(0, 9_000, new long[][] { { 0, 90 }, { 9_000, 100 } });
+ List<long[]> out = HealthRead.samples(Arrays.asList(a, b), 5_000, 15_000);
+ assertEquals(2, out.size());
+ assertArrayEquals(new long[] { 9_000, 100 }, out.get(0));
+ assertArrayEquals(new long[] { 15_000, 130 }, out.get(1));
+ }
+
+ @Test
+ public void implausibleBeatsAreLeftOut() {
+ HeartRateRecord a = hr(0, 3_000, new long[][] { { 0, 10 }, { 1_000, 300 }, { 2_000, 25 }, { 3_000, 250 } });
+ List<long[]> out = HealthRead.samples(Collections.singletonList(a), 0, 3_000);
+ assertEquals(2, out.size());
+ assertEquals(25, out.get(0)[1]);
+ assertEquals(250, out.get(1)[1]);
+ }
+
+ @Test
+ public void weighInsCarryTheirOriginAndClientId() {
+ Metadata scale = new Metadata(Metadata.RECORDING_METHOD_AUTOMATICALLY_RECORDED, "rec-1", new DataOrigin("com.withings.wiscale2"),
+ Instant.ofEpochMilli(5), null, 0, null);
+ Metadata ours = new Metadata(Metadata.RECORDING_METHOD_MANUAL_ENTRY, "rec-2", new DataOrigin("ch.duartesantos.opengym"),
+ Instant.ofEpochMilli(5), "opengym-bw-2026-10-15", 1, null);
+ List<HealthRead.Weight> out = HealthRead.weights(Arrays.asList(
+ new WeightRecord(Instant.ofEpochMilli(1_000), ZoneOffset.UTC, Mass.kilograms(81.25), scale),
+ new WeightRecord(Instant.ofEpochMilli(2_000), ZoneOffset.UTC, Mass.pounds(176), ours)));
+ assertEquals(2, out.size());
+ assertEquals(1_000, out.get(0).t);
+ assertEquals(81.25, out.get(0).kg, 1e-9);
+ assertEquals("com.withings.wiscale2", out.get(0).origin);
+ assertNull(out.get(0).clientId);
+ assertEquals("opengym-bw-2026-10-15", out.get(1).clientId);
+ assertEquals(79.83, out.get(1).kg, 0.01);
+ }
+
+ @Test
+ public void permissionNamesMatchTheManifest() {
+ assertEquals("android.permission.health.READ_HEART_RATE", HealthRead.readPermission("heartRate"));
+ assertEquals("android.permission.health.READ_WEIGHT", HealthRead.readPermission("weight"));
+ assertEquals("android.permission.health.WRITE_EXERCISE", HealthRead.writePermission("exercise"));
+ assertNull(HealthRead.readPermission("steps"));
+ }
+}
diff --git a/frontend/ios/App/App.xcodeproj/project.pbxproj b/frontend/ios/App/App.xcodeproj/project.pbxproj
index d8a0e1469..5424fe67f 100644
--- a/frontend/ios/App/App.xcodeproj/project.pbxproj
+++ b/frontend/ios/App/App.xcodeproj/project.pbxproj
@@ -32,6 +32,7 @@
AA0500000000000000000012 /* WidgetPreview.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0500000000000000000011 /* WidgetPreview.swift */; };
AA0700000000000000000002 /* WatchBridgePlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0700000000000000000001 /* WatchBridgePlugin.swift */; };
AA0600000000000000000002 /* ClipCodec.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0600000000000000000001 /* ClipCodec.swift */; };
+ AA0600000000000000000004 /* HealthReadCore.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0600000000000000000003 /* HealthReadCore.swift */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
@@ -65,6 +66,7 @@
AA0500000000000000000011 /* WidgetPreview.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WidgetPreview.swift; sourceTree = "<group>"; };
AA0700000000000000000001 /* WatchBridgePlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchBridgePlugin.swift; sourceTree = "<group>"; };
AA0600000000000000000001 /* ClipCodec.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = ClipCodec.swift; path = ../WatchCore/Sources/WatchCore/ClipCodec.swift; sourceTree = "<group>"; };
+ AA0600000000000000000003 /* HealthReadCore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = HealthReadCore.swift; path = ../WatchCore/Sources/WatchCore/HealthReadCore.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -127,6 +129,7 @@
AA0500000000000000000011 /* WidgetPreview.swift */,
AA0700000000000000000001 /* WatchBridgePlugin.swift */,
AA0600000000000000000001 /* ClipCodec.swift */,
+ AA0600000000000000000003 /* HealthReadCore.swift */,
AA0200000000000000000007 /* PrivacyInfo.xcprivacy */,
504EC30B1FED79650016851F /* Main.storyboard */,
504EC30E1FED79650016851F /* Assets.xcassets */,
@@ -280,6 +283,7 @@
AA0500000000000000000012 /* WidgetPreview.swift in Sources */,
AA0700000000000000000002 /* WatchBridgePlugin.swift in Sources */,
AA0600000000000000000002 /* ClipCodec.swift in Sources */,
+ AA0600000000000000000004 /* HealthReadCore.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
diff --git a/frontend/ios/App/App/AppleHealthPlugin.swift b/frontend/ios/App/App/AppleHealthPlugin.swift
index 0fb48274c..c7a7744f4 100644
--- a/frontend/ios/App/App/AppleHealthPlugin.swift
+++ b/frontend/ios/App/App/AppleHealthPlugin.swift
@@ -15,6 +15,12 @@ import UIKit
* watch as its source) is left as it is: it has the heart rate in it, and a second copy would count
* the session twice. Removing takes that copy out too, and says which ids Apple Health still holds
* afterwards, so lib/health-sync.js keeps them and tries again rather than forgetting them.
+ *
+ * Reading back (v1.4.3), each behind its own switch in Settings: the heart rate during a finished
+ * workout (readHeartRate, for any watch that saves to Apple Health, Garmin and Polar included) and
+ * weigh-ins other apps saved (readWeights). Foreground only, through HKSampleQuery; what to take is
+ * decided in JS (lib/health-read.js). Apple Health never says whether reading was allowed, so a
+ * refusal simply reads nothing.
*/
@objc(AppleHealthPlugin)
public class AppleHealthPlugin: CAPPlugin, CAPBridgedPlugin {
@@ -27,6 +33,8 @@ public class AppleHealthPlugin: CAPPlugin, CAPBridgedPlugin {
CAPPluginMethod(name: "remove", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "openSettings", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "setEnabled", returnType: CAPPluginReturnPromise),
+ CAPPluginMethod(name: "readHeartRate", returnType: CAPPluginReturnPromise),
+ CAPPluginMethod(name: "readWeights", returnType: CAPPluginReturnPromise),
]
static let enabledKey = "healthEnabled"
@@ -53,6 +61,15 @@ public class AppleHealthPlugin: CAPPlugin, CAPBridgedPlugin {
@objc override public func requestPermissions(_ call: CAPPluginCall) {
guard HKHealthStore.isHealthDataAvailable() else { call.resolve(["granted": false]); return }
+ // { read: ['heartRate' | 'weight'], write: [...] } asks for just those reads (the switches
+ // added in v1.4.3); without them, everything, as before.
+ if let read = call.getArray("read") as? [String] {
+ var types: Set<HKObjectType> = []
+ if read.contains("heartRate"), let hr = HKObjectType.quantityType(forIdentifier: .heartRate) { types.insert(hr) }
+ if read.contains("weight") { types.insert(bodyMass) }
+ store.requestAuthorization(toShare: [], read: types) { _, _ in call.resolve(["granted": self.granted]) }
+ return
+ }
store.requestAuthorization(toShare: shareTypes, read: readTypes) { _, _ in
call.resolve(["granted": self.granted])
}
@@ -103,6 +120,47 @@ public class AppleHealthPlugin: CAPPlugin, CAPBridgedPlugin {
}
}
+ @objc func readHeartRate(_ call: CAPPluginCall) {
+ guard let from = call.getDouble("from"), let to = call.getDouble("to"), to > from,
+ let type = HKObjectType.quantityType(forIdentifier: .heartRate) else {
+ call.reject("from and to are needed", "failed")
+ return
+ }
+ let predicate = HKQuery.predicateForSamples(withStart: Date(timeIntervalSince1970: from / 1000), end: Date(timeIntervalSince1970: to / 1000))
+ let perMinute = HKUnit.count().unitDivided(by: .minute())
+ query(type, predicate) { found in
+ let all = found.compactMap { $0 as? HKQuantitySample }.map {
+ HealthReadCore.HeartSample(ms: $0.startDate.timeIntervalSince1970 * 1000, bpm: $0.quantity.doubleValue(for: perMinute))
+ }
+ let origins = Array(Set(found.map { $0.sourceRevision.source.bundleIdentifier }))
+ call.resolve(["samples": HealthReadCore.samples(all, from: from, to: to), "origins": origins])
+ } failed: { self.fail(call, $0) }
+ }
+
+ @objc func readWeights(_ call: CAPPluginCall) {
+ guard let since = call.getDouble("since") else { call.reject("since is needed", "failed"); return }
+ let predicate = HKQuery.predicateForSamples(withStart: Date(timeIntervalSince1970: since / 1000), end: nil)
+ query(bodyMass, predicate) { found in
+ let all = found.compactMap { $0 as? HKQuantitySample }.map {
+ HealthReadCore.WeighIn(ms: $0.startDate.timeIntervalSince1970 * 1000, kg: $0.quantity.doubleValue(for: .gramUnit(with: .kilo)),
+ id: $0.uuid.uuidString, source: $0.sourceRevision.source.bundleIdentifier,
+ syncId: $0.metadata?[HKMetadataKeySyncIdentifier] as? String)
+ }
+ call.resolve(["records": HealthReadCore.weights(all)])
+ } failed: { self.fail(call, $0) }
+ }
+
+ /// Every sample of `type` matching `predicate`, oldest first.
+ private func query(_ type: HKSampleType, _ predicate: NSPredicate, done: @escaping ([HKSample]) -> Void, failed: @escaping (Error) -> Void) {
+ guard HKHealthStore.isHealthDataAvailable() else { failed(HKError(.errorHealthDataUnavailable)); return }
+ let sort = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: true)
+ let q = HKSampleQuery(sampleType: type, predicate: predicate, limit: HealthReadCore.maxSamples, sortDescriptors: [sort]) { _, found, error in
+ // Reading not allowed answers with no samples rather than an error; a real error is passed on.
+ if let error = error, (error as? HKError)?.code != .errorAuthorizationDenied { failed(error) } else { done(found ?? []) }
+ }
+ store.execute(q)
+ }
+
private func fail(_ call: CAPPluginCall, _ error: Error) {
if let hk = error as? HKError, hk.code == .errorAuthorizationDenied || hk.code == .errorAuthorizationNotDetermined {
call.reject("Apple Health permission not granted", "permission")
diff --git a/frontend/ios/App/App/Info.plist b/frontend/ios/App/App/Info.plist
index 31b868638..734bcfbf1 100644
--- a/frontend/ios/App/App/Info.plist
+++ b/frontend/ios/App/App/Info.plist
@@ -95,7 +95,7 @@
<key>NSSupportsLiveActivities</key>
<true/>
<key>NSHealthShareUsageDescription</key>
- <string>Used to show your heart rate on your Apple Watch while you train, next to each set.</string>
+ <string>Used to show your heart rate on your Apple Watch while you train, and, when you switch it on, to add the heart rate your watch saved and weigh-ins from other apps to your log.</string>
<key>NSHealthUpdateUsageDescription</key>
<string>Used to save your finished workouts and weigh-ins to Apple Health, when you switch it on.</string>
<key>NSFaceIDUsageDescription</key>
diff --git a/frontend/ios/App/WatchCore/Sources/WatchCore/HealthReadCore.swift b/frontend/ios/App/WatchCore/Sources/WatchCore/HealthReadCore.swift
new file mode 100644
index 000000000..833e74c15
--- /dev/null
+++ b/frontend/ios/App/WatchCore/Sources/WatchCore/HealthReadCore.swift
@@ -0,0 +1,57 @@
+import Foundation
+
+/// What AppleHealthPlugin hands to JS when it reads (openGym v1.4.3): plain values, no HealthKit,
+/// so `swift test` covers it on the Mac (HealthReadCoreTests). Compiled straight into the iPhone
+/// app next to the plugin (like ClipCodec). Heart rate as [ms, bpm] pairs inside the window asked
+/// for; weigh-ins as { t, kg, id, origin, clientId }. Which of them openGym takes, and how, is
+/// decided in JS (lib/health-read.js).
+public enum HealthReadCore {
+ /// Beyond this no reading is plausible; lib/heart-rate.js applies the same bounds again.
+ public static let bpmRange: ClosedRange<Double> = 25...250
+ /// A workout of a few hours at one sample a second is well under this.
+ public static let maxSamples = 50_000
+ /// The bundle ids that are openGym: the iPhone app, its Apple Watch app and widgets.
+ public static let ownPrefix = "ch.duartesantos.opengym"
+
+ public struct HeartSample: Equatable {
+ public let ms: Double
+ public let bpm: Double
+ public init(ms: Double, bpm: Double) { self.ms = ms; self.bpm = bpm }
+ }
+
+ public struct WeighIn: Equatable {
+ public let ms: Double
+ public let kg: Double
+ public let id: String
+ public let source: String
+ public let syncId: String?
+ public init(ms: Double, kg: Double, id: String, source: String, syncId: String?) {
+ self.ms = ms; self.kg = kg; self.id = id; self.source = source; self.syncId = syncId
+ }
+ }
+
+ /// The samples in [from, to] with a plausible rate, oldest first, as [[ms, bpm]].
+ public static func samples(_ all: [HeartSample], from: Double, to: Double) -> [[Double]] {
+ let kept = all.filter { $0.ms >= from && $0.ms <= to && bpmRange.contains($0.bpm) }
+ .sorted { $0.ms < $1.ms }
+ .prefix(maxSamples)
+ return kept.map { [$0.ms.rounded(), $0.bpm.rounded()] }
+ }
+
+ /// Whether openGym wrote this one itself (by its sync identifier or its source).
+ public static func isOwn(source: String, syncId: String?) -> Bool {
+ if let id = syncId, id.hasPrefix("opengym-") { return true }
+ return source == ownPrefix || source.hasPrefix(ownPrefix + ".")
+ }
+
+ /// Weigh-ins as JS takes them, openGym's own left out.
+ public static func weights(_ all: [WeighIn]) -> [[String: Any]] {
+ all.filter { $0.kg > 0 && !isOwn(source: $0.source, syncId: $0.syncId) }
+ .sorted { $0.ms < $1.ms }
+ .map { w in
+ var o: [String: Any] = ["t": w.ms.rounded(), "kg": w.kg, "id": w.id, "origin": w.source]
+ if let s = w.syncId { o["clientId"] = s }
+ return o
+ }
+ }
+}
diff --git a/frontend/ios/App/WatchCore/Tests/WatchCoreTests/HealthReadCoreTests.swift b/frontend/ios/App/WatchCore/Tests/WatchCoreTests/HealthReadCoreTests.swift
new file mode 100644
index 000000000..163e56897
--- /dev/null
+++ b/frontend/ios/App/WatchCore/Tests/WatchCoreTests/HealthReadCoreTests.swift
@@ -0,0 +1,36 @@
+import XCTest
+@testable import WatchCore
+
+/// openGym v1.4.3: what the iPhone app hands to JS when it reads heart rate and weigh-ins back
+/// from Apple Health.
+final class HealthReadCoreTests: XCTestCase {
+ func testSamplesInsideTheWindowOldestFirst() {
+ let s = [HealthReadCore.HeartSample(ms: 15_000, bpm: 130), .init(ms: 9_000, bpm: 100), .init(ms: 20_000, bpm: 140), .init(ms: 1_000, bpm: 90)]
+ XCTAssertEqual(HealthReadCore.samples(s, from: 5_000, to: 15_000), [[9_000, 100], [15_000, 130]])
+ }
+
+ func testImplausibleRatesAreLeftOut() {
+ let s = [HealthReadCore.HeartSample(ms: 0, bpm: 10), .init(ms: 1, bpm: 300), .init(ms: 2, bpm: 25), .init(ms: 3, bpm: 250.4)]
+ XCTAssertEqual(HealthReadCore.samples(s, from: 0, to: 10).map { $0[1] }, [25, 250])
+ }
+
+ func testOwnRecordsAreRecognised() {
+ XCTAssertTrue(HealthReadCore.isOwn(source: "com.withings.wiscale2", syncId: "opengym-bw-2026-10-15"))
+ XCTAssertTrue(HealthReadCore.isOwn(source: "ch.duartesantos.opengym", syncId: nil))
+ XCTAssertTrue(HealthReadCore.isOwn(source: "ch.duartesantos.opengym.watchkitapp", syncId: nil))
+ XCTAssertFalse(HealthReadCore.isOwn(source: "ch.duartesantos.opengymx", syncId: nil))
+ XCTAssertFalse(HealthReadCore.isOwn(source: "com.garmin.connect.mobile", syncId: "abc"))
+ }
+
+ func testWeighInsLeaveOutOpenGymsOwn() {
+ let out = HealthReadCore.weights([
+ .init(ms: 2_000, kg: 80, id: "b", source: "ch.duartesantos.opengym", syncId: "opengym-bw-2026-10-15"),
+ .init(ms: 1_000, kg: 81.25, id: "a", source: "com.withings.wiscale2", syncId: nil),
+ .init(ms: 3_000, kg: 0, id: "c", source: "com.example", syncId: nil),
+ ])
+ XCTAssertEqual(out.count, 1)
+ XCTAssertEqual(out[0]["kg"] as? Double, 81.25)
+ XCTAssertEqual(out[0]["origin"] as? String, "com.withings.wiscale2")
+ XCTAssertNil(out[0]["clientId"])
+ }
+}
diff --git a/frontend/src/lib/bodyweight.js b/frontend/src/lib/bodyweight.js
index 7e7683b11..2f50c9473 100644
--- a/frontend/src/lib/bodyweight.js
+++ b/frontend/src/lib/bodyweight.js
@@ -48,7 +48,7 @@ export function logWeighIn(s, w, at = Date.now()) {
if (!Array.isArray(s.bodyweight)) s.bodyweight = []
const d = isoOf(new Date(at))
const ex = s.bodyweight.find(b => b.d === d)
- if (ex) { ex.w = n; ex.t = at } else s.bodyweight.push({ d, w: n, t: at })
+ if (ex) { ex.w = n; ex.t = at; delete ex.src } else s.bodyweight.push({ d, w: n, t: at })
s.bodyweight.sort((a, b) => (a.d < b.d ? -1 : 1))
return true
}
diff --git a/frontend/src/lib/health-connect.js b/frontend/src/lib/health-connect.js
index 51aacacd7..7f09c05d3 100644
--- a/frontend/src/lib/health-connect.js
+++ b/frontend/src/lib/health-connect.js
@@ -85,7 +85,8 @@ export function healthRecords(S, { nameOf, speedUnit }) {
const unit = S?.unit === 'lb' ? 'lb' : 'kg'
return {
sessions: (S?.workouts || []).map(w => sessionRecord(w, { unit, nameOf, speedUnit })).filter(Boolean),
- weights: (S?.bodyweight || []).map(b => weightRecord(b, unit)).filter(Boolean),
+ // A weigh-in read from the hub (`src`, lib/health-read.js) is already there: never written back.
+ weights: (S?.bodyweight || []).filter(b => !b?.src).map(b => weightRecord(b, unit)).filter(Boolean),
}
}
diff --git a/frontend/src/lib/health-read.js b/frontend/src/lib/health-read.js
new file mode 100644
index 000000000..908ccda80
--- /dev/null
+++ b/frontend/src/lib/health-read.js
@@ -0,0 +1,110 @@
+// What openGym takes back from the phone's health hub (#544, #127): Health Connect on Android,
+// Apple Health on the iPhone. Two things, each behind its own switch in Settings:
+//
+// - the heart rate during a finished workout, per set and for the session (lib/heart-rate.js
+// works out which samples belong to which set), for every watch that saves to the hub;
+// - weigh-ins other apps saved there (a smart scale's, Garmin's, Withings', Samsung's...).
+//
+// Pure: lib/health-sync.js reads the hub and hands the records over; this decides what goes into
+// the log. The rules:
+// - a set that already has a heart rate keeps it (the Apple Watch measured it live);
+// - a day with a weigh-in typed into openGym keeps it: an imported one never replaces it, and
+// one typed in later replaces the imported one (lib/sync-merge.js mergeBodyweight);
+// - openGym's own records in the hub (what it wrote there itself) are never read back as new;
+// - an imported weigh-in carries `src` and is never written back to the hub (no ping-pong:
+// lib/health-connect.js healthRecords leaves it out).
+import { hrFromSamples, sanitizeHr } from './heart-rate.js'
+import { stampWorkout } from './sync-merge.js'
+import { isoOf } from './format.js'
+
+export const LB_PER_KG = 2.2046226218
+// Weigh-ins outside this are a typo or another person's profile in the hub, not a body weight.
+const KG_MIN = 20
+const KG_MAX = 400
+// Packages and bundle ids that are openGym: the app, its test build, the Apple Watch app.
+const OWN = /^ch\.duartesantos\.opengym(\.|$)/
+
+/** Whether a record in the hub is one openGym wrote itself (by its client id or by its origin). */
+export function isOwnRecord(rec) {
+ if (!rec || typeof rec !== 'object') return false
+ if (/^opengym-/.test(String(rec.clientId || ''))) return true
+ return OWN.test(String(rec.origin || ''))
+}
+
+/**
+ * The heart rate read for workout `wid` (`samples`: [ms, bpm] from the hub) put into the log `S`
+ * (mutated). Only sets without a reading get one; the session's reading is set when the workout
+ * has none, or replaced by a fuller one from the same hub (Garmin and Fitbit sync late, so a
+ * read right after the workout can hold only part of it). One the watch took is never replaced.
+ * The workout is stamped as edited, so a sync keeps the change. Returns whether anything changed.
+ */
+export function mergeHeartRate(S, wid, samples, src, now = Date.now()) {
+ const w = (S?.workouts || []).find(x => x && x.id === wid)
+ if (!w) return false
+ const res = hrFromSamples(w, samples)
+ let changed = false
+ for (const [key, got] of res.sets) {
+ const [ei, si] = key.split(':').map(Number)
+ const set = w.entries?.[ei]?.sets?.[si]
+ if (!set) continue
+ if (got.hr && !sanitizeHr(set.hr)) { set.hr = got.hr; changed = true }
+ if (got.restHr && !sanitizeHr(set.restHr)) { set.restHr = got.restHr; changed = true }
+ }
+ if (res.session) {
+ const cur = w.hr && typeof w.hr === 'object' ? w.hr : null
+ const fuller = !cur || (cur.src === src && res.n > (Number(cur.n) || 0))
+ if (fuller && cur?.src !== 'watch') {
+ w.hr = { ...res.session, src, n: res.n }
+ changed = true
+ }
+ }
+ if (changed) stampWorkout(w, now)
+ return changed
+}
+
+/** Whether a workout still has sets the hub could fill: one done and without a heart rate. */
+export function lacksHeartRate(w) {
+ if (!w || typeof w !== 'object') return false
+ if (!w.hr) return true
+ return (w.entries || []).some(e => (e?.sets || []).some(s => s && (s.done === true || s.sides) && !sanitizeHr(s.hr)))
+}
+
+/**
+ * Weigh-ins from the hub (`records`: [{ t, kg, id, origin, clientId }]) put into the log `S`
+ * (mutated), at most one per day: the latest of that day. `seen` is this phone's memo of what it
+ * imported ({ [day]: { id, t } }), updated in place, which makes a second read of the same records
+ * a no-op. A day is left alone when it has a weigh-in typed into openGym, when the weigh-in was
+ * deleted in openGym after the record was taken, or when the record is not newer than the one
+ * already imported for it. Weights go in in the profile's unit. Returns the days changed.
+ */
+export function mergeWeighIns(S, records, { src, seen = {} } = {}) {
+ const unit = S?.unit === 'lb' ? 'lb' : 'kg'
+ const latest = new Map()
+ for (const r of Array.isArray(records) ? records : []) {
+ if (!r || isOwnRecord(r)) continue
+ const t = Number(r.t), kg = Number(r.kg)
+ if (!(t > 0) || !(kg >= KG_MIN && kg <= KG_MAX)) continue
+ const d = isoOf(new Date(t))
+ const cur = latest.get(d)
+ if (!cur || t > cur.t) latest.set(d, { t, kg, id: r.id || null })
+ }
+ if (!latest.size) return []
+ if (!Array.isArray(S.bodyweight)) S.bodyweight = []
+ const deleted = S.deleted?.bodyweight && typeof S.deleted.bodyweight === 'object' ? S.deleted.bodyweight : {}
+ const days = []
+ for (const [d, r] of latest) {
+ const ex = S.bodyweight.find(b => b && b.d === d)
+ if (ex && !ex.src) continue // typed in: it wins
+ if (Number(deleted[d]) > r.t && !ex) continue // removed in openGym after it was taken
+ const before = seen[d] ? Number(seen[d].t) : ex ? Number(ex.t) || 0 : 0
+ if (ex && !(r.t > before)) continue
+ if (!ex && seen[d] && !(r.t > Number(seen[d].t))) continue
+ const w = Math.round((unit === 'lb' ? r.kg * LB_PER_KG : r.kg) * 10) / 10
+ if (ex) { ex.w = w; ex.t = r.t; ex.src = src }
+ else S.bodyweight.push({ d, w, t: r.t, src })
+ seen[d] = { id: r.id, t: r.t }
+ days.push(d)
+ }
+ if (days.length) S.bodyweight.sort((a, b) => (a.d < b.d ? -1 : 1))
+ return days
+}
diff --git a/frontend/src/lib/health-read.test.js b/frontend/src/lib/health-read.test.js
new file mode 100644
index 000000000..47e230c7f
--- /dev/null
+++ b/frontend/src/lib/health-read.test.js
@@ -0,0 +1,150 @@
+// v1.4.3 (#544, #127): what openGym takes back from Health Connect / Apple Health. Heart rate only
+// fills what is missing (the Apple Watch's own reading is never replaced), weigh-ins typed into
+// openGym always win, openGym's own records are never read back, nothing imported is written back.
+import { describe, expect, it } from 'vitest'
+import { isOwnRecord, mergeHeartRate, mergeWeighIns, lacksHeartRate } from './health-read.js'
+import { healthRecords, planSync } from './health-connect.js'
+import { mergeBodyweight, mergeStates, stampChange } from './sync-merge.js'
+import { logWeighIn } from './bodyweight.js'
+
+const T0 = Date.UTC(2026, 9, 15, 17, 0, 0)
+const s = sec => T0 + sec * 1000
+const dense = (from, to, bpm) => { const out = []; for (let x = from; x <= to; x++) out.push([s(x), bpm]); return out }
+const workout = sets => ({ id: 'w1', d: '2026-10-15', name: 'Push', start: s(0), end: s(600), _ts: 5, entries: [{ id: '0025', target: { mode: 'reps' }, sets }] })
+const at = (d, h) => new Date(2026, 9, d, h).getTime()
+const rec = (d, h, kg, extra = {}) => ({ t: at(d, h), kg, id: `r${d}${h}`, origin: 'com.withings.wiscale2', clientId: null, ...extra })
+
+describe('isOwnRecord', () => {
+ it('knows openGym by client id and by origin', () => {
+ expect(isOwnRecord({ clientId: 'opengym-bw-2026-10-15', origin: 'x' })).toBe(true)
+ expect(isOwnRecord({ origin: 'ch.duartesantos.opengym' })).toBe(true)
+ expect(isOwnRecord({ origin: 'ch.duartesantos.opengym.test' })).toBe(true)
+ expect(isOwnRecord({ origin: 'ch.duartesantos.opengymx' })).toBe(false)
+ expect(isOwnRecord({ origin: 'com.garmin.android.apps.connectmobile', clientId: 'abc' })).toBe(false)
+ })
+})
+
+describe('mergeHeartRate', () => {
+ it('fills sets without a reading and stamps the workout', () => {
+ const S = { workouts: [workout([{ w: 60, r: 8, done: true, at: s(100) }])] }
+ expect(mergeHeartRate(S, 'w1', dense(0, 600, 130), 'hc', 99)).toBe(true)
+ const w = S.workouts[0]
+ expect(w.entries[0].sets[0].hr).toEqual({ avg: 130, max: 130 })
+ expect(w.hr).toEqual({ avg: 130, max: 130, src: 'hc', n: 601 })
+ expect(w._ts).toBe(99)
+ })
+
+ it('never overwrites a heart rate the Apple Watch measured', () => {
+ const watch = { avg: 111, max: 122 }
+ const S = { workouts: [{ ...workout([{ w: 60, r: 8, done: true, at: s(100), hr: watch, restHr: watch }]), hr: { avg: 1, max: 2, src: 'watch', n: 900 } }] }
+ mergeHeartRate(S, 'w1', dense(0, 600, 150), 'ah', 99)
+ expect(S.workouts[0].entries[0].sets[0].hr).toEqual(watch)
+ expect(S.workouts[0].entries[0].sets[0].restHr).toEqual(watch)
+ expect(S.workouts[0].hr.src).toBe('watch')
+ })
+
+ it('takes a fuller read from the same hub later (a watch that syncs late), not a thinner one', () => {
+ const S = { workouts: [workout([{ w: 60, r: 8, done: true, at: s(100) }])] }
+ mergeHeartRate(S, 'w1', dense(0, 120, 120), 'hc', 1)
+ expect(S.workouts[0].hr.n).toBe(121)
+ mergeHeartRate(S, 'w1', dense(0, 600, 140), 'hc', 2)
+ expect(S.workouts[0].hr).toMatchObject({ avg: 140, n: 601 })
+ // The set's reading from the first read stays.
+ expect(S.workouts[0].entries[0].sets[0].hr.avg).toBe(120)
+ expect(mergeHeartRate(S, 'w1', dense(0, 100, 90), 'hc', 3)).toBe(false)
+ })
+
+ it('is a no-op the second time, and for a workout it does not know', () => {
+ const S = { workouts: [workout([{ w: 60, r: 8, done: true, at: s(100) }])] }
+ mergeHeartRate(S, 'w1', dense(0, 600, 130), 'hc', 1)
+ expect(mergeHeartRate(S, 'w1', dense(0, 600, 130), 'hc', 2)).toBe(false)
+ expect(mergeHeartRate(S, 'nope', dense(0, 600, 130), 'hc', 2)).toBe(false)
+ })
+
+ it('lacksHeartRate', () => {
+ expect(lacksHeartRate(workout([{ w: 60, r: 8, done: true }]))).toBe(true)
+ expect(lacksHeartRate({ ...workout([{ w: 60, r: 8, done: true, hr: { avg: 100, max: 120 } }]), hr: { avg: 1, max: 2 } })).toBe(false)
+ })
+
+ it('the fields survive a sync merge between two devices', () => {
+ const base = { _ts: 1, unit: 'kg', workouts: [workout([{ w: 60, r: 8, done: true, at: s(100) }])], routines: [], bodyweight: [] }
+ const phone = JSON.parse(JSON.stringify(base))
+ mergeHeartRate(phone, 'w1', dense(0, 600, 130), 'hc', 50)
+ phone._ts = stampChange(base, phone, 50)
+ const merged = mergeStates(phone, base)
+ expect(merged.workouts[0].hr.src).toBe('hc')
+ expect(merged.workouts[0].entries[0].sets[0].hr).toEqual({ avg: 130, max: 130 })
+ })
+})
+
+describe('mergeWeighIns', () => {
+ it('adds the latest weigh-in of each day, marked as imported', () => {
+ const S = { unit: 'kg', bodyweight: [] }
+ const days = mergeWeighIns(S, [rec(14, 7, 81.24), rec(14, 9, 80.96), rec(15, 7, 80.5)], { src: 'hc' })
+ expect(days).toEqual(['2026-10-14', '2026-10-15'])
+ expect(S.bodyweight).toEqual([
+ { d: '2026-10-14', w: 81, t: at(14, 9), src: 'hc' },
+ { d: '2026-10-15', w: 80.5, t: at(15, 7), src: 'hc' },
+ ])
+ })
+
+ it('skips openGym’s own records and implausible weights', () => {
+ const S = { unit: 'kg', bodyweight: [] }
+ mergeWeighIns(S, [rec(14, 7, 80, { clientId: 'opengym-bw-2026-10-14' }), rec(15, 7, 80, { origin: 'ch.duartesantos.opengym' }), rec(16, 7, 5), rec(17, 7, 900)], { src: 'hc' })
+ expect(S.bodyweight).toEqual([])
+ })
+
+ it('keeps a weigh-in typed into openGym that day', () => {
+ const S = { unit: 'kg', bodyweight: [{ d: '2026-10-15', w: 82, t: at(15, 6) }] }
+ expect(mergeWeighIns(S, [rec(15, 8, 80)], { src: 'hc' })).toEqual([])
+ expect(S.bodyweight).toEqual([{ d: '2026-10-15', w: 82, t: at(15, 6) }])
+ })
+
+ it('converts to pounds for a profile in lb', () => {
+ const S = { unit: 'lb', bodyweight: [] }
+ mergeWeighIns(S, [rec(15, 7, 80)], { src: 'ah' })
+ expect(S.bodyweight[0].w).toBe(176.4)
+ })
+
+ it('is idempotent on a second read, and takes a newer reading of the same day', () => {
+ const S = { unit: 'kg', bodyweight: [] }
+ const seen = {}
+ mergeWeighIns(S, [rec(15, 7, 80)], { src: 'hc', seen })
+ // The store stamps a new weigh-in with the time of the change (stampChange).
+ S.bodyweight[0].t = at(15, 12)
+ expect(mergeWeighIns(S, [rec(15, 7, 80)], { src: 'hc', seen })).toEqual([])
+ expect(mergeWeighIns(S, [rec(15, 7, 80), rec(15, 9, 79.5)], { src: 'hc', seen })).toEqual(['2026-10-15'])
+ expect(S.bodyweight).toEqual([{ d: '2026-10-15', w: 79.5, t: at(15, 9), src: 'hc' }])
+ })
+
+ it('does not bring back a weigh-in deleted in openGym after it was taken', () => {
+ const S = { unit: 'kg', bodyweight: [], deleted: { bodyweight: { '2026-10-15': at(15, 10) } } }
+ expect(mergeWeighIns(S, [rec(15, 7, 80)], { src: 'hc' })).toEqual([])
+ expect(mergeWeighIns(S, [rec(15, 11, 80)], { src: 'hc' })).toEqual(['2026-10-15'])
+ })
+
+ it('is never written back to the hub (no ping-pong)', () => {
+ const S = { unit: 'kg', workouts: [], bodyweight: [{ d: '2026-10-14', w: 81, t: at(14, 7) }] }
+ mergeWeighIns(S, [rec(15, 7, 80)], { src: 'hc' })
+ const recs = healthRecords(S, { nameOf: e => e.id })
+ expect(recs.weights.map(w => w.id)).toEqual(['opengym-bw-2026-10-14'])
+ expect(planSync(recs, {}).weights.map(w => w.id)).toEqual(['opengym-bw-2026-10-14'])
+ })
+})
+
+describe('a typed weigh-in beats an imported one in a sync merge', () => {
+ it('whichever is newer', () => {
+ const typed = { d: '2026-10-15', w: 82, t: at(15, 6) }
+ const imported = { d: '2026-10-15', w: 80, t: at(15, 20), src: 'hc' }
+ expect(mergeBodyweight([imported], [typed])).toEqual([typed])
+ expect(mergeBodyweight([typed], [imported])).toEqual([typed])
+ // Two imported or two typed: the newer, as before.
+ expect(mergeBodyweight([{ ...imported, t: 1 }], [imported])).toEqual([imported])
+ })
+
+ it('typing over an imported weigh-in makes it a typed one', () => {
+ const S = { bodyweight: [{ d: '2026-10-15', w: 80, t: at(15, 7), src: 'hc' }] }
+ logWeighIn(S, 81, at(15, 9))
+ expect(S.bodyweight[0]).toEqual({ d: '2026-10-15', w: 81, t: at(15, 9) })
+ })
+})
diff --git a/frontend/src/lib/health-sync.js b/frontend/src/lib/health-sync.js
index a272e7b96..1a25ddbbd 100644
--- a/frontend/src/lib/health-sync.js
+++ b/frontend/src/lib/health-sync.js
@@ -11,7 +11,14 @@
// the Apple Watch app (its workout session shows the heart rate per set), and tells the watch
// whether it is on (setEnabled: the App Group's "healthEnabled", which the watch link passes on).
//
+// Since v1.4.3 it can also read two things back (#544, #127), each behind a switch of its own and
+// off by default: the heart rate during a finished workout (for any watch that saves to the hub,
+// not just the Apple Watch), and weigh-ins other apps saved there. Only while the app is open, only
+// the workouts of the last day and the weigh-ins since the last read (30 days the first time), so
+// no background or history permission is asked for. What it decides is in lib/health-read.js.
+//
// The web build never gets here (MOBILE is a build-time flag).
+import { mergeHeartRate, mergeWeighIns, lacksHeartRate } from './health-read.js'
import { MOBILE, nativePlatform, readJsonFile, writeJsonFile } from './mobile.js'
import { healthRecords, planSync, writtenIds, goneIds } from './health-connect.js'
import { exerciseNameFor } from './i18n-core.js'
@@ -19,7 +26,7 @@ import { EXIDX } from './exercises.js'
import { speedUnitOf } from './speed.js'
export const HEALTH_FILE = 'opengym-health.json'
-const OFF = { on: false, written: {}, at: 0, error: null }
+const OFF = { on: false, written: {}, at: 0, error: null, readHr: false, readWeight: false, wCursor: 0, seen: {}, hrTried: {}, readError: null }
// Wrapped in an object, as in rest-alert.js: a Capacitor plugin proxy answers `then`, so a
// promise resolved with the bare proxy never settles.
@@ -43,7 +50,8 @@ let cached = null
export async function loadHealth() {
if (cached) return cached
const f = await readJsonFile(HEALTH_FILE)
- cached = f && typeof f === 'object' ? { ...OFF, ...f, written: f.written && typeof f.written === 'object' ? f.written : {} } : { ...OFF }
+ const map = v => (v && typeof v === 'object' && !Array.isArray(v) ? v : {})
+ cached = f && typeof f === 'object' ? { ...OFF, ...f, written: map(f.written), seen: map(f.seen), hrTried: map(f.hrTried) } : { ...OFF }
return cached
}
const saveHealth = h => { cached = h; return writeJsonFile(HEALTH_FILE, h) }
@@ -187,13 +195,151 @@ export async function disableHealth({ removeWritten = false } = {}) {
// Back in the foreground: a change synced from another device while the phone was away, or a
// permission the user granted again in Health Connect's own settings, is picked up then.
let started = false
-export function initHealthSync(getState) {
+export function initHealthSync(getState, apply = null) {
if (!MOBILE || started) return
started = true
+ applyRef = apply
import('@capacitor/app').then(({ App }) => {
- App.addListener('appStateChange', ({ isActive }) => { if (isActive) syncHealth(getState()).catch(() => {}) })
+ App.addListener('appStateChange', ({ isActive }) => {
+ if (!isActive) return
+ syncHealth(getState()).catch(() => {})
+ readHealth(getState, { force: true }).catch(() => {})
+ })
}).catch(() => {})
// Once at launch, for a workout finished just before the app was closed. Reading the file here
// also settles whether it is on, which the saves wait for (syncHealth).
- setTimeout(() => loadHealth().then(h => { mirrorOn(h.on); return syncHealth(getState()) }).catch(() => {}), 3000)
+ setTimeout(() => loadHealth().then(h => {
+ mirrorOn(h.on)
+ readHealth(getState, { force: true }).catch(() => {})
+ return syncHealth(getState())
+ }).catch(() => {}), 3000)
+}
+
+/* ------------------------------------------------------------------ reading back (v1.4.3) -- */
+
+// How long after a workout its heart rate is still looked for: Garmin and Fitbit hand theirs to
+// the hub when the watch next syncs, which can be hours later.
+export const HR_WINDOW_MS = 24 * 3600e3
+// Between two reads of the same thing, at most this often while the app is in use, and this often
+// when it comes back to the foreground.
+const READ_EVERY_MS = 10 * 60e3
+const RESUME_EVERY_MS = 2 * 60e3
+// The first read of weigh-ins goes this far back (what Health Connect gives without the history
+// permission); later ones from the newest seen, minus a margin for a scale that syncs late.
+export const WEIGHT_FIRST_MS = 30 * 24 * 3600e3
+const WEIGHT_MARGIN_MS = 2 * 24 * 3600e3
+const SEEN_KEEP_MS = 60 * 24 * 3600e3
+
+const srcOf = platform => (platform === 'ios' ? 'ah' : 'hc')
+
+// The store's update, given at launch (initHealthSync): a read result goes into the log the way any
+// other change does, so it is saved, stamped and synced.
+let applyRef = null
+let readRunning = null
+let lastWeightRead = 0
+
+/**
+ * Turns one of the two reads on (`kind`: 'hr' | 'weight'): asks for that read permission only,
+ * then reads once. Resolves with { ok, reason }; reason 'denied' when it was not granted.
+ */
+export async function enableRead(kind, getState, { apply = null } = {}) {
+ const p = await plugin()
+ if (!p) return { ok: false, reason: 'unsupported' }
+ const st = await p.HC.status().catch(() => ({ status: 'unsupported' }))
+ if (st.status !== 'available') return { ok: false, reason: st.status }
+ const perm = kind === 'hr' ? 'heartRate' : 'weight'
+ const res = await p.HC.requestPermissions({ read: [perm], write: [] }).catch(() => null)
+ // Apple Health never says whether reading was allowed (that it was refused is itself private):
+ // `read` is then missing, and a refusal just reads nothing.
+ const ok = res && (res.read ? res.read[perm] !== false : true)
+ if (!ok) return { ok: false, reason: 'denied' }
+ const h = await loadHealth()
+ const out = { ...h, [kind === 'hr' ? 'readHr' : 'readWeight']: true, readError: null }
+ await saveHealth(out)
+ told(out)
+ if (getState) await readHealth(getState, { force: true, apply }).catch(() => {})
+ return { ok: true, reason: null, health: cached }
+}
+
+/** Turns a read off. What it already brought in stays in the log, as the user's data. */
+export async function disableRead(kind) {
+ if (readRunning) await readRunning.catch(() => {})
+ const h = await loadHealth()
+ const out = kind === 'hr' ? { ...h, readHr: false, hrTried: {} } : { ...h, readWeight: false }
+ if (!out.readHr && !out.readWeight) out.readError = null
+ await saveHealth(out)
+ told(out)
+ return out
+}
+
+/**
+ * One read pass: the heart rate of every workout finished in the last day that still lacks some,
+ * and the weigh-ins since the last read. A no-op while both switches are off; never runs twice at
+ * once; reads the same thing at most every ten minutes (two after coming back to the foreground,
+ * `force`). The log changes only when something new came in.
+ */
+export function readHealth(getState, { force = false, now = Date.now(), apply = null } = {}) {
+ if (!MOBILE || !cached || !(cached.readHr || cached.readWeight)) return Promise.resolve(cached)
+ if (readRunning) return readRunning
+ readRunning = readOnce(getState, force, now, apply || applyRef).finally(() => { readRunning = null })
+ return readRunning
+}
+
+async function readOnce(getState, force, now, applyFn) {
+ const p = await plugin()
+ if (!p) return cached
+ const src = srcOf(p.platform)
+ const every = force ? RESUME_EVERY_MS : READ_EVERY_MS
+ let h = { ...(await loadHealth()) }
+ let error = null
+ // `decide` runs on a copy first: an update that changes nothing would still stamp and push.
+ const apply = (decide, fn = decide) => {
+ const probe = JSON.parse(JSON.stringify(getState() || {}))
+ if (!decide(probe)) return false
+ if (applyFn) applyFn(s => { fn(s) })
+ return true
+ }
+ const fail = e => { error = e?.code === 'permission' ? 'permission' : e?.code === 'unavailable' ? 'unavailable' : 'failed' }
+
+ if (h.readHr) {
+ const S = getState()
+ const tried = {}
+ for (const [wid, at] of Object.entries(h.hrTried || {})) if (now - Number(at) < HR_WINDOW_MS * 2) tried[wid] = at
+ for (const w of S?.workouts || []) {
+ const end = Number(w?.end), start = Number(w?.start)
+ if (!w?.id || !(start > 0) || !(end > start) || now - end > HR_WINDOW_MS || end > now) continue
+ if (!lacksHeartRate(w) && w.hr?.src !== src) continue
+ if (tried[w.id] && now - Number(tried[w.id]) < every) continue
+ try {
+ const res = await p.HC.readHeartRate({ from: start, to: end + 5 * 60e3 })
+ tried[w.id] = now
+ const samples = Array.isArray(res?.samples) ? res.samples : []
+ if (samples.length) apply(s => mergeHeartRate(s, w.id, samples, src, now))
+ } catch (e) { fail(e); break }
+ }
+ h.hrTried = tried
+ }
+
+ if (h.readWeight && (force ? now - lastWeightRead >= RESUME_EVERY_MS : now - lastWeightRead >= READ_EVERY_MS)) {
+ const since = h.wCursor > 0 ? Math.max(h.wCursor - WEIGHT_MARGIN_MS, now - WEIGHT_FIRST_MS) : now - WEIGHT_FIRST_MS
+ try {
+ const res = await p.HC.readWeights({ since })
+ lastWeightRead = now
+ const records = Array.isArray(res?.records) ? res.records : []
+ // The memo is filled in on the copy that decides; the store's update replays the same merge.
+ const seen = { ...(h.seen || {}) }
+ const before = { ...seen }
+ if (records.length) apply(probe => mergeWeighIns(probe, records, { src, seen }).length > 0,
+ s => { mergeWeighIns(s, records, { src, seen: { ...before } }) })
+ for (const [d, v] of Object.entries(seen)) if (now - Number(v?.t) > SEEN_KEEP_MS) delete seen[d]
+ h.seen = seen
+ const newest = records.reduce((m, r) => Math.max(m, Number(r?.t) || 0), 0)
+ if (newest > h.wCursor) h.wCursor = newest
+ } catch (e) { fail(e) }
+ }
+
+ h.readError = error
+ await saveHealth(h)
+ told(h)
+ return h
}
diff --git a/frontend/src/lib/health-sync.read.test.js b/frontend/src/lib/health-sync.read.test.js
new file mode 100644
index 000000000..2bce4bf2b
--- /dev/null
+++ b/frontend/src/lib/health-sync.read.test.js
@@ -0,0 +1,181 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+// v1.4.3 (#544, #127): reading heart rate and weigh-ins back from Health Connect / Apple Health.
+// The native plugin and the app's data directory are played in memory, the store by a plain
+// object and an `apply` that runs the change on it (as useStore's update does).
+const h = vi.hoisted(() => {
+ vi.stubEnv('VITE_MOBILE', '1')
+ return { files: new Map(), calls: [], platform: 'android', granted: { heartRate: true, weight: true }, hr: [], weights: [], fail: null }
+})
+
+vi.mock('@capacitor/filesystem', () => ({
+ Directory: { Data: 'DATA' },
+ Encoding: { UTF8: 'utf8' },
+ Filesystem: {
+ readFile: async ({ path }) => {
+ if (!h.files.has(path)) throw new Error('File does not exist')
+ return { data: h.files.get(path) }
+ },
+ writeFile: async ({ path, data }) => { h.files.set(path, data) },
+ },
+}))
+vi.mock('@capacitor/app', () => ({ App: { addListener: () => ({ remove() {} }) } }))
+vi.mock('@capacitor/core', () => ({
+ Capacitor: { getPlatform: () => h.platform },
+ registerPlugin: () => ({
+ status: async () => ({ status: 'available', granted: false, read: { ...h.granted } }),
+ requestPermissions: async arg => {
+ h.calls.push(['request', arg])
+ return h.platform === 'ios' ? { granted: false } : { granted: false, read: { ...h.granted } }
+ },
+ readHeartRate: async arg => {
+ h.calls.push(['readHeartRate', arg])
+ if (h.fail) throw Object.assign(new Error('no'), { code: h.fail })
+ return { samples: h.hr.filter(([t]) => t >= arg.from && t <= arg.to), origins: ['com.garmin.android.apps.connectmobile'] }
+ },
+ readWeights: async arg => {
+ h.calls.push(['readWeights', arg])
+ if (h.fail) throw Object.assign(new Error('no'), { code: h.fail })
+ return { records: h.weights.filter(r => r.t >= arg.since) }
+ },
+ write: async () => { h.calls.push(['write']) },
+ remove: async () => {},
+ openSettings: async () => {},
+ setEnabled: async () => {},
+ }),
+}))
+
+const NOW = Date.UTC(2026, 9, 15, 20, 0, 0)
+const s = sec => NOW - 3600e3 + sec * 1000
+const dense = (from, to, bpm) => { const out = []; for (let x = from; x <= to; x++) out.push([s(x), bpm]); return out }
+const workout = (id, endSec = 600, extra = {}) => ({ id, d: '2026-10-15', name: 'Push', start: s(0), end: s(endSec), entries: [{ id: '0025', target: { mode: 'reps' }, sets: [{ w: 60, r: 8, done: true, at: s(100) }] }], ...extra })
+const reads = kind => h.calls.filter(c => c[0] === kind)
+const file = () => JSON.parse(h.files.get('opengym-health.json') || 'null')
+
+let hs, S, applied
+const getState = () => S
+const apply = fn => { applied++; const next = JSON.parse(JSON.stringify(S)); fn(next); S = next }
+beforeEach(async () => {
+ vi.useFakeTimers({ toFake: ['Date'] })
+ vi.setSystemTime(NOW)
+ vi.resetModules()
+ h.files.clear(); h.calls = []; h.platform = 'android'; h.granted = { heartRate: true, weight: true }; h.hr = []; h.weights = []; h.fail = null
+ S = { unit: 'kg', workouts: [workout('w1')], bodyweight: [] }
+ applied = 0
+ hs = await import('./health-sync.js')
+})
+
+afterEach(() => { vi.useRealTimers() })
+
+describe('switched off (the default)', () => {
+ it('reads nothing at all', async () => {
+ await hs.loadHealth()
+ h.hr = dense(0, 600, 130)
+ await hs.readHealth(getState, { force: true, now: NOW, apply })
+ expect(h.calls).toEqual([])
+ expect(applied).toBe(0)
+ })
+})
+
+describe('heart rate', () => {
+ it('asks for that read permission only, then fills the workout just finished', async () => {
+ h.hr = dense(0, 600, 130)
+ const r = await hs.enableRead('hr', getState, { apply })
+ expect(r.ok).toBe(true)
+ expect(h.calls[0]).toEqual(['request', { read: ['heartRate'], write: [] }])
+ expect(reads('readHeartRate')).toHaveLength(1)
+ expect(S.workouts[0].entries[0].sets[0].hr).toEqual({ avg: 130, max: 130 })
+ expect(S.workouts[0].hr).toMatchObject({ src: 'hc', avg: 130 })
+ expect(file()).toMatchObject({ readHr: true, readWeight: false, on: false })
+ expect(reads('write')).toEqual([])
+ })
+
+ it('stays off when the permission is not granted', async () => {
+ h.granted.heartRate = false
+ expect(await hs.enableRead('hr', getState, { apply })).toEqual({ ok: false, reason: 'denied' })
+ expect(reads('readHeartRate')).toEqual([])
+ expect(file()).toBeNull()
+ })
+
+ it('looks only at workouts of the last 24 hours, and not more than every few minutes', async () => {
+ S.workouts.push({ ...workout('old'), start: NOW - 30 * 3600e3, end: NOW - 29 * 3600e3 })
+ await hs.enableRead('hr', getState, { apply })
+ expect(reads('readHeartRate').map(c => c[1].from)).toEqual([s(0)])
+ // Nothing yet (the watch has not synced): tried again later, not right away.
+ await hs.readHealth(getState, { now: NOW + 60e3, apply })
+ expect(reads('readHeartRate')).toHaveLength(1)
+ h.hr = dense(0, 600, 125)
+ await hs.readHealth(getState, { now: NOW + 11 * 60e3, apply })
+ expect(reads('readHeartRate')).toHaveLength(2)
+ expect(S.workouts[0].hr.avg).toBe(125)
+ // A day later it stops looking.
+ await hs.readHealth(getState, { force: true, now: NOW + 25 * 3600e3, apply })
+ expect(reads('readHeartRate')).toHaveLength(2)
+ })
+
+ it('never touches the Apple Watch’s own reading on the iPhone', async () => {
+ vi.resetModules(); h.platform = 'ios'; hs = await import('./health-sync.js')
+ const watch = { avg: 111, max: 140 }
+ S.workouts[0].entries[0].sets[0].hr = watch
+ S.workouts[0].hr = { avg: 110, max: 140, src: 'watch', n: 600 }
+ h.hr = dense(0, 600, 150)
+ await hs.enableRead('hr', getState, { apply })
+ expect(S.workouts[0].entries[0].sets[0].hr).toEqual(watch)
+ expect(S.workouts[0].hr.src).toBe('watch')
+ })
+
+ it('a withdrawn permission is remembered, for Settings to offer asking again', async () => {
+ await hs.enableRead('hr', getState, { apply })
+ h.fail = 'permission'
+ await hs.readHealth(getState, { force: true, now: NOW + 3 * 60e3, apply })
+ expect(file().readError).toBe('permission')
+ })
+
+ it('turning it off stops the reads and keeps what came in', async () => {
+ h.hr = dense(0, 600, 130)
+ await hs.enableRead('hr', getState, { apply })
+ await hs.disableRead('hr')
+ S.workouts.push(workout('w2'))
+ await hs.readHealth(getState, { force: true, now: NOW + 3 * 60e3, apply })
+ expect(reads('readHeartRate')).toHaveLength(1)
+ expect(S.workouts[0].hr.src).toBe('hc')
+ })
+})
+
+describe('weigh-ins', () => {
+ const rec = (hAgo, kg, extra = {}) => ({ t: NOW - hAgo * 3600e3, kg, id: 'r' + hAgo, origin: 'com.withings.wiscale2', clientId: null, ...extra })
+
+ it('reads the last 30 days the first time, then from the newest seen', async () => {
+ h.weights = [rec(2, 80.4), rec(26, 81, { clientId: 'opengym-bw-2026-10-14' })]
+ await hs.enableRead('weight', getState, { apply })
+ expect(h.calls[0]).toEqual(['request', { read: ['weight'], write: [] }])
+ expect(reads('readWeights')[0][1].since).toBe(NOW - 30 * 24 * 3600e3)
+ expect(S.bodyweight).toEqual([{ d: '2026-10-15', w: 80.4, t: NOW - 2 * 3600e3, src: 'hc' }])
+ expect(file().wCursor).toBe(NOW - 2 * 3600e3)
+ await hs.readHealth(getState, { force: true, now: NOW + 3 * 60e3, apply })
+ expect(reads('readWeights')[1][1].since).toBe(NOW - 2 * 3600e3 - 2 * 24 * 3600e3)
+ })
+
+ it('changes nothing on a second read of the same records', async () => {
+ h.weights = [rec(2, 80.4)]
+ await hs.enableRead('weight', getState, { apply })
+ expect(applied).toBe(1)
+ await hs.readHealth(getState, { force: true, now: NOW + 3 * 60e3, apply })
+ expect(applied).toBe(1)
+ })
+
+ it('leaves a day with a weigh-in typed into openGym alone', async () => {
+ S.bodyweight = [{ d: '2026-10-15', w: 82, t: NOW - 10 * 3600e3 }]
+ h.weights = [rec(2, 80.4)]
+ await hs.enableRead('weight', getState, { apply })
+ expect(applied).toBe(0)
+ expect(S.bodyweight).toEqual([{ d: '2026-10-15', w: 82, t: NOW - 10 * 3600e3 }])
+ })
+
+ it('on the iPhone, where Apple Health never says whether reading is allowed, just reads', async () => {
+ vi.resetModules(); h.platform = 'ios'; hs = await import('./health-sync.js')
+ h.weights = [rec(2, 80.4)]
+ expect((await hs.enableRead('weight', getState, { apply })).ok).toBe(true)
+ expect(S.bodyweight[0].src).toBe('ah')
+ })
+})
diff --git a/frontend/src/lib/heart-rate.js b/frontend/src/lib/heart-rate.js
index 394c5ac1c..edba3a7ef 100644
--- a/frontend/src/lib/heart-rate.js
+++ b/frontend/src/lib/heart-rate.js
@@ -6,6 +6,15 @@
//
// Nothing else changes: a set without them is exactly the set it always was, and every reader
// that does not know them (older apps, the server, the exports) carries them along untouched.
+//
+// Since v1.4.3 the same fields can also come from the phone's health hub (hrFromSamples below),
+// for every other watch; they only ever fill a set that has none, so the Apple Watch's own
+// reading is never replaced. A finished workout may carry the session's too:
+//
+// hr { avg, max, src, n } src: 'watch' | 'hc' (Health Connect) | 'ah' (Apple Health),
+// n: how many samples it was worked out from
+import { modeOf } from './history.js'
+import { isSideSet, dropsOf } from './workout-model.js'
const BPM_MIN = 25
const BPM_MAX = 250
@@ -24,3 +33,124 @@ export function hrLabel(set) {
const hr = sanitizeHr(set && set.hr)
return hr ? ` ♥ ${hr.avg}/${hr.max}` : ''
}
+
+/* ------------------------------------------------ heart rate read back from the phone's hub -- */
+//
+// Health Connect (Android) and Apple Health (iPhone) collect the heart rate every watch and band
+// saves there: Garmin, Fitbit, Galaxy Watch, Pixel Watch, Polar, Amazfit, Xiaomi, Gadgetbridge...
+// lib/health-sync.js reads the samples between a finished workout's start and end; this works
+// out which of them belong to which set. openGym keeps a tick per set (`at`), not a start, so a
+// set's window is estimated the way the .fit export does it (lib/fit-export.js): it ends at the
+// tick and lasts as long as its reps, seconds or minutes take, but never starts before the set
+// ahead of it was ticked. The rest after a set runs until the next one starts.
+
+const REP_MS = 3000
+const SET_MIN_MS = 15000
+const SET_MAX_MS = 120000
+// Ticks this close together were caught up after the fact, all in one go: they say nothing about
+// when the set was done.
+const WINDOW_MIN_MS = 5000
+const REST_MIN_MS = 10000
+const LAST_REST_MS = 5 * 60000
+// Samples further apart than this (in the median) are too sparse for a set of thirty seconds: a
+// band that saves one reading a minute. Then only the session gets a heart rate.
+const SPARSE_GAP_MS = 20000
+// A tick this far outside the session is not of it (a set edited the next day).
+const SLACK_MS = 60000
+
+const setLen = (row, mode) => {
+ if (mode === 'cardio') return (Number(row?.min) || 0) * 60000
+ if (mode === 'time') return (Number(row?.sec) || 0) * 1000
+ return Math.min(SET_MAX_MS, Math.max(SET_MIN_MS, (Math.round(Number(row?.r) || 0)) * REP_MS))
+}
+
+// One item per set that was done and ticked: its key ('entry:set'), its tick and how long it took
+// (both sides of a per-side set, and the drops of a drop set, in it).
+function tickedSets(w) {
+ const out = []
+ ;(w?.entries || []).forEach((entry, ei) => {
+ if (!entry) return
+ const mode = modeOf({ ...(entry.target || {}), id: entry.id })
+ ;(entry.sets || []).forEach((s, si) => {
+ if (!s) return
+ const rows = isSideSet(s) ? [s.sides.L, s.sides.R].filter(x => x?.done === true) : s.done === true ? [s] : []
+ if (!rows.length) return
+ let tick = -Infinity, len = 0
+ for (const row of rows) {
+ const at = Number.isFinite(Number(row.at)) && Number(row.at) > 0 ? Number(row.at) : Number(s.at)
+ if (Number.isFinite(at) && at > tick) tick = at
+ len += setLen(row, mode)
+ for (const d of dropsOf(row)) if (Number(d?.r) > 0) len += setLen(d, mode)
+ }
+ if (Number.isFinite(tick) && len > 0) out.push({ key: `${ei}:${si}`, tick, len })
+ })
+ })
+ return out.sort((a, b) => a.tick - b.tick)
+}
+
+// The samples in [from, to], or (from, to] with `open`: a set's window and the rest after it
+// share their boundary, the tick, which belongs to the set.
+function stats(samples, from, to, open = false) {
+ let n = 0, sum = 0, max = 0
+ for (const [t, bpm] of samples) {
+ if (t < from || (open && t === from) || t > to) continue
+ n++; sum += bpm
+ if (bpm > max) max = bpm
+ }
+ return n ? { n, hr: sanitizeHr({ avg: sum / n, max }) } : { n: 0, hr: null }
+}
+
+/** Plausible [ms, bpm] pairs, oldest first. */
+export function cleanSamples(samples) {
+ const out = []
+ for (const x of Array.isArray(samples) ? samples : []) {
+ const t = Number(Array.isArray(x) ? x[0] : x?.t), bpm = Math.round(Number(Array.isArray(x) ? x[1] : x?.bpm))
+ if (Number.isFinite(t) && t > 0 && bpm >= BPM_MIN && bpm <= BPM_MAX) out.push([t, bpm])
+ }
+ return out.sort((a, b) => a[0] - b[0])
+}
+
+/**
+ * The heart rate of a finished workout `w` from the hub's samples ([ms, bpm]):
+ * { session: { avg, max } | null, n, sets: Map<'entry:set', { hr?, restHr? }> }. `n` is how many
+ * samples fell inside the session. A set gets a reading only when at least one sample lies in its
+ * window and the samples are dense enough to tell one set from the next; otherwise it is left as
+ * it is (honest rather than interpolated), and only the session has one. Workouts without ticks
+ * (logged before v1.3.x, or typed in afterwards) get the session only.
+ */
+export function hrFromSamples(w, samples) {
+ const start = Number(w?.start), end = Number(w?.end)
+ const out = { session: null, n: 0, sets: new Map() }
+ if (!(start > 0) || !(end > start)) return out
+ const all = cleanSamples(samples).filter(([t]) => t >= start && t <= end + LAST_REST_MS)
+ const inSession = stats(all, start, end)
+ out.session = inSession.n >= 2 ? inSession.hr : null
+ out.n = inSession.n
+ if (!out.session) return out
+ const gaps = []
+ for (let i = 1; i < all.length; i++) gaps.push(all[i][0] - all[i - 1][0])
+ gaps.sort((a, b) => a - b)
+ if (!gaps.length || gaps[gaps.length >> 1] > SPARSE_GAP_MS) return out
+ const items = tickedSets(w).filter(x => x.tick >= start - SLACK_MS && x.tick <= end + SLACK_MS)
+ let prevTick = start
+ const windows = items.map(x => {
+ const from = Math.max(prevTick, x.tick - x.len)
+ prevTick = Math.max(prevTick, x.tick)
+ return { ...x, from }
+ })
+ windows.forEach((x, i) => {
+ const got = {}
+ if (x.tick - x.from >= WINDOW_MIN_MS) {
+ const s = stats(all, x.from, x.tick, true)
+ if (s.hr) got.hr = s.hr
+ }
+ const next = windows[i + 1]
+ const restTo = next ? next.from : Math.min(x.tick + LAST_REST_MS, Math.max(end, x.tick))
+ if (restTo - x.tick >= REST_MIN_MS) {
+ const r = stats(all, x.tick, restTo, true)
+ if (r.hr) got.restHr = r.hr
+ }
+ if (got.hr || got.restHr) out.sets.set(x.key, got)
+ })
+ return out
+}
diff --git a/frontend/src/lib/heart-rate.samples.test.js b/frontend/src/lib/heart-rate.samples.test.js
new file mode 100644
index 000000000..81c6d39b6
--- /dev/null
+++ b/frontend/src/lib/heart-rate.samples.test.js
@@ -0,0 +1,83 @@
+// v1.4.3: the heart rate read back from Health Connect / Apple Health, split over the sets of a
+// finished workout (hrFromSamples). Dense samples give each set its own reading; sparse ones only
+// the session; ticks that say nothing about when a set was done give nothing.
+import { describe, expect, it } from 'vitest'
+import { hrFromSamples, cleanSamples } from './heart-rate.js'
+
+const T0 = Date.UTC(2026, 9, 15, 17, 0, 0)
+const s = sec => T0 + sec * 1000
+// One sample a second from `from` to `to` (seconds), bpm from fn(second).
+const dense = (from, to, fn) => { const out = []; for (let x = from; x <= to; x++) out.push([s(x), fn(x)]); return out }
+const set = (at, extra = {}) => ({ w: 60, r: 8, done: true, at: s(at), ...extra })
+const workout = (sets, extra = {}) => ({ id: 'w1', d: '2026-10-15', start: s(0), end: s(600), entries: [{ id: '0025', target: { mode: 'reps' }, sets }], ...extra })
+// Work at 150 for 24 s (8 reps x 3 s) before each tick, rest at 100 in between.
+const bpmFor = ticks => x => (ticks.some(t => x > t - 24 && x <= t) ? 150 : 100)
+
+describe('hrFromSamples', () => {
+ it('gives each set its work and rest heart rate from dense samples', () => {
+ const ticks = [100, 250, 400]
+ const r = hrFromSamples(workout(ticks.map(t => set(t))), dense(0, 600, bpmFor(ticks)))
+ expect(r.n).toBe(601)
+ expect(r.session.max).toBe(150)
+ expect(r.sets.get('0:0').hr).toEqual({ avg: 150, max: 150 })
+ expect(r.sets.get('0:0').restHr).toEqual({ avg: 100, max: 100 })
+ expect(r.sets.get('0:2').hr.avg).toBe(150)
+ // The last rest runs to the end of the session at most.
+ expect(r.sets.get('0:2').restHr.avg).toBe(100)
+ })
+
+ it('gives only the session from sparse samples (one a minute)', () => {
+ const samples = []
+ for (let x = 0; x <= 600; x += 60) samples.push([s(x), 120 + (x % 120 ? 10 : 0)])
+ const r = hrFromSamples(workout([set(100), set(250)]), samples)
+ expect(r.session).toEqual({ avg: 125, max: 130 })
+ expect(r.sets.size).toBe(0)
+ })
+
+ it('leaves a set alone when no sample falls in its window (a gap)', () => {
+ const samples = [...dense(0, 60, () => 100), ...dense(200, 600, () => 140)]
+ const r = hrFromSamples(workout([set(100), set(300)]), samples)
+ expect(r.sets.get('0:0')?.hr).toBeUndefined()
+ expect(r.sets.get('0:1').hr.avg).toBe(140)
+ })
+
+ it('ignores samples outside the session and implausible rates', () => {
+ const samples = [[s(-100), 200], [s(50), 300], [s(60), 10], ...dense(70, 600, () => 110)]
+ const r = hrFromSamples(workout([set(100)]), samples)
+ expect(r.session).toEqual({ avg: 110, max: 110 })
+ expect(cleanSamples([[1, 10], [2, 300], [3, 80], { t: 4, bpm: 90 }])).toEqual([[3, 80], [4, 90]])
+ })
+
+ it('gives warm-up and drop sets theirs, a drop set a longer window', () => {
+ const w = workout([set(100, { warmup: true }), set(250, { type: 'drop', drops: [{ w: 40, r: 8 }, { w: 30, r: 8 }] })])
+ const samples = dense(0, 600, x => (x > 250 - 60 && x <= 250 ? 160 : 100))
+ const r = hrFromSamples(w, samples)
+ expect(r.sets.get('0:0').hr.avg).toBe(100)
+ // 24 reps x 3 s = 72 s window: the last 60 s at 160, the 12 before at 100.
+ expect(r.sets.get('0:1').hr.max).toBe(160)
+ expect(r.sets.get('0:1').hr.avg).toBeGreaterThan(140)
+ })
+
+ it('takes both sides of a per-side set as one', () => {
+ const side = { w: 20, r: 8, done: true }
+ const w = workout([{ w: 20, r: 16, done: true, sides: { L: { ...side, at: s(80) }, R: { ...side, at: s(110) } } }])
+ const r = hrFromSamples(w, dense(0, 600, x => (x > 62 && x <= 110 ? 150 : 100)))
+ expect(r.sets.get('0:0').hr.max).toBe(150)
+ })
+
+ it('gives only the session to a workout without ticks, or with ticks caught up all at once', () => {
+ const samples = dense(0, 600, () => 120)
+ const old = workout([{ w: 60, r: 8, done: true }, { w: 60, r: 8, done: true }])
+ expect(hrFromSamples(old, samples).sets.size).toBe(0)
+ expect(hrFromSamples(old, samples).session).toEqual({ avg: 120, max: 120 })
+ const burst = workout([set(590), { ...set(591), at: s(590) + 800 }, { ...set(592), at: s(590) + 1500 }])
+ const r = hrFromSamples(burst, samples)
+ expect(r.sets.get('0:1')?.hr).toBeUndefined()
+ expect(r.sets.get('0:2')?.hr).toBeUndefined()
+ })
+
+ it('gives nothing without a start and an end, or with too few samples', () => {
+ expect(hrFromSamples({ ...workout([set(100)]), end: null }, dense(0, 600, () => 120)).session).toBeNull()
+ expect(hrFromSamples(workout([set(100)]), [[s(100), 120]]).session).toBeNull()
+ })
+})
diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.js
index 2ce700ee8..8be90852a 100644
--- a/frontend/src/lib/pt-br-locale.test.js
+++ b/frontend/src/lib/pt-br-locale.test.js
@@ -41,7 +41,7 @@ describe('Brazilian Portuguese locale', () => {
// has to be taught is a number nobody reads. What the numbers stood for is asserted above.
// If the hash fails, review the changed keys and wording before accepting a new one. From
// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list
- expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('7ec991d955078ae3097c247e0ec238b77782e428630daa6e36d14281bd91d2f3')
+ expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('012fc6927eb89b8760dcac291d0b467be922828007462289e3b43fa130632454')
})
// pt-PT labelled Unpair 'Desfazer': Undo, in Portuguese (it is pt-BR's Undo), on the button that
diff --git a/frontend/src/lib/sync-merge.js b/frontend/src/lib/sync-merge.js
index ffe0664eb..6290217a6 100644
--- a/frontend/src/lib/sync-merge.js
+++ b/frontend/src/lib/sync-merge.js
@@ -169,7 +169,9 @@ export function mergeBodyweight(a = [], b = []) {
for (const e of [...list(a), ...list(b)]) {
if (!e || e.d == null) continue
const cur = byDay.get(e.d)
- if (!cur || (e.t || 0) > (cur.t || 0)) byDay.set(e.d, e)
+ // A weigh-in typed into openGym beats one read from the phone's health hub (`src`, lib/health-read.js)
+ // whichever is newer: the scale's reading is the fallback, never a correction of the user's own.
+ if (!cur || (!!cur.src !== !!e.src ? !e.src : (e.t || 0) > (cur.t || 0))) byDay.set(e.d, e)
}
return [...byDay.values()].sort((x, y) => (x.d < y.d ? -1 : 1))
}
diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.js
index 2618d79ec..692a193d2 100644
--- a/frontend/src/locales/ar.js
+++ b/frontend/src/locales/ar.js
@@ -2055,7 +2055,7 @@ export default {
'Install Health Connect to share workouts and weigh-ins with other apps.': 'ثبّت Health Connect لمشاركة التمارين وقياسات الوزن مع تطبيقات أخرى.',
'Update Health Connect to share workouts and weigh-ins with other apps.': 'حدّث Health Connect لمشاركة التمارين وقياسات الوزن مع تطبيقات أخرى.',
'Permission withdrawn. Tap to allow again': 'تم سحب الإذن — اضغط لمنحه مجددًا',
- 'Workouts and weigh-ins go to Health Connect when you finish or change them. openGym reads nothing back.': 'تذهب التمارين وقياسات الوزن إلى Health Connect عند إنهائها أو تعديلها. لا يقرأ openGym أي شيء منه.',
+ 'Workouts and weigh-ins go to Health Connect when you finish or change them.': 'تذهب التمارين وقياسات الوزن إلى Health Connect عند إنهائها أو تعديلها.',
'Health Connect permission not granted': 'لم يُمنح إذن Health Connect',
'Could not write to Health Connect': 'تعذّرت الكتابة في Health Connect',
'Writing to Health Connect': 'الكتابة في Health Connect مفعّلة',
@@ -2469,4 +2469,10 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'على هذا الجهاز تمرين واحد ليس في هذه النسخة الاحتياطية. الاستبدال يحذفه.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'على هذا الجهاز {0} تمارين ليست في هذه النسخة الاحتياطية. الاستبدال يحذفها.',
+ // --- reading back from Health Connect / Apple Health (v1.4.3) ---
+ 'Heart rate from your watch': 'نبض القلب من ساعتك',
+ 'After a workout, each set gets the heart rate your watch saved. Garmin, Fitbit, Galaxy Watch and friends welcome.': 'بعد التمرين، تحصل كل مجموعة على نبض القلب الذي حفظته ساعتك. أهلًا بـ Garmin وFitbit وGalaxy Watch ورفاقها.',
+ 'Weigh-ins from other apps': 'قياسات الوزن من تطبيقات أخرى',
+ 'Your smart scale’s weigh-ins land here. One you type in yourself always wins.': 'تصل قياسات ميزانك الذكي إلى هنا. القياس الذي تكتبه بنفسك يفوز دائمًا.',
+ 'openGym reads only while it is open: heart rate for workouts of the last day, weigh-ins of the last 30 days. Older workouts stay as they are.': 'يقرأ openGym فقط وهو مفتوح: نبض القلب لتمارين آخر يوم، وقياسات الوزن لآخر 30 يومًا. تبقى التمارين الأقدم كما هي.',
}
diff --git a/frontend/src/locales/bn.js b/frontend/src/locales/bn.js
index 80b006ca5..a4c2c3ada 100644
--- a/frontend/src/locales/bn.js
+++ b/frontend/src/locales/bn.js
@@ -2174,7 +2174,7 @@ export default {
'Install Health Connect to share workouts and weigh-ins with other apps.': 'অন্য অ্যাপের সাথে ওয়ার্কআউট আর ওজন মাপা শেয়ার করতে Health Connect ইনস্টল করুন।',
'Update Health Connect to share workouts and weigh-ins with other apps.': 'অন্য অ্যাপের সাথে ওয়ার্কআউট আর ওজন মাপা শেয়ার করতে Health Connect আপডেট করুন।',
'Permission withdrawn. Tap to allow again': 'অনুমতি তুলে নেওয়া হয়েছে। আবার দিতে ট্যাপ করুন',
- 'Workouts and weigh-ins go to Health Connect when you finish or change them. openGym reads nothing back.': 'ওয়ার্কআউট আর ওজন মাপা শেষ করলে বা বদলালে Health Connect-এ যায়। openGym ওখান থেকে কিছুই পড়ে না।',
+ 'Workouts and weigh-ins go to Health Connect when you finish or change them.': 'ওয়ার্কআউট আর ওজন মাপা শেষ করলে বা বদলালে Health Connect-এ যায়।',
'Health Connect permission not granted': 'Health Connect-এর অনুমতি দেওয়া হয়নি',
'Could not write to Health Connect': 'Health Connect-এ লেখা যায়নি',
'Writing to Health Connect': 'Health Connect-এ লেখা হচ্ছে',
@@ -2493,4 +2493,10 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'এই ডিভাইসে ১টি ওয়ার্কআউট আছে যা এই ব্যাকআপে নেই। প্রতিস্থাপন করলে এটি মুছে যাবে।',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'এই ডিভাইসে {0}টি ওয়ার্কআউট আছে যা এই ব্যাকআপে নেই। প্রতিস্থাপন করলে এগুলো মুছে যাবে।',
+ // --- reading back from Health Connect / Apple Health (v1.4.3) ---
+ 'Heart rate from your watch': 'আপনার ঘড়ি থেকে হার্ট রেট',
+ 'After a workout, each set gets the heart rate your watch saved. Garmin, Fitbit, Galaxy Watch and friends welcome.': 'ওয়ার্কআউটের পরে প্রতিটি সেট পায় আপনার ঘড়ির সেভ করা হার্ট রেট। Garmin, Fitbit, Galaxy Watch সবাইকে স্বাগতম।',
+ 'Weigh-ins from other apps': 'অন্য অ্যাপ থেকে ওজন',
+ 'Your smart scale’s weigh-ins land here. One you type in yourself always wins.': 'আপনার স্মার্ট স্কেলের ওজন এখানে চলে আসে। নিজে লিখলে সেটাই সবসময় জেতে।',
+ 'openGym reads only while it is open: heart rate for workouts of the last day, weigh-ins of the last 30 days. Older workouts stay as they are.': 'openGym শুধু খোলা থাকলেই পড়ে: শেষ এক দিনের ওয়ার্কআউটের হার্ট রেট, শেষ ৩০ দিনের ওজন। পুরোনো ওয়ার্কআউট যেমন আছে তেমনই থাকে।',
}
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index e092e5278..63703a9f1 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -2072,7 +2072,7 @@ export default {
'Install Health Connect to share workouts and weigh-ins with other apps.': 'Installiere Health Connect, um Workouts und Wiegungen mit anderen Apps zu teilen.',
'Update Health Connect to share workouts and weigh-ins with other apps.': 'Aktualisiere Health Connect, um Workouts und Wiegungen mit anderen Apps zu teilen.',
'Permission withdrawn. Tap to allow again': 'Berechtigung entzogen — tippen, um sie erneut zu erteilen',
- 'Workouts and weigh-ins go to Health Connect when you finish or change them. openGym reads nothing back.': 'Workouts und Wiegungen gehen an Health Connect, sobald du sie abschließt oder änderst. openGym liest nichts zurück.',
+ 'Workouts and weigh-ins go to Health Connect when you finish or change them.': 'Workouts und Wiegungen gehen an Health Connect, sobald du sie abschließt oder änderst.',
'Health Connect permission not granted': 'Health-Connect-Berechtigung nicht erteilt',
'Could not write to Health Connect': 'Schreiben in Health Connect fehlgeschlagen',
'Writing to Health Connect': 'Schreibt in Health Connect',
@@ -2434,4 +2434,10 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Auf diesem Gerät ist 1 Training, das nicht in diesem Backup ist. Ersetzen löscht es.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Auf diesem Gerät sind {0} Trainings, die nicht in diesem Backup sind. Ersetzen löscht sie.',
+ // --- reading back from Health Connect / Apple Health (v1.4.3) ---
+ 'Heart rate from your watch': 'Puls von deiner Uhr',
+ 'After a workout, each set gets the heart rate your watch saved. Garmin, Fitbit, Galaxy Watch and friends welcome.': 'Nach dem Training bekommt jeder Satz den Puls, den deine Uhr gespeichert hat. Garmin, Fitbit, Galaxy Watch und Co. willkommen.',
+ 'Weigh-ins from other apps': 'Wiegungen aus anderen Apps',
+ 'Your smart scale’s weigh-ins land here. One you type in yourself always wins.': 'Die Wiegungen deiner smarten Waage landen hier. Was du selbst eintippst, gewinnt immer.',
+ 'openGym reads only while it is open: heart rate for workouts of the last day, weigh-ins of the last 30 days. Older workouts stay as they are.': 'openGym liest nur, solange es offen ist: Puls für Trainings vom letzten Tag, Wiegungen der letzten 30 Tage. Ältere Trainings bleiben, wie sie sind.',
}
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 27517af80..03a659ca8 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -2052,7 +2052,7 @@ export default {
'Install Health Connect to share workouts and weigh-ins with other apps.': 'Instala Health Connect para compartir entrenamientos y pesajes con otras apps.',
'Update Health Connect to share workouts and weigh-ins with other apps.': 'Actualiza Health Connect para compartir entrenamientos y pesajes con otras apps.',
'Permission withdrawn. Tap to allow again': 'Permiso retirado — toca para concederlo de nuevo',
- 'Workouts and weigh-ins go to Health Connect when you finish or change them. openGym reads nothing back.': 'Los entrenamientos y pesajes van a Health Connect al terminarlos o cambiarlos. openGym no lee nada de vuelta.',
+ 'Workouts and weigh-ins go to Health Connect when you finish or change them.': 'Los entrenamientos y pesajes van a Health Connect al terminarlos o cambiarlos.',
'Health Connect permission not granted': 'Permiso de Health Connect no concedido',
'Could not write to Health Connect': 'No se pudo escribir en Health Connect',
'Writing to Health Connect': 'Escribiendo en Health Connect',
@@ -2414,4 +2414,10 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Este dispositivo tiene 1 entrenamiento que no está en esta copia. Reemplazar lo elimina.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Este dispositivo tiene {0} entrenamientos que no están en esta copia. Reemplazar los elimina.',
+ // --- reading back from Health Connect / Apple Health (v1.4.3) ---
+ 'Heart rate from your watch': 'Pulso de tu reloj',
+ 'After a workout, each set gets the heart rate your watch saved. Garmin, Fitbit, Galaxy Watch and friends welcome.': 'Después de entrenar, cada serie recibe el pulso que guardó tu reloj. Garmin, Fitbit, Galaxy Watch y compañía, bienvenidos.',
+ 'Weigh-ins from other apps': 'Pesajes de otras apps',
+ 'Your smart scale’s weigh-ins land here. One you type in yourself always wins.': 'Los pesajes de tu báscula inteligente llegan aquí. El que escribes tú siempre gana.',
+ 'openGym reads only while it is open: heart rate for workouts of the last day, weigh-ins of the last 30 days. Older workouts stay as they are.': 'openGym solo lee mientras está abierto: pulso de los entrenos del último día, pesajes de los últimos 30 días. Los entrenos anteriores se quedan como están.',
}
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index 314f49ae5..55449eb2e 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -2052,7 +2052,7 @@ export default {
'Install Health Connect to share workouts and weigh-ins with other apps.': 'Installez Santé Connect pour partager séances et pesées avec d’autres applis.',
'Update Health Connect to share workouts and weigh-ins with other apps.': 'Mettez à jour Santé Connect pour partager séances et pesées avec d’autres applis.',
'Permission withdrawn. Tap to allow again': 'Autorisation retirée — touchez pour l’accorder à nouveau',
- 'Workouts and weigh-ins go to Health Connect when you finish or change them. openGym reads nothing back.': 'Séances et pesées vont dans Santé Connect quand vous les terminez ou les modifiez. openGym n’y lit rien.',
+ 'Workouts and weigh-ins go to Health Connect when you finish or change them.': 'Séances et pesées vont dans Santé Connect quand vous les terminez ou les modifiez.',
'Health Connect permission not granted': 'Autorisation Santé Connect refusée',
'Could not write to Health Connect': 'Impossible d’écrire dans Santé Connect',
'Writing to Health Connect': 'Écriture dans Santé Connect activée',
@@ -2414,4 +2414,10 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Cet appareil a 1 séance absente de cette sauvegarde. Remplacer la supprime.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Cet appareil a {0} séances absentes de cette sauvegarde. Remplacer les supprime.',
+ // --- reading back from Health Connect / Apple Health (v1.4.3) ---
+ 'Heart rate from your watch': 'Fréquence cardiaque de votre montre',
+ 'After a workout, each set gets the heart rate your watch saved. Garmin, Fitbit, Galaxy Watch and friends welcome.': 'Après une séance, chaque série reçoit la fréquence cardiaque enregistrée par votre montre. Garmin, Fitbit, Galaxy Watch et compagnie bienvenus.',
+ 'Weigh-ins from other apps': 'Pesées d’autres apps',
+ 'Your smart scale’s weigh-ins land here. One you type in yourself always wins.': 'Les pesées de votre balance connectée arrivent ici. Celle que vous saisissez vous-même gagne toujours.',
+ 'openGym reads only while it is open: heart rate for workouts of the last day, weigh-ins of the last 30 days. Older workouts stay as they are.': 'openGym ne lit que lorsqu’il est ouvert : fréquence cardiaque des séances du dernier jour, pesées des 30 derniers jours. Les séances plus anciennes restent telles quelles.',
}
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index 9890c6b8f..d5888e2bf 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -2052,7 +2052,7 @@ export default {
'Install Health Connect to share workouts and weigh-ins with other apps.': 'वर्कआउट और वज़न दूसरे ऐप्स के साथ साझा करने के लिए Health Connect इंस्टॉल करें।',
'Update Health Connect to share workouts and weigh-ins with other apps.': 'वर्कआउट और वज़न दूसरे ऐप्स के साथ साझा करने के लिए Health Connect अपडेट करें।',
'Permission withdrawn. Tap to allow again': 'अनुमति वापस ली गई — फिर से देने के लिए टैप करें',
- 'Workouts and weigh-ins go to Health Connect when you finish or change them. openGym reads nothing back.': 'वर्कआउट और वज़न पूरा करने या बदलने पर Health Connect में जाते हैं। openGym वहाँ से कुछ नहीं पढ़ता।',
+ 'Workouts and weigh-ins go to Health Connect when you finish or change them.': 'वर्कआउट और वज़न पूरा करने या बदलने पर Health Connect में जाते हैं।',
'Health Connect permission not granted': 'Health Connect की अनुमति नहीं मिली',
'Could not write to Health Connect': 'Health Connect में नहीं लिखा जा सका',
'Writing to Health Connect': 'Health Connect में लिखना चालू है',
@@ -2414,4 +2414,10 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'इस डिवाइस पर 1 वर्कआउट है जो इस बैकअप में नहीं है। बदलने से यह मिट जाएगा।',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'इस डिवाइस पर {0} वर्कआउट हैं जो इस बैकअप में नहीं हैं। बदलने से ये मिट जाएँगे।',
+ // --- reading back from Health Connect / Apple Health (v1.4.3) ---
+ 'Heart rate from your watch': 'आपकी घड़ी से धड़कन',
+ 'After a workout, each set gets the heart rate your watch saved. Garmin, Fitbit, Galaxy Watch and friends welcome.': 'वर्कआउट के बाद हर सेट को वह धड़कन मिलती है जो आपकी घड़ी ने सहेजी। Garmin, Fitbit, Galaxy Watch और बाकी सबका स्वागत है।',
+ 'Weigh-ins from other apps': 'दूसरे ऐप्स से वज़न',
+ 'Your smart scale’s weigh-ins land here. One you type in yourself always wins.': 'आपके स्मार्ट स्केल का वज़न यहाँ आ जाता है। जो आप खुद लिखते हैं, वही हमेशा जीतता है।',
+ 'openGym reads only while it is open: heart rate for workouts of the last day, weigh-ins of the last 30 days. Older workouts stay as they are.': 'openGym सिर्फ़ तब पढ़ता है जब वह खुला हो: पिछले एक दिन के वर्कआउट की धड़कन, पिछले 30 दिन का वज़न। पुराने वर्कआउट जैसे हैं वैसे ही रहते हैं।',
}
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index 0b91e9e3c..29df779b5 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -2005,7 +2005,7 @@ export default {
'Install Health Connect to share workouts and weigh-ins with other apps.': 'Telepítsd a Health Connectet, hogy megoszthasd az edzéseket és mérlegeléseket más appokkal.',
'Update Health Connect to share workouts and weigh-ins with other apps.': 'Frissítsd a Health Connectet, hogy megoszthasd az edzéseket és mérlegeléseket más appokkal.',
'Permission withdrawn. Tap to allow again': 'Engedély visszavonva — koppints az újbóli megadáshoz',
- 'Workouts and weigh-ins go to Health Connect when you finish or change them. openGym reads nothing back.': 'Az edzések és mérlegelések a befejezésükkor vagy módosításukkor a Health Connectbe kerülnek. Az openGym semmit nem olvas vissza.',
+ 'Workouts and weigh-ins go to Health Connect when you finish or change them.': 'Az edzések és mérlegelések a befejezésükkor vagy módosításukkor a Health Connectbe kerülnek.',
'Health Connect permission not granted': 'A Health Connect engedély nincs megadva',
'Could not write to Health Connect': 'Nem sikerült írni a Health Connectbe',
'Writing to Health Connect': 'Írás a Health Connectbe bekapcsolva',
@@ -2417,4 +2417,10 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Ezen az eszközön 1 edzés van, amely nincs ebben a mentésben. A csere törli.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Ezen az eszközön {0} edzés van, amely nincs ebben a mentésben. A csere törli őket.',
+ // --- reading back from Health Connect / Apple Health (v1.4.3) ---
+ 'Heart rate from your watch': 'Pulzus az órádról',
+ 'After a workout, each set gets the heart rate your watch saved. Garmin, Fitbit, Galaxy Watch and friends welcome.': 'Edzés után minden sorozat megkapja a pulzust, amit az órád elmentett. Garmin, Fitbit, Galaxy Watch és társaik szívesen látottak.',
+ 'Weigh-ins from other apps': 'Mérlegelések más appokból',
+ 'Your smart scale’s weigh-ins land here. One you type in yourself always wins.': 'Az okosmérleged mérései ide érkeznek. Amit te magad írsz be, az mindig nyer.',
+ 'openGym reads only while it is open: heart rate for workouts of the last day, weigh-ins of the last 30 days. Older workouts stay as they are.': 'Az openGym csak nyitott állapotban olvas: az utolsó nap edzéseinek pulzusát és az utolsó 30 nap mérlegeléseit. A régebbi edzések maradnak, ahogy vannak.',
}
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index 2a694f890..50e239be7 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -2052,7 +2052,7 @@ export default {
'Install Health Connect to share workouts and weigh-ins with other apps.': 'Installa Connessione Salute per condividere allenamenti e pesate con altre app.',
'Update Health Connect to share workouts and weigh-ins with other apps.': 'Aggiorna Connessione Salute per condividere allenamenti e pesate con altre app.',
'Permission withdrawn. Tap to allow again': 'Permesso revocato — tocca per concederlo di nuovo',
- 'Workouts and weigh-ins go to Health Connect when you finish or change them. openGym reads nothing back.': 'Allenamenti e pesate vanno in Connessione Salute quando li concludi o li modifichi. openGym non legge nulla.',
+ 'Workouts and weigh-ins go to Health Connect when you finish or change them.': 'Allenamenti e pesate vanno in Connessione Salute quando li concludi o li modifichi.',
'Health Connect permission not granted': 'Permesso di Connessione Salute non concesso',
'Could not write to Health Connect': 'Impossibile scrivere in Connessione Salute',
'Writing to Health Connect': 'Scrittura in Connessione Salute attiva',
@@ -2414,4 +2414,10 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Su questo dispositivo c’è 1 allenamento che non è in questo backup. Sostituire lo elimina.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Su questo dispositivo ci sono {0} allenamenti che non sono in questo backup. Sostituire li elimina.',
+ // --- reading back from Health Connect / Apple Health (v1.4.3) ---
+ 'Heart rate from your watch': 'Battito dal tuo orologio',
+ 'After a workout, each set gets the heart rate your watch saved. Garmin, Fitbit, Galaxy Watch and friends welcome.': 'Dopo l’allenamento ogni serie riceve il battito salvato dal tuo orologio. Garmin, Fitbit, Galaxy Watch e compagnia benvenuti.',
+ 'Weigh-ins from other apps': 'Pesate da altre app',
+ 'Your smart scale’s weigh-ins land here. One you type in yourself always wins.': 'Le pesate della tua bilancia smart arrivano qui. Quella che inserisci tu vince sempre.',
+ 'openGym reads only while it is open: heart rate for workouts of the last day, weigh-ins of the last 30 days. Older workouts stay as they are.': 'openGym legge solo mentre è aperto: battito degli allenamenti dell’ultimo giorno, pesate degli ultimi 30 giorni. Gli allenamenti più vecchi restano come sono.',
}
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index d1d796aec..cf7206c60 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -2052,7 +2052,7 @@ export default {
'Install Health Connect to share workouts and weigh-ins with other apps.': '운동과 체중 기록을 다른 앱과 공유하려면 헬스 커넥트를 설치하세요.',
'Update Health Connect to share workouts and weigh-ins with other apps.': '운동과 체중 기록을 다른 앱과 공유하려면 헬스 커넥트를 업데이트하세요.',
'Permission withdrawn. Tap to allow again': '권한이 철회됨 — 다시 허용하려면 탭하세요',
- 'Workouts and weigh-ins go to Health Connect when you finish or change them. openGym reads nothing back.': '운동과 체중 기록은 완료하거나 수정할 때 헬스 커넥트로 갑니다. openGym은 아무것도 읽어 오지 않습니다.',
+ 'Workouts and weigh-ins go to Health Connect when you finish or change them.': '운동과 체중 기록은 완료하거나 수정할 때 헬스 커넥트로 갑니다.',
'Health Connect permission not granted': '헬스 커넥트 권한이 허용되지 않음',
'Could not write to Health Connect': '헬스 커넥트에 기록할 수 없음',
'Writing to Health Connect': '헬스 커넥트에 기록 중',
@@ -2414,4 +2414,10 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': '이 기기에 이 백업에 없는 운동이 1개 있습니다. 바꾸면 삭제됩니다.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': '이 기기에 이 백업에 없는 운동이 {0}개 있습니다. 바꾸면 삭제됩니다.',
+ // --- reading back from Health Connect / Apple Health (v1.4.3) ---
+ 'Heart rate from your watch': '워치의 심박수',
+ 'After a workout, each set gets the heart rate your watch saved. Garmin, Fitbit, Galaxy Watch and friends welcome.': '운동이 끝나면 각 세트에 워치가 저장한 심박수가 들어가요. Garmin, Fitbit, Galaxy Watch 다 환영해요.',
+ 'Weigh-ins from other apps': '다른 앱의 체중 기록',
+ 'Your smart scale’s weigh-ins land here. One you type in yourself always wins.': '스마트 체중계의 기록이 여기로 와요. 직접 입력한 기록이 항상 이겨요.',
+ 'openGym reads only while it is open: heart rate for workouts of the last day, weigh-ins of the last 30 days. Older workouts stay as they are.': 'openGym은 열려 있을 때만 읽어요: 최근 하루 동안의 운동 심박수와 최근 30일의 체중 기록. 그보다 오래된 운동은 그대로 둬요.',
}
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index 2188107d2..4f40058e1 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -2052,7 +2052,7 @@ export default {
'Install Health Connect to share workouts and weigh-ins with other apps.': 'Zainstaluj Health Connect, aby udostępniać treningi i pomiary wagi innym aplikacjom.',
'Update Health Connect to share workouts and weigh-ins with other apps.': 'Zaktualizuj Health Connect, aby udostępniać treningi i pomiary wagi innym aplikacjom.',
'Permission withdrawn. Tap to allow again': 'Uprawnienie cofnięte — dotknij, aby przyznać ponownie',
- 'Workouts and weigh-ins go to Health Connect when you finish or change them. openGym reads nothing back.': 'Treningi i pomiary wagi trafiają do Health Connect, gdy je kończysz lub zmieniasz. openGym niczego stamtąd nie odczytuje.',
+ 'Workouts and weigh-ins go to Health Connect when you finish or change them.': 'Treningi i pomiary wagi trafiają do Health Connect, gdy je kończysz lub zmieniasz.',
'Health Connect permission not granted': 'Nie przyznano uprawnienia Health Connect',
'Could not write to Health Connect': 'Nie udało się zapisać w Health Connect',
'Writing to Health Connect': 'Zapisywanie w Health Connect włączone',
@@ -2414,4 +2414,10 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Na tym urządzeniu jest 1 trening, którego nie ma w tej kopii. Zastąpienie danych go usunie.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Na tym urządzeniu są treningi, których nie ma w tej kopii ({0}). Zastąpienie danych je usunie.',
+ // --- reading back from Health Connect / Apple Health (v1.4.3) ---
+ 'Heart rate from your watch': 'Tętno z zegarka',
+ 'After a workout, each set gets the heart rate your watch saved. Garmin, Fitbit, Galaxy Watch and friends welcome.': 'Po treningu każda seria dostaje tętno zapisane przez zegarek. Garmin, Fitbit, Galaxy Watch i spółka mile widziani.',
+ 'Weigh-ins from other apps': 'Pomiary wagi z innych aplikacji',
+ 'Your smart scale’s weigh-ins land here. One you type in yourself always wins.': 'Pomiary z twojej inteligentnej wagi trafiają tutaj. Ten wpisany ręcznie zawsze wygrywa.',
+ 'openGym reads only while it is open: heart rate for workouts of the last day, weigh-ins of the last 30 days. Older workouts stay as they are.': 'openGym czyta tylko, gdy jest otwarty: tętno z treningów z ostatniej doby, pomiary wagi z ostatnich 30 dni. Starsze treningi zostają bez zmian.',
}
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index 8722ba9e7..48bcd748d 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -1260,7 +1260,7 @@ export const PT_BR_OVERRIDES = {
'Install Health Connect to share workouts and weigh-ins with other apps.': 'Instale o Conexão Saúde para compartilhar treinos e pesagens com outros apps.',
'Update Health Connect to share workouts and weigh-ins with other apps.': 'Atualize o Conexão Saúde para compartilhar treinos e pesagens com outros apps.',
'Permission withdrawn. Tap to allow again': 'Permissão retirada — toque para conceder de novo',
- 'Workouts and weigh-ins go to Health Connect when you finish or change them. openGym reads nothing back.': 'Treinos e pesagens vão para o Conexão Saúde quando você os conclui ou altera. O openGym não lê nada de volta.',
+ 'Workouts and weigh-ins go to Health Connect when you finish or change them.': 'Treinos e pesagens vão para o Conexão Saúde quando você os conclui ou altera.',
'Health Connect permission not granted': 'Permissão do Conexão Saúde não concedida',
'Could not write to Health Connect': 'Não foi possível gravar no Conexão Saúde',
'Writing to Health Connect': 'Gravando no Conexão Saúde',
@@ -1535,6 +1535,10 @@ export const PT_BR_OVERRIDES = {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Este dispositivo tem 1 treino que não está neste backup. Substituir exclui esse treino.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Este dispositivo tem {0} treinos que não estão neste backup. Substituir exclui esses treinos.',
+ // --- reading back from Health Connect / Apple Health (v1.4.3) ---
+ 'After a workout, each set gets the heart rate your watch saved. Garmin, Fitbit, Galaxy Watch and friends welcome.': 'Depois do treino, cada série recebe a frequência cardíaca que seu relógio salvou. Garmin, Fitbit, Galaxy Watch e companhia são bem-vindos.',
+ 'Weigh-ins from other apps': 'Pesagens de outros aplicativos',
+ 'Your smart scale’s weigh-ins land here. One you type in yourself always wins.': 'As pesagens da sua balança inteligente chegam aqui. A que você digitar sempre ganha.',
}
export default { ...pt, ...PT_BR_OVERRIDES }
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index ed106827d..957e55d45 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -2052,7 +2052,7 @@ export default {
'Install Health Connect to share workouts and weigh-ins with other apps.': 'Instale o Health Connect para partilhar treinos e pesagens com outras apps.',
'Update Health Connect to share workouts and weigh-ins with other apps.': 'Atualize o Health Connect para partilhar treinos e pesagens com outras apps.',
'Permission withdrawn. Tap to allow again': 'Permissão retirada — toque para a conceder de novo',
- 'Workouts and weigh-ins go to Health Connect when you finish or change them. openGym reads nothing back.': 'Treinos e pesagens vão para o Health Connect quando os termina ou altera. O openGym não lê nada de volta.',
+ 'Workouts and weigh-ins go to Health Connect when you finish or change them.': 'Treinos e pesagens vão para o Health Connect quando os termina ou altera.',
'Health Connect permission not granted': 'Permissão do Health Connect não concedida',
'Could not write to Health Connect': 'Não foi possível escrever no Health Connect',
'Writing to Health Connect': 'A escrever no Health Connect',
@@ -2414,4 +2414,10 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Este dispositivo tem 1 treino que não está nesta cópia. Substituir elimina-o.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Este dispositivo tem {0} treinos que não estão nesta cópia. Substituir elimina-os.',
+ // --- reading back from Health Connect / Apple Health (v1.4.3) ---
+ 'Heart rate from your watch': 'Frequência cardíaca do relógio',
+ 'After a workout, each set gets the heart rate your watch saved. Garmin, Fitbit, Galaxy Watch and friends welcome.': 'Depois do treino, cada série recebe a frequência cardíaca que o relógio guardou. Garmin, Fitbit, Galaxy Watch e companhia são bem-vindos.',
+ 'Weigh-ins from other apps': 'Pesagens de outras apps',
+ 'Your smart scale’s weigh-ins land here. One you type in yourself always wins.': 'As pesagens da balança inteligente chegam aqui. A que escrever à mão ganha sempre.',
+ 'openGym reads only while it is open: heart rate for workouts of the last day, weigh-ins of the last 30 days. Older workouts stay as they are.': 'O openGym só lê enquanto está aberto: frequência cardíaca dos treinos do último dia, pesagens dos últimos 30 dias. Os treinos mais antigos ficam como estão.',
}
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index c3bfc0ddb..58bc13c74 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -2056,7 +2056,7 @@ export default {
'Install Health Connect to share workouts and weigh-ins with other apps.': 'Установите Health Connect, чтобы делиться тренировками и взвешиваниями с другими приложениями.',
'Update Health Connect to share workouts and weigh-ins with other apps.': 'Обновите Health Connect, чтобы делиться тренировками и взвешиваниями с другими приложениями.',
'Permission withdrawn. Tap to allow again': 'Разрешение отозвано — нажмите, чтобы выдать снова',
- 'Workouts and weigh-ins go to Health Connect when you finish or change them. openGym reads nothing back.': 'Тренировки и взвешивания попадают в Health Connect, когда вы их завершаете или меняете. openGym ничего оттуда не читает.',
+ 'Workouts and weigh-ins go to Health Connect when you finish or change them.': 'Тренировки и взвешивания попадают в Health Connect, когда вы их завершаете или меняете.',
'Health Connect permission not granted': 'Разрешение Health Connect не выдано',
'Could not write to Health Connect': 'Не удалось записать в Health Connect',
'Writing to Health Connect': 'Запись в Health Connect включена',
@@ -2418,4 +2418,10 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'На этом устройстве есть 1 тренировка, которой нет в этой копии. Замена её удалит.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'На этом устройстве есть тренировки, которых нет в этой копии ({0}). Замена их удалит.',
+ // --- reading back from Health Connect / Apple Health (v1.4.3) ---
+ 'Heart rate from your watch': 'Пульс с ваших часов',
+ 'After a workout, each set gets the heart rate your watch saved. Garmin, Fitbit, Galaxy Watch and friends welcome.': 'После тренировки каждый подход получает пульс, который сохранили ваши часы. Garmin, Fitbit, Galaxy Watch и компания, добро пожаловать.',
+ 'Weigh-ins from other apps': 'Взвешивания из других приложений',
+ 'Your smart scale’s weigh-ins land here. One you type in yourself always wins.': 'Взвешивания с ваших умных весов попадают сюда. Введённое вручную всегда побеждает.',
+ 'openGym reads only while it is open: heart rate for workouts of the last day, weigh-ins of the last 30 days. Older workouts stay as they are.': 'openGym читает данные, только пока открыт: пульс тренировок за последние сутки, взвешивания за последние 30 дней. Старые тренировки остаются как есть.',
}
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index b75bf9b03..ae06f9ef8 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -2013,7 +2013,7 @@ export default {
'Install Health Connect to share workouts and weigh-ins with other apps.': 'ติดตั้ง Health Connect เพื่อแชร์การออกกำลังกายและการชั่งน้ำหนักกับแอปอื่น',
'Update Health Connect to share workouts and weigh-ins with other apps.': 'อัปเดต Health Connect เพื่อแชร์การออกกำลังกายและการชั่งน้ำหนักกับแอปอื่น',
'Permission withdrawn. Tap to allow again': 'สิทธิ์ถูกเพิกถอน — แตะเพื่ออนุญาตอีกครั้ง',
- 'Workouts and weigh-ins go to Health Connect when you finish or change them. openGym reads nothing back.': 'การออกกำลังกายและการชั่งน้ำหนักจะไปที่ Health Connect เมื่อคุณทำเสร็จหรือแก้ไข openGym ไม่อ่านอะไรกลับมา',
+ 'Workouts and weigh-ins go to Health Connect when you finish or change them.': 'การออกกำลังกายและการชั่งน้ำหนักจะไปที่ Health Connect เมื่อคุณทำเสร็จหรือแก้ไข',
'Health Connect permission not granted': 'ไม่ได้รับสิทธิ์ Health Connect',
'Could not write to Health Connect': 'เขียนลงใน Health Connect ไม่ได้',
'Writing to Health Connect': 'กำลังเขียนลงใน Health Connect',
@@ -2425,4 +2425,10 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'อุปกรณ์นี้มีการออกกำลังกาย 1 รายการที่ไม่อยู่ในข้อมูลสำรองนี้ การแทนที่จะลบรายการนั้น',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'อุปกรณ์นี้มีการออกกำลังกาย {0} รายการที่ไม่อยู่ในข้อมูลสำรองนี้ การแทนที่จะลบรายการเหล่านั้น',
+ // --- reading back from Health Connect / Apple Health (v1.4.3) ---
+ 'Heart rate from your watch': 'อัตราการเต้นของหัวใจจากนาฬิกา',
+ 'After a workout, each set gets the heart rate your watch saved. Garmin, Fitbit, Galaxy Watch and friends welcome.': 'หลังฝึก แต่ละเซ็ตจะได้อัตราการเต้นของหัวใจที่นาฬิกาบันทึกไว้ ยินดีต้อนรับ Garmin, Fitbit, Galaxy Watch และเพื่อน ๆ',
+ 'Weigh-ins from other apps': 'การชั่งน้ำหนักจากแอปอื่น',
+ 'Your smart scale’s weigh-ins land here. One you type in yourself always wins.': 'น้ำหนักจากเครื่องชั่งอัจฉริยะของคุณจะมาอยู่ที่นี่ ค่าที่คุณพิมพ์เองชนะเสมอ',
+ 'openGym reads only while it is open: heart rate for workouts of the last day, weigh-ins of the last 30 days. Older workouts stay as they are.': 'openGym อ่านเฉพาะตอนที่เปิดอยู่: อัตราการเต้นของหัวใจของการฝึกในวันล่าสุด และน้ำหนักใน 30 วันล่าสุด การฝึกที่เก่ากว่านั้นจะเหมือนเดิม',
}
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index dad1e4041..3f5e79a92 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -2052,7 +2052,7 @@ export default {
'Install Health Connect to share workouts and weigh-ins with other apps.': 'Antrenmanları ve tartılmaları diğer uygulamalarla paylaşmak için Health Connect’i yükleyin.',
'Update Health Connect to share workouts and weigh-ins with other apps.': 'Antrenmanları ve tartılmaları diğer uygulamalarla paylaşmak için Health Connect’i güncelleyin.',
'Permission withdrawn. Tap to allow again': 'İzin geri alındı — yeniden vermek için dokunun',
- 'Workouts and weigh-ins go to Health Connect when you finish or change them. openGym reads nothing back.': 'Antrenmanlar ve tartılmalar, bitirdiğinizde veya değiştirdiğinizde Health Connect’e gider. openGym oradan hiçbir şey okumaz.',
+ 'Workouts and weigh-ins go to Health Connect when you finish or change them.': 'Antrenmanlar ve tartılmalar, bitirdiğinizde veya değiştirdiğinizde Health Connect’e gider.',
'Health Connect permission not granted': 'Health Connect izni verilmedi',
'Could not write to Health Connect': 'Health Connect’e yazılamadı',
'Writing to Health Connect': 'Health Connect’e yazılıyor',
@@ -2414,4 +2414,10 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Bu cihazda bu yedekte olmayan 1 antrenman var. Değiştirmek onu siler.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Bu cihazda bu yedekte olmayan {0} antrenman var. Değiştirmek onları siler.',
+ // --- reading back from Health Connect / Apple Health (v1.4.3) ---
+ 'Heart rate from your watch': 'Saatinizden nabız',
+ 'After a workout, each set gets the heart rate your watch saved. Garmin, Fitbit, Galaxy Watch and friends welcome.': 'Antrenmandan sonra her set, saatinizin kaydettiği nabzı alır. Garmin, Fitbit, Galaxy Watch ve diğerleri, hoş geldiniz.',
+ 'Weigh-ins from other apps': 'Diğer uygulamalardan tartılmalar',
+ 'Your smart scale’s weigh-ins land here. One you type in yourself always wins.': 'Akıllı tartınızın ölçümleri buraya gelir. Kendi yazdığınız her zaman kazanır.',
+ 'openGym reads only while it is open: heart rate for workouts of the last day, weigh-ins of the last 30 days. Older workouts stay as they are.': 'openGym yalnızca açıkken okur: son bir günün antrenmanları için nabız, son 30 günün tartılmaları. Daha eski antrenmanlar olduğu gibi kalır.',
}
diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.js
index 90e0836d8..cbf180cbe 100644
--- a/frontend/src/locales/uk.js
+++ b/frontend/src/locales/uk.js
@@ -1997,7 +1997,7 @@ export default {
'Install Health Connect to share workouts and weigh-ins with other apps.': 'Установіть Health Connect, щоб ділитися тренуваннями та зважуваннями з іншими застосунками.',
'Update Health Connect to share workouts and weigh-ins with other apps.': 'Оновіть Health Connect, щоб ділитися тренуваннями та зважуваннями з іншими застосунками.',
'Permission withdrawn. Tap to allow again': 'Дозвіл відкликано — торкніться, щоб надати знову',
- 'Workouts and weigh-ins go to Health Connect when you finish or change them. openGym reads nothing back.': 'Тренування та зважування потрапляють до Health Connect, коли ви їх завершуєте або змінюєте. openGym нічого звідти не читає.',
+ 'Workouts and weigh-ins go to Health Connect when you finish or change them.': 'Тренування та зважування потрапляють до Health Connect, коли ви їх завершуєте або змінюєте.',
'Health Connect permission not granted': 'Дозвіл Health Connect не надано',
'Could not write to Health Connect': 'Не вдалося записати в Health Connect',
'Writing to Health Connect': 'Запис у Health Connect увімкнено',
@@ -2411,4 +2411,10 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'На цьому пристрої є 1 тренування, якого немає в цій копії. Заміна його видалить.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'На цьому пристрої є тренування, яких немає в цій копії ({0}). Заміна їх видалить.',
+ // --- reading back from Health Connect / Apple Health (v1.4.3) ---
+ 'Heart rate from your watch': 'Пульс із вашого годинника',
+ 'After a workout, each set gets the heart rate your watch saved. Garmin, Fitbit, Galaxy Watch and friends welcome.': 'Після тренування кожен підхід отримує пульс, який зберіг ваш годинник. Garmin, Fitbit, Galaxy Watch і компанія, ласкаво просимо.',
+ 'Weigh-ins from other apps': 'Зважування з інших застосунків',
+ 'Your smart scale’s weigh-ins land here. One you type in yourself always wins.': 'Зважування з ваших розумних ваг потрапляють сюди. Введене вручну завжди перемагає.',
+ 'openGym reads only while it is open: heart rate for workouts of the last day, weigh-ins of the last 30 days. Older workouts stay as they are.': 'openGym читає дані, лише поки відкритий: пульс тренувань за останню добу, зважування за останні 30 днів. Старіші тренування лишаються як є.',
}
diff --git a/frontend/src/locales/zh-TW.js b/frontend/src/locales/zh-TW.js
index 5077a4e61..6938b142c 100644
--- a/frontend/src/locales/zh-TW.js
+++ b/frontend/src/locales/zh-TW.js
@@ -2068,7 +2068,7 @@ export default {
'Install Health Connect to share workouts and weigh-ins with other apps.': '請安裝 Health Connect,才能與其他 App 分享訓練和體重紀錄。',
'Update Health Connect to share workouts and weigh-ins with other apps.': '請更新 Health Connect,才能與其他 App 分享訓練和體重紀錄。',
'Permission withdrawn. Tap to allow again': '權限已被撤回。點一下重新允許',
- 'Workouts and weigh-ins go to Health Connect when you finish or change them. openGym reads nothing back.': '訓練與體重紀錄會在你完成或修改時寫入 Health Connect。openGym 不會讀取任何資料。',
+ 'Workouts and weigh-ins go to Health Connect when you finish or change them.': '訓練與體重紀錄會在你完成或修改時寫入 Health Connect。',
'Health Connect permission not granted': '未授予 Health Connect 權限',
'Could not write to Health Connect': '無法寫入 Health Connect',
'Writing to Health Connect': '正在寫入 Health Connect',
@@ -2407,4 +2407,10 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': '此裝置上有 1 筆訓練紀錄不在此備份中。覆蓋將會刪除它。',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': '此裝置上有 {0} 筆訓練紀錄不在此備份中。覆蓋將會將其全數刪除。',
+ // --- reading back from Health Connect / Apple Health (v1.4.3) ---
+ 'Heart rate from your watch': '來自手錶的心率',
+ 'After a workout, each set gets the heart rate your watch saved. Garmin, Fitbit, Galaxy Watch and friends welcome.': '訓練結束後,每組都會得到手錶儲存的心率。Garmin、Fitbit、Galaxy Watch 等等都歡迎。',
+ 'Weigh-ins from other apps': '來自其他 App 的體重紀錄',
+ 'Your smart scale’s weigh-ins land here. One you type in yourself always wins.': '智慧體重計的紀錄會出現在這裡。你自己輸入的永遠優先。',
+ 'openGym reads only while it is open: heart rate for workouts of the last day, weigh-ins of the last 30 days. Older workouts stay as they are.': 'openGym 只在開啟時讀取:最近一天訓練的心率,最近 30 天的體重紀錄。更早的訓練維持不變。',
}
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index 7857c181c..3e4eb4495 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -2052,7 +2052,7 @@ export default {
'Install Health Connect to share workouts and weigh-ins with other apps.': '安装 Health Connect,即可与其他应用共享训练和称重。',
'Update Health Connect to share workouts and weigh-ins with other apps.': '更新 Health Connect,即可与其他应用共享训练和称重。',
'Permission withdrawn. Tap to allow again': '权限已撤销 — 轻触重新授予',
- 'Workouts and weigh-ins go to Health Connect when you finish or change them. openGym reads nothing back.': '训练和称重在你完成或修改时写入 Health Connect。openGym 不会从中读取任何内容。',
+ 'Workouts and weigh-ins go to Health Connect when you finish or change them.': '训练和称重在你完成或修改时写入 Health Connect。',
'Health Connect permission not granted': '未授予 Health Connect 权限',
'Could not write to Health Connect': '无法写入 Health Connect',
'Writing to Health Connect': '正在写入 Health Connect',
@@ -2414,4 +2414,10 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': '此设备上有 1 次训练不在此备份中。替换会删除它。',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': '此设备上有 {0} 次训练不在此备份中。替换会删除它们。',
+ // --- reading back from Health Connect / Apple Health (v1.4.3) ---
+ 'Heart rate from your watch': '来自手表的心率',
+ 'After a workout, each set gets the heart rate your watch saved. Garmin, Fitbit, Galaxy Watch and friends welcome.': '训练结束后,每组都会得到手表保存的心率。Garmin、Fitbit、Galaxy Watch 等等都欢迎。',
+ 'Weigh-ins from other apps': '来自其他应用的称重',
+ 'Your smart scale’s weigh-ins land here. One you type in yourself always wins.': '智能体重秤的称重会出现在这里。你自己输入的永远优先。',
+ 'openGym reads only while it is open: heart rate for workouts of the last day, weigh-ins of the last 30 days. Older workouts stay as they are.': 'openGym 只在打开时读取:最近一天训练的心率,最近 30 天的称重。更早的训练保持不变。',
}
diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx
index 0ee471643..5a5458f6c 100644
--- a/frontend/src/sheets.jsx
+++ b/frontend/src/sheets.jsx
@@ -309,7 +309,7 @@ function BwSheet({ required, onDone, close }) {
if (date !== todayISO() && st.bodyweight.some(b => b.d === date)) { toast(t('That date already has a weigh-in. Delete it first.')); return }
update(s => {
const ex = s.bodyweight.find(b => b.d === date)
- if (ex) { ex.w = n; ex.t = Date.now() } else s.bodyweight.push({ d: date, w: n, t: Date.now() })
+ if (ex) { ex.w = n; ex.t = Date.now(); delete ex.src } else s.bodyweight.push({ d: date, w: n, t: Date.now() })
s.bodyweight.sort((a, b) => (a.d < b.d ? -1 : 1))
})
close()
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js
index b5f54be7e..99a1c9f9a 100644
--- a/frontend/src/store/useStore.js
+++ b/frontend/src/store/useStore.js
@@ -7,7 +7,7 @@ import { DEMO, DEMO_SEEDED } from '../lib/demo.js'
import { rememberDefaultLang } from '../lib/default-lang.js'
import { guestAllowed } from '../lib/guest.js'
import { MOBILE, initReminderSync, nativeLoad, nativeSave, onAppActive, readJsonFile, syncReminder, writeAutoBackup, writeJsonFile } from '../lib/mobile.js'
-import { initHealthSync, syncHealth } from '../lib/health-sync.js'
+import { initHealthSync, syncHealth, readHealth } from '../lib/health-sync.js'
import { refillIfComplete } from '../lib/rotation.js'
import { liftLegacy } from '../lib/sync-legacy.js'
import { mergeStates, localExtras, stampChange, highestStamp, stampRestore, stampReplace, inUnitOf, keepReset, resetIdsOf, mergeResetIds, entryKey } from '../lib/sync-merge.js'
@@ -477,7 +477,8 @@ export const useStore = create((set, get) => {
}
initReminderSync(() => get().S)
- initHealthSync(() => get().S)
+ // What it reads back from the health hub (heart rate, weigh-ins) goes in as any change does.
+ initHealthSync(() => get().S, fn => get().update(fn))
// Mobile build: the file mirror, and beside it whose copy it is and which one (its `_ts`) —
// restoreFromMirror takes the file back only for that account, and only while the two agree,
@@ -497,7 +498,7 @@ export const useStore = create((set, get) => {
const nativePersist = (now = false) => {
clearTimeout(saveTm)
saveTm = null
- const write = () => { saveTm = null; syncReminder(get().S); syncHealth(get().S).catch(() => {}); return saveMirror() }
+ const write = () => { saveTm = null; syncReminder(get().S); syncHealth(get().S).catch(() => {}); readHealth(() => get().S).catch(() => {}); return saveMirror() }
if (now) return write()
saveTm = setTimeout(write, 800)
return null
diff --git a/frontend/src/views/Settings.health.test.jsx b/frontend/src/views/Settings.health.test.jsx
index e66af4ad6..e35dcc27f 100644
--- a/frontend/src/views/Settings.health.test.jsx
+++ b/frontend/src/views/Settings.health.test.jsx
@@ -19,6 +19,13 @@ const mocks = vi.hoisted(() => {
state.enableHealth = vi.fn(async () => { state.health = { ...state.health, on: true }; return { ok: true, health: state.health } })
state.disableHealth = vi.fn(async ({ removeWritten }) => { state.health = { ...state.health, on: false, written: removeWritten ? {} : state.health.written }; return state.health })
state.openHealthConnect = vi.fn(async () => {})
+ state.readGrant = true
+ state.enableRead = vi.fn(async kind => {
+ if (!state.readGrant) return { ok: false, reason: 'denied' }
+ state.health = { ...state.health, [kind === 'hr' ? 'readHr' : 'readWeight']: true }
+ return { ok: true, health: state.health }
+ })
+ state.disableRead = vi.fn(async kind => { state.health = { ...state.health, [kind === 'hr' ? 'readHr' : 'readWeight']: false }; return state.health })
state.menuSheet = vi.fn()
state.toast = vi.fn()
return state
@@ -51,6 +58,8 @@ vi.mock('../lib/health-sync.js', () => ({
disableHealth: (...a) => mocks.disableHealth(...a),
openHealthConnect: (...a) => mocks.openHealthConnect(...a),
onHealthChange: () => () => {},
+ enableRead: (...a) => mocks.enableRead(...a),
+ disableRead: (...a) => mocks.disableRead(...a),
}))
vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
vi.mock('../sheets.jsx', () => ({
@@ -67,7 +76,8 @@ beforeEach(() => {
mocks.android = true
mocks.status = { status: 'available', granted: false }
mocks.health = { on: false, written: {}, error: null }
- for (const k of ['enableHealth', 'disableHealth', 'openHealthConnect', 'menuSheet', 'toast']) mocks[k].mockClear()
+ mocks.readGrant = true
+ for (const k of ['enableHealth', 'disableHealth', 'openHealthConnect', 'menuSheet', 'toast', 'enableRead', 'disableRead']) mocks[k].mockClear()
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
@@ -166,3 +176,48 @@ describe('Settings — Apple Health', () => {
expect(appleSwitch()).toBeUndefined()
})
})
+
+// v1.4.3: reading heart rate and weigh-ins back, each its own switch, independent of writing.
+describe('Settings — reading back', () => {
+ const sw = text => row(text)?.querySelector('[role="switch"]')
+
+ it('offers both reads, off, next to the write switch on Android and iPhone', async () => {
+ await mount()
+ expect(sw('Heart rate from your watch').getAttribute('aria-checked')).toBe('false')
+ expect(sw('Weigh-ins from other apps').getAttribute('aria-checked')).toBe('false')
+ mocks.android = false
+ mocks.status = { status: 'available', granted: false, platform: 'ios' }
+ await mount()
+ expect(sw('Heart rate from your watch')).toBeTruthy()
+ })
+
+ it('turns one on without the write switch and without the other read', async () => {
+ await mount()
+ await act(async () => { sw('Heart rate from your watch').click() })
+ expect(mocks.enableRead).toHaveBeenCalledWith('hr', expect.any(Function))
+ expect(sw('Heart rate from your watch').getAttribute('aria-checked')).toBe('true')
+ expect(sw('Weigh-ins from other apps').getAttribute('aria-checked')).toBe('false')
+ expect(writeSwitch().getAttribute('aria-checked')).toBe('false')
+ expect(mocks.enableHealth).not.toHaveBeenCalled()
+ expect(host.textContent).toContain('openGym reads only while it is open')
+ expect(row('Open Health Connect')).toBeTruthy()
+ })
+
+ it('says so when the permission was not granted', async () => {
+ mocks.readGrant = false
+ await mount()
+ await act(async () => { sw('Weigh-ins from other apps').click() })
+ expect(mocks.toast).toHaveBeenCalledWith('Health Connect permission not granted')
+ expect(sw('Weigh-ins from other apps').getAttribute('aria-checked')).toBe('false')
+ })
+
+ it('turns off without asking, and offers to ask again after a withdrawn permission', async () => {
+ mocks.health = { on: false, written: {}, error: null, readWeight: true, readError: 'permission' }
+ await mount()
+ await act(async () => { row('Permission withdrawn').click() })
+ expect(mocks.enableRead).toHaveBeenCalledWith('weight', expect.any(Function))
+ await act(async () => { sw('Weigh-ins from other apps').click() })
+ expect(mocks.disableRead).toHaveBeenCalledWith('weight')
+ expect(mocks.menuSheet).not.toHaveBeenCalled()
+ })
+})
diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx
index 23ccc5958..c15ab88f5 100644
--- a/frontend/src/views/Settings.jsx
+++ b/frontend/src/views/Settings.jsx
@@ -1,7 +1,7 @@
import { useEffect, useRef, useState, forwardRef, useSyncExternalStore } from 'react'
import { useNavigate, useParams, useLocation, Navigate } from 'react-router-dom'
import { useStore, DEF, hasData } from '../store/useStore.js'
-import { healthStatus, loadHealth, enableHealth, disableHealth, openHealthConnect, onHealthChange } from '../lib/health-sync.js'
+import { healthStatus, loadHealth, enableHealth, disableHealth, openHealthConnect, onHealthChange, enableRead, disableRead } from '../lib/health-sync.js'
import { workoutControls } from '../lib/workout-controls.js'
import { speedUnitOf } from '../lib/speed.js'
import { formulaOf, FORMULA_NAMES } from '../lib/onerm.js'
@@ -1515,7 +1515,7 @@ function RegisterInline({ close, setUser, pushState, pullState, toast }) {
const HEALTH_COPY = {
android: () => ({
section: t('Health Connect'), write: t('Write to Health Connect'), open: t('Open Health Connect'),
- footer: t('Workouts and weigh-ins go to Health Connect when you finish or change them. openGym reads nothing back.'),
+ footer: t('Workouts and weigh-ins go to Health Connect when you finish or change them.'),
on: t('Writing to Health Connect'), denied: t('Health Connect permission not granted'), failed: t('Could not write to Health Connect'),
removeFailed: t('Could not remove it from Health Connect'), stop: t('Stop writing to Health Connect?'),
stopSub: t('What openGym already wrote can stay in Health Connect as your data, or be removed from it.'),
@@ -1530,6 +1530,7 @@ const HEALTH_COPY = {
}
function HealthConnectCard({ S, toast, android }) {
+ const getState = () => useStore.getState().S
const [st, setSt] = useState(null)
const [h, setH] = useState(null)
const [busy, setBusy] = useState(false)
@@ -1570,6 +1571,21 @@ function HealthConnectCard({ S, toast, android }) {
catch { toast(c.removeFailed) }
setBusy(false)
}
+ // Reading back (v1.4.3): heart rate during workouts and weigh-ins from other apps, each its own
+ // switch and its own permission. Turning one off keeps what it already brought in.
+ const toggleRead = kind => async v => {
+ setBusy(true)
+ try {
+ if (v) {
+ const r = await enableRead(kind, getState)
+ setH(r.health || await loadHealth())
+ if (!r.ok) toast(r.reason === 'denied' ? c.denied : c.failed)
+ } else setH(await disableRead(kind))
+ } catch { toast(c.failed) }
+ setBusy(false)
+ }
+ const reading = h.readHr || h.readWeight
+
// Off can mean two things for what is already there, so it asks; closing the sheet keeps it on.
const askOff = () => menuSheet({
title: c.stop,
@@ -1582,14 +1598,25 @@ function HealthConnectCard({ S, toast, android }) {
return (
<Section title={c.section}
- footer={h.on ? c.footer : null}>
+ footer={[h.on && c.footer, reading && t('openGym reads only while it is open: heart rate for workouts of the last day, weigh-ins of the last 30 days. Older workouts stay as they are.')].filter(Boolean).join(' ') || null}>
<Row icon="heart" iconTint="var(--red)" title={c.write}
subtitle={t('Finished workouts and weigh-ins, from this phone only.')}>
<Switch checked={!!h.on} disabled={busy} onChange={v => (v ? turnOn() : askOff())} />
</Row>
{h.on && h.error === 'permission' && <Row icon="warning" iconTint="var(--orange)"
title={t('Permission withdrawn. Tap to allow again')} accessory="chevron" onClick={turnOn} />}
- {h.on && <Row icon="list" iconTint="var(--blue)" title={c.open}
+ <Row icon="heart" iconTint="var(--red)" title={t('Heart rate from your watch')}
+ subtitle={t('After a workout, each set gets the heart rate your watch saved. Garmin, Fitbit, Galaxy Watch and friends welcome.')}>
+ <Switch checked={!!h.readHr} disabled={busy} onChange={toggleRead('hr')} />
+ </Row>
+ <Row icon="scale" iconTint="var(--teal)" title={t('Weigh-ins from other apps')}
+ subtitle={t('Your smart scale’s weigh-ins land here. One you type in yourself always wins.')}>
+ <Switch checked={!!h.readWeight} disabled={busy} onChange={toggleRead('weight')} />
+ </Row>
+ {reading && h.readError === 'permission' && <Row icon="warning" iconTint="var(--orange)"
+ title={t('Permission withdrawn. Tap to allow again')} accessory="chevron"
+ onClick={() => toggleRead(h.readHr ? 'hr' : 'weight')(true)} />}
+ {(h.on || reading) && <Row icon="list" iconTint="var(--blue)" title={c.open}
accessory="chevron" onClick={() => openHealthConnect().catch(() => {})} />}
</Section>
)
diff --git a/website/privacy.html b/website/privacy.html
index bc8b85826..19eda9e8b 100644
--- a/website/privacy.html
+++ b/website/privacy.html
@@ -103,7 +103,7 @@
<h1>Privacy</h1>
<p class="lead">This page covers the openGym apps for Android and iPhone (the APK from this
site and GitHub, the Google Play and App Store versions) and this website.
- Last changed: 11 October 2026.</p>
+ Last changed: 15 October 2026.</p>
<h2 id="short">The short version</h2>
<ul>
@@ -113,7 +113,7 @@
<li><b>Your training log stays on your phone.</b> Workouts, plans, body weight, photos and
settings are stored in the app's own storage on your device. We never receive them.</li>
<li><b>You decide what leaves the phone</b>, and only these things can: a backup you export,
- a server you connect, the AI coach if you set it up, and Health Connect if you switch it on.</li>
+ a server you connect, the AI coach if you set it up, and Health Connect or Apple Health if you switch them on.</li>
</ul>
<h2 id="online">When the app goes online</h2>
@@ -133,8 +133,14 @@
device for that provider only: switch providers and it asks again, and you can take it
back anytime in the coach's menu under AI data sharing. A model running on your own
network is not a third party, so nothing to ask there.</li>
- <li><b>Health Connect</b> (Android). If you switch it on, the app writes finished workouts and
- weigh-ins to Health Connect on your phone. It reads nothing from it.</li>
+ <li><b>Health Connect</b> (Android) and <b>Apple Health</b> (iPhone). Each part has its own
+ switch, all off until you turn them on. Writing puts finished workouts and weigh-ins into
+ the health store on your phone. Reading (since v1.4.3) takes two things back: the heart
+ rate your watch saved during a workout you logged (from the last day, while the app is
+ open) and weigh-ins other apps saved (from the last 30 days). They go into your own
+ workout log on the phone and never leave it, except inside that log when you sync it to
+ your own server. Nothing is read in the background, nothing else is read, and no health
+ data goes to us or to anyone else.</li>
<li><b>Update check</b> (only the APK from this site and GitHub). When you open Settings →
About, the app asks GitHub's public release list whether there is a newer version, and
downloads it from GitHub if you tap update. The store versions are updated by their store