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
address review (codex r4): preserve legacy instants + DST-safe/guarded client windows
[._.]/ Adam Eivy703c3edc1a34
diff --git a/client/src/components/meatspace/post/PostHistory.jsx b/client/src/components/meatspace/post/PostHistory.jsxindex 3bdace0162..c9d59cbdc4 100644--- a/client/src/components/meatspace/post/PostHistory.jsx+++ b/client/src/components/meatspace/post/PostHistory.jsx@@ -1,4 +1,4 @@-import { useState, useEffect, useCallback, useMemo } from 'react';+import { useState, useEffect, useCallback, useMemo, useRef } from 'react';import { useNavigate } from 'react-router-dom';import { ArrowLeft, ChevronRight, Flame, Trophy } from 'lucide-react';import {@@ -7,7 +7,7 @@ import {import { getPostSessions, getPostStats } from '../../../services/api';import useChartColors from '../../../hooks/useChartColors.js';import useUserTimezone from '../../../hooks/useUserTimezone.js';-import { dayKeyInTimezone } from '../../../utils/timezone.js';+import { todayKeyInTimezone, shiftDayKey } from '../../../utils/timezone.js';import { DRILL_TO_DOMAIN, DRILL_LABELS, domainLabel } from './constants';const RANGES = [@@ -41,17 +41,25 @@ export default function PostHistory({ onBack }) {const [sessions, setSessions] = useState([]);const [stats, setStats] = useState(null);const [range, setRange] = useState(30);+ // Generation guard: `timezone` resolves async (browser zone → configured zone),+ // so mount fires one load with the browser-derived floor and a second once the+ // configured tz arrives. Without ordering protection the first (stale) response+ // can land last and overwrite the correctly-filtered sessions (issue #2681 r4).+ const loadGenRef = useRef(0);const loadData = useCallback(async () => {- // Floor the window at the local day `range` days back (configured tz), so it- // lines up with the server's local-day session dates rather than a UTC bound.+ const gen = ++loadGenRef.current;+ // Floor the window at the local day `range` CALENDAR days back (configured tz),+ // via DST-safe day-string math — so it lines up with the server's DST-safe,+ // local-day session window rather than a UTC / elapsed-hours bound.const from = range > 0- ? dayKeyInTimezone(timezone, new Date(Date.now() - range * 86400000))+ ? shiftDayKey(todayKeyInTimezone(timezone), -range): undefined;const [s, st] = await Promise.all([getPostSessions(from).catch(err => { console.warn('⚠️ Failed to load POST sessions: ' + err.message); return []; }),getPostStats(range).catch(err => { console.warn('⚠️ Failed to load POST stats: ' + err.message); return null; })]);+ if (gen !== loadGenRef.current) return; // a newer load superseded this onesetSessions((s || []).slice().reverse());setStats(st);}, [range, timezone]);diff --git a/client/src/hooks/useUserTimezone.js b/client/src/hooks/useUserTimezone.jsindex cf6664342a..a882b9a860 100644--- a/client/src/hooks/useUserTimezone.js+++ b/client/src/hooks/useUserTimezone.js@@ -1,5 +1,6 @@import { useState, useEffect } from 'react';import { getSettings } from '../services/api';+import { isValidTimezone } from '../utils/timezone.js';/*** Resolve the user's CONFIGURED IANA timezone (`settings.timezone`) once on@@ -28,7 +29,14 @@ export default function useUserTimezone() {useEffect(() => {getSettings({ silent: true })- .then((s) => { if (s?.timezone) setTimezone(s.timezone); })+ .then((s) => {+ const tz = s?.timezone;+ if (!tz) return; // unconfigured: keep the browser zone (self-heal seeds it)+ // A hand-edited/invalid configured tz makes the server fall back to its+ // process timezone (UTC under TZ=UTC). Match that instead of letting+ // dayKeyInTimezone silently drift to the browser zone (issue #2681 r4).+ setTimezone(isValidTimezone(tz) ? tz : 'UTC');+ }).catch(() => {});}, []);diff --git a/client/src/utils/timezone.js b/client/src/utils/timezone.jsindex 60b44b29ec..d5718d5e6b 100644--- a/client/src/utils/timezone.js+++ b/client/src/utils/timezone.js@@ -34,3 +34,36 @@ export function dayKeyInTimezone(timezone, date = new Date()) {export function todayKeyInTimezone(timezone) {return dayKeyInTimezone(timezone, new Date());}++/**+ * Shift a `YYYY-MM-DD` day key by whole CALENDAR days — the browser mirror of the+ * server's `ymdShift` (server/lib/postStreak.js). Day arithmetic goes through UTC+ * midnight so it never drifts across a DST transition: subtracting+ * `range * 86400000` ms from a wall-clock instant counts elapsed HOURS and, across+ * a spring-forward, lands on the wrong calendar day (issue #2681 r4). Use this for+ * window floors so the client matches the server's DST-safe day windows.+ * @param {string} dayKey - `YYYY-MM-DD`+ * @param {number} deltaDays - signed day offset+ * @returns {string}+ */+export function shiftDayKey(dayKey, deltaDays) {+ const [y, m, d] = String(dayKey).split('-').map(Number);+ return new Date(Date.UTC(y, m - 1, d) + deltaDays * 86400000).toISOString().split('T')[0];+}++/**+ * True when `timezone` is a usable IANA zone. Lets callers apply the SERVER's+ * fallback (UTC) for an invalid configured value instead of silently drifting to+ * the browser zone (issue #2681 r4).+ * @param {string} timezone+ * @returns {boolean}+ */+export function isValidTimezone(timezone) {+ if (!timezone) return false;+ try {+ new Intl.DateTimeFormat('en-CA', { timeZone: timezone });+ return true;+ } catch {+ return false;+ }+}diff --git a/client/src/utils/timezone.test.js b/client/src/utils/timezone.test.jsindex 851e8b9ff5..a350c9710b 100644--- a/client/src/utils/timezone.test.js+++ b/client/src/utils/timezone.test.js@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest';-import { dayKeyInTimezone, todayKeyInTimezone } from './timezone.js';+import { dayKeyInTimezone, todayKeyInTimezone, shiftDayKey, isValidTimezone } from './timezone.js';describe('dayKeyInTimezone', () => {it('returns the local day for an instant whose UTC day is ahead of the local day', () => {@@ -35,3 +35,34 @@ describe('todayKeyInTimezone', () => {expect(todayKeyInTimezone('UTC')).toMatch(/^\d{4}-\d{2}-\d{2}$/);});});++describe('shiftDayKey', () => {+ it('shifts by whole calendar days', () => {+ expect(shiftDayKey('2026-07-15', -7)).toBe('2026-07-08');+ expect(shiftDayKey('2026-07-15', 1)).toBe('2026-07-16');+ expect(shiftDayKey('2026-07-15', 0)).toBe('2026-07-15');+ });++ it('crosses month/year boundaries correctly', () => {+ expect(shiftDayKey('2026-01-01', -1)).toBe('2025-12-31');+ expect(shiftDayKey('2026-03-01', -1)).toBe('2026-02-28');+ });++ it('is DST-safe: a 7-day shift across US spring-forward stays a whole day count', () => {+ // 2026 US DST begins 2026-03-08. Elapsed-hours math would drift here; calendar+ // day math does not — 7 days before the 15th is the 8th, exactly.+ expect(shiftDayKey('2026-03-15', -7)).toBe('2026-03-08');+ });+});++describe('isValidTimezone', () => {+ it('accepts real IANA zones', () => {+ expect(isValidTimezone('America/Los_Angeles')).toBe(true);+ expect(isValidTimezone('UTC')).toBe(true);+ });+ it('rejects invalid/empty values', () => {+ expect(isValidTimezone('Not/A_Zone')).toBe(false);+ expect(isValidTimezone('')).toBe(false);+ expect(isValidTimezone(undefined)).toBe(false);+ });+});diff --git a/scripts/migrations/192-post-dates-to-local-timezone.js b/scripts/migrations/192-post-dates-to-local-timezone.jsindex dcb5a5a4e1..eab6f4f025 100644--- a/scripts/migrations/192-post-dates-to-local-timezone.js+++ b/scripts/migrations/192-post-dates-to-local-timezone.js@@ -126,6 +126,14 @@ async function normalizeFile(path, arrayKey, instantOf, timezone) {if (!instant) continue; // no recoverable time — leave the stored date as-isconst localDay = localDayFor(instant, timezone);if (localDay && rec.date !== localDay) {+ // Preserve the exact instant before overwriting `date` with the day key.+ // A legacy memory-practice entry's ONLY instant is the full ISO in `date`+ // (the old writer added no `timestamp`); replacing it with a bare day would+ // irreversibly discard that time. Stash it in `timestamp` when the record+ // carries no other instant field (issue #2681 r4).+ if (!rec.timestamp && !rec.startedAt && !rec.completedAt) {+ rec.timestamp = instant;+ }rec.date = localDay;updated += 1;}diff --git a/scripts/migrations/192-post-dates-to-local-timezone.test.js b/scripts/migrations/192-post-dates-to-local-timezone.test.jsindex 2acc71077f..17051e477c 100644--- a/scripts/migrations/192-post-dates-to-local-timezone.test.js+++ b/scripts/migrations/192-post-dates-to-local-timezone.test.js@@ -104,6 +104,37 @@ describe('migration 192 — normalize POST dates to the user local timezone', ()expect(readJson(trainingPath).entries[0].date).toBe('2026-07-15');});+ it('preserves the exact instant of a legacy practice entry (full-ISO date, no timestamp) before rewriting date', async () => {+ // A legacy memory-practice entry's only instant is the full ISO in `date`;+ // the migration must stash it in `timestamp` before overwriting `date`.+ writeJson(settingsPath, { timezone: 'America/Los_Angeles' });+ writeJson(trainingPath, {+ entries: [{ id: 't1', date: '2026-07-16T05:00:00.000Z', memoryItemId: 'm1' }],+ });+ const result = await migration.up({ rootDir });+ expect(result.updated).toBe(1);+ const entry = readJson(trainingPath).entries[0];+ expect(entry.date).toBe('2026-07-15');+ expect(entry.timestamp).toBe('2026-07-16T05:00:00.000Z');+ });++ it('does not overwrite an existing timestamp/startedAt when normalizing date', async () => {+ writeJson(settingsPath, { timezone: 'America/Los_Angeles' });+ writeJson(sessionsPath, {+ sessions: [{+ id: 's1', date: '2026-07-16',+ startedAt: '2026-07-16T05:00:00.000Z',+ completedAt: '2026-07-16T05:30:00.000Z',+ }],+ });+ await migration.up({ rootDir });+ const s = readJson(sessionsPath).sessions[0];+ expect(s.date).toBe('2026-07-15');+ expect(s.startedAt).toBe('2026-07-16T05:00:00.000Z'); // untouched+ expect(s.completedAt).toBe('2026-07-16T05:30:00.000Z'); // untouched+ expect(s.timestamp).toBeUndefined(); // not added — instant already preserved+ });+it('leaves a record with no recoverable instant untouched', async () => {// Bare date-only, no completedAt/startedAt/timestamp — no way to know the// local day, so it must be preserved rather than guessed.