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: surface health settings failures and retry warning cleanup (#8278)
[._.]/ Adam Eivy38cf77a13f7f
diff --git a/client/src/components/SystemHealthWidget.jsx b/client/src/components/SystemHealthWidget.jsxindex 9779088e9a..f0c52f7167 100644--- a/client/src/components/SystemHealthWidget.jsx+++ b/client/src/components/SystemHealthWidget.jsx@@ -131,16 +131,18 @@ const SystemHealthWidget = memo(function SystemHealthWidget({ dashboardState })><AlertTriangle size={14} className="shrink-0" /><span className="flex-1">{warning.message}</span>- <button- type="button"- onClick={() => handleDismissWarning(warning)}- disabled={!refetchHealth || dismissingType === warning.type}- className="shrink-0 inline-flex min-h-[28px] min-w-[28px] items-center justify-center rounded text-port-warning/70 transition-colors hover:bg-port-warning/20 hover:text-port-warning disabled:cursor-not-allowed disabled:opacity-50"- title="Dismiss as resolved"- aria-label={`Dismiss warning: ${warning.message}`}- >- <X size={13} aria-hidden="true" />- </button>+ {warning.dismissible !== false && (+ <button+ type="button"+ onClick={() => handleDismissWarning(warning)}+ disabled={!refetchHealth || dismissingType === warning.type}+ className="shrink-0 inline-flex min-h-[28px] min-w-[28px] items-center justify-center rounded text-port-warning/70 transition-colors hover:bg-port-warning/20 hover:text-port-warning disabled:cursor-not-allowed disabled:opacity-50"+ title="Dismiss as resolved"+ aria-label={`Dismiss warning: ${warning.message}`}+ >+ <X size={13} aria-hidden="true" />+ </button>+ )}</div>))}</div>diff --git a/client/src/components/SystemHealthWidget.test.jsx b/client/src/components/SystemHealthWidget.test.jsxindex 15e43b0628..0839a76810 100644--- a/client/src/components/SystemHealthWidget.test.jsx+++ b/client/src/components/SystemHealthWidget.test.jsx@@ -100,6 +100,21 @@ describe('SystemHealthWidget', () => {expect(screen.getByText('80%')).toHaveClass('text-port-accent');});+ it('does not offer dismissal for an unavailable health-settings warning', () => {+ const message = 'System health settings are unavailable; default thresholds are being used and saved warning dismissals were ignored.';+ renderWidget({+ health: {+ ...HEALTH,+ thresholds: undefined,+ warnings: [{ type: 'health-settings', severity: 'warning', message, dismissible: false }],+ },+ refetchHealth: vi.fn(),+ });++ expect(screen.getByText(message)).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: `Dismiss warning: ${message}` })).not.toBeInTheDocument();+ });+it('dismisses a warning as resolved and refetches health', async () => {const user = userEvent.setup();const refetchHealth = vi.fn().mockResolvedValue(undefined);diff --git a/client/src/pages/SystemHealthPage.jsx b/client/src/pages/SystemHealthPage.jsxindex 7dde9a0367..d497677ad2 100644--- a/client/src/pages/SystemHealthPage.jsx+++ b/client/src/pages/SystemHealthPage.jsx@@ -128,6 +128,11 @@ function SystemHealthOverview() {// Seed the editable draft from server state on first load and after each save.useEffect(() => {+ if (health?.thresholdsAvailable === false) {+ setDraft(null);+ draftSeededRef.current = false;+ return;+ }if (health?.thresholds && !draftSeededRef.current) {setDraft(health.thresholds);draftSeededRef.current = true;@@ -222,7 +227,7 @@ function SystemHealthOverview() {size="md"icon={AlertTriangle}align="start"- actions={(+ actions={w.dismissible === false ? null : (<buttontype="button"onClick={() => handleDismissWarning(w)}@@ -315,30 +320,40 @@ function SystemHealthOverview() {<Zap size={16} />Alert thresholds</h3>- <span className="text-xs text-gray-500">Disk capacity alerts. Defaults: 90/98%.</span>+ <span className="text-xs text-gray-500">+ {health.thresholdsAvailable === false ? 'Configured thresholds unavailable' : 'Disk capacity alerts. Defaults: 90/98%.'}+ </span></div>- <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">- <ThresholdField id="system-health-disk-warn" label="Disk warn %" value={draft?.diskWarn} onChange={(v) => setDraft(d => ({ ...d, diskWarn: v }))} />- <ThresholdField id="system-health-disk-critical" 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>+ {health.thresholdsAvailable === false ? (+ <p role="status" className="text-sm text-port-warning">+ Default thresholds are being used for health checks. Repair the settings file before changing thresholds.+ </p>+ ) : (+ <>+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">+ <ThresholdField id="system-health-disk-warn" label="Disk warn %" value={draft?.diskWarn} onChange={(v) => setDraft(d => ({ ...d, diskWarn: v }))} />+ <ThresholdField id="system-health-disk-critical" 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>+ </>)}- <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>);diff --git a/client/src/pages/SystemHealthPage.test.jsx b/client/src/pages/SystemHealthPage.test.jsxindex 156fef07f4..ef6d2ad15c 100644--- a/client/src/pages/SystemHealthPage.test.jsx+++ b/client/src/pages/SystemHealthPage.test.jsx@@ -120,6 +120,29 @@ describe('SystemHealthPage remediation links', () => {expect(within(nav).getAllByRole('link')).toHaveLength(3);});+ it('keeps corrupt health settings visible and disables threshold editing and dismissal', async () => {+ const message = 'System health settings are unavailable; default thresholds are being used and saved warning dismissals were ignored.';+ api.getSystemHealth.mockResolvedValue({+ ...HEALTH,+ thresholds: undefined,+ thresholdsAvailable: false,+ warnings: [+ { type: 'health-settings', severity: 'warning', message, dismissible: false },+ { type: 'disk', severity: 'warning', message: 'Disk usage at or above 90%', dismissible: false },+ ],+ });+ renderPage();++ expect(await screen.findByText(message)).toBeInTheDocument();+ expect(screen.getByText('Configured thresholds unavailable')).toBeInTheDocument();+ expect(screen.getByText('Default thresholds are being used for health checks. Repair the settings file before changing thresholds.')).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: `Dismiss warning: ${message}` })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Dismiss warning: Disk usage at or above 90%' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Save thresholds' })).not.toBeInTheDocument();+ expect(screen.queryByLabelText('Disk warn %')).not.toBeInTheDocument();+ expect(api.updateHealthThresholds).not.toHaveBeenCalled();+ });+it('renders the drill-in links above the metric cards', async () => {api.getSystemHealth.mockResolvedValue(withWarnings([]));renderPage();diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 0d55527993..2dd0c5c718 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1638,7 +1638,7 @@ export const databaseExportSchema = z.object({// System health dashboard warnings — see server/routes/systemHealth.js. The// `type` enum mirrors every `rawWarnings.push({ type: ... })` call site there;// keep the two lists in sync.-export const SYSTEM_HEALTH_WARNING_TYPES = ['memory', 'cpu', 'disk', 'process', 'restarts', 'apps', 'database', 'forge', 'code-review'];+export const SYSTEM_HEALTH_WARNING_TYPES = ['memory', 'cpu', 'disk', 'process', 'restarts', 'apps', 'database', 'forge', 'code-review', 'health-settings'];export const systemHealthWarningParamsSchema = z.object({ type: z.enum(SYSTEM_HEALTH_WARNING_TYPES) });export const systemHealthWarningDismissSchema = z.object({ message: z.string().trim().min(1).max(500) });diff --git a/server/routes/health.test.js b/server/routes/health.test.jsindex a367acc2e8..332eadc5f5 100644--- a/server/routes/health.test.js+++ b/server/routes/health.test.js@@ -11,7 +11,7 @@ import { getSelf } from '../services/instanceIdentity.js';import { isAuthEnabled } from '../services/auth.js';import { checkGhHealth } from '../services/github.js';import { getBuildIdentity } from '../lib/buildIdentity.js';-import { getSettings, updateSettingsWith } from '../services/settings.js';+import { getSettingsWithStatus, updateSettingsWith } from '../services/settings.js';import { statfs } from 'fs/promises';vi.mock('../services/pm2.js', () => ({@@ -96,7 +96,7 @@ const codeReviewMock = vi.hoisted(() => ({vi.mock('../services/codeReview.js', () => codeReviewMock);vi.mock('../services/settings.js', () => ({- getSettings: vi.fn().mockResolvedValue({}),+ getSettingsWithStatus: vi.fn().mockResolvedValue({ corrupt: false, settings: {} }),updateSettings: vi.fn().mockResolvedValue({}),// PUT /health/thresholds was migrated to updateSettingsWith (a read-modify-write// that hands the mutator the current settings and returns its result). Mirror@@ -335,7 +335,7 @@ describe('System Health Routes', () => {const health = { status: 'warning', configFaults: reviewerHealth };let settings = { codeReview: { reviewerHealth } };await codeReviewMock.getReviewerConfigHealth.withImplementation(async () => health, async () => {- await getSettings.withImplementation(async () => settings, async () => {+ await getSettingsWithStatus.withImplementation(async () => ({ corrupt: false, settings }), async () => {await updateSettingsWith.withImplementation(async (mutate) => (settings = await mutate(settings)), async () => {const original = await request(app).get('/api/system/health/details');const warning = original.body.warnings.find((item) => item.type === 'code-review');@@ -477,8 +477,9 @@ describe('System Health Routes', () => {// Force a disk-warn condition (95% used) so the 'disk' warning fires,// then supply a dismissal recorded against that exact message.vi.mocked(statfs).mockResolvedValueOnce({ blocks: 100, bavail: 5, bsize: 1 });- getSettings.mockResolvedValueOnce({- health: { dismissedWarnings: { disk: { message: 'Disk usage at or above 90%', dismissedAt: '2026-01-01T00:00:00.000Z' } } }+ getSettingsWithStatus.mockResolvedValueOnce({+ corrupt: false,+ settings: { health: { dismissedWarnings: { disk: { message: 'Disk usage at or above 90%', dismissedAt: '2026-01-01T00:00:00.000Z' } } } }});const response = await request(app).get('/api/system/health/details');@@ -490,8 +491,9 @@ describe('System Health Routes', () => {// 99% used crosses diskCritical (98), not diskWarn (90) — a different// message than the one that was dismissed.vi.mocked(statfs).mockResolvedValueOnce({ blocks: 100, bavail: 1, bsize: 1 });- getSettings.mockResolvedValueOnce({- health: { dismissedWarnings: { disk: { message: 'Disk usage at or above 90%', dismissedAt: '2026-01-01T00:00:00.000Z' } } }+ getSettingsWithStatus.mockResolvedValueOnce({+ corrupt: false,+ settings: { health: { dismissedWarnings: { disk: { message: 'Disk usage at or above 90%', dismissedAt: '2026-01-01T00:00:00.000Z' } } } }});const response = await request(app).get('/api/system/health/details');@@ -504,8 +506,9 @@ describe('System Health Routes', () => {it('prunes a stale dismissal once its condition no longer holds', async () => {// Default disk mock (50% used) never raises a 'disk' warning, so a// stored disk dismissal is now stale and should be dropped.- getSettings.mockResolvedValueOnce({- health: { dismissedWarnings: { disk: { message: 'Disk usage at or above 90%', dismissedAt: '2026-01-01T00:00:00.000Z' } } }+ getSettingsWithStatus.mockResolvedValueOnce({+ corrupt: false,+ settings: { health: { dismissedWarnings: { disk: { message: 'Disk usage at or above 90%', dismissedAt: '2026-01-01T00:00:00.000Z' } } } }});vi.mocked(updateSettingsWith).mockClear();@@ -517,6 +520,126 @@ describe('System Health Routes', () => {expect(next.health.dismissedWarnings).toEqual({});});+ it('uses custom disk thresholds for health warnings', async () => {+ vi.mocked(statfs).mockResolvedValueOnce({ blocks: 100, bavail: 20, bsize: 1 });+ getSettingsWithStatus.mockResolvedValueOnce({+ corrupt: false,+ settings: { health: { diskWarn: 70, diskCritical: 90 } }+ });++ const { body } = await request(app).get('/api/system/health/details');++ expect(body.thresholdsAvailable).toBe(true);+ expect(body.thresholds).toMatchObject({ diskWarn: 70, diskCritical: 90 });+ expect(body.warnings).toContainEqual({+ type: 'disk', severity: 'warning', message: 'Disk usage at or above 70%'+ });+ });++ it('reports corrupt settings, ignores their thresholds and dismissals, and blocks settings writes', async () => {+ vi.mocked(statfs).mockResolvedValueOnce({ blocks: 100, bavail: 5, bsize: 1 });+ const healthSettingsWarning = 'System health settings are unavailable; default thresholds are being used and saved warning dismissals were ignored.';+ const corruptStatus = { corrupt: true, settings: {+ health: {+ diskWarn: 70,+ diskCritical: 75,+ dismissedWarnings: {+ 'health-settings': { message: healthSettingsWarning, dismissedAt: '2026-01-01T00:00:00.000Z' },+ disk: { message: 'Disk usage at or above 90%', dismissedAt: '2026-01-01T00:00:00.000Z' }+ }+ }+ } };+ getSettingsWithStatus+ .mockResolvedValueOnce(corruptStatus)+ .mockResolvedValueOnce(corruptStatus)+ .mockResolvedValueOnce(corruptStatus)+ .mockResolvedValueOnce(corruptStatus);+ vi.mocked(updateSettingsWith).mockClear();++ const { body } = await request(app).get('/api/system/health/details');++ expect(body.thresholdsAvailable).toBe(false);+ expect(body.thresholds).toBeUndefined();+ expect(body.warnings).toContainEqual(expect.objectContaining({+ type: 'health-settings', severity: 'warning', message: healthSettingsWarning, dismissible: false+ }));+ expect(body.warnings).toContainEqual({+ type: 'disk', severity: 'warning', message: 'Disk usage at or above 90%', dismissible: false+ });+ expect(updateSettingsWith).not.toHaveBeenCalled();++ const saveThresholds = await request(app).put('/api/system/health/thresholds').send({+ memoryWarn: 85, memoryCritical: 95, diskWarn: 70, diskCritical: 90+ });+ const dismissWarning = await request(app)+ .post('/api/system/health/warnings/disk/dismiss')+ .send({ message: 'Disk usage at or above 70%' });+ const undismissWarning = await request(app).delete('/api/system/health/warnings/disk/dismiss');+ const dismissSettingsWarning = await request(app)+ .post('/api/system/health/warnings/health-settings/dismiss')+ .send({ message: 'settings unavailable' });+ const undismissSettingsWarning = await request(app).delete('/api/system/health/warnings/health-settings/dismiss');++ expect(saveThresholds.status).toBe(503);+ expect(dismissWarning.status).toBe(503);+ expect(undismissWarning.status).toBe(503);+ expect(dismissSettingsWarning.status).toBe(400);+ expect(undismissSettingsWarning.status).toBe(400);+ expect(updateSettingsWith).not.toHaveBeenCalled();+ });++ it('keeps a recurring warning visible and retries a failed stale-dismissal prune', async () => {+ let persistedSettings = {+ health: {+ diskWarn: 70,+ diskCritical: 90,+ dismissedWarnings: {+ disk: { message: 'Disk usage at or above 70%', dismissedAt: '2026-01-01T00:00:00.000Z' }+ }+ }+ };+ const staleSnapshot = () => ({ corrupt: false, settings: structuredClone(persistedSettings) });+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ vi.mocked(updateSettingsWith).mockClear();++ try {+ vi.mocked(statfs).mockResolvedValueOnce({ blocks: 100, bavail: 50, bsize: 1 });+ getSettingsWithStatus.mockResolvedValueOnce(staleSnapshot());+ vi.mocked(updateSettingsWith).mockRejectedValueOnce(Object.assign(new Error('write failed'), { code: 'EIO' }));++ const cleared = await request(app).get('/api/system/health/details');++ expect(cleared.body.warnings.some((warning) => warning.type === 'disk')).toBe(false);+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('type=disk, error=EIO'));++ vi.mocked(statfs).mockResolvedValueOnce({ blocks: 100, bavail: 20, bsize: 1 });+ getSettingsWithStatus.mockResolvedValueOnce(staleSnapshot());+ vi.mocked(updateSettingsWith).mockImplementationOnce(async (mutate) => {+ persistedSettings = await mutate(persistedSettings);+ return persistedSettings;+ });++ const recurring = await request(app).get('/api/system/health/details');++ expect(recurring.body.warnings).toContainEqual({+ type: 'disk', severity: 'warning', message: 'Disk usage at or above 70%'+ });+ expect(persistedSettings.health.dismissedWarnings).toEqual({});++ vi.mocked(statfs).mockResolvedValueOnce({ blocks: 100, bavail: 20, bsize: 1 });+ getSettingsWithStatus.mockResolvedValueOnce(staleSnapshot());++ const afterRetry = await request(app).get('/api/system/health/details');++ expect(afterRetry.body.warnings).toContainEqual({+ type: 'disk', severity: 'warning', message: 'Disk usage at or above 70%'+ });+ expect(updateSettingsWith).toHaveBeenCalledTimes(2);+ } finally {+ errorSpy.mockRestore();+ }+ });+describe('POST /health/warnings/:type/dismiss', () => {it('records the dismissal and echoes it back', async () => {const response = await request(app)diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.jsindex dd37053602..83fd62b12c 100644--- a/server/routes/systemHealth.js+++ b/server/routes/systemHealth.js@@ -12,7 +12,7 @@ import { getMemoryStats } from '../lib/memoryStats.js';import { formatBytes, formatDuration } from '../lib/fileUtils.js';import { parseFilesystemStats } from '../lib/fileCore.js';import { validateRequest, systemHealthWarningParamsSchema, systemHealthWarningDismissSchema } from '../lib/validation.js';-import { getSettings, updateSettingsWith } from '../services/settings.js';+import { getSettingsWithStatus, updateSettingsWith } from '../services/settings.js';import { checkGhHealth } from '../services/github.js';import { isAuthEnabled } from '../services/auth.js';import { getHttpsEnabledAtBoot } from '../lib/httpsState.js';@@ -30,6 +30,12 @@ const DEFAULT_THRESHOLDS = {diskCritical: 98};+// When a stale dismissal cannot be removed, remember the exact record that+// needs pruning. A matching recurrence remains visible until a later health+// read successfully removes that same persisted value.+const pendingDismissalPrunes = new Map();+const sameDismissal = (left, right) => JSON.stringify(left) === JSON.stringify(right);+// Dashboard warnings are recomputed fresh on every read (nothing about them is// persisted), so "dismiss" can't delete a row — it has to remember, per warning// TYPE, the exact message that was dismissed. A later read matching that same@@ -43,10 +49,18 @@ const DEFAULT_THRESHOLDS = {// per concern), paying for two deep-clones of the settings cache on every// dashboard poll.async function loadHealthSettings() {- const settings = await getSettings().catch(() => ({}));- const h = settings.health || {};+ const status = await getSettingsWithStatus().catch(() => {+ console.error('❌ Failed to read system health settings; default thresholds will be used');+ return { corrupt: true, settings: {} };+ });+ const settingsAvailable = status?.corrupt === false+ && status.settings+ && typeof status.settings === 'object'+ && !Array.isArray(status.settings);+ const h = settingsAvailable ? (status.settings.health || {}) : {};const dismissedWarnings = h.dismissedWarnings;return {+ thresholdsAvailable: Boolean(settingsAvailable),thresholds: {memoryWarn: Number(h.memoryWarn) || DEFAULT_THRESHOLDS.memoryWarn,memoryCritical: Number(h.memoryCritical) || DEFAULT_THRESHOLDS.memoryCritical,@@ -59,6 +73,19 @@ async function loadHealthSettings() {};}+async function assertHealthSettingsWritable() {+ const status = await getSettingsWithStatus().catch(() => ({ corrupt: true }));+ if (status?.corrupt !== false || !status.settings || typeof status.settings !== 'object' || Array.isArray(status.settings)) {+ throw new ServerError('System health settings are unavailable; repair settings before changing thresholds or warning dismissals.', { status: 503 });+ }+}++const assertDismissibleWarningType = (type) => {+ if (type === 'health-settings') {+ throw new ServerError('The system health settings warning cannot be dismissed.', { status: 400 });+ }+};+// Every write below only ever touches settings.health — shallow-merging a// patch into whatever the write queue's freshest snapshot already holds there.const patchHealth = (current, patch) => ({ ...current, health: { ...(current.health || {}), ...patch } });@@ -154,7 +181,7 @@ router.get('/health/details', asyncHandler(async (req, res) => {.then(({ getReviewerConfigHealth }) => getReviewerConfigHealth()).catch(() => ({ status: 'unknown', configFaults: {} }))]);- const { thresholds, dismissedWarnings } = healthSettings;+ const { thresholds, dismissedWarnings, thresholdsAvailable } = healthSettings;const memUsagePercent = Math.round((memStats.used / memStats.total) * 100);const cpuLoad = os.loadavg()[0]; // 1-minute load average@@ -214,6 +241,15 @@ router.get('/health/details', asyncHandler(async (req, res) => {// Memory occupancy and CPU load describe work, not a health failure.+ if (!thresholdsAvailable) {+ rawWarnings.push({+ type: 'health-settings',+ severity: 'warning',+ message: 'System health settings are unavailable; default thresholds are being used and saved warning dismissals were ignored.',+ dismissible: false+ });+ }+if (disk) {if (disk.usagePercent >= thresholds.diskCritical) {rawWarnings.push({ type: 'disk', severity: 'critical', message: `Disk usage at or above ${thresholds.diskCritical}%` });@@ -273,6 +309,8 @@ router.get('/health/details', asyncHandler(async (req, res) => {});}+ if (!thresholdsAvailable) rawWarnings.forEach((warning) => { warning.dismissible = false; });+// A dismissal only stays applied while the warning it was recorded against// is still current (same type AND same message) — see loadHealthSettings.// Anything else (the condition cleared, or recurred with a different@@ -282,14 +320,45 @@ router.get('/health/details', asyncHandler(async (req, res) => {const warnings = [];for (const warning of rawWarnings) {const dismissal = dismissedWarnings[warning.type];- if (dismissal?.message === warning.message) {+ const pendingPrune = pendingDismissalPrunes.get(warning.type);+ if (dismissal?.message === warning.message && !sameDismissal(pendingPrune, dismissal)) {nextDismissedWarnings[warning.type] = dismissal;continue;}warnings.push(warning);}- if (Object.keys(dismissedWarnings).length !== Object.keys(nextDismissedWarnings).length) {- await updateSettingsWith((current) => patchHealth(current, { dismissedWarnings: nextDismissedWarnings })).catch(() => {});++ if (thresholdsAvailable) {+ for (const [type, pending] of pendingDismissalPrunes) {+ if (!Object.hasOwn(dismissedWarnings, type) || !sameDismissal(dismissedWarnings[type], pending)) {+ pendingDismissalPrunes.delete(type);+ }+ }++ const staleDismissals = Object.entries(dismissedWarnings)+ .filter(([type]) => !Object.hasOwn(nextDismissedWarnings, type));+ if (staleDismissals.length) {+ for (const [type, dismissal] of staleDismissals) pendingDismissalPrunes.set(type, dismissal);+ try {+ const saved = await updateSettingsWith((current) => {+ const next = { ...(current.health?.dismissedWarnings || {}) };+ for (const [type, dismissal] of staleDismissals) {+ if (sameDismissal(next[type], dismissal)) delete next[type];+ }+ return patchHealth(current, { dismissedWarnings: next });+ });+ for (const [type, dismissal] of staleDismissals) {+ if (sameDismissal(pendingDismissalPrunes.get(type), dismissal)+ && !sameDismissal(saved?.health?.dismissedWarnings?.[type], dismissal)) {+ pendingDismissalPrunes.delete(type);+ }+ }+ } catch (error) {+ for (const [type] of staleDismissals) {+ console.error(`❌ Failed to prune stale system health warning dismissal (type=${type}, error=${error?.code || 'write-failed'})`);+ }+ }+ }}const overallHealth = warnings.some(w => w.severity === 'critical')@@ -358,7 +427,8 @@ router.get('/health/details', asyncHandler(async (req, res) => {database: dbHealth,forge: forgeHealth,codeReview: reviewerConfigHealth,- thresholds,+ thresholds: thresholdsAvailable ? thresholds : undefined,+ thresholdsAvailable,topProcesses: [...pm2Processes].sort((a, b) => (b.memory || 0) - (a.memory || 0)).slice(0, 10)@@ -385,7 +455,9 @@ router.get('/health/details', asyncHandler(async (req, res) => {*/router.post('/health/warnings/:type/dismiss', asyncHandler(async (req, res) => {const { type } = validateRequest(systemHealthWarningParamsSchema, req.params);+ assertDismissibleWarningType(type);const { message } = validateRequest(systemHealthWarningDismissSchema, req.body || {});+ await assertHealthSettingsWritable();const next = await updateSettingsWith((current) => patchHealth(current, {dismissedWarnings: {...(current.health?.dismissedWarnings || {}),@@ -401,6 +473,8 @@ router.post('/health/warnings/:type/dismiss', asyncHandler(async (req, res) => {*/router.delete('/health/warnings/:type/dismiss', asyncHandler(async (req, res) => {const { type } = validateRequest(systemHealthWarningParamsSchema, req.params);+ assertDismissibleWarningType(type);+ await assertHealthSettingsWritable();await updateSettingsWith((current) => {const dismissedWarnings = { ...(current.health?.dismissedWarnings || {}) };delete dismissedWarnings[type];@@ -439,6 +513,7 @@ router.put('/health/thresholds', asyncHandler(async (req, res) => {// Merge the health thresholds against the freshest snapshot inside the write// queue so a concurrent settings write isn't clobbered by a stale base.+ await assertHealthSettingsWritable();await updateSettingsWith((current) => patchHealth(current, next));res.json(next);}));