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
Sync: an older app that changes the same setting, plan day or routine field twice in a row keeps its second change
Duarte Santosd52a205fef1e
diff --git a/api/server.js b/api/server.jsindex 65faef346..d65fc4322 100644--- a/api/server.js+++ b/api/server.js@@ -191,6 +191,12 @@ function readStateStrict(uid) {catch (e) { return e.code === 'ENOENT' ? null : UNREADABLE; }try { return JSON.parse(raw); } catch { return UNREADABLE; }}+// A stored document as a client gets it: without the server's own note `_unstamped`.+function forClient(S) {+ if (!S || typeof S !== 'object' || !('_unstamped' in S)) return S;+ const { _unstamped, ...rest } = S;+ return rest;+}// An entry is an object a reader can dereference, and `records` is every entry of a stored// list. PUT /api/data drops the rest on the way in — a null workout, a routine that is a// number — and refuses a list that is not an array at all, but a file written before it did@@ -2086,13 +2092,15 @@ const routes = {// `rev` is the server's own count of writes to this profile (also stored inside the document as// `_rev`, so every other reader of the file — reminder tick, admin, Coach, MCP — is unaffected).// A client pushes it back as `baseRev`, and a write over a document it never saw is refused.+ // `_unstamped` is the server's note of what it stamped for an older app's last push+ // (sync-stamps.js ownRecord): read back only by the next PUT, never sent to a client.'GET /api/data': async (req, res) => {const user = readSession(req);if (!user) return json(res, 401, { error: 'not signed in' });const state = readStateStrict(user.id);if (state === UNREADABLE) { console.error('state file unreadable for', user.id); return json(res, 503, { error: 'state unreadable' }); }notePull(user);- json(res, 200, { state, rev: state?._rev || 0 });+ json(res, 200, { state: forClient(state), rev: state?._rev || 0 });},// Just the revision: the client asks this every half minute while it is open and on every// return to the foreground, and fetches the document only when the number moved — a signed-in@@ -2152,7 +2160,7 @@ const routes = {// and a client reading a document can tell whether it descends from its own (useStore pullState).if ((body.baseRev != null && body.baseRev !== curRev) ||(body.baseRev != null && typeof body.baseWid === 'string' && cur?._wid && body.baseWid !== cur._wid)) {- return json(res, 409, { error: 'conflict', rev: curRev, state: cur });+ return json(res, 409, { error: 'conflict', rev: curRev, state: forClient(cur) });}delete body.state.active; // in-progress workouts stay device-local// "Reset everything" stamps the profile (`resetAt`, with `resetIds`: what it wiped). The stampdiff --git a/api/sync-stamps.js b/api/sync-stamps.jsindex e51feaa65..13f3562d6 100644--- a/api/sync-stamps.js+++ b/api/sync-stamps.js@@ -59,7 +59,7 @@ const capStamps = m => {return m;};const OWN_MERGE = new Set([- '_ts', '_rev', '_wid', '_wids', 'active', 'unit', 'unitSet', 'resetAt', 'resetIds', 'deleted', 'edited', 'undone', 'routineOrder',+ '_ts', '_rev', '_wid', '_wids', '_unstamped', 'active', 'unit', 'unitSet', 'resetAt', 'resetIds', 'deleted', 'edited', 'undone', 'routineOrder','workouts', 'routines', 'customEx', 'equipProfiles', 'gymCards', 'bodyweight', 'favEx','exWeights', 'balanceOverrides', 'loadKind', 'plates',]);@@ -144,8 +144,45 @@ function settleMarks(marks, stamps, now) {}const sameEntry = (a, b) => same({ ...a, _ts: 0, _f: 0, _u: 0 }, { ...b, _ts: 0, _f: 0, _u: 0 });+// What the server stamped for the last push of a writer that does not stamp (`_unstamped` on the+// stored document): an older app takes the revision it is told for its own push and reads the+// profile again only once that moves, so the stamps given to its change never reach it, and its+// next push still carries the record from before. Without this, its second change of the same+// setting, plan day or routine field looked like a stale copy of the first and was set back to it+// (RC verify 2026-10-07). `fp` is that writer's record of edits as sent: the same writer pushing+// again over the revision its push made sends the same one. `ed` and `f` hold the stamps it was+// given, per setting and per entry field, as long as they are still the stored ones.+const ownStamp = (m, k, v) => isMap(m) && Number(m[k]) > 0 && Number(m[k]) === Number(v);+function fingerprint(sent) {+ if (!isMap(sent)) return 'none';+ const str = JSON.stringify(Object.keys(sent).sort().map(k => [k, sent[k]]));+ let a = 0x811c9dc5, b = 5381;+ for (let i = 0; i < str.length; i++) {+ const c = str.charCodeAt(i);+ a = Math.imul(a ^ c, 0x01000193) >>> 0;+ b = (Math.imul(b, 33) + c) >>> 0;+ }+ return `${str.length}.${a.toString(36)}.${b.toString(36)}`;+}+function ownRecord(next, now, own, fp) {+ const ed = {}, f = {};+ for (const [k, v] of Object.entries(isMap(next.edited) ? next.edited : {})) {+ if (Number(v) === now || ownStamp(own?.ed, k, v)) ed[k] = Number(v);+ }+ for (const l of ENTRY_LISTS) {+ for (const x of list(next[l])) {+ if (!isMap(x) || x.id == null || !isMap(x._f)) continue;+ const key = `${l}|${x.id}`, m = {};+ for (const [k, v] of Object.entries(x._f)) if (Number(v) === now || ownStamp(own?.f?.[key], k, v)) m[k] = Number(v);+ if (Object.keys(m).length) f[key] = m;+ }+ }+ if (!Object.keys(ed).length && !Object.keys(f).length) return null;+ return { fp, ...(Object.keys(ed).length ? { ed } : {}), ...(Object.keys(f).length ? { f } : {}) };+}+// Step 2: what a writer that does not stamp changed against the copy it read, stamped at `now`.-function stampUnstamped(cur, next, sent, now) {+function stampUnstamped(cur, next, sent, now, own = null) {// Removals: every entry the stored copy had and this one lacks, unless already on record.const del = isMap(next.deleted) ? next.deleted : {};for (const [f, key] of Object.entries(DEL_LISTS)) {@@ -172,7 +209,8 @@ function stampUnstamped(cur, next, sent, now) {const ed = isMap(next.edited) ? next.edited : {};const mine = isMap(sent) ? sent : {}, theirs = isMap(cur.edited) ? cur.edited : {};const moved = k => (Number(mine[k]) || 0) > (Number(theirs[k]) || 0);- const stale = k => isMap(sent) && (Number(theirs[k]) || 0) > (Number(mine[k]) || 0);+ // A stamp the server gave this same writer's previous push is its own change, not one it missed.+ const stale = k => isMap(sent) && (Number(theirs[k]) || 0) > (Number(mine[k]) || 0) && !ownStamp(own?.ed, k, theirs[k]);for (const k of new Set([...Object.keys(cur), ...Object.keys(next)])) {if (OWN_MERGE.has(k)) continue;const p = cur[k], n = next[k];@@ -214,6 +252,7 @@ function stampUnstamped(cur, next, sent, now) {const base = isMap(x._f) ? x._f : {}, of = isMap(old._f) ? old._f : {};for (const k of new Set([...Object.keys(old), ...Object.keys(x)])) {if (ENTRY_META.has(k) || !((Number(of[k]) || 0) > (Number(base[k]) || 0))) continue;+ if (ownStamp(own?.f?.[`${f}|${x.id}`], k, of[k])) continue;if ((k in old) === (k in x) && same(old[k], x[k])) continue;if (k in old) x[k] = clone(old[k]); else delete x[k];}@@ -281,7 +320,7 @@ const V139_DROPS = {// The lists inside an entry that are walked too, and how their items are matched.const NESTED = { routines: ['ex'], workouts: ['entries'], 'workouts.entries': ['sets'] };// Server bookkeeping and the records merged on their own: never put back from the stored copy.-const NOT_KEPT = new Set(['_rev', '_wid', '_wids', 'active', 'resetAt', 'resetIds', 'deleted', 'edited']);+const NOT_KEPT = new Set(['_rev', '_wid', '_wids', '_unstamped', 'active', 'resetAt', 'resetIds', 'deleted', 'edited']);// `x` with every key of `old` it lacks and the writer cannot have dropped on purpose. Mutates `x`.function keepKeys(old, x, place) {@@ -365,7 +404,7 @@ function keepHeld(next, now) {*/// What a document says, without its stamps and the server's bookkeeping: whether the server put// back anything of what a writer sent (stampPut's `report`).-const BOOKKEEPING = new Set(['_ts', '_f', '_u', '_rev', '_wid', '_wids', 'edited', 'deleted', 'undone']);+const BOOKKEEPING = new Set(['_ts', '_f', '_u', '_rev', '_wid', '_wids', '_unstamped', 'edited', 'deleted', 'undone']);const content = S => JSON.stringify(S, (k, v) => (BOOKKEEPING.has(k) ? undefined : v));export function stampPut(cur, next, { overRead = false, stamped = false, now = Date.now(), report = null } = {}) {@@ -373,6 +412,8 @@ export function stampPut(cur, next, { overRead = false, stamped = false, now = Dconst t = Math.max(Number(now) || 0, highestStamp(cur) + 1, highestStamp(next) + 1);const reset = (Number(next.resetAt) || 0) > (Number(cur?.resetAt) || 0);const sent = isMap(next.edited) ? { ...next.edited } : null;+ // Only the push that made it may use it (see ownRecord); whatever a writer sent back goes.+ delete next._unstamped;if (cur && !reset) {const d = mergeDeletions(cur.deleted, next.deleted);if (d) next.deleted = d; else delete next.deleted;@@ -383,7 +424,13 @@ export function stampPut(cur, next, { overRead = false, stamped = false, now = Dif (e && Object.keys(e).length) next.edited = e; else delete next.edited;const before = !stamped && report ? content(next) : null;if (!stamped) keepUnknown(cur, next);- if (!stamped && overRead) stampUnstamped(cur, next, sent, t);+ if (!stamped && overRead) {+ const fp = fingerprint(sent);+ const own = isMap(cur._unstamped) && cur._unstamped.fp === fp ? cur._unstamped : null;+ stampUnstamped(cur, next, sent, t, own);+ const rec = ownRecord(next, t, own, fp);+ if (rec) next._unstamped = rec;+ }if (before != null && content(next) !== before) report.changed = true;}keepHeld(next, t);diff --git a/api/test/sync-stamps.test.js b/api/test/sync-stamps.test.jsindex e90b7f926..bd7a43555 100644--- a/api/test/sync-stamps.test.js+++ b/api/test/sync-stamps.test.js@@ -278,3 +278,89 @@ test('an older app that adds an exercise to a routine with one of them twice keestampPut(cur, next, { overRead: true, stamped: false, now: NOW });assert.deepEqual(next.routines[0].ex.map(e => e.pyramid || null), [[12, 10, 8, 6], null, null, [5, 5, 3], null]);});++// RC verify 2026-10-07: an older app that changed the same setting, plan day or routine field twice+// in a row had its second change set back to its first. Its own push does not move the revision it+// knows, so it never reads the stamp the server gave its first change, and the copy it sends still+// carries the record from before it: the server took its second change for a stale copy.+test('an older app changing the same setting, plan day and routine field twice in a row keeps the second change', () => {+ let cur = stored();+ cur.edited = { restSec: NOW - 4000, 'week.1': NOW - 4000 };+ cur.routines[0] = { id: 'r1', name: 'Legs', ex: [{ id: 'a', sets: 3 }], _ts: NOW - 4000, _f: { name: NOW - 4000, ex: NOW - 4000 } };+ const old = clone(cur); // what v1.3.9 read, record and all+ const put = (doc, now) => { const next = clone(doc); stampPut(clone(cur), next, { overRead: true, stamped: false, now }); cur = next; return next; };+ // 1st change+ old.restSec = 120; old.week = { 1: ['r1'] };+ old.routines[0].name = 'Legs B'; old.routines[0].ex.push({ id: 'b', sets: 3 }); old.routines[0]._ts = NOW - 100;+ old.routines.reverse(); old._ts = NOW - 100;+ put(old, NOW);+ assert.equal(cur.restSec, 120);+ // 2nd change of the same fields, on the same copy (it never read the one it wrote)+ old.restSec = 150; old.week = { 1: ['r1', 'r2'] };+ const r1 = old.routines.find(r => r.id === 'r1');+ r1.name = 'Legs C'; r1.ex.push({ id: 'c', sets: 3 }); r1._ts = NOW + 900;+ old.routines.reverse(); old._ts = NOW + 900;+ put(old, NOW + 1000);+ assert.equal(cur.restSec, 150);+ assert.deepEqual(cur.week, { 1: ['r1', 'r2'] });+ assert.equal(cur.routines.find(r => r.id === 'r1').name, 'Legs C');+ assert.deepEqual(cur.routines.find(r => r.id === 'r1').ex.map(e => e.id), ['a', 'b', 'c']);+ assert.deepEqual(cur.routines.map(r => r.id), ['r1', 'r2']);+ assert.ok(cur.edited.restSec >= NOW + 1000);+ // a 3rd write of something else, then a 4th of the first field again: still its own+ old.theme = 'dark'; put(old, NOW + 2000);+ old.restSec = 75; put(old, NOW + 3000);+ assert.equal(cur.restSec, 75);+ assert.equal(cur.theme, 'dark');+ assert.equal(cur.routines.find(r => r.id === 'r1').name, 'Legs C');+});++test('a stamp the server gave one older app still holds against another that read an older copy', () => {+ let cur = stored();+ cur.edited = { restSec: NOW - 4000 };+ const before = clone(cur);+ before.edited = { restSec: NOW - 8000 }; // the other phone read an earlier copy+ const one = clone(cur);+ one.restSec = 120;+ stampPut(clone(cur), one, { overRead: true, stamped: false, now: NOW });+ cur = one;+ const other = clone(before); // back from a dead spot: its merge kept its own+ other.restSec = 90;+ stampPut(clone(cur), other, { overRead: true, stamped: false, now: NOW + 1000 });+ assert.equal(other.restSec, 120);+ // and an updated app's write in between ends the run: the older app's next push is a 409 anyway,+ // and nothing of the record is left for it+ const app = clone(one); app.theme = 'x';+ stampPut(clone(one), app, { overRead: true, stamped: true, now: NOW + 2000 });+ assert.equal('_unstamped' in app, false);+});++test('PUT /api/data: an older app\'s two changes of one setting in a row both land, and the note stays on the server', async t => {+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-stamps-'));+ fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: [{ id: 'u1', name: 'One', created: new Date().toISOString() }], creds: [], subs: [], invites: [] }));+ const child = spawn(process.execPath, ['server.js'], { cwd: API, stdio: ['ignore', 'pipe', 'pipe'],+ env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' } });+ let log = '';+ child.stdout.on('data', d => log += d); child.stderr.on('data', d => log += d);+ t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });+ const base = `http://127.0.0.1:${await boundPort(child, () => log)}`;+ const headers = { Cookie: `gymsid=${mintSession('u1')}`, 'Content-Type': 'application/json' };+ const put = async body => { const r = await fetch(`${base}/api/data`, { method: 'PUT', headers, body: JSON.stringify(body) }); return { status: r.status, body: await r.json() }; };+ const get = async () => (await (await fetch(`${base}/api/data`, { headers })).json());+ // an updated app wrote last: the copy carries a record of edits+ let r = await put({ state: { _ts: 1, restSec: 100, edited: { restSec: 1 }, workouts: [], routines: [] }, stamped: true });+ const old = (await get()).state; // v1.3.9 reads it once+ old.restSec = 120;+ r = await put({ state: old, baseRev: r.body.rev });+ assert.equal(r.status, 200);+ old.restSec = 150; // and changes it again, on the copy it has+ r = await put({ state: old, baseRev: r.body.rev });+ assert.equal(r.status, 200);+ const now = await get();+ assert.equal(now.state.restSec, 150);+ assert.equal(now.rev, r.body.rev); // nothing set back, so nothing to read again+ assert.equal('_unstamped' in now.state, false);+ const onDisk = JSON.parse(fs.readFileSync(path.join(dataDir, 'state-u1.json'), 'utf8'));+ assert.ok(onDisk._unstamped?.ed?.restSec > 0);+});diff --git a/frontend/src/lib/sync-merge.js b/frontend/src/lib/sync-merge.jsindex 75720ac24..718b39bd6 100644--- a/frontend/src/lib/sync-merge.js+++ b/frontend/src/lib/sync-merge.js@@ -600,7 +600,7 @@ function applyDeletions(S, deleted) {// a rotation pass refilled on the phone survives a setting flipped on the desktop. Fields with a// merge of their own are not stamped here; a field nobody stamped follows the newer copy, as before.const OWN_MERGE = new Set([- '_ts', '_rev', '_wid', '_wids', 'active', 'unit', 'unitSet', 'resetAt', 'resetIds', 'deleted', 'edited', 'undone', 'routineOrder',+ '_ts', '_rev', '_wid', '_wids', '_unstamped', 'active', 'unit', 'unitSet', 'resetAt', 'resetIds', 'deleted', 'edited', 'undone', 'routineOrder','workouts', 'routines', 'customEx', 'equipProfiles', 'gymCards', 'bodyweight', 'favEx','exWeights', 'balanceOverrides', 'loadKind', 'plates',])@@ -861,6 +861,7 @@ export function mergeStates(a0, b0, { prefer } = {}) {delete out._revdelete out._widdelete out._wids+ delete out._unstamped // the server's own note (api/sync-stamps.js), never a client's// The accent fields end up in CSS: whatever either copy brought, only a clean value goes on.sanitizeAccent(out)return out