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: guard Telegram handlers and serialize checkin writes (#8907)

[._.]/ Adam Eivy23fbee5ef637
diff --git a/server/services/telegram.js b/server/services/telegram.js
index 62ea5c6ede..12f53acf9b 100644
--- a/server/services/telegram.js
+++ b/server/services/telegram.js
@@ -14,6 +14,7 @@ import { notificationEvents, getNotifications } from './notifications.js';
import { forwardNotification as forwardToTelegram } from './telegramForward.js';
import { approveMemory, rejectMemory } from './memoryBackend.js';
import { ensureDir, PATHS, readJSONFileStrict, formatDuration, atomicWrite } from '../lib/fileUtils.js';
+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
import { createTokenBucket } from '../lib/telegramRateLimit.js';
import { escapeHtml, CALLBACK_APPROVE, CALLBACK_REJECT } from '../lib/telegramMessage.js';
import { getActiveAgents } from './agentManagement.js';
@@ -46,6 +47,26 @@ const CHECKINS_DIR = join(PATHS.data, 'telegram');
const CHECKINS_FILE = join(CHECKINS_DIR, 'checkins.json');
const MAX_CHECKINS = 500;
+// Serializes the checkins.json load -> mutate -> save cycle (handleCheckinResponse)
+// against concurrent Telegram messages/callbacks, matching voice/timers.js's use of
+// the same helper for its single JSON state file.
+const queueCheckinsWrite = createFileWriteQueue();
+
+/**
+ * Wrap an async `bot.onText`/`bot.on(...)` callback so a rejection is caught
+ * and logged instead of leaking as an unhandled rejection. node-telegram-bot-api's
+ * EventEmitter never awaits these callbacks, so an uncaught throw/rejection
+ * bypasses every caller and lands on `process.on('unhandledRejection')`.
+ */
+function safeHandler(fn) {
+ return (...args) =>
+ Promise.resolve()
+ .then(() => fn(...args))
+ .catch((err) => {
+ console.error(`📱 Telegram: handler error — ${err?.message || String(err)}`);
+ });
+}
+
function cleanExpiredCheckins() {
const now = Date.now();
for (const [key, value] of pendingCheckins) {
@@ -95,37 +116,37 @@ export async function init(sendTestMessage = false) {
console.log(`📱 Telegram: connected as @${botUsername}`);
// Register /start handler (always works, no auth required)
- bot.onText(/\/start/, async (msg) => {
+ bot.onText(/\/start/, safeHandler(async (msg) => {
const fromChatId = String(msg.chat.id);
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' }
);
- });
+ }));
// Register command handlers
- bot.onText(/\/status/, async (msg) => {
+ bot.onText(/\/status/, safeHandler(async (msg) => {
if (!isAuthorized(msg)) return;
await handleStatusCommand(msg);
- });
+ }));
- bot.onText(/\/goals/, async (msg) => {
+ bot.onText(/\/goals/, safeHandler(async (msg) => {
if (!isAuthorized(msg)) return;
await handleGoalsCommand(msg);
- });
+ }));
- bot.onText(/\/agents/, async (msg) => {
+ bot.onText(/\/agents/, safeHandler(async (msg) => {
if (!isAuthorized(msg)) return;
await handleAgentsCommand(msg);
- });
+ }));
- bot.onText(/\/checkin/, async (msg) => {
+ bot.onText(/\/checkin/, safeHandler(async (msg) => {
if (!isAuthorized(msg)) return;
await handleCheckinCommand(msg);
- });
+ }));
- bot.onText(/\/help/, async (msg) => {
+ bot.onText(/\/help/, safeHandler(async (msg) => {
if (!isAuthorized(msg)) return;
await bot.sendMessage(String(msg.chat.id),
'<b>PortOS Bot Commands</b>\n\n' +
@@ -136,23 +157,23 @@ export async function init(sendTestMessage = false) {
'/help — Show this message',
{ parse_mode: 'HTML' }
);
- });
+ }));
// Handle non-command messages (check-in responses)
- bot.on('message', async (msg) => {
+ bot.on('message', safeHandler(async (msg) => {
if (msg.text?.startsWith('/')) return;
if (!isAuthorized(msg)) return;
await handleCheckinResponse(msg);
- });
+ }));
// Handle inline keyboard button clicks (memory approve/reject)
- bot.on('callback_query', async (query) => {
+ bot.on('callback_query', safeHandler(async (query) => {
if (String(query.message?.chat?.id) !== authorizedChatId) {
await bot.answerCallbackQuery(query.id, { text: 'Unauthorized' }).catch(() => {});
return;
}
await handleCallbackQuery(query);
- });
+ }));
// Start health check. setInterval doesn't await the async callback, so a
// rejection would leak as an unhandled rejection — catch it here.
@@ -460,31 +481,41 @@ async function handleCheckinResponse(msg) {
const pending = pendingCheckins.get(chatId);
if (!pending) return;
- const checkins = await loadCheckins();
- // Bail rather than write: pushing onto the empty default would atomicWrite a
- // one-entry log over the whole history. The pending check-in stays pending so
- // the answer can be re-sent once the file is readable again.
- if (!checkins) {
- await bot.sendMessage(chatId, "⚠️ Couldn't read your check-in history, so I didn't record that. Nothing was overwritten — send it again once it's readable.", { parse_mode: 'HTML' });
- return;
- }
- checkins.checkins.push({
- id: uuidv4(),
- question: pending.question,
- response: msg.text,
- goalId: pending.goalId,
- askedAt: pending.askedAt,
- answeredAt: new Date().toISOString()
+ // Serialize the load -> mutate -> save cycle on a single tail so two
+ // concurrent responses (or a response racing sendCheckin's own read) can't
+ // interleave and drop one's entry (createFileWriteQueue, matching
+ // voice/timers.js's use of the same helper for its single JSON state file).
+ const recorded = await queueCheckinsWrite(async () => {
+ const checkins = await loadCheckins();
+ // Bail rather than write: pushing onto the empty default would atomicWrite a
+ // one-entry log over the whole history. The pending check-in stays pending so
+ // the answer can be re-sent once the file is readable again.
+ if (!checkins) return false;
+
+ checkins.checkins.push({
+ id: uuidv4(),
+ question: pending.question,
+ response: msg.text,
+ goalId: pending.goalId,
+ askedAt: pending.askedAt,
+ answeredAt: new Date().toISOString()
+ });
+
+ // Cap at MAX_CHECKINS entries
+ if (checkins.checkins.length > MAX_CHECKINS) {
+ checkins.checkins = checkins.checkins.slice(-MAX_CHECKINS);
+ }
+
+ await saveCheckins(checkins);
+ return true;
});
- // Cap at MAX_CHECKINS entries
- if (checkins.checkins.length > MAX_CHECKINS) {
- checkins.checkins = checkins.checkins.slice(-MAX_CHECKINS);
+ if (!recorded) {
+ await bot.sendMessage(chatId, "⚠️ Couldn't read your check-in history, so I didn't record that. Nothing was overwritten — send it again once it's readable.", { parse_mode: 'HTML' });
+ return;
}
- await saveCheckins(checkins);
pendingCheckins.delete(chatId);
-
await bot.sendMessage(chatId, '✅ Check-in recorded. Thanks!', { parse_mode: 'HTML' });
}
diff --git a/server/services/telegram.test.js b/server/services/telegram.test.js
index eed1414417..51c33a73ce 100644
--- a/server/services/telegram.test.js
+++ b/server/services/telegram.test.js
@@ -104,21 +104,26 @@ vi.mock('./memoryBackend.js', () => ({
peekMemory: vi.fn(async () => mem.memory),
}));
-// Mutable disk stand-in. `strictRead` is what `readJSONFileStrict` returns
-// (null = "behave like a normal absent file"); `writes` records every
-// atomicWrite so a test can assert that NOTHING was written. Held in a hoisted
-// holder because loadTelegram() calls vi.resetModules(), which re-evaluates
-// this factory and would otherwise hand each test fresh, unreachable spies.
-const fu = vi.hoisted(() => ({ strictRead: null, writes: [] }));
+// Mutable disk stand-in. `strictRead` is what `readJSONFileStrict` returns when
+// set (null = "fall through to the persisted `store`, or the caller's default
+// when nothing has been written yet"); `writes` records every atomicWrite so a
+// test can assert that NOTHING was written. `store` reflects the latest
+// atomicWrite payload so a second read-modify-write cycle in the SAME test sees
+// the first cycle's persisted state — needed to prove the checkins write queue
+// serializes concurrent responses instead of one clobbering the other. Held in
+// a hoisted holder because loadTelegram() calls vi.resetModules(), which
+// re-evaluates this factory and would otherwise hand each test fresh,
+// unreachable spies.
+const fu = vi.hoisted(() => ({ strictRead: null, writes: [], store: null }));
// Exhaustive factory (no importActual spread) — every export telegram.js
// imports must be listed here or the access throws "not defined on the mock".
vi.mock('../lib/fileUtils.js', () => ({
ensureDir: vi.fn(async () => {}),
PATHS: { data: '/mock/data' },
- readJSONFileStrict: vi.fn(async (_path, def) => fu.strictRead ?? { ok: true, value: def }),
+ readJSONFileStrict: vi.fn(async (_path, def) => fu.strictRead ?? { ok: true, value: fu.store ?? def }),
formatDuration: vi.fn(() => '1m'),
- atomicWrite: vi.fn(async (path, data) => { fu.writes.push({ path, data }); }),
+ atomicWrite: vi.fn(async (path, data) => { fu.writes.push({ path, data }); fu.store = data; }),
}));
vi.mock('./agentManagement.js', () => ({ getActiveAgents: vi.fn(() => []) }));
@@ -144,6 +149,7 @@ describe('telegram service', () => {
fu.strictRead = null;
mem.memory = null;
fu.writes = [];
+ fu.store = null;
active = null;
h.textHandlers = [];
h.eventHandlers = {};
@@ -444,4 +450,94 @@ describe('telegram service', () => {
expect(fu.writes).toEqual([]);
});
});
+
+ /**
+ * Guarded handlers (#8907).
+ *
+ * node-telegram-bot-api's EventEmitter never awaits `bot.onText`/`bot.on(...)`
+ * callbacks, so an unhandled rejection inside one used to escape straight to
+ * `process.on('unhandledRejection')` instead of being logged and contained.
+ * These prove every registered handler is wrapped so a downstream failure
+ * (a thrown error or a rejected `bot.sendMessage`) is caught and logged
+ * instead of propagating out of the handler.
+ */
+ describe('guarded handlers (#8907)', () => {
+ it('catches a command handler rejection instead of letting it escape', async () => {
+ const telegram = await loadTelegramActive();
+ await telegram.init(false);
+
+ const statusEntry = h.textHandlers.find((t) => t.regex.source.includes('status'));
+ h.sendMessage.mockRejectedValueOnce(new Error('Telegram 429: rate limited'));
+
+ // The handler itself must not throw or return a rejected promise — the
+ // caller (node-telegram-bot-api) never awaits it, so a throw here would
+ // otherwise become an unhandled rejection.
+ await expect(statusEntry.fn({ chat: { id: 42 }, text: '/status' })).resolves.toBeUndefined();
+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('handler error'));
+ });
+
+ it('catches a message-handler rejection (check-in response) instead of letting it escape', async () => {
+ const telegram = await loadTelegramActive();
+ const { getGoals } = await import('./identity.js');
+ getGoals.mockResolvedValue({ goals: [{ id: 'g1', title: 'Example Goal', status: 'active', progress: 40 }] });
+ await telegram.init(false);
+ await telegram.sendCheckin();
+
+ const msgHandler = h.eventHandlers.message[0];
+ h.sendMessage.mockRejectedValueOnce(new Error('Telegram 403: bot was blocked by the user'));
+
+ await expect(msgHandler({ chat: { id: 42 }, text: 'Made good progress' })).resolves.toBeUndefined();
+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('handler error'));
+ });
+
+ it('catches a callback_query handler exception instead of letting it escape', async () => {
+ const telegram = await loadTelegramActive();
+ await telegram.init(false);
+
+ const cbHandler = h.eventHandlers.callback_query[0];
+ // handleCallbackQuery's internal try/catch only guards approveMemory /
+ // rejectMemory; a malformed `data` (not a string, e.g. a corrupt
+ // callback payload) throws synchronously on `.startsWith` before that
+ // try/catch is reached. That escape is exactly what the outer
+ // `safeHandler` wrap exists to contain.
+ await expect(
+ cbHandler({ id: 'cb-1', message: { chat: { id: 42 }, text: 'orig', message_id: 1 }, data: 12345 })
+ ).resolves.toBeUndefined();
+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('handler error'));
+ });
+ });
+
+ /**
+ * Checkins write queue (#8907).
+ *
+ * `handleCheckinResponse` is a `loadCheckins → push → atomicWrite` cycle. Two
+ * concurrent invocations racing against the same on-disk state used to
+ * interleave: both read the same pre-write snapshot, so whichever
+ * `atomicWrite` landed last silently discarded the other's entry. The fix
+ * routes the cycle through `createFileWriteQueue` so the second cycle only
+ * starts reading after the first has fully persisted.
+ */
+ describe('checkins write queue (#8907)', () => {
+ it('persists both records when two check-in responses are processed concurrently', async () => {
+ const telegram = await loadTelegramActive();
+ const { getGoals } = await import('./identity.js');
+ getGoals.mockResolvedValue({ goals: [{ id: 'g1', title: 'Example Goal', status: 'active', progress: 40 }] });
+ await telegram.init(false);
+ await telegram.sendCheckin();
+ h.sendMessage.mockClear();
+ fu.writes = [];
+
+ const msgHandler = h.eventHandlers.message[0];
+ // Fire both "responses" without awaiting between them, so both handler
+ // invocations are in flight before either reaches its persisted write —
+ // exactly the race the un-serialized RMW cycle used to lose.
+ const first = msgHandler({ chat: { id: 42 }, text: 'first response' });
+ const second = msgHandler({ chat: { id: 42 }, text: 'second response' });
+ await Promise.all([first, second]);
+
+ expect(fu.writes).toHaveLength(2);
+ const finalCheckins = fu.writes[fu.writes.length - 1].data.checkins;
+ expect(finalCheckins.map((c) => c.response)).toEqual(['first response', 'second response']);
+ });
+ });
});