frontend: #160 findings 1/2/9/10 — the local copy remembers its owner and is wiped when another profile signs in (open tabs follow), a copy adopted from the server keeps its timestamp, Reset everything says what it deletes and forgets the server-side Coach record, a 413 on sync is shown instead of swallowed

This commit is contained in:
Boris Kurktchiev committed 2026-09-11 10:23:13 -04:00
1 parent 6d9d7a6cba
commit 8b2fc43c8a
19 files changed
+490 -12

No files matched your search

+1 -1
View File
@@ -27,7 +27,7 @@ describe('Brazilian Portuguese locale', () => {
.sort(byCodeUnit)
const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(631)
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(633)
expect(inherited).toHaveLength(634)
// If this fails, review the changed keys and wording before accepting a new hash. From
// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list
+2
View File
@@ -344,6 +344,8 @@ export default {
'Reset everything?': 'Alles zurücksetzen?',
'Reset everything': 'Alles zurücksetzen',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Löscht Plan, Trainings und Körpergewicht auf diesem Gerät. Das kann nicht rückgängig gemacht werden.',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': 'Löscht Plan, Trainings und Körpergewicht aus deinem Profil auf diesem Server und auf allen angemeldeten Geräten. Das kann nicht rückgängig gemacht werden.',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': 'Synchronisierung fehlgeschlagen: Der Server hat den Upload als zu groß abgelehnt. Deine Änderungen sind noch nicht auf dem Server angekommen.',
'Delete everything': 'Alles löschen',
'All data reset': 'Alle Daten zurückgesetzt',
'Backup exported': 'Backup exportiert',
+2
View File
@@ -329,6 +329,8 @@ export default {
'Reset everything?': '¿Restablecer todo?',
'Reset everything': 'Restablecer todo',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Elimina tu plan, entrenamientos y peso corporal en este dispositivo. No se puede deshacer.',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': 'Elimina tu plan, entrenamientos y peso corporal de tu perfil en este servidor y en todos los dispositivos con sesión iniciada. No se puede deshacer.',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': 'Error de sincronización: el servidor rechazó la subida por ser demasiado grande. Tus cambios no han llegado al servidor.',
'Delete everything': 'Eliminar todo',
'All data reset': 'Todos los datos restablecidos',
'Backup exported': 'Copia exportada',
+2
View File
@@ -329,6 +329,8 @@ export default {
'Reset everything?': 'Tout réinitialiser ?',
'Reset everything': 'Tout réinitialiser',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Supprime ton plan, tes séances et ton poids corporel sur cet appareil. Irréversible.',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': 'Supprime ton plan, tes séances et ton poids corporel de ton profil sur ce serveur et sur tous les appareils connectés. Irréversible.',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': 'Échec de la synchronisation : le serveur a refusé l’envoi, trop volumineux. Tes modifications n’ont pas atteint le serveur.',
'Delete everything': 'Tout supprimer',
'All data reset': 'Toutes les données réinitialisées',
'Backup exported': 'Sauvegarde exportée',
+2
View File
@@ -329,6 +329,8 @@ export default {
'Reset everything?': 'सब कुछ रीसेट करें?',
'Reset everything': 'सब कुछ रीसेट करें',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'इस डिवाइस पर आपकी योजना, वर्कआउट और वज़न हट जाएँगे। इसे पूर्ववत नहीं किया जा सकता।',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': 'इस सर्वर पर आपकी प्रोफ़ाइल से और साइन इन किए हुए सभी डिवाइस से आपकी योजना, वर्कआउट और वज़न हट जाएँगे। इसे पूर्ववत नहीं किया जा सकता।',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': 'सिंक विफल: सर्वर ने अपलोड को बहुत बड़ा बताकर अस्वीकार कर दिया। आपके बदलाव सर्वर तक नहीं पहुँचे हैं।',
'Delete everything': 'सब हटाएँ',
'All data reset': 'सारा डेटा रीसेट',
'Backup exported': 'बैकअप निर्यात हुआ',
+2
View File
@@ -335,6 +335,8 @@ export default {
'Reset everything?': 'Mindent visszaállítasz?',
'Reset everything': 'Minden visszaállítása',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Törli a terved, edzéseid és testsúlyod ezen az eszközön. Ez nem vonható vissza.',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': 'Törli a terved, edzéseid és testsúlyod a profilodból ezen a szerveren és minden bejelentkezett eszközön. Ez nem vonható vissza.',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': 'A szinkronizálás nem sikerült: a szerver túl nagynak találta a feltöltést és elutasította. A módosításaid nem jutottak el a szerverre.',
'Delete everything': 'Minden törlése',
'All data reset': 'Minden adat visszaállítva',
'Backup exported': 'Biztonsági mentés exportálva',
+2
View File
@@ -329,6 +329,8 @@ export default {
'Reset everything?': 'Azzerare tutto?',
'Reset everything': 'Azzera tutto',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Elimina piano, allenamenti e peso corporeo su questo dispositivo. Irreversibile.',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': 'Elimina piano, allenamenti e peso corporeo dal tuo profilo su questo server e su tutti i dispositivi connessi. Irreversibile.',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': 'Sincronizzazione fallita: il server ha rifiutato il caricamento perché troppo grande. Le tue modifiche non hanno raggiunto il server.',
'Delete everything': 'Elimina tutto',
'All data reset': 'Tutti i dati azzerati',
'Backup exported': 'Backup esportato',
+2
View File
@@ -329,6 +329,8 @@ export default {
'Reset everything?': '전부 초기화할까요?',
'Reset everything': '전부 초기화',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': '이 기기의 계획, 운동, 체중을 삭제합니다. 되돌릴 수 없어요.',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': '이 서버의 프로필과 로그인된 모든 기기에서 계획, 운동, 체중을 삭제합니다. 되돌릴 수 없어요.',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': '동기화 실패: 서버가 업로드가 너무 크다며 거부했습니다. 변경 내용이 서버에 반영되지 않았습니다.',
'Delete everything': '전부 삭제',
'All data reset': '모든 데이터 초기화됨',
'Backup exported': '백업 내보냄',
+2
View File
@@ -329,6 +329,8 @@ export default {
'Reset everything?': 'Zresetować wszystko?',
'Reset everything': 'Zresetuj wszystko',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Usuwa plan, treningi i masę ciała na tym urządzeniu. Nie można tego cofnąć.',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': 'Usuwa plan, treningi i masę ciała z profilu na tym serwerze i ze wszystkich zalogowanych urządzeń. Nie można tego cofnąć.',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': 'Synchronizacja nie powiodła się: serwer odrzucił przesyłanie jako zbyt duże. Twoje zmiany nie dotarły na serwer.',
'Delete everything': 'Usuń wszystko',
'All data reset': 'Wszystkie dane zresetowane',
'Backup exported': 'Kopia wyeksportowana',
+2
View File
@@ -114,6 +114,8 @@ export const PT_BR_OVERRIDES = {
'Reset everything?': 'Redefinir tudo?',
'Reset everything': 'Redefinir tudo',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Exclui seu plano, seus treinos e seu peso corporal deste dispositivo. Esta ação não pode ser desfeita.',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': 'Exclui seu plano, seus treinos e seu peso corporal do seu perfil neste servidor e de todos os dispositivos conectados. Esta ação não pode ser desfeita.',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': 'A sincronização falhou: o servidor recusou o envio por ser grande demais. Suas alterações não chegaram ao servidor.',
'Delete everything': 'Excluir tudo',
'Backup exported': 'Backup exportado',
'Import backup?': 'Importar backup?',
+2
View File
@@ -329,6 +329,8 @@ export default {
'Reset everything?': 'Repor tudo?',
'Reset everything': 'Repor tudo',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Elimina o teu plano, treinos e peso corporal neste dispositivo. Não pode ser anulado.',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': 'Elimina o teu plano, treinos e peso corporal do teu perfil neste servidor e em todos os dispositivos com sessão iniciada. Não pode ser anulado.',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': 'A sincronização falhou: o servidor recusou o envio por ser demasiado grande. As tuas alterações não chegaram ao servidor.',
'Delete everything': 'Eliminar tudo',
'All data reset': 'Todos os dados repostos',
'Backup exported': 'Cópia exportada',
+2
View File
@@ -329,6 +329,8 @@ export default {
'Reset everything?': 'Сбросить всё?',
'Reset everything': 'Сбросить всё',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Удаляет план, тренировки и вес тела на этом устройстве. Отменить нельзя.',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': 'Удаляет план, тренировки и вес тела из профиля на этом сервере и со всех устройств, где выполнен вход. Отменить нельзя.',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': 'Синхронизация не удалась: сервер отклонил загрузку как слишком большую. Твои изменения не дошли до сервера.',
'Delete everything': 'Удалить всё',
'All data reset': 'Все данные сброшены',
'Backup exported': 'Копия экспортирована',
+2
View File
@@ -335,6 +335,8 @@ export default {
'Reset everything?': 'รีเซ็ตทุกอย่าง?',
'Reset everything': 'รีเซ็ตทุกอย่าง',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'จะลบแผน, การออกกำลังกาย และน้ำหนักตัวบนเครื่องนี้ ไม่สามารถย้อนกลับได้',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': 'จะลบแผน, การออกกำลังกาย และน้ำหนักตัวออกจากโปรไฟล์ของคุณบนเซิร์ฟเวอร์นี้ และจากทุกอุปกรณ์ที่เข้าสู่ระบบอยู่ ไม่สามารถย้อนกลับได้',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': 'ซิงค์ไม่สำเร็จ: เซิร์ฟเวอร์ปฏิเสธการอัปโหลดเพราะข้อมูลใหญ่เกินไป การเปลี่ยนแปลงของคุณยังไม่ถึงเซิร์ฟเวอร์',
'Delete everything': 'ลบทุกอย่าง',
'All data reset': 'รีเซ็ตข้อมูลทั้งหมดแล้ว',
'Backup exported': 'ส่งออกข้อมูลสำรองแล้ว',
+2
View File
@@ -329,6 +329,8 @@ export default {
'Reset everything?': 'Her şey sıfırlansın mı?',
'Reset everything': 'Her şeyi sıfırla',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Bu cihazdaki planını, antrenmanlarını ve vücut ağırlığını siler. Geri alınamaz.',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': 'Bu sunucudaki profilinden ve oturum açılmış tüm cihazlardan planını, antrenmanlarını ve vücut ağırlığını siler. Geri alınamaz.',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': 'Eşitleme başarısız: sunucu yüklemeyi çok büyük diye reddetti. Değişikliklerin sunucuya ulaşmadı.',
'Delete everything': 'Her şeyi sil',
'All data reset': 'Tüm veriler sıfırlandı',
'Backup exported': 'Yedek dışa aktarıldı',
+2
View File
@@ -329,6 +329,8 @@ export default {
'Reset everything?': '重置所有内容?',
'Reset everything': '重置所有内容',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': '删除本设备上的计划、训练和体重。无法撤销。',
'Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.': '从此服务器上的档案以及所有已登录设备中删除计划、训练和体重。无法撤销。',
'Sync failed: the server refused the upload as too large. Your changes have not reached the server.': '同步失败:服务器拒绝了上传,内容过大。你的更改尚未同步到服务器。',
'Delete everything': '全部删除',
'All data reset': '所有数据已重置',
'Backup exported': '备份已导出',
+58 -9
View File
@@ -1,6 +1,7 @@
import { create } from 'zustand'
import { api, setRemoteAuth } from '../lib/api.js'
import { localTZ } from '../lib/format.js'
import { t } from '../lib/i18n.js'
import { registerCustom } from '../lib/exercises.js'
import { DEMO, DEMO_SEEDED } from '../lib/demo.js'
import { guestAllowed } from '../lib/guest.js'
@@ -92,6 +93,7 @@ export function restoredStateFor(local, remote, dirty = false) {
export const useStore = create((set, get) => {
let pushTm = null
let saveTm = null
let toldTooLarge = false
initReminderSync(() => get().S)
@@ -102,8 +104,12 @@ export const useStore = create((set, get) => {
saveTm = setTimeout(() => { saveTm = null; nativeSave(get().S); syncReminder(get().S) }, 800)
}
const persist = (S, push = true) => {
S._ts = Date.now()
// `_ts` is when this device last changed the data — it decides which copy wins on the next
// pull (restoredStateFor). A copy merely adopted from the server or the file mirror keeps the
// stamp it came with: re-stamping a read would make an unchanged copy look newer than a real
// change made on another device, and push it over that change.
const persist = (S, push = true, stamp = true) => {
if (stamp) S._ts = Date.now()
registerCustom(S.customEx)
localStorage.setItem(KEY, JSON.stringify(S))
set({ S })
@@ -133,13 +139,31 @@ export const useStore = create((set, get) => {
}
})
// Everything a sign-out leaves behind on this device, whichever way it was triggered.
// 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
// shared copy and push it under the new session's cookie — so it drops the profile, and
// whoever signs in there passes the same check. The owner key is written last on both a
// sign-in and a sign-out, so on a new owner the copy in storage is already the wiped one; with
// no owner (a sign-out) this tab falls back to defaults rather than read the key at all — the
// previous profile's data must not stay here whichever key's event lands first.
window.addEventListener('storage', e => {
if (e.key !== 'gym_owner') return
const user = get().user
if (!user || e.newValue === user.id) return
clearTimeout(pushTm)
pushTm = null
set({ user: null, S: e.newValue ? loadState() : clone(DEF) })
})
// Everything a sign-out leaves behind on this device, whichever way it was triggered. The owner
// goes last, after the wiped copy is written — the storage listener above relies on the order.
const clearLocalSession = () => {
get().setUser(null)
localStorage.removeItem('gym_guest')
localStorage.removeItem('gym_dirty')
localStorage.removeItem(KEY)
persist(clone(DEF), false)
localStorage.removeItem('gym_owner')
}
return {
@@ -194,16 +218,41 @@ export const useStore = create((set, get) => {
},
setUser(u) {
if (u) { localStorage.setItem('gym_user', JSON.stringify(u)); localStorage.removeItem('gym_guest') }
else localStorage.removeItem('gym_user')
if (u) {
// The local copy belongs to whoever last signed in here. When a session expires or is
// revoked elsewhere, boot() only drops the user and the data stays; a different profile
// signing in next must not inherit it (pullState would push it into that account, and
// carry the in-progress workout along). A proper sign-out clears the owner, so a guest's
// data still moves into a freshly created profile.
const owner = localStorage.getItem('gym_owner')
if (owner && owner !== u.id) {
localStorage.removeItem('gym_dirty')
localStorage.removeItem(KEY)
persist(clone(DEF), false)
}
localStorage.setItem('gym_owner', u.id)
localStorage.setItem('gym_user', JSON.stringify(u)); localStorage.removeItem('gym_guest')
} else localStorage.removeItem('gym_user')
set({ user: u })
},
async pushState() {
if (!get().user) return
clearTimeout(pushTm)
try { await api('/api/data', { method: 'PUT', body: JSON.stringify({ state: get().S }) }); localStorage.removeItem('gym_dirty') }
catch (e) { localStorage.setItem('gym_dirty', '1') }
try { await api('/api/data', { method: 'PUT', body: JSON.stringify({ state: get().S }) }); localStorage.removeItem('gym_dirty'); toldTooLarge = false }
catch (e) {
localStorage.setItem('gym_dirty', '1')
// 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
// retries going. useUI imports this store, hence the lazy import.
if (e.status === 413 && !toldTooLarge) {
toldTooLarge = true
import('./useUI.js')
.then(({ useUI }) => useUI.getState().toast(t('Sync failed: the server refused the upload as too large. Your changes have not reached the server.')))
.catch(() => {})
}
}
},
async pullState() {
try {
@@ -212,7 +261,7 @@ export const useStore = create((set, get) => {
const dirty = localStorage.getItem('gym_dirty') === '1'
const restored = restoredStateFor(S, state, dirty)
if (restored) {
persist(restored, false)
persist(restored, false, false)
} else if (hasData(S)) { await get().pushState() }
} catch (e) { /* offline — keep local */ }
},
@@ -297,7 +346,7 @@ export const useStore = create((set, get) => {
const saved = await nativeLoad()
const S = get().S
if (saved && (!hasData(S) || (saved._ts || 0) >= (S._ts || 0))) {
persist(Object.assign(clone(DEF), saved), false)
persist(Object.assign(clone(DEF), saved), false, false)
} else if (hasData(S)) {
nativeSave(S) // first run after an update from a file-less version: seed the mirror
}
+229 -1
View File
@@ -3,12 +3,18 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('../lib/api.js', () => ({ api: vi.fn() }))
// pushState reaches the toast through a lazy import of useUI (which imports this store) — the
// tests only need to see that it was asked, not a rendered toast.
const { toast } = vi.hoisted(() => ({ toast: vi.fn() }))
vi.mock('./useUI.js', () => ({ useUI: { getState: () => ({ toast }) } }))
import { api } from '../lib/api.js'
import { DEF, restoredStateFor, useStore } from './useStore.js'
import { DEF, hasData, restoredStateFor, useStore } from './useStore.js'
const clone = value => JSON.parse(JSON.stringify(value))
const routine = id => ({ id, name: id, ex: [] })
const workout = id => ({ id, d: '2026-09-01', entries: [] })
const httpError = status => Object.assign(new Error('HTTP ' + status), { status })
beforeEach(() => {
localStorage.clear()
@@ -104,4 +110,226 @@ describe('saved workout state sync and restore', () => {
expect(useStore.getState().S.routines.map(r => r.id)).toEqual(['local'])
expect(api).toHaveBeenCalledTimes(1)
})
it('an adopted server state keeps the timestamp it came with', async () => {
const remote = { ...clone(DEF), _ts: 20, routines: [routine('remote')] }
useStore.setState({ S: clone(DEF), user: { id: 'user-1' }, ready: true })
api.mockResolvedValue({ state: remote })
await useStore.getState().pullState()
expect(useStore.getState().S._ts).toBe(20)
expect(JSON.parse(localStorage.getItem('gym_state_v1'))._ts).toBe(20)
})
// Device B logs a workout at T1 and pushes it 1.5 s later; device A reloads inside that window
// and adopts the server copy from T0 < T1. If adopting re-stamped A's copy with its own clock,
// A's next reload would see the server (T1) as older and push its stale copy over B's workout.
it('an unchanged adopted copy does not push over a newer change from another device', async () => {
useStore.setState({ S: clone(DEF), user: { id: 'user-1' }, ready: true })
api.mockResolvedValueOnce({ state: { ...clone(DEF), _ts: 1000000, workouts: [workout('w1')] } })
await useStore.getState().pullState()
expect(useStore.getState().S.workouts.map(w => w.id)).toEqual(['w1'])
api.mockResolvedValueOnce({ state: { ...clone(DEF), _ts: 1010000, workouts: [workout('w1'), workout('w2-from-B')] } })
await useStore.getState().pullState()
expect(api).toHaveBeenCalledTimes(2)
expect(api.mock.calls.every(([, opts]) => !opts)).toBe(true) // two GETs, no PUT
expect(useStore.getState().S.workouts.map(w => w.id)).toEqual(['w1', 'w2-from-B'])
expect(useStore.getState().S._ts).toBe(1010000)
})
})
// The saved copy is owned by whoever last signed in on this device. An expired or revoked session
// only drops the user (boot's 401 path), so the data is still here when the next profile signs in.
describe('signing in as a different profile', () => {
const active = { id: 'A-active', d: '2026-09-01', routineId: 'A', name: 'A', entries: [] }
const signInAsAThenExpire = () => {
useStore.getState().setUser({ id: 'A', name: 'A' })
useStore.getState().replaceState({ ...clone(DEF), _ts: 20, routines: [routine('A-routine')], bodyweight: [{ d: '2026-09-01', kg: 80 }], active })
useStore.getState().setUser(null)
expect(hasData(useStore.getState().S)).toBe(true)
}
it('does not move the previous profile data into a brand-new account', async () => {
signInAsAThenExpire()
api.mockResolvedValue({ state: null })
useStore.getState().setUser({ id: 'B', name: 'B' })
await useStore.getState().pullState()
expect(api).toHaveBeenCalledTimes(1) // the GET only — nothing was pushed under B
expect(useStore.getState().S.routines).toEqual([])
expect(useStore.getState().S.bodyweight).toEqual([])
expect(useStore.getState().S.active).toBeNull()
expect(JSON.parse(localStorage.getItem('gym_state_v1')).routines).toEqual([])
expect(localStorage.getItem('gym_owner')).toBe('B')
})
it('adopts the new profile own state even when it is older or a push failed after expiry', async () => {
signInAsAThenExpire()
localStorage.setItem('gym_dirty', '1') // a debounced push that hit the 401
const remoteB = { ...clone(DEF), _ts: 10, routines: [routine('B-routine')], active: null }
api.mockResolvedValue({ state: remoteB })
useStore.getState().setUser({ id: 'B', name: 'B' })
await useStore.getState().pullState()
expect(api).toHaveBeenCalledTimes(1)
expect(useStore.getState().S.routines.map(r => r.id)).toEqual(['B-routine'])
expect(useStore.getState().S.active).toBeNull() // A's in-progress workout is not carried over
expect(localStorage.getItem('gym_dirty')).toBeNull()
})
it('the same profile signing in again keeps and pushes its newer local copy', async () => {
signInAsAThenExpire()
api.mockResolvedValueOnce({ state: { ...clone(DEF), _ts: 10, routines: [routine('remote')] } }).mockResolvedValueOnce({})
useStore.getState().setUser({ id: 'A', name: 'A' })
await useStore.getState().pullState()
expect(api).toHaveBeenCalledTimes(2)
expect(JSON.parse(api.mock.calls[1][1].body).state.routines.map(r => r.id)).toEqual(['A-routine'])
expect(useStore.getState().S.active).toEqual(active)
})
// The check above runs in the tab that signs in. A second tab of the same browser still holding
// A learns about B through the storage event the sign-in fires.
it('a tab still holding the previous profile drops it when another profile signs in elsewhere', async () => {
vi.useFakeTimers()
try {
useStore.getState().setUser({ id: 'A', name: 'A' })
useStore.getState().replaceState({ ...clone(DEF), _ts: 20, routines: [routine('A-routine')], active }, true) // arms a push
api.mockResolvedValue({})
// B's setUser in the other tab: it wiped the copy, wrote defaults, then recorded the owner.
// B's own data only lands there after its pull — this tab never re-reads it.
localStorage.setItem('gym_state_v1', JSON.stringify({ ...clone(DEF), _ts: 30 }))
localStorage.setItem('gym_owner', 'B')
window.dispatchEvent(new StorageEvent('storage', { key: 'gym_owner', oldValue: 'A', newValue: 'B' }))
expect(useStore.getState().user).toBeNull()
expect(hasData(useStore.getState().S)).toBe(false)
expect(useStore.getState().S.active).toBeNull()
vi.advanceTimersByTime(3000) // the push armed under A must not fire under B's cookie
useStore.getState().update(s => { s.routines.push(routine('typed-after')) })
vi.advanceTimersByTime(3000)
await useStore.getState().pushState()
expect(api).not.toHaveBeenCalled()
expect(JSON.parse(localStorage.getItem('gym_state_v1')).routines.map(r => r.id)).toEqual(['typed-after'])
} finally { vi.useRealTimers() }
})
// A sign-out elsewhere removes the owner. Storage events arrive per key, so this tab may see
// the owner go while gym_state_v1 still holds A's copy — it must not keep that copy either way.
it('a tab still holding the previous profile drops its data when that profile signs out elsewhere', async () => {
useStore.getState().setUser({ id: 'A', name: 'A' })
useStore.getState().replaceState({ ...clone(DEF), _ts: 20, routines: [routine('A-routine')], bodyweight: [{ d: '2026-09-01', kg: 80 }], active })
api.mockResolvedValue({ state: null })
localStorage.removeItem('gym_owner') // gym_state_v1 still holds A's copy at this instant
window.dispatchEvent(new StorageEvent('storage', { key: 'gym_owner', oldValue: 'A', newValue: null }))
expect(useStore.getState().user).toBeNull()
expect(hasData(useStore.getState().S)).toBe(false)
expect(useStore.getState().S.active).toBeNull()
useStore.getState().setUser({ id: 'C', name: 'C' })
await useStore.getState().pullState()
expect(api).toHaveBeenCalledTimes(1) // the GET only — nothing of A's was pushed under C
expect(api.mock.calls[0][1]).toBeUndefined()
expect(hasData(useStore.getState().S)).toBe(false)
})
// The listener above reacts to the owner key alone, so the wiped copy has to be in storage
// before the owner is removed — the same order setUser uses when it records a new owner.
it('signing out removes the owner only after the wiped copy is written', async () => {
useStore.getState().setUser({ id: 'A', name: 'A' })
useStore.getState().replaceState({ ...clone(DEF), _ts: 20, routines: [routine('A-routine')] })
api.mockResolvedValue({})
const desc = Object.getOwnPropertyDescriptor(globalThis, 'localStorage')
const real = globalThis.localStorage
const writes = []
const recording = new Proxy(real, {
get(target, prop) {
const v = Reflect.get(target, prop)
if (prop === 'setItem' || prop === 'removeItem') return (...args) => { writes.push(prop + ' ' + args[0]); return v.apply(target, args) }
return typeof v === 'function' ? v.bind(target) : v
},
})
Object.defineProperty(globalThis, 'localStorage', { value: recording, configurable: true })
try { await useStore.getState().signOut() }
finally { Object.defineProperty(globalThis, 'localStorage', desc) }
expect(globalThis.localStorage).toBe(real)
expect(writes).toContain('removeItem gym_owner')
expect(writes.lastIndexOf('removeItem gym_owner')).toBeGreaterThan(writes.lastIndexOf('setItem gym_state_v1'))
expect(writes.lastIndexOf('removeItem gym_owner')).toBeGreaterThan(writes.lastIndexOf('removeItem gym_state_v1'))
expect(localStorage.getItem('gym_owner')).toBeNull()
expect(JSON.parse(localStorage.getItem('gym_state_v1')).routines).toEqual([])
})
it('a storage event for another key or the same profile changes nothing', () => {
useStore.getState().setUser({ id: 'A', name: 'A' })
useStore.getState().replaceState({ ...clone(DEF), _ts: 20, routines: [routine('A-routine')] })
window.dispatchEvent(new StorageEvent('storage', { key: 'gym_state_v1', newValue: '{}' }))
window.dispatchEvent(new StorageEvent('storage', { key: 'gym_owner', oldValue: 'A', newValue: 'A' }))
expect(useStore.getState().user).toEqual({ id: 'A', name: 'A' })
expect(useStore.getState().S.routines.map(r => r.id)).toEqual(['A-routine'])
})
it('guest data built after a sign-out still moves into a newly created profile', async () => {
api.mockResolvedValue({})
useStore.getState().setUser({ id: 'A', name: 'A' })
await useStore.getState().signOut()
expect(localStorage.getItem('gym_owner')).toBeNull()
expect(hasData(useStore.getState().S)).toBe(false)
useStore.getState().update(s => { s.routines.push(routine('guest')) }, false)
api.mockClear()
useStore.getState().setUser({ id: 'B', name: 'B' })
expect(hasData(useStore.getState().S)).toBe(true) // what the register sheet checks before pushing
await useStore.getState().pushState()
expect(api).toHaveBeenCalledTimes(1)
expect(api.mock.calls[0][1].method).toBe('PUT')
expect(JSON.parse(api.mock.calls[0][1].body).state.routines.map(r => r.id)).toEqual(['guest'])
})
})
describe('push failures', () => {
it('says once that the server refused the upload as too large, and keeps the copy dirty', async () => {
useStore.setState({ S: { ...clone(DEF), routines: [routine('local')] }, user: { id: 'user-1' }, ready: true })
api.mockRejectedValueOnce(httpError(401))
await useStore.getState().pushState()
expect(localStorage.getItem('gym_dirty')).toBe('1')
expect(toast).not.toHaveBeenCalled()
api.mockRejectedValueOnce(httpError(413))
await useStore.getState().pushState()
await vi.waitFor(() => expect(toast).toHaveBeenCalledTimes(1))
expect(toast.mock.calls[0][0]).toMatch(/too large/)
expect(localStorage.getItem('gym_dirty')).toBe('1')
api.mockRejectedValueOnce(httpError(413))
await useStore.getState().pushState()
await new Promise(r => setTimeout(r, 0))
expect(toast).toHaveBeenCalledTimes(1)
// A push that goes through ends the streak: the next refusal is news again.
api.mockResolvedValueOnce({})
await useStore.getState().pushState()
expect(localStorage.getItem('gym_dirty')).toBeNull()
api.mockRejectedValueOnce(httpError(413))
await useStore.getState().pushState()
await vi.waitFor(() => expect(toast).toHaveBeenCalledTimes(2))
})
})
+21 -1
View File
@@ -13,6 +13,7 @@ import { t, LANGS, INSTR_LANGS } from '../lib/i18n.js'
import { DEMO, REPO } from '../lib/demo.js'
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 Icon from '../components/Icon.jsx'
@@ -158,6 +159,25 @@ export default function Settings() {
catch (e) { toast(t('Could not sign out everywhere — you are still signed in.')) }
},
})
// Signed in, the empty state is pushed to the profile like any other change, so the wipe
// reaches the server and every device that syncs with it — the dialog has to say so. The Coach
// keeps its data outside S in two homes that can both be in use on one phone: a file per
// profile on the server, and — when it runs with the phone's own key — a file on the device.
// Each is cleared on its own; forgetCoach() alone would pick one by mode. A failed call must
// not stop the reset.
const resetEverything = () => confirmSheet({
title: t('Reset everything?'),
message: user
? t('Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.')
: t('Deletes your plan, workouts and body weight on this device. This cannot be undone.'),
confirmText: t('Delete everything'), danger: true,
onConfirm: () => {
if (user) api('/api/coach/forget', { method: 'POST', body: '{}' }).catch(() => {})
if (coachLocal?.mode === 'byok') forgetCoach().catch(() => {})
replaceState(JSON.parse(JSON.stringify(DEF)), true)
nav('/home'); toast(t('All data reset'))
},
})
return <div className="narrow">
<div className="hdr">
@@ -350,7 +370,7 @@ export default function Settings() {
subtitle={t('Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.')}>
<Switch checked={!!S.autoBackup} onChange={v => update(s => { s.autoBackup = v })} />
</Row>}
<Row icon="trash" iconTint="var(--red)" title={t('Reset everything')} danger onClick={() => confirmSheet({ title: t('Reset everything?'), message: t('Deletes your plan, workouts and body weight on this device. This cannot be undone.'), confirmText: t('Delete everything'), danger: true, onConfirm: () => { replaceState(JSON.parse(JSON.stringify(DEF)), true); nav('/home'); toast(t('All data reset')) } })} />
<Row icon="trash" iconTint="var(--red)" title={t('Reset everything')} danger onClick={resetEverything} />
</Section>
<input ref={fileRef} type="file" accept=".json,application/json" style={{ display: 'none' }} onChange={doImport} />
{/* Reset after reading so picking the same file twice still fires onChange. */}
+153
View File
@@ -0,0 +1,153 @@
// @vitest-environment happy-dom
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import Settings from './Settings.jsx'
globalThis.IS_REACT_ACT_ENVIRONMENT = true
// "Reset everything" is one dialog with two truths. A guest's data lives in this browser only.
// A signed-in profile pushes the empty state to the server like any other change, so the wipe
// reaches every device that syncs with it — and the Coach's own files have to go too: the
// per-profile one on the server, and the device one when the Coach runs with the phone's own key.
const mocks = vi.hoisted(() => {
const state = { S: null, user: null, coachLocal: null }
state.replaceState = vi.fn()
state.confirmSheet = vi.fn()
state.forgetCoach = vi.fn(() => Promise.resolve({ ok: true }))
state.api = vi.fn(() => Promise.resolve({ ok: true }))
state.toast = vi.fn()
state.snapshot = () => ({
S: state.S,
user: state.user,
coachLocal: state.coachLocal,
update: mut => {
const next = structuredClone(state.S)
mut(next)
state.S = next
},
replaceState: state.replaceState, setUser: vi.fn(), pullState: vi.fn(), pushState: vi.fn(),
signOut: vi.fn(), signOutAll: vi.fn(), resetDemo: vi.fn(), disconnectServer: vi.fn(),
})
return state
})
vi.mock('../store/useStore.js', () => {
const useStore = selector => selector ? selector(mocks.snapshot()) : mocks.snapshot()
useStore.getState = mocks.snapshot
return { useStore, DEF: { reminder: { time: '17:30' }, workouts: [] }, hasData: () => false }
})
vi.mock('../store/useUI.js', () => {
const snap = () => ({ toast: (...a) => mocks.toast(...a), openSheet: vi.fn() })
const useUI = selector => selector ? selector(snap()) : snap()
useUI.getState = snap
return { useUI }
})
vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
vi.mock('../lib/api.js', () => ({
api: (...a) => mocks.api(...a), webauthnOK: () => false, passkeyLogin: vi.fn(), passkeyRegister: vi.fn(), IS_ANDROID: false,
}))
vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() }))
vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))
vi.mock('../lib/mobile.js', () => ({ MOBILE: false, isAndroid: () => Promise.resolve(false), shareExport: vi.fn(), syncReminder: vi.fn() }))
vi.mock('../lib/coach-api.js', () => ({ forgetCoach: (...a) => mocks.forgetCoach(...a) }))
vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
vi.mock('../sheets.jsx', () => ({
starterPlanSheet: vi.fn(), confirmSheet: (...a) => mocks.confirmSheet(...a), importFromApp: vi.fn(),
importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(), menuSheet: vi.fn(),
}))
globalThis.__APP_VERSION__ ??= 'test'
let host, root
beforeEach(() => {
mocks.S = {
unit: 'kg', restSec: 90, restPauseSec: 15, sound: false, effort: 'none',
gifSize: 'full', workouts: [], routines: [], exWeights: {},
}
mocks.user = null
mocks.coachLocal = null
mocks.replaceState.mockClear()
mocks.confirmSheet.mockClear()
mocks.forgetCoach.mockClear()
mocks.api.mockClear()
mocks.toast.mockClear()
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
})
afterEach(() => {
act(() => root.unmount())
host.remove()
})
const mount = () => act(() => root.render(<Settings />))
const resetRow = () => [...host.querySelectorAll('.lrow')].find(r => r.textContent.includes('Reset everything'))
const openDialog = () => {
act(() => { resetRow().click() })
expect(mocks.confirmSheet).toHaveBeenCalledTimes(1)
return mocks.confirmSheet.mock.calls[0][0]
}
const serverForgetCalls = () => mocks.api.mock.calls.filter(([path]) => path === '/api/coach/forget')
describe('Settings — reset everything', () => {
it('guest: says the wipe is local, resets to the defaults, never calls the Coach', () => {
mount()
const dialog = openDialog()
expect(dialog.title).toBe('Reset everything?')
expect(dialog.message).toBe('Deletes your plan, workouts and body weight on this device. This cannot be undone.')
act(() => { dialog.onConfirm() })
expect(mocks.replaceState).toHaveBeenCalledTimes(1)
expect(mocks.replaceState.mock.calls[0]).toEqual([{ reminder: { time: '17:30' }, workouts: [] }, true])
expect(serverForgetCalls()).toHaveLength(0)
expect(mocks.forgetCoach).not.toHaveBeenCalled()
expect(mocks.toast).toHaveBeenCalledWith('All data reset')
})
it('signed in: says the wipe reaches the server and every device, and forgets the Coach on the server too', () => {
mocks.user = { uid: 'u1', name: 'Ana' }
mount()
const dialog = openDialog()
expect(dialog.message).toBe('Deletes your plan, workouts and body weight from your profile on this server and on every signed-in device. This cannot be undone.')
act(() => { dialog.onConfirm() })
expect(serverForgetCalls()).toHaveLength(1)
expect(serverForgetCalls()[0][1]).toEqual({ method: 'POST', body: '{}' })
expect(mocks.forgetCoach).not.toHaveBeenCalled() // no device Coach here
expect(mocks.replaceState).toHaveBeenCalledTimes(1)
expect(mocks.replaceState.mock.calls[0][1]).toBe(true)
expect(mocks.toast).toHaveBeenCalledWith('All data reset')
})
it('signed in: a failing Coach call does not block the reset', async () => {
mocks.user = { uid: 'u1', name: 'Ana' }
mocks.api.mockRejectedValueOnce(new Error('offline'))
mount()
const dialog = openDialog()
await act(async () => { dialog.onConfirm(); await Promise.resolve() })
expect(serverForgetCalls()).toHaveLength(1)
expect(mocks.replaceState).toHaveBeenCalledTimes(1)
expect(mocks.toast).toHaveBeenCalledWith('All data reset')
})
// A paired phone running the Coach with its own key has Coach data in both homes.
it('paired phone with its own key: clears the Coach on the server and on the device', () => {
mocks.user = { uid: 'u1', name: 'Ana' }
mocks.coachLocal = { mode: 'byok', provider: 'anthropic' }
mount()
const dialog = openDialog()
act(() => { dialog.onConfirm() })
expect(serverForgetCalls()).toHaveLength(1)
expect(mocks.forgetCoach).toHaveBeenCalledTimes(1)
expect(mocks.replaceState).toHaveBeenCalledTimes(1)
expect(mocks.toast).toHaveBeenCalledWith('All data reset')
})
it('own key, no server: clears the device Coach without touching the server', () => {
mocks.coachLocal = { mode: 'byok', provider: 'anthropic' }
mount()
const dialog = openDialog()
act(() => { dialog.onConfirm() })
expect(serverForgetCalls()).toHaveLength(0)
expect(mocks.forgetCoach).toHaveBeenCalledTimes(1)
expect(mocks.replaceState).toHaveBeenCalledTimes(1)
})
})