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

refactor: share one notification-forward pipeline between the two Telegram transports (#5688)

[._.]/ Adam Eivy8f50dc05e5b1
diff --git a/server/lib/README.md b/server/lib/README.md
index 68911cfb33..6f2434be1a 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -409,6 +409,8 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `renderSlot.js` | Render-slot helpers for `(proof\|final)Image` per stage. |
| `renderTargets.js` | Render-target alphabet (#3231): `RENDER_TARGET`/`RENDER_TARGETS` name every creative surface that enqueues renders (universe-bible, sprite-reference, music-video, …) — the keys into `settings.renderDefaults` — plus the `RENDER_TARGET_BACKEND_AUTO` fall-through sentinel. Dependency-free leaf; resolved per surface by `services/imageGen/cloudProviderConfig.js#resolveRenderTargetConfig`. |
| `telegramClient.js` | Telegram bot client. |
+| `telegramMessage.js` | Pure builder for the Telegram notification wire message, shared by both transports (`services/telegram.js` and `services/telegramBridge.js`, which drifted apart while each kept a copy — #5688). `buildNotificationMessage(notification, { approvalBody })` → `{ text, options }`: emoji + escaped title, the body truncated to `TELEGRAM_MAX_RAW_CHARS` (2800) BEFORE escaping so the escaped result stays under Telegram's 4096 cap and a slice can't split an entity, the priority line, and the memory approve/reject `reply_markup` as a plain OBJECT (both transports post JSON, so a pre-serialized string would arrive as a literal string). `approvalBody` is resolved by the caller because the memory lookup is I/O. Also exports `escapeHtml`, `truncateForTelegram`, `isMemoryApprovalNotification`, the `NOTIFICATION_EMOJI`/`PRIORITY_EMOJI` maps (keyed by literal `NOTIFICATION_TYPES` values to stay a dependency-free leaf; pinned to the real enum by a parity test), and the `CALLBACK_APPROVE`/`CALLBACK_REJECT` prefixes the bot's `callback_query` handler parses back out. |
+| `telegramRateLimit.js` | `createTokenBucket({ max = 30, refillMs = 60_000 })` → `{ consume() }` — the coarse full-refill-per-window bucket both Telegram transports use against Telegram's ~30 msg/min throttle. Each transport creates its OWN instance: they are never both active, and one shared bucket would let a transport inherit the other's drained budget. Pure (reads `Date.now()`, owns no timer). |
| `tempPathGuard.js` | Throwaway-path guard for destructive test fixtures. `isTempPath(target)` — true only for an absolute path that is a STRICT descendant of `os.tmpdir()` **after symlinks are resolved** (`os.tmpdir()` itself is refused, or `destroyGitSandbox(tmpdir())` would wipe every process's scratch; a `..` segment is refused rather than lexically collapsed; macOS `/var/folders/...` and `/private/var/folders/...` both pass). `assertTempPath(target, operation)` throws otherwise and returns `target` so it can wrap an argument inline. Use it before any fixture `git init` / `git config` / `rm -rf`: `spawn` silently substitutes `process.cwd()` for a missing cwd, which is how a test run once set `core.bare = true` on a real checkout (#4554). |
| `vaultCrypto.js` | Privacy Center PII Vault field-level encryption (issue #2140). AES-256-GCM `encryptValue`/`decryptValue` (`v1:<iv>:<tag>:<ct>` format, per-value 12-byte IV), `ensureVaultKey()` self-heal (generates `PRIVACY_VAULT_KEY` into the install root's `.env` on first write, replacing any invalid line; never logs the value), key resolution that falls back to reading `.env` so decrypt/status survive a server restart, `isVaultKeyConfigured()`, and the per-type `maskValue(type, plaintext)` display masking (last-4 / domain-visible / street-masked). Plaintext must never be logged by callers. |
diff --git a/server/lib/index.js b/server/lib/index.js
index f87a18b527..a67ffd4b59 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -389,6 +389,8 @@ export * from './spriteAnimationTracks.js';
export * from './spriteAnimationTrackStore.js';
export * from './postDrillTypes.js';
export * from './telegramClient.js';
+export * from './telegramMessage.js';
+export * from './telegramRateLimit.js';
export * from './tempPathGuard.js';
export * from './textUtils.js';
export * from './vaultCrypto.js';
diff --git a/server/lib/telegramMessage.js b/server/lib/telegramMessage.js
new file mode 100644
index 0000000000..5a9588cd15
--- /dev/null
+++ b/server/lib/telegramMessage.js
@@ -0,0 +1,116 @@
+/**
+ * Telegram notification message builder (pure — no I/O).
+ *
+ * Single source of truth for the wire message both Telegram transports send:
+ * `services/telegram.js` (the direct polling bot) and
+ * `services/telegramBridge.js` (the MCP-plugin HTTP bridge). They are never both
+ * active — `routes/telegram.js` picks one from `settings.telegram.method` — but a
+ * user can flip between them, so the message they emit must be identical. The
+ * copies had already drifted: the bridge silently dropped the memory-approval
+ * inline keyboard and the length cap (#5688).
+ *
+ * Kept dependency-free so it stays a pure leaf: the emoji map is keyed by the
+ * literal `NOTIFICATION_TYPES` values rather than importing the notifications
+ * service (which owns disk I/O and an EventEmitter). `telegramMessage.test.js`
+ * pins those keys against the real enum.
+ */
+
+// Callback-data prefixes for the memory approve/reject inline keyboard. The
+// direct bot's `callback_query` handler parses these back out, so the builder
+// and the handler must agree on them.
+export const CALLBACK_APPROVE = 'mem_approve';
+export const CALLBACK_REJECT = 'mem_reject';
+
+/**
+ * Telegram rejects a message over 4096 characters outright. Cap the raw body
+ * BEFORE escaping so the escaped result is guaranteed under the limit: escaping
+ * expands at most 5x per character (`&` → `&amp;`) but typical prose is <1.2x,
+ * so 2800 raw lands conservatively under 4096 escaped.
+ */
+export const TELEGRAM_MAX_RAW_CHARS = 2800;
+
+// Emoji per notification type. Types with no row here (AGENT_WARNING,
+// AUTOPILOT_PAUSED, CREATIVE_COMMISSION) intentionally fall back to 🔔.
+export const NOTIFICATION_EMOJI = {
+ memory_approval: '🧠',
+ task_approval: '✅',
+ code_review: '🔍',
+ health_issue: '⚠️',
+ briefing_ready: '📋',
+ autobiography_prompt: '📝',
+ plan_question: '❓',
+ daily_post_reminder: '🧪'
+};
+
+export const PRIORITY_EMOJI = {
+ low: '🟢',
+ medium: '🟡',
+ high: '🟠',
+ critical: '🔴'
+};
+
+/**
+ * Escape the HTML entities Telegram's `parse_mode: 'HTML'` treats as markup.
+ */
+export function escapeHtml(text) {
+ if (!text) return '';
+ return text
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;');
+}
+
+/**
+ * Truncate to the raw-character cap, appending an ellipsis when it bites.
+ * Callers must truncate BEFORE escaping — slicing escaped text can split an
+ * entity (`&am`) and produce broken markup.
+ */
+export function truncateForTelegram(text) {
+ if (!text) return '';
+ return text.length > TELEGRAM_MAX_RAW_CHARS
+ ? `${text.slice(0, TELEGRAM_MAX_RAW_CHARS)}…`
+ : text;
+}
+
+/**
+ * Whether a notification should carry the memory approve/reject keyboard.
+ */
+export function isMemoryApprovalNotification(notification) {
+ return notification?.type === 'memory_approval' && Boolean(notification?.metadata?.memoryId);
+}
+
+/**
+ * Build the Telegram message for a notification.
+ *
+ * @param {object} notification - the notification record ({ type, title, description, priority, metadata })
+ * @param {{ approvalBody?: string|null }} [opts] - `approvalBody` is the
+ * already-resolved memory text for a memory-approval notification (the lookup
+ * is I/O, so it stays in the caller); falls back to the description.
+ * @returns {{ text: string, options: object }} text plus the sendMessage options
+ * (`parse_mode`, and `reply_markup` as a plain object — both transports post
+ * JSON, so a pre-serialized string would reach Telegram as a literal string).
+ */
+export function buildNotificationMessage(notification, { approvalBody = null } = {}) {
+ const emoji = NOTIFICATION_EMOJI[notification.type] || '🔔';
+ const priorityEmoji = PRIORITY_EMOJI[notification.priority] || '';
+ const lines = [`${emoji} <b>${escapeHtml(notification.title)}</b>`];
+ const options = { parse_mode: 'HTML' };
+
+ const isApproval = isMemoryApprovalNotification(notification);
+ const body = truncateForTelegram((isApproval ? approvalBody : null) || notification.description || '');
+ if (body) lines.push(escapeHtml(body));
+
+ if (isApproval) {
+ const { memoryId } = notification.metadata;
+ options.reply_markup = {
+ inline_keyboard: [[
+ { text: '✅ Approve', callback_data: `${CALLBACK_APPROVE}:${memoryId}` },
+ { text: '❌ Reject', callback_data: `${CALLBACK_REJECT}:${memoryId}` }
+ ]]
+ };
+ }
+
+ if (notification.priority) lines.push(`Priority: ${priorityEmoji} ${notification.priority}`);
+
+ return { text: lines.join('\n'), options };
+}
diff --git a/server/lib/telegramMessage.test.js b/server/lib/telegramMessage.test.js
new file mode 100644
index 0000000000..748498ecc1
--- /dev/null
+++ b/server/lib/telegramMessage.test.js
@@ -0,0 +1,87 @@
+/**
+ * Focused tests for the pure Telegram message builder.
+ *
+ * The transports' own suites drive `buildNotificationMessage` through
+ * `forwardNotification` end-to-end. What an integration test would NOT localise
+ * is the truncate-then-escape ORDERING: slicing already-escaped text can cut an
+ * HTML entity in half (`&am`), which Telegram renders as broken markup rather
+ * than rejecting outright — a silent corruption, not a visible failure.
+ *
+ * The emoji-map parity check lives here too: the map is keyed by literal type
+ * strings so the module stays a dependency-free leaf, and this pins those keys
+ * to the real `NOTIFICATION_TYPES` enum.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ buildNotificationMessage,
+ escapeHtml,
+ truncateForTelegram,
+ NOTIFICATION_EMOJI,
+ TELEGRAM_MAX_RAW_CHARS,
+ CALLBACK_APPROVE,
+ CALLBACK_REJECT
+} from './telegramMessage.js';
+import { NOTIFICATION_TYPES } from '../services/notifications.js';
+
+describe('telegramMessage', () => {
+ describe('truncate/escape ordering', () => {
+ it('truncates the RAW body before escaping so a slice cannot split an entity', () => {
+ // Land an `&` exactly on the cut so escaping first would leave `&am`.
+ const body = `${'a'.repeat(TELEGRAM_MAX_RAW_CHARS - 1)}&${'b'.repeat(50)}`;
+ const { text } = buildNotificationMessage({ type: 'health_issue', title: 'T', description: body });
+
+ const line = text.split('\n')[1];
+ expect(line.endsWith('&amp;…')).toBe(true);
+ expect(line).not.toMatch(/&(?!amp;|lt;|gt;)/);
+ });
+
+ it('appends the ellipsis only when the cap actually bites', () => {
+ const exact = 'x'.repeat(TELEGRAM_MAX_RAW_CHARS);
+ expect(truncateForTelegram(exact)).toBe(exact);
+ expect(truncateForTelegram(`${exact}y`)).toBe(`${exact}…`);
+ });
+
+ it('escapes every markup character Telegram HTML mode would interpret', () => {
+ expect(escapeHtml('a & b <i>c</i>')).toBe('a &amp; b &lt;i&gt;c&lt;/i&gt;');
+ expect(escapeHtml('')).toBe('');
+ expect(escapeHtml(undefined)).toBe('');
+ });
+ });
+
+ describe('memory approval', () => {
+ it('prefers the resolved approval body over the description and attaches the keyboard', () => {
+ const { text, options } = buildNotificationMessage(
+ {
+ type: NOTIFICATION_TYPES.MEMORY_APPROVAL,
+ title: 'New memory',
+ description: 'fallback text',
+ priority: 'high',
+ metadata: { memoryId: 'mem-1' }
+ },
+ { approvalBody: 'the memory summary' }
+ );
+
+ expect(text).toContain('the memory summary');
+ expect(text).not.toContain('fallback text');
+ expect(options.reply_markup.inline_keyboard[0].map(b => b.callback_data)).toEqual([
+ `${CALLBACK_APPROVE}:mem-1`,
+ `${CALLBACK_REJECT}:mem-1`
+ ]);
+ });
+
+ it('carries no keyboard when the approval notification has no memoryId', () => {
+ const { options } = buildNotificationMessage({
+ type: NOTIFICATION_TYPES.MEMORY_APPROVAL,
+ title: 'Orphan',
+ metadata: {}
+ });
+ expect(options).toEqual({ parse_mode: 'HTML' });
+ });
+ });
+
+ it('keys the emoji map by real NOTIFICATION_TYPES values', () => {
+ const known = new Set(Object.values(NOTIFICATION_TYPES));
+ expect(Object.keys(NOTIFICATION_EMOJI).filter(k => !known.has(k))).toEqual([]);
+ });
+});
diff --git a/server/lib/telegramRateLimit.js b/server/lib/telegramRateLimit.js
new file mode 100644
index 0000000000..1f6b40145b
--- /dev/null
+++ b/server/lib/telegramRateLimit.js
@@ -0,0 +1,38 @@
+/**
+ * Telegram outbound rate limiter (pure — no I/O, no timers).
+ *
+ * Telegram throttles bots at roughly 30 messages/minute. Both transports
+ * (`services/telegram.js`, `services/telegramBridge.js`) enforce that with the
+ * same coarse token bucket: a full refill once the window has elapsed since the
+ * last refill, rather than a continuous drip.
+ *
+ * Each transport creates its OWN instance. They are never both active, and a
+ * single module-level bucket shared between them would be a behaviour change —
+ * switching transports would inherit the other one's drained budget.
+ */
+
+const DEFAULT_MAX = 30;
+const DEFAULT_REFILL_MS = 60_000;
+
+/**
+ * @param {{ max?: number, refillMs?: number }} [opts]
+ * @returns {{ consume: () => boolean }} `consume()` takes a token, returning
+ * false when the bucket is empty for the current window.
+ */
+export function createTokenBucket({ max = DEFAULT_MAX, refillMs = DEFAULT_REFILL_MS } = {}) {
+ let tokens = max;
+ let lastRefill = Date.now();
+
+ return {
+ consume() {
+ const now = Date.now();
+ if (now - lastRefill >= refillMs) {
+ tokens = max;
+ lastRefill = now;
+ }
+ if (tokens <= 0) return false;
+ tokens--;
+ return true;
+ }
+ };
+}
diff --git a/server/services/telegram.js b/server/services/telegram.js
index 2dd5cf90eb..c59c1b645c 100644
--- a/server/services/telegram.js
+++ b/server/services/telegram.js
@@ -9,11 +9,12 @@ import { createTelegramBot } from '../lib/telegramClient.js';
import { join } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { getSettings } from './settings.js';
-import { notificationEvents, NOTIFICATION_TYPES, getNotifications } from './notifications.js';
-import { getDomainAutonomyMode } from './cosState.js';
-import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';
-import { approveMemory, rejectMemory, peekMemory } from './memoryBackend.js';
+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 { createTokenBucket } from '../lib/telegramRateLimit.js';
+import { escapeHtml, CALLBACK_APPROVE, CALLBACK_REJECT } from '../lib/telegramMessage.js';
import { getActiveAgents } from './agentManagement.js';
import { getGoals } from './identity.js';
@@ -32,11 +33,9 @@ let notificationSubscription = null;
let authorizedChatId = null;
let cachedForwardTypes = null;
-// Rate limiter: token bucket (30 messages/minute)
-let tokenBucket = 30;
-let lastTokenRefill = Date.now();
-const BUCKET_MAX = 30;
-const REFILL_INTERVAL = 60000; // 1 minute
+// Rate limiter: token bucket (30 messages/minute). Per-transport instance —
+// see lib/telegramRateLimit.js for why it is not shared with the bridge.
+const rateLimiter = createTokenBucket();
// Pending check-ins with 10-minute TTL
const pendingCheckins = new Map();
@@ -46,41 +45,6 @@ const CHECKINS_DIR = join(PATHS.data, 'telegram');
const CHECKINS_FILE = join(CHECKINS_DIR, 'checkins.json');
const MAX_CHECKINS = 500;
-// Emoji map for notification types
-const NOTIFICATION_EMOJI = {
- [NOTIFICATION_TYPES.MEMORY_APPROVAL]: '🧠',
- [NOTIFICATION_TYPES.TASK_APPROVAL]: '✅',
- [NOTIFICATION_TYPES.CODE_REVIEW]: '🔍',
- [NOTIFICATION_TYPES.HEALTH_ISSUE]: '⚠️',
- [NOTIFICATION_TYPES.BRIEFING_READY]: '📋',
- [NOTIFICATION_TYPES.AUTOBIOGRAPHY_PROMPT]: '📝',
- [NOTIFICATION_TYPES.PLAN_QUESTION]: '❓',
- [NOTIFICATION_TYPES.DAILY_POST_REMINDER]: '🧪'
-};
-
-// Priority emoji
-const PRIORITY_EMOJI = {
- low: '🟢',
- medium: '🟡',
- high: '🟠',
- critical: '🔴'
-};
-
-function refillTokens() {
- const now = Date.now();
- if (now - lastTokenRefill >= REFILL_INTERVAL) {
- tokenBucket = BUCKET_MAX;
- lastTokenRefill = now;
- }
-}
-
-function consumeToken() {
- refillTokens();
- if (tokenBucket <= 0) return false;
- tokenBucket--;
- return true;
-}
-
function cleanExpiredCheckins() {
const now = Date.now();
for (const [key, value] of pendingCheckins) {
@@ -90,14 +54,6 @@ function cleanExpiredCheckins() {
}
}
-function escapeHtml(text) {
- if (!text) return '';
- return text
- .replace(/&/g, '&amp;')
- .replace(/</g, '&lt;')
- .replace(/>/g, '&gt;');
-}
-
/**
* Initialize the Telegram bot
* @param {boolean} sendTestMessage - Send a test message after connecting
@@ -292,7 +248,7 @@ async function healthCheck() {
export async function sendMessage(text, opts = { parse_mode: 'HTML' }) {
if (!bot || !authorizedChatId) return { success: false, error: !bot ? 'Bot not initialized' : 'No chatId configured' };
- if (!consumeToken()) {
+ if (!rateLimiter.consume()) {
console.log('📱 Telegram: rate limit reached, skipping message');
return { success: false, error: 'Rate limit exceeded' };
}
@@ -326,10 +282,6 @@ export function updateCachedForwardTypes(forwardTypes) {
cachedForwardTypes = forwardTypes;
}
-// Callback data prefixes for inline keyboard actions
-const CALLBACK_APPROVE = 'mem_approve';
-const CALLBACK_REJECT = 'mem_reject';
-
/**
* Handle inline keyboard callback queries (memory approve/reject)
*/
@@ -377,68 +329,10 @@ async function handleCallbackQuery(query) {
}
}
-/**
- * Forward a notification to Telegram
- */
-async function forwardNotification(notification) {
- // Use cached forwardTypes to avoid disk I/O on every notification.
- // (Runs before the per-domain gate so a filtered-out notification skips the
- // state read entirely, and so dry-run only reports what execute would send.)
- if (Array.isArray(cachedForwardTypes) && cachedForwardTypes.length > 0) {
- if (!cachedForwardTypes.includes(notification.type)) return;
- }
-
- // Per-domain autonomy gate: `off` suppresses outbound forwarding; `dry-run`
- // logs what would have been sent without actually messaging the channel.
- const mode = await getDomainAutonomyMode('messages');
- if (mode !== 'execute') {
- if (mode === 'dry-run') {
- console.log(`📨 [dry-run] Messages auto-send would forward notification: ${notification.type} — "${notification.title}"`);
- }
- return;
- }
-
- // Daily messages budget (#711): once today's auto-send count reaches the cap,
- // suppress further forwarding for the rest of the day (acts like `off`).
- const budget = await getDomainBudgetStatus('messages');
- if (!budget.withinBudget) {
- console.log(`📨 Messages auto-send daily ${budget.exceeded} budget reached — suppressing forward: ${notification.type} — "${notification.title}"`);
- return;
- }
-
- const emoji = NOTIFICATION_EMOJI[notification.type] || '🔔';
- const priorityEmoji = PRIORITY_EMOJI[notification.priority] || '';
- const lines = [`${emoji} <b>${escapeHtml(notification.title)}</b>`];
- const opts = { parse_mode: 'HTML' };
- const isMemoryApproval = notification.type === NOTIFICATION_TYPES.MEMORY_APPROVAL && notification.metadata?.memoryId;
-
- if (isMemoryApproval) {
- const memory = await peekMemory(notification.metadata.memoryId).catch(() => null);
- const raw = memory?.summary || memory?.content || notification.description || '';
- // Telegram 4096 char limit; truncate raw text before escaping to guarantee
- // the escaped result stays under limit (escaping expands at most 5x per char
- // for &amp; but typical text is <1.2x; 2800 raw → ≤3500 escaped conservatively)
- const MAX_RAW = 2800;
- const truncated = raw.length > MAX_RAW ? raw.slice(0, MAX_RAW) + '…' : raw;
- if (truncated) lines.push(escapeHtml(truncated));
- opts.reply_markup = JSON.stringify({
- inline_keyboard: [[
- { text: '✅ Approve', callback_data: `${CALLBACK_APPROVE}:${notification.metadata.memoryId}` },
- { text: '❌ Reject', callback_data: `${CALLBACK_REJECT}:${notification.metadata.memoryId}` }
- ]]
- });
- } else if (notification.description) {
- lines.push(escapeHtml(notification.description));
- }
-
- if (notification.priority) lines.push(`Priority: ${priorityEmoji} ${notification.priority}`);
- const startTime = Date.now();
- await sendMessage(lines.join('\n'), opts);
- // Count the forward (and its wall-clock) against the messages daily budget
- // (#711) so both the actions and minutes caps are enforced for this domain.
- await recordDomainUsage('messages', { actions: 1, ms: Date.now() - startTime })
- .catch(err => console.error(`❌ Failed to record messages budget usage: ${err.message}`));
-}
+// Forward a notification through the shared pipeline. An arrow (not a bound
+// reference) so the CURRENT cachedForwardTypes is read on every event.
+const forwardNotification = (notification) =>
+ forwardToTelegram(notification, { cachedForwardTypes, sendMessage });
/**
* Subscribe to notification events for forwarding
diff --git a/server/services/telegram.test.js b/server/services/telegram.test.js
index a8d85293b8..168290d619 100644
--- a/server/services/telegram.test.js
+++ b/server/services/telegram.test.js
@@ -13,6 +13,7 @@
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { TELEGRAM_MAX_RAW_CHARS } from '../lib/telegramMessage.js';
// Shared, mutable holder for the fake bot's captured handlers + spies. Reset in
// beforeEach so each test sees a clean bot. `vi.hoisted` makes it available to
@@ -90,10 +91,13 @@ vi.mock('./domainUsage.js', () => ({
recordDomainUsage: vi.fn(async () => {}),
}));
+// `memory` is what peekMemory resolves to; held in a hoisted holder because
+// loadTelegram() calls vi.resetModules(), which re-evaluates this factory.
+const mem = vi.hoisted(() => ({ memory: null }));
vi.mock('./memoryBackend.js', () => ({
approveMemory: vi.fn(async () => ({ success: true })),
rejectMemory: vi.fn(async () => ({ success: true })),
- peekMemory: vi.fn(async () => null),
+ peekMemory: vi.fn(async () => mem.memory),
}));
// Mutable disk stand-in. `strictRead` is what `readJSONFileStrict` returns
@@ -134,6 +138,7 @@ describe('telegram service', () => {
beforeEach(() => {
cfg.settings = defaultSettings();
fu.strictRead = null;
+ mem.memory = null;
fu.writes = [];
active = null;
h.textHandlers = [];
@@ -266,6 +271,61 @@ describe('telegram service', () => {
});
});
+ /**
+ * Shared notification-forward pipeline (#5688).
+ *
+ * The message body is now built by lib/telegramMessage.js for BOTH transports.
+ * These mirror telegramBridge.test.js so a change that pleases one transport
+ * cannot silently regress the other.
+ */
+ describe('notification forwarding (#5688)', () => {
+ async function forward(notification) {
+ const telegram = await loadTelegramActive();
+ await telegram.init(false);
+ h.sendMessage.mockClear();
+ notifEmitter.emit('added', notification);
+ // Let the async forward chain (gates -> peekMemory -> send) settle.
+ for (let i = 0; i < 5; i++) await new Promise((r) => setImmediate(r));
+ return h.sendMessage.mock.calls[0];
+ }
+
+ it('attaches the memory approve/reject keyboard to a MEMORY_APPROVAL forward', async () => {
+ mem.memory = { summary: 'Remember the example project deadline' };
+ const call = await forward({
+ type: 'memory_approval',
+ title: 'Approve memory?',
+ description: 'ignored once the memory resolves',
+ priority: 'medium',
+ metadata: { memoryId: 'mem-1' },
+ });
+
+ expect(call, 'a memory approval must be forwarded').toBeDefined();
+ const [chatId, text, options] = call;
+ expect(chatId).toBe('42');
+ expect(text).toContain('Remember the example project deadline');
+ expect(text).not.toContain('ignored once the memory resolves');
+ expect(options.reply_markup.inline_keyboard[0]).toEqual([
+ { text: '✅ Approve', callback_data: 'mem_approve:mem-1' },
+ { text: '❌ Reject', callback_data: 'mem_reject:mem-1' },
+ ]);
+ });
+
+ it('truncates a body past the raw cap before escaping it', async () => {
+ // '&' sits exactly on the cut: escaping first would leave a split '&am'.
+ mem.memory = { content: `${'a'.repeat(TELEGRAM_MAX_RAW_CHARS - 1)}&${'b'.repeat(200)}` };
+ const call = await forward({
+ type: 'memory_approval',
+ title: 'Long one',
+ priority: 'low',
+ metadata: { memoryId: 'mem-2' },
+ });
+
+ const bodyLine = call[1].split('\n')[1];
+ expect(bodyLine.endsWith('&amp;…')).toBe(true);
+ expect(bodyLine).not.toContain('b');
+ });
+ });
+
/**
* Strict-read regression (#4115).
*
diff --git a/server/services/telegramBridge.js b/server/services/telegramBridge.js
index e2a1029a39..007ec94573 100644
--- a/server/services/telegramBridge.js
+++ b/server/services/telegramBridge.js
@@ -12,9 +12,9 @@
import { join } from 'path';
import { homedir } from 'os';
import { tryReadFile } from '../lib/fileUtils.js';
-import { notificationEvents, NOTIFICATION_TYPES } from './notifications.js';
-import { getDomainAutonomyMode } from './cosState.js';
-import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';
+import { notificationEvents } from './notifications.js';
+import { forwardNotification as forwardToTelegram } from './telegramForward.js';
+import { createTokenBucket } from '../lib/telegramRateLimit.js';
const CHANNELS_DIR = join(homedir(), '.claude', 'channels', 'telegram');
const ENV_FILE = join(CHANNELS_DIR, '.env');
@@ -28,53 +28,9 @@ let botUsername = null;
let isActive = false;
let notificationSubscription = null;
-// Rate limiter: token bucket (30 messages/minute)
-let tokenBucket = 30;
-let lastTokenRefill = Date.now();
-const BUCKET_MAX = 30;
-const REFILL_INTERVAL = 60000;
-
-// Emoji maps (shared with manual bot)
-const NOTIFICATION_EMOJI = {
- [NOTIFICATION_TYPES.MEMORY_APPROVAL]: '🧠',
- [NOTIFICATION_TYPES.TASK_APPROVAL]: '✅',
- [NOTIFICATION_TYPES.CODE_REVIEW]: '🔍',
- [NOTIFICATION_TYPES.HEALTH_ISSUE]: '⚠️',
- [NOTIFICATION_TYPES.BRIEFING_READY]: '📋',
- [NOTIFICATION_TYPES.AUTOBIOGRAPHY_PROMPT]: '📝',
- [NOTIFICATION_TYPES.PLAN_QUESTION]: '❓',
- [NOTIFICATION_TYPES.DAILY_POST_REMINDER]: '🧪'
-};
-
-const PRIORITY_EMOJI = {
- low: '🟢',
- medium: '🟡',
- high: '🟠',
- critical: '🔴'
-};
-
-function refillTokens() {
- const now = Date.now();
- if (now - lastTokenRefill >= REFILL_INTERVAL) {
- tokenBucket = BUCKET_MAX;
- lastTokenRefill = now;
- }
-}
-
-function consumeToken() {
- refillTokens();
- if (tokenBucket <= 0) return false;
- tokenBucket--;
- return true;
-}
-
-function escapeHtml(text) {
- if (!text) return '';
- return text
- .replace(/&/g, '&amp;')
- .replace(/</g, '&lt;')
- .replace(/>/g, '&gt;');
-}
+// Rate limiter: token bucket (30 messages/minute). Per-transport instance —
+// see lib/telegramRateLimit.js for why it is not shared with the direct bot.
+const rateLimiter = createTokenBucket();
/**
* Read bot token from MCP plugin's .env file
@@ -168,21 +124,19 @@ export async function cleanup() {
/**
* Send a message via direct Bot API HTTP call
*/
-export async function sendMessage(text) {
+export async function sendMessage(text, opts = { parse_mode: 'HTML' }) {
if (!botToken || !chatId) {
return { success: false, error: !botToken ? 'No bot token' : 'No chat ID' };
}
- if (!consumeToken()) {
+ if (!rateLimiter.consume()) {
console.log('📱 TG Bridge: rate limit reached, skipping message');
return { success: false, error: 'Rate limit exceeded' };
}
- const result = await apiCall('sendMessage', {
- chat_id: chatId,
- text,
- parse_mode: 'HTML'
- });
+ // Spread the caller's options so parse_mode AND reply_markup (the memory
+ // approve/reject keyboard) reach the API call, not just the text.
+ const result = await apiCall('sendMessage', { chat_id: chatId, text, ...opts });
return result
? { success: true }
@@ -221,48 +175,10 @@ export function updateCachedForwardTypes(forwardTypes) {
cachedForwardTypes = forwardTypes;
}
-/**
- * Forward a notification to Telegram via HTTP API
- */
-async function forwardNotification(notification) {
- // Cached forward-type filter first (mirrors telegram.js): a filtered-out
- // notification skips the state read, and dry-run only reports what execute
- // would actually send.
- if (Array.isArray(cachedForwardTypes) && cachedForwardTypes.length > 0) {
- if (!cachedForwardTypes.includes(notification.type)) return;
- }
-
- // Per-domain autonomy gate (mirrors telegram.js): `off` suppresses outbound
- // forwarding; `dry-run` logs what would have been sent without messaging.
- const mode = await getDomainAutonomyMode('messages');
- if (mode !== 'execute') {
- if (mode === 'dry-run') {
- console.log(`📨 [dry-run] Messages auto-send would forward notification: ${notification.type} — "${notification.title}"`);
- }
- return;
- }
-
- // Daily messages budget (#711, mirrors telegram.js): once today's auto-send
- // count reaches the cap, suppress further forwarding for the rest of the day.
- const budget = await getDomainBudgetStatus('messages');
- if (!budget.withinBudget) {
- console.log(`📨 Messages auto-send daily ${budget.exceeded} budget reached — suppressing forward: ${notification.type} — "${notification.title}"`);
- return;
- }
-
- const emoji = NOTIFICATION_EMOJI[notification.type] || '🔔';
- const priorityEmoji = PRIORITY_EMOJI[notification.priority] || '';
- const lines = [`${emoji} <b>${escapeHtml(notification.title)}</b>`];
- if (notification.description) lines.push(escapeHtml(notification.description));
- if (notification.priority) lines.push(`Priority: ${priorityEmoji} ${notification.priority}`);
-
- const startTime = Date.now();
- await sendMessage(lines.join('\n'));
- // Count the forward (and its wall-clock) against the messages daily budget
- // (#711) so both the actions and minutes caps are enforced for this domain.
- await recordDomainUsage('messages', { actions: 1, ms: Date.now() - startTime })
- .catch(err => console.error(`❌ Failed to record messages budget usage: ${err.message}`));
-}
+// Forward a notification through the shared pipeline. An arrow (not a bound
+// reference) so the CURRENT cachedForwardTypes is read on every event.
+const forwardNotification = (notification) =>
+ forwardToTelegram(notification, { cachedForwardTypes, sendMessage });
/**
* Subscribe to notification events
diff --git a/server/services/telegramBridge.test.js b/server/services/telegramBridge.test.js
index 7d794290d1..8450685ccf 100644
--- a/server/services/telegramBridge.test.js
+++ b/server/services/telegramBridge.test.js
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { homedir } from 'os';
+import { TELEGRAM_MAX_RAW_CHARS } from '../lib/telegramMessage.js';
import { join } from 'path';
const ENV_FILE = join(homedir(), '.claude', 'channels', 'telegram', '.env');
@@ -29,6 +30,15 @@ vi.mock('./cosState.js', () => ({
getDomainAutonomyMode: vi.fn(async () => mockMessagesMode)
}));
+// The shared forward pipeline (services/telegramForward.js) resolves the pending
+// memory for a MEMORY_APPROVAL notification. Mocked so the bridge suite never
+// touches the real memory backend (Postgres) — `mockApprovalMemory` is what
+// peekMemory returns.
+let mockApprovalMemory = null;
+vi.mock('./memoryBackend.js', () => ({
+ peekMemory: vi.fn(async () => mockApprovalMemory)
+}));
+
// The bridge also reads the messages daily budget; keep it always-within-budget
// here (the budget math itself is covered by domainBudgets/domainUsage tests) so
// these gate tests stay focused on the autonomy mode.
@@ -114,6 +124,7 @@ describe('telegramBridge service', () => {
updateCachedForwardTypes(null);
mockMessagesMode = 'execute';
mockMessagesWithinBudget = true;
+ mockApprovalMemory = null;
vi.useRealTimers();
vi.restoreAllMocks();
vi.unstubAllGlobals();
@@ -337,6 +348,61 @@ describe('telegramBridge service', () => {
}
});
+ // #5688 — the bridge was a copy-paste of the direct bot and had silently
+ // dropped the approval keyboard and the length cap. Both now come from the
+ // one shared pipeline, so these pin the parity from the bridge side.
+ it('attaches the memory approve/reject keyboard to a MEMORY_APPROVAL forward (#5688)', async () => {
+ mockApprovalMemory = { summary: 'Remember the example project deadline' };
+ seedCredentials();
+ const fetchSpy = mockTelegramFetch();
+ vi.stubGlobal('fetch', fetchSpy);
+ await init();
+ fetchSpy.mockClear();
+
+ notificationEvents.emit('added', {
+ type: NOTIFICATION_TYPES.MEMORY_APPROVAL,
+ title: 'Approve memory?',
+ description: 'ignored once the memory resolves',
+ priority: PRIORITY_LEVELS.MEDIUM,
+ metadata: { memoryId: 'mem-1' }
+ });
+ await flush();
+
+ const sendCall = fetchSpy.mock.calls.find(([url]) => url.endsWith('/sendMessage'));
+ expect(sendCall, 'a memory approval must still be forwarded').toBeDefined();
+ const body = JSON.parse(sendCall[1].body);
+ expect(body.text).toContain('Remember the example project deadline');
+ // A pre-serialized string would reach Telegram as a literal string, so the
+ // keyboard must survive as a real object through the HTTP body.
+ expect(body.reply_markup.inline_keyboard[0]).toEqual([
+ { text: '✅ Approve', callback_data: 'mem_approve:mem-1' },
+ { text: '❌ Reject', callback_data: 'mem_reject:mem-1' }
+ ]);
+ });
+
+ it('truncates a body past the raw cap before escaping it (#5688)', async () => {
+ // '&' sits exactly on the cut: escaping first would leave a split '&am'.
+ mockApprovalMemory = { content: `${'a'.repeat(TELEGRAM_MAX_RAW_CHARS - 1)}&${'b'.repeat(200)}` };
+ seedCredentials();
+ const fetchSpy = mockTelegramFetch();
+ vi.stubGlobal('fetch', fetchSpy);
+ await init();
+ fetchSpy.mockClear();
+
+ notificationEvents.emit('added', {
+ type: NOTIFICATION_TYPES.MEMORY_APPROVAL,
+ title: 'Long one',
+ priority: PRIORITY_LEVELS.LOW,
+ metadata: { memoryId: 'mem-2' }
+ });
+ await flush();
+
+ const sendCall = fetchSpy.mock.calls.find(([url]) => url.endsWith('/sendMessage'));
+ const bodyLine = JSON.parse(sendCall[1].body).text.split('\n')[1];
+ expect(bodyLine.endsWith('&amp;…')).toBe(true);
+ expect(bodyLine).not.toContain('b');
+ });
+
it('suppresses forwarding when the messages daily budget is exhausted (#711)', async () => {
mockMessagesWithinBudget = false; // over budget while mode stays execute
seedCredentials();
diff --git a/server/services/telegramForward.js b/server/services/telegramForward.js
new file mode 100644
index 0000000000..b92c1e697f
--- /dev/null
+++ b/server/services/telegramForward.js
@@ -0,0 +1,92 @@
+/**
+ * The one notification-forward pipeline shared by both Telegram transports.
+ *
+ * `telegram.js` (the direct polling bot) and `telegramBridge.js` (the
+ * MCP-plugin HTTP bridge) are selected by `settings.telegram.method` and run the
+ * identical chain: forward-type filter → per-domain autonomy gate → daily
+ * messages budget → message assembly → send → usage accounting. They used to
+ * carry a copy each, and the copies drifted — the bridge silently lost the
+ * memory-approval keyboard and the length cap (#5688). The only per-transport
+ * piece is the `sendMessage` implementation, which the caller injects.
+ *
+ * Lives in `services/` rather than `lib/` because it reads domain autonomy and
+ * budget state and resolves the pending memory; the pure message assembly is in
+ * `lib/telegramMessage.js`.
+ */
+
+import { getDomainAutonomyMode } from './cosState.js';
+import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';
+import { peekMemory } from './memoryBackend.js';
+import { buildNotificationMessage, isMemoryApprovalNotification } from '../lib/telegramMessage.js';
+
+const DOMAIN = 'messages';
+
+/**
+ * Whether a notification may be forwarded to Telegram.
+ *
+ * The cached forward-type filter runs FIRST so a filtered-out notification skips
+ * the state reads entirely, and so `dry-run` only reports what `execute` would
+ * actually have sent.
+ *
+ * @param {object} notification - the notification record
+ * @param {string[]|null} cachedForwardTypes - configured whitelist; null/empty means "all"
+ * @returns {Promise<boolean>}
+ */
+async function shouldForward(notification, cachedForwardTypes) {
+ if (Array.isArray(cachedForwardTypes) && cachedForwardTypes.length > 0
+ && !cachedForwardTypes.includes(notification.type)) {
+ return false;
+ }
+
+ // Per-domain autonomy gate: `off` suppresses outbound forwarding; `dry-run`
+ // logs what would have been sent without actually messaging the channel.
+ const mode = await getDomainAutonomyMode(DOMAIN);
+ if (mode !== 'execute') {
+ if (mode === 'dry-run') {
+ console.log(`📨 [dry-run] Messages auto-send would forward notification: ${notification.type} — "${notification.title}"`);
+ }
+ return false;
+ }
+
+ // Daily messages budget (#711): once today's auto-send count reaches the cap,
+ // suppress further forwarding for the rest of the day (acts like `off`).
+ const budget = await getDomainBudgetStatus(DOMAIN);
+ if (!budget.withinBudget) {
+ console.log(`📨 Messages auto-send daily ${budget.exceeded} budget reached — suppressing forward: ${notification.type} — "${notification.title}"`);
+ return false;
+ }
+
+ return true;
+}
+
+/**
+ * Gate, build and send one notification through the given transport.
+ *
+ * @param {object} notification - the notification record
+ * @param {object} deps
+ * @param {string[]|null} deps.cachedForwardTypes - the transport's cached whitelist,
+ * read at call time so a `updateCachedForwardTypes` between events takes effect
+ * @param {(text: string, options: object) => Promise<any>} deps.sendMessage -
+ * the transport's own sender; it must forward `options` (`parse_mode`,
+ * `reply_markup`) to the Telegram API call
+ */
+export async function forwardNotification(notification, { cachedForwardTypes, sendMessage }) {
+ if (!await shouldForward(notification, cachedForwardTypes)) return;
+
+ // The approval body is the one piece of the message that needs I/O, so it is
+ // resolved here and handed to the pure builder.
+ const approvalBody = isMemoryApprovalNotification(notification)
+ ? await peekMemory(notification.metadata.memoryId)
+ .then(memory => memory?.summary || memory?.content || null)
+ .catch(() => null)
+ : null;
+
+ const { text, options } = buildNotificationMessage(notification, { approvalBody });
+
+ // Count the forward (and its wall-clock) against the messages daily budget
+ // (#711) so both the actions and minutes caps are enforced for this domain.
+ const startTime = Date.now();
+ await sendMessage(text, options);
+ await recordDomainUsage(DOMAIN, { actions: 1, ms: Date.now() - startTime })
+ .catch(err => console.error(`❌ Failed to record messages budget usage: ${err.message}`));
+}