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
Accounts: a copy whose session ended is kept aside when another account signs in, running workout included
Duarte Santos54dfd84af5d6
diff --git a/frontend/src/components/ServerSync.jsx b/frontend/src/components/ServerSync.jsxindex 994a23168..4e3fa09a7 100644--- a/frontend/src/components/ServerSync.jsx+++ b/frontend/src/components/ServerSync.jsx@@ -8,10 +8,10 @@ import { useUI } from '../store/useUI.js'import { t, tn } from '../lib/i18n.js'import { fmtAgo, changeCount } from '../lib/format.js'import { passkeyLogin, passkeyError, webauthnOK } from '../lib/api.js'-import { MOBILE } from '../lib/mobile.js'+import { MOBILE, shareExport } from '../lib/mobile.js'import { syncMedia } from '../lib/media-sync.js'import { DEMO } from '../lib/demo.js'-import { askAddDeviceData } from '../sheets.jsx'+import { askAddDeviceData, menuSheet } from '../sheets.jsx'import { ConnectSheet } from '../views/MobileOnboarding.jsx'import { passwordOn, openPasswordSignIn } from './PasswordAuth.jsx'import { Section, Row, Button } from './ui.jsx'@@ -292,7 +292,21 @@ export function KeptChangesRows() {return () => { gone = true }}, [kept, user?.id, rev])if (DEMO) return null+ // A copy kept for an account that may never come back here (its server lost it, or it was+ // deleted) is saved as a backup file, to import into another profile with "Merge them in".+ const save = async k => {+ const state = await useStore.getState().keptState(k.server, k.uid)+ if (!state) return+ const json = JSON.stringify(state, null, 2)+ const name = 'opengym-kept-' + String(k.name || k.uid).replace(/[^\w-]+/g, '_') + '-' + new Date().toISOString().slice(0, 10) + '.json'+ if (MOBILE) { try { await shareExport(json, name); useUI.getState().toast(t('Backup exported')) } catch { /* share sheet dismissed */ } return }+ const a = document.createElement('a'); a.href = URL.createObjectURL(new Blob([json], { type: 'application/json' })); a.download = name; a.click()+ setTimeout(() => URL.revokeObjectURL(a.href), 60000)+ useUI.getState().toast(t('Backup exported'))+ }return rows.map(k => <Row key={(k.server || '') + '|' + k.uid} icon="history" iconTint="var(--orange)"title={t('Changes kept for {0}', k.name || k.uid)}- subtitle={(k.server ? hostOf(k.server) + ' · ' : '') + t('Added back when this device connects as that account again.')} />)+ subtitle={(k.server ? hostOf(k.server) + ' · ' : '') + t('Added back when this device connects as that account again.')}+ accessory="chevron"+ onClick={() => menuSheet({ title: t('Changes kept for {0}', k.name || k.uid), items: [{ icon: 'download', label: t('Save as a backup file'), onClick: () => save(k) }] })} />)}diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.jsindex 1e06452cf..68200631f 100644--- a/frontend/src/locales/ar.js+++ b/frontend/src/locales/ar.js@@ -1981,4 +1981,5 @@ export default {'Left deletes, right copies': 'لليمين حذف، لليسار نسخ','Options: copy, remove': 'خيارات: نسخ، إزالة','Another device synced while you were importing, so its changes were kept next to the backup.': 'زامن جهاز آخر أثناء الاستيراد، فاحتفظنا بتغييراته إلى جانب النسخة الاحتياطية.',+ 'Save as a backup file': 'حفظ كملف نسخة احتياطية',}diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex bd11ecff9..9b6ff4dcb 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -1948,4 +1948,5 @@ export default {'Left deletes, right copies': 'Links löscht, rechts kopiert','Options: copy, remove': 'Optionen: kopieren, entfernen','Another device synced while you were importing, so its changes were kept next to the backup.': 'Ein anderes Gerät hat während des Imports synchronisiert, seine Änderungen bleiben neben dem Backup erhalten.',+ 'Save as a backup file': 'Als Backup-Datei sichern',}diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.jsindex 30f683228..946f6c35e 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -1928,4 +1928,5 @@ export default {'Left deletes, right copies': 'Izquierda borra, derecha copia','Options: copy, remove': 'Opciones: copiar, quitar','Another device synced while you were importing, so its changes were kept next to the backup.': 'Otro dispositivo se sincronizó mientras importabas, así que sus cambios se quedan junto a la copia.',+ 'Save as a backup file': 'Guardar como archivo de copia',}diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.jsindex e1442b5a8..c98927ba6 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -1928,4 +1928,5 @@ export default {'Left deletes, right copies': 'Gauche supprime, droite copie','Options: copy, remove': 'Options : copier, supprimer','Another device synced while you were importing, so its changes were kept next to the backup.': 'Un autre appareil a synchronisé pendant l’import, ses changements sont gardés à côté de la sauvegarde.',+ 'Save as a backup file': 'Enregistrer comme fichier de sauvegarde',}diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.jsindex d3961837e..011b33307 100644--- a/frontend/src/locales/hi.js+++ b/frontend/src/locales/hi.js@@ -1928,4 +1928,5 @@ export default {'Left deletes, right copies': 'बाएँ हटाता है, दाएँ कॉपी करता है','Options: copy, remove': 'विकल्प: कॉपी, हटाएँ','Another device synced while you were importing, so its changes were kept next to the backup.': 'आयात के दौरान किसी दूसरे डिवाइस ने सिंक किया, इसलिए उसके बदलाव बैकअप के साथ रखे गए।',+ 'Save as a backup file': 'बैकअप फ़ाइल के रूप में सहेजें',}diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.jsindex b52e0c126..a097a42c9 100644--- a/frontend/src/locales/hu.js+++ b/frontend/src/locales/hu.js@@ -1931,4 +1931,5 @@ export default {'Left deletes, right copies': 'Balra töröl, jobbra másol','Options: copy, remove': 'Lehetőségek: másolás, eltávolítás','Another device synced while you were importing, so its changes were kept next to the backup.': 'Egy másik eszköz szinkronizált importálás közben, így a változásai megmaradtak a mentés mellett.',+ 'Save as a backup file': 'Mentés biztonsági fájlként',}diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.jsindex 4ba57142e..2f55f8d6c 100644--- a/frontend/src/locales/it.js+++ b/frontend/src/locales/it.js@@ -1928,4 +1928,5 @@ export default {'Left deletes, right copies': 'Sinistra elimina, destra copia','Options: copy, remove': 'Opzioni: copia, rimuovi','Another device synced while you were importing, so its changes were kept next to the backup.': 'Un altro dispositivo ha sincronizzato durante l’importazione, quindi le sue modifiche restano accanto al backup.',+ 'Save as a backup file': 'Salva come file di backup',}diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.jsindex c3dd4a5dc..9558cc2cf 100644--- a/frontend/src/locales/ko.js+++ b/frontend/src/locales/ko.js@@ -1928,4 +1928,5 @@ export default {'Left deletes, right copies': '왼쪽은 삭제, 오른쪽은 복사','Options: copy, remove': '옵션: 복사, 삭제','Another device synced while you were importing, so its changes were kept next to the backup.': '가져오는 동안 다른 기기가 동기화해서, 그 변경 사항도 백업과 함께 남겨 뒀어요.',+ 'Save as a backup file': '백업 파일로 저장',}diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.jsindex fe7c58798..193e90c95 100644--- a/frontend/src/locales/pl.js+++ b/frontend/src/locales/pl.js@@ -1928,4 +1928,5 @@ export default {'Left deletes, right copies': 'W lewo usuwa, w prawo kopiuje','Options: copy, remove': 'Opcje: kopiuj, usuń','Another device synced while you were importing, so its changes were kept next to the backup.': 'Inne urządzenie zsynchronizowało się podczas importu, więc jego zmiany zostały obok kopii.',+ 'Save as a backup file': 'Zapisz jako plik kopii',}diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.jsindex c72d28815..29fac1e1b 100644--- a/frontend/src/locales/pt-BR.js+++ b/frontend/src/locales/pt-BR.js@@ -1193,6 +1193,7 @@ export const PT_BR_OVERRIDES = {'Psst: swipe a set. Left deletes, right copies.': 'Psiu: deslize uma série. Esquerda exclui, direita copia.','Left deletes, right copies': 'Esquerda exclui, direita copia','Another device synced while you were importing, so its changes were kept next to the backup.': 'Outro dispositivo sincronizou durante a importação, então as alterações dele ficaram junto com o backup.',+ 'Save as a backup file': 'Salvar como arquivo de backup',}export default { ...pt, ...PT_BR_OVERRIDES }diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.jsindex 249e22c62..03b1e9c06 100644--- a/frontend/src/locales/pt.js+++ b/frontend/src/locales/pt.js@@ -1928,4 +1928,5 @@ export default {'Left deletes, right copies': 'Esquerda elimina, direita copia','Options: copy, remove': 'Opções: copiar, remover','Another device synced while you were importing, so its changes were kept next to the backup.': 'Outro dispositivo sincronizou durante a importação, por isso as alterações dele ficaram junto à cópia.',+ 'Save as a backup file': 'Guardar como ficheiro de cópia',}diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.jsindex 6831d0c22..4fbc44491 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -1932,4 +1932,5 @@ export default {'Left deletes, right copies': 'Влево удаляет, вправо копирует','Options: copy, remove': 'Действия: копировать, удалить','Another device synced while you were importing, so its changes were kept next to the backup.': 'Другое устройство синхронизировалось во время импорта, поэтому его изменения сохранены рядом с копией.',+ 'Save as a backup file': 'Сохранить как файл копии',}diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.jsindex 29f423637..29c7d4290 100644--- a/frontend/src/locales/th.js+++ b/frontend/src/locales/th.js@@ -1939,4 +1939,5 @@ export default {'Left deletes, right copies': 'ซ้ายลบ ขวาคัดลอก','Options: copy, remove': 'ตัวเลือก: คัดลอก, ลบ','Another device synced while you were importing, so its changes were kept next to the backup.': 'อุปกรณ์อื่นซิงก์ระหว่างที่คุณนำเข้า เลยเก็บการเปลี่ยนแปลงของมันไว้คู่กับข้อมูลสำรอง',+ 'Save as a backup file': 'บันทึกเป็นไฟล์สำรอง',}diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.jsindex f9befbea4..8e8054ef3 100644--- a/frontend/src/locales/tr.js+++ b/frontend/src/locales/tr.js@@ -1928,4 +1928,5 @@ export default {'Left deletes, right copies': 'Sola silir, sağa kopyalar','Options: copy, remove': 'Seçenekler: kopyala, kaldır','Another device synced while you were importing, so its changes were kept next to the backup.': 'İçe aktarırken başka bir cihaz eşitlendi, onun değişiklikleri de yedeğin yanında tutuldu.',+ 'Save as a backup file': 'Yedek dosyası olarak kaydet',}diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.jsindex 53d2adf8f..2104837ec 100644--- a/frontend/src/locales/uk.js+++ b/frontend/src/locales/uk.js@@ -1925,4 +1925,5 @@ export default {'Left deletes, right copies': 'Ліворуч видаляє, праворуч копіює','Options: copy, remove': 'Дії: копіювати, видалити','Another device synced while you were importing, so its changes were kept next to the backup.': 'Інший пристрій синхронізувався під час імпорту, тож його зміни збережено поруч із копією.',+ 'Save as a backup file': 'Зберегти як файл копії',}diff --git a/frontend/src/locales/zh-TW.js b/frontend/src/locales/zh-TW.jsindex c04de2edf..71825eaf0 100644--- a/frontend/src/locales/zh-TW.js+++ b/frontend/src/locales/zh-TW.js@@ -1921,4 +1921,5 @@ export default {'Left deletes, right copies': '左滑刪除,右滑複製','Options: copy, remove': '選項:複製、刪除','Another device synced while you were importing, so its changes were kept next to the backup.': '匯入時另一台裝置同步了,所以它的變更也和備份一起保留了。',+ 'Save as a backup file': '儲存為備份檔案',}diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.jsindex 09a9762a6..a0d944b34 100644--- a/frontend/src/locales/zh.js+++ b/frontend/src/locales/zh.js@@ -1928,4 +1928,5 @@ export default {'Left deletes, right copies': '左滑删除,右滑复制','Options: copy, remove': '选项:复制、删除','Another device synced while you were importing, so its changes were kept next to the backup.': '导入时另一台设备同步了,所以它的更改也和备份一起保留了。',+ 'Save as a backup file': '保存为备份文件',}diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex 92b765754..a04ede409 100644--- a/frontend/src/store/useStore.js+++ b/frontend/src/store/useStore.js@@ -830,25 +830,32 @@ export const useStore = create((set, get) => {set({ keptRev: get().keptRev + 1 })return ok || empty}- // A different account signing in on a copy that still owes its own: the copy goes, as it always- // has — it must not be pushed into the new account — but what it owed is kept aside first, the- // way a forced sign-out keeps it, for when that account comes back. Written to localStorage- // right here, since setUser wipes the copy straight after; on a phone the file follows, and- // pairing waits for it (`keeping`) before it goes on.- // Photos or videos that never reached that account's server count as owed on their own, even on- // a copy with no workouts or routines yet — the custom exercise they belong to is all there is.+ // A different account signing in on a copy whose session ended without a sign-out (it expired,+ // was revoked, the server no longer knows the account) — or on a live one that still owes it or+ // runs a workout: the copy goes, as it always has — it+ // must not be pushed into the new account — but it is kept aside first, the way a forced+ // sign-out keeps what it owed, for when that account comes back. Not only what it owed: a copy+ // in step with a server that has since lost the account (rebuilt, the account deleted, the data+ // directory gone) is the last one there is, and a workout running here never reached any server.+ // A proper sign-out clears the owner first, so a shared device keeps nothing after one. Written+ // to localStorage right here, since setUser wipes the copy straight after; on a phone the file+ // follows, and pairing waits for it (`keeping`) before it goes on. Kept changes can be saved as a+ // backup file from Settings (keptState), to import into another profile.const keepForPrevious = uid => {syncFromSaved()const S = get().S- // (owesOwn: the hold set for the account signing in now says nothing about this copy)- if (!(owesOwn() && hasData(S)) && !pendingRefCount(S)) return+ if (!hasData(S) && !S.active && !pendingRefCount(S)) return+ // Still signed in (an account switch on a live session): its server has the copy, so only+ // what it owes and a running workout are kept, as before.+ const live = get().user?.id === uid+ if (live && !(owesOwn() && hasData(S)) && !pendingRefCount(S) && !S.active) returnconst server = serverBase()const key = stashKey(server, uid)let all = {}try { all = JSON.parse(localStorage.getItem(STASH_KEY)) || {} } catch { /* none */ }const prev = all[key]?.stateconst state = prev ? mergeStates(S, prev) : clone(S)- state.active = S.active || prev?.active || null+ state.active = carryActive(S, state) || carryActive(prev, state) || null// The name comes from beside the owner when the account is no longer signed in here (its// session ended), so the screens say whose changes these are rather than an id.let name = get().user?.id === uid ? get().user.name || '' : ''@@ -1469,6 +1476,11 @@ export const useStore = create((set, get) => {const all = await readStashes()return Object.values(all).map(({ server, uid, name, at }) => ({ server: server || null, uid, name, at }))},+ // The copy kept for one account (keptChanges' server and uid), to save as a backup file.+ async keptState(server, uid) {+ const all = await readStashes()+ return all[stashKey(server, uid)]?.state || null+ },// Every photo and video file the stashes refer to: they are kept on this device for as long// as the stash is (lib/media-sync.js localMediaGc, Reset everything).async stashedMediaHashes() {diff --git a/frontend/src/store/useStore.kept-copy.test.jsx b/frontend/src/store/useStore.kept-copy.test.jsxnew file mode 100644index 000000000..a4107adf4--- /dev/null+++ b/frontend/src/store/useStore.kept-copy.test.jsx@@ -0,0 +1,64 @@+// @vitest-environment happy-dom++/* A different account signing in on a copy whose session ended without a sign-out wiped that copy+ unless it owed its server something. When the server had lost the account (rebuilt, the+ account deleted, the data directory gone), that was the last copy of weeks of history; and a+ workout running here, which never reaches a server, was wiped even for an account that comes+ back. Now the copy is kept aside, comes back when that account signs in here again, and can be+ saved as a backup file. (QA 2026-10-06, also in v1.3.9.) */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++vi.mock('../lib/api.js', () => ({ api: vi.fn(), setRemoteAuth: vi.fn() }))+vi.mock('./useUI.js', () => ({ useUI: { getState: () => ({ toast: vi.fn(), stopRest: vi.fn(), abandonWork: vi.fn() }) } }))++import { api } from '../lib/api.js'+import { DEF, useStore } from './useStore.js'++const clone = v => JSON.parse(JSON.stringify(v))+const w = (id, d = '2026-09-01') => ({ id, d, start: 1, end: 2, entries: [] })+const ids = xs => (xs || []).map(x => x.id).sort()++beforeEach(() => { localStorage.clear(); api.mockReset() })+afterEach(() => { localStorage.clear(); useStore.setState({ S: clone(DEF), user: null, ready: false }) })++// Olga's copy, in step with her server, whose session has ended (boot's 401 leaves it so)+const olgasCopy = (extra = {}) => {+ localStorage.setItem('gym_owner', 'olga')+ localStorage.setItem('gym_owner_name', 'Olga')+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 9, ts: 500 }))+ useStore.setState({ S: { ...clone(DEF), _ts: 500, workouts: [w('o1'), w('o2', '2026-09-02')], routines: [{ id: 'r1', name: 'Push', ex: [] }], ...extra }, user: null, ready: true })+}++describe('another account on a copy whose session ended', () => {+ it('a synced copy is kept aside, not wiped, and can be read back for a backup file', async () => {+ olgasCopy()+ useStore.getState().setUser({ id: 'yuri', name: 'Yuri' })+ expect(useStore.getState().S.workouts).toEqual([])+ const kept = await useStore.getState().keptChanges()+ expect(kept.map(k => k.uid)).toEqual(['olga'])+ const state = await useStore.getState().keptState(kept[0].server, 'olga')+ expect(ids(state.workouts)).toEqual(['o1', 'o2'])+ expect(state.routines.map(r => r.id)).toEqual(['r1'])+ })++ it('a running workout comes back when that account signs in here again', async () => {+ olgasCopy({ active: { id: 'run', start: 1, entries: [{ id: 'bench', sets: [{ w: 60, r: 5, done: true }] }] } })+ useStore.getState().setUser({ id: 'yuri', name: 'Yuri' })+ expect(useStore.getState().S.active).toBe(null)+ // Yuri signs out; Olga signs in again+ useStore.setState({ user: null })+ localStorage.removeItem('gym_owner')+ const server = { ...clone(DEF), _ts: 500, workouts: [w('o1'), w('o2', '2026-09-02')], _rev: 9 }+ api.mockImplementation(async (p, o) => (o?.method === 'PUT' ? { ok: true, rev: 10 } : { state: clone(server), rev: 9 }))+ useStore.getState().setUser({ id: 'olga', name: 'Olga' }, { adopt: true })+ await useStore.getState().adoptProfile(async () => false)+ expect(useStore.getState().S.active?.id).toBe('run')+ })++ it('a proper sign-out still leaves nothing behind for the next account', async () => {+ localStorage.removeItem('gym_owner')+ useStore.setState({ S: { ...clone(DEF), _ts: 500, workouts: [w('g1')] }, user: null, ready: true })+ useStore.getState().setUser({ id: 'yuri', name: 'Yuri' })+ expect(await useStore.getState().keptChanges()).toEqual([])+ })+})