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([issue-12611]): schedule goal time blocks in user timezone with proper boundary handling
[._.]/ Adam Eivya1eac7bc91c7
diff --git a/server/services/goalCalendarScheduler.js b/server/services/goalCalendarScheduler.jsindex f25c2f11ac..58e4c72c53 100644--- a/server/services/goalCalendarScheduler.js+++ b/server/services/goalCalendarScheduler.js@@ -3,6 +3,8 @@ import { v4 as uuidv4 } from '../lib/uuid.js';import { ServerError } from '../lib/errorHandler.js';import { getAuthenticatedClient, needsScopeUpgrade, getTokens, GOOGLE_API_TIMEOUT_MS } from './googleAuth.js';import { loadJSON, mutateGoals, GOALS_FILE, DEFAULT_GOALS } from './identity/store.js';+import { getUserTimezone } from './userTimezone.js';+import { todayInTimezone } from '../lib/timezone.js';const TIME_SLOT_HOURS = {morning: 9,@@ -14,6 +16,38 @@ const DAY_MAP = {sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6};+function addDays(dateStr, days) {+ const [y, m, d] = dateStr.split('-').map(Number);+ const dt = new Date(Date.UTC(y, m - 1, d));+ if (y < 100) dt.setUTCFullYear(y);+ dt.setUTCDate(dt.getUTCDate() + days);+ const year = String(dt.getUTCFullYear()).padStart(4, '0');+ const month = String(dt.getUTCMonth() + 1).padStart(2, '0');+ const day = String(dt.getUTCDate()).padStart(2, '0');+ return `${year}-${month}-${day}`;+}++function getDayOfWeek(dateStr) {+ const [y, m, d] = dateStr.split('-').map(Number);+ const dt = new Date(Date.UTC(y, m - 1, d));+ if (y < 100) dt.setUTCFullYear(y);+ return dt.getUTCDay();+}++function toWallClockString(dateStr, hour, minute, addMinutes = 0) {+ const [y, m, d] = dateStr.split('-').map(Number);+ const dt = new Date(Date.UTC(y, m - 1, d, hour, minute));+ if (y < 100) dt.setUTCFullYear(y);+ if (addMinutes) dt.setUTCMinutes(dt.getUTCMinutes() + addMinutes);+ const year = String(dt.getUTCFullYear()).padStart(4, '0');+ const month = String(dt.getUTCMonth() + 1).padStart(2, '0');+ const day = String(dt.getUTCDate()).padStart(2, '0');+ const h = String(dt.getUTCHours()).padStart(2, '0');+ const min = String(dt.getUTCMinutes()).padStart(2, '0');+ const sec = String(dt.getUTCSeconds()).padStart(2, '0');+ return `${year}-${month}-${day}T${h}:${min}:${sec}`;+}+function resolveTimeSlotHour(timeSlot) {if (TIME_SLOT_HOURS[timeSlot] !== undefined) return TIME_SLOT_HOURS[timeSlot];return parseInt(timeSlot.split(':')[0], 10);@@ -78,40 +112,38 @@ export async function scheduleTimeBlocks(goalId) {const preferredDayNums = new Set(preferredDays.map(d => DAY_MAP[d]));const hour = resolveTimeSlotHour(timeSlot);const minute = resolveTimeSlotMinute(timeSlot);- const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;-- const today = new Date();- today.setHours(0, 0, 0, 0);+ const tz = await getUserTimezone();+ const today = todayInTimezone(tz);// Collect all events to createconst eventDefs = [];+ let prevRangeStart = today;for (let i = 0; i < milestones.length; i++) {const ms = milestones[i];+ const rangeStart = i === 0+ ? today+ : (milestones[i - 1]?.targetDate ? addDays(milestones[i - 1].targetDate, 1) : prevRangeStart);+ prevRangeStart = rangeStart;+if (ms.completedAt) continue;- const rangeStart = i === 0 ? today : new Date(milestones[i - 1].targetDate + 'T00:00:00');- const rangeEnd = ms.targetDate ? new Date(ms.targetDate + 'T00:00:00') : new Date(goal.targetDate + 'T00:00:00');+ const rangeEnd = ms.targetDate || goal.targetDate;- const cursor = new Date(Math.max(rangeStart.getTime(), today.getTime()));+ let cursor = rangeStart < today ? today : rangeStart;while (cursor <= rangeEnd) {- if (preferredDayNums.has(cursor.getDay())) {- const startTime = new Date(cursor);- startTime.setHours(hour, minute, 0, 0);- const endTime = new Date(startTime);- endTime.setMinutes(endTime.getMinutes() + sessionDurationMinutes);-+ if (preferredDayNums.has(getDayOfWeek(cursor))) {eventDefs.push({milestoneId: ms.id,- date: cursor.toISOString().slice(0, 10),+ date: cursor,requestBody: {summary: `${goal.title} - ${ms.title}`,description: `${ms.description || ''}\n\nGoal: ${goal.title}`.trim(),- start: { dateTime: startTime.toISOString(), timeZone: tz },- end: { dateTime: endTime.toISOString(), timeZone: tz }+ start: { dateTime: toWallClockString(cursor, hour, minute), timeZone: tz },+ end: { dateTime: toWallClockString(cursor, hour, minute, sessionDurationMinutes), timeZone: tz }}});}- cursor.setDate(cursor.getDate() + 1);+ cursor = addDays(cursor, 1);}}diff --git a/server/services/goalCalendarScheduler.test.js b/server/services/goalCalendarScheduler.test.jsindex d0e89f0827..ddc29a9dcb 100644--- a/server/services/goalCalendarScheduler.test.js+++ b/server/services/goalCalendarScheduler.test.js@@ -56,9 +56,14 @@ vi.mock('./googleAuth.js', () => ({getTokens: vi.fn(async () => ({ access_token: 'fake' })),}));+vi.mock('./userTimezone.js', () => ({+ getUserTimezone: vi.fn(async () => 'UTC'),+}));+import * as goalStore from './identity/store.js';import { scheduleTimeBlocks, removeScheduledEvents, rescheduleTimeBlocks } from './goalCalendarScheduler.js';import { addProgressEntry, deleteGoal } from './identity/goals.js';+import { getUserTimezone } from './userTimezone.js';afterAll(() => { if (tempRoot) rmSync(tempRoot, { recursive: true, force: true }); });@@ -91,6 +96,7 @@ describe('goalCalendarScheduler write serialization (#8755)', () => {insertAttempts = 0;rejectInsert = undefined;deleteEvent.mockReset().mockResolvedValue({});+ getUserTimezone.mockResolvedValue('UTC');vi.useFakeTimers({ toFake: ['Date'] });vi.setSystemTime(new Date('2026-12-20T12:00:00Z'));});@@ -313,4 +319,128 @@ describe('goalCalendarScheduler write serialization (#8755)', () => {const written = JSON.parse(readFileSync(goalsFile(), 'utf8'));expect(written.goals[0].scheduledEvents).toEqual([]);});++ describe('user timezone and milestone boundary scheduling (#12611)', () => {+ it('schedules events in the user timezone with local wall-clock times and correct local weekdays under TZ=UTC', async () => {+ getUserTimezone.mockResolvedValue('America/Los_Angeles');+ // 2026-10-21T01:00:00Z is 2026-10-20T18:00:00 in America/Los_Angeles (Tuesday evening).+ // Under TZ=UTC, server Date is Wednesday Oct 21, but in LA it is Tuesday Oct 20.+ vi.setSystemTime(new Date('2026-10-21T01:00:00Z'));++ const goal = {+ id: 'g-la',+ title: 'Morning Routine',+ status: 'active',+ createdAt: '2026-10-20T00:00:00.000Z',+ targetDate: '2026-10-28',+ milestones: [+ { id: 'ms1', title: 'Phase 1', order: 0, targetDate: '2026-10-28', completedAt: null }+ ],+ timeBlockConfig: {+ preferredDays: ['mon', 'wed'],+ timeSlot: 'morning',+ sessionDurationMinutes: 30,+ },+ scheduledEvents: [],+ };+ writeFileSync(goalsFile(), JSON.stringify({ goals: [goal] }));++ const result = await scheduleTimeBlocks('g-la');+ expect(result.count).toBe(3);++ // Local LA days starting from Tuesday Oct 20: Wed Oct 21, Mon Oct 26, Wed Oct 28+ const firstEvent = insertedEvents[0].requestBody;+ expect(firstEvent.start).toEqual({+ dateTime: '2026-10-21T09:00:00',+ timeZone: 'America/Los_Angeles',+ });+ expect(firstEvent.end).toEqual({+ dateTime: '2026-10-21T09:30:00',+ timeZone: 'America/Los_Angeles',+ });++ const dates = insertedEvents.map(e => e.requestBody.start.dateTime.slice(0, 10));+ expect(dates).toEqual(['2026-10-21', '2026-10-26', '2026-10-28']);++ for (const event of insertedEvents) {+ expect(event.requestBody.start.timeZone).toBe('America/Los_Angeles');+ expect(event.requestBody.start.dateTime).toMatch(/T09:00:00$/);+ expect(event.requestBody.start.dateTime).not.toContain('Z');+ expect(event.requestBody.end.timeZone).toBe('America/Los_Angeles');+ expect(event.requestBody.end.dateTime).toMatch(/T09:30:00$/);+ expect(event.requestBody.end.dateTime).not.toContain('Z');+ }+ });++ it('allocates exactly one session on a preferred boundary day shared by consecutive milestones', async () => {+ getUserTimezone.mockResolvedValue('America/Los_Angeles');+ // 2026-10-19 is Monday+ vi.setSystemTime(new Date('2026-10-19T12:00:00Z'));++ const goal = {+ id: 'g-boundary',+ title: 'Milestone Goal',+ status: 'active',+ createdAt: '2026-10-19T00:00:00.000Z',+ targetDate: '2026-10-28',+ milestones: [+ { id: 'ms1', title: 'Phase 1', order: 0, targetDate: '2026-10-21', completedAt: null }, // Wednesday+ { id: 'ms2', title: 'Phase 2', order: 1, targetDate: '2026-10-28', completedAt: null }, // Wednesday+ ],+ timeBlockConfig: {+ preferredDays: ['wed'],+ timeSlot: 'morning',+ sessionDurationMinutes: 60,+ },+ scheduledEvents: [],+ };+ writeFileSync(goalsFile(), JSON.stringify({ goals: [goal] }));++ const result = await scheduleTimeBlocks('g-boundary');+ expect(result.count).toBe(2);++ const boundaryEvents = insertedEvents.filter(e => e.requestBody.start.dateTime.startsWith('2026-10-21'));+ expect(boundaryEvents).toHaveLength(1);+ expect(boundaryEvents[0].requestBody.summary).toBe('Milestone Goal - Phase 1');++ const phase2Events = insertedEvents.filter(e => e.requestBody.summary.includes('Phase 2'));+ expect(phase2Events).toHaveLength(1);+ expect(phase2Events[0].requestBody.start.dateTime).toBe('2026-10-28T09:00:00');+ });++ it('continues scheduling sessions for a milestone following one with targetDate: null', async () => {+ getUserTimezone.mockResolvedValue('America/Los_Angeles');+ // 2026-10-19 is Monday+ vi.setSystemTime(new Date('2026-10-19T12:00:00Z'));++ const goal = {+ id: 'g-undated',+ title: 'Undated Milestone Goal',+ status: 'active',+ createdAt: '2026-10-19T00:00:00.000Z',+ targetDate: '2026-10-30',+ milestones: [+ { id: 'ms1', title: 'Phase 1', order: 0, targetDate: '2026-10-21', completedAt: null }, // Wednesday+ { id: 'ms2', title: 'Phase 2 (undated)', order: 1, targetDate: null, completedAt: null },+ { id: 'ms3', title: 'Phase 3', order: 2, targetDate: '2026-10-30', completedAt: null }, // Friday+ ],+ timeBlockConfig: {+ preferredDays: ['mon', 'wed', 'fri'],+ timeSlot: 'morning',+ sessionDurationMinutes: 30,+ },+ scheduledEvents: [],+ };+ writeFileSync(goalsFile(), JSON.stringify({ goals: [goal] }));++ const result = await scheduleTimeBlocks('g-undated');+ expect(result.count).toBeGreaterThan(0);++ const phase2Events = insertedEvents.filter(e => e.requestBody.summary.includes('Phase 2 (undated)'));+ expect(phase2Events.length).toBeGreaterThan(0);++ const phase3Events = insertedEvents.filter(e => e.requestBody.summary.includes('Phase 3'));+ expect(phase3Events.length).toBeGreaterThan(0);+ });+ });});