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

refactor: share the local-day window helper and reuse client formatters

[._.]/ Adam Eivyfa6d6e3fc9d9
diff --git a/client/src/components/dashboard/builtins/TodayAgendaWidget.jsx b/client/src/components/dashboard/builtins/TodayAgendaWidget.jsx
index 538f017e1c..daac3e2d01 100644
--- a/client/src/components/dashboard/builtins/TodayAgendaWidget.jsx
+++ b/client/src/components/dashboard/builtins/TodayAgendaWidget.jsx
@@ -1,33 +1,29 @@
import { Link } from 'react-router';
import { CalendarDays, ArrowRight } from 'lucide-react';
+import { useTimeTick } from '../../../hooks/useTimeTick';
+import { formatTimeOfDay } from '../../../utils/formatters';
// Glanceable "what's left today" agenda. Reads the shared `calendarAgenda`
// slice of dashboardState (populated from GET /api/calendar/agenda — the
// server owns the timezone-correct day window, so this never re-derives it)
// and deep-links into Calendar → Agenda. Gated off until the user has a
// calendar account connected.
-
-const timeLabel = (iso) => {
- const d = new Date(iso);
- if (Number.isNaN(d.getTime())) return null;
- return d.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
-};
-
export default function TodayAgendaWidget({ dashboardState }) {
+ // Minute tick keeps the past-event dimming and remaining count honest as
+ // the day advances between dashboard data refreshes.
+ const now = useTimeTick(60000);
const agenda = dashboardState?.calendarAgenda;
if (!agenda) return null;
- const now = Date.now();
const events = Array.isArray(agenda.events) ? agenda.events : [];
// An event is "done" once it has ended (all-day events never dim).
- const isPast = (e) => {
- if (e.isAllDay) return false;
- const end = new Date(e.endTime || e.startTime).getTime();
- return Number.isFinite(end) && end < now;
- };
- const nextEvent = events.find((e) => !e.isAllDay && !isPast(e));
- const remaining = events.filter((e) => !isPast(e)).length;
- const overflow = (agenda.total ?? events.length) - events.length;
+ const rows = events.map((event) => {
+ const end = new Date(event.endTime || event.startTime).getTime();
+ return { event, past: !event.isAllDay && Number.isFinite(end) && end < now };
+ });
+ const nextEvent = rows.find((r) => !r.event.isAllDay && !r.past)?.event;
+ const remaining = rows.filter((r) => !r.past).length;
+ const total = agenda.total ?? events.length;
return (
<Link
@@ -47,34 +43,30 @@ export default function TodayAgendaWidget({ dashboardState }) {
) : (
<>
<div className="text-xs text-gray-500 mb-2">
- {remaining} of {agenda.total ?? events.length} event{(agenda.total ?? events.length) !== 1 ? 's' : ''} remaining
+ {remaining} of {total} event{total !== 1 ? 's' : ''} remaining
</div>
<ul className="space-y-1">
- {events.map((e) => {
- const past = isPast(e);
- const isNext = nextEvent && e === nextEvent;
- return (
- <li
- key={`${e.accountId}:${e.id}`}
- className={`flex items-center gap-2 text-xs ${past ? 'opacity-50' : ''}`}
+ {rows.map(({ event, past }) => (
+ <li
+ key={`${event.accountId}:${event.id}`}
+ className={`flex items-center gap-2 text-xs ${past ? 'opacity-50' : ''}`}
+ >
+ <span
+ className={`shrink-0 w-16 tabular-nums ${event === nextEvent ? 'text-port-accent font-semibold' : 'text-gray-500'}`}
+ >
+ {event.isAllDay ? 'All day' : formatTimeOfDay(event.startTime) || 'TBD'}
+ </span>
+ <span
+ className={`flex-1 truncate ${past ? 'line-through text-gray-500' : 'text-gray-300'}`}
+ title={event.location ? `${event.title} — ${event.location}` : event.title}
>
- <span
- className={`shrink-0 w-16 tabular-nums ${isNext ? 'text-port-accent font-semibold' : 'text-gray-500'}`}
- >
- {e.isAllDay ? 'All day' : timeLabel(e.startTime) || 'TBD'}
- </span>
- <span
- className={`flex-1 truncate ${past ? 'line-through text-gray-500' : 'text-gray-300'}`}
- title={e.location ? `${e.title} — ${e.location}` : e.title}
- >
- {e.title}
- </span>
- </li>
- );
- })}
+ {event.title}
+ </span>
+ </li>
+ ))}
</ul>
- {overflow > 0 && (
- <div className="text-xs text-gray-500 mt-2">+{overflow} more</div>
+ {total > events.length && (
+ <div className="text-xs text-gray-500 mt-2">+{total - events.length} more</div>
)}
</>
)}
diff --git a/scripts/migrations/327-seed-today-agenda-widget.js b/scripts/migrations/327-seed-today-agenda-widget.js
index 21c57717b4..21c2fccb0c 100644
--- a/scripts/migrations/327-seed-today-agenda-widget.js
+++ b/scripts/migrations/327-seed-today-agenda-widget.js
@@ -22,11 +22,8 @@ function applyToLayout(layout) {
// Append at the end of the packing sequence — the widget is gated, so a
// trailing cell that gates off leaves only harmless trailing space.
const grid = Array.isArray(layout.grid) ? layout.grid : [];
- const nextOrder = grid.reduce(
- (max, item) => (Number.isFinite(item?.order) && item.order >= max ? item.order + 1 : max),
- grid.length,
- );
- layout.grid = [...grid, { id: WIDGET_ID, x: 0, w: 4, order: nextOrder, h: 4 }];
+ const maxOrder = grid.reduce((max, item) => Math.max(max, Number.isFinite(item?.order) ? item.order : -1), -1);
+ layout.grid = [...grid, { id: WIDGET_ID, x: 0, w: 4, order: maxOrder + 1, h: 4 }];
}
return true;
}
diff --git a/server/lib/timezone.js b/server/lib/timezone.js
index 817855783a..0fc5e0ac4d 100644
--- a/server/lib/timezone.js
+++ b/server/lib/timezone.js
@@ -129,6 +129,25 @@ export function anchorLocalMidnightUtc(dayStr, tz) {
return naiveUtc - refinedOffset
}
+/**
+ * The user's current local calendar day expressed as UTC ISO bounds — the
+ * shared "today's events" query window (calendar agenda route, voice
+ * calendar_today tool). `startDate` is local midnight; `endDate` is
+ * 23:59:59.999 later.
+ * @param {string} timezone - IANA timezone string
+ * @param {Date} [atDate] - instant to key (defaults to now)
+ * @returns {{ date: string, startDate: string, endDate: string }}
+ */
+export function localDayWindowUtc(timezone, atDate = new Date()) {
+ const date = todayInTimezone(timezone, atDate)
+ const startMs = anchorLocalMidnightUtc(date, timezone)
+ return {
+ date,
+ startDate: new Date(startMs).toISOString(),
+ endDate: new Date(startMs + 86399999).toISOString(),
+ }
+}
+
// ---------------------------------------------------------------------------
// HH:MM time-window primitives
//
diff --git a/server/lib/timezone.test.js b/server/lib/timezone.test.js
index 617b412051..202381b4a1 100644
--- a/server/lib/timezone.test.js
+++ b/server/lib/timezone.test.js
@@ -7,7 +7,7 @@ vi.mock('../services/settings.js', () => ({
}))
import { getSettings } from '../services/settings.js'
-import { getLocalParts, getUtcOffsetMs, nextLocalTime, todayInTimezone, anchorLocalMidnightUtc, HHMM_RE, HHMM_STRICT_RE, parseHHMM, isWithinTimeWindow } from './timezone.js'
+import { getLocalParts, getUtcOffsetMs, nextLocalTime, todayInTimezone, anchorLocalMidnightUtc, localDayWindowUtc, HHMM_RE, HHMM_STRICT_RE, parseHHMM, isWithinTimeWindow } from './timezone.js'
import { getTimezoneUpdatedAt } from '../services/userTimezone.js'
describe('timezone', () => {
@@ -229,6 +229,17 @@ describe('timezone', () => {
})
})
+ describe('localDayWindowUtc', () => {
+ it('bounds the current local day as UTC ISO strings', () => {
+ // 2026-04-17T03:00Z is still 2026-04-16 evening in Los Angeles.
+ const at = new Date('2026-04-17T03:00:00Z')
+ const { date, startDate, endDate } = localDayWindowUtc('America/Los_Angeles', at)
+ expect(date).toBe('2026-04-16')
+ expect(startDate).toBe('2026-04-16T07:00:00.000Z')
+ expect(endDate).toBe('2026-04-17T06:59:59.999Z')
+ })
+ })
+
describe('getTimezoneUpdatedAt (#2040)', () => {
it('returns the stamped numeric timestamp when set', async () => {
getSettings.mockResolvedValue({ timezone: 'UTC', timezoneUpdatedAt: 1700000000000 })
diff --git a/server/routes/calendar.js b/server/routes/calendar.js
index 8ef834bd61..eee4696a59 100644
--- a/server/routes/calendar.js
+++ b/server/routes/calendar.js
@@ -12,7 +12,7 @@ import * as calendarGoogleApiSync from '../services/calendarGoogleApiSync.js';
import * as googleOAuthAutoConfig from '../services/googleOAuthAutoConfig.js';
import { getToken, getTokenStatus, clearTokenCache } from '../services/messageTokenExtractor.js';
import { getUserTimezone } from '../services/userTimezone.js';
-import { anchorLocalMidnightUtc, todayInTimezone } from '../lib/timezone.js';
+import { localDayWindowUtc } from '../lib/timezone.js';
const router = express.Router();
@@ -139,25 +139,19 @@ router.get('/sync/:accountId/status', asyncHandler(async (req, res) => {
// === Event Routes ===
-// Today's agenda in the user's timezone — the dashboard widget's read. Bounds
-// mirror the voice calendar_today tool: the user's LOCAL day expressed in UTC
-// (event startTimes carry an offset/Z and the server runs TZ=UTC), anchored via
-// anchorLocalMidnightUtc so DST-transition days keep the right window.
+// Today's agenda in the user's timezone — the dashboard widget's read. The
+// day window comes from localDayWindowUtc (shared with the voice
+// calendar_today tool) so DST-transition days keep the right bounds.
router.get('/agenda', asyncHandler(async (req, res) => {
- const { limit: parsedLimit } = parsePagination(req.query, { defaultLimit: 8, maxLimit: 20 });
+ const { limit } = parsePagination(req.query, { defaultLimit: 8, maxLimit: 20 });
const accounts = await calendarAccounts.listAccounts();
const accountCount = accounts.filter((a) => a.enabled !== false).length;
if (accountCount === 0) {
return res.json({ date: null, timezone: null, accountCount: 0, events: [], total: 0 });
}
const timezone = await getUserTimezone();
- const date = todayInTimezone(timezone);
- const dayStartUtc = anchorLocalMidnightUtc(date, timezone);
- const { events = [], total = 0 } = await calendarSync.getEvents({
- startDate: new Date(dayStartUtc).toISOString(),
- endDate: new Date(dayStartUtc + 86399999).toISOString(),
- limit: parsedLimit
- });
+ const { date, startDate, endDate } = localDayWindowUtc(timezone);
+ const { events = [], total = 0 } = await calendarSync.getEvents({ startDate, endDate, limit });
res.json({
date,
timezone,
diff --git a/server/services/voice/tools.test.js b/server/services/voice/tools.test.js
index 035066f115..3fcff6c1cc 100644
--- a/server/services/voice/tools.test.js
+++ b/server/services/voice/tools.test.js
@@ -54,9 +54,12 @@ vi.mock('../../lib/timezone.js', () => ({
todayInTimezone: vi.fn(() => '2026-04-17'),
getLocalParts: vi.fn(() => ({ year: 2026, month: 4, day: 17 })),
getUtcOffsetMs: vi.fn(() => -7 * 3600 * 1000),
- // Pinned PDT midnight for the pinned day; the real DST math is covered in
- // lib/timezone.test.js.
- anchorLocalMidnightUtc: vi.fn((dayStr) => Date.parse(`${dayStr}T07:00:00Z`)),
+ // Pinned PDT day window; the real DST math is covered in lib/timezone.test.js.
+ localDayWindowUtc: vi.fn(() => ({
+ date: '2026-04-17',
+ startDate: '2026-04-17T07:00:00.000Z',
+ endDate: '2026-04-18T06:59:59.999Z',
+ })),
}));
vi.mock('../userTimezone.js', () => ({
getUserTimezone: vi.fn(async () => 'America/Los_Angeles'),
diff --git a/server/services/voice/tools/ambient.js b/server/services/voice/tools/ambient.js
index 1af8926081..f16c8936b7 100644
--- a/server/services/voice/tools/ambient.js
+++ b/server/services/voice/tools/ambient.js
@@ -5,7 +5,7 @@
import { getEvents as getCalendarEvents } from '../../calendarSync.js';
import { fetchWithTimeout } from '../../../lib/fetchWithTimeout.js';
-import { anchorLocalMidnightUtc, todayInTimezone, getLocalParts } from '../../../lib/timezone.js';
+import { localDayWindowUtc, getLocalParts } from '../../../lib/timezone.js';
import { getUserTimezone } from '../../userTimezone.js';
import { getSettings } from '../../settings.js';
import { clampLimit } from './shared.js';
@@ -97,19 +97,9 @@ export const AMBIENT_TOOLS = [
execute: async ({ limit = 10 } = {}) => {
const max = clampLimit(limit, 10, 20);
const tz = await getUserTimezone();
- const today = todayInTimezone(tz); // YYYY-MM-DD in the user's TZ
- // The server runs TZ=UTC and event startTimes carry an offset/Z, so the
- // [startDate, endDate] bounds must be the user's LOCAL day expressed in
- // UTC — otherwise a late-evening PT event lands on the next UTC day and
- // gets dropped. Anchor midnight-local by subtracting the TZ offset, but
- // evaluate that offset at the TARGET day's midnight (not at `now`): on a
- // DST-transition day the offset at `now` can differ from the offset at
- // midnight by an hour, shifting the window and dropping/duplicating
- // boundary events. Two passes converge (the first guess lands within
- // ~14h of local midnight; the second re-evaluates at that instant).
- const localMidnightUtc = anchorLocalMidnightUtc(today, tz);
- const startDate = new Date(localMidnightUtc).toISOString();
- const endDate = new Date(localMidnightUtc + 86399999).toISOString();
+ // The user's LOCAL day expressed as UTC bounds — the server runs TZ=UTC,
+ // so a naive window would drop late-evening events; see localDayWindowUtc.
+ const { date: today, startDate, endDate } = localDayWindowUtc(tz);
const { events = [] } = await getCalendarEvents({ startDate, endDate, limit: max });
const items = events.map((e) => ({
title: e.title,