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: drag-and-drop dashboard widget arrangement
Adam Eivy4eac0e893b5a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b525ba0e01..0330bd41ea 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -11,6 +11,18 @@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`.+- **Drag-and-drop dashboard widget arrangement (free-form 12-col grid)** — every widget is now positionable. The Dashboard exposes an "Arrange" button next to the layout picker; in arrange mode every widget gets a top-right move handle and a bottom-right resize handle. Drag snaps to a 12-column × 80px-row grid with Tetris-style collision: the dropped widget pins where you let go, and surrounding widgets compact upward into the smallest non-colliding y position. Pointer events power the gesture (works for mouse + touch); `passive: true` on the window listeners + a snap-cell dedup guard mean a drag generates one React update per crossed snap boundary instead of one per pointermove. Save persists the new positions to the active layout's `grid` array; Cancel discards in-flight edits without writing.++ Layouts now carry `grid: [{ id, x, y, w, h }]` in addition to the existing widget list. When a layout's grid is empty (legacy + freshly-created layouts), the renderer falls back to `synthesizeGrid` — a row-flow auto-layout based on each widget's `width` keyword and new `defaultH` field. Below 640px viewport width the grid collapses to a single-column stack and drag/resize is disabled (touch targets would fight scroll on mobile). Adding/removing widgets via the existing LayoutEditor preserves saved positions: removed widgets drop out of the grid, added widgets are auto-placed at the bottom-left.++ All four built-in layouts now ship with hand-tuned grids designed for a typical desktop viewport — most-useful widgets above the fold (~768px). **Everything**: capture row + Upcoming Tasks at top, then System Health (5-wide) with Proactive Alerts beside it, Activity Streak / Death Clock / Review Hub on the right, secondary widgets banded below, full-width Hourly Activity + Apps at the bottom. **Focus**: Quick Task compact top-left, tall Upcoming Tasks right, CoS below. **Morning Review**: Proactive Alerts top-left, tall Upcoming Tasks center, Death Clock + Goal Progress stacked top-right, Review Hub bottom-left — all 5 widgets above the fold. **Ops**: System Health top-left wide, Quick Stats top-right, CoS mid-right, Backup mid-left, Apps full-width bottom (h=11). Existing installs upgrade automatically: a read-time `hydrateDefaultGrid` swaps the new default grid into any built-in layout whose persisted grid is empty AND whose widget list still matches the default — user customizations (non-empty grids, removed/added widgets) are never overwritten.++ Cross-field server validation: grid items must reference a widget in the layout's `widgets` list, must be unique by id, and `x + w` must fit inside `GRID_COLS`. Bounds (`GRID_COLS`, `GRID_ROW_MAX`, `GRID_ITEM_H_MAX`) are exported from the service and bundled into the `LIMITS` payload so the client can enforce the same caps.++ **Reuse**: extracted the inline `useContainerWidth` hook from `CalendarTab.jsx` into `client/src/hooks/useContainerWidth.js` (`ResizeObserver` + `[ref, width]` return) and wired both consumers to the shared hook.++ Files: `client/src/components/dashboard/DashboardGrid.jsx` (new — ~280 lines, free-form grid renderer + `synthesizeGrid` / `reconcileGrid` / `placeAndCompact` helpers), `client/src/hooks/useContainerWidth.js` (new), `client/src/pages/Dashboard.jsx` (Arrange/Save/Cancel buttons, draft-grid state, `renderGrid` reconcile pipeline), `client/src/components/dashboard/widgetRegistry.jsx` (`defaultH` per widget, `WIDTH_TO_COLS`, `GRID_COLS`/`GRID_DEFAULT_H` exports), `client/src/services/apiDashboard.js` (`saveDashboardLayout` accepts `grid`), `client/src/components/meatspace/tabs/CalendarTab.jsx` (uses shared hook), `server/services/dashboardLayouts.js` (`sanitizeGridItem`, grid-aware `sanitizeLayout`, `hydrateDefaultGrid`, hand-tuned default grids for all 4 built-ins, new `GRID_COLS`/`GRID_ROW_MAX`/`GRID_ITEM_H_MAX` exports), `server/routes/dashboardLayouts.js` (`gridItemSchema` + 3-refine `layoutSchema` chain), `server/routes/dashboardLayouts.test.js` (4 new test cases — grid round-trip, orphan rejection, x+w overflow, dup-id rejection, no-grid back-compat). `CLAUDE.md` documents the grid model, "Arrange" mode, and `defaultH` for future widget authors.+- **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 (streak, hourly activity, quick stats) auto-hide when there's nothing to show. The Apps tile is intentionally un-gated — it renders its own "Add App" empty-state CTA on a blank install. 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.diff --git a/CLAUDE.md b/CLAUDE.mdindex 4b160822f6..e6df92b766 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -97,14 +97,16 @@ Fail-fast guards at module load catch missing fields, non-slash paths, and dupli### 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.+Dashboard widgets are registered in `client/src/components/dashboard/widgetRegistry.jsx` — each entry has `{ id, label, Component, width, defaultH?, 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.++**Grid positions:** layouts also carry a `grid: [{ id, x, y, w, h }]` array — free-form positions on a 12-column grid (rows ~80px each). When `grid` is empty (legacy/unmigrated layouts) the renderer auto-flows widgets using `synthesizeGrid` based on each widget's `width` keyword and `defaultH`. The "Arrange" button on the Dashboard enters edit mode where every widget exposes a move (top-right) and resize (bottom-right) handle; drag is snap-to-grid with collision-resolve via `placeAndCompact` (pins the moved item, slots others into the smallest non-colliding y). Save persists to the active layout's `grid`. The grid renderer collapses to a single-column stack below 640px viewport width — drag/resize is desktop-only.**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.+1. Add a `{ id, label, Component, width, defaultH?, gate? }` entry to `WIDGETS` in `widgetRegistry.jsx`. Use a stable `id` (kebab-case) — it's the contract stored in layouts. Pick `defaultH` based on the widget's natural content height (default `4`); this controls the size when it's first auto-placed into a grid.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.+5. Users can toggle widgets on/off per layout via the Dashboard's layout picker → Edit, and arrange/resize them via the "Arrange" button.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.diff --git a/client/src/components/dashboard/DashboardGrid.jsx b/client/src/components/dashboard/DashboardGrid.jsxnew file mode 100644index 0000000000..88f836dbf7--- /dev/null+++ b/client/src/components/dashboard/DashboardGrid.jsx@@ -0,0 +1,319 @@+import { useState, useRef, useEffect, useMemo, useCallback } from 'react';+import { GripVertical, MoveDiagonal2 } from 'lucide-react';+import { GRID_COLS, GRID_DEFAULT_H, WIDTH_TO_COLS, WIDGETS_BY_ID } from './widgetRegistry.jsx';+import useContainerWidth from '../../hooks/useContainerWidth';++// Free-form 12-column grid with snap-to-grid drag and resize.+//+// Items: [{ id, x, y, w, h }] where x/y/w/h are integer grid units+// - x: 0..11 (column origin)+// - y: 0..n (row origin; rows are uniform ROW_HEIGHT_PX tall)+// - w: 1..12 (column span)+// - h: 1..n (row span)+//+// In edit mode each item exposes a top-right move handle and a bottom-right+// resize handle. Pointer events power both so the same handlers work for+// mouse and touch. Pointer capture isn't used because the drag math reads+// window-level coordinates regardless of which element the pointer crosses+// — the listener lives on `window` for the duration of the gesture.+//+// Collision policy after drag/resize: pin the moved item at its dropped+// position, then slot every other item into the smallest y that doesn't+// collide with anything already placed (top-left items processed first).+// Tetris-style compaction — same feel as react-grid-layout / gridstack.++const ROW_HEIGHT_PX = 80;+const GAP_PX = 16;+const MIN_W = 2;+const MIN_H = 2;+// Mobile breakpoint: below this width the grid collapses to a single column+// stacked vertically. Drag/resize is disabled — phones don't have the screen+// real estate to make positional editing useful, and the touch targets would+// fight scrolling.+const MOBILE_BREAKPOINT_PX = 640;++function getColWidth(containerWidth) {+ return (containerWidth - GAP_PX * (GRID_COLS - 1)) / GRID_COLS;+}++function rectFor(item, colWidth) {+ return {+ left: item.x * (colWidth + GAP_PX),+ top: item.y * (ROW_HEIGHT_PX + GAP_PX),+ width: item.w * colWidth + (item.w - 1) * GAP_PX,+ height: item.h * ROW_HEIGHT_PX + (item.h - 1) * GAP_PX,+ };+}++function overlaps(a, b) {+ return !(a.x + a.w <= b.x || b.x + b.w <= a.x || a.y + a.h <= b.y || b.y + b.h <= a.y);+}++function sameRect(a, b) {+ return a.x === b.x && a.y === b.y && a.w === b.w && a.h === b.h;+}++// Shared drag/resize handle. Move and resize are visually + behaviorally+// near-identical (icon, position, drag kind), so they share one component+// instead of duplicating the button block.+function DragHandle({ kind, item, icon: Icon, onStart, className }) {+ return (+ <button+ type="button"+ onPointerDown={(e) => onStart(e, item, kind)}+ aria-label={`${kind === 'move' ? 'Move' : 'Resize'} ${item.id}`}+ className={`absolute z-20 p-1 bg-port-bg/90 border border-port-border rounded text-gray-300 hover:text-white hover:border-port-accent ${className}`}+ style={{ touchAction: 'none' }}+ >+ <Icon size={14} />+ </button>+ );+}++// Pin the moved item at its dropped position, then slide every other item+// upward to the smallest y that doesn't collide with anything already+// placed. Combines collision-resolve and compact in one pass: the moved+// item goes first (so it acts as an obstacle for everyone else) and the+// rest are processed in current (y, x) order so top-left items keep+// precedence. Returns a new array — never mutates input.+function placeAndCompact(items, movedId) {+ const moved = items.find((i) => i.id === movedId);+ if (!moved) return items.map((it) => ({ ...it }));+ const rest = items+ .filter((i) => i.id !== movedId)+ .sort((a, b) => a.y - b.y || a.x - b.x);+ const placed = [{ ...moved }];+ for (const item of rest) {+ let y = 0;+ while (placed.some((p) => overlaps({ ...item, y }, p))) y += 1;+ placed.push({ ...item, y });+ }+ return placed;+}++// Auto-place a new widget at the bottom of the grid, left-aligned. Used when+// LayoutEditor adds a widget to a layout without specifying coordinates.+export function placeNewWidget(items, widgetId) {+ const meta = WIDGETS_BY_ID[widgetId];+ const w = WIDTH_TO_COLS[meta?.width] ?? 4;+ const h = meta?.defaultH ?? GRID_DEFAULT_H;+ const bottom = items.reduce((max, it) => Math.max(max, it.y + it.h), 0);+ return [...items, { id: widgetId, x: 0, y: bottom, w, h }];+}++// Synthesize a row-flow grid from a plain widget id list. Mirrors the+// previous CSS-grid layout so unmigrated layouts open in the same visual+// arrangement they had before the grid feature shipped.+export function synthesizeGrid(widgetIds) {+ const items = [];+ let cursorX = 0;+ let cursorY = 0;+ let rowMaxH = 0;+ for (const id of widgetIds) {+ const meta = WIDGETS_BY_ID[id];+ if (!meta) continue;+ const w = WIDTH_TO_COLS[meta.width] ?? 4;+ const h = meta.defaultH ?? GRID_DEFAULT_H;+ if (cursorX + w > GRID_COLS) {+ cursorX = 0;+ cursorY += rowMaxH;+ rowMaxH = 0;+ }+ items.push({ id, x: cursorX, y: cursorY, w, h });+ cursorX += w;+ rowMaxH = Math.max(rowMaxH, h);+ }+ return items;+}++// Reconcile a saved grid against the visible widget list. Adds positions for+// any widgets missing from the grid (auto-placed at the bottom) and drops+// grid entries whose widget is no longer in the layout (gated off, deleted,+// etc.). Keeps the renderer's input always coherent with what should display.+export function reconcileGrid(grid, visibleIds) {+ const visible = new Set(visibleIds);+ const present = new Set();+ let kept = [];+ for (const item of grid) {+ if (!visible.has(item.id)) continue;+ if (present.has(item.id)) continue;+ present.add(item.id);+ kept.push(item);+ }+ for (const id of visibleIds) {+ if (present.has(id)) continue;+ kept = placeNewWidget(kept, id);+ }+ return kept;+}++export default function DashboardGrid({ items, editable, onChange, renderItem }) {+ const [containerRef, containerWidth] = useContainerWidth();+ // Drag state lives outside React when active to avoid a setState on every+ // pointermove (would spam re-renders of every widget). React only learns+ // about the new ghost when we call setDragGhost, throttled by RAF.+ const dragRef = useRef(null);+ const [dragGhost, setDragGhost] = useState(null);++ const isMobile = containerWidth > 0 && containerWidth < MOBILE_BREAKPOINT_PX;++ const totalRows = useMemo(+ () => items.reduce((max, it) => Math.max(max, it.y + it.h), 0),+ [items]+ );+ const containerHeight = totalRows * (ROW_HEIGHT_PX + GAP_PX);++ const startDrag = useCallback((e, item, kind) => {+ if (!editable || isMobile) return;+ // Prevent text selection mid-drag. preventDefault on the handle's+ // pointerdown is enough because the listener lives on window and we+ // never let the pointer leave the gesture.+ e.preventDefault();+ e.stopPropagation();+ dragRef.current = {+ id: item.id,+ kind,+ startPointer: { x: e.clientX, y: e.clientY },+ startItem: { ...item },+ ghost: { ...item },+ };+ setDragGhost({ ...item });+ }, [editable, isMobile]);++ useEffect(() => {+ if (!dragGhost) return undefined;+ const colWidth = getColWidth(containerWidth);+ let raf = 0;++ const onPointerMove = (e) => {+ const drag = dragRef.current;+ if (!drag) return;+ const dx = e.clientX - drag.startPointer.x;+ const dy = e.clientY - drag.startPointer.y;+ const colStep = colWidth + GAP_PX;+ const rowStep = ROW_HEIGHT_PX + GAP_PX;++ let next;+ if (drag.kind === 'move') {+ const newX = Math.max(0, Math.min(GRID_COLS - drag.startItem.w, Math.round(drag.startItem.x + dx / colStep)));+ const newY = Math.max(0, Math.round(drag.startItem.y + dy / rowStep));+ next = { ...drag.startItem, x: newX, y: newY };+ } else {+ const newW = Math.max(MIN_W, Math.min(GRID_COLS - drag.startItem.x, Math.round(drag.startItem.w + dx / colStep)));+ const newH = Math.max(MIN_H, Math.round(drag.startItem.h + dy / rowStep));+ next = { ...drag.startItem, w: newW, h: newH };+ }+ // Snap dedup: pointermove fires at 200+ Hz, but `next` only changes+ // when the cursor crosses a snap boundary. Skip the React update+ // when we're still inside the same snap cell — saves ~60 widget+ // re-renders per drag and keeps the rAF callback a no-op.+ if (sameRect(drag.ghost, next)) return;+ drag.ghost = next;+ if (!raf) {+ raf = requestAnimationFrame(() => {+ raf = 0;+ if (dragRef.current) setDragGhost({ ...dragRef.current.ghost });+ });+ }+ };++ const finish = (commit) => {+ if (raf) { cancelAnimationFrame(raf); raf = 0; }+ const drag = dragRef.current;+ dragRef.current = null;+ setDragGhost(null);+ if (!drag || !commit) return;+ // Skip the write entirely when nothing actually changed — avoids a+ // 200 OK on every accidental click on the drag handle.+ if (sameRect(drag.startItem, drag.ghost)) return;+ const updated = items.map((it) => (it.id === drag.id ? { ...it, ...drag.ghost } : it));+ onChange(placeAndCompact(updated, drag.id));+ };++ const onPointerUp = () => finish(true);+ const onPointerCancel = () => finish(false);++ // Passive listeners — none of these handlers call preventDefault.+ // preventDefault on the pointerdown (in startDrag) is enough to suppress+ // text selection mid-drag.+ window.addEventListener('pointermove', onPointerMove, { passive: true });+ window.addEventListener('pointerup', onPointerUp, { passive: true });+ window.addEventListener('pointercancel', onPointerCancel, { passive: true });+ return () => {+ window.removeEventListener('pointermove', onPointerMove);+ window.removeEventListener('pointerup', onPointerUp);+ window.removeEventListener('pointercancel', onPointerCancel);+ if (raf) cancelAnimationFrame(raf);+ };+ // dragGhost in the deps array re-installs the listeners only when the+ // gesture starts/ends — pointermove updates dragRef.current directly.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [dragGhost ? 'active' : 'idle', items, onChange, containerWidth]);++ // Mobile fallback: stack widgets full-width in source order. Uses CSS flow+ // (no absolute positioning) so the layout adapts to widget content height.+ if (isMobile) {+ return (+ <div ref={containerRef} className="space-y-4">+ {items.map((item) => (+ <div key={item.id} className="w-full">+ {renderItem(item)}+ </div>+ ))}+ </div>+ );+ }++ const colWidth = getColWidth(containerWidth);++ return (+ <div+ ref={containerRef}+ className="relative w-full"+ style={{ height: containerWidth ? containerHeight : 'auto', minHeight: '4rem' }}+ >+ {items.map((item) => {+ const isDragging = dragGhost?.id === item.id;+ const renderRect = rectFor(item, colWidth);+ return (+ <div+ key={item.id}+ className={`absolute ${isDragging ? 'opacity-40' : ''} ${dragGhost ? '' : 'transition-[left,top,width,height] duration-150'}`}+ style={{+ left: renderRect.left,+ top: renderRect.top,+ width: renderRect.width,+ height: renderRect.height,+ }}+ >+ <div className={`relative w-full h-full overflow-hidden rounded-xl ${editable ? 'ring-1 ring-port-border' : ''}`}>+ {renderItem(item)}+ {editable && containerWidth > 0 && (+ <>+ <DragHandle+ kind="move" item={item} icon={GripVertical} onStart={startDrag}+ className="top-1.5 right-1.5 cursor-move"+ />+ <DragHandle+ kind="resize" item={item} icon={MoveDiagonal2} onStart={startDrag}+ className="bottom-1 right-1 cursor-se-resize"+ />+ </>+ )}+ </div>+ </div>+ );+ })}++ {/* Drop preview during drag — outline showing where the item will+ land after snap. Pointer-events:none so it never intercepts the+ gesture. */}+ {dragGhost && containerWidth > 0 && (+ <div+ className="absolute pointer-events-none border-2 border-dashed border-port-accent rounded-xl bg-port-accent/10 z-30"+ style={rectFor(dragGhost, colWidth)}+ />+ )}+ </div>+ );+}diff --git a/client/src/components/dashboard/widgetRegistry.jsx b/client/src/components/dashboard/widgetRegistry.jsxindex 9914c0233b..e769dd64bd 100644--- a/client/src/components/dashboard/widgetRegistry.jsx+++ b/client/src/components/dashboard/widgetRegistry.jsx@@ -14,26 +14,32 @@ 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`+// Each entry: { id, label, Component, width, defaultH?, gate? }. `gate(state) => bool`// skips the widget when it has nothing useful to show. The Apps tile is// intentionally un-gated — it renders its own empty-state CTA so the "add// your first app" path is always visible on a blank install.+//+// `defaultH` is the row count (each row ≈ 80px) used when a widget is+// auto-placed into the grid for the first time — picked from the widget's+// natural content height so unmigrated layouts and newly-added widgets land+// at a usable size instead of the generic h=4 fallback. Once a layout has+// been edited, persisted h values win.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) },+ { id: 'quick-brain', label: 'Quick Brain Capture', Component: QuickBrainCapture, width: 'half', defaultH: 3 },+ { id: 'quick-task', label: 'Quick Task', Component: QuickTaskWidget, width: 'half', defaultH: 3 },+ { id: 'apps', label: 'Apps Grid', Component: AppsGridWidget, width: 'full', defaultH: 5 },+ { id: 'cos', label: 'Chief of Staff', Component: CosDashboardWidget, width: 'third', defaultH: 6 },+ { id: 'goal-progress', label: 'Goal Progress', Component: GoalProgressWidget, width: 'third', defaultH: 5 },+ { id: 'upcoming-tasks', label: 'Upcoming Tasks', Component: UpcomingTasksWidget, width: 'third', defaultH: 5 },+ { id: 'proactive-alerts', label: 'Proactive Alerts', Component: ProactiveAlertsWidget, width: 'quarter', defaultH: 4 },+ { id: 'review-hub', label: 'Review Hub', Component: ReviewHubCard, width: 'quarter', defaultH: 4 },+ { id: 'system-health', label: 'System Health', Component: SystemHealthWidget, width: 'quarter', defaultH: 8 },+ { id: 'backup', label: 'Backup', Component: BackupWidget, width: 'quarter', defaultH: 5 },+ { id: 'death-clock', label: 'Death Clock', Component: DeathClockWidget, width: 'quarter', defaultH: 4 },+ { id: 'quick-stats', label: 'Quick Stats', Component: QuickStatsWidget, width: 'quarter', defaultH: 3, gate: (s) => s.apps.length > 0 },+ { id: 'decision-log', label: 'Decision Log', Component: DecisionLogWidget, width: 'quarter', defaultH: 4 },+ { id: 'activity-streak', label: 'Activity Streak', Component: ActivityStreakWidget, width: 'third', defaultH: 3, gate: (s) => s.usage?.currentStreak > 0 || s.usage?.longestStreak > 0 },+ { id: 'hourly-activity', label: 'Activity by Hour', Component: HourlyActivityWidget, width: 'full', defaultH: 4, gate: (s) => !!s.usage?.hourlyActivity && s.usage.hourlyActivity.some((v) => v > 0) },];export const WIDGETS_BY_ID = Object.fromEntries(WIDGETS.map((w) => [w.id, w]));@@ -54,3 +60,15 @@ export const WIDTH_CLASS = {third: 'col-span-12 md:col-span-6 lg:col-span-4',quarter: 'col-span-12 sm:col-span-6 lg:col-span-3',};++// Width keyword → 12-column grid units. Used when synthesizing a default+// grid for a layout that hasn't been positionally edited yet.+export const WIDTH_TO_COLS = {+ full: 12,+ half: 6,+ third: 4,+ quarter: 3,+};++export const GRID_COLS = 12;+export const GRID_DEFAULT_H = 4;diff --git a/client/src/components/meatspace/tabs/CalendarTab.jsx b/client/src/components/meatspace/tabs/CalendarTab.jsxindex 3a89e704e3..372ae5cd3a 100644--- a/client/src/components/meatspace/tabs/CalendarTab.jsx+++ b/client/src/components/meatspace/tabs/CalendarTab.jsx@@ -8,6 +8,7 @@ import { Link } from 'react-router-dom';import toast from '../../ui/Toast';import * as api from '../../../services/api';import BrailleSpinner from '../../BrailleSpinner';+import useContainerWidth from '../../../hooks/useContainerWidth';const ICON_MAP = {coffee: Coffee, droplets: Droplets, utensils: Utensils, dumbbell: Dumbbell,@@ -111,22 +112,6 @@ const UNIT_CELL_SIZES = {days: { size: 16, gap: 2 },};-// Hook: track container width via ResizeObserver for responsive sizing-function useContainerWidth() {- const ref = useRef(null);- const [width, setWidth] = useState(0);- useEffect(() => {- if (!ref.current) return;- const ro = new ResizeObserver(entries => {- const w = entries[0]?.contentRect?.width;- if (w) setWidth(Math.floor(w));- });- ro.observe(ref.current);- return () => ro.disconnect();- }, []);- return [ref, width];-}-const MS_PER_DAY = 86400000;// === Grid computation helpers ===diff --git a/client/src/hooks/useContainerWidth.js b/client/src/hooks/useContainerWidth.jsnew file mode 100644index 0000000000..f0c6efd7f0--- /dev/null+++ b/client/src/hooks/useContainerWidth.js@@ -0,0 +1,20 @@+import { useEffect, useRef, useState } from 'react';++// Track a container element's width via ResizeObserver. Returns [ref, width]+// — attach the ref to the element you want to measure, read width on each+// render. Width is 0 until the first observer callback fires; consumers+// should treat 0 as "not yet measured" and skip layout math.+export default function useContainerWidth() {+ const ref = useRef(null);+ const [width, setWidth] = useState(0);+ useEffect(() => {+ if (!ref.current) return undefined;+ const ro = new ResizeObserver((entries) => {+ const w = entries[0]?.contentRect?.width;+ if (w) setWidth(Math.floor(w));+ });+ ro.observe(ref.current);+ return () => ro.disconnect();+ }, []);+ return [ref, width];+}diff --git a/client/src/pages/Dashboard.jsx b/client/src/pages/Dashboard.jsxindex e00ab06fd5..5d2d36ff2c 100644--- a/client/src/pages/Dashboard.jsx+++ b/client/src/pages/Dashboard.jsx@@ -3,9 +3,10 @@ import { Link } from 'react-router-dom';import BrailleSpinner from '../components/BrailleSpinner';import LayoutPicker from '../components/dashboard/LayoutPicker';import LayoutEditor from '../components/dashboard/LayoutEditor';-import { WIDGETS_BY_ID, WIDTH_CLASS, FALLBACK_LAYOUT } from '../components/dashboard/widgetRegistry.jsx';+import DashboardGrid, { reconcileGrid, synthesizeGrid } from '../components/dashboard/DashboardGrid.jsx';+import { WIDGETS_BY_ID, FALLBACK_LAYOUT } from '../components/dashboard/widgetRegistry.jsx';import { DASHBOARD_LAYOUT_CHANGED } from '../constants/events.js';-import { Monitor } from 'lucide-react';+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';@@ -23,6 +24,12 @@ export default function Dashboard() {const [layoutLimits, setLayoutLimits] = useState(null);const [activeLayoutId, setActiveLayoutId] = useState(null);const [editorOpen, setEditorOpen] = useState(false);+ // Grid edit mode is local — entered via the "Arrange" button. Holds an+ // in-flight grid snapshot the user can Save/Cancel without touching the+ // server until they commit.+ const [editingGrid, setEditingGrid] = useState(false);+ const [draftGrid, setDraftGrid] = useState(null);+ const [savingGrid, setSavingGrid] = useState(false);const fetchData = useCallback(async () => {setDataError(null);@@ -114,6 +121,52 @@ export default function Dashboard() {[activeLayout, dashboardState]);+ // Build the grid the renderer actually uses:+ // - If the user is mid-edit, prefer the local draft.+ // - Else, if the layout has a saved grid, reconcile it against the+ // visible-widget list (fills in gaps, drops gated/missing widgets).+ // - Else (legacy / unmigrated layouts), synthesize a row-flow grid from+ // the widget order so the layout opens looking like it always has.+ const visibleIds = useMemo(() => visibleWidgets.map((w) => w.id), [visibleWidgets]);+ const renderGrid = useMemo(() => {+ if (editingGrid && draftGrid) return draftGrid;+ if (!activeLayout) return [];+ if (Array.isArray(activeLayout.grid) && activeLayout.grid.length > 0) {+ return reconcileGrid(activeLayout.grid, visibleIds);+ }+ return synthesizeGrid(visibleIds);+ }, [editingGrid, draftGrid, activeLayout, visibleIds]);++ // Cancel grid edit mode whenever the user switches layouts so unsaved+ // positional edits don't bleed across layouts.+ useEffect(() => {+ setEditingGrid(false);+ setDraftGrid(null);+ }, [activeLayoutId]);++ const startGridEdit = () => {+ setDraftGrid(renderGrid);+ setEditingGrid(true);+ };++ const cancelGridEdit = () => {+ setEditingGrid(false);+ setDraftGrid(null);+ };++ const saveGridEdit = async () => {+ if (!activeLayout || !draftGrid) return;+ setSavingGrid(true);+ const ok = await api+ .saveDashboardLayout(activeLayout.id, activeLayout.name, activeLayout.widgets, draftGrid)+ .then((result) => { setLayouts(result.layouts); return true; }, () => false);+ setSavingGrid(false);+ if (!ok) return;+ setEditingGrid(false);+ setDraftGrid(null);+ toast.success('Layout saved');+ };+const selectLayout = async (id) => {const previousId = activeLayoutId;setActiveLayoutId(id);@@ -127,14 +180,27 @@ export default function Dashboard() {});};+ // Preserve the existing grid on widget add/remove so positional edits+ // 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 result = await api.saveDashboardLayout(id, name, widgets);+ 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);setLayouts(result.layouts);};const duplicateLayout = async ({ id, name, widgets }) => {const previousId = activeLayoutId;- const result = await api.saveDashboardLayout(id, name, widgets);+ // 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);setLayouts(result.layouts);setActiveLayoutId(id);// Mirror selectLayout's revert-on-failure so the picker doesn't@@ -176,7 +242,7 @@ export default function Dashboard() {Server: <span className="text-port-success">Online</span></div>)}- {layouts.length > 0 && (+ {layouts.length > 0 && !editingGrid && (<LayoutPickerlayouts={layouts}activeLayoutId={activeLayoutId}@@ -184,6 +250,36 @@ export default function Dashboard() {onEdit={() => setEditorOpen(true)}/>)}+ {!editingGrid && activeLayout && visibleWidgets.length > 0 && (+ <button+ onClick={startGridEdit}+ 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]"+ title="Drag and resize widgets"+ >+ <Move size={14} />+ <span className="hidden sm:inline">Arrange</span>+ </button>+ )}+ {editingGrid && (+ <>+ <button+ onClick={cancelGridEdit}+ disabled={savingGrid}+ 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] disabled:opacity-50"+ >+ <X size={14} />+ <span className="hidden sm:inline">Cancel</span>+ </button>+ <button+ onClick={saveGridEdit}+ disabled={savingGrid}+ className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-port-accent text-white hover:bg-port-accent/80 transition-colors text-sm min-h-[40px] disabled:opacity-50"+ >+ <Save size={14} />+ <span className="hidden sm:inline">{savingGrid ? 'Saving…' : 'Save layout'}</span>+ </button>+ </>+ )}<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]"@@ -219,13 +315,24 @@ export default function Dashboard() {)}{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} />+ <>+ {editingGrid && (+ <div className="rounded-lg border border-port-accent/40 bg-port-accent/5 px-3 py-2 text-sm text-gray-300">+ Drag the <Move size={12} className="inline mx-0.5" /> handle to move widgets, or+ the <span className="inline-block px-1">↘</span> handle to resize. Click <strong className="text-white">Save layout</strong> when you're done.</div>- ))}- </div>+ )}+ <DashboardGrid+ items={renderGrid}+ editable={editingGrid}+ onChange={setDraftGrid}+ renderItem={(item) => {+ const meta = WIDGETS_BY_ID[item.id];+ if (!meta) return null;+ return <meta.Component dashboardState={dashboardState} />;+ }}+ />+ </>)}{editorOpen && layouts.length > 0 && (diff --git a/client/src/services/apiDashboard.js b/client/src/services/apiDashboard.jsindex d2967531c2..58bf68be6f 100644--- a/client/src/services/apiDashboard.js+++ b/client/src/services/apiDashboard.js@@ -8,10 +8,10 @@ export const setActiveDashboardLayout = (id) =>body: JSON.stringify({ id }),});-export const saveDashboardLayout = (id, name, widgets) =>+export const saveDashboardLayout = (id, name, widgets, grid) =>request(`/dashboard/layouts/${encodeURIComponent(id)}`, {method: 'PUT',- body: JSON.stringify({ name, widgets }),+ body: JSON.stringify({ name, widgets, grid: grid ?? [] }),});export const deleteDashboardLayout = (id) =>diff --git a/server/routes/dashboardLayouts.js b/server/routes/dashboardLayouts.jsindex c86b6a88b6..d8b2b5f8db 100644--- a/server/routes/dashboardLayouts.js+++ b/server/routes/dashboardLayouts.js@@ -17,6 +17,19 @@ const router = Router();// at the API boundary agree by construction.const idSchema = z.string().trim().min(1).max(svc.ID_MAX_LENGTH).regex(svc.ID_PATTERN, 'id must be lowercase kebab');+// Grid items carry per-widget x/y/w/h so the dashboard can render a+// free-form layout. Bounds mirror the service-layer sanitizeGridItem so+// reads and writes agree by construction. The route enforces structural+// validity here; cross-field invariants (id ∈ widgets, dedup, x+w ≤ cols)+// are enforced by the .refine() on layoutSchema below and the service.+const gridItemSchema = z.object({+ id: z.string().trim().min(1).max(svc.WIDGET_ID_MAX_LENGTH),+ x: z.number().int().min(0).max(svc.GRID_COLS - 1),+ y: z.number().int().min(0).max(svc.GRID_ROW_MAX),+ w: z.number().int().min(1).max(svc.GRID_COLS),+ h: z.number().int().min(1).max(svc.GRID_ITEM_H_MAX),+});+const layoutSchema = z.object({id: idSchema,// Trim before min-length check so whitespace-only names are rejected.@@ -28,7 +41,26 @@ const layoutSchema = z.object({.array(z.string().trim().min(1).max(svc.WIDGET_ID_MAX_LENGTH)).max(svc.WIDGETS_MAX).refine((w) => new Set(w).size === w.length, { message: 'widgets must be unique' }),-});+ // Optional — older clients (and pre-migration layouts) post no `grid` and+ // the dashboard auto-flows widgets. When present, grid items must:+ // 1. reference a widget that's in the `widgets` list (no orphans),+ // 2. be unique by id (one position per widget), and+ // 3. fit horizontally (x + w ≤ GRID_COLS).+ grid: z+ .array(gridItemSchema)+ .max(svc.WIDGETS_MAX)+ .optional()+ .default([]),+}).refine(+ (l) => l.grid.every((g) => l.widgets.includes(g.id)),+ { message: 'grid items must reference widgets in the layout', path: ['grid'] }+).refine(+ (l) => new Set(l.grid.map((g) => g.id)).size === l.grid.length,+ { message: 'grid items must be unique by id', path: ['grid'] }+).refine(+ (l) => l.grid.every((g) => g.x + g.w <= svc.GRID_COLS),+ { message: 'grid item x+w must fit in cols', path: ['grid'] }+);const setActiveSchema = z.object({id: idSchema,diff --git a/server/routes/dashboardLayouts.test.js b/server/routes/dashboardLayouts.test.jsindex f15164d2d1..3bc8d605ac 100644--- a/server/routes/dashboardLayouts.test.js+++ b/server/routes/dashboardLayouts.test.js@@ -11,6 +11,9 @@ vi.mock('../services/dashboardLayouts.js', () => ({NAME_MAX_LENGTH: 80,WIDGETS_MAX: 50,WIDGET_ID_MAX_LENGTH: 80,+ GRID_COLS: 12,+ GRID_ROW_MAX: 200,+ GRID_ITEM_H_MAX: 50,getState: vi.fn(),setActiveLayout: vi.fn(),saveLayout: vi.fn(),@@ -83,6 +86,7 @@ describe('PUT /api/dashboard/layouts/:id', () => {id: 'my-custom',name: 'Custom',widgets: ['apps', 'cos'],+ grid: [],});});@@ -101,6 +105,84 @@ describe('PUT /api/dashboard/layouts/:id', () => {expect(res.status).toBe(400);expect(svc.saveLayout).not.toHaveBeenCalled();});++ it('saves a layout with a grid', async () => {+ svc.saveLayout.mockResolvedValue({ activeLayoutId: 'default', layouts: [] });+ const res = await request(makeApp())+ .put('/api/dashboard/layouts/my-custom')+ .send({+ name: 'Custom',+ widgets: ['apps', 'cos'],+ grid: [+ { id: 'apps', x: 0, y: 0, w: 12, h: 4 },+ { id: 'cos', x: 0, y: 4, w: 6, h: 3 },+ ],+ });+ expect(res.status).toBe(200);+ expect(svc.saveLayout).toHaveBeenCalledWith({+ id: 'my-custom',+ name: 'Custom',+ widgets: ['apps', 'cos'],+ grid: [+ { id: 'apps', x: 0, y: 0, w: 12, h: 4 },+ { id: 'cos', x: 0, y: 4, w: 6, h: 3 },+ ],+ });+ });++ it('rejects grid items that reference unknown widgets', async () => {+ const res = await request(makeApp())+ .put('/api/dashboard/layouts/my-custom')+ .send({+ name: 'Custom',+ widgets: ['apps'],+ grid: [{ id: 'apps', x: 0, y: 0, w: 4, h: 4 }, { id: 'ghost', x: 4, y: 0, w: 4, h: 4 }],+ });+ expect(res.status).toBe(400);+ expect(svc.saveLayout).not.toHaveBeenCalled();+ });++ it('rejects grid items where x+w exceeds the column count', async () => {+ const res = await request(makeApp())+ .put('/api/dashboard/layouts/my-custom')+ .send({+ name: 'Custom',+ widgets: ['apps'],+ grid: [{ id: 'apps', x: 6, y: 0, w: 8, h: 4 }],+ });+ expect(res.status).toBe(400);+ expect(svc.saveLayout).not.toHaveBeenCalled();+ });++ it('rejects duplicate grid ids', async () => {+ const res = await request(makeApp())+ .put('/api/dashboard/layouts/my-custom')+ .send({+ name: 'Custom',+ widgets: ['apps'],+ grid: [+ { id: 'apps', x: 0, y: 0, w: 4, h: 4 },+ { id: 'apps', x: 4, y: 0, w: 4, h: 4 },+ ],+ });+ expect(res.status).toBe(400);+ expect(svc.saveLayout).not.toHaveBeenCalled();+ });++ it('accepts a layout with no grid (back-compat for unmigrated clients)', async () => {+ svc.saveLayout.mockResolvedValue({ activeLayoutId: 'default', layouts: [] });+ const res = await request(makeApp())+ .put('/api/dashboard/layouts/my-custom')+ .send({ name: 'Custom', widgets: ['apps'] });+ expect(res.status).toBe(200);+ // Default-applied grid is an empty array — defaults inside .refine() chain.+ expect(svc.saveLayout).toHaveBeenCalledWith({+ id: 'my-custom',+ name: 'Custom',+ widgets: ['apps'],+ grid: [],+ });+ });});describe('PUT /api/dashboard/layouts/active — id validation', () => {diff --git a/server/services/dashboardLayouts.js b/server/services/dashboardLayouts.jsindex 47b4e9b38b..b9e96f9a84 100644--- a/server/services/dashboardLayouts.js+++ b/server/services/dashboardLayouts.js@@ -24,6 +24,11 @@ const makeErr = (message, code) => Object.assign(new Error(message), { code });// Widget ids are the contract between this file and the client registry —// see client/src/components/dashboard/widgetRegistry.jsx. If a layout refers// to an unknown id, the client skips it gracefully.+// Built-in layouts ship with a `grid` so they look right out-of-the-box+// instead of falling back to the client's row-flow synthesis. The grids+// 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.const DEFAULT_LAYOUTS = [{id: 'default',@@ -36,24 +41,78 @@ const DEFAULT_LAYOUTS = ['proactive-alerts', 'review-hub', 'system-health', 'backup', 'death-clock', 'quick-stats', 'decision-log','activity-streak', 'hourly-activity',],+ // Above-the-fold (rows 0–7): capture row + the 3 most-glanced widgets+ // (system-health, cos, upcoming-tasks). Everything else stacks below.+ grid: [+ // Row 0–1: capture row + tasks+ { id: 'quick-brain', x: 0, y: 0, w: 3, h: 2 },+ { id: 'quick-task', x: 3, y: 0, w: 5, h: 2 },+ { id: 'upcoming-tasks', x: 8, y: 0, w: 4, h: 4 },+ // Row 2–6: primary monitoring + alerts+ { id: 'system-health', x: 0, y: 2, w: 5, h: 5 },+ { id: 'proactive-alerts', x: 5, y: 2, w: 3, h: 3 },+ { id: 'death-clock', x: 8, y: 4, w: 4, h: 2 },+ { id: 'review-hub', x: 5, y: 5, w: 3, h: 2 },+ { id: 'activity-streak', x: 9, y: 6, w: 3, h: 3 },+ // Row 7–10: secondary widgets+ { id: 'backup', x: 0, y: 7, w: 3, h: 4 },+ { id: 'quick-stats', x: 3, y: 7, w: 3, h: 3 },+ { id: 'goal-progress', x: 6, y: 7, w: 3, h: 4 },+ // Row 11–14: lower-priority + cos+ { id: 'decision-log', x: 0, y: 11, w: 4, h: 2 },+ { id: 'cos', x: 4, y: 11, w: 5, h: 4 },+ // Row 15+: full-width visualizations + apps+ { id: 'hourly-activity', x: 0, y: 15, w: 12, h: 3 },+ { id: 'apps', x: 0, y: 18, w: 12, h: 8 },+ ],},{id: 'focus',name: 'Focus',builtIn: true,widgets: ['quick-task', 'upcoming-tasks', 'cos'],+ // All three widgets above the fold. Quick-task small at top-left for+ // capture; upcoming-tasks tall on the right (the focus list); cos+ // below quick-task for streak/progress context.+ grid: [+ { id: 'quick-task', x: 0, y: 0, w: 6, h: 2 },+ { id: 'upcoming-tasks', x: 6, y: 0, w: 6, h: 8 },+ { id: 'cos', x: 0, y: 2, w: 6, h: 6 },+ ],},{id: 'morning-review',name: 'Morning Review',builtIn: true,widgets: ['proactive-alerts', 'upcoming-tasks', 'review-hub', 'goal-progress', 'death-clock'],+ // Scan-and-act morning ritual — all 5 widgets above the fold.+ // Tasks list takes the tall center column (the actionable hot zone);+ // alerts top-left grab attention first; death-clock top-right for+ // mortality framing; review + goals fill the remaining quadrants.+ grid: [+ { id: 'proactive-alerts', x: 0, y: 0, w: 4, h: 4 },+ { id: 'upcoming-tasks', x: 4, y: 0, w: 5, h: 8 },+ { id: 'death-clock', x: 9, y: 0, w: 3, h: 2 },+ { id: 'goal-progress', x: 9, y: 2, w: 3, h: 4 },+ { id: 'review-hub', x: 0, y: 4, w: 4, h: 4 },+ ],},{id: 'ops',name: 'Ops',builtIn: true,widgets: ['system-health', 'cos', 'backup', 'apps', 'quick-stats'],+ // System monitoring focus — system-health takes the tall left column+ // (the primary alarm surface), cos in the center for ChiefOfStaff+ // status, backup + quick-stats stacked on the right, apps grid fills+ // the empty cell below cos so all 5 widgets fit above the fold.+ grid: [+ { id: 'system-health', x: 0, y: 0, w: 6, h: 5 },+ { id: 'quick-stats', x: 6, y: 0, w: 6, h: 3 },+ { id: 'cos', x: 6, y: 3, w: 6, h: 4 },+ { id: 'backup', x: 0, y: 5, w: 6, h: 3 },+ { id: 'apps', x: 0, y: 8, w: 12, h: 11 },+ ],},];@@ -73,6 +132,32 @@ export const NAME_MAX_LENGTH = 80;export const WIDGETS_MAX = 50;export const WIDGET_ID_MAX_LENGTH = 80;+// Grid placement bounds. The dashboard is a 12-column responsive grid; rows+// are integer steps (each ~80px tall). GRID_ROW_MAX caps total layout depth+// so a hand-edited file can't push y to absurd values that break the+// container-height calculation in DashboardGrid.jsx.+export const GRID_COLS = 12;+export const GRID_ROW_MAX = 200;+export const GRID_ITEM_H_MAX = 50;++// 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+// off-grid positions that break the snap math in the client renderer.+const sanitizeGridItem = (g, validIds) => {+ if (!g || typeof g !== 'object') return null;+ if (typeof g.id !== 'string') return null;+ const id = g.id.trim();+ if (!id || !validIds.has(id)) return null;+ const numOr = (v, fallback) => (Number.isFinite(v) ? Math.floor(v) : fallback);+ const x = Math.max(0, Math.min(GRID_COLS - 1, numOr(g.x, 0)));+ const y = Math.max(0, Math.min(GRID_ROW_MAX, numOr(g.y, 0)));+ const wRaw = Math.max(1, Math.min(GRID_COLS, numOr(g.w, 1)));+ const w = Math.min(wRaw, GRID_COLS - x);+ const h = Math.max(1, Math.min(GRID_ITEM_H_MAX, numOr(g.h, 1)));+ return { id, x, y, w, h };+};+// Sanitize a single layout entry — protect against hand-edits that produce// non-object elements, missing fields, non-array widget lists, or duplicate// widget ids (duplicates would collide on React keys in the grid).@@ -98,7 +183,22 @@ const sanitizeLayout = (l) => {if (widgets.length >= WIDGETS_MAX) break;}}- return { id: l.id, name, builtIn: BUILTIN_IDS.has(l.id), widgets };+ // Grid items must reference a widget in the layout's `widgets` list — a+ // grid entry without a matching widget is dead data and would render+ // nothing. Dedup by id so two entries can't both claim the same widget.+ const validIds = new Set(widgets);+ const grid = [];+ const seenGrid = new Set();+ if (Array.isArray(l.grid)) {+ for (const g of l.grid) {+ const item = sanitizeGridItem(g, validIds);+ if (!item) continue;+ if (seenGrid.has(item.id)) continue;+ seenGrid.add(item.id);+ grid.push(item);+ }+ }+ return { id: l.id, name, builtIn: BUILTIN_IDS.has(l.id), widgets, grid };};// Bundled so clients can enforce the same limits without duplicating magic@@ -108,8 +208,31 @@ export const LIMITS = Object.freeze({nameMaxLength: NAME_MAX_LENGTH,widgetsMax: WIDGETS_MAX,widgetIdMaxLength: WIDGET_ID_MAX_LENGTH,+ gridCols: GRID_COLS,+ gridRowMax: GRID_ROW_MAX,+ gridItemHeightMax: GRID_ITEM_H_MAX,});+// Read-time hydration for upgrades: existing installs already have built-in+// layouts persisted with `grid: []` (from before the grid feature shipped).+// When we ship better default grids, we want those installs to pick them+// up — but only when the user hasn't already arranged the layout (grid+// non-empty) AND hasn't customized which widgets are in it. If the widget+// list still matches the default, swap in the default grid; otherwise+// leave grid empty and let the client's synthesizeGrid handle it.+function hydrateDefaultGrid(layout) {+ if (!BUILTIN_IDS.has(layout.id)) return layout;+ if (layout.grid.length > 0) return layout;+ const def = DEFAULT_LAYOUTS.find((l) => l.id === layout.id);+ if (!def?.grid) return layout;+ // Widget-list match check: same set of ids (order doesn't matter for+ // grid validity since positions are explicit).+ if (layout.widgets.length !== def.widgets.length) return layout;+ const defSet = new Set(def.widgets);+ if (!layout.widgets.every((w) => defSet.has(w))) return layout;+ return { ...layout, grid: def.grid.map((g) => ({ ...g })) };+}+export async function getState() {await ensureDir(PATHS.data);const raw = await readJSONFile(STATE_PATH, DEFAULT_STATE, { logError: false });@@ -120,7 +243,7 @@ export async function getState() {const s = sanitizeLayout(entry);if (!s || seenIds.has(s.id)) continue; // first-occurrence wins; no React key collisionsseenIds.add(s.id);- sanitized.push(s);+ sanitized.push(hydrateDefaultGrid(s));}}const layouts = sanitized.length > 0 ? sanitized : DEFAULT_LAYOUTS;