Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

let dashboard widgets be reordered on mobile, where drag was switched off entirely

[._.]/ Adam Eivy3aececd3268f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 1de7239c0d..594b7238fe 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -34,6 +34,10 @@
## Fixed
+- **Dragging dashboard widgets did nothing on a phone — "Arrange" opened an edit mode with no handles in it.** The grid renderer collapses to a single-column stack below 640px, and drag was switched off entirely there on the reasoning that a phone has no room for positional editing. That is true of *where* a widget sits, but not of *what order* the stack is in — which is the only thing a phone user can see, and the one arrangement question the mobile layout actually answers. Edit mode on mobile now gives each widget a reorder handle (a wider touch target than the desktop pair) that sorts it up and down the stack. The sort runs through `@dnd-kit/sortable`, the same sensor pairing the CoS task list and the universe-builder chips already use, so it arrives with touch, keyboard (focus the handle, press space, then the arrow keys), screen-reader announcements, multi-pointer safety, and auto-scroll past the fold — none of which a hand-rolled pointer gesture would have had. On drop the grid is re-flowed so its reading order matches the new stack order, preserving every widget's width and height: a one-dimensional edit can only be expressed as 2D coordinates by re-packing, so a mobile reorder does re-pack the wide-screen arrangement, and the edit-mode hint now says so rather than leaving it to be discovered.
+
+ Three things around it were wrong in the same way. The stack rendered in grid-array order, but `placeAndCompact` hoists the moved item to the front of that array on every desktop drag — so a phone showed the most recently moved widget first regardless of where it had been dropped; reading order (`y`, then `x`) is now what both the stack and the DOM/tab order follow. Saving an arrangement left the layout's `widgets` list in its old order, so the layout editor listed widgets in an order the dashboard didn't show; it's rewritten to the grid's reading order on save. And the edit-mode hint picked its wording from a CSS `sm:` breakpoint while the grid picks its mode from its own measured container — page padding makes the container narrower, so in a ~30px band the hint described handles that weren't on screen. The grid reports its mode to the page now, so there is one seam instead of two.
+
- **Quota-burn tasks were queued and then never picked up, so the window they were meant to spend expired unspent anyway.** Three separate faults, each of which alone was enough to strand a burn. First, a queued burn inherited the per-app *review cooldown* — a 30-minute throttle re-stamped by every task that completes on that app. On an app that carries any other recurring CoS work (a perpetual claim-issue drain, which is itself exempt from the cooldown and therefore keeps completing) the cooldown never lapses, so the burn task sat in Pending indefinitely while agents ran past it. The cooldown was never this task's throttle: the burn plan's own gate ladder — the reset horizon, the family's reserve, and `maxDispatchesPerWindow` — is checked before the task is queued at all, so burns now bypass it, as pipeline continuations and perpetual drains already did. Tasks already queued carry no marker, so migration 225 back-fills it onto them rather than leaving them stranded — and a stranded burn is worse than late, because `addTask` dedupes on description + app, so a pending twin makes the runner report "an identical burn task is already pending" and that job in the plan is permanently unreachable. Second, the runner always walked the family's job plan from the top, and an `agent-prompt` job always probes as "work pending" (its probe only checks that an app and a provider resolve) — so job #1 won every dispatch forever and the other seven audits in an eight-job plan never ran once. The walk now resumes after the family's last dispatch, read from the run log rather than a second cursor file, and still runs the first job with pending work from there, so a probing job like `universe-bible-images` keeps its ordering. Third, the plan only advanced once per `checkIntervalMinutes` — at the 12-hour default, two dispatches a day against an allowance of five on a five-hour window. Each finished burn agent now re-evaluates its own family, so the plan is walked one agent at a time until a gate actually closes; the chain is bounded by the same ledger every other cycle charges, and switching the feature off ends it immediately. That re-evaluation reads only the burning family's quota card rather than respawning every enabled provider's TUI for numbers it then discards — a per-family scrape the usage page already asked for this way.
- **Quota Burn was watching the 5-hour window and calling it the weekly one, so its one real gate never gated anything — and it kept dispatching after the provider started refusing.** Every subscription family publishes two windows on the same card: a short rolling one (claude/codex `session` ≈ 5h, antigravity `5-hour`) and a long one (`week`, `month`). Selection picked "the soonest-resetting window", and the short one is nearly always the soonest — so a plan written against a weekly allowance showed "62% left · resets in 3h" on its card, `resetWithinHours: 24` was satisfied by a horizon that re-opened every five hours (making "only spend as the window is about to expire" bound nothing at all), and `maxDispatchesPerWindow: 5` silently meant *five burns every five hours* rather than five per week, because the dispatch ledger keyed on the short window's reset. A family now burns against its **target** window — the broadest one in scope, classified by period in the new `server/lib/quotaWindows.js` — and the card names which window its percentage and countdown describe, so the two can never be confused again. The **limiting** window (the narrowest) and the **tightest** window (least headroom, what `reservePercent` already guarded) stay separate concepts, because they answer different questions; the per-family Window scope field still pins the target explicitly for anyone who wants the old behavior. A provider whose window vocabulary this can't classify falls back to soonest-reset ordering rather than parking.
diff --git a/PLAN.md b/PLAN.md
index e049cedd2f..54e4172449 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -338,3 +338,7 @@ is not reliably announced.
### Hold the iOS `playback` audio session on the other output-only players too
- [ ] The SongBook drum play-along now passes `audioSession: 'playback'` to `createLookaheadTransport` so the iPhone ring/silent switch can't mute it (claimed on play, released on teardown, arbitrated against live mic claims — see the audio-session note in `client/src/lib/audioContext.js`). The same silence still applies to every other output-only surface: `client/src/lib/chiptunePlayback.js` (drives the same transport from `ChiptunePanel`, so it is a one-key change), `client/src/components/meatspace/post/MorseTrainer.jsx` (own per-mount context — needs an `acquireAudioSession('playback')` claim around its own play lifecycle, not the transport option), and `client/src/pages/Security.jsx`'s alert tones. The players NOT to touch are `scorePlayback` / `midiPlayback` / `metronome`: they run on the Songs training views beside `useSingToScore` / `useSingToVerify`, and while the arbiter would now keep those mics working, claiming `playback` there buys nothing those views asked for — that's why the option is per-player rather than baked into the transport. While you're there, claim `play-and-record` in `useSingToScore` / `useSingToVerify` around their own `getUserMedia` for symmetry with `voiceClient` / `audioRecorder`: they are safe today only because no `playback` claimant shares their route, which is an accident of routing rather than an invariant. Each needs an actual iPhone with the ringer switch OFF to verify; a jsdom test can only pin the claim/release calls (as `drumPlayer.test.js` does). Deferred from the drums fix, which was scoped to the reported page. Surfaced by the /simplify altitude review and the codex review pass.
+
+### Make LayoutEditor's Move up/down buttons actually move a widget
+
+- [ ] `client/src/components/dashboard/LayoutEditor.jsx:97` (`move`) reorders the layout's `widgets` array, but `Dashboard.jsx#saveLayout` persists the grid via `reconcileGrid(baseGrid, widgets)`, which iterates the **grid** and uses `widgets` only for membership — and the renderer reads the grid. So once a layout has a `grid` (every layout, after the first Arrange or the `synthesizeGrid` fallback is saved), those buttons produce no visible change at all. The component's own header calls itself a "keyboard-first editor… reorder uses up/down buttons," so this is a control advertising a capability it lost. The mobile reorder handle now edits the same underlying order through `reflowToOrder`, which makes the contradiction user-facing: two reorder affordances for the same widgets, one inert. Fix: have `saveLayout` reflow the grid when the incoming `widgets` order differs from `readingOrderIds(existing.grid)` (both exported from `DashboardGrid.jsx` already). The reason this was NOT rolled into the mobile-drag change: layouts arranged before `saveGridEdit` started syncing `widgets` to reading order can have the two already out of sync, so a naive "orders differ → reflow" would re-pack a carefully arranged desktop layout the first time someone renames it or toggles a widget. Needs either a one-shot migration that stamps `widgets = readingOrderIds(grid)` onto every stored layout (`server/services/dashboardLayouts.js`, `scripts/migrations/`) before the comparison goes live, or a reorder signal from LayoutEditor that says "this save is a reorder" instead of inferring it. Surfaced by the /simplify altitude review.
diff --git a/client/src/components/dashboard/CLAUDE.md b/client/src/components/dashboard/CLAUDE.md
index e0b62ab683..6605d80ae6 100644
--- a/client/src/components/dashboard/CLAUDE.md
+++ b/client/src/components/dashboard/CLAUDE.md
@@ -2,7 +2,15 @@
Dashboard widgets are registered in `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.
+**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 container width, rendered in reading order (`y`, then `x`) — never grid-array order, which `placeAndCompact` deliberately scrambles by hoisting the moved item to the front.
+
+**Mobile editing.** Free-form move/resize is desktop-only (a phone has no room for positional editing), but *reordering* works on mobile: edit mode swaps the two grid handles for a single reorder handle. The 1-D sort goes through **`@dnd-kit/sortable`** — the same `PointerSensor` + `KeyboardSensor` + `verticalListSortingStrategy` pairing as `cos/tabs/TasksTab.jsx` and `universeBuilder/InfluenceChipsInput.jsx` — which is what supplies touch, keyboard (space to lift, arrows to move), multi-pointer safety, screen-reader announcements and edge auto-scroll. **Do not hand-roll a pointer gesture for this**; the free-form 2-D drag stays hand-rolled only because arbitrary grid placement is not what a sortable list does. Use `dndTransformToCss` from `client/src/lib/dndTransform.js` in the style object, never `@dnd-kit/utilities`.
+
+On drop, `onDragEnd` re-flows the whole grid through `reflowToOrder` so its reading order matches the new stack order, preserving each widget's `w`/`h`. That means a mobile reorder re-packs the desktop layout into row-flow — the only coherent way to express a one-dimensional edit as 2D coordinates, and the edit-mode hint says so. `synthesizeGrid` is built on the same helper. The handle keeps `touch-action: none`; without it the browser claims the pointer stream for scrolling and the gesture never starts.
+
+**One source of truth for the mobile/desktop seam.** `DashboardGrid` measures its own *container* (`useContainerWidth`), which page padding makes narrower than the viewport — so a Tailwind `sm:` breakpoint disagrees with it in a ~30px band. Anything outside the grid that needs to know which affordance is live (the Dashboard's edit-mode hint) reads it from the `onLayoutModeChange` callback, never from a CSS breakpoint.
+
+**Widget order lives in the grid.** `saveGridEdit` rewrites the layout's `widgets` array into `readingOrderIds(grid)` so LayoutEditor lists widgets in the order the dashboard actually shows them. Note that `reconcileGrid` iterates the *grid* and uses `widgets` only for membership, so LayoutEditor's own Move up/down buttons currently do not move anything once a layout has a grid — see the PLAN.md item.
**When adding a new dashboard widget:**
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.
diff --git a/client/src/components/dashboard/DashboardGrid.jsx b/client/src/components/dashboard/DashboardGrid.jsx
index 96414368b9..f430285d89 100644
--- a/client/src/components/dashboard/DashboardGrid.jsx
+++ b/client/src/components/dashboard/DashboardGrid.jsx
@@ -1,7 +1,23 @@
-import { useState, useRef, useEffect, useMemo, useCallback } from 'react';
-import { GripVertical, MoveDiagonal2 } from 'lucide-react';
+import { useState, useRef, useEffect, useMemo, useCallback, memo } from 'react';
+import { GripVertical, MoveDiagonal2, GripHorizontal } from 'lucide-react';
+import {
+ DndContext,
+ KeyboardSensor,
+ PointerSensor,
+ closestCenter,
+ useSensor,
+ useSensors,
+} from '@dnd-kit/core';
+import {
+ SortableContext,
+ arrayMove,
+ sortableKeyboardCoordinates,
+ useSortable,
+ verticalListSortingStrategy,
+} from '@dnd-kit/sortable';
import { GRID_COLS, GRID_DEFAULT_H, WIDTH_TO_COLS, WIDGETS_BY_ID } from './widgetRegistry.jsx';
import useContainerWidth from '../../hooks/useContainerWidth';
+import { dndTransformToCss } from '../../lib/dndTransform';
// Free-form 12-column grid with snap-to-grid drag and resize.
//
@@ -17,6 +33,16 @@ import useContainerWidth from '../../hooks/useContainerWidth';
// window-level coordinates regardless of which element the pointer crosses
// — the listener lives on `window` for the duration of the gesture.
//
+// Below MOBILE_BREAKPOINT_PX the grid collapses to a single column, so x/w
+// have nowhere to go — but ORDER still does. There, edit mode swaps the two
+// grid handles for one reorder handle that sorts the stack via dnd-kit (the
+// same PointerSensor/KeyboardSensor pairing as every other sortable list in
+// the app); on drop the whole grid is re-flowed so its reading order matches
+// the new stack order (`reflowToOrder`). The free-form 2-D drag stays
+// hand-rolled — arbitrary grid placement isn't what a sortable list does —
+// but the 1-D case is exactly dnd-kit's job, and going through it is what
+// buys touch, keyboard, multi-pointer and edge auto-scroll for free.
+//
// 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).
@@ -27,15 +53,25 @@ 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.
+// stacked vertically. Free-form move/resize is off there — a phone has no
+// room for positional editing — but drag-to-reorder is on (see above).
+// Deliberately NOT exported: a caller that needs to know which affordance is
+// live gets it from `onLayoutModeChange`, because this threshold is measured
+// against the CONTAINER and re-deriving it outside would read the viewport.
const MOBILE_BREAKPOINT_PX = 640;
function getColWidth(containerWidth) {
return (containerWidth - GAP_PX * (GRID_COLS - 1)) / GRID_COLS;
}
+// Reading order: top-to-bottom, then left-to-right. This is the order the
+// single-column mobile stack renders in, and the order `reflowToOrder`
+// consumes. `placeAndCompact` returns the moved item first regardless of
+// where it landed, so grid array order can't be trusted for this.
+function byReadingOrder(a, b) {
+ return a.y - b.y || a.x - b.x;
+}
+
function rectFor(item, colWidth) {
return {
left: item.x * (colWidth + GAP_PX),
@@ -53,19 +89,39 @@ 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 }) {
+// Everything that differs between the three handles, on one row each. `kind`
+// already discriminates them, so icon/size/placement hang off it rather than
+// travelling as separate props.
+const HANDLE_KINDS = {
+ move: { label: 'Move', Icon: GripVertical, size: 14, className: 'top-1.5 right-1.5 p-1 cursor-move' },
+ resize: { label: 'Resize', Icon: MoveDiagonal2, size: 14, className: 'bottom-1 right-1 p-1 cursor-se-resize' },
+ reorder: {
+ label: 'Reorder',
+ Icon: GripHorizontal,
+ size: 18,
+ // Fatter target than the desktop pair: this one is only ever hit by a thumb.
+ className: 'top-1.5 right-1.5 p-2.5 cursor-grab active:cursor-grabbing',
+ },
+};
+
+// Shared drag/resize/reorder handle. `handleProps` is how dnd-kit's sortable
+// attributes + listeners reach the reorder variant; the two grid handles pass
+// their own onPointerDown instead. `touchAction: 'none'` is what makes any of
+// them work under a finger — without it the browser claims the pointer stream
+// for scrolling.
+function DragHandle({ kind, item, onPointerDown, handleProps }) {
+ const { label, Icon, size, className } = HANDLE_KINDS[kind];
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}`}
+ onPointerDown={onPointerDown}
+ // The registry label, not the raw id — this is read aloud.
+ aria-label={`${label} ${WIDGETS_BY_ID[item.id]?.label ?? item.id}`}
+ className={`absolute z-20 bg-port-bg/90 border border-port-border rounded text-gray-300 hover:text-white hover:border-port-accent ${className}`}
style={{ touchAction: 'none' }}
+ {...handleProps}
>
- <Icon size={14} />
+ <Icon size={size} aria-hidden="true" />
</button>
);
}
@@ -79,9 +135,7 @@ function DragHandle({ kind, item, icon: Icon, onStart, className }) {
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 rest = items.filter((i) => i.id !== movedId).sort(byReadingOrder);
const placed = [{ ...moved }];
for (const item of rest) {
let y = 0;
@@ -101,29 +155,42 @@ export function placeNewWidget(items, widgetId) {
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 = [];
+// Row-flow items into the 12-column grid following `orderedIds`, preserving
+// each item's w/h and dropping anything not in the order. This is how a mobile
+// reorder becomes a grid: the single-column stack has no x/y to drop onto, so
+// the new stack order is re-flowed into fresh coordinates. Items that already
+// sit in flow order (the common case) come back with the same coordinates.
+export function reflowToOrder(items, orderedIds = items.map((it) => it.id)) {
+ const byId = new Map(items.map((it) => [it.id, it]));
+ const flowed = [];
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;
+ for (const id of orderedIds) {
+ const item = byId.get(id);
+ if (!item) continue;
+ const w = Math.min(item.w, GRID_COLS);
if (cursorX + w > GRID_COLS) {
cursorX = 0;
cursorY += rowMaxH;
rowMaxH = 0;
}
- items.push({ id, x: cursorX, y: cursorY, w, h });
+ flowed.push({ ...item, x: cursorX, y: cursorY, w });
cursorX += w;
- rowMaxH = Math.max(rowMaxH, h);
+ rowMaxH = Math.max(rowMaxH, item.h);
}
- return items;
+ return flowed;
+}
+
+// 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) {
+ return reflowToOrder(widgetIds.flatMap((id) => {
+ const meta = WIDGETS_BY_ID[id];
+ if (!meta) return [];
+ return [{ id, w: WIDTH_TO_COLS[meta.width] ?? 4, h: meta.defaultH ?? GRID_DEFAULT_H }];
+ }));
}
// Reconcile a saved grid against the visible widget list. Adds positions for
@@ -147,7 +214,53 @@ export function reconcileGrid(grid, visibleIds) {
return kept;
}
-export default function DashboardGrid({ items, editable, onChange, renderItem }) {
+// Reading order of a grid — what the mobile stack shows, and what a layout's
+// `widgets` array should agree with so LayoutEditor lists them as displayed.
+export function readingOrderIds(grid) {
+ return [...grid].sort(byReadingOrder).map((it) => it.id);
+}
+
+// One dashboard cell. Split out (and memoized) because every indicator tick of
+// a drag re-renders the grid, and without this each tick would re-run
+// `renderItem` for all ~12 widgets to move one card.
+const GridCell = memo(function GridCell({
+ item, isMobile, editable, sortable, colWidth, isGridDragging, gridDragActive,
+ onStartGridDrag, renderItem,
+}) {
+ const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
+ id: item.id,
+ disabled: !sortable,
+ });
+
+ const itemStyle = isMobile
+ ? { transform: dndTransformToCss(transform), transition, opacity: isDragging ? 0.4 : undefined }
+ : rectFor(item, colWidth);
+ const itemClass = isMobile
+ ? 'w-full'
+ : `absolute ${isGridDragging ? 'opacity-40' : ''} ${gridDragActive ? '' : 'transition-[left,top,width,height] duration-150'}`;
+ const innerClass = isMobile
+ ? 'relative'
+ : `relative w-full h-full overflow-hidden rounded-xl ${editable ? 'ring-1 ring-port-border' : ''}`;
+
+ return (
+ <div ref={setNodeRef} className={itemClass} style={itemStyle}>
+ <div className={innerClass}>
+ {renderItem(item)}
+ {editable && !isMobile && (
+ <>
+ <DragHandle kind="move" item={item} onPointerDown={(e) => onStartGridDrag(e, item, 'move')} />
+ <DragHandle kind="resize" item={item} onPointerDown={(e) => onStartGridDrag(e, item, 'resize')} />
+ </>
+ )}
+ {sortable && (
+ <DragHandle kind="reorder" item={item} handleProps={{ ...attributes, ...listeners }} />
+ )}
+ </div>
+ </div>
+ );
+});
+
+export default function DashboardGrid({ items, editable, onChange, onLayoutModeChange, 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
@@ -156,6 +269,18 @@ export default function DashboardGrid({ items, editable, onChange, renderItem })
const [dragGhost, setDragGhost] = useState(null);
const isMobile = containerWidth > 0 && containerWidth < MOBILE_BREAKPOINT_PX;
+ // The mobile/desktop seam is measured off the CONTAINER, so a caller that
+ // wants to describe the active affordance has to be told — a CSS `sm:`
+ // breakpoint reads the viewport and disagrees on a padded page.
+ useEffect(() => {
+ if (containerWidth > 0) onLayoutModeChange?.(isMobile);
+ }, [isMobile, containerWidth, onLayoutModeChange]);
+
+ // Render in reading order always, not grid-array order: the mobile stack
+ // depends on it, and on desktop it keeps DOM/tab order matching what the
+ // eye sees. Keyed children survive reordering, so widget state is safe.
+ const ordered = useMemo(() => [...items].sort(byReadingOrder), [items]);
+ const orderedIds = useMemo(() => ordered.map((it) => it.id), [ordered]);
const totalRows = useMemo(
() => items.reduce((max, it) => Math.max(max, it.y + it.h), 0),
@@ -249,61 +374,69 @@ export default function DashboardGrid({ items, editable, onChange, renderItem })
// gesture starts/ends — pointermove updates dragRef.current directly.
}, [dragGhost ? 'active' : 'idle', items, onChange, containerWidth]);
- // Single render tree across mobile and desktop — only the className/style
- // toggle. If we returned a different JSX shape per mode (separate mobile
- // branch with shallower wrappers), React would unmount every widget on the
- // breakpoint cross, wiping in-progress form input. Rotating an iPhone from
- // portrait (~390px) to landscape (~844px) crosses MOBILE_BREAKPOINT_PX, so
- // structural divergence here = "my Quick Capture text vanished when I
- // rotated." Keep the wrapper depth identical and let CSS handle the rest.
+ // A short activation distance keeps a tap on the handle from registering as
+ // a drag; the keyboard sensor is what makes the handle usable without one.
+ const sensors = useSensors(
+ useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
+ useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
+ );
+
+ const onSortEnd = useCallback(({ active, over }) => {
+ if (!over || active.id === over.id) return;
+ const from = orderedIds.indexOf(active.id);
+ const to = orderedIds.indexOf(over.id);
+ if (from < 0 || to < 0) return;
+ onChange(reflowToOrder(items, arrayMove(orderedIds, from, to)));
+ }, [orderedIds, items, onChange]);
+
+ const sortable = editable && isMobile;
const colWidth = isMobile ? 0 : getColWidth(containerWidth);
- const showDragHandles = editable && !isMobile && containerWidth > 0;
return (
- <div
- ref={containerRef}
- className={isMobile ? 'space-y-4' : 'relative w-full'}
- style={isMobile ? undefined : { height: containerWidth ? containerHeight : 'auto', minHeight: '4rem' }}
- >
- {items.map((item) => {
- const isDragging = !isMobile && dragGhost?.id === item.id;
- const itemStyle = isMobile ? undefined : rectFor(item, colWidth);
- const itemClass = isMobile
- ? 'w-full'
- : `absolute ${isDragging ? 'opacity-40' : ''} ${dragGhost ? '' : 'transition-[left,top,width,height] duration-150'}`;
- const innerClass = isMobile
- ? 'relative'
- : `relative w-full h-full overflow-hidden rounded-xl ${editable ? 'ring-1 ring-port-border' : ''}`;
- return (
- <div key={item.id} className={itemClass} style={itemStyle}>
- <div className={innerClass}>
- {renderItem(item)}
- {showDragHandles && (
- <>
- <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. */}
- {!isMobile && dragGhost && containerWidth > 0 && (
+ // DndContext/SortableContext render no DOM of their own, so they can wrap
+ // unconditionally — which matters, because a conditional wrapper would
+ // remount every widget on a breakpoint cross (see the note below).
+ <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={onSortEnd}>
+ <SortableContext items={orderedIds} strategy={verticalListSortingStrategy}>
+ {/* Single render tree across mobile and desktop — only the
+ className/style toggle. If we returned a different JSX shape per
+ mode (separate mobile branch with shallower wrappers), React would
+ unmount every widget on the breakpoint cross, wiping in-progress
+ form input. Rotating an iPhone from portrait (~390px) to landscape
+ (~844px) crosses MOBILE_BREAKPOINT_PX, so structural divergence
+ here = "my Quick Capture text vanished when I rotated." Keep the
+ wrapper depth identical and let CSS handle the rest. */}
<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>
+ ref={containerRef}
+ className={isMobile ? 'space-y-4' : 'relative w-full'}
+ style={isMobile ? undefined : { height: containerWidth ? containerHeight : 'auto', minHeight: '4rem' }}
+ >
+ {ordered.map((item) => (
+ <GridCell
+ key={item.id}
+ item={item}
+ isMobile={isMobile}
+ editable={editable && containerWidth > 0}
+ sortable={sortable}
+ colWidth={colWidth}
+ isGridDragging={!isMobile && dragGhost?.id === item.id}
+ gridDragActive={Boolean(dragGhost)}
+ onStartGridDrag={startDrag}
+ renderItem={renderItem}
+ />
+ ))}
+
+ {/* Drop preview during the free-form drag — outline showing where
+ the item will land after snap. Pointer-events:none so it never
+ intercepts the gesture. */}
+ {!isMobile && 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>
+ </SortableContext>
+ </DndContext>
);
}
diff --git a/client/src/components/dashboard/DashboardGrid.test.jsx b/client/src/components/dashboard/DashboardGrid.test.jsx
new file mode 100644
index 0000000000..ab27a71288
--- /dev/null
+++ b/client/src/components/dashboard/DashboardGrid.test.jsx
@@ -0,0 +1,198 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen } from '@testing-library/react';
+
+// Stub @dnd-kit/core's DndContext so drag-end can be fired imperatively. The
+// real implementation needs DOM measurement + pointer sensors, which jsdom
+// doesn't provide reliably — and the behavior under test is "what does the
+// grid do when onDragEnd reports these ids," which is all driven through the
+// callback captured here. Same shape as InfluenceChipsInput.test.jsx.
+const dndState = { onDragEnd: null };
+
+vi.mock('@dnd-kit/core', () => ({
+ DndContext: ({ children, onDragEnd }) => {
+ dndState.onDragEnd = onDragEnd;
+ return <>{children}</>;
+ },
+ KeyboardSensor: function KeyboardSensorStub() {},
+ PointerSensor: function PointerSensorStub() {},
+ closestCenter: () => null,
+ useSensor: () => null,
+ useSensors: () => [],
+}));
+
+// Keep arrayMove real (the ordering invariant is the point) but stub the
+// hook + provider, which need a live DndContext.
+vi.mock('@dnd-kit/sortable', async () => {
+ const actual = await vi.importActual('@dnd-kit/sortable');
+ return {
+ ...actual,
+ SortableContext: ({ children }) => <>{children}</>,
+ sortableKeyboardCoordinates: () => null,
+ verticalListSortingStrategy: null,
+ useSortable: ({ disabled }) => ({
+ attributes: { 'data-sortable-disabled': String(Boolean(disabled)) },
+ listeners: {},
+ setNodeRef: () => {},
+ transform: null,
+ transition: null,
+ isDragging: false,
+ }),
+ };
+});
+
+const DashboardGrid = (await import('./DashboardGrid.jsx')).default;
+const { reflowToOrder, synthesizeGrid, reconcileGrid, readingOrderIds } = await import('./DashboardGrid.jsx');
+
+// jsdom has no ResizeObserver, and useContainerWidth (which decides mobile vs
+// desktop) depends on one. Stand in a fake reporting whatever width the test
+// asked for.
+let mockWidth = 1200;
+
+class FakeResizeObserver {
+ constructor(callback) { this.callback = callback; }
+ observe() { this.callback([{ contentRect: { width: mockWidth } }]); }
+ disconnect() {}
+}
+
+beforeEach(() => {
+ vi.stubGlobal('ResizeObserver', FakeResizeObserver);
+ dndState.onDragEnd = null;
+});
+
+const THREE = [
+ { id: 'a', x: 0, y: 0, w: 12, h: 2 },
+ { id: 'b', x: 0, y: 2, w: 12, h: 2 },
+ { id: 'c', x: 0, y: 4, w: 12, h: 2 },
+];
+
+function renderGrid(items = THREE) {
+ const onChange = vi.fn();
+ render(
+ <DashboardGrid
+ items={items}
+ editable
+ onChange={onChange}
+ renderItem={(item) => <div data-testid={`widget-${item.id}`}>{item.id}</div>}
+ />
+ );
+ return onChange;
+}
+
+describe('reflowToOrder', () => {
+ it('renumbers coordinates to match the requested order, keeping w/h', () => {
+ const flowed = reflowToOrder(THREE, ['c', 'a', 'b']);
+ expect(flowed.map((it) => it.id)).toEqual(['c', 'a', 'b']);
+ expect(flowed.map((it) => it.y)).toEqual([0, 2, 4]);
+ expect(flowed.every((it) => it.w === 12 && it.h === 2)).toBe(true);
+ });
+
+ it('packs items that fit side by side into the same row', () => {
+ const items = [
+ { id: 'a', x: 0, y: 0, w: 6, h: 3 },
+ { id: 'b', x: 6, y: 0, w: 6, h: 2 },
+ { id: 'c', x: 0, y: 3, w: 6, h: 2 },
+ ];
+ expect(reflowToOrder(items, ['b', 'a', 'c'])).toEqual([
+ { id: 'b', x: 0, y: 0, w: 6, h: 2 },
+ { id: 'a', x: 6, y: 0, w: 6, h: 3 },
+ { id: 'c', x: 0, y: 3, w: 6, h: 2 },
+ ]);
+ });
+
+ it('leaves an already-in-flow layout untouched, and defaults to the given order', () => {
+ expect(reflowToOrder(THREE, ['a', 'b', 'c'])).toEqual(THREE);
+ expect(reflowToOrder(THREE)).toEqual(THREE);
+ });
+
+ it('drops ids with no matching item and ignores items absent from the order', () => {
+ expect(reflowToOrder(THREE, ['b', 'ghost'])).toEqual([{ id: 'b', x: 0, y: 0, w: 12, h: 2 }]);
+ });
+
+ it('still flows a widget whose stored width exceeds the grid', () => {
+ expect(reflowToOrder([{ id: 'a', x: 0, y: 0, w: 20, h: 2 }], ['a']))
+ .toEqual([{ id: 'a', x: 0, y: 0, w: 12, h: 2 }]);
+ });
+});
+
+describe('readingOrderIds', () => {
+ it('sorts top-to-bottom then left-to-right without mutating the input', () => {
+ const grid = [
+ { id: 'c', x: 0, y: 4, w: 6, h: 2 },
+ { id: 'b', x: 6, y: 0, w: 6, h: 2 },
+ { id: 'a', x: 0, y: 0, w: 6, h: 2 },
+ ];
+ expect(readingOrderIds(grid)).toEqual(['a', 'b', 'c']);
+ expect(grid[0].id).toBe('c');
+ });
+});
+
+describe('synthesizeGrid', () => {
+ it('skips ids that are not registered widgets', () => {
+ expect(synthesizeGrid(['not-a-widget'])).toEqual([]);
+ });
+});
+
+describe('reconcileGrid', () => {
+ it('drops hidden widgets and appends newly visible ones', () => {
+ expect(reconcileGrid(THREE, ['a', 'c']).map((it) => it.id)).toEqual(['a', 'c']);
+ });
+});
+
+describe('DashboardGrid mobile reorder', () => {
+ beforeEach(() => { mockWidth = 400; });
+
+ it('exposes a reorder handle per widget, and no grid move/resize handles', () => {
+ renderGrid();
+ expect(screen.getByLabelText('Reorder a')).toBeInTheDocument();
+ expect(screen.getByLabelText('Reorder c')).toBeInTheDocument();
+ expect(screen.queryByLabelText('Move a')).not.toBeInTheDocument();
+ expect(screen.queryByLabelText('Resize a')).not.toBeInTheDocument();
+ });
+
+ it('enables the sortable so the handle can actually start a drag', () => {
+ renderGrid();
+ expect(screen.getByLabelText('Reorder a')).toHaveAttribute('data-sortable-disabled', 'false');
+ });
+
+ it('reflows the grid to the new order when a widget is dropped on another', () => {
+ const onChange = renderGrid();
+ dndState.onDragEnd({ active: { id: 'a' }, over: { id: 'c' } });
+
+ expect(onChange).toHaveBeenCalledTimes(1);
+ const next = onChange.mock.calls[0][0];
+ expect(next.map((it) => it.id)).toEqual(['b', 'c', 'a']);
+ expect(next.map((it) => it.y)).toEqual([0, 2, 4]);
+ });
+
+ it('reads the drag against reading order, not grid-array order', () => {
+ // placeAndCompact hoists the moved item to the front of the array, so a
+ // saved grid routinely arrives out of visual order.
+ const onChange = renderGrid([
+ { id: 'c', x: 0, y: 4, w: 12, h: 2 },
+ { id: 'a', x: 0, y: 0, w: 12, h: 2 },
+ { id: 'b', x: 0, y: 2, w: 12, h: 2 },
+ ]);
+ expect(screen.getAllByTestId(/^widget-/).map((el) => el.textContent)).toEqual(['a', 'b', 'c']);
+
+ dndState.onDragEnd({ active: { id: 'c' }, over: { id: 'a' } });
+ expect(onChange.mock.calls[0][0].map((it) => it.id)).toEqual(['c', 'a', 'b']);
+ });
+
+ it('does not write when the drag ends on itself or outside the list', () => {
+ const onChange = renderGrid();
+ dndState.onDragEnd({ active: { id: 'a' }, over: { id: 'a' } });
+ dndState.onDragEnd({ active: { id: 'a' }, over: null });
+ expect(onChange).not.toHaveBeenCalled();
+ });
+});
+
+describe('DashboardGrid desktop', () => {
+ beforeEach(() => { mockWidth = 1200; });
+
+ it('keeps the move/resize handles and hides the reorder handle', () => {
+ renderGrid();
+ expect(screen.getByLabelText('Move a')).toBeInTheDocument();
+ expect(screen.getByLabelText('Resize a')).toBeInTheDocument();
+ expect(screen.queryByLabelText('Reorder a')).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/pages/Dashboard.jsx b/client/src/pages/Dashboard.jsx
index 7e71a5170c..ae8f5401a1 100644
--- a/client/src/pages/Dashboard.jsx
+++ b/client/src/pages/Dashboard.jsx
@@ -5,12 +5,12 @@ import PageSkeleton from '../components/ui/PageSkeleton';
import LayoutPicker from '../components/dashboard/LayoutPicker';
import LayoutEditor from '../components/dashboard/LayoutEditor';
import WidgetSuggestions from '../components/dashboard/WidgetSuggestions';
-import DashboardGrid, { reconcileGrid, synthesizeGrid } from '../components/dashboard/DashboardGrid.jsx';
+import DashboardGrid, { readingOrderIds, reconcileGrid, synthesizeGrid } from '../components/dashboard/DashboardGrid.jsx';
import { WIDGETS_BY_ID, FALLBACK_LAYOUT } from '../components/dashboard/widgetRegistry.jsx';
import WidgetSkeleton from '../components/dashboard/WidgetSkeleton';
import { SchematicLabel } from '../components/micrographics';
import { DASHBOARD_LAYOUT_CHANGED } from '../constants/events.js';
-import { Monitor, Move, Save, X } from 'lucide-react';
+import { GripHorizontal, Monitor, Move, Save, X } from 'lucide-react';
import * as api from '../services/api';
import socket from '../services/socket';
import toast from '../components/ui/Toast';
@@ -60,6 +60,12 @@ export default function Dashboard() {
const [editingGrid, setEditingGrid] = useState(false);
const [draftGrid, setDraftGrid] = useState(null);
const [savingGrid, setSavingGrid] = useState(false);
+ // Which affordance the grid is actually offering. Reported by DashboardGrid
+ // rather than derived from a Tailwind `sm:` breakpoint, because the grid
+ // measures its own CONTAINER — page padding makes that narrower than the
+ // viewport, so the two disagree in a ~30px band and the hint would describe
+ // handles that aren't on screen.
+ const [gridIsMobile, setGridIsMobile] = useState(false);
const fetchData = useCallback(async () => {
setDataError(null);
@@ -222,6 +228,37 @@ export default function Dashboard() {
setDraftGrid(null);
}, [activeLayoutId]);
+ // Stable identity so DashboardGrid's memoized cells actually bail out — a
+ // fresh closure here would re-render every widget on each drag tick.
+ const renderWidget = useCallback((item) => {
+ const meta = WIDGETS_BY_ID[item.id];
+ if (!meta) return null;
+ // Per-cell Suspense so a slow widget can't block sibling cells.
+ const widget = (
+ <Suspense fallback={<WidgetSkeleton label={meta.label} />}>
+ <meta.Component dashboardState={dashboardState} />
+ </Suspense>
+ );
+ if (!meta.module) return widget;
+ // Tab sits inside the wrapper (DashboardGrid clips with overflow-hidden);
+ // sm:pt-4 reserves a header zone so the tab doesn't overlap widget
+ // header content.
+ return (
+ <div className="relative h-full sm:pt-4">
+ <span className="hidden sm:inline">
+ <SchematicLabel
+ module={meta.module.id}
+ status={meta.module.status}
+ glyph={meta.module.glyph}
+ state="active"
+ variant="tab"
+ />
+ </span>
+ {widget}
+ </div>
+ );
+ }, [dashboardState]);
+
const startGridEdit = () => {
setDraftGrid(renderGrid);
setEditingGrid(true);
@@ -235,8 +272,17 @@ export default function Dashboard() {
const saveGridEdit = async () => {
if (!activeLayout || !draftGrid) return;
setSavingGrid(true);
+ // Rewrite `widgets` in the grid's reading order too. The grid is what the
+ // renderer reads, so leaving the widget list in its old order would make
+ // LayoutEditor list widgets in an order the dashboard doesn't show —
+ // widgets hidden by a gate keep their relative position at the end.
+ const orderedIds = readingOrderIds(draftGrid);
+ const widgets = [
+ ...orderedIds,
+ ...activeLayout.widgets.filter((id) => !orderedIds.includes(id)),
+ ];
const ok = await api
- .saveDashboardLayout(activeLayout.id, { name: activeLayout.name, widgets: activeLayout.widgets, grid: draftGrid })
+ .saveDashboardLayout(activeLayout.id, { name: activeLayout.name, widgets, grid: draftGrid })
.then((result) => { setLayouts(result.layouts); return true; }, () => false);
setSavingGrid(false);
if (!ok) return;
@@ -369,7 +415,7 @@ export default function Dashboard() {
<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"
+ title="Reorder, move and resize widgets"
>
<Move size={14} />
<span className="hidden sm:inline">Arrange</span>
@@ -446,42 +492,27 @@ export default function Dashboard() {
<>
{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&apos;re done.
+ {gridIsMobile ? (
+ <>
+ Drag the <GripHorizontal size={12} className="inline mx-0.5" /> handle up or down
+ to reorder widgets — or focus it and press space, then the arrow keys. Reordering
+ re-packs the wide-screen arrangement to match; widths and heights are unchanged.
+ </>
+ ) : (
+ <>
+ 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&apos;re done.
</div>
)}
<DashboardGrid
items={renderGrid}
editable={editingGrid}
onChange={setDraftGrid}
- renderItem={(item) => {
- const meta = WIDGETS_BY_ID[item.id];
- if (!meta) return null;
- // Per-cell Suspense so a slow widget can't block sibling cells.
- const widget = (
- <Suspense fallback={<WidgetSkeleton label={meta.label} />}>
- <meta.Component dashboardState={dashboardState} />
- </Suspense>
- );
- if (!meta.module) return widget;
- // Tab sits inside the wrapper (DashboardGrid clips with
- // overflow-hidden); sm:pt-4 reserves a header zone so
- // the tab doesn't overlap widget header content.
- return (
- <div className="relative h-full sm:pt-4">
- <span className="hidden sm:inline">
- <SchematicLabel
- module={meta.module.id}
- status={meta.module.status}
- glyph={meta.module.glyph}
- state="active"
- variant="tab"
- />
- </span>
- {widget}
- </div>
- );
- }}
+ onLayoutModeChange={setGridIsMobile}
+ renderItem={renderWidget}
/>
</>
)}