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
refactor([dedupe-hhmm-time-window-helpers]): centralize HH:MM helpers in timezone.js
Adam Eivybecd8bcb3e65
diff --git a/client/src/utils/timeWindow.js b/client/src/utils/timeWindow.jsindex 51cf11c0cc..f968c12935 100644--- a/client/src/utils/timeWindow.js+++ b/client/src/utils/timeWindow.js@@ -1,5 +1,8 @@// Time-window helpers for dashboard layout auto-activation.-// Predicate logic is mirrored on the server (`server/services/dashboardLayouts.js`).+// Predicate logic (`isInTimeWindow`) mirrors the server's `isWithinTimeWindow`+// in `server/lib/timezone.js`; the regex below mirrors that file's strict,+// zero-padded `HHMM_STRICT_RE`. Keep the two literals in sync (parity-tested+// in timeWindow.test.js and timezone.test.js).export const TIME_STRING_RE = /^([01]\d|2[0-3]):[0-5]\d$/;diff --git a/client/src/utils/timeWindow.test.js b/client/src/utils/timeWindow.test.jsindex 549ba85812..997dde73e2 100644--- a/client/src/utils/timeWindow.test.js+++ b/client/src/utils/timeWindow.test.js@@ -1,5 +1,13 @@import { describe, it, expect, beforeEach } from 'vitest';-import { isInTimeWindow, isValidTimeString, MORNING_DEFAULT_WINDOW, pickActiveLayoutId, recordManualLayoutPick } from './timeWindow.js';+import { isInTimeWindow, isValidTimeString, MORNING_DEFAULT_WINDOW, pickActiveLayoutId, recordManualLayoutPick, TIME_STRING_RE } from './timeWindow.js';++describe('TIME_STRING_RE parity', () => {+ // Must stay byte-for-byte equal to HHMM_STRICT_RE in server/lib/timezone.js+ // (and the dashboard route mock). If this fails, sync all three.+ it('mirrors the server HHMM_STRICT_RE source', () => {+ expect(TIME_STRING_RE.source).toBe('^([01]\\d|2[0-3]):[0-5]\\d$');+ });+});describe('isValidTimeString', () => {it('accepts HH:MM in 24h format', () => {diff --git a/server/lib/timezone.js b/server/lib/timezone.jsindex 3025398539..067cc69bb1 100644--- a/server/lib/timezone.js+++ b/server/lib/timezone.js@@ -125,3 +125,44 @@ export function todayInTimezone(timezone) {const parts = getLocalParts(new Date(), timezone)return `${parts.year}-${String(parts.month).padStart(2, '0')}-${String(parts.day).padStart(2, '0')}`}++// ---------------------------------------------------------------------------+// HH:MM time-window primitives+//+// Two consumers validate "HH:MM" (24h) strings with deliberately different+// strictness, so both regexes live here as the single source of truth:+// - HHMM_RE (lenient): tolerates a single-digit hour ("9:00") as well as+// the zero-padded form. Used by voice quiet-hours (routes/voice.js via+// proactiveSpeech.js), which has always accepted single-digit hours.+// - HHMM_STRICT_RE: requires a zero-padded hour ("09:00"). Used by the+// dashboard activateWindow validator (services/dashboardLayouts.js) and+// mirrored client-side in client/src/utils/timeWindow.js — keep all three+// in sync (each has a parity test against the literal pattern).+// ---------------------------------------------------------------------------+export const HHMM_RE = /^([01]?\d|2[0-3]):([0-5]\d)$/+export const HHMM_STRICT_RE = /^([01]\d|2[0-3]):[0-5]\d$/++// Parse "HH:MM" → minutes-from-midnight. Lenient (accepts single-digit hours)+// so callers can validate strictness separately at their boundary. Returns+// null for malformed input so the caller can fall through or error.+export function parseHHMM(s) {+ if (typeof s !== 'string') return null+ const m = s.match(HHMM_RE)+ if (!m) return null+ return Number(m[1]) * 60 + Number(m[2])+}++// Half-open [start, end) window-inclusion check against minutes-from-midnight.+// Handles the overnight case (start > end, e.g. 22:00 → 07:00) by wrapping.+// start === end is an empty window → never matches. Malformed bounds → false+// (caller treats as "window off"). Shared by voice quiet-hours and mirrored+// client-side for dashboard time-windowed layout auto-activation.+export function isWithinTimeWindow({ start, end, nowMinutes }) {+ const s = parseHHMM(start)+ const e = parseHHMM(end)+ if (s === null || e === null) return false+ if (s === e) return false+ if (s < e) return nowMinutes >= s && nowMinutes < e+ // Overnight wrap: in-window if at-or-after start OR before end.+ return nowMinutes >= s || nowMinutes < e+}diff --git a/server/lib/timezone.test.js b/server/lib/timezone.test.jsindex d0d646f439..a677604fac 100644--- a/server/lib/timezone.test.js+++ b/server/lib/timezone.test.js@@ -1,5 +1,14 @@import { describe, it, expect, vi } from 'vitest'-import { getLocalParts, getUtcOffsetMs, nextLocalTime, todayInTimezone } from './timezone.js'+import {+ getLocalParts,+ getUtcOffsetMs,+ nextLocalTime,+ todayInTimezone,+ HHMM_RE,+ HHMM_STRICT_RE,+ parseHHMM,+ isWithinTimeWindow,+} from './timezone.js'describe('timezone', () => {describe('getLocalParts', () => {@@ -98,6 +107,67 @@ describe('timezone', () => {})})+ describe('HH:MM regexes', () => {+ it('HHMM_RE (lenient) accepts both single- and zero-padded hours', () => {+ expect(HHMM_RE.test('9:00')).toBe(true)+ expect(HHMM_RE.test('09:00')).toBe(true)+ expect(HHMM_RE.test('23:59')).toBe(true)+ expect(HHMM_RE.test('24:00')).toBe(false)+ expect(HHMM_RE.test('12:60')).toBe(false)+ })++ it('HHMM_STRICT_RE requires a zero-padded hour', () => {+ expect(HHMM_STRICT_RE.test('09:00')).toBe(true)+ expect(HHMM_STRICT_RE.test('23:59')).toBe(true)+ expect(HHMM_STRICT_RE.test('9:00')).toBe(false)+ expect(HHMM_STRICT_RE.test('24:00')).toBe(false)+ })++ // Parity guard: the client mirror in client/src/utils/timeWindow.js and the+ // dashboard route mock both pin this exact source. Update all three together.+ it('HHMM_STRICT_RE has the documented canonical source', () => {+ expect(HHMM_STRICT_RE.source).toBe('^([01]\\d|2[0-3]):[0-5]\\d$')+ })+ })++ describe('parseHHMM', () => {+ it.each([+ ['00:00', 0],+ ['07:00', 420],+ ['22:00', 1320],+ ['23:59', 23 * 60 + 59],+ ['9:30', 9 * 60 + 30],+ ])('parses %s → %s', (s, expected) => {+ expect(parseHHMM(s)).toBe(expected)+ })++ it.each(['', '24:00', '12:60', 'abc', null, undefined, '12'])('rejects %s', (s) => {+ expect(parseHHMM(s)).toBeNull()+ })+ })++ describe('isWithinTimeWindow', () => {+ it('matches inside a same-day window (half-open)', () => {+ const win = { start: '09:00', end: '17:00' }+ expect(isWithinTimeWindow({ ...win, nowMinutes: 10 * 60 })).toBe(true)+ expect(isWithinTimeWindow({ ...win, nowMinutes: 9 * 60 })).toBe(true)+ expect(isWithinTimeWindow({ ...win, nowMinutes: 17 * 60 })).toBe(false)+ expect(isWithinTimeWindow({ ...win, nowMinutes: 8 * 60 })).toBe(false)+ })++ it('wraps overnight (start > end)', () => {+ const win = { start: '22:00', end: '07:00' }+ expect(isWithinTimeWindow({ ...win, nowMinutes: 23 * 60 })).toBe(true)+ expect(isWithinTimeWindow({ ...win, nowMinutes: 5 * 60 })).toBe(true)+ expect(isWithinTimeWindow({ ...win, nowMinutes: 14 * 60 })).toBe(false)+ })++ it('returns false for empty (start === end) or malformed bounds', () => {+ expect(isWithinTimeWindow({ start: '08:00', end: '08:00', nowMinutes: 8 * 60 })).toBe(false)+ expect(isWithinTimeWindow({ start: 'abc', end: '07:00', nowMinutes: 5 * 60 })).toBe(false)+ })+ })+describe('todayInTimezone', () => {it('returns date string in YYYY-MM-DD format', () => {const result = todayInTimezone('UTC')diff --git a/server/services/dashboardLayouts.js b/server/services/dashboardLayouts.jsindex 450742f2e6..f275240a27 100644--- a/server/services/dashboardLayouts.js+++ b/server/services/dashboardLayouts.js@@ -13,6 +13,7 @@import { join } from 'path';import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../lib/fileUtils.js';+import { HHMM_STRICT_RE } from '../lib/timezone.js';const STATE_PATH = join(PATHS.data, 'dashboard-layouts.json');@@ -195,8 +196,9 @@ export const GRID_ITEM_H_MAX = 50;// activateWindow and the local clock falls inside it, the dashboard// auto-selects that layout on a fresh visit (unless the user picked a// different one today). Stored as a literal "HH:MM" pair so a hand-edited-// JSON is human-readable.-export const TIME_STRING_RE = /^([01]\d|2[0-3]):[0-5]\d$/;+// JSON is human-readable. Sourced from the strict (zero-padded) shared regex+// in server/lib/timezone.js; mirrored client-side in client/src/utils/timeWindow.js.+export const TIME_STRING_RE = HHMM_STRICT_RE;// Sanitize a layout's activateWindow. Returns null for any malformed shape// (missing fields, non-string types, off-format strings). A null resultdiff --git a/server/services/voice/proactiveSpeech.js b/server/services/voice/proactiveSpeech.jsindex 436cb7289b..4e7ed6ef0b 100644--- a/server/services/voice/proactiveSpeech.js+++ b/server/services/voice/proactiveSpeech.js@@ -18,21 +18,13 @@import { synthesize } from './tts.js';import { getVoiceConfig } from './config.js';import { rememberTtsForAllSockets } from './echo.js';-import { getUserTimezone, getLocalParts } from '../../lib/timezone.js';+import { getUserTimezone, getLocalParts, isWithinTimeWindow } from '../../lib/timezone.js';-// 24-hour HH:MM regex shared with the route-level Zod schema in-// `routes/voice.js`. Both ends of the config write path validate the same-// shape so a passing schema is guaranteed to parse here.-export const HHMM_RE = /^([01]?\d|2[0-3]):([0-5]\d)$/;--// Parse "HH:MM" → minutes-from-midnight. Returns null for malformed input so-// the caller can decide whether to fall through (quiet hours off) or error.-export const parseHHMM = (s) => {- if (typeof s !== 'string') return null;- const m = s.match(HHMM_RE);- if (!m) return null;- return Number(m[1]) * 60 + Number(m[2]);-};+// HH:MM helpers live in server/lib/timezone.js (single source of truth shared+// with the dashboard's time-window validator). Re-exported here so the+// route-level Zod schema in `routes/voice.js` validates the same lenient+// HH:MM shape and tests can exercise the parser directly.+export { HHMM_RE, parseHHMM } from '../../lib/timezone.js';// Maximum spoken-text length for proactive lines. The /api/voice/speak Zod// schema already caps HTTP payloads at 4000 chars, but `speakProactive` is@@ -43,18 +35,11 @@ export const parseHHMM = (s) => {// needs to.export const MAX_PROACTIVE_TEXT_LEN = 4000;-// Quiet-hours window inclusion check. Handles the overnight case (start>end,-// e.g. 22:00 → 07:00) by wrapping. Same-value start/end means "the window is-// empty" — proactive speech is always allowed.-export const isWithinQuietHours = ({ start, end, nowMinutes }) => {- const s = parseHHMM(start);- const e = parseHHMM(end);- if (s === null || e === null) return false;- if (s === e) return false;- if (s < e) return nowMinutes >= s && nowMinutes < e;- // Overnight wrap: in-window if at-or-after start OR before end.- return nowMinutes >= s || nowMinutes < e;-};+// Quiet-hours inclusion is exactly the generic time-window predicate — a+// half-open [start, end) window with overnight wrap (same-value start/end =+// empty window, so proactive speech is always allowed). Kept as a domain-named+// alias so callers and tests read clearly.+export const isWithinQuietHours = isWithinTimeWindow;// Pull the user's current local minutes-from-midnight via Intl. Server runs// TZ=UTC, so a naive `new Date().getHours()` would compare quiet hoursdiff --git a/server/services/voice/proactiveSpeech.test.js b/server/services/voice/proactiveSpeech.test.jsindex 3114f7ec30..16a232836a 100644--- a/server/services/voice/proactiveSpeech.test.js+++ b/server/services/voice/proactiveSpeech.test.js@@ -11,7 +11,10 @@ vi.mock('./config.js', () => ({vi.mock('./tts.js', () => ({synthesize: vi.fn(async () => ({ wav: Buffer.alloc(64), latencyMs: 12 })),}));-vi.mock('../../lib/timezone.js', () => ({+// Keep the real HH:MM helpers (HHMM_RE/parseHHMM/isWithinTimeWindow now live+// here) and override only the timezone-lookup pair the integration path needs.+vi.mock('../../lib/timezone.js', async (importOriginal) => ({+ ...(await importOriginal()),getUserTimezone: vi.fn(async () => 'UTC'),getLocalParts: vi.fn(() => ({ hour: 14, minute: 0 })),}));