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: isolate per-listener throws on imageGenEvents/videoGenEvents (#8931)
[._.]/ Adam Eivyb6456be301d3
diff --git a/server/lib/README.md b/server/lib/README.mdindex ebffe5164f..0fa77b26c4 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -330,6 +330,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `agentInstructionsFile.js` | The `AGENTS.md` + bridge `CLAUDE.md` pair a repo carries (#4852). `writeAgentInstructions(repoPath, content)` writes the body to `AGENTS.md` and the one-line `@AGENTS.md` import beside it — use it in scaffolders instead of a bare `writeFile(join(repoPath, 'CLAUDE.md'), …)`, since a generated repo carrying only one name is unreadable to half the CLIs PortOS can point at it. Constants: `AGENT_INSTRUCTIONS_FILENAME`, `CLAUDE_BRIDGE_FILENAME`, `AGENT_INSTRUCTIONS_IMPORT`. || `scaffoldSnippets.js` | Shared generated-project source snippets: `CORS_SNIPPET` provides dependency-free Express CORS middleware for the Express, PortOS, and Vite scaffold generators. || `failureLogging.js` | `logFailureWithStack(prefix, error, logger = console.error)` — logs `${prefix}: ${message}` plus `error.stack` as a second argument, so a fire-and-forget failure (boot init, a scheduled event handler) keeps its source location instead of collapsing to one message-only line (#6934, #7549). |+| `faultIsolatedEmitter.js` | `makeEmitterFaultIsolating(emitter)` overrides an `EventEmitter`'s `emit()` so each listener for a given event runs in its own try/catch — a throw in one listener no longer aborts dispatch to later listeners for that same call. Preserves emit order, `once` semantics (invokes `rawListeners()`, whose self-removing wrapper runs before the real listener), and the `true`/`false` had-listeners return value; leaves `'error'` events on Node's default semantics. Applied to `imageGenEvents`/`videoGenEvents` (#8931), whose multiple independent listeners (socket relay, quota accounting, waiter resolution, asset indexing) must not suppress each other. || `fileCore.js` | Cross-cutting filesystem primitives (`atomicWrite`, `writeFileGuarded`, `appendFileGuarded`, `copyFileGuarded`, `rmGuarded`, `unlinkGuarded`, `createWriteStreamGuarded`, directory helpers, `parseFilesystemStats(stats)` → canonical/byte-alias metrics or `null`, bounded tail reads/watchers), time/format helpers, directory sizing, and SHA-256 helpers. || `familySettingsMap.js` | The merge rule every per-provider-family map in `data/settings.json` shares (plan prices, plan tiers) — `normalizeFamilyMap(raw, normalizeValue)` and `mergeFamilyMap(stored, patch, normalizeValue)`, which hold the absent-vs-present-but-empty contract in ONE place: an omitted family keeps its stored value, one sent empty is an intentional clear and is deleted. Each store supplies only its value normalizer. Pure. || `fileUtils.js` | Backward-compatible facade re-exporting the focused file utility modules so existing deep imports need no caller changes. |diff --git a/server/lib/faultIsolatedEmitter.js b/server/lib/faultIsolatedEmitter.jsnew file mode 100644index 0000000000..47e6ca8306--- /dev/null+++ b/server/lib/faultIsolatedEmitter.js@@ -0,0 +1,36 @@+// Wraps a Node `EventEmitter` so a throwing listener cannot suppress the+// other listeners registered for the same emitted event.+//+// `EventEmitter.emit()` invokes listeners for one event synchronously, in+// registration order; if an earlier listener throws, `emit()` propagates+// that exception and every LATER listener for that call is skipped. Several+// PortOS media-gen event buses (`imageGenEvents`, `videoGenEvents`, …) have+// multiple independent listeners per event (socket relay, quota accounting,+// waiter resolution, asset indexing) — a throw in one must not suppress the+// others.+//+// `'error'` keeps Node's default semantics (including throwing when no+// listener is registered) — this helper never touches that event, since an+// unhandled `'error'` emit is a deliberate crash signal, not something to+// swallow.+export function makeEmitterFaultIsolating(emitter) {+ emitter.emit = function faultIsolatedEmit(eventName, ...args) {+ if (eventName === 'error') {+ return Object.getPrototypeOf(emitter).emit.call(emitter, eventName, ...args);+ }+ // `rawListeners` (not `listeners`) returns the internal `once` wrapper,+ // whose self-removal runs before it invokes the real listener — so+ // once-registration semantics survive calling listeners directly here+ // instead of going through the native dispatch loop.+ const listeners = emitter.rawListeners(eventName);+ for (const listener of listeners) {+ try {+ listener.apply(emitter, args);+ } catch (err) {+ console.error(`❌ Listener for '${String(eventName)}' threw: ${err.message}`);+ }+ }+ return listeners.length > 0;+ };+ return emitter;+}diff --git a/server/lib/faultIsolatedEmitter.test.js b/server/lib/faultIsolatedEmitter.test.jsnew file mode 100644index 0000000000..ced8af94bb--- /dev/null+++ b/server/lib/faultIsolatedEmitter.test.js@@ -0,0 +1,58 @@+import { describe, it, expect, vi } from 'vitest';+import { EventEmitter } from 'events';+import { makeEmitterFaultIsolating } from './faultIsolatedEmitter.js';++describe('makeEmitterFaultIsolating', () => {+ it('runs a later listener even after an earlier one throws, in registration order', () => {+ const emitter = makeEmitterFaultIsolating(new EventEmitter());+ const calls = [];+ emitter.on('completed', () => {+ calls.push('first');+ throw new Error('boom');+ });+ emitter.on('completed', () => calls.push('second'));++ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ emitter.emit('completed', { ok: true });+ errorSpy.mockRestore();++ expect(calls).toEqual(['first', 'second']);+ });++ it('preserves once() self-removal even when the once listener throws', () => {+ const emitter = makeEmitterFaultIsolating(new EventEmitter());+ let onceCalls = 0;+ emitter.once('progress', () => {+ onceCalls += 1;+ throw new Error('boom');+ });++ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ emitter.emit('progress');+ emitter.emit('progress');+ errorSpy.mockRestore();++ expect(onceCalls).toBe(1);+ expect(emitter.listenerCount('progress')).toBe(0);+ });++ it('returns true when listeners existed, false otherwise', () => {+ const emitter = makeEmitterFaultIsolating(new EventEmitter());+ expect(emitter.emit('unheard')).toBe(false);+ emitter.on('heard', () => {});+ expect(emitter.emit('heard')).toBe(true);+ });++ it('leaves the "error" event on Node default semantics (throws with no listener)', () => {+ const emitter = makeEmitterFaultIsolating(new EventEmitter());+ expect(() => emitter.emit('error', new Error('unhandled'))).toThrow('unhandled');+ });++ it('does not swallow an "error" event handled by a real listener', () => {+ const emitter = makeEmitterFaultIsolating(new EventEmitter());+ const received = [];+ emitter.on('error', (err) => received.push(err.message));+ expect(() => emitter.emit('error', new Error('handled'))).not.toThrow();+ expect(received).toEqual(['handled']);+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 2b1551ab88..b633ce3dc1 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -289,6 +289,7 @@ export * from './downloadPreflight.js';export * from './agentInstructionsFile.js';export * from './scaffoldSnippets.js';export * from './failureLogging.js';+export * from './faultIsolatedEmitter.js';export * from './fileCore.js';export * as fileUtils from './fileUtils.js';export * from './fileWriteQueue.js';diff --git a/server/services/imageGenEvents.js b/server/services/imageGenEvents.jsindex 65b21e7a35..1174f00ebf 100644--- a/server/services/imageGenEvents.js+++ b/server/services/imageGenEvents.js@@ -1,6 +1,7 @@import { EventEmitter } from 'events';+import { makeEmitterFaultIsolating } from '../lib/faultIsolatedEmitter.js';-export const imageGenEvents = new EventEmitter();+export const imageGenEvents = makeEmitterFaultIsolating(new EventEmitter());// Each in-flight image job attaches ~6 listeners (progress/status/completed/// failed + 2 watchdog activity tracers). With CODEX_PARALLEL_MAX = 10 codex// renders in flight plus a concurrent local image render, that's 60+ livediff --git a/server/services/imageGenEvents.test.js b/server/services/imageGenEvents.test.jsnew file mode 100644index 0000000000..dcf1d576ea--- /dev/null+++ b/server/services/imageGenEvents.test.js@@ -0,0 +1,22 @@+import { describe, it, expect, vi, afterEach } from 'vitest';+import { imageGenEvents } from './imageGenEvents.js';++describe('imageGenEvents', () => {+ afterEach(() => {+ imageGenEvents.removeAllListeners('completed');+ });++ it('runs later listeners on the same event even when an earlier listener throws (#8931)', () => {+ const secondListener = vi.fn();+ imageGenEvents.on('completed', () => {+ throw new Error('quota accounting exploded');+ });+ imageGenEvents.on('completed', secondListener);++ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ expect(() => imageGenEvents.emit('completed', { jobId: 'job-1' })).not.toThrow();+ errorSpy.mockRestore();++ expect(secondListener).toHaveBeenCalledWith({ jobId: 'job-1' });+ });+});diff --git a/server/services/videoGen/events.js b/server/services/videoGen/events.jsindex bf2c009495..d459eafe37 100644--- a/server/services/videoGen/events.js+++ b/server/services/videoGen/events.js@@ -1,8 +1,9 @@import { EventEmitter } from 'events';+import { makeEmitterFaultIsolating } from '../../lib/faultIsolatedEmitter.js';// Bridge for video gen progress — server/services/socket.js subscribes// and forwards as Socket.IO events `video-gen:started|progress|completed|failed`.-export const videoGenEvents = new EventEmitter();+export const videoGenEvents = makeEmitterFaultIsolating(new EventEmitter());// Video runs serially (one MLX GPU job at a time) so the listener count is// bounded, but raise the cap anyway so short job-churn windows don't trip// the warning. See imageGenEvents.js for the longer rationale.diff --git a/server/services/videoGen/events.test.js b/server/services/videoGen/events.test.jsnew file mode 100644index 0000000000..55da214b96--- /dev/null+++ b/server/services/videoGen/events.test.js@@ -0,0 +1,22 @@+import { describe, it, expect, vi, afterEach } from 'vitest';+import { videoGenEvents } from './events.js';++describe('videoGenEvents', () => {+ afterEach(() => {+ videoGenEvents.removeAllListeners('completed');+ });++ it('runs later listeners on the same event even when an earlier listener throws (#8931)', () => {+ const secondListener = vi.fn();+ videoGenEvents.on('completed', () => {+ throw new Error('socket relay exploded');+ });+ videoGenEvents.on('completed', secondListener);++ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ expect(() => videoGenEvents.emit('completed', { jobId: 'job-1' })).not.toThrow();+ errorSpy.mockRestore();++ expect(secondListener).toHaveBeenCalledWith({ jobId: 'job-1' });+ });+});