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
feat(today-agenda-dashboard-widget): add Today's Agenda dashboard widget
[._.]/ Adam Eivy270bf725e8df
diff --git a/PLAN.md b/PLAN.mdindex bafecebacc..5dbe3b0e56 100644--- a/PLAN.md+++ b/PLAN.md@@ -1,3 +1,3 @@# PLAN-+- [x] [today-agenda-dashboard-widget] Today's Agenda dashboard widget — glanceable list of today's remaining calendar events (new `GET /api/calendar/agenda` with a timezone-correct day window, gated on a connected calendar account, seeded into the Everything and Morning Review layouts)diff --git a/client/src/components/dashboard/builtins/TodayAgendaWidget.jsx b/client/src/components/dashboard/builtins/TodayAgendaWidget.jsxnew file mode 100644index 0000000000..538f017e1c--- /dev/null+++ b/client/src/components/dashboard/builtins/TodayAgendaWidget.jsx@@ -0,0 +1,83 @@+import { Link } from 'react-router';+import { CalendarDays, ArrowRight } from 'lucide-react';++// 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 }) {+ 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;++ return (+ <Link+ to="/calendar/agenda"+ className="bg-port-card border border-port-border rounded-xl p-4 h-full block hover:border-gray-600 transition-colors"+ >+ <div className="flex items-center gap-2 mb-3">+ <CalendarDays size={16} className="text-gray-500" />+ <h3 className="text-sm font-semibold text-white">Today's Agenda</h3>+ <span className="ml-auto flex items-center gap-1 text-xs text-port-accent">+ Open <ArrowRight size={12} />+ </span>+ </div>++ {events.length === 0 ? (+ <div className="text-xs text-gray-500">Nothing on the calendar today 🎉</div>+ ) : (+ <>+ <div className="text-xs text-gray-500 mb-2">+ {remaining} of {agenda.total ?? events.length} event{(agenda.total ?? events.length) !== 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' : ''}`}+ >+ <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>+ );+ })}+ </ul>+ {overflow > 0 && (+ <div className="text-xs text-gray-500 mt-2">+{overflow} more</div>+ )}+ </>+ )}+ </Link>+ );+}diff --git a/client/src/components/dashboard/builtins/TodayAgendaWidget.test.jsx b/client/src/components/dashboard/builtins/TodayAgendaWidget.test.jsxnew file mode 100644index 0000000000..4ec30dcd82--- /dev/null+++ b/client/src/components/dashboard/builtins/TodayAgendaWidget.test.jsx@@ -0,0 +1,56 @@+import { describe, it, expect } from 'vitest';+import { render, screen } from '@testing-library/react';+import { MemoryRouter } from 'react-router';+import TodayAgendaWidget from './TodayAgendaWidget';++const renderWidget = (calendarAgenda) =>+ render(+ <MemoryRouter>+ <TodayAgendaWidget dashboardState={{ calendarAgenda }} />+ </MemoryRouter>+ );++const iso = (offsetMs) => new Date(Date.now() + offsetMs).toISOString();++describe('TodayAgendaWidget', () => {+ it('renders nothing when the agenda is absent (fetch failed / no data)', () => {+ const { container } = renderWidget(null);+ expect(container.firstChild).toBeNull();+ });++ it('shows the clear-day state and deep-links to Calendar → Agenda', () => {+ renderWidget({ date: '2026-09-01', accountCount: 1, events: [], total: 0 });+ expect(screen.getByText(/Nothing on the calendar today/)).toBeTruthy();+ expect(screen.getByRole('link').getAttribute('href')).toBe('/calendar/agenda');+ });++ it('lists events with times, dims finished ones, and counts what remains', () => {+ renderWidget({+ date: '2026-09-01',+ accountCount: 1,+ total: 3,+ events: [+ { id: 'a', accountId: 'acc', title: 'Done meeting', startTime: iso(-7200000), endTime: iso(-3600000), isAllDay: false, location: null },+ { id: 'b', accountId: 'acc', title: 'Focus block', startTime: iso(3600000), endTime: iso(7200000), isAllDay: false, location: 'Office' },+ { id: 'c', accountId: 'acc', title: 'Launch day', startTime: iso(0), endTime: null, isAllDay: true, location: null },+ ],+ });++ expect(screen.getByText('2 of 3 events remaining')).toBeTruthy();+ expect(screen.getByText('All day')).toBeTruthy();+ expect(screen.getByText('Done meeting').className).toContain('line-through');+ expect(screen.getByText('Focus block').className).not.toContain('line-through');+ });++ it('surfaces the overflow count when the server truncated the list', () => {+ renderWidget({+ date: '2026-09-01',+ accountCount: 1,+ total: 10,+ events: [+ { id: 'a', accountId: 'acc', title: 'One', startTime: iso(3600000), endTime: iso(7200000), isAllDay: false, location: null },+ ],+ });+ expect(screen.getByText('+9 more')).toBeTruthy();+ });+});diff --git a/client/src/components/dashboard/widgetRegistry.jsx b/client/src/components/dashboard/widgetRegistry.jsxindex 9b7edb8957..17dce3c9a0 100644--- a/client/src/components/dashboard/widgetRegistry.jsx+++ b/client/src/components/dashboard/widgetRegistry.jsx@@ -27,6 +27,7 @@ const FeedsWidget = lazyWithReload(() => import('./builtins/FeedsWidgeconst MeatSpaceStreakWidget = lazyWithReload(() => import('./builtins/MeatSpaceStreakWidget'));const AutoFixMetricsWidget = lazyWithReload(() => import('./builtins/AutoFixMetricsWidget'));const DailyDriverWidget = lazyWithReload(() => import('./builtins/DailyDriverWidget'));+const TodayAgendaWidget = lazyWithReload(() => import('./builtins/TodayAgendaWidget'));const ActiveProcessingWidget = lazyWithReload(() => import('./ActiveProcessingWidget'));const DailyActionsWidget = lazyWithReload(() => import('../DailyActionsWidget'));@@ -71,6 +72,7 @@ export const WIDGETS = [{ id: 'hourly-activity', label: 'Activity by Hour', Component: HourlyActivityWidget, width: 'full', defaultH: 4, gate: (s) => !!s.usage?.hourlyActivity && s.usage.hourlyActivity.some((v) => v > 0) },{ id: 'feeds', label: 'Feeds Digest', Component: FeedsWidget, width: 'quarter', defaultH: 4, gate: (s) => (s.feeds?.totalFeeds ?? 0) > 0 },{ id: 'meatspace-streak', label: 'Health Logging Streak', Component: MeatSpaceStreakWidget, width: 'third', defaultH: 4, gate: (s) => (s.meatspaceLogging?.totalLogged ?? 0) > 0 },+ { id: 'today-agenda', label: 'Today\'s Agenda', Component: TodayAgendaWidget, width: 'third', defaultH: 4, gate: (s) => (s.calendarAgenda?.accountCount ?? 0) > 0 },{ id: 'autofix-metrics', label: 'Auto-Fix Telemetry', Component: AutoFixMetricsWidget, width: 'quarter', defaultH: 5 },{ id: 'active-processing', label: 'Active Processing', Component: ActiveProcessingWidget, width: 'half', defaultH: 5 },];diff --git a/client/src/pages/Dashboard.jsx b/client/src/pages/Dashboard.jsxindex c462f0db1a..5dc4e6ee2d 100644--- a/client/src/pages/Dashboard.jsx+++ b/client/src/pages/Dashboard.jsx@@ -28,6 +28,7 @@ export default function Dashboard() {const [tribeCare, setTribeCare] = useState(null);const [feeds, setFeeds] = useState(null);const [meatspaceLogging, setMeatspaceLogging] = useState(null);+ const [calendarAgenda, setCalendarAgenda] = useState(null);const [dailyDriver, setDailyDriver] = useState(null);const [dailyActions, setDailyActions] = useState(null);const [loading, setLoading] = useState(true);@@ -112,6 +113,7 @@ export default function Dashboard() {api.getTribeCareSummary({ silent: true }).catch(() => null).then(setTribeCare),api.getFeedStats({ silent: true }).catch(() => null).then(setFeeds),api.getMeatspaceLoggingStats({ silent: true }).catch(() => null).then(setMeatspaceLogging),+ api.getCalendarAgenda({ silent: true }).catch(() => null).then(setCalendarAgenda),// GET records the first-visit-of-day signal (issue #2666); a failure just// hides the Daily Driver card via its gate. No LLM calls here.api.getDailyDriverState().catch(() => null).then(setDailyDriver),@@ -237,8 +239,8 @@ export default function Dashboard() {}), [activeApps]);const dashboardState = useMemo(- () => ({ apps: appList, appsLoading, sortedApps, activeApps, appStats, health, usage, tribeCare, feeds, meatspaceLogging, dailyDriver, dailyActions, instanceFeatures, refetch: fetchData, refetchHealth: refreshHealth }),- [appList, appsLoading, sortedApps, activeApps, appStats, health, usage, tribeCare, feeds, meatspaceLogging, dailyDriver, dailyActions, instanceFeatures, fetchData, refreshHealth]+ () => ({ apps: appList, appsLoading, sortedApps, activeApps, appStats, health, usage, tribeCare, feeds, meatspaceLogging, calendarAgenda, dailyDriver, dailyActions, instanceFeatures, refetch: fetchData, refetchHealth: refreshHealth }),+ [appList, appsLoading, sortedApps, activeApps, appStats, health, usage, tribeCare, feeds, meatspaceLogging, calendarAgenda, dailyDriver, dailyActions, instanceFeatures, fetchData, refreshHealth]);// Falls back to a local minimal layout only AFTER the initial fetch hasdiff --git a/client/src/services/apiCalendar.js b/client/src/services/apiCalendar.jsindex e5edc2970e..9153e15695 100644--- a/client/src/services/apiCalendar.js+++ b/client/src/services/apiCalendar.js@@ -11,6 +11,7 @@ export const getCalendarEvents = (params = {}) => {const str = new URLSearchParams(Object.entries(params).filter(([, v]) => v != null)).toString();return request(`/calendar/events${str ? `?${str}` : ''}`);};+export const getCalendarAgenda = (options = {}) => request('/calendar/agenda', options);export const getCalendarTokenStatus = () => request('/calendar/debug/token-status');export const testCalendarToken = (provider) => request('/calendar/debug/test-token', { method: 'POST', body: JSON.stringify({ provider }) });export const clearCalendarToken = (provider) => request('/calendar/debug/clear-token', { method: 'POST', body: JSON.stringify({ provider }) });diff --git a/scripts/migrations/327-seed-today-agenda-widget.js b/scripts/migrations/327-seed-today-agenda-widget.jsnew file mode 100644index 0000000000..21c57717b4--- /dev/null+++ b/scripts/migrations/327-seed-today-agenda-widget.js@@ -0,0 +1,48 @@+/**+ * Seed the Today's Agenda calendar widget into the built-in Everything and+ * Morning Review layouts. The widget is gated on a connected calendar account,+ * so installs without one see no change. Custom/user layouts are intentionally+ * untouched: the layout editor is the user's source of truth for those.+ */++import { readLayoutsDoc, writeLayoutsDoc } from './_lib.js';++const LABEL = 'migration 327';+const TARGET_LAYOUTS = new Set(['default', 'morning-review']);+const WIDGET_ID = 'today-agenda';++function applyToLayout(layout) {+ if (!layout || !TARGET_LAYOUTS.has(layout.id) || !Array.isArray(layout.widgets)) return false;+ const hasWidget = layout.widgets.includes(WIDGET_ID);+ const hasGridEntry = Array.isArray(layout.grid) && layout.grid.some((item) => item?.id === WIDGET_ID);+ if (hasWidget && hasGridEntry) return false;++ if (!hasWidget) layout.widgets = [...layout.widgets, WIDGET_ID];+ if (!hasGridEntry) {+ // 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 }];+ }+ return true;+}++export default {+ async up({ rootDir }) {+ const result = await readLayoutsDoc({ rootDir, label: LABEL });+ if (!result.ok) return { updated: 0, reason: result.reason };+ const { doc, path } = result;+ let updated = 0;+ for (const layout of doc.layouts) {+ if (applyToLayout(layout)) updated += 1;+ }+ if (updated === 0) return { updated: 0, reason: 'already-applied' };+ await writeLayoutsDoc(path, doc);+ console.log(`📅 ${LABEL}: seeded Today's Agenda widget in ${updated} built-in dashboard layout(s).`);+ return { updated };+ },+};diff --git a/scripts/migrations/327-seed-today-agenda-widget.test.js b/scripts/migrations/327-seed-today-agenda-widget.test.jsnew file mode 100644index 0000000000..2d4eaf9da8--- /dev/null+++ b/scripts/migrations/327-seed-today-agenda-widget.test.js@@ -0,0 +1,78 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import migration from './327-seed-today-agenda-widget.js';++const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);+const readJson = (path) => JSON.parse(readFileSync(path, 'utf8'));++describe('migration 327 — seed Today\'s Agenda dashboard widget', () => {+ let rootDir;+ let layoutsPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-327-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ layoutsPath = join(rootDir, 'data', 'dashboard-layouts.json');+ });++ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));++ it('does nothing on a fresh install with no persisted layouts', async () => {+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'no-state' });+ });++ it('appends the agenda widget after the existing grid and skips custom layouts', async () => {+ writeJson(layoutsPath, {+ activeLayoutId: 'default',+ layouts: [+ {+ id: 'default', name: 'Everything', builtIn: true,+ widgets: ['quick-brain', 'apps'],+ grid: [+ { id: 'quick-brain', x: 0, w: 3, order: 0, h: 2 },+ { id: 'apps', x: 0, w: 12, order: 1, h: 8 },+ ],+ },+ {+ id: 'morning-review', name: 'Morning Review', builtIn: true,+ widgets: ['proactive-alerts'], grid: [{ id: 'proactive-alerts', x: 0, w: 4, order: 0, h: 4 }],+ },+ {+ id: 'custom', name: 'Mine', builtIn: false,+ widgets: ['quick-brain'], grid: [{ id: 'quick-brain', x: 0, w: 12, order: 0, h: 2 }],+ },+ ],+ });++ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 2 });+ const after = readJson(layoutsPath);+ const seeded = after.layouts.find((layout) => layout.id === 'default');+ expect(seeded.widgets).toEqual(['quick-brain', 'apps', 'today-agenda']);+ expect(seeded.grid).toEqual([+ { id: 'quick-brain', x: 0, w: 3, order: 0, h: 2 },+ { id: 'apps', x: 0, w: 12, order: 1, h: 8 },+ { id: 'today-agenda', x: 0, w: 4, order: 2, h: 4 },+ ]);+ const morning = after.layouts.find((layout) => layout.id === 'morning-review');+ expect(morning.widgets).toContain('today-agenda');+ expect(morning.grid.at(-1)).toEqual({ id: 'today-agenda', x: 0, w: 4, order: 1, h: 4 });+ expect(after.layouts.find((layout) => layout.id === 'custom').widgets).toEqual(['quick-brain']);+ });++ it('is idempotent once the widget is present', async () => {+ writeJson(layoutsPath, {+ activeLayoutId: 'default',+ layouts: [+ {+ id: 'default', name: 'Everything', builtIn: true,+ widgets: ['today-agenda'],+ grid: [{ id: 'today-agenda', x: 0, w: 4, order: 0, h: 4 }],+ },+ ],+ });++ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });+ });+});diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex 1078e817d7..ce1cbd1d5b 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -3522,7 +3522,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 85+ "line": 87}]},@@ -3533,7 +3533,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 90+ "line": 92}]},@@ -3544,7 +3544,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 108+ "line": 110}]},@@ -3555,7 +3555,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 97+ "line": 99}]},@@ -3566,7 +3566,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 166+ "line": 205}]},@@ -3577,7 +3577,18 @@"sources": [{"source": "server/routes/calendar.js",- "line": 175+ "line": 214+ }+ ]+ },+ {+ "method": "GET",+ "path": "/api/calendar/agenda",+ "mountPath": "/api/calendar",+ "sources": [+ {+ "source": "server/routes/calendar.js",+ "line": 146}]},@@ -3588,7 +3599,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 365+ "line": 404}]},@@ -3599,7 +3610,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 342+ "line": 381}]},@@ -3610,7 +3621,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 337+ "line": 376}]},@@ -3621,7 +3632,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 139+ "line": 178}]},@@ -3632,7 +3643,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 156+ "line": 195}]},@@ -3643,7 +3654,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 265+ "line": 304}]},@@ -3654,7 +3665,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 226+ "line": 265}]},@@ -3665,7 +3676,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 221+ "line": 260}]},@@ -3676,7 +3687,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 236+ "line": 275}]},@@ -3687,7 +3698,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 277+ "line": 316}]},@@ -3698,7 +3709,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 283+ "line": 322}]},@@ -3709,7 +3720,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 271+ "line": 310}]},@@ -3720,7 +3731,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 245+ "line": 284}]},@@ -3731,7 +3742,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 317+ "line": 356}]},@@ -3742,7 +3753,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 326+ "line": 365}]},@@ -3753,7 +3764,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 311+ "line": 350}]},@@ -3764,7 +3775,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 120+ "line": 122}]},@@ -3775,7 +3786,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 291+ "line": 330}]},@@ -3786,7 +3797,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 200+ "line": 239}]},@@ -3797,7 +3808,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 300+ "line": 339}]},@@ -3808,7 +3819,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 211+ "line": 250}]},@@ -3819,7 +3830,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 189+ "line": 228}]},@@ -3830,7 +3841,7 @@"sources": [{"source": "server/routes/calendar.js",- "line": 129+ "line": 131}]},@@ -23753,8 +23764,8 @@],"stats": {"mounts": 146,- "operations": 2143,- "declarations": 2146,+ "operations": 2144,+ "declarations": 2147,"sourceFiles": 227}}diff --git a/server/lib/timezone.js b/server/lib/timezone.jsindex 8aea41a023..817855783a 100644--- a/server/lib/timezone.js+++ b/server/lib/timezone.js@@ -109,6 +109,26 @@ export function todayInTimezone(timezone, atDate = new Date()) {return `${parts.year}-${String(parts.month).padStart(2, '0')}-${String(parts.day).padStart(2, '0')}`}+/**+ * UTC timestamp (ms) of local midnight for the `YYYY-MM-DD` day string in `tz`.+ * The server runs TZ=UTC, so we subtract the TZ offset from the naive UTC parse+ * of the day string. Evaluate the offset AT the target day's midnight (not at+ * `now`) so a DST transition elsewhere in the day can't shift the result by an+ * hour. The naive parse lands within ~14h of local midnight — close enough that+ * re-evaluating the offset at that candidate instant converges to the correct+ * offset across a DST boundary.+ * @param {string} dayStr - Local day as `YYYY-MM-DD`+ * @param {string} tz - IANA timezone string+ * @returns {number} UTC timestamp (ms) of that day's local midnight+ */+export function anchorLocalMidnightUtc(dayStr, tz) {+ const naiveUtc = Date.parse(`${dayStr}T00:00:00Z`)+ const firstOffset = getUtcOffsetMs(new Date(naiveUtc), tz)+ const candidate = naiveUtc - firstOffset+ const refinedOffset = getUtcOffsetMs(new Date(candidate), tz)+ return naiveUtc - refinedOffset+}+// ---------------------------------------------------------------------------// HH:MM time-window primitives//diff --git a/server/lib/timezone.test.js b/server/lib/timezone.test.jsindex 7399135ecd..617b412051 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, HHMM_RE, HHMM_STRICT_RE, parseHHMM, isWithinTimeWindow } from './timezone.js'+import { getLocalParts, getUtcOffsetMs, nextLocalTime, todayInTimezone, anchorLocalMidnightUtc, HHMM_RE, HHMM_STRICT_RE, parseHHMM, isWithinTimeWindow } from './timezone.js'import { getTimezoneUpdatedAt } from '../services/userTimezone.js'describe('timezone', () => {@@ -196,6 +196,39 @@ describe('timezone', () => {})})+ describe('anchorLocalMidnightUtc (DST-safe local-midnight anchor)', () => {+ const localClock = (ms, tz) =>+ new Date(ms).toLocaleTimeString('en-US', { timeZone: tz, hour12: false, hour: '2-digit', minute: '2-digit' })++ it('anchors a constant-offset day to local midnight (PDT midnight = 07:00 UTC)', () => {+ const anchor = anchorLocalMidnightUtc('2026-04-17', 'America/Los_Angeles')+ expect(anchor).toBe(Date.parse('2026-04-17T00:00:00Z') + 7 * 3600 * 1000)+ expect(localClock(anchor, 'America/Los_Angeles')).toBe('00:00')+ })++ it('uses the PRE-transition offset on a spring-forward day (midnight is still PST)', () => {+ // US DST starts 2026-03-08 at 02:00 local — midnight that day is still+ // PST (-8), even though most of the day runs PDT (-7). A single-pass+ // offset evaluated later in the day would shift the window by an hour.+ const anchor = anchorLocalMidnightUtc('2026-03-08', 'America/Los_Angeles')+ expect(anchor).toBe(Date.parse('2026-03-08T00:00:00Z') + 8 * 3600 * 1000)+ expect(localClock(anchor, 'America/Los_Angeles')).toBe('00:00')+ })++ it('anchors a fall-back day to the still-PDT midnight', () => {+ // US DST ends 2026-11-01 at 02:00 local — midnight that day is still PDT.+ const anchor = anchorLocalMidnightUtc('2026-11-01', 'America/Los_Angeles')+ expect(anchor).toBe(Date.parse('2026-11-01T00:00:00Z') + 7 * 3600 * 1000)+ expect(localClock(anchor, 'America/Los_Angeles')).toBe('00:00')+ })++ it('handles timezones ahead of UTC', () => {+ const anchor = anchorLocalMidnightUtc('2026-04-17', 'Asia/Tokyo')+ expect(anchor).toBe(Date.parse('2026-04-17T00:00:00Z') - 9 * 3600 * 1000)+ expect(localClock(anchor, 'Asia/Tokyo')).toBe('00:00')+ })+ })+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.jsindex 3ca2e3829b..8ef834bd61 100644--- a/server/routes/calendar.js+++ b/server/routes/calendar.js@@ -11,6 +11,8 @@ import * as googleAuth from '../services/googleAuth.js';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';const router = express.Router();@@ -136,6 +138,43 @@ 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.+router.get('/agenda', asyncHandler(async (req, res) => {+ const { limit: parsedLimit } = 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+ });+ res.json({+ date,+ timezone,+ accountCount,+ events: events.map((e) => ({+ id: e.id,+ accountId: e.accountId,+ title: e.title || 'Untitled event',+ startTime: e.startTime,+ endTime: e.endTime ?? null,+ isAllDay: !!e.isAllDay,+ location: e.location || null+ })),+ total+ });+}));+router.get('/events', asyncHandler(async (req, res) => {const { accountId, search, startDate, endDate } = req.query;if (accountId && !UUID_RE.test(accountId)) {diff --git a/server/routes/calendar.test.js b/server/routes/calendar.test.jsindex 097a63d878..cd348decfd 100644--- a/server/routes/calendar.test.js+++ b/server/routes/calendar.test.js@@ -58,8 +58,14 @@ vi.mock('../services/messageTokenExtractor.js', () => ({clearTokenCache: vi.fn()}));+vi.mock('../services/userTimezone.js', () => ({+ getUserTimezone: vi.fn()+}));+import calendarRoutes from './calendar.js';+import * as calendarAccounts from '../services/calendarAccounts.js';import * as calendarSync from '../services/calendarSync.js';+import { getUserTimezone } from '../services/userTimezone.js';import * as calendarGoogleSync from '../services/calendarGoogleSync.js';import * as calendarGoogleApiSync from '../services/calendarGoogleApiSync.js';import * as googleAuth from '../services/googleAuth.js';@@ -168,6 +174,69 @@ describe('Calendar Routes — normalized error handling', () => {});});+ describe('GET /agenda — today\'s events for the dashboard widget', () => {+ it('reports zero accounts without touching events when none are enabled', async () => {+ calendarAccounts.listAccounts.mockResolvedValue([{ id: ACCOUNT_ID, enabled: false }]);++ const response = await request(app).get('/api/calendar/agenda');++ expect(response.status).toBe(200);+ expect(response.body).toEqual({ date: null, timezone: null, accountCount: 0, events: [], total: 0 });+ expect(calendarSync.getEvents).not.toHaveBeenCalled();+ });++ it('returns today\'s window in the user timezone with trimmed event fields', async () => {+ calendarAccounts.listAccounts.mockResolvedValue([+ { id: ACCOUNT_ID, enabled: true },+ { id: '22222222-2222-2222-2222-222222222222', enabled: false }+ ]);+ getUserTimezone.mockResolvedValue('America/Los_Angeles');+ calendarSync.getEvents.mockResolvedValue({+ events: [+ {+ id: 'evt-1', accountId: ACCOUNT_ID, title: 'Standup',+ startTime: '2026-09-01T17:00:00Z', endTime: '2026-09-01T17:30:00Z',+ isAllDay: false, location: 'Room 4', description: 'secret notes stay server-side'+ },+ { id: 'evt-2', accountId: ACCOUNT_ID, title: '', startTime: '2026-09-01T20:00:00Z' }+ ],+ total: 2+ });++ const response = await request(app).get('/api/calendar/agenda');++ expect(response.status).toBe(200);+ expect(response.body.accountCount).toBe(1);+ expect(response.body.timezone).toBe('America/Los_Angeles');+ expect(response.body.total).toBe(2);+ expect(response.body.events).toEqual([+ {+ id: 'evt-1', accountId: ACCOUNT_ID, title: 'Standup',+ startTime: '2026-09-01T17:00:00Z', endTime: '2026-09-01T17:30:00Z',+ isAllDay: false, location: 'Room 4'+ },+ {+ id: 'evt-2', accountId: ACCOUNT_ID, title: 'Untitled event',+ startTime: '2026-09-01T20:00:00Z', endTime: null,+ isAllDay: false, location: null+ }+ ]);++ // The bounds are the user's LOCAL day expressed in UTC: startDate is+ // local midnight in the configured timezone and the window spans 24h.+ const [{ startDate, endDate, limit }] = calendarSync.getEvents.mock.calls[0];+ expect(limit).toBe(8);+ const localStart = new Date(startDate).toLocaleTimeString('en-US', {+ timeZone: 'America/Los_Angeles', hour12: false, hour: '2-digit', minute: '2-digit'+ });+ expect(localStart).toBe('00:00');+ expect(new Date(endDate).getTime() - new Date(startDate).getTime()).toBe(86399999);+ expect(response.body.date).toBe(+ new Date(startDate).toLocaleDateString('en-CA', { timeZone: 'America/Los_Angeles' })+ );+ });+ });+describe('GET /google/oauth/callback stays browser-friendly (redirects, never JSON errors)', () => {it('redirects to the config page on success', async () => {googleAuth.handleCallback.mockResolvedValue({ success: true });diff --git a/server/services/dashboardLayouts.js b/server/services/dashboardLayouts.jsindex 790c05785c..e64dfc2603 100644--- a/server/services/dashboardLayouts.js+++ b/server/services/dashboardLayouts.js@@ -111,7 +111,7 @@ const DEFAULT_LAYOUTS = ['apps','cos', 'goal-progress', 'upcoming-tasks','proactive-alerts', 'review-hub', 'while-away', 'system-health', 'active-processing', 'network-exposure', 'backup', 'death-clock', 'quick-stats', 'decision-log',- 'hourly-activity', 'tribe-care', 'feeds',+ 'hourly-activity', 'tribe-care', 'feeds', 'today-agenda',],// Above-the-fold capture row stretches to h=5 so the Quick Task card// can show its expanded options (worktree/PR/simplify/etc.) without@@ -149,6 +149,8 @@ const DEFAULT_LAYOUTS = [{ id: 'tribe-care', x: 4, w: 4, order: 19, h: 4 },// Gated on having subscribed feeds — hidden on installs with none.{ id: 'feeds', x: 8, w: 3, order: 20, h: 4 },+ // Gated on a connected calendar account — hidden until one exists.+ { id: 'today-agenda', x: 0, w: 4, order: 21, h: 4 },],},{@@ -170,7 +172,7 @@ const DEFAULT_LAYOUTS = [id: 'morning-review',name: 'Morning Review',builtIn: true,- widgets: ['proactive-alerts', 'upcoming-tasks', 'review-hub', 'goal-progress', 'death-clock', 'daily-driver'],+ widgets: ['proactive-alerts', 'upcoming-tasks', 'review-hub', 'goal-progress', 'death-clock', 'daily-driver', 'today-agenda'],// Scan-and-act morning ritual — the classic scan quadrants above the fold.// Tasks list takes the tall center column (the actionable hot zone); alerts// top-left grab attention first; death-clock top-right for mortality framing;@@ -187,6 +189,9 @@ const DEFAULT_LAYOUTS = [{ id: 'goal-progress', x: 9, w: 3, order: 3, h: 4 },{ id: 'review-hub', x: 0, w: 4, order: 4, h: 4 },{ id: 'daily-driver', x: 0, w: 12, order: 5, h: 6 },+ // Gated on a connected calendar account — sequenced last (like the+ // gated tribe-care/feeds widgets) so its absence leaves only trailing space.+ { id: 'today-agenda', x: 0, w: 4, order: 6, h: 4 },],},{diff --git a/server/services/voice/tools.js b/server/services/voice/tools.jsindex 650cdf44ed..d7442e7f1a 100644--- a/server/services/voice/tools.js+++ b/server/services/voice/tools.js@@ -5,8 +5,7 @@// (TOOL_GROUPS + GROUP_INTENT), and exposes the stable public API consumed by// the voice pipeline (pipeline.js) and the ⌘K command palette (routes/palette.js):// getToolSpecs, getToolSpecsForIntent, getAllToolNames, getToolMetadata,-// classifyIntent, dispatchTool, UI_KINDS, UI_INTENT_RE, UI_FILL_INTENT_RE,-// anchorLocalMidnightUtc.+// classifyIntent, dispatchTool, UI_KINDS, UI_INTENT_RE, UI_FILL_INTENT_RE.// Add a new tool by adding it to its domain module's tool array (and, if it// should be intent-gated, mapping its name in TOOL_GROUPS to a GROUP_INTENT key).@@ -18,7 +17,7 @@ import { DAILYLOG_TOOLS, DAILYLOG_INTENT_RE } from './tools/dailylog.js';import { UI_TOOLS, UI_INTENT_RE, UI_FILL_INTENT_RE } from './tools/ui.js';import { ASK_TOOLS, ASK_INTENT_RE } from './tools/ask.js';import { VISION_TOOLS, VISION_INTENT_RE } from './tools/vision.js';-import { AMBIENT_TOOLS, CALENDAR_INTENT_RE, WEATHER_INTENT_RE, anchorLocalMidnightUtc } from './tools/ambient.js';+import { AMBIENT_TOOLS, CALENDAR_INTENT_RE, WEATHER_INTENT_RE } from './tools/ambient.js';import { TIMER_TOOLS, TIMER_INTENT_RE } from './tools/timer.js';import { MEDIA_TOOLS, MEDIA_INTENT_RE } from './tools/media.js';import { PIPELINE_TOOLS, PIPELINE_INTENT_RE } from './tools/pipeline.js';@@ -28,9 +27,8 @@ import { WORKSPACE_TOOLS, WORKSPACE_INTENT_RE } from './tools/workspace.js';import { UI_KINDS } from './tools/shared.js';// Re-exported for pipeline.js (UI_KINDS, UI_INTENT_RE) and the form-fill-// suppression check; anchorLocalMidnightUtc is re-exported for the unit tests-// that exercise the DST-anchoring math directly.-export { UI_KINDS, UI_INTENT_RE, UI_FILL_INTENT_RE, anchorLocalMidnightUtc };+// suppression check.+export { UI_KINDS, UI_INTENT_RE, UI_FILL_INTENT_RE };// The registry. Order is not load-bearing (consumers resolve by name/id) but// kept domain-grouped for readability.diff --git a/server/services/voice/tools.test.js b/server/services/voice/tools.test.jsindex 8df5afdeaa..035066f115 100644--- a/server/services/voice/tools.test.js+++ b/server/services/voice/tools.test.js@@ -54,6 +54,9 @@ 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`)),}));vi.mock('../userTimezone.js', () => ({getUserTimezone: vi.fn(async () => 'America/Los_Angeles'),@@ -193,8 +196,7 @@ vi.mock('../providers.js', () => ({getProviderById: vi.fn(async () => null),}));-const { dispatchTool, getToolSpecs, getToolSpecsForIntent, classifyIntent, anchorLocalMidnightUtc } = await import('./tools.js');-const { getUtcOffsetMs: mockedGetUtcOffsetMs } = await import('../../lib/timezone.js');+const { dispatchTool, getToolSpecs, getToolSpecsForIntent, classifyIntent } = await import('./tools.js');const { getVoiceConfig: mockedGetVoiceConfig } = await import('./config.js');const { addTask: mockedAddTask, isRunning: mockedIsRunning } = await import('../cos.js');const { getActiveProvider: mockedGetActiveProvider, getAllProviders: mockedGetAllProviders, getProviderById: mockedGetProviderById } = await import('../providers.js');@@ -1372,29 +1374,6 @@ describe('calendar_next', () => {});});-describe('anchorLocalMidnightUtc (DST-safe local-midnight anchor)', () => {- it('subtracts the constant offset off the naive UTC parse', () => {- // Both passes see the mocked -7h (PDT) offset → local midnight is +7h of the- // naive UTC parse of the day string (PDT midnight = 07:00 UTC).- const naive = Date.parse('2026-04-17T00:00:00Z');- expect(anchorLocalMidnightUtc('2026-04-17', 'America/Los_Angeles'))- .toBe(naive + 7 * 3600 * 1000);- });-- it('uses the offset evaluated AT the target midnight, not the first guess', () => {- // Simulate a DST boundary: the offset at the naive-parse instant differs- // from the offset at the refined candidate instant. The returned anchor must- // use the SECOND (refined) offset, proving the two-pass convergence.- const naive = Date.parse('2026-03-08T00:00:00Z');- mockedGetUtcOffsetMs- .mockImplementationOnce(() => -8 * 3600 * 1000) // first pass: PST- .mockImplementationOnce(() => -7 * 3600 * 1000); // refined: PDT- expect(anchorLocalMidnightUtc('2026-03-08', 'America/Los_Angeles'))- .toBe(naive + 7 * 3600 * 1000); // refined offset wins- mockedGetUtcOffsetMs.mockReturnValue(-7 * 3600 * 1000); // restore default- });-});-describe('meatspace_log_workout', () => {it('rejects missing type', async () => {await expect(dispatchTool('meatspace_log_workout', {})).rejects.toThrow(/type is required/);diff --git a/server/services/voice/tools/ambient.js b/server/services/voice/tools/ambient.jsindex ddb8afea27..1af8926081 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 { todayInTimezone, getLocalParts, getUtcOffsetMs } from '../../../lib/timezone.js';+import { anchorLocalMidnightUtc, todayInTimezone, getLocalParts } from '../../../lib/timezone.js';import { getUserTimezone } from '../../userTimezone.js';import { getSettings } from '../../settings.js';import { clampLimit } from './shared.js';@@ -36,20 +36,6 @@ const summarizeEvent = (e, tz) => {const loc = e?.location ? ` at ${e.location}` : '';return `${e?.title || 'Untitled event'} (${when})${loc}`;};-// UTC timestamp (ms) of local midnight for the `YYYY-MM-DD` day string in `tz`.-// The server runs TZ=UTC, so we subtract the TZ offset from the naive UTC parse-// of the day string. Evaluate the offset AT the target day's midnight (not at-// `now`) so a DST transition elsewhere in the day can't shift the result by an-// hour. The naive parse lands within ~14h of local midnight — close enough that-// re-evaluating the offset at that candidate instant converges to the correct-// offset across a DST boundary.-export const anchorLocalMidnightUtc = (dayStr, tz) => {- const naiveUtc = Date.parse(`${dayStr}T00:00:00Z`);- const firstOffset = getUtcOffsetMs(new Date(naiveUtc), tz);- const candidate = naiveUtc - firstOffset;- const refinedOffset = getUtcOffsetMs(new Date(candidate), tz);- return naiveUtc - refinedOffset;-};// ----- Weather helpers (weather_now) -----// WMO weather interpretation codes → short spoken text. Open-Meteo returns the