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
test: cover telegramClient, telegram service, and errorHandler asyncHandler (#2550)
Adam Eivy45855d3187b9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 380b4358ae..6d137a5755 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -7,6 +7,7 @@## Changed+- **[issue-2550] Add direct unit tests for `telegramClient`, the telegram service, and `errorHandler.asyncHandler`.** Three previously under-covered modules gain colocated `*.test.js` suites, all driven with an injected/mock `fetch` (no network): `server/lib/telegramClient.test.js` now covers the poll loop (getUpdates dispatch to matching/non-matching `onText` + `message`/`callback_query` listeners, offset advance, `stopPolling` abort, and non-ok retry via fake timers) and the `apiCall` methods (`getMe`/`sendMessage` happy path, `reply_markup` string→object parse, non-ok throw); a new `server/services/telegram.test.js` exercises the token-bucket rate limiter (30-message cap then `Rate limit exceeded`) and unauthorized-chat rejection (message/command/callback_query paths) through `init()` with all deps mocked; and `server/lib/errorHandler.test.js` adds `asyncHandler` coverage (thrown ServerError → status+body+emit, plain Error → 500 normalization, success no-op, and the no-io path). Test-only change — no runtime behavior change.- **[issue-2530] Decompose `cos.js` `dequeueNextTask` and split `cosAgents.js` into focused modules.** The ~370-line `dequeueNextTask` scheduler is now a thin orchestrator that threads a shared `ctx` through five `spawnDequeuePriorityN(ctx)` tier helpers (mirroring `evaluateTasks`), with the pure per-cycle capacity tracker (`createDequeueCapacity`) and mission/idle tier-eligibility predicates extracted to a new `server/services/cosDequeue.js` — so the scheduler and its unit tests exercise the *same* guards instead of a local replica. The ~1090-line `cosAgents.js` is split into focused siblings — `cosAgentIndex.js` (date-bucket index / migration / prune / archive layout), `cosAgentLifecycle.js` (register / complete / output / terminate / pause / kill / BTW / zombie cleanup), `cosAgentFeedback.js` (feedback capture + classifier), `cosAgentArchive.js` (state-eviction sweeps) — with `cosAgents.js` kept as a thin barrel so every existing import path is unchanged. Pure mechanical refactor: no behavior change.- **[issue-2533] Thin the apps-list route and split the imageGen setup routes into their own module.** The `GET /api/apps` handler's ~80 lines of inline PM2 enrichment (one read per `pm2Home`, absent-vs-empty status classification, ecosystem-config process backfill, port derivation) moved into a new `server/services/appListEnrichment.js` (`enrichAppsWithPm2Status(apps)`), so the route just fetches the raw records and responds; the pure port/status helpers (`deriveUiPort`/`deriveAppPorts`/`computeOverallStatus`) live there too and are re-exported from `routes/apps/shared.js` so the detail/lifecycle routes keep one shared implementation. The `/api/image-gen/setup/*` handlers (python probe/venv bootstrap, FLUX.2 install/status, HuggingFace-token store, pip installer) split out of the large `routes/imageGen.js` render router into `routes/imageGenSetup.js`, with the setup-check cache and pip allowlist relocated to `services/imageGen/setup.js`. Pure mechanical refactor — no behavior change.- **[issue-2531] Split the pipeline `issues.js` and `visualStages.js` monoliths along CRUD/stage/sync seams.** The ~1470-line `server/services/pipeline/issues.js` is now a thin barrel over `issuesShared.js` (store facade + per-series write queue + record sanitizers + `renumberInline`), `issueCrud.js` (create/read/list/update/delete + numbering/reassign), `issueStages.js` (per-stage merge/history/restore), and `issueSync.js` (peer-sync LWW merge + tombstone GC). The ~1760-line `visualStages.js` is now a thin barrel over `visualStageHelpers.js` (shared style/prompt composers + image-gen enqueue plumbing), `covers.js` (comic + volume front/back covers), `comicPages.js` (comic page renders + panel prompt refine), and `storyboards.js` (scene/shot renders + scene refine). Pure mechanical refactor — no behavior change; the single-tail-per-series write serialization (`queueSeriesIssuesWrite`) and the store's `queueTypeIndexWrite` merge snapshot are preserved, and every existing `from './issues.js'` / `from './visualStages.js'` import path still resolves through the barrels.diff --git a/server/lib/errorHandler.test.js b/server/lib/errorHandler.test.jsindex 2fa2d12a75..5131025ff2 100644--- a/server/lib/errorHandler.test.js+++ b/server/lib/errorHandler.test.js@@ -1,12 +1,27 @@-import { describe, it, expect, vi } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import {ServerError,normalizeError,emitErrorEvent,errorEvents,- errorMiddleware+ errorMiddleware,+ asyncHandler} from './errorHandler.js';+// Build a fake Express req/res pair. `res.status()` and `res.json()` are+// chainable (they return `res`) to mirror Express, and `req.app.get('io')`+// resolves to whatever io stub the test supplies (or null for the no-io path).+function makeReqRes(io) {+ const res = { status: vi.fn(() => res), json: vi.fn(() => res) };+ const req = { method: 'GET', originalUrl: '/api/thing', app: { get: vi.fn(() => io) } };+ return { req, res };+}++// asyncHandler wires the rejection handling onto a `.catch()` microtask and the+// returned middleware does not itself return that promise — so flush the+// microtask queue before asserting the response/emit happened.+const flushMicrotasks = () => new Promise((r) => setImmediate(r));+describe('errorHandler.js', () => {describe('ServerError', () => {it('should create error with default options', () => {@@ -231,4 +246,97 @@ describe('errorHandler.js', () => {errorEvents.off('error', listener);});});++ describe('asyncHandler', () => {+ // `errorEvents` is a Node EventEmitter: emitting 'error' with zero listeners+ // re-throws the argument (the classic footgun). Production always has+ // subscribers (autoFixer / socket.js); keep a noop attached so emitErrorEvent+ // doesn't throw out of asyncHandler's catch during these tests.+ let noopErrorListener;+ beforeEach(() => {+ noopErrorListener = () => {};+ errorEvents.on('error', noopErrorListener);+ });+ afterEach(() => {+ errorEvents.off('error', noopErrorListener);+ });++ it('catches a thrown ServerError, emits, and responds with status + body', async () => {+ const io = { emit: vi.fn() };+ const { req, res } = makeReqRes(io);+ const events = [];+ const listener = (err, ctx) => events.push({ err, ctx });+ errorEvents.on('error', listener);+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ const handler = asyncHandler(async () => {+ throw new ServerError('nope', { status: 403, code: 'FORBIDDEN', context: { detail: 'x' } });+ });+ await handler(req, res, vi.fn());+ await flushMicrotasks();++ errorEvents.off('error', listener);+ errorSpy.mockRestore();++ expect(res.status).toHaveBeenCalledWith(403);+ const body = res.json.mock.calls[0][0];+ expect(body.error).toBe('nope');+ expect(body.code).toBe('FORBIDDEN');+ expect(body.timestamp).toBeDefined();+ expect(body.context).toEqual({ detail: 'x' });+ // Both channels fire: the process-local errorEvents emitter and the io broadcast.+ expect(events).toHaveLength(1);+ expect(io.emit).toHaveBeenCalledWith(+ 'error:occurred',+ expect.objectContaining({ code: 'FORBIDDEN', status: 403, message: 'nope' })+ );+ });++ it('normalizes a plain thrown Error to a 500 INTERNAL_ERROR response', async () => {+ const io = { emit: vi.fn() };+ const { req, res } = makeReqRes(io);+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ const handler = asyncHandler(async () => {+ throw new Error('kaboom');+ });+ await handler(req, res, vi.fn());+ await flushMicrotasks();++ errorSpy.mockRestore();++ expect(res.status).toHaveBeenCalledWith(500);+ const body = res.json.mock.calls[0][0];+ expect(body.code).toBe('INTERNAL_ERROR');+ expect(body.error).toBe('kaboom');+ });++ it('does not touch res when the wrapped handler resolves successfully', async () => {+ const { req, res } = makeReqRes({ emit: vi.fn() });++ const handler = asyncHandler(async () => 'ok');+ await handler(req, res, vi.fn());+ await flushMicrotasks();++ expect(res.status).not.toHaveBeenCalled();+ expect(res.json).not.toHaveBeenCalled();+ });++ it('still responds when no io is registered on the app', async () => {+ const { req, res } = makeReqRes(null);+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ const handler = asyncHandler(async () => {+ throw new ServerError('missing', { status: 404 });+ });+ await handler(req, res, vi.fn());+ await flushMicrotasks();++ errorSpy.mockRestore();++ expect(res.status).toHaveBeenCalledWith(404);+ // status→code derivation still runs even without an io channel.+ expect(res.json.mock.calls[0][0].code).toBe('NOT_FOUND');+ });+ });});diff --git a/server/lib/telegramClient.test.js b/server/lib/telegramClient.test.jsindex 16dce7d7ce..9bc37481c9 100644--- a/server/lib/telegramClient.test.js+++ b/server/lib/telegramClient.test.js@@ -98,3 +98,211 @@ describe('createTelegramBot — async handler rejections', () => {expect(errorSpy).toHaveBeenCalled();});});++describe('createTelegramBot — poll loop dispatch', () => {+ let originalFetch;++ beforeEach(() => {+ originalFetch = global.fetch;+ });++ afterEach(() => {+ global.fetch = originalFetch;+ });++ it('dispatches a getUpdates message to matching onText and message listeners', async () => {+ global.fetch = makeFetchMock();+ const bot = createTelegramBot('test-token', { polling: true });++ let textMsg = null;+ let textMatch = null;+ let msgEvent = null;+ bot.onText(/\/(\w+)/, (msg, match) => { textMsg = msg; textMatch = match; });+ bot.on('message', (msg) => { msgEvent = msg; });++ await waitFor(() => textMsg && msgEvent);+ await bot.stopPolling();++ expect(textMsg.text).toBe('/boom');+ // The regex capture group is passed through as match[1].+ expect(textMatch[1]).toBe('boom');+ expect(msgEvent.chat.id).toBe(42);+ });++ it('does not dispatch onText when the regex does not match', async () => {+ global.fetch = makeFetchMock();+ const bot = createTelegramBot('test-token', { polling: true });++ let matched = false;+ let sawMessage = false;+ bot.onText(/\/nope/, () => { matched = true; });+ bot.on('message', () => { sawMessage = true; });++ await waitFor(() => sawMessage);+ await bot.stopPolling();++ expect(sawMessage).toBe(true);+ expect(matched).toBe(false);+ });++ it('advances the offset past a consumed update on the next getUpdates', async () => {+ const bodies = [];+ let calls = 0;+ global.fetch = vi.fn((_url, opts = {}) => {+ calls++;+ if (opts.body) bodies.push(JSON.parse(opts.body));+ 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' }));+ });+ });+ });+ const bot = createTelegramBot('test-token', { polling: true });++ await waitFor(() => calls >= 2);+ await bot.stopPolling();++ // First poll starts at offset 0; after consuming update_id 1 the next poll+ // must request offset 2 so the same update is never re-delivered.+ expect(bodies[0].offset).toBe(0);+ expect(bodies[1].offset).toBe(2);+ });++ it('emits callback_query updates to callback_query listeners', async () => {+ const callbackUpdate = {+ ok: true,+ result: [{ update_id: 5, callback_query: { id: 'cb-1', data: 'do:thing' } }]+ };+ let calls = 0;+ global.fetch = vi.fn((_url, opts = {}) => {+ calls++;+ if (calls === 1) return Promise.resolve(jsonRes(callbackUpdate));+ return new Promise((_resolve, reject) => {+ opts.signal?.addEventListener('abort', () => {+ reject(Object.assign(new Error('aborted'), { name: 'AbortError' }));+ });+ });+ });+ const bot = createTelegramBot('test-token', { polling: true });++ let query = null;+ bot.on('callback_query', (q) => { query = q; });++ await waitFor(() => query);+ await bot.stopPolling();++ expect(query.id).toBe('cb-1');+ });++ it('stopPolling aborts the in-flight long-poll request', async () => {+ let capturedSignal = null;+ global.fetch = vi.fn((_url, opts = {}) => {+ capturedSignal = opts.signal;+ return new Promise((_resolve, reject) => {+ opts.signal?.addEventListener('abort', () => {+ reject(Object.assign(new Error('aborted'), { name: 'AbortError' }));+ });+ });+ });+ const bot = createTelegramBot('test-token', { polling: true });++ await waitFor(() => capturedSignal !== null);+ expect(capturedSignal.aborted).toBe(false);++ await bot.stopPolling();+ expect(capturedSignal.aborted).toBe(true);+ });++ it('retries after a non-ok getUpdates response instead of dispatching', async () => {+ // RETRY_DELAY_API_ERROR_MS in telegramClient.js is 5000ms; drive it with+ // fake timers so the retry is instant rather than a real 5s wait.+ vi.useFakeTimers();+ let calls = 0;+ global.fetch = vi.fn((_url, opts = {}) => {+ calls++;+ if (calls === 1) return Promise.resolve(jsonRes({ ok: false, description: 'flood wait' }));+ if (calls === 2) return Promise.resolve(jsonRes(messageUpdate));+ return new Promise((_resolve, reject) => {+ opts.signal?.addEventListener('abort', () => {+ reject(Object.assign(new Error('aborted'), { name: 'AbortError' }));+ });+ });+ });+ const bot = createTelegramBot('test-token', { polling: true });++ let matched = null;+ bot.onText(/\/boom/, (_msg, match) => { matched = match; });++ // Flush the first (non-ok) fetch + parse, then advance past the retry delay+ // so the loop issues its second getUpdates, which delivers the message.+ await vi.advanceTimersByTimeAsync(5000);+ await vi.advanceTimersByTimeAsync(20);++ expect(calls).toBeGreaterThanOrEqual(2);+ // A non-ok response must not have dispatched anything on the first pass.+ expect(matched?.[0]).toBe('/boom');++ await bot.stopPolling();+ vi.useRealTimers();+ });+});++describe('createTelegramBot — apiCall methods', () => {+ let originalFetch;++ beforeEach(() => {+ originalFetch = global.fetch;+ });++ afterEach(() => {+ global.fetch = originalFetch;+ });++ it('getMe posts to /getMe and returns the result on an ok response', async () => {+ const fetchMock = vi.fn(async (url) => {+ expect(url).toContain('/getMe');+ return jsonRes({ ok: true, result: { username: 'example_bot' } });+ });+ global.fetch = fetchMock;+ const bot = createTelegramBot('tok');++ const me = await bot.getMe();+ expect(me.username).toBe('example_bot');+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('sendMessage posts chat_id + text and returns the result', async () => {+ const fetchMock = vi.fn(async (url, opts) => {+ expect(url).toContain('/sendMessage');+ const body = JSON.parse(opts.body);+ expect(body.chat_id).toBe(42);+ expect(body.text).toBe('hi there');+ return jsonRes({ ok: true, result: { message_id: 7 } });+ });+ global.fetch = fetchMock;+ const bot = createTelegramBot('tok');++ const res = await bot.sendMessage(42, 'hi there');+ expect(res.message_id).toBe(7);+ });++ it('parses a string reply_markup into an object before sending', async () => {+ let sentBody = null;+ global.fetch = vi.fn(async (_url, opts) => {+ sentBody = JSON.parse(opts.body);+ return jsonRes({ ok: true, result: {} });+ });+ const bot = createTelegramBot('tok');++ await bot.sendMessage(42, 'hi', { reply_markup: JSON.stringify({ inline_keyboard: [] }) });+ expect(sentBody.reply_markup).toEqual({ inline_keyboard: [] });+ });++ it('throws with the Telegram description when the response is not ok', async () => {+ global.fetch = vi.fn(async () => jsonRes({ ok: false, description: 'Unauthorized: invalid token' }));+ const bot = createTelegramBot('tok');++ await expect(bot.getMe()).rejects.toThrow('Unauthorized: invalid token');+ });+});diff --git a/server/services/telegram.test.js b/server/services/telegram.test.jsnew file mode 100644index 0000000000..5745374077--- /dev/null+++ b/server/services/telegram.test.js@@ -0,0 +1,219 @@+/**+ * Tests for the settings-backed Telegram bot service (server/services/telegram.js).+ *+ * The rate limiter (token bucket) and the "unauthorized chat" rejection are the+ * two behaviors called out in the issue. Neither helper is exported, so they are+ * exercised through the public surface: `init()` wires a fake bot (created via a+ * mocked `createTelegramBot`) and registers the message/callback handlers, and+ * `sendMessage()` drives the token bucket. All external modules are mocked so no+ * network, disk, or real timers are touched.+ *+ * Each test re-imports the module via `loadTelegram()` (resetModules) so the+ * module-level token bucket and `authorizedChatId` start fresh.+ */++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++// 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+// the hoisted `vi.mock` factory below.+const h = vi.hoisted(() => ({+ textHandlers: [],+ eventHandlers: {},+ sendMessage: null,+ answerCallbackQuery: null,+ editMessageText: null,+ getMe: null,+ stopPolling: null,+}));++vi.mock('../lib/telegramClient.js', () => ({+ createTelegramBot: vi.fn(() => ({+ getMe: (...a) => h.getMe(...a),+ sendMessage: (...a) => h.sendMessage(...a),+ answerCallbackQuery: (...a) => h.answerCallbackQuery(...a),+ editMessageText: (...a) => h.editMessageText(...a),+ onText: (regex, fn) => h.textHandlers.push({ regex, fn }),+ on: (event, fn) => { (h.eventHandlers[event] ||= []).push(fn); },+ stopPolling: (...a) => h.stopPolling(...a),+ })),+}));++// Settings supply the token + authorized chat id init() caches.+vi.mock('./settings.js', () => ({+ getSettings: vi.fn(async () => ({+ secrets: { telegram: { token: 'test-token' } },+ telegram: { chatId: '42', forwardTypes: null },+ backup: { enabled: false },+ })),+}));++// A minimal EventEmitter stand-in so init()'s notification subscription works.+const notifEmitter = vi.hoisted(() => {+ const listeners = {};+ return {+ on(event, fn) { (listeners[event] ||= []).push(fn); },+ removeListener(event, fn) {+ listeners[event] = (listeners[event] || []).filter((f) => f !== fn);+ },+ emit(event, ...args) { (listeners[event] || []).forEach((fn) => fn(...args)); },+ };+});++vi.mock('./notifications.js', () => ({+ notificationEvents: notifEmitter,+ NOTIFICATION_TYPES: {+ MEMORY_APPROVAL: 'memory_approval',+ TASK_APPROVAL: 'task_approval',+ CODE_REVIEW: 'code_review',+ HEALTH_ISSUE: 'health_issue',+ BRIEFING_READY: 'briefing_ready',+ AUTOBIOGRAPHY_PROMPT: 'autobiography_prompt',+ PLAN_QUESTION: 'plan_question',+ DAILY_POST_REMINDER: 'daily_post_reminder',+ },+ getNotifications: vi.fn(async () => []),+}));++vi.mock('./cosState.js', () => ({+ getDomainAutonomyMode: vi.fn(async () => 'execute'),+}));++vi.mock('./domainUsage.js', () => ({+ getDomainBudgetStatus: vi.fn(async () => ({ withinBudget: true, exceeded: null })),+ recordDomainUsage: vi.fn(async () => {}),+}));++vi.mock('./memoryBackend.js', () => ({+ approveMemory: vi.fn(async () => ({ success: true })),+ rejectMemory: vi.fn(async () => ({ success: true })),+ peekMemory: vi.fn(async () => null),+}));++vi.mock('../lib/fileUtils.js', () => ({+ ensureDir: vi.fn(async () => {}),+ PATHS: { data: '/mock/data' },+ readJSONFile: vi.fn(async (_path, def) => def),+ formatDuration: vi.fn(() => '1m'),+ atomicWrite: vi.fn(async () => {}),+}));++vi.mock('./subAgentSpawner.js', () => ({ getActiveAgents: vi.fn(() => []) }));+vi.mock('./identity.js', () => ({ getGoals: vi.fn(async () => ({ goals: [] })) }));+vi.mock('../lib/uuid.js', () => ({ v4: vi.fn(() => 'test-uuid') }));++async function loadTelegram() {+ vi.resetModules();+ return import('./telegram.js');+}++describe('telegram service', () => {+ let logSpy;+ let errorSpy;++ beforeEach(() => {+ h.textHandlers = [];+ h.eventHandlers = {};+ h.sendMessage = vi.fn(async () => ({ message_id: 1 }));+ h.answerCallbackQuery = vi.fn(async () => {});+ h.editMessageText = vi.fn(async () => {});+ h.getMe = vi.fn(async () => ({ username: 'example_bot' }));+ h.stopPolling = vi.fn(async () => {});+ logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ });++ afterEach(() => {+ logSpy.mockRestore();+ errorSpy.mockRestore();+ });++ describe('rate limiting (token bucket)', () => {+ it('sends up to the bucket max then rejects further messages until refill', async () => {+ const telegram = await loadTelegram();+ await telegram.init(false);++ const results = [];+ // BUCKET_MAX is 30 in telegram.js; the 31st send must be rate limited.+ for (let i = 0; i < 31; i++) {+ results.push(await telegram.sendMessage(`msg ${i}`));+ }++ await telegram.cleanup();++ const successes = results.filter((r) => r.success).length;+ expect(successes).toBe(30);+ expect(results[30]).toEqual({ success: false, error: 'Rate limit exceeded' });+ // The underlying bot.sendMessage is only called for the 30 that passed the gate.+ expect(h.sendMessage).toHaveBeenCalledTimes(30);+ });++ it('returns an error without calling the bot when no chatId is configured', async () => {+ const telegram = await loadTelegram();+ // Never init(): authorizedChatId stays null.+ const res = await telegram.sendMessage('hello');+ expect(res.success).toBe(false);+ expect(h.sendMessage).not.toHaveBeenCalled();+ });+ });++ describe('unauthorized chat rejection', () => {+ it('rejects a message from a non-authorized chat id and notifies that chat', async () => {+ const telegram = await loadTelegram();+ await telegram.init(false);++ const messageHandler = h.eventHandlers.message[0];+ expect(messageHandler).toBeTypeOf('function');++ // A message from chat id 999 (authorized is 42) must be rejected.+ await messageHandler({ chat: { id: 999 }, text: 'let me in' });++ // isAuthorized fires a "not configured for your chat ID" notice to the+ // sender's own chat, not the authorized one.+ expect(h.sendMessage).toHaveBeenCalledWith(+ '999',+ expect.stringContaining('not configured for your chat ID')+ );++ await telegram.cleanup();+ });++ it('does not run command handlers for an unauthorized chat', async () => {+ const telegram = await loadTelegram();+ await telegram.init(false);++ // /status is guarded by isAuthorized; find its handler.+ const statusEntry = h.textHandlers.find((t) => t.regex.source.includes('status'));+ expect(statusEntry).toBeDefined();++ h.sendMessage.mockClear();+ await statusEntry.fn({ chat: { id: 999 }, text: '/status' });++ // The only send is the rejection notice — the status report never runs, so+ // getMe/status content is never sent to the unauthorized chat.+ expect(h.sendMessage).toHaveBeenCalledTimes(1);+ expect(h.sendMessage).toHaveBeenCalledWith(+ '999',+ expect.stringContaining('not configured for your chat ID')+ );++ await telegram.cleanup();+ });++ it('rejects a callback_query from a non-authorized chat with an Unauthorized answer', async () => {+ const telegram = await loadTelegram();+ await telegram.init(false);++ const cbHandler = h.eventHandlers.callback_query[0];+ expect(cbHandler).toBeTypeOf('function');++ await cbHandler({ id: 'cb-1', message: { chat: { id: 999 } }, data: 'mem_approve:abc' });++ expect(h.answerCallbackQuery).toHaveBeenCalledWith('cb-1', { text: 'Unauthorized' });+ // The memory action must not run for an unauthorized chat.+ expect(h.editMessageText).not.toHaveBeenCalled();++ await telegram.cleanup();+ });+ });+});