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.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Android: the end of a rest can buzz on a phone that is on silent
Duarte Santosa12f8c1b556e
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.javaindex 568837912..63fa8b290 100644--- a/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlert.java+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlert.java@@ -14,8 +14,10 @@ import android.media.AudioFormat;import android.media.AudioTrack;import android.os.Build;import android.os.PowerManager;+import android.os.VibrationAttributes;import android.os.VibrationEffect;import android.os.Vibrator;+import android.os.VibratorManager;import android.util.Log;/**@@ -42,6 +44,7 @@ public final class RestAlert {private static String lastAlertTitle = "Rest over";private static boolean lastSound = true;private static boolean lastVibrate = true;+ private static boolean lastAlarmBuzz = false;private static String lastChannel = CHANNEL_ID;private static String labPause = "Pause";private static String labResume = "Resume";@@ -62,15 +65,22 @@ public final class RestAlert {private RestAlert() {}+ /**+ * `alarmBuzz` is Settings → "Vibrate when the phone is on silent" (#375): the end buzzes as an+ * alarm, which silent mode lets through, and the notification goes out on the quiet channel so+ * a phone with its ringer on does not buzz twice.+ */public static void schedule(Context ctx, long at, int id, String title, boolean sound, boolean vibrate,- String channelId, String visibility, String importance, boolean localOnly,- String countdownTitle, long totalMs) {+ boolean alarmBuzz, String channelId, String visibility, String importance,+ boolean localOnly, String countdownTitle, long totalMs) {+ alarmBuzz = vibrate && alarmBuzz;channelId = channelFor(channelId, vibrate);Intent intent = alarmIntent(ctx);intent.putExtra("id", id);intent.putExtra("title", title == null ? "" : title);intent.putExtra("sound", sound);intent.putExtra("vibrate", vibrate);+ intent.putExtra("alarmBuzz", alarmBuzz);intent.putExtra("channelId", channelId);intent.putExtra("visibility", visibility == null ? "public" : visibility);intent.putExtra("importance", importance == null ? "high" : importance);@@ -89,11 +99,13 @@ public final class RestAlert {if (!exact) Log.w("openGym", "exact alarms not allowed; the rest countdown sounds the end itself");if (Build.VERSION.SDK_INT >= 26) {NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);- ensureChannel(ctx, nm, channelId, importanceOf(importance), visibilityOf(visibility), vibrate);+ String posted = alarmBuzz ? QUIET_CHANNEL_ID : channelId;+ ensureChannel(ctx, nm, posted, importanceOf(importance), visibilityOf(visibility), !alarmBuzz && vibrate);}lastAlertTitle = title == null ? "Rest over" : title;lastSound = sound;lastVibrate = vibrate;+ lastAlarmBuzz = alarmBuzz;lastChannel = channelId;startCountdown(ctx, at, totalMs, countdownTitle);}@@ -134,6 +146,7 @@ public final class RestAlert {intent.putExtra("title", lastAlertTitle);intent.putExtra("sound", lastSound);intent.putExtra("vibrate", lastVibrate);+ intent.putExtra("alarmBuzz", lastAlarmBuzz);intent.putExtra("channelId", lastChannel);intent.putExtra("at", at);new Thread(() -> fire(ctx, intent), "opengym-rest").start();@@ -166,9 +179,13 @@ public final class RestAlert {}pokeScreen(ctx);boolean vibrate = intent.getBooleanExtra("vibrate", true);- boolean shown = showNotification(ctx, intent);+ boolean alarmBuzz = vibrate && intent.getBooleanExtra("alarmBuzz", false);+ boolean shown = showNotification(ctx, intent, alarmBuzz);+ // On silent the channel's buzz is muted; an alarm's is not (#375). The notification+ // went out on the quiet channel, so this is the one buzz with the ringer on too.+ if (alarmBuzz) buzz(ctx, VIBRATE);// Settings → Vibrate off is off here too: without notifications this buzz is the alert.- if (!shown && vibrate) vibrateFallback(ctx);+ else if (!shown && vibrate) vibrateFallback(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);@@ -205,10 +222,11 @@ public final class RestAlert {}@SuppressWarnings("deprecation")- private static boolean showNotification(Context ctx, Intent intent) {+ private static boolean showNotification(Context ctx, Intent intent, boolean alarmBuzz) {String title = intent.getStringExtra("title");if (title == null || title.isEmpty()) title = "Rest over — next set!";- boolean vibrate = intent.getBooleanExtra("vibrate", true);+ // With the alarm buzz on, the notification itself stays still: the buzz comes from buzz().+ boolean vibrate = intent.getBooleanExtra("vibrate", true) && !alarmBuzz;String channelId = channelFor(intent.getStringExtra("channelId"), vibrate);int id = intent.getIntExtra("id", NOTIFICATION_ID);boolean localOnly = intent.getBooleanExtra("localOnly", false);@@ -298,6 +316,36 @@ public final class RestAlert {} catch (Exception ignored) { /* */ }}+ /**+ * A buzz silent mode lets through (#375): vibration with the alarm usage, which the system+ * plays in silent and vibrate-only modes like the clock app's alarm. `pattern` is Android's+ * waveform (off, on, off, on…). Do Not Disturb still decides, as it does for alarms.+ */+ @SuppressWarnings("deprecation")+ static void buzz(Context ctx, long[] pattern) {+ try {+ Vibrator vibrator;+ if (Build.VERSION.SDK_INT >= 31) {+ VibratorManager vm = (VibratorManager) ctx.getSystemService(Context.VIBRATOR_MANAGER_SERVICE);+ vibrator = vm == null ? null : vm.getDefaultVibrator();+ } else {+ vibrator = (Vibrator) ctx.getSystemService(Context.VIBRATOR_SERVICE);+ }+ if (vibrator == null || !vibrator.hasVibrator()) return;+ if (Build.VERSION.SDK_INT >= 33) {+ vibrator.vibrate(VibrationEffect.createWaveform(pattern, -1),+ VibrationAttributes.createForUsage(VibrationAttributes.USAGE_ALARM));+ return;+ }+ AudioAttributes alarm = new AudioAttributes.Builder()+ .setUsage(AudioAttributes.USAGE_ALARM)+ .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)+ .build();+ if (Build.VERSION.SDK_INT >= 26) vibrator.vibrate(VibrationEffect.createWaveform(pattern, -1), alarm);+ else vibrator.vibrate(pattern, -1, alarm);+ } catch (Exception ignored) { /* nothing else to fall back on here */ }+ }+static void updateAlarm(Context ctx, long at) {if (at <= System.currentTimeMillis()) {cancelAlarmOnly(ctx, NOTIFICATION_ID);@@ -308,6 +356,7 @@ public final class RestAlert {intent.putExtra("title", lastAlertTitle);intent.putExtra("sound", lastSound);intent.putExtra("vibrate", lastVibrate);+ intent.putExtra("alarmBuzz", lastAlarmBuzz);intent.putExtra("channelId", lastChannel);intent.putExtra("visibility", "public");intent.putExtra("importance", "high");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.javaindex 09383bead..8fa9ac575 100644--- a/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlertPlugin.java+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlertPlugin.java@@ -2,6 +2,7 @@ package ch.duartesantos.opengym;import android.content.Context;import android.content.Intent;+import com.getcapacitor.JSArray;import com.getcapacitor.JSObject;import com.getcapacitor.Plugin;import com.getcapacitor.PluginCall;@@ -17,6 +18,7 @@ import com.getcapacitor.annotation.CapacitorPlugin;* const RestAlert = registerPlugin('RestAlert');* await RestAlert.schedule({ id, at, title, sound, vibrate, channelId, visibility, importance, localOnly });* await RestAlert.cancel({ id });+ * await RestAlert.buzz({ pattern: [200, 100, 200] }); // navigator.vibrate's shape, as an alarm*/@CapacitorPlugin(name = "RestAlert")public class RestAlertPlugin extends Plugin {@@ -83,6 +85,7 @@ public class RestAlertPlugin extends Plugin {call.getString("title", "Rest over"),!Boolean.FALSE.equals(call.getBoolean("sound", Boolean.TRUE)),!Boolean.FALSE.equals(call.getBoolean("vibrate", Boolean.TRUE)),+ Boolean.TRUE.equals(call.getBoolean("alarmBuzz", Boolean.FALSE)),call.getString("channelId", RestAlert.CHANNEL_ID),call.getString("visibility", "public"),call.getString("importance", "high"),@@ -93,6 +96,34 @@ public class RestAlertPlugin extends Plugin {call.resolve();}+ /**+ * The page's end-of-rest or end-of-hold buzz with Settings → "Vibrate when the phone is on+ * silent" on (#375). `pattern` is navigator.vibrate's (on, off, on…); Android's waveform starts+ * with an off, so a 0 goes in front.+ */+ @PluginMethod+ public void buzz(PluginCall call) {+ Context ctx = getContext();+ if (ctx == null) {+ call.reject("no context");+ return;+ }+ long[] pattern = new long[] {0, 200, 100, 200};+ JSArray given = call.getArray("pattern");+ if (given != null && given.length() > 0 && given.length() <= 20) {+ long[] p = new long[given.length() + 1];+ boolean ok = true;+ for (int i = 0; i < given.length(); i++) {+ long v = given.optLong(i, -1);+ if (v < 0 || v > 10_000) { ok = false; break; }+ p[i + 1] = v;+ }+ if (ok) pattern = p;+ }+ RestAlert.buzz(ctx.getApplicationContext(), pattern);+ call.resolve();+ }+@PluginMethodpublic void cancel(PluginCall call) {Context ctx = getContext();diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex 0117a2b9d..1f99a92ec 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -6,7 +6,8 @@ import { bindUI } from './components/ui.jsx'import { ACCENTS, setWeightDecimals } from './lib/format.js'import { setLang, useLang, baseLang } from './lib/i18n.js'import { effectiveLang } from './lib/default-lang.js'-import { setPlayOnSilent, setVibrate } from './lib/sound.js'+import { setPlayOnSilent, setVibrate, setAlarmBuzzer } from './lib/sound.js'+import { buzzAsAlarm } from './lib/rest-alert.js'import { setNav } from './lib/nav.js'import { initBackButton } from './lib/back.js'import { useWakeLock } from './lib/wakelock.js'@@ -70,6 +71,9 @@ function Shell() {useEffect(() => { setPlayOnSilent(!!S.soundOnSilent) }, [S.soundOnSilent])// Settings → Vibrate, the same way: one page-level switch rather than a check at each buzz.useEffect(() => { setVibrate(S.vibrate !== false) }, [S.vibrate])+ // Android app: "Vibrate when the phone is on silent" sends the end-of-rest buzz through the+ // native side as an alarm (#375). buzzAsAlarm answers false off Android, so iOS buzzes as before.+ useEffect(() => { setAlarmBuzzer(MOBILE && S.vibrate !== false && S.vibrateOnSilent ? buzzAsAlarm : null) }, [S.vibrate, S.vibrateOnSilent])const isGuest = useStore(s => s.isGuest())const needsMobileOnboarding = useStore(s => s.needsMobileOnboarding)const langV = useLang() // re-renders the whole shell when the language (pack) changesdiff --git a/frontend/src/components/RestTimer.ready.test.jsx b/frontend/src/components/RestTimer.ready.test.jsxindex e5c746b77..9af07ba35 100644--- a/frontend/src/components/RestTimer.ready.test.jsx+++ b/frontend/src/components/RestTimer.ready.test.jsx@@ -8,7 +8,7 @@ import { useStore } from '../store/useStore.js'globalThis.IS_REACT_ACT_ENVIRONMENT = true-vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), chime: vi.fn(), vibrate: vi.fn() }))+vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), chime: vi.fn(), vibrate: vi.fn(), alertBuzz: vi.fn() }))let host, root, originalSdiff --git a/frontend/src/lib/rest-alert.js b/frontend/src/lib/rest-alert.jsindex 187f2d14f..e97d2fa25 100644--- a/frontend/src/lib/rest-alert.js+++ b/frontend/src/lib/rest-alert.js@@ -26,7 +26,7 @@ export function accentColors(key) {return { accent: argb(ACCENTS[k]), ink: argb(ACCENT_INK[k]) }}-export function buildRestAlert({ at, title, countdownTitle, totalSec, accent, sound = true, vibrate = true, now = Date.now() } = {}) {+export function buildRestAlert({ at, title, countdownTitle, totalSec, accent, sound = true, vibrate = true, alarmBuzz = false, now = Date.now() } = {}) {if (typeof at !== 'number' || !(at > now)) return nullconst totalMs = Math.max(1000, Math.round((totalSec > 0 ? totalSec : (at - now) / 1000) * 1000))const colors = accentColors(accent)@@ -47,6 +47,9 @@ export function buildRestAlert({ at, title, countdownTitle, totalSec, accent, soallowWhileIdle: true,sound: !!sound,vibrate: !!vibrate,+ // Settings → "Vibrate when the phone is on silent" (#375): the end buzzes as an alarm, which+ // silent mode lets through, instead of through the notification channel, which it mutes.+ alarmBuzz: !!vibrate && !!alarmBuzz,localOnly: false,visibility: 'public',importance: 'high',@@ -82,7 +85,7 @@ const restPlugin = () => pluginP || (pluginP = (async () => {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, vibrate: opts.vibrate !== false })+ const alert = buildRestAlert({ at, title: opts.title, countdownTitle: opts.countdownTitle, totalSec: opts.totalSec, accent: opts.accent, sound: opts.sound, vibrate: opts.vibrate !== false, alarmBuzz: !!opts.alarmBuzz })if (!alert) return Promise.resolve(false)return enqueue(async () => {let kind = 'failed'@@ -124,6 +127,18 @@ if (MOBILE) {.catch(() => {})}+// A buzz that silent mode lets through (#375): the native side vibrates as an alarm. Resolves true+// once it did, false anywhere it cannot (the web, iOS, a failed call) for the caller to buzz the+// ordinary way instead. Never resolves with the plugin itself — see restPlugin.+export function buzzAsAlarm(pattern) {+ if (!MOBILE) return Promise.resolve(false)+ const p = Array.isArray(pattern) ? pattern.filter(n => Number.isFinite(n) && n >= 0).map(Math.round) : (Number.isFinite(pattern) && pattern > 0 ? [Math.round(pattern)] : [])+ if (!p.length) return Promise.resolve(false)+ return restPlugin()+ .then(plugin => (plugin ? plugin.RestAlert.buzz({ pattern: p }).then(() => true) : false))+ .catch(() => false)+}+// The running countdown repaints with this swatch. No-op when no rest is on screen.export function setRestAccent(key) {if (!MOBILE) return@@ -162,6 +177,7 @@ async function deliver(alert) {// The end of a rest the app is not in front for: the notification, or the buzz standing in// for it where notifications are off. With the app in front the page buzzes (lib/sound.js).vibrate: alert.vibrate,+ alarmBuzz: alert.alarmBuzz,channelId: alert.channelId,visibility: alert.visibility,importance: alert.importance,diff --git a/frontend/src/lib/rest-alert.native.test.js b/frontend/src/lib/rest-alert.native.test.jsindex e08d3e016..49049a874 100644--- a/frontend/src/lib/rest-alert.native.test.js+++ b/frontend/src/lib/rest-alert.native.test.js@@ -114,6 +114,50 @@ describe('the rest alert in the Android app', () => {})})+// #375: "Vibrate when the phone is on silent".+describe('the alarm buzz in the Android app', () => {+ const capture = () => {+ const calls = {}+ h.registerPlugin = vi.fn(() => new Proxy({}, {+ get: (_, prop) => {+ if (prop === 'then') return () => new Promise(() => {})+ return async (...args) => { (calls[prop] = calls[prop] || []).push(args[0]); return prop === 'addListener' ? { remove: async () => {} } : undefined }+ },+ }))+ return calls+ }++ it('tells the alarm to buzz as an alarm only with Vibrate on', async () => {+ h.platform = 'android'+ const calls = capture()+ const alert = await import('./rest-alert.js')+ await alert.armRestAlert(Date.now() + 90_000, { totalSec: 90, alarmBuzz: true })+ expect(calls.schedule.at(-1)).toMatchObject({ vibrate: true, alarmBuzz: true })+ await alert.armRestAlert(Date.now() + 90_000, { totalSec: 90, vibrate: false, alarmBuzz: true })+ expect(calls.schedule.at(-1)).toMatchObject({ vibrate: false, alarmBuzz: false })+ await alert.armRestAlert(Date.now() + 90_000, { totalSec: 90 })+ expect(calls.schedule.at(-1)).toMatchObject({ alarmBuzz: false })+ })++ it('buzzAsAlarm reaches the plugin with the pattern and answers true', async () => {+ h.platform = 'android'+ const calls = capture()+ const alert = await import('./rest-alert.js')+ await expect(alert.buzzAsAlarm([200, 100, 200])).resolves.toBe(true)+ expect(calls.buzz).toEqual([{ pattern: [200, 100, 200] }])+ await expect(alert.buzzAsAlarm([])).resolves.toBe(false)+ expect(calls.buzz).toHaveLength(1)+ })++ it('answers false in the iOS app without touching any plugin', async () => {+ h.platform = 'ios'+ const alert = await import('./rest-alert.js')+ await expect(alert.buzzAsAlarm([200, 100, 200])).resolves.toBe(false)+ expect(h.registerPlugin).not.toHaveBeenCalled()+ expect(unhandled).toEqual([])+ })+})+// The native half cannot run here; what it must do with the flag is read off its source.describe('the Android side of Vibrate off', () => {const src = name => readFileSync(new URL(`../../android/app/src/main/java/ch/duartesantos/opengym/${name}.java`, import.meta.url), 'utf8')@@ -138,3 +182,25 @@ describe('the Android side of Vibrate off', () => {expect(alert).toMatch(/intent\.putExtra\("vibrate", vibrate\);/)})})++describe('the Android side of the alarm buzz (#375)', () => {+ const src = name => readFileSync(new URL(`../../android/app/src/main/java/ch/duartesantos/opengym/${name}.java`, import.meta.url), 'utf8')+ const alert = src('RestAlert')+ const plugin = src('RestAlertPlugin')++ it('reads the flag from the page, off for an older page, and offers buzz()', () => {+ expect(plugin).toMatch(/call\.getBoolean\("alarmBuzz", Boolean\.FALSE\)/)+ expect(plugin).toMatch(/@PluginMethod\s+public void buzz\(PluginCall call\)/)+ })++ it('buzzes with the alarm usage, on every API level the app runs on', () => {+ expect(alert).toMatch(/VibrationAttributes\.createForUsage\(VibrationAttributes\.USAGE_ALARM\)/)+ expect(alert).toMatch(/setUsage\(AudioAttributes\.USAGE_ALARM\)/)+ })++ it('posts the notification on the quiet channel then, so the ringer-on phone buzzes once', () => {+ expect(alert).toMatch(/boolean vibrate = intent\.getBooleanExtra\("vibrate", true\) && !alarmBuzz;/)+ expect(alert).toMatch(/if \(alarmBuzz\) buzz\(ctx, VIBRATE\);/)+ expect(alert.match(/intent\.putExtra\("alarmBuzz", lastAlarmBuzz\);/g)).toHaveLength(2)+ })+})diff --git a/frontend/src/lib/sound.js b/frontend/src/lib/sound.jsindex 22ac68c63..628898f23 100644--- a/frontend/src/lib/sound.js+++ b/frontend/src/lib/sound.js@@ -138,3 +138,19 @@ export function vibrate(p) {if (!buzz) returntry { navigator.vibrate && navigator.vibrate(p) } catch (e) { /* */ }}++// Settings → "Vibrate when the phone is on silent" (#375), Android app only. The page's buzz is an+// ordinary one, and a phone on silent drops it; the end of a rest or a hold then goes through the+// native side as an alarm (lib/rest-alert.js buzzAsAlarm), which silent mode lets through. App.jsx+// hands that buzzer in while the setting is on; it answers false when it could not buzz, and the+// page's own buzz stands in. A set tick never comes here: it should not override silent.+let alarmBuzzer = null+export function setAlarmBuzzer(fn) { alarmBuzzer = typeof fn === 'function' ? fn : null }+export function alertBuzz(p) {+ if (!buzz) return+ const native = alarmBuzzer+ if (!native) { vibrate(p); return }+ let asked+ try { asked = Promise.resolve(native(p)) } catch (e) { asked = Promise.resolve(false) }+ asked.then(ok => { if (!ok) vibrate(p) }, () => vibrate(p))+}diff --git a/frontend/src/lib/sound.test.js b/frontend/src/lib/sound.test.jsindex 047396bcd..40fa857bb 100644--- a/frontend/src/lib/sound.test.js+++ b/frontend/src/lib/sound.test.js@@ -327,3 +327,52 @@ describe('vibrate switch', () => {expect(() => sound.vibrate(30)).not.toThrow()})})++// #375: the end of a rest or a hold, with "Vibrate when the phone is on silent" on in the Android+// app, buzzes through the native alarm buzz App.jsx hands in; anything else is an ordinary buzz.+describe('alertBuzz', () => {+ let calls+ const flush = async () => { for (let i = 0; i < 5; i++) await Promise.resolve() }+ beforeEach(() => {+ calls = []+ Object.defineProperty(navigator, 'vibrate', { value: p => { calls.push(p); return true }, configurable: true, writable: true })+ })+ afterEach(() => { delete navigator.vibrate; sound.setAlarmBuzzer(null) })++ it('without a native buzzer it is the ordinary buzz', () => {+ sound.alertBuzz([200, 100, 200])+ expect(calls).toEqual([[200, 100, 200]])+ })++ it('with one it goes there, and not also the ordinary way', async () => {+ const native = vi.fn(async () => true)+ sound.setAlarmBuzzer(native)+ sound.alertBuzz([200, 100, 200])+ await flush()+ expect(native).toHaveBeenCalledWith([200, 100, 200])+ expect(calls).toEqual([])+ })++ it('falls back to the ordinary buzz when the native one could not, or threw', async () => {+ sound.setAlarmBuzzer(async () => false)+ sound.alertBuzz([200])+ await flush()+ sound.setAlarmBuzzer(() => { throw new Error('bridge gone') })+ sound.alertBuzz([300])+ await flush()+ sound.setAlarmBuzzer(() => Promise.reject(new Error('no plugin')))+ sound.alertBuzz([400])+ await flush()+ expect(calls).toEqual([[200], [300], [400]])+ })++ it('Vibrate off is off for it too', async () => {+ const native = vi.fn(async () => true)+ sound.setAlarmBuzzer(native)+ sound.setVibrate(false)+ sound.alertBuzz([200, 100, 200])+ await flush()+ expect(native).not.toHaveBeenCalled()+ expect(calls).toEqual([])+ })+})diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.jsindex efa44dc6a..b5dcc5e48 100644--- a/frontend/src/locales/ar.js+++ b/frontend/src/locales/ar.js@@ -1719,4 +1719,6 @@ export default {'Enter how long it took — at least 1 minute.': 'أدخل المدة التي استغرقها — دقيقة واحدة على الأقل.','Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'تم الوصول إلى خادمك، لكنه رفض طلب التطبيق (CORS). إذا كان وكيل عكسي مثل Traefik يضيف ترويسات CORS، فدَع الطلبات القادمة من {0} تمر إلى openGym دون تغيير — راجع «Phone app and CORS» في docs/SELF_HOSTING.md.','Could not reach {0}. Check the address and that this phone can reach it.': 'تعذّر الوصول إلى {0}. تحقّق من العنوان ومن أن هذا الهاتف يستطيع الوصول إليه.',+ 'Vibrate when the phone is on silent': 'الاهتزاز عندما يكون الهاتف صامتًا',+ 'The end of a rest or a hold buzzes like an alarm, even in silent mode.': 'تهتز نهاية الراحة أو التثبيت مثل المنبّه، حتى في الوضع الصامت.',}diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex c9b16e9bc..ea70cf2fa 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -1686,4 +1686,6 @@ export default {'Enter how long it took — at least 1 minute.': 'Gib ein, wie lange es gedauert hat — mindestens 1 Minute.','Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'Dein Server wurde erreicht, hat die Anfrage der App aber abgelehnt (CORS). Wenn ein Reverse Proxy wie Traefik CORS-Header setzt, lass Anfragen von {0} unverändert zu openGym durch — siehe „Phone app and CORS“ in docs/SELF_HOSTING.md.','Could not reach {0}. Check the address and that this phone can reach it.': '{0} ist nicht erreichbar. Prüf die Adresse und ob dieses Handy den Server erreichen kann.',+ 'Vibrate when the phone is on silent': 'Auch bei stummgeschaltetem Telefon vibrieren',+ 'The end of a rest or a hold buzzes like an alarm, even in silent mode.': 'Das Ende einer Pause oder einer Haltezeit vibriert wie ein Wecker, auch im Lautlos-Modus.',}diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.jsindex 7d45c2bb1..e9743db00 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -1666,4 +1666,6 @@ export default {'Enter how long it took — at least 1 minute.': 'Indica cuánto duró — al menos 1 minuto.','Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'Se llegó a tu servidor, pero rechazó la solicitud de la app (CORS). Si un proxy inverso como Traefik añade cabeceras CORS, deja pasar sin cambios hasta openGym las solicitudes de {0}; consulta «Phone app and CORS» en docs/SELF_HOSTING.md.','Could not reach {0}. Check the address and that this phone can reach it.': 'No se pudo llegar a {0}. Comprueba la dirección y que este teléfono pueda alcanzarlo.',+ 'Vibrate when the phone is on silent': 'Vibrar con el teléfono en silencio',+ 'The end of a rest or a hold buzzes like an alarm, even in silent mode.': 'El final de un descanso o de un aguante vibra como una alarma, incluso en silencio.',}diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.jsindex d578d101b..0a724f96d 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -1666,4 +1666,6 @@ export default {'Enter how long it took — at least 1 minute.': 'Indique combien de temps ça a duré — au moins 1 minute.','Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'Ton serveur a été joint, mais il a refusé la requête de l’app (CORS). Si un proxy inverse comme Traefik ajoute des en-têtes CORS, laisse passer les requêtes de {0} jusqu’à openGym sans les modifier — voir « Phone app and CORS » dans docs/SELF_HOSTING.md.','Could not reach {0}. Check the address and that this phone can reach it.': 'Impossible de joindre {0}. Vérifie l’adresse et que ce téléphone peut y accéder.',+ 'Vibrate when the phone is on silent': 'Vibrer même si le téléphone est en mode silencieux',+ 'The end of a rest or a hold buzzes like an alarm, even in silent mode.': 'La fin d’un repos ou d’un maintien vibre comme une alarme, même en mode silencieux.',}diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.jsindex 696c6d937..e5197a8a2 100644--- a/frontend/src/locales/hi.js+++ b/frontend/src/locales/hi.js@@ -1666,4 +1666,6 @@ export default {'Enter how long it took — at least 1 minute.': 'बताएँ कि इसमें कितना समय लगा — कम से कम 1 मिनट।','Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'आपका सर्वर मिल गया, लेकिन उसने ऐप का अनुरोध अस्वीकार कर दिया (CORS)। अगर Traefik जैसा कोई रिवर्स प्रॉक्सी CORS हेडर जोड़ता है, तो {0} से आने वाले अनुरोधों को बिना बदले openGym तक जाने दें — docs/SELF_HOSTING.md में “Phone app and CORS” देखें।','Could not reach {0}. Check the address and that this phone can reach it.': '{0} तक नहीं पहुँच सके। पता जाँचें और देखें कि यह फ़ोन उस तक पहुँच सकता है।',+ 'Vibrate when the phone is on silent': 'फ़ोन साइलेंट पर हो तब भी कंपन करें',+ 'The end of a rest or a hold buzzes like an alarm, even in silent mode.': 'आराम या होल्ड का अंत अलार्म की तरह कंपन करता है, साइलेंट मोड में भी।',}diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.jsindex 9917400e8..b6d4abfff 100644--- a/frontend/src/locales/hu.js+++ b/frontend/src/locales/hu.js@@ -1669,4 +1669,6 @@ export default {'Enter how long it took — at least 1 minute.': 'Add meg, meddig tartott — legalább 1 perc.','Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'A szervered elérhető, de elutasította az app kérését (CORS). Ha egy reverse proxy, például a Traefik CORS-fejléceket ad hozzá, engedd át változatlanul az openGymhez a(z) {0} felől érkező kéréseket — lásd: „Phone app and CORS”, docs/SELF_HOSTING.md.','Could not reach {0}. Check the address and that this phone can reach it.': 'A(z) {0} nem érhető el. Ellenőrizd a címet, és hogy ez a telefon eléri-e.',+ 'Vibrate when the phone is on silent': 'Rezgés akkor is, ha a telefon némítva van',+ 'The end of a rest or a hold buzzes like an alarm, even in silent mode.': 'A pihenő vagy a tartás vége ébresztőként rezeg, néma módban is.',}diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.jsindex 391573347..3649d8f60 100644--- a/frontend/src/locales/it.js+++ b/frontend/src/locales/it.js@@ -1666,4 +1666,6 @@ export default {'Enter how long it took — at least 1 minute.': 'Inserisci quanto è durato — almeno 1 minuto.','Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'Il server è stato raggiunto, ma ha rifiutato la richiesta dell’app (CORS). Se un reverse proxy come Traefik aggiunge header CORS, lascia passare fino a openGym, senza modificarle, le richieste da {0} — vedi «Phone app and CORS» in docs/SELF_HOSTING.md.','Could not reach {0}. Check the address and that this phone can reach it.': 'Impossibile raggiungere {0}. Controlla l’indirizzo e che questo telefono possa raggiungerlo.',+ 'Vibrate when the phone is on silent': 'Vibra anche con il telefono in silenzioso',+ 'The end of a rest or a hold buzzes like an alarm, even in silent mode.': 'La fine di un recupero o di una tenuta vibra come una sveglia, anche in silenzioso.',}diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.jsindex 525754830..81b0b39a8 100644--- a/frontend/src/locales/ko.js+++ b/frontend/src/locales/ko.js@@ -1666,4 +1666,6 @@ export default {'Enter how long it took — at least 1 minute.': '걸린 시간을 입력하세요 — 최소 1분.','Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': '서버에 연결되었지만 앱의 요청을 거부했습니다(CORS). Traefik 같은 리버스 프록시가 CORS 헤더를 추가한다면 {0}에서 오는 요청을 그대로 openGym까지 통과시키세요 — docs/SELF_HOSTING.md의 “Phone app and CORS”를 참고하세요.','Could not reach {0}. Check the address and that this phone can reach it.': '{0}에 연결할 수 없습니다. 주소와 이 휴대폰에서 접속할 수 있는지 확인하세요.',+ 'Vibrate when the phone is on silent': '무음 모드에서도 진동',+ 'The end of a rest or a hold buzzes like an alarm, even in silent mode.': '휴식이나 버티기가 끝나면 무음 모드에서도 알람처럼 진동합니다.',}diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.jsindex 5d3e26904..59d6ca8c5 100644--- a/frontend/src/locales/pl.js+++ b/frontend/src/locales/pl.js@@ -1666,4 +1666,6 @@ export default {'Enter how long it took — at least 1 minute.': 'Wpisz, ile to trwało — co najmniej 1 minutę.','Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'Serwer odpowiada, ale odrzucił żądanie aplikacji (CORS). Jeśli reverse proxy, np. Traefik, dodaje nagłówki CORS, przepuść żądania z {0} do openGym bez zmian — zobacz „Phone app and CORS” w docs/SELF_HOSTING.md.','Could not reach {0}. Check the address and that this phone can reach it.': 'Nie można połączyć się z {0}. Sprawdź adres i czy ten telefon ma do niego dostęp.',+ 'Vibrate when the phone is on silent': 'Wibruj także przy wyciszonym telefonie',+ 'The end of a rest or a hold buzzes like an alarm, even in silent mode.': 'Koniec przerwy lub utrzymania wibruje jak budzik, nawet w trybie cichym.',}diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.jsindex 4ee6861a2..012459691 100644--- a/frontend/src/locales/pt-BR.js+++ b/frontend/src/locales/pt-BR.js@@ -1011,6 +1011,8 @@ export const PT_BR_OVERRIDES = {'Move out of the superset': 'Tirar do superset','Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'Seu servidor foi alcançado, mas recusou a solicitação do aplicativo (CORS). Se um proxy reverso como o Traefik adiciona cabeçalhos CORS, deixe as solicitações de {0} passarem até o openGym sem alterações — veja “Phone app and CORS” em docs/SELF_HOSTING.md.','Could not reach {0}. Check the address and that this phone can reach it.': 'Não foi possível alcançar {0}. Verifique o endereço e se este celular consegue acessá-lo.',+ 'Vibrate when the phone is on silent': 'Vibrar com o celular no silencioso',+ 'The end of a rest or a hold buzzes like an alarm, even in silent mode.': 'O fim de um descanso ou de uma isometria vibra como um alarme, mesmo no silencioso.',}export default { ...pt, ...PT_BR_OVERRIDES }diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.jsindex 7a132bd06..eda8ad3e8 100644--- a/frontend/src/locales/pt.js+++ b/frontend/src/locales/pt.js@@ -1666,4 +1666,6 @@ export default {'Enter how long it took — at least 1 minute.': 'Indica quanto tempo demorou — pelo menos 1 minuto.','Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'O teu servidor foi alcançado, mas recusou o pedido da app (CORS). Se um proxy inverso como o Traefik acrescenta cabeçalhos CORS, deixa passar os pedidos de {0} até ao openGym sem alterações — vê “Phone app and CORS” em docs/SELF_HOSTING.md.','Could not reach {0}. Check the address and that this phone can reach it.': 'Não foi possível alcançar {0}. Verifica o endereço e se este telemóvel o consegue alcançar.',+ 'Vibrate when the phone is on silent': 'Vibrar com o telemóvel em silêncio',+ 'The end of a rest or a hold buzzes like an alarm, even in silent mode.': 'O fim de um descanso ou de uma isometria vibra como um alarme, mesmo em silêncio.',}diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.jsindex e51c35bef..fbf189a2e 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -1666,4 +1666,6 @@ export default {'Enter how long it took — at least 1 minute.': 'Укажите, сколько это длилось — не меньше 1 минуты.','Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'Сервер доступен, но отклонил запрос приложения (CORS). Если обратный прокси, например Traefik, добавляет заголовки CORS, пропускайте запросы с {0} к openGym без изменений — см. «Phone app and CORS» в docs/SELF_HOSTING.md.','Could not reach {0}. Check the address and that this phone can reach it.': 'Не удалось связаться с {0}. Проверьте адрес и доступен ли сервер с этого телефона.',+ 'Vibrate when the phone is on silent': 'Вибрировать в беззвучном режиме',+ 'The end of a rest or a hold buzzes like an alarm, even in silent mode.': 'Конец отдыха или удержания вибрирует как будильник, даже в беззвучном режиме.',}diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.jsindex 229c189cc..fe6557863 100644--- a/frontend/src/locales/th.js+++ b/frontend/src/locales/th.js@@ -1677,4 +1677,6 @@ export default {'Enter how long it took — at least 1 minute.': 'ใส่ระยะเวลาที่ใช้ — อย่างน้อย 1 นาที','Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'เข้าถึงเซิร์ฟเวอร์ได้ แต่เซิร์ฟเวอร์ปฏิเสธคำขอของแอป (CORS) หากรีเวิร์สพร็อกซีอย่าง Traefik เพิ่มเฮดเดอร์ CORS ให้ปล่อยคำขอจาก {0} ผ่านไปยัง openGym โดยไม่แก้ไข — ดู “Phone app and CORS” ใน docs/SELF_HOSTING.md','Could not reach {0}. Check the address and that this phone can reach it.': 'ไม่สามารถเข้าถึง {0} ได้ ตรวจสอบที่อยู่และดูว่าโทรศัพท์เครื่องนี้เข้าถึงได้หรือไม่',+ 'Vibrate when the phone is on silent': 'สั่นแม้โทรศัพท์อยู่ในโหมดเงียบ',+ 'The end of a rest or a hold buzzes like an alarm, even in silent mode.': 'เมื่อหมดเวลาพักหรือการค้าง โทรศัพท์จะสั่นเหมือนนาฬิกาปลุก แม้อยู่ในโหมดเงียบ',}diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.jsindex d58e8a1b3..c41272dea 100644--- a/frontend/src/locales/tr.js+++ b/frontend/src/locales/tr.js@@ -1666,4 +1666,6 @@ export default {'Enter how long it took — at least 1 minute.': 'Ne kadar sürdüğünü gir — en az 1 dakika.','Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': "Sunucuna ulaşıldı ama uygulamanın isteğini reddetti (CORS). Traefik gibi bir ters vekil sunucu CORS başlıkları ekliyorsa {0} adresinden gelen istekleri değiştirmeden openGym'e ilet — docs/SELF_HOSTING.md içindeki “Phone app and CORS” bölümüne bak.",'Could not reach {0}. Check the address and that this phone can reach it.': '{0} adresine ulaşılamadı. Adresi ve bu telefonun ona erişebildiğini kontrol et.',+ 'Vibrate when the phone is on silent': 'Telefon sessizdeyken de titreş',+ 'The end of a rest or a hold buzzes like an alarm, even in silent mode.': 'Dinlenmenin ya da tutuşun sonu, sessiz modda bile alarm gibi titreşir.',}diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.jsindex 27245bbe9..c99ec200d 100644--- a/frontend/src/locales/uk.js+++ b/frontend/src/locales/uk.js@@ -1663,4 +1663,6 @@ export default {'Enter how long it took — at least 1 minute.': 'Вкажи, скільки це тривало — щонайменше 1 хвилину.','Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': 'Сервер доступний, але відхилив запит застосунку (CORS). Якщо зворотний проксі, як-от Traefik, додає заголовки CORS, пропускай запити з {0} до openGym без змін — див. «Phone app and CORS» у docs/SELF_HOSTING.md.','Could not reach {0}. Check the address and that this phone can reach it.': 'Не вдалося зв’язатися з {0}. Перевір адресу і чи може цей телефон до нього дістатися.',+ 'Vibrate when the phone is on silent': 'Вібрувати в беззвучному режимі',+ 'The end of a rest or a hold buzzes like an alarm, even in silent mode.': 'Кінець відпочинку чи утримання вібрує як будильник, навіть у беззвучному режимі.',}diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.jsindex 2ae4e3217..6734611aa 100644--- a/frontend/src/locales/zh.js+++ b/frontend/src/locales/zh.js@@ -1666,4 +1666,6 @@ export default {'Enter how long it took — at least 1 minute.': '请输入用时 — 至少 1 分钟。','Your server was reached, but it refused the app’s request (CORS). If a reverse proxy such as Traefik adds CORS headers, let requests from {0} through to openGym unchanged — see “Phone app and CORS” in docs/SELF_HOSTING.md.': '已连接到你的服务器,但它拒绝了应用的请求(CORS)。如果 Traefik 等反向代理会添加 CORS 头,请让来自 {0} 的请求原样转发到 openGym — 参见 docs/SELF_HOSTING.md 中的 “Phone app and CORS”。','Could not reach {0}. Check the address and that this phone can reach it.': '无法连接到 {0}。请检查地址,以及这部手机能否访问它。',+ 'Vibrate when the phone is on silent': '手机静音时也振动',+ 'The end of a rest or a hold buzzes like an alarm, even in silent mode.': '休息或保持结束时会像闹钟一样振动,即使在静音模式下。',}diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex ad87486e6..037023bde 100644--- a/frontend/src/store/useStore.js+++ b/frontend/src/store/useStore.js@@ -72,7 +72,7 @@ const gainedWorkoutMedia = (prev, next) => {return workoutMediaHashes(next).some(h => !had.has(h))}export const DEF = {- unit: 'kg', restSec: 90, restPauseSec: 15, sound: true, soundOnSilent: false, timerFlash: false, timedSetOvertime: false, keepAwake: true, lang: 'en',+ unit: 'kg', restSec: 90, restPauseSec: 15, sound: true, soundOnSilent: false, vibrateOnSilent: false, timerFlash: false, timedSetOvertime: false, keepAwake: true, lang: 'en',theme: 'dark', accent: 'lime', body: 'male', targetW: null,bodyweight: [], routines: [], week: {}, dayPlan: {},exWeights: {}, workouts: [], active: null, customEx: [], gifSize: 'full',diff --git a/frontend/src/store/useUI.js b/frontend/src/store/useUI.jsindex 74f803eb4..b9b22686d 100644--- a/frontend/src/store/useUI.js+++ b/frontend/src/store/useUI.js@@ -1,6 +1,6 @@import { create } from 'zustand'import { uid } from '../lib/format.js'-import { beep, chime, vibrate } from '../lib/sound.js'+import { beep, chime, vibrate, alertBuzz } from '../lib/sound.js'import { api } from '../lib/api.js'import { t } from '../lib/i18n.js'import { deviceId } from '../lib/push.js'@@ -21,7 +21,7 @@ const cancelPushRestTimer = () => { if (useStore.getState().user) api('/api/pushconst bookRestEnd = (endsAt, totalSec) => {if (!MOBILE) { pushRestTimer(Math.max(1, Math.round((endsAt - Date.now()) / 1000))); return }const { S } = useStore.getState()- armRestAlert(endsAt, { title: t('Rest over — next set!'), countdownTitle: t('Rest'), totalSec, accent: S.accent, sound: !!S.sound, vibrate: S.vibrate !== false })+ armRestAlert(endsAt, { title: t('Rest over — next set!'), countdownTitle: t('Rest'), totalSec, accent: S.accent, sound: !!S.sound, vibrate: S.vibrate !== false, alarmBuzz: S.vibrate !== false && !!S.vibrateOnSilent }).then(ok => {// Only for the rest that asked: one skipped or moved since then has booked its own end.const tm = useUI.getState().timer@@ -99,7 +99,7 @@ const runRest = (set, get) => {// The Android alarm for this end stays quiet while the app is on screen, so this chime is// the only one. Locked, this branch never runs and the alarm's tone does.chime(snd)- vibrate([200, 100, 200]); get().flashTimer()+ alertBuzz([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@@ -280,7 +280,7 @@ export const useUI = create((set, get) => ({if (left <= 0) {if (seenLive && !wk.alerted) {chime(snd)- vibrate([200, 100, 200]); get().flashTimer()+ alertBuzz([200, 100, 200]); get().flashTimer()}if (wk.overtime && left > -MAX_WORK_OVERTIME_SEC) { set({ work: { ...wk, left, alerted: true } }); return }const done = workDonediff --git a/frontend/src/store/useUI.native-rest.test.js b/frontend/src/store/useUI.native-rest.test.jsindex e006f388e..77ca7a604 100644--- a/frontend/src/store/useUI.native-rest.test.js+++ b/frontend/src/store/useUI.native-rest.test.js@@ -14,7 +14,7 @@ vi.mock('../lib/rest-alert.js', () => ({disarmRestAlert: vi.fn(),bindNativeRest: vi.fn(cb => { h.native = cb }),}))-vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), chime: vi.fn(), vibrate: vi.fn() }))+vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), chime: vi.fn(), vibrate: vi.fn(), alertBuzz: vi.fn() }))vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({ ok: true })) }))import { useUI } from './useUI.js'diff --git a/frontend/src/store/useUI.pause.test.js b/frontend/src/store/useUI.pause.test.jsindex 3ce1d3a17..2b8895af1 100644--- a/frontend/src/store/useUI.pause.test.js+++ b/frontend/src/store/useUI.pause.test.js@@ -5,7 +5,7 @@ import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest'vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({ ok: true })) }))const { beep, chime } = vi.hoisted(() => ({ beep: vi.fn(), chime: vi.fn() }))-vi.mock('../lib/sound.js', () => ({ beep, chime, vibrate: vi.fn() }))+vi.mock('../lib/sound.js', () => ({ beep, chime, vibrate: vi.fn(), alertBuzz: vi.fn() }))import { api } from '../lib/api.js'import { useUI } from './useUI.js'diff --git a/frontend/src/store/useUI.silent-buzz.test.js b/frontend/src/store/useUI.silent-buzz.test.jsnew file mode 100644index 000000000..b1760d0e7--- /dev/null+++ b/frontend/src/store/useUI.silent-buzz.test.js@@ -0,0 +1,74 @@+// @vitest-environment happy-dom+// #375: on silent, the end of a rest buzzed nowhere — the page's buzz and the notification+// channel's are both muted. With "Vibrate when the phone is on silent" on, the native alarm is+// told to buzz as an alarm, and the page's own end-of-rest buzz goes through alertBuzz (which+// App.jsx points at the native alarm buzz). A set tick stays an ordinary buzz.+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++vi.mock('../lib/mobile.js', async importOriginal => ({ ...(await importOriginal()), MOBILE: true }))+vi.mock('../lib/rest-alert.js', () => ({+ armRestAlert: vi.fn(() => Promise.resolve(true)),+ holdRestAlert: vi.fn(),+ disarmRestAlert: vi.fn(),+ bindNativeRest: vi.fn(),+}))+vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), chime: vi.fn(), vibrate: vi.fn(), alertBuzz: vi.fn() }))+vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({ ok: true })) }))++import { useUI } from './useUI.js'+import { useStore } from './useStore.js'+import { armRestAlert } from '../lib/rest-alert.js'+import { alertBuzz, vibrate } from '../lib/sound.js'++let original+beforeEach(() => {+ vi.useFakeTimers()+ original = useStore.getState().S+ useUI.setState({ timer: null, timerFlashId: 0 })+ for (const f of [armRestAlert, alertBuzz, vibrate]) f.mockClear()+ Object.defineProperty(document, 'hidden', { configurable: true, get: () => false })+})+afterEach(() => {+ useUI.getState().stopRest()+ useStore.setState({ S: original })+ vi.useRealTimers()+})++const withSettings = over => useStore.setState({ S: { ...original, sound: false, ...over }, user: null })++describe('vibrate on silent', () => {+ it('asks the native alarm for an alarm buzz only with the setting and Vibrate both on', () => {+ withSettings({ vibrate: true, vibrateOnSilent: true })+ useUI.getState().startRest(60)+ expect(armRestAlert).toHaveBeenLastCalledWith(expect.any(Number), expect.objectContaining({ vibrate: true, alarmBuzz: true }))++ withSettings({ vibrate: false, vibrateOnSilent: true })+ useUI.getState().startRest(60)+ expect(armRestAlert).toHaveBeenLastCalledWith(expect.any(Number), expect.objectContaining({ vibrate: false, alarmBuzz: false }))++ withSettings({ vibrate: true })+ useUI.getState().startRest(60)+ expect(armRestAlert).toHaveBeenLastCalledWith(expect.any(Number), expect.objectContaining({ alarmBuzz: false }))+ })++ it('the end of a rest seen on screen buzzes through alertBuzz', async () => {+ withSettings({ vibrate: true, vibrateOnSilent: true })+ useUI.getState().startRest(2)+ await vi.advanceTimersByTimeAsync(3000)+ expect(alertBuzz).toHaveBeenCalledWith([200, 100, 200])+ expect(vibrate).not.toHaveBeenCalledWith([200, 100, 200])+ })++ it('a hold that ends early only ticks, the ordinary way', () => {+ withSettings({ vibrate: true, vibrateOnSilent: true })+ useUI.getState().startWork(30, 'Plank', () => {})+ useUI.getState().finishWorkEarly()+ expect(vibrate).toHaveBeenCalledWith(30)+ expect(alertBuzz).not.toHaveBeenCalled()+ })++ it('is off for a profile that never chose', async () => {+ const { DEF } = await import('./useStore.js')+ expect(DEF.vibrateOnSilent).toBe(false)+ })+})diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsxindex d04cc7246..cb7b2ae9e 100644--- a/frontend/src/views/Settings.jsx+++ b/frontend/src/views/Settings.jsx@@ -484,6 +484,15 @@ export default function Settings() {<Switch checked={S.vibrate !== false} onChange={v => update(s => { s.vibrate = v })} /></Row>)}+ {/* Android app only (#375): silent mode mutes the ordinary buzz and the notification's, so+ the end of a rest or a hold can buzz as an alarm instead. Opt-in, like the iOS row above:+ an alarm-class buzz is the most insistent thing an app can do on some phones. */}+ {MOBILE && android && vibrateSupported() && S.vibrate !== false && (+ <Row icon="bell" iconTint="var(--indigo)" title={t('Vibrate when the phone is on silent')}+ subtitle={t('The end of a rest or a hold buzzes like an alarm, even in silent mode.')}>+ <Switch checked={!!S.vibrateOnSilent} onChange={v => update(s => { s.vibrateOnSilent = v })} />+ </Row>+ )}<Row icon="sun" iconTint="var(--yellow)" title={t('Flash screen when timer ends')}><Switch checked={!!S.timerFlash} onChange={v => update(s => { s.timerFlash = v })} /></Row>diff --git a/frontend/src/views/Settings.vibrate-silent.test.jsx b/frontend/src/views/Settings.vibrate-silent.test.jsxnew file mode 100644index 000000000..e6298b977--- /dev/null+++ b/frontend/src/views/Settings.vibrate-silent.test.jsx@@ -0,0 +1,127 @@+// @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++// #375: "Vibrate when the phone is on silent" is an Android-app setting — only there can the+// native side buzz as an alarm — and it belongs to Vibrate, so it shows only with Vibrate on.+const mocks = vi.hoisted(() => {+ const state = { S: null, MOBILE: false, android: false }+ state.snapshot = () => ({+ S: state.S,+ user: null,+ update: mut => {+ const next = structuredClone(state.S)+ mut(next)+ state.S = next+ },+ 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.checkForUpdate = vi.fn(() => Promise.resolve({ hasUpdate: true, latestVersion: '9.9.9', apkUrl: 'https://x/opengym.apk', hashUrl: null }))+ state.confirmSheet = 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: vi.fn(), 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 }))+// MOBILE is read at render time through a getter so one module mock serves both builds.+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: (...a) => mocks.checkForUpdate(...a),+ downloadAndInstall: vi.fn(),+}))+vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))+vi.mock('../sheets.jsx', () => ({+ starterPlanSheet: vi.fn(), confirmSheet: (...a) => mocks.confirmSheet(...a), importFromApp: vi.fn(),+ importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(), menuSheet: vi.fn(),+}))++globalThis.__APP_VERSION__ ??= 'test'++let host, root+beforeEach(() => {+ mocks.S = {+ unit: 'kg', restSec: 90, restPauseSec: 15, sound: false, effort: 'none', vibrateOnSilent: false,+ gifSize: 'full', workouts: [], routines: [], exWeights: {},+ }+ mocks.MOBILE = false+ mocks.android = false+ mocks.checkForUpdate.mockClear()+ mocks.confirmSheet.mockClear()+ Object.defineProperty(navigator, 'vibrate', { value: () => true, configurable: true, writable: true })+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+})+afterEach(() => {+ act(() => root.unmount())+ host.remove()+ delete navigator.vibrate+})++// The effect resolves two promises (isAndroid, then checkForUpdate) before the row can render.+const mount = async () => {+ await act(async () => { root.render(<Settings />) })+ await act(async () => { await Promise.resolve(); await Promise.resolve() })+}+const TITLE = 'Vibrate when the phone is on silent'+const rowTitled = title => [...host.querySelectorAll('.lrow')].find(r => r.querySelector('.lrow-t')?.textContent === title)+const switchIn = row => row.querySelector('[role="switch"]') || row.querySelector('input[type="checkbox"]') || row.querySelector('button')++describe('Settings — vibrate when the phone is on silent', () => {+ it('Android app: offered right under Vibrate, off by default, and writes the setting', async () => {+ mocks.MOBILE = true+ mocks.android = true+ await mount()+ const row = rowTitled(TITLE)+ expect(row).toBeTruthy()+ expect(row.querySelector('.lrow-s').textContent).toBe('The end of a rest or a hold buzzes like an alarm, even in silent mode.')+ const rows = [...host.querySelectorAll('.lrow')]+ expect(rows.indexOf(row)).toBe(rows.indexOf(rowTitled('Vibrate')) + 1)+ expect(switchIn(row).getAttribute('aria-checked')).toBe('false')+ act(() => { switchIn(row).click() })+ expect(mocks.S.vibrateOnSilent).toBe(true)+ })++ it('not offered while Vibrate is off', async () => {+ mocks.MOBILE = true+ mocks.android = true+ mocks.S.vibrate = false+ await mount()+ expect(rowTitled('Vibrate')).toBeTruthy()+ expect(rowTitled(TITLE)).toBeUndefined()+ })++ it('not offered on the web or in the iOS app', async () => {+ await mount()+ expect(rowTitled('Vibrate')).toBeTruthy()+ expect(rowTitled(TITLE)).toBeUndefined()+ act(() => root.unmount())+ root = createRoot(host)+ mocks.MOBILE = true+ await mount()+ expect(rowTitled(TITLE)).toBeUndefined()+ })+})diff --git a/frontend/src/views/Workout.edit-empty.test.jsx b/frontend/src/views/Workout.edit-empty.test.jsxindex b2a11ad6c..9d748d555 100644--- a/frontend/src/views/Workout.edit-empty.test.jsx+++ b/frontend/src/views/Workout.edit-empty.test.jsx@@ -11,7 +11,7 @@ import { DEF, useStore } from '../store/useStore.js'import { useUI } from '../store/useUI.js'import { editCompletedSession } from '../lib/session-edit.js'-vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), chime: vi.fn(), vibrate: vi.fn(), unlock: vi.fn() }))+vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), chime: vi.fn(), vibrate: vi.fn(), alertBuzz: vi.fn(), unlock: vi.fn() }))vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})), appBase: () => '/' }))globalThis.IS_REACT_ACT_ENVIRONMENT = truediff --git a/frontend/src/views/Workout.hold.test.jsx b/frontend/src/views/Workout.hold.test.jsxindex 7ff6b152e..93de2d7df 100644--- a/frontend/src/views/Workout.hold.test.jsx+++ b/frontend/src/views/Workout.hold.test.jsx@@ -9,9 +9,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import Workout from './Workout.jsx'import { DEF, useStore } from '../store/useStore.js'import { useUI } from '../store/useUI.js'-import { beep, chime, vibrate } from '../lib/sound.js'+import { beep, chime, vibrate, alertBuzz } from '../lib/sound.js'-vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), chime: vi.fn(), vibrate: vi.fn(), unlock: vi.fn() }))+vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), chime: vi.fn(), vibrate: vi.fn(), alertBuzz: vi.fn(), unlock: vi.fn() }))vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})), appBase: () => '/' }))globalThis.IS_REACT_ACT_ENVIRONMENT = true@@ -44,7 +44,7 @@ const doneOf = () => useStore.getState().S.active.entries[0].sets.map(s => s.donbeforeEach(() => {vi.useFakeTimers()localStorage.clear()- vi.mocked(beep).mockClear(); vi.mocked(chime).mockClear(); vi.mocked(vibrate).mockClear()+ vi.mocked(beep).mockClear(); vi.mocked(chime).mockClear(); vi.mocked(vibrate).mockClear(); vi.mocked(alertBuzz).mockClear()useUI.setState({ sheets: [], toastMsg: '', timer: null, work: null })root = nullcontainer = null@@ -67,7 +67,9 @@ describe('the end of a hold', () => {expect(doneOf()).toEqual([true, false])expect(chime).toHaveBeenCalledOnce()expect(tickBeeps()).toEqual([])- expect(vibrate.mock.calls).toEqual([[[200, 100, 200]]])+ // The end's buzz goes through alertBuzz, which can buzz as an alarm on silent (#375).+ expect(alertBuzz.mock.calls).toEqual([[[200, 100, 200]]])+ expect(vibrate).not.toHaveBeenCalled()})it('finished early with Done: the set ticks the way a tap does, beep and buzz', () => {diff --git a/frontend/src/views/Workout.keys.test.jsx b/frontend/src/views/Workout.keys.test.jsxindex 0ac899f71..59fefb84e 100644--- a/frontend/src/views/Workout.keys.test.jsx+++ b/frontend/src/views/Workout.keys.test.jsx@@ -9,7 +9,7 @@ import Workout from './Workout.jsx'import { DEF, useStore } from '../store/useStore.js'import { useUI } from '../store/useUI.js'-vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), chime: vi.fn(), vibrate: vi.fn(), unlock: vi.fn() }))+vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), chime: vi.fn(), vibrate: vi.fn(), alertBuzz: vi.fn(), unlock: vi.fn() }))vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})), appBase: () => '/' }))globalThis.IS_REACT_ACT_ENVIRONMENT = truediff --git a/frontend/src/views/Workout.noprog-session.test.jsx b/frontend/src/views/Workout.noprog-session.test.jsxindex b5d0b556f..6d5ca40de 100644--- a/frontend/src/views/Workout.noprog-session.test.jsx+++ b/frontend/src/views/Workout.noprog-session.test.jsx@@ -14,7 +14,7 @@ import { editCompletedSession } from '../lib/session-edit.js'import { lastEntryFor } from '../lib/history.js'import { EXDB } from '../lib/exercises.js'-vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), chime: vi.fn(), vibrate: vi.fn(), unlock: vi.fn() }))+vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), chime: vi.fn(), vibrate: vi.fn(), alertBuzz: vi.fn(), unlock: vi.fn() }))vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})), appBase: () => '/' }))globalThis.IS_REACT_ACT_ENVIRONMENT = truediff --git a/frontend/src/views/Workout.noprog.test.jsx b/frontend/src/views/Workout.noprog.test.jsxindex a6399682e..1a07ef0b2 100644--- a/frontend/src/views/Workout.noprog.test.jsx+++ b/frontend/src/views/Workout.noprog.test.jsx@@ -16,7 +16,7 @@ import { buildSessionEntries } from '../lib/session-start.js'import { swapActiveWorkoutExercise } from '../sheets.jsx'import { EXDB } from '../lib/exercises.js'-vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), chime: vi.fn(), vibrate: vi.fn(), unlock: vi.fn() }))+vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), chime: vi.fn(), vibrate: vi.fn(), alertBuzz: vi.fn(), unlock: vi.fn() }))vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})), appBase: () => '/' }))globalThis.IS_REACT_ACT_ENVIRONMENT = truediff --git a/frontend/src/views/Workout.plates.test.jsx b/frontend/src/views/Workout.plates.test.jsxindex c8eaddf91..38ba9c222 100644--- a/frontend/src/views/Workout.plates.test.jsx+++ b/frontend/src/views/Workout.plates.test.jsx@@ -10,7 +10,7 @@ import { DEF, useStore } from '../store/useStore.js'import { useUI } from '../store/useUI.js'import { EXIDX } from '../lib/exercises.js'-vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), vibrate: vi.fn(), unlock: vi.fn(), restOver: vi.fn() }))+vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), vibrate: vi.fn(), alertBuzz: vi.fn(), unlock: vi.fn(), restOver: vi.fn() }))vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})) }))globalThis.IS_REACT_ACT_ENVIRONMENT = truediff --git a/frontend/src/views/Workout.remove.test.jsx b/frontend/src/views/Workout.remove.test.jsxindex 7e8c8f942..f432dcfbf 100644--- a/frontend/src/views/Workout.remove.test.jsx+++ b/frontend/src/views/Workout.remove.test.jsx@@ -8,7 +8,7 @@ import { DEF, useStore } from '../store/useStore.js'import { useUI } from '../store/useUI.js'import { LANGS, DERIVED_LOCALES } from '../lib/i18n-core.js'-vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), vibrate: vi.fn(), unlock: vi.fn() }))+vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), vibrate: vi.fn(), alertBuzz: vi.fn(), unlock: vi.fn() }))vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})) }))globalThis.IS_REACT_ACT_ENVIRONMENT = truediff --git a/frontend/src/views/Workout.speed.test.jsx b/frontend/src/views/Workout.speed.test.jsxindex 74c039ac8..3a0a276e6 100644--- a/frontend/src/views/Workout.speed.test.jsx+++ b/frontend/src/views/Workout.speed.test.jsx@@ -8,7 +8,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'import Workout from './Workout.jsx'import { DEF, useStore } from '../store/useStore.js'-vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), vibrate: vi.fn(), unlock: vi.fn() }))+vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), vibrate: vi.fn(), alertBuzz: vi.fn(), unlock: vi.fn() }))vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})) }))globalThis.IS_REACT_ACT_ENVIRONMENT = true