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.

Phone: hand the scheduled nudges and reminders to a background check

Duarte Santos7faadb622077
diff --git a/frontend/src/lib/api.js b/frontend/src/lib/api.js
index d92fc6fb9..20d0b7ceb 100644
--- a/frontend/src/lib/api.js
+++ b/frontend/src/lib/api.js
@@ -33,6 +33,10 @@ export function setAccessHeaders(h, origin) { accessHeaders = Object.assign({},
const originOf = base => { try { return new URL(base).origin } catch { return '' } }
const accessFor = base => (base && accessOrigin && originOf(base) === accessOrigin ? accessHeaders : {})
const remoteHeaders = () => Object.assign({}, accessFor(remoteBase), remoteToken ? { Authorization: 'Bearer ' + remoteToken } : {})
+// The paired server and what a request to it carries (the token, an Access service token for that
+// origin), for the phone's background check (lib/nudge-check.js), which runs with no WebView and
+// so has to be handed them. null when this is not a paired phone.
+export const remoteAuth = () => (remoteBase && remoteToken ? { base: remoteBase, headers: remoteHeaders() } : null)
export { appBase }
diff --git a/frontend/src/lib/mobile.js b/frontend/src/lib/mobile.js
index 5615056c2..4b08b8883 100644
--- a/frontend/src/lib/mobile.js
+++ b/frontend/src/lib/mobile.js
@@ -195,12 +195,15 @@ export async function syncReminder(S, interactive = false) {
...Array.from({ length: NUDGE_WINDOW_DAYS }, (_, d) => ({ id: NUDGE_ID_BASE + d })),
] }).catch(() => {})
const r = S.reminder
- if (!r?.on) return true
+ // The background check (lib/nudge-check.js) follows what is scheduled: nothing, nothing to check.
+ const check = notifications => import('./nudge-check.js').then(m => m.armNudgeCheck(S, notifications)).catch(() => {})
+ if (!r?.on) { await check([]); return true }
let perm = await LocalNotifications.checkPermissions()
if (perm.display !== 'granted' && interactive) perm = await LocalNotifications.requestPermissions()
- if (perm.display !== 'granted') return false
+ if (perm.display !== 'granted') { await check([]); return false }
const notifications = [...buildReminderNotifications(S), ...buildNudgeNotifications(S)]
if (notifications.length) await LocalNotifications.schedule({ notifications })
+ await check(notifications)
return true
} catch (e) { return false }
}
diff --git a/frontend/src/lib/mobile.nudge-check.test.js b/frontend/src/lib/mobile.nudge-check.test.js
new file mode 100644
index 000000000..ca3ad1efd
--- /dev/null
+++ b/frontend/src/lib/mobile.nudge-check.test.js
@@ -0,0 +1,37 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+/* syncReminder hands what it scheduled to the background check (lib/nudge-check.js), and nothing
+ once nothing is scheduled: the check follows the notifications, never the other way round. */
+const mocks = vi.hoisted(() => ({ perm: 'granted', schedule: vi.fn(async () => {}), arm: vi.fn(async () => true) }))
+vi.mock('@capacitor/local-notifications', () => ({
+ LocalNotifications: {
+ cancel: vi.fn(async () => {}),
+ checkPermissions: async () => ({ display: mocks.perm }),
+ requestPermissions: async () => ({ display: mocks.perm }),
+ schedule: (...a) => mocks.schedule(...a),
+ }
+}))
+vi.mock('./nudge-check.js', () => ({ armNudgeCheck: (...a) => mocks.arm(...a) }))
+
+import { syncReminder } from './mobile.js'
+
+const S = reminder => ({ reminder, routines: [{ id: 'push', name: 'Push' }], week: { 0: ['push'], 1: ['push'], 2: ['push'], 3: ['push'], 4: ['push'], 5: ['push'], 6: ['push'] }, workouts: [] })
+
+beforeEach(() => { mocks.perm = 'granted'; mocks.schedule.mockClear(); mocks.arm.mockClear() })
+
+describe('syncReminder and the background check', () => {
+ it('hands over exactly what it scheduled', async () => {
+ const state = S({ on: true, nudge: true, time: '08:00' })
+ expect(await syncReminder(state)).toBe(true)
+ const scheduled = mocks.schedule.mock.calls[0][0].notifications
+ expect(scheduled.length).toBeGreaterThan(0)
+ expect(mocks.arm).toHaveBeenCalledWith(state, scheduled)
+ })
+ it('the reminder off, or no permission: the check is handed nothing', async () => {
+ await syncReminder(S({ on: false }))
+ mocks.perm = 'denied'
+ await syncReminder(S({ on: true, nudge: true, time: '08:00' }))
+ expect(mocks.arm.mock.calls.map(c => c[1])).toEqual([[], []])
+ expect(mocks.schedule).not.toHaveBeenCalled()
+ })
+})
diff --git a/frontend/src/lib/nudge-check.js b/frontend/src/lib/nudge-check.js
new file mode 100644
index 000000000..7590f3f5d
--- /dev/null
+++ b/frontend/src/lib/nudge-check.js
@@ -0,0 +1,84 @@
+// The phone's background check before a nudge or a reminder it scheduled on itself (lib/mobile.js
+// syncReminder). Both are local notifications, worked out from this phone's copy of the profile:
+// a workout logged on the web or on another phone, with this one left in a pocket, used to be
+// followed at 20:00 by "you missed it". So a paired phone also hands the native NudgeCheck plugin
+// (ios/App/App/NudgeCheckPlugin.swift: BGAppRefreshTask; android/.../NudgeCheckPlugin.java:
+// JobScheduler) the days it has something scheduled for. Shortly before each one fires, the
+// plugin asks the server how that day stands (GET /api/nudge-check, a few bytes) and takes back
+// what no longer applies. Offline, the server down, an answer it cannot read: nothing changes.
+// When the app comes back to the foreground it resyncs from the full state as before.
+//
+// iOS decides when a background refresh actually runs (how much the app is used, battery, Low
+// Power Mode), so there the check is a good chance, not a promise; Android runs it in the window
+// asked for unless the phone is in deep sleep. See docs/MOBILE.md.
+import { MOBILE } from './mobile.js'
+import { isoOf } from './format.js'
+import { remoteAuth } from './api.js'
+
+// The id ranges syncReminder schedules (lib/mobile.js): workout-day reminders, then nudges.
+export const REMINDER_IDS = [1000, 1999]
+export const NUDGE_IDS = [2000, 2999]
+const inRange = (id, [lo, hi]) => id >= lo && id <= hi
+
+/**
+ * The days a background check is for, from the notifications syncReminder just scheduled:
+ * `{ date, at, reminder: [ids], nudge: [ids] }` per calendar day, `at` the first of them to fire
+ * (ms), soonest first. Only what is still ahead of `now`.
+ */
+export function nudgeCheckPlan(notifications, now = Date.now()) {
+ const byDate = new Map()
+ for (const n of notifications || []) {
+ const when = n?.schedule?.at instanceof Date ? n.schedule.at.getTime() : NaN
+ if (!Number.isFinite(when) || when <= now) continue
+ const kind = inRange(n.id, NUDGE_IDS) ? 'nudge' : inRange(n.id, REMINDER_IDS) ? 'reminder' : null
+ if (!kind) continue
+ const date = isoOf(new Date(when))
+ const e = byDate.get(date) || { date, at: when, reminder: [], nudge: [] }
+ e.at = Math.min(e.at, when)
+ e[kind].push(n.id)
+ byDate.set(date, e)
+ }
+ return [...byDate.values()].sort((a, b) => a.at - b.at)
+}
+
+/**
+ * What one answer from GET /api/nudge-check takes back for its day: everything once the day was
+ * trained or excused (`done`), only the nudge when the server would not nudge it (its plan moved),
+ * nothing on anything else. No answer (offline, an error) or one that is not the server's for this
+ * day: nothing, the phone keeps what it planned. The native plugins apply the same rule.
+ */
+export function idsToCancel(entry, answer) {
+ if (!entry || !answer || typeof answer !== 'object' || answer.date !== entry.date) return []
+ if (answer.done === true) return [...entry.reminder, ...entry.nudge]
+ if (answer.nudge === false) return [...entry.nudge]
+ return []
+}
+
+// Registered once, and handed out inside an object: a Capacitor plugin proxy answers `then` with
+// a native call that never settles, so a promise resolved with the bare proxy hangs (#42).
+let pluginP = null
+const checkPlugin = () => pluginP || (pluginP = (async () => {
+ if (!MOBILE) return null
+ const { registerPlugin } = await import('@capacitor/core')
+ return { NudgeCheck: registerPlugin('NudgeCheck') }
+})().catch(() => null))
+
+/**
+ * Hands the plan to the native side, or takes it back: armed only on a paired phone with the
+ * reminder and the missed-day nudge on. Never throws; a phone without the plugin (an older native
+ * shell) just goes without the check, as before.
+ */
+export async function armNudgeCheck(S, notifications, now = Date.now()) {
+ const p = await checkPlugin()
+ if (!p) return false
+ const r = S?.reminder
+ const auth = remoteAuth()
+ const entries = r?.on && r.nudge && auth ? nudgeCheckPlan(notifications, now) : []
+ try {
+ if (!entries.length) { await p.NudgeCheck.disarm(); return false }
+ await p.NudgeCheck.arm({ server: auth.base, headers: auth.headers, entries })
+ return true
+ } catch { return false }
+}
+
+export function _resetNudgeCheck() { pluginP = null }
diff --git a/frontend/src/lib/nudge-check.test.js b/frontend/src/lib/nudge-check.test.js
new file mode 100644
index 000000000..41d8b9422
--- /dev/null
+++ b/frontend/src/lib/nudge-check.test.js
@@ -0,0 +1,90 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+/* The phone's background check before a nudge or a reminder it scheduled on itself
+ (lib/nudge-check.js): which days it is for, what an answer from GET /api/nudge-check takes back,
+ and when it is handed to the native NudgeCheck plugin at all. The plugin is a stand-in shaped
+ like Capacitor's: a Proxy whose `then` is a native call that never answers (#42). */
+const mocks = vi.hoisted(() => ({ MOBILE: true, auth: null, arm: vi.fn(async () => {}), disarm: vi.fn(async () => {}), registered: 0 }))
+vi.mock('./mobile.js', () => ({ get MOBILE() { return mocks.MOBILE } }))
+vi.mock('./api.js', () => ({ remoteAuth: () => mocks.auth }))
+vi.mock('@capacitor/core', () => ({
+ registerPlugin: name => {
+ mocks.registered++
+ expect(name).toBe('NudgeCheck')
+ return new Proxy({}, { get: (_, k) => k === 'arm' ? mocks.arm : k === 'disarm' ? mocks.disarm : () => new Promise(() => {}) })
+ }
+}))
+
+import { nudgeCheckPlan, idsToCancel, armNudgeCheck, _resetNudgeCheck } from './nudge-check.js'
+
+const at = (iso, hhmm) => new Date(`${iso}T${hhmm}:00`)
+const n = (id, iso, hhmm) => ({ id, title: 'x', body: 'y', schedule: { at: at(iso, hhmm), allowWhileIdle: true } })
+const NOW = at('2026-10-13', '12:00').getTime()
+// What syncReminder schedules at noon: today's nudge, tomorrow's reminder and nudge.
+const scheduled = [n(1001, '2026-10-14', '08:00'), n(2000, '2026-10-13', '20:00'), n(2001, '2026-10-14', '20:00'), n(1000, '2026-10-13', '08:00')]
+const today = { date: '2026-10-13', at: at('2026-10-13', '20:00').getTime(), reminder: [], nudge: [2000] }
+const tomorrow = { date: '2026-10-14', at: at('2026-10-14', '08:00').getTime(), reminder: [1001], nudge: [2001] }
+const S = (reminder = { on: true, nudge: true, time: '08:00' }) => ({ reminder })
+
+beforeEach(() => {
+ mocks.MOBILE = true
+ mocks.auth = { base: 'https://gym.example.com', headers: { Authorization: 'Bearer tok' } }
+ mocks.arm.mockClear(); mocks.disarm.mockClear()
+ _resetNudgeCheck()
+})
+
+describe('nudgeCheckPlan', () => {
+ it('one entry per day still ahead, soonest first, reminders and nudges apart', () => {
+ expect(nudgeCheckPlan(scheduled, NOW)).toEqual([today, tomorrow])
+ })
+ it('leaves out what has fired, and anything that is not a reminder or a nudge', () => {
+ expect(nudgeCheckPlan([n(1000, '2026-10-13', '08:00'), n(42, '2026-10-14', '09:00'), { id: 2003 }], NOW)).toEqual([])
+ expect(nudgeCheckPlan(null, NOW)).toEqual([])
+ })
+})
+
+describe('idsToCancel', () => {
+ it('logged on another device: the day’s nudge and reminder go', () => {
+ expect(idsToCancel(tomorrow, { date: '2026-10-14', done: true, nudge: false, rev: 9 })).toEqual([1001, 2001])
+ })
+ it('a day note written elsewhere counts the same (the server says done)', () => {
+ expect(idsToCancel(today, { date: '2026-10-13', done: true, nudge: false, rev: 9 })).toEqual([2000])
+ })
+ it('not logged: everything stays', () => {
+ expect(idsToCancel(tomorrow, { date: '2026-10-14', done: false, nudge: true, rev: 9 })).toEqual([])
+ })
+ it('the plan moved elsewhere, nothing due that day: only the nudge goes, the reminder is the next sync’s', () => {
+ expect(idsToCancel(tomorrow, { date: '2026-10-14', done: false, nudge: false, rev: 9 })).toEqual([2001])
+ })
+ it('no answer, an error, or an answer about another day: nothing changes', () => {
+ for (const a of [null, undefined, 'offline', { error: 'not signed in' }, { date: '2026-10-13', done: true }]) {
+ expect(idsToCancel(tomorrow, a), JSON.stringify(a)).toEqual([])
+ }
+ })
+})
+
+describe('armNudgeCheck', () => {
+ it('a paired phone with the reminder and the nudge on hands over the server, its headers and the days', async () => {
+ expect(await armNudgeCheck(S(), scheduled, NOW)).toBe(true)
+ expect(mocks.arm).toHaveBeenCalledWith({ server: 'https://gym.example.com', headers: { Authorization: 'Bearer tok' }, entries: [today, tomorrow] })
+ expect(mocks.disarm).not.toHaveBeenCalled()
+ })
+ it('takes it back when there is nothing to check: not paired, the nudge or the reminder off, nothing scheduled', async () => {
+ for (const [state, list, auth] of [[S(), scheduled, null], [S({ on: true, nudge: false }), scheduled, mocks.auth], [S({ on: false, nudge: true }), scheduled, mocks.auth], [S(), [], mocks.auth]]) {
+ mocks.auth = auth
+ expect(await armNudgeCheck(state, list, NOW)).toBe(false)
+ }
+ expect(mocks.disarm).toHaveBeenCalledTimes(4)
+ expect(mocks.arm).not.toHaveBeenCalled()
+ })
+ it('the web build registers nothing', async () => {
+ mocks.MOBILE = false
+ mocks.registered = 0
+ expect(await armNudgeCheck(S(), scheduled, NOW)).toBe(false)
+ expect(mocks.registered).toBe(0)
+ })
+ it('a native shell without the plugin goes without the check, quietly', async () => {
+ mocks.arm.mockRejectedValueOnce(new Error('"NudgeCheck" plugin is not implemented on ios'))
+ expect(await armNudgeCheck(S(), scheduled, NOW)).toBe(false)
+ })
+})