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

feat: actionable /system-health detail page + saner default thresholds

Adam Eivy57bcd12cc0ac
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 2bc2f46ea3..1b4d333480 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -6,8 +6,14 @@
- **PortOS brand mark + favicon refresh.** Replaced the old portal-ring SVG logo with the new PortOS brand image (`client/public/portos-logo.png`, 512×512). The `Logo` component now renders a `<PortOSMark>` `<img>` so the full-color PNG ships verbatim — the previous `currentColor` SVG variant (and the unused `LogoGrid` / `LogoAnchor` / `LogoHex` / `LogoP` alternates) are removed. `AppIcon`'s `portos` glyph delegates to the same mark so the bookmarked-app tile matches the chrome. Sidebar and mobile-header logos go from `size=18/24` to `22/28` and drop the `text-port-accent` tint now that the artwork is its own color. Favicon, apple-touch-icon, and 192/512 PWA icons regenerated from the new artwork; `favicon.svg` simplified to embed `/portos-logo.png` for SVG-favicon-only browsers; `client/index.html` switches the primary `rel="icon"` to the PNG and updates `theme-color` to `#070B12` (matched in `manifest.json`'s `theme_color` + `background_color`). Added `docs/media/portos-logo.png` and embedded it in the README header. `.gitignore` keeps the global `*.png` ignore but allowlists the two committed brand PNGs so future contributors don't have to remember `git add -f`. Files: `client/src/components/Logo.jsx`, `client/src/components/AppIcon.jsx`, `client/src/components/Layout.jsx`, `client/index.html`, `client/public/{favicon.svg,favicon.ico,apple-touch-icon.png,icon-192.png,icon-512.png,manifest.json,portos-logo.png}`, `docs/media/portos-logo.png`, `README.md`, `.gitignore`.
+## Added
+
+- **`/system-health` — actionable detail page for the System Health widget.** The widget's "Details →" used to jump to `/apps`, which has nothing to do with what the alert is telling you. New page shows: per-resource cards (Memory / CPU / Disk) with the threshold bands annotated underneath ("warn 85% · critical 95%"), top-10 PM2 processes sorted by memory with status dot + CPU% + crash-loop badge, deep links to `/devtools/processes`, `/apps`, and `/data` for drill-down, and an inline Alert Thresholds editor (memory warn/critical, disk warn/critical) that persists to `data/settings.json` under `health` via a new `PUT /api/system/health/thresholds` endpoint. Reachable via Cmd+K (`system-health` / `memory-usage` / `disk-usage` / `cpu-usage`) and registered in `NAV_COMMANDS`. The widget's Details link now points here. Files: `client/src/pages/SystemHealthPage.jsx` (new), `client/src/App.jsx`, `client/src/components/SystemHealthWidget.jsx`, `client/src/services/apiSystem.js`, `server/routes/systemHealth.js`, `server/lib/navManifest.js`.
+
## Fixed
+- **System Health alert thresholds were tuned for a server, not a dev machine.** Defaults were warn=75% / critical=90% for memory and warn=85% / critical=95% for disk. On a real workstation that runs LLMs (mflux, kokoro, browser, etc.) plus normal app surface, memory sits in the 78-85% band as a baseline and big SSDs commonly cross 90% before a real problem — so the widget reported "Critical · Memory usage above 75% · Disk usage at or above 95%" perpetually. Bumped defaults to warn=85% / critical=95% memory, warn=90% / critical=98% disk; both are now also user-overridable from `/system-health` (persisted under `settings.health`). The threshold values flow into the warning text too — "Memory usage at or above 85%" instead of the hard-coded "above 75%". Files: `server/routes/systemHealth.js`, `server/routes/health.test.js`.
+
- **Review Hub: CoS-spawned tasks lingered as "pending" forever.** The review service emitted a `cos`-type item every time `cosEvents.emit('task:ready', ...)` fired, but nothing closed the loop when the agent actually finished — so the user saw a permanent backlog of "CoS Actions" they had to manually tick off, even for tasks the agent completed unattended. `server/services/review.js` now also listens for `agent:completed` and auto-completes any pending review item whose `metadata.referenceId` matches the agent's `taskId` when `result.success` is truthy (failures stay pending so the user still sees them). Mirrors the existing `memory:approval-needed` → `memory:approved`/`rejected` dismiss pattern. Refactored the helper into a single `updateStatusByReferenceId(id, status)` so dismiss and complete share the loop. Added two tests against the registered `agent:completed` listener (success → complete; failure → no-op). Files: `server/services/review.js`, `server/services/review.test.js`.
- **Review Hub: only had a "Mark All Read" (dismiss) bulk action.** Added a green "Complete All" button next to the renamed "Dismiss All" so the user can clear a queue of finished items as completed (correct status for things that were actually done) instead of dismissing them (which means "ignored"). File: `client/src/pages/Review.jsx`.
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 33efddef03..0d68f28daa 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -66,6 +66,7 @@ const JiraReports = lazyWithReload(() => import('./pages/JiraReports'));
const DataManager = lazyWithReload(() => import('./pages/DataManager'));
const Insights = lazyWithReload(() => import('./pages/Insights'));
const Instances = lazyWithReload(() => import('./pages/Instances'));
+const SystemHealthPage = lazyWithReload(() => import('./pages/SystemHealthPage'));
const MeatSpace = lazyWithReload(() => import('./pages/MeatSpace'));
const Post = lazyWithReload(() => import('./pages/Post'));
const Review = lazyWithReload(() => import('./pages/Review'));
@@ -158,6 +159,7 @@ export default function App() {
<Route path="insights" element={<Navigate to="/insights/overview" replace />} />
<Route path="insights/:tab" element={<Insights />} />
<Route path="instances" element={<Instances />} />
+ <Route path="system-health" element={<SystemHealthPage />} />
<Route path="loops" element={<Loops />} />
<Route path="meatspace" element={<Navigate to="/meatspace/overview" replace />} />
<Route path="meatspace/:tab" element={<MeatSpace />} />
diff --git a/client/src/components/SystemHealthWidget.jsx b/client/src/components/SystemHealthWidget.jsx
index 0417703034..325d5816fd 100644
--- a/client/src/components/SystemHealthWidget.jsx
+++ b/client/src/components/SystemHealthWidget.jsx
@@ -134,7 +134,7 @@ const SystemHealthWidget = memo(function SystemHealthWidget() {
<MicroGlyph variant="matrix" size={28} intensity={matrixIntensity} />
</span>
<Link
- to="/apps"
+ to="/system-health"
className="flex items-center gap-1 text-sm text-port-accent hover:text-port-accent/80 transition-colors min-h-[40px] px-2"
>
<span className="hidden sm:inline">Details</span>
diff --git a/client/src/pages/SystemHealthPage.jsx b/client/src/pages/SystemHealthPage.jsx
new file mode 100644
index 0000000000..51e663bb86
--- /dev/null
+++ b/client/src/pages/SystemHealthPage.jsx
@@ -0,0 +1,245 @@
+import { useEffect, useState } from 'react';
+import { Link } from 'react-router-dom';
+import { Activity, AlertTriangle, CheckCircle, XCircle, HardDrive, Cpu, Database, ServerCog, Zap } from 'lucide-react';
+import * as api from '../services/api';
+import toast from '../components/ui/Toast';
+import BrailleSpinner from '../components/BrailleSpinner';
+
+const HEALTH_STYLE = {
+ healthy: { color: 'text-port-success', bg: 'bg-port-success/10', icon: CheckCircle, label: 'Healthy' },
+ warning: { color: 'text-port-warning', bg: 'bg-port-warning/10', icon: AlertTriangle, label: 'Warning' },
+ critical: { color: 'text-port-error', bg: 'bg-port-error/10', icon: XCircle, label: 'Critical' }
+};
+
+function pctTone(pct, warn, critical) {
+ if (pct >= critical) return 'text-port-error';
+ if (pct >= warn) return 'text-port-warning';
+ return 'text-port-success';
+}
+
+function barTone(pct, warn, critical) {
+ if (pct >= critical) return 'bg-port-error';
+ if (pct >= warn) return 'bg-port-warning';
+ return 'bg-port-success';
+}
+
+export default function SystemHealthPage() {
+ const [health, setHealth] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [draft, setDraft] = useState(null);
+ const [saving, setSaving] = useState(false);
+
+ const load = async () => {
+ const data = await api.getSystemHealth({ silent: true }).catch(() => null);
+ setHealth(data);
+ if (data?.thresholds) setDraft(data.thresholds);
+ setLoading(false);
+ };
+
+ useEffect(() => {
+ load();
+ const interval = setInterval(load, 15000);
+ return () => clearInterval(interval);
+ }, []);
+
+ const handleSaveThresholds = async () => {
+ if (!draft) return;
+ setSaving(true);
+ const result = await api.updateHealthThresholds(draft).catch(err => {
+ toast.error(err?.message || 'Failed to save thresholds');
+ return null;
+ });
+ setSaving(false);
+ if (result) {
+ toast.success('Thresholds saved');
+ load();
+ }
+ };
+
+ const handleResetThresholds = () => {
+ setDraft({ memoryWarn: 85, memoryCritical: 95, diskWarn: 90, diskCritical: 98 });
+ };
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-64">
+ <BrailleSpinner text="Loading system health" />
+ </div>
+ );
+ }
+
+ if (!health) {
+ return <div className="p-6 text-gray-400">System health unavailable.</div>;
+ }
+
+ const style = HEALTH_STYLE[health.overallHealth] || HEALTH_STYLE.healthy;
+ const StatusIcon = style.icon;
+ const t = health.thresholds;
+ const draftValid =
+ draft &&
+ draft.memoryWarn < draft.memoryCritical &&
+ draft.diskWarn < draft.diskCritical;
+ const draftDirty =
+ draft &&
+ (draft.memoryWarn !== t.memoryWarn ||
+ draft.memoryCritical !== t.memoryCritical ||
+ draft.diskWarn !== t.diskWarn ||
+ draft.diskCritical !== t.diskCritical);
+
+ return (
+ <div className="h-full overflow-auto p-4 md:p-6">
+ <div className="max-w-5xl mx-auto space-y-4">
+ <div className="flex items-center justify-between gap-3">
+ <h2 className="text-xl font-bold text-white flex items-center gap-2">
+ <ServerCog size={20} />
+ System Health
+ </h2>
+ <div className={`flex items-center gap-2 px-3 py-1.5 rounded-lg border border-current/20 ${style.color} ${style.bg}`}>
+ <StatusIcon size={16} />
+ <span className="font-semibold">{style.label}</span>
+ <span className="text-gray-500">·</span>
+ <span className="text-gray-400 text-sm">{health.system.uptimeFormatted}</span>
+ </div>
+ </div>
+
+ {health.warnings.length > 0 && (
+ <section className="space-y-2">
+ {health.warnings.map((w, i) => (
+ <div key={i} className="flex items-center gap-2 px-3 py-2 rounded-lg bg-port-warning/10 border border-port-warning/30 text-port-warning text-sm">
+ <AlertTriangle size={14} />
+ <span>{w.message}</span>
+ </div>
+ ))}
+ </section>
+ )}
+
+ <section className="grid grid-cols-1 md:grid-cols-3 gap-3">
+ <ResourceCard
+ icon={HardDrive}
+ label="Memory"
+ pct={health.system.memory.usagePercent}
+ warn={t.memoryWarn}
+ critical={t.memoryCritical}
+ sub={`${health.system.memory.usedFormatted} / ${health.system.memory.totalFormatted}`}
+ />
+ <ResourceCard
+ icon={Cpu}
+ label="CPU Load (1m)"
+ pct={Math.min(100, health.system.cpu.usagePercent)}
+ warn={75}
+ critical={100}
+ sub={`${health.system.cpu.cores} cores · ${health.system.cpu.loadAvg1m.toFixed(2)} load`}
+ />
+ {health.system.disk && (
+ <ResourceCard
+ icon={Database}
+ label="Disk"
+ pct={health.system.disk.usagePercent}
+ warn={t.diskWarn}
+ critical={t.diskCritical}
+ sub={`${health.system.disk.usedFormatted} / ${health.system.disk.totalFormatted}`}
+ />
+ )}
+ </section>
+
+ <section className="bg-port-card border border-port-border rounded-xl p-4">
+ <h3 className="text-sm font-semibold text-white mb-3 flex items-center gap-2">
+ <Activity size={16} />
+ Top processes by memory
+ </h3>
+ {health.topProcesses && health.topProcesses.length > 0 ? (
+ <div className="space-y-1">
+ {health.topProcesses.map((p) => (
+ <div key={p.name} className="flex items-center gap-3 px-3 py-2 rounded-lg bg-port-bg/40 hover:bg-port-bg/60 text-sm">
+ <span className={`w-2 h-2 rounded-full ${p.status === 'online' ? 'bg-port-success' : p.status === 'errored' ? 'bg-port-error' : 'bg-gray-500'}`} />
+ <span className="flex-1 text-gray-200 font-mono text-xs truncate">{p.name}</span>
+ <span className="text-gray-400 tabular-nums">{p.cpu.toFixed(0)}% CPU</span>
+ <span className="text-gray-100 tabular-nums w-24 text-right">{p.memoryFormatted}</span>
+ {p.unstableRestarts > 0 && (
+ <span className="text-port-warning text-xs">{p.unstableRestarts} crash-loop</span>
+ )}
+ </div>
+ ))}
+ </div>
+ ) : (
+ <p className="text-gray-500 text-sm">No PM2 processes reporting.</p>
+ )}
+ <div className="mt-3 flex items-center gap-3 text-xs">
+ <Link to="/devtools/processes" className="text-port-accent hover:text-port-accent/80">All processes →</Link>
+ <Link to="/apps" className="text-port-accent hover:text-port-accent/80">Apps →</Link>
+ <Link to="/data" className="text-port-accent hover:text-port-accent/80">Disk usage breakdown →</Link>
+ </div>
+ </section>
+
+ <section className="bg-port-card border border-port-border rounded-xl p-4">
+ <div className="flex items-center justify-between mb-3 gap-3">
+ <h3 className="text-sm font-semibold text-white flex items-center gap-2">
+ <Zap size={16} />
+ Alert thresholds
+ </h3>
+ <span className="text-xs text-gray-500">Tune to your machine. Defaults: 85/95 mem, 90/98 disk.</span>
+ </div>
+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
+ <ThresholdField label="Memory warn %" value={draft?.memoryWarn} onChange={(v) => setDraft(d => ({ ...d, memoryWarn: v }))} />
+ <ThresholdField label="Memory critical %" value={draft?.memoryCritical} onChange={(v) => setDraft(d => ({ ...d, memoryCritical: v }))} />
+ <ThresholdField label="Disk warn %" value={draft?.diskWarn} onChange={(v) => setDraft(d => ({ ...d, diskWarn: v }))} />
+ <ThresholdField label="Disk critical %" value={draft?.diskCritical} onChange={(v) => setDraft(d => ({ ...d, diskCritical: v }))} />
+ </div>
+ {!draftValid && (
+ <p className="mt-2 text-xs text-port-error">Warn thresholds must be lower than critical thresholds.</p>
+ )}
+ <div className="mt-3 flex gap-2">
+ <button
+ onClick={handleSaveThresholds}
+ disabled={!draftDirty || !draftValid || saving}
+ className="px-3 py-2 text-sm bg-port-accent hover:bg-port-accent/80 disabled:opacity-40 disabled:cursor-not-allowed rounded-lg text-white transition-colors"
+ >
+ {saving ? 'Saving…' : 'Save thresholds'}
+ </button>
+ <button
+ onClick={handleResetThresholds}
+ className="px-3 py-2 text-sm bg-port-border/50 hover:bg-port-border rounded-lg text-gray-300 transition-colors"
+ >
+ Reset to defaults
+ </button>
+ </div>
+ </section>
+ </div>
+ </div>
+ );
+}
+
+function ResourceCard({ icon: Icon, label, pct, warn, critical, sub }) {
+ return (
+ <div className="bg-port-card border border-port-border rounded-xl p-4">
+ <div className="flex items-center gap-2 text-xs uppercase tracking-wide text-gray-500 mb-2">
+ <Icon size={14} />
+ {label}
+ </div>
+ <div className={`text-3xl font-bold ${pctTone(pct, warn, critical)}`}>{Math.round(pct)}%</div>
+ <div className="text-xs text-gray-500 mt-1">{sub}</div>
+ <div className="mt-3 h-1.5 bg-port-border rounded-full overflow-hidden">
+ <div className={`h-full ${barTone(pct, warn, critical)} transition-all`} style={{ width: `${Math.min(100, pct)}%` }} />
+ </div>
+ <div className="mt-2 text-[11px] text-gray-600">
+ warn {warn}% · critical {critical}%
+ </div>
+ </div>
+ );
+}
+
+function ThresholdField({ label, value, onChange }) {
+ return (
+ <label className="flex flex-col gap-1 text-xs text-gray-400">
+ <span>{label}</span>
+ <input
+ type="number"
+ min={50}
+ max={99}
+ value={value ?? ''}
+ onChange={(e) => onChange(Number(e.target.value))}
+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white focus:outline-none focus:border-port-accent"
+ />
+ </label>
+ );
+}
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index 50459ca363..77d59f82f7 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -6,6 +6,10 @@ export const getAlertsSummary = (options) => request('/alerts/summary', options)
// Health
export const checkHealth = () => request('/system/health');
export const getSystemHealth = (options) => request('/system/health/details', options);
+export const updateHealthThresholds = (thresholds) => request('/system/health/thresholds', {
+ method: 'PUT',
+ body: JSON.stringify(thresholds)
+});
// Update
export const getUpdateStatus = () => request('/update/status');
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 87efaece77..8bdb5faade 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -120,6 +120,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.loops', path: '/loops', label: 'Loops', section: 'System', aliases: ['loops'] },
{ id: 'nav.devtools.processes', path: '/devtools/processes', label: 'Processes', section: 'System', aliases: ['devtools-processes', 'processes'] },
{ id: 'nav.security', path: '/security', label: 'Security', section: 'System', aliases: ['security'] },
+ { id: 'nav.system-health', path: '/system-health', label: 'System Health', section: 'System', aliases: ['system-health', 'system-status', 'memory-usage', 'disk-usage', 'cpu-usage'], keywords: ['memory', 'cpu', 'disk', 'thresholds', 'top processes', 'resource usage'] },
{ id: 'nav.cos.jobs', path: '/cos/jobs', label: 'System Tasks', section: 'System', aliases: ['cos-jobs', 'system-tasks'] },
{ id: 'nav.uploads', path: '/uploads', label: 'Uploads', section: 'System', aliases: ['uploads'] },
diff --git a/server/routes/health.test.js b/server/routes/health.test.js
index 3bee4b01e9..d38773b76e 100644
--- a/server/routes/health.test.js
+++ b/server/routes/health.test.js
@@ -20,8 +20,14 @@ vi.mock('../lib/db.js', () => ({
checkHealth: vi.fn().mockResolvedValue({ connected: false, hasSchema: false })
}));
+vi.mock('../services/settings.js', () => ({
+ getSettings: vi.fn().mockResolvedValue({}),
+ updateSettings: vi.fn().mockResolvedValue({})
+}));
+
describe('System Health Routes', () => {
const app = express();
+ app.use(express.json());
app.use('/api/system', systemHealthRoutes);
it('should return health status', async () => {
@@ -61,4 +67,45 @@ describe('System Health Routes', () => {
expect(restartWarnings[0].message).toContain('crash-loop');
expect(restartWarnings[0].message).toContain('flaky-svc');
});
+
+ it('exposes thresholds and topProcesses (sorted by memory desc)', async () => {
+ listProcesses.mockResolvedValueOnce([
+ { name: 'small', status: 'online', memory: 100, cpu: 1, restarts: 0, unstableRestarts: 0 },
+ { name: 'big', status: 'online', memory: 5_000_000, cpu: 50, restarts: 0, unstableRestarts: 0 },
+ { name: 'mid', status: 'online', memory: 2_000_000, cpu: 5, restarts: 0, unstableRestarts: 0 }
+ ]);
+ const response = await request(app).get('/api/system/health/details');
+ expect(response.body.thresholds).toMatchObject({
+ memoryWarn: expect.any(Number),
+ memoryCritical: expect.any(Number),
+ diskWarn: expect.any(Number),
+ diskCritical: expect.any(Number)
+ });
+ expect(response.body.topProcesses.map(p => p.name)).toEqual(['big', 'mid', 'small']);
+ });
+
+ describe('PUT /health/thresholds', () => {
+ it('rejects invalid numbers', async () => {
+ const response = await request(app)
+ .put('/api/system/health/thresholds')
+ .send({ memoryWarn: 'oops', memoryCritical: 95, diskWarn: 90, diskCritical: 98 });
+ expect(response.status).toBe(400);
+ });
+
+ it('rejects warn >= critical', async () => {
+ const response = await request(app)
+ .put('/api/system/health/thresholds')
+ .send({ memoryWarn: 95, memoryCritical: 90, diskWarn: 80, diskCritical: 95 });
+ expect(response.status).toBe(400);
+ expect(response.body.error).toMatch(/memoryWarn/);
+ });
+
+ it('clamps and persists valid thresholds', async () => {
+ const response = await request(app)
+ .put('/api/system/health/thresholds')
+ .send({ memoryWarn: 87, memoryCritical: 96, diskWarn: 92, diskCritical: 99 });
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual({ memoryWarn: 87, memoryCritical: 96, diskWarn: 92, diskCritical: 99 });
+ });
+ });
});
diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.js
index a3b59bffad..551c7573b5 100644
--- a/server/routes/systemHealth.js
+++ b/server/routes/systemHealth.js
@@ -9,6 +9,30 @@ import { checkHealth } from '../lib/db.js';
import { getCurrentVersion } from '../services/updateChecker.js';
import { asyncHandler } from '../lib/errorHandler.js';
import { getMemoryStats } from '../lib/memoryStats.js';
+import { getSettings } from '../services/settings.js';
+
+// Defaults are tuned for a real dev machine: memory routinely sits in the
+// 75-85% band on a host with a couple of LLMs loaded, and big SSDs commonly
+// run >85% before being a real problem. Earlier thresholds (75/90 mem,
+// 85/95 disk) fired warnings on every healthy laptop. Users can override
+// these from /system-health (persisted to settings.json under `health`).
+const DEFAULT_THRESHOLDS = {
+ memoryWarn: 85,
+ memoryCritical: 95,
+ diskWarn: 90,
+ diskCritical: 98
+};
+
+async function loadThresholds() {
+ const settings = await getSettings().catch(() => ({}));
+ const h = settings.health || {};
+ return {
+ memoryWarn: Number(h.memoryWarn) || DEFAULT_THRESHOLDS.memoryWarn,
+ memoryCritical: Number(h.memoryCritical) || DEFAULT_THRESHOLDS.memoryCritical,
+ diskWarn: Number(h.diskWarn) || DEFAULT_THRESHOLDS.diskWarn,
+ diskCritical: Number(h.diskCritical) || DEFAULT_THRESHOLDS.diskCritical
+ };
+}
const router = Router();
@@ -35,7 +59,7 @@ 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] = await Promise.all([
+ const [pm2Processes, allApps, cosStatus, self, dbHealth, version, diskStats, memStats, thresholds] = await Promise.all([
listProcesses().catch(() => []),
apps.getAllApps({ includeArchived: false }).catch(() => []),
cos.getStatus().catch(() => null),
@@ -43,7 +67,8 @@ router.get('/health/details', asyncHandler(async (req, res) => {
checkHealth().catch(() => ({ connected: false, hasSchema: false, error: 'Health check failed' })),
getCurrentVersion().catch(() => null),
statfs('/').catch(() => null),
- getMemoryStats()
+ getMemoryStats(),
+ loadThresholds()
]);
const memUsagePercent = Math.round((memStats.used / memStats.total) * 100);
@@ -95,12 +120,12 @@ router.get('/health/details', asyncHandler(async (req, res) => {
let overallHealth = 'healthy';
const warnings = [];
- if (memUsagePercent > 90) {
+ if (memUsagePercent >= thresholds.memoryCritical) {
overallHealth = 'critical';
- warnings.push({ type: 'memory', message: 'Memory usage above 90%' });
- } else if (memUsagePercent > 75) {
+ warnings.push({ type: 'memory', message: `Memory usage at or above ${thresholds.memoryCritical}%` });
+ } else if (memUsagePercent >= thresholds.memoryWarn) {
if (overallHealth !== 'critical') overallHealth = 'warning';
- warnings.push({ type: 'memory', message: 'Memory usage above 75%' });
+ warnings.push({ type: 'memory', message: `Memory usage at or above ${thresholds.memoryWarn}%` });
}
if (cpuUsagePercent > 100) {
@@ -109,12 +134,12 @@ router.get('/health/details', asyncHandler(async (req, res) => {
}
if (disk) {
- if (disk.usagePercent >= 95) {
+ if (disk.usagePercent >= thresholds.diskCritical) {
overallHealth = 'critical';
- warnings.push({ type: 'disk', message: 'Disk usage at or above 95%' });
- } else if (disk.usagePercent >= 85) {
+ warnings.push({ type: 'disk', message: `Disk usage at or above ${thresholds.diskCritical}%` });
+ } else if (disk.usagePercent >= thresholds.diskWarn) {
if (overallHealth !== 'critical') overallHealth = 'warning';
- warnings.push({ type: 'disk', message: 'Disk usage at or above 85%' });
+ warnings.push({ type: 'disk', message: `Disk usage at or above ${thresholds.diskWarn}%` });
}
}
@@ -210,8 +235,55 @@ router.get('/health/details', asyncHandler(async (req, res) => {
processes: processStats,
apps: appStats,
cos: cosInfo,
- database: dbHealth
+ database: dbHealth,
+ thresholds,
+ topProcesses: [...pm2Processes]
+ .sort((a, b) => (b.memory || 0) - (a.memory || 0))
+ .slice(0, 10)
+ .map(p => ({
+ name: p.name,
+ status: p.status,
+ memory: p.memory || 0,
+ memoryFormatted: formatBytes(p.memory || 0),
+ cpu: p.cpu || 0,
+ restarts: p.restarts || 0,
+ unstableRestarts: p.unstableRestarts || 0
+ }))
});
}));
+const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
+
+router.put('/health/thresholds', asyncHandler(async (req, res) => {
+ const body = req.body || {};
+ const incoming = {
+ memoryWarn: Number(body.memoryWarn),
+ memoryCritical: Number(body.memoryCritical),
+ diskWarn: Number(body.diskWarn),
+ diskCritical: Number(body.diskCritical)
+ };
+ for (const [k, v] of Object.entries(incoming)) {
+ if (!Number.isFinite(v)) {
+ return res.status(400).json({ error: `Invalid threshold value for ${k}` });
+ }
+ }
+ const next = {
+ memoryWarn: clamp(Math.round(incoming.memoryWarn), 50, 99),
+ memoryCritical: clamp(Math.round(incoming.memoryCritical), 50, 99),
+ diskWarn: clamp(Math.round(incoming.diskWarn), 50, 99),
+ diskCritical: clamp(Math.round(incoming.diskCritical), 50, 99)
+ };
+ if (next.memoryWarn >= next.memoryCritical) {
+ return res.status(400).json({ error: 'memoryWarn must be less than memoryCritical' });
+ }
+ if (next.diskWarn >= next.diskCritical) {
+ return res.status(400).json({ error: 'diskWarn must be less than diskCritical' });
+ }
+
+ const { updateSettings } = await import('../services/settings.js');
+ const current = await getSettings().catch(() => ({}));
+ await updateSettings({ ...current, health: { ...(current.health || {}), ...next } });
+ res.json(next);
+}));
+
export default router;