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
Signed in, the server's profile is the truth: sign-in and pairing adopt it and ask once about workouts logged while signed out (Add them / Keep profile as is); the app polls the revision every 30 s and on every resume (GET /api/data/rev) and fetches only what moved; offline and unsynced states show a banner, retry on reconnect and confirm with a toast; pagehide flushes a pending change
Duarte Santos826432a3a20d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3a5ecde0c..690fc8e0c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,6 +21,25 @@ tab bar mid-screen during a workout. Web bundle, APK and API image.and nothing pushes before the first pull of a session has landed. Older clients that send norevision keep overwriting as before, so a paired phone on an old build still syncs.Import and "Reset everything" are deliberate replacements and skip the merge.+- 👤 **Signed in, the server's profile is the truth — always.** Signing in used to keep whatever+ copy had the newer timestamp, and anything tracked while signed out is always newer: the owner+ signed out, logged a session as a guest, signed back in and kept seeing the guest copy while the+ desktop showed the real profile. Sign-in (and pairing a phone) now adopts the server's profile —+ settings, plan, history, everything — and asks one question when the device holds workouts or+ weigh-ins the profile does not have: **Add them** (only those entries join the profile) or+ **Keep profile as is**. A profile that has no state yet still takes the device's data, as+ creating one always did.+- 📡 **The newest copy is fetched every chance it gets.** While the app is open and signed in it+ asks the server for its revision every 30 seconds (one tiny request, `GET /api/data/rev`) and on+ every return to the tab, window, app or network, and fetches the document only when the number+ moved. A desktop tab left open all day now shows the phone's session within half a minute.+- 📴 **Offline mode says so.** A signed-in user who cannot reach the server sees one line under the+ header — "Offline — your changes are saved on this device and sync when you are back online" —+ or "Not synced yet — tap to retry" when the server refused a push. The changes stay on the device,+ are retried by the poll and the moment the network is back, and a toast confirms "Back online —+ synced with the server". The app also flushes a pending change on `pagehide`, since Safari can+ kill the home-screen app without a visibility event. Guests and the standalone Android build have+ no server and see none of this.- 🔔 **Reminders that were due still arrive.** The workout-day reminder wanted its exact minute:an API restart, a redeploy or a stalled tick across those 60 seconds lost the whole day'sreminder. A reminder is now sent for up to 15 minutes after its time, once per day, never later.diff --git a/api/openapi.yaml b/api/openapi.yamlindex a409874cb..876deae2f 100644--- a/api/openapi.yaml+++ b/api/openapi.yaml@@ -566,6 +566,25 @@ paths:invalid: { value: { error: "invalid state" } }'401': { $ref: '#/components/responses/Unauthorized' }+ /api/data/rev:+ get:+ tags: [Data]+ summary: Current revision of the caller's profile state+ description: |+ The `rev` that `GET /api/data` would return, without the document. Signed-in clients poll+ this while open and on every return to the foreground and fetch the document only when+ the number changed.+ responses:+ '200':+ description: The current revision (0 when the profile has no state yet).+ content:+ application/json:+ schema:+ type: object+ properties:+ rev: { type: integer }+ '401': { $ref: '#/components/responses/Unauthorized' }+/api/push/public-key:get:tags: [push]diff --git a/api/server.js b/api/server.jsindex d27fe82f3..5f2745cc3 100644--- a/api/server.js+++ b/api/server.js@@ -855,6 +855,14 @@ const routes = {const state = readState(user.id);json(res, 200, { 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+ // device is meant to show what the server has, and this is what keeps that cheap.+ 'GET /api/data/rev': async (req, res) => {+ const user = readSession(req);+ if (!user) return json(res, 401, { error: 'not signed in' });+ json(res, 200, { rev: readState(user.id)?._rev || 0 });+ },'PUT /api/data': async (req, res) => {const user = readSession(req);diff --git a/api/test/server-data-rev-endpoint.test.js b/api/test/server-data-rev-endpoint.test.jsnew file mode 100644index 000000000..e1df73ba3--- /dev/null+++ b/api/test/server-data-rev-endpoint.test.js@@ -0,0 +1,36 @@+// GET /api/data/rev hands out the revision alone — what a signed-in client polls.+import { test } from 'node:test';+import assert from 'node:assert/strict';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import crypto from 'node:crypto';+import { spawn } from 'node:child_process';+import { fileURLToPath } from 'node:url';++const API = path.dirname(path.dirname(fileURLToPath(import.meta.url)));+const SECRET = 'test-secret-rev-endpoint';+const uid = 'u_rev_1';+const cookie = () => { const p = `${uid}:${Date.now() + 86400000}:0`; return `gymsid=${p}.${crypto.createHmac('sha256', SECRET).update(p).digest('base64url')}`; };+const freePort = () => new Promise(r => { const s = require_net().createServer(); s.listen(0, () => { const p = s.address().port; s.close(() => r(p)); }); });+import net from 'node:net';+function require_net() { return net; }++test('GET /api/data/rev tracks PUT /api/data', async t => {+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-rev-'));+ fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: [{ id: uid, name: 'R', created: new Date().toISOString() }], creds: [], subs: [], invites: [] }));+ const port = await freePort();+ const child = spawn(process.execPath, ['server.js'], { cwd: API, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, PORT: String(port), DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' } });+ t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });+ const base = `http://127.0.0.1:${port}`;+ let up = false;+ for (let i = 0; i < 100 && !up; i++) { try { up = (await fetch(`${base}/api/health`)).ok; } catch {} if (!up) await new Promise(r => setTimeout(r, 100)); }+ assert.ok(up);+ const h = { cookie: cookie(), origin: 'http://localhost:8080', 'content-type': 'application/json' };+ assert.equal((await fetch(`${base}/api/data/rev`)).status, 401);+ assert.deepEqual(await (await fetch(`${base}/api/data/rev`, { headers: h })).json(), { rev: 0 });+ const put = await fetch(`${base}/api/data`, { method: 'PUT', headers: h, body: JSON.stringify({ state: { workouts: [], routines: [] }, baseRev: 0 }) });+ assert.equal(put.status, 200);+ assert.deepEqual(await (await fetch(`${base}/api/data/rev`, { headers: h })).json(), { rev: 1 });+});diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex b6ba503aa..c1f84f810 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -18,6 +18,7 @@ import TabBar from './components/TabBar.jsx'import ErrorBoundary from './components/ErrorBoundary.jsx'import Modals from './components/Modals.jsx'import Toast from './components/Toast.jsx'+import SyncBanner from './components/SyncBanner.jsx'import RestTimer from './components/RestTimer.jsx'import TimerFlash from './components/TimerFlash.jsx'import Login from './views/Login.jsx'@@ -128,6 +129,7 @@ function Shell() {re-mounts the boundary, so the tab bar is always a way out */}<div id="app" className="vfade" key={loc.pathname}><ErrorBoundary>+ {authed && !needsMobileOnboarding && <SyncBanner />}{!authed ? <Login /> : needsMobileOnboarding ? <MobileOnboarding /> : (<Routes><Route path="/home" element={<Home />} />diff --git a/frontend/src/components/SyncBanner.jsx b/frontend/src/components/SyncBanner.jsxnew file mode 100644index 000000000..d47cae978--- /dev/null+++ b/frontend/src/components/SyncBanner.jsx@@ -0,0 +1,22 @@+import { useStore } from '../store/useStore.js'+import { t } from '../lib/i18n.js'+import Icon from './Icon.jsx'++// One line under the header for a signed-in user whose changes are not on the server: offline,+// or a push the server refused. Guests and the standalone phone build have no server to sync+// with, so it never shows for them. Tapping retries at once instead of waiting for the poll.+export default function SyncBanner() {+ const user = useStore(s => s.user)+ const sync = useStore(s => s.sync)+ const pushState = useStore(s => s.pushState)+ const pullState = useStore(s => s.pullState)+ if (!user || !sync) return null+ if (!sync.offline && !sync.pending) return null+ const retry = () => { pushState(); pullState() }+ return <button className={'sync-banner' + (sync.offline ? ' off' : '')} onClick={retry}>+ <Icon name={sync.offline ? 'bellSlash' : 'reset'} />+ <span>{sync.offline+ ? (sync.pending ? t('Offline — your changes are saved on this device and sync when you are back online.') : t('Offline — showing the last copy synced with the server.'))+ : t('Not synced yet — tap to retry.')}</span>+ </button>+}diff --git a/frontend/src/index.css b/frontend/src/index.cssindex 88f23a158..f5ff32849 100644--- a/frontend/src/index.css+++ b/frontend/src/index.css@@ -172,6 +172,14 @@ body.resting #app{padding-bottom:calc(206px + var(--sab))}@keyframes viewfade{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}#app.vfade{animation:viewfade var(--med) var(--ease)}+/* sync banner: one line for a signed-in user whose changes are not on the server yet */+.sync-banner{+ display:flex;align-items:center;gap:9px;width:100%;text-align:left;+ margin:0 0 12px;padding:9px 12px;border-radius:var(--r);+ background:color-mix(in srgb,var(--yellow) 16%,var(--surface));color:var(--label);font-size:13px;line-height:1.35;+}+.sync-banner.off{background:color-mix(in srgb,var(--label-3) 18%,var(--surface))}+.sync-banner .icn,.sync-banner svg{flex:none;font-size:16px;color:var(--label-2)}/* large title, the way a nav bar does it */.hdr{display:flex;align-items:flex-end;justify-content:space-between;gap:12px;margin:8px 0 18px}.hdr h1{font-size:34px;line-height:1.06;font-weight:700;letter-spacing:-.028em}diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.jsindex 962f69f68..544cf4293 100644--- a/frontend/src/lib/pt-br-locale.test.js+++ b/frontend/src/lib/pt-br-locale.test.js@@ -27,11 +27,11 @@ describe('Brazilian Portuguese locale', () => {.sort(byCodeUnit)const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')- expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(635)- expect(inherited).toHaveLength(639)+ expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(639)+ expect(inherited).toHaveLength(643)// If this fails, review the changed keys and wording before accepting a new hash. From// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list- expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('39ca0cba5a4413823f571470c39739fd1708ec1e94a9eca4bbb6646a729a9397')+ expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('f9f572ecbbdd79fbc62a1a7804224f219d23e07810121f0160e594b4518d09ac')})test('does not leak European Portuguese UI terms', () => {diff --git a/frontend/src/lib/sync-merge.js b/frontend/src/lib/sync-merge.jsindex 4ce274060..d1a458433 100644--- a/frontend/src/lib/sync-merge.js+++ b/frontend/src/lib/sync-merge.js@@ -66,10 +66,13 @@ function mergeExWeights(n = {}, o = {}) {return out}-export function mergeStates(a, b) {+// `prefer` names the side whose settings, plan and per-exercise config win regardless of `_ts`:+// on sign-in the server's profile is the truth and the device only contributes the entries it+// logged while signed out. Without it the newer copy decides, as for a conflict between devices.+export function mergeStates(a, b, { prefer } = {}) {if (!a) return b ? clone(b) : bif (!b) return clone(a)- const n = newerOf(a, b)+ const n = prefer === 'a' ? a : prefer === 'b' ? b : newerOf(a, b)const o = n === a ? b : aconst out = clone(n)out.workouts = unionById(n.workouts, o.workouts, workoutKey).map(clone).sort(byDayStart)@@ -86,3 +89,17 @@ export function mergeStates(a, b) {delete out._revreturn out}++// What `local` holds that `server` does not: the workouts and weigh-ins a device logged while it+// was signed out, and the custom exercises they use. Sign-in asks about these before the server's+// profile replaces the local copy; zero of each means there is nothing to ask about.+export function localExtras(local, server) {+ const have = new Set(list(server?.workouts).map(workoutKey))+ const days = new Set(list(server?.bodyweight).map(e => e?.d))+ const ex = new Set(list(server?.customEx).map(e => e?.id))+ return {+ workouts: list(local?.workouts).filter(w => !have.has(workoutKey(w))).length,+ bodyweight: list(local?.bodyweight).filter(e => e && e.d != null && !days.has(e.d)).length,+ customEx: list(local?.customEx).filter(e => e && !ex.has(e.id)).length+ }+}diff --git a/frontend/src/lib/sync-merge.test.js b/frontend/src/lib/sync-merge.test.jsindex 608da779a..62c6a6fbe 100644--- a/frontend/src/lib/sync-merge.test.js+++ b/frontend/src/lib/sync-merge.test.js@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest'-import { mergeBodyweight, mergeStates, newerOf, unionById } from './sync-merge.js'+import { localExtras, mergeBodyweight, mergeStates, newerOf, unionById } from './sync-merge.js'const workout = (id, d = '2026-09-01', start = 1) => ({ id, d, start, entries: [] })const routine = (id, name = id) => ({ id, name, ex: [] })@@ -131,3 +131,23 @@ describe('mergeStates', () => {expect(m._ts).toBe(1002)})})++describe('sign-in adoption helpers', () => {+ const server = { _ts: 100, unit: 'lb', restSec: 60, workouts: [{ id: 'w1', d: '2026-09-01' }], bodyweight: [{ d: '2026-09-01', w: 80, t: 1 }], routines: [{ id: 'r1', name: 'A' }], week: { 1: ['r1'] } }+ const local = { _ts: 900, unit: 'kg', restSec: 90, workouts: [{ id: 'w9', d: '2026-09-11' }], bodyweight: [{ d: '2026-09-11', w: 81, t: 2 }, { d: '2026-09-01', w: 79, t: 9 }], routines: [{ id: 'rg', name: 'Guest' }], customEx: [{ id: 'c1', name: 'x' }], week: { 2: ['rg'] } }+ it('localExtras counts what the device has that the server does not', () => {+ expect(localExtras(local, server)).toEqual({ workouts: 1, bodyweight: 1, customEx: 1 })+ expect(localExtras(server, server)).toEqual({ workouts: 0, bodyweight: 0, customEx: 0 })+ expect(localExtras(null, server)).toEqual({ workouts: 0, bodyweight: 0, customEx: 0 })+ })+ it('mergeStates with prefer keeps the preferred side\'s settings and plan although the other is newer', () => {+ const m = mergeStates(server, local, { prefer: 'a' })+ expect(m.unit).toBe('lb'); expect(m.restSec).toBe(60); expect(m.week).toEqual({ 1: ['r1'] })+ expect(m.workouts.map(w => w.id)).toEqual(['w1', 'w9'])+ expect(m.routines.map(r => r.id).sort()).toEqual(['r1', 'rg'])+ expect(m.customEx.map(e => e.id)).toEqual(['c1'])+ // the weigh-in both sides have for the same day: the later `t` wins, as between devices+ expect(m.bodyweight.find(e => e.d === '2026-09-01').w).toBe(79)+ expect(mergeStates(server, local).unit).toBe('kg') // without prefer the newer copy decides+ })+})diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex ee9764736..f72b606c0 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -1237,4 +1237,13 @@ export default {'Exercise': 'Übung','Layout': 'Layout','No exercises yet.': 'Noch keine Übungen.',+ // --- sign-in adoption + offline banner (v1.3.6) ---+ 'Add this device\'s workouts to your profile?': 'Trainings von diesem Gerät zum Profil hinzufügen?',+ '{0} workouts and {1} weigh-ins were logged on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': '{0} Trainings und {1} Wiegungen wurden auf diesem Gerät ohne Anmeldung erfasst. Zum Profil hinzufügen oder das Profil genau so lassen, wie es auf dem Server ist.',+ 'Add them': 'Hinzufügen',+ 'Keep profile as is': 'Profil so lassen',+ 'Offline — your changes are saved on this device and sync when you are back online.': 'Offline — deine Änderungen sind auf diesem Gerät gespeichert und werden synchronisiert, sobald du wieder online bist.',+ 'Offline — showing the last copy synced with the server.': 'Offline — zeigt die zuletzt mit dem Server synchronisierte Kopie.',+ 'Not synced yet — tap to retry.': 'Noch nicht synchronisiert — tippen zum Wiederholen.',+ 'Back online — synced with the server.': 'Wieder online — mit dem Server synchronisiert.',}diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.jsindex 475108c6a..8295e0a82 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -1217,4 +1217,13 @@ export default {'Exercise': 'Ejercicio','Layout': 'Diseño','No exercises yet.': 'Aún no hay ejercicios.',+ // --- sign-in adoption + offline banner (v1.3.6) ---+ 'Add this device\'s workouts to your profile?': '¿Añadir los entrenamientos de este dispositivo a tu perfil?',+ '{0} workouts and {1} weigh-ins were logged on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': '{0} entrenamientos y {1} pesajes se registraron en este dispositivo sin iniciar sesión. Añádelos a tu perfil o deja el perfil exactamente como está en el servidor.',+ 'Add them': 'Añadirlos',+ 'Keep profile as is': 'Dejar el perfil como está',+ 'Offline — your changes are saved on this device and sync when you are back online.': 'Sin conexión: tus cambios se guardan en este dispositivo y se sincronizarán cuando vuelvas a estar en línea.',+ 'Offline — showing the last copy synced with the server.': 'Sin conexión: se muestra la última copia sincronizada con el servidor.',+ 'Not synced yet — tap to retry.': 'Aún no sincronizado: toca para reintentar.',+ 'Back online — synced with the server.': 'De nuevo en línea: sincronizado con el servidor.',}diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.jsindex 33d7e70dd..780435543 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -1217,4 +1217,13 @@ export default {'Exercise': 'Exercice','Layout': 'Disposition','No exercises yet.': 'Aucun exercice pour l’instant.',+ // --- sign-in adoption + offline banner (v1.3.6) ---+ 'Add this device\'s workouts to your profile?': 'Ajouter les séances de cet appareil à votre profil ?',+ '{0} workouts and {1} weigh-ins were logged on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': '{0} séances et {1} pesées ont été enregistrées sur cet appareil sans connexion. Ajoutez-les à votre profil ou gardez le profil exactement tel qu’il est sur le serveur.',+ 'Add them': 'Les ajouter',+ 'Keep profile as is': 'Garder le profil tel quel',+ 'Offline — your changes are saved on this device and sync when you are back online.': 'Hors ligne — vos modifications sont enregistrées sur cet appareil et seront synchronisées dès le retour de la connexion.',+ 'Offline — showing the last copy synced with the server.': 'Hors ligne — affichage de la dernière copie synchronisée avec le serveur.',+ 'Not synced yet — tap to retry.': 'Pas encore synchronisé — touchez pour réessayer.',+ 'Back online — synced with the server.': 'De retour en ligne — synchronisé avec le serveur.',}diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.jsindex 2ae66c12a..17e88d190 100644--- a/frontend/src/locales/hi.js+++ b/frontend/src/locales/hi.js@@ -1217,4 +1217,13 @@ export default {'Exercise': 'व्यायाम','Layout': 'लेआउट','No exercises yet.': 'अभी कोई व्यायाम नहीं।',+ // --- sign-in adoption + offline banner (v1.3.6) ---+ 'Add this device\'s workouts to your profile?': 'इस डिवाइस के वर्कआउट अपनी प्रोफ़ाइल में जोड़ें?',+ '{0} workouts and {1} weigh-ins were logged on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': '{0} वर्कआउट और {1} वज़न इस डिवाइस पर बिना साइन इन किए दर्ज किए गए। इन्हें अपनी प्रोफ़ाइल में जोड़ें, या प्रोफ़ाइल को ठीक वैसा ही रखें जैसा सर्वर पर है।',+ 'Add them': 'जोड़ें',+ 'Keep profile as is': 'प्रोफ़ाइल वैसी ही रखें',+ 'Offline — your changes are saved on this device and sync when you are back online.': 'ऑफ़लाइन — आपके बदलाव इस डिवाइस पर सहेजे गए हैं और ऑनलाइन होते ही सिंक हो जाएँगे।',+ 'Offline — showing the last copy synced with the server.': 'ऑफ़लाइन — सर्वर से सिंक की गई आख़िरी प्रति दिखाई जा रही है।',+ 'Not synced yet — tap to retry.': 'अभी सिंक नहीं हुआ — फिर से कोशिश के लिए टैप करें।',+ 'Back online — synced with the server.': 'फिर से ऑनलाइन — सर्वर से सिंक हो गया।',}diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.jsindex 20879efe6..f72e54277 100644--- a/frontend/src/locales/hu.js+++ b/frontend/src/locales/hu.js@@ -1220,4 +1220,13 @@ export default {'Exercise': 'Gyakorlat','Layout': 'Elrendezés','No exercises yet.': 'Még nincsenek gyakorlatok.',+ // --- sign-in adoption + offline banner (v1.3.6) ---+ 'Add this device\'s workouts to your profile?': 'Hozzáadod az eszközön lévő edzéseket a profilodhoz?',+ '{0} workouts and {1} weigh-ins were logged on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': '{0} edzés és {1} mérés került rögzítésre ezen az eszközön bejelentkezés nélkül. Add hozzá őket a profilodhoz, vagy hagyd a profilt pontosan úgy, ahogy a szerveren van.',+ 'Add them': 'Hozzáadás',+ 'Keep profile as is': 'Profil marad',+ 'Offline — your changes are saved on this device and sync when you are back online.': 'Offline — a módosításaid ezen az eszközön vannak mentve, és szinkronizálódnak, amint újra online leszel.',+ 'Offline — showing the last copy synced with the server.': 'Offline — a szerverrel utoljára szinkronizált másolat látható.',+ 'Not synced yet — tap to retry.': 'Még nincs szinkronizálva — koppints az újrapróbáláshoz.',+ 'Back online — synced with the server.': 'Újra online — szinkronizálva a szerverrel.',}diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.jsindex 4441618de..71057e807 100644--- a/frontend/src/locales/it.js+++ b/frontend/src/locales/it.js@@ -1217,4 +1217,13 @@ export default {'Exercise': 'Esercizio','Layout': 'Layout','No exercises yet.': 'Ancora nessun esercizio.',+ // --- sign-in adoption + offline banner (v1.3.6) ---+ 'Add this device\'s workouts to your profile?': 'Aggiungere gli allenamenti di questo dispositivo al tuo profilo?',+ '{0} workouts and {1} weigh-ins were logged on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': '{0} allenamenti e {1} pesate sono stati registrati su questo dispositivo senza accesso. Aggiungili al tuo profilo o lascia il profilo esattamente com’è sul server.',+ 'Add them': 'Aggiungili',+ 'Keep profile as is': 'Lascia il profilo com’è',+ 'Offline — your changes are saved on this device and sync when you are back online.': 'Offline — le tue modifiche sono salvate su questo dispositivo e verranno sincronizzate quando tornerai online.',+ 'Offline — showing the last copy synced with the server.': 'Offline — viene mostrata l’ultima copia sincronizzata con il server.',+ 'Not synced yet — tap to retry.': 'Non ancora sincronizzato — tocca per riprovare.',+ 'Back online — synced with the server.': 'Di nuovo online — sincronizzato con il server.',}diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.jsindex eaa7a8687..470861e5c 100644--- a/frontend/src/locales/ko.js+++ b/frontend/src/locales/ko.js@@ -1217,4 +1217,13 @@ export default {'Exercise': '운동','Layout': '레이아웃','No exercises yet.': '아직 운동이 없습니다.',+ // --- sign-in adoption + offline banner (v1.3.6) ---+ 'Add this device\'s workouts to your profile?': '이 기기의 운동을 프로필에 추가할까요?',+ '{0} workouts and {1} weigh-ins were logged on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': '로그인하지 않은 상태에서 이 기기에 운동 {0}개와 체중 기록 {1}개가 기록되었습니다. 프로필에 추가하거나 서버에 있는 프로필을 그대로 유지하세요.',+ 'Add them': '추가',+ 'Keep profile as is': '프로필 그대로 유지',+ 'Offline — your changes are saved on this device and sync when you are back online.': '오프라인 — 변경 사항은 이 기기에 저장되며 다시 온라인이 되면 동기화됩니다.',+ 'Offline — showing the last copy synced with the server.': '오프라인 — 서버와 마지막으로 동기화된 사본을 표시합니다.',+ 'Not synced yet — tap to retry.': '아직 동기화되지 않음 — 다시 시도하려면 탭하세요.',+ 'Back online — synced with the server.': '다시 온라인 — 서버와 동기화되었습니다.',}diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.jsindex 13001d405..e4ebafd2b 100644--- a/frontend/src/locales/pl.js+++ b/frontend/src/locales/pl.js@@ -1217,4 +1217,13 @@ export default {'Exercise': 'Ćwiczenie','Layout': 'Układ','No exercises yet.': 'Brak ćwiczeń.',+ // --- sign-in adoption + offline banner (v1.3.6) ---+ 'Add this device\'s workouts to your profile?': 'Dodać treningi z tego urządzenia do profilu?',+ '{0} workouts and {1} weigh-ins were logged on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': '{0} treningów i {1} ważeń zapisano na tym urządzeniu bez logowania. Dodaj je do profilu albo zostaw profil dokładnie taki, jaki jest na serwerze.',+ 'Add them': 'Dodaj',+ 'Keep profile as is': 'Zostaw profil bez zmian',+ 'Offline — your changes are saved on this device and sync when you are back online.': 'Offline — zmiany są zapisane na tym urządzeniu i zsynchronizują się, gdy znów będziesz online.',+ 'Offline — showing the last copy synced with the server.': 'Offline — wyświetlana jest ostatnia kopia zsynchronizowana z serwerem.',+ 'Not synced yet — tap to retry.': 'Jeszcze nie zsynchronizowano — dotknij, aby ponowić.',+ 'Back online — synced with the server.': 'Znów online — zsynchronizowano z serwerem.',}diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.jsindex 1e3de0837..fb0320095 100644--- a/frontend/src/locales/pt-BR.js+++ b/frontend/src/locales/pt-BR.js@@ -4,6 +4,10 @@import pt from './pt.js'export const PT_BR_OVERRIDES = {+ '{0} workouts and {1} weigh-ins were logged on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': '{0} treinos e {1} pesagens foram registrados neste dispositivo sem login. Adicione-os ao seu perfil ou mantenha o perfil exatamente como está no servidor.',+ 'Add this device\'s workouts to your profile?': 'Adicionar os treinos deste dispositivo ao seu perfil?',+ 'Offline — your changes are saved on this device and sync when you are back online.': 'Offline — suas alterações ficam salvas neste dispositivo e sincronizam assim que você voltar a ficar online.',+ 'Not synced yet — tap to retry.': 'Ainda não sincronizado — toque para tentar novamente.','Enter a positive step to use this progression rule.': 'Digite um passo positivo para usar esta regra de progressão.','Layout': 'Layout','No sessions logged yet': 'Ainda não há sessões registradas',diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.jsindex f01583a7f..82354bbc3 100644--- a/frontend/src/locales/pt.js+++ b/frontend/src/locales/pt.js@@ -1217,4 +1217,13 @@ export default {'Exercise': 'Exercício','Layout': 'Disposição','No exercises yet.': 'Ainda sem exercícios.',+ // --- sign-in adoption + offline banner (v1.3.6) ---+ 'Add this device\'s workouts to your profile?': 'Adicionar os treinos deste dispositivo ao teu perfil?',+ '{0} workouts and {1} weigh-ins were logged on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': '{0} treinos e {1} pesagens foram registados neste dispositivo sem sessão iniciada. Adiciona-os ao teu perfil ou mantém o perfil exatamente como está no servidor.',+ 'Add them': 'Adicionar',+ 'Keep profile as is': 'Manter o perfil como está',+ 'Offline — your changes are saved on this device and sync when you are back online.': 'Offline — as tuas alterações ficam guardadas neste dispositivo e sincronizam assim que voltares a estar online.',+ 'Offline — showing the last copy synced with the server.': 'Offline — a mostrar a última cópia sincronizada com o servidor.',+ 'Not synced yet — tap to retry.': 'Ainda não sincronizado — toca para tentar de novo.',+ 'Back online — synced with the server.': 'De volta online — sincronizado com o servidor.',}diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.jsindex 3285a9658..b44293703 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -1217,4 +1217,13 @@ export default {'Exercise': 'Упражнение','Layout': 'Вид','No exercises yet.': 'Пока нет упражнений.',+ // --- sign-in adoption + offline banner (v1.3.6) ---+ 'Add this device\'s workouts to your profile?': 'Добавить тренировки с этого устройства в профиль?',+ '{0} workouts and {1} weigh-ins were logged on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': '{0} тренировок и {1} взвешиваний были записаны на этом устройстве без входа. Добавьте их в профиль или оставьте профиль ровно таким, как на сервере.',+ 'Add them': 'Добавить',+ 'Keep profile as is': 'Оставить профиль как есть',+ 'Offline — your changes are saved on this device and sync when you are back online.': 'Офлайн — изменения сохранены на этом устройстве и синхронизируются, как только появится сеть.',+ 'Offline — showing the last copy synced with the server.': 'Офлайн — показана последняя копия, синхронизированная с сервером.',+ 'Not synced yet — tap to retry.': 'Ещё не синхронизировано — нажмите, чтобы повторить.',+ 'Back online — synced with the server.': 'Снова онлайн — синхронизировано с сервером.',}diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.jsindex c46ad18a2..04198369b 100644--- a/frontend/src/locales/th.js+++ b/frontend/src/locales/th.js@@ -1228,4 +1228,13 @@ export default {'Exercise': 'ท่าออกกำลังกาย','Layout': 'เลย์เอาต์','No exercises yet.': 'ยังไม่มีท่าออกกำลังกาย',+ // --- sign-in adoption + offline banner (v1.3.6) ---+ 'Add this device\'s workouts to your profile?': 'เพิ่มการฝึกจากอุปกรณ์นี้ลงในโปรไฟล์ของคุณหรือไม่',+ '{0} workouts and {1} weigh-ins were logged on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': 'มีการบันทึกการฝึก {0} ครั้งและการชั่งน้ำหนัก {1} ครั้งบนอุปกรณ์นี้ขณะไม่ได้ลงชื่อเข้าใช้ เพิ่มลงในโปรไฟล์ของคุณ หรือคงโปรไฟล์ไว้ตามที่อยู่บนเซิร์ฟเวอร์',+ 'Add them': 'เพิ่ม',+ 'Keep profile as is': 'คงโปรไฟล์ไว้',+ 'Offline — your changes are saved on this device and sync when you are back online.': 'ออฟไลน์ — การเปลี่ยนแปลงถูกบันทึกไว้ในอุปกรณ์นี้และจะซิงค์เมื่อกลับมาออนไลน์',+ 'Offline — showing the last copy synced with the server.': 'ออฟไลน์ — แสดงสำเนาล่าสุดที่ซิงค์กับเซิร์ฟเวอร์',+ 'Not synced yet — tap to retry.': 'ยังไม่ได้ซิงค์ — แตะเพื่อลองใหม่',+ 'Back online — synced with the server.': 'กลับมาออนไลน์แล้ว — ซิงค์กับเซิร์ฟเวอร์แล้ว',}diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.jsindex 9f21eebc4..bdb5211ce 100644--- a/frontend/src/locales/tr.js+++ b/frontend/src/locales/tr.js@@ -1217,4 +1217,13 @@ export default {'Exercise': 'Egzersiz','Layout': 'Düzen','No exercises yet.': 'Henüz egzersiz yok.',+ // --- sign-in adoption + offline banner (v1.3.6) ---+ 'Add this device\'s workouts to your profile?': 'Bu cihazdaki antrenmanlar profiline eklensin mi?',+ '{0} workouts and {1} weigh-ins were logged on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': 'Bu cihazda oturum açılmadan {0} antrenman ve {1} tartım kaydedildi. Bunları profiline ekle ya da profili sunucudaki hâliyle bırak.',+ 'Add them': 'Ekle',+ 'Keep profile as is': 'Profili olduğu gibi bırak',+ 'Offline — your changes are saved on this device and sync when you are back online.': 'Çevrimdışı — değişikliklerin bu cihazda kayıtlı, tekrar çevrimiçi olunca eşitlenecek.',+ 'Offline — showing the last copy synced with the server.': 'Çevrimdışı — sunucuyla en son eşitlenen kopya gösteriliyor.',+ 'Not synced yet — tap to retry.': 'Henüz eşitlenmedi — yeniden denemek için dokun.',+ 'Back online — synced with the server.': 'Yeniden çevrimiçi — sunucuyla eşitlendi.',}diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.jsindex a0502fa58..d2cc00a5b 100644--- a/frontend/src/locales/zh.js+++ b/frontend/src/locales/zh.js@@ -1217,4 +1217,13 @@ export default {'Exercise': '动作','Layout': '布局','No exercises yet.': '还没有动作。',+ // --- sign-in adoption + offline banner (v1.3.6) ---+ 'Add this device\'s workouts to your profile?': '把此设备上的训练加入你的个人资料?',+ '{0} workouts and {1} weigh-ins were logged on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.': '此设备在未登录时记录了 {0} 次训练和 {1} 次体重。把它们加入你的个人资料,或保持个人资料与服务器上的完全一致。',+ 'Add them': '加入',+ 'Keep profile as is': '保持不变',+ 'Offline — your changes are saved on this device and sync when you are back online.': '离线 — 你的更改已保存在此设备上,恢复联网后会自动同步。',+ 'Offline — showing the last copy synced with the server.': '离线 — 正在显示最后一次与服务器同步的副本。',+ 'Not synced yet — tap to retry.': '尚未同步 — 点按重试。',+ 'Back online — synced with the server.': '已恢复联网 — 已与服务器同步。',}diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsxindex c76ef5f9e..611aa6a28 100644--- a/frontend/src/sheets.jsx+++ b/frontend/src/sheets.jsx@@ -45,15 +45,26 @@ const toast = m => ui().toast(m)const snd = () => S().sound/* ============================ custom confirm dialog ============================ */-function ConfirmDialog({ title, message, confirmText, cancelText, danger, onConfirm, close }) {+function ConfirmDialog({ title, message, confirmText, cancelText, danger, onConfirm, onCancel, close }) {return <div style={{ textAlign: 'center', padding: '4px 0' }}>{title && <h3 style={{ marginBottom: 8 }}>{title}</h3>}<div className="muted" style={{ marginBottom: 18, lineHeight: 1.5 }}>{message}</div><button className={'btn ' + (danger ? 'danger' : 'primary')} onClick={() => { close(); onConfirm && onConfirm() }}>{confirmText || t('Confirm')}</button><div style={{ height: 8 }} />- <Button variant="ghost" className="dim" onClick={close}>{cancelText || t('Cancel')}</Button>+ <Button variant="ghost" className="dim" onClick={() => { close(); onCancel && onCancel() }}>{cancelText || t('Cancel')}</Button></div>}+// Sign-in found workouts on this device that the profile does not have (logged while signed+// out). The profile is the truth — settings and plan come from the server either way — the+// question is only whether these entries are added to it or dropped. Resolves true to add.+export function askAddDeviceData(extras) {+ return new Promise(resolve => confirmSheet({+ title: t('Add this device\'s workouts to your profile?'),+ message: t('{0} workouts and {1} weigh-ins were logged on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.', extras.workouts, extras.bodyweight),+ confirmText: t('Add them'), cancelText: t('Keep profile as is'),+ onConfirm: () => resolve(true), onCancel: () => resolve(false), locked: true+ }))+}/* ============================ menu sheet ============================ */// A list of actions, one per row, closing on tap. This is where the workout screen parks// everything that is not a set you are about to log: the point of a single "more" button is@@ -81,7 +92,7 @@ export function menuSheet(opts) {// Themed replacement for window.confirm — callback-based (no blocking).export function confirmSheet(opts) {- ui().openSheet(close => <ConfirmDialog {...opts} close={close} />, { kind: 'center' })+ ui().openSheet(close => <ConfirmDialog {...opts} close={close} />, { kind: 'center', ...(opts.locked ? { locked: true } : {}) })}/* ============================ starter plan ============================ */diff --git a/frontend/src/store/useStore.adopt.test.jsx b/frontend/src/store/useStore.adopt.test.jsxnew file mode 100644index 000000000..02eabce04--- /dev/null+++ b/frontend/src/store/useStore.adopt.test.jsx@@ -0,0 +1,140 @@+// @vitest-environment happy-dom++/* Signed in, the server's profile is the truth: sign-in adopts it whatever the timestamps say,+ asking only about entries the device logged while signed out; the store polls the revision+ while open and flags offline / unsynced for the banner. */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++vi.mock('../lib/api.js', () => ({ api: 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'++const clone = value => JSON.parse(JSON.stringify(value))+const routine = id => ({ id, name: id, ex: [] })+const workout = (id, d = '2026-09-01') => ({ id, d, start: 1, entries: [] })+const sync = () => JSON.parse(localStorage.getItem('gym_sync'))+const puts = () => api.mock.calls.filter(([, o]) => o?.method === 'PUT').map(([, o]) => JSON.parse(o.body))+const paths = () => api.mock.calls.map(([p]) => p)+const signedIn = (S, extra = {}) => useStore.setState({ S, user: { id: 'user-1' }, ready: true, sync: { offline: false, pending: false, lastSynced: 0 }, ...extra })+const netErr = () => new TypeError('Failed to fetch')++const server = { ...clone(DEF), _ts: 100, unit: 'lb', restSec: 60, workouts: [workout('w1')], routines: [routine('r1')], week: { 1: ['r1'] }, _rev: 4 }+// what a guest tracked after signing out: newer, one workout, its own routine and settings+const guest = { ...clone(DEF), _ts: 900, unit: 'kg', restSec: 120, workouts: [workout('w9', '2026-09-11')], routines: [routine('rg')], week: { 2: ['rg'] }, active: { id: 'running' } }++beforeEach(() => { localStorage.clear(); api.mockReset(); toast.mockReset(); useStore.setState({ S: clone(DEF), user: null, ready: false }) })+afterEach(() => { vi.useRealTimers(); localStorage.clear(); useStore.setState({ S: clone(DEF), user: null, ready: false }) })++describe('adoptProfile — sign-in takes the server profile', () => {+ it('adopts the server copy over newer local data when the user keeps the profile as is', async () => {+ signedIn(clone(guest))+ api.mockResolvedValueOnce({ state: clone(server), rev: 4 })+ const ask = vi.fn(async () => false)+ const r = await useStore.getState().adoptProfile(ask)+ expect(ask).toHaveBeenCalledWith({ workouts: 1, bodyweight: 0, customEx: 0 })+ const S = useStore.getState().S+ expect(S.unit).toBe('lb'); expect(S.restSec).toBe(60)+ expect(S.workouts.map(w => w.id)).toEqual(['w1'])+ expect(S.routines.map(x => x.id)).toEqual(['r1'])+ expect(S.active).toEqual({ id: 'running' }) // the in-progress session stays with the device+ expect(puts()).toHaveLength(0)+ expect(sync()).toEqual({ rev: 4, ts: 100 })+ expect(r).toEqual({ adopted: true, added: false })+ })++ it('adds the device\'s entries to the profile when asked to, keeping the profile\'s settings and plan', async () => {+ signedIn(clone(guest))+ api.mockResolvedValueOnce({ state: clone(server), rev: 4 })+ api.mockResolvedValueOnce({ ok: true, rev: 5 })+ await useStore.getState().adoptProfile(async () => true)+ const S = useStore.getState().S+ expect(S.unit).toBe('lb'); expect(S.week).toEqual({ 1: ['r1'] })+ expect(S.workouts.map(w => w.id)).toEqual(['w1', 'w9'])+ expect(S.routines.map(x => x.id).sort()).toEqual(['r1', 'rg'])+ expect(puts()).toHaveLength(1)+ expect(puts()[0].baseRev).toBe(4)+ expect(puts()[0].state.workouts.map(w => w.id)).toEqual(['w1', 'w9'])+ expect(sync().rev).toBe(5)+ })++ it('does not ask when the device has nothing the profile lacks', async () => {+ signedIn({ ...clone(DEF), _ts: 900, unit: 'kg' })+ api.mockResolvedValueOnce({ state: clone(server), rev: 4 })+ const ask = vi.fn(async () => true)+ await useStore.getState().adoptProfile(ask)+ expect(ask).not.toHaveBeenCalled()+ expect(useStore.getState().S.unit).toBe('lb')+ expect(puts()).toHaveLength(0)+ })++ it('moves the device data into a profile that has no state yet', async () => {+ signedIn(clone(guest))+ api.mockResolvedValueOnce({ state: null, rev: 0 })+ api.mockResolvedValueOnce({ ok: true, rev: 1 })+ const ask = vi.fn()+ await useStore.getState().adoptProfile(ask)+ expect(ask).not.toHaveBeenCalled()+ expect(puts()).toHaveLength(1)+ expect(puts()[0].baseRev).toBeUndefined() // a deliberate replace of an empty profile+ expect(puts()[0].state.workouts.map(w => w.id)).toEqual(['w9'])+ expect(useStore.getState().S.unit).toBe('kg')+ })+})++describe('offline and unsynced flags', () => {+ it('a push that cannot reach the server marks offline + pending and keeps the change owed', async () => {+ signedIn({ ...clone(DEF), _ts: 500, workouts: [workout('w1')] })+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))+ api.mockRejectedValueOnce(netErr())+ await useStore.getState().pushState()+ expect(useStore.getState().sync).toMatchObject({ offline: true, pending: true })+ expect(localStorage.getItem('gym_dirty')).toBe('1')+ // back online: the push lands, the flags clear, and the user hears about it once+ api.mockResolvedValueOnce({ ok: true, rev: 2 })+ await useStore.getState().pushState()+ expect(useStore.getState().sync).toMatchObject({ offline: false, pending: false })+ expect(localStorage.getItem('gym_dirty')).toBeNull()+ await new Promise(r => setTimeout(r, 0)) // the toast goes through a lazy import of useUI+ expect(toast).toHaveBeenCalledWith('Back online — synced with the server.')+ })++ it('a push the server refused is pending but not offline', async () => {+ signedIn({ ...clone(DEF), _ts: 500, workouts: [workout('w1')] })+ api.mockRejectedValueOnce(Object.assign(new Error('HTTP 500'), { status: 500, data: {} }))+ await useStore.getState().pushState()+ expect(useStore.getState().sync).toMatchObject({ offline: false, pending: true })+ expect(toast).not.toHaveBeenCalled()+ })+})++describe('revision check on resume', () => {+ it('asks only for the revision and pulls the document when it moved', async () => {+ signedIn({ ...clone(DEF), _ts: 100, workouts: [workout('w1')] })+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))+ api.mockResolvedValueOnce({ rev: 1 })+ window.dispatchEvent(new Event('online')) // forced: no throttle+ await new Promise(r => setTimeout(r, 0))+ expect(paths()).toEqual(['/api/data/rev'])+ api.mockReset()+ api.mockResolvedValueOnce({ rev: 2 })+ api.mockResolvedValueOnce({ state: { ...clone(DEF), _ts: 200, workouts: [workout('w1'), workout('w2')], _rev: 2 }, rev: 2 })+ window.dispatchEvent(new Event('online'))+ await new Promise(r => setTimeout(r, 10))+ expect(paths()).toEqual(['/api/data/rev', '/api/data'])+ expect(useStore.getState().S.workouts.map(w => w.id)).toEqual(['w1', 'w2'])+ expect(sync().rev).toBe(2)+ })++ it('a revision check that cannot reach the server only flags offline', async () => {+ signedIn({ ...clone(DEF), _ts: 100, workouts: [workout('w1')] })+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))+ api.mockRejectedValueOnce(netErr())+ window.dispatchEvent(new Event('online'))+ await new Promise(r => setTimeout(r, 0))+ expect(useStore.getState().sync.offline).toBe(true)+ expect(useStore.getState().S.workouts.map(w => w.id)).toEqual(['w1'])+ })+})diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex c8a3cd85b..08fc35342 100644--- a/frontend/src/store/useStore.js+++ b/frontend/src/store/useStore.js@@ -6,7 +6,7 @@ import { registerCustom } from '../lib/exercises.js'import { DEMO, DEMO_SEEDED } from '../lib/demo.js'import { guestAllowed } from '../lib/guest.js'import { MOBILE, initReminderSync, nativeLoad, nativeSave, onAppActive, syncReminder, writeAutoBackup } from '../lib/mobile.js'-import { mergeStates } from '../lib/sync-merge.js'+import { mergeStates, localExtras } from '../lib/sync-merge.js'import { loadRemote, chooseLocal, forgetRemote, connect } from '../lib/remote.js'import { loadCoachDevice, saveCoachDevice, coachDeviceSettings } from '../lib/coach-device.js'@@ -18,7 +18,8 @@ const KEY = 'gym_state_v1'// a document this device never saw is refused (409) instead of dropping another device's work;// `ts` tells a pull whether anything changed here since. See pushState/pullState.const SYNC_KEY = 'gym_sync'-const PULL_MIN_MS = 15000 // resume pulls closer together than this are noise, not news+const CHECK_MIN_MS = 3000 // rev checks closer together than this are the same event (focus + visibility)+const POLL_MS = 30000 // while the app is open and signed in, ask the server for its revision this oftenexport const DEF = {unit: 'kg', restSec: 90, restPauseSec: 15, sound: true, timerFlash: false, keepAwake: true, lang: 'en',theme: 'dark', accent: 'lime', body: 'male', targetW: null,@@ -106,10 +107,19 @@ export const useStore = create((set, get) => {let pulling = null // the GET in flight, so two resume signals make one requestlet pushPending = false // a change made before boot's pull — pushed once boot is throughlet forceNext = false // the next push replaces the server copy outright (import, reset)- let lastPull = 0+ let lastCheck = 0+ let pollTm = nullconst readSync = () => { try { return JSON.parse(localStorage.getItem(SYNC_KEY)) || null } catch { return null } }const writeSync = (rev, ts) => localStorage.setItem(SYNC_KEY, JSON.stringify({ rev, ts: ts || 0 }))+ // What the banner shows a signed-in user: `offline` when the server could not be reached at+ // all, `pending` while a change is still owed to it (either way, or a push the server refused).+ const setSync = patch => {+ const cur = get().sync+ const next = { ...cur, ...patch }+ if (next.offline !== cur.offline || next.pending !== cur.pending || next.lastSynced !== cur.lastSynced) set({ sync: next })+ }+ const isNetworkError = e => e && e.status == null // fetch itself failed: no response at allinitReminderSync(() => get().S)@@ -148,20 +158,39 @@ export const useStore = create((set, get) => {pushPending = false}- // The other side of the hidden-tab flush below: coming back — to the tab, the window, the app,- // the network — asks the server what happened meanwhile. A phone that sat in a pocket all- // afternoon and a desktop tab left open all week used to show, and then push, whatever they- // last had; now they catch up first. Throttled, since focus and visibility fire together.- const resumePull = (force = false) => {+ // A signed-in device shows what the server has. Coming back — to the tab, the window, the app,+ // the network — and every half minute while open, it asks the server for its revision (one+ // small GET) and fetches the document only when the number moved; a change still owed to the+ // server is pushed on the same occasion. A phone that sat in a pocket all afternoon and a+ // desktop tab left open all week used to show, and then push, whatever they last had.+ const checkRev = async (force = false) => {if (!get().user || !get().ready || document.visibilityState === 'hidden') return- if (!force && Date.now() - lastPull < PULL_MIN_MS) return- get().pullState()+ if (!force && Date.now() - lastCheck < CHECK_MIN_MS) return+ lastCheck = Date.now()+ if (pulling) return pulling+ const sync = readSync()+ const owed = localStorage.getItem('gym_dirty') === '1' || pushTm !== null || pushPending+ if (!sync || owed) return get().pullState()+ try {+ const { rev } = await api('/api/data/rev')+ setSync({ offline: false })+ if (rev !== sync.rev) return get().pullState()+ } catch (e) {+ if (e.status === 401) return+ if (isNetworkError(e)) setSync({ offline: true })+ else return get().pullState() // a server that lacks the route (older API) — the full pull knows the old protocol+ }+ }+ const schedulePoll = () => {+ clearTimeout(pollTm)+ pollTm = setTimeout(() => { checkRev(); schedulePoll() }, POLL_MS)}- document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') resumePull() })- window.addEventListener('focus', () => resumePull())- window.addEventListener('pageshow', e => { if (e.persisted) resumePull() })- window.addEventListener('online', () => resumePull(true)) // also retries a push that failed offline- onAppActive(() => resumePull())+ document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') checkRev() })+ window.addEventListener('focus', () => checkRev())+ window.addEventListener('pageshow', e => { if (e.persisted) checkRev() })+ window.addEventListener('online', () => checkRev(true)) // also retries a push that failed offline+ onAppActive(() => checkRev())+ schedulePoll()// Both copies changed: keep both sides' entries, let the newer copy decide the rest// (lib/sync-merge.js), and remember the server's revision so the push that follows is@@ -192,9 +221,17 @@ export const useStore = create((set, get) => {else writeSync(r.rev, S._ts)localStorage.removeItem('gym_dirty')toldTooLarge = false+ // Back from offline with changes that were waiting: say so once — the banner that promised+ // "syncs when you're back online" has just kept its word.+ const was = get().sync+ setSync({ offline: false, pending: false, lastSynced: Date.now() })+ if (was.offline && was.pending) {+ import('./useUI.js').then(({ useUI }) => useUI.getState().toast(t('Back online — synced with the server.'))).catch(() => {})+ }} catch (e) {// A session that is gone is boot's business (/api/me); the copy stays owed to the server.if (e.status === 401) { localStorage.setItem('gym_dirty', '1'); return }+ if (isNetworkError(e)) { localStorage.setItem('gym_dirty', '1'); setSync({ offline: true, pending: true }); return }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@@ -203,6 +240,7 @@ export const useStore = create((set, get) => {return doPush(attempt + 1)}localStorage.setItem('gym_dirty', '1')+ setSync({ offline: false, pending: true })// A 413 comes from the proxy in front of the API (nginx: client_max_body_size), which// caps the request body. Every later push is at least as big, so nothing reaches the// server until the limit is raised — said once per refusal streak; gym_dirty keeps the@@ -220,8 +258,7 @@ export const useStore = create((set, get) => {// (e.g. setting the reminder time then immediately backgrounding to test it). On mobile the// same applies to the file mirror — backgrounding is often the last thing before the OS// kills the app.- document.addEventListener('visibilitychange', () => {- if (document.visibilityState !== 'hidden') return+ const flush = () => {if (MOBILE && saveTm) {clearTimeout(saveTm)saveTm = null@@ -233,7 +270,9 @@ export const useStore = create((set, get) => {pushTm = nullget().pushState()}- })+ }+ document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') flush() })+ window.addEventListener('pagehide', flush) // Safari kills the home-screen app without a visibilitychange at times// The owner check in setUser only runs in the tab that signs in. Another tab of the same// browser still holding the previous profile would keep writing that profile's data over the@@ -267,6 +306,8 @@ export const useStore = create((set, get) => {S: (() => { const s = loadState(); registerCustom(s.customEx); return s })(),user: (() => { try { return JSON.parse(localStorage.getItem('gym_user')) || null } catch { return null } })(),ready: false,+ // Server sync as the banner sees it (components/SyncBanner.jsx). Only meaningful signed in.+ sync: { offline: false, pending: localStorage.getItem('gym_dirty') === '1', lastSynced: 0 },/* Instance capabilities from GET /api/config. `config.coach` is present only when the ownerhas both enabled the Coach and connected a provider — every Coach entry point in the apphangs off it via coachAvailable(), so an unconfigured instance renders exactly what it@@ -360,7 +401,8 @@ export const useStore = create((set, get) => {if (pushTm) { clearTimeout(pushTm); pushTm = null; await get().pushState() }else if (pushing) await pushingconst res = await api('/api/data')- lastPull = Date.now()+ lastCheck = Date.now()+ setSync({ offline: false })const { state, rev } = resconst S = get().S// Owed to the server: a push that failed, or a change made while boot was still pulling.@@ -393,12 +435,49 @@ export const useStore = create((set, get) => {mergeInto(S, state, rev)pushPending = falseawait get().pushState()- } catch (e) { /* offline — keep local */ }+ } catch (e) { if (isNetworkError(e)) setSync({ offline: true }) /* keep local; the poll retries */ }finally { pulling = null }})()return pulling},+ // Sign-in (and pairing a phone) takes the server's profile as this device's copy — the+ // profile is the truth for a signed-in user, whatever the timestamps say. The only thing+ // the device may add are the entries it logged while signed out: `ask(extras)` (a dialog,+ // supplied by the caller) decides whether those workouts, weigh-ins and custom exercises+ // are added to the profile or dropped. A profile with no state yet simply takes the+ // device's data, as creating a profile always did.+ async adoptProfile(ask) {+ if (pulling) await pulling+ const res = await api('/api/data') // a failure here is the caller's toast: sign-in needed the server anyway+ const { state, rev } = res+ const S = get().S+ setSync({ offline: false })+ if (!state) {+ localStorage.removeItem('gym_dirty')+ if (hasData(S)) { if (rev != null) writeSync(rev, 0); forceNext = true; await get().pushState() }+ else if (rev != null) writeSync(rev, 0)+ return { adopted: false, added: false }+ }+ const extras = localExtras(S, state)+ const keep = (extras.workouts || extras.bodyweight || extras.customEx) && typeof ask === 'function' ? await ask(extras) : false+ const serverCopy = Object.assign(clone(DEF), state, { active: S.active || null })+ if (keep) {+ const merged = Object.assign(clone(DEF), mergeStates(state, S, { prefer: 'a' }))+ merged.active = S.active || null+ persist(merged, false)+ if (rev != null) writeSync(rev, 0)+ else localStorage.removeItem(SYNC_KEY)+ await get().pushState()+ return { adopted: true, added: true }+ }+ localStorage.removeItem('gym_dirty')+ if (rev != null) adopt(serverCopy, rev)+ else { localStorage.removeItem(SYNC_KEY); persist(serverCopy, false, false) }+ setSync({ pending: false })+ return { adopted: true, added: false }+ },+async signOut() {try { await get().pushState(); await api('/api/logout', { method: 'POST', body: '{}' }) } catch (e) { /* */ }clearLocalSession()@@ -413,11 +492,11 @@ export const useStore = create((set, get) => {},// Redeems the pairing code shown in the browser (Settings → "Pair the mobile app") and// switches this device over to that account, same as signing in on the web does.- async connectToServer(url, code) {+ async connectToServer(url, code, ask) {const user = await connect(url, code) // throws on a bad URL/expired code — caller shows itget().setUser(user)await get().refreshConfig() // what this server offers (the Coach, guest mode) — see boot()- await get().pullState()+ await get().adoptProfile(ask)syncReminder(get().S)set({ needsMobileOnboarding: false })},diff --git a/frontend/src/views/Login.jsx b/frontend/src/views/Login.jsxindex 0df9748c1..f373ff762 100644--- a/frontend/src/views/Login.jsx+++ b/frontend/src/views/Login.jsx@@ -8,6 +8,7 @@ import { guestAllowed } from '../lib/guest.js'import { useState, useRef, useEffect } from 'react'import Icon from '../components/Icon.jsx'import { Button } from '../components/ui.jsx'+import { askAddDeviceData } from '../sheets.jsx'function RegisterSheet({ close }) {const { setUser, pushState, pullState, loadConfig } = useStore()@@ -47,11 +48,11 @@ function RegisterSheet({ close }) {}export default function Login() {- const { setUser, pullState, setGuest } = useStore()+ const { setUser, adoptProfile, setGuest } = useStore()const config = useStore(s => s.config)const canGuest = guestAllowed(config)const signIn = async () => {- try { const u = await passkeyLogin(); setUser(u); await pullState(); useUI.getState().toast(t('Welcome back, {0}', u.name)) }+ try { const u = await passkeyLogin(); setUser(u); await adoptProfile(askAddDeviceData); useUI.getState().toast(t('Welcome back, {0}', u.name)) }catch (e) { if (e.name !== 'NotAllowedError' && e.name !== 'AbortError') useUI.getState().toast(e.message || t('Sign-in failed')) }}const head = <>diff --git a/frontend/src/views/MobileOnboarding.jsx b/frontend/src/views/MobileOnboarding.jsxindex 45bf75ff8..7f0527aaf 100644--- a/frontend/src/views/MobileOnboarding.jsx+++ b/frontend/src/views/MobileOnboarding.jsx@@ -7,6 +7,7 @@ import { useUI } from '../store/useUI.js'import { t } from '../lib/i18n.js'import Icon from '../components/Icon.jsx'import { Button } from '../components/ui.jsx'+import { askAddDeviceData } from '../sheets.jsx'export function ConnectSheet({ close }) {const { connectToServer } = useStore()@@ -18,7 +19,7 @@ export function ConnectSheet({ close }) {const go = async () => {if (!url.trim() || !code.trim()) { useUI.getState().toast(t('Enter your server address and the code')); return }setBusy(true)- try { await connectToServer(url.trim(), code.trim()); close(); useUI.getState().toast(t('Connected')) }+ try { await connectToServer(url.trim(), code.trim(), askAddDeviceData); close(); useUI.getState().toast(t('Connected')) }catch (e) { useUI.getState().toast(e.message || t('Could not connect')) }finally { setBusy(false) }}diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsxindex 83d3d7e22..3b931a48f 100644--- a/frontend/src/views/Settings.jsx+++ b/frontend/src/views/Settings.jsx@@ -15,7 +15,7 @@ import { MOBILE, isAndroid, shareExport, syncReminder } from '../lib/mobile.js'import { checkForUpdate, downloadAndInstall } from '../lib/update.js'import { forgetCoach } from '../lib/coach-api.js'import { ConnectSheet } from './MobileOnboarding.jsx'-import { starterPlanSheet, confirmSheet, importFromApp, importFromHevy, equipmentProfileSheet, menuSheet } from '../sheets.jsx'+import { starterPlanSheet, confirmSheet, importFromApp, importFromHevy, equipmentProfileSheet, menuSheet, askAddDeviceData } from '../sheets.jsx'import Icon from '../components/Icon.jsx'import { Section, Row, SelectRow, Switch, Segmented, Button, TextField } from '../components/ui.jsx'@@ -24,7 +24,7 @@ export default function Settings() {const S = useStore(s => s.S)const user = useStore(s => s.user)const coachLocal = useStore(s => s.coachLocal)- const { update, replaceState, setUser, pullState, pushState, signOut, signOutAll, resetDemo, disconnectServer } = useStore()+ const { update, replaceState, setUser, pullState, pushState, adoptProfile, signOut, signOutAll, resetDemo, disconnectServer } = useStore()const toast = useUI(s => s.toast)const fileRef = useRef(null)const importRef = useRef(null)@@ -143,7 +143,7 @@ export default function Settings() {rd.readAsText(f)}const signInHere = async () => {- try { const u = await passkeyLogin(); setUser(u); await pullState(); toast(t('Welcome back, {0}', u.name)) }+ try { const u = await passkeyLogin(); setUser(u); await adoptProfile(askAddDeviceData); toast(t('Welcome back, {0}', u.name)) }catch (e) { if (e.name !== 'NotAllowedError' && e.name !== 'AbortError') toast(e.message || t('Sign-in failed')) }}const registerHere = () => useUI.getState().openSheet(close => <RegisterInline close={close} setUser={setUser} pushState={pushState} pullState={pullState} toast={toast} />)