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 Connect on Android: write finished workouts and weigh-ins (#200)

DrDamnation507cb36cdad6
diff --git a/docs/MOBILE.md b/docs/MOBILE.md
index 9c7e41cd4..a685cb023 100644
--- a/docs/MOBILE.md
+++ b/docs/MOBILE.md
@@ -120,6 +120,47 @@ video autoplays muted in the Android WebView; a long video seeks from its `_capa
URL on both platforms; an iPhone photo arrives as JPEG and an iPhone video (HEVC or H.264 MOV)
plays; the zip export opens the share sheet.
+### Health Connect (Android)
+
+Settings → **Health Connect** writes finished workouts and weigh-ins to Health Connect, Android's
+on-device store for health data, where other apps (Google Fit, Samsung Health, a smartwatch app…)
+can read them. It is off until the user turns it on, and nothing is asked of Health Connect before
+that.
+
+- **What is written:** each finished workout as an exercise session — its start and end, its name
+ as the title, the exercises and sets as "Copy as text" writes them as the notes, and a type
+ (strength training as soon as one exercise is not cardio; walking, running, stationary bike,
+ elliptical or stair machine for a cardio-only workout on a catalogue machine; "other" otherwise).
+ 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.
+- **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.
+- **This phone only.** Whether it is on, and a fingerprint of each record already written, live in
+ `opengym-health.json` in the app's data directory, never in the synced state: it does not travel
+ to a server, into a backup export, or to a second phone. It works the same in local mode and
+ paired with a server, because the writing happens on the phone.
+- **When it writes:** after each save (finishing a workout, a weigh-in, an edit), when the app comes
+ back to the foreground, and once at launch. While it is off, a save costs nothing: the file is
+ read once at launch and kept in memory.
+- **Turning it off** asks whether to keep what openGym wrote in Health Connect, as the user's own
+ data, or to remove exactly those records.
+- **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.
+
+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.
+
## Prerequisites
- Node 20+
diff --git a/frontend/android/app/build.gradle b/frontend/android/app/build.gradle
index 4a3f8dcc2..0a9a67b2a 100644
--- a/frontend/android/app/build.gradle
+++ b/frontend/android/app/build.gradle
@@ -48,6 +48,10 @@ dependencies {
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
+ // Writing workouts and weigh-ins to Health Connect (#200, HealthConnectPlugin). Off until the
+ // user turns it on. 1.1.0-alpha12 is the last release that builds with compileSdk 35 and AGP
+ // 8.7; 1.1.0 stable asks for compileSdk 36 and AGP 8.9.1.
+ implementation "androidx.health.connect:connect-client:$healthConnectVersion"
implementation project(':capacitor-android')
testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
diff --git a/frontend/android/app/src/main/AndroidManifest.xml b/frontend/android/app/src/main/AndroidManifest.xml
index 4a7aeddbe..ccee08949 100644
--- a/frontend/android/app/src/main/AndroidManifest.xml
+++ b/frontend/android/app/src/main/AndroidManifest.xml
@@ -1,5 +1,11 @@
<?xml version="1.0" encoding="utf-8" ?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:tools="http://schemas.android.com/tools">
+
+ <!-- Health Connect (#200): its client library asks for Android 8 and Health Connect itself
+ needs 9. The app keeps running on older phones, where HealthConnectPlugin answers
+ "unsupported" before touching the library. -->
+ <uses-sdk tools:overrideLibrary="androidx.health.connect.client" />
<application
android:allowBackup="true"
android:fullBackupContent="@xml/backup_rules"
@@ -24,6 +30,28 @@
</intent-filter>
</activity>
+ <!-- Health Connect (#200) opens the app from its permission screen to say why the
+ permissions are asked for: Android 14 and up through VIEW_PERMISSION_USAGE, 13 and
+ lower through the Health Connect app's rationale action. Both land in the app. -->
+ <activity-alias
+ android:name="ViewPermissionUsageActivity"
+ android:exported="true"
+ android:targetActivity=".MainActivity"
+ android:permission="android.permission.START_VIEW_PERMISSION_USAGE">
+ <intent-filter>
+ <action android:name="android.intent.action.VIEW_PERMISSION_USAGE" />
+ <category android:name="android.intent.category.HEALTH_PERMISSIONS" />
+ </intent-filter>
+ </activity-alias>
+ <activity-alias
+ android:name="HealthPermissionsRationaleActivity"
+ android:exported="true"
+ android:targetActivity=".MainActivity">
+ <intent-filter>
+ <action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
+ </intent-filter>
+ </activity-alias>
+
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
@@ -79,4 +107,13 @@
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
<!-- 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. -->
+ <uses-permission android:name="android.permission.health.WRITE_EXERCISE" />
+ <uses-permission android:name="android.permission.health.WRITE_WEIGHT" />
+
+ <!-- Whether the Health Connect app is there, on Android 13 and lower. -->
+ <queries>
+ <package android:name="com.google.android.apps.healthdata" />
+ </queries>
</manifest>
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
new file mode 100644
index 000000000..8c9f1736f
--- /dev/null
+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/HealthConnectPlugin.java
@@ -0,0 +1,278 @@
+package ch.duartesantos.opengym;
+
+import android.content.Intent;
+import android.net.Uri;
+import android.os.Build;
+import androidx.activity.result.ActivityResult;
+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.Record;
+import androidx.health.connect.client.records.WeightRecord;
+import androidx.health.connect.client.records.metadata.Metadata;
+import androidx.health.connect.client.units.Mass;
+import com.getcapacitor.JSArray;
+import com.getcapacitor.JSObject;
+import com.getcapacitor.Plugin;
+import com.getcapacitor.PluginCall;
+import com.getcapacitor.PluginMethod;
+import com.getcapacitor.annotation.ActivityCallback;
+import com.getcapacitor.annotation.CapacitorPlugin;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZoneOffset;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import kotlin.coroutines.EmptyCoroutineContext;
+import kotlin.jvm.JvmClassMappingKt;
+import kotlinx.coroutines.BuildersKt;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+/**
+ * Writes finished workouts and weigh-ins to Health Connect (#200), the phone's own store for
+ * health data, so other apps can read them. Write-only and off until the user turns it on in
+ * Settings: no permission is asked for before that. What to write is worked out in JS
+ * (lib/health-connect.js); this side only turns those plain objects into records.
+ *
+ * Every record carries openGym's own id as its clientRecordId, so writing it again replaces it,
+ * and "remove" finds exactly the records openGym wrote. The version is the time of the write:
+ * Health Connect keeps a rewritten record only when its version is higher than the stored one.
+ *
+ * The client's API is Kotlin suspend functions. They are called from a worker thread through
+ * runBlocking, which keeps the Android project Java-only.
+ *
+ * The client library needs Android 8 (API 26) and Health Connect itself Android 9 (API 28); the
+ * app supports Android 6, so every entry point checks the version before a Health Connect class
+ * is touched, and answers "unsupported" below 9.
+ *
+ * Usage from JS (lib/health-sync.js):
+ * const HC = registerPlugin('HealthConnect');
+ * await HC.status(); // { status: 'available' | 'update' | 'missing' | 'unsupported', granted }
+ * await HC.requestPermissions(); // { granted }
+ * await HC.write({ sessions: [...], weights: [...] });
+ * await HC.remove({ sessions: [ids], weights: [ids] });
+ * await HC.openSettings(); // Health Connect's data screen, or its store page
+ */
+@CapacitorPlugin(name = "HealthConnect")
+public class HealthConnectPlugin extends Plugin {
+
+ private static final String PROVIDER = "com.google.android.apps.healthdata";
+ // 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";
+ // Health Connect takes at most this many records in one insert.
+ private static final int CHUNK = 500;
+
+ // One at a time, in order: a remove queued behind a write must not overtake it.
+ private final ExecutorService worker = Executors.newSingleThreadExecutor();
+
+ private static boolean supported() {
+ return Build.VERSION.SDK_INT >= Build.VERSION_CODES.P;
+ }
+
+ private static Set<String> permissions() {
+ Set<String> p = new HashSet<>();
+ p.add(WRITE_EXERCISE);
+ p.add(WRITE_WEIGHT);
+ return p;
+ }
+
+ private String sdkStatus() {
+ if (!supported()) return "unsupported";
+ int s = HealthConnectClient.Companion.getSdkStatus(getContext(), PROVIDER);
+ if (s == HealthConnectClient.SDK_AVAILABLE) return "available";
+ if (s == HealthConnectClient.SDK_UNAVAILABLE_PROVIDER_UPDATE_REQUIRED) return "update";
+ // Android 13 and lower need the Health Connect app; 14 and up have it built in, so
+ // "missing" there means the phone has no Health Connect at all (some Android Go builds).
+ return Build.VERSION.SDK_INT >= 34 ? "unsupported" : "missing";
+ }
+
+ private HealthConnectClient client() {
+ return HealthConnectClient.Companion.getOrCreate(getContext(), PROVIDER);
+ }
+
+ @SuppressWarnings("unchecked")
+ private Set<String> granted() throws InterruptedException {
+ PermissionController pc = client().getPermissionController();
+ return (Set<String>) BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE, (scope, cont) -> pc.getGrantedPermissions(cont));
+ }
+
+ @PluginMethod
+ public void status(PluginCall call) {
+ String status = sdkStatus();
+ if (!"available".equals(status)) {
+ JSObject r = new JSObject();
+ r.put("status", status);
+ r.put("granted", false);
+ call.resolve(r);
+ return;
+ }
+ worker.execute(() -> {
+ try {
+ JSObject r = new JSObject();
+ r.put("status", status);
+ r.put("granted", granted().containsAll(permissions()));
+ call.resolve(r);
+ } catch (Exception e) {
+ call.reject(e.getMessage(), "failed");
+ }
+ });
+ }
+
+ @PluginMethod
+ public void requestPermissions(PluginCall call) {
+ if (!"available".equals(sdkStatus())) {
+ call.reject("Health Connect is not available", "unavailable");
+ return;
+ }
+ ActivityResultContract<Set<String>, Set<String>> contract = PermissionController.createRequestPermissionResultContract(PROVIDER);
+ Intent intent = contract.createIntent(getContext(), permissions());
+ startActivityForResult(call, intent, "permissionsResult");
+ }
+
+ @ActivityCallback
+ private void permissionsResult(PluginCall call, ActivityResult result) {
+ if (call == null) return;
+ ActivityResultContract<Set<String>, Set<String>> contract = PermissionController.createRequestPermissionResultContract(PROVIDER);
+ Set<String> got = contract.parseResult(result.getResultCode(), result.getData());
+ // The dialog answers only for this time; ask Health Connect what stands now, since the
+ // user may also have granted one of the two and not the other.
+ worker.execute(() -> {
+ try {
+ JSObject r = new JSObject();
+ r.put("granted", (got != null && got.containsAll(permissions())) || granted().containsAll(permissions()));
+ call.resolve(r);
+ } catch (Exception e) {
+ call.reject(e.getMessage(), "failed");
+ }
+ });
+ }
+
+ @PluginMethod
+ public void write(PluginCall call) {
+ if (!"available".equals(sdkStatus())) {
+ call.reject("Health Connect is not available", "unavailable");
+ return;
+ }
+ JSArray sessions = call.getArray("sessions", new JSArray());
+ JSArray weights = call.getArray("weights", new JSArray());
+ worker.execute(() -> {
+ try {
+ long version = System.currentTimeMillis();
+ List<Record> records = new ArrayList<>();
+ for (int i = 0; i < sessions.length(); i++) records.add(session(sessions.getJSONObject(i), version));
+ for (int i = 0; i < weights.length(); i++) records.add(weight(weights.getJSONObject(i), version));
+ for (int from = 0; from < records.size(); from += CHUNK) {
+ List<Record> part = records.subList(from, Math.min(records.size(), from + CHUNK));
+ BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE, (scope, cont) -> client().insertRecords(part, cont));
+ }
+ call.resolve();
+ } catch (SecurityException e) {
+ call.reject(e.getMessage(), "permission");
+ } catch (Exception e) {
+ call.reject(e.getMessage(), "failed");
+ }
+ });
+ }
+
+ @PluginMethod
+ public void remove(PluginCall call) {
+ if (!"available".equals(sdkStatus())) {
+ call.reject("Health Connect is not available", "unavailable");
+ return;
+ }
+ JSArray sessions = call.getArray("sessions", new JSArray());
+ JSArray weights = call.getArray("weights", new JSArray());
+ worker.execute(() -> {
+ try {
+ delete(ExerciseSessionRecord.class, ids(sessions));
+ delete(WeightRecord.class, ids(weights));
+ call.resolve();
+ } catch (SecurityException e) {
+ call.reject(e.getMessage(), "permission");
+ } catch (Exception e) {
+ call.reject(e.getMessage(), "failed");
+ }
+ });
+ }
+
+ // 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
+ public void openSettings(PluginCall call) {
+ String status = sdkStatus();
+ if ("unsupported".equals(status)) {
+ call.reject("Health Connect is not available", "unavailable");
+ return;
+ }
+ try {
+ Intent intent = "available".equals(status)
+ ? HealthConnectClient.Companion.getHealthConnectManageDataIntent(getContext(), PROVIDER)
+ : new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + PROVIDER + "&url=healthconnect%3A%2F%2Fonboarding"));
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ getContext().startActivity(intent);
+ call.resolve();
+ } catch (Exception e) {
+ call.reject(e.getMessage(), "failed");
+ }
+ }
+
+ private void delete(Class<? extends Record> type, List<String> clientIds) throws InterruptedException {
+ for (int from = 0; from < clientIds.size(); from += CHUNK) {
+ List<String> part = clientIds.subList(from, Math.min(clientIds.size(), from + CHUNK));
+ BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE, (scope, cont) ->
+ client().deleteRecords(JvmClassMappingKt.getKotlinClass(type), Collections.emptyList(), part, cont));
+ }
+ }
+
+ private static List<String> ids(JSArray array) throws JSONException {
+ List<String> out = new ArrayList<>();
+ for (int i = 0; i < array.length(); i++) out.add(array.getString(i));
+ return out;
+ }
+
+ // The offset in force at that moment where the phone is now: what Health Connect shows the
+ // session's local time with.
+ private static ZoneOffset offsetAt(Instant at) {
+ return ZoneId.systemDefault().getRules().getOffset(at);
+ }
+
+ private static ExerciseSessionRecord session(JSONObject s, long version) throws JSONException {
+ Instant start = Instant.ofEpochMilli(s.getLong("start"));
+ Instant end = Instant.ofEpochMilli(s.getLong("end"));
+ String title = s.optString("title", "");
+ String notes = s.optString("notes", "");
+ return new ExerciseSessionRecord(
+ start, offsetAt(start), end, offsetAt(end),
+ Metadata.manualEntry(s.getString("id"), version),
+ exerciseType(s.optString("type")),
+ title.isEmpty() ? null : title,
+ notes.isEmpty() ? null : notes);
+ }
+
+ private static WeightRecord weight(JSONObject w, long version) throws JSONException {
+ Instant time = Instant.ofEpochMilli(w.getLong("time"));
+ return new WeightRecord(time, offsetAt(time), Mass.kilograms(w.getDouble("kg")),
+ Metadata.manualEntry(w.getString("id"), version));
+ }
+
+ // The names lib/health-connect.js uses (SESSION_TYPES); anything else is "other".
+ private static int exerciseType(String name) {
+ switch (name) {
+ case "strength_training": return ExerciseSessionRecord.EXERCISE_TYPE_STRENGTH_TRAINING;
+ case "walking": return ExerciseSessionRecord.EXERCISE_TYPE_WALKING;
+ case "running": return ExerciseSessionRecord.EXERCISE_TYPE_RUNNING;
+ case "biking_stationary": return ExerciseSessionRecord.EXERCISE_TYPE_BIKING_STATIONARY;
+ case "elliptical": return ExerciseSessionRecord.EXERCISE_TYPE_ELLIPTICAL;
+ case "stair_climbing_machine": return ExerciseSessionRecord.EXERCISE_TYPE_STAIR_CLIMBING_MACHINE;
+ default: return ExerciseSessionRecord.EXERCISE_TYPE_OTHER_WORKOUT;
+ }
+ }
+}
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 54bf83884..4a74dedec 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
@@ -20,6 +20,7 @@ public class MainActivity extends BridgeActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
+ registerPlugin(HealthConnectPlugin.class);
registerPlugin(InstallPlugin.class);
registerPlugin(PrintPlugin.class);
registerPlugin(RestAlertPlugin.class);
diff --git a/frontend/android/variables.gradle b/frontend/android/variables.gradle
index 2c8e4083f..efaa2a2b0 100644
--- a/frontend/android/variables.gradle
+++ b/frontend/android/variables.gradle
@@ -13,4 +13,5 @@ ext {
androidxJunitVersion = '1.2.1'
androidxEspressoCoreVersion = '3.6.1'
cordovaAndroidVersion = '10.1.1'
+ healthConnectVersion = '1.1.0-alpha12'
}
\ No newline at end of file
diff --git a/frontend/src/lib/health-connect.js b/frontend/src/lib/health-connect.js
new file mode 100644
index 000000000..ffc72cb9b
--- /dev/null
+++ b/frontend/src/lib/health-connect.js
@@ -0,0 +1,146 @@
+// What the Android app writes to Health Connect (#200), worked out from the state alone. Health
+// Connect is the phone's own store for health data: other apps read the workouts and weigh-ins from
+// there. Nothing here talks to it — lib/health-sync.js hands these records to the native plugin.
+//
+// Write-only, and only on request: the user turns it on in Settings, on each phone. Every record
+// carries a client id of its own (a workout's id, a weigh-in's day), so writing it again replaces
+// it instead of adding a second one, and anything openGym wrote can be found and removed again.
+import { workoutText } from './workout-text.js'
+import { modeForEntry, hasCompletedWork } from './workout-model.js'
+import { isoOf } from './format.js'
+
+const LB_PER_KG = 2.2046226218
+// Health Connect refuses a title or notes over 1000 characters (ExerciseSessionRecord).
+export const TEXT_MAX = 1000
+
+// The session type Health Connect files a workout under. A workout with any strength work in it is
+// strength training: ten minutes on the treadmill before the squats do not make it a walk. One that
+// is all cardio takes the machine's type when the catalogue says which machine it is, and "other"
+// when it does not (a custom exercise, burpees, cardio on two different machines).
+// The native side maps each name to its ExerciseSessionRecord.EXERCISE_TYPE_* constant.
+const CARDIO_TYPES = {
+ '3666': 'walking', // walking on incline treadmill
+ '0685': 'running', '0684': 'running', '3656': 'running',
+ '2138': 'biking_stationary', '0798': 'biking_stationary',
+ '2141': 'elliptical', '2331': 'elliptical',
+ '2311': 'stair_climbing_machine',
+}
+export const SESSION_TYPES = ['strength_training', 'walking', 'running', 'biking_stationary', 'elliptical', 'stair_climbing_machine', 'other_workout']
+
+export function sessionType(w) {
+ const done = (w?.entries || []).filter(e => (e.sets || []).some(hasCompletedWork))
+ if (!done.length) return 'other_workout'
+ if (done.some(e => modeForEntry(e) !== 'cardio')) return 'strength_training'
+ const types = new Set(done.map(e => CARDIO_TYPES[e.id] || 'other_workout'))
+ return types.size === 1 ? [...types][0] : 'other_workout'
+}
+
+const clip = s => (s.length > TEXT_MAX ? s.slice(0, TEXT_MAX - 1) + '…' : s)
+
+// The exercises and sets as "Copy as text" writes them, without its heading: the title already
+// carries the name, and Health Connect shows the date and the duration itself.
+function sessionNotes(w, opts) {
+ const blocks = workoutText(w, opts).split('\n\n').slice(1)
+ return clip(blocks.join('\n\n'))
+}
+
+/**
+ * One exercise session per finished workout. A workout with no start or end (or an end not after
+ * its start) is left out rather than given made-up times: Health Connect needs both.
+ */
+export function sessionRecord(w, { unit, nameOf, speedUnit }) {
+ const start = Number(w?.start), end = Number(w?.end)
+ if (!w?.id || !(start > 0) || !(end > start)) return null
+ return {
+ id: 'opengym-w-' + w.id,
+ start, end,
+ type: sessionType(w),
+ title: clip(String(w.name || '').trim()),
+ notes: sessionNotes(w, { unit, nameOf, speedUnit }),
+ }
+}
+
+/**
+ * One weight record per weigh-in day. `t` is when it was typed, which for a weigh-in added to an
+ * earlier day is not on that day; then it is put at 08:00 local time on the day it belongs to.
+ */
+export function weightRecord(b, unit) {
+ const w = Number(b?.w)
+ if (!b?.d || !(w > 0)) return null
+ const typed = Number(b.t)
+ const time = typed > 0 && isoOf(new Date(typed)) === b.d ? typed : localMorning(b.d)
+ if (!(time > 0)) return null
+ const kg = unit === 'lb' ? w / LB_PER_KG : w
+ return { id: 'opengym-bw-' + b.d, time, kg: Math.round(kg * 1000) / 1000 }
+}
+
+function localMorning(iso) {
+ const [y, m, d] = String(iso).split('-').map(Number)
+ if (!y || !m || !d) return NaN
+ return new Date(y, m - 1, d, 8, 0, 0, 0).getTime()
+}
+
+/** Everything the state has to give Health Connect: { sessions, weights }. */
+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 record's content as a short fingerprint, to tell a changed record from one already written as
+// it is. Key order is fixed by the builders above, so the same record always gives the same one.
+// cyrb53: 53 bits are plenty to tell two versions of one record apart, and the file that keeps a
+// fingerprint per record stays small next to a history of hundreds of workouts with their notes.
+export function recordKey(rec) {
+ const str = JSON.stringify(rec)
+ let h1 = 0xdeadbeef, h2 = 0x41c6ce57
+ for (let i = 0; i < str.length; i++) {
+ const ch = str.charCodeAt(i)
+ h1 = Math.imul(h1 ^ ch, 2654435761)
+ h2 = Math.imul(h2 ^ ch, 1597334677)
+ }
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909)
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909)
+ return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36)
+}
+
+/**
+ * What a sync has to do, given the records now and `written`, what this phone wrote before
+ * ({ [id]: { k: 'session' | 'weight', h: recordKey } }). New and changed records are written,
+ * records that are gone from openGym (a deleted workout, a removed weigh-in) are removed.
+ * Returns { sessions, weights, remove: { sessions: [id], weights: [id] }, written } — `written`
+ * being what the phone has written once the sync went through.
+ */
+export function planSync({ sessions, weights }, written = {}) {
+ const next = {}
+ const out = { sessions: [], weights: [], remove: { sessions: [], weights: [] } }
+ const take = (list, k, into) => {
+ for (const rec of list) {
+ if (next[rec.id]) continue // two workouts with one id: the first is the one written
+ const h = recordKey(rec)
+ next[rec.id] = { k, h }
+ if (written[rec.id]?.h !== h) into.push(rec)
+ }
+ }
+ take(sessions, 'session', out.sessions)
+ take(weights, 'weight', out.weights)
+ for (const [id, was] of Object.entries(written || {})) {
+ if (next[id]) continue
+ if (was?.k === 'session') out.remove.sessions.push(id)
+ else if (was?.k === 'weight') out.remove.weights.push(id)
+ }
+ out.written = next
+ return out
+}
+
+/** Every record this phone wrote, by type — what "remove what openGym wrote" takes away. */
+export function writtenIds(written = {}) {
+ const out = { sessions: [], weights: [] }
+ for (const [id, was] of Object.entries(written || {})) {
+ if (was?.k === 'session') out.sessions.push(id)
+ else if (was?.k === 'weight') out.weights.push(id)
+ }
+ return out
+}
diff --git a/frontend/src/lib/health-connect.test.js b/frontend/src/lib/health-connect.test.js
new file mode 100644
index 000000000..17364f046
--- /dev/null
+++ b/frontend/src/lib/health-connect.test.js
@@ -0,0 +1,141 @@
+import { describe, expect, it } from 'vitest'
+import { healthRecords, planSync, recordKey, sessionRecord, sessionType, SESSION_TYPES, TEXT_MAX, weightRecord, writtenIds } from './health-connect.js'
+
+// #200: what the Android app writes to Health Connect, worked out from the state alone.
+const nameOf = e => ({ '0025': 'barbell bench press', '3666': 'walking on incline treadmill', '2138': 'stationary bike run v. 3' })[e.id] || e.id
+const at = (h, m = 0) => new Date(2026, 8, 17, h, m).getTime()
+const strength = { id: '0025', target: { mode: 'reps' }, sets: [{ w: 60, r: 8, done: true }, { w: 60, r: 8, done: true }] }
+const treadmill = { id: '3666', target: { mode: 'cardio' }, sets: [{ min: 20, speed: 5, done: true }] }
+const bike = { id: '2138', target: { mode: 'cardio' }, sets: [{ min: 15, speed: 20, done: true }] }
+const workout = (entries, extra = {}) => ({ id: 'w1', d: '2026-09-17', start: at(18), end: at(19), name: 'Push', entries, ...extra })
+
+describe('sessionType', () => {
+ it('is strength training as soon as one exercise is not cardio', () => {
+ expect(sessionType(workout([treadmill, strength]))).toBe('strength_training')
+ })
+ it('takes the machine of an all-cardio workout from the catalogue', () => {
+ expect(sessionType(workout([treadmill]))).toBe('walking')
+ expect(sessionType(workout([bike]))).toBe('biking_stationary')
+ })
+ it('is "other" for cardio on two machines, or on one the catalogue does not place', () => {
+ expect(sessionType(workout([treadmill, bike]))).toBe('other_workout')
+ expect(sessionType(workout([{ ...treadmill, id: 'custom-rower' }]))).toBe('other_workout')
+ })
+ it('ignores exercises with no set done', () => {
+ const skipped = { ...strength, sets: [{ w: 60, r: 8, done: false }] }
+ expect(sessionType(workout([treadmill, skipped]))).toBe('walking')
+ })
+ it('only ever answers a type the native side knows', () => {
+ for (const w of [workout([]), workout([strength]), workout([treadmill]), workout([bike, treadmill])]) {
+ expect(SESSION_TYPES).toContain(sessionType(w))
+ }
+ })
+})
+
+describe('sessionRecord', () => {
+ it('carries the workout id, its times, the name and the sets as text', () => {
+ const rec = sessionRecord(workout([strength], { note: 'Felt strong.' }), { unit: 'kg', nameOf })
+ expect(rec).toEqual({
+ id: 'opengym-w-w1', start: at(18), end: at(19), type: 'strength_training', title: 'Push',
+ notes: 'Barbell Bench Press\n60×8, 60×8\n\nFelt strong.',
+ })
+ })
+ it('leaves out a workout without real times instead of inventing them', () => {
+ expect(sessionRecord(workout([strength], { start: undefined }), { unit: 'kg', nameOf })).toBeNull()
+ expect(sessionRecord(workout([strength], { end: at(18) }), { unit: 'kg', nameOf })).toBeNull()
+ expect(sessionRecord(workout([strength], { id: undefined }), { unit: 'kg', nameOf })).toBeNull()
+ })
+ it('keeps title and notes within what Health Connect accepts', () => {
+ const long = 'x'.repeat(3000)
+ const rec = sessionRecord(workout([strength], { name: long, note: long }), { unit: 'kg', nameOf })
+ expect(rec.title.length).toBe(TEXT_MAX)
+ expect(rec.notes.length).toBe(TEXT_MAX)
+ })
+})
+
+describe('weightRecord', () => {
+ it('is in kilograms whatever the profile unit', () => {
+ expect(weightRecord({ d: '2026-09-17', w: 80, t: at(7) }, 'kg').kg).toBe(80)
+ expect(weightRecord({ d: '2026-09-17', w: 176.4, t: at(7) }, 'lb').kg).toBeCloseTo(80.014, 3)
+ })
+ it('is at the time it was typed when that was on its own day', () => {
+ expect(weightRecord({ d: '2026-09-17', w: 80, t: at(7, 12) }, 'kg')).toEqual({ id: 'opengym-bw-2026-09-17', time: at(7, 12), kg: 80 })
+ })
+ it('is at 08:00 on its day when it was added to that day later, or carries no time', () => {
+ const morning = new Date(2026, 8, 10, 8).getTime()
+ expect(weightRecord({ d: '2026-09-10', w: 80, t: at(7) }, 'kg').time).toBe(morning)
+ expect(weightRecord({ d: '2026-09-10', w: 80 }, 'kg').time).toBe(morning)
+ })
+ it('skips a weigh-in with no day or no weight', () => {
+ expect(weightRecord({ w: 80 }, 'kg')).toBeNull()
+ expect(weightRecord({ d: '2026-09-17', w: 0 }, 'kg')).toBeNull()
+ })
+})
+
+describe('healthRecords', () => {
+ it('turns the state into sessions and weights, dropping what cannot be written', () => {
+ const S = {
+ unit: 'kg',
+ workouts: [workout([strength]), workout([strength], { id: 'w2', start: undefined })],
+ bodyweight: [{ d: '2026-09-17', w: 80, t: at(7) }, { d: '2026-09-18', w: null }],
+ }
+ const r = healthRecords(S, { nameOf })
+ expect(r.sessions.map(s => s.id)).toEqual(['opengym-w-w1'])
+ expect(r.weights.map(s => s.id)).toEqual(['opengym-bw-2026-09-17'])
+ })
+ it('copes with a state that has neither', () => {
+ expect(healthRecords({}, { nameOf })).toEqual({ sessions: [], weights: [] })
+ })
+})
+
+describe('planSync', () => {
+ const S = { unit: 'kg', workouts: [workout([strength])], bodyweight: [{ d: '2026-09-17', w: 80, t: at(7) }] }
+ const records = () => healthRecords(S, { nameOf })
+
+ it('writes everything the first time', () => {
+ const plan = planSync(records(), {})
+ expect(plan.sessions).toHaveLength(1)
+ expect(plan.weights).toHaveLength(1)
+ expect(plan.remove).toEqual({ sessions: [], weights: [] })
+ expect(Object.keys(plan.written)).toEqual(['opengym-w-w1', 'opengym-bw-2026-09-17'])
+ })
+ it('writes nothing again when nothing changed', () => {
+ const { written } = planSync(records(), {})
+ const again = planSync(records(), written)
+ expect(again.sessions).toEqual([])
+ expect(again.weights).toEqual([])
+ expect(again.written).toEqual(written)
+ })
+ it('writes a record again when it was edited', () => {
+ const { written } = planSync(records(), {})
+ const edited = healthRecords({ ...S, bodyweight: [{ d: '2026-09-17', w: 79.5, t: at(7) }] }, { nameOf })
+ const plan = planSync(edited, written)
+ expect(plan.weights.map(w => w.kg)).toEqual([79.5])
+ expect(plan.sessions).toEqual([])
+ })
+ it('removes what was deleted from openGym, and only what this phone wrote', () => {
+ const { written } = planSync(records(), {})
+ const plan = planSync({ sessions: [], weights: [] }, written)
+ expect(plan.remove).toEqual({ sessions: ['opengym-w-w1'], weights: ['opengym-bw-2026-09-17'] })
+ expect(plan.written).toEqual({})
+ })
+ it('writes one record for two workouts that share an id', () => {
+ const twice = { sessions: [...records().sessions, { ...records().sessions[0], title: 'Copy' }], weights: [] }
+ expect(planSync(twice, {}).sessions.map(s => s.title)).toEqual(['Push'])
+ })
+})
+
+describe('recordKey', () => {
+ it('is the same for the same record and differs for a changed one', () => {
+ const rec = { id: 'opengym-bw-2026-09-17', time: at(7), kg: 80 }
+ expect(recordKey({ ...rec })).toBe(recordKey(rec))
+ expect(recordKey({ ...rec, kg: 80.1 })).not.toBe(recordKey(rec))
+ })
+})
+
+describe('writtenIds', () => {
+ it('lists what this phone wrote, by type', () => {
+ expect(writtenIds({ a: { k: 'session', h: '1' }, b: { k: 'weight', h: '2' }, c: { k: 'other' } }))
+ .toEqual({ sessions: ['a'], weights: ['b'] })
+ })
+})
diff --git a/frontend/src/lib/health-sync.js b/frontend/src/lib/health-sync.js
new file mode 100644
index 000000000..530c7775a
--- /dev/null
+++ b/frontend/src/lib/health-sync.js
@@ -0,0 +1,178 @@
+// Health Connect on the Android app (#200): turning it on, and keeping it in step with the log.
+// What gets written is worked out in lib/health-connect.js; this file owns the native plugin
+// (HealthConnectPlugin.java) and the phone's own record of what it wrote.
+//
+// It is a fact about this phone, not about the training log: kept in its own file in the app's
+// data directory, never in S, so it does not sync to a server, ride in a backup, or switch on a
+// second phone. Off until the user turns it on; nothing is asked of Health Connect before that.
+//
+// The web build never gets here (MOBILE is a build-time flag), and iOS answers 'unsupported'.
+import { MOBILE, isAndroid, readJsonFile, writeJsonFile } from './mobile.js'
+import { healthRecords, planSync, writtenIds } from './health-connect.js'
+import { exerciseNameFor } from './i18n-core.js'
+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 }
+
+// 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.
+let pluginP = null
+const plugin = () => pluginP || (pluginP = (async () => {
+ if (!(await isAndroid())) return null
+ const { registerPlugin } = await import('@capacitor/core')
+ return { HC: registerPlugin('HealthConnect') }
+})().catch(() => null))
+
+// The file's content, read once and then kept here: a save while it is off (the usual case) must
+// not cost a file read, and every change to it goes through saveHealth anyway.
+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 }
+ return cached
+}
+const saveHealth = h => { cached = h; return writeJsonFile(HEALTH_FILE, h) }
+
+/** { status: 'available' | 'update' | 'missing' | 'unsupported', granted } */
+export async function healthStatus() {
+ if (!MOBILE) return { status: 'unsupported', granted: false }
+ try {
+ const p = await plugin()
+ if (!p) return { status: 'unsupported', granted: false }
+ return await p.HC.status()
+ } catch { return { status: 'unsupported', granted: false } }
+}
+
+/** Health Connect's own screen for what apps wrote, or its store page where it is missing. */
+export async function openHealthConnect() {
+ const p = await plugin()
+ if (p) await p.HC.openSettings()
+}
+
+const nameOf = e => (EXIDX[e.id] ? exerciseNameFor(EXIDX[e.id]) : (e.n || e.id))
+
+// One sync at a time. A change that comes in while one runs is not lost: the running one is
+// followed by a single further pass with the newest state.
+let running = null
+let again = null
+const listeners = new Set()
+/** Called with the file's new content after every sync, for the Settings row. */
+export function onHealthChange(cb) { listeners.add(cb); return () => listeners.delete(cb) }
+const told = h => { listeners.forEach(cb => { try { cb(h) } catch { /* a closed screen */ } }) }
+
+/**
+ * Writes what changed since the last sync and removes what was deleted from openGym. A no-op
+ * while it is off. Resolves with the file's content afterwards; `error` is 'permission' when
+ * Health Connect refused (the user took the permission back), 'unavailable' when it is gone.
+ */
+export function syncHealth(S) {
+ if (!MOBILE) return Promise.resolve(null)
+ // Not read yet: initHealthSync reads it at launch and syncs then, which covers a save made
+ // before that; the save path itself never waits on the file.
+ if (!cached || !cached.on) return Promise.resolve(cached)
+ if (running) { again = S; return running }
+ again = null
+ running = (async () => {
+ let h = await loadHealth()
+ let next = S
+ while (next) {
+ if (h.on) h = await syncOnce(next, h)
+ // A state that came in meanwhile, taken only now: cleared before a pass, it would lose a
+ // change made while the pass was starting.
+ next = again
+ again = null
+ }
+ return h
+ })().finally(() => { running = null })
+ return running
+}
+
+async function syncOnce(S, h) {
+ const p = await plugin()
+ if (!p) return h
+ const plan = planSync(healthRecords(S, { nameOf, speedUnit: speedUnitOf(S) }), h.written)
+ const nothing = !plan.sessions.length && !plan.weights.length && !plan.remove.sessions.length && !plan.remove.weights.length
+ if (nothing) {
+ if (!h.error) return h
+ // Nothing to write, but the last attempt failed: clear it once Health Connect says yes again.
+ const st = await p.HC.status().catch(() => null)
+ if (!(st?.status === 'available' && st.granted)) return h
+ const out = { ...h, error: null }
+ await saveHealth(out)
+ told(out)
+ return out
+ }
+ let out = { ...h }
+ try {
+ if (plan.sessions.length || plan.weights.length) {
+ await p.HC.write({ sessions: plan.sessions, weights: plan.weights })
+ // Written but not yet removed: kept as written, so a failed remove is tried again.
+ const kept = Object.fromEntries(Object.entries(h.written).filter(([id]) => !plan.written[id]))
+ out.written = { ...kept, ...plan.written }
+ }
+ if (plan.remove.sessions.length || plan.remove.weights.length) await p.HC.remove(plan.remove)
+ out = { ...out, written: plan.written, at: Date.now(), error: null }
+ } catch (e) {
+ out.error = e?.code === 'permission' ? 'permission' : e?.code === 'unavailable' ? 'unavailable' : 'failed'
+ }
+ await saveHealth(out)
+ told(out)
+ return out
+}
+
+/**
+ * Turning it on: asks for the two write permissions, then writes the whole log once. Resolves
+ * with { ok, reason } — reason 'denied' when the user did not grant both, or the status when
+ * Health Connect is not there to ask.
+ */
+export async function enableHealth(S) {
+ 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 granted = st.granted || (await p.HC.requestPermissions().catch(() => ({ granted: false }))).granted
+ if (!granted) return { ok: false, reason: 'denied' }
+ const h = await loadHealth()
+ await saveHealth({ ...h, on: true, error: null })
+ const after = await syncHealth(S)
+ return { ok: !after?.error, reason: after?.error || null, health: after }
+}
+
+/**
+ * Turning it off stops the writing. With `removeWritten`, what openGym wrote is taken out of
+ * Health Connect too; without it, it stays there as the user's own data. Rejects when the
+ * removal fails, and then stays on, so nothing is left behind that the phone forgot it wrote.
+ */
+export async function disableHealth({ removeWritten = false } = {}) {
+ if (running) await running.catch(() => {})
+ const h = await loadHealth()
+ if (removeWritten) {
+ const ids = writtenIds(h.written)
+ if (ids.sessions.length || ids.weights.length) {
+ const p = await plugin()
+ if (!p) throw new Error('unavailable')
+ await p.HC.remove(ids)
+ }
+ }
+ const out = { ...h, on: false, error: null, written: removeWritten ? {} : h.written }
+ await saveHealth(out)
+ told(out)
+ return out
+}
+
+// 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) {
+ if (!MOBILE || started) return
+ started = true
+ import('@capacitor/app').then(({ App }) => {
+ App.addListener('appStateChange', ({ isActive }) => { if (isActive) syncHealth(getState()).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(() => syncHealth(getState())).catch(() => {}), 3000)
+}
diff --git a/frontend/src/lib/health-sync.test.js b/frontend/src/lib/health-sync.test.js
new file mode 100644
index 000000000..5f6172ba2
--- /dev/null
+++ b/frontend/src/lib/health-sync.test.js
@@ -0,0 +1,145 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+// #200: the Android app keeping Health Connect in step with the log. The native plugin
+// (HealthConnectPlugin.java) and the app's data directory are played in memory.
+const h = vi.hoisted(() => {
+ vi.stubEnv('VITE_MOBILE', '1')
+ return { files: new Map(), calls: [], status: { status: 'available', granted: false }, grant: true, 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: () => 'android' },
+ registerPlugin: () => ({
+ status: async () => ({ ...h.status }),
+ requestPermissions: async () => { h.calls.push(['request']); h.status.granted = h.grant; return { granted: h.grant } },
+ write: async arg => {
+ h.calls.push(['write', arg])
+ if (h.fail) throw Object.assign(new Error('refused'), { code: h.fail })
+ },
+ remove: async arg => { h.calls.push(['remove', arg]) },
+ openSettings: async () => {},
+ }),
+}))
+
+const at = (d, hh) => new Date(2026, 8, d, hh).getTime()
+const workout = (id, d) => ({ id, d: `2026-09-${d}`, start: at(d, 18), end: at(d, 19), name: 'Push',
+ entries: [{ id: '0025', target: { mode: 'reps' }, sets: [{ w: 60, r: 8, done: true }] }] })
+const state = (workouts, bodyweight = []) => ({ unit: 'kg', workouts, bodyweight })
+const writes = () => h.calls.filter(c => c[0] === 'write').map(c => c[1])
+const removes = () => h.calls.filter(c => c[0] === 'remove').map(c => c[1])
+const file = () => JSON.parse(h.files.get('opengym-health.json') || 'null')
+
+let hs
+beforeEach(async () => {
+ vi.resetModules()
+ h.files.clear(); h.calls = []; h.status = { status: 'available', granted: false }; h.grant = true; h.fail = null
+ hs = await import('./health-sync.js')
+})
+
+describe('off (the default)', () => {
+ it('writes nothing and asks for nothing, even after the file is read', async () => {
+ await hs.loadHealth()
+ await hs.syncHealth(state([workout('w1', 17)]))
+ expect(h.calls).toEqual([])
+ expect(h.files.has('opengym-health.json')).toBe(false)
+ })
+})
+
+describe('turning it on', () => {
+ it('asks for the permissions, then writes the whole log once', async () => {
+ const r = await hs.enableHealth(state([workout('w1', 17)], [{ d: '2026-09-17', w: 80, t: at(17, 7) }]))
+ expect(r.ok).toBe(true)
+ expect(h.calls[0]).toEqual(['request'])
+ expect(writes()).toHaveLength(1)
+ expect(writes()[0].sessions.map(s => s.id)).toEqual(['opengym-w-w1'])
+ expect(writes()[0].weights.map(s => s.id)).toEqual(['opengym-bw-2026-09-17'])
+ expect(file().on).toBe(true)
+ expect(Object.keys(file().written)).toEqual(['opengym-w-w1', 'opengym-bw-2026-09-17'])
+ })
+ it('stays off when the permissions are not granted', async () => {
+ h.grant = false
+ const r = await hs.enableHealth(state([workout('w1', 17)]))
+ expect(r).toEqual({ ok: false, reason: 'denied' })
+ expect(writes()).toEqual([])
+ expect(file()).toBeNull()
+ })
+ it('does not ask again when they were granted before', async () => {
+ h.status.granted = true
+ await hs.enableHealth(state([]))
+ expect(h.calls.find(c => c[0] === 'request')).toBeUndefined()
+ })
+ it('says so when Health Connect is not there', async () => {
+ h.status = { status: 'missing', granted: false }
+ expect(await hs.enableHealth(state([]))).toEqual({ ok: false, reason: 'missing' })
+ })
+})
+
+describe('keeping in step', () => {
+ it('writes only what is new, and removes what was deleted', async () => {
+ await hs.enableHealth(state([workout('w1', 17)]))
+ h.calls = []
+ await hs.syncHealth(state([workout('w1', 17)]))
+ expect(h.calls).toEqual([])
+
+ await hs.syncHealth(state([workout('w1', 17), workout('w2', 18)]))
+ expect(writes().map(w => w.sessions.map(s => s.id))).toEqual([['opengym-w-w2']])
+
+ h.calls = []
+ await hs.syncHealth(state([workout('w2', 18)]))
+ expect(writes()).toEqual([])
+ expect(removes()).toEqual([{ sessions: ['opengym-w-w1'], weights: [] }])
+ expect(Object.keys(file().written)).toEqual(['opengym-w-w2'])
+ })
+ it('remembers a refused permission, keeps what it has, and clears it once allowed again', async () => {
+ await hs.enableHealth(state([workout('w1', 17)]))
+ h.fail = 'permission'
+ await hs.syncHealth(state([workout('w1', 17), workout('w2', 18)]))
+ expect(file().error).toBe('permission')
+ expect(Object.keys(file().written)).toEqual(['opengym-w-w1'])
+
+ h.fail = null
+ await hs.syncHealth(state([workout('w1', 17), workout('w2', 18)]))
+ expect(file().error).toBeNull()
+ expect(Object.keys(file().written)).toEqual(['opengym-w-w1', 'opengym-w-w2'])
+ })
+ it('runs one sync at a time and follows it with the newest state', async () => {
+ await hs.enableHealth(state([]))
+ h.calls = []
+ const a = hs.syncHealth(state([workout('w1', 17)]))
+ const b = hs.syncHealth(state([workout('w1', 17), workout('w2', 18)]))
+ const c = hs.syncHealth(state([workout('w1', 17), workout('w2', 18), workout('w3', 19)]))
+ await Promise.all([a, b, c])
+ // The second call is overtaken by the third before it runs: two writes, not three.
+ expect(writes().map(w => w.sessions.map(s => s.id))).toEqual([['opengym-w-w1'], ['opengym-w-w2', 'opengym-w-w3']])
+ })
+})
+
+describe('turning it off', () => {
+ it('can leave what it wrote in Health Connect', async () => {
+ await hs.enableHealth(state([workout('w1', 17)]))
+ h.calls = []
+ await hs.disableHealth({ removeWritten: false })
+ expect(removes()).toEqual([])
+ expect(file().on).toBe(false)
+ await hs.syncHealth(state([workout('w1', 17), workout('w2', 18)]))
+ expect(writes()).toEqual([])
+ })
+ it('or remove exactly what it wrote', async () => {
+ await hs.enableHealth(state([workout('w1', 17)], [{ d: '2026-09-17', w: 80, t: at(17, 7) }]))
+ await hs.disableHealth({ removeWritten: true })
+ expect(removes()).toEqual([{ sessions: ['opengym-w-w1'], weights: ['opengym-bw-2026-09-17'] }])
+ expect(file()).toMatchObject({ on: false, written: {} })
+ })
+})
diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.js
index 07697206c..da1e12a0e 100644
--- a/frontend/src/locales/ar.js
+++ b/frontend/src/locales/ar.js
@@ -1716,4 +1716,21 @@ export default {
'Teal': 'أزرق مخضر',
'Yellow': 'أصفر',
'Enter how long it took — at least 1 minute.': 'أدخل المدة التي استغرقها — دقيقة واحدة على الأقل.',
+ // Health Connect on the Android app (#200)
+ 'Health Connect': 'Health Connect',
+ 'Write to Health Connect': 'الكتابة في Health Connect',
+ 'Finished workouts and weigh-ins, from this phone only.': 'التمارين المنتهية وقياسات الوزن، من هذا الهاتف فقط.',
+ 'Open Health Connect': 'فتح Health Connect',
+ '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 أي شيء منه.',
+ 'Health Connect permission not granted': 'لم يُمنح إذن Health Connect',
+ 'Could not write to Health Connect': 'تعذّرت الكتابة في Health Connect',
+ 'Writing to Health Connect': 'الكتابة في Health Connect مفعّلة',
+ 'Stop writing to Health Connect?': 'إيقاف الكتابة في Health Connect؟',
+ 'What openGym already wrote can stay in Health Connect as your data, or be removed from it.': 'ما كتبه openGym بالفعل يمكن أن يبقى في Health Connect كبياناتك، أو أن يُزال منه.',
+ 'Stop, keep what it wrote': 'إيقاف مع إبقاء ما كُتب',
+ 'Stop and remove what it wrote': 'إيقاف وإزالة ما كُتب',
+ 'Could not remove it from Health Connect': 'تعذّرت إزالته من Health Connect',
}
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index 663a5a5bb..89d3b194c 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -1683,4 +1683,21 @@ export default {
'Teal': 'Türkis',
'Yellow': 'Gelb',
'Enter how long it took — at least 1 minute.': 'Gib ein, wie lange es gedauert hat — mindestens 1 Minute.',
+ // Health Connect on the Android app (#200)
+ 'Health Connect': 'Health Connect',
+ 'Write to Health Connect': 'In Health Connect schreiben',
+ 'Finished workouts and weigh-ins, from this phone only.': 'Abgeschlossene Workouts und Wiegungen, nur von diesem Telefon.',
+ 'Open Health Connect': 'Health Connect öffnen',
+ '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.',
+ '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',
+ 'Stop writing to Health Connect?': 'Nicht mehr in Health Connect schreiben?',
+ 'What openGym already wrote can stay in Health Connect as your data, or be removed from it.': 'Was openGym bereits geschrieben hat, kann als deine Daten in Health Connect bleiben oder daraus entfernt werden.',
+ 'Stop, keep what it wrote': 'Beenden, Geschriebenes behalten',
+ 'Stop and remove what it wrote': 'Beenden und Geschriebenes entfernen',
+ 'Could not remove it from Health Connect': 'Entfernen aus Health Connect fehlgeschlagen',
}
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 8e1d9aa99..f938324ef 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -1663,4 +1663,21 @@ export default {
'Teal': 'Turquesa',
'Yellow': 'Amarillo',
'Enter how long it took — at least 1 minute.': 'Indica cuánto duró — al menos 1 minuto.',
+ // Health Connect on the Android app (#200)
+ 'Health Connect': 'Health Connect',
+ 'Write to Health Connect': 'Escribir en Health Connect',
+ 'Finished workouts and weigh-ins, from this phone only.': 'Entrenamientos terminados y pesajes, solo desde este teléfono.',
+ 'Open Health Connect': 'Abrir Health Connect',
+ '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.',
+ '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',
+ 'Stop writing to Health Connect?': '¿Dejar de escribir en Health Connect?',
+ 'What openGym already wrote can stay in Health Connect as your data, or be removed from it.': 'Lo que openGym ya escribió puede quedarse en Health Connect como tus datos o eliminarse de allí.',
+ 'Stop, keep what it wrote': 'Parar y conservar lo escrito',
+ 'Stop and remove what it wrote': 'Parar y eliminar lo escrito',
+ 'Could not remove it from Health Connect': 'No se pudo eliminar de Health Connect',
}
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index ee904194c..fe648ac0a 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -1663,4 +1663,21 @@ export default {
'Teal': 'Turquoise',
'Yellow': 'Jaune',
'Enter how long it took — at least 1 minute.': 'Indique combien de temps ça a duré — au moins 1 minute.',
+ // Health Connect on the Android app (#200)
+ 'Health Connect': 'Santé Connect',
+ 'Write to Health Connect': 'Écrire dans Santé Connect',
+ 'Finished workouts and weigh-ins, from this phone only.': 'Séances terminées et pesées, depuis ce téléphone uniquement.',
+ 'Open Health Connect': 'Ouvrir Santé Connect',
+ '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.',
+ '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',
+ 'Stop writing to Health Connect?': 'Arrêter d’écrire dans Santé Connect ?',
+ 'What openGym already wrote can stay in Health Connect as your data, or be removed from it.': 'Ce qu’openGym a déjà écrit peut rester dans Santé Connect comme vos données, ou en être retiré.',
+ 'Stop, keep what it wrote': 'Arrêter, garder ce qui a été écrit',
+ 'Stop and remove what it wrote': 'Arrêter et retirer ce qui a été écrit',
+ 'Could not remove it from Health Connect': 'Impossible de le retirer de Santé Connect',
}
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index ccb0ca2aa..f976a3ded 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -1663,4 +1663,21 @@ export default {
'Teal': 'फ़िरोज़ी',
'Yellow': 'पीला',
'Enter how long it took — at least 1 minute.': 'बताएँ कि इसमें कितना समय लगा — कम से कम 1 मिनट।',
+ // Health Connect on the Android app (#200)
+ 'Health Connect': 'Health Connect',
+ 'Write to Health Connect': 'Health Connect में लिखें',
+ 'Finished workouts and weigh-ins, from this phone only.': 'पूरे हुए वर्कआउट और वज़न, सिर्फ़ इसी फ़ोन से।',
+ 'Open Health Connect': 'Health Connect खोलें',
+ '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 वहाँ से कुछ नहीं पढ़ता।',
+ 'Health Connect permission not granted': 'Health Connect की अनुमति नहीं मिली',
+ 'Could not write to Health Connect': 'Health Connect में नहीं लिखा जा सका',
+ 'Writing to Health Connect': 'Health Connect में लिखना चालू है',
+ 'Stop writing to Health Connect?': 'Health Connect में लिखना बंद करें?',
+ 'What openGym already wrote can stay in Health Connect as your data, or be removed from it.': 'openGym ने जो पहले लिखा है, वह आपके डेटा के रूप में Health Connect में रह सकता है, या वहाँ से हटाया जा सकता है।',
+ 'Stop, keep what it wrote': 'बंद करें, लिखा हुआ रखें',
+ 'Stop and remove what it wrote': 'बंद करें और लिखा हुआ हटाएँ',
+ 'Could not remove it from Health Connect': 'Health Connect से हटाया नहीं जा सका',
}
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index 61b151edc..e4be37917 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -1666,4 +1666,21 @@ export default {
'Teal': 'Türkiz',
'Yellow': 'Sárga',
'Enter how long it took — at least 1 minute.': 'Add meg, meddig tartott — legalább 1 perc.',
+ // Health Connect on the Android app (#200)
+ 'Health Connect': 'Health Connect',
+ 'Write to Health Connect': 'Írás a Health Connectbe',
+ 'Finished workouts and weigh-ins, from this phone only.': 'Befejezett edzések és mérlegelések, csak erről a telefonról.',
+ 'Open Health Connect': 'Health Connect megnyitása',
+ '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.',
+ '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',
+ 'Stop writing to Health Connect?': 'Abbahagyod az írást a Health Connectbe?',
+ 'What openGym already wrote can stay in Health Connect as your data, or be removed from it.': 'Amit az openGym már beírt, a te adataidként a Health Connectben maradhat, vagy eltávolítható onnan.',
+ 'Stop, keep what it wrote': 'Leállítás, a beírtak maradnak',
+ 'Stop and remove what it wrote': 'Leállítás és a beírtak eltávolítása',
+ 'Could not remove it from Health Connect': 'Nem sikerült eltávolítani a Health Connectből',
}
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index 48e5dd34d..5da2f0944 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -1663,4 +1663,21 @@ export default {
'Teal': 'Turchese',
'Yellow': 'Giallo',
'Enter how long it took — at least 1 minute.': 'Inserisci quanto è durato — almeno 1 minuto.',
+ // Health Connect on the Android app (#200)
+ 'Health Connect': 'Connessione Salute',
+ 'Write to Health Connect': 'Scrivi in Connessione Salute',
+ 'Finished workouts and weigh-ins, from this phone only.': 'Allenamenti conclusi e pesate, solo da questo telefono.',
+ 'Open Health Connect': 'Apri Connessione Salute',
+ '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.',
+ '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',
+ 'Stop writing to Health Connect?': 'Smettere di scrivere in Connessione Salute?',
+ 'What openGym already wrote can stay in Health Connect as your data, or be removed from it.': 'Quello che openGym ha già scritto può restare in Connessione Salute come tuoi dati, oppure essere rimosso.',
+ 'Stop, keep what it wrote': 'Smetti, tieni quello che ha scritto',
+ 'Stop and remove what it wrote': 'Smetti e rimuovi quello che ha scritto',
+ 'Could not remove it from Health Connect': 'Impossibile rimuoverlo da Connessione Salute',
}
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index 02628fa0a..5d96de07c 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -1663,4 +1663,21 @@ export default {
'Teal': '청록',
'Yellow': '노랑',
'Enter how long it took — at least 1 minute.': '걸린 시간을 입력하세요 — 최소 1분.',
+ // Health Connect on the Android app (#200)
+ 'Health Connect': '헬스 커넥트',
+ 'Write to Health Connect': '헬스 커넥트에 기록',
+ 'Finished workouts and weigh-ins, from this phone only.': '완료한 운동과 체중 기록, 이 휴대전화에서만.',
+ 'Open Health Connect': '헬스 커넥트 열기',
+ '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은 아무것도 읽어 오지 않습니다.',
+ 'Health Connect permission not granted': '헬스 커넥트 권한이 허용되지 않음',
+ 'Could not write to Health Connect': '헬스 커넥트에 기록할 수 없음',
+ 'Writing to Health Connect': '헬스 커넥트에 기록 중',
+ 'Stop writing to Health Connect?': '헬스 커넥트 기록을 중단할까요?',
+ 'What openGym already wrote can stay in Health Connect as your data, or be removed from it.': 'openGym이 이미 기록한 내용은 내 데이터로 헬스 커넥트에 남겨 두거나 삭제할 수 있습니다.',
+ 'Stop, keep what it wrote': '중단하고 기록은 유지',
+ 'Stop and remove what it wrote': '중단하고 기록 삭제',
+ 'Could not remove it from Health Connect': '헬스 커넥트에서 삭제할 수 없음',
}
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index f5910a684..a28d08268 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -1663,4 +1663,21 @@ export default {
'Teal': 'Turkusowy',
'Yellow': 'Żółty',
'Enter how long it took — at least 1 minute.': 'Wpisz, ile to trwało — co najmniej 1 minutę.',
+ // Health Connect on the Android app (#200)
+ 'Health Connect': 'Health Connect',
+ 'Write to Health Connect': 'Zapisuj w Health Connect',
+ 'Finished workouts and weigh-ins, from this phone only.': 'Ukończone treningi i pomiary wagi, tylko z tego telefonu.',
+ 'Open Health Connect': 'Otwórz Health Connect',
+ '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.',
+ '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',
+ 'Stop writing to Health Connect?': 'Przestać zapisywać w Health Connect?',
+ 'What openGym already wrote can stay in Health Connect as your data, or be removed from it.': 'To, co openGym już zapisał, może zostać w Health Connect jako Twoje dane albo zostać stamtąd usunięte.',
+ 'Stop, keep what it wrote': 'Przestań, zachowaj zapisane',
+ 'Stop and remove what it wrote': 'Przestań i usuń zapisane',
+ 'Could not remove it from Health Connect': 'Nie udało się usunąć z Health Connect',
}
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index 41505d76e..b075f16d2 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -1008,6 +1008,23 @@ export const PT_BR_OVERRIDES = {
'Teal': 'Turquesa',
'Yellow': 'Amarelo',
'Enter how long it took — at least 1 minute.': 'Informe quanto tempo levou — pelo menos 1 minuto.',
+ // Health Connect on the Android app (#200); "Conexão Saúde" is its name on Brazilian Android.
+ 'Health Connect': 'Conexão Saúde',
+ 'Write to Health Connect': 'Gravar no Conexão Saúde',
+ 'Finished workouts and weigh-ins, from this phone only.': 'Treinos concluídos e pesagens, só deste celular.',
+ 'Open Health Connect': 'Abrir o Conexão Saúde',
+ '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.',
+ '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',
+ 'Stop writing to Health Connect?': 'Parar de gravar no Conexão Saúde?',
+ 'What openGym already wrote can stay in Health Connect as your data, or be removed from it.': 'O que o openGym já gravou pode ficar no Conexão Saúde como seus dados, ou ser removido de lá.',
+ 'Stop, keep what it wrote': 'Parar e manter o que gravou',
+ 'Stop and remove what it wrote': 'Parar e remover o que gravou',
+ 'Could not remove it from Health Connect': 'Não foi possível remover do Conexão Saúde',
}
export default { ...pt, ...PT_BR_OVERRIDES }
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index 65dd8ff54..a93190d3d 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -1663,4 +1663,21 @@ export default {
'Teal': 'Turquesa',
'Yellow': 'Amarelo',
'Enter how long it took — at least 1 minute.': 'Indica quanto tempo demorou — pelo menos 1 minuto.',
+ // Health Connect on the Android app (#200)
+ 'Health Connect': 'Health Connect',
+ 'Write to Health Connect': 'Escrever no Health Connect',
+ 'Finished workouts and weigh-ins, from this phone only.': 'Treinos terminados e pesagens, só a partir deste telemóvel.',
+ 'Open Health Connect': 'Abrir o Health Connect',
+ '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.',
+ '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',
+ 'Stop writing to Health Connect?': 'Deixar de escrever no Health Connect?',
+ 'What openGym already wrote can stay in Health Connect as your data, or be removed from it.': 'O que o openGym já escreveu pode ficar no Health Connect como dados seus, ou ser removido de lá.',
+ 'Stop, keep what it wrote': 'Parar e manter o que escreveu',
+ 'Stop and remove what it wrote': 'Parar e remover o que escreveu',
+ 'Could not remove it from Health Connect': 'Não foi possível remover do Health Connect',
}
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index 2df1568f7..c33e888c3 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -1663,4 +1663,21 @@ export default {
'Teal': 'Бирюзовый',
'Yellow': 'Жёлтый',
'Enter how long it took — at least 1 minute.': 'Укажите, сколько это длилось — не меньше 1 минуты.',
+ // Health Connect on the Android app (#200)
+ 'Health Connect': 'Health Connect',
+ 'Write to Health Connect': 'Записывать в Health Connect',
+ 'Finished workouts and weigh-ins, from this phone only.': 'Завершённые тренировки и взвешивания, только с этого телефона.',
+ 'Open Health Connect': 'Открыть Health Connect',
+ '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 ничего оттуда не читает.',
+ 'Health Connect permission not granted': 'Разрешение Health Connect не выдано',
+ 'Could not write to Health Connect': 'Не удалось записать в Health Connect',
+ 'Writing to Health Connect': 'Запись в Health Connect включена',
+ 'Stop writing to Health Connect?': 'Перестать записывать в Health Connect?',
+ 'What openGym already wrote can stay in Health Connect as your data, or be removed from it.': 'То, что openGym уже записал, может остаться в Health Connect как ваши данные или быть оттуда удалено.',
+ 'Stop, keep what it wrote': 'Остановить, оставить записанное',
+ 'Stop and remove what it wrote': 'Остановить и удалить записанное',
+ 'Could not remove it from Health Connect': 'Не удалось удалить из Health Connect',
}
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index 3604d80fa..fad180220 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -1674,4 +1674,21 @@ export default {
'Teal': 'เขียวน้ำทะเล',
'Yellow': 'เหลือง',
'Enter how long it took — at least 1 minute.': 'ใส่ระยะเวลาที่ใช้ — อย่างน้อย 1 นาที',
+ // Health Connect on the Android app (#200)
+ 'Health Connect': 'Health Connect',
+ 'Write to Health Connect': 'เขียนลงใน Health Connect',
+ 'Finished workouts and weigh-ins, from this phone only.': 'การออกกำลังกายที่เสร็จแล้วและการชั่งน้ำหนัก จากโทรศัพท์เครื่องนี้เท่านั้น',
+ 'Open Health Connect': 'เปิด Health Connect',
+ '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 ไม่อ่านอะไรกลับมา',
+ 'Health Connect permission not granted': 'ไม่ได้รับสิทธิ์ Health Connect',
+ 'Could not write to Health Connect': 'เขียนลงใน Health Connect ไม่ได้',
+ 'Writing to Health Connect': 'กำลังเขียนลงใน Health Connect',
+ 'Stop writing to Health Connect?': 'หยุดเขียนลงใน Health Connect ไหม',
+ 'What openGym already wrote can stay in Health Connect as your data, or be removed from it.': 'สิ่งที่ openGym เขียนไว้แล้วจะเก็บไว้ใน Health Connect เป็นข้อมูลของคุณ หรือลบออกก็ได้',
+ 'Stop, keep what it wrote': 'หยุด และเก็บสิ่งที่เขียนไว้',
+ 'Stop and remove what it wrote': 'หยุด และลบสิ่งที่เขียนไว้',
+ 'Could not remove it from Health Connect': 'ลบออกจาก Health Connect ไม่ได้',
}
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index 1c96ebc30..1ba3a10ed 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -1663,4 +1663,21 @@ export default {
'Teal': 'Turkuaz',
'Yellow': 'Sarı',
'Enter how long it took — at least 1 minute.': 'Ne kadar sürdüğünü gir — en az 1 dakika.',
+ // Health Connect on the Android app (#200)
+ 'Health Connect': 'Health Connect',
+ 'Write to Health Connect': 'Health Connect’e yaz',
+ 'Finished workouts and weigh-ins, from this phone only.': 'Biten antrenmanlar ve tartılmalar, yalnızca bu telefondan.',
+ 'Open Health Connect': 'Health Connect’i aç',
+ '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.',
+ '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',
+ 'Stop writing to Health Connect?': 'Health Connect’e yazmayı bırakmak mı?',
+ 'What openGym already wrote can stay in Health Connect as your data, or be removed from it.': 'openGym’in zaten yazdıkları verileriniz olarak Health Connect’te kalabilir ya da oradan kaldırılabilir.',
+ 'Stop, keep what it wrote': 'Durdur, yazılanları koru',
+ 'Stop and remove what it wrote': 'Durdur ve yazılanları kaldır',
+ 'Could not remove it from Health Connect': 'Health Connect’ten kaldırılamadı',
}
diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.js
index ba239e0c8..4ccf4a35c 100644
--- a/frontend/src/locales/uk.js
+++ b/frontend/src/locales/uk.js
@@ -1660,4 +1660,21 @@ export default {
'Teal': 'Бірюзовий',
'Yellow': 'Жовтий',
'Enter how long it took — at least 1 minute.': 'Вкажи, скільки це тривало — щонайменше 1 хвилину.',
+ // Health Connect on the Android app (#200)
+ 'Health Connect': 'Health Connect',
+ 'Write to Health Connect': 'Записувати в Health Connect',
+ 'Finished workouts and weigh-ins, from this phone only.': 'Завершені тренування та зважування, лише з цього телефона.',
+ 'Open Health Connect': 'Відкрити Health Connect',
+ '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 нічого звідти не читає.',
+ 'Health Connect permission not granted': 'Дозвіл Health Connect не надано',
+ 'Could not write to Health Connect': 'Не вдалося записати в Health Connect',
+ 'Writing to Health Connect': 'Запис у Health Connect увімкнено',
+ 'Stop writing to Health Connect?': 'Припинити записувати в Health Connect?',
+ 'What openGym already wrote can stay in Health Connect as your data, or be removed from it.': 'Те, що openGym уже записав, може залишитися в Health Connect як ваші дані або бути звідти видалене.',
+ 'Stop, keep what it wrote': 'Зупинити, залишити записане',
+ 'Stop and remove what it wrote': 'Зупинити й видалити записане',
+ 'Could not remove it from Health Connect': 'Не вдалося видалити з Health Connect',
}
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index 84237894a..1b5936703 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -1663,4 +1663,21 @@ export default {
'Teal': '青色',
'Yellow': '黄色',
'Enter how long it took — at least 1 minute.': '请输入用时 — 至少 1 分钟。',
+ // Health Connect on the Android app (#200)
+ 'Health Connect': 'Health Connect',
+ 'Write to Health Connect': '写入 Health Connect',
+ 'Finished workouts and weigh-ins, from this phone only.': '已完成的训练和称重,仅来自这部手机。',
+ 'Open Health Connect': '打开 Health Connect',
+ '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 不会从中读取任何内容。',
+ 'Health Connect permission not granted': '未授予 Health Connect 权限',
+ 'Could not write to Health Connect': '无法写入 Health Connect',
+ 'Writing to Health Connect': '正在写入 Health Connect',
+ 'Stop writing to Health Connect?': '停止写入 Health Connect?',
+ 'What openGym already wrote can stay in Health Connect as your data, or be removed from it.': 'openGym 已写入的内容可以作为你的数据保留在 Health Connect 中,也可以从中移除。',
+ 'Stop, keep what it wrote': '停止,保留已写入的内容',
+ 'Stop and remove what it wrote': '停止并移除已写入的内容',
+ 'Could not remove it from Health Connect': '无法从 Health Connect 中移除',
}
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js
index ba46ca8f2..420a95efb 100644
--- a/frontend/src/store/useStore.js
+++ b/frontend/src/store/useStore.js
@@ -7,6 +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 { mergeStates, localExtras, stampRoutines, stampCustomEx, inUnitOf, keepReset, resetIdsOf, mergeResetIds, entryKey } from '../lib/sync-merge.js'
import { convertStateUnit } from '../lib/units.js'
import { pendingRefCount, settleMedia, loadPending } from '../lib/media-owed.js'
@@ -363,6 +364,7 @@ export const useStore = create((set, get) => {
}
initReminderSync(() => get().S)
+ initHealthSync(() => get().S)
// 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,
@@ -377,12 +379,13 @@ export const useStore = create((set, get) => {
await writeJsonFile(MIRROR_OWNER_FILE, { owner, ts: S._ts || 0 })
}).catch(() => {}))
// Mobile build: mirror the state into a file in the app's data directory (survives WebView
- // storage eviction) and keep the native reminder schedule in step with the weekly plan.
+ // storage eviction), keep the native reminder schedule in step with the weekly plan, and
+ // Health Connect with the log where the user turned that on (lib/health-sync.js).
// `now` skips the wait and returns the write, for a copy that replaced the last one wholesale.
const nativePersist = (now = false) => {
clearTimeout(saveTm)
saveTm = null
- const write = () => { saveTm = null; syncReminder(get().S); return saveMirror() }
+ const write = () => { saveTm = null; syncReminder(get().S); syncHealth(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
new file mode 100644
index 000000000..1cf5b92bc
--- /dev/null
+++ b/frontend/src/views/Settings.health.test.jsx
@@ -0,0 +1,139 @@
+// @vitest-environment happy-dom
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import Settings from './Settings.jsx'
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+
+// #200: the Health Connect card. Only on the Android app, only where Health Connect is there or
+// can be installed, off until switched on, and turning it off asks what happens to what was
+// already written. lib/health-sync.js is mocked; its own tests cover the writing.
+const mocks = vi.hoisted(() => {
+ const state = { S: null, MOBILE: true, android: true, status: { status: 'available', granted: false }, health: { on: false, written: {}, error: null } }
+ state.snapshot = () => ({
+ S: state.S, user: null, update: vi.fn(),
+ replaceState: vi.fn(), setUser: vi.fn(), pullState: vi.fn(), pushState: vi.fn(),
+ signOut: vi.fn(), signOutAll: vi.fn(), resetDemo: vi.fn(), disconnectServer: vi.fn(),
+ })
+ 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.menuSheet = vi.fn()
+ state.toast = vi.fn()
+ return state
+})
+vi.mock('../store/useStore.js', () => {
+ const useStore = selector => selector ? selector(mocks.snapshot()) : mocks.snapshot()
+ useStore.getState = mocks.snapshot
+ return { useStore, DEF: { reminder: { time: '17:30' } }, hasData: () => false }
+})
+vi.mock('../store/useUI.js', () => {
+ const snap = () => ({ toast: mocks.toast, openSheet: vi.fn() })
+ const useUI = selector => selector ? selector(snap()) : snap()
+ useUI.getState = snap
+ return { useUI }
+})
+vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
+vi.mock('../lib/api.js', () => ({ api: vi.fn(), webauthnOK: () => false, passkeyLogin: vi.fn(), passkeyRegister: vi.fn(), IS_ANDROID: false }))
+vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() }))
+vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))
+vi.mock('../lib/mobile.js', () => ({
+ get MOBILE() { return mocks.MOBILE },
+ isAndroid: () => Promise.resolve(mocks.android),
+ shareExport: vi.fn(), syncReminder: vi.fn(),
+}))
+vi.mock('../lib/update.js', () => ({ checkForUpdate: () => Promise.resolve({ hasUpdate: false }), downloadAndInstall: vi.fn() }))
+vi.mock('../lib/health-sync.js', () => ({
+ healthStatus: () => Promise.resolve(mocks.status),
+ loadHealth: () => Promise.resolve(mocks.health),
+ enableHealth: (...a) => mocks.enableHealth(...a),
+ disableHealth: (...a) => mocks.disableHealth(...a),
+ openHealthConnect: (...a) => mocks.openHealthConnect(...a),
+ onHealthChange: () => () => {},
+}))
+vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
+vi.mock('../sheets.jsx', () => ({
+ starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),
+ importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(), menuSheet: (...a) => mocks.menuSheet(...a),
+}))
+
+globalThis.__APP_VERSION__ ??= 'test'
+
+let host, root
+beforeEach(() => {
+ mocks.S = { unit: 'kg', restSec: 90, restPauseSec: 15, sound: false, effort: 'none', gifSize: 'full', workouts: [], routines: [], exWeights: {} }
+ mocks.MOBILE = true
+ 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()
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+})
+afterEach(() => {
+ act(() => root.unmount())
+ host.remove()
+})
+
+const mount = async () => {
+ await act(async () => { root.render(<Settings />) })
+ await act(async () => { await Promise.resolve(); await Promise.resolve() })
+}
+const row = text => [...host.querySelectorAll('.lrow')].find(r => r.textContent.includes(text))
+const writeSwitch = () => row('Write to Health Connect')?.querySelector('[role="switch"]')
+
+describe('Settings — Health Connect', () => {
+ it('is not there on the web build, on iOS, or on a phone without Health Connect', async () => {
+ mocks.MOBILE = false
+ await mount()
+ expect(row('Health Connect')).toBeUndefined()
+
+ mocks.MOBILE = true
+ mocks.android = false
+ await mount()
+ expect(row('Health Connect')).toBeUndefined()
+
+ mocks.android = true
+ mocks.status = { status: 'unsupported', granted: false }
+ await mount()
+ expect(row('Health Connect')).toBeUndefined()
+ })
+
+ it('starts off, and turning it on goes through enableHealth', async () => {
+ await mount()
+ expect(writeSwitch().getAttribute('aria-checked')).toBe('false')
+ expect(row('Open Health Connect')).toBeUndefined()
+ await act(async () => { writeSwitch().click() })
+ expect(mocks.enableHealth).toHaveBeenCalledTimes(1)
+ expect(writeSwitch().getAttribute('aria-checked')).toBe('true')
+ expect(row('Open Health Connect')).toBeTruthy()
+ })
+
+ it('turning it off asks whether to keep or remove what was written', async () => {
+ mocks.health = { on: true, written: { 'opengym-w-w1': { k: 'session', h: 'x' } }, error: null }
+ await mount()
+ act(() => { writeSwitch().click() })
+ expect(mocks.disableHealth).not.toHaveBeenCalled()
+ const items = mocks.menuSheet.mock.calls[0][0].items
+ await act(async () => { await items[1].onClick() })
+ expect(mocks.disableHealth).toHaveBeenCalledWith({ removeWritten: true })
+ expect(writeSwitch().getAttribute('aria-checked')).toBe('false')
+ })
+
+ it('offers to grant the permission again when Health Connect refused it', async () => {
+ mocks.health = { on: true, written: {}, error: 'permission' }
+ await mount()
+ await act(async () => { row('Permission withdrawn').click() })
+ expect(mocks.enableHealth).toHaveBeenCalledTimes(1)
+ })
+
+ it('points to installing Health Connect where it is an app of its own', async () => {
+ mocks.status = { status: 'missing', granted: false }
+ await mount()
+ expect(writeSwitch()).toBeUndefined()
+ await act(async () => { row('Install Health Connect').click() })
+ expect(mocks.openHealthConnect).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx
index d04cc7246..c25ec862e 100644
--- a/frontend/src/views/Settings.jsx
+++ b/frontend/src/views/Settings.jsx
@@ -23,6 +23,7 @@ import { getMediaStatus, subscribeMediaStatus, pendingRefCount } from '../lib/me
import { limitsFrom, fmtMB, MB } from '../lib/media-limits.js'
import { setRestAccent } from '../lib/rest-alert.js'
import { checkForUpdate, downloadAndInstall } from '../lib/update.js'
+import { healthStatus, loadHealth, enableHealth, disableHealth, openHealthConnect, onHealthChange } from '../lib/health-sync.js'
import { forgetCoach } from '../lib/coach-api.js'
import { starterPlanSheet, confirmSheet, importFromApp, importFromHevy, equipmentProfileSheet, plateInventorySheet, menuSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
@@ -503,6 +504,7 @@ export default function Settings() {
</Section>
{(user || MOBILE) && <NotificationsCard S={S} update={update} toast={toast} />}
+ {MOBILE && android && <HealthConnectCard S={S} toast={toast} />}
{/* ---------- equipment ---------- */}
<EquipmentCard S={S} update={update} />
@@ -695,6 +697,75 @@ function effortHelpSheet() {
</>)
}
+// Android app: writing finished workouts and weigh-ins to Health Connect (#200), the phone's
+// own store for health data, where other apps can read them. A fact about this phone, kept in
+// its own file (lib/health-sync.js) and not in S, so it never switches on anywhere else. The card
+// stays out of the way on a phone without Health Connect, and only points to installing it on
+// Android 13 and lower, where it is an app of its own.
+function HealthConnectCard({ S, toast }) {
+ const [st, setSt] = useState(null)
+ const [h, setH] = useState(null)
+ const [busy, setBusy] = useState(false)
+ useEffect(() => {
+ let gone = false
+ Promise.all([healthStatus(), loadHealth()]).then(([s, f]) => { if (!gone) { setSt(s); setH(f) } }).catch(() => {})
+ const off = onHealthChange(f => { if (!gone) setH(f) })
+ return () => { gone = true; off() }
+ }, [])
+ if (!st || !h || st.status === 'unsupported') return null
+
+ if (st.status !== 'available') return (
+ <Section title={t('Health Connect')}>
+ <Row icon="heart" iconTint="var(--red)" title={t('Health Connect')}
+ subtitle={st.status === 'update'
+ ? t('Update Health Connect to share workouts and weigh-ins with other apps.')
+ : t('Install Health Connect to share workouts and weigh-ins with other apps.')}
+ accessory="chevron" onClick={() => openHealthConnect().catch(() => {})} />
+ </Section>
+ )
+
+ const turnOn = async () => {
+ setBusy(true)
+ try {
+ const r = await enableHealth(S)
+ if (r.health) setH(r.health)
+ else setH(await loadHealth())
+ if (r.ok) toast(t('Writing to Health Connect'))
+ else toast(r.reason === 'denied' ? t('Health Connect permission not granted') : t('Could not write to Health Connect'))
+ } catch { toast(t('Could not write to Health Connect')) }
+ setBusy(false)
+ }
+ const turnOff = removeWritten => async () => {
+ setBusy(true)
+ try { setH(await disableHealth({ removeWritten })) }
+ catch { toast(t('Could not remove it from Health Connect')) }
+ setBusy(false)
+ }
+ // Off can mean two things for what is already there, so it asks; closing the sheet keeps it on.
+ const askOff = () => menuSheet({
+ title: t('Stop writing to Health Connect?'),
+ subtitle: t('What openGym already wrote can stay in Health Connect as your data, or be removed from it.'),
+ items: [
+ { icon: 'check', label: t('Stop, keep what it wrote'), onClick: turnOff(false) },
+ { icon: 'trash', label: t('Stop and remove what it wrote'), danger: true, onClick: turnOff(true) },
+ ],
+ })
+
+ return (
+ <Section title={t('Health Connect')}
+ footer={h.on ? t('Workouts and weigh-ins go to Health Connect when you finish or change them. openGym reads nothing back.') : null}>
+ <Row icon="heart" iconTint="var(--red)" title={t('Write to Health Connect')}
+ 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={t('Open Health Connect')}
+ accessory="chevron" onClick={() => openHealthConnect().catch(() => {})} />}
+ </Section>
+ )
+}
+
function NotificationsCard({ S, update, toast }) {
if (MOBILE) return <MobileReminderCard S={S} update={update} toast={toast} />
return <PushCard S={S} update={update} toast={toast} />