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.

Widgets and Live Activity, the page's side

Duarte Santos4107fb56d986
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index f75d8d77e..f062e1697 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -13,6 +13,8 @@ import { setNav, notePath, keyBefore } from './lib/nav.js'
import { setSystemBarsLight } from './lib/system-bars.js'
import { initBackButton } from './lib/back.js'
import { installEdgeSwipeBack, BACK_PREVIEW_EVENT } from './lib/edge-swipe-back.js'
+import { startWidgetSync } from './lib/widgets.js'
+import { startLiveActivitySync } from './lib/live-activity.js'
import { useWakeLock } from './lib/wakelock.js'
import { installViewportGuard } from './lib/viewport-guard.js'
import { installChipDrag } from './lib/hchips.js'
@@ -325,5 +327,15 @@ export default function App() {
}, [])
// iOS: swipe from the left edge for the page's own back button (lib/edge-swipe-back.js)
useEffect(() => installEdgeSwipeBack(), [])
+ // iPhone app: the Home Screen widgets and the workout's Live Activity (lib/widgets.js,
+ // lib/live-activity.js). Nothing at all on the web or on Android.
+ useEffect(() => {
+ if (!MOBILE) return
+ const stops = [], gone = { v: false }
+ const keep = fn => { if (gone.v) fn(); else stops.push(fn) }
+ startWidgetSync({ useStore }).then(keep).catch(() => {})
+ startLiveActivitySync({ useStore, useUI }).then(keep).catch(() => {})
+ return () => { gone.v = true; stops.forEach(fn => fn()) }
+ }, [])
return <HashRouter><Shell /></HashRouter>
}
diff --git a/frontend/src/lib/live-activity.js b/frontend/src/lib/live-activity.js
new file mode 100644
index 000000000..c7c24bd59
--- /dev/null
+++ b/frontend/src/lib/live-activity.js
@@ -0,0 +1,243 @@
+// The running workout on the iPhone's Lock Screen and in the Dynamic Island (a Live Activity), the
+// page's side (native: ios/App/App/LiveActivityPlugin.swift and WorkoutActivity.swift, the views in
+// ios/App/OpenGymWidgets). An Apple Watch shows the same activity in its Smart Stack.
+//
+// Page → activity: while a workout runs, its state as the Lock Screen shows it (the set to do now
+// and the few after it, the rest's end, how far along the session is) whenever that changes. The
+// rest counts down on the Lock Screen by itself (Text(timerInterval:)), so nothing is sent per
+// second.
+//
+// Activity → page: its Done button ticks the set it shows. iOS runs that in the app (an App Intent)
+// even with the page asleep, so the native side queues it as a small event ({ id, type: 'setDone',
+// wid, exId, entryIdx, setIdx, at }), moves the activity on to the next set itself, and the page
+// applies the event when it can: through the workout screen's own tick (bindLiveActions), the one
+// a tap in the app runs (rest timer, the high-water mark, the end-of-workout sheet), never a second
+// copy of it. Each event is applied once, by its id, and only then acknowledged, which takes it out
+// of the native queue; until the workout screen is there to apply it, it waits there.
+//
+// Text only: no exercise animations or pictures (Gym visual licence). iPhone app only.
+import { MOBILE, nativePlatform } from './mobile.js'
+import { EXIDX } from './exercises.js'
+import { exerciseNameFor, t } from './i18n.js'
+import { setLabel, supersetUnits } from './history.js'
+import { isWarmupRow } from './workout-model.js'
+import { restSecFor } from './supersetFlow.js'
+import { speedUnitOf } from './speed.js'
+import { accentPair, accentValue } from './accent.js'
+
+export const LIVE_VERSION = 1
+const APPLIED_KEY = 'gym_live_applied'
+const APPLIED_MAX = 300
+const SEND_DEBOUNCE_MS = 300
+// The sets after the current one the activity carries, so its Done can move on without the page.
+export const LIVE_AHEAD = 3
+
+const num = v => (typeof v === 'number' && Number.isFinite(v) ? v : null)
+
+/* ---------- what the activity shows ---------- */
+
+/**
+ * The sets still to do, in the order the workout screen leads through them: from the current
+ * exercise's unit on, a superset round by round (a1, b1, a2, b2), then the units after it, then
+ * the ones before it that still have sets open. Each with the rest that follows it.
+ */
+export function upcomingSets (S) {
+ const A = S && S.active
+ if (!A || !Array.isArray(A.entries) || !A.entries.length) return []
+ const units = supersetUnits(A.entries)
+ const cur = Math.max(0, Math.min(A.entries.length - 1, A.cur || 0))
+ const start = Math.max(0, units.findIndex(u => u.includes(cur)))
+ const order = [...units.slice(start), ...units.slice(0, start)]
+ const out = []
+ for (const unit of order) {
+ const rounds = Math.max(0, ...unit.map(i => (A.entries[i]?.sets || []).length))
+ let rest = 0
+ try { rest = restSecFor(A.entries, unit, num(S.restSec) || 0) || 0 } catch { rest = num(S.restSec) || 0 }
+ for (let r = 0; r < rounds; r++) {
+ const inRound = unit.filter(i => { const s = A.entries[i]?.sets?.[r]; return s && !s.done })
+ inRound.forEach((i, k) => out.push({ entryIdx: i, setIdx: r, restAfter: k === inRound.length - 1 ? rest : 0 }))
+ }
+ }
+ return out
+}
+
+function setView (S, A, { entryIdx, setIdx, restAfter }) {
+ const e = A.entries[entryIdx]
+ const s = e.sets[setIdx]
+ const target = e.target || {}
+ const work = (e.sets || []).filter(x => !isWarmupRow(x))
+ const warmup = !!isWarmupRow(s)
+ const n = warmup ? (e.sets || []).filter(isWarmupRow).indexOf(s) + 1 : work.indexOf(s) + 1
+ let label = ''
+ try { label = setLabel(e.id, s, target, speedUnitOf(S)) } catch { label = '' }
+ return {
+ exId: String(e.id),
+ entryIdx,
+ setIdx,
+ exName: EXIDX[e.id] ? exerciseNameFor(EXIDX[e.id]) : String(target.name || e.name || e.id),
+ setLine: warmup ? t('Warm-up') + ' ' + n : t('Set {0} of {1}', n, work.length),
+ target: label,
+ restAfter: Math.max(0, Math.round(restAfter || 0)),
+ }
+}
+
+/**
+ * The activity's fixed part (`attributes`: what stays the same for the workout) and its state, or
+ * null when no workout is running here. `timer` is the rest as useUI holds it.
+ */
+export function buildLiveActivity (S, timer = null) {
+ const A = S && S.active
+ if (!A || !Array.isArray(A.entries) || !A.entries.length || A.editingWorkoutId) return null
+ const next = upcomingSets(S)
+ let done = 0, total = 0
+ for (const e of A.entries) for (const s of e?.sets || []) { total++; if (s?.done) done++ }
+ const rest = timer && !timer.ready && timer.kind !== 'switch' ? timer : null
+ const pair = accentPair(accentValue(S))
+ return {
+ attributes: {
+ v: LIVE_VERSION,
+ wid: String(A.id || ''),
+ start: num(A.start),
+ accent: pair.accent,
+ ink: pair.ink,
+ labels: {
+ done: t('Done'),
+ rest: t('Rest'),
+ next: t('Up next'),
+ allDone: t('All sets done'),
+ restOver: t('Rest’s over. Next set!'),
+ },
+ },
+ state: {
+ name: A.name || '',
+ cur: next.length ? setView(S, A, next[0]) : null,
+ ahead: next.slice(1, 1 + LIVE_AHEAD).map(x => setView(S, A, x)),
+ restEndsAt: rest && !rest.paused ? num(rest.endsAt) : null,
+ restLeft: rest && rest.paused ? num(rest.left) : null,
+ restTotal: rest ? num(rest.total) : null,
+ done,
+ total,
+ },
+ }
+}
+
+/* ---------- applying the activity's events ---------- */
+
+let handlers = null // the workout screen's: setDone
+const readApplied = () => { try { return JSON.parse(localStorage.getItem(APPLIED_KEY)) || [] } catch { return [] } }
+const writeApplied = ids => { try { localStorage.setItem(APPLIED_KEY, JSON.stringify(ids.slice(-APPLIED_MAX))) } catch { /* the queue's ack is what counts */ } }
+
+function entryIndexOf (A, ev) {
+ if (A.entries[ev.entryIdx] && String(A.entries[ev.entryIdx].id) === String(ev.exId)) return ev.entryIdx
+ return A.entries.findIndex(e => String(e.id) === String(ev.exId))
+}
+
+/**
+ * Applies the events not applied yet, in order, and returns the ids that are done with: applied
+ * now, applied before, or about a workout that is not running any more. Without the workout
+ * screen's actions the run stops, and that event and the ones after it stay queued.
+ */
+export function applyLiveEvents (events, getState) {
+ if (!Array.isArray(events)) return []
+ const applied = readApplied()
+ const done = []
+ for (const ev of events) {
+ if (!ev || typeof ev.id !== 'string') continue
+ if (applied.includes(ev.id)) { done.push(ev.id); continue }
+ const A = getState()?.S?.active
+ const ours = A && Array.isArray(A.entries) && !A.editingWorkoutId && (!ev.wid || ev.wid === String(A.id))
+ if (ev.type === 'setDone' && ours) {
+ if (!handlers) break
+ const idx = entryIndexOf(A, ev)
+ const set = idx >= 0 ? A.entries[idx].sets?.[ev.setIdx] : null
+ if (set && !set.done) handlers.setDone(idx, ev.setIdx, { at: num(ev.at) })
+ }
+ // Applied, or meaningless now (another workout, a set that is gone or already ticked).
+ applied.push(ev.id)
+ done.push(ev.id)
+ }
+ writeApplied(applied)
+ return done
+}
+
+/* ---------- the native plugin ---------- */
+
+let pluginP = null
+// Inside an object: a Capacitor plugin proxy answers `then` (lib/rest-alert.js, the Coach hang #42).
+const livePlugin = () => pluginP || (pluginP = (async () => {
+ if (!MOBILE || (await nativePlatform()) !== 'ios') return null
+ const { registerPlugin } = await import('@capacitor/core')
+ return { LiveActivity: registerPlugin('LiveActivity') }
+})().catch(() => null))
+
+let getStateRef = null
+let draining = null
+
+/** Takes the Done taps from the native queue, applies them, and acknowledges what is done. */
+export function drainLiveEvents () {
+ if (draining) return draining
+ draining = (async () => {
+ try {
+ const p = await livePlugin()
+ if (!p || !getStateRef) return []
+ const { events = [] } = (await p.LiveActivity.drain()) || {}
+ const done = applyLiveEvents(events, getStateRef)
+ if (done.length) await p.LiveActivity.ack({ ids: done })
+ return done
+ } catch { return [] } finally { draining = null }
+ })()
+ return draining
+}
+
+/** The workout screen hands over its own tick while it is mounted. Returns the unbind. */
+export function bindLiveActions (h) {
+ handlers = h
+ drainLiveEvents()
+ return () => { if (handlers === h) handlers = null }
+}
+
+/**
+ * Started once by the app: shows, updates and ends the activity as the workout and its rest
+ * change (debounced, only what differs from the last one sent), and drains the Done taps when the
+ * app comes back or the native side says one came in. Resolves with the stop function.
+ */
+export async function startLiveActivitySync ({ useStore, useUI }) {
+ const p = await livePlugin()
+ if (!p) return () => {}
+ getStateRef = () => useStore.getState()
+ let supported = false
+ try { supported = !!(await p.LiveActivity.status())?.supported } catch { supported = false }
+ let last = null, tm = null
+ const send = async () => {
+ tm = null
+ try {
+ const live = buildLiveActivity(useStore.getState().S, useUI.getState().timer)
+ const json = live ? JSON.stringify(live) : ''
+ if (json === last) return
+ if (live) await p.LiveActivity.update({ wid: live.attributes.wid, attributes: JSON.stringify(live.attributes), state: JSON.stringify(live.state) })
+ else await p.LiveActivity.end()
+ last = json
+ } catch { /* not now: the next change tries again */ }
+ }
+ const schedule = () => { if (!supported) return; clearTimeout(tm); tm = setTimeout(send, SEND_DEBOUNCE_MS) }
+ const offStore = useStore.subscribe((s, prev) => { if (s.S !== prev.S) schedule() })
+ const restOf = x => (x ? `${x.endsAt}|${!!x.paused}|${!!x.ready}|${x.left}|${x.kind || ''}` : '')
+ const offUI = useUI.subscribe((s, prev) => {
+ if (s.timer === prev.timer) return
+ // A running rest changes `left` every second; only a start, a stop or a pause matters here.
+ const a = s.timer, b = prev.timer
+ const same = a && b && !a.paused && !b.paused && a.endsAt === b.endsAt && !!a.ready === !!b.ready
+ if (!same && restOf(a) !== restOf(b)) schedule()
+ })
+ const sub = await p.LiveActivity.addListener('liveActivityEvent', () => { drainLiveEvents() }).catch(() => null)
+ const onVisible = () => { if (document.visibilityState === 'visible') { drainLiveEvents(); schedule() } }
+ document.addEventListener('visibilitychange', onVisible)
+ // At launch: a workout that ended while the app was gone takes its activity with it.
+ if (supported) send()
+ drainLiveEvents()
+ return () => { offStore(); offUI(); sub?.remove?.(); document.removeEventListener('visibilitychange', onVisible); clearTimeout(tm) }
+}
+
+// Test seams.
+export function _setLivePluginForTest (plugin, getState) { pluginP = Promise.resolve(plugin ? { LiveActivity: plugin } : null); getStateRef = getState || null }
+export function _resetLiveActivity () { handlers = null; pluginP = null; getStateRef = null; draining = null }
diff --git a/frontend/src/lib/live-activity.test.js b/frontend/src/lib/live-activity.test.js
new file mode 100644
index 000000000..b8692cc56
--- /dev/null
+++ b/frontend/src/lib/live-activity.test.js
@@ -0,0 +1,163 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+// The workout's Live Activity (lib/live-activity.js): the state the Lock Screen and the Dynamic
+// Island show, and the Done taps that come back from it. A tap is applied once, by its id, through
+// the workout screen's own tick, and only then taken out of the native queue.
+const h = vi.hoisted(() => { vi.stubEnv('VITE_MOBILE', '1'); return { platform: 'ios' } })
+vi.mock('./mobile.js', () => ({ MOBILE: true, nativePlatform: async () => h.platform }))
+
+const L = await import('./live-activity.js')
+
+const set = (over = {}) => ({ w: 60, r: 8, done: false, ...over })
+const entry = (id, sets, over = {}) => ({ id, target: { mode: 'reps', restSec: 120 }, sets, ...over })
+const S = (active, over = {}) => ({ unit: 'kg', restSec: 90, accent: 'lime', active, ...over })
+
+describe('upcomingSets', () => {
+ it('goes through the current exercise first, then the ones after it, then the ones before', () => {
+ const A = { id: 'a', cur: 1, entries: [entry('0025', [set(), set()]), entry('0043', [set({ done: true }), set()]), entry('0001', [set()])] }
+ expect(L.upcomingSets(S(A)).map(x => [x.entryIdx, x.setIdx])).toEqual([[1, 1], [2, 0], [0, 0], [0, 1]])
+ })
+ it('takes a superset round by round, resting after each round only', () => {
+ const A = { id: 'a', cur: 0, entries: [entry('0025', [set(), set()], { sg: 'g' }), entry('0043', [set(), set()], { sg: 'g' })] }
+ const up = L.upcomingSets(S(A))
+ expect(up.map(x => [x.entryIdx, x.setIdx])).toEqual([[0, 0], [1, 0], [0, 1], [1, 1]])
+ expect(up.map(x => x.restAfter > 0)).toEqual([false, true, false, true])
+ })
+ it('is empty without a workout', () => {
+ expect(L.upcomingSets(S(null))).toEqual([])
+ })
+})
+
+describe('buildLiveActivity', () => {
+ const A = { id: 'w1', name: 'Push', start: 1000, cur: 0, entries: [entry('0025', [set({ done: true }), set({ w: 62.5 }), set()]), entry('c9', [set()], { target: { name: 'Cable thing', mode: 'reps' } })] }
+
+ it('shows the set to do now, the few after it, and how far along the session is', () => {
+ const live = L.buildLiveActivity(S(A))
+ expect(live.attributes).toMatchObject({ v: 1, wid: 'w1', start: 1000, accent: '#30d158' })
+ for (const k of ['done', 'rest', 'next', 'allDone', 'restOver']) expect(typeof live.attributes.labels[k], k).toBe('string')
+ expect(live.state.name).toBe('Push')
+ expect(live.state.cur).toMatchObject({ exId: '0025', entryIdx: 0, setIdx: 1, setLine: 'Set 2 of 3', restAfter: 120 })
+ expect(live.state.cur.target).toMatch(/62[.,]5/)
+ expect(live.state.ahead.map(x => [x.entryIdx, x.setIdx])).toEqual([[0, 2], [1, 0]])
+ expect(live.state.ahead[1].exName).toBe('Cable thing')
+ expect(live.state).toMatchObject({ done: 1, total: 4, restEndsAt: null, restLeft: null })
+ })
+ it('carries the rest: its end while it runs, what is left while paused, nothing once over', () => {
+ expect(L.buildLiveActivity(S(A), { endsAt: 5000, total: 90, left: 40 }).state).toMatchObject({ restEndsAt: 5000, restTotal: 90, restLeft: null })
+ expect(L.buildLiveActivity(S(A), { endsAt: 5000, total: 90, left: 40, paused: true }).state).toMatchObject({ restEndsAt: null, restLeft: 40 })
+ expect(L.buildLiveActivity(S(A), { endsAt: 5000, total: 90, left: 0, ready: true }).state.restEndsAt).toBeNull()
+ })
+ it('has no current set once everything is ticked', () => {
+ const all = { ...A, entries: A.entries.map(e => ({ ...e, sets: e.sets.map(s => ({ ...s, done: true })) })) }
+ expect(L.buildLiveActivity(S(all)).state).toMatchObject({ cur: null, ahead: [], done: 4, total: 4 })
+ })
+ it('is null without a running workout, and for a saved one being edited', () => {
+ expect(L.buildLiveActivity(S(null))).toBeNull()
+ expect(L.buildLiveActivity(S({ ...A, editingWorkoutId: 'w0' }))).toBeNull()
+ })
+})
+
+describe('the Done taps', () => {
+ let state, calls
+ const A = () => ({ id: 'w1', cur: 0, entries: [entry('0025', [set(), set()]), entry('0043', [set()])] })
+ const getState = () => ({ S: state })
+ const ev = (id, over = {}) => ({ id, type: 'setDone', wid: 'w1', exId: '0025', entryIdx: 0, setIdx: 0, at: 1234, ...over })
+ let unbind = null
+ const bind = () => {
+ unbind = L.bindLiveActions({ setDone: (idx, i, opts) => { calls.push([idx, i, opts]); state.active.entries[idx].sets[i].done = true } })
+ }
+ beforeEach(() => { localStorage.clear(); L._resetLiveActivity(); state = S(A()); calls = [] })
+ afterEach(() => { unbind?.(); unbind = null })
+
+ it('ticks through the workout screen once per event, whatever the queue sends twice', () => {
+ bind()
+ expect(L.applyLiveEvents([ev('e1')], getState)).toEqual(['e1'])
+ expect(L.applyLiveEvents([ev('e1')], getState)).toEqual(['e1'])
+ expect(calls).toEqual([[0, 0, { at: 1234 }]])
+ })
+ it('finds the exercise when the list moved, and leaves a set already ticked alone', () => {
+ bind()
+ L.applyLiveEvents([ev('e1', { exId: '0043', entryIdx: 0 })], getState)
+ expect(calls).toEqual([[1, 0, { at: 1234 }]])
+ state.active.entries[0].sets[1].done = true
+ L.applyLiveEvents([ev('e2', { setIdx: 1 })], getState)
+ expect(calls).toHaveLength(1)
+ })
+ it('drops an event about another workout, or one that ended', () => {
+ bind()
+ expect(L.applyLiveEvents([ev('e1', { wid: 'old' })], getState)).toEqual(['e1'])
+ state.active = null
+ expect(L.applyLiveEvents([ev('e2')], getState)).toEqual(['e2'])
+ expect(calls).toEqual([])
+ })
+ it('keeps the events queued, in order, until the workout screen is there', () => {
+ expect(L.applyLiveEvents([ev('e1'), ev('e2', { setIdx: 1 })], getState)).toEqual([])
+ bind()
+ expect(L.applyLiveEvents([ev('e1'), ev('e2', { setIdx: 1 })], getState)).toEqual(['e1', 'e2'])
+ expect(calls.map(c => c[1])).toEqual([0, 1])
+ })
+ it('drains the native queue and acknowledges what it applied', async () => {
+ const acked = []
+ const queue = [ev('e1')]
+ L._setLivePluginForTest({ drain: async () => ({ events: queue }), ack: async ({ ids }) => { acked.push(...ids) } }, getState)
+ bind()
+ await L.drainLiveEvents()
+ expect(calls).toHaveLength(1)
+ expect(acked).toEqual(['e1'])
+ })
+})
+
+describe('startLiveActivitySync', () => {
+ let state, timer, storeSubs, uiSubs, calls
+ const useStore = { getState: () => ({ S: state }), subscribe: fn => { storeSubs.push(fn); return () => {} } }
+ const useUI = { getState: () => ({ timer }), subscribe: fn => { uiSubs.push(fn); return () => {} } }
+ const plugin = (supported = true) => ({
+ status: async () => ({ supported }),
+ update: async arg => { calls.push(['update', arg.wid, JSON.parse(arg.state)]) },
+ end: async () => { calls.push(['end']) },
+ drain: async () => ({ events: [] }),
+ ack: async () => {},
+ addListener: async () => ({ remove () {} }),
+ })
+ const active = () => ({ id: 'w1', name: 'Push', cur: 0, entries: [entry('0025', [set(), set()])] })
+ beforeEach(() => { vi.useFakeTimers(); localStorage.clear(); L._resetLiveActivity(); state = S(active()); timer = null; storeSubs = []; uiSubs = []; calls = [] })
+ afterEach(() => { vi.useRealTimers(); L._resetLiveActivity() })
+
+ it('shows the workout, updates it on a change, and ends it with the workout', async () => {
+ L._setLivePluginForTest(plugin())
+ const stop = await L.startLiveActivitySync({ useStore, useUI })
+ await vi.runAllTimersAsync()
+ expect(calls).toEqual([['update', 'w1', expect.objectContaining({ name: 'Push', done: 0, total: 2 })]])
+ // a rest starts: the end goes out once, not every second it counts
+ timer = { endsAt: 99000, total: 90, left: 90 }
+ uiSubs.forEach(fn => fn({ timer }, { timer: null }))
+ await vi.runAllTimersAsync()
+ const ticking = { ...timer, left: 89 }
+ uiSubs.forEach(fn => fn({ timer: ticking }, { timer }))
+ await vi.runAllTimersAsync()
+ expect(calls).toHaveLength(2)
+ expect(calls[1][2].restEndsAt).toBe(99000)
+ // the workout is finished
+ const prev = state; state = { ...state, active: null }
+ storeSubs.forEach(fn => fn({ S: state }, { S: prev }))
+ await vi.runAllTimersAsync()
+ expect(calls.at(-1)).toEqual(['end'])
+ stop()
+ })
+
+ it('sends nothing where iOS has no Live Activities, and nothing off the iPhone app', async () => {
+ L._setLivePluginForTest(plugin(false))
+ const stop = await L.startLiveActivitySync({ useStore, useUI })
+ await vi.runAllTimersAsync()
+ expect(calls).toEqual([])
+ stop()
+ L._resetLiveActivity()
+ h.platform = 'android'
+ const stop2 = await L.startLiveActivitySync({ useStore, useUI })
+ await vi.runAllTimersAsync()
+ expect(calls).toEqual([])
+ stop2()
+ h.platform = 'ios'
+ })
+})
diff --git a/frontend/src/lib/widgets.js b/frontend/src/lib/widgets.js
new file mode 100644
index 000000000..f583380fd
--- /dev/null
+++ b/frontend/src/lib/widgets.js
@@ -0,0 +1,165 @@
+// The iPhone app's Home Screen and Lock Screen widgets, the page's side (native:
+// ios/App/App/WidgetBridgePlugin.swift writes what this builds to the App Group, and the widget
+// extension in ios/App/OpenGymWidgets reads it).
+//
+// A widget runs without the app, so the page hands it a small snapshot whenever something it shows
+// changes: the plan for today and the coming week (so the widget can turn the page at midnight on
+// its own), this week's progress, the streak, the last PR, and a workout that is running. Every
+// word in it is already in the app's language, and the accent is the app's, so the widgets look
+// and talk like the app. Text only: no exercise animations or pictures (Gym visual licence).
+//
+// iPhone app only. Nothing here runs on the web or on Android.
+import { MOBILE, nativePlatform } from './mobile.js'
+import { EXIDX } from './exercises.js'
+import { exerciseNameFor, t, dateLocale } from './i18n.js'
+import { effectiveRoutines, streakWeeks, exLine, bestWeightForEntry } from './history.js'
+import { deriveSessionName } from './session-merge.js'
+import { queueOf, weekTally } from './queue.js'
+import { todayISO, isoOf, fmtNum, weekStartOf, startOfWeek } from './format.js'
+import { accentPair, accentValue } from './accent.js'
+import { speedUnitOf } from './speed.js'
+
+export const WIDGET_SNAPSHOT_VERSION = 1
+// Today and the week after it: enough for "next workout" to still be right a few days on.
+export const WIDGET_DAYS = 8
+// What the large widget lists of today's plan.
+export const WIDGET_EXERCISES_MAX = 8
+const WRITE_DEBOUNCE_MS = 1000
+
+const nameOfCfg = cfg => (EXIDX[cfg?.id] ? exerciseNameFor(EXIDX[cfg.id]) : String(cfg?.name || cfg?.n || cfg?.id || ''))
+const routineIdsOf = w => (Array.isArray(w?.routineIds) ? w.routineIds : w?.routineId ? [w.routineId] : [])
+const shift = (iso, days) => { const d = new Date(iso + 'T12:00:00'); d.setDate(d.getDate() + days); return isoOf(d) }
+
+// One day of the plan as the widget shows it. The exercises only for today: the other days are a
+// name and a count, which is all a widget has room for.
+function dayOf (S, iso, today) {
+ let routines = []
+ try { routines = effectiveRoutines(S, iso).filter(r => (r.ex || []).length) } catch { routines = [] }
+ const weekday = new Date(iso + 'T12:00:00').toLocaleDateString(dateLocale(), { weekday: 'long' })
+ if (!routines.length) return { iso, weekday, name: null, count: 0 }
+ const day = {
+ iso,
+ weekday,
+ name: deriveSessionName(routines.map(r => r.name || '')) || '',
+ count: routines.reduce((n, r) => n + (r.ex || []).length, 0),
+ }
+ if (iso === today) {
+ const unit = S.unit === 'lb' ? 'lb' : 'kg'
+ const speed = speedUnitOf(S)
+ day.exercises = routines.flatMap(r => r.ex || []).slice(0, WIDGET_EXERCISES_MAX).map(cfg => {
+ let line = ''
+ try { line = exLine(cfg, unit, speed) } catch { line = '' }
+ return { name: nameOfCfg(cfg), line }
+ })
+ // Logged already (as the Home screen's today row says it): every routine of the day covered
+ // by a workout from today. A coach-queue session is never covered that way.
+ const queueIds = queueOf(S)?.ids || []
+ const logged = (S.workouts || []).filter(w => w && w.d === today)
+ day.done = routines.every(r => !queueIds.includes(r.id) && logged.some(w => routineIdsOf(w).includes(r.id)))
+ }
+ return day
+}
+
+// The newest workout with a PR in it, and that lift's best weight there.
+function lastPrOf (S) {
+ const ws = (S.workouts || []).filter(w => w && Array.isArray(w.prs) && w.prs.length)
+ if (!ws.length) return null
+ const w = ws.reduce((a, b) => ((b.d || '') > (a.d || '') || ((b.d || '') === (a.d || '') && (b.end || 0) > (a.end || 0)) ? b : a))
+ const id = w.prs[0]
+ const entry = (w.entries || []).find(e => e && e.id === id)
+ const name = EXIDX[id] ? exerciseNameFor(EXIDX[id]) : String(entry?.target?.name || entry?.name || id)
+ let best = 0
+ try { best = entry ? bestWeightForEntry(entry) : 0 } catch { best = 0 }
+ const unit = S.unit === 'lb' ? 'lb' : 'kg'
+ return { name, value: best > 0 ? `${fmtNum(best)} ${unit}` : '', d: w.d || null }
+}
+
+function activeOf (S) {
+ const A = S.active
+ if (!A || !Array.isArray(A.entries) || A.editingWorkoutId) return null
+ let done = 0, total = 0
+ for (const e of A.entries) for (const s of e?.sets || []) { total++; if (s?.done) done++ }
+ return { id: A.id || null, name: A.name || '', start: typeof A.start === 'number' ? A.start : null, done, total }
+}
+
+/** Everything the widgets show, as plain JSON (the `today` argument pins the clock for tests). */
+export function buildWidgetSnapshot (S, { today = todayISO() } = {}) {
+ const st = { ...S, routines: S?.routines || [], week: S?.week || {}, dayPlan: S?.dayPlan || {}, workouts: S?.workouts || [] }
+ const days = []
+ for (let i = 0; i < WIDGET_DAYS; i++) days.push(dayOf(st, shift(today, i), today))
+ let week = { done: 0, planned: 0 }
+ try { week = weekTally(st, today) } catch { /* the widget shows no fraction then */ }
+ let streak = 0
+ try { streak = streakWeeks(st) } catch { streak = 0 }
+ const ws = weekStartOf(st)
+ const weekFrom = isoOf(startOfWeek(today, ws))
+ const pair = accentPair(accentValue(st))
+ return {
+ v: WIDGET_SNAPSHOT_VERSION,
+ today,
+ weekFrom,
+ weekUntil: shift(weekFrom, 7),
+ unit: st.unit === 'lb' ? 'lb' : 'kg',
+ accent: pair?.accent || '#30d158',
+ ink: pair?.ink || '#000000',
+ days,
+ week: { done: week.done || 0, planned: week.planned || 0 },
+ streak,
+ lastPR: lastPrOf(st),
+ active: activeOf(st),
+ labels: {
+ today: t('Today'),
+ restDay: t('Rest day'),
+ upNext: t('Up next'),
+ thisWeek: t('This week'),
+ weekStreak: t('Week streak'),
+ streak: t('{0} week streak', streak),
+ lastPR: t('Last PR'),
+ done: t('Done'),
+ running: t('Workout running'),
+ exercises: t('{0} exercises', days[0].count),
+ sets: t('Sets'),
+ start: t('Start workout'),
+ },
+ }
+}
+
+/* ---------- the native plugin ---------- */
+
+let pluginP = null
+// Inside an object: a Capacitor plugin proxy answers `then` (lib/rest-alert.js, the Coach hang #42).
+const widgetPlugin = () => pluginP || (pluginP = (async () => {
+ if (!MOBILE || (await nativePlatform()) !== 'ios') return null
+ const { registerPlugin } = await import('@capacitor/core')
+ return { WidgetBridge: registerPlugin('WidgetBridge') }
+})().catch(() => null))
+
+/**
+ * Started once by the app: writes the snapshot when what it shows changes (debounced, and only
+ * when it differs from the last one written), and again when the app comes back, which may be on
+ * another day. Resolves with the stop function.
+ */
+export async function startWidgetSync ({ useStore }) {
+ const p = await widgetPlugin()
+ if (!p) return () => {}
+ let last = null, tm = null
+ const write = async () => {
+ tm = null
+ try {
+ const json = JSON.stringify(buildWidgetSnapshot(useStore.getState().S))
+ if (json === last) return
+ await p.WidgetBridge.write({ json })
+ last = json
+ } catch { /* not now: the next change writes it */ }
+ }
+ const schedule = () => { clearTimeout(tm); tm = setTimeout(write, WRITE_DEBOUNCE_MS) }
+ const off = useStore.subscribe((s, prev) => { if (s.S !== prev.S) schedule() })
+ const onVisible = () => { if (document.visibilityState === 'visible') schedule() }
+ document.addEventListener('visibilitychange', onVisible)
+ write()
+ return () => { off(); clearTimeout(tm); document.removeEventListener('visibilitychange', onVisible) }
+}
+
+// Test seams.
+export function _setWidgetPluginForTest (plugin) { pluginP = Promise.resolve(plugin ? { WidgetBridge: plugin } : null) }
+export function _resetWidgets () { pluginP = null }
diff --git a/frontend/src/lib/widgets.test.js b/frontend/src/lib/widgets.test.js
new file mode 100644
index 000000000..9af0b3bce
--- /dev/null
+++ b/frontend/src/lib/widgets.test.js
@@ -0,0 +1,123 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+// The iPhone widgets' snapshot (lib/widgets.js): what the page hands the widget extension through
+// the App Group. The shape is what ios/App/OpenGymWidgets/WidgetSnapshot.swift decodes, so a field
+// renamed here is a widget gone blank there. Text only, nothing from the exercise media.
+const h = vi.hoisted(() => { vi.stubEnv('VITE_MOBILE', '1'); return { platform: 'ios' } })
+vi.mock('./mobile.js', () => ({ MOBILE: true, nativePlatform: async () => h.platform }))
+
+const { buildWidgetSnapshot, startWidgetSync, _setWidgetPluginForTest, _resetWidgets, WIDGET_DAYS } = await import('./widgets.js')
+
+// 2026-10-14 is a Wednesday (getDay 3).
+const TODAY = '2026-10-14'
+const push = { id: 'r1', name: 'Push', ex: [{ id: '0025', sets: 3, reps: 8, weight: 60 }, { id: 'c1', name: 'Cable thing', sets: 2, reps: 12 }] }
+const legs = { id: 'r2', name: 'Legs', ex: [{ id: '0043', sets: 5, reps: 5, weight: 100 }] }
+const S = (over = {}) => ({
+ unit: 'kg', accent: 'sky', routines: [push, legs], week: { 3: ['r1'], 5: ['r2'] }, dayPlan: {}, workouts: [], bodyweight: [], ...over,
+})
+
+describe('buildWidgetSnapshot', () => {
+ it('has the plan for today and the week after it, today with its exercises', () => {
+ const snap = buildWidgetSnapshot(S(), { today: TODAY })
+ expect(snap.v).toBe(1)
+ expect(snap.today).toBe(TODAY)
+ expect(snap.days).toHaveLength(WIDGET_DAYS)
+ expect(snap.days.map(d => d.iso)).toEqual(['2026-10-14', '2026-10-15', '2026-10-16', '2026-10-17', '2026-10-18', '2026-10-19', '2026-10-20', '2026-10-21'])
+ const [today, thu, fri] = snap.days
+ expect(today).toMatchObject({ name: 'Push', count: 2, done: false })
+ expect(today.exercises).toHaveLength(2)
+ expect(today.exercises[0].line).toMatch(/3 × 8 · 60 kg/)
+ expect(today.exercises[1].name).toBe('Cable thing')
+ expect(typeof today.weekday).toBe('string')
+ // A rest day is a day without a name; other days carry no exercise list.
+ expect(thu).toMatchObject({ name: null, count: 0 })
+ expect(fri).toMatchObject({ name: 'Legs', count: 1 })
+ expect(fri.exercises).toBeUndefined()
+ // the next week's Wednesday again
+ expect(snap.days[7].name).toBe('Push')
+ })
+
+ it('says today is done once a workout from today covers it', () => {
+ const w = { id: 'w1', d: TODAY, start: 1, end: 2, routineIds: ['r1'], entries: [] }
+ expect(buildWidgetSnapshot(S({ workouts: [w] }), { today: TODAY }).days[0].done).toBe(true)
+ const other = { ...w, routineIds: ['r2'] }
+ expect(buildWidgetSnapshot(S({ workouts: [other] }), { today: TODAY }).days[0].done).toBe(false)
+ })
+
+ it('counts the week, the streak and names the last PR with its best weight', () => {
+ const older = { id: 'w0', d: '2026-10-01', end: 1, prs: ['0043'], entries: [{ id: '0043', target: { mode: 'reps' }, sets: [{ w: 90, r: 5, done: true }] }] }
+ const newer = { id: 'w1', d: '2026-10-13', end: 5, prs: ['0025'], entries: [{ id: '0025', target: { mode: 'reps' }, sets: [{ w: 62.5, r: 8, done: true }, { w: 65, r: 6, done: true }] }] }
+ const snap = buildWidgetSnapshot(S({ workouts: [newer, older] }), { today: TODAY })
+ expect(snap.week).toEqual({ done: 1, planned: 2 })
+ expect(snap.weekFrom).toBe('2026-10-12')
+ expect(snap.weekUntil).toBe('2026-10-19')
+ expect(typeof snap.streak).toBe('number')
+ expect(snap.lastPR).toMatchObject({ value: '65 kg', d: '2026-10-13' })
+ expect(snap.lastPR.name).toBeTruthy()
+ expect(buildWidgetSnapshot(S(), { today: TODAY }).lastPR).toBeNull()
+ })
+
+ it('shows a running workout, but not a saved one being edited', () => {
+ const active = { id: 'a1', name: 'Push', start: 1000, entries: [{ id: '0025', sets: [{ done: true }, { done: false }, { done: false }] }] }
+ expect(buildWidgetSnapshot(S({ active }), { today: TODAY }).active).toEqual({ id: 'a1', name: 'Push', start: 1000, done: 1, total: 3 })
+ expect(buildWidgetSnapshot(S({ active: { ...active, editingWorkoutId: 'w9' } }), { today: TODAY }).active).toBeNull()
+ expect(buildWidgetSnapshot(S(), { today: TODAY }).active).toBeNull()
+ })
+
+ it('carries the accent and its words, and stands up to a thin state', () => {
+ const snap = buildWidgetSnapshot(S(), { today: TODAY })
+ expect(snap.accent).toBe('#0a84ff')
+ expect(snap.ink).toBe('#ffffff')
+ expect(buildWidgetSnapshot(S({ accent: 'custom', accentCustom: '#123456' }), { today: TODAY }).accent).toBe('#123456')
+ for (const k of ['today', 'restDay', 'upNext', 'thisWeek', 'weekStreak', 'streak', 'lastPR', 'done', 'running', 'exercises', 'sets', 'start']) {
+ expect(typeof snap.labels[k], k).toBe('string')
+ }
+ const thin = buildWidgetSnapshot({}, { today: TODAY })
+ expect(thin.days.every(d => d.name === null)).toBe(true)
+ expect(thin.week).toEqual({ done: 0, planned: 0 })
+ // plain JSON all the way down
+ expect(JSON.parse(JSON.stringify(snap))).toEqual(snap)
+ })
+})
+
+describe('startWidgetSync', () => {
+ let state, subs, writes
+ const useStore = {
+ getState: () => ({ S: state }),
+ subscribe: fn => { subs.push(fn); return () => {} },
+ }
+ beforeEach(() => {
+ vi.useFakeTimers()
+ state = S(); subs = []; writes = []
+ _setWidgetPluginForTest({ write: async ({ json }) => { writes.push(JSON.parse(json)) } })
+ })
+ afterEach(() => { vi.useRealTimers(); _resetWidgets() })
+
+ it('writes at start, then only when what the widgets show changed', async () => {
+ const stop = await startWidgetSync({ useStore })
+ await vi.runAllTimersAsync()
+ expect(writes).toHaveLength(1)
+ // a change to the state that leaves the snapshot as it was writes nothing
+ const prev = state; state = { ...state }
+ subs.forEach(fn => fn({ S: state }, { S: prev }))
+ await vi.runAllTimersAsync()
+ expect(writes).toHaveLength(1)
+ const before = state; state = { ...state, routines: [{ ...push, name: 'Push heavy' }, legs] }
+ subs.forEach(fn => fn({ S: state }, { S: before }))
+ await vi.runAllTimersAsync()
+ expect(writes).toHaveLength(2)
+ expect(writes[1].days.some(d => d.name === 'Push heavy')).toBe(true)
+ stop()
+ })
+
+ it('does nothing off the iPhone app', async () => {
+ _resetWidgets()
+ h.platform = 'android'
+ const stop = await startWidgetSync({ useStore })
+ await vi.runAllTimersAsync()
+ expect(writes).toEqual([])
+ stop()
+ h.platform = 'ios'
+ })
+})
diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx
index b684b1566..cadcca262 100644
--- a/frontend/src/views/Workout.jsx
+++ b/frontend/src/views/Workout.jsx
@@ -40,6 +40,7 @@ import { sessionNoProg, setSessionNoProg, setEntryNoProg, joinSessionNoProg } fr
import { glyphOf } from '../lib/glyphs.js'
import { markAllSetsDone, sessionHistory } from '../lib/backfill.js'
import { bestSetFor } from '../lib/exercise-history.js'
+import { bindLiveActions } from '../lib/live-activity.js'
import { isWarmupRow, isFailureSet, toggleFailure, isDropSet, isRestPauseSet, dropsOf, clustersOf, addDrop, addCluster, removeDropAt, removeClusterAt, setDropAt, setClusterAt, nextDropWeight, nextBurstReps, isSideSet, makeSideSet, setSideField, toggleSide, addSideDrop, removeSideDropAt, setSideDropAt, addSideCluster, removeSideClusterAt, setSideClusterAt, WEIGHT_ORIGIN_MANUAL } from '../lib/workout-model.js'
import { canMoveActiveWorkoutUnit, moveActiveWorkoutUnit, canMoveActiveWorkoutEntry, moveActiveWorkoutEntry } from '../lib/active-workout-order.js'
import { nextOpenSet, workoutKeyAction } from '../lib/workout-keys.js'
@@ -1753,6 +1754,20 @@ function ActiveWorkout() {
}
}
+ // The Lock Screen's Done (lib/live-activity.js) ticks its set through this same toggle, as if
+ // tapped here (rest timer, high-water mark, the end-of-workout sheet). The time is the tap's: the
+ // page may hear of it much later (lib/finish-workout.js sessionEnd reads the sets' times).
+ const liveToggleRef = useRef(toggle)
+ liveToggleRef.current = toggle
+ useEffect(() => bindLiveActions({
+ setDone: (idx, i, { at }) => {
+ const A = useStore.getState().S.active
+ if (!A || A.editingWorkoutId || A.entries?.[idx]?.sets?.[i]?.done) return
+ liveToggleRef.current(idx, i)
+ if (at) mutEntry(idx, en => { const set = en.sets[i]; if (set?.done) set.at = at })
+ },
+ }), [])
+
// After the finished exercise folded away (toggle, above): the new current one is the next thing
// to do, so if it now sits under the header or low on the screen with little more than its title
// showing, it glides up under the header. Where it is already in reach the page stays put. Run