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

fix(lifecycle): attach error listeners to boot-armed fs.watch watchers (#12071) (#12215)

[._.]/be2409547999
diff --git a/lib/tailscale-https.js b/lib/tailscale-https.js
index 4d4e317c75..946923a81e 100644
--- a/lib/tailscale-https.js
+++ b/lib/tailscale-https.js
@@ -116,10 +116,19 @@ export function watchCertReload(httpsServer, certDir, opts = {}) {
};
// fs.watch debounced — Tailscale rewrites both files, we get a burst of events
- const watchers = [
- watch(certPath, reload),
- watch(keyPath, reload)
- ];
+ const watchers = [];
+ for (const filePath of [certPath, keyPath]) {
+ try {
+ const w = watch(filePath, reload);
+ w.on('error', (err) => {
+ log(`⚠️ cert watch error on ${filePath}: ${err.message}`);
+ w.close();
+ });
+ watchers.push(w);
+ } catch (err) {
+ log(`⚠️ failed to watch ${filePath}: ${err.message}`);
+ }
+ }
return () => {
clearTimeout(pending);
diff --git a/lib/tailscale-https.test.js b/lib/tailscale-https.test.js
new file mode 100644
index 0000000000..978e1db587
--- /dev/null
+++ b/lib/tailscale-https.test.js
@@ -0,0 +1,45 @@
+import { describe, expect, it, vi } from 'vitest';
+import EventEmitter from 'node:events';
+
+const fakeWatcher1 = new EventEmitter();
+fakeWatcher1.close = vi.fn();
+const fakeWatcher2 = new EventEmitter();
+fakeWatcher2.close = vi.fn();
+
+const createdWatchers = [fakeWatcher1, fakeWatcher2];
+let index = 0;
+
+vi.mock('node:fs', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ watch: vi.fn(() => createdWatchers[index++]),
+ };
+});
+
+import { watchCertReload } from './tailscale-https.js';
+
+describe('watchCertReload', () => {
+ it('attaches error listeners on watchers and does not throw on error event', async () => {
+ const logs = [];
+ const log = (msg) => logs.push(msg);
+ const fakeServer = { setSecureContext: vi.fn() };
+
+ const stop = watchCertReload(fakeServer, '/fake/cert/dir', { log });
+
+ // Both fake watchers should have 'error' listeners attached
+ expect(fakeWatcher1.listenerCount('error')).toBe(1);
+ expect(fakeWatcher2.listenerCount('error')).toBe(1);
+
+ // Emitting error must not throw
+ expect(() => {
+ fakeWatcher1.emit('error', new Error('EPERM: operation not permitted'));
+ }).not.toThrow();
+
+ expect(fakeWatcher1.close).toHaveBeenCalled();
+ expect(logs.some(l => l.includes('cert watch error') && l.includes('EPERM'))).toBe(true);
+
+ stop();
+ expect(fakeWatcher2.close).toHaveBeenCalled();
+ });
+});
diff --git a/server/services/maintenanceControl.js b/server/services/maintenanceControl.js
index 17a07add55..3d712fb491 100644
--- a/server/services/maintenanceControl.js
+++ b/server/services/maintenanceControl.js
@@ -17,6 +17,7 @@ function readinessProjection(status = maintenance.status()) {
function emitChanges() {
boundIo?.emit('maintenance:changed');
const next = readinessProjection();
+ if (!watcher && boundIo) bindMaintenanceIo(boundIo);
if (lastReadiness && lastReadiness.state === next.state && lastReadiness.blockerCount === next.blockerCount) return;
lastReadiness = next;
boundIo?.emit('maintenance:readiness', next);
@@ -30,12 +31,26 @@ export function bindMaintenanceIo(io) {
mkdirSync(maintenance.directory, { recursive: true, mode: 0o700 });
// Cross-process runner settlements also invalidate the UI. Payload contains
// no operation capability or private resource identity; GET remains auth gated.
- watcher = watch(maintenance.directory, () => {
- if (timer) clearTimeout(timer);
- timer = setTimeout(() => { timer = null; emitChanges(); }, 100);
- timer.unref?.();
- });
- watcher.unref?.();
+ try {
+ watcher = watch(maintenance.directory, () => {
+ if (timer) clearTimeout(timer);
+ timer = setTimeout(() => { timer = null; emitChanges(); }, 100);
+ timer.unref?.();
+ });
+ watcher.on('error', (err) => {
+ console.error(`❌ Maintenance directory watcher error: ${err.message}`);
+ watcher?.close();
+ watcher = null;
+ });
+ watcher.unref?.();
+ } catch (err) {
+ console.error(`❌ Failed to watch maintenance directory: ${err.message}`);
+ watcher = null;
+ }
+}
+
+export function _getMaintenanceWatcher() {
+ return watcher;
}
export async function resumeMaintenance(input) {
diff --git a/server/services/maintenanceControl.test.js b/server/services/maintenanceControl.test.js
index 6f6d05c1bd..879ff0c7dd 100644
--- a/server/services/maintenanceControl.test.js
+++ b/server/services/maintenanceControl.test.js
@@ -11,7 +11,7 @@ vi.mock('../lib/maintenanceAdmission.js', async () => {
gate.admission = actual.createMaintenanceAdmission(gate.root);
return { ...actual, maintenance: gate.admission };
});
-import { bindMaintenanceIo } from './maintenanceControl.js';
+import { bindMaintenanceIo, _getMaintenanceWatcher } from './maintenanceControl.js';
afterAll(() => rmSync(gate.root, { recursive: true, force: true }));
@@ -50,4 +50,21 @@ describe('maintenance notifications', () => {
// Nothing private is broadcast.
expect(JSON.stringify(sent)).not.toMatch(/resource-that-must-not-leak|pid|owner|hold/i);
});
+
+ it('handles watcher error without throwing and recovers watching on next emit', async () => {
+ const watcher = _getMaintenanceWatcher();
+ expect(watcher).toBeDefined();
+ expect(watcher.listenerCount('error')).toBe(1);
+
+ // Emitting error should close watcher and not throw
+ expect(() => {
+ watcher.emit('error', new Error('EPERM: operation not permitted'));
+ }).not.toThrow();
+
+ expect(_getMaintenanceWatcher()).toBeNull();
+
+ // Re-arming through bindMaintenanceIo or emitChanges restores the watcher
+ bindMaintenanceIo(io);
+ expect(_getMaintenanceWatcher()).not.toBeNull();
+ });
});
diff --git a/server/services/peerExecutionRuntime.js b/server/services/peerExecutionRuntime.js
index 34d55ec06a..670f3d3f88 100644
--- a/server/services/peerExecutionRuntime.js
+++ b/server/services/peerExecutionRuntime.js
@@ -38,20 +38,45 @@ async function compose() {
adapters: { prepare: adapters.preparePeerExecution, run: adapters.runPeerExecution, reconcile: adapters.reconcilePeerExecution },
changed: () => io?.emit('peer-execution:changed'),
resume: async input => (await import('./maintenanceControl.js')).resumeMaintenance(input) });
- return { ...receiver, ledger, coordinator };
+ const result = { ...receiver, ledger, coordinator };
+ const rawKick = receiver.kick;
+ result.kick = () => {
+ if (!watcher) armPeerExecutionWatcher(result);
+ return rawKick();
+ };
+ return result;
}
export async function initializePeerExecution() {
const receiver = await peerExecutionRuntime();
// A new install remains silent and default-deny; no ledger/authority init at boot.
if (receiver.ledger.authority.read()) await receiver.recover();
- if (!watcher) {
- assertNotRealDataWrite(receiver.coordinator.directory, 'peer execution drain notifications');
- mkdirSync(receiver.coordinator.directory, { recursive: true, mode: 0o700 });
- watcher = watch(receiver.coordinator.directory, () => receiver.kick());
+ armPeerExecutionWatcher(receiver);
+}
+
+function armPeerExecutionWatcher(receiver) {
+ if (watcher) return;
+ assertNotRealDataWrite(receiver.coordinator.directory, 'peer execution drain notifications');
+ mkdirSync(receiver.coordinator.directory, { recursive: true, mode: 0o700 });
+ try {
+ watcher = watch(receiver.coordinator.directory, () => {
+ receiver.kick();
+ });
+ watcher.on('error', (err) => {
+ console.error(`❌ Peer execution directory watcher error: ${err.message}`);
+ watcher?.close();
+ watcher = null;
+ });
watcher.unref?.();
+ } catch (err) {
+ console.error(`❌ Failed to watch peer execution coordinator directory: ${err.message}`);
+ watcher = null;
}
}
+export function _getPeerExecutionWatcher() {
+ return watcher;
+}
+
export async function withPeerExecutionIdentityRestore(fn) {
const { createPeerExecutionAuthority } = await import('../lib/peerExecutionAuthority.js');
return withInstanceIdentityLock(async () => {
diff --git a/server/services/peerExecutionRuntime.test.js b/server/services/peerExecutionRuntime.test.js
new file mode 100644
index 0000000000..7264065664
--- /dev/null
+++ b/server/services/peerExecutionRuntime.test.js
@@ -0,0 +1,49 @@
+import { describe, expect, it, vi } from 'vitest';
+import EventEmitter from 'node:events';
+
+const fakeWatcher = new EventEmitter();
+fakeWatcher.close = vi.fn();
+fakeWatcher.unref = vi.fn();
+
+vi.mock('node:fs', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ watch: vi.fn(() => fakeWatcher),
+ mkdirSync: vi.fn(),
+ };
+});
+
+vi.mock('../lib/testDataIsolation.js', () => ({
+ assertNotRealDataWrite: vi.fn(),
+}));
+
+vi.mock('../lib/db.js', () => ({
+ query: vi.fn(),
+}));
+
+import { initializePeerExecution, peerExecutionRuntime, _getPeerExecutionWatcher } from './peerExecutionRuntime.js';
+
+describe('peerExecutionRuntime watcher', () => {
+ it('attaches an error listener to watcher and re-arms on receiver.kick()', async () => {
+ await initializePeerExecution();
+
+ const watcher = _getPeerExecutionWatcher();
+ expect(watcher).toBe(fakeWatcher);
+ expect(watcher.listenerCount('error')).toBe(1);
+
+ // Emitting error should close watcher and not throw
+ expect(() => {
+ fakeWatcher.emit('error', new Error('EPERM: operation not permitted'));
+ }).not.toThrow();
+
+ expect(fakeWatcher.close).toHaveBeenCalled();
+ expect(_getPeerExecutionWatcher()).toBeNull();
+
+ // Calling receiver.kick() re-arms the watcher
+ const receiver = await peerExecutionRuntime();
+ receiver.kick();
+
+ expect(_getPeerExecutionWatcher()).toBe(fakeWatcher);
+ });
+});