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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: guard POST reminder catch-up against global timezone change (#2040)
Adam Eivyc82c29f75194
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 3a531ba3eb..3fee28c040 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -25,4 +25,5 @@- Consolidated five component-local duration/uptime/time-until formatters onto the shared `utils/formatters.js` helpers (`formatDurationMs`, `timeUntil`), per the "do not re-define formatters inside components" convention (#2028). `formatDurationMs` gained a day bucket (`2d 3h`) so long uptimes no longer render as an unbounded hours count; ProcessesTab, CityHud, Shell session ages, the CoS QuickSummary "next job" countdown, and the Loops interval label now all route through the shared helpers, and a `console.log` in `memoryClassifier.js` was collapsed to a single interpolated line.- Migration 155 heals `data/prompts/stages/cd-treatment.md` installs that #1808's anchor-based migration 148 left stranded (#2042). Installs seeded before the `imageStrength` scene knob (older pre-#1808 template) got the `## Cast & ingredients` list but missed the per-scene `"cast": [{ "ingredientId": … }]` field, so the Creative Director cast-threading regression test stayed red on the runtime template and migration 148 (already applied) never re-ran. The new hash-driven prompt-replace upgrades those copies (and both pristine pre-#1808 shipped versions) to the current shipped reference, leaving hand-customized copies untouched. Also folds `cd-treatment.md` into `buildPromptDriftTables` so setup-data.js's drift warning classifies a stranded copy correctly.- Replaced the last hardcoded `port-*` hex stragglers with design tokens (#2031). The Security page's audio-level meter used raw `#ef4444`/`#f59e0b`/`#22c55e` in an inline `backgroundColor`; these now resolve through `rgb(var(--port-error))`/`--port-warning`/`--port-success` so they track the theme. The Chief-of-Staff page's "CoS" wordmark gradient was duplicated inline three times and is now a single module-level `COS_TITLE_GRADIENT` constant. Visual output is unchanged.+- Fixed a POST daily-reminder false-nudge after a global timezone change (#2040). `settings.js` now stamps a `timezoneUpdatedAt` timestamp whenever the `timezone` value actually changes (unrelated saves leave it untouched), exposed via `getTimezoneUpdatedAt()` in `timezone.js`. The reminder's boot-time missed-slot catch-up (`catchUpMissedSlot`) now skips a slot that predates the LATER of the reminder's own config save (#2015) or the last timezone change — so switching timezones and then restarting the server the same day can no longer replay a slot that was never scheduled under the active zone. The new field is reusable by any other timezone-dependent scheduler.- Fixed double error toasts across ~50 call sites that owned a custom `.catch` toast: they now pass `{ silent: true }` so the `apiCore.request()` default toast no longer fires alongside the component's own, per the "Silent vs. toasting API requests" convention (#2026). Also added the missing trailing `options = {}` passthrough to ~40 `api*.js` wrappers (CoS tasks/agents/jobs, Brain people/projects/ideas/admin/memories/buckets/inbox, GSD, memory approve/reject, app task-type overrides, feature-agent controls, browser/backup/system, MeatSpace POST drills, goals, messages) so callers can actually suppress the built-in toast. Sites whose `.catch` only reverts state (no toast) were intentionally left on the default single toast.diff --git a/server/lib/timezone.js b/server/lib/timezone.jsindex 067cc69bb1..099e3c56bb 100644--- a/server/lib/timezone.js+++ b/server/lib/timezone.js@@ -51,6 +51,24 @@ export async function getUserTimezone() {return Intl.DateTimeFormat().resolvedOptions().timeZone}+/**+ * Get the UTC-ms timestamp at which the user's `timezone` setting last actually+ * changed, or null when it has never been recorded. Stamped by settings.js's+ * write path (`save()`) only when the `timezone` value genuinely differs from+ * the prior on-disk value. Timezone-dependent schedulers use this to avoid+ * replaying a slot that "occurred" under a timezone that was no longer active —+ * see catchUpMissedSlot in meatspacePostReminder.js (#2040).+ *+ * Sentinel discipline: null (not a number, ≤ 0) means "never changed / unset",+ * so callers must NOT treat absence as a floor — an unset value gates nothing.+ * @returns {Promise<number|null>} UTC ms, or null when unset.+ */+export async function getTimezoneUpdatedAt() {+ const settings = await getSettings()+ const ts = settings.timezoneUpdatedAt+ return typeof ts === 'number' && ts > 0 ? ts : null+}+/*** Get local date/time parts for a UTC Date in the given timezone.* @param {Date} utcDate - Date object (interpreted as UTC since TZ=UTC)diff --git a/server/lib/timezone.test.js b/server/lib/timezone.test.jsindex a677604fac..7a6f04003a 100644--- a/server/lib/timezone.test.js+++ b/server/lib/timezone.test.js@@ -1,9 +1,18 @@import { describe, it, expect, vi } from 'vitest'++// getUserTimezone/getTimezoneUpdatedAt read from settings.js; the pure helpers+// below don't touch settings, so mocking it only affects the getter tests.+vi.mock('../services/settings.js', () => ({+ getSettings: vi.fn()+}))++import { getSettings } from '../services/settings.js'import {getLocalParts,getUtcOffsetMs,nextLocalTime,todayInTimezone,+ getTimezoneUpdatedAt,HHMM_RE,HHMM_STRICT_RE,parseHHMM,@@ -187,4 +196,23 @@ describe('timezone', () => {vi.useRealTimers()})})++ describe('getTimezoneUpdatedAt (#2040)', () => {+ it('returns the stamped numeric timestamp when set', async () => {+ getSettings.mockResolvedValue({ timezone: 'UTC', timezoneUpdatedAt: 1700000000000 })+ expect(await getTimezoneUpdatedAt()).toBe(1700000000000)+ })++ it('returns null when the field is absent (unset sentinel — never gates)', async () => {+ getSettings.mockResolvedValue({ timezone: 'UTC' })+ expect(await getTimezoneUpdatedAt()).toBeNull()+ })++ it('returns null for a non-numeric or non-positive value', async () => {+ getSettings.mockResolvedValue({ timezoneUpdatedAt: '1700000000000' })+ expect(await getTimezoneUpdatedAt()).toBeNull()+ getSettings.mockResolvedValue({ timezoneUpdatedAt: 0 })+ expect(await getTimezoneUpdatedAt()).toBeNull()+ })+ })})diff --git a/server/services/meatspacePostReminder.js b/server/services/meatspacePostReminder.jsindex ea7cdb269b..d73bd9deba 100644--- a/server/services/meatspacePostReminder.js+++ b/server/services/meatspacePostReminder.js@@ -24,7 +24,7 @@*/import { schedule, cancel, parseCronToPrevRun } from './eventScheduler.js';-import { getUserTimezone, getLocalParts, todayInTimezone, HHMM_STRICT_RE } from '../lib/timezone.js';+import { getUserTimezone, getTimezoneUpdatedAt, getLocalParts, todayInTimezone, HHMM_STRICT_RE } from '../lib/timezone.js';import { getPostConfig, getPostSessions, postConfigEvents } from './meatspacePost.js';import { addNotification, getNotifications, NOTIFICATION_TYPES, PRIORITY_LEVELS } from './notifications.js';import { settingsEvents } from './settings.js';@@ -147,18 +147,20 @@ export async function firePostReminderIfIncomplete() {* already-notified-today guards), so calling it here is safe even on a rare* false-positive gate.*- * KNOWN LIMITATION (tracked in #2040, deliberately out of scope here): this- * only guards against the reminder's OWN config changing, not the user's- * GLOBAL timezone changing. If the effective timezone changes such that+ * `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, this can still fire- * a catch-up for a slot that was never scheduled under the timezone active- * when it "occurred." Fixing that generally requires a timezone-change- * timestamp in the shared settings layer (server/services/settings.js), used- * by every timezone-dependent scheduler — not just this one — so it's- * tracked separately rather than folded into this issue's narrower scope.+ * 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) {+async function catchUpMissedSlot(cron, timezone, reminderUpdatedAt, timezoneUpdatedAt) {const now = Date.now();const prevRun = parseCronToPrevRun(cron, new Date(now), timezone);if (!prevRun) return;@@ -167,7 +169,19 @@ async function catchUpMissedSlot(cron, timezone, reminderUpdatedAt) {const todayStr = todayInTimezone(timezone);if (!isOnLocalDay(prevRunMs, timezone, todayStr)) return;- if (reminderUpdatedAt && prevRunMs < new Date(reminderUpdatedAt).getTime()) 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();@@ -216,7 +230,8 @@ export async function registerPostReminderSchedule({ catchUpMissedSlot: shouldCaconsole.log(`🔔 POST reminder: registered daily at ${time} (${timezone})`);if (shouldCatchUp) {- await catchUpMissedSlot(cron, timezone, updatedAt);+ const timezoneUpdatedAt = await getTimezoneUpdatedAt();+ await catchUpMissedSlot(cron, timezone, updatedAt, timezoneUpdatedAt);}}diff --git a/server/services/meatspacePostReminder.test.js b/server/services/meatspacePostReminder.test.jsindex 1ce46a82ac..3f5f7fd7d9 100644--- a/server/services/meatspacePostReminder.test.js+++ b/server/services/meatspacePostReminder.test.js@@ -38,6 +38,7 @@ vi.mock('./eventScheduler.js', () => ({vi.mock('../lib/timezone.js', () => ({getUserTimezone: vi.fn().mockResolvedValue('UTC'),+ getTimezoneUpdatedAt: vi.fn().mockResolvedValue(null),getLocalParts: vi.fn(),todayInTimezone: vi.fn(),HHMM_STRICT_RE: /^([01]\d|2[0-3]):[0-5]\d$/@@ -61,7 +62,7 @@ vi.mock('./settings.js', () => ({}));import { schedule, cancel, parseCronToPrevRun } from './eventScheduler.js';-import { getUserTimezone, getLocalParts, todayInTimezone } from '../lib/timezone.js';+import { getUserTimezone, getTimezoneUpdatedAt, getLocalParts, todayInTimezone } from '../lib/timezone.js';import { getPostConfig, getPostSessions } from './meatspacePost.js';import { addNotification, getNotifications } from './notifications.js';import {@@ -92,6 +93,7 @@ describe('registerPostReminderSchedule', () => {beforeEach(() => {vi.clearAllMocks();getUserTimezone.mockResolvedValue('UTC');+ getTimezoneUpdatedAt.mockResolvedValue(null);parseCronToPrevRun.mockReturnValue(null);});@@ -250,6 +252,92 @@ describe('registerPostReminderSchedule', () => {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');diff --git a/server/services/settings.js b/server/services/settings.jsindex 919fa23660..87f61500e6 100644--- a/server/services/settings.js+++ b/server/services/settings.js@@ -78,6 +78,21 @@ const queueWrite = createFileWriteQueue();const save = async (settings) => {const cleaned = stripStoreKeys(settings);+ // Stamp `timezoneUpdatedAt` whenever the effective `timezone` actually+ // changes, so timezone-dependent schedulers can gate catch-up/re-evaluation+ // logic on "when did the zone last change" (see meatspacePostReminder's+ // missed-slot catch-up, #2040). Compare against the previous on-disk value so+ // unrelated settings saves NEVER touch the field. The read runs inside the+ // same queued write turn (every caller wraps save in queueWrite), so the+ // comparison is against the freshest persisted snapshot, and any prior+ // `timezoneUpdatedAt` on an unchanged-timezone save rides through untouched+ // via the merged object.+ if (isPlainObject(cleaned)) {+ const prev = stripStoreKeys(await loadRaw());+ if (isPlainObject(prev) && cleaned.timezone !== prev.timezone) {+ cleaned.timezoneUpdatedAt = Date.now();+ }+ }// atomicWrite (temp-file + rename) so a mid-write crash never truncates// settings.json. Pass a pre-stringified string to preserve the trailing// newline; atomicWrite's own JSON.stringify omits it.diff --git a/server/services/settings.test.js b/server/services/settings.test.jsindex e71e016b57..3f739eb36e 100644--- a/server/services/settings.test.js+++ b/server/services/settings.test.js@@ -250,6 +250,60 @@ describe('settings.js', () => {});});+ describe('timezoneUpdatedAt stamping (#2040)', () => {+ it('stamps timezoneUpdatedAt when the timezone value actually changes', async () => {+ tryReadFile.mockResolvedValue(JSON.stringify({ timezone: 'UTC', theme: 'dark' }));++ const before = Date.now();+ const result = await updateSettings({ timezone: 'Asia/Tokyo' });++ expect(result.timezone).toBe('Asia/Tokyo');+ expect(typeof result.timezoneUpdatedAt).toBe('number');+ expect(result.timezoneUpdatedAt).toBeGreaterThanOrEqual(before);+ });++ it('stamps on first-ever set (unset → value)', async () => {+ tryReadFile.mockResolvedValue(JSON.stringify({ theme: 'dark' }));++ const result = await updateSettings({ timezone: 'UTC' });++ expect(typeof result.timezoneUpdatedAt).toBe('number');+ });++ it('does NOT stamp when an unrelated setting is saved (timezone unchanged)', async () => {+ tryReadFile.mockResolvedValue(JSON.stringify({ timezone: 'UTC', theme: 'dark' }));++ const result = await updateSettings({ theme: 'light' });++ expect(result.timezone).toBe('UTC');+ expect(result.timezoneUpdatedAt).toBeUndefined();+ });++ it('does NOT stamp when the timezone is re-saved with the same value', async () => {+ tryReadFile.mockResolvedValue(JSON.stringify({ timezone: 'UTC' }));++ const result = await updateSettings({ timezone: 'UTC' });++ expect(result.timezoneUpdatedAt).toBeUndefined();+ });++ it('preserves an existing timezoneUpdatedAt across an unrelated save (does not clear it)', async () => {+ tryReadFile.mockResolvedValue(JSON.stringify({ timezone: 'UTC', timezoneUpdatedAt: 1234567890 }));++ const result = await updateSettings({ theme: 'dark' });++ expect(result.timezoneUpdatedAt).toBe(1234567890);+ });++ it('re-stamps (overwrites the old timestamp) when the timezone changes again', async () => {+ tryReadFile.mockResolvedValue(JSON.stringify({ timezone: 'UTC', timezoneUpdatedAt: 1 }));++ const result = await updateSettings({ timezone: 'Europe/Paris' });++ expect(result.timezoneUpdatedAt).toBeGreaterThan(1);+ });+ });+describe('MortalLoom store key pollution guard', () => {it('strips MortalLoom-store top-level keys on read', async () => {// Simulates the historical corruption: settings.json contains both@@ -306,6 +360,10 @@ describe('settings.js', () => {const [, content] = atomicWrite.mock.calls[0];const written = JSON.parse(content);+ // Setting the timezone (undefined → 'UTC' here) stamps timezoneUpdatedAt;+ // strip it before comparing the rest of the cleaned shape.+ expect(typeof written.timezoneUpdatedAt).toBe('number');+ delete written.timezoneUpdatedAt;expect(written).toEqual({ theme: 'dark', timezone: 'UTC' });});