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 r2): complete tz threading for memory practice + windows

[._.]/ Adam Eivyb4f8a5bd64dd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 42bbbedb83..9bbff29241 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: `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-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. 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
index deeebd0eb5..2f1fb71def 100644
--- a/scripts/migrations/192-post-dates-to-local-timezone.js
+++ b/scripts/migrations/192-post-dates-to-local-timezone.js
@@ -74,11 +74,15 @@ function localDayFor(instant, timezone) {
}).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.
+// Pick the UTC instant that best represents the session's ORIGINAL day. Prefer
+// `startedAt`: an idempotent re-submit (submitPostSession) deliberately preserves
+// the original `startedAt` (and `date`) but OVERWRITES `completedAt` — so a retry
+// that crosses local midnight would, via `completedAt`, redate the session to the
+// retry day and undo that invariant. `startedAt` keeps it on the day it began.
+// A full-ISO `date` (contains 'T') is only a fallback for pre-timestamp 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?.completedAt === 'string' && s.completedAt.includes('T')) return s.completedAt;
if (typeof s?.date === 'string' && s.date.includes('T')) return s.date;
return null;
}
diff --git a/scripts/migrations/192-post-dates-to-local-timezone.test.js b/scripts/migrations/192-post-dates-to-local-timezone.test.js
index f0a21e6210..e39d38d11b 100644
--- a/scripts/migrations/192-post-dates-to-local-timezone.test.js
+++ b/scripts/migrations/192-post-dates-to-local-timezone.test.js
@@ -76,6 +76,22 @@ describe('migration 192 — normalize POST dates to the user local timezone', ()
expect(days).toEqual(['2026-07-15', '2026-07-16']);
});
+ it('prefers startedAt over completedAt so a cross-midnight retry keeps its original day', async () => {
+ // An idempotent re-submit preserves the original startedAt (local July 15)
+ // but overwrites completedAt to the retry instant (local July 16). The
+ // migration must key off startedAt so the session stays on July 15.
+ writeJson(settingsPath, { timezone: 'America/Los_Angeles' });
+ writeJson(sessionsPath, {
+ sessions: [{
+ id: 's1', date: '2026-07-16',
+ startedAt: '2026-07-16T04:00:00.000Z', // 2026-07-15 21:00 PDT
+ completedAt: '2026-07-17T05:00:00.000Z', // 2026-07-16 22:00 PDT (retry)
+ }],
+ });
+ await migration.up({ rootDir });
+ expect(readJson(sessionsPath).sessions[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/services/meatspacePostMemory.js b/server/services/meatspacePostMemory.js
index 8db52186df..af5d6661f3 100644
--- a/server/services/meatspacePostMemory.js
+++ b/server/services/meatspacePostMemory.js
@@ -9,6 +9,7 @@ import { join } from 'path';
import { randomUUID } from 'crypto';
import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';
import { shuffle } from '../lib/arrayUtils.js';
+import { userLocalToday } from '../lib/timezone.js';
const MEATSPACE_DIR = PATHS.meatspace;
const MEMORY_ITEMS_FILE = join(MEATSPACE_DIR, 'post-memory-items.json');
@@ -451,6 +452,13 @@ export async function submitPractice(id, practiceData) {
const { mode, chunkId, results, totalMs } = practiceData;
const now = new Date().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();
// Update chunk mastery
if (chunkId) {
@@ -507,7 +515,8 @@ export async function submitPractice(id, practiceData) {
correct: results.filter(r => r.correct).length,
total: results.length,
totalMs: totalMs || 0,
- date: now,
+ date: todayLocal,
+ timestamp: now,
});
await saveTrainingLog(log);
diff --git a/server/services/meatspacePostMemory.test.js b/server/services/meatspacePostMemory.test.js
index b430f47dc0..d1d46eabf3 100644
--- a/server/services/meatspacePostMemory.test.js
+++ b/server/services/meatspacePostMemory.test.js
@@ -9,6 +9,14 @@ tryReadFile: vi.fn().mockResolvedValue(null),
readJSONFile: vi.fn().mockResolvedValue({ items: [] }),
}));
+// submitPractice stamps the training-log entry's day via userLocalToday →
+// getSettings (issue #2681). Pin it to UTC so the day-key is deterministic
+// regardless of the runner's own system timezone.
+const memorySettingsState = vi.hoisted(() => ({ current: { timezone: 'UTC' } }));
+vi.mock('../services/settings.js', () => ({
+ getSettings: () => Promise.resolve(memorySettingsState.current),
+}));
+
import { readJSONFile, atomicWrite } from '../lib/fileUtils.js';
import {
getMemoryItems,
@@ -422,6 +430,29 @@ describe('submitPractice', () => {
expect(result.mastery.chunks['verse-1'].attempts).toBe(3);
expect(result.mastery.chunks['verse-1'].lastPracticed).toBeTruthy();
});
+
+ it('stamps the training-log entry date in the user local timezone (issue #2681)', async () => {
+ // 2026-07-16T05:00Z = 2026-07-15 22:00 PDT — UTC day July 16, LA day July 15.
+ // The logged practice must key off the local day so it counts toward today's
+ // unified streak, with the exact instant preserved in `timestamp`.
+ memorySettingsState.current = { timezone: 'America/Los_Angeles' };
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-07-16T05:00:00.000Z'));
+ try {
+ await submitPractice('elements-song', {
+ mode: 'element-flash', chunkId: null,
+ results: [{ correct: true, element: 'H' }], totalMs: 1000,
+ });
+ const trainingWrite = atomicWrite.mock.calls.find(([p]) => String(p).includes('post-training-log'));
+ expect(trainingWrite).toBeTruthy();
+ const entry = trainingWrite[1].entries.at(-1);
+ expect(entry.date).toBe('2026-07-15');
+ expect(entry.timestamp).toBe('2026-07-16T05:00:00.000Z');
+ } finally {
+ vi.useRealTimers();
+ memorySettingsState.current = { timezone: 'UTC' };
+ }
+ });
});
describe('advanceScheduleFromSession', () => {
diff --git a/server/services/meatspacePostTraining.js b/server/services/meatspacePostTraining.js
index 7837173998..e900cd2b7c 100644
--- a/server/services/meatspacePostTraining.js
+++ b/server/services/meatspacePostTraining.js
@@ -9,6 +9,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 { ymdShift } from '../lib/postStreak.js';
import { getUnifiedActivityStreak } from './meatspacePost.js';
const MEATSPACE_DIR = PATHS.meatspace;
@@ -77,9 +78,10 @@ export async function getTrainingStats(days = 30) {
let entries = allEntries;
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 strings the training/practice writers now stamp (issue #2681);
+ // a UTC-day cutoff would clip the oldest local day or admit an extra one.
+ const cutoffStr = ymdShift(await userLocalToday(), -days);
entries = allEntries.filter(e => String(e.date || '').split('T')[0] >= cutoffStr);
}
diff --git a/server/services/meatspacePostTraining.test.js b/server/services/meatspacePostTraining.test.js
index 55738c4b98..2c91709ff8 100644
--- a/server/services/meatspacePostTraining.test.js
+++ b/server/services/meatspacePostTraining.test.js
@@ -11,11 +11,13 @@ tryReadFile: vi.fn().mockResolvedValue(null),
readJSONFile: vi.fn().mockResolvedValue({ entries: [] }),
}));
-// 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.
+// submitTrainingEntry + getUnifiedActivityStreak + getTrainingStats (via
+// meatspacePost.js) derive the local day through getUserTimezone → getSettings
+// (issue #2681). Default-pin to UTC so the day boundary is the UTC day regardless
+// of the runner's own system timezone; tz-specific tests set settingsState.current.
+const settingsState = vi.hoisted(() => ({ current: { timezone: 'UTC' } }));
vi.mock('../services/settings.js', () => ({
- getSettings: () => Promise.resolve({ timezone: 'UTC' }),
+ getSettings: () => Promise.resolve(settingsState.current),
}));
import { readJSONFile, atomicWrite } from '../lib/fileUtils.js';
@@ -188,6 +190,30 @@ describe('getTrainingStats', () => {
const stats = await getTrainingStats(7);
expect(stats.totalEntries).toBe(1);
});
+
+ it('derives the window cutoff from the user local day, not the server UTC day (issue #2681)', async () => {
+ // Freeze at 2026-07-16T05:00Z = 2026-07-15 22:00 PDT (UTC day July 16, LA day
+ // July 15) and configure LA. A 7-day window ends at local July 15, so its
+ // cutoff is 2026-07-08; an entry dated 2026-07-08 (local) is the oldest that
+ // must be INCLUDED. Under the old UTC-day cutoff (today=July 16 → cutoff
+ // July 09) that entry would be wrongly excluded.
+ settingsState.current = { timezone: 'America/Los_Angeles' };
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-07-16T05:00:00.000Z'));
+ try {
+ readJSONFile.mockResolvedValue({
+ entries: [
+ { date: '2026-07-08', module: 'mental-math', drillType: 'powers', questionCount: 5, correctCount: 5, totalMs: 3000 },
+ { date: '2026-07-07', module: 'mental-math', drillType: 'powers', questionCount: 5, correctCount: 4, totalMs: 3000 },
+ ],
+ });
+ const stats = await getTrainingStats(7);
+ expect(stats.totalEntries).toBe(1); // only 2026-07-08 falls inside the local window
+ } finally {
+ vi.useRealTimers();
+ settingsState.current = { timezone: 'UTC' };
+ }
+ });
});
describe('getTrainingEntries', () => {