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
Make the dashboard and Brain capture form appear faster on a phone (#12779)
[._.]/d1a1529c5fb8
diff --git a/client/src/App.jsx b/client/src/App.jsxindex 56c154b881..84334b7cb7 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -90,7 +90,15 @@ const DeckDetail = lazyWithReload(() => import('./pages/DeckDetail'));const CreateApp = lazyWithReload(() => import('./pages/CreateApp'));const Templates = lazyWithReload(() => import('./pages/Templates'));const PromptManager = lazyWithReload(() => import('./pages/PromptManager'));-const Brain = lazyWithReload(() => import('./pages/Brain'));+// Inbox (the capture form) is Brain's landing tab and its own lazy chunk; start+// it alongside the page chunk instead of after it renders, one round trip+// fewer before the form can take input on a phone.+const Brain = lazyWithReload(() => {+ if (/^\/brain(\/inbox)?\/?$/.test(window.location.pathname)) {+ import('./components/brain/tabs/InboxTab').catch(() => {});+ }+ return import('./pages/Brain');+});const BrainScanReport = lazyWithReload(() => import('./pages/BrainScanReport'));const Security = lazyWithReload(() => import('./pages/Security'));const DigitalTwin = lazyWithReload(() => import('./pages/DigitalTwin'));diff --git a/client/src/components/Layout.test.jsx b/client/src/components/Layout.test.jsxindex 88274e1dd6..ed7a5e9d57 100644--- a/client/src/components/Layout.test.jsx+++ b/client/src/components/Layout.test.jsx@@ -88,7 +88,6 @@ vi.mock('../services/api', () => ({getApps: vi.fn(() => Promise.resolve([])),listPipelineSeriesNames: vi.fn(() => Promise.resolve([])),listUniverseNames: vi.fn(() => Promise.resolve([])),- getDailyActions: vi.fn(() => Promise.resolve({ actions: [] })),getReviewQueue: vi.fn(() => new Promise(() => {})),getInstanceFeatures: vi.fn(() => Promise.resolve({ features: featureMock.features })),}));diff --git a/client/src/components/dashboard/AGENTS.md b/client/src/components/dashboard/AGENTS.mdindex 16069b603e..27c8e17180 100644--- a/client/src/components/dashboard/AGENTS.md+++ b/client/src/components/dashboard/AGENTS.md@@ -21,10 +21,12 @@ On drop, `onDragEnd` re-flows the whole grid through `reflowToOrder` so its read**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. By default `reconcileGrid` iterates the *grid* and uses `widgets` only for membership — position edits survive a widget toggle or a rename. LayoutEditor's Move up/down buttons therefore have to say so explicitly: `save`/`commitDuplicate` pass `reordered`, which `isReordered()` derives by comparing the draft list against the `unmovedOrder` ref — the order the draft would have had if the user had never pressed Move (`add` appends to it, `remove` filters it, `move` deliberately doesn't touch it). That baseline can't be reconstructed from the widget list after the fact, since nothing in it records which widgets were added this session or in what order; keeping it means a move-up-then-back nets out to `false` while a just-added widget being moved, or any reorder in a layout that started empty, still reads as `true`, and `Dashboard.jsx` forwards it as `reconcileGrid(base, widgets, { reorder })`, which re-flows the reconciled grid to the list order. **Never infer that flag by comparing `widgets` to `readingOrderIds(grid)`** — layouts arranged before `saveGridEdit` started syncing the two can already disagree, so inferring would re-pack a carefully arranged desktop layout on the first unrelated save (#4132).**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` from the widget's rough content height (default `4`); it only has to be close, since the cell measures itself once painted.-2. If the widget needs dashboard data (apps/health), read it from the `dashboardState` prop — do NOT issue a duplicate fetch from inside the widget.+1. Add a `{ id, label, Component, width, defaultH?, needs?, gate? }` entry to `WIDGETS` in `widgetRegistry.jsx`. Use a stable `id` (kebab-case) — it's the contract stored in layouts. Pick `defaultH` from the widget's rough content height (default `4`); it only has to be close, since the cell measures itself once painted.+2. If the widget needs dashboard data (apps/health), read it from the `dashboardState` prop — do NOT issue a duplicate fetch from inside the widget — and list the streams it (or its `gate`) reads in `needs`. The page fetches only the streams the active layout's widgets need, and passes `dashboardState` only to widgets that declare `needs`; a widget without it gets no prop, so it is not re-rendered as each stream lands.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, and arrange/resize them via the "Arrange" button.+**First paint comes from a local copy (`dashboardBoot.js`).** The last server-confirmed layouts response is cached in `localStorage`, so a reload paints the user's grid and starts its widget chunks before `GET /api/dashboard/layouts` returns, and data reads wait until a layout is known so they never queue the layouts read behind them on a phone's handful of HTTP/1.1 connections. The cached copy is display-only: the picker, Arrange and the editor stay hidden until the server's copy lands, and the cache is never written back.+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/dashboardBoot.js b/client/src/components/dashboard/dashboardBoot.jsnew file mode 100644index 0000000000..55694af396--- /dev/null+++ b/client/src/components/dashboard/dashboardBoot.js@@ -0,0 +1,41 @@+import { safeReadJsonStorage, safeWriteJsonStorage } from '../../lib/safeStorage';+import { WIDGETS_BY_ID } from './widgetRegistry.jsx';++// The last server-confirmed layouts response, kept so a reload paints the+// user's own grid (and starts its widget chunks downloading) before the+// layouts GET returns. The server read still runs and always wins; this copy+// is only a first-paint hint and is never written back.+export const LAYOUT_CACHE_KEY = 'portos.dashboard.layoutsCache.v1';++const isCachedLayout = (l) => !!l && typeof l === 'object'+ && typeof l.id === 'string'+ && Array.isArray(l.widgets) && l.widgets.every((id) => typeof id === 'string')+ && (l.grid === undefined || Array.isArray(l.grid));++// Returns { layouts, activeLayoutId } or null for a missing, corrupt, or+// foreign-shaped entry.+export function readLayoutCache() {+ const cached = safeReadJsonStorage(LAYOUT_CACHE_KEY, null);+ if (!cached || !Array.isArray(cached.layouts) || cached.layouts.length === 0) return null;+ if (!cached.layouts.every(isCachedLayout)) return null;+ return {+ layouts: cached.layouts,+ activeLayoutId: typeof cached.activeLayoutId === 'string' ? cached.activeLayoutId : null,+ };+}++export function writeLayoutCache(layouts, activeLayoutId) {+ if (!Array.isArray(layouts) || layouts.length === 0) return;+ safeWriteJsonStorage(LAYOUT_CACHE_KEY, { layouts, activeLayoutId });+}++// The dashboardState streams a layout's widgets read (registry `needs`), so the+// page skips requests no visible widget would render and leaves the phone's+// few connections free for the ones that will. Sorted for a stable effect key.+export function streamsForWidgets(widgetIds) {+ const needed = new Set();+ for (const id of widgetIds ?? []) {+ for (const stream of WIDGETS_BY_ID[id]?.needs ?? []) needed.add(stream);+ }+ return [...needed].sort();+}diff --git a/client/src/components/dashboard/widgetRegistry.jsx b/client/src/components/dashboard/widgetRegistry.jsxindex da91c3b0d7..2f0a35cba6 100644--- a/client/src/components/dashboard/widgetRegistry.jsx+++ b/client/src/components/dashboard/widgetRegistry.jsx@@ -36,7 +36,11 @@ const postFeatureEnabled = (state) => state?.instanceFeatures?.features?.some((feature) => feature.id === 'post' && feature.enabled === true) === true;-// Each entry: { id, label, Component, width, defaultH?, gate? }.+// Each entry: { id, label, Component, width, defaultH?, needs?, gate? }.+// `needs` names the dashboardState streams the widget (or its gate) reads; the+// page fetches only the streams a layout's widgets need and passes+// `dashboardState` only to widgets that declare one, so a self-fetching widget+// is not re-rendered as each unrelated stream lands.// `gate(state) => bool` skips the widget when it has nothing useful to show.// The Apps tile waits for its first read before rendering so a slow response// cannot flash the empty-state CTA over an existing installation. It still@@ -51,30 +55,30 @@ export const WIDGETS = [{ id: 'daily-actions', label: 'Today\'s Actions', Component: DailyActionsWidget, width: 'full', defaultH: 4 },// Daily Driver self-hides once the day is handled — gated on the per-day// first-visit/handled state so a handled day reserves no grid cell (#2666).- { id: 'daily-driver', label: 'Daily Driver', Component: DailyDriverWidget, width: 'third', defaultH: 6, gate: (s) => !!s.dailyDriver && !s.dailyDriver.handledToday },+ { id: 'daily-driver', label: 'Daily Driver', Component: DailyDriverWidget, width: 'third', needs: ['dailyDriver'], defaultH: 6, gate: (s) => !!s.dailyDriver && !s.dailyDriver.handledToday },{ id: 'quick-brain', label: 'Quick Brain Capture', Component: QuickBrainCapture, width: 'half', defaultH: 4 },{ id: 'quick-idea', label: 'Quick Idea (Catalog)', Component: QuickIdeaCapture, width: 'half', defaultH: 4 },{ id: 'quick-image', label: 'Quick Image Prompt', Component: QuickImagePrompt, width: 'half', defaultH: 6 },{ id: 'quick-task', label: 'Quick Task', Component: QuickTaskWidget, width: 'half', defaultH: 5 },- { id: 'apps', label: 'Apps Grid', Component: AppsGridWidget, width: 'full', defaultH: 5, gate: (s) => s.appsLoading === false },+ { id: 'apps', label: 'Apps Grid', Component: AppsGridWidget, width: 'full', needs: ['apps'], defaultH: 5, gate: (s) => s.appsLoading === false },{ 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: 'while-away', label: 'While You Were Away', Component: WhileAwayWidget, width: 'third', defaultH: 5 },- { id: 'system-health', label: 'System Health', Component: SystemHealthWidget, width: 'quarter', defaultH: 8 },+ { id: 'system-health', label: 'System Health', Component: SystemHealthWidget, width: 'quarter', needs: ['health'], defaultH: 8 },{ id: 'network-exposure', label: 'Network Exposure', Component: NetworkExposureWidget, width: 'quarter', defaultH: 5 },{ id: 'backup', label: 'Backup', Component: BackupWidget, width: 'quarter', defaultH: 5 },{ id: 'death-clock', label: 'Meatspace Time Remaining', Component: DeathClockWidget, width: 'quarter', defaultH: 4 },{ id: 'daily-post', label: 'Daily POST', Component: DailyPostWidget, width: 'quarter', defaultH: 3, gate: postFeatureEnabled },- { id: 'tribe-care', label: 'Tribe Care', Component: TribeCareWidget, width: 'quarter', defaultH: 4, gate: (s) => !!s.tribeCare?.hasPeople },- { id: 'quick-stats', label: 'Quick Stats', Component: QuickStatsWidget, width: 'quarter', defaultH: 3, gate: (s) => s.apps.length > 0 },+ { id: 'tribe-care', label: 'Tribe Care', Component: TribeCareWidget, width: 'quarter', needs: ['tribeCare'], defaultH: 4, gate: (s) => !!s.tribeCare?.hasPeople },+ { id: 'quick-stats', label: 'Quick Stats', Component: QuickStatsWidget, width: 'quarter', needs: ['apps'], defaultH: 3, gate: (s) => s.apps.length > 0 },{ id: 'decision-log', label: 'Decision Log', Component: DecisionLogWidget, width: 'quarter', defaultH: 4 },- { id: 'feeds', label: 'Feeds Digest', Component: FeedsWidget, width: 'quarter', defaultH: 4, gate: (s) => (s.feeds?.totalFeeds ?? 0) > 0 },- { id: 'meatspace-streak', label: 'Health Logging Streak', Component: MeatSpaceStreakWidget, width: 'third', defaultH: 4, gate: (s) => (s.meatspaceLogging?.totalLogged ?? 0) > 0 },- { id: 'today-agenda', label: 'Today\'s Agenda', Component: TodayAgendaWidget, width: 'third', defaultH: 4, gate: (s) => (s.calendarAgenda?.accountCount ?? 0) > 0 },- { id: 'on-this-day', label: 'On This Day', Component: OnThisDayWidget, width: 'third', defaultH: 4, gate: (s) => (s.brainOnThisDay?.total ?? 0) > 0 },+ { id: 'feeds', label: 'Feeds Digest', Component: FeedsWidget, width: 'quarter', needs: ['feeds'], defaultH: 4, gate: (s) => (s.feeds?.totalFeeds ?? 0) > 0 },+ { id: 'meatspace-streak', label: 'Health Logging Streak', Component: MeatSpaceStreakWidget, width: 'third', needs: ['meatspaceLogging'], defaultH: 4, gate: (s) => (s.meatspaceLogging?.totalLogged ?? 0) > 0 },+ { id: 'today-agenda', label: 'Today\'s Agenda', Component: TodayAgendaWidget, width: 'third', needs: ['calendarAgenda'], defaultH: 4, gate: (s) => (s.calendarAgenda?.accountCount ?? 0) > 0 },+ { id: 'on-this-day', label: 'On This Day', Component: OnThisDayWidget, width: 'third', needs: ['brainOnThisDay'], defaultH: 4, gate: (s) => (s.brainOnThisDay?.total ?? 0) > 0 },{ id: 'open-threads', label: 'Open Threads', Component: OpenThreadsWidget, width: 'third', defaultH: 4 },{ id: 'autofix-metrics', label: 'Auto-Fix Telemetry', Component: AutoFixMetricsWidget, width: 'quarter', defaultH: 5 },{ id: 'active-processing', label: 'Active Processing', Component: ActiveProcessingWidget, width: 'half', defaultH: 5 },diff --git a/client/src/pages/Dashboard.boot.test.jsx b/client/src/pages/Dashboard.boot.test.jsxnew file mode 100644index 0000000000..5988d342a4--- /dev/null+++ b/client/src/pages/Dashboard.boot.test.jsx@@ -0,0 +1,76 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { act, render, screen, waitFor } from '@testing-library/react';+import { MemoryRouter } from 'react-router';++vi.mock('../services/socket', async () => {+ const { EventEmitter } = await import('node:events');+ return { default: new EventEmitter() };+});++vi.mock('../services/api', () => ({+ getDashboardLayouts: vi.fn(),+ setActiveDashboardLayout: vi.fn(() => Promise.resolve({})),+ getApps: vi.fn(() => Promise.resolve([])),+ getSystemHealth: vi.fn(() => Promise.resolve({ ok: true })),+ getTribeCareSummary: vi.fn(() => Promise.resolve({ hasPeople: true })),+ getFeedStats: vi.fn(() => Promise.resolve(null)),+ getMeatspaceLoggingStats: vi.fn(() => Promise.resolve(null)),+ getCalendarAgenda: vi.fn(() => Promise.resolve(null)),+ getBrainOnThisDay: vi.fn(() => Promise.resolve(null)),+ getDailyDriverState: vi.fn(() => Promise.resolve(null)),+}));++vi.mock('../hooks/useInstanceFeatures.js', () => ({ useInstanceFeatures: () => ({ features: [] }) }));+vi.mock('../components/onboarding/FirstRunCard.jsx', () => ({ default: () => null }));+vi.mock('../components/SystemHealthWidget', () => ({ default: () => <div>Health body</div> }));+vi.mock('../components/QuickBrainCapture', () => ({ default: () => <div>Quick capture body</div> }));+vi.mock('../components/TribeCareWidget', () => ({+ default: ({ dashboardState }) => <div>Tribe body {dashboardState?.tribeCare ? 'loaded' : 'pending'}</div>,+}));++import * as api from '../services/api';+import Dashboard from './Dashboard';+import { LAYOUT_CACHE_KEY } from '../components/dashboard/dashboardBoot.js';++const LAYOUT = { id: 'mine', name: 'Mine', widgets: ['quick-brain', 'tribe-care', 'system-health'], grid: [] };+const renderPage = () => render(<MemoryRouter><Dashboard /></MemoryRouter>);++describe('Dashboard first paint', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ localStorage.clear();+ });++ it('paints a cached layout and fetches only its streams before the layouts read returns', async () => {+ localStorage.setItem(LAYOUT_CACHE_KEY, JSON.stringify({ layouts: [LAYOUT], activeLayoutId: 'mine' }));+ api.getDashboardLayouts.mockReturnValue(new Promise(() => {}));++ renderPage();++ expect(await screen.findByText('Quick capture body')).toBeInTheDocument();+ expect(await screen.findByText('Tribe body loaded')).toBeInTheDocument();+ expect(api.getTribeCareSummary).toHaveBeenCalledTimes(1);+ expect(api.getApps).not.toHaveBeenCalled();+ expect(api.getFeedStats).not.toHaveBeenCalled();+ // Layout edits wait for the server's copy.+ expect(screen.queryByTitle('Reorder, move and resize widgets')).not.toBeInTheDocument();+ });++ it('holds data reads until the first layouts read lands, then caches it', async () => {+ let resolveLayouts;+ api.getDashboardLayouts.mockReturnValue(new Promise((resolve) => { resolveLayouts = resolve; }));++ renderPage();+ await act(async () => {});+ expect(api.getSystemHealth).not.toHaveBeenCalled();+ expect(api.getTribeCareSummary).not.toHaveBeenCalled();++ await act(async () => resolveLayouts({ layouts: [LAYOUT], activeLayoutId: 'mine' }));++ expect(await screen.findByText('Quick capture body')).toBeInTheDocument();+ await waitFor(() => expect(api.getTribeCareSummary).toHaveBeenCalledTimes(1));+ expect(api.getSystemHealth).toHaveBeenCalledTimes(1);+ expect(JSON.parse(localStorage.getItem(LAYOUT_CACHE_KEY))).toEqual({ layouts: [LAYOUT], activeLayoutId: 'mine' });+ expect(screen.getByTitle('Reorder, move and resize widgets')).toBeInTheDocument();+ });+});diff --git a/client/src/pages/Dashboard.jsx b/client/src/pages/Dashboard.jsxindex 78732e9bce..2e185384a3 100644--- a/client/src/pages/Dashboard.jsx+++ b/client/src/pages/Dashboard.jsx@@ -1,14 +1,14 @@-import { useState, useEffect, useCallback, useMemo, useRef, Suspense } from 'react';+import { memo, useState, useEffect, useCallback, useMemo, useRef, Suspense } from 'react';import { Link } from 'react-router';import BrailleSpinner from '../components/BrailleSpinner';-import PageSkeleton from '../components/ui/PageSkeleton';import LayoutPicker from '../components/dashboard/LayoutPicker';import LayoutEditor from '../components/dashboard/LayoutEditor';import DashboardGrid, { readingOrderIds, reconcileGrid, synthesizeGrid } from '../components/dashboard/DashboardGrid.jsx';import { WIDGETS_BY_ID, FALLBACK_LAYOUT } from '../components/dashboard/widgetRegistry.jsx';+import { readLayoutCache, streamsForWidgets, writeLayoutCache } from '../components/dashboard/dashboardBoot.js';import WidgetSkeleton from '../components/dashboard/WidgetSkeleton';import FirstRunCard from '../components/onboarding/FirstRunCard.jsx';-import { DASHBOARD_LAYOUT_CHANGED, INSTANCE_FEATURES_CHANGED } from '../constants/events.js';+import { DASHBOARD_LAYOUT_CHANGED } from '../constants/events.js';import PageHeader from '../components/PageHeader';import { ChevronsDownUp, GripHorizontal, Monitor, Move, Save, X } from 'lucide-react';import * as api from '../services/api';@@ -19,28 +19,51 @@ import { useInstanceFeatures } from '../hooks/useInstanceFeatures.js';export const isAppsLoading = (appsReadSettled) => !appsReadSettled;+// Optional dashboardState streams, fetched only when a visible widget `needs`+// one. Health (the header dot) and the Daily Driver read (it records the+// first-visit-of-day signal, #2666) are always fetched; apps has its own error+// and settled tracking below.+const OPTIONAL_STREAMS = {+ tribeCare: () => api.getTribeCareSummary({ silent: true }),+ feeds: () => api.getFeedStats({ silent: true }),+ meatspaceLogging: () => api.getMeatspaceLoggingStats({ silent: true }),+ calendarAgenda: () => api.getCalendarAgenda({ silent: true }),+ brainOnThisDay: () => api.getBrainOnThisDay({ silent: true }),+};++// Renders one widget body. Memoized so a widget that declares no `needs`+// (and so receives no dashboardState) skips the re-render each stream's+// arrival triggers in the page.+const WidgetBody = memo(function WidgetBody({ Component, dashboardState }) {+ return dashboardState ? <Component dashboardState={dashboardState} /> : <Component />;+});+export default function Dashboard() {+ // Read once: the cached copy of the last confirmed layouts paints the grid+ // before the layouts GET returns (see dashboardBoot.js).+ const [layoutCache] = useState(readLayoutCache);// null means the first apps read has not completed. Keep that distinct from// a successful empty response so the Apps tile cannot flash its empty-state// CTA while an existing installation is still being read.const [apps, setApps] = useState(null);const [appsReadSettled, setAppsReadSettled] = useState(false);- const [health, setHealth] = useState(null);- const [tribeCare, setTribeCare] = useState(null);- const [feeds, setFeeds] = useState(null);- const [meatspaceLogging, setMeatspaceLogging] = useState(null);- const [calendarAgenda, setCalendarAgenda] = useState(null);- const [brainOnThisDay, setBrainOnThisDay] = useState(null);+ // undefined = first read pending; null = read failed; object = online.+ const [health, setHealth] = useState(undefined);+ const [streams, setStreams] = useState({});const [dailyDriver, setDailyDriver] = useState(null);- const [dailyActions, setDailyActions] = useState(null);- const [loading, setLoading] = useState(true);const [dataError, setDataError] = useState(null);const [layoutsError, setLayoutsError] = useState(null);- const [layouts, setLayouts] = useState([]);+ const [layouts, setLayouts] = useState(() => layoutCache?.layouts ?? []);const [layoutsLoading, setLayoutsLoading] = useState(true);+ // True once the server has answered a layouts read this mount. Until then a+ // cached layout is display-only: layout edits stay hidden so nothing saves+ // a grid the server may have moved past.+ const [layoutsConfirmed, setLayoutsConfirmed] = useState(false);const [layoutLimits, setLayoutLimits] = useState(null);- const [activeLayoutId, setActiveLayoutId] = useState(null);+ const [activeLayoutId, setActiveLayoutId] = useState(() => (+ layoutCache ? pickActiveLayoutId(layoutCache.activeLayoutId, layoutCache.layouts, false) : null+ ));// Last active-layout id the SERVER confirmed (initial GET, a successful// setActive PUT, or a delete response). Failed optimistic switches revert// to this — never to a `previousId` snapshot, which can itself be an@@ -85,73 +108,27 @@ export default function Dashboard() {const refreshHealth = useCallback(async () => {// Keep the last good snapshot visible when a manual refresh hits a- // transient failure. `undefined` is the failed-to-fetch sentinel; a real- // response is always an object, even when some of its collections are empty.+ // transient failure; only a failed FIRST read marks the server offline.const data = await api.getSystemHealth({ silent: true }).catch(() => undefined);if (data) setHealth(data);+ else setHealth((prev) => (prev === undefined ? null : prev));return data;}, []);- const fetchDailyActions = useCallback(- () => api.getDailyActions({ silent: true }).catch(() => null),- [],- );-- const fetchData = useCallback(async () => {- setDataError(null);- // The shell and layout have their own loading states. Release the page- // immediately so a slow PM2/apps read cannot hold the entire dashboard- // behind a single network response.- setLoading(false);- // Apps and the remaining widgets are independent hydration streams. Health- // and daily-actions in particular can involve slow subsystem/database work- // that should not hold every widget behind one Promise.all barrier.- const appsRead = api.getApps({ includeQuality: true })- .catch((err) => { setDataError(err.message); return null; })- .finally(() => setAppsReadSettled(true));- const secondaryRead = Promise.all([- refreshHealth(),- api.getTribeCareSummary({ silent: true }).catch(() => null).then(setTribeCare),- api.getFeedStats({ silent: true }).catch(() => null).then(setFeeds),- api.getMeatspaceLoggingStats({ silent: true }).catch(() => null).then(setMeatspaceLogging),- api.getCalendarAgenda({ silent: true }).catch(() => null).then(setCalendarAgenda),- api.getBrainOnThisDay({ silent: true }).catch(() => null).then(setBrainOnThisDay),- // GET records the first-visit-of-day signal (issue #2666); a failure just- // hides the Daily Driver card via its gate. No LLM calls here.- api.getDailyDriverState().catch(() => null).then(setDailyDriver),- fetchDailyActions().then(setDailyActions),- ]);- const appsData = await appsRead;- if (Array.isArray(appsData)) setApps(appsData);- await secondaryRead;- }, [fetchDailyActions, refreshHealth]);-- useEffect(() => {- fetchData();- const handleAppsChanged = () => fetchData();- socket.on('apps:changed', handleAppsChanged);- return () => {- socket.off('apps:changed', handleAppsChanged);- };- }, [fetchData]);-- // Daily Actions is a dashboard-state consumer rather than a feature-aware- // widget. Refresh it when the shared feature hook applies a toggle so a- // POST action cannot remain visible after POST is disabled (or stay absent- // after it is enabled) until an unrelated dashboard refresh.- useEffect(() => {- let active = true;- const handleFeaturesChanged = () => {- fetchDailyActions().then((data) => {- if (active) setDailyActions(data);- });- };- window.addEventListener(INSTANCE_FEATURES_CHANGED, handleFeaturesChanged);- return () => {- active = false;- window.removeEventListener(INSTANCE_FEATURES_CHANGED, handleFeaturesChanged);- };- }, [fetchDailyActions]);+ // Health and the Daily Driver are always-on reads, and apps has its own+ // fetcher, so names without an OPTIONAL_STREAMS entry are skipped here.+ const fetchStreams = useCallback((names) => Promise.all(names+ .filter((name) => Object.hasOwn(OPTIONAL_STREAMS, name))+ .map((name) => OPTIONAL_STREAMS[name]()+ .catch(() => null)+ .then((value) => setStreams((prev) => ({ ...prev, [name]: value }))))), []);++ const fetchApps = useCallback(() => api.getApps({ includeQuality: true })+ .then((appsData) => {+ setDataError(null);+ if (Array.isArray(appsData)) setApps(appsData);+ }, (err) => setDataError(err.message))+ .finally(() => setAppsReadSettled(true)), []);// One-shot per mount — guards against re-evaluation stomping manual picks.// Serialization across concurrent writers (auto-window + manual pick +@@ -200,6 +177,7 @@ export default function Dashboard() {});}if (data.limits) setLayoutLimits(data.limits);+ setLayoutsConfirmed(true);setLayoutsError(null);}).catch((err) => { if (!cancelled) setLayoutsError(err.message); })@@ -240,11 +218,6 @@ export default function Dashboard() {unknown: activeApps.filter((a) => a.degraded || a.overallStatus === 'unknown').length,}), [activeApps]);- const dashboardState = useMemo(- () => ({ apps: appList, appsLoading, sortedApps, activeApps, appStats, health, tribeCare, feeds, meatspaceLogging, calendarAgenda, brainOnThisDay, dailyDriver, dailyActions, instanceFeatures, refetch: fetchData, refetchHealth: refreshHealth }),- [appList, appsLoading, sortedApps, activeApps, appStats, health, tribeCare, feeds, meatspaceLogging, calendarAgenda, brainOnThisDay, dailyDriver, dailyActions, instanceFeatures, fetchData, refreshHealth]- );-// Falls back to a local minimal layout only AFTER the initial fetch has// settled so the spinner isn't rendered alongside a flash of fallback// widgets. A failed refresh preserves the prior `layouts` (the .catch()@@ -256,6 +229,64 @@ export default function Dashboard() {return layoutsLoading ? undefined : FALLBACK_LAYOUT;}, [layouts, activeLayoutId, layoutsLoading]);+ // Refresh the first-paint copy whenever the server-confirmed view changes.+ useEffect(() => {+ if (layoutsConfirmed) writeLayoutCache(layouts, activeLayoutId);+ }, [layoutsConfirmed, layouts, activeLayoutId]);++ // Data reads start only once a layout is known (instantly from the cache) and+ // only for streams its widgets need, so the layouts read is never queued+ // behind them on a phone's handful of connections.+ const layoutKnown = !!activeLayout;+ const neededStreams = useMemo(() => streamsForWidgets(activeLayout?.widgets), [activeLayout]);+ const neededKey = neededStreams.join(',');+ const neededRef = useRef(neededStreams);+ neededRef.current = neededStreams;+ const fetchedStreamsRef = useRef(new Set());++ const fetchData = useCallback(async () => {+ const needed = neededRef.current;+ needed.forEach((name) => fetchedStreamsRef.current.add(name));+ await Promise.all([+ refreshHealth(),+ // GET records the first-visit-of-day signal (issue #2666); a failure just+ // hides the Daily Driver card via its gate. No LLM calls here.+ api.getDailyDriverState().catch(() => null).then(setDailyDriver),+ needed.includes('apps') ? fetchApps() : null,+ fetchStreams(needed),+ ]);+ }, [fetchApps, fetchStreams, refreshHealth]);++ const initialFetchDoneRef = useRef(false);+ useEffect(() => {+ if (!layoutKnown) return;+ if (!initialFetchDoneRef.current) {+ initialFetchDoneRef.current = true;+ fetchData();+ return;+ }+ // A layout switch that adds a widget fetches just the streams it brings.+ const added = neededRef.current.filter((name) => !fetchedStreamsRef.current.has(name));+ if (added.length === 0) return;+ added.forEach((name) => fetchedStreamsRef.current.add(name));+ if (added.includes('apps')) fetchApps();+ fetchStreams(added);+ }, [layoutKnown, neededKey, fetchData, fetchApps, fetchStreams]);++ useEffect(() => {+ const handleAppsChanged = () => { if (neededRef.current.includes('apps')) fetchApps(); };+ socket.on('apps:changed', handleAppsChanged);+ return () => {+ socket.off('apps:changed', handleAppsChanged);+ };+ }, [fetchApps]);++ const { tribeCare = null, feeds = null, meatspaceLogging = null, calendarAgenda = null, brainOnThisDay = null } = streams;+ const dashboardState = useMemo(+ () => ({ apps: appList, appsLoading, sortedApps, activeApps, appStats, health: health ?? null, tribeCare, feeds, meatspaceLogging, calendarAgenda, brainOnThisDay, dailyDriver, instanceFeatures, refetch: fetchData, refetchHealth: refreshHealth }),+ [appList, appsLoading, sortedApps, activeApps, appStats, health, tribeCare, feeds, meatspaceLogging, calendarAgenda, brainOnThisDay, dailyDriver, instanceFeatures, fetchData, refreshHealth]+ );+const visibleWidgets = useMemo(() => (activeLayout?.widgets ?? []).map((id) => WIDGETS_BY_ID[id])@@ -294,7 +325,7 @@ export default function Dashboard() {// Per-cell Suspense so a slow widget can't block sibling cells.return (<Suspense fallback={<WidgetSkeleton label={meta.label} />}>- <meta.Component dashboardState={dashboardState} />+ <WidgetBody Component={meta.Component} dashboardState={meta.needs ? dashboardState : undefined} /></Suspense>);}, [dashboardState]);@@ -415,17 +446,9 @@ export default function Dashboard() {toast.success('Layout deleted');};- if (loading) {- return (- <PageSkeleton- label="Loading dashboard"- headerRowClass="flex flex-row items-center justify-between gap-2 sm:gap-4"- titleWidthClass="w-40"- layout="grid"- cards={6}- />- );- }+ // Grey while the first health read is pending, so a slow read on a phone+ // doesn't flash "offline" red at a server that is up.+ const healthLabel = health ? 'Server online' : health === undefined ? 'Checking server' : 'Server offline';return (<div className="space-y-6">@@ -439,17 +462,17 @@ export default function Dashboard() {<><spanclassName="relative inline-flex h-2.5 w-2.5"- title={health ? 'Server online' : 'Server offline'}- aria-label={health ? 'Server online' : 'Server offline'}+ title={healthLabel}+ aria-label={healthLabel}>{health && (<span className="absolute inline-flex h-full w-full rounded-full bg-port-success opacity-60 animate-ping" />)}<span- className={`relative inline-flex rounded-full h-2.5 w-2.5 ${health ? 'bg-port-success shadow-[0_0_8px_rgb(var(--port-success))]' : 'bg-port-error shadow-[0_0_8px_rgb(var(--port-error))]'}`}+ className={`relative inline-flex rounded-full h-2.5 w-2.5 ${health ? 'bg-port-success shadow-[0_0_8px_rgb(var(--port-success))]' : health === undefined ? 'bg-gray-600' : 'bg-port-error shadow-[0_0_8px_rgb(var(--port-error))]'}`}/></span>- {layouts.length > 0 && !editingGrid && (+ {layoutsConfirmed && layouts.length > 0 && !editingGrid && (<LayoutPickerlayouts={layouts}activeLayoutId={activeLayoutId}@@ -457,7 +480,7 @@ export default function Dashboard() {onEdit={() => setEditorOpen(true)}/>)}- {!editingGrid && activeLayout && visibleWidgets.length > 0 && (+ {layoutsConfirmed && !editingGrid && activeLayout && visibleWidgets.length > 0 && (<buttononClick={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]"@@ -511,7 +534,7 @@ export default function Dashboard() {</div>)}- {layoutsLoading && !layoutsError && (+ {layoutsLoading && !layoutsError && !activeLayout && (<div className="flex items-center justify-center h-24"><BrailleSpinner text="Loading layout" /></div>@@ -556,7 +579,7 @@ export default function Dashboard() {</>)}- {editorOpen && layouts.length > 0 && (+ {editorOpen && layoutsConfirmed && layouts.length > 0 && (<LayoutEditorlayouts={layouts}activeLayoutId={activeLayoutId}diff --git a/client/src/services/apiDashboard.js b/client/src/services/apiDashboard.jsindex 22e3d9cfa8..ef514959a7 100644--- a/client/src/services/apiDashboard.js+++ b/client/src/services/apiDashboard.js@@ -2,11 +2,6 @@ import { request } from './apiCore.js';export const getDashboardLayouts = () => request('/dashboard/layouts');-// Deterministic product-engagement actions for the dashboard and global-// reminder toast. The server returns explicit unavailable sentinels inside-// `metrics`; callers must not turn those into zero-count activity.-export const getDailyActions = (options = {}) => request('/dashboard/daily-actions', { silent: true, ...options });-// All mutations of dashboard-layouts.json are serialized through a single// module-level promise tail so concurrent callers (Dashboard auto-window,// Dashboard manual pick, ⌘K palette pick, LayoutEditor save) hit the server