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(dashboard): system health "Apps" tile now shows real counts
Adam Eivy3e8871f35c63
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex dedaac86ab..e4cc9d6414 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -38,6 +38,8 @@## Fixed+- **Dashboard System Health — "0/16 apps" was always zero, and counted Xcode/iOS projects that can't run.** The widget called `getAllApps()` and filtered by `overallStatus === 'online'`, but `overallStatus` is only computed inside the `/api/apps` route's PM2 enrichment — `getAllApps()` returns the raw records, so the filter never matched and the count was always `0`. The denominator also included native projects (`xcode`, `ios-native`, `macos-native`, `swift`) that have no detectable runtime state at all. Replaced with a new `getAppStatusSummary()` helper in `services/apps.js` that groups apps by `pm2Home`, queries each unique home once, and computes `{ total, online, stopped, notStarted, unmanaged }` — `total` covers PM2-runnable apps only, while `unmanaged` separately tracks native projects. The widget tile now reads "Services" instead of "Apps", shows real running counts (e.g. `1/9` plus `+7 native`), uses "All running" instead of the confusing "Ready" fallback, and falls back to an em-dash when no PM2 apps exist (with a "N native only" subtext). A tooltip explains what's counted. Touched: `server/services/apps.js`, `server/routes/systemHealth.js`, `client/src/components/SystemHealthWidget.jsx`.+- **Writers Room mobile editor squashed to ~150px (regression).** `WritersRoom`'s `<main>` element had `min-h-0 flex flex-col` with no `flex-1`, so on mobile (below `md:`, where the parent flips to `display: grid`) the main area sized to its natural content height — collapsing the textarea to whatever space was left after the library, header, and tab strip. Added `flex-1` so main grows to fill the remaining viewport on mobile; desktop is unaffected because `md:grid` takes over and the `flex-1` is dormant. Touched: `client/src/pages/WritersRoom.jsx`.- **Collapsed sidebar footer overflow — theme toggle + bell wouldn't fit in the 64px rail.** The footer's two visible icons (ThemeModeToggle ~30px and NotificationDropdown bell ~36px plus a 2px focus-ring offset) summed to ~70–80px side-by-side, blowing out a `lg:w-16` collapsed sidebar that has only 32px of content width after `p-4`. Reduced collapsed-state footer padding to `p-2` (lg only) and stacked the buttons vertically (`lg:flex-col`) so each icon centers in the rail. Expanded layout is unchanged. Touched: `client/src/components/Layout.jsx`.diff --git a/client/src/components/SystemHealthWidget.jsx b/client/src/components/SystemHealthWidget.jsxindex 325d5816fd..dbe50b7ebe 100644--- a/client/src/components/SystemHealthWidget.jsx+++ b/client/src/components/SystemHealthWidget.jsx@@ -221,27 +221,45 @@ const SystemHealthWidget = memo(function SystemHealthWidget() {</div></div>- {/* Apps */}- <div className="bg-port-bg/50 rounded-lg p-3">+ {/* Services — PM2-managed apps; native (Xcode/iOS) projects shown as "+N native" */}+ <div+ className="bg-port-bg/50 rounded-lg p-3"+ title="PM2-managed apps online vs. total. Native projects (Xcode, iOS) have no detectable runtime and are listed separately."+ ><div className="flex items-center gap-2 mb-1"><Zap size={14} className="text-amber-400" />- <span className="text-xs text-gray-500">Apps</span>- </div>- <div className="text-lg sm:text-xl font-bold text-white">- {apps.online}- <span className="text-sm font-normal text-gray-500">/{apps.total}</span>- </div>- <div className="flex items-center gap-1 text-xs text-gray-500">- {apps.stopped > 0 ? (- <span>{apps.stopped} stopped</span>- ) : apps.notStarted > 0 ? (- <span>{apps.notStarted} offline</span>- ) : apps.online === apps.total ? (- <span className="text-port-success">All online</span>- ) : (- <span>Ready</span>- )}+ <span className="text-xs text-gray-500">Services</span></div>+ {apps.total > 0 ? (+ <>+ <div className="text-lg sm:text-xl font-bold text-white">+ {apps.online}+ <span className="text-sm font-normal text-gray-500">/{apps.total}</span>+ </div>+ <div className="flex items-center gap-1 text-xs text-gray-500">+ {apps.online === apps.total ? (+ <span className="text-port-success">All running</span>+ ) : apps.stopped > 0 ? (+ <span>{apps.stopped} stopped</span>+ ) : apps.notStarted > 0 ? (+ <span>{apps.notStarted} not running</span>+ ) : null}+ {apps.unmanaged > 0 && (+ <span className="text-gray-500">+ {(apps.online === apps.total || apps.stopped > 0 || apps.notStarted > 0) ? ' · ' : ''}+ +{apps.unmanaged} native+ </span>+ )}+ </div>+ </>+ ) : (+ <>+ <div className="text-lg sm:text-xl font-bold text-gray-500">—</div>+ <div className="text-xs text-gray-500">+ {apps.unmanaged > 0 ? `${apps.unmanaged} native only` : 'No apps'}+ </div>+ </>+ )}</div>{/* Disk Usage */}diff --git a/server/routes/health.test.js b/server/routes/health.test.jsindex d38773b76e..11d6f7574d 100644--- a/server/routes/health.test.js+++ b/server/routes/health.test.js@@ -9,7 +9,14 @@ vi.mock('../services/pm2.js', () => ({}));vi.mock('../services/apps.js', () => ({- getAllApps: vi.fn().mockResolvedValue([])+ getAllApps: vi.fn().mockResolvedValue([]),+ getAppStatusSummary: vi.fn().mockResolvedValue({+ total: 0,+ online: 0,+ stopped: 0,+ notStarted: 0,+ unmanaged: 0+ })}));vi.mock('../services/cos.js', () => ({diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.jsindex b0fae06247..70caf507a8 100644--- a/server/routes/systemHealth.js+++ b/server/routes/systemHealth.js@@ -59,9 +59,9 @@ router.get('/health/details', asyncHandler(async (req, res) => {const startTime = Date.now();// Gather data in parallel- const [pm2Processes, allApps, cosStatus, self, dbHealth, version, diskStats, memStats, thresholds] = await Promise.all([+ const [pm2Processes, appStatusSummary, cosStatus, self, dbHealth, version, diskStats, memStats, thresholds] = await Promise.all([listProcesses().catch(() => []),- apps.getAllApps({ includeArchived: false }).catch(() => []),+ apps.getAppStatusSummary().catch(() => ({ total: 0, online: 0, stopped: 0, notStarted: 0, unmanaged: 0 })),cos.getStatus().catch(() => null),getSelf().catch(() => null),checkHealth().catch(() => ({ connected: false, hasSchema: false, error: 'Health check failed' })),@@ -108,13 +108,10 @@ router.get('/health/details', asyncHandler(async (req, res) => {unstableRestarts: pm2Processes.reduce((sum, p) => sum + (p.unstableRestarts || 0), 0)};- // App status summary- const appStats = {- total: allApps.length,- online: allApps.filter(a => a.overallStatus === 'online').length,- stopped: allApps.filter(a => a.overallStatus === 'stopped').length,- notStarted: allApps.filter(a => a.overallStatus === 'not_started' || a.overallStatus === 'not_found').length- };+ // App status summary — PM2-managed apps only (Xcode/iOS-native projects+ // have no detectable runtime state, so they're tracked under `unmanaged`+ // and excluded from the running denominator)+ const appStats = appStatusSummary;// Determine overall health statuslet overallHealth = 'healthy';diff --git a/server/services/apps.js b/server/services/apps.jsindex c21e4b5581..ac596bef4f 100644--- a/server/services/apps.js+++ b/server/services/apps.js@@ -3,7 +3,8 @@ import { join } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';import EventEmitter from 'events';import { ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';-import { NON_PM2_TYPES } from './streamingDetect.js';+import { NON_PM2_TYPES, usesPm2 } from './streamingDetect.js';+import { listProcesses } from './pm2.js';import { SELF_IMPROVEMENT_TASK_TYPES } from './taskSchedule.js';import { sanitizeTaskMetadata } from '../lib/validation.js';import { PORTS } from '../lib/ports.js';@@ -174,6 +175,59 @@ export async function getActiveApps() {return getAllApps({ includeArchived: false });}+/**+ * Summarize PM2-managed app status for dashboards.+ *+ * Only counts apps whose `type` is PM2-runnable (Express services, etc.).+ * Native projects (Xcode, iOS, macOS) have no detectable runtime state and+ * are reported separately under `unmanaged` so callers can show context+ * without inflating the running denominator.+ */+export async function getAppStatusSummary() {+ const apps = await getAllApps({ includeArchived: false });++ const pm2Apps = apps.filter(a => usesPm2(a.type));+ const unmanaged = apps.length - pm2Apps.length;++ // Group by pm2Home so each unique home is queried at most once+ const homeGroups = new Map();+ for (const app of pm2Apps) {+ const home = app.pm2Home || null;+ if (!homeGroups.has(home)) homeGroups.set(home, []);+ homeGroups.get(home).push(app);+ }++ const procMaps = new Map();+ for (const home of homeGroups.keys()) {+ const procs = await listProcesses(home).catch(() => []);+ procMaps.set(home, new Map(procs.map(p => [p.name, p])));+ }++ let online = 0;+ let stopped = 0;+ let notStarted = 0;+ for (const app of pm2Apps) {+ const procMap = procMaps.get(app.pm2Home || null) || new Map();+ const names = app.pm2ProcessNames || [];+ if (names.length === 0) {+ notStarted++;+ continue;+ }+ const statuses = names.map(n => procMap.get(n)?.status || 'not_found');+ if (statuses.some(s => s === 'online')) online++;+ else if (statuses.some(s => s === 'stopped')) stopped++;+ else notStarted++;+ }++ return {+ total: pm2Apps.length,+ online,+ stopped,+ notStarted,+ unmanaged+ };+}+/*** Get app by ID (injects id from key)*/diff --git a/server/services/apps.test.js b/server/services/apps.test.jsindex e2515e1128..ca45ef14a1 100644--- a/server/services/apps.test.js+++ b/server/services/apps.test.js@@ -22,8 +22,13 @@ vi.mock('./taskSchedule.js', () => ({SELF_IMPROVEMENT_TASK_TYPES: [],}));+vi.mock('./pm2.js', () => ({+ listProcesses: vi.fn().mockResolvedValue([]),+}));+import { readJSONFile } from '../lib/fileUtils.js';-import { getReservedPorts, invalidateCache, PORTOS_APP_ID } from './apps.js';+import { listProcesses } from './pm2.js';+import { getAppStatusSummary, getReservedPorts, invalidateCache, PORTOS_APP_ID } from './apps.js';describe('getReservedPorts', () => {beforeEach(() => {@@ -115,3 +120,138 @@ describe('getReservedPorts', () => {expect(reserved.every(p => Number.isInteger(p) && p >= 1 && p <= 65535)).toBe(true);});});++describe('getAppStatusSummary', () => {+ beforeEach(() => {+ invalidateCache();+ vi.clearAllMocks();+ });++ it('counts only PM2-managed apps in total and tracks native projects separately', async () => {+ readJSONFile.mockResolvedValue({+ apps: {+ [PORTOS_APP_ID]: {+ name: 'PortOS',+ type: 'express',+ pm2ProcessNames: ['portos-server']+ },+ 'svc-a': {+ name: 'svc-a',+ type: 'express',+ pm2ProcessNames: ['svc-a']+ },+ 'svc-b': {+ name: 'svc-b',+ type: 'express',+ pm2ProcessNames: ['svc-b']+ },+ 'ios-app': {+ name: 'iOS App',+ type: 'ios-native'+ },+ 'xcode-app': {+ name: 'Xcode App',+ type: 'xcode'+ }+ }+ });+ listProcesses.mockResolvedValue([+ { name: 'portos-server', status: 'online' },+ { name: 'svc-a', status: 'stopped' }+ // svc-b is missing → not_found → notStarted+ ]);++ const summary = await getAppStatusSummary();+ expect(summary).toEqual({+ total: 3,+ online: 1,+ stopped: 1,+ notStarted: 1,+ unmanaged: 2+ });+ });++ it('returns zero counts when no apps are registered (native or otherwise)', async () => {+ readJSONFile.mockResolvedValue({+ apps: {+ [PORTOS_APP_ID]: {+ name: 'PortOS',+ type: 'express',+ pm2ProcessNames: ['portos-server']+ }+ }+ });+ listProcesses.mockResolvedValue([{ name: 'portos-server', status: 'online' }]);++ const summary = await getAppStatusSummary();+ expect(summary).toEqual({+ total: 1,+ online: 1,+ stopped: 0,+ notStarted: 0,+ unmanaged: 0+ });+ });++ it('queries each unique pm2Home only once', async () => {+ readJSONFile.mockResolvedValue({+ apps: {+ [PORTOS_APP_ID]: {+ name: 'PortOS',+ type: 'express',+ pm2ProcessNames: ['portos-server']+ },+ 'shared-home-a': {+ name: 'a',+ type: 'express',+ pm2ProcessNames: ['a']+ },+ 'shared-home-b': {+ name: 'b',+ type: 'express',+ pm2ProcessNames: ['b']+ },+ 'custom-home': {+ name: 'c',+ type: 'express',+ pm2Home: '/tmp/other-pm2',+ pm2ProcessNames: ['c']+ }+ }+ });+ listProcesses.mockImplementation(async (home) => {+ if (home === '/tmp/other-pm2') return [{ name: 'c', status: 'online' }];+ return [+ { name: 'portos-server', status: 'online' },+ { name: 'a', status: 'online' },+ { name: 'b', status: 'stopped' }+ ];+ });++ const summary = await getAppStatusSummary();+ expect(listProcesses).toHaveBeenCalledTimes(2);+ expect(summary).toMatchObject({ total: 4, online: 3, stopped: 1, notStarted: 0, unmanaged: 0 });+ });++ it('skips archived apps', async () => {+ readJSONFile.mockResolvedValue({+ apps: {+ [PORTOS_APP_ID]: {+ name: 'PortOS',+ type: 'express',+ pm2ProcessNames: ['portos-server']+ },+ 'old-app': {+ name: 'old',+ type: 'express',+ pm2ProcessNames: ['old'],+ archived: true+ }+ }+ });+ listProcesses.mockResolvedValue([{ name: 'portos-server', status: 'online' }]);++ const summary = await getAppStatusSummary();+ expect(summary.total).toBe(1);+ });+});