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([codex5-dashboard-intent-layouts]): intent layouts, time-window auto-activate, widget suggestions
[._.]/ Adam Eivyb6fffc129121
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex f834b6ffe5..fc38670beb 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -3,6 +3,7 @@## Added- **[codex5-client-error-reporter] Browser-side errors and unhandled promise rejections surface in Review Hub.** Crashes that used to vanish into the browser console now land as Review Hub alerts so they can be triaged alongside server errors and CoS work. Repeats of the same error within a day aggregate into a single entry, and bursty render storms are throttled so the hub stays readable.+- **[codex5-dashboard-intent-layouts] Dashboard layouts for Deep Work, Health, and Agent Watch — plus a time-window "morning default."** Three new built-in layouts ship alongside Everything / Focus / Morning Review / Ops, picked for task-focus, health framing, and CoS monitoring respectively. Any layout can now carry an auto-activate window (e.g. 06:00–11:00) — when the dashboard opens during that window it loads with the matching layout selected, unless you manually picked something else today. The layout editor adds a one-click "Set as morning default" toggle and a custom time-window picker. The dashboard also surfaces inline "Add <Widget>?" suggestion chips when a layout omits a widget whose data is populated (e.g. Quick Stats shows up once you have apps registered).- **[versioning-diff-view-per-stage-persist-last-n] Pipeline text stages now keep a version history.** Each regenerate snapshots the prior draft (up to five back) and a new "History" button on the Idea / Prose / Comic Script / Teleplay editors opens a side-by-side word diff against the current version with one-click restore.## Changeddiff --git a/PLAN.md b/PLAN.mdindex 0473ee55b2..928b3617da 100644--- a/PLAN.md+++ b/PLAN.md@@ -9,8 +9,9 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel- [ ] [useautorefetch-shared-visibility-listener] **Shared `visibilitychange` listener for `useAutoRefetch` consumers.** Each `useAutoRefetch` caller currently attaches its own `document.addEventListener('visibilitychange', ...)`. On a page with 20+ widgets (Dashboard), tab show fires 20+ near-simultaneous `loadData()` calls. Extract a singleton emitter (e.g. `client/src/hooks/useVisibilityEvent.js`) and have `useAutoRefetch` subscribe to that instead. Trivial overhead today; revisit if Dashboard widget count grows or profiling flags it.- [ ] [useautorefetch-pollonly-mode] **`useAutoRefetch` `{ pollOnly: true }` mode.** Several callers (Brain, DigitalTwin, ChiefOfStaff, meatspace OverviewTab, MediaJobsQueue, Loops, etc.) use the hook purely as a poll tick — they own their own state via the fetchFn's side-effects and ignore `data` / `loading`. The `return null;` ceremony is documented but signals "I'm not using the hook's data". Add a `{ pollOnly: true }` option that skips the `data` / `loading` useStates and returns `{ refetch }` only, so side-effect-only callers don't carry unused state. Defer until there are enough such callers that the noise is worth abstracting.- [ ] [agents-tab-cooldown-tick-extraction] **Extract a shared cooldown-tick hook for the agents tabs.** `agents/{OverviewTab,ToolsTab,WorldTab}.jsx` each spin a 1s `setInterval` that both (a) ticks `setTick(t => t + 1)` so countdown labels update and (b) conditionally refetches rate limits when every cooldown has expired. Not a fit for `useAutoRefetch` (the tick is primarily UI-driven, the refetch is incidental). Extract `useCooldownTick({ cooldownEnds, onAllExpired })` so all three callers share one tested implementation. Surfaced while migrating sibling pollers in `[codex5-polling-consolidation]`.-- [ ] [codex5-dashboard-intent-layouts] **[P2][DASHBOARD]** Finish intent-named layouts + morning default + widget suggestions. `server/services/dashboardLayouts.js` seeds `morning-review` and `ops` already; still missing `Deep Work`, `Health`, `Agent Watch`. Add the three remaining seeded layouts, a "make this my morning default" toggle that activates a layout in a configured time window, and a "widget suggestion" hint: when a layout omits a widget whose data source is populated (e.g. layout has no calendar widget but calendar is connected), surface an inline "Add Calendar?" affordance.- [ ] [codex5-onboarding-capability-map] **[P2][ONBOARDING]** Capability map of connected systems. One page showing each integration's status: Providers (per-provider configured/available/throttled), Calendar, Brain/memory embeddings, Voice (mic + TTS), Tailscale + HTTPS, Genome/health imports, Telegram/messages, App registry/PM2. Each row links to the relevant settings page. Doubles as a setup checklist and a runtime health overview.+- [ ] [dedupe-hhmm-time-window-helpers] **Dedupe HH:MM time-window helpers across server.** `server/services/voice/proactiveSpeech.js` exports `HHMM_RE` + `parseHHMM` + `isWithinQuietHours` (lines 26–57). `server/services/dashboardLayouts.js#sanitizeActivateWindow` + the inlined `isInTimeWindow` logic (post `[codex5-dashboard-intent-layouts]`) duplicate the same predicate (~25 LOC). Lift the three primitives to `server/lib/timezone.js` (where `getLocalParts` already lives) and have both `proactiveSpeech.js` and `dashboardLayouts.js` import from there. The dashboard route's Zod schema (`TIME_STRING_RE`) can keep aliasing the shared regex. Also evaluate whether `client/src/utils/timeWindow.js` (intentional client mirror) needs a parity test against the server primitive — surfaced by /simplify reuse review during `[codex5-dashboard-intent-layouts]` claim 2026-05-20.+- [ ] [extract-layout-doc-io-helper-from-migrations] **Extract `readLayoutsDoc` / `writeLayoutsDoc` helper for migrations.** Migrations 029 and 030 both repeat the same `readFile → JSON.parse → Array.isArray(doc.layouts) guard → writeFile` shell with near-identical logging strings. `scripts/migrations/_lib.js` already exists as the shared library for prompt-replace migrations — add a layouts-doc helper there so a future migration that touches `data/dashboard-layouts.json` doesn't fork the pattern a third time. Surfaced by /simplify quality review during `[codex5-dashboard-intent-layouts]` claim 2026-05-20.- [ ] [migrate-two-remaining-local-formatters] **Migrate two remaining local formatters surfaced during the module-discovery PR.** Two additional local format definitions were found that aren't in the original tracker: (1) `client/src/components/calendar/EventDetail.jsx:10` defines `formatDateTime(dateStr, isAllDay)` with an all-day branch the shared `formatDateTime` lacks — extend the shared helper to take `{ allDay: true }` or keep this local and rename to `formatEventDateTime`. (2) `client/src/components/cos/tabs/TaskItem.jsx:78` defines `formatDurationMin(mins)` with a `~` approximation prefix (`~3h 30m`) — extend shared `formatDurationMin` with an `{ approximate: true }` option. Low priority; visual semantics need to be preserved exactly.- [ ] [wire-proactive-cos-speech-to-real-triggers] **Wire proactive CoS speech to real triggers.** Plumbing landed (`POST /api/voice/speak` + `voice:speak` socket event); hook to high-severity `errorEvents`, `task:ready`, and `notificationEvents` with per-source rate-limits.- [ ] [optimize-voice-ui-index-text-payload-lazy-only-run] **Optimize `voice:ui:index` text payload.** Lazy: only run `extractVisibleText` when server requests via `voice:ui:read-request`. Keep current behavior as fallback.diff --git a/client/src/components/CmdKSearch.jsx b/client/src/components/CmdKSearch.jsxindex 8af965a8e5..fc4e6a686d 100644--- a/client/src/components/CmdKSearch.jsx+++ b/client/src/components/CmdKSearch.jsx@@ -8,6 +8,7 @@ import { search, getPaletteManifest, runPaletteAction, getDashboardLayouts, setAimport toast from './ui/Toast';import { modKey } from '../utils/platform';import { DASHBOARD_LAYOUT_CHANGED } from '../constants/events.js';+import { recordManualLayoutPick } from '../utils/timeWindow.js';const ICON_MAP = { Brain, Cpu, Package, History, HeartPulse };@@ -218,6 +219,9 @@ export default function CmdKSearch() {// navigate('/') is a no-op if the user is already there.const ok = await setActiveDashboardLayout(item.layoutId).then(() => true, () => false);if (!ok) { close(); return; }+ // Lock in for the day so the next dashboard mount doesn't bump us+ // back to a time-window layout — palette picks are intentional.+ recordManualLayoutPick(item.layoutId);window.dispatchEvent(new CustomEvent(DASHBOARD_LAYOUT_CHANGED));navigate('/');toast.success(`Switched to "${item.layoutName}"`);diff --git a/client/src/components/dashboard/LayoutEditor.jsx b/client/src/components/dashboard/LayoutEditor.jsxindex c927e42ce8..42d2b69232 100644--- a/client/src/components/dashboard/LayoutEditor.jsx+++ b/client/src/components/dashboard/LayoutEditor.jsx@@ -1,7 +1,8 @@import { useState, useEffect, useRef, useCallback } from 'react';-import { X, ArrowUp, ArrowDown, Trash2, Plus, Save } from 'lucide-react';+import { X, ArrowUp, ArrowDown, Trash2, Plus, Save, Clock } from 'lucide-react';import { useScrollLock } from '../../hooks/useScrollLock';import { WIDGETS, WIDGETS_BY_ID } from './widgetRegistry.jsx';+import { isValidTimeString, MORNING_DEFAULT_WINDOW } from '../../utils/timeWindow.js';import toast from '../ui/Toast';import Modal from '../ui/Modal';@@ -23,6 +24,7 @@ export default function LayoutEditor({ layouts, activeLayoutId, limits, onClose,const editing = layouts.find((l) => l.id === editingId);const [widgets, setWidgets] = useState(editing?.widgets ?? []);const [name, setName] = useState(editing?.name ?? '');+ const [activateWindow, setActivateWindow] = useState(editing?.activateWindow ?? null);const [dirty, setDirty] = useState(false);const [mode, setMode] = useState('idle'); // 'idle' | 'duplicate' | 'delete' | 'switch'const [dupName, setDupName] = useState('');@@ -47,6 +49,7 @@ export default function LayoutEditor({ layouts, activeLayoutId, limits, onClose,if (dirty) return;setWidgets(cur.widgets);setName(cur.name);+ setActivateWindow(cur.activateWindow ?? null);setMode('idle');setDupName('');setPendingSwitchId(null);@@ -127,12 +130,27 @@ export default function LayoutEditor({ layouts, activeLayoutId, limits, onClose,const save = async () => {const trimmed = name.trim();if (!trimmed) { toast.error('Name required'); return; }- const ok = await onSave({ id: editingId, name: trimmed, widgets }).then(() => true, () => false);+ if (activateWindow && !(isValidTimeString(activateWindow.start) && isValidTimeString(activateWindow.end) && activateWindow.start !== activateWindow.end)) {+ toast.error('Time window: start and end must be HH:MM and differ');+ return;+ }+ const ok = await onSave({ id: editingId, name: trimmed, widgets, activateWindow }).then(() => true, () => false);if (!ok) return;setDirty(false);toast.success('Layout saved');};+ const updateWindowField = (field, value) => {+ setActivateWindow((prev) => {+ const next = { ...(prev ?? { start: '', end: '' }), [field]: value };+ if (!next.start && !next.end) return null;+ return next;+ });+ setDirty(true);+ };+ const clearWindow = () => { setActivateWindow(null); setDirty(true); };+ const setMorningDefault = () => { setActivateWindow({ ...MORNING_DEFAULT_WINDOW }); setDirty(true); };+const commitDuplicate = async () => {const trimmed = dupName.trim();if (!trimmed) { toast.error('Name required'); return; }@@ -152,7 +170,8 @@ export default function LayoutEditor({ layouts, activeLayoutId, limits, onClose,let n = 1;let id = fitId(n);while (existingIds.has(id)) { n += 1; id = fitId(n); }- const ok = await onDuplicate({ id, name: trimmed, widgets }).then(() => true, () => false);+ // Duplicate inherits the source's activateWindow — easier to clear post-duplicate than to re-enter.+ const ok = await onDuplicate({ id, name: trimmed, widgets, activateWindow }).then(() => true, () => false);if (!ok) return;// The duplicate IS saved — clear dirty so the rehydrate effect runs// when the new layout lands in `layouts` props; otherwise the editor@@ -216,8 +235,9 @@ export default function LayoutEditor({ layouts, activeLayoutId, limits, onClose,<div className="sm:col-span-2 p-4 overflow-y-auto space-y-4"><div>- <label className="block text-xs text-gray-400 mb-1">Name</label>+ <label htmlFor="layout-editor-name" className="block text-xs text-gray-400 mb-1">Name</label><input+ id="layout-editor-name"type="text"value={name}onChange={(e) => { setName(e.target.value); setDirty(true); }}@@ -226,6 +246,55 @@ export default function LayoutEditor({ layouts, activeLayoutId, limits, onClose,/></div>+ <div>+ <div className="flex items-center justify-between mb-1">+ <label htmlFor="layout-editor-window-start" className="text-xs text-gray-400 flex items-center gap-1.5">+ <Clock size={12} aria-hidden="true" />+ Auto-activate window+ </label>+ {!activateWindow && (+ <button+ type="button"+ onClick={setMorningDefault}+ className="text-xs text-port-accent hover:text-port-accent/80"+ >+ Set as morning default+ </button>+ )}+ {activateWindow && (+ <button+ type="button"+ onClick={clearWindow}+ className="text-xs text-gray-500 hover:text-port-error"+ >+ Clear+ </button>+ )}+ </div>+ {activateWindow ? (+ <div className="flex items-center gap-2 text-sm">+ <input+ id="layout-editor-window-start"+ type="time"+ value={activateWindow.start}+ onChange={(e) => updateWindowField('start', e.target.value)}+ className="bg-port-bg border border-port-border rounded-lg px-2 py-1.5 text-white focus:border-port-accent outline-hidden"+ />+ <span className="text-gray-500">to</span>+ <input+ id="layout-editor-window-end"+ type="time"+ value={activateWindow.end}+ onChange={(e) => updateWindowField('end', e.target.value)}+ className="bg-port-bg border border-port-border rounded-lg px-2 py-1.5 text-white focus:border-port-accent outline-hidden"+ />+ <span className="text-xs text-gray-500 ml-2">Activates on dashboard load if now is in this window.</span>+ </div>+ ) : (+ <p className="text-xs text-gray-500">No auto-activation. Set a window to make this layout the default during specific hours.</p>+ )}+ </div>+<div><h3 className="text-xs text-gray-400 uppercase tracking-wide mb-2">Widgets ({widgets.length})</h3><ul className="space-y-1">diff --git a/client/src/components/dashboard/WidgetSuggestions.jsx b/client/src/components/dashboard/WidgetSuggestions.jsxnew file mode 100644index 0000000000..9bf5a1f7be--- /dev/null+++ b/client/src/components/dashboard/WidgetSuggestions.jsx@@ -0,0 +1,68 @@+import { useMemo, useState } from 'react';+import { Plus, X } from 'lucide-react';+import { WIDGETS } from './widgetRegistry.jsx';++// Surfaces "Add <Widget>?" chips for widgets whose data source is populated+// (gate(state) returns true) but that aren't in `presentWidgetIds`.+// Dismissal is per-mount; persistence is deferred until the suggestion+// catalog outgrows the 3 gated widgets we ship today.+export default function WidgetSuggestions({ presentWidgetIds, dashboardState, onAdd }) {+ const [dismissed, setDismissed] = useState(() => new Set());++ const suggestions = useMemo(() => {+ if (!Array.isArray(presentWidgetIds)) return [];+ const present = new Set(presentWidgetIds);+ return WIDGETS.filter((w) => {+ if (!w.gate) return false;+ if (present.has(w.id)) return false;+ if (dismissed.has(w.id)) return false;+ // Defensive: future gate predicates might destructure partial state.+ let active;+ try { active = w.gate(dashboardState); }+ catch { return false; }+ return Boolean(active);+ });+ }, [presentWidgetIds, dashboardState, dismissed]);++ if (suggestions.length === 0) return null;++ const dismiss = (id) => setDismissed((prev) => {+ const next = new Set(prev);+ next.add(id);+ return next;+ });++ const add = (id) => {+ Promise.resolve(onAdd(id)).catch(() => {});+ };++ return (+ <div className="rounded-lg border border-port-border bg-port-card/60 px-3 py-2">+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-xs text-gray-400 uppercase tracking-wide pr-1">Suggested</span>+ {suggestions.map((w) => (+ <span key={w.id} className="inline-flex items-center gap-1 rounded-full border border-port-accent/40 bg-port-accent/10 pl-2 pr-1 py-0.5 text-xs text-gray-200">+ <button+ type="button"+ onClick={() => add(w.id)}+ className="inline-flex items-center gap-1 text-port-accent hover:text-white"+ aria-label={`Add ${w.label} to layout`}+ >+ <Plus size={12} aria-hidden="true" />+ <span>Add {w.label}?</span>+ </button>+ <button+ type="button"+ onClick={() => dismiss(w.id)}+ className="p-0.5 rounded text-gray-500 hover:text-gray-300"+ aria-label={`Dismiss ${w.label} suggestion`}+ title="Hide this suggestion"+ >+ <X size={11} aria-hidden="true" />+ </button>+ </span>+ ))}+ </div>+ </div>+ );+}diff --git a/client/src/components/dashboard/WidgetSuggestions.test.jsx b/client/src/components/dashboard/WidgetSuggestions.test.jsxnew file mode 100644index 0000000000..8904da6500--- /dev/null+++ b/client/src/components/dashboard/WidgetSuggestions.test.jsx@@ -0,0 +1,60 @@+import { describe, it, expect, vi } from 'vitest';+import { render, screen, fireEvent } from '@testing-library/react';+import WidgetSuggestions from './WidgetSuggestions';++// `quick-stats` ships with gate: (s) => s.apps.length > 0 — a deterministic+// fixture lets us exercise the "data populated but widget missing" path+// without mocking the registry.++describe('WidgetSuggestions', () => {+ const emptyState = { apps: [], usage: null };+ const populatedState = {+ apps: [{ id: 'a1', name: 'app', overallStatus: 'online' }],+ usage: { currentStreak: 5, longestStreak: 5, hourlyActivity: [0, 0, 1, 0] },+ };++ it('renders nothing when every gated widget is already present', () => {+ const { container } = render(+ <WidgetSuggestions+ presentWidgetIds={['quick-stats', 'activity-streak', 'hourly-activity']}+ dashboardState={populatedState}+ onAdd={() => {}}+ />+ );+ expect(container).toBeEmptyDOMElement();+ });++ it('renders nothing when no gated widget has data', () => {+ const { container } = render(+ <WidgetSuggestions presentWidgetIds={[]} dashboardState={emptyState} onAdd={() => {}} />+ );+ expect(container).toBeEmptyDOMElement();+ });++ it('suggests a missing-but-data-populated widget', () => {+ render(<WidgetSuggestions presentWidgetIds={[]} dashboardState={populatedState} onAdd={() => {}} />);+ expect(screen.getByText(/Quick Stats/)).toBeDefined();+ });++ it('calls onAdd with just the widget id (no layout shape leakage)', () => {+ const onAdd = vi.fn().mockResolvedValue();+ render(<WidgetSuggestions presentWidgetIds={['cos']} dashboardState={populatedState} onAdd={onAdd} />);+ fireEvent.click(screen.getByLabelText('Add Quick Stats to layout'));+ expect(onAdd).toHaveBeenCalledWith('quick-stats');+ });++ it('dismissing a suggestion hides it for the lifetime of the mount', () => {+ render(<WidgetSuggestions presentWidgetIds={[]} dashboardState={populatedState} onAdd={() => {}} />);+ expect(screen.queryByText(/Quick Stats/)).not.toBeNull();+ fireEvent.click(screen.getByLabelText('Dismiss Quick Stats suggestion'));+ expect(screen.queryByText(/Quick Stats/)).toBeNull();+ });++ it('swallows gate-predicate exceptions without surfacing the widget', () => {+ // Future widgets may add gate predicates that destructure partial state.+ const { container } = render(+ <WidgetSuggestions presentWidgetIds={[]} dashboardState={undefined} onAdd={() => {}} />+ );+ expect(container).toBeEmptyDOMElement();+ });+});diff --git a/client/src/pages/Dashboard.jsx b/client/src/pages/Dashboard.jsxindex 2a39105299..5a0c1af884 100644--- a/client/src/pages/Dashboard.jsx+++ b/client/src/pages/Dashboard.jsx@@ -1,8 +1,9 @@-import { useState, useEffect, useCallback, useMemo, Suspense } from 'react';+import { useState, useEffect, useCallback, useMemo, useRef, Suspense } from 'react';import { Link } from 'react-router-dom';import BrailleSpinner from '../components/BrailleSpinner';import LayoutPicker from '../components/dashboard/LayoutPicker';import LayoutEditor from '../components/dashboard/LayoutEditor';+import WidgetSuggestions from '../components/dashboard/WidgetSuggestions';import DashboardGrid, { reconcileGrid, synthesizeGrid } from '../components/dashboard/DashboardGrid.jsx';import { WIDGETS_BY_ID, FALLBACK_LAYOUT } from '../components/dashboard/widgetRegistry.jsx';import WidgetSkeleton from '../components/dashboard/WidgetSkeleton';@@ -12,6 +13,7 @@ import { Monitor, Move, Save, X } from 'lucide-react';import * as api from '../services/api';import socket from '../services/socket';import toast from '../components/ui/Toast';+import { pickActiveLayoutId, recordManualLayoutPick } from '../utils/timeWindow.js';export default function Dashboard() {const [apps, setApps] = useState([]);@@ -53,6 +55,9 @@ export default function Dashboard() {return () => socket.off('apps:changed', handleAppsChanged);}, [fetchData]);+ // One-shot per mount — guards against re-evaluation stomping manual picks.+ const autoSwitchedRef = useRef(false);+useEffect(() => {// `cancelled` guard prevents setState-on-unmounted warnings (and// accidental state writes) when the user navigates away before the@@ -63,7 +68,12 @@ export default function Dashboard() {.then((data) => {if (cancelled) return;setLayouts(data.layouts);- setActiveLayoutId(data.activeLayoutId);+ const desiredActiveId = pickActiveLayoutId(data.activeLayoutId, data.layouts, autoSwitchedRef.current);+ autoSwitchedRef.current = true;+ setActiveLayoutId(desiredActiveId);+ if (desiredActiveId !== data.activeLayoutId) {+ api.setActiveDashboardLayout(desiredActiveId).catch(() => {});+ }if (data.limits) setLayoutLimits(data.limits);setLayoutsError(null);})@@ -160,7 +170,7 @@ export default function Dashboard() {if (!activeLayout || !draftGrid) return;setSavingGrid(true);const ok = await api- .saveDashboardLayout(activeLayout.id, activeLayout.name, activeLayout.widgets, draftGrid)+ .saveDashboardLayout(activeLayout.id, { name: activeLayout.name, widgets: activeLayout.widgets, grid: draftGrid }).then((result) => { setLayouts(result.layouts); return true; }, () => false);setSavingGrid(false);if (!ok) return;@@ -172,6 +182,7 @@ export default function Dashboard() {const selectLayout = async (id) => {const previousId = activeLayoutId;setActiveLayoutId(id);+ recordManualLayoutPick(id);// Revert on failure. request() already surfaces the error via toast,// so swallow here to prevent an unhandled rejection from click handlers.// Guard the revert with a functional setState — if the user has since@@ -186,23 +197,23 @@ export default function Dashboard() {// don't get wiped when the user toggles a widget in the LayoutEditor.// reconcileGrid drops removed widgets and appends any new ones at the// bottom, mirroring what the renderer does at view time.- const saveLayout = async ({ id, name, widgets }) => {+ const saveLayout = async ({ id, name, widgets, activateWindow }) => {const existing = layouts.find((l) => l.id === id);const baseGrid = (existing?.grid && existing.grid.length > 0)? existing.grid: synthesizeGrid(existing?.widgets ?? widgets);const nextGrid = reconcileGrid(baseGrid, widgets);- const result = await api.saveDashboardLayout(id, name, widgets, nextGrid);+ const result = await api.saveDashboardLayout(id, { name, widgets, grid: nextGrid, activateWindow });setLayouts(result.layouts);};- const duplicateLayout = async ({ id, name, widgets }) => {+ const duplicateLayout = async ({ id, name, widgets, activateWindow }) => {const previousId = activeLayoutId;// New layouts inherit the current renderGrid so "Save as new…" from a// visually-arranged dashboard captures what the user actually sees.const sourceGrid = renderGrid && renderGrid.length > 0 ? renderGrid : synthesizeGrid(widgets);const grid = reconcileGrid(sourceGrid, widgets);- const result = await api.saveDashboardLayout(id, name, widgets, grid);+ const result = await api.saveDashboardLayout(id, { name, widgets, grid, activateWindow });setLayouts(result.layouts);setActiveLayoutId(id);// Mirror selectLayout's revert-on-failure so the picker doesn't@@ -321,6 +332,19 @@ export default function Dashboard() {</div>)}+ {!editingGrid && activeLayout && activeLayout.id !== FALLBACK_LAYOUT.id && (+ <WidgetSuggestions+ presentWidgetIds={activeLayout.widgets}+ dashboardState={dashboardState}+ onAdd={(widgetId) => saveLayout({+ id: activeLayout.id,+ name: activeLayout.name,+ widgets: [...activeLayout.widgets, widgetId],+ activateWindow: activeLayout.activateWindow ?? null,+ })}+ />+ )}+{visibleWidgets.length > 0 && (<>{editingGrid && (diff --git a/client/src/services/apiDashboard.js b/client/src/services/apiDashboard.jsindex 58bf68be6f..e4176252a2 100644--- a/client/src/services/apiDashboard.js+++ b/client/src/services/apiDashboard.js@@ -8,11 +8,17 @@ export const setActiveDashboardLayout = (id) =>body: JSON.stringify({ id }),});-export const saveDashboardLayout = (id, name, widgets, grid) =>- request(`/dashboard/layouts/${encodeURIComponent(id)}`, {+// `activateWindow` is partial-aware: omit to preserve the existing value,+// pass `null` to clear, pass `{ start, end }` to set. Mirrors the merge in+// `server/services/dashboardLayouts.js#saveLayout`.+export const saveDashboardLayout = (id, { name, widgets, grid, activateWindow }) => {+ const body = { name, widgets, grid: grid ?? [] };+ if (activateWindow !== undefined) body.activateWindow = activateWindow;+ return request(`/dashboard/layouts/${encodeURIComponent(id)}`, {method: 'PUT',- body: JSON.stringify({ name, widgets, grid: grid ?? [] }),+ body: JSON.stringify(body),});+};export const deleteDashboardLayout = (id) =>request(`/dashboard/layouts/${encodeURIComponent(id)}`, { method: 'DELETE' });diff --git a/client/src/utils/timeWindow.js b/client/src/utils/timeWindow.jsnew file mode 100644index 0000000000..56ba615c92--- /dev/null+++ b/client/src/utils/timeWindow.js@@ -0,0 +1,88 @@+// Time-window helpers for dashboard layout auto-activation.+// Predicate logic is mirrored on the server (`server/services/dashboardLayouts.js`).++export const TIME_STRING_RE = /^([01]\d|2[0-3]):[0-5]\d$/;++export function isValidTimeString(s) {+ return typeof s === 'string' && TIME_STRING_RE.test(s);+}++export function timeStringToMinutes(s) {+ const [h, m] = s.split(':').map(Number);+ return h * 60 + m;+}++// Half-open [start, end). Handles overnight wrap when start > end.+export function isInTimeWindow(window, now = new Date()) {+ if (!window || typeof window !== 'object') return false;+ if (!isValidTimeString(window.start) || !isValidTimeString(window.end)) return false;+ if (window.start === window.end) return false;+ const startMin = timeStringToMinutes(window.start);+ const endMin = timeStringToMinutes(window.end);+ const nowMin = now.getHours() * 60 + now.getMinutes();+ if (startMin < endMin) return nowMin >= startMin && nowMin < endMin;+ return nowMin >= startMin || nowMin < endMin;+}++// First layout whose window covers `now`. Order matters when windows overlap.+function findActiveWindowLayout(layouts, now = new Date()) {+ if (!Array.isArray(layouts)) return null;+ return layouts.find((l) => isInTimeWindow(l?.activateWindow, now)) || null;+}++export const MORNING_DEFAULT_WINDOW = Object.freeze({ start: '06:00', end: '11:00' });++// localStorage key per-day so each new day clears the user's daily lock and+// a window-layout can auto-activate again.+const USER_PICK_KEY_PREFIX = 'dashboard:userPick:';+const localDateKey = (now = new Date()) => {+ const y = now.getFullYear();+ const m = String(now.getMonth() + 1).padStart(2, '0');+ const d = String(now.getDate()).padStart(2, '0');+ return `${y}-${m}-${d}`;+};+const userPickKey = (now = new Date()) => `${USER_PICK_KEY_PREFIX}${localDateKey(now)}`;++// Drop stale `dashboard:userPick:*` keys older than today so the key count+// stays O(1) over time. Best-effort; failures are silent.+const pruneStaleUserPickKeys = (todayKey) => {+ if (typeof window === 'undefined' || !window.localStorage) return;+ try {+ const remove = [];+ for (let i = 0; i < window.localStorage.length; i += 1) {+ const k = window.localStorage.key(i);+ if (k && k.startsWith(USER_PICK_KEY_PREFIX) && k !== todayKey) remove.push(k);+ }+ for (const k of remove) window.localStorage.removeItem(k);+ } catch { /* private mode / disabled — nothing to prune */ }+};++export function recordManualLayoutPick(layoutId, now = new Date()) {+ if (typeof window === 'undefined' || !window.localStorage) return;+ try {+ const todayKey = userPickKey(now);+ window.localStorage.setItem(todayKey, String(layoutId));+ pruneStaleUserPickKeys(todayKey);+ } catch { /* quota / disabled — auto-switch will fire next visit */ }+}++function readManualLayoutPick(now = new Date()) {+ if (typeof window === 'undefined' || !window.localStorage) return null;+ try { return window.localStorage.getItem(userPickKey(now)) ?? null; }+ catch { return null; }+}++// Decide which layout id should be active on a fresh dashboard load.+// - alreadyAutoSwitched → keep the server's choice (subsequent refetches+// must not stomp a manual pick the user just made).+// - user has a recorded pick for today → honor it.+// - a window layout currently covers `now` → auto-pick it.+// - otherwise → server's active layout.+export function pickActiveLayoutId(serverActiveId, layouts, alreadyAutoSwitched, now = new Date()) {+ if (alreadyAutoSwitched) return serverActiveId;+ const userPickId = readManualLayoutPick(now);+ if (userPickId && layouts?.some((l) => l.id === userPickId)) return userPickId;+ const windowLayout = findActiveWindowLayout(layouts, now);+ if (windowLayout) return windowLayout.id;+ return serverActiveId;+}diff --git a/client/src/utils/timeWindow.test.js b/client/src/utils/timeWindow.test.jsnew file mode 100644index 0000000000..56ca716182--- /dev/null+++ b/client/src/utils/timeWindow.test.js@@ -0,0 +1,110 @@+import { describe, it, expect, beforeEach } from 'vitest';+import { isInTimeWindow, isValidTimeString, MORNING_DEFAULT_WINDOW, pickActiveLayoutId, recordManualLayoutPick } from './timeWindow.js';++describe('isValidTimeString', () => {+ it('accepts HH:MM in 24h format', () => {+ expect(isValidTimeString('00:00')).toBe(true);+ expect(isValidTimeString('06:30')).toBe(true);+ expect(isValidTimeString('23:59')).toBe(true);+ });++ it('rejects malformed strings', () => {+ expect(isValidTimeString('24:00')).toBe(false);+ expect(isValidTimeString('6:30')).toBe(false);+ expect(isValidTimeString('06:60')).toBe(false);+ expect(isValidTimeString('foo')).toBe(false);+ expect(isValidTimeString('')).toBe(false);+ expect(isValidTimeString(null)).toBe(false);+ });+});++describe('isInTimeWindow', () => {+ it('returns true inside a non-wrap window', () => {+ const now = new Date('2026-05-20T07:30:00');+ expect(isInTimeWindow({ start: '06:00', end: '11:00' }, now)).toBe(true);+ });++ it('returns true at exact start, false at exact end (half-open)', () => {+ expect(isInTimeWindow({ start: '06:00', end: '11:00' }, new Date('2026-05-20T06:00:00'))).toBe(true);+ expect(isInTimeWindow({ start: '06:00', end: '11:00' }, new Date('2026-05-20T11:00:00'))).toBe(false);+ });++ it('handles overnight wrap correctly', () => {+ const win = { start: '22:00', end: '02:00' };+ expect(isInTimeWindow(win, new Date('2026-05-20T23:30:00'))).toBe(true);+ expect(isInTimeWindow(win, new Date('2026-05-20T01:00:00'))).toBe(true);+ expect(isInTimeWindow(win, new Date('2026-05-20T10:00:00'))).toBe(false);+ });++ it('returns false for malformed input', () => {+ const now = new Date('2026-05-20T07:30:00');+ expect(isInTimeWindow(null, now)).toBe(false);+ expect(isInTimeWindow({ start: 'nope', end: '11:00' }, now)).toBe(false);+ expect(isInTimeWindow({ start: '06:00', end: '06:00' }, now)).toBe(false);+ });+});++describe('MORNING_DEFAULT_WINDOW', () => {+ it('is the canonical 06:00–11:00 window', () => {+ expect(MORNING_DEFAULT_WINDOW).toEqual({ start: '06:00', end: '11:00' });+ });+});++// pickActiveLayoutId + recordManualLayoutPick touch window.localStorage, so+// only the client's jsdom vitest can run them. Server vitest also picks up+// `**/*.test.js` from `client/src/**` and would error under node env.+const hasLocalStorage = typeof window !== 'undefined' && typeof window.localStorage !== 'undefined';++describe.skipIf(!hasLocalStorage)('pickActiveLayoutId', () => {+ beforeEach(() => { window.localStorage.clear(); });++ const layouts = [+ { id: 'morning', activateWindow: { start: '06:00', end: '11:00' } },+ { id: 'focus', activateWindow: null },+ { id: 'default', activateWindow: null },+ ];++ it('returns server active when already auto-switched (one-shot guard)', () => {+ const now = new Date('2026-05-20T07:30:00');+ expect(pickActiveLayoutId('focus', layouts, true, now)).toBe('focus');+ });++ it('honors today\'s manual pick when set', () => {+ const now = new Date('2026-05-20T07:30:00');+ recordManualLayoutPick('default', now);+ expect(pickActiveLayoutId('focus', layouts, false, now)).toBe('default');+ });++ it('auto-picks a window-matching layout when no manual pick', () => {+ const now = new Date('2026-05-20T07:30:00');+ expect(pickActiveLayoutId('focus', layouts, false, now)).toBe('morning');+ });++ it('falls through to server active when no window matches and no manual pick', () => {+ const now = new Date('2026-05-20T15:00:00');+ expect(pickActiveLayoutId('focus', layouts, false, now)).toBe('focus');+ });++ it('ignores a manual pick whose layout no longer exists', () => {+ const now = new Date('2026-05-20T07:30:00');+ recordManualLayoutPick('deleted-layout', now);+ // Falls through to window auto-pick.+ expect(pickActiveLayoutId('focus', layouts, false, now)).toBe('morning');+ });+});++describe.skipIf(!hasLocalStorage)('recordManualLayoutPick — stale key pruning', () => {+ beforeEach(() => { window.localStorage.clear(); });++ it('removes prior-day userPick keys when recording today', () => {+ window.localStorage.setItem('dashboard:userPick:2025-01-01', 'old');+ window.localStorage.setItem('dashboard:userPick:2025-06-15', 'older');+ window.localStorage.setItem('unrelated-key', 'keep');+ const now = new Date('2026-05-20T10:00:00');+ recordManualLayoutPick('today-pick', now);+ expect(window.localStorage.getItem('dashboard:userPick:2026-05-20')).toBe('today-pick');+ expect(window.localStorage.getItem('dashboard:userPick:2025-01-01')).toBe(null);+ expect(window.localStorage.getItem('dashboard:userPick:2025-06-15')).toBe(null);+ expect(window.localStorage.getItem('unrelated-key')).toBe('keep');+ });+});diff --git a/scripts/migrations/030-seed-intent-dashboard-layouts.js b/scripts/migrations/030-seed-intent-dashboard-layouts.jsnew file mode 100644index 0000000000..5e6a6e1dcd--- /dev/null+++ b/scripts/migrations/030-seed-intent-dashboard-layouts.js@@ -0,0 +1,59 @@+/**+ * Seed the three new intent-named built-in dashboard layouts into installs+ * that already have a persisted `data/dashboard-layouts.json`.+ *+ * Background:+ * `server/services/dashboardLayouts.js#DEFAULT_LAYOUTS` ships+ * `deep-work`, `health`, and `agent-watch` alongside the original four+ * built-ins. `getState()` returns the sanitized persisted layouts whenever+ * the file exists, so adding new built-ins in code only affects fresh+ * installs — existing users never see them.+ *+ * This migration walks `data/dashboard-layouts.json` and inserts any of+ * the three new built-ins that aren't already present, with their+ * server-side default grid. Re-runs detect each layout already exists by+ * id and skip, so the migration is idempotent.+ *+ * If the user previously deleted one of the new built-in ids (the+ * `health` widget doesn't survive deletion of a built-in today because+ * built-ins are guarded — but a hand-edit could remove it), we will+ * re-seed it. This matches the behavior of the fresh-install path.+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';+import { INTENT_LAYOUTS } from '../../server/services/dashboardLayouts.js';++export default {+ async up({ rootDir }) {+ const path = join(rootDir, 'data', 'dashboard-layouts.json');+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) {+ console.log(`📦 migration 030: no dashboard-layouts.json yet — fresh install will seed from defaults.`);+ return { updated: 0, reason: 'no-state' };+ }+ let doc;+ try { doc = JSON.parse(raw); } catch {+ console.log(`📦 migration 030: dashboard-layouts.json unreadable — skipping.`);+ return { updated: 0, reason: 'unreadable' };+ }+ if (!doc || !Array.isArray(doc.layouts)) {+ return { updated: 0, reason: 'no-layouts-array' };+ }++ const existingIds = new Set(doc.layouts.map((l) => l?.id).filter(Boolean));+ const toAdd = INTENT_LAYOUTS.filter((l) => !existingIds.has(l.id));+ if (toAdd.length === 0) {+ console.log(`📦 migration 030: intent layouts already present.`);+ return { updated: 0, reason: 'already-applied' };+ }++ doc.layouts.push(...toAdd.map((l) => ({ ...l, builtIn: true })));+ await writeFile(path, JSON.stringify(doc, null, 2));+ console.log(`📦 migration 030: seeded ${toAdd.length} intent layout(s) (${toAdd.map((l) => l.id).join(', ')}).`);+ return { updated: toAdd.length };+ },+};diff --git a/scripts/migrations/030-seed-intent-dashboard-layouts.test.js b/scripts/migrations/030-seed-intent-dashboard-layouts.test.jsnew file mode 100644index 0000000000..b35dace7b4--- /dev/null+++ b/scripts/migrations/030-seed-intent-dashboard-layouts.test.js@@ -0,0 +1,112 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './030-seed-intent-dashboard-layouts.js';++const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++describe('migration 030 — seed intent-named dashboard layouts', () => {+ let rootDir;+ let layoutsPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-030-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ layoutsPath = join(rootDir, 'data', 'dashboard-layouts.json');+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('no-ops cleanly when dashboard-layouts.json is missing (fresh install)', async () => {+ const result = await migration.up({ rootDir });+ expect(result.updated).toBe(0);+ expect(result.reason).toBe('no-state');+ expect(existsSync(layoutsPath)).toBe(false);+ });++ it('inserts all three new built-ins when none are present', async () => {+ writeJson(layoutsPath, {+ activeLayoutId: 'default',+ layouts: [+ { id: 'default', name: 'Everything', builtIn: true, widgets: ['quick-task'], grid: [] },+ ],+ });+ const result = await migration.up({ rootDir });+ expect(result.updated).toBe(3);+ const after = readJson(layoutsPath);+ const ids = after.layouts.map((l) => l.id);+ expect(ids).toContain('deep-work');+ expect(ids).toContain('health');+ expect(ids).toContain('agent-watch');+ const dw = after.layouts.find((l) => l.id === 'deep-work');+ expect(dw.builtIn).toBe(true);+ expect(dw.widgets).toContain('upcoming-tasks');+ expect(dw.grid.length).toBeGreaterThan(0);+ });++ it('is idempotent — second run is a no-op', async () => {+ writeJson(layoutsPath, {+ activeLayoutId: 'default',+ layouts: [+ { id: 'default', name: 'Everything', builtIn: true, widgets: ['quick-task'], grid: [] },+ ],+ });+ await migration.up({ rootDir });+ const result = await migration.up({ rootDir });+ expect(result.updated).toBe(0);+ expect(result.reason).toBe('already-applied');+ });++ it('seeds only the missing layouts when some are already present', async () => {+ writeJson(layoutsPath, {+ activeLayoutId: 'default',+ layouts: [+ { id: 'default', name: 'Everything', builtIn: true, widgets: ['quick-task'], grid: [] },+ { id: 'health', name: 'Health (custom)', builtIn: true, widgets: ['death-clock'], grid: [] },+ ],+ });+ const result = await migration.up({ rootDir });+ expect(result.updated).toBe(2);+ const after = readJson(layoutsPath);+ const ids = after.layouts.map((l) => l.id);+ expect(ids).toContain('deep-work');+ expect(ids).toContain('agent-watch');+ expect(after.layouts.find((l) => l.id === 'health').name).toBe('Health (custom)');+ });++ it('preserves user layouts untouched', async () => {+ writeJson(layoutsPath, {+ activeLayoutId: 'my-custom',+ layouts: [+ { id: 'default', name: 'Everything', builtIn: true, widgets: ['quick-task'], grid: [] },+ { id: 'my-custom', name: 'My Custom', builtIn: false, widgets: ['cos'], grid: [{ id: 'cos', x: 0, y: 0, w: 12, h: 4 }] },+ ],+ });+ const result = await migration.up({ rootDir });+ expect(result.updated).toBe(3);+ const after = readJson(layoutsPath);+ expect(after.activeLayoutId).toBe('my-custom');+ const custom = after.layouts.find((l) => l.id === 'my-custom');+ expect(custom.widgets).toEqual(['cos']);+ expect(custom.grid).toEqual([{ id: 'cos', x: 0, y: 0, w: 12, h: 4 }]);+ });++ it('survives an unreadable JSON file', async () => {+ writeFileSync(layoutsPath, 'not json');+ const result = await migration.up({ rootDir });+ expect(result.updated).toBe(0);+ expect(result.reason).toBe('unreadable');+ });++ it('does nothing when the file has no layouts array', async () => {+ writeJson(layoutsPath, { activeLayoutId: 'default' });+ const result = await migration.up({ rootDir });+ expect(result.updated).toBe(0);+ expect(result.reason).toBe('no-layouts-array');+ });+});diff --git a/server/routes/dashboardLayouts.js b/server/routes/dashboardLayouts.jsindex d8b2b5f8db..255f790843 100644--- a/server/routes/dashboardLayouts.js+++ b/server/routes/dashboardLayouts.js@@ -30,6 +30,16 @@ const gridItemSchema = z.object({h: z.number().int().min(1).max(svc.GRID_ITEM_H_MAX),});+// Time-window strings (HH:MM, 24h). The route accepts `null` to clear an+// existing window — clients send `activateWindow: null` to remove the+// auto-activation. The service's sanitizer also drops malformed shapes on+// read so unknown fields can never sneak through.+const timeStringSchema = z.string().regex(svc.TIME_STRING_RE, 'must be HH:MM (24h)');+const activateWindowSchema = z.object({+ start: timeStringSchema,+ end: timeStringSchema,+}).refine((w) => w.start !== w.end, { message: 'start and end must differ' });+const layoutSchema = z.object({id: idSchema,// Trim before min-length check so whitespace-only names are rejected.@@ -51,6 +61,10 @@ const layoutSchema = z.object({.max(svc.WIDGETS_MAX).optional().default([]),+ // Optional — when set, the dashboard auto-selects this layout on cold+ // load if the local clock falls in the window. `null` is the explicit+ // clear signal; `undefined` (key missing) preserves whatever's on disk.+ activateWindow: activateWindowSchema.nullable().optional(),}).refine((l) => l.grid.every((g) => l.widgets.includes(g.id)),{ message: 'grid items must reference widgets in the layout', path: ['grid'] }diff --git a/server/routes/dashboardLayouts.test.js b/server/routes/dashboardLayouts.test.jsindex 3bc8d605ac..4b5f8db59e 100644--- a/server/routes/dashboardLayouts.test.js+++ b/server/routes/dashboardLayouts.test.js@@ -14,6 +14,7 @@ vi.mock('../services/dashboardLayouts.js', () => ({GRID_COLS: 12,GRID_ROW_MAX: 200,GRID_ITEM_H_MAX: 50,+ TIME_STRING_RE: /^([01]\d|2[0-3]):[0-5]\d$/,getState: vi.fn(),setActiveLayout: vi.fn(),saveLayout: vi.fn(),@@ -183,6 +184,56 @@ describe('PUT /api/dashboard/layouts/:id', () => {grid: [],});});++ it('accepts a valid activateWindow', async () => {+ svc.saveLayout.mockResolvedValue({ activeLayoutId: 'default', layouts: [] });+ const res = await request(makeApp())+ .put('/api/dashboard/layouts/morning')+ .send({+ name: 'Morning',+ widgets: ['upcoming-tasks'],+ activateWindow: { start: '06:00', end: '11:00' },+ });+ expect(res.status).toBe(200);+ expect(svc.saveLayout).toHaveBeenCalledWith(expect.objectContaining({+ activateWindow: { start: '06:00', end: '11:00' },+ }));+ });++ it('accepts activateWindow=null as an explicit clear signal', async () => {+ svc.saveLayout.mockResolvedValue({ activeLayoutId: 'default', layouts: [] });+ const res = await request(makeApp())+ .put('/api/dashboard/layouts/morning')+ .send({ name: 'Morning', widgets: ['upcoming-tasks'], activateWindow: null });+ expect(res.status).toBe(200);+ expect(svc.saveLayout).toHaveBeenCalledWith(expect.objectContaining({+ activateWindow: null,+ }));+ });++ it('rejects activateWindow with off-format time strings', async () => {+ const res = await request(makeApp())+ .put('/api/dashboard/layouts/morning')+ .send({+ name: 'Morning',+ widgets: ['upcoming-tasks'],+ activateWindow: { start: '25:99', end: '11:00' },+ });+ expect(res.status).toBe(400);+ expect(svc.saveLayout).not.toHaveBeenCalled();+ });++ it('rejects activateWindow with start === end', async () => {+ const res = await request(makeApp())+ .put('/api/dashboard/layouts/morning')+ .send({+ name: 'Morning',+ widgets: ['upcoming-tasks'],+ activateWindow: { start: '06:00', end: '06:00' },+ });+ expect(res.status).toBe(400);+ expect(svc.saveLayout).not.toHaveBeenCalled();+ });});describe('PUT /api/dashboard/layouts/active — id validation', () => {diff --git a/server/services/dashboardLayouts.js b/server/services/dashboardLayouts.jsindex 92dc9a0107..e51549091f 100644--- a/server/services/dashboardLayouts.js+++ b/server/services/dashboardLayouts.js@@ -29,6 +29,49 @@ const makeErr = (message, code) => Object.assign(new Error(message), { code });// are designed for a typical desktop viewport (12 cols × ~80px rows): the// most useful widgets sit in rows 0–7 (~768px) so they're above the fold// without scrolling, and lower-priority widgets stack below.++// Intent-named layouts shipped post-029. Exported so the migration that+// seeds them into existing installs (scripts/migrations/030-…) imports+// from this file rather than mirroring the grid by hand — fresh-install+// and migrated-install layouts can't drift on a future tweak.+export const INTENT_LAYOUTS = [+ {+ id: 'deep-work',+ name: 'Deep Work',+ widgets: ['quick-task', 'upcoming-tasks', 'cos', 'decision-log'],+ grid: [+ { id: 'quick-task', x: 0, y: 0, w: 6, h: 5 },+ { id: 'upcoming-tasks', x: 6, y: 0, w: 6, h: 10 },+ { id: 'cos', x: 0, y: 5, w: 6, h: 3 },+ { id: 'decision-log', x: 0, y: 8, w: 6, h: 3 },+ ],+ },+ {+ id: 'health',+ name: 'Health',+ widgets: ['death-clock', 'goal-progress', 'activity-streak', 'quick-brain', 'hourly-activity'],+ grid: [+ { id: 'death-clock', x: 0, y: 0, w: 4, h: 3 },+ { id: 'goal-progress', x: 4, y: 0, w: 5, h: 5 },+ { id: 'activity-streak', x: 9, y: 0, w: 3, h: 3 },+ { id: 'quick-brain', x: 0, y: 3, w: 4, h: 2 },+ { id: 'hourly-activity', x: 0, y: 5, w: 12, h: 4 },+ ],+ },+ {+ id: 'agent-watch',+ name: 'Agent Watch',+ widgets: ['cos', 'proactive-alerts', 'review-hub', 'system-health', 'decision-log'],+ grid: [+ { id: 'cos', x: 0, y: 0, w: 6, h: 5 },+ { id: 'proactive-alerts', x: 6, y: 0, w: 3, h: 3 },+ { id: 'review-hub', x: 9, y: 0, w: 3, h: 3 },+ { id: 'system-health', x: 6, y: 3, w: 6, h: 5 },+ { id: 'decision-log', x: 0, y: 5, w: 6, h: 3 },+ ],+ },+];+const DEFAULT_LAYOUTS = [{id: 'default',@@ -119,6 +162,7 @@ const DEFAULT_LAYOUTS = [{ id: 'apps', x: 0, y: 10, w: 12, h: 11 },],},+ ...INTENT_LAYOUTS.map((l) => ({ ...l, builtIn: true })),];const DEFAULT_STATE = {@@ -145,6 +189,26 @@ export const GRID_COLS = 12;export const GRID_ROW_MAX = 200;export const GRID_ITEM_H_MAX = 50;+// Time-window auto-activation: HH:MM strings (24h). When a layout carries an+// 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$/;++// Sanitize a layout's activateWindow. Returns null for any malformed shape+// (missing fields, non-string types, off-format strings). A null result+// strips the field on read so a hand-edited JSON with garbage can't+// accidentally drive an auto-switch. start === end collapses to null —+// a zero-length window can never match.+const sanitizeActivateWindow = (w) => {+ if (!w || typeof w !== 'object') return null;+ if (typeof w.start !== 'string' || typeof w.end !== 'string') return null;+ if (!TIME_STRING_RE.test(w.start) || !TIME_STRING_RE.test(w.end)) return null;+ if (w.start === w.end) return null;+ return { start: w.start, end: w.end };+};+// Clamp a single grid item to valid bounds. Returns null when the entry is// unusable (missing id, non-numeric coords, etc.). Numeric fields are// floored before clamping so JSON containing decimals can't smuggle in@@ -203,7 +267,8 @@ const sanitizeLayout = (l) => {grid.push(item);}}- return { id: l.id, name, builtIn: BUILTIN_IDS.has(l.id), widgets, grid };+ const activateWindow = sanitizeActivateWindow(l.activateWindow);+ return { id: l.id, name, builtIn: BUILTIN_IDS.has(l.id), widgets, grid, activateWindow };};// Bundled so clients can enforce the same limits without duplicating magic@@ -256,9 +321,31 @@ export async function saveLayout(layout) {// produce a new `ops` that sanitizeLayout() later treats as built-in while// the write-path echoed `builtIn: false` to the client.const builtIn = BUILTIN_IDS.has(layout.id);+ // Partial-aware merge: `activateWindow` is preserved when the caller+ // doesn't include the key, but cleared when the caller sends `null`. The+ // existing editor's saveLayout() doesn't send activateWindow, so a vanilla+ // widget edit must NOT wipe a previously-configured morning window.+ // Mirrors the "absent vs intentionally empty" convention in CLAUDE.md.+ const existing = idx >= 0 ? state.layouts[idx] : null;+ const buildEntry = () => {+ const entry = {+ id: layout.id,+ name: layout.name,+ builtIn,+ widgets: layout.widgets,+ grid: layout.grid ?? [],+ };+ // `undefined` (key absent OR set undefined) means "preserve"; `null` is+ // the explicit clear. Spread alone would clobber existing.activateWindow+ // with undefined when the caller omits the key.+ entry.activateWindow = layout.activateWindow !== undefined+ ? layout.activateWindow+ : (existing?.activateWindow ?? null);+ return entry;+ };const merged = idx >= 0- ? state.layouts.map((l, i) => i === idx ? { ...l, ...layout, builtIn } : l)- : [...state.layouts, { ...layout, builtIn }];+ ? state.layouts.map((l, i) => i === idx ? buildEntry() : l)+ : [...state.layouts, buildEntry()];const next = { activeLayoutId: state.activeLayoutId, layouts: merged };await atomicWrite(STATE_PATH, next);return { ...next, limits: LIMITS };diff --git a/server/services/dashboardLayouts.test.js b/server/services/dashboardLayouts.test.jsnew file mode 100644index 0000000000..ddd3d8b1d6--- /dev/null+++ b/server/services/dashboardLayouts.test.js@@ -0,0 +1,131 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, mkdirSync, existsSync, unlinkSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++// The service captures STATE_PATH at module-load time, so the scratch dir+// must exist before the import resolves. vi.hoisted runs before any imports+// (including the mocked module), so we mint the dir there and just clear+// its contents between tests.+const scratch = vi.hoisted(() => {+ const { mkdtempSync: mk, mkdirSync: mkd } = require('fs');+ const { tmpdir: tmp } = require('os');+ const { join: j } = require('path');+ const dir = mk(j(tmp(), 'dashboard-svc-'));+ mkd(j(dir, 'data'), { recursive: true });+ return { dir };+});+vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return {+ ...actual,+ PATHS: { ...actual.PATHS, data: join(scratch.dir, 'data') },+ };+});++import * as svc from './dashboardLayouts.js';++const STATE_FILE = join(scratch.dir, 'data', 'dashboard-layouts.json');+const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2));++describe('dashboardLayouts service', () => {+ beforeEach(() => {+ // Each test starts with a clean state file. The dir itself is reused.+ if (existsSync(STATE_FILE)) unlinkSync(STATE_FILE);+ });++ afterEach(() => {});++ describe('saveLayout — activateWindow merge behavior', () => {+ const stateFile = () => STATE_FILE;++ it('preserves activateWindow when the caller omits the key', async () => {+ writeJson(stateFile(), {+ activeLayoutId: 'morning',+ layouts: [+ { id: 'morning', name: 'Morning', builtIn: false, widgets: ['cos'], grid: [], activateWindow: { start: '06:00', end: '11:00' } },+ ],+ });+ // Vanilla edit: rename only. The caller doesn't know about activateWindow.+ await svc.saveLayout({ id: 'morning', name: 'Morning v2', widgets: ['cos'], grid: [] });+ const after = await svc.getState();+ const found = after.layouts.find((l) => l.id === 'morning');+ expect(found.name).toBe('Morning v2');+ expect(found.activateWindow).toEqual({ start: '06:00', end: '11:00' });+ });++ it('clears activateWindow when the caller sends null', async () => {+ writeJson(stateFile(), {+ activeLayoutId: 'morning',+ layouts: [+ { id: 'morning', name: 'Morning', builtIn: false, widgets: ['cos'], grid: [], activateWindow: { start: '06:00', end: '11:00' } },+ ],+ });+ await svc.saveLayout({ id: 'morning', name: 'Morning', widgets: ['cos'], grid: [], activateWindow: null });+ const after = await svc.getState();+ const found = after.layouts.find((l) => l.id === 'morning');+ expect(found.activateWindow).toBe(null);+ });++ it('sets activateWindow when the caller provides one', async () => {+ writeJson(stateFile(), {+ activeLayoutId: 'morning',+ layouts: [+ { id: 'morning', name: 'Morning', builtIn: false, widgets: ['cos'], grid: [] },+ ],+ });+ await svc.saveLayout({+ id: 'morning',+ name: 'Morning',+ widgets: ['cos'],+ grid: [],+ activateWindow: { start: '07:00', end: '10:00' },+ });+ const after = await svc.getState();+ const found = after.layouts.find((l) => l.id === 'morning');+ expect(found.activateWindow).toEqual({ start: '07:00', end: '10:00' });+ });++ it('drops malformed activateWindow on read', async () => {+ // Hand-edit produces garbage shapes — sanitizer must null them out.+ writeJson(stateFile(), {+ activeLayoutId: 'busted',+ layouts: [+ { id: 'busted', name: 'Busted', builtIn: false, widgets: ['cos'], grid: [], activateWindow: { start: '25:99', end: '11:00' } },+ ],+ });+ const after = await svc.getState();+ const found = after.layouts.find((l) => l.id === 'busted');+ expect(found.activateWindow).toBe(null);+ });+ });++ describe('saveLayout — surfaces builtIn correctly for new ids', () => {+ it('persists builtIn=true for a built-in id (deep-work) when seeded through saveLayout', async () => {+ // A fresh state file is fine — getState() will seed defaults, then we save.+ await svc.saveLayout({ id: 'deep-work', name: 'Deep Work renamed', widgets: ['cos'], grid: [] });+ const after = await svc.getState();+ const found = after.layouts.find((l) => l.id === 'deep-work');+ expect(found?.builtIn).toBe(true);+ });+ });++ describe('built-in layouts ship with the three new intent variants', () => {+ it('seeds deep-work, health, agent-watch on first read', async () => {+ const state = await svc.getState();+ const ids = state.layouts.map((l) => l.id);+ expect(ids).toContain('deep-work');+ expect(ids).toContain('health');+ expect(ids).toContain('agent-watch');+ // The new built-ins should be flagged so the editor refuses to delete them.+ expect(state.layouts.find((l) => l.id === 'deep-work').builtIn).toBe(true);+ });++ it('does not write the state file on first read (defaults are in-memory)', async () => {+ // getState() doesn't write — only saveLayout / setActive / delete do.+ // Verify by reading getState() and confirming no file got written.+ await svc.getState();+ expect(existsSync(STATE_FILE)).toBe(false);+ });+ });+});