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

address review (codex): tz-stamp training writer + migrate legacy POST dates

[._.]/ Adam Eivyc0d60c92417e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7261f02786..42bbbedb83 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -59,7 +59,7 @@
## Fixed
-- **[issue-2681] POST daily status now uses your timezone, not the server's UTC day.** `completedToday`, `todayScore`, and the scored-session streak in the MeatSpace POST service derived the day boundary from the server's UTC day (the process runs `TZ=UTC`), so for anyone outside UTC a POST completed the previous local evening could read as "done today," or a just-completed local-day POST could read as incomplete — and the Daily Post widget and the Daily Driver card (#2666), which both render `completedToday` from `getPostStats()`, inherited the drift. The day boundary now threads your configured timezone (`getUserTimezone`/`todayInTimezone`) through both sides: `submitPostSession` stamps a new session's `date` in your local day, and `getPostStats`/`getPostProgress`/`getUnifiedActivityStreak` derive "today" in your local day — mirroring the Daily Driver's tz-correct first-visit/handled markers so the two surfaces agree. The stats-window cutoff uses DST-safe day math off the local today. Existing session history keeps its stored dates (no migration); the streak grace window absorbs any one-time boundary shift.
+- **[issue-2681] POST daily status now uses your timezone, not the server's UTC day.** `completedToday`, `todayScore`, and the POST streaks in the MeatSpace POST service derived the day boundary from the server's UTC day (the process runs `TZ=UTC`), so for anyone outside UTC a POST completed the previous local evening could read as "done today," or a just-completed local-day POST could read as incomplete — and the Daily Post widget and the Daily Driver card (#2666), which both render `completedToday` from `getPostStats()`, inherited the drift. The day boundary now threads your configured timezone (`getUserTimezone`/`todayInTimezone`, via a shared `userLocalToday()` helper) through both sides: `submitPostSession` and `submitTrainingEntry` stamp a new record's `date` in your local day, and `getPostStats`/`getPostProgress`/`getUnifiedActivityStreak` (plus the mastery-window cutoffs) derive "today" in your local day — mirroring the Daily Driver's tz-correct first-visit/handled markers so every surface agrees. The stats/mastery-window cutoffs use DST-safe day math off the local today. A one-time migration (`192-post-dates-to-local-timezone`) re-derives existing session and training-log day-strings from each record's stored UTC timestamp in your timezone, so historical streaks stay correct and don't collide with newly-written local-day records; it's a no-op for UTC/unconfigured installs.
- **[issue-2567] Stop double error toasts across the Settings tabs and the JIRA integration page.** Several Settings surfaces routed a request through the auto-toasting `request()` helper AND showed their own `toast.error` in a custom catch, so a failure stacked two toasts. Every such call now passes `{ silent: true }` so the caller's catch is the single error layer — covering VoiceTab (config load/save, Piper voice download), ImageGenTab (settings/tools load, save, tool register/update, test render), TelegramTab (settings load, method/config/test/disconnect, forward-types), BackupTab (settings load + save), DatabaseTab (status load), EmbeddingsTab (save), MortalLoomTab and CaptionModelPicker (save), and the JIRA instances page (load/save/delete/test — mirroring the DataDog fix from #2520). Loaders and callers without a custom toast are unchanged (single default-helper layer preserved). The `getVoiceConfig`/`updateVoiceConfig`/`fetchPiperVoice`, telegram, `registerTool`/`updateTool`/`getToolsList`, and `getDatabaseStatus` wrappers gained a backward-compatible trailing `options` param so callers can opt into silent. Follow-up sweep of the remaining pipeline/writers-room/universe/media/etc. areas is tracked in #2669.
diff --git a/scripts/migrations/192-post-dates-to-local-timezone.js b/scripts/migrations/192-post-dates-to-local-timezone.js
new file mode 100644
index 0000000000..deeebd0eb5
--- /dev/null
+++ b/scripts/migrations/192-post-dates-to-local-timezone.js
@@ -0,0 +1,156 @@
+/**
+ * Normalize existing POST session & training-log day-strings to the user's local
+ * timezone (issue #2681).
+ *
+ * Background:
+ * `completedToday`/`todayScore` and the POST streaks used to derive "today"
+ * from the server's UTC day (the process runs `TZ=UTC`), and both the scored-
+ * session writer (`submitPostSession`) and the training writer
+ * (`submitTrainingEntry`) stamped each record's `date` with that same UTC day.
+ * Issue #2681 moves BOTH the read side (today derivation) and the write side
+ * (new records) onto the user's *local* day.
+ *
+ * That leaves already-stored records dated by the OLD (UTC) day while readers
+ * now interpret every `date` as a local day. For a non-UTC user, a session or
+ * practice completed in the local evening was stamped on the *next* UTC day, so
+ * read as a local day it lands one day late — mislabeling streak history and
+ * even colliding with a genuinely-next-day record. This migration re-derives
+ * each stored `date` from the record's own UTC timestamp (`completedAt` /
+ * `startedAt` for sessions, `timestamp` for training entries — falling back to
+ * a full-ISO `date` when present) in the user's configured timezone, so all
+ * history uses the same local-day semantics the new writers do.
+ *
+ * No-op by construction for installs where the local day already equals the UTC
+ * day: an unconfigured timezone resolves to the process tz (UTC under `TZ=UTC`),
+ * and an explicitly-`UTC` setting short-circuits — so nothing is rewritten and
+ * the common case can't be corrupted. Records with no recoverable instant
+ * (a bare date-only string and no timestamp) are left untouched.
+ */
+
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+
+const SESSIONS_REL = 'data/meatspace/post-sessions.json';
+const TRAINING_REL = 'data/meatspace/post-training-log.json';
+const SETTINGS_REL = 'data/settings.json';
+
+// Resolve the install's configured timezone the same way the runtime does:
+// a valid `settings.timezone`, else the process timezone (UTC under `TZ=UTC`),
+// so an unconfigured install is a guaranteed no-op.
+async function resolveTimezone(rootDir) {
+ const raw = await readFile(join(rootDir, SETTINGS_REL), 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ let tz = null;
+ if (raw != null) {
+ try {
+ tz = JSON.parse(raw)?.timezone ?? null;
+ } catch {
+ tz = null;
+ }
+ }
+ if (tz) {
+ try {
+ new Intl.DateTimeFormat('en-CA', { timeZone: tz });
+ return tz;
+ } catch {
+ // Invalid configured tz — fall through to the process default.
+ }
+ }
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
+}
+
+// `YYYY-MM-DD` for a UTC instant, evaluated in `timezone`. `en-CA` formats
+// dates as ISO `YYYY-MM-DD`, matching the runtime `todayInTimezone` output.
+function localDayFor(instant, timezone) {
+ const d = new Date(instant);
+ if (Number.isNaN(d.getTime())) return null;
+ return new Intl.DateTimeFormat('en-CA', {
+ timeZone: timezone,
+ year: 'numeric',
+ month: '2-digit',
+ day: '2-digit',
+ }).format(d);
+}
+
+// Pick the UTC instant that best represents when a session was completed. A
+// full-ISO `date` (contains 'T') is only a fallback for pre-completedAt records.
+function sessionInstant(s) {
+ if (typeof s?.completedAt === 'string' && s.completedAt.includes('T')) return s.completedAt;
+ if (typeof s?.startedAt === 'string' && s.startedAt.includes('T')) return s.startedAt;
+ if (typeof s?.date === 'string' && s.date.includes('T')) return s.date;
+ return null;
+}
+
+// Training entries carry `timestamp` (full UTC ISO); memory-practice entries
+// historically stored a full ISO in `date` itself.
+function trainingInstant(e) {
+ if (typeof e?.timestamp === 'string' && e.timestamp.includes('T')) return e.timestamp;
+ if (typeof e?.date === 'string' && e.date.includes('T')) return e.date;
+ return null;
+}
+
+async function normalizeFile(path, arrayKey, instantOf, timezone) {
+ const raw = await readFile(path, 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (raw == null) return { updated: 0, reason: 'no-file' };
+
+ let data;
+ try {
+ data = JSON.parse(raw);
+ } catch (err) {
+ console.log(`⚠️ ${path}: invalid JSON, skipping (${err.message})`);
+ return { updated: 0, reason: 'invalid-json' };
+ }
+
+ const records = Array.isArray(data?.[arrayKey]) ? data[arrayKey] : null;
+ if (!records) return { updated: 0, reason: 'no-records' };
+
+ let updated = 0;
+ for (const rec of records) {
+ const instant = instantOf(rec);
+ if (!instant) continue; // no recoverable time — leave the stored date as-is
+ const localDay = localDayFor(instant, timezone);
+ if (localDay && rec.date !== localDay) {
+ rec.date = localDay;
+ updated += 1;
+ }
+ }
+
+ if (updated > 0) {
+ // Re-sort by the normalized day so ordering matches the writers' invariant.
+ records.sort((a, b) => String(a.date).localeCompare(String(b.date)));
+ await writeFile(path, `${JSON.stringify(data, null, 2)}\n`);
+ }
+ return { updated };
+}
+
+export default {
+ async up({ rootDir }) {
+ const timezone = await resolveTimezone(rootDir);
+ // If local day == UTC day for this install, every re-derivation is a no-op —
+ // skip the file rewrites entirely so a UTC install is never touched.
+ if (timezone === 'UTC' || timezone === 'Etc/UTC') {
+ console.log('🕓 POST dates: timezone resolves to UTC — no local-day normalization needed');
+ return { updated: 0, reason: 'utc-timezone' };
+ }
+
+ const sessions = await normalizeFile(
+ join(rootDir, SESSIONS_REL), 'sessions', sessionInstant, timezone,
+ );
+ const training = await normalizeFile(
+ join(rootDir, TRAINING_REL), 'entries', trainingInstant, timezone,
+ );
+
+ const total = sessions.updated + training.updated;
+ if (total > 0) {
+ console.log(`📝 POST dates: normalized ${sessions.updated} session(s) + ${training.updated} training entr${training.updated === 1 ? 'y' : 'ies'} to ${timezone} local days`);
+ } else {
+ console.log(`✅ POST dates: already local-day consistent for ${timezone} — no changes`);
+ }
+ return { updated: total, timezone };
+ },
+};
diff --git a/scripts/migrations/192-post-dates-to-local-timezone.test.js b/scripts/migrations/192-post-dates-to-local-timezone.test.js
new file mode 100644
index 0000000000..f0a21e6210
--- /dev/null
+++ b/scripts/migrations/192-post-dates-to-local-timezone.test.js
@@ -0,0 +1,139 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import migration from './192-post-dates-to-local-timezone.js';
+
+const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');
+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));
+
+describe('migration 192 — normalize POST dates to the user local timezone', () => {
+ let rootDir;
+ let sessionsPath;
+ let trainingPath;
+ let settingsPath;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-192-'));
+ mkdirSync(join(rootDir, 'data', 'meatspace'), { recursive: true });
+ sessionsPath = join(rootDir, 'data', 'meatspace', 'post-sessions.json');
+ trainingPath = join(rootDir, 'data', 'meatspace', 'post-training-log.json');
+ settingsPath = join(rootDir, 'data', 'settings.json');
+ });
+
+ afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+ });
+
+ it('no-ops when no data files exist (and tz is set)', async () => {
+ writeJson(settingsPath, { timezone: 'America/Los_Angeles' });
+ const result = await migration.up({ rootDir });
+ expect(result.updated).toBe(0);
+ expect(existsSync(sessionsPath)).toBe(false);
+ expect(existsSync(trainingPath)).toBe(false);
+ });
+
+ it('short-circuits with no file rewrites when the timezone resolves to UTC', async () => {
+ writeJson(settingsPath, { timezone: 'UTC' });
+ // A session whose UTC completion day differs from its stored date would be
+ // rewritten if the migration ran — assert it is left untouched under UTC.
+ writeJson(sessionsPath, {
+ sessions: [{ id: 's1', date: '2026-07-16', completedAt: '2026-07-16T05:00:00.000Z' }],
+ });
+ const result = await migration.up({ rootDir });
+ expect(result).toEqual({ updated: 0, reason: 'utc-timezone' });
+ expect(readJson(sessionsPath).sessions[0].date).toBe('2026-07-16');
+ });
+
+ it('re-derives a session date from completedAt in a non-UTC timezone', async () => {
+ // 2026-07-16T05:00Z = 2026-07-15 22:00 PDT — stored under the UTC day, but the
+ // session was completed on the user local day July 15.
+ writeJson(settingsPath, { timezone: 'America/Los_Angeles' });
+ writeJson(sessionsPath, {
+ sessions: [
+ { id: 's1', date: '2026-07-16', completedAt: '2026-07-16T05:00:00.000Z', score: 80 },
+ ],
+ });
+ const result = await migration.up({ rootDir });
+ expect(result.updated).toBe(1);
+ expect(readJson(sessionsPath).sessions[0].date).toBe('2026-07-15');
+ });
+
+ it('does not collapse a genuinely-next-local-day session onto the prior day', async () => {
+ // Two sessions: one completed local July 15 evening (UTC July 16), one local
+ // July 16 evening (UTC July 17). Under local semantics they stay on distinct
+ // days — the exact "missing day / collapse" case the migration prevents.
+ writeJson(settingsPath, { timezone: 'America/Los_Angeles' });
+ writeJson(sessionsPath, {
+ sessions: [
+ { id: 's1', date: '2026-07-16', completedAt: '2026-07-16T05:00:00.000Z' },
+ { id: 's2', date: '2026-07-17', completedAt: '2026-07-17T05:00:00.000Z' },
+ ],
+ });
+ await migration.up({ rootDir });
+ const days = readJson(sessionsPath).sessions.map((s) => s.date).sort();
+ expect(days).toEqual(['2026-07-15', '2026-07-16']);
+ });
+
+ it('re-derives a training entry date from its timestamp', async () => {
+ writeJson(settingsPath, { timezone: 'America/Los_Angeles' });
+ writeJson(trainingPath, {
+ entries: [
+ { id: 't1', date: '2026-07-16', timestamp: '2026-07-16T05:00:00.000Z', module: 'mental-math' },
+ ],
+ });
+ const result = await migration.up({ rootDir });
+ expect(result.updated).toBe(1);
+ expect(readJson(trainingPath).entries[0].date).toBe('2026-07-15');
+ });
+
+ 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.
+ writeJson(settingsPath, { timezone: 'America/Los_Angeles' });
+ writeJson(sessionsPath, { sessions: [{ id: 's1', date: '2026-07-16' }] });
+ const result = await migration.up({ rootDir });
+ expect(result.updated).toBe(0);
+ expect(readJson(sessionsPath).sessions[0].date).toBe('2026-07-16');
+ });
+
+ it('is idempotent across re-runs', async () => {
+ writeJson(settingsPath, { timezone: 'America/Los_Angeles' });
+ writeJson(sessionsPath, {
+ sessions: [{ id: 's1', date: '2026-07-16', completedAt: '2026-07-16T05:00:00.000Z' }],
+ });
+ await migration.up({ rootDir });
+ const afterFirst = readJson(sessionsPath);
+ const second = await migration.up({ rootDir });
+ expect(second.updated).toBe(0);
+ expect(readJson(sessionsPath)).toEqual(afterFirst);
+ });
+
+ it('falls back to the process timezone when none is configured', async () => {
+ // No settings file → resolves to the runner's own system timezone. Assert the
+ // outcome relative to THAT tz so the test is deterministic on any runner: a
+ // UTC runner short-circuits (no rewrite); a non-UTC runner re-derives the day.
+ const sysTz = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
+ const instant = '2026-07-16T05:00:00.000Z';
+ writeJson(sessionsPath, { sessions: [{ id: 's1', date: '2026-07-16', completedAt: instant }] });
+ const result = await migration.up({ rootDir });
+ if (sysTz === 'UTC' || sysTz === 'Etc/UTC') {
+ expect(result).toEqual({ updated: 0, reason: 'utc-timezone' });
+ expect(readJson(sessionsPath).sessions[0].date).toBe('2026-07-16');
+ } else {
+ const expected = new Intl.DateTimeFormat('en-CA', {
+ timeZone: sysTz, year: 'numeric', month: '2-digit', day: '2-digit',
+ }).format(new Date(instant));
+ expect(readJson(sessionsPath).sessions[0].date).toBe(expected);
+ }
+ });
+
+ it('skips a malformed data file without throwing', async () => {
+ writeJson(settingsPath, { timezone: 'America/Los_Angeles' });
+ writeFileSync(sessionsPath, '{ not json');
+ const result = await migration.up({ rootDir });
+ // Malformed sessions file is skipped; training absent → total 0, no throw.
+ expect(result.updated).toBe(0);
+ });
+});
diff --git a/server/lib/timezone.js b/server/lib/timezone.js
index 099e3c56bb..eddb8d58f2 100644
--- a/server/lib/timezone.js
+++ b/server/lib/timezone.js
@@ -144,6 +144,22 @@ export function todayInTimezone(timezone) {
return `${parts.year}-${String(parts.month).padStart(2, '0')}-${String(parts.day).padStart(2, '0')}`
}
+/**
+ * Today's `YYYY-MM-DD` in the USER's configured timezone — the resolve-tz-then-
+ * derive-today combination that every per-day feature keying off the local day
+ * needs (POST daily status/streaks in meatspacePost.js & meatspacePostTraining.js,
+ * the Daily Driver). Kept here (in lib) so both the scored-session service and the
+ * training-log service share ONE day boundary without importing each other (they
+ * already have a mutual dependency; this avoids adding to it). The process runs
+ * `TZ=UTC`, so deriving the day from a bare `new Date().toISOString()` would use
+ * the server's UTC day and misfile activity around the local/UTC midnight boundary
+ * for non-UTC users (issue #2681).
+ * @returns {Promise<string>}
+ */
+export async function userLocalToday() {
+ return todayInTimezone(await getUserTimezone())
+}
+
// ---------------------------------------------------------------------------
// HH:MM time-window primitives
//
diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.js
index 46b08c3330..35960b75b9 100644
--- a/server/services/meatspacePost.js
+++ b/server/services/meatspacePost.js
@@ -26,25 +26,22 @@ import { applySessionToReviewSchedule, getDueReviews, getRetentionReport } from
import { getAllTrainingEntries } from './meatspacePostTraining.js';
import { getMorseProgress, MAX_KOCH_LEVEL } from './meatspacePostMorse.js';
import { computePostStreaks, computeUnifiedStreak, ymdToUTC, ymdShift } from '../lib/postStreak.js';
-import { getUserTimezone, todayInTimezone } from '../lib/timezone.js';
+import { userLocalToday as localToday } from '../lib/timezone.js';
// Re-export the shared streak helper so existing importers of
// `computePostStreaks` from this module keep working after it moved to
// server/lib/postStreak.js (single implementation — see that file).
export { computePostStreaks };
-// Today's `YYYY-MM-DD` in the USER's configured timezone (not the server's UTC
-// day). The process runs `TZ=UTC`, so a bare `new Date().toISOString()` day
-// derivation misfiles POSTs around the local/UTC midnight boundary — a scored
-// session completed the previous local evening reads as "done today," or a
-// just-completed local-day session reads as incomplete (issue #2681). Both the
-// session `date` stamp (write side) and the `completedToday`/`todayScore`/streak
-// derivations (read side) key off this so they agree on the user's local day,
-// mirroring the Daily Driver's tz-correct first-visit/handled markers (#2666).
-async function localToday() {
- const tz = await getUserTimezone();
- return todayInTimezone(tz);
-}
+// `localToday()` = today's `YYYY-MM-DD` in the USER's configured timezone (shared
+// helper in server/lib/timezone.js). The process runs `TZ=UTC`, so a bare
+// `new Date().toISOString()` day derivation misfiles POSTs around the local/UTC
+// midnight boundary — a scored session completed the previous local evening reads
+// as "done today," or a just-completed local-day session reads as incomplete
+// (issue #2681). Both the session `date` stamp (write side) and the
+// `completedToday`/`todayScore`/streak derivations (read side) key off this so
+// they agree on the user's local day, mirroring the Daily Driver's tz-correct
+// first-visit/handled markers (#2666).
const MEATSPACE_DIR = PATHS.meatspace;
const SESSIONS_FILE = join(MEATSPACE_DIR, 'post-sessions.json');
diff --git a/server/services/meatspacePost.test.js b/server/services/meatspacePost.test.js
index ae6deb285b..8a22817dbc 100644
--- a/server/services/meatspacePost.test.js
+++ b/server/services/meatspacePost.test.js
@@ -15,10 +15,12 @@ vi.mock('../lib/fileUtils.js', () => ({
// getUserTimezone (via ../lib/timezone.js) reads getSettings() to derive the
// user's local day (issue #2681). Mock settings so the day-boundary is
-// controllable. Default `{}` = no configured timezone, so getUserTimezone falls
-// back to the process timezone (the suite runs TZ=UTC) and every existing
-// UTC-today assertion holds unchanged; tz-specific tests set settingsState.current.
-const settingsState = vi.hoisted(() => ({ current: {} }));
+// controllable. Default `{ timezone: 'UTC' }` pins the boundary to the UTC day
+// regardless of the runner's own system timezone — so every existing UTC-today
+// assertion holds deterministically (an unpinned `{}` would fall back to the
+// runner's system tz and break these suites off a non-UTC CI runner). tz-specific
+// tests set settingsState.current to a real IANA zone.
+const settingsState = vi.hoisted(() => ({ current: { timezone: 'UTC' } }));
vi.mock('../services/settings.js', () => ({
getSettings: () => Promise.resolve(settingsState.current),
}));
@@ -1312,7 +1314,7 @@ describe('getPostStats — byModule averaging, days window cutoff, empty-window
describe('getPostStats / submitPostSession — timezone-correct day boundary (issue #2681)', () => {
beforeEach(() => { vi.clearAllMocks(); });
- afterEach(() => { vi.useRealTimers(); settingsState.current = {}; });
+ afterEach(() => { vi.useRealTimers(); settingsState.current = { timezone: 'UTC' }; });
function mockSessions(sessions) {
readJSONFile.mockImplementation((path, defaultValue) => {
diff --git a/server/services/meatspacePostProgress.test.js b/server/services/meatspacePostProgress.test.js
index b86c178743..6e69bf0b50 100644
--- a/server/services/meatspacePostProgress.test.js
+++ b/server/services/meatspacePostProgress.test.js
@@ -19,11 +19,10 @@ vi.mock('../lib/fileUtils.js', () => ({
}));
// getUserTimezone (via ../lib/timezone.js) reads getSettings() for the local-day
-// boundary (issue #2681). Mock it to no configured tz so getUserTimezone falls
-// back to the process timezone (TZ=UTC in tests) — matching these tests' UTC-today
-// assumptions.
+// boundary (issue #2681). Pin it to UTC so "today" is the UTC day regardless of
+// the runner's own system timezone — matching these tests' UTC-today assumptions.
vi.mock('../services/settings.js', () => ({
- getSettings: () => Promise.resolve({}),
+ getSettings: () => Promise.resolve({ timezone: 'UTC' }),
}));
import { getPostProgress, getPostStats, getUnifiedActivityStreak } from './meatspacePost.js';
diff --git a/server/services/meatspacePostRecommendations.test.js b/server/services/meatspacePostRecommendations.test.js
index de5df2651d..4bda19dcbd 100644
--- a/server/services/meatspacePostRecommendations.test.js
+++ b/server/services/meatspacePostRecommendations.test.js
@@ -24,10 +24,10 @@ vi.mock('../lib/fileUtils.js', () => ({
}));
// getPostStats (via getPostRecommendations) derives the local day through
-// getUserTimezone → getSettings (issue #2681). Mock it to no configured tz so
-// the day boundary falls back to the process timezone (TZ=UTC in tests).
+// getUserTimezone → getSettings (issue #2681). Pin it to UTC so the day boundary
+// is the UTC day regardless of the runner's own system timezone.
vi.mock('../services/settings.js', () => ({
- getSettings: () => Promise.resolve({}),
+ getSettings: () => Promise.resolve({ timezone: 'UTC' }),
}));
import {
diff --git a/server/services/meatspacePostTraining.js b/server/services/meatspacePostTraining.js
index 508ec77bb2..7837173998 100644
--- a/server/services/meatspacePostTraining.js
+++ b/server/services/meatspacePostTraining.js
@@ -8,6 +8,7 @@
import { join } from 'path';
import { randomUUID } from 'crypto';
import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';
+import { userLocalToday } from '../lib/timezone.js';
import { getUnifiedActivityStreak } from './meatspacePost.js';
const MEATSPACE_DIR = PATHS.meatspace;
@@ -30,10 +31,16 @@ async function saveTrainingLog(data) {
export async function submitTrainingEntry(entry) {
const data = await loadTrainingLog();
const now = new Date().toISOString();
+ // Stamp the entry's day in the user's local timezone (issue #2681). Training
+ // entries feed the SHARED unified streak (getUnifiedActivityStreak), which now
+ // compares against the user's local `today` — a bare UTC-day stamp here would
+ // date a local-evening practice on tomorrow's UTC day and drop it from today's
+ // streak. `timestamp` stays the full UTC ISO instant for exact ordering.
+ const todayLocal = await userLocalToday();
const record = {
id: randomUUID(),
- date: now.split('T')[0],
+ date: todayLocal,
timestamp: now,
module: entry.module,
drillType: entry.drillType,
diff --git a/server/services/meatspacePostTraining.test.js b/server/services/meatspacePostTraining.test.js
index a702b408b7..55738c4b98 100644
--- a/server/services/meatspacePostTraining.test.js
+++ b/server/services/meatspacePostTraining.test.js
@@ -11,11 +11,11 @@ tryReadFile: vi.fn().mockResolvedValue(null),
readJSONFile: vi.fn().mockResolvedValue({ entries: [] }),
}));
-// getUnifiedActivityStreak (via meatspacePost.js) derives the local day through
-// getUserTimezone → getSettings (issue #2681). Mock it to no configured tz so
-// the day boundary falls back to the process timezone (TZ=UTC in tests).
+// submitTrainingEntry + getUnifiedActivityStreak (via meatspacePost.js) derive the
+// local day through getUserTimezone → getSettings (issue #2681). Pin it to UTC so
+// the day boundary is the UTC day regardless of the runner's own system timezone.
vi.mock('../services/settings.js', () => ({
- getSettings: () => Promise.resolve({}),
+ getSettings: () => Promise.resolve({ timezone: 'UTC' }),
}));
import { readJSONFile, atomicWrite } from '../lib/fileUtils.js';