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
Data safety: nothing the watch, the Live Activity or a set tick hands over can be lost on the way
Duarte Santosd92ce229253d
diff --git a/frontend/ios/App/App/WatchBridgePlugin.swift b/frontend/ios/App/App/WatchBridgePlugin.swiftindex 62797a158..0ca29ba40 100644--- a/frontend/ios/App/App/WatchBridgePlugin.swift+++ b/frontend/ios/App/App/WatchBridgePlugin.swift@@ -262,14 +262,17 @@ public class WatchBridgePlugin: CAPPlugin, CAPBridgedPlugin, WCSessionDelegate {let data = json.data(using: .utf8),let event = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],event["id"] is String else { return }- queue.async {+ // On disk before this returns: once it has, WatchConnectivity counts the transfer as+ // delivered, and an app woken in the background for it may be suspended right after. An+ // async write could then never run, and the watch would not send the set again.+ queue.sync {var events = self.readEvents()if !events.contains(where: { ($0["id"] as? String) == (event["id"] as? String) }) {events.append(event)self.writeEvents(events)}- DispatchQueue.main.async { self.notifyListeners("watchEvent", data: event) }}+ DispatchQueue.main.async { self.notifyListeners("watchEvent", data: event) }}/// The page asked for the status before the session was up (right after launch): it is told now.diff --git a/frontend/src/lib/live-activity.js b/frontend/src/lib/live-activity.jsindex 510dd7d68..0ddc8d8b2 100644--- a/frontend/src/lib/live-activity.js+++ b/frontend/src/lib/live-activity.js@@ -172,16 +172,23 @@ const livePlugin = () => pluginP || (pluginP = (async () => {let getStateRef = nulllet draining = null+// As in lib/watch-sync.js: nothing is applied, acknowledged or sent before the store has its copy+// back (boot's finishBoot), so a tap is never dropped against an empty, not yet restored state.+const storeReady = () => getStateRef?.()?.ready !== false-/** Takes the Done taps from the native queue, applies them, and acknowledges what is done. */+/**+ * Takes the Done taps from the native queue, applies them, and acknowledges what is done once the+ * change is on disk (the store's saveNow): until then the queue is the tap's only copy.+ */export function drainLiveEvents () {if (draining) return drainingdraining = (async () => {try {const p = await livePlugin()- if (!p || !getStateRef) return []+ if (!p || !getStateRef || !storeReady()) return []const { events = [] } = (await p.LiveActivity.drain()) || {}const done = applyLiveEvents(events, getStateRef)+ if (done.length) await getStateRef()?.saveNow?.()if (done.length) await p.LiveActivity.ack({ ids: done })return done} catch { return [] } finally { draining = null }@@ -210,6 +217,8 @@ export async function startLiveActivitySync ({ useStore, useUI }) {let last = null, tm = nullconst send = async () => {tm = null+ // An empty, not yet restored copy would end the activity of a workout that is still running.+ if (!storeReady()) returntry {const live = buildLiveActivity(useStore.getState().S, useUI.getState().timer)const json = live ? JSON.stringify(live) : ''@@ -220,7 +229,10 @@ export async function startLiveActivitySync ({ useStore, useUI }) {} 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 offStore = useStore.subscribe((s, prev) => {+ if (s.ready && !prev.ready) { drainLiveEvents(); schedule() }+ else 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) returndiff --git a/frontend/src/lib/live-activity.test.js b/frontend/src/lib/live-activity.test.jsindex b8692cc56..db870f0f1 100644--- a/frontend/src/lib/live-activity.test.js+++ b/frontend/src/lib/live-activity.test.js@@ -97,6 +97,18 @@ describe('the Done taps', () => {expect(L.applyLiveEvents([ev('e1'), ev('e2', { setIdx: 1 })], getState)).toEqual(['e1', 'e2'])expect(calls.map(c => c[1])).toEqual([0, 1])})+ it('applies nothing before the store has its copy back, and acknowledges only after the save', async () => {+ const order = []+ let ready = false+ const saveNow = async () => { order.push('saved') }+ L._setLivePluginForTest({ drain: async () => ({ events: [ev('e1')] }), ack: async ({ ids }) => { order.push('ack:' + ids) } }, () => ({ S: ready ? state : { active: null }, ready, saveNow }))+ unbind = L.bindLiveActions({ setDone: (idx, i) => { order.push('applied'); state.active.entries[idx].sets[i].done = true } })+ expect(await L.drainLiveEvents()).toEqual([])+ expect(order).toEqual([])+ ready = true+ expect(await L.drainLiveEvents()).toEqual(['e1'])+ expect(order).toEqual(['applied', 'saved', 'ack:e1'])+ })it('drains the native queue and acknowledges what it applied', async () => {const acked = []const queue = [ev('e1')]@@ -124,6 +136,20 @@ describe('startLiveActivitySync', () => {beforeEach(() => { vi.useFakeTimers(); localStorage.clear(); L._resetLiveActivity(); state = S(active()); timer = null; storeSubs = []; uiSubs = []; calls = [] })afterEach(() => { vi.useRealTimers(); L._resetLiveActivity() })+ it('at launch, an empty copy not restored yet does not end the running workout\'s activity', async () => {+ let ready = false+ const blank = { ...state, active: null }+ const store = { getState: () => ({ S: ready ? state : blank, ready }), subscribe: useStore.subscribe }+ L._setLivePluginForTest(plugin())+ const stop = await L.startLiveActivitySync({ useStore: store, useUI })+ await vi.runAllTimersAsync()+ expect(calls).toEqual([])+ ready = true+ storeSubs.forEach(fn => fn({ S: state, ready: true }, { S: blank, ready: false }))+ await vi.runAllTimersAsync()+ expect(calls).toEqual([['update', 'w1', expect.objectContaining({ name: 'Push' })]])+ stop()+ })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 })diff --git a/frontend/src/lib/mobile-state-file.test.js b/frontend/src/lib/mobile-state-file.test.jsnew file mode 100644index 000000000..6c8ff1cac--- /dev/null+++ b/frontend/src/lib/mobile-state-file.test.js@@ -0,0 +1,73 @@+// The phone's durable copy of the profile (lib/mobile.js nativeSave / nativeLoad): written whole to+// a second file and moved over the first, so a write cut short never leaves half a file where the+// last good copy was (data safety, owner 2026-10-14).+import { beforeEach, describe, expect, it, vi } from 'vitest'++const h = vi.hoisted(() => ({ files: new Map(), failRename: false, failWrite: new Set() }))+vi.mock('@capacitor/filesystem', () => ({+ Directory: { Data: 'DATA' },+ Encoding: { UTF8: 'utf8' },+ Filesystem: {+ readFile: async ({ path }) => {+ if (!h.files.has(path)) throw new Error('File does not exist')+ return { data: h.files.get(path) }+ },+ writeFile: async ({ path, data }) => {+ if (h.failWrite.has(path)) throw new Error('No space left on device')+ h.files.set(path, data)+ },+ rename: async ({ from, to }) => {+ if (h.failRename) throw new Error('interrupted')+ h.files.set(to, h.files.get(from))+ h.files.delete(from)+ },+ },+}))++let M+beforeEach(async () => {+ h.files.clear(); h.failRename = false; h.failWrite.clear()+ M = await import('./mobile.js')+})++describe('the state file', () => {+ it('lands under its own name, with nothing left beside it', async () => {+ await M.nativeSave({ _ts: 1, workouts: ['a'] })+ expect([...h.files.keys()]).toEqual(['opengym-state.json'])+ expect(await M.nativeLoad()).toEqual({ _ts: 1, workouts: ['a'] })+ })++ it('a move cut short keeps both copies, and the later one is read', async () => {+ await M.nativeSave({ _ts: 1, workouts: ['a'] })+ h.failRename = true+ h.failWrite.add('opengym-state.json') // and the plain write after it fails too+ await M.nativeSave({ _ts: 2, workouts: ['a', 'b'] })+ expect(JSON.parse(h.files.get('opengym-state.json'))._ts).toBe(1)+ expect(await M.nativeLoad()).toEqual({ _ts: 2, workouts: ['a', 'b'] })+ })++ it('a half-written main file is not the end: the other copy is read', async () => {+ await M.nativeSave({ _ts: 1, workouts: ['a'] })+ h.files.set('opengym-state.next.json', JSON.stringify({ _ts: 1, workouts: ['a'] }))+ h.files.set('opengym-state.json', '{"_ts":2,"workouts":["a",')+ expect(await M.nativeLoad()).toEqual({ _ts: 1, workouts: ['a'] })+ })++ it('an older leftover never wins over the main file', async () => {+ h.files.set('opengym-state.next.json', JSON.stringify({ _ts: 1 }))+ await M.nativeSave({ _ts: 5 })+ h.files.set('opengym-state.next.json', JSON.stringify({ _ts: 1 }))+ expect((await M.nativeLoad())._ts).toBe(5)+ })++ it('without a move (an older plugin), it writes the file itself as before', async () => {+ const { Filesystem } = await import('@capacitor/filesystem')+ const rename = Filesystem.rename+ delete Filesystem.rename+ try {+ await M.nativeSave({ _ts: 3 })+ expect([...h.files.keys()]).toEqual(['opengym-state.json'])+ expect((await M.nativeLoad())._ts).toBe(3)+ } finally { Filesystem.rename = rename }+ })+})diff --git a/frontend/src/lib/mobile.js b/frontend/src/lib/mobile.jsindex 4b08b8883..c77b93f0f 100644--- a/frontend/src/lib/mobile.js+++ b/frontend/src/lib/mobile.js@@ -48,18 +48,37 @@ export async function nativePlatform() {const FILE = 'opengym-state.json'+// Written whole to a second file first and then moved over the first, so a write cut short (the+// app killed mid-write, the battery gone) never leaves a half file where the last good copy was.+// A move that did not finish leaves the new copy under FILE_NEW: whichever of the two parses and+// is the later one (`_ts`) is the copy.+const FILE_NEW = 'opengym-state.next.json'+export async function nativeLoad() {try {const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')- const r = await Filesystem.readFile({ path: FILE, directory: Directory.Data, encoding: Encoding.UTF8 })- return JSON.parse(r.data)+ const read = async path => {+ try { return JSON.parse((await Filesystem.readFile({ path, directory: Directory.Data, encoding: Encoding.UTF8 })).data) } catch { return null }+ }+ const main = await read(FILE)+ const next = typeof Filesystem.rename === 'function' ? await read(FILE_NEW) : null+ if (next && typeof next === 'object' && (!main || (Number(next._ts) || 0) > (Number(main._ts) || 0))) return next+ return main} catch (e) { return null } // first launch, or unreadable — localStorage copy takes over}export async function nativeSave(state) {try {const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')- await Filesystem.writeFile({ path: FILE, directory: Directory.Data, data: JSON.stringify(state), encoding: Encoding.UTF8 })+ const data = JSON.stringify(state)+ if (typeof Filesystem.rename === 'function') {+ try {+ await Filesystem.writeFile({ path: FILE_NEW, directory: Directory.Data, data, encoding: Encoding.UTF8 })+ await Filesystem.rename({ from: FILE_NEW, to: FILE, directory: Directory.Data, toDirectory: Directory.Data })+ return+ } catch { /* the plain write below */ }+ }+ await Filesystem.writeFile({ path: FILE, directory: Directory.Data, data, encoding: Encoding.UTF8 })} catch (e) { /* keep the localStorage copy */ }}diff --git a/frontend/src/lib/watch-sync.js b/frontend/src/lib/watch-sync.jsindex b713a4333..8d4a9ce15 100644--- a/frontend/src/lib/watch-sync.js+++ b/frontend/src/lib/watch-sync.js@@ -291,16 +291,25 @@ const watchPlugin = () => pluginP || (pluginP = (async () => {let getStateRef = nulllet draining = null+// The store has its copy back (boot's finishBoot: the file mirror, the server's pull). Before that,+// S can be the empty copy a WebView whose storage was evicted starts with: a tick would find no+// workout, count as meaningless and be acknowledged away, and a "start" would begin a new session+// over it. A store without the flag (a test's) counts as ready.+const storeReady = () => getStateRef?.()?.ready !== false-/** Takes what the watch sent from the native queue, applies it, and acknowledges what is done. */+/**+ * Takes what the watch sent from the native queue, applies it, and acknowledges what is done, but+ * only once the change is on disk (the store's saveNow): the queue is the event's last copy.+ */export function drainWatchEvents () {if (draining) return drainingdraining = (async () => {try {const p = await watchPlugin()- if (!p || !getStateRef) return []+ if (!p || !getStateRef || !storeReady()) return []const { events = [] } = (await p.WatchBridge.drain()) || {}const done = applyEvents(events, getStateRef)+ if (done.length) await getStateRef()?.saveNow?.()if (done.length) await p.WatchBridge.ack({ ids: done })return done} catch { return [] } finally { draining = null }@@ -399,7 +408,8 @@ export async function startWatchSync ({ useStore, useUI }) {} catch { /* no Apple Health here: the watch measures nothing */ }const send = async () => {tm = null- if (!linked) return+ // Not before the store has its copy: an empty one would tell the watch its workout is over.+ if (!linked || !storeReady()) returntry {const S = useStore.getState().Sconst prefs = readWatchPrefs()@@ -428,6 +438,8 @@ export async function startWatchSync ({ useStore, useUI }) {}const schedule = () => { if (!linked) return; clearTimeout(tm); tm = setTimeout(send, SEND_DEBOUNCE_MS) }const offStore = useStore.subscribe((s, prev) => {+ // Boot done: what the watch sent meanwhile is applied now, and the watch hears the real state.+ if (s.ready && !prev.ready) { drainWatchEvents(); schedule() }if (s.S === prev.S) returnschedule()// A workout started on the phone: the watch app opens with it (HealthKit's startWatchApp).diff --git a/frontend/src/lib/watch-sync.open.test.js b/frontend/src/lib/watch-sync.open.test.jsindex 32c845c44..3eed2bda7 100644--- a/frontend/src/lib/watch-sync.open.test.js+++ b/frontend/src/lib/watch-sync.open.test.js@@ -105,6 +105,27 @@ describe('startWatchSync', () => {stop2()})+ // Data safety: an empty copy at launch (storage evicted, the file mirror not read back yet) must+ // not tell the watch its workout is over, nor drain its queue against nothing.+ it('sends nothing and drains nothing before the store has its copy back', async () => {+ vi.useFakeTimers()+ try {+ const b = bridge()+ _setWatchPluginForTest(b)+ const st = store({ S: S0, ready: false })+ _setWatchPluginForTest(b, () => st.getState())+ const stop = await startWatchSync({ useStore: st, useUI: ui })+ await vi.runAllTimersAsync()+ expect(b.sendSnapshot).not.toHaveBeenCalled()+ expect(b.drain).not.toHaveBeenCalled()+ st.setState({ S: { ...S0, active: live({ start: Date.now() - 3600e3 }) }, ready: true })+ await vi.runAllTimersAsync()+ expect(b.drain).toHaveBeenCalled()+ expect(JSON.parse(b.sendSnapshot.mock.calls.at(-1)[0].json).active.id).toBe('w-9')+ stop()+ } finally { vi.useRealTimers() }+ })+it('tells the watch the phone\'s Apple Health switch, and again when it changes', async () => {vi.useFakeTimers()try {diff --git a/frontend/src/lib/watch-sync.test.js b/frontend/src/lib/watch-sync.test.jsindex 6253f6d40..bfe469884 100644--- a/frontend/src/lib/watch-sync.test.js+++ b/frontend/src/lib/watch-sync.test.js@@ -101,6 +101,32 @@ describe('the native queue', () => {expect(p.ack).not.toHaveBeenCalled()})+ // Data safety (owner, 10-14): at launch S can be the empty copy of an evicted WebView until boot+ // has the file mirror back. A tick drained then found no workout and was acknowledged away.+ it('waits for the store to have its copy back before it applies or acknowledges anything', async () => {+ let store = { S: { unit: 'kg', workouts: [], active: null }, ready: false }+ const p = plugin([{ id: 'x1', type: 'setDone', wid: 'w-1', exId: '0025', entryIdx: 0, setIdx: 1, w: 60, r: 8 }])+ _setWatchPluginForTest(p, () => store)+ const setDone = vi.fn()+ bindWatchActions({ setDone })+ expect(await drainWatchEvents()).toEqual([])+ expect(p.drain).not.toHaveBeenCalled()+ expect(p.ack).not.toHaveBeenCalled()+ store = { S: state(), ready: true }+ expect(await drainWatchEvents()).toEqual(['x1'])+ expect(setDone).toHaveBeenCalledTimes(1)+ })++ it('acknowledges only once the change is saved: the queue is its last copy until then', async () => {+ const order = []+ const p = { drain: async () => ({ events: [{ id: 'x1', type: 'setDone', wid: 'w-1', exId: '0025', entryIdx: 0, setIdx: 1 }] }), ack: async () => { order.push('ack') } }+ const saveNow = vi.fn(async () => { await new Promise(r => setTimeout(r, 5)); order.push('saved') })+ _setWatchPluginForTest(p, () => ({ S: state(), ready: true, saveNow }))+ bindWatchActions({ setDone: () => order.push('applied') })+ await drainWatchEvents()+ expect(order).toEqual(['applied', 'saved', 'ack'])+ })+it('off the iPhone app there is no plugin and nothing happens', async () => {_setWatchPluginForTest(null, () => ({ S: state() }))bindWatchActions({ setDone: vi.fn() })diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.jsindex 20d194143..ac85ab9f3 100644--- a/frontend/src/locales/ar.js+++ b/frontend/src/locales/ar.js@@ -2449,4 +2449,7 @@ export default {'Days per week': 'أيام في الأسبوع','Hours': 'الساعات','h': 'س',+ // --- import with no account: workouts on this device ---+ 'This device has 1 workout that is not in this backup. Replacing deletes it.': 'على هذا الجهاز تمرين واحد ليس في هذه النسخة الاحتياطية. الاستبدال يحذفه.',+ 'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'على هذا الجهاز {0} تمارين ليست في هذه النسخة الاحتياطية. الاستبدال يحذفها.',}diff --git a/frontend/src/locales/bn.js b/frontend/src/locales/bn.jsindex 5ef422188..3174d9005 100644--- a/frontend/src/locales/bn.js+++ b/frontend/src/locales/bn.js@@ -2473,4 +2473,7 @@ export default {'Days per week': 'সপ্তাহে কত দিন','Hours': 'ঘণ্টা','h': 'ঘ.',+ // --- import with no account: workouts on this device ---+ 'This device has 1 workout that is not in this backup. Replacing deletes it.': 'এই ডিভাইসে ১টি ওয়ার্কআউট আছে যা এই ব্যাকআপে নেই। প্রতিস্থাপন করলে এটি মুছে যাবে।',+ 'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'এই ডিভাইসে {0}টি ওয়ার্কআউট আছে যা এই ব্যাকআপে নেই। প্রতিস্থাপন করলে এগুলো মুছে যাবে।',}diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex 8a5cda2e5..0825ced5a 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -2414,4 +2414,7 @@ export default {'Days per week': 'Tage pro Woche','Hours': 'Stunden','h': 'h',+ // --- import with no account: workouts on this device ---+ 'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Auf diesem Gerät ist 1 Training, das nicht in diesem Backup ist. Ersetzen löscht es.',+ 'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Auf diesem Gerät sind {0} Trainings, die nicht in diesem Backup sind. Ersetzen löscht sie.',}diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.jsindex 7df683a40..e2375ca24 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -2394,4 +2394,7 @@ export default {'Days per week': 'Días por semana','Hours': 'Horas','h': 'h',+ // --- import with no account: workouts on this device ---+ 'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Este dispositivo tiene 1 entrenamiento que no está en esta copia. Reemplazar lo elimina.',+ 'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Este dispositivo tiene {0} entrenamientos que no están en esta copia. Reemplazar los elimina.',}diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.jsindex 19d0252c4..c188a974e 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -2394,4 +2394,7 @@ export default {'Days per week': 'Jours par semaine','Hours': 'Heures','h': 'h',+ // --- import with no account: workouts on this device ---+ 'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Cet appareil a 1 séance absente de cette sauvegarde. Remplacer la supprime.',+ 'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Cet appareil a {0} séances absentes de cette sauvegarde. Remplacer les supprime.',}diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.jsindex f9838e1d2..ea96d1e23 100644--- a/frontend/src/locales/hi.js+++ b/frontend/src/locales/hi.js@@ -2394,4 +2394,7 @@ export default {'Days per week': 'हफ़्ते में दिन','Hours': 'घंटे','h': 'घं.',+ // --- import with no account: workouts on this device ---+ 'This device has 1 workout that is not in this backup. Replacing deletes it.': 'इस डिवाइस पर 1 वर्कआउट है जो इस बैकअप में नहीं है। बदलने से यह मिट जाएगा।',+ 'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'इस डिवाइस पर {0} वर्कआउट हैं जो इस बैकअप में नहीं हैं। बदलने से ये मिट जाएँगे।',}diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.jsindex 1278c018e..d24678d6a 100644--- a/frontend/src/locales/hu.js+++ b/frontend/src/locales/hu.js@@ -2397,4 +2397,7 @@ export default {'Days per week': 'Nap hetente','Hours': 'Órák','h': 'ó',+ // --- import with no account: workouts on this device ---+ 'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Ezen az eszközön 1 edzés van, amely nincs ebben a mentésben. A csere törli.',+ 'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Ezen az eszközön {0} edzés van, amely nincs ebben a mentésben. A csere törli őket.',}diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.jsindex a6c3469a2..8783df938 100644--- a/frontend/src/locales/it.js+++ b/frontend/src/locales/it.js@@ -2394,4 +2394,7 @@ export default {'Days per week': 'Giorni a settimana','Hours': 'Ore','h': 'h',+ // --- import with no account: workouts on this device ---+ 'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Su questo dispositivo c’è 1 allenamento che non è in questo backup. Sostituire lo elimina.',+ 'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Su questo dispositivo ci sono {0} allenamenti che non sono in questo backup. Sostituire li elimina.',}diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.jsindex 7c5fc9a45..de1aae956 100644--- a/frontend/src/locales/ko.js+++ b/frontend/src/locales/ko.js@@ -2394,4 +2394,7 @@ export default {'Days per week': '주당 일수','Hours': '시간','h': '시간',+ // --- import with no account: workouts on this device ---+ 'This device has 1 workout that is not in this backup. Replacing deletes it.': '이 기기에 이 백업에 없는 운동이 1개 있습니다. 바꾸면 삭제됩니다.',+ 'This device has {0} workouts that are not in this backup. Replacing deletes them.': '이 기기에 이 백업에 없는 운동이 {0}개 있습니다. 바꾸면 삭제됩니다.',}diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.jsindex 9e50944eb..e901b1a84 100644--- a/frontend/src/locales/pl.js+++ b/frontend/src/locales/pl.js@@ -2394,4 +2394,7 @@ export default {'Days per week': 'Dni w tygodniu','Hours': 'Godziny','h': 'godz.',+ // --- import with no account: workouts on this device ---+ 'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Na tym urządzeniu jest 1 trening, którego nie ma w tej kopii. Zastąpienie danych go usunie.',+ 'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Na tym urządzeniu są treningi, których nie ma w tej kopii ({0}). Zastąpienie danych je usunie.',}diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.jsindex fbe909f49..ec4edee75 100644--- a/frontend/src/locales/pt-BR.js+++ b/frontend/src/locales/pt-BR.js@@ -1515,6 +1515,9 @@ export const PT_BR_OVERRIDES = {'Switch it off anytime in Settings': 'Desligue quando quiser nas Configurações','You can change it anytime in Settings.': 'Você pode mudar isso quando quiser nas Configurações.','Workout running': 'Treino em andamento',+ // --- import with no account: workouts on this device ---+ 'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Este dispositivo tem 1 treino que não está neste backup. Substituir exclui esse treino.',+ 'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Este dispositivo tem {0} treinos que não estão neste backup. Substituir exclui esses treinos.',}export default { ...pt, ...PT_BR_OVERRIDES }diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.jsindex 99d22e147..566590171 100644--- a/frontend/src/locales/pt.js+++ b/frontend/src/locales/pt.js@@ -2394,4 +2394,7 @@ export default {'Days per week': 'Dias por semana','Hours': 'Horas','h': 'h',+ // --- import with no account: workouts on this device ---+ 'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Este dispositivo tem 1 treino que não está nesta cópia. Substituir elimina-o.',+ 'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Este dispositivo tem {0} treinos que não estão nesta cópia. Substituir elimina-os.',}diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.jsindex d46a39c71..d81a4313b 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -2398,4 +2398,7 @@ export default {'Days per week': 'Дней в неделю','Hours': 'Часы','h': 'ч',+ // --- import with no account: workouts on this device ---+ 'This device has 1 workout that is not in this backup. Replacing deletes it.': 'На этом устройстве есть 1 тренировка, которой нет в этой копии. Замена её удалит.',+ 'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'На этом устройстве есть тренировки, которых нет в этой копии ({0}). Замена их удалит.',}diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.jsindex b71a612e6..57accd94b 100644--- a/frontend/src/locales/th.js+++ b/frontend/src/locales/th.js@@ -2405,4 +2405,7 @@ export default {'Days per week': 'วันต่อสัปดาห์','Hours': 'ชั่วโมง','h': 'ชม.',+ // --- import with no account: workouts on this device ---+ 'This device has 1 workout that is not in this backup. Replacing deletes it.': 'อุปกรณ์นี้มีการออกกำลังกาย 1 รายการที่ไม่อยู่ในข้อมูลสำรองนี้ การแทนที่จะลบรายการนั้น',+ 'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'อุปกรณ์นี้มีการออกกำลังกาย {0} รายการที่ไม่อยู่ในข้อมูลสำรองนี้ การแทนที่จะลบรายการเหล่านั้น',}diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.jsindex e7985267c..3f4ee6f12 100644--- a/frontend/src/locales/tr.js+++ b/frontend/src/locales/tr.js@@ -2394,4 +2394,7 @@ export default {'Days per week': 'Haftada kaç gün','Hours': 'Saat','h': 'sa',+ // --- import with no account: workouts on this device ---+ 'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Bu cihazda bu yedekte olmayan 1 antrenman var. Değiştirmek onu siler.',+ 'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Bu cihazda bu yedekte olmayan {0} antrenman var. Değiştirmek onları siler.',}diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.jsindex 06e75de87..63e29f256 100644--- a/frontend/src/locales/uk.js+++ b/frontend/src/locales/uk.js@@ -2391,4 +2391,7 @@ export default {'Days per week': 'Днів на тиждень','Hours': 'Години','h': 'год',+ // --- import with no account: workouts on this device ---+ 'This device has 1 workout that is not in this backup. Replacing deletes it.': 'На цьому пристрої є 1 тренування, якого немає в цій копії. Заміна його видалить.',+ 'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'На цьому пристрої є тренування, яких немає в цій копії ({0}). Заміна їх видалить.',}diff --git a/frontend/src/locales/zh-TW.js b/frontend/src/locales/zh-TW.jsindex 66b40fab2..77b5f8f38 100644--- a/frontend/src/locales/zh-TW.js+++ b/frontend/src/locales/zh-TW.js@@ -2387,4 +2387,7 @@ export default {'Days per week': '每週天數','Hours': '小時','h': '小時',+ // --- import with no account: workouts on this device ---+ 'This device has 1 workout that is not in this backup. Replacing deletes it.': '此裝置上有 1 筆訓練紀錄不在此備份中。覆蓋將會刪除它。',+ 'This device has {0} workouts that are not in this backup. Replacing deletes them.': '此裝置上有 {0} 筆訓練紀錄不在此備份中。覆蓋將會將其全數刪除。',}diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.jsindex 64d7ab289..075b406a8 100644--- a/frontend/src/locales/zh.js+++ b/frontend/src/locales/zh.js@@ -2394,4 +2394,7 @@ export default {'Days per week': '每周天数','Hours': '小时','h': '小时',+ // --- import with no account: workouts on this device ---+ 'This device has 1 workout that is not in this backup. Replacing deletes it.': '此设备上有 1 次训练不在此备份中。替换会删除它。',+ 'This device has {0} workouts that are not in this backup. Replacing deletes them.': '此设备上有 {0} 次训练不在此备份中。替换会删除它们。',}diff --git a/frontend/src/store/useStore.import-check.test.jsx b/frontend/src/store/useStore.import-check.test.jsxindex 21245355f..a8b4adcb5 100644--- a/frontend/src/store/useStore.import-check.test.jsx+++ b/frontend/src/store/useStore.import-check.test.jsx@@ -128,3 +128,33 @@ describe('a backup imported while a workout is running', () => {expect(useStore.getState().S.active).toEqual(running)})})++// Data safety (owner, 10-14): without an account this copy is the only one. A workout logged+// since the backup was made is asked about, and "Merge them in" keeps it; nothing is sent anywhere.+describe('importing a backup with no account (local mode, a guest)', () => {+ const local = () => useStore.setState({ S: { ...clone(DEF), _ts: 200, workouts: [workout('w1'), workout('since', '2026-09-28')] }, user: null, ready: true })++ it('names the workouts on this device that the backup lacks, without asking a server', async () => {+ local()+ const c = await useStore.getState().importConflict(BACKUP)+ expect(c).toMatchObject({ workouts: 1, device: true })+ expect(api).not.toHaveBeenCalled()+ })++ it('"Merge them in" keeps the backup\'s settings and every workout of both', async () => {+ local()+ const c = await useStore.getState().importConflict(BACKUP)+ useStore.getState().importBackup(BACKUP, { mergeWith: c })+ const S = useStore.getState().S+ expect(ids(S.workouts).sort()).toEqual(['since', 'w1', 'w2'])+ expect(S.restSec).toBe(120)+ expect(api).not.toHaveBeenCalled()+ })++ it('"Replace anyway" still replaces', async () => {+ local()+ await useStore.getState().importConflict(BACKUP)+ useStore.getState().importBackup(BACKUP)+ expect(ids(useStore.getState().S.workouts)).toEqual(['w1', 'w2'])+ })+})diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex 81d07cd49..93144e664 100644--- a/frontend/src/store/useStore.js+++ b/frontend/src/store/useStore.js@@ -604,11 +604,16 @@ export const useStore = create((set, get) => {}meta.set(S, { base, owed: owed || !saved || (!!joined && storedOwed()) })if (!saved) saveOwed(true)+ // The running workout changed (a set ticked, a workout started or finished): on a phone it goes+ // to the file at once rather than after the usual wait. localStorage alone is not enough there:+ // the WebView writes it to disk on its own schedule, and an app killed within that moment (or+ // iOS ending it in the background before the page's timers run again) lost the last set.+ const workoutMoved = MOBILE && JSON.stringify(get()?.S?.active ?? null) !== JSON.stringify(S.active ?? null)set({ S })// A copy that replaces the last one wholesale and keeps an older stamp — adopted from the// server — goes to the file at once. Until it does, the file holds the copy it replaced,// which looks newer, and a start in between would take that one back (restoreFromMirror).- if (MOBILE) nativePersist(!stamp)+ if (MOBILE) nativePersist(!stamp || workoutMoved)if (push && get().user) {// Before boot has pulled, the copy in hand may be older than the server's: a push now// would carry it with a stale (or no) baseRev. It waits for finishBoot.@@ -782,6 +787,9 @@ export const useStore = create((set, get) => {}document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') flush() })window.addEventListener('pagehide', flush) // Safari kills the home-screen app without a visibilitychange at times+ // The phone app: Capacitor's own "going to the background" too, in case the WebView's+ // visibilitychange comes late or not at all before iOS suspends the page.+ document.addEventListener('pause', flush)// The owner check in setUser only runs in the tab that signs in. Another tab of the same// browser still holding the previous profile, or a guest's copy, would keep writing it over the@@ -1325,6 +1333,13 @@ export const useStore = create((set, get) => {// Mutate a draft of S via producer fn, then persist + schedule sync. Every routine the change// touched carries the time of it, for a conflict to keep the version edited last.+ // The copy as it is now, on disk: the file mirror on a phone (written at once, not after the+ // usual wait), localStorage everywhere (persist writes it on every change). What hands a change+ // over from somewhere that keeps its own copy until told (the watch's and the Live Activity's+ // queues) waits for this before it lets go of it.+ saveNow() {+ return MOBILE ? nativePersist(true) : Promise.resolve()+ },update(mut, push = true) {const prev = get().Sconst S = clone(prev)@@ -1404,7 +1419,14 @@ export const useStore = create((set, get) => {// them in instead (importBackup). null when there are none, when nobody is signed in, or when// the server cannot be asked — the replace then goes as it always has.async importConflict(backup) {- if (!get().user) return null+ // No account (a phone in local mode, a guest): this copy is the only one there is, so the+ // workouts it holds that the backup lacks are asked about the same way, never just replaced.+ if (!get().user) {+ const key = w => entryKey('workouts', w)+ const inBackup = new Set((Array.isArray(backup?.workouts) ? backup.workouts : []).filter(Boolean).map(key))+ const here = (get().S.workouts || []).filter(w => w && !inBackup.has(key(w))).length+ return here ? { workouts: here, state: get().S, rev: null, device: true } : null+ }let restry { res = await api('/api/data') } catch { return null }const state = res?.state@@ -1441,6 +1463,15 @@ export const useStore = create((set, get) => {// so the import keeps it (in the backup's unit). Only with none running does a backup taken// mid-workout bring its own session back. Both the replace and "Merge them in" dropped it.const running = carryActive(cur, next) || next.active || null+ // No account: "Merge them in" joins this copy's own entries into the backup's.+ if (mergeWith?.device && !uid) {+ const merged = keepReset(cur, Object.assign(clone(DEF), mergeStates(next, cur, { prefer: 'a' })))+ stampRestore(merged, [cur, next], now)+ merged._ts = now+ merged.active = carryActive({ unit: next.unit, active: running }, merged)+ persist(merged, false)+ return+ }if (!mergeWith?.state || !uid) {stampRestore(next, [cur, server], now)// …and like a reset of what it replaces: an unsent change of another device from before itdiff --git a/frontend/src/store/useStore.mobile-durable.test.jsx b/frontend/src/store/useStore.mobile-durable.test.jsxnew file mode 100644index 000000000..69f164c24--- /dev/null+++ b/frontend/src/store/useStore.mobile-durable.test.jsx@@ -0,0 +1,122 @@+// @vitest-environment happy-dom++/* Data safety on the phone (owner, 2026-10-14: "make sure data is never ever lost"). A phone in+ local mode has no server: the file mirror in the app's data directory is the copy that survives+ a WebView whose storage iOS evicted, or localStorage the WebView had not written to disk yet when+ the app was killed. Real modules: store/useStore.js, lib/mobile.js. Mocked: the Capacitor+ plugins, with an in-memory Directory.Data. */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const h = vi.hoisted(() => {+ vi.stubEnv('VITE_MOBILE', '1')+ return { files: new Map() }+})+vi.mock('@capacitor/filesystem', () => ({+ Directory: { Data: 'DATA', Documents: 'DOCUMENTS', Cache: 'CACHE' },+ Encoding: { UTF8: 'utf8' },+ Filesystem: {+ readFile: async ({ path, directory }) => {+ const k = directory + '/' + path+ if (!h.files.has(k)) throw new Error('File does not exist')+ return { data: h.files.get(k) }+ },+ writeFile: async ({ path, directory, data }) => { h.files.set(directory + '/' + path, data); return { uri: 'file://' + path } },+ rename: async ({ from, to, directory }) => { h.files.set(directory + '/' + to, h.files.get(directory + '/' + from)); h.files.delete(directory + '/' + from) },+ },+}))+vi.mock('@capacitor/local-notifications', () => ({+ LocalNotifications: { cancel: async () => {}, checkPermissions: async () => ({ display: 'granted' }), requestPermissions: async () => ({ display: 'granted' }), schedule: async () => {} },+}))+vi.mock('@capacitor/app', () => ({ App: { addListener: () => ({ remove() {} }) } }))+vi.mock('@capacitor/core', () => ({ Capacitor: { getPlatform: () => 'ios', isNativePlatform: () => true }, registerPlugin: () => ({}) }))+vi.mock('./useUI.js', () => ({ useUI: { getState: () => ({ toast: () => {} }) } }))++const readFile = name => { const v = h.files.get('DATA/' + name); return v == null ? null : JSON.parse(v) }+const tick = () => new Promise(r => setTimeout(r, 20))+const workout = id => ({ id, d: '2026-10-10', start: 1, end: 2, entries: [] })++let stores = []+async function freshStore() {+ vi.resetModules()+ const { useStore } = await import('./useStore.js')+ stores.push(useStore)+ return useStore+}+// A phone in local mode with a history and a workout running, in localStorage and in the file.+async function localPhone() {+ const { DEF } = await import('./useStore.js')+ const S = { ...JSON.parse(JSON.stringify(DEF)), _ts: 5000, workouts: [workout('w1'), workout('w2')],+ active: { id: 'run', d: '2026-10-14', start: 4000, cur: 0, entries: [{ id: '0025', target: { mode: 'reps' }, sets: [{ w: 60, r: 8, done: false }, { w: 60, r: 8, done: false }] }] } }+ h.files.clear()+ localStorage.clear()+ h.files.set('DATA/opengym-remote.json', JSON.stringify({ mode: 'local' }))+ h.files.set('DATA/opengym-state.json', JSON.stringify(S))+ localStorage.setItem('gym_state_v1', JSON.stringify(S))+ localStorage.setItem('gym_guest', '1')+ return S+}++afterEach(async () => {+ window.dispatchEvent(new Event('pagehide'))+ await tick()+ for (const s of stores) s.setState({ user: null, ready: false })+ stores = []+ localStorage.clear()+})++describe('a phone with no server', () => {+ beforeEach(() => { h.files.clear() })++ it('a ticked set is in the file at once, not after the usual wait', async () => {+ await localPhone()+ const useStore = await freshStore()+ await useStore.getState().boot()+ useStore.getState().update(s => { s.active.entries[0].sets[0].done = true })+ await tick() // far less than the 800 ms of other changes+ expect(readFile('opengym-state.json').active.entries[0].sets.map(x => x.done)).toEqual([true, false])+ expect(h.files.has('DATA/opengym-state.next.json')).toBe(false)+ })++ it('a finished workout is in the file at once too', async () => {+ await localPhone()+ const useStore = await freshStore()+ await useStore.getState().boot()+ useStore.getState().update(s => { s.workouts.push({ ...s.active, end: 9000 }); s.active = null })+ await tick()+ const file = readFile('opengym-state.json')+ expect(file.active).toBeNull()+ expect(file.workouts.map(w => w.id)).toEqual(['w1', 'w2', 'run'])+ })++ it('storage evicted: the file brings everything back, and the store says ready only then', async () => {+ await localPhone()+ localStorage.clear()+ const useStore = await freshStore()+ expect(useStore.getState().ready).toBe(false)+ expect(useStore.getState().S.workouts).toEqual([])+ await useStore.getState().boot()+ expect(useStore.getState().ready).toBe(true)+ expect(useStore.getState().S.workouts.map(w => w.id)).toEqual(['w1', 'w2'])+ expect(useStore.getState().S.active.id).toBe('run')+ })++ it('saveNow writes the copy to the file without waiting', async () => {+ await localPhone()+ const useStore = await freshStore()+ await useStore.getState().boot()+ useStore.getState().update(s => { s.restSec = 75 })+ expect(readFile('opengym-state.json').restSec).not.toBe(75)+ await useStore.getState().saveNow()+ expect(readFile('opengym-state.json').restSec).toBe(75)+ })++ it('going to the background (Capacitor\'s pause) writes a change still waiting', async () => {+ await localPhone()+ const useStore = await freshStore()+ await useStore.getState().boot()+ useStore.getState().update(s => { s.restSec = 80 })+ document.dispatchEvent(new Event('pause'))+ await tick()+ expect(readFile('opengym-state.json').restSec).toBe(80)+ })+})diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsxindex 1661294ed..0cfd42c0f 100644--- a/frontend/src/views/Settings.jsx+++ b/frontend/src/views/Settings.jsx@@ -337,9 +337,12 @@ export default function Settings({ page = null, find = null, via = null, entryKeconst n = conflict.workoutsmenuSheet({title: t('Import backup?'),- subtitle: t(n === 1- ? 'The server has 1 workout that is not in this backup, logged since it was made or on another device. Replacing deletes it.'- : 'The server has {0} workouts that are not in this backup, logged since it was made or on another device. Replacing deletes them.', n),+ subtitle: conflict.device+ ? t(n === 1 ? 'This device has 1 workout that is not in this backup. Replacing deletes it.'+ : 'This device has {0} workouts that are not in this backup. Replacing deletes them.', n)+ : t(n === 1+ ? 'The server has 1 workout that is not in this backup, logged since it was made or on another device. Replacing deletes it.'+ : 'The server has {0} workouts that are not in this backup, logged since it was made or on another device. Replacing deletes them.', n),items: [{ icon: 'trash', label: t('Replace anyway'), danger: true, onClick: () => apply(null) },{ icon: 'merge', label: t('Merge them in'), onClick: () => apply(conflict) },