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 r5): tz-correct Morse rounds + single-instant day keys
[._.]/ Adam Eivy62897e94eaa8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 3b54f305c2..ffc939a3e0 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 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: every writer that stamps a day (`submitPostSession`, `submitTrainingEntry`, and memory-practice logging in `submitPractice`) records a new record's `date` in your local day, and every reader (`getPostStats`/`getPostProgress`/`getUnifiedActivityStreak`/`getTrainingStats`, plus the mastery-window cutoffs) derives "today" in your local day — mirroring the Daily Driver's tz-correct first-visit/handled markers so every surface agrees. All window cutoffs use DST-safe day math off the local today. The POST launcher's "completed today"/today's-minutes and the history range floor also derive their day key in your configured timezone (new `useUserTimezone` hook + `dayKeyInTimezone` util) so the client agrees with the server instead of computing "today" in UTC. 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 (preferring the retry-stable `startedAt`), so historical streaks stay correct and don't collide with newly-written local-day records; it falls back to UTC (matching the server's `TZ=UTC` runtime), making it a no-op for UTC/unconfigured installs.+- **[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: every writer that stamps a day (`submitPostSession`, `submitTrainingEntry`, memory-practice `submitPractice`, and Morse `appendMorseRound`) records a new record's `date` in your local day — derived from the same instant it stamps into `timestamp`/`startedAt` so a midnight boundary can't split the two — and every reader (`getPostStats`/`getPostProgress`/`getUnifiedActivityStreak`/`getTrainingStats`/`getMorseProgress`, plus the mastery-window cutoffs) derives "today" in your local day, mirroring the Daily Driver's tz-correct first-visit/handled markers so every surface agrees. All window cutoffs use DST-safe day math off the local today. The POST launcher's "completed today"/today's-minutes and the history range floor also derive their day key in your configured timezone (new `useUserTimezone` hook + `dayKeyInTimezone` util) so the client agrees with the server instead of computing "today" in UTC. A one-time migration (`192-post-dates-to-local-timezone`) re-derives existing session, training-log, and Morse-round day-strings from each record's stored UTC timestamp in your timezone (preferring the retry-stable `startedAt`, and preserving a legacy practice entry's only instant into `timestamp` before rewriting `date`), so historical streaks stay correct and don't collide with newly-written local-day records; it falls back to UTC (matching the server's `TZ=UTC` runtime), making it 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.jsindex eab6f4f025..0f189f1ccd 100644--- a/scripts/migrations/192-post-dates-to-local-timezone.js+++ b/scripts/migrations/192-post-dates-to-local-timezone.js@@ -32,6 +32,7 @@ import { join } from 'path';const SESSIONS_REL = 'data/meatspace/post-sessions.json';const TRAINING_REL = 'data/meatspace/post-training-log.json';+const MORSE_REL = 'data/meatspace/post-morse-progress.json';const SETTINGS_REL = 'data/settings.json';// Resolve the install's configured timezone the same way the runtime does:@@ -95,7 +96,8 @@ function sessionInstant(s) {}// Training entries carry `timestamp` (full UTC ISO); memory-practice entries-// historically stored a full ISO in `date` itself.+// historically stored a full ISO in `date` itself. Morse rounds share the same+// `{ date, timestamp }` shape, so this doubles as their instant resolver.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;@@ -163,10 +165,14 @@ export default {const training = await normalizeFile(join(rootDir, TRAINING_REL), 'entries', trainingInstant, timezone,);+ // Morse rounds share the training entry's `{ date, timestamp }` shape.+ const morse = await normalizeFile(+ join(rootDir, MORSE_REL), 'rounds', trainingInstant, timezone,+ );- const total = sessions.updated + training.updated;+ const total = sessions.updated + training.updated + morse.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`);+ console.log(`📝 POST dates: normalized ${sessions.updated} session(s) + ${training.updated} training + ${morse.updated} Morse to ${timezone} local days`);} else {console.log(`✅ POST dates: already local-day consistent for ${timezone} — no changes`);}diff --git a/scripts/migrations/192-post-dates-to-local-timezone.test.js b/scripts/migrations/192-post-dates-to-local-timezone.test.jsindex 17051e477c..3a6424065f 100644--- a/scripts/migrations/192-post-dates-to-local-timezone.test.js+++ b/scripts/migrations/192-post-dates-to-local-timezone.test.js@@ -14,11 +14,14 @@ describe('migration 192 — normalize POST dates to the user local timezone', ()let trainingPath;let settingsPath;+ let morsePath;+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');+ morsePath = join(rootDir, 'data', 'meatspace', 'post-morse-progress.json');settingsPath = join(rootDir, 'data', 'settings.json');});@@ -92,6 +95,17 @@ describe('migration 192 — normalize POST dates to the user local timezone', ()expect(readJson(sessionsPath).sessions[0].date).toBe('2026-07-15');});+ it('re-derives Morse round dates from their timestamps', async () => {+ writeJson(settingsPath, { timezone: 'America/Los_Angeles' });+ writeJson(morsePath, {+ kochLevel: 2, settings: null,+ rounds: [{ id: 'r1', date: '2026-07-16', timestamp: '2026-07-16T05:00:00.000Z', mode: 'copy' }],+ });+ const result = await migration.up({ rootDir });+ expect(result.updated).toBe(1);+ expect(readJson(morsePath).rounds[0].date).toBe('2026-07-15');+ });+it('re-derives a training entry date from its timestamp', async () => {writeJson(settingsPath, { timezone: 'America/Los_Angeles' });writeJson(trainingPath, {diff --git a/server/lib/timezone.js b/server/lib/timezone.jsindex eddb8d58f2..02dafbafd5 100644--- a/server/lib/timezone.js+++ b/server/lib/timezone.js@@ -135,12 +135,16 @@ export function nextLocalTime(afterMs, hours, minutes, timezone) {}/**- * Get today's date string (YYYY-MM-DD) in the user's timezone.+ * Get the date string (YYYY-MM-DD) for an instant in the user's timezone —+ * "today" by default, or a caller-supplied instant. Pass the SAME instant a+ * writer stamped into its `timestamp`/`startedAt` so the day key and the instant+ * can't land on different days across a midnight boundary (issue #2681).* @param {string} timezone - IANA timezone string+ * @param {Date} [atDate] - instant to key (defaults to now)* @returns {string}*/-export function todayInTimezone(timezone) {- const parts = getLocalParts(new Date(), timezone)+export function todayInTimezone(timezone, atDate = new Date()) {+ const parts = getLocalParts(atDate, timezone)return `${parts.year}-${String(parts.month).padStart(2, '0')}-${String(parts.day).padStart(2, '0')}`}@@ -154,10 +158,15 @@ export function todayInTimezone(timezone) {* `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).+ * Pass `atDate` (the instant a writer already captured for its timestamp) so the+ * day key derives from the SAME instant, never a fresh `new Date()` sampled after+ * the awaited settings read — which could cross midnight and split the two fields+ * onto different days (issue #2681 r5).+ * @param {Date} [atDate] - instant to key (defaults to now)* @returns {Promise<string>}*/-export async function userLocalToday() {- return todayInTimezone(await getUserTimezone())+export async function userLocalToday(atDate = new Date()) {+ return todayInTimezone(await getUserTimezone(), atDate)}// ---------------------------------------------------------------------------diff --git a/server/lib/timezone.test.js b/server/lib/timezone.test.jsindex 7a6f04003a..0031209e9d 100644--- a/server/lib/timezone.test.js+++ b/server/lib/timezone.test.js@@ -195,6 +195,14 @@ describe('timezone', () => {vi.useRealTimers()})++ it('keys a caller-supplied instant (not a fresh Date) when atDate is passed', () => {+ // 2026-07-16T05:00Z = 2026-07-15 22:00 PDT. The passed instant, not "now",+ // must drive the day key so a writer's date + timestamp stay on one day.+ const instant = new Date('2026-07-16T05:00:00.000Z')+ expect(todayInTimezone('America/Los_Angeles', instant)).toBe('2026-07-15')+ expect(todayInTimezone('UTC', instant)).toBe('2026-07-16')+ })})describe('getTimezoneUpdatedAt (#2040)', () => {diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.jsindex 35960b75b9..6cf7e59335 100644--- a/server/services/meatspacePost.js+++ b/server/services/meatspacePost.js@@ -215,11 +215,14 @@ export async function getPostSession(id) {export async function submitPostSession(sessionData) {const config = await getPostConfig();const data = await loadSessions();- const now = new Date().toISOString();+ const nowDate = new Date();+ const now = nowDate.toISOString();// Stamp the session's day in the user's local timezone, so `completedToday`// and the day-keyed streak/stats math classify it by the local day the user- // actually completed it — not the server's UTC day (issue #2681).- const todayLocal = await localToday();+ // actually completed it — not the server's UTC day (issue #2681). Derive the+ // day from the SAME `nowDate` used for startedAt/completedAt so a midnight+ // boundary can't split the day key and the timestamps onto different days.+ const todayLocal = await localToday(nowDate);// Strip client-provided score/correct — plus every separated metric field// (issue #2094) — and recompute server-side. Stripping up front means thediff --git a/server/services/meatspacePostMemory.js b/server/services/meatspacePostMemory.jsindex af5d6661f3..3f071166b0 100644--- a/server/services/meatspacePostMemory.js+++ b/server/services/meatspacePostMemory.js@@ -451,14 +451,16 @@ export async function submitPractice(id, practiceData) {if (!item) return null;const { mode, chunkId, results, totalMs } = practiceData;- const now = new Date().toISOString();+ const nowDate = new Date();+ const now = nowDate.toISOString();// Day-key in the user's local timezone (issue #2681): this practice is a// training-log entry feeding the SHARED unified streak, which now reads against// the user's local `today`. A full UTC ISO here (the old `date: now`) split to// the UTC day would drop a local-evening practice from today's streak. `date`// is a day-key (every reader does `String(date).split('T')[0]`); `timestamp`- // keeps the exact instant, matching submitTrainingEntry's shape.- const todayLocal = await userLocalToday();+ // keeps the exact instant, matching submitTrainingEntry's shape. Derive the day+ // from the SAME `nowDate` so a midnight boundary can't split date and timestamp.+ const todayLocal = await userLocalToday(nowDate);// Update chunk masteryif (chunkId) {diff --git a/server/services/meatspacePostMorse.js b/server/services/meatspacePostMorse.jsindex fc7e0393dd..0c4fb87956 100644--- a/server/services/meatspacePostMorse.js+++ b/server/services/meatspacePostMorse.js@@ -25,6 +25,8 @@import { join } from 'path';import { randomUUID } from 'crypto';import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';+import { userLocalToday } from '../lib/timezone.js';+import { ymdShift } from '../lib/postStreak.js';const MEATSPACE_DIR = PATHS.meatspace;const MORSE_FILE = join(MEATSPACE_DIR, 'post-morse-progress.json');@@ -107,14 +109,21 @@ function normalizeItems(items) {export async function appendMorseRound(round) {return withMorseWriteTail(async () => {const data = await loadMorseProgress();- const now = new Date().toISOString();+ const nowDate = new Date();+ const now = nowDate.toISOString();+ // Stamp the round's day in the user's local timezone (issue #2681): a Morse+ // drill completion also writes a training-log entry (submitTrainingEntry, now+ // local), and Morse trends window on `date` — a UTC-day stamp here would date+ // the same completion differently and skew the trend window. Derive from the+ // SAME nowDate used for `timestamp` so a midnight boundary can't split them.+ const todayLocal = await userLocalToday(nowDate);const items = normalizeItems(round.items);const correctCount = items.filter((i) => i.correct).length;const accuracy = items.length > 0 ? Math.round((correctCount / items.length) * 100) : 0;const record = {id: randomUUID(),- date: now.split('T')[0],+ date: todayLocal,timestamp: now,mode: MORSE_MODES.includes(round.mode) ? round.mode : 'copy',kochLevel: typeof round.kochLevel === 'number' ? clampLevel(round.kochLevel) : (data.kochLevel ?? DEFAULT_KOCH_LEVEL),@@ -178,9 +187,9 @@ export async function getMorseProgress(days = 30) {let rounds = data.rounds;if (days > 0) {- const cutoff = new Date();- cutoff.setDate(cutoff.getDate() - days);- const cutoffStr = cutoff.toISOString().split('T')[0];+ // Window off the user's local today (DST-safe day math) so the cutoff matches+ // the local-day round dates now stamped above (issue #2681).+ const cutoffStr = ymdShift(await userLocalToday(), -days);rounds = rounds.filter((r) => (r.date || '') >= cutoffStr);}diff --git a/server/services/meatspacePostMorse.test.js b/server/services/meatspacePostMorse.test.jsindex 4643f19351..22224245c0 100644--- a/server/services/meatspacePostMorse.test.js+++ b/server/services/meatspacePostMorse.test.js@@ -7,6 +7,13 @@ vi.mock('../lib/fileUtils.js', () => ({readJSONFile: vi.fn(),}));+// appendMorseRound / getMorseProgress derive the local day via userLocalToday →+// getSettings (issue #2681). Pin to UTC so the day-key is the UTC day regardless+// of the runner's system timezone (matching the UTC-today assertions below).+vi.mock('../services/settings.js', () => ({+ getSettings: () => Promise.resolve({ timezone: 'UTC' }),+}));+import { readJSONFile, atomicWrite } from '../lib/fileUtils.js';import {appendMorseRound,diff --git a/server/services/meatspacePostTraining.js b/server/services/meatspacePostTraining.jsindex e900cd2b7c..f853751789 100644--- a/server/services/meatspacePostTraining.js+++ b/server/services/meatspacePostTraining.js@@ -31,13 +31,15 @@ async function saveTrainingLog(data) {*/export async function submitTrainingEntry(entry) {const data = await loadTrainingLog();- const now = new Date().toISOString();+ const nowDate = new Date();+ const now = nowDate.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();+ // streak. Derive the day from the SAME `nowDate` used for `timestamp` so a+ // midnight boundary can't split them onto different days.+ const todayLocal = await userLocalToday(nowDate);const record = {id: randomUUID(),