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([issue-12603]): Telegram reconnect no longer orphans timers or gives up after one failed attempt

[._.]/ Adam Eivy92b6b3298912
diff --git a/server/services/telegram.js b/server/services/telegram.js
index 71fdc04ae1..633cc70853 100644
--- a/server/services/telegram.js
+++ b/server/services/telegram.js
@@ -79,11 +79,18 @@ function cleanExpiredCheckins() {
/**
* Initialize the Telegram bot
* @param {boolean} sendTestMessage - Send a test message after connecting
+ * @param {{ fromReconnect?: boolean }} [opts] - Internal: set by the reconnect timer so a failed
+ * getMe() keeps the backoff going instead of leaving the connector down.
*/
-export async function init(sendTestMessage = false) {
+export async function init(sendTestMessage = false, { fromReconnect = false } = {}) {
await cleanup();
const settings = await getSettings();
+ // The MCP bridge owns the token while selected; a stray timer must not start a second poller.
+ if (settings.telegram?.method === 'mcp-bridge') {
+ console.log('📱 Telegram: method is mcp-bridge — manual bot not started');
+ return;
+ }
const token = settings.secrets?.telegram?.token;
const chatId = settings.telegram?.chatId;
authorizedChatId = chatId || null;
@@ -98,7 +105,6 @@ export async function init(sendTestMessage = false) {
await ensureDir(CHECKINS_DIR);
bot = createTelegramBot(token, { polling: true });
- reconnectionAttempts = 0;
// Validate token
const me = await bot.getMe().catch(async err => {
@@ -108,7 +114,11 @@ export async function init(sendTestMessage = false) {
return null;
});
- if (!me) return;
+ if (!me) {
+ if (fromReconnect) await reconnect();
+ return;
+ }
+ reconnectionAttempts = 0;
botUsername = me.username;
isConnected = true;
@@ -237,6 +247,8 @@ export async function cleanup() {
* Reconnect with exponential backoff
*/
async function reconnect() {
+ // One outage arms one timer; cleanup() can only cancel the timer it can see.
+ if (reconnectionTimeout) return;
if (reconnectionAttempts >= 10) {
console.error('📱 Telegram: max reconnection attempts reached');
return;
@@ -246,7 +258,8 @@ async function reconnect() {
console.log(`📱 Telegram: reconnecting in ${delay / 1000}s (attempt ${reconnectionAttempts}/10)`);
reconnectionTimeout = setTimeout(async () => {
- await init(false).catch(err => {
+ reconnectionTimeout = null;
+ await init(false, { fromReconnect: true }).catch(err => {
console.error(`📱 Telegram: reconnection failed — ${err.message}`);
});
}, delay);
@@ -260,8 +273,10 @@ async function healthCheck() {
// Piggyback expired-checkin cleanup on the existing health-check cadence
// rather than adding a separate timer.
cleanExpiredCheckins();
+ const checkedBot = bot;
await bot.getMe().catch(async (err) => {
console.error(`📱 Telegram: health check failed — ${err.message}`);
+ if (bot !== checkedBot) return; // cleaned up or replaced mid-flight: don't arm a timer for a dead bot
isConnected = false;
noteReadinessChanged();
await reconnect();
@@ -279,8 +294,10 @@ export async function sendMessage(text, opts = { parse_mode: 'HTML' }) {
return { success: false, error: 'Rate limit exceeded' };
}
+ const sendingBot = bot;
const result = await bot.sendMessage(authorizedChatId, text, opts).catch(async (err) => {
console.error(`📱 Telegram: send failed — ${err.message}`);
+ if (bot !== sendingBot) return null; // cleaned up or replaced mid-flight: don't arm a timer for a dead bot
isConnected = false;
noteReadinessChanged();
await reconnect();
diff --git a/server/services/telegram.test.js b/server/services/telegram.test.js
index 219a4b26d1..993d866c90 100644
--- a/server/services/telegram.test.js
+++ b/server/services/telegram.test.js
@@ -634,4 +634,82 @@ describe('telegram service', () => {
expect(fu.writes[0].data.checkins[1]).toMatchObject({ goalId: 'g2', response: 'g2 answer' });
});
});
+
+ describe('reconnect backoff', () => {
+ async function connectThenDropNetwork() {
+ vi.useFakeTimers();
+ const telegram = await loadTelegramActive();
+ await telegram.init(false);
+ h.getMe.mockClear();
+ h.getMe.mockRejectedValue(new Error('network down'));
+ h.sendMessage.mockRejectedValue(new Error('network down'));
+ return telegram;
+ }
+
+ it('arms exactly one reconnect timer for a burst of failed sends', async () => {
+ const telegram = await connectThenDropNetwork();
+ const baseline = vi.getTimerCount();
+
+ for (let i = 0; i < 3; i++) await telegram.sendMessage(`msg ${i}`);
+
+ expect(vi.getTimerCount()).toBe(baseline + 1);
+ await telegram.cleanup();
+ // cleanup() can cancel it because it is the only one
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('keeps retrying with a growing delay after a failed reconnect, stops at 10, and resets on success', async () => {
+ const telegram = await connectThenDropNetwork();
+ await telegram.sendMessage('first'); // attempt 1 armed: 5s
+
+ await vi.advanceTimersByTimeAsync(4_999);
+ expect(h.getMe).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(h.getMe).toHaveBeenCalledTimes(1);
+
+ // attempt 2 is armed with a 10s delay, not dropped
+ await vi.advanceTimersByTimeAsync(9_999);
+ expect(h.getMe).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(h.getMe).toHaveBeenCalledTimes(2);
+
+ // attempts 3..10 keep failing until the cap leaves nothing armed
+ await vi.advanceTimersByTimeAsync(5_000 * (3 + 4 + 5 + 6 + 7 + 8 + 9 + 10));
+ expect(h.getMe).toHaveBeenCalledTimes(10);
+ expect(vi.getTimerCount()).toBe(0);
+ await vi.advanceTimersByTimeAsync(600_000);
+ expect(h.getMe).toHaveBeenCalledTimes(10);
+
+ // A later successful connection resets the counter: the next outage starts at 5s again.
+ h.getMe.mockResolvedValue({ username: 'example_bot' });
+ await telegram.init(false);
+ expect(telegram.getStatus().connected).toBe(true);
+ h.getMe.mockRejectedValue(new Error('network down'));
+ h.getMe.mockClear();
+ h.sendMessage.mockRejectedValue(new Error('network down'));
+ await telegram.sendMessage('again');
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(h.getMe).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not restart the manual bot after switching to the MCP bridge', async () => {
+ const telegram = await connectThenDropNetwork();
+ await telegram.sendMessage('first');
+
+ // Even a timer that survives (cleanup not run) must not bring the bot back.
+ cfg.settings.telegram.method = 'mcp-bridge';
+ h.getMe.mockResolvedValue({ username: 'example_bot' });
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(h.getMe).not.toHaveBeenCalled();
+ expect(telegram.getStatus().connected).toBe(false);
+
+ // And the routes' cleanup() leaves no pending reconnect.
+ cfg.settings.telegram.method = undefined;
+ await telegram.init(false);
+ h.sendMessage.mockRejectedValue(new Error('network down'));
+ await telegram.sendMessage('second');
+ await telegram.cleanup();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+ });
});