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
Rest alarm: never wait on the notification prompt, skip an end that already passed
Duarte Santos74cce8844db8
diff --git a/frontend/src/lib/rest-alert.js b/frontend/src/lib/rest-alert.jsindex bcfbeb619..070771204 100644--- a/frontend/src/lib/rest-alert.js+++ b/frontend/src/lib/rest-alert.js@@ -87,6 +87,10 @@ export function armRestAlert(at, opts = {}) {const mine = ++tokenconst 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)+ // Outside the chain and never awaited: the alarm, its tone and the alarm buzz do not need the+ // notification permission, and a dialog left open while the phone is put away must not hold+ // the alarm back until the rest is long over.+ askNotifPermissionOnce()return enqueue(async () => {let kind = 'failed'try { kind = await deliver(alert) } catch { kind = 'failed' }@@ -149,26 +153,50 @@ export function setRestAccent(key) {})}-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- }+// The notification permission is asked once, the first time a rest starts. The answer is kept:+// Android lets an app ask again after a "Don't allow", and asking on every rest would pop the+// dialog between every set. Settings → Notifications in the system is where it changes later.+export const NOTIF_ASKED_KEY = 'gym_rest_notif_asked'+let askP = null+const readAsked = () => { try { return localStorage.getItem(NOTIF_ASKED_KEY) } catch { return null } }+const writeAsked = v => { try { localStorage.setItem(NOTIF_ASKED_KEY, v) } catch { /* asked again next launch */ } }++export function askNotifPermissionOnce() {+ if (askP) return askP+ askP = (async () => {+ try {+ if (!(await isAndroid())) return false+ const { LocalNotifications } = await import('@capacitor/local-notifications')+ const perm = await LocalNotifications.checkPermissions()+ if (perm.display === 'granted') return true+ if (perm.display === 'denied' || readAsked()) return false+ const got = await LocalNotifications.requestPermissions()+ // Kept only once really answered. Leaving the app closes the dialog and reports "denied",+ // but the permission still reads 'prompt' then: nobody chose, so the next launch asks again+ // (this one does not: askP holds the answer for the rest of the session).+ const after = got.display === 'granted' ? got : await LocalNotifications.checkPermissions().catch(() => got)+ if (after.display !== 'prompt') writeAsked(got.display === 'granted' ? 'granted' : 'denied')+ return got.display === 'granted'+ } catch {+ return false+ }+ })()+ return askP}+// Test seam: a fresh launch.+export function _resetNotifAsk() { askP = null }+async function deliver(alert) {+ // The end passed while the call waited its turn (a slow bridge, a frozen WebView): nothing to+ // ring any more, and the plugin would refuse it ("at must be in the future").+ if (!(alert.at > Date.now())) return 'expired'const p = await restPlugin()if (!p) return 'skipped'const { RestAlert } = p- await ensureNotifPermission()- // Sound still schedules when notification permission is missing: the alarm tone does- // not need it. The notification does, which is why we ask above.+ if (!(alert.at > Date.now())) return 'expired'+ // Sound, the alarm buzz and the alarm itself need no notification permission; only the+ // countdown card does, and askNotifPermissionOnce() asks for it on the side.await RestAlert.schedule({id: alert.id,at: alert.at,diff --git a/frontend/src/lib/rest-alert.native.test.js b/frontend/src/lib/rest-alert.native.test.jsindex 9d175837b..d8fa2ccd8 100644--- a/frontend/src/lib/rest-alert.native.test.js+++ b/frontend/src/lib/rest-alert.native.test.js@@ -8,7 +8,9 @@ import { readFileSync } from 'node:fs'const h = vi.hoisted(() => {vi.stubEnv('VITE_MOBILE', '1') // lib/mobile.js: MOBILE = import.meta.env.VITE_MOBILE === '1'- return { platform: 'android', calls: [], registerPlugin: null }+ const store = new Map()+ vi.stubGlobal('localStorage', { getItem: k => (store.has(k) ? store.get(k) : null), setItem: (k, v) => store.set(k, String(v)), clear: () => store.clear() })+ return { platform: 'android', calls: [], registerPlugin: null, perm: 'granted', request: null }})// Shaped like the proxy registerPlugin() returns: every property is a native method, `then`@@ -31,8 +33,8 @@ vi.mock('@capacitor/core', () => ({}))vi.mock('@capacitor/local-notifications', () => ({LocalNotifications: {- checkPermissions: async () => ({ display: 'granted' }),- requestPermissions: async () => ({ display: 'granted' }),+ checkPermissions: async () => ({ display: h.perm }),+ requestPermissions: (...args) => (h.request ? h.request(...args) : Promise.resolve({ display: 'granted' })),},}))@@ -45,6 +47,9 @@ beforeEach(() => {vi.resetModules()h.calls = []h.registerPlugin = vi.fn(() => pluginProxy())+ h.perm = 'granted'+ h.request = null+ localStorage.clear()unhandled.length = 0process.on('unhandledRejection', onUnhandled)})@@ -204,3 +209,108 @@ describe('the Android side of the alarm buzz (#375)', () => {expect(alert.match(/intent\.putExtra\("alarmBuzz", lastAlarmBuzz\);/g)).toHaveLength(2)})})++// Fresh install, notifications not decided yet: the first rest pops the permission dialog. The+// QA left the app with the dialog open; the alarm waited behind the answer, so nothing rang, and+// once answered the schedule was refused ("at must be in the future") and blocked what followed.+describe('the notification permission never holds the rest alarm back', () => {+ 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('schedules the alarm while the permission dialog is still open', async () => {+ h.platform = 'android'+ h.perm = 'prompt'+ h.request = vi.fn(() => new Promise(() => {})) // the dialog nobody answers+ const calls = capture()+ const alert = await import('./rest-alert.js')+ await expect(alert.armRestAlert(Date.now() + 60_000, { totalSec: 60, alarmBuzz: true })).resolves.toBe(true)+ expect(calls.schedule).toHaveLength(1)+ expect(calls.schedule[0]).toMatchObject({ alarmBuzz: true })+ alert.disarmRestAlert()+ await expect(alert.armRestAlert(Date.now() + 60_000, { totalSec: 60 })).resolves.toBe(true)+ await settle()+ expect(calls.cancel).toHaveLength(1)+ expect(calls.schedule).toHaveLength(2)+ expect(h.request).toHaveBeenCalledTimes(1)+ })++ it('skips an end that passed before its turn instead of failing and blocking the next one', async () => {+ h.platform = 'android'+ const schedule = vi.fn(async a => { if (!(a.at > Date.now())) throw new Error('at must be in the future') })+ let release+ const gate = new Promise(r => { release = r })+ h.registerPlugin = vi.fn(() => new Proxy({}, {+ get: (_, prop) => prop === 'then' ? () => new Promise(() => {})+ : prop === 'schedule' ? schedule+ : prop === 'hold' ? () => gate+ : async () => ({ remove: async () => {} }),+ }))+ const alert = await import('./rest-alert.js')+ alert.holdRestAlert(30, 60) // a slow bridge call ahead in the chain+ const late = alert.armRestAlert(Date.now() + 30, { totalSec: 1 })+ await new Promise(r => setTimeout(r, 60))+ release()+ await expect(late).resolves.toBe(false)+ expect(schedule).not.toHaveBeenCalled()+ await expect(alert.armRestAlert(Date.now() + 60_000, { totalSec: 60 })).resolves.toBe(true)+ expect(schedule).toHaveBeenCalledTimes(1)+ })++ it('asks once, and after a "Don\'t allow" never again, not even after a restart', async () => {+ h.platform = 'android'+ h.perm = 'prompt'+ h.request = vi.fn(async () => { h.perm = 'prompt-with-rationale'; return { display: 'denied' } })+ capture()+ let alert = await import('./rest-alert.js')+ for (let i = 0; i < 3; i++) await expect(alert.armRestAlert(Date.now() + 60_000, { totalSec: 60, alarmBuzz: true })).resolves.toBe(true)+ await settle()+ expect(h.request).toHaveBeenCalledTimes(1)+ vi.resetModules() // the app is started again+ alert = await import('./rest-alert.js')+ await expect(alert.armRestAlert(Date.now() + 60_000, { totalSec: 60 })).resolves.toBe(true)+ await settle()+ expect(h.request).toHaveBeenCalledTimes(1)+ })++ // On the emulator: Home pressed with the dialog open closes it, requestPermissions answers+ // "denied", and the permission still reads 'prompt'. Nobody said no; the next launch asks.+ it('a dialog closed by leaving the app is not a "Don\'t allow": asked again next launch, not this session', async () => {+ h.platform = 'android'+ h.perm = 'prompt'+ h.request = vi.fn(async () => ({ display: 'denied' }))+ capture()+ let alert = await import('./rest-alert.js')+ await alert.armRestAlert(Date.now() + 60_000, { totalSec: 60 })+ await alert.armRestAlert(Date.now() + 60_000, { totalSec: 60 })+ await settle()+ expect(h.request).toHaveBeenCalledTimes(1)+ expect(localStorage.getItem('gym_rest_notif_asked')).toBeNull()+ vi.resetModules()+ alert = await import('./rest-alert.js')+ await alert.armRestAlert(Date.now() + 60_000, { totalSec: 60 })+ await settle()+ expect(h.request).toHaveBeenCalledTimes(2)+ })++ it('does not ask when notifications are already allowed or turned off', async () => {+ h.platform = 'android'+ h.request = vi.fn(async () => ({ display: 'granted' }))+ capture()+ for (const perm of ['granted', 'denied']) {+ vi.resetModules()+ h.perm = perm+ const alert = await import('./rest-alert.js')+ await alert.armRestAlert(Date.now() + 60_000, { totalSec: 60 })+ await settle()+ }+ expect(h.request).not.toHaveBeenCalled()+ })+})