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.

Import: a restored backup brings back what was deleted since, and keeps what another device synced meanwhile

Duarte Santos16243da185b8
diff --git a/frontend/src/lib/sync-merge.js b/frontend/src/lib/sync-merge.js
index fca32afdc..8c1bd98d1 100644
--- a/frontend/src/lib/sync-merge.js
+++ b/frontend/src/lib/sync-merge.js
@@ -655,6 +655,42 @@ export function keepReset(cur, next) {
return next
}
+// ---- A restored backup ------------------------------------------------------------------------
+//
+// A backup brought back over the profile (Settings, Import) is a deliberate add-back: the main way
+// to undo a mistake. Its entries are older than any removal recorded since it was made, so the
+// merge used to delete them again (the removal record outlived the restore), at once with "Merge
+// them in" and on the next conflict of any other device with "Replace". And a device with an older
+// unsent setting change won over the restored settings, which carried no stamp. So a restore marks
+// every entry it holds whose removal is on record (here or in `others`) as added back at `now`,
+// stamps its settings, plan days and plans as changed at `now`, and keeps the record of removals.
+
+/** Stamps `next`, a restored backup, as described above. Mutates and returns `next`. */
+export function stampRestore(next, others = [], now = Date.now()) {
+ if (!next || typeof next !== 'object') return next
+ let del = mergeDeletions(next.deleted, null)
+ for (const o of others) del = mergeDeletions(del, o?.deleted)
+ del = del || {}
+ for (const [f, key] of Object.entries(DEL_LISTS)) {
+ const m = del[f]
+ if (!isMap(m)) continue
+ for (const x of list(next[f])) {
+ if (x == null) continue
+ const k = String(key(x))
+ if (Number(m[k]) > 0) m[k] = -now
+ }
+ }
+ if (Object.keys(del).length) next.deleted = del; else delete next.deleted
+ const ed = isMap(next.edited) ? { ...next.edited } : {}
+ for (const k of Object.keys(next)) if (!OWN_MERGE.has(k) && !PER_KEY.has(k)) ed[k] = now
+ for (const f of PER_KEY) {
+ for (const S of [next, ...others]) for (const s of Object.keys(isMap(S?.[f]) ? S[f] : {})) ed[`${f}.${s}`] = now
+ }
+ next.edited = ed
+ for (const f of ['routines', 'customEx']) for (const x of list(next[f])) if (x && typeof x === 'object') x._ts = now
+ return next
+}
+
// ---- One causal time per change ---------------------------------------------------------------
//
// Every stamp above is a wall-clock time, compared between devices. A phone whose clock runs
diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.js
index 59de5e58c..1e06452cf 100644
--- a/frontend/src/locales/ar.js
+++ b/frontend/src/locales/ar.js
@@ -1980,4 +1980,5 @@ export default {
'Swipe on sets': 'السحب على المجموعات',
'Left deletes, right copies': 'لليمين حذف، لليسار نسخ',
'Options: copy, remove': 'خيارات: نسخ، إزالة',
+ 'Another device synced while you were importing, so its changes were kept next to the backup.': 'زامن جهاز آخر أثناء الاستيراد، فاحتفظنا بتغييراته إلى جانب النسخة الاحتياطية.',
}
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index 227e69cbc..bd11ecff9 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -1947,4 +1947,5 @@ export default {
'Swipe on sets': 'Wischen auf Sätzen',
'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.',
}
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index d8d72ee20..30f683228 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -1927,4 +1927,5 @@ export default {
'Swipe on sets': 'Deslizar en las series',
'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.',
}
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index 6056afdd3..e1442b5a8 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -1927,4 +1927,5 @@ export default {
'Swipe on sets': 'Glisser sur les séries',
'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.',
}
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index 762287183..d3961837e 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -1927,4 +1927,5 @@ export default {
'Swipe on sets': 'सेट पर स्वाइप',
'Left deletes, right copies': 'बाएँ हटाता है, दाएँ कॉपी करता है',
'Options: copy, remove': 'विकल्प: कॉपी, हटाएँ',
+ 'Another device synced while you were importing, so its changes were kept next to the backup.': 'आयात के दौरान किसी दूसरे डिवाइस ने सिंक किया, इसलिए उसके बदलाव बैकअप के साथ रखे गए।',
}
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index 35060e21e..b52e0c126 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -1930,4 +1930,5 @@ export default {
'Swipe on sets': 'Húzás a sorozatokon',
'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.',
}
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index 79e9a9368..4ba57142e 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -1927,4 +1927,5 @@ export default {
'Swipe on sets': 'Scorri sulle serie',
'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.',
}
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index 9f6b1e563..c3dd4a5dc 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -1927,4 +1927,5 @@ export default {
'Swipe on sets': '세트 스와이프',
'Left deletes, right copies': '왼쪽은 삭제, 오른쪽은 복사',
'Options: copy, remove': '옵션: 복사, 삭제',
+ 'Another device synced while you were importing, so its changes were kept next to the backup.': '가져오는 동안 다른 기기가 동기화해서, 그 변경 사항도 백업과 함께 남겨 뒀어요.',
}
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index 349cc75e1..fe7c58798 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -1927,4 +1927,5 @@ export default {
'Swipe on sets': 'Przesuwanie serii',
'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.',
}
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index dd1d99e94..c72d28815 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -1192,6 +1192,7 @@ export const PT_BR_OVERRIDES = {
'Too late, that one’s gone': 'Tarde demais, já era',
'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.',
}
export default { ...pt, ...PT_BR_OVERRIDES }
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index 4ed2329eb..249e22c62 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -1927,4 +1927,5 @@ export default {
'Swipe on sets': 'Deslizar nas séries',
'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.',
}
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index b404d5704..6831d0c22 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -1931,4 +1931,5 @@ export default {
'Swipe on sets': 'Свайп по подходам',
'Left deletes, right copies': 'Влево удаляет, вправо копирует',
'Options: copy, remove': 'Действия: копировать, удалить',
+ 'Another device synced while you were importing, so its changes were kept next to the backup.': 'Другое устройство синхронизировалось во время импорта, поэтому его изменения сохранены рядом с копией.',
}
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index f74488274..29f423637 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -1938,4 +1938,5 @@ export default {
'Swipe on sets': 'ปัดบนเซ็ต',
'Left deletes, right copies': 'ซ้ายลบ ขวาคัดลอก',
'Options: copy, remove': 'ตัวเลือก: คัดลอก, ลบ',
+ 'Another device synced while you were importing, so its changes were kept next to the backup.': 'อุปกรณ์อื่นซิงก์ระหว่างที่คุณนำเข้า เลยเก็บการเปลี่ยนแปลงของมันไว้คู่กับข้อมูลสำรอง',
}
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index 3b4ba9f80..f9befbea4 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -1927,4 +1927,5 @@ export default {
'Swipe on sets': 'Setlerde kaydırma',
'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.',
}
diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.js
index 733a4e63f..53d2adf8f 100644
--- a/frontend/src/locales/uk.js
+++ b/frontend/src/locales/uk.js
@@ -1924,4 +1924,5 @@ export default {
'Swipe on sets': 'Свайп по підходах',
'Left deletes, right copies': 'Ліворуч видаляє, праворуч копіює',
'Options: copy, remove': 'Дії: копіювати, видалити',
+ 'Another device synced while you were importing, so its changes were kept next to the backup.': 'Інший пристрій синхронізувався під час імпорту, тож його зміни збережено поруч із копією.',
}
diff --git a/frontend/src/locales/zh-TW.js b/frontend/src/locales/zh-TW.js
index 4bed58755..c04de2edf 100644
--- a/frontend/src/locales/zh-TW.js
+++ b/frontend/src/locales/zh-TW.js
@@ -1920,4 +1920,5 @@ export default {
'Swipe on sets': '在組上滑動',
'Left deletes, right copies': '左滑刪除,右滑複製',
'Options: copy, remove': '選項:複製、刪除',
+ 'Another device synced while you were importing, so its changes were kept next to the backup.': '匯入時另一台裝置同步了,所以它的變更也和備份一起保留了。',
}
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index 2b391cfc7..09a9762a6 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -1927,4 +1927,5 @@ export default {
'Swipe on sets': '在组上滑动',
'Left deletes, right copies': '左滑删除,右滑复制',
'Options: copy, remove': '选项:复制、删除',
+ 'Another device synced while you were importing, so its changes were kept next to the backup.': '导入时另一台设备同步了,所以它的更改也和备份一起保留了。',
}
diff --git a/frontend/src/store/useStore.import-check.test.jsx b/frontend/src/store/useStore.import-check.test.jsx
index 310d2358f..1f94ece2b 100644
--- a/frontend/src/store/useStore.import-check.test.jsx
+++ b/frontend/src/store/useStore.import-check.test.jsx
@@ -70,13 +70,21 @@ describe('importing a backup over a profile that moved on', () => {
expect(ids(puts().at(-1).state.workouts)).toEqual(['w1', 'w2', 'elsewhere', 'unsent'])
})
- it('"Replace anyway" is the replace it always was', async () => {
+ it('"Replace anyway" replaces, against the revision the check read (or the copy\'s own)', async () => {
signedIn({ ...clone(DEF), _ts: 200, workouts: [workout('w1')] }, 6)
+ api.mockResolvedValueOnce({ state: clone(SERVER), rev: 7 })
+ await useStore.getState().importConflict(BACKUP)
api.mockResolvedValueOnce({ ok: true, rev: 8 })
useStore.getState().importBackup(BACKUP)
await useStore.getState().pushState()
- const put = puts().at(-1)
- expect(put.baseRev).toBeUndefined()
+ let put = puts().at(-1)
+ expect(put.baseRev).toBe(7)
expect(ids(put.state.workouts)).toEqual(['w1', 'w2'])
+ // no check before it (the server could not be asked): the copy's own revision
+ api.mockResolvedValueOnce({ ok: true, rev: 9 })
+ useStore.getState().importBackup(BACKUP)
+ await useStore.getState().pushState()
+ put = puts().at(-1)
+ expect(put.baseRev).toBe(8)
})
})
diff --git a/frontend/src/store/useStore.import-restore.test.jsx b/frontend/src/store/useStore.import-restore.test.jsx
new file mode 100644
index 000000000..68e39b98f
--- /dev/null
+++ b/frontend/src/store/useStore.import-restore.test.jsx
@@ -0,0 +1,94 @@
+// @vitest-environment happy-dom
+
+/* Restoring a backup is how a mistake is undone, so what the backup holds must come back and stay,
+ though it was deleted since (QA 2026-10-06): the removal record used to delete it again, at once
+ with "Merge them in" and on the next conflict of any other device with "Replace". And the
+ replace must not wipe what another device synced while the confirm was open. The server below
+ answers like api/server.js (409 with the current document on a stale baseRev). */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('../lib/api.js', () => ({ api: vi.fn(), setRemoteAuth: vi.fn() }))
+const { toast } = vi.hoisted(() => ({ toast: vi.fn() }))
+vi.mock('./useUI.js', () => ({ useUI: { getState: () => ({ toast }) } }))
+
+import { api } from '../lib/api.js'
+import { DEF, useStore } from './useStore.js'
+import { mergeStates, stampChange } from '../lib/sync-merge.js'
+
+const clone = v => JSON.parse(JSON.stringify(v))
+const ids = xs => (xs || []).map(x => x.id).sort()
+const workout = (id, t) => ({ id, d: '2026-09-20', start: t - 3600e3, end: t, entries: [] })
+const httpError = (status, data) => Object.assign(new Error('HTTP ' + status), { status, data })
+const T = Date.now() - 86400e3
+
+let doc
+const serve = () => api.mockImplementation(async (path, o = {}) => {
+ const body = o.body ? JSON.parse(o.body) : null
+ if ((o.method || 'GET') === 'GET') return { state: clone(doc), rev: doc._rev }
+ if (o.method === 'PUT') {
+ if (body.baseRev != null && body.baseRev !== doc._rev) throw httpError(409, { error: 'conflict', rev: doc._rev, state: clone(doc) })
+ doc = { ...body.state, _rev: doc._rev + 1 }
+ return { ok: true, rev: doc._rev }
+ }
+ throw new Error('unexpected ' + path)
+})
+const change = (prev, mut, wall = Date.now() - 60000) => { const n = clone(prev); mut(n); n._ts = stampChange(prev, n, wall); return n }
+
+let backup, other
+beforeEach(() => {
+ localStorage.clear(); api.mockReset(); toast.mockReset()
+ // w1..w3 logged and synced; the backup holds them; w4 logged; then w2 deleted (on this device)
+ const synced = { ...clone(DEF), _ts: T, workouts: [workout('w1', T - 3e6), workout('w2', T - 2e6), workout('w3', T - 1e6)] }
+ backup = clone(synced)
+ const withW4 = change(synced, S => { S.workouts.push(workout('w4', Date.now() - 5000)) })
+ const now = change(withW4, S => { S.workouts = S.workouts.filter(w => w.id !== 'w2') })
+ doc = { ...clone(now), _rev: 5 }
+ other = clone(now) // device B, synced to rev 5, then offline with an unsent change
+ other = change(other, S => { S.workouts.push(workout('w5', Date.now() - 1000)) })
+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 5, ts: now._ts }))
+ useStore.setState({ S: clone(now), user: { id: 'u1' }, ready: true, sync: { offline: false, pending: false, lastSynced: 0 } })
+ serve()
+})
+afterEach(() => { localStorage.clear(); useStore.setState({ S: clone(DEF), user: null, ready: false }) })
+
+describe('a restored backup brings back what it holds, and it stays', () => {
+ it('"Merge them in" restores a deleted workout, on the server and on a stale device', async () => {
+ const c = await useStore.getState().importConflict(backup)
+ useStore.getState().importBackup(backup, { mergeWith: c || { state: clone(doc), rev: doc._rev } })
+ await useStore.getState().pushState()
+ expect(ids(useStore.getState().S.workouts)).toEqual(['w1', 'w2', 'w3', 'w4'])
+ expect(ids(doc.workouts)).toEqual(['w1', 'w2', 'w3', 'w4'])
+ // B comes back online: its push gets the 409 and it merges the server's copy
+ expect(ids(mergeStates(other, doc).workouts)).toEqual(['w1', 'w2', 'w3', 'w4', 'w5'])
+ })
+
+ it('"Replace" restores it too, and a stale device with an unsent change does not delete it again', async () => {
+ await useStore.getState().importConflict(backup)
+ useStore.getState().importBackup(backup)
+ await useStore.getState().pushState()
+ expect(ids(doc.workouts)).toEqual(['w1', 'w2', 'w3'])
+ // w4, which the replace dropped without a record, is still on B and comes back: kept, not lost
+ expect(ids(mergeStates(other, doc).workouts)).toEqual(['w1', 'w2', 'w3', 'w4', 'w5'])
+ expect(ids(mergeStates(doc, other).workouts)).toEqual(['w1', 'w2', 'w3', 'w4', 'w5'])
+ })
+
+ it('the backup\'s settings win over an older unsent setting change on another device', async () => {
+ other = change(other, S => { S.restSec = 45 })
+ backup.restSec = 150
+ await useStore.getState().importConflict(backup)
+ useStore.getState().importBackup(backup)
+ await useStore.getState().pushState()
+ expect(mergeStates(other, doc).restSec).toBe(150)
+ })
+
+ it('a workout another device synced while the confirm was open is kept, and that is said', async () => {
+ await useStore.getState().importConflict(backup)
+ // the other device syncs w6 while the sheet is open
+ doc = { ...clone(doc), workouts: [...doc.workouts, workout('w6', Date.now())], _rev: doc._rev + 1 }
+ useStore.getState().importBackup(backup)
+ await useStore.getState().pushState()
+ expect(ids(doc.workouts)).toContain('w6')
+ expect(ids(doc.workouts)).toEqual(expect.arrayContaining(['w1', 'w2', 'w3']))
+ await vi.waitFor(() => expect(toast).toHaveBeenCalled())
+ })
+})
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js
index 97b857904..99124e988 100644
--- a/frontend/src/store/useStore.js
+++ b/frontend/src/store/useStore.js
@@ -8,7 +8,7 @@ import { rememberDefaultLang } from '../lib/default-lang.js'
import { guestAllowed } from '../lib/guest.js'
import { MOBILE, initReminderSync, nativeLoad, nativeSave, onAppActive, readJsonFile, syncReminder, writeAutoBackup, writeJsonFile } from '../lib/mobile.js'
import { refillIfComplete } from '../lib/rotation.js'
-import { mergeStates, localExtras, stampChange, highestStamp, inUnitOf, keepReset, resetIdsOf, mergeResetIds, entryKey } from '../lib/sync-merge.js'
+import { mergeStates, localExtras, stampChange, highestStamp, stampRestore, inUnitOf, keepReset, resetIdsOf, mergeResetIds, entryKey } from '../lib/sync-merge.js'
import { convertStateUnit } from '../lib/units.js'
import { pendingRefCount, settleMedia, loadPending } from '../lib/media-owed.js'
import { referencedHashes } from '../lib/media-refs.js'
@@ -275,7 +275,11 @@ export const useStore = create((set, get) => {
let pulling = null // the GET in flight, so two resume signals make one request
let configFetch = null // the /api/config in flight, so two callers make one request
let pushPending = false // a change made before boot's pull — pushed once boot is through
- let forceNext = false // the next push replaces the server copy outright (import, reset)
+ let forceNext = false // the next push replaces the server copy outright (reset)
+ // A backup import's replace: pushed against the revision the import's check read (importRead),
+ // so a change another device synced while the confirm was open is merged in, not wiped.
+ let replaceRev = null
+ let importRead = null // what importConflict last read: { uid, state, rev }
let lastCheck = 0
let pollTm = null
let offlineChanges = false // a push failed for lack of network — the next one that lands says so
@@ -554,8 +558,11 @@ export const useStore = create((set, get) => {
// replaced whatever another device had written in the meantime.
const force = forceNext
forceNext = false
+ const asReplace = replaceRev
+ replaceRev = null
const body = { state: S }
- if (!force && base) body.baseRev = base.rev
+ if (asReplace != null) body.baseRev = asReplace
+ else if (!force && base) body.baseRev = base.rev
try {
const r = await api('/api/data', { method: 'PUT', body: JSON.stringify(body) })
// A server from before revisions answers without one — then there is nothing to hold the
@@ -575,7 +582,13 @@ export const useStore = create((set, get) => {
if (e.status === 409 && e.data && attempt < 2) {
// Another device wrote since this one last read. The server sent its document along;
// merge and push once more against that revision. A second refusal in a row leaves the
- // copy owed and the next resume pull takes it from there.
+ // copy owed and the next resume pull takes it from there. A backup import whose replace
+ // met another device's sync keeps that device's changes too, and says so.
+ if (asReplace != null) {
+ import('./useUI.js')
+ .then(({ useUI }) => useUI.getState().toast(t('Another device synced while you were importing, so its changes were kept next to the backup.')))
+ .catch(() => {})
+ }
mergeInto(get().S, e.data.state, e.data.rev || 0)
return doPush(attempt + 1)
}
@@ -1100,6 +1113,7 @@ export const useStore = create((set, get) => {
let res
try { res = await api('/api/data') } catch { return null }
const state = res?.state
+ importRead = { uid: get().user?.id, state: state || null, rev: res?.rev ?? null }
if (!state) return null
const key = w => entryKey('workouts', w)
const inBackup = new Set((Array.isArray(backup?.workouts) ? backup.workouts : []).filter(Boolean).map(key))
@@ -1115,21 +1129,43 @@ export const useStore = create((set, get) => {
// any): the backup's settings and plan, every entry of all of them (mergeStates with the backup
// preferred, in the backup's unit), pushed against that revision like any other change, so a
// workout logged meanwhile elsewhere, or here, is not lost either.
+ //
+ // Either way the backup is a deliberate add-back (lib/sync-merge.js stampRestore): what it holds
+ // stays, though this device or the server recorded it as deleted since, and its settings and
+ // plan are the latest choice, on every device. The replace goes against the revision the check
+ // read (or this copy's own): a change another device synced meanwhile is merged in, not wiped.
importBackup(backup, { mergeWith } = {}) {
+ const cur = get().S
+ const uid = get().user?.id
+ const read = mergeWith?.state ? mergeWith : importRead && importRead.uid === uid ? importRead : null
+ importRead = null
+ const server = read?.state || null
+ const now = Math.max(Date.now(), highestStamp(cur) + 1, highestStamp(server) + 1, highestStamp(backup) + 1)
const next = Object.assign(clone(DEF), backup)
- if (!mergeWith?.state || !get().user) { get().replaceState(next, !!get().user); return }
- const others = mergeWith.local ? mergeStates(get().S, mergeWith.state) : mergeWith.state
+ if (!mergeWith?.state || !uid) {
+ stampRestore(next, [cur, server], now)
+ next._ts = now
+ get().replaceState(next, !!uid, { baseRev: read?.rev ?? metaOf().base?.rev ?? null })
+ return
+ }
+ const others = mergeWith.local ? mergeStates(cur, mergeWith.state) : mergeWith.state
// The merge keeps the backup's reset stamp (prefer); a later one this copy or the server's
// holds stays, as it does on a replace.
- const merged = keepReset(others, keepReset(get().S, Object.assign(clone(DEF), mergeStates(next, others, { prefer: 'a' }))))
+ const merged = keepReset(others, keepReset(cur, Object.assign(clone(DEF), mergeStates(next, others, { prefer: 'a' }))))
+ stampRestore(merged, [cur, mergeWith.state, next], now)
+ merged._ts = now
merged.active = next.active || null
persist(merged, true)
if (mergeWith.rev != null) writeSync(mergeWith.rev, 0)
},
// A replace that is meant to reach the server (backup import, reset) is a deliberate
- // overwrite, not a change to merge: the push it arms goes without a baseRev. It never takes
- // the reset stamp back (keepReset).
- replaceState(S, push = false) { if (push) forceNext = true; persist(keepReset(get().S, clone(S)), push) },
+ // overwrite, not a change to merge: the push it arms goes without a baseRev — or, given one
+ // (an import), against that revision, so a 409 merges what another device wrote since. It
+ // never takes the reset stamp back (keepReset).
+ replaceState(S, push = false, { baseRev = null } = {}) {
+ if (push) { if (baseRev != null) replaceRev = baseRev; else forceNext = true }
+ persist(keepReset(get().S, clone(S)), push)
+ },
// Fires after the moments where losing local data would actually hurt — a workout just
// logged, a routine just edited — not on every keystroke. No-op off mobile or with the