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: catch unhandled rejections from Telegram handlers and health/probe timers (#2536)
Adam Eivy978670016b71
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 92139c4c51..64f4c4a1c9 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -9,6 +9,7 @@## Fixed+- **[issue-2536] Catch unhandled rejections from Telegram handlers and health/probe timers.** Several async boundaries were fire-and-forget: the Telegram client dispatched `onText`/`emitter.on` handlers without awaiting or catching, `telegram.js` ran `setInterval(healthCheck)` and a couple of sync-context `bot.sendMessage(...)` calls without a `.catch`, and `instances.js` scheduled `probeAllPeers()` from `setTimeout`/`setInterval` without one — so a rejected handler or a failed fs/network read leaked an unhandled promise rejection (process-killing on Node ≥15). The client now routes every handler invocation through a `runHandler` wrapper that logs a single emoji-prefixed line on rejection; the health-check interval and both probe timers wrap their async callback in `.catch`; and the `/start`, `/help`, and unauthorized-notice sends now await or `.catch` their promise. A vitest suite drives the client's `onText` and `message` paths with a throwing handler and asserts no `unhandledRejection` escapes.- **[issue-2519] CoS handlers no longer flash a false-success toast after a failed API call.** Several Chief of Staff actions (`handleForceEvaluate` on the CoS page, the Tasks tab "Run Now" button, and the Config tab's Save + autonomy-level change) `.catch`-swallowed the request rejection and then unconditionally toasted success and mutated optimistic UI — so a network/server error still read as "done." Each now awaits inside try/catch and only toasts success / advances state after the request resolves: a failed Save keeps the editor open, and a failed autonomy-level change reverts the optimistic form params. Errors surface via a single `toast.error` (the calls already pass `{ silent: true }`).- **[issue-2510] MidiPianoRoll: clear the stale hover overlay when the transcription data changes.** The piano-roll kept its hovered note/chord identity (objects from the previous parse) when the `data`/`chords` props swapped on a mounted instance, so a re-transcription or Retry while a hover was active and the pointer sat still would keep stroking the old note at coordinates mapped into the new file until the next pointer move or Escape. A `useEffect` now drops the hover identity whenever `data`/`chords` change.- **[issue-2513] Block loopback/metadata hosts in Layered Intelligence custom `http` sources.** `fetchHttpSource` used a bare `fetch` with only an `http(s)` scheme check, so a hand-edited config could point a custom source at `127.0.0.1`, `169.254.169.254`, or `metadata.google.internal` and exfiltrate up to 8KB into the reasoner prompt. It now routes through the shared SSRF-guarded `fetchPublicText` (default posture): loopback, link-local, and cloud-metadata hosts are blocked and redirects are revalidated, while LAN/Tailscale hosts stay intentionally allowed for this single-user tool.diff --git a/server/lib/telegramClient.js b/server/lib/telegramClient.jsindex 5ed3a6e967..9510cb66e4 100644--- a/server/lib/telegramClient.js+++ b/server/lib/telegramClient.js@@ -46,6 +46,16 @@ export function createTelegramBot(token, opts = {}) {let polling = false;let activePollController = null;+ // EventEmitter/onText handlers may be async and reject. The emitter does not+ // await listeners, so a rejected promise would surface as an unhandled+ // rejection (process-killing on Node ≥15). Route every handler invocation+ // through this wrapper so a throwing handler logs instead of crashing.+ function runHandler(label, fn, args) {+ Promise.resolve()+ .then(() => fn(...args))+ .catch(err => console.error(`❌ Telegram ${label} handler error: ${err?.message || String(err)}`));+ }+async function pollLoop() {while (polling) {activePollController = new AbortController();@@ -81,7 +91,7 @@ export function createTelegramBot(token, opts = {}) {if (msg.text) {for (const { regex, fn } of textHandlers) {const match = msg.text.match(regex);- if (match) fn(msg, match);+ if (match) runHandler(`onText(${regex})`, fn, [msg, match]);}}emitter.emit('message', msg);@@ -123,7 +133,8 @@ export function createTelegramBot(token, opts = {}) {textHandlers.push({ regex, fn });},on(event, fn) {- emitter.on(event, fn);+ // Wrap so an async listener that rejects can't leak an unhandled rejection.+ emitter.on(event, (...args) => runHandler(event, fn, args));},async stopPolling() {polling = false;diff --git a/server/lib/telegramClient.test.js b/server/lib/telegramClient.test.jsnew file mode 100644index 0000000000..16dce7d7ce--- /dev/null+++ b/server/lib/telegramClient.test.js@@ -0,0 +1,100 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { createTelegramBot } from './telegramClient.js';++// Build a minimal fetch-Response stand-in that readResponseJson can consume+// (it only calls .text()).+function jsonRes(payload) {+ return { text: async () => JSON.stringify(payload) };+}++// A poll response carrying a single text message so the client dispatches it to+// registered onText / 'message' handlers.+const messageUpdate = {+ ok: true,+ result: [{ update_id: 1, message: { chat: { id: 42 }, text: '/boom' } }]+};++// Drive the poll loop exactly once (one batch of updates), then park every+// subsequent getUpdates on a promise that only settles when the request is+// aborted by stopPolling(). Keeps the test from busy-looping.+function makeFetchMock() {+ let calls = 0;+ return vi.fn((_url, opts = {}) => {+ calls++;+ if (calls === 1) return Promise.resolve(jsonRes(messageUpdate));+ return new Promise((_resolve, reject) => {+ opts.signal?.addEventListener('abort', () => {+ reject(Object.assign(new Error('aborted'), { name: 'AbortError' }));+ });+ });+ });+}++async function waitFor(predicate, timeoutMs = 2000) {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ if (predicate()) return;+ await new Promise(r => setTimeout(r, 10));+ }+}++describe('createTelegramBot — async handler rejections', () => {+ let unhandled;+ let onUnhandled;+ let originalFetch;+ let errorSpy;++ beforeEach(() => {+ unhandled = null;+ onUnhandled = (reason) => { unhandled = reason; };+ process.on('unhandledRejection', onUnhandled);+ originalFetch = global.fetch;+ errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ });++ afterEach(() => {+ process.off('unhandledRejection', onUnhandled);+ global.fetch = originalFetch;+ errorSpy.mockRestore();+ });++ it('does not leak an unhandled rejection when an onText handler rejects', async () => {+ global.fetch = makeFetchMock();+ const bot = createTelegramBot('test-token', { polling: true });++ let called = false;+ bot.onText(/\/boom/, async () => {+ called = true;+ throw new Error('handler exploded');+ });++ await waitFor(() => called);+ // Give the rejected handler promise a few microtask/macrotask turns to+ // surface as an unhandled rejection if it were going to.+ await new Promise(r => setTimeout(r, 50));+ await bot.stopPolling();++ expect(called).toBe(true);+ expect(unhandled).toBeNull();+ expect(errorSpy).toHaveBeenCalled();+ });++ it("does not leak an unhandled rejection when an 'message' listener rejects", async () => {+ global.fetch = makeFetchMock();+ const bot = createTelegramBot('test-token', { polling: true });++ let called = false;+ bot.on('message', async () => {+ called = true;+ throw new Error('listener exploded');+ });++ await waitFor(() => called);+ await new Promise(r => setTimeout(r, 50));+ await bot.stopPolling();++ expect(called).toBe(true);+ expect(unhandled).toBeNull();+ expect(errorSpy).toHaveBeenCalled();+ });+});diff --git a/server/services/instances.js b/server/services/instances.jsindex ba33884d48..4408916bef 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -1073,10 +1073,16 @@ function beginPolling() {if (cleared > 0) console.log(`🌐 Cleared backoff on ${cleared} peer(s) for fresh probe after boot`);}).catch(err => console.error(`❌ Failed to clear peer backoff on boot: ${err.message}`));- // Initial probe after a short delay- setTimeout(() => probeAllPeers(), INITIAL_PROBE_DELAY_MS);-- pollTimer = setInterval(() => probeAllPeers(), POLL_INTERVAL_MS);+ // Initial probe after a short delay. probeAllPeers() awaits fs/network work+ // that can reject; setTimeout/setInterval don't await the callback, so catch+ // here to avoid a process-killing unhandled rejection.+ setTimeout(() => {+ probeAllPeers().catch(err => console.error(`❌ Initial peer probe failed: ${err?.message || String(err)}`));+ }, INITIAL_PROBE_DELAY_MS);++ pollTimer = setInterval(() => {+ probeAllPeers().catch(err => console.error(`❌ Peer probe failed: ${err?.message || String(err)}`));+ }, POLL_INTERVAL_MS);}// A peer we can only reach over the tailnet: its probe URL (see peerBaseUrl)diff --git a/server/services/telegram.js b/server/services/telegram.jsindex 7f894e3e9a..9a51d29e87 100644--- a/server/services/telegram.js+++ b/server/services/telegram.js@@ -136,9 +136,9 @@ export async function init(sendTestMessage = false) {console.log(`📱 Telegram: connected as @${botUsername}`);// Register /start handler (always works, no auth required)- bot.onText(/\/start/, (msg) => {+ bot.onText(/\/start/, async (msg) => {const fromChatId = String(msg.chat.id);- bot.sendMessage(fromChatId,+ await bot.sendMessage(fromChatId,`Your Chat ID: <code>${fromChatId}</code>\n\n` +'Paste this into the PortOS Settings → Telegram → Chat ID field, then click Save & Test.',{ parse_mode: 'HTML' }@@ -168,7 +168,7 @@ export async function init(sendTestMessage = false) {bot.onText(/\/help/, async (msg) => {if (!isAuthorized(msg)) return;- bot.sendMessage(String(msg.chat.id),+ await bot.sendMessage(String(msg.chat.id),'<b>PortOS Bot Commands</b>\n\n' +'/status — System overview\n' +'/goals — Active goals with progress\n' +@@ -195,8 +195,11 @@ export async function init(sendTestMessage = false) {await handleCallbackQuery(query);});- // Start health check- healthCheckInterval = setInterval(healthCheck, HEALTH_CHECK_INTERVAL_MS);+ // Start health check. setInterval doesn't await the async callback, so a+ // rejection would leak as an unhandled rejection — catch it here.+ healthCheckInterval = setInterval(() => {+ healthCheck().catch(err => console.error(`📱 Telegram: health check error — ${err?.message || String(err)}`));+ }, HEALTH_CHECK_INTERVAL_MS);// Subscribe to notification eventsinitNotificationForwarding();@@ -212,10 +215,12 @@ export async function init(sendTestMessage = false) {function isAuthorized(msg) {const fromChatId = String(msg.chat.id);if (fromChatId !== authorizedChatId) {+ // Fire-and-forget from a sync guard — catch so the send failure can't leak+ // an unhandled rejection.bot?.sendMessage(fromChatId,'This bot is not configured for your chat ID.\n' +'If you own this bot, message /start to see your chat ID, then configure it in PortOS Settings.'- );+ ).catch(err => console.error(`📱 Telegram: unauthorized-notice send failed — ${err?.message || String(err)}`));return false;}return true;