Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

Settings: a Server & sync block with Sync now, and Disconnect or Sign out ask before leaving changes the server has not got

Duarte Santosc4e118587c77
diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx
index 749d5b76b..8250e4f7d 100644
--- a/frontend/src/views/Settings.jsx
+++ b/frontend/src/views/Settings.jsx
@@ -7,7 +7,7 @@ import { useUI } from '../store/useUI.js'
import { ACCENTS, todayISO, localTZ, weekStartOf, MONDAY, SUNDAY } from '../lib/format.js'
import { effortOf } from '../lib/history.js'
import { unlock, playOnSilentSupported } from '../lib/sound.js'
-import { api, webauthnOK, passkeyLogin, passkeyRegister, IS_ANDROID } from '../lib/api.js'
+import { api, webauthnOK, passkeyRegister, IS_ANDROID } from '../lib/api.js'
import { pushSupported, enablePush, disablePush, sendTestPush, syncPushSubscription } from '../lib/push.js'
import { wakeLockSupported } from '../lib/wakelock.js'
import { t, LANGS, INSTR_LANGS } from '../lib/i18n.js'
@@ -15,9 +15,9 @@ 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, askAddDeviceData } from '../sheets.jsx'
+import { starterPlanSheet, confirmSheet, importFromApp, importFromHevy, equipmentProfileSheet, menuSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
+import { ServerSyncSection, KeptChangesRows, leaveServer, connectServer, signInAgain } from '../components/ServerSync.jsx'
import { Section, Row, SelectRow, Switch, Segmented, Button, TextField } from '../components/ui.jsx'
export default function Settings() {
@@ -25,7 +25,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, adoptProfile, signOut, signOutAll, resetDemo, disconnectServer } = useStore()
+ const { update, replaceState, setUser, pullState, pushState, resetDemo } = useStore()
const toast = useUI(s => s.toast)
const fileRef = useRef(null)
const importRef = useRef(null)
@@ -119,8 +119,10 @@ export default function Settings() {
}
}
+ // Reads the store at the moment of the tap: the sheet that asks before a sign-out offers it too,
+ // and the copy it exports is the one that has not reached the server.
const doExport = async () => {
- const json = JSON.stringify(S, null, 2)
+ const json = JSON.stringify(useStore.getState().S, null, 2)
const name = 'opengym-backup-' + todayISO() + '.json'
// WKWebView can't download blob URLs — the native build hands the file to the share sheet.
if (MOBILE) {
@@ -143,24 +145,33 @@ export default function Settings() {
}
rd.readAsText(f)
}
- const signInHere = async () => {
- 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} />)
- // Ends the profile's sessions on every device — this one included, so on success it lands in
- // the same place as the plain sign-out above (home, local data cleared). On failure nothing
- // local is touched: still signed in here, and say so rather than leaving a half-signed-out app.
+ /* Disconnect (phone), Sign out, Sign out everywhere. None of them wipes this device while the
+ server is missing a change: the confirm no longer promises a sync it never checked, and when
+ something is owed, a second sheet says how much and offers to try again, to export a backup,
+ or to go ahead anyway with the changes kept on this device (components/ServerSync.jsx).
+ "Sign out everywhere" also ends every paired phone's token — the phones have no passkey to
+ sign in with, so they have to be paired again, and the confirm says so. Failing, it touches
+ nothing local: still signed in here, and the toast says so. */
+ const kept = t('The changes your server has not seen are kept on this device, and added back when it connects as this account again.')
+ const leave = (kind, after) => leaveServer(kind, { exportBackup: doExport, done: r => { nav('/home'); if (r.stashed) toast(kept); else if (after) toast(after) } })
+ const disconnect = () => confirmSheet({
+ title: t('Disconnect from your server?'),
+ message: t('This phone switches back to local-only and its copy of your account is removed. First it checks that your server has every change — if not, you choose what happens to them.'),
+ confirmText: t('Disconnect'), danger: true,
+ onConfirm: () => leave('disconnect', t('Disconnected — back to local-only')),
+ })
+ const signOutHere = () => confirmSheet({
+ title: t('Sign out?'),
+ message: t('Your data is removed from this browser; your profile on the server keeps it. First it checks that the server has every change — if not, you choose what happens to them.'),
+ confirmText: t('Sign out'), danger: true,
+ onConfirm: () => leave('signout'),
+ })
const signOutEverywhere = () => confirmSheet({
title: t('Sign out everywhere?'),
- message: t('Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.'),
+ message: t('Signs this profile out on every device, including this one. Phones paired with it are disconnected and have to be paired again. Your passkeys keep working — sign in with them again anytime.'),
confirmText: t('Sign out everywhere'), danger: true,
- onConfirm: async () => {
- // Refused while changes are still owed to the server: nothing was signed out or wiped,
- // and the sync banner says what is waiting.
- try { const r = await signOutAll(); if (r?.owed && !r.stashed) return; nav('/home'); toast(t('Signed out on all devices')) }
- catch (e) { toast(t('Could not sign out everywhere — you are still signed in.')) }
- },
+ onConfirm: () => leave('everywhere', t('Signed out on all devices')),
})
// 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
@@ -188,41 +199,44 @@ export default function Settings() {
<div style={{ flex: 1, marginLeft: 10 }}><h1>{t('Settings')}</h1></div>
</div>
- {/* ---------- account (demo and mobile builds have nothing to sign in to) ---------- */}
- <Section title={MOBILE ? (user ? t('Your server') : t('Your data')) : DEMO ? t('Demo') : t('Account')}>
- {MOBILE ? (user ? <>
- <Row icon="personCircle" iconTint="var(--grey)" title={user.name} subtitle={t('Synced with your openGym server.')} />
+ {/* ---------- the server: which one, which account, how that stands, "Sync now" ----------
+ A paired phone's Admin and Disconnect sit in the same block; a browser's account rows
+ follow in their own. */}
+ {user && !DEMO && <ServerSyncSection>
+ {MOBILE && <>
{user.admin && <Row icon="wrench" iconTint="var(--indigo)" title={t('Admin dashboard')} accessory="chevron" onClick={() => nav('/admin')} />}
- <Row icon="signOut" iconTint="var(--red)" title={t('Disconnect')} danger onClick={() => confirmSheet({
- title: t('Disconnect from your server?'),
- message: t('Your data is synced to your server first, then this device switches back to local-only.'),
- confirmText: t('Disconnect'), danger: true,
- onConfirm: async () => { const r = await disconnectServer(); if (r?.owed && !r.stashed) return; nav('/home'); toast(t('Disconnected — back to local-only')) },
- })} />
- </> : <>
+ <Row icon="signOut" iconTint="var(--red)" title={t('Disconnect')} danger onClick={disconnect} />
+ </>}
+ </ServerSyncSection>}
+
+ {/* ---------- account (demo and mobile builds have nothing to sign in to) ---------- */}
+ {!(MOBILE && user) && <Section title={MOBILE ? t('Your data') : DEMO ? t('Demo') : t('Account')}>
+ {MOBILE ? <>
<Row icon="lock" iconTint="var(--acc)" title={t('All data stays on this phone')} subtitle={t('No account, no cloud — back it up anytime with Export below.')} />
<Row icon="link" iconTint="var(--indigo)" title={t('Connect to my server')} subtitle={t('Sync this device to your own self-hosted openGym instead.')} accessory="chevron"
- onClick={() => useUI.getState().openSheet(close => <ConnectSheet close={close} />)} />
- </>) : DEMO ? <>
+ onClick={connectServer} />
+ <KeptChangesRows />
+ </> : DEMO ? <>
<Row icon="sparkles" iconTint="var(--acc)" title={t('You’re in the demo')} subtitle={t('Example data, stored only in this browser — change anything you like.')} />
<Row icon="reset" iconTint="var(--blue)" title={t('Reset demo data')} accessory="chevron"
onClick={() => confirmSheet({ title: t('Reset demo data?'), message: t('Puts the example plan, workouts and weigh-ins back the way they started.'), confirmText: t('Reset'), onConfirm: () => { resetDemo(); nav('/home'); toast(t('Demo data reset')) } })} />
<Row icon="rocket" iconTint="var(--indigo)" title={t('Self-host openGym')} subtitle={t('Passkey sign-in, sync across your devices, your own data.')} accessory="chevron"
onClick={() => window.open(REPO, '_blank', 'noopener')} />
</> : user ? <>
- <Row icon="personCircle" iconTint="var(--grey)" title={user.name} subtitle={t('Signed in with passkey — data syncs to this profile.')} />
{user.admin && <Row icon="wrench" iconTint="var(--indigo)" title={t('Admin dashboard')} accessory="chevron" onClick={() => nav('/admin')} />}
<Row icon="link" iconTint="var(--blue)" title={t('Pair the mobile app')} subtitle={t('Connect the openGym app on your phone to this account.')} accessory="chevron"
onClick={() => useUI.getState().openSheet(close => <PairSheet close={close} />)} />
- <Row icon="signOut" iconTint="var(--red)" title={t('Sign out')} danger onClick={() => confirmSheet({ title: t('Sign out?'), message: t('Your data is synced to your profile first, then cleared from this device.'), confirmText: t('Sign out'), danger: true, onConfirm: async () => { const r = await signOut(); if (r?.owed && !r.stashed) return; nav('/home') } })} />
+ <Row icon="signOut" iconTint="var(--red)" title={t('Sign out')} danger onClick={signOutHere} />
<Row icon="shield" iconTint="var(--red)" title={t('Sign out everywhere')} subtitle={t('Ends this profile’s sessions on all your devices.')} danger onClick={signOutEverywhere} />
</> : webauthnOK() ? <>
<Row icon="sparkles" iconTint="var(--acc)" title={t('Create passkey profile')} subtitle={t('Keeps your data safe and separate per person.')} accessory="chevron" onClick={registerHere} />
- <Row icon="person" iconTint="var(--blue)" title={t('Sign in with passkey')} accessory="chevron" onClick={signInHere} />
- </> : (
+ <Row icon="person" iconTint="var(--blue)" title={t('Sign in with passkey')} accessory="chevron" onClick={signInAgain} />
+ <KeptChangesRows />
+ </> : <>
<Row icon="lock" iconTint="var(--grey)" title={t('Passkeys not supported in this browser.')} />
- )}
- </Section>
+ <KeptChangesRows />
+ </>}
+ </Section>}
{!user && !DEMO && !MOBILE && <p className="sect-f" style={{ marginTop: -18, marginBottom: 22 }}>{t('Guest mode — data lives only in this browser.')}</p>}
{/* ---------- the Coach on a phone: through the paired server, or with the user's own key ---------- */}
diff --git a/frontend/src/views/Settings.server-sync.test.jsx b/frontend/src/views/Settings.server-sync.test.jsx
new file mode 100644
index 000000000..93ae9edb5
--- /dev/null
+++ b/frontend/src/views/Settings.server-sync.test.jsx
@@ -0,0 +1,259 @@
+// @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
+
+/* Settings → "Server & sync": which server, which account, how things stand, when this device
+ last held what the server holds, how much is still waiting, and "Sync now" with its outcome.
+ Then the way out — Disconnect, Sign out, Sign out everywhere — which no longer promises a sync
+ it never checked, and which asks before leaving changes the server has not got: try again,
+ export a backup, or go ahead anyway with the changes kept on the device. */
+const mocks = vi.hoisted(() => {
+ const state = { S: null, user: null, sync: null, MOBILE: false, unsynced: { owed: false, count: 0 }, kept: [], sheets: [], navs: [] }
+ state.toast = vi.fn()
+ state.confirmSheet = vi.fn()
+ state.syncNow = vi.fn(async () => state.sync)
+ state.disconnectServer = vi.fn()
+ state.signOut = vi.fn()
+ state.signOutAll = vi.fn()
+ state.shareExport = vi.fn(async () => {})
+ state.snapshot = () => ({
+ S: state.S, user: state.user, sync: state.sync, coachLocal: null,
+ update: vi.fn(), replaceState: vi.fn(), setUser: vi.fn(), pullState: vi.fn(), pushState: vi.fn(), resetDemo: vi.fn(),
+ syncNow: state.syncNow, unsyncedChanges: () => state.unsynced, keptChanges: async () => state.kept,
+ disconnectServer: state.disconnectServer, signOut: state.signOut, signOutAll: state.signOutAll,
+ adoptProfile: 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' } }, hasData: () => false }
+})
+vi.mock('../store/useUI.js', () => {
+ const snap = () => ({ toast: (...a) => mocks.toast(...a), openSheet: (render, opts) => { mocks.sheets.push({ render, opts }); return {} } })
+ const useUI = selector => selector ? selector(snap()) : snap()
+ useUI.getState = snap
+ return { useUI }
+})
+vi.mock('react-router-dom', () => ({ useNavigate: () => to => mocks.navs.push(to) }))
+vi.mock('../lib/api.js', () => ({
+ api: vi.fn(() => Promise.resolve({})), webauthnOK: () => true, 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', () => ({
+ get MOBILE() { return mocks.MOBILE },
+ isAndroid: () => Promise.resolve(false), shareExport: (...a) => mocks.shareExport(...a), syncReminder: vi.fn(),
+}))
+vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: props => <div className="connect" data-url={props.initialUrl ?? ''} data-again={String(!!props.again)} /> }))
+vi.mock('../sheets.jsx', () => ({
+ starterPlanSheet: vi.fn(), confirmSheet: (...a) => mocks.confirmSheet(...a), importFromApp: vi.fn(),
+ importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(), menuSheet: vi.fn(), askAddDeviceData: vi.fn(),
+}))
+
+globalThis.__APP_VERSION__ ??= 'test'
+
+const BASE = 'https://gym.example.com'
+const USER = { id: 'u1', name: 'andi' }
+const sync = (status, extra = {}) => ({ status, offline: false, pending: false, auth: false, lastError: null, lastSynced: 0, server: BASE, ...extra })
+
+const mounted = []
+function mount(el) {
+ const host = document.createElement('div')
+ document.body.appendChild(host)
+ const root = createRoot(host)
+ mounted.push({ root, host })
+ act(() => root.render(el))
+ return host
+}
+const settle = () => act(() => new Promise(r => setTimeout(r, 0)))
+beforeEach(() => {
+ mocks.S = { unit: 'kg', restSec: 90, restPauseSec: 15, sound: false, effort: 'none', gifSize: 'full', workouts: [], routines: [], exWeights: {} }
+ mocks.user = USER
+ mocks.MOBILE = true
+ mocks.sync = sync('ok', { lastSynced: Date.now() - 5 * 60000 })
+ mocks.unsynced = { owed: false, count: 0 }
+ mocks.kept = []
+ mocks.sheets.length = 0
+ mocks.navs.length = 0
+ for (const f of [mocks.toast, mocks.confirmSheet, mocks.syncNow, mocks.disconnectServer, mocks.signOut, mocks.signOutAll, mocks.shareExport]) f.mockClear()
+})
+afterEach(() => { act(() => { mounted.splice(0).forEach(({ root, host }) => { root.unmount(); host.remove() }) }) })
+
+const block = page => [...page.querySelectorAll('.sect')].find(s => s.querySelector('.sect-t')?.textContent === 'Server & sync')
+const rowByTitle = (el, title) => [...el.querySelectorAll('.lrow')].find(r => r.querySelector('.lrow-t')?.textContent === title)
+const buttonByText = (el, text) => [...el.querySelectorAll('button')].find(b => b.textContent === text)
+const openSheet = (i = -1) => mount(mocks.sheets.at(i).render(() => {}))
+
+describe('Server & sync', () => {
+ it('a paired phone in step: server, account, "All synced" with the time, and Sync now reporting back', async () => {
+ const page = mount(<Settings />)
+ const b = block(page)
+ expect(b).toBeTruthy()
+ expect(rowByTitle(b, 'gym.example.com').textContent).toContain('Signed in as andi')
+ expect(rowByTitle(b, 'All synced').textContent).toContain('Last synced: 5 minutes ago')
+ expect(rowByTitle(b, 'Disconnect')).toBeTruthy() // the phone's own rows sit in the block
+ expect(rowByTitle(b, 'Pair again')).toBeUndefined() // nothing to fix
+
+ await act(async () => { rowByTitle(b, 'Sync now').click() })
+ expect(mocks.syncNow).toHaveBeenCalledTimes(1)
+ expect(mocks.toast).toHaveBeenCalledWith('All synced')
+ })
+
+ it('refused by the server: says so, how much is waiting, and offers "Pair again" with the address filled in', async () => {
+ mocks.sync = sync('auth', { auth: true, pending: true, lastSynced: Date.now() - 2 * 86400000, lastError: { status: 401, code: 'auth' } })
+ mocks.unsynced = { owed: true, count: 3 }
+ const page = mount(<Settings />)
+ const b = block(page)
+ const status = rowByTitle(b, 'The server refuses this phone')
+ expect(status.textContent).toContain('Last synced: 2 days ago')
+ expect(status.textContent).toContain('Not on your server yet: 3 changes')
+ act(() => rowByTitle(b, 'Pair again').click())
+ const sheet = openSheet().querySelector('.connect')
+ expect(sheet.dataset.url).toBe(BASE)
+ expect(sheet.dataset.again).toBe('true')
+
+ // Sync now reports the outcome, whatever it is.
+ await act(async () => { rowByTitle(b, 'Sync now').click() })
+ expect(mocks.toast).toHaveBeenCalledWith('The server refuses this phone')
+ })
+
+ it('a browser with a server error shows the HTTP code; one that never synced here says so', () => {
+ mocks.MOBILE = false
+ mocks.sync = sync('error', { pending: true, lastError: { status: 502, code: 'http' } })
+ mocks.unsynced = { owed: true, count: 1 }
+ const page = mount(<Settings />)
+ const status = rowByTitle(block(page), 'Server error (HTTP 502)')
+ expect(status.textContent).toContain('Not synced with this server yet')
+ expect(status.textContent).toContain('Not on your server yet: 1 change')
+ // The browser's account rows follow in their own section.
+ expect(rowByTitle(page, 'Sign out')).toBeTruthy()
+ })
+
+ it('while everything is fine, a change still in its debounce is not counted as waiting', () => {
+ mocks.unsynced = { owed: true, count: 1 }
+ const page = mount(<Settings />)
+ expect(rowByTitle(block(page), 'All synced').textContent).not.toContain('Not on your server yet')
+ })
+
+ it('a phone kept local has no server block, and lists the changes a forced disconnect kept', async () => {
+ mocks.user = null
+ mocks.sync = sync('local', { server: null })
+ mocks.kept = [{ server: BASE, uid: 'u1', name: 'andi', at: 1 }]
+ const page = mount(<Settings />)
+ await settle()
+ expect(block(page)).toBeUndefined()
+ const kept = rowByTitle(page, 'Changes kept for andi')
+ expect(kept.textContent).toContain('gym.example.com')
+ expect(kept.textContent).toContain('Added back when this device connects as that account again.')
+ })
+})
+
+describe('leaving the server', () => {
+ const confirm = () => mocks.confirmSheet.mock.calls.at(-1)[0]
+
+ it('Disconnect no longer promises a sync it did not check, and goes straight through when nothing is waiting', async () => {
+ mocks.disconnectServer.mockResolvedValueOnce({ owed: false })
+ const page = mount(<Settings />)
+ act(() => rowByTitle(page, 'Disconnect').click())
+ expect(confirm().message).not.toMatch(/synced to your server first/)
+ expect(confirm().message).toContain('checks that your server has every change')
+ await act(async () => { await confirm().onConfirm() })
+ expect(mocks.disconnectServer).toHaveBeenCalledWith(undefined)
+ expect(mocks.sheets).toHaveLength(0)
+ expect(mocks.navs).toEqual(['/home'])
+ expect(mocks.toast).toHaveBeenCalledWith('Disconnected — back to local-only')
+ })
+
+ it('with changes waiting it asks: how many, try again, export, or disconnect anyway — which keeps them', async () => {
+ mocks.disconnectServer.mockResolvedValueOnce({ owed: true, count: 2 })
+ const page = mount(<Settings />)
+ act(() => rowByTitle(page, 'Disconnect').click())
+ await act(async () => { await confirm().onConfirm() })
+ expect(mocks.navs).toEqual([]) // nothing left, nothing wiped
+ expect(mocks.sheets.at(-1).opts).toMatchObject({ kind: 'center' })
+ const sheet = openSheet()
+ expect(sheet.textContent).toContain('Not on your server yet: 2 changes')
+ expect(sheet.textContent).toContain('keeps a copy of these changes on this device')
+
+ await act(async () => { buttonByText(sheet, 'Export backup (JSON)').click() })
+ expect(mocks.shareExport).toHaveBeenCalledTimes(1) // the phone exports through the share sheet
+ expect(mocks.shareExport.mock.calls[0][1]).toMatch(/^opengym-backup-\d{4}-\d{2}-\d{2}\.json$/)
+
+ mocks.disconnectServer.mockResolvedValueOnce({ owed: true, count: 2, stashed: true })
+ await act(async () => { buttonByText(sheet, 'Disconnect anyway').click() })
+ expect(mocks.disconnectServer).toHaveBeenLastCalledWith({ force: true })
+ expect(mocks.navs).toEqual(['/home'])
+ expect(mocks.toast).toHaveBeenLastCalledWith('The changes your server has not seen are kept on this device, and added back when it connects as this account again.')
+ })
+
+ it('"Try again" syncs, and leaves once the server has everything', async () => {
+ mocks.disconnectServer.mockResolvedValueOnce({ owed: true, count: 1 })
+ const page = mount(<Settings />)
+ act(() => rowByTitle(page, 'Disconnect').click())
+ await act(async () => { await confirm().onConfirm() })
+ const sheet = openSheet()
+
+ mocks.disconnectServer.mockResolvedValueOnce({ owed: true, count: 1 })
+ mocks.sync = sync('offline', { offline: true, pending: true, lastError: { status: 0, code: 'network' } })
+ await act(async () => { buttonByText(sheet, 'Try again').click() })
+ expect(mocks.syncNow).toHaveBeenCalledTimes(1)
+ expect(mocks.navs).toEqual([])
+ expect(sheet.textContent).toContain('Offline — the server cannot be reached') // why it is still waiting
+
+ mocks.disconnectServer.mockResolvedValueOnce({ owed: false })
+ await act(async () => { buttonByText(sheet, 'Try again').click() })
+ expect(mocks.navs).toEqual(['/home'])
+ })
+
+ it('refused by the server, "Try again" makes way for "Pair again" — pairing is what brings the changes over', async () => {
+ mocks.sync = sync('auth', { auth: true, pending: true, lastError: { status: 401, code: 'auth' } })
+ mocks.disconnectServer.mockResolvedValueOnce({ owed: true, count: null })
+ const page = mount(<Settings />)
+ act(() => rowByTitle(page, 'Disconnect').click())
+ await act(async () => { await confirm().onConfirm() })
+ const sheet = openSheet()
+ expect(sheet.textContent).toContain('Some changes on this device have not reached your server.')
+ expect(buttonByText(sheet, 'Try again')).toBeUndefined()
+ act(() => buttonByText(sheet, 'Pair again').click())
+ expect(openSheet().querySelector('.connect').dataset.again).toBe('true')
+ })
+
+ it('a copy that cannot be kept aside is not wiped either, and it says so', async () => {
+ mocks.disconnectServer.mockResolvedValueOnce({ owed: true, count: 1 })
+ const page = mount(<Settings />)
+ act(() => rowByTitle(page, 'Disconnect').click())
+ await act(async () => { await confirm().onConfirm() })
+ const sheet = openSheet()
+ mocks.disconnectServer.mockResolvedValueOnce({ owed: true, count: 1, stashed: false })
+ await act(async () => { buttonByText(sheet, 'Disconnect anyway').click() })
+ expect(mocks.navs).toEqual([])
+ expect(mocks.toast).toHaveBeenLastCalledWith('Could not keep a copy of the changes on this device — nothing was removed.')
+ })
+
+ it('browser: Sign out checks first too, and "Sign out everywhere" says paired phones have to be paired again', async () => {
+ mocks.MOBILE = false
+ mocks.signOut.mockResolvedValueOnce({ owed: true, count: 4 })
+ const page = mount(<Settings />)
+ act(() => rowByTitle(page, 'Sign out').click())
+ expect(confirm().message).not.toMatch(/synced to your profile first/)
+ await act(async () => { await confirm().onConfirm() })
+ const sheet = openSheet()
+ expect(sheet.textContent).toContain('Not on your server yet: 4 changes')
+ mocks.signOut.mockResolvedValueOnce({ owed: true, count: 4, stashed: true })
+ await act(async () => { buttonByText(sheet, 'Sign out anyway').click() })
+ expect(mocks.signOut).toHaveBeenLastCalledWith({ force: true })
+ expect(mocks.navs).toEqual(['/home'])
+
+ act(() => rowByTitle(page, 'Sign out everywhere').click())
+ expect(confirm().message).toContain('Phones paired with it are disconnected and have to be paired again.')
+ mocks.signOutAll.mockRejectedValueOnce(new Error('HTTP 502'))
+ await act(async () => { await confirm().onConfirm() })
+ expect(mocks.toast).toHaveBeenLastCalledWith('Could not sign out everywhere — you are still signed in.')
+ })
+})