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.

feat(android): show the rest countdown in a notification

vitox013b092c015ee69
diff --git a/docs/MOBILE.md b/docs/MOBILE.md
index 7ef63c3f5..11d248530 100644
--- a/docs/MOBILE.md
+++ b/docs/MOBILE.md
@@ -160,6 +160,7 @@ membership, the distribution certificate and profile as protected file variables
- **License:** openGym is AGPL-3.0, which by itself sits badly with app-store terms of
service. `NOTICE.md` carries an app-store exception (an additional permission under
AGPL §7) granted by the copyright holder — relevant only if store distribution ever happens.
-- The app requests notification permission only when the workout-day reminder is switched
- on, and (on Android) declares `SCHEDULE_EXACT_ALARM` so the reminder fires to the minute
- where the user allows it.
+- The app requests notification permission when the workout-day reminder is switched on,
+ and again for the rest-timer alarm if it is still unanswered. On Android it declares
+ `SCHEDULE_EXACT_ALARM` so the reminder and the rest alert can fire on time with the
+ screen locked, where the user allows exact alarms.
diff --git a/docs/SELF_HOSTING.md b/docs/SELF_HOSTING.md
index e256873fd..ef086b631 100644
--- a/docs/SELF_HOSTING.md
+++ b/docs/SELF_HOSTING.md
@@ -272,9 +272,11 @@ automatically when they turn the reminder on — it fires at their local time, a
they travel, regardless of what timezone the server itself runs in.
Where it works: any desktop browser, Android Chrome, and on iOS only the app **added to the Home
-Screen** (Safari in a tab has no Web Push). The Android APK does not use Web Push at all — its
-day reminder is a local notification scheduled on the phone, and rest-timer alerts there only
-sound while the app is in the foreground. A reminder that was due while the server was down or
+Screen** (Safari in a tab has no Web Push). The Android APK's day reminder is a local
+notification. Its rest timer is a local alarm: the notification shade shows the time left as a
+shrinking bar, and the end alert still fires with the screen off. The lock screen shows that
+notification only when notifications are enabled and the system is set to show them there. A paired account still gets the server push if that alarm
+cannot be scheduled. A reminder that was due while the server was down or
restarting is still sent up to 15 minutes late, once; the browser re-registers its subscription
with the server on every signed-in start, so a subscription the server lost heals itself.
diff --git a/frontend/android/app/src/main/AndroidManifest.xml b/frontend/android/app/src/main/AndroidManifest.xml
index cd316aa9b..1fe604391 100644
--- a/frontend/android/app/src/main/AndroidManifest.xml
+++ b/frontend/android/app/src/main/AndroidManifest.xml
@@ -30,6 +30,24 @@
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" />
</provider>
+ <!-- Rest-over alarm. Explicit class, no intent-filter: only this app can send it. -->
+ <receiver
+ android:name=".RestAlertReceiver"
+ android:exported="false" />
+
+ <!-- Reposts the rest countdown every second so the notification shade keeps the
+ clock and a shrinking bar after the WebView is frozen. The lock screen shows
+ it only when the user allows notifications there. specialUse: this is a timer,
+ not media playback. -->
+ <service
+ android:name=".RestTimerService"
+ android:exported="false"
+ android:foregroundServiceType="specialUse">
+ <property
+ android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
+ android:value="Shows how long is left in the rest between sets." />
+ </service>
+
<!-- Gym check-in scanner (@capacitor-mlkit/barcode-scanning): pre-fetch the ML Kit
barcode model at install time so the first scan doesn't wait on a download. -->
<meta-data android:name="com.google.mlkit.vision.DEPENDENCIES" android:value="barcode_ui" />
@@ -43,6 +61,13 @@
on Android 12+. Where it isn't granted, scheduling silently falls back to inexact
alarms — the reminder still arrives, just not to the minute. -->
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
+ <!-- Same exact-alarm permission as the day reminder. Where it isn't granted, the rest
+ alert falls back to an inexact alarm and, if this phone is paired, to Web Push. -->
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
+ <uses-permission android:name="android.permission.VIBRATE" />
+ <uses-permission android:name="android.permission.WAKE_LOCK" />
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
+ <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" />
</manifest>
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 344028b2e..adf4a4152 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
@@ -8,6 +8,7 @@ public class MainActivity extends BridgeActivity {
public void onCreate(Bundle savedInstanceState) {
registerPlugin(InstallPlugin.class);
registerPlugin(PrintPlugin.class);
+ registerPlugin(RestAlertPlugin.class);
super.onCreate(savedInstanceState);
}
}
diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlert.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlert.java
new file mode 100644
index 000000000..8e55285c7
--- /dev/null
+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlert.java
@@ -0,0 +1,481 @@
+package ch.duartesantos.opengym;
+
+import android.app.AlarmManager;
+import android.app.Notification;
+import android.app.NotificationChannel;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.content.Context;
+import android.content.res.ColorStateList;
+import android.content.Intent;
+import android.widget.RemoteViews;
+import android.media.AudioAttributes;
+import android.media.AudioFormat;
+import android.media.AudioTrack;
+import android.os.Build;
+import android.os.PowerManager;
+import android.os.VibrationEffect;
+import android.os.Vibrator;
+import android.util.Log;
+
+/**
+ * Alarm for the rest between sets. The WebView timer does not run with the screen locked.
+ * This posts a notification for the countdown and, when the rest ends, the end alert and tone.
+ * The shade shows it when notifications are allowed. The lock screen shows it only when
+ * the user also allows notifications there.
+ */
+public final class RestAlert {
+ static final String ACTION = "ch.duartesantos.opengym.action.REST_OVER";
+ static final String ACTION_PAUSE = "ch.duartesantos.opengym.rest.PAUSE";
+ static final String ACTION_MINUS = "ch.duartesantos.opengym.rest.MINUS";
+ static final String ACTION_PLUS = "ch.duartesantos.opengym.rest.PLUS";
+ static final String ACTION_SKIP = "ch.duartesantos.opengym.rest.SKIP";
+ static final String ACTION_ACCENT = "ch.duartesantos.opengym.rest.ACCENT";
+ static final String CHANNEL_ID = "rest-over";
+ private static volatile boolean toneSuppressed;
+ private static String lastAlertTitle = "Rest over";
+ private static boolean lastSound = true;
+ private static String lastChannel = CHANNEL_ID;
+ private static String labPause = "Pause";
+ private static String labResume = "Resume";
+ private static String labMinus = "\u2212 15s";
+ private static String labPlus = "+ 15s";
+ private static String labSkip = "Skip";
+ private static int lastAccent = 0xFF30D158;
+ private static int lastInk = 0xFF000000;
+ static final int COUNTDOWN_ID = 41;
+ static final int NOTIFICATION_ID = 42;
+ static final String COUNTDOWN_CHANNEL_ID = "rest-countdown";
+ private static final int FLAGS = PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE;
+ private static final int RATE = 22050;
+ private static final long[] VIBRATE = new long[] {0, 200, 100, 200, 100, 400};
+
+ private static AudioTrack current;
+
+ private RestAlert() {}
+
+ public static void schedule(Context ctx, long at, int id, String title, boolean sound,
+ String channelId, String visibility, String importance, boolean localOnly,
+ String countdownTitle, long totalMs) {
+ if (channelId == null || channelId.isEmpty()) channelId = CHANNEL_ID;
+ // A new rest may play its tone. The in-app beep sets this only for the one it covers.
+ toneSuppressed = false;
+ Intent intent = alarmIntent(ctx);
+ intent.putExtra("id", id);
+ intent.putExtra("title", title == null ? "" : title);
+ intent.putExtra("sound", sound);
+ intent.putExtra("channelId", channelId);
+ intent.putExtra("visibility", visibility == null ? "public" : visibility);
+ intent.putExtra("importance", importance == null ? "high" : importance);
+ intent.putExtra("localOnly", localOnly);
+ PendingIntent pi = PendingIntent.getBroadcast(ctx, id, intent, FLAGS);
+ AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
+ boolean exact = canExact(am);
+ try {
+ if (exact) am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pi);
+ else am.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pi);
+ } catch (SecurityException e) {
+ am.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pi);
+ exact = false;
+ }
+ if (!exact) Log.w("openGym", "exact alarms not allowed; rest alert may be late with the screen off");
+ if (Build.VERSION.SDK_INT >= 26) {
+ NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
+ ensureChannel(ctx, nm, channelId, importanceOf(importance), visibilityOf(visibility));
+ }
+ lastAlertTitle = title == null ? "Rest over" : title;
+ lastSound = sound;
+ lastChannel = channelId;
+ startCountdown(ctx, at, totalMs, countdownTitle);
+ }
+
+ public static void suppressTone() { toneSuppressed = true; }
+
+ public static void allowTone() { toneSuppressed = false; }
+
+ public static void setAccentColor(int accent, int ink) {
+ lastAccent = accent;
+ lastInk = ink;
+ }
+
+ public static void setLabels(String pause, String resume, String minus, String plus, String skip) {
+ if (pause != null && !pause.isEmpty()) labPause = pause;
+ if (resume != null && !resume.isEmpty()) labResume = resume;
+ if (minus != null && !minus.isEmpty()) labMinus = minus;
+ if (plus != null && !plus.isEmpty()) labPlus = plus;
+ if (skip != null && !skip.isEmpty()) labSkip = skip;
+ }
+
+ public static void cancel(Context ctx, int id) {
+ stopCountdown(ctx);
+ AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
+ PendingIntent pi = PendingIntent.getBroadcast(ctx, id, alarmIntent(ctx), FLAGS);
+ am.cancel(pi);
+ pi.cancel();
+ NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
+ nm.cancel(id);
+ }
+
+ /** Runs off the main thread. Holds the CPU until the tone has finished. */
+ public static void fire(Context ctx, Intent intent) {
+ PowerManager.WakeLock cpu = null;
+ try {
+ PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
+ cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "opengym:rest");
+ cpu.acquire(10_000);
+ } catch (Exception ignored) { /* tone still attempts without the lock */ }
+ try {
+ pokeScreen(ctx);
+ boolean shown = showNotification(ctx, intent);
+ if (!shown) vibrateFallback(ctx);
+ // One beep. The in-app tone already played if the page was visible, and it asked
+ // us to skip this one. Locked, the page never gets there, so this is the beep.
+ boolean play = intent.getBooleanExtra("sound", true) && !toneSuppressed;
+ toneSuppressed = false;
+ if (play) playSound(ctx);
+ // The countdown card is the foreground-service notification. Drop it once the
+ // "rest over" alert is up, including when the WebView is frozen.
+ stopCountdown(ctx);
+ } finally {
+ if (cpu != null && cpu.isHeld()) cpu.release();
+ }
+ }
+
+ private static Intent alarmIntent(Context ctx) {
+ Intent intent = new Intent(ctx, RestAlertReceiver.class);
+ intent.setAction(ACTION);
+ return intent;
+ }
+
+ private static boolean canExact(AlarmManager am) {
+ if (Build.VERSION.SDK_INT < 31) return true;
+ return am.canScheduleExactAlarms();
+ }
+
+ @SuppressWarnings("deprecation")
+ private static void pokeScreen(Context ctx) {
+ // Best effort so the notification is already lit. Newer Android builds ignore
+ // ACQUIRE_CAUSES_WAKEUP; the posted notification is what the shade still shows.
+ try {
+ PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
+ PowerManager.WakeLock screen = pm.newWakeLock(
+ PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,
+ "opengym:rest-screen");
+ screen.acquire(3000);
+ } catch (Exception ignored) { /* */ }
+ }
+
+ @SuppressWarnings("deprecation")
+ private static boolean showNotification(Context ctx, Intent intent) {
+ String title = intent.getStringExtra("title");
+ if (title == null || title.isEmpty()) title = "Rest over — next set!";
+ String channelId = intent.getStringExtra("channelId");
+ if (channelId == null || channelId.isEmpty()) channelId = CHANNEL_ID;
+ int id = intent.getIntExtra("id", NOTIFICATION_ID);
+ boolean localOnly = intent.getBooleanExtra("localOnly", false);
+ int visibility = visibilityOf(intent.getStringExtra("visibility"));
+ NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
+ if (Build.VERSION.SDK_INT >= 24 && !nm.areNotificationsEnabled()) return false;
+ ensureChannel(ctx, nm, channelId, importanceOf(intent.getStringExtra("importance")), visibility);
+ Notification.Builder b = Build.VERSION.SDK_INT >= 26
+ ? new Notification.Builder(ctx, channelId)
+ : new Notification.Builder(ctx);
+ b.setSmallIcon(R.drawable.ic_stat_dumbbell)
+ .setContentTitle(title)
+ .setWhen(System.currentTimeMillis())
+ .setShowWhen(true)
+ .setAutoCancel(true)
+ .setCategory(Notification.CATEGORY_ALARM)
+ .setVisibility(visibility)
+ .setColor(lastAccent)
+ .setContentIntent(openApp(ctx))
+ .setVibrate(VIBRATE);
+ if (Build.VERSION.SDK_INT >= 26) b.setOnlyAlertOnce(false);
+ else b.setPriority(Notification.PRIORITY_HIGH);
+ if (localOnly) b.setLocalOnly(true);
+ try {
+ nm.notify(id, b.build());
+ return true;
+ } catch (Exception e) {
+ return false;
+ }
+ }
+
+ private static void ensureChannel(Context ctx, NotificationManager nm, String channelId, int importance, int visibility) {
+ if (Build.VERSION.SDK_INT < 26) return;
+ if (nm.getNotificationChannel(channelId) != null) return;
+ NotificationChannel channel = new NotificationChannel(
+ channelId, ctx.getString(R.string.rest_channel_name), importance);
+ channel.setDescription(ctx.getString(R.string.rest_channel_desc));
+ channel.setLockscreenVisibility(visibility);
+ channel.enableVibration(true);
+ channel.setVibrationPattern(VIBRATE);
+ // Silent on purpose. The beep is the in-app tone or playSound(), not a second ding
+ // from this channel.
+ channel.setSound(null, null);
+ nm.createNotificationChannel(channel);
+ }
+
+ private static PendingIntent openApp(Context ctx) {
+ Intent open = new Intent(ctx, MainActivity.class);
+ open.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
+ return PendingIntent.getActivity(ctx, NOTIFICATION_ID + 1, open, FLAGS);
+ }
+
+ private static int importanceOf(String name) {
+ if ("max".equals(name)) return NotificationManager.IMPORTANCE_MAX;
+ if ("low".equals(name)) return NotificationManager.IMPORTANCE_LOW;
+ if ("min".equals(name)) return NotificationManager.IMPORTANCE_MIN;
+ if ("default".equals(name)) return NotificationManager.IMPORTANCE_DEFAULT;
+ return NotificationManager.IMPORTANCE_HIGH;
+ }
+
+ private static int visibilityOf(String name) {
+ if ("secret".equals(name)) return Notification.VISIBILITY_SECRET;
+ if ("private".equals(name)) return Notification.VISIBILITY_PRIVATE;
+ return Notification.VISIBILITY_PUBLIC;
+ }
+
+ @SuppressWarnings("deprecation")
+ private static void vibrateFallback(Context ctx) {
+ try {
+ Vibrator vibrator = (Vibrator) ctx.getSystemService(Context.VIBRATOR_SERVICE);
+ if (vibrator == null) return;
+ if (Build.VERSION.SDK_INT >= 26) vibrator.vibrate(VibrationEffect.createWaveform(VIBRATE, -1));
+ else vibrator.vibrate(VIBRATE, -1);
+ } catch (Exception ignored) { /* */ }
+ }
+
+ static void updateAlarm(Context ctx, long at) {
+ if (at <= System.currentTimeMillis()) {
+ cancelAlarmOnly(ctx, NOTIFICATION_ID);
+ return;
+ }
+ Intent intent = alarmIntent(ctx);
+ intent.putExtra("id", NOTIFICATION_ID);
+ intent.putExtra("title", lastAlertTitle);
+ intent.putExtra("sound", lastSound);
+ intent.putExtra("channelId", lastChannel);
+ intent.putExtra("visibility", "public");
+ intent.putExtra("importance", "high");
+ intent.putExtra("localOnly", false);
+ PendingIntent pi = PendingIntent.getBroadcast(ctx, NOTIFICATION_ID, intent, FLAGS);
+ AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
+ try {
+ if (canExact(am)) am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pi);
+ else am.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pi);
+ } catch (SecurityException e) {
+ am.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pi);
+ }
+ }
+
+ static void cancelAlarmOnly(Context ctx, int id) {
+ AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
+ PendingIntent pi = PendingIntent.getBroadcast(ctx, id, alarmIntent(ctx), FLAGS);
+ am.cancel(pi);
+ }
+
+ static void startCountdown(Context ctx, long endsAt, long totalMs, String title) {
+ Intent i = new Intent(ctx, RestTimerService.class);
+ i.putExtra("endsAt", endsAt);
+ i.putExtra("totalMs", totalMs);
+ i.putExtra("title", title == null || title.isEmpty() ? "Rest" : title);
+ i.putExtra("pause", labPause);
+ i.putExtra("resume", labResume);
+ i.putExtra("minus", labMinus);
+ i.putExtra("plus", labPlus);
+ i.putExtra("skip", labSkip);
+ i.putExtra("accent", lastAccent);
+ i.putExtra("ink", lastInk);
+ try {
+ if (Build.VERSION.SDK_INT >= 26) ctx.startForegroundService(i);
+ else ctx.startService(i);
+ } catch (Exception e) {
+ Log.w("openGym", "rest countdown not started", e);
+ }
+ }
+
+ static void stopCountdown(Context ctx) {
+ try {
+ ctx.stopService(new Intent(ctx, RestTimerService.class));
+ } catch (Exception ignored) { /* already gone */ }
+ }
+
+ /**
+ * One clock and one bar, in both the collapsed and the expanded card. The standard
+ * title/text/subtext slots are left empty: Samsung prints each of them, which stacked
+ * the same time three times next to the bar.
+ */
+ @SuppressWarnings("deprecation")
+ static Notification countdownNotification(Context ctx, long leftMs, long totalMs, boolean paused,
+ String pause, String resume, String minus, String plus, String skip,
+ int accent, int ink) {
+ int max = (int) Math.max(1, Math.round(totalMs / 1000.0));
+ int left = (int) Math.min(max, (Math.max(0, leftMs) + 999) / 1000);
+ String clock = clock(left);
+ NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
+ ensureCountdownChannel(ctx, nm);
+ RemoteViews compact = new RemoteViews(ctx.getPackageName(), R.layout.rest_countdown);
+ fillClock(compact, clock, max, left, accent);
+ RemoteViews expanded = new RemoteViews(ctx.getPackageName(), R.layout.rest_countdown_big);
+ fillClock(expanded, clock, max, left, accent);
+ applyAccent(expanded, accent, ink);
+ expanded.setTextViewText(R.id.rest_pause, paused ? resume : pause);
+ expanded.setTextViewText(R.id.rest_minus, minus);
+ expanded.setTextViewText(R.id.rest_plus, plus);
+ expanded.setTextViewText(R.id.rest_skip, skip);
+ expanded.setOnClickPendingIntent(R.id.rest_pause, control(ctx, ACTION_PAUSE, 51));
+ expanded.setOnClickPendingIntent(R.id.rest_minus, control(ctx, ACTION_MINUS, 52));
+ expanded.setOnClickPendingIntent(R.id.rest_plus, control(ctx, ACTION_PLUS, 53));
+ expanded.setOnClickPendingIntent(R.id.rest_skip, control(ctx, ACTION_SKIP, 54));
+ Notification.Builder b = Build.VERSION.SDK_INT >= 26
+ ? new Notification.Builder(ctx, COUNTDOWN_CHANNEL_ID)
+ : new Notification.Builder(ctx);
+ b.setSmallIcon(R.drawable.ic_stat_dumbbell)
+ .setShowWhen(false)
+ .setOngoing(true)
+ .setCategory(Notification.CATEGORY_PROGRESS)
+ .setVisibility(Notification.VISIBILITY_PUBLIC)
+ .setColor(accent)
+ .setContentIntent(openApp(ctx))
+ .setLocalOnly(true);
+ if (Build.VERSION.SDK_INT >= 24) {
+ b.setCustomContentView(compact);
+ b.setCustomBigContentView(expanded);
+ b.setStyle(new Notification.DecoratedCustomViewStyle());
+ } else {
+ b.setContentTitle(clock);
+ b.setProgress(max, left, false);
+ }
+ if (Build.VERSION.SDK_INT >= 26) b.setOnlyAlertOnce(true);
+ else b.setPriority(Notification.PRIORITY_DEFAULT);
+ // Android 12+ holds the first foreground-service notification for 10 seconds
+ // unless the notification asks to be shown immediately. Later rests in the
+ // same process skip that hold, which is why only the first one looked late.
+ if (Build.VERSION.SDK_INT >= 31) {
+ b.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE);
+ }
+ return b.build();
+ }
+
+ private static void fillClock(RemoteViews views, String clock, int max, int left, int accent) {
+ views.setTextViewText(R.id.rest_clock, clock);
+ views.setProgressBar(R.id.rest_bar, max, left, false);
+ if (Build.VERSION.SDK_INT >= 31) {
+ views.setColorStateList(R.id.rest_bar, "setProgressTintList", ColorStateList.valueOf(accent));
+ }
+ }
+
+ private static void applyAccent(RemoteViews views, int accent, int ink) {
+ views.setTextColor(R.id.rest_pause, accent);
+ views.setTextColor(R.id.rest_minus, accent);
+ views.setTextColor(R.id.rest_plus, accent);
+ views.setTextColor(R.id.rest_skip, ink);
+ if (Build.VERSION.SDK_INT >= 31) {
+ views.setColorStateList(R.id.rest_skip, "setBackgroundTintList", ColorStateList.valueOf(accent));
+ }
+ }
+
+ private static PendingIntent control(Context ctx, String action, int code) {
+ Intent i = new Intent(ctx, RestTimerService.class);
+ i.setAction(action);
+ return PendingIntent.getService(ctx, code, i, FLAGS);
+ }
+
+ static String clock(int sec) {
+ return (sec / 60) + ":" + (sec % 60 < 10 ? "0" : "") + (sec % 60);
+ }
+
+ private static void ensureCountdownChannel(Context ctx, NotificationManager nm) {
+ if (Build.VERSION.SDK_INT < 26) return;
+ if (nm.getNotificationChannel(COUNTDOWN_CHANNEL_ID) != null) return;
+ NotificationChannel channel = new NotificationChannel(
+ COUNTDOWN_CHANNEL_ID,
+ ctx.getString(R.string.rest_countdown_channel_name),
+ NotificationManager.IMPORTANCE_DEFAULT);
+ channel.setDescription(ctx.getString(R.string.rest_channel_desc));
+ channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
+ channel.setSound(null, null);
+ channel.enableVibration(false);
+ nm.createNotificationChannel(channel);
+ }
+
+ private static void playSound(Context ctx) {
+ playClip(ctx, renderBeeps());
+ }
+
+ private static void playClip(Context ctx, short[] samples) {
+ AudioTrack track = null;
+ try {
+ int bytes = samples.length * 2;
+ int min = AudioTrack.getMinBufferSize(RATE, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
+ if (min > bytes) {
+ short[] padded = new short[(min / 2) + 1];
+ System.arraycopy(samples, 0, padded, 0, samples.length);
+ samples = padded;
+ bytes = samples.length * 2;
+ }
+ track = new AudioTrack.Builder()
+ .setAudioAttributes(new AudioAttributes.Builder()
+ .setUsage(AudioAttributes.USAGE_MEDIA)
+ .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
+ .build())
+ .setAudioFormat(new AudioFormat.Builder()
+ .setEncoding(AudioFormat.ENCODING_PCM_16BIT)
+ .setSampleRate(RATE)
+ .setChannelMask(AudioFormat.CHANNEL_OUT_MONO)
+ .build())
+ .setBufferSizeInBytes(bytes)
+ .setTransferMode(AudioTrack.MODE_STATIC)
+ .build();
+ if (track.getState() != AudioTrack.STATE_INITIALIZED) return;
+ track.write(samples, 0, samples.length);
+ track.setVolume(1f);
+ stopCurrent();
+ current = track;
+ track.play();
+ Thread.sleep((samples.length * 1000L / RATE) + 60);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ } catch (Exception ignored) { /* the notification still posted */ }
+ finally {
+ if (track != null) {
+ try { track.pause(); } catch (Exception ignored) { /* */ }
+ try { track.release(); } catch (Exception ignored) { /* */ }
+ if (current == track) current = null;
+ }
+ }
+ }
+
+ private static synchronized void stopCurrent() {
+ if (current == null) return;
+ try { current.pause(); } catch (Exception ignored) { /* */ }
+ try { current.release(); } catch (Exception ignored) { /* */ }
+ current = null;
+ }
+
+ /** Same three tones the in-page beep uses (880, 880, 1320), at full scale. */
+ static short[] renderBeeps() {
+ int[] freq = {880, 880, 1320};
+ double[] dur = {0.15, 0.15, 0.40};
+ double[] gap = {0.10, 0.10, 0};
+ int total = 0;
+ for (int i = 0; i < freq.length; i++) total += (int) (RATE * (dur[i] + gap[i]));
+ short[] out = new short[total];
+ int pos = 0;
+ for (int i = 0; i < freq.length; i++) {
+ int n = (int) (RATE * dur[i]);
+ int g = (int) (RATE * gap[i]);
+ int fade = Math.max(1, RATE / 200);
+ for (int s = 0; s < n; s++) {
+ double env = 1;
+ if (s < fade) env = s / (double) fade;
+ else if (s > n - fade) env = (n - s) / (double) fade;
+ double wave = Math.sin(2 * Math.PI * freq[i] * s / RATE);
+ out[pos++] = (short) Math.max(-32767, Math.min(32767, wave * env * 0.85 * 32767));
+ }
+ pos += g;
+ }
+ return out;
+ }
+}
diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlertPlugin.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlertPlugin.java
new file mode 100644
index 000000000..be522a877
--- /dev/null
+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlertPlugin.java
@@ -0,0 +1,120 @@
+package ch.duartesantos.opengym;
+
+import android.content.Context;
+import android.content.Intent;
+import com.getcapacitor.JSObject;
+import com.getcapacitor.Plugin;
+import com.getcapacitor.PluginCall;
+import com.getcapacitor.PluginMethod;
+import com.getcapacitor.annotation.CapacitorPlugin;
+
+/**
+ * Schedules the rest-over alarm from the WebView. The receiver fires it later, so the
+ * WebView being frozen does not matter.
+ *
+ * Usage from JS:
+ * import { registerPlugin } from '@capacitor/core';
+ * const RestAlert = registerPlugin('RestAlert');
+ * await RestAlert.schedule({ id, at, title, sound, channelId, visibility, importance, localOnly });
+ * await RestAlert.cancel({ id });
+ */
+@CapacitorPlugin(name = "RestAlert")
+public class RestAlertPlugin extends Plugin {
+ private static RestAlertPlugin instance;
+
+ @Override
+ public void load() {
+ instance = this;
+ super.load();
+ }
+
+ static void emit(String type, long endsAt, long totalMs, long leftMs, boolean paused) {
+ if (instance == null) return;
+ JSObject data = new JSObject();
+ data.put("type", type);
+ data.put("endsAt", endsAt);
+ data.put("totalMs", totalMs);
+ data.put("leftMs", leftMs);
+ data.put("paused", paused);
+ instance.notifyListeners("rest", data);
+ }
+
+ @PluginMethod
+ public void schedule(PluginCall call) {
+ Context ctx = getContext();
+ if (ctx == null) {
+ call.reject("no context");
+ return;
+ }
+ long at = number(call, "at", -1);
+ if (at <= System.currentTimeMillis()) {
+ call.reject("at must be in the future");
+ return;
+ }
+ RestAlert.setAccentColor((int) number(call, "accent", 0xFF30D158L), (int) number(call, "ink", 0xFF000000L));
+ RestAlert.setLabels(
+ call.getString("pause", "Pause"),
+ call.getString("resume", "Resume"),
+ call.getString("minus", "\u2212 15s"),
+ call.getString("plus", "+ 15s"),
+ call.getString("skip", "Skip")
+ );
+ RestAlert.schedule(
+ ctx.getApplicationContext(),
+ at,
+ (int) number(call, "id", RestAlert.NOTIFICATION_ID),
+ call.getString("title", "Rest over"),
+ !Boolean.FALSE.equals(call.getBoolean("sound", Boolean.TRUE)),
+ call.getString("channelId", RestAlert.CHANNEL_ID),
+ call.getString("visibility", "public"),
+ call.getString("importance", "high"),
+ Boolean.TRUE.equals(call.getBoolean("localOnly", Boolean.FALSE)),
+ call.getString("countdownTitle", "Rest"),
+ number(call, "totalMs", 0)
+ );
+ call.resolve();
+ }
+
+ @PluginMethod
+ public void cancel(PluginCall call) {
+ Context ctx = getContext();
+ if (ctx == null) {
+ call.reject("no context");
+ return;
+ }
+ RestAlert.cancel(ctx.getApplicationContext(), (int) number(call, "id", RestAlert.NOTIFICATION_ID));
+ call.resolve();
+ }
+
+ @PluginMethod
+ public void setAccent(PluginCall call) {
+ int color = (int) number(call, "accent", 0xFF30D158L);
+ int ink = (int) number(call, "ink", 0xFF000000L);
+ RestAlert.setAccentColor(color, ink);
+ Context ctx = getContext();
+ if (ctx != null) {
+ Intent i = new Intent(ctx, RestTimerService.class);
+ i.setAction(RestAlert.ACTION_ACCENT);
+ i.putExtra("accent", color);
+ i.putExtra("ink", ink);
+ try { ctx.startService(i); } catch (Exception ignored) { /* no rest running */ }
+ }
+ call.resolve();
+ }
+
+ @PluginMethod
+ public void suppressTone(PluginCall call) {
+ RestAlert.suppressTone();
+ call.resolve();
+ }
+
+ // PluginCall.getLong only accepts a Long, and a JS timestamp often arrives as a Double
+ // (or a Long when it no longer fits in an int). Number covers all three.
+ private static long number(PluginCall call, String name, long fallback) {
+ JSObject data = call.getData();
+ if (data == null) return fallback;
+ Object value = data.opt(name);
+ if (value instanceof Number) return ((Number) value).longValue();
+ return fallback;
+ }
+}
diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlertReceiver.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlertReceiver.java
new file mode 100644
index 000000000..71bc8731f
--- /dev/null
+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlertReceiver.java
@@ -0,0 +1,22 @@
+package ch.duartesantos.opengym;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+
+/** Fired by AlarmManager when a rest ends, including while the screen is locked. */
+public class RestAlertReceiver extends BroadcastReceiver {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ if (intent == null) return;
+ final PendingResult pending = goAsync();
+ final Context app = context.getApplicationContext();
+ new Thread(() -> {
+ try {
+ RestAlert.fire(app, intent);
+ } finally {
+ pending.finish();
+ }
+ }, "opengym-rest").start();
+ }
+}
diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestTimerService.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestTimerService.java
new file mode 100644
index 000000000..f1c3ae950
--- /dev/null
+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestTimerService.java
@@ -0,0 +1,186 @@
+package ch.duartesantos.opengym;
+
+import android.app.Notification;
+import android.app.Service;
+import android.content.Intent;
+import android.content.pm.ServiceInfo;
+import android.os.Build;
+import android.os.Handler;
+import android.os.IBinder;
+import android.os.Looper;
+
+/**
+ * Foreground while a rest is running. Reposts one clock and one bar every second, and
+ * applies the same controls as the in-app timer: pause, −15s, +15s, skip.
+ */
+public class RestTimerService extends Service {
+ private final Handler handler = new Handler(Looper.getMainLooper());
+ private long endsAt;
+ private long totalMs;
+ private long pausedLeft;
+ private boolean paused;
+ private boolean running;
+ private String pauseLabel = "Pause";
+ private String resumeLabel = "Resume";
+ private String minusLabel = "\u2212 15s";
+ private String plusLabel = "+ 15s";
+ private String skipLabel = "Skip";
+ private int accent = 0xFF30D158;
+ private int ink = 0xFF000000;
+ private final Runnable tick = new Runnable() {
+ @Override
+ public void run() {
+ if (!running || paused || endsAt <= 0) return;
+ show();
+ if (endsAt > System.currentTimeMillis()) handler.postDelayed(this, 1000);
+ }
+ };
+
+ @Override
+ public IBinder onBind(Intent intent) {
+ return null;
+ }
+
+ @Override
+ public int onStartCommand(Intent intent, int flags, int startId) {
+ String action = intent == null ? null : intent.getAction();
+ if (RestAlert.ACTION_ACCENT.equals(action)) {
+ if (!running) {
+ stopSelf();
+ return START_NOT_STICKY;
+ }
+ accent = intent.getIntExtra("accent", accent);
+ ink = intent.getIntExtra("ink", ink);
+ RestAlert.setAccentColor(accent, ink);
+ show();
+ return START_NOT_STICKY;
+ }
+ if (RestAlert.ACTION_SKIP.equals(action)) {
+ finishSkip();
+ return START_NOT_STICKY;
+ }
+ if (RestAlert.ACTION_PAUSE.equals(action)) {
+ if (running) togglePause();
+ return START_NOT_STICKY;
+ }
+ if (RestAlert.ACTION_MINUS.equals(action)) {
+ if (running) nudge(-15_000);
+ return START_NOT_STICKY;
+ }
+ if (RestAlert.ACTION_PLUS.equals(action)) {
+ if (running) nudge(15_000);
+ return START_NOT_STICKY;
+ }
+ long nextEnd = intent == null ? 0 : intent.getLongExtra("endsAt", 0);
+ if (nextEnd <= System.currentTimeMillis()) {
+ stopForegroundCompat();
+ stopSelf();
+ return START_NOT_STICKY;
+ }
+ endsAt = nextEnd;
+ long passed = intent.getLongExtra("totalMs", 0);
+ totalMs = passed > 0 ? passed : Math.max(1000, endsAt - System.currentTimeMillis());
+ paused = false;
+ running = true;
+ pauseLabel = text(intent, "pause", pauseLabel);
+ resumeLabel = text(intent, "resume", resumeLabel);
+ minusLabel = text(intent, "minus", minusLabel);
+ plusLabel = text(intent, "plus", plusLabel);
+ skipLabel = text(intent, "skip", skipLabel);
+ if (intent != null && intent.hasExtra("accent")) accent = intent.getIntExtra("accent", accent);
+ if (intent != null && intent.hasExtra("ink")) ink = intent.getIntExtra("ink", ink);
+ handler.removeCallbacks(tick);
+ tick.run();
+ return START_NOT_STICKY;
+ }
+
+ @Override
+ public void onDestroy() {
+ running = false;
+ handler.removeCallbacks(tick);
+ endsAt = 0;
+ stopForegroundCompat();
+ super.onDestroy();
+ }
+
+ private void togglePause() {
+ if (!paused) {
+ pausedLeft = Math.max(0, endsAt - System.currentTimeMillis());
+ paused = true;
+ handler.removeCallbacks(tick);
+ RestAlert.cancelAlarmOnly(this, RestAlert.NOTIFICATION_ID);
+ } else {
+ endsAt = System.currentTimeMillis() + pausedLeft;
+ paused = false;
+ RestAlert.updateAlarm(this, endsAt);
+ handler.removeCallbacks(tick);
+ tick.run();
+ }
+ show();
+ emit("pause");
+ }
+
+ private void nudge(long deltaMs) {
+ long now = System.currentTimeMillis();
+ // endsAt may already be in the past when +15 lands on the last second.
+ // Adding the delta to that old deadline would leave the clock stuck.
+ long left = paused ? pausedLeft : Math.max(0, endsAt - now);
+ left += deltaMs;
+ totalMs = Math.max(1000, totalMs + deltaMs);
+ if (left <= 0) {
+ finishSkip();
+ return;
+ }
+ RestAlert.allowTone();
+ if (paused) pausedLeft = left;
+ else {
+ endsAt = now + left;
+ RestAlert.updateAlarm(this, endsAt);
+ handler.removeCallbacks(tick);
+ handler.post(tick);
+ }
+ show();
+ emit("adjust");
+ }
+
+ private void finishSkip() {
+ running = false;
+ handler.removeCallbacks(tick);
+ RestAlert.cancelAlarmOnly(this, RestAlert.NOTIFICATION_ID);
+ RestAlertPlugin.emit("skip", 0, 0, 0, false);
+ stopForegroundCompat();
+ stopSelf();
+ }
+
+ private void emit(String type) {
+ long left = paused ? pausedLeft : Math.max(0, endsAt - System.currentTimeMillis());
+ RestAlertPlugin.emit(type, endsAt, totalMs, left, paused);
+ }
+
+ private void show() {
+ try {
+ long left = paused ? pausedLeft : Math.max(0, endsAt - System.currentTimeMillis());
+ Notification n = RestAlert.countdownNotification(
+ this, left, totalMs, paused, pauseLabel, resumeLabel, minusLabel, plusLabel, skipLabel, accent, ink);
+ if (Build.VERSION.SDK_INT >= 34) {
+ startForeground(RestAlert.COUNTDOWN_ID, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE);
+ } else {
+ startForeground(RestAlert.COUNTDOWN_ID, n);
+ }
+ } catch (Exception e) {
+ stopSelf();
+ }
+ }
+
+ private static String text(Intent intent, String key, String fallback) {
+ if (intent == null) return fallback;
+ String v = intent.getStringExtra(key);
+ return v == null || v.isEmpty() ? fallback : v;
+ }
+
+ @SuppressWarnings("deprecation")
+ private void stopForegroundCompat() {
+ if (Build.VERSION.SDK_INT >= 24) stopForeground(STOP_FOREGROUND_REMOVE);
+ else stopForeground(true);
+ }
+}
diff --git a/frontend/android/app/src/main/res/drawable/ic_stat_dumbbell.xml b/frontend/android/app/src/main/res/drawable/ic_stat_dumbbell.xml
new file mode 100644
index 000000000..99cedf5ac
--- /dev/null
+++ b/frontend/android/app/src/main/res/drawable/ic_stat_dumbbell.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <!-- Status-bar icons are an alpha mask, so this stays white. -->
+ <path
+ android:fillColor="#FFFFFFFF"
+ android:pathData="M2,8h2.4v8H2zM4.8,9.6h1.8v4.8H4.8zM7,11.1h10v1.8H7zM17.4,9.6h1.8v4.8h-1.8zM19.6,8H22v8h-2.4z" />
+</vector>
diff --git a/frontend/android/app/src/main/res/drawable/rest_skip_bg.xml b/frontend/android/app/src/main/res/drawable/rest_skip_bg.xml
new file mode 100644
index 000000000..01b5e147e
--- /dev/null
+++ b/frontend/android/app/src/main/res/drawable/rest_skip_bg.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
+ <solid android:color="#FFFFFF" />
+ <corners android:radius="14dp" />
+</shape>
diff --git a/frontend/android/app/src/main/res/layout/rest_countdown.xml b/frontend/android/app/src/main/res/layout/rest_countdown.xml
new file mode 100644
index 000000000..45696ec20
--- /dev/null
+++ b/frontend/android/app/src/main/res/layout/rest_countdown.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Collapsed: one clock, one bar. The system header already names the app. -->
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:gravity="center_vertical"
+ android:orientation="horizontal">
+
+ <TextView
+ android:id="@+id/rest_clock"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:fontFeatureSettings="tnum"
+ android:minWidth="52dp"
+ android:textAppearance="@android:style/TextAppearance.Material.Notification.Title"
+ android:textSize="22sp"
+ android:textStyle="bold" />
+
+ <ProgressBar
+ android:id="@+id/rest_bar"
+ style="?android:attr/progressBarStyleHorizontal"
+ android:layout_width="0dp"
+ android:layout_height="6dp"
+ android:layout_marginStart="12dp"
+ android:layout_weight="1"
+ android:max="100"
+ android:progress="100"
+ android:progressBackgroundTint="#3A3A3C" />
+</LinearLayout>
diff --git a/frontend/android/app/src/main/res/layout/rest_countdown_big.xml b/frontend/android/app/src/main/res/layout/rest_countdown_big.xml
new file mode 100644
index 000000000..c25c0094a
--- /dev/null
+++ b/frontend/android/app/src/main/res/layout/rest_countdown_big.xml
@@ -0,0 +1,91 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Expanded: the in-app rest bar. Clock and bar on one row, controls on the next.
+ Skip sits at the far edge, away from the buttons that only change the time. -->
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:orientation="vertical">
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:gravity="center_vertical"
+ android:orientation="horizontal">
+
+ <TextView
+ android:id="@+id/rest_clock"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:fontFeatureSettings="tnum"
+ android:minWidth="58dp"
+ android:textAppearance="@android:style/TextAppearance.Material.Notification.Title"
+ android:textSize="26sp"
+ android:textStyle="bold" />
+
+ <ProgressBar
+ android:id="@+id/rest_bar"
+ style="?android:attr/progressBarStyleHorizontal"
+ android:layout_width="0dp"
+ android:layout_height="6dp"
+ android:layout_marginStart="12dp"
+ android:layout_weight="1"
+ android:max="100"
+ android:progress="100"
+ android:progressBackgroundTint="#3A3A3C" />
+ </LinearLayout>
+
+ <LinearLayout
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="12dp"
+ android:gravity="center_vertical"
+ android:orientation="horizontal">
+
+ <TextView
+ android:id="@+id/rest_pause"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:paddingTop="10dp"
+ android:paddingBottom="10dp"
+ android:paddingEnd="10dp"
+ android:textSize="15sp"
+ android:textStyle="bold" />
+
+ <TextView
+ android:id="@+id/rest_minus"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:padding="10dp"
+ android:textSize="15sp"
+ android:textStyle="bold" />
+
+ <TextView
+ android:id="@+id/rest_plus"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:padding="10dp"
+ android:textSize="15sp"
+ android:textStyle="bold" />
+
+ <!-- RemoteViews cannot inflate a plain View; a blank TextView is the spacer. -->
+ <TextView
+ android:layout_width="0dp"
+ android:layout_height="0dp"
+ android:layout_weight="1" />
+
+ <TextView
+ android:id="@+id/rest_skip"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:background="@drawable/rest_skip_bg"
+ android:gravity="center"
+ android:minWidth="84dp"
+ android:paddingStart="16dp"
+ android:paddingTop="10dp"
+ android:paddingEnd="16dp"
+ android:paddingBottom="10dp"
+ android:textColor="#000000"
+ android:textSize="15sp"
+ android:textStyle="bold" />
+ </LinearLayout>
+</LinearLayout>
diff --git a/frontend/android/app/src/main/res/values/strings.xml b/frontend/android/app/src/main/res/values/strings.xml
index e1ae069fa..72c1cdce7 100644
--- a/frontend/android/app/src/main/res/values/strings.xml
+++ b/frontend/android/app/src/main/res/values/strings.xml
@@ -4,4 +4,7 @@
<string name="title_activity_main">openGym</string>
<string name="package_name">ch.duartesantos.opengym</string>
<string name="custom_url_scheme">ch.duartesantos.opengym</string>
+ <string name="rest_countdown_channel_name">Rest countdown</string>
+ <string name="rest_channel_name">Rest timer</string>
+ <string name="rest_channel_desc">Rest between sets, in the notification shade. The lock screen shows it only when notifications are allowed there.</string>
</resources>
diff --git a/frontend/src/lib/format.js b/frontend/src/lib/format.js
index fe8b040d2..42fbee410 100644
--- a/frontend/src/lib/format.js
+++ b/frontend/src/lib/format.js
@@ -91,4 +91,8 @@ export const weekKey = (iso, ws = MONDAY) => isoOf(startOfWeek(iso, ws))
export const localTZ = () => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC' } catch { return 'UTC' } }
export const uid = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 7)
-export const ACCENTS = { lime: '#30d158', sky: '#0a84ff', orange: '#ff9f0a', violet: '#bf5af2', pink: '#ff375f', red: '#ff453a', teal: '#40c8e0', gold: '#ffd60a' }
\ No newline at end of file
+export const ACCENTS = { lime: '#30d158', sky: '#0a84ff', orange: '#ff9f0a', violet: '#bf5af2', pink: '#ff375f', red: '#ff453a', teal: '#40c8e0', gold: '#ffd60a' }
+// Text drawn on top of that swatch. Matches the --on-acc values in index.css.
+export const ACCENT_INK = { lime: '#000000', sky: '#ffffff', orange: '#000000', violet: '#ffffff', pink: '#ffffff', red: '#ffffff', teal: '#000000', gold: '#000000' }
+// Android color int, opaque. JS bitwise ops are signed, so the high bit is cleared back to unsigned.
+export const argb = hex => (0xff000000 | parseInt(hex.slice(1), 16)) >>> 0
\ No newline at end of file
diff --git a/frontend/src/lib/rest-alert.js b/frontend/src/lib/rest-alert.js
new file mode 100644
index 000000000..f67021515
--- /dev/null
+++ b/frontend/src/lib/rest-alert.js
@@ -0,0 +1,167 @@
+// Rest-over alert for the Capacitor app.
+//
+// The in-page countdown is a setInterval in the WebView. Android freezes that as soon as the
+// screen locks, so the beep never runs and nothing is posted. Scheduling a real alarm at
+// startRest() is what still fires with the screen off: the receiver posts the notification
+// and plays the end tone. The card in the notification shade is the in-app shape: clock plus
+// a shrinking bar. The lock screen shows it only when notifications are allowed and the
+// system is set to show them there.
+//
+// The web build keeps Web Push (useUI). This file no-ops there; MOBILE is a build-time flag.
+import { t } from './i18n-core.js'
+import { ACCENTS, ACCENT_INK, argb } from './format.js'
+import { MOBILE, isAndroid } from './mobile.js'
+
+export const REST_ALERT_ID = 42
+export const REST_CHANNEL_ID = 'rest-over'
+
+// One object the native side schedules. Public + high is what the notification shade can show.
+// The lock screen follows the user's notification settings.
+export function accentColors(key) {
+ const k = ACCENTS[key] ? key : 'lime'
+ return { accent: argb(ACCENTS[k]), ink: argb(ACCENT_INK[k]) }
+}
+
+export function buildRestAlert({ at, title, countdownTitle, totalSec, accent, sound = true, now = Date.now() } = {}) {
+ if (typeof at !== 'number' || !(at > now)) return null
+ const totalMs = Math.max(1000, Math.round((totalSec > 0 ? totalSec : (at - now) / 1000) * 1000))
+ const colors = accentColors(accent)
+ return {
+ id: REST_ALERT_ID,
+ channelId: REST_CHANNEL_ID,
+ title: title || t('Rest over'),
+ countdownTitle: countdownTitle || t('Rest'),
+ pause: t('Pause'),
+ resume: t('Resume'),
+ minus: '− 15s',
+ plus: '+ 15s',
+ skip: t('Skip'),
+ accent: colors.accent,
+ ink: colors.ink,
+ totalMs,
+ at,
+ allowWhileIdle: true,
+ sound: !!sound,
+ localOnly: false,
+ visibility: 'public',
+ importance: 'high',
+ }
+}
+
+// Serialises schedule/cancel. startRest() disarms the previous alarm and arms the next in
+// the same turn; if those two bridge calls raced, a cancel finishing last would swallow the
+// new alarm. `token` stops a slow schedule from adopting the beep after a later disarm.
+let chain = Promise.resolve()
+let token = 0
+
+const enqueue = fn => {
+ const run = chain.then(fn, fn)
+ chain = run.then(() => {}, () => {})
+ return run
+}
+
+// Resolves true only when an Android alarm was scheduled. Callers use false as
+// "fall back to the server push" — web, iOS, and a failed schedule.
+export function armRestAlert(at, opts = {}) {
+ if (!MOBILE) return Promise.resolve(false)
+ const mine = ++token
+ const alert = buildRestAlert({ at, title: opts.title, countdownTitle: opts.countdownTitle, totalSec: opts.totalSec, accent: opts.accent, sound: opts.sound })
+ if (!alert) return Promise.resolve(false)
+ return enqueue(async () => {
+ let kind = 'failed'
+ try { kind = await deliver(alert) } catch { kind = 'failed' }
+ if (mine !== token) return false
+ return kind === 'android'
+ })
+}
+
+export function disarmRestAlert() {
+ token++
+ if (!MOBILE) return
+ enqueue(async () => {
+ try { await cancelDelivered() } catch { /* the next arm replaces this alarm */ }
+ })
+}
+
+// The page is visible and about to play the in-app beep. Skip the native tone so
+// the two don't both sound. The notification itself still posts.
+let onNativeRest = null
+export function bindNativeRest(cb) { onNativeRest = cb }
+
+if (MOBILE) {
+ import('@capacitor/core').then(({ registerPlugin }) => {
+ const RestAlert = registerPlugin('RestAlert')
+ RestAlert.addListener('rest', ev => { if (onNativeRest) onNativeRest(ev) })
+ }).catch(() => {})
+}
+
+// The running countdown repaints with this swatch. No-op when no rest is on screen.
+export function setRestAccent(key) {
+ if (!MOBILE) return
+ const { accent, ink } = accentColors(key)
+ enqueue(async () => {
+ if (!(await isAndroid())) return
+ const { registerPlugin } = await import('@capacitor/core')
+ const RestAlert = registerPlugin('RestAlert')
+ await RestAlert.setAccent({ accent, ink })
+ })
+}
+
+export function hushRestTone() {
+ if (!MOBILE) return
+ enqueue(async () => {
+ if (!(await isAndroid())) return
+ const { registerPlugin } = await import('@capacitor/core')
+ const RestAlert = registerPlugin('RestAlert')
+ await RestAlert.suppressTone()
+ })
+}
+
+async function ensureNotifPermission() {
+ try {
+ const { LocalNotifications } = await import('@capacitor/local-notifications')
+ let perm = await LocalNotifications.checkPermissions()
+ if (perm.display === 'granted') return true
+ if (perm.display === 'denied') return false
+ perm = await LocalNotifications.requestPermissions()
+ return perm.display === 'granted'
+ } catch {
+ return false
+ }
+}
+
+async function deliver(alert) {
+ if (!(await isAndroid())) return 'skipped'
+ await ensureNotifPermission()
+ const { registerPlugin } = await import('@capacitor/core')
+ const RestAlert = registerPlugin('RestAlert')
+ // Sound still schedules when notification permission is missing: the alarm tone does
+ // not need it. The notification does, which is why we ask above.
+ await RestAlert.schedule({
+ id: alert.id,
+ at: alert.at,
+ title: alert.title,
+ sound: alert.sound,
+ channelId: alert.channelId,
+ visibility: alert.visibility,
+ importance: alert.importance,
+ localOnly: alert.localOnly,
+ countdownTitle: alert.countdownTitle,
+ totalMs: alert.totalMs,
+ pause: alert.pause,
+ resume: alert.resume,
+ minus: alert.minus,
+ plus: alert.plus,
+ skip: alert.skip,
+ accent: alert.accent,
+ ink: alert.ink,
+ })
+ return 'android'
+}
+
+async function cancelDelivered() {
+ if (!(await isAndroid())) return
+ const { registerPlugin } = await import('@capacitor/core')
+ const RestAlert = registerPlugin('RestAlert')
+ await RestAlert.cancel({ id: REST_ALERT_ID })
+}
diff --git a/frontend/src/lib/rest-alert.test.js b/frontend/src/lib/rest-alert.test.js
new file mode 100644
index 000000000..2bf8a60a4
--- /dev/null
+++ b/frontend/src/lib/rest-alert.test.js
@@ -0,0 +1,45 @@
+import { describe, expect, it } from 'vitest'
+import { armRestAlert, buildRestAlert, disarmRestAlert, REST_ALERT_ID, REST_CHANNEL_ID } from './rest-alert.js'
+
+describe('buildRestAlert', () => {
+ const now = 1_700_000_000_000
+
+ it('schedules a public notification', () => {
+ const alert = buildRestAlert({ at: now + 90_000, title: 'Rest over — next set!', sound: true, now })
+ expect(alert).toMatchObject({
+ id: REST_ALERT_ID,
+ channelId: REST_CHANNEL_ID,
+ title: 'Rest over — next set!',
+ at: now + 90_000,
+ allowWhileIdle: true,
+ countdownTitle: 'Rest',
+ totalMs: 90_000,
+ sound: true,
+ localOnly: false,
+ visibility: 'public',
+ importance: 'high',
+ })
+ })
+
+ it('paints the notification with the chosen accent, not the default green', () => {
+ const alert = buildRestAlert({ at: now + 1000, accent: 'red', now })
+ expect(alert.accent).toBe((0xff000000 | 0xff453a) >>> 0)
+ expect(alert.ink).toBe((0xff000000 | 0xffffff) >>> 0)
+ })
+
+ it('still schedules when sound is off', () => {
+ expect(buildRestAlert({ at: now + 1000, sound: false, now }).sound).toBe(false)
+ })
+
+ it('refuses a deadline that has already passed', () => {
+ expect(buildRestAlert({ at: now, now })).toBe(null)
+ expect(buildRestAlert({ at: now - 1, now })).toBe(null)
+ })
+})
+
+describe('rest alert outside the mobile build', () => {
+ it('does not schedule an alarm, so the caller keeps the server push', async () => {
+ await expect(armRestAlert(Date.now() + 90_000, { title: 'Rest over', sound: true })).resolves.toBe(false)
+ disarmRestAlert()
+ })
+})
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index dc0a877ca..2307844b6 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -22,6 +22,7 @@ export default {
'Home': 'Start',
'Start': 'Los',
'Resume': 'Weiter',
+ 'Pause': 'Pause',
'Stats': 'Statistik',
'Exercises': 'Übungen',
'By muscle': 'Nach Muskel',
@@ -221,6 +222,7 @@ export default {
'Superset · do these back-to-back, rest when done': 'Supersatz · direkt nacheinander, Pause erst danach',
'Freestyle workout — add your first exercise.': 'Freies Training — füge deine erste Übung hinzu.',
'Finish workout early · {0} exercises': 'Training vorzeitig beenden · {0} Übungen',
+ 'Rest over': 'Pause vorbei',
'Rest over — next set!': 'Pause vorbei — nächster Satz!',
// --- home ---
'Hi {0}': 'Hi {0}',
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 2393a0c16..b7857fda2 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -21,6 +21,7 @@ export default {
'Home': 'Inicio',
'Start': 'Empezar',
'Resume': 'Seguir',
+ 'Pause': 'Pausa',
'Stats': 'Progreso',
'Exercises': 'Ejercicios',
'By muscle': 'Por músculo',
@@ -213,6 +214,7 @@ export default {
'Superset · do these back-to-back, rest when done': 'Superserie · hazlos seguidos, descansa al final',
'Freestyle workout — add your first exercise.': 'Entrenamiento libre — añade tu primer ejercicio.',
'Finish workout early · {0} exercises': 'Terminar antes · {0} ejercicios',
+ 'Rest over': 'Listo',
'Rest over — next set!': '¡Descanso terminado — siguiente serie!',
'Hi {0}': 'Hola {0}',
'This week': 'Esta semana',
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index 15e014795..e9d55ca4e 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -21,6 +21,7 @@ export default {
'Home': 'Accueil',
'Start': 'Démarrer',
'Resume': 'Reprendre',
+ 'Pause': 'Pause',
'Stats': 'Stats',
'Exercises': 'Exercices',
'By muscle': 'Par muscle',
@@ -213,6 +214,7 @@ export default {
'Superset · do these back-to-back, rest when done': 'Superset · enchaîne-les, repos à la fin',
'Freestyle workout — add your first exercise.': 'Séance libre — ajoute ton premier exercice.',
'Finish workout early · {0} exercises': 'Terminer plus tôt · {0} exercices',
+ 'Rest over': 'Repos fini',
'Rest over — next set!': 'Repos fini — série suivante !',
'Hi {0}': 'Salut {0}',
'This week': 'Cette semaine',
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index 95c35c135..094a8265e 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -21,6 +21,7 @@ export default {
'Home': 'होम',
'Start': 'शुरू',
'Resume': 'जारी रखें',
+ 'Pause': 'रोकें',
'Stats': 'आँकड़े',
'Exercises': 'व्यायाम',
'By muscle': 'मांसपेशी से',
@@ -213,6 +214,7 @@ export default {
'Superset · do these back-to-back, rest when done': 'सुपरसेट · इन्हें लगातार करें, अंत में आराम',
'Freestyle workout — add your first exercise.': 'फ्रीस्टाइल वर्कआउट — पहला व्यायाम जोड़ें।',
'Finish workout early · {0} exercises': 'जल्दी समाप्त करें · {0} व्यायाम',
+ 'Rest over': 'आराम खत्म',
'Rest over — next set!': 'आराम खत्म — अगला सेट!',
'Hi {0}': 'नमस्ते {0}',
'This week': 'इस हफ़्ते',
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index a1cf236c0..486018666 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -23,6 +23,7 @@ export default {
'Home': 'Kezdőlap',
'Start': 'Indítás',
'Resume': 'Folytatás',
+ 'Pause': 'Szünet',
'Stats': 'Statisztika',
'Exercises': 'Gyakorlatok',
'By muscle': 'Izom szerint',
@@ -212,6 +213,7 @@ export default {
'Superset · do these back-to-back, rest when done': 'Szuperszett · végezd egymás után, pihenj csak utána',
'Freestyle workout — add your first exercise.': 'Szabad edzés — add hozzá az első gyakorlatot.',
'Finish workout early · {0} exercises': 'Edzés korai befejezése · {0} gyakorlat',
+ 'Rest over': 'Pihenő vége',
'Rest over — next set!': 'Pihenő vége — jöhet a következő sorozat!',
// --- home ---
'Hi {0}': 'Szia {0}',
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index 89d904785..50755bcaf 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -21,6 +21,7 @@ export default {
'Home': 'Home',
'Start': 'Inizia',
'Resume': 'Riprendi',
+ 'Pause': 'Pausa',
'Stats': 'Statistiche',
'Exercises': 'Esercizi',
'By muscle': 'Per muscolo',
@@ -213,6 +214,7 @@ export default {
'Superset · do these back-to-back, rest when done': 'Superset · falli uno dopo l’altro, riposo alla fine',
'Freestyle workout — add your first exercise.': 'Allenamento libero — aggiungi il primo esercizio.',
'Finish workout early · {0} exercises': 'Termina in anticipo · {0} esercizi',
+ 'Rest over': 'Riposo finito',
'Rest over — next set!': 'Riposo finito — prossima serie!',
'Hi {0}': 'Ciao {0}',
'This week': 'Questa settimana',
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index f36bbe008..002b0cba3 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -21,6 +21,7 @@ export default {
'Home': '홈',
'Start': '시작',
'Resume': '이어하기',
+ 'Pause': '일시정지',
'Stats': '통계',
'Exercises': '운동',
'By muscle': '근육별',
@@ -213,6 +214,7 @@ export default {
'Superset · do these back-to-back, rest when done': '슈퍼세트 · 연달아 수행하고, 전부 끝난 뒤 휴식',
'Freestyle workout — add your first exercise.': '자유 운동 — 첫 운동을 추가하세요.',
'Finish workout early · {0} exercises': '일찍 마치기 · 운동 {0}개',
+ 'Rest over': '휴식 끝',
'Rest over — next set!': '휴식 끝 — 다음 세트!',
'Hi {0}': '안녕하세요 {0}',
'This week': '이번 주',
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index 529d5ab92..aa78ca023 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -21,6 +21,7 @@ export default {
'Home': 'Start',
'Start': 'Trenuj',
'Resume': 'Wznów',
+ 'Pause': 'Pauza',
'Stats': 'Statystyki',
'Exercises': 'Ćwiczenia',
'By muscle': 'Według mięśnia',
@@ -213,6 +214,7 @@ export default {
'Superset · do these back-to-back, rest when done': 'Superseria · rób jedno po drugim, odpocznij na końcu',
'Freestyle workout — add your first exercise.': 'Trening dowolny — dodaj pierwsze ćwiczenie.',
'Finish workout early · {0} exercises': 'Zakończ wcześniej · {0} ćwiczeń',
+ 'Rest over': 'Koniec',
'Rest over — next set!': 'Koniec przerwy — następna seria!',
'Hi {0}': 'Cześć {0}',
'This week': 'Ten tydzień',
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index d07541e8d..c8cd084d8 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -21,6 +21,7 @@ export default {
'Home': 'Início',
'Start': 'Começar',
'Resume': 'Retomar',
+ 'Pause': 'Pausar',
'Stats': 'Estatísticas',
'Exercises': 'Exercícios',
'By muscle': 'Por músculo',
@@ -213,6 +214,7 @@ export default {
'Superset · do these back-to-back, rest when done': 'Supersérie · faz seguidos, descansa no final',
'Freestyle workout — add your first exercise.': 'Treino livre — adiciona o teu primeiro exercício.',
'Finish workout early · {0} exercises': 'Terminar mais cedo · {0} exercícios',
+ 'Rest over': 'Acabou',
'Rest over — next set!': 'Descanso terminado — próxima série!',
'Hi {0}': 'Olá {0}',
'This week': 'Esta semana',
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index accc919de..12f8646c6 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -21,6 +21,7 @@ export default {
'Home': 'Главная',
'Start': 'Старт',
'Resume': 'Продолжить',
+ 'Pause': 'Пауза',
'Stats': 'Статистика',
'Exercises': 'Упражнения',
'By muscle': 'По мышцам',
@@ -213,6 +214,7 @@ export default {
'Superset · do these back-to-back, rest when done': 'Суперсет · выполняй подряд, отдых в конце',
'Freestyle workout — add your first exercise.': 'Свободная тренировка — добавь первое упражнение.',
'Finish workout early · {0} exercises': 'Завершить раньше · упражнений: {0}',
+ 'Rest over': 'Готово',
'Rest over — next set!': 'Отдых окончен — следующий подход!',
'Hi {0}': 'Привет, {0}',
'This week': 'Эта неделя',
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index e8fdc2ff5..d1d78b423 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -23,6 +23,7 @@ export default {
'Home': 'หน้าหลัก',
'Start': 'เริ่ม',
'Resume': 'เล่นต่อ',
+ 'Pause': 'หยุด',
'Stats': 'สถิติ',
'Exercises': 'ท่าออกกำลังกาย',
'By muscle': 'ตามกล้ามเนื้อ',
@@ -212,6 +213,7 @@ export default {
'Superset · do these back-to-back, rest when done': 'ซูเปอร์เซ็ต · ทำต่อเนื่องกัน แล้วค่อยพักหลังทำครบทั้งคู่',
'Freestyle workout — add your first exercise.': 'ออกกำลังกายแบบฟรีสไตล์ — เพิ่มท่าแรกของคุณ',
'Finish workout early · {0} exercises': 'จบก่อนกำหนด · {0} ท่า',
+ 'Rest over': 'พักครบ',
'Rest over — next set!': 'หมดเวลาพัก — เซ็ตถัดไป!',
// --- home ---
'Hi {0}': 'สวัสดี {0}',
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index 82f934fed..f42a95154 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -21,6 +21,7 @@ export default {
'Home': 'Ana sayfa',
'Start': 'Başla',
'Resume': 'Devam et',
+ 'Pause': 'Duraklat',
'Stats': 'İstatistik',
'Exercises': 'Egzersizler',
'By muscle': 'Kasa göre',
@@ -213,6 +214,7 @@ export default {
'Superset · do these back-to-back, rest when done': 'Süperset · art arda yap, sonunda dinlen',
'Freestyle workout — add your first exercise.': 'Serbest antrenman — ilk egzersizini ekle.',
'Finish workout early · {0} exercises': 'Erken bitir · {0} egzersiz',
+ 'Rest over': 'Bitti',
'Rest over — next set!': 'Dinlenme bitti — sıradaki set!',
'Hi {0}': 'Selam {0}',
'This week': 'Bu hafta',
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index 7f4492b44..a0b582940 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -21,6 +21,7 @@ export default {
'Home': '首页',
'Start': '开始',
'Resume': '继续',
+ 'Pause': '暂停',
'Stats': '统计',
'Exercises': '动作库',
'By muscle': '按肌肉',
@@ -213,6 +214,7 @@ export default {
'Superset · do these back-to-back, rest when done': '超级组 · 连续完成,全部做完再休息',
'Freestyle workout — add your first exercise.': '自由训练——添加你的第一个动作。',
'Finish workout early · {0} exercises': '提前结束 · {0} 个动作',
+ 'Rest over': '休息结束',
'Rest over — next set!': '休息结束——下一组!',
'Hi {0}': '你好,{0}',
'This week': '本周',
diff --git a/frontend/src/store/useUI.js b/frontend/src/store/useUI.js
index 01e1fc70f..1c1a4f901 100644
--- a/frontend/src/store/useUI.js
+++ b/frontend/src/store/useUI.js
@@ -4,6 +4,8 @@ import { beep, vibrate } from '../lib/sound.js'
import { api } from '../lib/api.js'
import { t } from '../lib/i18n.js'
import { deviceId } from '../lib/push.js'
+import { MOBILE } from '../lib/mobile.js'
+import { armRestAlert, bindNativeRest, disarmRestAlert, hushRestTone } from '../lib/rest-alert.js'
import { useStore } from './useStore.js'
// Fire-and-forget: lets the server push a "rest over" alert if this tab gets suspended
@@ -19,7 +21,9 @@ const notificationsSupported = () => typeof window !== 'undefined' && 'Notificat
// clear it themselves once they're running visible again. Lets a completion tick tell
// "the countdown hit zero while the app was actually open" from "it hit zero while
// backgrounded/closed and we're only just catching up now that it's open again" — the
-// latter must skip beep/vibrate/flash/toast and rely solely on the push notification.
+// latter must skip beep/vibrate/flash and rely on the alert armed when the rest started
+// (a native alarm on the mobile build, Web Push on the web build). The toast still shows
+// on reopen so a countdown that vanished does not look like a bug.
let pageHiddenAt = null
if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', () => { if (document.hidden) pageHiddenAt = Date.now() })
@@ -94,25 +98,38 @@ export const useUI = create((set, get) => ({
if (!(sec > 0)) return
const endsAt = Date.now() + sec * 1000
set({ timer: { left: sec, total: sec, endsAt, forIdx } })
- pushRestTimer(sec)
+ // Mobile: the alarm is armed now, because the WebView will not be around to notice
+ // zero if the screen locks. Web, iOS, and a failed Android schedule keep the server push.
+ armRestAlert(endsAt, { title: t('Rest over'), countdownTitle: t('Rest'), totalSec: sec, accent: useStore.getState().S.accent, sound: !!useStore.getState().S.sound })
+ .then(ok => { if (!ok) pushRestTimer(sec) })
timerTick = () => {
const tm = get().timer
- if (!tm) return
+ if (!tm || tm.paused) return
const left = Math.max(0, Math.round((tm.endsAt - Date.now()) / 1000))
const seenLive = !document.hidden && pageHiddenAt === null
if (!document.hidden) pageHiddenAt = null
if (left === tm.left) return
const snd = useStore.getState().S.sound
if (left <= 0) {
+ // +15 on the notification can move the deadline in the same instant this tick
+ // decided the rest was over. If it did, keep counting instead of closing.
+ const extended = get().timer
+ if (extended && !extended.paused && extended.endsAt - Date.now() > 500) return
if (seenLive) {
+ // The alarm is about to post the same moment. Tell it not to play, so this
+ // beep is the only one. Locked, this branch never runs and the alarm tone does.
+ hushRestTone()
beep(snd, 880, 0.15); beep(snd, 880, 0.15, 0.25); beep(snd, 1320, 0.4, 0.5)
vibrate([200, 100, 200]); get().flashTimer()
}
// The toast stays even when the rest ran out while the app was hidden: a guest, or anyone
// without push permission, gets no notification, and a countdown that silently vanishes
// on reopen reads like a bug. Only the loud parts (beep, vibration, flash) are gated.
+ // keepAlert: this tick is often a little early, and with the screen locked it never
+ // runs at all. Cancelling here would drop the alarm before it fires.
get().toast(t('Rest over — next set!'))
- maybeRestNotification(); get().stopRest(); return
+ if (!MOBILE) maybeRestNotification()
+ get().stopRest({ keepAlert: true }); return
}
if (left <= 3) beep(snd, 660, 0.1)
set({ timer: { ...tm, left } })
@@ -127,8 +144,10 @@ export const useUI = create((set, get) => ({
// taking off more than is left means "I'm ready now" — same as skipping, and it keeps a
// negative duration out of both the progress bar and the server-side push schedule
if (left <= 0) { get().stopRest(); return }
- set({ timer: { ...tm, left, total: tm.total + sec, endsAt: tm.endsAt + sec * 1000 } })
- pushRestTimer(left)
+ const endsAt = tm.endsAt + sec * 1000
+ set({ timer: { ...tm, left, total: tm.total + sec, endsAt } })
+ armRestAlert(endsAt, { title: t('Rest over'), countdownTitle: t('Rest'), totalSec: tm.total + sec, accent: useStore.getState().S.accent, sound: !!useStore.getState().S.sound })
+ .then(ok => { if (!ok) pushRestTimer(left) })
},
// The active list changed shape (an exercise removed or inserted at `at`): keep the rest
// pointing at the same exercise. Returns nothing; the caller decides whether to stop instead.
@@ -137,9 +156,43 @@ export const useUI = create((set, get) => ({
if (!tm || !(tm.forIdx >= at)) return
set({ timer: { ...tm, forIdx: tm.forIdx + delta } })
},
- stopRest() {
+ // The notification added time after this screen had already closed the rest.
+ // Put the countdown back without tearing down the native timer that is still running.
+ reviveRest(endsAt, total, left, paused) {
+ set({ timer: { left, total, endsAt, paused: !!paused, forIdx: get().timer?.forIdx } })
+ if (paused || timerInt) return
+ timerTick = () => {
+ const tm = get().timer
+ if (!tm || tm.paused) return
+ const leftNow = Math.max(0, Math.round((tm.endsAt - Date.now()) / 1000))
+ const seenLive = !document.hidden && pageHiddenAt === null
+ if (!document.hidden) pageHiddenAt = null
+ if (leftNow === tm.left) return
+ const snd = useStore.getState().S.sound
+ if (leftNow <= 0) {
+ const extended = get().timer
+ if (extended && !extended.paused && extended.endsAt - Date.now() > 500) return
+ if (seenLive) {
+ hushRestTone()
+ beep(snd, 880, 0.15); beep(snd, 880, 0.15, 0.25); beep(snd, 1320, 0.4, 0.5)
+ vibrate([200, 100, 200]); get().flashTimer()
+ }
+ get().toast(t('Rest over — next set!'))
+ if (!MOBILE) maybeRestNotification()
+ get().stopRest({ keepAlert: true }); return
+ }
+ if (leftNow <= 3) beep(snd, 660, 0.1)
+ set({ timer: { ...tm, left: leftNow } })
+ }
+ timerInt = setInterval(timerTick, 1000)
+ document.addEventListener('visibilitychange', timerTick)
+ },
+ stopRest({ keepAlert = false } = {}) {
if (timerInt) clearInterval(timerInt); timerInt = null
if (timerTick) document.removeEventListener('visibilitychange', timerTick); timerTick = null
+ // A natural finish leaves the scheduled alarm in place. Skip, replace, and "rest off"
+ // cancel it — otherwise the alert fires after the user already moved on.
+ if (!keepAlert) disarmRestAlert()
if (get().timer) cancelPushRestTimer()
set({ timer: null })
},
@@ -201,3 +254,18 @@ export const useUI = create((set, get) => ({
set({ work: null })
}
}))
+
+// Buttons on the rest notification (pause, ±15s, skip) change the countdown in the
+// service first, then mirror that into the in-app timer. skip ends it.
+bindNativeRest(ev => {
+ if (!ev) return
+ if (ev.type === 'skip') { useUI.getState().stopRest(); return }
+ const tm = useUI.getState().timer
+ const left = Math.max(0, Math.round((ev.leftMs || 0) / 1000))
+ const total = Math.max(1, Math.round((ev.totalMs || 0) / 1000))
+ if (!tm) {
+ if (ev.type === 'adjust' && left > 0) useUI.getState().reviveRest(ev.endsAt, total, left, ev.paused)
+ return
+ }
+ useUI.setState({ timer: { ...tm, left, total, endsAt: ev.endsAt || tm.endsAt, paused: !!ev.paused } })
+})
diff --git a/frontend/src/store/useUI.native-rest.test.js b/frontend/src/store/useUI.native-rest.test.js
new file mode 100644
index 000000000..8e623c637
--- /dev/null
+++ b/frontend/src/store/useUI.native-rest.test.js
@@ -0,0 +1,121 @@
+// @vitest-environment happy-dom
+// The locked-phone bug: the WebView countdown never reaches zero, so the only alert that
+// can fire is the one armed when the rest starts. Completing (or catching up) must not
+// cancel it. Skipping the rest must.
+import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest'
+import { useUI } from './useUI.js'
+import { useStore } from './useStore.js'
+import { armRestAlert, disarmRestAlert } from '../lib/rest-alert.js'
+import { beep, vibrate } from '../lib/sound.js'
+
+vi.mock('../lib/rest-alert.js', () => ({
+ armRestAlert: vi.fn(() => Promise.resolve(true)),
+ disarmRestAlert: vi.fn(),
+ hushRestTone: vi.fn(),
+ bindNativeRest: vi.fn(),
+}))
+vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), vibrate: vi.fn() }))
+
+const hide = hidden => {
+ Object.defineProperty(document, 'hidden', { configurable: true, get: () => hidden })
+ Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => hidden ? 'hidden' : 'visible' })
+ document.dispatchEvent(new Event('visibilitychange'))
+}
+
+let originalSettings
+beforeEach(() => {
+ vi.useFakeTimers()
+ originalSettings = useStore.getState().S
+ useStore.setState({ S: { ...originalSettings, sound: true, timerFlash: false }, user: null })
+ useUI.setState({ timer: null, timerFlashId: 0 })
+ armRestAlert.mockClear()
+ disarmRestAlert.mockClear()
+ beep.mockClear()
+ vibrate.mockClear()
+ hide(false)
+})
+afterEach(() => {
+ useUI.getState().stopRest()
+ useStore.setState({ S: originalSettings })
+ hide(false)
+ vi.useRealTimers()
+})
+
+describe('native rest alert', () => {
+ it('arms when the rest starts and rearms when time is added', () => {
+ useUI.getState().startRest(90)
+ const first = armRestAlert.mock.calls.at(-1)[0]
+ useUI.getState().addRest(15)
+ const second = armRestAlert.mock.calls.at(-1)[0]
+ expect(second - first).toBe(15_000)
+ expect(armRestAlert).toHaveBeenLastCalledWith(second, expect.objectContaining({
+ title: 'Rest over', countdownTitle: 'Rest', totalSec: 105, sound: true,
+ }))
+ })
+
+ it('keeps the alarm when the countdown ends, including while the app is hidden', () => {
+ useUI.getState().startRest(90)
+ const armed = disarmRestAlert.mock.calls.length
+ hide(true)
+ vi.setSystemTime(Date.now() + 91_000)
+ hide(false) // reopening catches up; the alarm armed at the start must still be pending
+ expect(disarmRestAlert.mock.calls.length).toBe(armed)
+ expect(useUI.getState().timer).toBe(null)
+ expect(beep).not.toHaveBeenCalled()
+ })
+
+ it('cancels the alarm when the rest is skipped', () => {
+ useUI.getState().startRest(90)
+ const armed = disarmRestAlert.mock.calls.length
+ useUI.getState().stopRest()
+ expect(disarmRestAlert.mock.calls.length).toBe(armed + 1)
+ })
+
+ it('still plays the in-app beep when the rest finishes on screen', () => {
+ useStore.setState({ S: { ...useStore.getState().S, timerFlash: true } })
+ useUI.getState().startRest(1)
+ vi.advanceTimersByTime(1000)
+ expect(beep).toHaveBeenCalled()
+ expect(useUI.getState().timerFlashId).toBe(1)
+ })
+
+ it('stays open when time is added as the countdown hits zero', () => {
+ useUI.getState().startRest(1)
+ vi.advanceTimersByTime(500)
+ const tm = useUI.getState().timer
+ useUI.setState({ timer: { ...tm, endsAt: Date.now() + 15_000, left: 15, total: tm.total + 15 } })
+ vi.advanceTimersByTime(1000)
+ expect(useUI.getState().timer).not.toBe(null)
+ expect(useUI.getState().timer.left).toBeGreaterThan(10)
+ })
+
+ it('reopens the rest after it closed if the notification added time', () => {
+ useUI.getState().startRest(1)
+ vi.advanceTimersByTime(1500)
+ expect(useUI.getState().timer).toBe(null)
+ useUI.getState().reviveRest(Date.now() + 15_000, 16, 15, false)
+ expect(useUI.getState().timer.left).toBe(15)
+ vi.advanceTimersByTime(2000)
+ expect(useUI.getState().timer.left).toBeLessThan(15)
+ })
+
+ it('does not finish a rest that was paused', () => {
+ useUI.getState().startRest(2)
+ useUI.setState({ timer: { ...useUI.getState().timer, paused: true } })
+ vi.advanceTimersByTime(5000)
+ expect(useUI.getState().timer).not.toBe(null)
+ expect(useUI.getState().timer.paused).toBe(true)
+ })
+
+ it('plays the last-seconds ticks', () => {
+ useUI.getState().startRest(5)
+ vi.advanceTimersByTime(3000)
+ expect(beep).toHaveBeenCalled()
+ })
+
+ it('still schedules an alert when sound is off', () => {
+ useStore.setState({ S: { ...useStore.getState().S, sound: false } })
+ useUI.getState().startRest(90)
+ expect(armRestAlert).toHaveBeenCalledWith(expect.any(Number), expect.objectContaining({ sound: false }))
+ })
+})
diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx
index 993c0373d..9931b7e83 100644
--- a/frontend/src/views/Settings.jsx
+++ b/frontend/src/views/Settings.jsx
@@ -13,6 +13,7 @@ import { wakeLockSupported } from '../lib/wakelock.js'
import { t, LANGS, INSTR_LANGS } from '../lib/i18n.js'
import { DEMO, REPO } from '../lib/demo.js'
import { MOBILE, isAndroid, shareExport, syncReminder } from '../lib/mobile.js'
+import { setRestAccent } from '../lib/rest-alert.js'
import { checkForUpdate, downloadAndInstall } from '../lib/update.js'
import { forgetCoach } from '../lib/coach-api.js'
import { ConnectSheet } from './MobileOnboarding.jsx'
@@ -375,7 +376,7 @@ export default function Settings() {
<div className="swatches">
{Object.entries(ACCENTS).map(([k, c]) => (
<button key={k} className={'swatch' + ((S.accent || 'lime') === k ? ' on' : '')}
- style={{ background: c }} onClick={() => update(s => { s.accent = k })} aria-label={k} />
+ style={{ background: c }} onClick={() => { update(s => { s.accent = k }); setRestAccent(k) }} aria-label={k} />
))}
</div>
</div>