Push: reminders owed within 15 minutes still arrive, the subscription heals itself on every boot, rest-timer alerts belong to the device that started the rest

- reminder tick: a due reminder is sent for up to 15 minutes after its time (once per local
  date) instead of only on the exact minute — a restart across that minute used to lose the day;
  state files are stat'ed and re-read only when they changed
- sendPush prunes 403 (stale VAPID key) like 404/410; optional device targeting
- POST /api/push/subscribe is an upsert that keeps created and stores a deviceId;
  GET /api/push/status says whether the server holds an endpoint
- rest timers keyed per user+device; cancel without a device id keeps the old account-wide
  behaviour
- sw.js: payload parsed inside waitUntil (never a silent push), pushsubscriptionchange
  re-subscribes and registers the new endpoint
- lib/push.js: syncPushSubscription() (called once per signed-in boot from App.jsx and when
  Settings opens) re-registers a lost row, replaces a subscription made against another key,
  pushSupported() is false off https; deviceId() per browser
- Settings: the notifications switch shows what the server holds
- tests: server-reminder (window, dedupe, trained day), server-push-status (upsert, status,
  per-device timers), lib/push.test.js
This commit is contained in:
Duarte Santos committed 2026-09-12 13:18:29 +02:00
1 parent c92cfc372a
commit 477fc07f8b
10 files changed
+534 -44

No files matched your search

+65 -8
View File
@@ -597,7 +597,9 @@ paths:
the two protocol keys are kept. The endpoint must be a public `https://` URL —
private/loopback/link-local addresses are refused (here and again at send
time, against DNS rebinding). At most 20 subscriptions per user; the oldest
are dropped first. Re-subscribing an existing endpoint replaces it.
are dropped first. Re-subscribing an existing endpoint replaces it and keeps
its original `created` — the client re-sends its subscription on every
signed-in boot, so a row the instance lost comes back on its own.
requestBody:
required: true
content:
@@ -607,6 +609,13 @@ paths:
required: [subscription]
properties:
subscription: { $ref: '#/components/schemas/PushSubscription' }
deviceId:
type: string
pattern: '^[A-Za-z0-9_-]{8,64}$'
description: >-
A token the browser made up for itself (stored in its localStorage),
so rest-timer pushes can be aimed at the device that started the
rest. Optional; anything that is not a short token is ignored.
responses:
'200':
description: Stored.
@@ -623,6 +632,33 @@ paths:
private: { value: { error: "endpoint must not point at a private address" } }
'401': { $ref: '#/components/responses/Unauthorized' }
/api/push/status:
get:
tags: [push]
operationId: pushStatus
summary: Does the server hold this subscription?
description: >-
Whether the caller's account has a stored subscription with exactly this
`endpoint`. The browser's `PushManager.getSubscription()` says nothing about
the server's side — a row pruned after a dead send (404/410/403) leaves the
browser subscribed to nowhere — so the client asks here before showing the
notifications switch as on, and re-registers when the answer is no.
parameters:
- in: query
name: endpoint
required: true
schema: { type: string, format: uri }
responses:
'200':
description: The answer.
content:
application/json:
schema:
type: object
properties:
subscribed: { type: boolean }
'401': { $ref: '#/components/responses/Unauthorized' }
/api/push/unsubscribe:
post:
tags: [push]
@@ -654,7 +690,8 @@ paths:
description: >-
Sends a test push to all of the caller's subscriptions (localized with the
`lang` in their synced state). Returns 200 even if delivery to individual
endpoints fails — dead endpoints (404/410) are pruned as a side effect.
endpoints fails — dead endpoints (404/410, and 403 for a subscription made
against a VAPID key the instance no longer has) are pruned as a side effect.
responses:
'200':
description: Sends attempted.
@@ -669,10 +706,14 @@ paths:
operationId: pushRestTimer
summary: Schedule a server-side rest-timer push
description: |
Schedules one push after `seconds` (clamped to 1–3600; one pending timer per
user, a new call replaces it). The client schedules this on rest start/extend
and cancels on skip or on-screen completion — the push only actually fires
when the tab was backgrounded/suspended and never got to cancel it.
Schedules one push after `seconds` (clamped to 1–3600). One pending timer per
device — `deviceId`, the same token the subscription was registered with; a
new call from the same device replaces it, and the push goes only to that
device's subscriptions. Without a `deviceId` there is one timer per account
and the push goes to every subscription, as before. The client schedules this
on rest start/extend and cancels on skip or on-screen completion — the push
only actually fires when the tab was backgrounded/suspended and never got to
cancel it. Timers live in memory: an API restart drops them.
Note: the documented `400 seconds required` exists in the code but is
unreachable — the clamp turns any missing/invalid value into 1.
@@ -688,7 +729,11 @@ paths:
type: number
minimum: 1
maximum: 3600
example: { seconds: 90 }
deviceId:
type: string
pattern: '^[A-Za-z0-9_-]{8,64}$'
description: The browser's own token, see `POST /api/push/subscribe`. Optional.
example: { seconds: 90, deviceId: "3f9c1d2e7b0a4c6d9e8f1a2b3c4d5e6f" }
responses:
'200':
description: Timer scheduled.
@@ -702,7 +747,19 @@ paths:
tags: [push]
operationId: pushRestTimerCancel
summary: Cancel the pending rest-timer push
description: Cancels the caller's scheduled rest-timer push, if any. Idempotent.
description: >-
Cancels the caller's scheduled rest-timer push, if any. With a `deviceId` only
that device's timer; without one, every pending timer of the account. Idempotent.
requestBody:
required: false
content:
application/json:
schema:
type: object
properties:
deviceId:
type: string
pattern: '^[A-Za-z0-9_-]{8,64}$'
responses:
'200':
description: Cancelled (or nothing was pending).
+83 -18
View File
@@ -185,8 +185,12 @@ function pushEndpointError(raw) {
return null;
}
async function sendPush(userId, payload) {
const subs = db.subs.filter(s => s.userId === userId);
// `deviceId` narrows the send to the subscriptions one browser registered (the rest-timer alert
// belongs to the device that started the rest); a subscription stored without one — an older
// client — still gets everything, as before.
async function sendPush(userId, payload, deviceId) {
let subs = db.subs.filter(s => s.userId === userId);
if (deviceId && subs.some(s => s.deviceId === deviceId)) subs = subs.filter(s => s.deviceId === deviceId);
if (!subs.length) return;
const body = JSON.stringify(payload);
let dirty = false;
@@ -212,7 +216,11 @@ async function sendPush(userId, payload) {
{ urgency: 'high', timeout: PUSH_TIMEOUT_MS, agent: PUSH_AGENT });
} catch (e) {
console.error('push send failed', userId, e.statusCode, e.body || e.message);
if (e.statusCode === 404 || e.statusCode === 410) {
// 404/410: the push service says the subscription is gone. 403: it refuses our VAPID
// signature — a subscription made against a key this instance no longer has (data/vapid.json
// regenerated). Neither will ever deliver again; keeping them only hides the fact from the
// Settings toggle, which reads the browser's side. The client re-subscribes on its next boot.
if (e.statusCode === 404 || e.statusCode === 410 || e.statusCode === 403) {
db.subs = db.subs.filter(s => s.endpoint !== sub.endpoint); dirty = true;
}
}
@@ -224,19 +232,30 @@ async function sendPush(userId, payload) {
// Rest-timer alerts: client schedules on start/extend, cancels on skip or on-screen completion —
// this only fires when the tab was backgrounded/suspended and never got to cancel it itself.
const restTimers = new Map(); // userId -> Timeout
function scheduleRestTimer(userId, sec, lang) {
const t = restTimers.get(userId);
// One timer per device, not per account: a phone resting in the gym and a desktop tab at home
// each carry their own, so the tab's on-screen completion (which cancels) cannot silence the
// phone's alert. A client that sends no device id gets the old account-wide behaviour.
// In memory only — an API restart drops whatever is pending.
const restTimers = new Map(); // `${userId}:${deviceId}` -> Timeout
const restKey = (userId, deviceId) => `${userId}:${deviceId || ''}`;
function scheduleRestTimer(userId, deviceId, sec, lang) {
const k = restKey(userId, deviceId);
const t = restTimers.get(k);
if (t) clearTimeout(t);
restTimers.set(userId, setTimeout(() => {
restTimers.delete(userId);
sendPush(userId, restTimerPush(lang));
restTimers.set(k, setTimeout(() => {
restTimers.delete(k);
sendPush(userId, restTimerPush(lang), deviceId);
}, sec * 1000));
}
function cancelRestTimer(userId) {
const t = restTimers.get(userId);
if (t) { clearTimeout(t); restTimers.delete(userId); }
function cancelRestTimer(userId, deviceId) {
// no device id: an older client — clear everything the account has pending, as it always did
for (const [k, t] of restTimers) {
if (deviceId ? k === restKey(userId, deviceId) : k.startsWith(userId + ':')) { clearTimeout(t); restTimers.delete(k); }
}
}
// A device id is what the browser made up for itself (lib/push.js): one short token per browser
// profile, nothing identifying. Anything else is treated as absent.
const deviceIdOf = v => (typeof v === 'string' && /^[A-Za-z0-9_-]{8,64}$/.test(v) ? v : undefined);
// "Workout planned today" reminder — one per user per day, at their chosen time.
// Duplicated (not imported) from frontend/src/lib/history.js effectiveRoutineId — tiny pure helper, not worth sharing across the two runtimes.
@@ -263,6 +282,34 @@ function userNow(tz) {
return { date, hhmm: `${g('hour')}:${g('minute')}`, weekday: new Date(date + 'T12:00:00Z').getUTCDay() };
} catch { return null; } // unknown/invalid tz string — skip this user rather than guess
}
// The tick used to want the exact minute: `reminder.time === now.hhmm`, checked every 10 s. Any
// restart, redeploy or stalled event loop across that one minute lost the whole day's reminder —
// "sometimes it just doesn't come". A reminder that is due is now sent for up to this many
// minutes after its time, once per local date (`user.lastReminder`); later than that it is
// skipped rather than delivered at a time nobody asked for.
const REMINDER_WINDOW_MIN = 15;
// How often the tick looks. 10 s keeps a reminder within ~9 s of its minute; the tests shorten it.
const REMINDER_TICK_MS = Math.max(50, +(process.env.REMINDER_TICK_MS || 10000));
const hhmmToMin = v => {
const m = /^(\d{2}):(\d{2})$/.exec(v || '');
return m ? Number(m[1]) * 60 + Number(m[2]) : NaN;
};
// Minutes since the reminder's time on the user's clock; negative before it, NaN when either
// side does not parse. Same-day only — a 23:55 reminder is not owed at 00:05 the next day.
const minutesLate = (time, now) => hhmmToMin(now.hhmm) - hhmmToMin(time);
// The tick reads every subscribed user's state file every 10 s. Most of those files do not
// change between ticks; a stat is far cheaper than a read and a parse of a state that can be
// megabytes, and it keeps the tick short — a slow tick was one more way to miss the minute.
const stateCache = new Map(); // uid -> { mtimeMs, size, S }
function readStateCached(uid) {
let st;
try { st = fs.statSync(stateFile(uid)); } catch { stateCache.delete(uid); return null; }
const hit = stateCache.get(uid);
if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) return hit.S;
const S = readState(uid);
stateCache.set(uid, { mtimeMs: st.mtimeMs, size: st.size, S });
return S;
}
setInterval(() => {
for (const user of db.users) {
if (!db.subs.some(s => s.userId === user.id)) continue;
@@ -270,10 +317,12 @@ setInterval(() => {
// skipped, not allowed to take the process — and everyone else's reminders — down with it.
// PUT /api/data refuses the obvious shapes, but a file already on disk answers to nobody.
try {
const S = readState(user.id);
const S = readStateCached(user.id);
if (!S?.reminder?.on) continue;
const now = userNow(S.reminder.tz || 'UTC');
if (!now || S.reminder.time !== now.hhmm) continue;
if (!now) continue;
const late = minutesLate(S.reminder.time, now);
if (!(late >= 0 && late <= REMINDER_WINDOW_MIN)) continue;
if (user.lastReminder === now.date) continue;
if ((S.workouts || []).some(w => w.d === now.date)) continue;
const rid = effectiveRoutineId(S, now.date);
@@ -289,7 +338,7 @@ setInterval(() => {
}
// 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();
}, REMINDER_TICK_MS).unref();
/* ---------- sessions (signed cookie) ---------- */
function sign(payload) {
@@ -848,6 +897,11 @@ const routes = {
// Only the two keys the push protocol needs are kept: `sub` is caller-supplied and would
// otherwise put arbitrary fields into db.json, which every admin route reads back out.
const keys = { p256dh: String(sub.keys.p256dh), auth: String(sub.keys.auth) };
const deviceId = deviceIdOf(body.deviceId);
// An upsert: the client re-sends its subscription on every boot (lib/push.js) so a row this
// instance lost — pruned after a dead send, a rebuilt db.json — comes back without anyone
// touching Settings. The same endpoint sent again keeps its original `created`.
const prev = db.subs.find(s => s.endpoint === sub.endpoint);
db.subs = db.subs.filter(s => s.endpoint !== sub.endpoint);
// A browser holds one subscription per device, so this cap is far above real use. Without
// it a single account could pile up endpoints without limit — every one of them a target
@@ -857,11 +911,21 @@ const routes = {
const drop = new Set(mine.slice(0, mine.length - MAX_SUBS_PER_USER + 1).map(s => s.endpoint));
db.subs = db.subs.filter(s => !drop.has(s.endpoint));
}
db.subs.push({ userId: user.id, endpoint: sub.endpoint, keys, created: new Date().toISOString() });
db.subs.push({ userId: user.id, endpoint: sub.endpoint, keys, ...(deviceId ? { deviceId } : {}), created: prev?.created || new Date().toISOString() });
saveDb();
json(res, 200, { ok: true });
},
// Whether this instance still holds the caller's subscription for `endpoint`. The browser's
// side (PushManager.getSubscription) says nothing about ours — a row pruned after a dead send
// leaves the browser subscribed to nowhere — so Settings asks here before it shows "on".
'GET /api/push/status': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
const endpoint = new URL(req.url, 'http://x').searchParams.get('endpoint') || '';
json(res, 200, { subscribed: db.subs.some(s => s.userId === user.id && s.endpoint === endpoint) });
},
'POST /api/push/unsubscribe': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
@@ -884,14 +948,15 @@ const routes = {
const body = await readBody(req);
const sec = Math.max(1, Math.min(3600, Math.round(+body.seconds || 0)));
if (!sec) return json(res, 400, { error: 'seconds required' });
scheduleRestTimer(user.id, sec, readState(user.id)?.lang);
scheduleRestTimer(user.id, deviceIdOf(body.deviceId), sec, readState(user.id)?.lang);
json(res, 200, { ok: true });
},
'POST /api/push/rest-timer/cancel': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
cancelRestTimer(user.id);
const body = await readBody(req);
cancelRestTimer(user.id, deviceIdOf(body.deviceId));
json(res, 200, { ok: true });
},
+110
View File
@@ -0,0 +1,110 @@
/* The subscription's server side. The browser keeps its PushSubscription through anything that
happens here — a row pruned after a dead send, a rebuilt db.json — so the client re-sends it on
every boot (an upsert that keeps `created`), asks /api/push/status before Settings shows "on",
and tags it with a device id so a rest-timer alert goes to the device that started the rest.
Real server.js in a child. */
import { test } from 'node:test';
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import net from 'node:net';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const SECRET = crypto.randomBytes(32).toString('hex');
function mintSession(uid) {
const payload = `${uid}:${Date.now() + 86400000}:0`;
return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');
}
const cookie = { Cookie: `gymsid=${mintSession('u_test_1')}` };
const other = { Cookie: `gymsid=${mintSession('u_test_2')}` };
const keys = { p256dh: 'p', auth: 'a' };
const freePort = () => new Promise(r => {
const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); });
});
async function startServer(t, subs = []) {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-pushstatus-'));
fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({
users: [{ id: 'u_test_1', name: 'One', created: new Date().toISOString() }, { id: 'u_test_2', name: 'Two', 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' }
});
const h = { api: `http://127.0.0.1:${port}`, dataDir, log: '' };
child.stdout.on('data', d => h.log += d);
child.stderr.on('data', d => h.log += d);
t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
let up = false;
for (let i = 0; i < 100 && !up; i++) {
try { up = (await fetch(`${h.api}/api/health`)).ok; } catch { /* not up yet */ }
if (!up) await new Promise(r => setTimeout(r, 100));
}
assert.ok(up, `server never came up:\n${h.log}`);
return h;
}
const readDb = h => JSON.parse(fs.readFileSync(path.join(h.dataDir, 'db.json'), 'utf8'));
const post = (h, p, body, hdr = cookie) => fetch(`${h.api}${p}`, { method: 'POST', headers: hdr, body: JSON.stringify(body) });
const status = (h, endpoint, hdr = cookie) => fetch(`${h.api}/api/push/status?endpoint=${encodeURIComponent(endpoint)}`, { headers: hdr }).then(r => r.json());
test('status tells whether the server holds the endpoint; subscribe is an upsert that keeps created and stores the device id', async t => {
const h = await startServer(t);
const endpoint = 'https://push.example/one';
assert.deepEqual(await status(h, endpoint), { subscribed: false });
assert.equal((await post(h, '/api/push/subscribe', { subscription: { endpoint, keys }, deviceId: 'dev_aaaaaaaa' })).status, 200);
assert.deepEqual(await status(h, endpoint), { subscribed: true });
assert.deepEqual(await status(h, endpoint, other), { subscribed: false }, 'another account does not see it');
const first = readDb(h).subs[0];
assert.equal(first.deviceId, 'dev_aaaaaaaa');
await new Promise(r => setTimeout(r, 20));
assert.equal((await post(h, '/api/push/subscribe', { subscription: { endpoint, keys: { p256dh: 'p2', auth: 'a2' } }, deviceId: 'dev_bbbbbbbb' })).status, 200);
const subs = readDb(h).subs;
assert.equal(subs.length, 1, 'same endpoint sent again is one row');
assert.equal(subs[0].created, first.created, 'created survives the re-send');
assert.equal(subs[0].deviceId, 'dev_bbbbbbbb');
assert.deepEqual(subs[0].keys, { p256dh: 'p2', auth: 'a2' });
// a device id that is not a short token is dropped, not stored
assert.equal((await post(h, '/api/push/subscribe', { subscription: { endpoint: 'https://push.example/two', keys }, deviceId: { evil: true } })).status, 200);
assert.equal('deviceId' in readDb(h).subs.find(s => s.endpoint.endsWith('/two')), false);
assert.equal((await fetch(`${h.api}/api/push/status?endpoint=x`)).status, 401);
});
test('a rest timer belongs to the device that set it: another device cancelling does not silence it', async t => {
// localhost resolves to a loopback address, which PUSH_AGENT refuses — every send fails locally
// and quietly, and "push send failed" in the log is the proof that a send was attempted.
const mk = (deviceId, n) => ({ userId: 'u_test_1', endpoint: `https://localhost/${n}`, keys, deviceId, created: new Date().toISOString() });
const h = await startServer(t, [mk('dev_phone000', 'phone'), mk('dev_desk0000', 'desk')]);
const sends = () => (h.log.match(/push send failed u_test_1/g) || []).length;
assert.equal((await post(h, '/api/push/rest-timer', { seconds: 1, deviceId: 'dev_phone000' })).status, 200);
assert.equal((await post(h, '/api/push/rest-timer/cancel', { deviceId: 'dev_desk0000' })).status, 200);
await new Promise(r => setTimeout(r, 2500));
assert.equal(sends(), 1, `the phone's alert went out, to the phone's subscription only:\n${h.log}`);
assert.equal((await post(h, '/api/push/rest-timer', { seconds: 1, deviceId: 'dev_phone000' })).status, 200);
assert.equal((await post(h, '/api/push/rest-timer/cancel', { deviceId: 'dev_phone000' })).status, 200);
await new Promise(r => setTimeout(r, 2500));
assert.equal(sends(), 1, 'cancelled by its own device: nothing more went out');
// an older client, no device id: the account-wide behaviour it always had
assert.equal((await post(h, '/api/push/rest-timer', { seconds: 1 })).status, 200);
assert.equal((await post(h, '/api/push/rest-timer/cancel', {})).status, 200);
await new Promise(r => setTimeout(r, 2500));
assert.equal(sends(), 1, 'legacy cancel clears the legacy timer');
assert.equal((await post(h, '/api/push/rest-timer', { seconds: 1 })).status, 200);
await new Promise(r => setTimeout(r, 2500));
assert.equal(sends(), 3, 'a legacy timer goes to every subscription of the account');
});
+51 -1
View File
@@ -42,7 +42,7 @@ async function startServer(t, subs = []) {
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' }
env: { ...process.env, PORT: String(port), DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost', REMINDER_TICK_MS: '300' }
});
const h = { api: `http://127.0.0.1:${port}`, dataDir, child, log: '' };
child.stdout.on('data', d => h.log += d);
@@ -113,3 +113,53 @@ test('a non-array workouts on disk is logged and skipped by the reminder tick; t
const db = JSON.parse(fs.readFileSync(path.join(h.dataDir, 'db.json'), 'utf8'));
assert.ok(db.users.find(u => u.id === 'u_test_2').lastReminder, 'the good user\'s reminder was recorded');
});
/* The catch-up window. The tick used to want the exact minute — an API restart or a stalled
tick across those 60 s lost the whole day's reminder. A reminder is now owed for 15 minutes
after its time, once per local date, and not later than that. */
const hhmmMinusMinutes = m => {
const d = new Date(Date.now() - m * 60000);
const parts = new Intl.DateTimeFormat('en-CA', { timeZone: 'UTC', hour12: false, hour: '2-digit', minute: '2-digit' }).formatToParts(d);
const g = type => parts.find(p => p.type === type)?.value;
return { hhmm: `${g('hour')}:${g('minute')}`, sameDay: d.getUTCDate() === new Date().getUTCDate() };
};
const goodState = (time, over = {}) => JSON.stringify({
reminder: { on: true, time, tz: 'UTC' },
routines: [{ id: 'r1', name: 'Full body', emoji: '💪', ex: [] }],
week: { 0: 'r1', 1: 'r1', 2: 'r1', 3: 'r1', 4: 'r1', 5: 'r1', 6: 'r1' },
workouts: [], ...over
});
const sub = { userId: 'u_test_1', endpoint: 'https://localhost/x', keys: { p256dh: 'p', auth: 'a' }, created: new Date().toISOString() };
const firings = log => (log.match(/reminder firing u_test_1 r1/g) || []).length;
const wait = ms => new Promise(r => setTimeout(r, ms));
test('a reminder whose minute passed 3 minutes ago still fires — once', async t => {
const late = hhmmMinusMinutes(3);
if (!late.sameDay) return t.skip('just after midnight UTC — a same-day window cannot be set up');
const h = await startServer(t, [sub]);
fs.writeFileSync(path.join(h.dataDir, 'state-u_test_1.json'), goodState(late.hhmm));
const deadline = Date.now() + 30000;
while (Date.now() < deadline && !firings(h.log)) await wait(300);
assert.equal(firings(h.log), 1, h.log);
// several more ticks: the date-level dedupe holds inside the window
await wait(1500);
assert.equal(firings(h.log), 1, 'fired again inside the window');
const db = JSON.parse(fs.readFileSync(path.join(h.dataDir, 'db.json'), 'utf8'));
assert.ok(db.users.find(u => u.id === 'u_test_1').lastReminder, 'the day is recorded');
});
test('a reminder 20 minutes past is not delivered late, and a day already trained is skipped', async t => {
const stale = hhmmMinusMinutes(20);
const late = hhmmMinusMinutes(2);
if (!stale.sameDay || !late.sameDay) return t.skip('just after midnight UTC — a same-day window cannot be set up');
const h = await startServer(t, [sub]);
const file = path.join(h.dataDir, 'state-u_test_1.json');
fs.writeFileSync(file, goodState(stale.hhmm));
await wait(1500); // several ticks
assert.equal(firings(h.log), 0, `20 minutes late must stay silent:\n${h.log}`);
// inside the window but today's workout is already logged
const today = new Intl.DateTimeFormat('en-CA', { timeZone: 'UTC', year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date());
fs.writeFileSync(file, goodState(late.hhmm, { workouts: [{ id: 'w1', d: today }] }));
await wait(1500);
assert.equal(firings(h.log), 0, `a trained day must stay silent:\n${h.log}`);
});