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
fix: reduce CoS and dashboard load latency
[._.]/ Adam Eivy7da5f3ca57cc
diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex be6a3ed5ec..81aaa84fb4 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -19,30 +19,19 @@ import {summarizeHealthIssues,healthIssueTone,fresherHealth,- CoSCharacter,- StateLabel,- TerminalCoSPanel,- StatusIndicator,- StatCard,- StatusBubble,- EventLog,- QuickSummary,- ActionableInsightsBanner,- TasksTab,- AgentsTab,- JobsTab,- ScheduleTab,- WorkflowTab,- DigestTab,- GsdTab,- ProductivityTab,- LearningTab,- MemoryTab,- HealthTab,- ConfigTab,- BriefingTab-} from '../components/cos';-import { resolveDynamicAvatar } from '../components/cos/constants';+ resolveDynamicAvatar,+} from '../components/cos/constants';+import CoSCharacter from '../components/cos/CoSCharacter';+import StateLabel from '../components/cos/StateLabel';+import TerminalCoSPanel from '../components/cos/TerminalCoSPanel';+import StatusIndicator from '../components/cos/StatusIndicator';+import StatCard from '../components/cos/StatCard';+import StatusBubble from '../components/cos/StatusBubble';+import EventLog from '../components/cos/EventLog';+import QuickSummary from '../components/cos/QuickSummary';+import ActionableInsightsBanner from '../components/cos/ActionableInsightsBanner';+import TasksTab from '../components/cos/tabs/TasksTab';+import AgentsTab from '../components/cos/tabs/AgentsTab';// The Runs tab (full AI run history + its log modal) is lazy-loaded so its weight// stays out of the eager CoS chunk every /cos/* visit pays for — same reason the@@ -52,6 +41,20 @@ const RunsTab = lazy(() => import('../components/cos/tabs/RunsTab'));// post-mortem surface nobody opens on a normal day, and it pulls the whole// ledger read path with it.const RunEventsTab = lazy(() => import('../components/cos/tabs/RunEventsTab'));+// The task and agent tabs are the default CoS landing surfaces and stay eager.+// Every other tab is loaded only when selected so the common queue view does+// not pay for charts, memory graphs, briefing readers, or configuration forms.+const JobsTab = lazy(() => import('../components/cos/tabs/JobsTab'));+const ScheduleTab = lazy(() => import('../components/cos/tabs/ScheduleTab'));+const WorkflowTab = lazy(() => import('../components/cos/tabs/WorkflowTab'));+const DigestTab = lazy(() => import('../components/cos/tabs/DigestTab'));+const GsdTab = lazy(() => import('../components/cos/tabs/GsdTab'));+const ProductivityTab = lazy(() => import('../components/cos/tabs/ProductivityTab'));+const LearningTab = lazy(() => import('../components/cos/tabs/LearningTab'));+const MemoryTab = lazy(() => import('../components/cos/tabs/MemoryTab'));+const HealthTab = lazy(() => import('../components/cos/tabs/HealthTab'));+const ConfigTab = lazy(() => import('../components/cos/tabs/ConfigTab'));+const BriefingTab = lazy(() => import('../components/cos/tabs/BriefingTab'));// Three.js-based avatars lazy-loaded so the R3F stack isn't bundled unless the// user's chosen avatar style actually needs it.@@ -74,6 +77,10 @@ const CANVAS_AVATAR_STYLES = new Set([// Shared brand gradient for the "CoS" wordmark headings (clipped to text).const COS_TITLE_GRADIENT = 'linear-gradient(135deg, #6366f1, #8b5cf6, #06b6d4)';+function TabLoadFallback({ label }) {+ return <div className="flex items-center justify-center py-12"><BrailleSpinner text={`Loading ${label}`} /></div>;+}+export default function ChiefOfStaff() {const { tab } = useParams();const navigate = useNavigate();@@ -164,10 +171,17 @@ export default function ChiefOfStaff() {const fetchData = useCallback(async () => {const queueSeq = queueSeqRef.current;- const [statusData, tasksData, agentsData, healthData, providersData, appsData, learningSummaryData, insightsData] = await Promise.all([+ // The queue is the critical path for both the Tasks and Agents tabs. Start+ // the secondary reads at the same time, but do not make the first paint+ // wait for them: actionable insights runs a server-side PM2/memory health+ // check, and provider/app/learning data can be hydrated after the queue is+ // already usable.+ const coreRead = Promise.all([api.getCosStatus().catch(() => null),api.getCosTasks().catch(() => ({ user: null, cos: null })),api.getCosAgents().catch(() => []),+ ]);+ const secondaryRead = Promise.all([api.getCosHealth().catch(() => null),api.getProviders().catch(() => ({ providers: [] })),api.getApps().catch(() => []),@@ -176,16 +190,32 @@ export default function ChiefOfStaff() {// retired 60s poll; `.catch(() => null)` → preserve last-good below.api.getCosActionableInsights({ silent: true }).catch(() => null)]);++ const [statusData, tasksData, agentsData] = await coreRead;setStatus(statusData);- // fetchData is the SLOW read (8 endpoints, one of which runs a server health- // check), so a queue refresh started later routinely resolves first. Its task- // payload would then be clobbered by this older, pre-flip one — restoring the- // pending-AND-active render this change exists to remove. Drop only the queue- // half of a superseded read; the rest of the batch has no fresher writer.+ // A queue refresh started later can still resolve first. Its task payload+ // must not be clobbered by this older, pre-flip read — otherwise the row+ // returns to the pending-AND-active state this guard exists to remove.if (queueSeqRef.current === queueSeq) {setTasks(tasksData);setAgents(agentsData);}++ setLoading(false);++ // Paint the shell and queue before waiting for health, providers, apps,+ // learning, and insights. Those values fill in below without delaying the+ // tab the user asked to open.+ const initialHealth = healthRef.current;+ const initialState = deriveAgentState(statusData, agentsData, initialHealth);+ setAgentState(initialState);+ setStatusMessage(statusData?.paused+ ? `Paused${statusData.pauseReason ? ` — ${statusData.pauseReason}` : ''}`+ : (initialState === 'investigating' && summarizeHealthIssues(initialHealth?.issues)) || STATE_MESSAGES[initialState]);+ const runningAgent = agentsData.find(a => a.status === 'running');+ setActiveAgentMeta(runningAgent?.metadata || null);++ const [healthData, providersData, appsData, learningSummaryData, insightsData] = await secondaryRead;// `getCosHealth` above reads the *pre-check* persisted health, while the// getCosActionableInsights call in this same batch triggers a fresh server// health check (cos.runHealthCheck) that emits `cos:health:check` — the@@ -203,7 +233,6 @@ export default function ChiefOfStaff() {// from a failed/transient fetch preserves the last-good array so the banner// doesn't flicker empty on a blip.if (insightsData?.insights) setInsights(insightsData.insights);- setLoading(false);const newState = deriveAgentState(statusData, agentsData, mergedHealth);setAgentState(newState);@@ -215,9 +244,6 @@ export default function ChiefOfStaff() {? `Paused${statusData.pauseReason ? ` — ${statusData.pauseReason}` : ''}`: (newState === 'investigating' && summarizeHealthIssues(mergedHealth?.issues)) || STATE_MESSAGES[newState]);- // Set active agent metadata for dynamic avatar (use first running agent)- const runningAgent = agentsData.find(a => a.status === 'running');- setActiveAgentMeta(runningAgent?.metadata || null);}, [deriveAgentState, applyHealth]);// A cheap, read-only refresh of just the queue — the task lists plus the agent@@ -1032,7 +1058,9 @@ export default function ChiefOfStaff() {{/* Tab Content */}{activeTab === 'briefing' && (<div role="tabpanel" id="tabpanel-briefing" aria-labelledby="tab-briefing">- <BriefingTab />+ <Suspense fallback={<TabLoadFallback label="briefing" />}>+ <BriefingTab />+ </Suspense></div>)}{activeTab === 'tasks' && (@@ -1051,66 +1079,86 @@ export default function ChiefOfStaff() {)}{activeTab === 'jobs' && (<div role="tabpanel" id="tabpanel-jobs" aria-labelledby="tab-jobs">- <JobsTab />+ <Suspense fallback={<TabLoadFallback label="jobs" />}>+ <JobsTab />+ </Suspense></div>)}{activeTab === 'runs' && (<div role="tabpanel" id="tabpanel-runs" aria-labelledby="tab-runs">- <Suspense fallback={<div className="flex items-center justify-center py-12"><BrailleSpinner text="Loading runs" /></div>}>+ <Suspense fallback={<TabLoadFallback label="runs" />}><RunsTab /></Suspense></div>)}{activeTab === 'run-events' && (<div role="tabpanel" id="tabpanel-run-events" aria-labelledby="tab-run-events">- <Suspense fallback={<div className="flex items-center justify-center py-12"><BrailleSpinner text="Loading run events" /></div>}>+ <Suspense fallback={<TabLoadFallback label="run events" />}><RunEventsTab /></Suspense></div>)}{activeTab === 'schedule' && (<div role="tabpanel" id="tabpanel-schedule" aria-labelledby="tab-schedule">- <ScheduleTab apps={apps} providers={providers} activeProviderId={activeProviderId} />+ <Suspense fallback={<TabLoadFallback label="schedule" />}>+ <ScheduleTab apps={apps} providers={providers} activeProviderId={activeProviderId} />+ </Suspense></div>)}{activeTab === 'workflow' && (<div role="tabpanel" id="tabpanel-workflow" aria-labelledby="tab-workflow">- <WorkflowTab apps={apps} providers={providers} />+ <Suspense fallback={<TabLoadFallback label="workflow" />}>+ <WorkflowTab apps={apps} providers={providers} />+ </Suspense></div>)}{activeTab === 'digest' && (<div role="tabpanel" id="tabpanel-digest" aria-labelledby="tab-digest">- <DigestTab />+ <Suspense fallback={<TabLoadFallback label="digest" />}>+ <DigestTab />+ </Suspense></div>)}{activeTab === 'gsd' && (<div role="tabpanel" id="tabpanel-gsd" aria-labelledby="tab-gsd">- <GsdTab />+ <Suspense fallback={<TabLoadFallback label="GSD" />}>+ <GsdTab />+ </Suspense></div>)}{activeTab === 'productivity' && (<div role="tabpanel" id="tabpanel-productivity" aria-labelledby="tab-productivity">- <ProductivityTab />+ <Suspense fallback={<TabLoadFallback label="productivity" />}>+ <ProductivityTab />+ </Suspense></div>)}{activeTab === 'learning' && (<div role="tabpanel" id="tabpanel-learning" aria-labelledby="tab-learning">- <LearningTab />+ <Suspense fallback={<TabLoadFallback label="learning" />}>+ <LearningTab />+ </Suspense></div>)}{activeTab === 'memory' && (<div role="tabpanel" id="tabpanel-memory" aria-labelledby="tab-memory">- <MemoryTab apps={apps} />+ <Suspense fallback={<TabLoadFallback label="memory" />}>+ <MemoryTab apps={apps} />+ </Suspense></div>)}{activeTab === 'health' && (<div role="tabpanel" id="tabpanel-health" aria-labelledby="tab-health">- <HealthTab health={health} onCheck={handleHealthCheck} />+ <Suspense fallback={<TabLoadFallback label="health" />}>+ <HealthTab health={health} onCheck={handleHealthCheck} />+ </Suspense></div>)}{activeTab === 'config' && (<div role="tabpanel" id="tabpanel-config" aria-labelledby="tab-config">- <ConfigTab config={status?.config} onUpdate={fetchData} onEvaluate={handleForceEvaluate} avatarStyle={configAvatarStyle} setAvatarStyle={setAvatarStyle} />+ <Suspense fallback={<TabLoadFallback label="configuration" />}>+ <ConfigTab config={status?.config} onUpdate={fetchData} onEvaluate={handleForceEvaluate} avatarStyle={configAvatarStyle} setAvatarStyle={setAvatarStyle} />+ </Suspense></div>)}</div>diff --git a/client/src/pages/ChiefOfStaff.test.jsx b/client/src/pages/ChiefOfStaff.test.jsxindex 75cd9707cd..42cd77a2c6 100644--- a/client/src/pages/ChiefOfStaff.test.jsx+++ b/client/src/pages/ChiefOfStaff.test.jsx@@ -114,6 +114,30 @@ describe('ChiefOfStaff loading skeleton', () => {// The old spinner shell — a fixed 16rem box centering its child.expect(container.querySelector('.h-64')).toBeNull();});++ it('shows the queue before the slow ancillary reads settle', async () => {+ let releaseInsights;+ api.getCosTasks.mockResolvedValue({+ user: { tasks: [{ id: 'task-1', description: 'Example queued task', status: 'pending', metadata: {} }] },+ cos: { tasks: [] },+ });+ api.getCosActionableInsights.mockReturnValue(new Promise((resolve) => { releaseInsights = resolve; }));++ render(+ <MemoryRouter initialEntries={['/cos/tasks']}>+ <Routes>+ <Route path="/cos/:tab" element={<ChiefOfStaff />} />+ </Routes>+ </MemoryRouter>,+ );++ expect(await screen.findByText('Example queued task')).toBeInTheDocument();+ expect(screen.queryByRole('status', { name: 'Loading Chief of Staff' })).toBeNull();++ await act(async () => {+ releaseInsights({ insights: [] });+ });+ });});describe('ChiefOfStaff handleForceEvaluate', () => {diff --git a/client/src/pages/Dashboard.jsx b/client/src/pages/Dashboard.jsxindex 9e3f2b0aa2..6d0f721130 100644--- a/client/src/pages/Dashboard.jsx+++ b/client/src/pages/Dashboard.jsx@@ -99,8 +99,15 @@ export default function Dashboard() {const fetchData = useCallback(async () => {setDataError(null);- const [appsData, , usageData, tribeCareData, feedsData, meatspaceLoggingData, dailyDriverData, dailyActionsData] = await Promise.all([- api.getApps().catch((err) => { setDataError(err.message); return []; }),+ // 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().catch((err) => { setDataError(err.message); return []; });+ const secondaryRead = Promise.all([refreshHealth(),api.getUsage().catch(() => null),api.getTribeCareSummary({ silent: true }).catch(() => null),@@ -112,14 +119,16 @@ export default function Dashboard() {api.getDailyActions({ silent: true }).catch(() => null),refreshInstanceFeatures(),]);+ const appsData = await appsRead;setApps(appsData);++ const [, usageData, tribeCareData, feedsData, meatspaceLoggingData, dailyDriverData, dailyActionsData] = await secondaryRead;setUsage(usageData);setTribeCare(tribeCareData);setFeeds(feedsData);setMeatspaceLogging(meatspaceLoggingData);setDailyDriver(dailyDriverData);setDailyActions(dailyActionsData);- setLoading(false);}, [refreshHealth, refreshInstanceFeatures]);useEffect(() => {diff --git a/server/routes/cos.test.js b/server/routes/cos.test.jsindex e0324e946e..3fcdf41349 100644--- a/server/routes/cos.test.js+++ b/server/routes/cos.test.js@@ -522,8 +522,9 @@ describe('CoS Routes', () => {});describe('GET /api/cos/agents', () => {- it('should return state-resident agents after cleaning zombies', async () => {- cos.cleanupZombieAgents.mockResolvedValue({ cleaned: [], count: 0 });+ it('should return state-resident agents without waiting for zombie cleanup', async () => {+ let releaseCleanup;+ cos.cleanupZombieAgents.mockReturnValue(new Promise((resolve) => { releaseCleanup = resolve; }));cos.getAgents.mockResolvedValue([{ id: 'agent-001', status: 'running' },{ id: 'agent-002', status: 'completed' }@@ -534,6 +535,7 @@ describe('CoS Routes', () => {expect(response.status).toBe(200);expect(response.body).toHaveLength(2);expect(cos.cleanupZombieAgents).toHaveBeenCalled();+ releaseCleanup({ cleaned: [], count: 0 });});});diff --git a/server/routes/cosAgentRoutes.js b/server/routes/cosAgentRoutes.jsindex 83d2f1bb6c..ce161b1e50 100644--- a/server/routes/cosAgentRoutes.js+++ b/server/routes/cosAgentRoutes.js@@ -38,7 +38,14 @@ router.post('/health/check', asyncHandler(async (req, res) => {// GET /api/cos/agents - Get state-resident agents (running + recently completed, auto-cleans zombies)// Strips output arrays from listing — output is loaded on demand via GET /agents/:idrouter.get('/agents', asyncHandler(async (req, res) => {- await cos.cleanupZombieAgents();+ // Zombie cleanup probes the standalone runner and can wait up to its+ // transport timeout when that optional process is restarting or offline.+ // The state listing is still useful while that repair runs, so keep cleanup+ // off the response critical path and let it complete independently; the next+ // normal refresh will see any repaired records.+ void cos.cleanupZombieAgents().catch((err) => {+ console.error(`🧹 Background zombie cleanup failed: ${err.message}`);+ });const agents = await cos.getAgents();res.json(agents.map(({ output, ...rest }) => rest));}));