Compare commits

...
8 Commits
Author SHA1 Message Date
Duarte Santos fbc615aa26 Release v1.1.1 2026-07-21 12:48:12 +02:00
Duarte Santos e83d642e1b Remove push delivery latency disclaimer from Settings
Confirmed working reliably after the 10s check-interval + high-urgency
push fixes.
2026-07-21 12:45:57 +02:00
Duarte Santos 95c4b2b279 Add honest delivery-latency disclaimer under push notification settings
Web Push through Apple/Google isn't instant or guaranteed even with
high urgency — set the expectation up front instead of letting people
assume it's unreliable/broken when it lags.
2026-07-21 12:34:32 +02:00
Duarte Santos c5cf31e2ca Tighten reminder timing: 10s check interval + high-urgency push
Reminder loop only checked once a minute, unaligned to the minute
boundary, so it could sit up to 59s on the target time before noticing
- now capped at ~9s. Also mark pushes as urgency:'high', the one lever
we actually have over delivery speed (iOS/Android throttle low-urgency
background push harder under battery saving). Remaining delivery lag
after that is Apple/Google's own push relay scheduling, not something
we control from here.
2026-07-21 12:25:24 +02:00
Duarte Santos 10fa150d09 Flush pending state save immediately when tab backgrounds/closes
Settings changes (like the reminder time) were saved via a 1.5s
debounce; closing or switching away from the tab right after an edit
could kill that pending save before it reached the server, silently
losing the change. Now flushed on visibilitychange instead of relying
on the timer alone.

Also confirmed via a live server-side test (bypassing the client
entirely) that the reminder loop itself fires correctly — trimmed the
verbose per-tick debug log added for that test, kept the one for an
actual match.
2026-07-21 12:00:49 +02:00
Duarte Santos 5a7ce13ca2 Update docs: reminder timezone is now auto-detected per user, not a server env var 2026-07-21 11:47:26 +02:00
Duarte Santos 0ac531acb8 Fix workout reminder using the server's timezone instead of the user's
The reminder compared 'now' against a single TZ env var, so it only
worked correctly for whoever's local time happened to match the
server's. The browser now reports its own IANA timezone (auto-
detected, no picker) and stores it with the reminder; the server
computes each user's local time/date individually via Intl, and the
client re-stamps it on every app load so it follows you when you
travel.
2026-07-21 11:46:45 +02:00
Duarte Santos 7dea9ccfcc Log push send failures instead of swallowing them silently
sendPush caught every webpush.sendNotification error to clean up
expired subscriptions, but never logged anything for other failure
modes — made a delivery problem indistinguishable from 'nothing to
send' when debugging.
2026-07-21 11:42:40 +02:00
9 changed files with 82 additions and 38 deletions

No files matched your search

+4 -8
View File
@@ -20,11 +20,7 @@ RP_NAME=openGym
# (Point your proxy at the web container's WEB_PORT. See docs/SELF_HOSTING.md.)
# ── Notifications (optional) ───────────────────────────────────────────────
# Push works out of the box — VAPID keys are generated on first run and saved
# to ./data/vapid.json. The only thing worth setting yourself:
#
# TZ=Europe/Zurich
#
# Sets the container's timezone so the workout-day reminder fires at the time
# you actually pick, not UTC. Find your zone name at
# https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
# Push works out of the box — nothing to set. VAPID keys are generated on first
# run and saved to ./data/vapid.json. Each user's browser reports its own
# timezone automatically, so the workout-day reminder fires at their local
# time regardless of where the server runs or where they're travelling.
+14
View File
@@ -1,5 +1,19 @@
# Changelog
## v1.1.1 — 2026-07-21
Reliability fixes for the push notifications shipped in v1.1.0, found through live testing:
- 🌍 Workout day reminder now fires by each user's own browser-detected timezone instead of a
single server-wide one — works correctly regardless of where the server runs, and follows you
automatically if you travel.
- 💾 Settings changes (like the reminder time) are flushed to the server immediately when the tab
backgrounds or closes, instead of relying solely on a 1.5s debounce that could get cut short.
- ⏱️ Reminder check tightened from a 60s to a 10s interval, and pushes are now marked
`urgency: 'high'` — cuts avoidable delay on top of it, though delivery time is ultimately up to
Apple/Google's push relay.
- 🪵 Push send failures are now logged instead of silently swallowed.
## v1.1.0 — 2026-07-21
- 🐳 Prebuilt Docker images published to `ghcr.io/duartesantos8/opengym-{api,web}` (amd64 + arm64)
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "gym-api",
"version": "1.1.0",
"version": "1.1.1",
"private": true,
"type": "module",
"main": "server.js",
+30 -14
View File
@@ -56,8 +56,14 @@ async function sendPush(userId, payload) {
const body = JSON.stringify(payload);
let dirty = false;
await Promise.all(subs.map(async sub => {
try { await webpush.sendNotification({ endpoint: sub.endpoint, keys: sub.keys }, body); }
// urgency 'high' is the one lever we have over delivery speed — iOS/Android throttle
// low-urgency background push more aggressively under battery-saving modes. TTL is left
// at the library default (long) so a briefly-offline device still gets it once reconnected,
// rather than risking it being dropped for the sake of shaving off latency that TTL doesn't
// actually control anyway.
try { await webpush.sendNotification({ endpoint: sub.endpoint, keys: sub.keys }, body, { urgency: 'high' }); }
catch (e) {
console.error('push send failed', userId, e.statusCode, e.body || e.message);
if (e.statusCode === 404 || e.statusCode === 410) {
db.subs = db.subs.filter(s => s.endpoint !== sub.endpoint); dirty = true;
}
@@ -91,24 +97,32 @@ function effectiveRoutineId(S, iso) {
const wd = new Date(iso + 'T12:00:00').getDay();
return S.week?.[wd] || null;
}
const todayISO = () => {
const d = new Date();
return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
};
// Computes "now" in an arbitrary IANA zone (e.g. "Europe/Lisbon") instead of the server's own —
// each user's reminder fires by their own clock, wherever they and their phone actually are.
function userNow(tz) {
try {
const parts = new Intl.DateTimeFormat('en-CA', {
timeZone: tz, hour12: false,
year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit'
}).formatToParts(new Date());
const g = t => parts.find(p => p.type === t)?.value;
return { date: `${g('year')}-${g('month')}-${g('day')}`, hhmm: `${g('hour')}:${g('minute')}` };
} catch { return null; } // unknown/invalid tz string — skip this user rather than guess
}
setInterval(() => {
const now = new Date();
const hhmm = String(now.getHours()).padStart(2, '0') + ':' + String(now.getMinutes()).padStart(2, '0');
const today = todayISO();
for (const user of db.users) {
if (user.lastReminder === today) continue;
if (!db.subs.some(s => s.userId === user.id)) continue;
const S = readState(user.id);
if (!S?.reminder?.on || S.reminder.time !== hhmm) continue;
if ((S.workouts || []).some(w => w.d === today)) continue;
const rid = effectiveRoutineId(S, today);
if (!S?.reminder?.on) continue;
const now = userNow(S.reminder.tz || 'UTC');
if (!now || S.reminder.time !== now.hhmm) continue;
if (user.lastReminder === now.date) continue;
if ((S.workouts || []).some(w => w.d === now.date)) continue;
const rid = effectiveRoutineId(S, now.date);
if (!rid) continue; // rest day — nothing planned
const routine = (S.routines || []).find(r => r.id === rid);
user.lastReminder = today;
console.log('reminder firing', user.id, rid);
user.lastReminder = now.date;
saveDb();
sendPush(user.id, {
title: routine ? `${routine.emoji || '🏋️'} ${routine.name} today` : 'Workout planned today',
@@ -116,7 +130,9 @@ setInterval(() => {
tag: 'day-reminder'
});
}
}, 60000).unref();
// Checked every 10s (not 60s) — ticks aren't aligned to the top of the minute, so a 60s
// interval could sit on your target minute for up to 59s before noticing. 10s caps that at ~9s.
}, 10000).unref();
/* ---------- sessions (signed cookie) ---------- */
function sign(payload) {
+5 -9
View File
@@ -109,14 +109,10 @@ rest-timer-over, and a reminder on days you have a workout planned but haven't l
Turn it on per-profile in **Settings → Notifications** (requires a signed-in passkey profile and
HTTPS — see section 3).
No setup needed server-side: VAPID keys are generated on first run and saved to `./data/vapid.json`.
The one thing worth setting is your timezone, so the day reminder fires at the time you actually
picked rather than UTC:
```bash
# .env
TZ=Europe/Zurich
```
No setup needed server-side, and nothing to configure per timezone: VAPID keys are generated on
first run and saved to `./data/vapid.json`, and each user's browser reports its own timezone
automatically when they turn the reminder on — it fires at their local time, and follows them if
they travel, regardless of what timezone the server itself runs in.
## 7. Updating
@@ -147,6 +143,6 @@ downloaded media are untouched.
| Media didn't download | `docker compose logs media`. Re-run `docker compose up -d`, or run `./scripts/fetch-media.sh`. |
| Port 8080 already used | Set `WEB_PORT=9090` in `.env` (and update `ORIGIN` for local testing). |
| No "Notifications" option in Settings | Requires a signed-in profile and HTTPS (or `localhost`) — guest mode and plain HTTP over LAN can't subscribe. |
| Day reminder fires at the wrong time | Set `TZ=Continent/City` in `.env` and restart (see section 6). Defaults to UTC. |
| Day reminder fires at the wrong time | Toggle it off and on in Settings so it re-detects your browser's timezone (also happens automatically on every app load — see section 6). |
| Want to reset a stuck login | Delete the cookie in your browser; sessions are just signed cookies. |
| `docker compose pull` fails with "denied" / "unauthorized" | The prebuilt images aren't published yet, or need to be, or the GHCR package is still private — build from source instead (`docker compose up -d --build`). |
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "opengym-frontend",
"private": true,
"version": "1.1.0",
"version": "1.1.1",
"type": "module",
"scripts": {
"dev": "vite",
+2
View File
@@ -31,5 +31,7 @@ export function weekKey(d) {
return dt.getFullYear() + '-' + week
}
export const localTZ = () => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC' } catch { return 'UTC' } }
export const uid = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 7)
export const ACCENTS = { lime: '#a3e635', sky: '#38bdf8', orange: '#fb923c', violet: '#a78bfa', pink: '#f472b6', red: '#f87171', teal: '#2dd4bf', gold: '#fbbf24' }
+18 -1
View File
@@ -1,5 +1,6 @@
import { create } from 'zustand'
import { api } from '../lib/api.js'
import { localTZ } from '../lib/format.js'
const KEY = 'gym_state_v1'
export const DEF = {
@@ -7,7 +8,7 @@ export const DEF = {
theme: 'dark', accent: 'lime', targetW: null,
bodyweight: [], routines: [], week: {}, dayPlan: {},
exWeights: {}, workouts: [], active: null,
reminder: { on: false, time: '08:00' }
reminder: { on: false, time: '08:00', tz: null }
}
const clone = o => JSON.parse(JSON.stringify(o))
@@ -34,6 +35,16 @@ export const useStore = create((set, get) => {
}
}
// A setting changed right before switching away/closing the tab must not get lost mid-debounce
// (e.g. setting the reminder time then immediately backgrounding to test it).
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden' && pushTm) {
clearTimeout(pushTm)
pushTm = null
get().pushState()
}
})
return {
S: loadState(),
user: (() => { try { return JSON.parse(localStorage.getItem('gym_user')) || null } catch { return null } })(),
@@ -91,6 +102,12 @@ export const useStore = create((set, get) => {
const me = await api('/api/me')
get().setUser(me.user)
await get().pullState()
// Re-stamp the reminder's timezone on every load — keeps it correct if you're travelling,
// without needing to revisit Settings.
const tz = localTZ()
if (get().S.reminder?.on && get().S.reminder.tz !== tz) {
get().update(s => { s.reminder = { ...s.reminder, tz } })
}
} catch (e) {
if (e.status === 401) get().setUser(null)
}
+7 -4
View File
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore, DEF, hasData } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { ACCENTS, todayISO } from '../lib/format.js'
import { ACCENTS, todayISO, localTZ } from '../lib/format.js'
import { webauthnOK, passkeyLogin, passkeyRegister, IS_ANDROID } from '../lib/api.js'
import { pushSupported, enablePush, disablePush, sendTestPush } from '../lib/push.js'
import { loadStarterPlan, confirmSheet } from '../sheets.jsx'
@@ -136,14 +136,17 @@ function NotificationsCard({ S, update, toast }) {
{on && <>
<div className="row between" style={{ padding: '8px 0' }}>
<span>Workout day reminder</span>
<button className={'chip' + (S.reminder?.on ? ' on' : '')} onClick={() => update(s => { s.reminder = { ...(s.reminder || DEF.reminder), on: !s.reminder?.on } })}>{S.reminder?.on ? 'On' : 'Off'}</button>
<button className={'chip' + (S.reminder?.on ? ' on' : '')} onClick={() => update(s => { s.reminder = { ...(s.reminder || DEF.reminder), on: !s.reminder?.on, tz: localTZ() } })}>{S.reminder?.on ? 'On' : 'Off'}</button>
</div>
{S.reminder?.on && <div className="row between" style={{ padding: '8px 0' }}>
<span>Reminder time</span>
<input type="time" className="input" style={{ width: 120 }} value={S.reminder?.time || DEF.reminder.time}
onChange={e => update(s => { s.reminder = { ...(s.reminder || DEF.reminder), time: e.target.value } })} />
onChange={e => update(s => { s.reminder = { ...(s.reminder || DEF.reminder), time: e.target.value, tz: localTZ() } })} />
</div>}
<div className="small dim" style={{ margin: '6px 0' }}>Only sent on days you have a routine planned and haven't logged a workout yet.</div>
<div className="small dim" style={{ margin: '6px 0' }}>
Only sent on days you have a routine planned and haven't logged a workout yet.
{S.reminder?.on && S.reminder?.tz && <> Timezone: {S.reminder.tz} (auto-detected, updates if you travel).</>}
</div>
<button className="btn sm" onClick={test}>Send test notification</button>
</>}
</>}