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: customizable dashboard with saved layouts
Adam Eivybaf6052effa5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 3d9e456f8f..a868a36554 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -11,6 +11,12 @@Files: `server/lib/navManifest.js` (new), `server/routes/palette.js` (new), `server/services/voice/tools.js` (refactored), `server/index.js` (mounts `/api/palette`), `client/src/services/apiPalette.js` (new), `client/src/components/CmdKSearch.jsx` (palette behavior), `client/src/components/KeyboardHelp.jsx` (updated copy). Tests: `server/lib/navManifest.test.js`, `server/routes/palette.test.js`.+- **Customizable Dashboard with Saved Layouts** — the Dashboard is no longer a static hardcoded widget list. A widget registry (`client/src/components/dashboard/widgetRegistry.jsx`) describes each tile (`{ id, label, Component, width, gate? }`) and the Dashboard renders the active layout's ordered widget list over a 12-column grid. Four built-in layouts ship: **Everything** (the original), **Focus** (quick-task + cos + upcoming), **Morning Review** (alerts + upcoming + review-hub + goals + death-clock), **Ops** (system-health + cos + backup + apps + quick-stats). New layouts can be created via the layout picker → "Edit layouts…" → Save as new. Widgets can be added/removed per layout, reordered with ↑/↓ buttons (keyboard- and touch-accessible), and gated so data-dependent widgets (apps grid, streak, hourly activity) auto-hide when there's nothing to show. Persisted to `data/dashboard-layouts.json` via `GET/PUT/DELETE /api/dashboard/layouts`; built-in layouts are protected from deletion. Inline-state delete/duplicate confirmations — no `window.confirm`/`prompt`.++ **Palette integration**: `⌘K` synthesizes one command per layout ("Dashboard: Focus", "Dashboard: Ops", etc.) so users can switch layouts from anywhere with a keystroke. Layouts re-fetch on every palette open so newly-created or renamed layouts show up without a page remount.++ Files: `server/services/dashboardLayouts.js` (new), `server/routes/dashboardLayouts.js` (new), `server/routes/dashboardLayouts.test.js` (new, 7 tests), `server/index.js` (mounts route), `client/src/services/apiDashboard.js` (new), `client/src/components/dashboard/{widgetRegistry.jsx,LayoutPicker.jsx,LayoutEditor.jsx,builtins/*}` (new), `client/src/pages/Dashboard.jsx` (fully rewritten), `client/src/components/CmdKSearch.jsx` (layouts section), `CLAUDE.md` ("Dashboard Widgets & Layouts" section with widget-entry contract).+## Changed- **Command palette cleanup pass** — post-review simplify: `normalizeLabel` is exported once from `navManifest.js` and imported by `voice/tools.js` (was duplicated verbatim); `getToolMetadata(id)` added to `voice/tools.js` so `routes/palette.js` no longer reaches through the OpenAI-shaped function spec; palette manifest frozen at module load (`buildActionManifest` no longer runs per request) with `Cache-Control: private, max-age=300`. Client scorer precomputes lowercased `_label`/`_aliases`/`_keywords`/`_section` so per-keystroke fuzzy matching does zero re-lowercasing over the 117-entry manifest. `CmdKSearch.jsx` trimmed ~80 lines: collapsed the triple `useMemo` chain, merged `renderCommandRow` + inline search-result row into a single `renderRow`/`renderGroup` pair, flattened `dispatchCommand` into a `DISPATCH` lookup table, dropped the dead `running` state, removed two `.catch()` error-swallows (errors now propagate to the central toast handler per CLAUDE.md), cleared `resultRefs` on close. `ALIAS_KEYS` cached once in `resolveNavCommand`. Decorative section-banner comments and narration comments removed across the new files.diff --git a/CLAUDE.md b/CLAUDE.mdindex 0bfd3f652e..4b160822f6 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -95,6 +95,19 @@ Fail-fast guards at module load catch missing fields, non-slash paths, and dupli**Tests:** `server/lib/navManifest.test.js` asserts shape invariants + alias resolution; `server/routes/palette.test.js` asserts the manifest endpoint + action dispatch + whitelist enforcement. Any new entry is automatically covered by the shape-invariant tests.+### Dashboard Widgets & Layouts++Dashboard widgets are registered in `client/src/components/dashboard/widgetRegistry.jsx` — each entry has `{ id, label, Component, width, gate? }`. The Dashboard page renders the active layout's widget list from this registry; named layouts persist in `data/dashboard-layouts.json` and are managed via `GET/PUT/DELETE /api/dashboard/layouts`. Built-in layouts (`default`, `focus`, `morning-review`, `ops`) are seeded on first read and cannot be deleted.++**When adding a new dashboard widget:**+1. Add a `{ id, label, Component, width, gate? }` entry to `WIDGETS` in `widgetRegistry.jsx`. Use a stable `id` (kebab-case) — it's the contract stored in layouts.+2. If the widget needs dashboard data (apps/usage/health), read it from the `dashboardState` prop — do NOT issue a duplicate fetch from inside the widget.+3. If the widget only makes sense in some cases (e.g. only when apps exist), add a `gate: (state) => boolean` predicate.+4. Add the widget id to the built-in `default` layout in `server/services/dashboardLayouts.js` if it should appear out of the box.+5. Users can toggle widgets on/off per layout via the Dashboard's layout picker → Edit.++Switching layouts is also wired into the `⌘K` palette — it synthesizes a `Dashboard: <name>` command per layout at palette-open time, so any layout the user creates is instantly keyboard-reachable without further registration.+### Slashdo Commands (`lib/slashdo`)PortOS bundles [slashdo](https://github.com/atomantic/slashdo) as a git submodule at `lib/slashdo`. This provides slash commands (`/do:review`, `/do:pr`, `/do:push`, `/do:release`, etc.) and shared libraries without requiring a separate global install.diff --git a/PLAN.md b/PLAN.mdindex 710702b52b..86dbf02b98 100644--- a/PLAN.md+++ b/PLAN.md@@ -47,7 +47,9 @@ Three high-value work items drawn from an inventory of the current app surface (----### 2. Customizable Dashboard with Saved Layouts+### 2. Customizable Dashboard with Saved Layouts ✅ SHIPPED 2026-04-24++> Widget registry at `client/src/components/dashboard/widgetRegistry.jsx` (13 widgets + 4 built-in data-dependent ones). Layouts persist to `data/dashboard-layouts.json` via `GET/PUT/DELETE /api/dashboard/layouts`. Built-in layouts seeded on first read: `default` (Everything), `focus`, `morning-review`, `ops`. Keyboard-accessible layout editor with up/down reorder buttons, inline add-widget picker, inline confirm-before-delete, rename + "save as new" in-line prompts (no `window.confirm`/`prompt`). Palette integration: `⌘K` → any layout name switches instantly. Drag-and-drop deferred — reorder buttons are fully functional and a11y-correct without a new dependency. See CLAUDE.md "Dashboard Widgets & Layouts" for the widget contract.**Problem.** `client/src/pages/Dashboard.jsx` hard-codes the widget list: `BackupWidget`, `SystemHealthWidget`, `CosDashboardWidget`, `GoalProgressWidget`, `UpcomingTasksWidget`, `DecisionLogWidget`, `DeathClockWidget`, `ProactiveAlertsWidget`, `QuickBrainCapture`, `QuickTaskWidget`, `ReviewHubCard`. Every user-visible feature competes for space on the same grid; nothing can be hidden, reordered, or scoped to context. Already called out in `PLAN.md` Future Ideas as "Dashboard Customization — Drag-and-drop widgets, named layouts."diff --git a/client/src/components/CmdKSearch.jsx b/client/src/components/CmdKSearch.jsxindex ae848edff0..04e2d9cec2 100644--- a/client/src/components/CmdKSearch.jsx+++ b/client/src/components/CmdKSearch.jsx@@ -1,10 +1,10 @@import { useState, useEffect, useRef, useCallback, useMemo } from 'react';import { createPortal } from 'react-dom';import { useNavigate } from 'react-router-dom';-import { Brain, Cpu, Package, History, HeartPulse, Search, Loader2, Navigation, Play } from 'lucide-react';+import { Brain, Cpu, Package, History, HeartPulse, Search, Loader2, Navigation, Play, LayoutGrid } from 'lucide-react';import { useCmdKSearch } from '../hooks/useCmdKSearch';import { useScrollLock } from '../hooks/useScrollLock';-import { search, getPaletteManifest, runPaletteAction } from '../services/api';+import { search, getPaletteManifest, runPaletteAction, getDashboardLayouts, setActiveDashboardLayout } from '../services/api';import toast from './ui/Toast';import { modKey } from '../utils/platform';@@ -86,13 +86,29 @@ export default function CmdKSearch() {}}, [open]);+ // Manifest (nav + actions) is cached for the lifetime of the component —+ // static at module load on the server. Dashboard layouts change whenever+ // the user creates/renames one, so they're re-fetched on every open to+ // avoid a stale list on the same page mount.useEffect(() => {- if (!open || manifest) return;- getPaletteManifest().then((data) => {- setManifest({- nav: (data?.nav || []).map(precompute),- actions: (data?.actions || []).map(precompute),- });+ if (!open) return;+ const manifestPromise = manifest+ ? Promise.resolve({ nav: manifest.nav, actions: manifest.actions })+ : getPaletteManifest().then((data) => ({+ nav: (data?.nav || []).map(precompute),+ actions: (data?.actions || []).map(precompute),+ }));+ Promise.all([manifestPromise, getDashboardLayouts()]).then(([m, dashboards]) => {+ const layouts = (dashboards?.layouts || []).map((l) => precompute({+ id: `layout.${l.id}`,+ layoutId: l.id,+ layoutName: l.name,+ label: `Dashboard: ${l.name}`,+ section: 'Layouts',+ aliases: ['layout', l.id, ...l.name.toLowerCase().split(/\s+/)],+ keywords: ['dashboard', 'layout', 'view'],+ }));+ setManifest({ nav: m.nav, actions: m.actions, layouts });});}, [open, manifest]);@@ -116,12 +132,12 @@ export default function CmdKSearch() {}, [searchResults, query]);const combined = useMemo(() => {- if (!manifest) return [];+ if (!manifest) return { nav: [], actions: [], layouts: [], commandCount: 0 };const q = query.trim().toLowerCase();if (!q) {const nav = manifest.nav.filter((c) => DEFAULT_NAV_IDS.has(c.id)).map((c) => ({ ...c, kind: 'nav' }));const actions = manifest.actions.filter((a) => DEFAULT_ACTION_IDS.has(a.id)).map((a) => ({ ...a, kind: 'action' }));- return { nav, actions, commandCount: nav.length + actions.length };+ return { nav, actions, layouts: [], commandCount: nav.length + actions.length };}const rank = (items, max) => items.map((c) => ({ cmd: c, score: scoreCommand(c, q) }))@@ -131,7 +147,8 @@ export default function CmdKSearch() {.map((x) => x.cmd);const nav = rank(manifest.nav, 8).map((c) => ({ ...c, kind: 'nav' }));const actions = rank(manifest.actions, 5).map((a) => ({ ...a, kind: 'action' }));- return { nav, actions, commandCount: nav.length + actions.length };+ const layouts = rank(manifest.layouts || [], 5).map((l) => ({ ...l, kind: 'layout' }));+ return { nav, actions, layouts, commandCount: nav.length + actions.length + layouts.length };}, [manifest, query]);const flatSearchResults = useMemo(@@ -143,7 +160,7 @@ export default function CmdKSearch() {);const focusable = useMemo(- () => [...combined.nav, ...combined.actions, ...flatSearchResults],+ () => [...combined.nav, ...combined.actions, ...combined.layouts, ...flatSearchResults],[combined, flatSearchResults]);@@ -157,6 +174,12 @@ export default function CmdKSearch() {const DISPATCH = useMemo(() => ({nav: (item) => { navigate(item.path); close(); },search: (item) => { navigate(item.url); close(); },+ layout: async (item) => {+ await setActiveDashboardLayout(item.layoutId);+ navigate('/');+ toast.success(`Switched to "${item.layoutName}"`);+ close();+ },action: async (item) => {const required = item.parameters?.required || [];if (required.length > 0) {@@ -278,6 +301,14 @@ export default function CmdKSearch() {))}+ {renderGroup(+ <LayoutGrid size={14} />,+ 'Dashboard layout',+ combined.layouts.map((l) =>+ renderRow(l, { icon: LayoutGrid, title: l.label, subtitle: 'Switch dashboard layout', badge: 'LAYOUT' })+ )+ )}+{loading && (<div className="flex items-center justify-center py-4"><Loader2 size={18} className="animate-spin text-gray-400" />diff --git a/client/src/components/dashboard/LayoutEditor.jsx b/client/src/components/dashboard/LayoutEditor.jsxnew file mode 100644index 0000000000..584c48ac2a--- /dev/null+++ b/client/src/components/dashboard/LayoutEditor.jsx@@ -0,0 +1,241 @@+import { useState, useEffect, useRef, useCallback } from 'react';+import { createPortal } from 'react-dom';+import { X, ArrowUp, ArrowDown, Trash2, Plus, Save } from 'lucide-react';+import { useScrollLock } from '../../hooks/useScrollLock';+import { WIDGETS, WIDGETS_BY_ID } from './widgetRegistry.jsx';+import toast from '../ui/Toast';++// Keyboard-first editor. No drag-and-drop dep — reorder uses up/down buttons+// (keyboard + touch friendly). Delete and "save as new" use inline state+// instead of window.confirm/prompt per project convention.+export default function LayoutEditor({ layouts, activeLayoutId, onClose, onSave, onDelete, onDuplicate }) {+ const [editingId, setEditingId] = useState(activeLayoutId);+ const editing = layouts.find((l) => l.id === editingId);+ const [widgets, setWidgets] = useState(editing?.widgets ?? []);+ const [name, setName] = useState(editing?.name ?? '');+ const [dirty, setDirty] = useState(false);+ const [mode, setMode] = useState('idle'); // 'idle' | 'duplicate' | 'delete'+ const [dupName, setDupName] = useState('');+ const closeRef = useRef(null);++ useScrollLock(true);++ useEffect(() => {+ requestAnimationFrame(() => closeRef.current?.focus());+ }, []);++ // Rehydrate draft state ONLY when the user switches layouts. Keyed on+ // `layouts` too would clobber in-flight edits every time the parent+ // refreshes the list after save — surprised the user on save-as-new.+ useEffect(() => {+ const cur = layouts.find((l) => l.id === editingId);+ if (!cur) return;+ setWidgets(cur.widgets);+ setName(cur.name);+ setDirty(false);+ setMode('idle');+ setDupName('');+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [editingId]);++ const close = useCallback(() => { onClose(); }, [onClose]);++ const onKeyDown = (e) => {+ if (e.key === 'Escape') close();+ };++ const move = (index, delta) => {+ setWidgets((prev) => {+ const target = index + delta;+ if (target < 0 || target >= prev.length) return prev;+ const next = [...prev];+ [next[index], next[target]] = [next[target], next[index]];+ return next;+ });+ setDirty(true);+ };++ const remove = (id) => {+ setWidgets((prev) => prev.filter((w) => w !== id));+ setDirty(true);+ };++ const add = (id) => {+ if (widgets.includes(id)) return;+ setWidgets((prev) => [...prev, id]);+ setDirty(true);+ };++ const save = async () => {+ const trimmed = name.trim();+ if (!trimmed) { toast.error('Name required'); return; }+ await onSave({ id: editingId, name: trimmed, widgets });+ setDirty(false);+ toast.success('Layout saved');+ };++ const commitDuplicate = async () => {+ const trimmed = dupName.trim();+ if (!trimmed) { toast.error('Name required'); return; }+ const baseId = trimmed.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');+ if (!baseId) { toast.error('Use letters/numbers in the name'); return; }+ const existingIds = new Set(layouts.map((l) => l.id));+ let id = baseId;+ let n = 2;+ while (existingIds.has(id)) id = `${baseId}-${n++}`;+ await onDuplicate({ id, name: trimmed, widgets });+ setEditingId(id);+ setMode('idle');+ toast.success('New layout created');+ };++ const commitDelete = async () => {+ await onDelete(editingId);+ const remaining = layouts.filter((l) => l.id !== editingId);+ setMode('idle');+ if (remaining.length > 0) setEditingId(remaining[0].id);+ else close();+ };++ const available = WIDGETS.filter((w) => !widgets.includes(w.id));++ const overlay = (+ <div className="fixed inset-0 z-[9999] flex items-start justify-center pt-[10vh]" onKeyDown={onKeyDown}>+ <div className="absolute inset-0 bg-black/60" onClick={close} aria-hidden="true" />++ <div role="dialog" aria-modal="true" aria-labelledby="layout-editor-title" className="relative w-full max-w-3xl mx-4 bg-port-card rounded-xl border border-port-border shadow-2xl overflow-hidden">+ <div className="flex items-center justify-between px-5 py-4 border-b border-port-border">+ <h2 id="layout-editor-title" className="text-sm font-semibold text-white">Edit Layouts</h2>+ <button ref={closeRef} onClick={close} className="p-1 text-gray-500 hover:text-white transition-colors rounded" aria-label="Close">+ <X size={16} />+ </button>+ </div>++ <div className="grid grid-cols-1 sm:grid-cols-3 gap-0 max-h-[70vh] overflow-hidden">+ <div className="border-r border-port-border overflow-y-auto">+ {layouts.map((l) => (+ <button+ key={l.id}+ onClick={() => setEditingId(l.id)}+ className={`w-full text-left px-4 py-2 text-sm border-l-2 ${+ l.id === editingId ? 'border-port-accent bg-white/5 text-white' : 'border-transparent text-gray-400 hover:bg-white/5 hover:text-white'+ }`}+ >+ <div className="truncate">{l.name}</div>+ {l.builtIn && <div className="text-[10px] text-gray-500 uppercase">Built-in</div>}+ </button>+ ))}+ </div>++ <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>+ <input+ type="text"+ value={name}+ onChange={(e) => { setName(e.target.value); setDirty(true); }}+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:border-port-accent outline-hidden"+ />+ </div>++ <div>+ <h3 className="text-xs text-gray-400 uppercase tracking-wide mb-2">Widgets ({widgets.length})</h3>+ <ul className="space-y-1">+ {widgets.map((id, idx) => {+ const meta = WIDGETS_BY_ID[id];+ return (+ <li key={id} className="flex items-center gap-2 bg-port-bg border border-port-border rounded-lg px-3 py-2">+ <span className="flex-1 text-sm text-white truncate">+ {meta?.label ?? id}+ {!meta && <span className="ml-2 text-xs text-port-warning">(unknown — skipped)</span>}+ </span>+ <button onClick={() => move(idx, -1)} disabled={idx === 0} className="p-1 rounded text-gray-400 hover:text-white disabled:opacity-30 disabled:hover:text-gray-400" aria-label="Move up"><ArrowUp size={14} /></button>+ <button onClick={() => move(idx, 1)} disabled={idx === widgets.length - 1} className="p-1 rounded text-gray-400 hover:text-white disabled:opacity-30 disabled:hover:text-gray-400" aria-label="Move down"><ArrowDown size={14} /></button>+ <button onClick={() => remove(id)} className="p-1 rounded text-gray-400 hover:text-port-error" aria-label="Remove widget"><Trash2 size={14} /></button>+ </li>+ );+ })}+ {widgets.length === 0 && (+ <li className="text-sm text-gray-500 py-4 text-center">No widgets — add some below</li>+ )}+ </ul>+ </div>++ {available.length > 0 && (+ <div>+ <h3 className="text-xs text-gray-400 uppercase tracking-wide mb-2">Add widget</h3>+ <div className="flex flex-wrap gap-2">+ {available.map((w) => (+ <button+ key={w.id}+ onClick={() => add(w.id)}+ className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg bg-port-bg border border-port-border text-xs text-gray-300 hover:border-port-accent hover:text-white transition-colors"+ >+ <Plus size={12} />+ <span>{w.label}</span>+ </button>+ ))}+ </div>+ </div>+ )}+ </div>+ </div>++ <div className="flex flex-col gap-2 px-5 py-3 border-t border-port-border">+ {mode === 'duplicate' && (+ <div className="flex items-center gap-2">+ <input+ type="text"+ value={dupName}+ autoFocus+ onChange={(e) => setDupName(e.target.value)}+ onKeyDown={(e) => { if (e.key === 'Enter') commitDuplicate(); if (e.key === 'Escape') setMode('idle'); }}+ placeholder="Name for new layout"+ className="flex-1 bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:border-port-accent outline-hidden"+ />+ <button onClick={commitDuplicate} className="px-3 py-1.5 text-sm rounded-lg bg-port-accent text-white hover:bg-port-accent/80">Create</button>+ <button onClick={() => setMode('idle')} className="px-3 py-1.5 text-sm text-gray-300 hover:text-white rounded-lg border border-port-border">Cancel</button>+ </div>+ )}+ {mode === 'delete' && (+ <div className="flex items-center gap-2">+ <span className="flex-1 text-sm text-port-error">Delete “{editing?.name}”? This can't be undone.</span>+ <button onClick={commitDelete} className="px-3 py-1.5 text-sm rounded-lg bg-port-error text-white hover:bg-port-error/80">Delete</button>+ <button onClick={() => setMode('idle')} className="px-3 py-1.5 text-sm text-gray-300 hover:text-white rounded-lg border border-port-border">Cancel</button>+ </div>+ )}+ {mode === 'idle' && (+ <div className="flex items-center justify-between gap-2">+ <div className="flex items-center gap-2">+ <button+ onClick={() => { setDupName(`${name} (copy)`); setMode('duplicate'); }}+ className="px-3 py-1.5 text-sm text-gray-300 hover:text-white rounded-lg border border-port-border hover:border-gray-600"+ >+ Save as new…+ </button>+ {editing && !editing.builtIn && (+ <button+ onClick={() => setMode('delete')}+ className="px-3 py-1.5 text-sm text-port-error hover:bg-port-error/10 rounded-lg border border-port-border"+ >+ Delete+ </button>+ )}+ </div>+ <button+ onClick={save}+ disabled={!dirty}+ className="flex items-center gap-1.5 px-4 py-1.5 text-sm rounded-lg bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-40"+ >+ <Save size={14} />+ <span>Save</span>+ </button>+ </div>+ )}+ </div>+ </div>+ </div>+ );++ return createPortal(overlay, document.body);+}diff --git a/client/src/components/dashboard/LayoutPicker.jsx b/client/src/components/dashboard/LayoutPicker.jsxnew file mode 100644index 0000000000..8dc0ed3af5--- /dev/null+++ b/client/src/components/dashboard/LayoutPicker.jsx@@ -0,0 +1,57 @@+import { useState, useRef, useEffect } from 'react';+import { LayoutGrid, Check, Pencil } from 'lucide-react';++export default function LayoutPicker({ layouts, activeLayoutId, onSelect, onEdit }) {+ const [open, setOpen] = useState(false);+ const ref = useRef(null);+ const active = layouts.find((l) => l.id === activeLayoutId) || layouts[0];++ useEffect(() => {+ if (!open) return;+ const onDocClick = (e) => { if (!ref.current?.contains(e.target)) setOpen(false); };+ document.addEventListener('mousedown', onDocClick);+ return () => document.removeEventListener('mousedown', onDocClick);+ }, [open]);++ return (+ <div ref={ref} className="relative">+ <button+ onClick={() => setOpen((v) => !v)}+ className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-port-card border border-port-border hover:border-gray-600 transition-colors text-sm text-gray-300 hover:text-white min-h-[40px]"+ title="Switch dashboard layout"+ >+ <LayoutGrid size={14} />+ <span className="hidden sm:inline">{active?.name || 'Layout'}</span>+ </button>++ {open && (+ <div className="absolute right-0 mt-1 w-56 bg-port-card border border-port-border rounded-lg shadow-2xl overflow-hidden z-50">+ <div className="py-1">+ {layouts.map((l) => (+ <button+ key={l.id}+ onClick={() => { onSelect(l.id); setOpen(false); }}+ className={`w-full text-left flex items-center gap-2 px-3 py-2 text-sm hover:bg-white/5 ${+ l.id === activeLayoutId ? 'text-white' : 'text-gray-300'+ }`}+ >+ {l.id === activeLayoutId ? <Check size={14} className="text-port-success" /> : <span className="w-3.5" />}+ <span className="flex-1 truncate">{l.name}</span>+ {l.builtIn && <span className="text-[10px] text-gray-500 uppercase">Built-in</span>}+ </button>+ ))}+ </div>+ <div className="border-t border-port-border">+ <button+ onClick={() => { setOpen(false); onEdit(); }}+ className="w-full flex items-center gap-2 px-3 py-2 text-sm text-gray-300 hover:bg-white/5 hover:text-white"+ >+ <Pencil size={14} />+ <span>Edit layouts…</span>+ </button>+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/dashboard/builtins/ActivityStreakWidget.jsx b/client/src/components/dashboard/builtins/ActivityStreakWidget.jsxnew file mode 100644index 0000000000..afa62b104d--- /dev/null+++ b/client/src/components/dashboard/builtins/ActivityStreakWidget.jsx@@ -0,0 +1,43 @@+export default function ActivityStreakWidget({ dashboardState }) {+ const { usage } = dashboardState;+ if (!usage) return null;+ return (+ <div className="bg-port-card border border-port-border rounded-xl p-4">+ <div className="flex items-center gap-3 mb-3">+ <div className="text-2xl" aria-hidden="true">+ {usage.currentStreak >= 7 ? '🔥' : usage.currentStreak >= 3 ? '⚡' : '✨'}+ </div>+ <div>+ <div className="text-xl font-bold text-white">+ {usage.currentStreak} day{usage.currentStreak !== 1 ? 's' : ''}+ </div>+ <div className="text-xs text-gray-500">Current streak</div>+ </div>+ {usage.longestStreak > usage.currentStreak && (+ <div className="ml-auto text-right">+ <div className="text-sm font-semibold text-port-accent">{usage.longestStreak} days</div>+ <div className="text-xs text-gray-500">Best</div>+ </div>+ )}+ {usage.currentStreak === usage.longestStreak && usage.currentStreak > 0 && (+ <div className="ml-auto px-2 py-1 bg-port-success/20 text-port-success text-xs rounded-full">+ Personal best!+ </div>+ )}+ </div>+ <div className="flex gap-1">+ {usage.last7Days?.map((day) => (+ <div+ key={day.date}+ className={`flex-1 h-2 rounded-full ${day.sessions > 0 ? 'bg-port-success' : 'bg-port-border'}`}+ title={`${day.label}: ${day.sessions} sessions`}+ />+ ))}+ </div>+ <div className="mt-1 flex justify-between text-xs text-gray-500">+ <span>7d ago</span>+ <span>Today</span>+ </div>+ </div>+ );+}diff --git a/client/src/components/dashboard/builtins/AppsGridWidget.jsx b/client/src/components/dashboard/builtins/AppsGridWidget.jsxnew file mode 100644index 0000000000..ccf475dafc--- /dev/null+++ b/client/src/components/dashboard/builtins/AppsGridWidget.jsx@@ -0,0 +1,28 @@+import { Link } from 'react-router-dom';+import AppTile from '../../AppTile';++export default function AppsGridWidget({ dashboardState }) {+ const { apps, sortedApps, refetch } = dashboardState;+ if (apps.length === 0) {+ return (+ <div className="bg-port-card border border-port-border rounded-xl p-8 sm:p-12 text-center">+ <div className="text-4xl mb-4">📦</div>+ <h3 className="text-xl font-semibold text-white mb-2">No apps registered</h3>+ <p className="text-gray-500 mb-6">Register your first app to get started</p>+ <Link+ to="/apps/create"+ className="inline-flex items-center justify-center px-6 py-3 min-h-10 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"+ >+ Add App+ </Link>+ </div>+ );+ }+ return (+ <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-3">+ {sortedApps.map((app) => (+ <AppTile key={app.id} app={app} onUpdate={refetch} />+ ))}+ </div>+ );+}diff --git a/client/src/components/dashboard/builtins/HourlyActivityWidget.jsx b/client/src/components/dashboard/builtins/HourlyActivityWidget.jsxnew file mode 100644index 0000000000..f3788640f1--- /dev/null+++ b/client/src/components/dashboard/builtins/HourlyActivityWidget.jsx@@ -0,0 +1,81 @@+export default function HourlyActivityWidget({ dashboardState }) {+ const hourlyActivity = dashboardState.usage?.hourlyActivity;+ if (!hourlyActivity) return null;++ const maxActivity = Math.max(...hourlyActivity, 1);+ const peakValue = Math.max(...hourlyActivity);+ const peakHours = hourlyActivity+ .map((val, idx) => ({ hour: idx, count: val }))+ .filter((h) => h.count === peakValue && h.count > 0);+ const totalSessions = hourlyActivity.reduce((sum, val) => sum + val, 0);++ const formatHour = (hour) => {+ if (hour === 0) return '12a';+ if (hour === 12) return '12p';+ return hour < 12 ? `${hour}a` : `${hour - 12}p`;+ };++ const getIntensityClass = (count) => {+ if (count === 0) return 'bg-port-border/30';+ const intensity = count / maxActivity;+ if (intensity >= 0.8) return 'bg-port-success';+ if (intensity >= 0.5) return 'bg-port-success/70';+ if (intensity >= 0.25) return 'bg-port-success/40';+ return 'bg-port-success/20';+ };++ const peakDescription = peakHours.length === 0 || peakValue === 0+ ? null+ : peakHours.length === 1+ ? `Peak: ${formatHour(peakHours[0].hour)} (${peakValue} sessions)`+ : `Peak hours: ${peakHours.slice(0, 3).map((h) => formatHour(h.hour)).join(', ')} (${peakValue} sessions each)`;++ if (totalSessions === 0) return null;++ return (+ <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6">+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 mb-4">+ <div className="flex items-center gap-3">+ <div className="text-2xl" aria-hidden="true">⏰</div>+ <div>+ <h3 className="text-lg font-semibold text-white">Activity by Hour</h3>+ <p className="text-sm text-gray-500">{totalSessions} total sessions tracked</p>+ </div>+ </div>+ {peakDescription && <div className="text-sm text-port-success">{peakDescription}</div>}+ </div>++ <div className="grid grid-cols-6 sm:grid-cols-12 gap-1.5 sm:gap-1" role="img" aria-label="Hourly activity heatmap">+ {hourlyActivity.map((count, hour) => (+ <div+ key={hour}+ className={`aspect-square rounded-xs ${getIntensityClass(count)} transition-colors cursor-default min-w-[20px] min-h-[20px]`}+ title={`${formatHour(hour)}: ${count} session${count !== 1 ? 's' : ''}`}+ aria-label={`${formatHour(hour)}: ${count} sessions`}+ />+ ))}+ </div>++ <div className="mt-2 grid grid-cols-6 sm:grid-cols-12 gap-1.5 sm:gap-1 text-xs text-gray-500">+ {hourlyActivity.map((_, hour) => (+ <div key={hour} className="text-center">+ <span className="hidden sm:inline">{hour % 3 === 0 ? formatHour(hour) : ''}</span>+ <span className="sm:hidden">{hour % 4 === 0 ? formatHour(hour) : ''}</span>+ </div>+ ))}+ </div>++ <div className="mt-4 flex items-center justify-end gap-2 text-xs text-gray-500">+ <span>Less</span>+ <div className="flex gap-1">+ <div className="w-4 h-4 sm:w-3 sm:h-3 rounded-xs bg-port-border/30" />+ <div className="w-4 h-4 sm:w-3 sm:h-3 rounded-xs bg-port-success/20" />+ <div className="w-4 h-4 sm:w-3 sm:h-3 rounded-xs bg-port-success/40" />+ <div className="w-4 h-4 sm:w-3 sm:h-3 rounded-xs bg-port-success/70" />+ <div className="w-4 h-4 sm:w-3 sm:h-3 rounded-xs bg-port-success" />+ </div>+ <span>More</span>+ </div>+ </div>+ );+}diff --git a/client/src/components/dashboard/builtins/QuickStatsWidget.jsx b/client/src/components/dashboard/builtins/QuickStatsWidget.jsxnew file mode 100644index 0000000000..d56aa82f72--- /dev/null+++ b/client/src/components/dashboard/builtins/QuickStatsWidget.jsx@@ -0,0 +1,26 @@+export default function QuickStatsWidget({ dashboardState }) {+ const { appStats } = dashboardState;+ return (+ <div className="bg-port-card border border-port-border rounded-xl p-4 h-full">+ <h3 className="text-sm font-semibold text-white mb-3">Quick Stats</h3>+ <div className="grid grid-cols-2 gap-2">+ <StatCard label="Total Apps" value={appStats.total} icon="📦" />+ <StatCard label="Online" value={appStats.online} icon="🟢" />+ <StatCard label="Stopped" value={appStats.stopped} icon="🟡" />+ <StatCard label="Offline" value={appStats.notStarted} icon="⚪" />+ </div>+ </div>+ );+}++function StatCard({ label, value, icon }) {+ return (+ <div className="bg-port-bg border border-port-border rounded-lg p-3" role="group" aria-label={`${label}: ${value}`}>+ <div className="flex items-center gap-2 mb-1">+ <span aria-hidden="true" className="text-base">{icon}</span>+ <span className="text-xs text-gray-500">{label}</span>+ </div>+ <div className="text-xl font-bold text-white">{value}</div>+ </div>+ );+}diff --git a/client/src/components/dashboard/widgetRegistry.jsx b/client/src/components/dashboard/widgetRegistry.jsxnew file mode 100644index 0000000000..91b072c6fb--- /dev/null+++ b/client/src/components/dashboard/widgetRegistry.jsx@@ -0,0 +1,44 @@+import BackupWidget from '../BackupWidget';+import SystemHealthWidget from '../SystemHealthWidget';+import CosDashboardWidget from '../CosDashboardWidget';+import GoalProgressWidget from '../GoalProgressWidget';+import UpcomingTasksWidget from '../UpcomingTasksWidget';+import DecisionLogWidget from '../DecisionLogWidget';+import DeathClockWidget from '../DeathClockWidget';+import ProactiveAlertsWidget from '../ProactiveAlertsWidget';+import QuickBrainCapture from '../QuickBrainCapture';+import QuickTaskWidget from '../QuickTaskWidget';+import ReviewHubCard from '../ReviewHubCard';+import AppsGridWidget from './builtins/AppsGridWidget';+import QuickStatsWidget from './builtins/QuickStatsWidget';+import ActivityStreakWidget from './builtins/ActivityStreakWidget';+import HourlyActivityWidget from './builtins/HourlyActivityWidget';++// Each entry: { id, label, Component, width, gate? }. `gate(state) => bool`+// skips the widget when it has nothing useful to show (e.g. no apps).+export const WIDGETS = [+ { id: 'quick-brain', label: 'Quick Brain Capture', Component: QuickBrainCapture, width: 'half' },+ { id: 'quick-task', label: 'Quick Task', Component: QuickTaskWidget, width: 'half' },+ { id: 'apps', label: 'Apps Grid', Component: AppsGridWidget, width: 'full' },+ { id: 'cos', label: 'Chief of Staff', Component: CosDashboardWidget, width: 'third' },+ { id: 'goal-progress', label: 'Goal Progress', Component: GoalProgressWidget, width: 'third' },+ { id: 'upcoming-tasks', label: 'Upcoming Tasks', Component: UpcomingTasksWidget, width: 'third' },+ { id: 'proactive-alerts', label: 'Proactive Alerts', Component: ProactiveAlertsWidget, width: 'quarter' },+ { id: 'review-hub', label: 'Review Hub', Component: ReviewHubCard, width: 'quarter' },+ { id: 'system-health', label: 'System Health', Component: SystemHealthWidget, width: 'quarter' },+ { id: 'backup', label: 'Backup', Component: BackupWidget, width: 'quarter' },+ { id: 'death-clock', label: 'Death Clock', Component: DeathClockWidget, width: 'quarter' },+ { id: 'quick-stats', label: 'Quick Stats', Component: QuickStatsWidget, width: 'quarter', gate: (s) => s.apps.length > 0 },+ { id: 'decision-log', label: 'Decision Log', Component: DecisionLogWidget, width: 'quarter' },+ { id: 'activity-streak', label: 'Activity Streak', Component: ActivityStreakWidget, width: 'third', gate: (s) => s.usage?.currentStreak > 0 || s.usage?.longestStreak > 0 },+ { id: 'hourly-activity', label: 'Activity by Hour', Component: HourlyActivityWidget, width: 'full', gate: (s) => !!s.usage?.hourlyActivity && s.usage.hourlyActivity.some((v) => v > 0) },+];++export const WIDGETS_BY_ID = Object.fromEntries(WIDGETS.map((w) => [w.id, w]));++export const WIDTH_CLASS = {+ full: 'col-span-12',+ half: 'col-span-12 md:col-span-6',+ third: 'col-span-12 md:col-span-6 lg:col-span-4',+ quarter: 'col-span-12 sm:col-span-6 lg:col-span-3',+};diff --git a/client/src/pages/Dashboard.jsx b/client/src/pages/Dashboard.jsxindex 6b101e9595..7a4f6bcafc 100644--- a/client/src/pages/Dashboard.jsx+++ b/client/src/pages/Dashboard.jsx@@ -1,21 +1,13 @@import { useState, useEffect, useCallback, useMemo } from 'react';import { Link } from 'react-router-dom';-import AppTile from '../components/AppTile';-import BackupWidget from '../components/BackupWidget';import BrailleSpinner from '../components/BrailleSpinner';-import SystemHealthWidget from '../components/SystemHealthWidget';-import CosDashboardWidget from '../components/CosDashboardWidget';-import GoalProgressWidget from '../components/GoalProgressWidget';-import UpcomingTasksWidget from '../components/UpcomingTasksWidget';-import DecisionLogWidget from '../components/DecisionLogWidget';-import DeathClockWidget from '../components/DeathClockWidget';-import ProactiveAlertsWidget from '../components/ProactiveAlertsWidget';-import QuickBrainCapture from '../components/QuickBrainCapture';-import QuickTaskWidget from '../components/QuickTaskWidget';-import ReviewHubCard from '../components/ReviewHubCard';+import LayoutPicker from '../components/dashboard/LayoutPicker';+import LayoutEditor from '../components/dashboard/LayoutEditor';+import { WIDGETS_BY_ID, WIDTH_CLASS } from '../components/dashboard/widgetRegistry.jsx';import { Monitor } from 'lucide-react';import * as api from '../services/api';import socket from '../services/socket';+import toast from '../components/ui/Toast';export default function Dashboard() {const [apps, setApps] = useState([]);@@ -24,12 +16,16 @@ export default function Dashboard() {const [loading, setLoading] = useState(true);const [error, setError] = useState(null);+ const [layouts, setLayouts] = useState([]);+ const [activeLayoutId, setActiveLayoutId] = useState(null);+ const [editorOpen, setEditorOpen] = useState(false);+const fetchData = useCallback(async () => {setError(null);const [appsData, healthData, usageData] = await Promise.all([- api.getApps().catch(err => { setError(err.message); return []; }),+ api.getApps().catch((err) => { setError(err.message); return []; }),api.checkHealth().catch(() => null),- api.getUsage().catch(() => null)+ api.getUsage().catch(() => null),]);setApps(appsData);setHealth(healthData);@@ -39,18 +35,20 @@ export default function Dashboard() {useEffect(() => {fetchData();-- const handleAppsChanged = () => {- fetchData();- };+ const handleAppsChanged = () => fetchData();socket.on('apps:changed', handleAppsChanged);-- return () => {- socket.off('apps:changed', handleAppsChanged);- };+ return () => socket.off('apps:changed', handleAppsChanged);}, [fetchData]);- // Sort apps: active first, archived last, alphabetical within each group+ useEffect(() => {+ api.getDashboardLayouts()+ .then((data) => {+ setLayouts(data.layouts);+ setActiveLayoutId(data.activeLayoutId);+ })+ .catch((err) => setError(`Layouts: ${err.message}`));+ }, []);+const sortedApps = useMemo(() =>[...apps].sort((a, b) => {const archiveDiff = (a.archived ? 1 : 0) - (b.archived ? 1 : 0);@@ -60,15 +58,55 @@ export default function Dashboard() {[apps]);- // Memoize derived stats (exclude archived)- const activeApps = useMemo(() => apps.filter(a => !a.archived), [apps]);+ const activeApps = useMemo(() => apps.filter((a) => !a.archived), [apps]);const appStats = useMemo(() => ({total: activeApps.length,- online: activeApps.filter(a => a.overallStatus === 'online').length,- stopped: activeApps.filter(a => a.overallStatus === 'stopped').length,- notStarted: activeApps.filter(a => a.overallStatus === 'not_started' || a.overallStatus === 'not_found').length+ online: activeApps.filter((a) => a.overallStatus === 'online').length,+ stopped: activeApps.filter((a) => a.overallStatus === 'stopped').length,+ notStarted: activeApps.filter((a) => a.overallStatus === 'not_started' || a.overallStatus === 'not_found').length,}), [activeApps]);+ const dashboardState = useMemo(+ () => ({ apps, sortedApps, activeApps, appStats, health, usage, refetch: fetchData }),+ [apps, sortedApps, activeApps, appStats, health, usage, fetchData]+ );++ const activeLayout = useMemo(+ () => layouts.find((l) => l.id === activeLayoutId) || layouts[0],+ [layouts, activeLayoutId]+ );++ const visibleWidgets = useMemo(+ () => (activeLayout?.widgets ?? [])+ .map((id) => WIDGETS_BY_ID[id])+ .filter((w) => w && (!w.gate || w.gate(dashboardState))),+ [activeLayout, dashboardState]+ );++ const selectLayout = async (id) => {+ setActiveLayoutId(id);+ await api.setActiveDashboardLayout(id);+ };++ const saveLayout = async ({ id, name, widgets }) => {+ const result = await api.saveDashboardLayout(id, name, widgets);+ setLayouts(result.layouts);+ };++ const duplicateLayout = async ({ id, name, widgets }) => {+ const result = await api.saveDashboardLayout(id, name, widgets);+ setLayouts(result.layouts);+ setActiveLayoutId(id);+ await api.setActiveDashboardLayout(id);+ };++ const deleteLayoutById = async (id) => {+ const result = await api.deleteDashboardLayout(id);+ setLayouts(result.layouts);+ setActiveLayoutId(result.activeLayoutId);+ toast.success('Layout deleted');+ };+if (loading) {return (<div className="flex items-center justify-center h-64">@@ -79,7 +117,6 @@ export default function Dashboard() {return (<div className="space-y-6">- {/* Header */}<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 sm:gap-4"><div><h2 className="text-2xl font-bold text-white">Dashboard</h2>@@ -93,6 +130,14 @@ export default function Dashboard() {Server: <span className="text-port-success">Online</span></div>)}+ {layouts.length > 0 && (+ <LayoutPicker+ layouts={layouts}+ activeLayoutId={activeLayoutId}+ onSelect={selectLayout}+ onEdit={() => setEditorOpen(true)}+ />+ )}<Linkto="/ambient"className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-port-card border border-port-border hover:border-gray-600 transition-colors text-sm text-gray-400 hover:text-white min-h-[40px]"@@ -104,228 +149,38 @@ export default function Dashboard() {</div></div>- {/* Error */}{error && (<div className="p-4 bg-port-error/20 border border-port-error rounded-lg text-port-error">{error}</div>)}- {/* Row 1 — Quick entry */}- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">- <QuickBrainCapture />- <QuickTaskWidget />- </div>-- {/* Row 2 — Apps */}- {apps.length === 0 ? (- <div className="bg-port-card border border-port-border rounded-xl p-8 sm:p-12 text-center">- <div className="text-4xl mb-4">📦</div>- <h3 className="text-xl font-semibold text-white mb-2">No apps registered</h3>- <p className="text-gray-500 mb-6">- Register your first app to get started- </p>- <Link- to="/apps/create"- className="inline-flex items-center justify-center px-6 py-3 min-h-10 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"- >- Add App- </Link>- </div>- ) : (- <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-3">- {sortedApps.map(app => (- <AppTile key={app.id} app={app} onUpdate={fetchData} />- ))}+ {activeLayout && visibleWidgets.length === 0 && (+ <div className="bg-port-card border border-port-border rounded-xl p-8 text-center text-gray-500">+ This layout has no widgets. Click the layout picker and choose “Edit layouts…” to add some.</div>)}- {/* Row 3 — AI/CoS intelligence */}- <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">- <CosDashboardWidget />- <GoalProgressWidget />- <UpcomingTasksWidget />- </div>-- {/* Row 4 — Status, stats, decisions */}- <div className="grid grid-cols-1 lg:grid-cols-4 gap-4">- <ProactiveAlertsWidget />- <ReviewHubCard />- <SystemHealthWidget />- <BackupWidget />- <DeathClockWidget />- {apps.length > 0 && (- <div className="bg-port-card border border-port-border rounded-xl p-4 h-full">- <h3 className="text-sm font-semibold text-white mb-3">Quick Stats</h3>- <div className="grid grid-cols-2 gap-2">- <StatCard label="Total Apps" value={appStats.total} icon="📦" />- <StatCard label="Online" value={appStats.online} icon="🟢" />- <StatCard label="Stopped" value={appStats.stopped} icon="🟡" />- <StatCard label="Offline" value={appStats.notStarted} icon="⚪" />- </div>- </div>- )}- <DecisionLogWidget />- </div>-- {/* Row 5 — Activity data */}- {(usage?.currentStreak > 0 || usage?.longestStreak > 0 || usage?.hourlyActivity) && (- <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">- {/* Activity Streak */}- {usage && (usage.currentStreak > 0 || usage.longestStreak > 0) && (- <div className="bg-port-card border border-port-border rounded-xl p-4">- <div className="flex items-center gap-3 mb-3">- <div className="text-2xl" aria-hidden="true">- {usage.currentStreak >= 7 ? '🔥' : usage.currentStreak >= 3 ? '⚡' : '✨'}- </div>- <div>- <div className="text-xl font-bold text-white">- {usage.currentStreak} day{usage.currentStreak !== 1 ? 's' : ''}- </div>- <div className="text-xs text-gray-500">Current streak</div>- </div>- {usage.longestStreak > usage.currentStreak && (- <div className="ml-auto text-right">- <div className="text-sm font-semibold text-port-accent">- {usage.longestStreak} days- </div>- <div className="text-xs text-gray-500">Best</div>- </div>- )}- {usage.currentStreak === usage.longestStreak && usage.currentStreak > 0 && (- <div className="ml-auto px-2 py-1 bg-port-success/20 text-port-success text-xs rounded-full">- Personal best!- </div>- )}- </div>- {/* Mini streak visualization */}- <div className="flex gap-1">- {usage.last7Days?.map((day) => (- <div- key={day.date}- className={`flex-1 h-2 rounded-full ${- day.sessions > 0 ? 'bg-port-success' : 'bg-port-border'- }`}- title={`${day.label}: ${day.sessions} sessions`}- />- ))}- </div>- <div className="mt-1 flex justify-between text-xs text-gray-500">- <span>7d ago</span>- <span>Today</span>- </div>- </div>- )}-- {/* Hourly Activity Heatmap */}- {usage?.hourlyActivity && (- <div className="lg:col-span-2">- <HourlyActivityHeatmap hourlyActivity={usage.hourlyActivity} />+ {visibleWidgets.length > 0 && (+ <div className="grid grid-cols-12 gap-4">+ {visibleWidgets.map((w) => (+ <div key={w.id} className={WIDTH_CLASS[w.width] || WIDTH_CLASS.quarter}>+ <w.Component dashboardState={dashboardState} /></div>- )}+ ))}</div>)}- </div>- );-}--function StatCard({ label, value, icon }) {- return (- <div className="bg-port-bg border border-port-border rounded-lg p-3" role="group" aria-label={`${label}: ${value}`}>- <div className="flex items-center gap-2 mb-1">- <span aria-hidden="true" className="text-base">{icon}</span>- <span className="text-xs text-gray-500">{label}</span>- </div>- <div className="text-xl font-bold text-white">{value}</div>- </div>- );-}--function HourlyActivityHeatmap({ hourlyActivity }) {- const maxActivity = Math.max(...hourlyActivity, 1);-- const peakValue = Math.max(...hourlyActivity);- const peakHours = hourlyActivity- .map((val, idx) => ({ hour: idx, count: val }))- .filter(h => h.count === peakValue && h.count > 0);-- const totalSessions = hourlyActivity.reduce((sum, val) => sum + val, 0);-- const formatHour = (hour) => {- if (hour === 0) return '12a';- if (hour === 12) return '12p';- return hour < 12 ? `${hour}a` : `${hour - 12}p`;- };- const getIntensityClass = (count) => {- if (count === 0) return 'bg-port-border/30';- const intensity = count / maxActivity;- if (intensity >= 0.8) return 'bg-port-success';- if (intensity >= 0.5) return 'bg-port-success/70';- if (intensity >= 0.25) return 'bg-port-success/40';- return 'bg-port-success/20';- };-- const getPeakTimeDescription = () => {- if (peakHours.length === 0 || peakValue === 0) return null;- if (peakHours.length === 1) {- const hour = peakHours[0].hour;- return `Peak: ${formatHour(hour)} (${peakValue} sessions)`;- }- const hours = peakHours.slice(0, 3).map(h => formatHour(h.hour)).join(', ');- return `Peak hours: ${hours} (${peakValue} sessions each)`;- };-- if (totalSessions === 0) return null;-- return (- <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6">- <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 mb-4">- <div className="flex items-center gap-3">- <div className="text-2xl" aria-hidden="true">⏰</div>- <div>- <h3 className="text-lg font-semibold text-white">Activity by Hour</h3>- <p className="text-sm text-gray-500">{totalSessions} total sessions tracked</p>- </div>- </div>- {getPeakTimeDescription() && (- <div className="text-sm text-port-success">- {getPeakTimeDescription()}- </div>- )}- </div>-- <div className="grid grid-cols-6 sm:grid-cols-12 gap-1.5 sm:gap-1" role="img" aria-label="Hourly activity heatmap">- {hourlyActivity.map((count, hour) => (- <div- key={hour}- className={`aspect-square rounded-xs ${getIntensityClass(count)} transition-colors cursor-default min-w-[20px] min-h-[20px]`}- title={`${formatHour(hour)}: ${count} session${count !== 1 ? 's' : ''}`}- aria-label={`${formatHour(hour)}: ${count} sessions`}- />- ))}- </div>-- <div className="mt-2 grid grid-cols-6 sm:grid-cols-12 gap-1.5 sm:gap-1 text-xs text-gray-500">- {hourlyActivity.map((_, hour) => (- <div key={hour} className="text-center">- <span className="hidden sm:inline">{hour % 3 === 0 ? formatHour(hour) : ''}</span>- <span className="sm:hidden">{hour % 4 === 0 ? formatHour(hour) : ''}</span>- </div>- ))}- </div>-- <div className="mt-4 flex items-center justify-end gap-2 text-xs text-gray-500">- <span>Less</span>- <div className="flex gap-1">- <div className="w-4 h-4 sm:w-3 sm:h-3 rounded-xs bg-port-border/30" />- <div className="w-4 h-4 sm:w-3 sm:h-3 rounded-xs bg-port-success/20" />- <div className="w-4 h-4 sm:w-3 sm:h-3 rounded-xs bg-port-success/40" />- <div className="w-4 h-4 sm:w-3 sm:h-3 rounded-xs bg-port-success/70" />- <div className="w-4 h-4 sm:w-3 sm:h-3 rounded-xs bg-port-success" />- </div>- <span>More</span>- </div>+ {editorOpen && layouts.length > 0 && (+ <LayoutEditor+ layouts={layouts}+ activeLayoutId={activeLayoutId}+ onClose={() => setEditorOpen(false)}+ onSave={saveLayout}+ onDelete={deleteLayoutById}+ onDuplicate={duplicateLayout}+ />+ )}</div>);}diff --git a/client/src/services/api.js b/client/src/services/api.jsindex a1ce5e06e1..0bb9104513 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -33,6 +33,7 @@ export * from './apiMeatspace.js';export * from './apiMortalLoom.js';export * from './apiOpenClaw.js';export * from './apiPalette.js';+export * from './apiDashboard.js';// Default export for simplified imports (get/post/put/delete helpers)export { default } from './apiCore.js';diff --git a/client/src/services/apiDashboard.js b/client/src/services/apiDashboard.jsnew file mode 100644index 0000000000..d2967531c2--- /dev/null+++ b/client/src/services/apiDashboard.js@@ -0,0 +1,18 @@+import { request } from './apiCore.js';++export const getDashboardLayouts = () => request('/dashboard/layouts');++export const setActiveDashboardLayout = (id) =>+ request('/dashboard/layouts/active', {+ method: 'PUT',+ body: JSON.stringify({ id }),+ });++export const saveDashboardLayout = (id, name, widgets) =>+ request(`/dashboard/layouts/${encodeURIComponent(id)}`, {+ method: 'PUT',+ body: JSON.stringify({ name, widgets }),+ });++export const deleteDashboardLayout = (id) =>+ request(`/dashboard/layouts/${encodeURIComponent(id)}`, { method: 'DELETE' });diff --git a/server/index.js b/server/index.jsindex 1f56bbd1cc..0df16d159e 100644--- a/server/index.js+++ b/server/index.js@@ -61,6 +61,7 @@ import backupRoutes from './routes/backup.js';import databaseRoutes from './routes/database.js';import searchRoutes from './routes/search.js';import paletteRoutes from './routes/palette.js';+import dashboardLayoutsRoutes from './routes/dashboardLayouts.js';import dataSyncRoutes from './routes/dataSync.js';import identityRoutes from './routes/identity.js';import instancesRoutes from './routes/instances.js';@@ -246,6 +247,7 @@ app.use('/api/usage', usageRoutes);app.use('/api/screenshots', screenshotsRoutes);app.use('/api/search', searchRoutes);app.use('/api/palette', paletteRoutes);+app.use('/api/dashboard/layouts', dashboardLayoutsRoutes);app.use('/api/attachments', attachmentsRoutes);app.use('/api/backup', backupRoutes);app.use('/api/database', databaseRoutes);diff --git a/server/routes/dashboardLayouts.js b/server/routes/dashboardLayouts.jsnew file mode 100644index 0000000000..7dd2961306--- /dev/null+++ b/server/routes/dashboardLayouts.js@@ -0,0 +1,50 @@+/**+ * GET /api/dashboard/layouts → { activeLayoutId, layouts }+ * PUT /api/dashboard/layouts/active → { activeLayoutId } (body: { id })+ * PUT /api/dashboard/layouts/:id → saves/updates a single layout+ * DELETE /api/dashboard/layouts/:id → deletes a user-created layout+ */++import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import * as svc from '../services/dashboardLayouts.js';++const router = Router();++const layoutSchema = z.object({+ id: z.string().min(1).max(60).regex(/^[a-z0-9-]+$/, 'id must be lowercase kebab'),+ name: z.string().min(1).max(80),+ widgets: z.array(z.string().min(1).max(80)).max(50),+});++const setActiveSchema = z.object({+ id: z.string().min(1).max(60),+});++router.get('/', asyncHandler(async (_req, res) => {+ res.json(await svc.getState());+}));++router.put('/active', asyncHandler(async (req, res) => {+ const { id } = validateRequest(setActiveSchema, req.body ?? {});+ const state = await svc.setActiveLayout(id).catch((err) => {+ throw new ServerError(err.message, { status: 404 });+ });+ res.json(state);+}));++router.put('/:id', asyncHandler(async (req, res) => {+ const body = validateRequest(layoutSchema, { ...req.body, id: req.params.id });+ res.json(await svc.saveLayout(body));+}));++router.delete('/:id', asyncHandler(async (req, res) => {+ const state = await svc.deleteLayout(String(req.params.id)).catch((err) => {+ throw new ServerError(err.message, { status: err.message.includes('Cannot delete') ? 400 : 404 });+ });+ res.json(state);+}));++export default router;diff --git a/server/routes/dashboardLayouts.test.js b/server/routes/dashboardLayouts.test.jsnew file mode 100644index 0000000000..a1057c4781--- /dev/null+++ b/server/routes/dashboardLayouts.test.js@@ -0,0 +1,96 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++vi.mock('../services/dashboardLayouts.js', () => ({+ getState: vi.fn(),+ setActiveLayout: vi.fn(),+ saveLayout: vi.fn(),+ deleteLayout: vi.fn(),+}));++const svc = await import('../services/dashboardLayouts.js');+const { default: routes } = await import('./dashboardLayouts.js');++const makeApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/dashboard/layouts', routes);+ app.use(errorMiddleware);+ return app;+};++beforeEach(() => {+ vi.clearAllMocks();+});++describe('GET /api/dashboard/layouts', () => {+ it('returns active layout id + layouts list', async () => {+ svc.getState.mockResolvedValue({+ activeLayoutId: 'default',+ layouts: [{ id: 'default', name: 'Everything', builtIn: true, widgets: ['apps'] }],+ });+ const res = await request(makeApp()).get('/api/dashboard/layouts');+ expect(res.status).toBe(200);+ expect(res.body.activeLayoutId).toBe('default');+ expect(res.body.layouts).toHaveLength(1);+ });+});++describe('PUT /api/dashboard/layouts/active', () => {+ it('switches the active layout', async () => {+ svc.setActiveLayout.mockResolvedValue({ activeLayoutId: 'focus', layouts: [] });+ const res = await request(makeApp())+ .put('/api/dashboard/layouts/active')+ .send({ id: 'focus' });+ expect(res.status).toBe(200);+ expect(svc.setActiveLayout).toHaveBeenCalledWith('focus');+ });++ it('404s on unknown layout', async () => {+ svc.setActiveLayout.mockRejectedValue(new Error('Unknown layout id: nope'));+ const res = await request(makeApp())+ .put('/api/dashboard/layouts/active')+ .send({ id: 'nope' });+ expect(res.status).toBe(404);+ });+});++describe('PUT /api/dashboard/layouts/:id', () => {+ it('saves a layout', async () => {+ svc.saveLayout.mockResolvedValue({ activeLayoutId: 'default', layouts: [] });+ const res = await request(makeApp())+ .put('/api/dashboard/layouts/my-custom')+ .send({ name: 'Custom', widgets: ['apps', 'cos'] });+ expect(res.status).toBe(200);+ expect(svc.saveLayout).toHaveBeenCalledWith({+ id: 'my-custom',+ name: 'Custom',+ widgets: ['apps', 'cos'],+ });+ });++ it('rejects invalid layout ids', async () => {+ const res = await request(makeApp())+ .put('/api/dashboard/layouts/NotKebab')+ .send({ name: 'x', widgets: [] });+ expect(res.status).toBeGreaterThanOrEqual(400);+ expect(svc.saveLayout).not.toHaveBeenCalled();+ });+});++describe('DELETE /api/dashboard/layouts/:id', () => {+ it('deletes a user layout', async () => {+ svc.deleteLayout.mockResolvedValue({ activeLayoutId: 'default', layouts: [] });+ const res = await request(makeApp()).delete('/api/dashboard/layouts/my-custom');+ expect(res.status).toBe(200);+ expect(svc.deleteLayout).toHaveBeenCalledWith('my-custom');+ });++ it('400s when trying to delete a built-in layout', async () => {+ svc.deleteLayout.mockRejectedValue(new Error('Cannot delete built-in layout: default'));+ const res = await request(makeApp()).delete('/api/dashboard/layouts/default');+ expect(res.status).toBe(400);+ });+});diff --git a/server/services/dashboardLayouts.js b/server/services/dashboardLayouts.jsnew file mode 100644index 0000000000..d3c421bfd6--- /dev/null+++ b/server/services/dashboardLayouts.js@@ -0,0 +1,104 @@+/**+ * Dashboard Layouts+ *+ * Named, user-customizable dashboard layouts. Each layout stores an ordered+ * list of widget ids; the client's widget registry decides how to render+ * each id. Persisted to data/dashboard-layouts.json.+ *+ * Seeded on first read with a "Default" layout (mirrors the current hardcoded+ * layout) plus "Focus", "Morning Review", and "Ops" starter layouts so the+ * feature has value out of the box.+ */++import { join } from 'path';+import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../lib/fileUtils.js';++const STATE_PATH = join(PATHS.data, 'dashboard-layouts.json');++// Widget ids are the contract between this file and the client registry —+// see client/src/components/dashboard/widgetRegistry.js. If a layout refers+// to an unknown id, the client skips it gracefully.+const DEFAULT_LAYOUTS = [+ {+ id: 'default',+ name: 'Everything',+ builtIn: true,+ widgets: [+ 'quick-brain', 'quick-task',+ 'apps',+ 'cos', 'goal-progress', 'upcoming-tasks',+ 'proactive-alerts', 'review-hub', 'system-health', 'backup', 'death-clock', 'quick-stats', 'decision-log',+ 'activity-streak', 'hourly-activity',+ ],+ },+ {+ id: 'focus',+ name: 'Focus',+ builtIn: true,+ widgets: ['quick-task', 'upcoming-tasks', 'cos'],+ },+ {+ id: 'morning-review',+ name: 'Morning Review',+ builtIn: true,+ widgets: ['proactive-alerts', 'upcoming-tasks', 'review-hub', 'goal-progress', 'death-clock'],+ },+ {+ id: 'ops',+ name: 'Ops',+ builtIn: true,+ widgets: ['system-health', 'cos', 'backup', 'apps', 'quick-stats'],+ },+];++const DEFAULT_STATE = {+ activeLayoutId: 'default',+ layouts: DEFAULT_LAYOUTS,+};++export async function getState() {+ await ensureDir(PATHS.data);+ const raw = await readJSONFile(STATE_PATH, DEFAULT_STATE, { logError: false });+ // If the file exists but has drifted (missing fields, or user deleted all+ // layouts), merge in defaults conservatively rather than returning junk.+ const layouts = Array.isArray(raw.layouts) && raw.layouts.length > 0+ ? raw.layouts+ : DEFAULT_LAYOUTS;+ const activeLayoutId = layouts.find((l) => l.id === raw.activeLayoutId)+ ? raw.activeLayoutId+ : layouts[0].id;+ return { activeLayoutId, layouts };+}++export async function setActiveLayout(id) {+ const state = await getState();+ if (!state.layouts.find((l) => l.id === id)) {+ throw new Error(`Unknown layout id: ${id}`);+ }+ const next = { ...state, activeLayoutId: id };+ await atomicWrite(STATE_PATH, next);+ return next;+}++export async function saveLayout(layout) {+ const state = await getState();+ const idx = state.layouts.findIndex((l) => l.id === layout.id);+ const merged = idx >= 0+ ? state.layouts.map((l, i) => i === idx ? { ...l, ...layout, builtIn: l.builtIn } : l)+ : [...state.layouts, { ...layout, builtIn: false }];+ const next = { ...state, layouts: merged };+ await atomicWrite(STATE_PATH, next);+ return next;+}++export async function deleteLayout(id) {+ const state = await getState();+ const target = state.layouts.find((l) => l.id === id);+ if (!target) throw new Error(`Unknown layout id: ${id}`);+ if (target.builtIn) throw new Error(`Cannot delete built-in layout: ${id}`);+ const remaining = state.layouts.filter((l) => l.id !== id);+ const activeLayoutId = state.activeLayoutId === id ? remaining[0].id : state.activeLayoutId;+ const next = { activeLayoutId, layouts: remaining };+ await atomicWrite(STATE_PATH, next);+ return next;+}