Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

extract the daily-reminder scheduler POST and the story prompt now share

[._.]/ Adam Eivya6d9c59e2336
diff --git a/server/lib/timezone.js b/server/lib/timezone.js
index 743123bbb8..a8982128f3 100644
--- a/server/lib/timezone.js
+++ b/server/lib/timezone.js
@@ -113,6 +113,27 @@ export function todayInTimezone(timezone, atDate = new Date()) {
return `${parts.year}-${String(parts.month).padStart(2, '0')}-${String(parts.day).padStart(2, '0')}`
}
+/**
+ * Does a UTC timestamp fall on the given "YYYY-MM-DD" LOCAL calendar day?
+ *
+ * The question every day-scoped "did this already happen today" gate asks: a
+ * record carries a precise UTC instant, the day bucket it must be compared
+ * against is a local calendar day, and for any negative-UTC-offset zone the two
+ * disagree for several hours around the rollover. Keyed through
+ * `todayInTimezone` so the record's day and the scheduler's "today" are derived
+ * by one rule rather than two that must stay byte-identical.
+ *
+ * A missing or unparseable timestamp answers false — "no evidence it happened
+ * today" — rather than throwing, because every caller is a guard deciding
+ * whether to stay quiet.
+ */
+export function isLocalDay(timestamp, timezone, dayStr) {
+ if (!timestamp) return false
+ const at = new Date(timestamp)
+ if (Number.isNaN(at.getTime())) return false
+ return todayInTimezone(timezone, at) === dayStr
+}
+
const DAY_MS = 24 * 60 * 60 * 1000
const LOCAL_DAY_SEARCH_RADIUS_MS = 36 * 60 * 60 * 1000
@@ -272,3 +293,16 @@ export function isWithinTimeWindow({ start, end, nowMinutes }) {
// Overnight wrap: in-window if at-or-after start OR before end.
return nowMinutes >= s || nowMinutes < e
}
+
+// "HH:MM" → the daily cron expression ("M H * * *") that fires at that local
+// wall-clock time. STRICT on purpose (zero-padded hour): the value comes from
+// a user-editable reminder setting, and a malformed one must be visible as a
+// refusal to schedule rather than silently rounded into some other slot — so
+// this returns null and the caller cancels instead of registering a bad cron.
+// Shared by every daily-reminder scheduler (POST, autobiography) so two of
+// them cannot drift on what "09:00" registers as.
+export function dailyCronFromHHMM(time) {
+ if (typeof time !== 'string' || !HHMM_STRICT_RE.test(time)) return null
+ const [hour, minute] = time.split(':').map(Number)
+ return `${minute} ${hour} * * *`
+}
diff --git a/server/services/dailyReminderScheduler.js b/server/services/dailyReminderScheduler.js
new file mode 100644
index 0000000000..e1c5c690e2
--- /dev/null
+++ b/server/services/dailyReminderScheduler.js
@@ -0,0 +1,255 @@
+/**
+ * Daily Reminder Scheduler — the shared machinery behind every opt-in,
+ * user-timed "you haven't done X today" nudge.
+ *
+ * Two features had grown byte-identical copies of this: the POST session
+ * reminder and the autobiography story prompt. What actually differs between
+ * them is two predicates and a notification; everything else — cron
+ * registration, the feature gate, the fire-time re-read, the day-scoped
+ * duplicate guard, the missed-slot catch-up and its two `updatedAt` floors, the
+ * timezone-change reconcile — is the same code twice, and it is the subtle
+ * half. The catch-up floors in particular are bug-fix history (#2015, #2040):
+ * duplicated, the third such fix has to be found and made in two places.
+ *
+ * A feature supplies:
+ * - `alreadyHandledToday({ timezone, todayStr })` — did the user already do
+ * the thing this reminder nags about, on their LOCAL calendar day?
+ * - `notify()` — send the nudge.
+ * - where to read its `{ enabled, time, updatedAt }` slice, and which event
+ * announces a save of it.
+ *
+ * Nothing here calls an AI provider. A reminder is a deterministic cron nudge,
+ * which is what keeps it inside AGENTS.md's AI Provider Usage Policy even
+ * before the "user-configured scheduled automation" exception applies.
+ */
+
+import { schedule, cancel, parseCronToPrevRun } from './eventScheduler.js';
+import { todayInTimezone, isLocalDay, dailyCronFromHHMM } from '../lib/timezone.js';
+import { getUserTimezone, getTimezoneUpdatedAt } from './userTimezone.js';
+import { isInstanceFeatureEnabled } from './instanceFeatures.js';
+import { getNotifications } from './notifications.js';
+import { settingsEvents } from './settings.js';
+
+/**
+ * Normalize an ISO string or epoch-ms number to a UTC-ms floor, treating
+ * unset/invalid as 0 so it never gates. Sentinel-guarded on purpose: an install
+ * that never recorded the value must keep plain catch-up rather than losing it.
+ */
+function toMs(value) {
+ if (!value) return 0;
+ const t = typeof value === 'number' ? value : new Date(value).getTime();
+ return Number.isFinite(t) ? t : 0;
+}
+
+/**
+ * @param {Object} spec
+ * @param {string} spec.id - eventScheduler registration id (also the cancel key)
+ * @param {string} spec.logPrefix - emoji-prefixed label for this reminder's logs
+ * @param {string} spec.featureId - instance feature that gates the whole reminder
+ * @param {() => Promise<{enabled?: boolean, time?: string, updatedAt?: string}>} spec.readReminderSlice
+ * @param {string} spec.notificationType - type used for the day-scoped duplicate guard
+ * @param {(ctx: {timezone: string, todayStr: string}) => Promise<boolean>} spec.alreadyHandledToday
+ * @param {() => Promise<void>} spec.notify
+ * @param {{emitter: {on: Function}, event: string}} [spec.configEvents] - save announcement to reconcile on
+ * @returns {{eventId: string, fire: Function, register: Function, reconcile: Function, stop: Function}}
+ */
+export function createDailyReminderScheduler({
+ id,
+ logPrefix,
+ featureId,
+ readReminderSlice,
+ notificationType,
+ alreadyHandledToday,
+ notify,
+ configEvents
+}) {
+ // Timezone actually applied to the current registration — tracked so a global
+ // settings save that doesn't touch the timezone (most of them) skips a
+ // redundant reschedule + log line. Null whenever nothing is registered, which
+ // is also what makes a re-enable reschedule rather than short-circuit.
+ let lastAppliedTimezone = null;
+
+ const unregister = () => {
+ cancel(id);
+ lastAppliedTimezone = null;
+ };
+
+ /**
+ * Fire the nudge if — and only if — it is still wanted. Re-reads the feature
+ * flag and the config at fire time so a disable between registration and the
+ * scheduled minute is respected instead of nagging once more.
+ */
+ async function fire() {
+ if (!await isInstanceFeatureEnabled(featureId)) {
+ console.log(`${logPrefix}: feature disabled on this instance — skipping`);
+ return;
+ }
+
+ const slice = await readReminderSlice();
+ if (slice?.enabled !== true) {
+ console.log(`${logPrefix}: disabled since registration — skipping`);
+ return;
+ }
+
+ // The cron fires on the user's LOCAL wall-clock time, so every "today" here
+ // is their local calendar day, derived from each record's own precise UTC
+ // timestamp — never from a coarser UTC-dated bucket, which for any
+ // negative-offset zone rolls over hours before local midnight.
+ const timezone = await getUserTimezone();
+ const todayStr = todayInTimezone(timezone);
+
+ if (await alreadyHandledToday({ timezone, todayStr })) {
+ console.log(`${logPrefix}: already handled today — no nudge`);
+ return;
+ }
+
+ // De-dupe against a nudge already sent today. Without this the missed-slot
+ // catch-up (run on every server restart) would re-nag if the server
+ // restarts again later the same day after the normal tick already fired —
+ // "still outstanding" alone doesn't prove this run is the first one today.
+ // Day-scoped rather than `notifications.exists(type)`, which matches ANY
+ // notification of the type ever sent: that would silence the reminder
+ // permanently after its first nudge.
+ const existing = await getNotifications({ type: notificationType });
+ if (existing.some(n => isLocalDay(n?.timestamp, timezone, todayStr))) {
+ console.log(`${logPrefix}: already notified today — skipping duplicate`);
+ return;
+ }
+
+ await notify();
+ }
+
+ /**
+ * If today's cron slot has already elapsed (the server was down, or just
+ * booted after the scheduled minute), fire now instead of waiting for
+ * tomorrow.
+ *
+ * `parseCronToPrevRun` always returns SOME past occurrence — typically last
+ * night's, which already fired normally — whenever `now` is earlier in the
+ * day than the configured time. A bound expressed in elapsed time can't tell
+ * "yesterday's slot, already handled" from "today's slot, genuinely missed",
+ * so the gate is whether the occurrence lands on TODAY'S LOCAL CALENDAR DAY.
+ *
+ * The two floors then refuse a slot the CURRENT configuration never owned:
+ * - `reminder.updatedAt` — enabling the reminder (or changing its time) for
+ * an already-past time today, then restarting later that same day, would
+ * otherwise replay a slot that happened under different, possibly
+ * disabled, settings.
+ * - the global timezone's `updatedAt` (#2040) — switching zones can make
+ * today's slot newly appear elapsed, and a restart before the next
+ * natural tick would replay an occurrence never scheduled under the zone
+ * active when it "happened".
+ * Both are sentinel-guarded, so an install that recorded neither keeps the
+ * backward-compatible catch-up it already had. `fire` is itself idempotent,
+ * so a rare false positive at this gate is safe.
+ */
+ async function catchUpMissedSlot(cron, timezone, reminderUpdatedAt, timezoneUpdatedAt) {
+ const prevRun = parseCronToPrevRun(cron, new Date(), timezone);
+ if (!prevRun) return;
+
+ const prevRunMs = prevRun.getTime();
+ if (!isLocalDay(prevRunMs, timezone, todayInTimezone(timezone))) return;
+
+ const cutoff = Math.max(toMs(reminderUpdatedAt), toMs(timezoneUpdatedAt));
+ if (cutoff && prevRunMs < cutoff) {
+ console.log(`${logPrefix}: missed slot (${prevRun.toISOString()}) predates last config/timezone change — skipping catch-up`);
+ return;
+ }
+
+ console.log(`${logPrefix}: missed slot detected (${prevRun.toISOString()}) — catching up now`);
+ await fire();
+ }
+
+ /**
+ * Register (or cancel) the daily cron from the current config. Safe to call
+ * repeatedly — `schedule()` replaces any existing registration under the same
+ * id, so this doubles as the reconciler.
+ *
+ * @param {Object} [options]
+ * @param {boolean} [options.catchUpMissedSlot] - Check for and fire a slot
+ * that already elapsed (server-restart recovery). Only the boot-time call
+ * sets this; a reschedule from a config or timezone save must not replay a
+ * slot the user did not miss.
+ */
+ async function register({ catchUpMissedSlot: shouldCatchUp = false } = {}) {
+ if (!await isInstanceFeatureEnabled(featureId)) {
+ unregister();
+ return;
+ }
+
+ const { enabled, time, updatedAt } = await readReminderSlice() || {};
+ if (!enabled) {
+ unregister();
+ return;
+ }
+
+ const cron = dailyCronFromHHMM(time);
+ if (!cron) {
+ console.error(`❌ ${logPrefix}: invalid time "${time}" — not scheduling`);
+ unregister();
+ return;
+ }
+
+ const timezone = await getUserTimezone();
+ lastAppliedTimezone = timezone;
+ schedule({ id, type: 'cron', cron, timezone, handler: fire, metadata: { source: id } });
+ console.log(`${logPrefix}: registered daily at ${time} (${timezone})`);
+
+ if (shouldCatchUp) {
+ await catchUpMissedSlot(cron, timezone, updatedAt, await getTimezoneUpdatedAt());
+ }
+ }
+
+ /**
+ * Bring the registration back in line with state that changed elsewhere — the
+ * feature toggle or the user's GLOBAL timezone. AGENTS.md requires a feature
+ * toggle that arms background work to reconcile it at toggle time, not only
+ * at boot; both ride the same `settings:updated` event, so this is the one
+ * handler for both. It re-registers only when the effective timezone actually
+ * changed, so tweaking an unrelated setting doesn't spam a reschedule.
+ */
+ async function reconcile() {
+ if (!await isInstanceFeatureEnabled(featureId)) {
+ unregister();
+ return;
+ }
+
+ const slice = await readReminderSlice();
+ if (slice?.enabled !== true) {
+ unregister();
+ return;
+ }
+
+ const timezone = await getUserTimezone();
+ // A null `lastAppliedTimezone` means nothing is currently registered (boot,
+ // or a cancel from a feature/reminder disable), so this re-arms rather than
+ // short-circuiting — that is what makes re-enabling take effect at once.
+ if (timezone === lastAppliedTimezone) return;
+
+ console.log(`${logPrefix}: rescheduling (timezone ${lastAppliedTimezone || 'unset'} → ${timezone})`);
+ await register();
+ }
+
+ settingsEvents.on('settings:updated', () => {
+ reconcile().catch(err => console.error(`❌ ${logPrefix} reconcile failed: ${err.message}`));
+ });
+
+ // Reschedule-on-save lives here rather than in a route handler so every
+ // current and future caller of the feature's config updater gets it for free
+ // (#2015). Gated on the `reminder` slice actually being in the patch, so
+ // unrelated config saves don't trigger a redundant reschedule + log line.
+ if (configEvents) {
+ configEvents.emitter.on(configEvents.event, ({ updates } = {}) => {
+ if (!updates?.reminder) return;
+ register().catch(err => console.error(`❌ ${logPrefix} reschedule failed: ${err.message}`));
+ });
+ }
+
+ return {
+ eventId: id,
+ fire,
+ register,
+ reconcile,
+ stop: unregister
+ };
+}
diff --git a/server/services/dailyReminderScheduler.test.js b/server/services/dailyReminderScheduler.test.js
new file mode 100644
index 0000000000..4dfd7931d3
--- /dev/null
+++ b/server/services/dailyReminderScheduler.test.js
@@ -0,0 +1,429 @@
+/**
+ * Tests for the shared daily-reminder machinery: the half that used to be
+ * duplicated between the POST reminder and the autobiography story prompt.
+ *
+ * Covered here ONCE, through a synthetic feature, so the rules can't drift
+ * between the two real ones: when a cron is registered at all (feature flag,
+ * `reminder.enabled`, a malformed time), the fire-time re-reads, the day-scoped
+ * duplicate guard, the missed-slot catch-up and both of its `updatedAt` floors
+ * (#2015, #2040), and the two re-registration paths. Each real reminder's own
+ * suite then covers only what is specific to it.
+ *
+ * The timezone helpers are deliberately NOT mocked — the local-day arithmetic
+ * is the thing under test, and a stub would assert nothing about it.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+const settingsEventEmitter = vi.hoisted(() => {
+ const listeners = {};
+ return {
+ on(event, fn) { (listeners[event] ||= []).push(fn); },
+ emit(event, ...args) { (listeners[event] || []).forEach(fn => fn(...args)); },
+ };
+});
+const configEventEmitter = vi.hoisted(() => {
+ const listeners = {};
+ return {
+ on(event, fn) { (listeners[event] ||= []).push(fn); },
+ emit(event, ...args) { (listeners[event] || []).forEach(fn => fn(...args)); },
+ };
+});
+
+vi.mock('./eventScheduler.js', () => ({
+ schedule: vi.fn(),
+ cancel: vi.fn(),
+ parseCronToPrevRun: vi.fn()
+}));
+vi.mock('./userTimezone.js', () => ({
+ getUserTimezone: vi.fn().mockResolvedValue('UTC'),
+ getTimezoneUpdatedAt: vi.fn().mockResolvedValue(null),
+}));
+vi.mock('./instanceFeatures.js', () => ({
+ isInstanceFeatureEnabled: vi.fn().mockResolvedValue(true),
+}));
+vi.mock('./notifications.js', () => ({
+ getNotifications: vi.fn().mockResolvedValue([]),
+}));
+vi.mock('./settings.js', () => ({ settingsEvents: settingsEventEmitter }));
+
+const { schedule, cancel, parseCronToPrevRun } = await import('./eventScheduler.js');
+const { getUserTimezone, getTimezoneUpdatedAt } = await import('./userTimezone.js');
+const { isInstanceFeatureEnabled } = await import('./instanceFeatures.js');
+const { getNotifications } = await import('./notifications.js');
+const { createDailyReminderScheduler } = await import('./dailyReminderScheduler.js');
+
+const EVENT_ID = 'test-daily-reminder';
+const readReminderSlice = vi.fn();
+const alreadyHandledToday = vi.fn();
+const notify = vi.fn();
+
+const scheduler = createDailyReminderScheduler({
+ id: EVENT_ID,
+ logPrefix: '🧪 Test reminder',
+ featureId: 'test-feature',
+ notificationType: 'test_reminder',
+ readReminderSlice,
+ alreadyHandledToday,
+ notify,
+ configEvents: { emitter: configEventEmitter, event: 'test-config:updated' }
+});
+
+// Only Date is faked — `vi.waitFor` in the re-registration tests needs real
+// timers, and the rest only needs a fixed "now".
+const freezeClock = (iso) => vi.useFakeTimers({ now: new Date(iso), toFake: ['Date'] });
+
+beforeEach(() => {
+ scheduler.stop();
+ vi.clearAllMocks();
+ isInstanceFeatureEnabled.mockResolvedValue(true);
+ getUserTimezone.mockResolvedValue('UTC');
+ getTimezoneUpdatedAt.mockResolvedValue(null);
+ getNotifications.mockResolvedValue([]);
+ parseCronToPrevRun.mockReturnValue(null);
+ readReminderSlice.mockResolvedValue({ enabled: true, time: '09:00' });
+ alreadyHandledToday.mockResolvedValue(false);
+ notify.mockResolvedValue(undefined);
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('register', () => {
+ it('registers a daily cron at the configured local time', async () => {
+ await scheduler.register();
+
+ expect(schedule).toHaveBeenCalledTimes(1);
+ expect(schedule.mock.calls[0][0]).toMatchObject({
+ id: EVENT_ID, type: 'cron', cron: '0 9 * * *', timezone: 'UTC'
+ });
+ });
+
+ it('cancels instead of scheduling when the instance feature is off', async () => {
+ isInstanceFeatureEnabled.mockResolvedValue(false);
+
+ await scheduler.register();
+
+ expect(schedule).not.toHaveBeenCalled();
+ expect(cancel).toHaveBeenCalledWith(EVENT_ID);
+ // The feature flag short-circuits before the config is even read.
+ expect(readReminderSlice).not.toHaveBeenCalled();
+ });
+
+ it('cancels instead of scheduling when the reminder is disabled (the default)', async () => {
+ readReminderSlice.mockResolvedValue({ enabled: false, time: '09:00' });
+
+ await scheduler.register();
+
+ expect(schedule).not.toHaveBeenCalled();
+ expect(cancel).toHaveBeenCalledWith(EVENT_ID);
+ });
+
+ it('cancels when the reminder slice is entirely absent', async () => {
+ readReminderSlice.mockResolvedValue(undefined);
+
+ await scheduler.register();
+
+ expect(schedule).not.toHaveBeenCalled();
+ expect(cancel).toHaveBeenCalledWith(EVENT_ID);
+ });
+
+ it('refuses a malformed time rather than registering a bad cron', async () => {
+ readReminderSlice.mockResolvedValue({ enabled: true, time: '9:00' });
+
+ await scheduler.register();
+
+ expect(schedule).not.toHaveBeenCalled();
+ expect(cancel).toHaveBeenCalledWith(EVENT_ID);
+ });
+
+ it('re-registers under the same id rather than accumulating registrations', async () => {
+ await scheduler.register();
+ readReminderSlice.mockResolvedValue({ enabled: true, time: '18:30' });
+ await scheduler.register();
+
+ expect(schedule).toHaveBeenCalledTimes(2);
+ expect(schedule.mock.calls[1][0]).toMatchObject({ id: EVENT_ID, cron: '30 18 * * *' });
+ });
+
+ it('does not look for a missed slot unless catch-up was requested', async () => {
+ await scheduler.register();
+
+ expect(parseCronToPrevRun).not.toHaveBeenCalled();
+ expect(notify).not.toHaveBeenCalled();
+ });
+});
+
+describe('fire', () => {
+ beforeEach(() => {
+ freezeClock('2026-07-01T12:00:00.000Z');
+ });
+
+ it('notifies when the thing is still outstanding today', async () => {
+ await scheduler.fire();
+
+ expect(notify).toHaveBeenCalledTimes(1);
+ expect(alreadyHandledToday).toHaveBeenCalledWith({ timezone: 'UTC', todayStr: '2026-07-01' });
+ });
+
+ it('stays silent when the feature was turned off since registration', async () => {
+ isInstanceFeatureEnabled.mockResolvedValue(false);
+
+ await scheduler.fire();
+
+ expect(notify).not.toHaveBeenCalled();
+ expect(readReminderSlice).not.toHaveBeenCalled();
+ });
+
+ it('re-reads config at fire time so a disable since registration is respected', async () => {
+ readReminderSlice.mockResolvedValue({ enabled: false, time: '09:00' });
+
+ await scheduler.fire();
+
+ expect(notify).not.toHaveBeenCalled();
+ expect(alreadyHandledToday).not.toHaveBeenCalled();
+ });
+
+ it('stays silent when the feature says today is already handled', async () => {
+ alreadyHandledToday.mockResolvedValue(true);
+
+ await scheduler.fire();
+
+ expect(notify).not.toHaveBeenCalled();
+ });
+
+ it('does not nudge twice for the same local day', async () => {
+ getNotifications.mockResolvedValue([{ timestamp: '2026-07-01T09:00:05.000Z' }]);
+
+ await scheduler.fire();
+
+ expect(notify).not.toHaveBeenCalled();
+ });
+
+ // Regression: the guard must be DAY-scoped, not "has this type ever been
+ // sent". `notifications.exists(type)` matches any notification of the type
+ // ever created, which would silence a daily reminder permanently after its
+ // very first nudge.
+ it('nudges again the next day, even though yesterday\'s notification still exists', async () => {
+ getNotifications.mockResolvedValue([
+ { timestamp: '2026-06-30T09:00:05.000Z' },
+ { timestamp: '2026-06-29T09:00:05.000Z' }
+ ]);
+
+ await scheduler.fire();
+
+ expect(notify).toHaveBeenCalledTimes(1);
+ });
+
+ it('judges "today" by the local calendar day, not the UTC one', async () => {
+ // 2026-07-01T12:00Z is 05:00 on the 1st in Los Angeles. A notification
+ // stamped 2026-07-01T04:00Z is 21:00 on JUNE 30 there — yesterday for this
+ // user — so today's nudge must still go out. Comparing raw UTC dates would
+ // see two 2026-07-01 stamps and suppress it.
+ getUserTimezone.mockResolvedValue('America/Los_Angeles');
+ getNotifications.mockResolvedValue([{ timestamp: '2026-07-01T04:00:00.000Z' }]);
+
+ await scheduler.fire();
+
+ expect(notify).toHaveBeenCalledTimes(1);
+ expect(alreadyHandledToday).toHaveBeenCalledWith({
+ timezone: 'America/Los_Angeles', todayStr: '2026-07-01'
+ });
+ });
+});
+
+describe('missed-slot catch-up', () => {
+ beforeEach(() => {
+ freezeClock('2026-07-01T12:00:00.000Z');
+ });
+
+ it('fires for a slot that already elapsed today', async () => {
+ parseCronToPrevRun.mockReturnValue(new Date('2026-07-01T09:00:00.000Z'));
+
+ await scheduler.register({ catchUpMissedSlot: true });
+
+ expect(notify).toHaveBeenCalledTimes(1);
+ });
+
+ it('does nothing when there is no prior occurrence at all', async () => {
+ parseCronToPrevRun.mockReturnValue(null);
+
+ await scheduler.register({ catchUpMissedSlot: true });
+
+ expect(notify).not.toHaveBeenCalled();
+ expect(alreadyHandledToday).not.toHaveBeenCalled();
+ });
+
+ // parseCronToPrevRun always returns SOME past occurrence — for a 09:00
+ // reminder booted at 07:00 that is YESTERDAY's slot, which already fired last
+ // night. Without the local-day gate, every boot before the scheduled hour
+ // would send a spurious nudge.
+ it('skips a slot that fell on a previous local day', async () => {
+ parseCronToPrevRun.mockReturnValue(new Date('2026-06-30T09:00:00.000Z'));
+
+ await scheduler.register({ catchUpMissedSlot: true });
+
+ expect(notify).not.toHaveBeenCalled();
+ expect(alreadyHandledToday).not.toHaveBeenCalled();
+ });
+
+ it('skips a slot that predates the reminder config change that owns it', async () => {
+ readReminderSlice.mockResolvedValue({ enabled: true, time: '09:00', updatedAt: '2026-07-01T10:00:00.000Z' });
+ parseCronToPrevRun.mockReturnValue(new Date('2026-07-01T09:00:00.000Z'));
+
+ await scheduler.register({ catchUpMissedSlot: true });
+
+ expect(notify).not.toHaveBeenCalled();
+ });
+
+ it('fires for a slot that postdates the reminder config change', async () => {
+ readReminderSlice.mockResolvedValue({ enabled: true, time: '09:00', updatedAt: '2026-06-01T00:00:00.000Z' });
+ parseCronToPrevRun.mockReturnValue(new Date('2026-07-01T09:00:00.000Z'));
+
+ await scheduler.register({ catchUpMissedSlot: true });
+
+ expect(notify).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps plain catch-up on a config saved before updatedAt existed', async () => {
+ parseCronToPrevRun.mockReturnValue(new Date('2026-07-01T09:00:00.000Z'));
+
+ await scheduler.register({ catchUpMissedSlot: true });
+
+ expect(notify).toHaveBeenCalledTimes(1);
+ });
+
+ // #2040: a zone switch can make today's slot newly appear elapsed, and a
+ // restart before the next natural tick would replay an occurrence that was
+ // never scheduled under the zone active when it "happened".
+ it('skips a slot that predates the last global timezone change', async () => {
+ parseCronToPrevRun.mockReturnValue(new Date('2026-07-01T09:00:00.000Z'));
+ getTimezoneUpdatedAt.mockResolvedValue(Date.parse('2026-07-01T10:00:00.000Z'));
+
+ await scheduler.register({ catchUpMissedSlot: true });
+
+ expect(notify).not.toHaveBeenCalled();
+ });
+
+ it('fires for a slot that postdates the last global timezone change', async () => {
+ parseCronToPrevRun.mockReturnValue(new Date('2026-07-01T09:00:00.000Z'));
+ getTimezoneUpdatedAt.mockResolvedValue(Date.parse('2026-06-01T00:00:00.000Z'));
+
+ await scheduler.register({ catchUpMissedSlot: true });
+
+ expect(notify).toHaveBeenCalledTimes(1);
+ });
+
+ it('uses the LATER of the two cutoffs — timezone wins', async () => {
+ readReminderSlice.mockResolvedValue({ enabled: true, time: '09:00', updatedAt: '2026-07-01T08:00:00.000Z' });
+ parseCronToPrevRun.mockReturnValue(new Date('2026-07-01T09:00:00.000Z'));
+ getTimezoneUpdatedAt.mockResolvedValue(Date.parse('2026-07-01T10:00:00.000Z'));
+
+ await scheduler.register({ catchUpMissedSlot: true });
+
+ expect(notify).not.toHaveBeenCalled();
+ });
+
+ it('uses the LATER of the two cutoffs — reminder config wins', async () => {
+ readReminderSlice.mockResolvedValue({ enabled: true, time: '09:00', updatedAt: '2026-07-01T10:00:00.000Z' });
+ parseCronToPrevRun.mockReturnValue(new Date('2026-07-01T09:00:00.000Z'));
+ getTimezoneUpdatedAt.mockResolvedValue(Date.parse('2026-07-01T08:00:00.000Z'));
+
+ await scheduler.register({ catchUpMissedSlot: true });
+
+ expect(notify).not.toHaveBeenCalled();
+ });
+
+ it('is idempotent — catch-up still respects the already-handled-today gate', async () => {
+ alreadyHandledToday.mockResolvedValue(true);
+ parseCronToPrevRun.mockReturnValue(new Date('2026-07-01T09:00:00.000Z'));
+
+ await scheduler.register({ catchUpMissedSlot: true });
+
+ expect(notify).not.toHaveBeenCalled();
+ });
+});
+
+describe('reconcile via settingsEvents', () => {
+ it('reschedules when the global timezone changes', async () => {
+ await scheduler.register();
+ schedule.mockClear();
+ getUserTimezone.mockResolvedValue('America/Los_Angeles');
+
+ settingsEventEmitter.emit('settings:updated');
+
+ await vi.waitFor(() => expect(schedule).toHaveBeenCalledTimes(1));
+ expect(schedule.mock.calls[0][0]).toMatchObject({ timezone: 'America/Los_Angeles' });
+ });
+
+ it('does not reschedule when the effective timezone is unchanged', async () => {
+ await scheduler.register();
+ schedule.mockClear();
+
+ settingsEventEmitter.emit('settings:updated');
+
+ await new Promise(resolve => setImmediate(resolve));
+ expect(schedule).not.toHaveBeenCalled();
+ });
+
+ // AGENTS.md: a feature toggle that arms background work must reconcile it at
+ // toggle time, not only at boot. Turning the instance feature off has to
+ // cancel a live registration on the same `settings:updated` event the toggle
+ // rides, rather than leaving the cron armed until the next restart.
+ it('cancels a live registration when the instance feature is turned off', async () => {
+ await scheduler.register();
+ cancel.mockClear();
+ isInstanceFeatureEnabled.mockResolvedValue(false);
+
+ settingsEventEmitter.emit('settings:updated');
+
+ await vi.waitFor(() => expect(cancel).toHaveBeenCalledWith(EVENT_ID));
+ });
+
+ it('re-arms after a disable/re-enable cycle', async () => {
+ await scheduler.register();
+ isInstanceFeatureEnabled.mockResolvedValue(false);
+ settingsEventEmitter.emit('settings:updated');
+ await vi.waitFor(() => expect(cancel).toHaveBeenCalledWith(EVENT_ID));
+
+ schedule.mockClear();
+ isInstanceFeatureEnabled.mockResolvedValue(true);
+ settingsEventEmitter.emit('settings:updated');
+
+ await vi.waitFor(() => expect(schedule).toHaveBeenCalledTimes(1));
+ });
+
+ it('does nothing when the reminder itself is disabled', async () => {
+ readReminderSlice.mockResolvedValue({ enabled: false, time: '09:00' });
+
+ settingsEventEmitter.emit('settings:updated');
+
+ await new Promise(resolve => setImmediate(resolve));
+ expect(schedule).not.toHaveBeenCalled();
+ });
+});
+
+describe('reschedule via the feature\'s config events', () => {
+ it('reschedules when the saved patch touches the reminder slice', async () => {
+ configEventEmitter.emit('test-config:updated', { updates: { reminder: { time: '07:30' } } });
+
+ await vi.waitFor(() => expect(schedule).toHaveBeenCalledTimes(1));
+ });
+
+ it('ignores a saved patch that does not touch the reminder slice', async () => {
+ configEventEmitter.emit('test-config:updated', { updates: { somethingElse: true } });
+
+ await new Promise(resolve => setImmediate(resolve));
+ expect(schedule).not.toHaveBeenCalled();
+ expect(readReminderSlice).not.toHaveBeenCalled();
+ });
+});
+
+describe('stop', () => {
+ it('cancels the registration', () => {
+ scheduler.stop();
+
+ expect(cancel).toHaveBeenCalledWith(EVENT_ID);
+ });
+});
diff --git a/server/services/meatspacePostReminder.js b/server/services/meatspacePostReminder.js
index 2abca1eb3f..ac2a9b17a0 100644
--- a/server/services/meatspacePostReminder.js
+++ b/server/services/meatspacePostReminder.js
@@ -3,295 +3,51 @@
*
* Optional, opt-in (default OFF) scheduled nudge: fires a single deterministic
* (no LLM) in-app notification at a user-chosen time-of-day when today's POST
- * (Power On Self Test) session is still incomplete. Nothing here calls an AI
- * provider — the "scheduled automations are user-configured" exception in
- * AGENTS.md's AI Provider Usage Policy covers this even though it's moot, since
- * this feature makes zero LLM calls of its own.
+ * (Power On Self Test) session is still incomplete.
*
- * Mirrors backupScheduler.js's daily-cron registration pattern via
- * eventScheduler.js, but — unlike backupScheduler's fixed-at-registration cron
- * expression — the time-of-day is user-editable at runtime:
- * registerPostReminderSchedule() is called at server boot, whenever
- * updatePostConfig() saves a `reminder` change (via meatspacePost.js's
- * postConfigEvents — see below), and whenever the user's global timezone
- * changes (via settings.js's settingsEvents) — so a changed time, enabled
- * flag, or timezone all take effect on the next tick without a restart (same
- * idea as cosJobScheduler.js's `registerSingleJobSchedule`, simplified since
- * a daily HH:MM nudge doesn't need that module's weekday/interval-fallback
- * machinery). The boot-time call additionally checks for a missed slot
- * (mirrors taskSchedule.js's `parseCronToPrevRun` catch-up) so a reminder
- * whose slot elapsed while the server was down still fires once it's back up.
+ * All the scheduling machinery — cron registration, the feature gate, the
+ * fire-time re-read, the day-scoped duplicate guard, the missed-slot catch-up
+ * and its `updatedAt` floors, the timezone reconcile — lives in
+ * dailyReminderScheduler.js. This module is the two things that are actually
+ * specific to POST: what "already handled today" means (today's session
+ * completed) and what the nudge says.
*/
-import { schedule, cancel, parseCronToPrevRun } from './eventScheduler.js';
-import { getLocalParts, todayInTimezone, HHMM_STRICT_RE } from '../lib/timezone.js';
-import { getUserTimezone, getTimezoneUpdatedAt } from './userTimezone.js';
+import { createDailyReminderScheduler } from './dailyReminderScheduler.js';
+import { isLocalDay } from '../lib/timezone.js';
import { getPostConfig, getPostSessions, postConfigEvents } from './meatspacePost.js';
-import { isInstanceFeatureEnabled } from './instanceFeatures.js';
-import { addNotification, getNotifications, NOTIFICATION_TYPES, PRIORITY_LEVELS } from './notifications.js';
-import { settingsEvents } from './settings.js';
+import { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } from './notifications.js';
export const POST_REMINDER_EVENT_ID = 'post-daily-reminder';
-// Timezone actually applied to the current cron registration — tracked so a
-// global settings save that doesn't touch the timezone (most of them) skips
-// a redundant reschedule + log line (see settingsEvents subscription below).
-// Reset to null whenever the reminder is disabled/unregistered.
-let lastAppliedTimezone = null;
-
-/**
- * Convert an "HH:MM" time-of-day into a daily cron expression ("M H * * *").
- * Pure — exported for unit testing. Returns null for a malformed/missing time
- * so callers can skip scheduling rather than register a bad cron string.
- */
-export function reminderTimeToCron(time) {
- if (typeof time !== 'string' || !HHMM_STRICT_RE.test(time)) return null;
- const [hour, minute] = time.split(':').map(Number);
- return `${minute} ${hour} * * *`;
-}
-
-/**
- * True if a UTC timestamp falls on the given "YYYY-MM-DD" LOCAL calendar day
- * (in `timezone`). Shared by both the "did today's session complete" and
- * "did a reminder already go out today" checks below — both need the same
- * UTC-timestamp-to-local-day comparison, just against a different collection.
- */
-function isOnLocalDay(timestamp, timezone, dayStr) {
- if (!timestamp) return false;
- const parts = getLocalParts(new Date(timestamp), timezone);
- const localDate = `${parts.year}-${String(parts.month).padStart(2, '0')}-${String(parts.day).padStart(2, '0')}`;
- return localDate === dayStr;
-}
-
-/**
- * Fire the reminder notification if — and only if — today's POST is still
- * incomplete. Re-reads config at fire time (mirrors backupScheduler's
- * re-check) so a disable that happened between registration and the
- * scheduled minute is respected instead of nagging once more.
- */
-export async function firePostReminderIfIncomplete() {
- if (!await isInstanceFeatureEnabled('post')) {
- console.log(`🔔 POST reminder: feature disabled on this instance — skipping`);
- return;
- }
-
- const config = await getPostConfig();
- if (config.reminder?.enabled !== true) {
- console.log(`🔔 POST reminder: disabled since registration — skipping`);
- return;
- }
-
- // The cron itself fires on the user's LOCAL wall-clock time (registerPostReminderSchedule
- // schedules it with `timezone` from getUserTimezone()), so "today" for the completeness
- // check must be the user's local calendar day. Sessions are day-bucketed server-side via
- // `session.date`, stamped from the raw UTC date (see submitPostSession in meatspacePost.js)
- // — that bucket does NOT line up with local calendar days for any non-UTC timezone, and for
- // negative-UTC-offset zones (the Americas) the UTC date can roll over several hours before
- // local midnight. Comparing against that bucket (even after converting only the "now" side
- // to local time) would still mismatch for a session completed in the gap between the UTC
- // rollover and local midnight. So this derives each session's local day directly from its
- // precise `startedAt` timestamp instead of trusting the coarse UTC-dated bucket at all —
- // correct regardless of what time of day, relative to either boundary, a session actually
- // completed.
- const timezone = await getUserTimezone();
- const todayStr = todayInTimezone(timezone);
- const sessions = await getPostSessions();
- const completedToday = sessions.some(s => isOnLocalDay(s?.startedAt, timezone, todayStr));
- if (completedToday) {
- console.log(`🔔 POST reminder: today's session already complete — no nudge`);
- return;
- }
-
- // De-dupe against a notification already sent today. Without this, the
- // missed-slot catch-up (registerPostReminderSchedule, run on every server
- // restart) would re-nag if the server restarts again later the same day
- // after the normal cron tick already fired — "still incomplete" alone
- // isn't enough to guarantee this run is the first one today.
- const existing = await getNotifications({ type: NOTIFICATION_TYPES.DAILY_POST_REMINDER });
- const alreadyNotifiedToday = existing.some(n => isOnLocalDay(n?.timestamp, timezone, todayStr));
- if (alreadyNotifiedToday) {
- console.log(`🔔 POST reminder: already notified today — skipping duplicate`);
- return;
- }
-
- await addNotification({
- type: NOTIFICATION_TYPES.DAILY_POST_REMINDER,
- title: "Today's POST is still open",
- description: "You haven't completed a Power On Self Test session today — a quick one keeps your streak alive.",
- priority: PRIORITY_LEVELS.LOW,
- link: '/post/launcher'
- });
- console.log(`🔔 POST reminder: nudge sent (today's session incomplete)`);
-}
-
-/**
- * If today's cron slot has already elapsed (the server was down or just
- * booted after the scheduled minute), fire the reminder immediately instead
- * of waiting for tomorrow's tick. Mirrors taskSchedule.js's
- * `parseCronToPrevRun`-based catch-up, but — unlike a repeating task with no
- * fixed time-of-day — a daily HH:MM reminder's "was a slot missed" question
- * has an exact answer: is the most recent past occurrence ON TODAY'S LOCAL
- * CALENDAR DAY? `parseCronToPrevRun` always returns SOME past occurrence
- * (typically "last night's", which already fired normally) whenever `now` is
- * earlier in the day than the configured time — a bound expressed only in
- * elapsed time (e.g. "within one cron period") can't distinguish "yesterday's
- * slot, already handled" from "today's slot, genuinely missed," and would
- * wrongly fire on every boot before the scheduled hour. Gating on the local
- * calendar day removes that ambiguity outright.
- *
- * `reminderUpdatedAt` (from `config.reminder.updatedAt`, stamped by
- * updatePostConfig whenever the reminder slice is saved) additionally guards
- * against replaying a slot the CURRENT settings never actually owned: if the
- * user enables the reminder (or changes its time) for an already-past time
- * today, then the server happens to restart later that same day, the most
- * recent occurrence still falls on today's local day — but it happened
- * before this configuration took effect, under whatever settings (possibly
- * disabled) were active at that moment. Absent `updatedAt` (older on-disk
- * configs saved before this field existed), skip the guard rather than
- * blocking catch-up outright — there's no information to restrict it, and
- * that's the existing behavior those installs already have.
- * `firePostReminderIfIncomplete` itself is idempotent (completedToday +
- * already-notified-today guards), so calling it here is safe even on a rare
- * false-positive gate.
- *
- * `timezoneUpdatedAt` (from getTimezoneUpdatedAt(), stamped by settings.js
- * whenever the user's GLOBAL timezone actually changes) closes the parallel
- * gap #2040 tracked: if the user switches their global timezone such that
- * today's slot newly appears to have already passed under the new zone, and
- * the server then restarts before the next natural tick, the most recent
- * occurrence still falls on today's local day — but it was never scheduled
- * under the timezone active when it "occurred." The effective floor is the
- * LATER of (reminder config last saved, timezone last changed): a slot that
- * predates EITHER wasn't genuinely owned by the configuration active at that
- * moment. Both are sentinel-guarded — an absent/unset value (null, 0, missing)
- * contributes no floor, preserving backward-compatible catch-up for installs
- * that never recorded them.
- */
-async function catchUpMissedSlot(cron, timezone, reminderUpdatedAt, timezoneUpdatedAt) {
- const now = Date.now();
- const prevRun = parseCronToPrevRun(cron, new Date(now), timezone);
- if (!prevRun) return;
-
- const prevRunMs = prevRun.getTime();
- const todayStr = todayInTimezone(timezone);
- if (!isOnLocalDay(prevRunMs, timezone, todayStr)) return;
-
- // Normalize either cutoff (ISO string reminderUpdatedAt, numeric-ms
- // timezoneUpdatedAt) to a valid UTC-ms floor, treating unset/invalid as 0 so
- // it never gates. The effective cutoff is the later of the two.
- const toMs = (v) => {
- if (!v) return 0;
- const t = typeof v === 'number' ? v : new Date(v).getTime();
- return Number.isFinite(t) ? t : 0;
- };
- const cutoff = Math.max(toMs(reminderUpdatedAt), toMs(timezoneUpdatedAt));
- if (cutoff && prevRunMs < cutoff) {
- console.log(`🔔 POST reminder: missed slot (${prevRun.toISOString()}) predates last config/timezone change — skipping catch-up`);
- return;
- }
-
- console.log(`🔔 POST reminder: missed slot detected (${prevRun.toISOString()}) — catching up now`);
- await firePostReminderIfIncomplete();
-}
-
-/**
- * Register (or cancel) the daily reminder cron job from the current POST
- * config. Safe to call repeatedly — `schedule()` replaces any existing
- * registration under the same id, so calling this again after a settings
- * change reschedules immediately.
- *
- * @param {Object} [options]
- * @param {boolean} [options.catchUpMissedSlot] - Check for and fire a slot
- * that already elapsed (server-restart recovery). Only the boot-time
- * registration in server/index.js sets this — reschedules triggered by a
- * config/timezone save should NOT replay a slot the user didn't miss.
- */
-export async function registerPostReminderSchedule({ catchUpMissedSlot: shouldCatchUp = false } = {}) {
- if (!await isInstanceFeatureEnabled('post')) {
- cancel(POST_REMINDER_EVENT_ID);
- lastAppliedTimezone = null;
- return;
- }
-
- const config = await getPostConfig();
- const { enabled, time, updatedAt } = config.reminder || {};
-
- if (!enabled) {
- cancel(POST_REMINDER_EVENT_ID);
- lastAppliedTimezone = null;
- return;
- }
-
- const cron = reminderTimeToCron(time);
- if (!cron) {
- console.error(`❌ POST reminder: invalid time "${time}" — not scheduling`);
- cancel(POST_REMINDER_EVENT_ID);
- lastAppliedTimezone = null;
- return;
- }
-
- const timezone = await getUserTimezone();
- lastAppliedTimezone = timezone;
- schedule({
- id: POST_REMINDER_EVENT_ID,
- type: 'cron',
- cron,
- timezone,
- handler: firePostReminderIfIncomplete,
- metadata: { source: 'meatspacePostReminder' }
- });
- console.log(`🔔 POST reminder: registered daily at ${time} (${timezone})`);
-
- if (shouldCatchUp) {
- const timezoneUpdatedAt = await getTimezoneUpdatedAt();
- await catchUpMissedSlot(cron, timezone, updatedAt, timezoneUpdatedAt);
- }
-}
-
-/**
- * Refresh the cron's timezone when the user's global timezone setting
- * changes elsewhere (Settings page, not this feature's own config) — without
- * this, the reminder keeps firing at the OLD offset until the next unrelated
- * POST-config save happens to reschedule it. Fired on every `settings:updated`
- * event but only actually reschedules (and logs) when the effective timezone
- * changed, so tweaking an unrelated setting doesn't spam a reschedule.
- */
-async function refreshTimezoneIfChanged() {
- if (!await isInstanceFeatureEnabled('post')) {
- cancel(POST_REMINDER_EVENT_ID);
- lastAppliedTimezone = null;
- return;
- }
-
- const config = await getPostConfig();
- if (config.reminder?.enabled !== true) return; // nothing scheduled to refresh
-
- const timezone = await getUserTimezone();
- if (timezone === lastAppliedTimezone) return;
-
- console.log(`🔔 POST reminder: timezone changed (${lastAppliedTimezone || 'unset'} → ${timezone}) — rescheduling`);
- await registerPostReminderSchedule();
-}
-
-settingsEvents.on('settings:updated', () => {
- refreshTimezoneIfChanged().catch(err => console.error(`❌ POST reminder timezone refresh failed: ${err.message}`));
-});
-
-// Centralizes reschedule-on-save inside updatePostConfig() (via its
-// postConfigEvents emitter) rather than bolting it onto one route handler —
-// any current or future caller of updatePostConfig gets the reschedule for
-// free (#2015). Gated on the `reminder` slice actually being part of the
-// patch so unrelated config saves (drill settings, adaptive toggle, etc.)
-// don't trigger a redundant reschedule + log line.
-postConfigEvents.on('post-config:updated', ({ updates }) => {
- if (!updates?.reminder) return;
- registerPostReminderSchedule().catch(err => console.error(`❌ POST reminder reschedule failed: ${err.message}`));
+const scheduler = createDailyReminderScheduler({
+ id: POST_REMINDER_EVENT_ID,
+ logPrefix: '🔔 POST reminder',
+ featureId: 'post',
+ notificationType: NOTIFICATION_TYPES.DAILY_POST_REMINDER,
+ readReminderSlice: async () => (await getPostConfig()).reminder,
+ // Sessions are day-bucketed server-side via `session.date`, stamped from the
+ // raw UTC date — a bucket that does NOT line up with local calendar days in
+ // any non-UTC zone. So the local day is derived from each session's precise
+ // `startedAt` instead, which is correct whatever time of day, relative to
+ // either boundary, a session actually completed.
+ alreadyHandledToday: async ({ timezone, todayStr }) => {
+ const sessions = await getPostSessions();
+ return sessions.some(s => isLocalDay(s?.startedAt, timezone, todayStr));
+ },
+ notify: async () => {
+ await addNotification({
+ type: NOTIFICATION_TYPES.DAILY_POST_REMINDER,
+ title: "Today's POST is still open",
+ description: "You haven't completed a Power On Self Test session today — a quick one keeps your streak alive.",
+ priority: PRIORITY_LEVELS.LOW,
+ link: '/post/launcher'
+ });
+ console.log(`🔔 POST reminder: nudge sent (today's session incomplete)`);
+ },
+ configEvents: { emitter: postConfigEvents, event: 'post-config:updated' }
});
-/**
- * Cancel the reminder schedule outright (explicit teardown / test cleanup).
- */
-export function stopPostReminderSchedule() {
- cancel(POST_REMINDER_EVENT_ID);
- lastAppliedTimezone = null;
-}
+export const firePostReminderIfIncomplete = scheduler.fire;
+export const registerPostReminderSchedule = scheduler.register;
+export const stopPostReminderSchedule = scheduler.stop;
diff --git a/server/services/meatspacePostReminder.test.js b/server/services/meatspacePostReminder.test.js
index 0f134308cc..2db383822c 100644
--- a/server/services/meatspacePostReminder.test.js
+++ b/server/services/meatspacePostReminder.test.js
@@ -1,27 +1,18 @@
/**
- * Tests for meatspacePostReminder — the opt-in (default OFF) daily reminder
- * for POST sessions. Covers: the pure HH:MM -> cron conversion, that the
- * scheduler only registers when enabled, that it reschedules (not
- * double-registers) on repeated calls, that the fired handler only sends a
- * notification when today's session is genuinely incomplete AND it hasn't
- * already notified today, the missed-slot catch-up on server restart, the
- * timezone-change refresh via settingsEvents, and the centralized
- * reschedule-on-save via meatspacePost.js's postConfigEvents (#2015).
+ * Tests for the POST daily reminder's own contract. The scheduling machinery —
+ * registration gates, catch-up floors, day-scoped de-dupe, reconcile — is
+ * shared and covered once in dailyReminderScheduler.test.js; what's left here
+ * is what only POST decides: that "already handled today" means a session was
+ * started on the user's LOCAL calendar day (not the raw-UTC `session.date`
+ * bucket the sessions file is keyed by), and what the nudge itself says.
+ *
+ * The timezone helpers are deliberately real — the UTC-instant-to-local-day
+ * derivation is the thing under test.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-// Minimal EventEmitter stubs so `<emitter>.on(...)` at module-load time works
-// and tests can `.emit(...)` to drive the subscription paths directly —
-// mirrors sharing/annotationIdentity.test.js's settingsEvents stub.
-const settingsEventEmitter = vi.hoisted(() => {
- const listeners = {};
- return {
- on(event, fn) { (listeners[event] ||= []).push(fn); },
- emit(event, ...args) { (listeners[event] || []).forEach(fn => fn(...args)); },
- };
-});
-
+const settingsEventEmitter = vi.hoisted(() => ({ on() {}, emit() {} }));
const postConfigEventEmitter = vi.hoisted(() => {
const listeners = {};
return {
@@ -35,463 +26,67 @@ vi.mock('./eventScheduler.js', () => ({
cancel: vi.fn(),
parseCronToPrevRun: vi.fn()
}));
-
-vi.mock('../lib/timezone.js', () => ({
- getLocalParts: vi.fn(),
- todayInTimezone: vi.fn(),
- HHMM_STRICT_RE: /^([01]\d|2[0-3]):[0-5]\d$/,
-}));
vi.mock('./userTimezone.js', () => ({
getUserTimezone: vi.fn().mockResolvedValue('UTC'),
getTimezoneUpdatedAt: vi.fn().mockResolvedValue(null),
}));
-
vi.mock('./meatspacePost.js', () => ({
getPostConfig: vi.fn(),
getPostSessions: vi.fn(),
postConfigEvents: postConfigEventEmitter
}));
-
vi.mock('./instanceFeatures.js', () => ({
isInstanceFeatureEnabled: vi.fn().mockResolvedValue(true),
}));
-
vi.mock('./notifications.js', () => ({
addNotification: vi.fn().mockResolvedValue({ id: 'n1' }),
getNotifications: vi.fn().mockResolvedValue([]),
NOTIFICATION_TYPES: { DAILY_POST_REMINDER: 'daily_post_reminder' },
PRIORITY_LEVELS: { LOW: 'low' }
}));
-
-vi.mock('./settings.js', () => ({
- settingsEvents: settingsEventEmitter
-}));
-
-import { schedule, cancel, parseCronToPrevRun } from './eventScheduler.js';
-import { getLocalParts, todayInTimezone } from '../lib/timezone.js';
-import { getUserTimezone, getTimezoneUpdatedAt } from './userTimezone.js';
-import { getPostConfig, getPostSessions } from './meatspacePost.js';
-import { isInstanceFeatureEnabled } from './instanceFeatures.js';
-import { addNotification, getNotifications } from './notifications.js';
-import {
- reminderTimeToCron,
+vi.mock('./settings.js', () => ({ settingsEvents: settingsEventEmitter }));
+
+const { schedule, cancel } = await import('./eventScheduler.js');
+const { getUserTimezone } = await import('./userTimezone.js');
+const { getPostConfig, getPostSessions } = await import('./meatspacePost.js');
+const { isInstanceFeatureEnabled } = await import('./instanceFeatures.js');
+const { addNotification, getNotifications } = await import('./notifications.js');
+const {
registerPostReminderSchedule,
firePostReminderIfIncomplete,
stopPostReminderSchedule,
POST_REMINDER_EVENT_ID
-} from './meatspacePostReminder.js';
-
-describe('reminderTimeToCron', () => {
- it('converts HH:MM to a daily cron expression', () => {
- expect(reminderTimeToCron('09:30')).toBe('30 9 * * *');
- expect(reminderTimeToCron('00:00')).toBe('0 0 * * *');
- expect(reminderTimeToCron('23:59')).toBe('59 23 * * *');
- });
-
- it('returns null for malformed or missing input', () => {
- expect(reminderTimeToCron('9:30')).toBeNull();
- expect(reminderTimeToCron('25:00')).toBeNull();
- expect(reminderTimeToCron('not-a-time')).toBeNull();
- expect(reminderTimeToCron(undefined)).toBeNull();
- expect(reminderTimeToCron(null)).toBeNull();
- });
-});
-
-describe('registerPostReminderSchedule', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- isInstanceFeatureEnabled.mockResolvedValue(true);
- getUserTimezone.mockResolvedValue('UTC');
- getTimezoneUpdatedAt.mockResolvedValue(null);
- parseCronToPrevRun.mockReturnValue(null);
- });
-
- it('cancels the schedule and does not register when disabled (default off)', async () => {
- getPostConfig.mockResolvedValue({ reminder: { enabled: false, time: '09:00' } });
- await registerPostReminderSchedule();
- expect(schedule).not.toHaveBeenCalled();
- expect(cancel).toHaveBeenCalledWith(POST_REMINDER_EVENT_ID);
- });
-
- it('cancels the schedule when POST is disabled for this instance', async () => {
- isInstanceFeatureEnabled.mockResolvedValue(false);
- getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });
-
- await registerPostReminderSchedule();
-
- expect(schedule).not.toHaveBeenCalled();
- expect(cancel).toHaveBeenCalledWith(POST_REMINDER_EVENT_ID);
- expect(getPostConfig).not.toHaveBeenCalled();
- });
-
- it('cancels and skips scheduling when the reminder block is entirely absent', async () => {
- getPostConfig.mockResolvedValue({});
- await registerPostReminderSchedule();
- expect(schedule).not.toHaveBeenCalled();
- expect(cancel).toHaveBeenCalledWith(POST_REMINDER_EVENT_ID);
- });
-
- it('registers a daily cron at the configured time when enabled', async () => {
- getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });
- await registerPostReminderSchedule();
- expect(schedule).toHaveBeenCalledTimes(1);
- expect(schedule.mock.calls[0][0]).toMatchObject({
- id: POST_REMINDER_EVENT_ID,
- type: 'cron',
- cron: '0 9 * * *',
- timezone: 'UTC'
- });
- });
-
- it('cancels rather than registers when enabled but the time is invalid', async () => {
- getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: 'garbage' } });
- await registerPostReminderSchedule();
- expect(schedule).not.toHaveBeenCalled();
- expect(cancel).toHaveBeenCalledWith(POST_REMINDER_EVENT_ID);
- });
-
- it('reschedules (re-registers under the same id) rather than accumulating on repeated calls', async () => {
- getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });
- await registerPostReminderSchedule();
- getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '18:30' } });
- await registerPostReminderSchedule();
- expect(schedule).toHaveBeenCalledTimes(2);
- expect(schedule.mock.calls[1][0]).toMatchObject({ id: POST_REMINDER_EVENT_ID, cron: '30 18 * * *' });
- });
-
- it('does not check for a missed slot unless catchUpMissedSlot is requested', async () => {
- getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });
- await registerPostReminderSchedule();
- expect(parseCronToPrevRun).not.toHaveBeenCalled();
- expect(getPostSessions).not.toHaveBeenCalled();
- });
-
- // Missed-slot catch-up (finding 2): mirrors taskSchedule.js's
- // parseCronToPrevRun-based recovery — a slot that already elapsed while
- // the server was down fires immediately instead of waiting for tomorrow.
- describe('catchUpMissedSlot: true (boot-time recovery)', () => {
- // Pin the clock so "prevRunMs <= now" comparisons in catchUpMissedSlot
- // are deterministic regardless of what time of day the suite runs.
- beforeEach(() => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date('2026-07-01T12:00:00.000Z'));
- });
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it('fires the reminder immediately when the most recent cron slot already elapsed today', async () => {
- getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });
- getPostSessions.mockResolvedValue([]);
- todayInTimezone.mockReturnValue('2026-07-01');
- getLocalParts.mockReturnValue({ year: 2026, month: 7, day: 1 }); // prevRun falls on today
- parseCronToPrevRun.mockReturnValue(new Date('2026-07-01T09:00:00.000Z'));
-
- await registerPostReminderSchedule({ catchUpMissedSlot: true });
-
- expect(addNotification).toHaveBeenCalledTimes(1);
- });
-
- it('does not fire when there is no prior cron occurrence at all', async () => {
- getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });
- parseCronToPrevRun.mockReturnValue(null);
-
- await registerPostReminderSchedule({ catchUpMissedSlot: true });
-
- expect(addNotification).not.toHaveBeenCalled();
- expect(getPostSessions).not.toHaveBeenCalled();
- });
-
- // Regression: parseCronToPrevRun always returns SOME past occurrence
- // whenever `now` is earlier in the day than the configured time — e.g. a
- // 09:00 reminder restarted at 07:00 resolves "the most recent past
- // occurrence" to YESTERDAY's 09:00, which already fired normally last
- // night. Without gating on the local calendar day, catchUpMissedSlot
- // would wrongly treat that as a missed slot and fire a spurious reminder
- // on every boot before the scheduled hour — not just on genuine downtime
- // spanning the scheduled minute.
- it('does not fire when the most recent past occurrence is from a prior day', async () => {
- getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });
- todayInTimezone.mockReturnValue('2026-07-01');
- getLocalParts.mockReturnValue({ year: 2026, month: 6, day: 30 }); // yesterday, not today
- parseCronToPrevRun.mockReturnValue(new Date('2026-06-30T09:00:00.000Z'));
-
- await registerPostReminderSchedule({ catchUpMissedSlot: true });
-
- expect(addNotification).not.toHaveBeenCalled();
- expect(getPostSessions).not.toHaveBeenCalled();
- });
-
- // Regression (codex review finding): a same-day missed slot is only a
- // genuine miss if the CURRENT reminder settings actually owned it. If the
- // user enables the reminder (or changes its time) for an already-past
- // time today, then the server restarts later that same day for unrelated
- // reasons, the slot still falls on today's local day — but it happened
- // before this configuration existed, so replaying it would nag for a
- // period the reminder wasn't even active for.
- it('does not fire when the missed slot occurred before the reminder config was last saved', async () => {
- getPostConfig.mockResolvedValue({
- reminder: { enabled: true, time: '09:00', updatedAt: '2026-07-01T10:00:00.000Z' }
- });
- todayInTimezone.mockReturnValue('2026-07-01');
- getLocalParts.mockReturnValue({ year: 2026, month: 7, day: 1 });
- // The 09:00 slot happened BEFORE the 10:00 config save.
- parseCronToPrevRun.mockReturnValue(new Date('2026-07-01T09:00:00.000Z'));
-
- await registerPostReminderSchedule({ catchUpMissedSlot: true });
-
- expect(addNotification).not.toHaveBeenCalled();
- expect(getPostSessions).not.toHaveBeenCalled();
- });
-
- it('fires when the missed slot occurred after the reminder config was last saved', async () => {
- getPostConfig.mockResolvedValue({
- reminder: { enabled: true, time: '09:00', updatedAt: '2026-06-01T00:00:00.000Z' }
- });
- getPostSessions.mockResolvedValue([]);
- todayInTimezone.mockReturnValue('2026-07-01');
- getLocalParts.mockReturnValue({ year: 2026, month: 7, day: 1 });
- parseCronToPrevRun.mockReturnValue(new Date('2026-07-01T09:00:00.000Z'));
-
- await registerPostReminderSchedule({ catchUpMissedSlot: true });
-
- expect(addNotification).toHaveBeenCalledTimes(1);
- });
-
- it('fires regardless of slot timing when the config predates the updatedAt field (backward compat)', async () => {
- // Older on-disk configs saved before this field existed have no
- // `updatedAt` at all — absence must not block catch-up outright.
- getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });
- getPostSessions.mockResolvedValue([]);
- todayInTimezone.mockReturnValue('2026-07-01');
- getLocalParts.mockReturnValue({ year: 2026, month: 7, day: 1 });
- parseCronToPrevRun.mockReturnValue(new Date('2026-07-01T09:00:00.000Z'));
-
- await registerPostReminderSchedule({ catchUpMissedSlot: true });
-
- expect(addNotification).toHaveBeenCalledTimes(1);
- });
-
- // Regression (#2040): a same-day missed slot must ALSO be gated on when the
- // user's GLOBAL timezone last changed, not just the reminder's own config.
- // If the user switches timezone such that today's slot newly appears
- // already-passed under the new zone, then the server restarts later the
- // same local day, replaying that slot would nag for a slot that was never
- // scheduled under the timezone active when it "occurred."
- it('does not fire when the missed slot predates the last global timezone change', async () => {
- getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });
- todayInTimezone.mockReturnValue('2026-07-01');
- getLocalParts.mockReturnValue({ year: 2026, month: 7, day: 1 });
- // The 09:00 slot happened BEFORE the 10:00 timezone switch.
- parseCronToPrevRun.mockReturnValue(new Date('2026-07-01T09:00:00.000Z'));
- getTimezoneUpdatedAt.mockResolvedValue(new Date('2026-07-01T10:00:00.000Z').getTime());
-
- await registerPostReminderSchedule({ catchUpMissedSlot: true });
-
- expect(addNotification).not.toHaveBeenCalled();
- expect(getPostSessions).not.toHaveBeenCalled();
- });
-
- it('fires when the missed slot occurred after the last global timezone change', async () => {
- getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });
- getPostSessions.mockResolvedValue([]);
- todayInTimezone.mockReturnValue('2026-07-01');
- getLocalParts.mockReturnValue({ year: 2026, month: 7, day: 1 });
- parseCronToPrevRun.mockReturnValue(new Date('2026-07-01T09:00:00.000Z'));
- // Timezone last changed BEFORE the slot — the slot is genuinely owned by
- // the currently-active zone, so catch-up proceeds.
- getTimezoneUpdatedAt.mockResolvedValue(new Date('2026-06-01T00:00:00.000Z').getTime());
-
- await registerPostReminderSchedule({ catchUpMissedSlot: true });
-
- expect(addNotification).toHaveBeenCalledTimes(1);
- });
-
- // The effective floor is the LATER of the two cutoffs. Here the reminder
- // config was saved BEFORE the slot (its own guard alone would allow the
- // fire), but the timezone changed AFTER the slot — the later (timezone)
- // cutoff must win and block the catch-up.
- it('uses the later of (reminder config, timezone change) cutoffs — timezone wins', async () => {
- getPostConfig.mockResolvedValue({
- reminder: { enabled: true, time: '09:00', updatedAt: '2026-07-01T08:00:00.000Z' }
- });
- todayInTimezone.mockReturnValue('2026-07-01');
- getLocalParts.mockReturnValue({ year: 2026, month: 7, day: 1 });
- parseCronToPrevRun.mockReturnValue(new Date('2026-07-01T09:00:00.000Z'));
- getTimezoneUpdatedAt.mockResolvedValue(new Date('2026-07-01T10:00:00.000Z').getTime());
-
- await registerPostReminderSchedule({ catchUpMissedSlot: true });
-
- expect(addNotification).not.toHaveBeenCalled();
- });
-
- // Inverse: timezone changed BEFORE the slot but the reminder config was
- // saved AFTER it — the later (reminder) cutoff wins and blocks.
- it('uses the later of (reminder config, timezone change) cutoffs — reminder config wins', async () => {
- getPostConfig.mockResolvedValue({
- reminder: { enabled: true, time: '09:00', updatedAt: '2026-07-01T10:00:00.000Z' }
- });
- todayInTimezone.mockReturnValue('2026-07-01');
- getLocalParts.mockReturnValue({ year: 2026, month: 7, day: 1 });
- parseCronToPrevRun.mockReturnValue(new Date('2026-07-01T09:00:00.000Z'));
- getTimezoneUpdatedAt.mockResolvedValue(new Date('2026-07-01T08:00:00.000Z').getTime());
-
- await registerPostReminderSchedule({ catchUpMissedSlot: true });
-
- expect(addNotification).not.toHaveBeenCalled();
- });
-
- // Both cutoffs predate the slot → the slot is owned by the current config
- // AND the current zone, so catch-up fires.
- it('fires when the slot postdates both the reminder config and the timezone change', async () => {
- getPostConfig.mockResolvedValue({
- reminder: { enabled: true, time: '09:00', updatedAt: '2026-06-15T00:00:00.000Z' }
- });
- getPostSessions.mockResolvedValue([]);
- todayInTimezone.mockReturnValue('2026-07-01');
- getLocalParts.mockReturnValue({ year: 2026, month: 7, day: 1 });
- parseCronToPrevRun.mockReturnValue(new Date('2026-07-01T09:00:00.000Z'));
- getTimezoneUpdatedAt.mockResolvedValue(new Date('2026-06-20T00:00:00.000Z').getTime());
-
- await registerPostReminderSchedule({ catchUpMissedSlot: true });
-
- expect(addNotification).toHaveBeenCalledTimes(1);
- });
-
- it('is idempotent — firePostReminderIfIncomplete still skips when today is already complete', async () => {
- getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });
- todayInTimezone.mockReturnValue('2026-07-01');
- getPostSessions.mockResolvedValue([{ startedAt: '2026-07-01T15:00:00.000Z' }]);
- getLocalParts.mockReturnValue({ year: 2026, month: 7, day: 1 });
- parseCronToPrevRun.mockReturnValue(new Date('2026-07-01T09:00:00.000Z'));
-
- await registerPostReminderSchedule({ catchUpMissedSlot: true });
-
- expect(addNotification).not.toHaveBeenCalled();
- });
- });
-
- // Timezone refresh (finding 1): a global timezone change elsewhere (not
- // through POST config) must reschedule the cron at the new offset.
- describe('timezone refresh via settingsEvents', () => {
- it('reschedules when the global timezone changes', async () => {
- getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });
- getUserTimezone.mockResolvedValue('UTC');
- await registerPostReminderSchedule();
- expect(schedule).toHaveBeenCalledTimes(1);
-
- getUserTimezone.mockResolvedValue('America/Los_Angeles');
- settingsEventEmitter.emit('settings:updated', { timezone: 'America/Los_Angeles' });
-
- await vi.waitFor(() => {
- expect(schedule).toHaveBeenCalledTimes(2);
- });
- expect(schedule.mock.calls[1][0]).toMatchObject({ timezone: 'America/Los_Angeles' });
- });
-
- it('does not reschedule when the effective timezone is unchanged', async () => {
- getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });
- getUserTimezone.mockResolvedValue('UTC');
- await registerPostReminderSchedule();
- expect(schedule).toHaveBeenCalledTimes(1);
-
- settingsEventEmitter.emit('settings:updated', { timezone: 'UTC' });
- // Flush any pending microtasks from the (no-op) listener before asserting.
- await Promise.resolve();
- await Promise.resolve();
-
- expect(schedule).toHaveBeenCalledTimes(1);
- });
-
- it('does not reschedule when the reminder is disabled', async () => {
- getPostConfig.mockResolvedValue({ reminder: { enabled: false, time: '09:00' } });
- settingsEventEmitter.emit('settings:updated', { timezone: 'America/Los_Angeles' });
- await Promise.resolve();
- await Promise.resolve();
-
- expect(schedule).not.toHaveBeenCalled();
- });
- });
-
- // Centralized reschedule-on-save (finding 3): meatspacePost.js's
- // updatePostConfig() emits postConfigEvents on every save; this module
- // reschedules whenever the `reminder` slice was part of the patch,
- // regardless of which caller invoked updatePostConfig.
- describe('reschedule via meatspacePost.js postConfigEvents', () => {
- it('reschedules when the saved patch includes a reminder block', async () => {
- getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });
-
- postConfigEventEmitter.emit('post-config:updated', {
- config: { reminder: { enabled: true, time: '09:00' } },
- updates: { reminder: { enabled: true, time: '09:00' } }
- });
-
- await vi.waitFor(() => {
- expect(schedule).toHaveBeenCalledTimes(1);
- });
- });
-
- it('does not reschedule when the saved patch has no reminder key', async () => {
- postConfigEventEmitter.emit('post-config:updated', {
- config: { adaptive: { enabled: true } },
- updates: { adaptive: { enabled: true } }
- });
- await Promise.resolve();
- await Promise.resolve();
-
- expect(schedule).not.toHaveBeenCalled();
- expect(getPostConfig).not.toHaveBeenCalled();
- });
- });
+} = await import('./meatspacePostReminder.js');
+
+beforeEach(() => {
+ stopPostReminderSchedule();
+ vi.clearAllMocks();
+ vi.useFakeTimers({ now: new Date('2026-07-01T12:00:00.000Z'), toFake: ['Date'] });
+ isInstanceFeatureEnabled.mockResolvedValue(true);
+ getUserTimezone.mockResolvedValue('UTC');
+ getNotifications.mockResolvedValue([]);
+ getPostSessions.mockResolvedValue([]);
+ getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });
});
-describe('stopPostReminderSchedule', () => {
- it('cancels the reminder event', () => {
- vi.clearAllMocks();
- stopPostReminderSchedule();
- expect(cancel).toHaveBeenCalledWith(POST_REMINDER_EVENT_ID);
- });
+afterEach(() => {
+ vi.useRealTimers();
});
describe('firePostReminderIfIncomplete', () => {
- it('does not notify when POST is disabled for this instance', async () => {
- isInstanceFeatureEnabled.mockResolvedValue(false);
-
- await firePostReminderIfIncomplete();
-
- expect(addNotification).not.toHaveBeenCalled();
- expect(getPostConfig).not.toHaveBeenCalled();
- });
-
- beforeEach(() => {
- vi.clearAllMocks();
- isInstanceFeatureEnabled.mockResolvedValue(true);
- getPostSessions.mockResolvedValue([]);
- getNotifications.mockResolvedValue([]);
- getUserTimezone.mockResolvedValue('UTC');
- todayInTimezone.mockReturnValue('2026-07-01');
- // Default: getLocalParts on any session's startedAt resolves to "today" —
- // individual tests override to simulate a specific local day per session.
- getLocalParts.mockReturnValue({ year: 2026, month: 7, day: 1 });
- });
-
- it('sends a notification when the reminder is enabled and there are no sessions at all', async () => {
- getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });
- getPostSessions.mockResolvedValue([]);
-
+ it('nudges to the POST launcher when no session exists at all', async () => {
await firePostReminderIfIncomplete();
expect(addNotification).toHaveBeenCalledTimes(1);
expect(addNotification.mock.calls[0][0]).toMatchObject({
type: 'daily_post_reminder',
+ priority: 'low',
link: '/post/launcher'
});
});
- it('does not nag once a session has been completed today (by local calendar day)', async () => {
- getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });
+ it('does not nag once a session has been started today', async () => {
getPostSessions.mockResolvedValue([{ startedAt: '2026-07-01T15:00:00.000Z' }]);
- getLocalParts.mockReturnValue({ year: 2026, month: 7, day: 1 });
await firePostReminderIfIncomplete();
@@ -499,9 +94,7 @@ describe('firePostReminderIfIncomplete', () => {
});
it('nags when every session on record is from a different local day', async () => {
- getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });
getPostSessions.mockResolvedValue([{ startedAt: '2026-06-30T15:00:00.000Z' }]);
- getLocalParts.mockReturnValue({ year: 2026, month: 6, day: 30 }); // yesterday, not today
await firePostReminderIfIncomplete();
@@ -509,7 +102,6 @@ describe('firePostReminderIfIncomplete', () => {
});
it('ignores a session missing startedAt rather than crashing', async () => {
- getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });
getPostSessions.mockResolvedValue([{ date: '2026-07-01' }]); // no startedAt
await firePostReminderIfIncomplete();
@@ -517,74 +109,53 @@ describe('firePostReminderIfIncomplete', () => {
expect(addNotification).toHaveBeenCalledTimes(1);
});
- it('skips entirely if disabled since registration', async () => {
- getPostConfig.mockResolvedValue({ reminder: { enabled: false, time: '09:00' } });
-
- await firePostReminderIfIncomplete();
-
- expect(addNotification).not.toHaveBeenCalled();
- expect(getPostSessions).not.toHaveBeenCalled();
- });
-
- // De-dupe guard backing the missed-slot catch-up: a second evaluation of
- // the same local day (e.g. catch-up re-running after the normal cron tick
- // already fired earlier) must not send a second notification.
- it('does not nag again if a reminder notification already exists for today', async () => {
- getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });
- getPostSessions.mockResolvedValue([]);
- getNotifications.mockResolvedValue([{ timestamp: '2026-07-01T09:00:05.000Z' }]);
- getLocalParts.mockReturnValue({ year: 2026, month: 7, day: 1 });
+ // Regression: sessions are day-bucketed server-side by a raw-UTC
+ // `session.date` string, which for any negative-offset zone rolls over hours
+ // before local midnight. The completeness check must derive the local day
+ // from the precise `startedAt` instead, or a session finished in that gap is
+ // credited to the wrong day.
+ it('reads a session\'s local day from startedAt, not its UTC date bucket', async () => {
+ // Now is 05:00 on July 1 in Los Angeles. The session's UTC stamp is also
+ // July 1, but locally it is 21:00 on JUNE 30 — yesterday — so today is
+ // still outstanding and the nudge must go out.
+ getUserTimezone.mockResolvedValue('America/Los_Angeles');
+ getPostSessions.mockResolvedValue([
+ { date: '2026-07-01', startedAt: '2026-07-01T04:00:00.000Z' }
+ ]);
await firePostReminderIfIncomplete();
- expect(addNotification).not.toHaveBeenCalled();
+ expect(addNotification).toHaveBeenCalledTimes(1);
});
+});
- it('nags when the only existing reminder notification is from a different local day', async () => {
- getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });
- getPostSessions.mockResolvedValue([]);
- getNotifications.mockResolvedValue([{ timestamp: '2026-06-30T09:00:05.000Z' }]);
- getLocalParts.mockReturnValue({ year: 2026, month: 6, day: 30 }); // yesterday
-
- await firePostReminderIfIncomplete();
+describe('registerPostReminderSchedule', () => {
+ it('registers under the POST reminder id at the configured time', async () => {
+ await registerPostReminderSchedule();
- expect(addNotification).toHaveBeenCalledTimes(1);
+ expect(schedule.mock.calls[0][0]).toMatchObject({
+ id: POST_REMINDER_EVENT_ID, cron: '0 9 * * *', timezone: 'UTC'
+ });
});
- // Regression (finding 1 + its follow-up): the reminder cron fires on the
- // user's LOCAL wall-clock time, so "is today done" must be evaluated in
- // that same local calendar day. Sessions are day-bucketed server-side via
- // a raw-UTC `session.date` string that does not line up with local
- // calendar days for non-UTC timezones — so this must NOT compare against
- // that bucket at all. Instead it derives each session's local day directly
- // from its precise `startedAt` timestamp, which is correct regardless of
- // what time of day (relative to either the UTC or local day boundary) the
- // session actually completed.
- it("derives 'today' and each session's day from the local timezone, not the raw UTC date/bucket", async () => {
- getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '20:00' } });
- getUserTimezone.mockResolvedValue('America/Los_Angeles');
- todayInTimezone.mockReturnValue('2026-07-01');
- // A session with a raw UTC session.date of "2026-07-02" (recorded late in the
- // local evening, after the UTC date had already rolled over) still resolves to
- // local day "2026-07-01" via its precise startedAt timestamp + getLocalParts —
- // proving the check no longer trusts the UTC-dated bucket.
- getPostSessions.mockResolvedValue([{ date: '2026-07-02', startedAt: '2026-07-02T03:30:00.000Z' }]);
- getLocalParts.mockReturnValue({ year: 2026, month: 7, day: 1 });
+ it('stays silent on an install where the POST feature is off', async () => {
+ isInstanceFeatureEnabled.mockResolvedValue(false);
- await firePostReminderIfIncomplete();
+ await registerPostReminderSchedule();
- expect(getLocalParts).toHaveBeenCalledWith(new Date('2026-07-02T03:30:00.000Z'), 'America/Los_Angeles');
- expect(addNotification).not.toHaveBeenCalled();
+ expect(isInstanceFeatureEnabled).toHaveBeenCalledWith('post');
+ expect(schedule).not.toHaveBeenCalled();
+ expect(cancel).toHaveBeenCalledWith(POST_REMINDER_EVENT_ID);
});
- it("zero-pads single-digit month/day when comparing a session's local day", async () => {
- getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });
- todayInTimezone.mockReturnValue('2026-03-05');
- getPostSessions.mockResolvedValue([{ startedAt: '2026-03-05T12:00:00.000Z' }]);
- getLocalParts.mockReturnValue({ year: 2026, month: 3, day: 5 });
-
- await firePostReminderIfIncomplete();
+ // updatePostConfig() emits on every save; the reminder re-registers whenever
+ // the `reminder` slice was in the patch, whichever caller saved it (#2015).
+ it('reschedules when updatePostConfig saves a reminder change', async () => {
+ postConfigEventEmitter.emit('post-config:updated', {
+ config: { reminder: { enabled: true, time: '09:00' } },
+ updates: { reminder: { enabled: true, time: '09:00' } }
+ });
- expect(addNotification).not.toHaveBeenCalled();
+ await vi.waitFor(() => expect(schedule).toHaveBeenCalledTimes(1));
});
});