Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

chore(e2e): remove telegram channel flow tests and mock routes

Steven Enamakelc4b0f5d3d5c6
diff --git a/app/scripts/e2e-run-all-flows.sh b/app/scripts/e2e-run-all-flows.sh
index 2bceb57b17..4e582cd7cd 100755
--- a/app/scripts/e2e-run-all-flows.sh
+++ b/app/scripts/e2e-run-all-flows.sh
@@ -322,9 +322,6 @@ fi
if should_run_suite "providers"; then
echo ""
echo "## Running suite: providers"
- # telegram-flow.spec.ts was renamed to telegram-channel-flow.spec.ts;
- # only the latter exists in the repo today.
- run "test/e2e/specs/telegram-channel-flow.spec.ts" "telegram-channel" "providers"
run "test/e2e/specs/gmail-flow.spec.ts" "gmail" "providers"
run "test/e2e/specs/accounts-provider-modal.spec.ts" "accounts-providers" "providers"
_mini_summary "providers"
diff --git a/app/test/e2e/mock-server.ts b/app/test/e2e/mock-server.ts
index a146374477..89ede2fd80 100644
--- a/app/test/e2e/mock-server.ts
+++ b/app/test/e2e/mock-server.ts
@@ -15,63 +15,3 @@ export {
startMockServer,
stopMockServer,
} from '../../../scripts/mock-api-core.mjs';
-
-// ── Telegram mock helpers ──────────────────────────────────────────────────
-// Convenience wrappers for E2E specs that drive the Telegram channel.
-// These call the admin HTTP endpoints so they work from the WDIO process
-// (which cannot import the mock server module directly when it is running
-// in a separate process).
-
-async function telegramAdminFetch(path, options) {
- // Resolve port lazily so this module can be imported before the server
- // is started. The `getMockServerPort` export above resolves at call time.
- const { getMockServerPort } = await import('../../../scripts/mock-api/index.mjs');
- const port = getMockServerPort();
- if (!port) throw new Error('[mock-server] mock server is not running');
- return fetch(`http://127.0.0.1:${port}${path}`, options);
-}
-
-/**
- * Inject one Telegram Update into the mock server's pending queue.
- * The Telegram provider will receive it on the next `getUpdates` poll.
- *
- * @param update - A Telegram Update object (https://core.telegram.org/bots/api#update)
- */
-export async function injectTelegramUpdate(update) {
- const res = await telegramAdminFetch('/__admin/telegram/inject-update', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(update),
- });
- return res.json();
-}
-
-/**
- * Return all outbound Telegram API calls that the bot has made since the
- * last reset. Useful for asserting the bot's reply text and method.
- */
-export async function getTelegramSentMessages() {
- const res = await telegramAdminFetch('/__admin/telegram/sent');
- const data = await res.json();
- if (!res.ok) {
- throw new Error(
- `[mock-server] /__admin/telegram/sent failed (${res.status}): ${JSON.stringify(data)}`
- );
- }
- if (Array.isArray(data)) return data;
- if (data && Array.isArray((data as { messages?: unknown }).messages)) {
- return (data as { messages: unknown[] }).messages;
- }
- throw new Error(
- `[mock-server] /__admin/telegram/sent returned unexpected payload: ${JSON.stringify(data)}`
- );
-}
-
-/**
- * Clear the Telegram mock state (pending update queue + sent messages log +
- * message_id counter). Does NOT affect other mock state.
- */
-export async function resetTelegramMock() {
- const res = await telegramAdminFetch('/__admin/telegram/reset', { method: 'POST' });
- return res.json();
-}
diff --git a/app/test/e2e/specs/telegram-channel-flow.spec.ts b/app/test/e2e/specs/telegram-channel-flow.spec.ts
deleted file mode 100644
index ce230e05af..0000000000
--- a/app/test/e2e/specs/telegram-channel-flow.spec.ts
+++ /dev/null
@@ -1,733 +0,0 @@
-/**
- * E2E: Telegram channel connect / receive / send / disconnect flows.
- *
- * Drives the `openhuman.channels_*` RPC surface against the mock backend
- * (Telegram Bot API routes wired by WS-A, API-base override wired by WS-B).
- *
- * Scenarios implemented:
- * C.1 channels_list includes telegram with bot_token auth mode
- * C.2 channels_describe for telegram returns capabilities + auth modes + field schemas
- * C.3 Bot-token connect happy path — credentials stored; status shows connected
- * C.4 Bot-token connect failure — telegramGetMeFails=1; channels_test reflects error shape
- * C.5 Inbound text message round-trip — inject update; bot sends reply via mock
- * C.6 Unauthorized user — inject from excluded sender; approval-required reply observed
- * C.7 Group mention-only — without mention (no reply); with mention (reply appears)
- * C.8 Disconnect — channels_disconnect; status shows disconnected
- * C.9 Reconnect after disconnect — second connect; status shows connected again
- * C.10 Remote /status command — inject /status; reply contains Thread: and Provider:
- *
- * Infrastructure notes:
- * - Mock Telegram routes: scripts/mock-api/routes/telegram.mjs (WS-A).
- * - API base override: OPENHUMAN_TELEGRAM_API_BASE env var (WS-B).
- * - The in-process core starts the channel polling loop AFTER the config is
- * written (channels_connect sets restart_required: true). In E2E the core
- * is already running with the bot_token config already applied at startup
- * via OPENHUMAN_WORKSPACE. For scenarios that require the live polling loop
- * (C.5–C.10) we rely on the core restarting the channel listener after the
- * connect call — or we use channels_test to validate the bot token against
- * the mock without waiting for the full poll loop.
- *
- * Scenarios C.5–C.10 are marked with a comment when they depend on the channel
- * runtime actively polling; where the E2E bundle cannot trigger a live listener
- * restart within the test window, we assert at the RPC/mock-request level and
- * document the limitation inline.
- *
- * Pattern: composio-triggers-flow.spec.ts (RPC-driven) +
- * chat-harness-send-stream.spec.ts (mock server setup).
- */
-import { waitForApp } from '../helpers/app-helpers';
-import { callOpenhumanRpc } from '../helpers/core-rpc';
-import { resetApp } from '../helpers/reset-app';
-import {
- assertNoTelegramReply,
- buildTelegramUpdate,
- connectTelegramBot,
- disconnectTelegramBot,
- getTelegramChannelStatus,
- injectTelegramUpdate,
- waitForTelegramReply,
-} from '../helpers/telegram';
-import {
- clearRequestLog,
- getRequestLog,
- resetMockBehavior,
- resetTelegramMock,
- setMockBehavior,
- startMockServer,
- stopMockServer,
-} from '../mock-server';
-
-// ---------------------------------------------------------------------------
-// Constants
-// ---------------------------------------------------------------------------
-
-const LOG_PREFIX = '[TelegramChannel]';
-const USER_ID = 'e2e-telegram-channel-flow';
-
-/** Bot token used for the happy-path scenarios. */
-const BOT_TOKEN = 'e2e-bot-token-12345:AAFakeTokenForE2E';
-/** Second bot token used for the reconnect scenario (C.9). */
-const BOT_TOKEN_2 = 'e2e-bot-token-99999:AASecondFakeTokenForE2E';
-
-/** Chat IDs for test scenarios. */
-const CHAT_ID_ALICE = 100_001;
-const CHAT_ID_BOB = 100_002;
-const CHAT_ID_GROUP = -100_003;
-
-/** Sender IDs and usernames. */
-const ALICE_ID = 200_001;
-const ALICE_USERNAME = 'alice_e2e';
-
-const BOB_ID = 200_002;
-const BOB_USERNAME = 'bob_e2e';
-
-/** Bot username configured in the mock. */
-const BOT_USERNAME = 'e2e_test_bot';
-// Listener startup is optional in this harness because channels_connect can
-// require a core restart. Probe briefly, then take the documented RPC-only path.
-const LISTENER_PROBE_TIMEOUT_MS = 8_000;
-
-// ---------------------------------------------------------------------------
-// Suite
-// ---------------------------------------------------------------------------
-
-describe('Telegram channel — connect / receive / send / disconnect', () => {
- // ──────────────────────────────────────────────────────────────────────────
- // Suite setup
- // ──────────────────────────────────────────────────────────────────────────
-
- before(async function beforeSuite() {
- this.timeout(120_000);
- console.log(`${LOG_PREFIX} before: starting mock server and resetting app`);
-
- await startMockServer();
-
- // Configure mock Telegram behavior before connecting.
- // telegramPollDelayMs=0 keeps getUpdates non-blocking for speed.
- // telegramBotUsername sets the username the mock getMe returns.
- setMockBehavior('telegramBotUsername', BOT_USERNAME);
- setMockBehavior('telegramPollDelayMs', '0');
-
- await waitForApp();
- await resetApp(USER_ID);
-
- // Reset telegram mock state so prior runs don't pollute this suite.
- await resetTelegramMock();
- clearRequestLog();
-
- console.log(`${LOG_PREFIX} before: suite ready`);
- });
-
- // ──────────────────────────────────────────────────────────────────────────
- // Per-test setup
- // ──────────────────────────────────────────────────────────────────────────
-
- beforeEach(async function () {
- // Clear request log and telegram state between tests so assertions are
- // isolated. Restore bot-username behavior in case a prior test changed it.
- clearRequestLog();
- resetMockBehavior();
- setMockBehavior('telegramBotUsername', BOT_USERNAME);
- setMockBehavior('telegramPollDelayMs', '0');
- await resetTelegramMock();
- console.log(`${LOG_PREFIX} beforeEach: cleared state`);
- });
-
- // ──────────────────────────────────────────────────────────────────────────
- // Suite teardown
- // ──────────────────────────────────────────────────────────────────────────
-
- after(async function afterSuite() {
- // Best-effort disconnect so config.toml is clean for subsequent suites.
- try {
- await disconnectTelegramBot();
- console.log(`${LOG_PREFIX} after: disconnected telegram (cleanup)`);
- } catch (err) {
- console.warn(`${LOG_PREFIX} after: disconnect best-effort failed (non-fatal): ${err}`);
- }
-
- await stopMockServer();
- console.log(`${LOG_PREFIX} after: suite done`);
- });
-
- // ──────────────────────────────────────────────────────────────────────────
- // C.1 — channels_list includes telegram with bot_token auth mode
- // ──────────────────────────────────────────────────────────────────────────
-
- it('C.1 channels_list includes telegram with bot_token auth mode', async function () {
- this.timeout(30_000);
- console.log(`${LOG_PREFIX} C.1: calling channels_list`);
-
- const out = await callOpenhumanRpc('openhuman.channels_list', {});
- console.log(`${LOG_PREFIX} C.1: result = ${JSON.stringify(out).slice(0, 500)}`);
-
- expect(out.ok).toBe(true);
-
- // channels_list wraps its result in Outcome — drill one level down.
- const resultRaw = (out.result as Record<string, unknown> | null) ?? {};
- const channels: unknown[] = Array.isArray(resultRaw)
- ? resultRaw
- : Array.isArray((resultRaw as Record<string, unknown>).channels)
- ? ((resultRaw as Record<string, unknown>).channels as unknown[])
- : Array.isArray((resultRaw as Record<string, unknown>).result)
- ? ((resultRaw as Record<string, unknown>).result as unknown[])
- : [];
-
- console.log(`${LOG_PREFIX} C.1: ${channels.length} channel(s) in list`);
- expect(channels.length).toBeGreaterThan(0);
-
- const telegram = channels.find(
- (ch: unknown) => (ch as Record<string, unknown>).id === 'telegram'
- ) as Record<string, unknown> | undefined;
-
- expect(telegram).toBeDefined();
- expect(telegram?.id).toBe('telegram');
-
- // The definition exposes auth_modes (snake_case from serde serialization).
- const authModes: unknown[] = Array.isArray(telegram?.auth_modes)
- ? (telegram?.auth_modes as unknown[])
- : Array.isArray(telegram?.authModes)
- ? (telegram?.authModes as unknown[])
- : [];
-
- console.log(`${LOG_PREFIX} C.1: telegram auth_modes = ${JSON.stringify(authModes)}`);
-
- const hasBotToken = authModes.some(
- (m: unknown) => (m as Record<string, unknown>).mode === 'bot_token' || m === 'bot_token'
- );
- expect(hasBotToken).toBe(true);
- });
-
- // ──────────────────────────────────────────────────────────────────────────
- // C.2 — channels_describe for telegram
- // ──────────────────────────────────────────────────────────────────────────
-
- it('C.2 channels_describe for telegram returns capabilities + auth modes + fields', async function () {
- this.timeout(30_000);
- console.log(`${LOG_PREFIX} C.2: calling channels_describe`);
-
- const out = await callOpenhumanRpc('openhuman.channels_describe', { channel: 'telegram' });
- console.log(`${LOG_PREFIX} C.2: result = ${JSON.stringify(out).slice(0, 800)}`);
-
- expect(out.ok).toBe(true);
-
- const resultRaw = (out.result as Record<string, unknown> | null) ?? {};
- // Drill into definition — it may be at result.result or result directly.
- const def: Record<string, unknown> =
- typeof (resultRaw as Record<string, unknown>).result === 'object' &&
- (resultRaw as Record<string, unknown>).result !== null
- ? ((resultRaw as Record<string, unknown>).result as Record<string, unknown>)
- : typeof (resultRaw as Record<string, unknown>).definition === 'object' &&
- (resultRaw as Record<string, unknown>).definition !== null
- ? ((resultRaw as Record<string, unknown>).definition as Record<string, unknown>)
- : resultRaw;
-
- expect(def.id ?? (def as Record<string, unknown>).channel_id).toBe('telegram');
-
- // Auth modes array must include bot_token.
- const authModes: unknown[] = Array.isArray(def.auth_modes) ? (def.auth_modes as unknown[]) : [];
- const hasBotToken = authModes.some(
- (m: unknown) => (m as Record<string, unknown>).mode === 'bot_token'
- );
- expect(hasBotToken).toBe(true);
-
- // The bot_token spec must define a `bot_token` field.
- const botTokenSpec = authModes.find(
- (m: unknown) => (m as Record<string, unknown>).mode === 'bot_token'
- ) as Record<string, unknown> | undefined;
-
- expect(botTokenSpec).toBeDefined();
- const fields: unknown[] = Array.isArray(botTokenSpec?.fields)
- ? (botTokenSpec?.fields as unknown[])
- : [];
- const hasBotTokenField = fields.some(
- (f: unknown) => (f as Record<string, unknown>).key === 'bot_token'
- );
- expect(hasBotTokenField).toBe(true);
-
- console.log(
- `${LOG_PREFIX} C.2: description validated — auth_modes=${authModes.length}, bot_token field present=${hasBotTokenField}`
- );
- });
-
- // ──────────────────────────────────────────────────────────────────────────
- // C.3 — Bot-token connect happy path
- // ──────────────────────────────────────────────────────────────────────────
-
- it('C.3 bot-token connect happy path — credentials stored; status shows connected', async function () {
- this.timeout(30_000);
- console.log(`${LOG_PREFIX} C.3: connecting with bot token`);
-
- const connectResult = await connectTelegramBot({ botToken: BOT_TOKEN });
- console.log(`${LOG_PREFIX} C.3: connect result = ${JSON.stringify(connectResult)}`);
-
- expect(connectResult.ok).toBe(true);
-
- // The connect call writes TOML config + credentials; the status check
- // reads the credentials store — both must agree the channel is connected.
- expect(connectResult.status).toBe('connected');
- // The channel requires a core restart to start the listener; the RPC
- // advertises this via restart_required.
- expect(connectResult.restartRequired).toBe(true);
-
- // Verify via channels_status that the credential is now present.
- const status = await getTelegramChannelStatus();
- console.log(`${LOG_PREFIX} C.3: status = ${JSON.stringify(status)}`);
-
- expect(status).not.toBeNull();
- expect(status?.connected).toBe(true);
- expect(status?.hasCredentials).toBe(true);
-
- // channels_connect does NOT call getMe (that happens in the polling loop
- // which requires a core restart). We verify the mock received no getMe
- // call from this connect RPC path.
- // NOTE: If the core restarts its channel listener asynchronously (which
- // is implementation-dependent), getMe MAY appear after a delay. We do
- // not assert its absence here to avoid a timing-sensitive assertion.
-
- console.log(`${LOG_PREFIX} C.3: pass — channel connected, status=connected`);
- });
-
- // ──────────────────────────────────────────────────────────────────────────
- // C.4 — Bot-token connect failure (invalid token)
- // ──────────────────────────────────────────────────────────────────────────
-
- it('C.4 bot-token connect with missing token fails with validation error', async function () {
- this.timeout(30_000);
- console.log(`${LOG_PREFIX} C.4: attempting connect without bot_token`);
-
- // The channels_connect RPC validates that bot_token is present and
- // non-empty; missing it produces an error at the RPC layer.
- // (The telegramGetMeFails behavior key affects the live polling getMe
- // call, not the RPC-level credential write. We test the RPC validation
- // here since that is the observable failure mode at the E2E boundary.)
- const out = await callOpenhumanRpc('openhuman.channels_connect', {
- channel: 'telegram',
- authMode: 'bot_token',
- credentials: { bot_token: '' },
- });
-
- console.log(`${LOG_PREFIX} C.4: result = ${JSON.stringify(out).slice(0, 500)}`);
-
- // Either the RPC call returns ok=false OR ok=true with an error status.
- // The Rust layer returns a JSON-RPC error string for "missing required bot_token".
- const isError =
- !out.ok ||
- (typeof out.error === 'string' && out.error.length > 0) ||
- (typeof (out.result as Record<string, unknown>)?.status === 'string' &&
- (out.result as Record<string, unknown>).status === 'error');
-
- expect(isError).toBe(true);
-
- // The important assertion is that the RPC rejected the empty token (checked
- // above). A failed connect attempt does not clear the existing connection
- // established by C.3 — assert it positively.
- const status = await getTelegramChannelStatus();
- expect(status?.connected).toBe(true);
- console.log(
- `${LOG_PREFIX} C.4: pass — connect rejected empty bot_token, existing connection intact`
- );
- });
-
- // ──────────────────────────────────────────────────────────────────────────
- // C.5 — Inbound text message round-trip
- //
- // IMPORTANT: This scenario requires the Telegram channel polling loop to be
- // actively running (i.e. the in-process core is polling mock getUpdates).
- // The polling loop only starts after channels_connect writes config AND the
- // core restarts the channel listener. In E2E we first connect the bot (C.3
- // already passed), then inject an update. Whether the reply appears depends
- // on whether the core's channel runtime has started polling within the test
- // window. We assert the mock getUpdates was called and, if a reply appears,
- // validate its content. If no reply appears within the timeout window we log
- // a TODO rather than hard-failing, since the listener restart is async.
- // ──────────────────────────────────────────────────────────────────────────
-
- it('C.5 inbound text message round-trip — inject update; observe or document reply path', async function () {
- // Internal budget is up to 30s (getUpdates poll) + 25s (reply) + connect/LLM
- // overhead — that sums past a 60s ceiling on the slower macOS runner, so the
- // working round-trip blew the Mocha `it` timeout instead of asserting. 90s
- // (matching C.7) gives the observed flow headroom without masking a real hang:
- // the getUpdates soft-pass at line ~386 still short-circuits if the listener
- // never polls.
- this.timeout(90_000);
- console.log(`${LOG_PREFIX} C.5: setting up inbound message round-trip`);
-
- // First ensure the bot is connected (writes credentials + TOML config).
- await connectTelegramBot({ botToken: BOT_TOKEN, allowedUsers: [ALICE_USERNAME] });
-
- // Configure the mock LLM to respond deterministically.
- setMockBehavior(
- 'llmForcedResponses',
- JSON.stringify([
- {
- content: 'Hello Alice! I received your message and I am responding via Telegram.',
- finish_reason: 'stop',
- },
- ])
- );
-
- // Inject an inbound update from Alice.
- const update = buildTelegramUpdate({
- updateId: 1001,
- chatId: CHAT_ID_ALICE,
- userId: ALICE_ID,
- username: ALICE_USERNAME,
- text: 'Hello bot, are you there?',
- });
-
- await injectTelegramUpdate(update);
- console.log(`${LOG_PREFIX} C.5: update injected — waiting for getUpdates poll`);
-
- // Wait for the mock to receive a getUpdates call (confirms the channel
- // polling loop is active against the mock server).
- const getUpdatesDeadline = Date.now() + LISTENER_PROBE_TIMEOUT_MS;
- let getUpdatesObserved = false;
- while (Date.now() < getUpdatesDeadline) {
- const log = getRequestLog() as Array<{ method: string; url: string }>;
- if (log.some(r => r.url.includes('getUpdates'))) {
- getUpdatesObserved = true;
- break;
- }
- await browser.pause(500);
- }
-
- if (!getUpdatesObserved) {
- // TODO(channels): The Telegram polling loop did not observe getUpdates
- // within 30s. This means either: (a) the core did not restart the
- // channel listener after channels_connect (expected when restart is
- // manual), or (b) OPENHUMAN_TELEGRAM_API_BASE is not propagating to
- // the in-process core's channel runtime constructor.
- // The connect + status path (C.3) is fully validated above. The
- // message round-trip requires a live listener restart and is
- // architecture-dependent in the E2E harness.
- console.warn(
- `${LOG_PREFIX} C.5: getUpdates not observed within the probe window — channel listener may require ` +
- `manual core restart. Asserting RPC-level path only.`
- );
- // Validate the mock server is reachable and configured correctly.
- expect(true).toBe(true); // placeholder — test documents the gap
- return;
- }
-
- console.log(`${LOG_PREFIX} C.5: getUpdates observed — waiting for sendMessage reply`);
-
- // If getUpdates was polled, wait for the bot's reply to appear.
- try {
- const reply = await waitForTelegramReply({
- chatId: CHAT_ID_ALICE,
- contains: 'Alice',
- timeoutMs: 25_000,
- });
- console.log(`${LOG_PREFIX} C.5: pass — reply observed: ${JSON.stringify(reply)}`);
- expect(reply).toBeDefined();
- } catch (err) {
- // TODO(channels): Reply not observed despite getUpdates being polled.
- // The harness may be blocking on the agent turn (LLM call) or the
- // sendMessage is failing. Check mock sendMessage handler in WS-A.
- console.warn(`${LOG_PREFIX} C.5: sendMessage not observed — ${err}`);
- // Do not hard-fail: getUpdates was confirmed, which validates the
- // channel runtime is using OPENHUMAN_TELEGRAM_API_BASE correctly.
- expect(getUpdatesObserved).toBe(true);
- }
- });
-
- // ──────────────────────────────────────────────────────────────────────────
- // C.6 — Unauthorized user
- //
- // Connect with an allowedUsers list that excludes Bob. Inject a message
- // from Bob. Assert the bot sends the approval-required reply.
- // Like C.5, this requires an active polling loop.
- // ──────────────────────────────────────────────────────────────────────────
-
- it('C.6 unauthorized user — connect with allowlist; excluded sender gets approval prompt', async function () {
- // 30s getUpdates poll + 20s reply wait + connect/LLM overhead exceeds 60s on the
- // slower macOS runner; 90s fits the working flow. The getUpdates soft-pass still
- // guards against a genuinely dead listener.
- this.timeout(90_000);
- console.log(`${LOG_PREFIX} C.6: connecting with allowlist excluding Bob`);
-
- // Connect with Alice in the allowlist — Bob is excluded.
- await connectTelegramBot({ botToken: BOT_TOKEN, allowedUsers: [ALICE_USERNAME] });
-
- // Inject a message from Bob (not in the allowlist).
- const update = buildTelegramUpdate({
- updateId: 2001,
- chatId: CHAT_ID_BOB,
- userId: BOB_ID,
- username: BOB_USERNAME,
- text: 'Hey bot, let me in!',
- });
-
- await injectTelegramUpdate(update);
- console.log(`${LOG_PREFIX} C.6: Bob's update injected`);
-
- // Wait for getUpdates poll to confirm listener is active.
- const getUpdatesDeadline = Date.now() + LISTENER_PROBE_TIMEOUT_MS;
- let getUpdatesObserved = false;
- while (Date.now() < getUpdatesDeadline) {
- const log = getRequestLog() as Array<{ method: string; url: string }>;
- if (log.some(r => r.url.includes('getUpdates'))) {
- getUpdatesObserved = true;
- break;
- }
- await browser.pause(500);
- }
-
- if (!getUpdatesObserved) {
- // TODO(channels): Same listener-restart caveat as C.5.
- console.warn(`${LOG_PREFIX} C.6: getUpdates not observed — documenting listener gap`);
- expect(true).toBe(true);
- return;
- }
-
- // The Telegram channel sends "🔐 This bot requires operator approval."
- // to unauthorized senders (see channel_recv.rs handle_unauthorized_message).
- try {
- const reply = await waitForTelegramReply({
- chatId: CHAT_ID_BOB,
- contains: 'operator approval',
- timeoutMs: 20_000,
- });
- console.log(`${LOG_PREFIX} C.6: pass — approval prompt observed: ${JSON.stringify(reply)}`);
- expect(reply).toBeDefined();
- const replyText = String(reply.text ?? reply.message ?? '');
- expect(replyText).toContain('operator approval');
- } catch (err) {
- console.warn(`${LOG_PREFIX} C.6: approval prompt not observed — ${err}`);
- expect(getUpdatesObserved).toBe(true);
- }
- });
-
- // ──────────────────────────────────────────────────────────────────────────
- // C.7 — Group mention-only filtering
- //
- // Connect with mentionOnly: true. Inject a group message without @mention
- // (no reply expected). Inject a group message with @e2e_test_bot (reply).
- // ──────────────────────────────────────────────────────────────────────────
-
- it('C.7 group mention-only — no mention skipped; with @mention bot replies', async function () {
- this.timeout(90_000);
- console.log(`${LOG_PREFIX} C.7: connecting with mentionOnly=true`);
-
- await connectTelegramBot({
- botToken: BOT_TOKEN,
- allowedUsers: [ALICE_USERNAME],
- mentionOnly: true,
- });
-
- // Wait for listener to start (getUpdates poll) before injecting.
- const listenerDeadline = Date.now() + LISTENER_PROBE_TIMEOUT_MS;
- let listenerActive = false;
- while (Date.now() < listenerDeadline) {
- const log = getRequestLog() as Array<{ method: string; url: string }>;
- if (log.some(r => r.url.includes('getUpdates'))) {
- listenerActive = true;
- break;
- }
- await browser.pause(500);
- }
-
- if (!listenerActive) {
- // TODO(channels): Listener not active — see C.5 gap note.
- console.warn(`${LOG_PREFIX} C.7: listener not active — skipping mention-only assertions`);
- expect(true).toBe(true);
- return;
- }
-
- // --- Part 1: group message WITHOUT mention — no reply expected ---
- await resetTelegramMock();
- clearRequestLog();
-
- const updateNoMention = buildTelegramUpdate({
- updateId: 3001,
- chatId: CHAT_ID_GROUP,
- userId: ALICE_ID,
- username: ALICE_USERNAME,
- text: 'Just chatting in the group, not mentioning the bot.',
- isGroup: true,
- });
-
- await injectTelegramUpdate(updateNoMention);
- console.log(`${LOG_PREFIX} C.7: no-mention update injected — asserting no reply`);
-
- const noReply = await assertNoTelegramReply({ chatId: CHAT_ID_GROUP, timeoutMs: 8_000 });
- expect(noReply).toBe(true);
- console.log(`${LOG_PREFIX} C.7: no-mention case passed — bot correctly silent`);
-
- // --- Part 2: group message WITH @mention — reply expected ---
- await resetTelegramMock();
- clearRequestLog();
-
- setMockBehavior(
- 'llmForcedResponses',
- JSON.stringify([
- { content: 'Hi group! You mentioned me so I am responding.', finish_reason: 'stop' },
- ])
- );
-
- const updateWithMention = buildTelegramUpdate({
- updateId: 3002,
- chatId: CHAT_ID_GROUP,
- userId: ALICE_ID,
- username: ALICE_USERNAME,
- text: `@${BOT_USERNAME} what can you do?`,
- isGroup: true,
- });
-
- await injectTelegramUpdate(updateWithMention);
- console.log(`${LOG_PREFIX} C.7: @mention update injected — waiting for reply`);
-
- try {
- const reply = await waitForTelegramReply({ chatId: CHAT_ID_GROUP, timeoutMs: 25_000 });
- console.log(`${LOG_PREFIX} C.7: pass — @mention triggered reply: ${JSON.stringify(reply)}`);
- expect(reply).toBeDefined();
- } catch (err) {
- // TODO(channels): @mention reply not observed — the bot username may
- // not have been propagated to the channel runtime (get_bot_username()
- // is called lazily on first getUpdates when mention_only=true). If
- // getMe is not returning the correct username from the mock, the
- // mention check falls back and may reject all messages.
- console.warn(`${LOG_PREFIX} C.7: @mention reply not observed — ${err}`);
- expect(listenerActive).toBe(true);
- }
- });
-
- // ──────────────────────────────────────────────────────────────────────────
- // C.8 — Disconnect
- // ──────────────────────────────────────────────────────────────────────────
-
- it('C.8 disconnect — channels_disconnect; status shows disconnected', async function () {
- this.timeout(30_000);
- console.log(`${LOG_PREFIX} C.8: ensuring bot is connected before disconnect`);
-
- // Connect first so we have something to disconnect.
- const connect = await connectTelegramBot({ botToken: BOT_TOKEN });
- expect(connect.ok).toBe(true);
-
- const beforeStatus = await getTelegramChannelStatus();
- expect(beforeStatus?.connected).toBe(true);
-
- console.log(`${LOG_PREFIX} C.8: calling channels_disconnect`);
- const disconnected = await disconnectTelegramBot();
- expect(disconnected).toBe(true);
-
- // After disconnect the credentials are removed; status must show not connected.
- const afterStatus = await getTelegramChannelStatus();
- console.log(`${LOG_PREFIX} C.8: status after disconnect = ${JSON.stringify(afterStatus)}`);
-
- // Either null (no entry) or connected=false.
- const isDisconnected = afterStatus === null || afterStatus.connected === false;
- expect(isDisconnected).toBe(true);
-
- console.log(`${LOG_PREFIX} C.8: pass — status shows disconnected`);
- });
-
- // ──────────────────────────────────────────────────────────────────────────
- // C.9 — Reconnect after disconnect
- // ──────────────────────────────────────────────────────────────────────────
-
- it('C.9 reconnect after disconnect — second connect succeeds; status connected', async function () {
- this.timeout(30_000);
- console.log(`${LOG_PREFIX} C.9: disconnect then reconnect`);
-
- // Connect, disconnect, reconnect with a different token.
- await connectTelegramBot({ botToken: BOT_TOKEN });
- await disconnectTelegramBot();
-
- const midStatus = await getTelegramChannelStatus();
- const isMidDisconnected = midStatus === null || midStatus.connected === false;
- expect(isMidDisconnected).toBe(true);
- console.log(`${LOG_PREFIX} C.9: mid-point disconnected confirmed`);
-
- // Reconnect with a new bot token.
- const reconnect = await connectTelegramBot({ botToken: BOT_TOKEN_2 });
- console.log(`${LOG_PREFIX} C.9: reconnect result = ${JSON.stringify(reconnect)}`);
-
- expect(reconnect.ok).toBe(true);
- expect(reconnect.status).toBe('connected');
-
- const afterStatus = await getTelegramChannelStatus();
- console.log(`${LOG_PREFIX} C.9: status after reconnect = ${JSON.stringify(afterStatus)}`);
-
- expect(afterStatus?.connected).toBe(true);
- expect(afterStatus?.hasCredentials).toBe(true);
-
- console.log(`${LOG_PREFIX} C.9: pass — reconnect successful`);
- });
-
- // ──────────────────────────────────────────────────────────────────────────
- // C.10 — Remote /status command
- //
- // Inject a message with text `/status`. Assert the bot sends a status
- // response containing the expected markers ("Thread:", "Provider:").
- // Like C.5-C.7, requires an active polling loop.
- // ──────────────────────────────────────────────────────────────────────────
-
- it('C.10 remote /status command — bot replies with Thread: and Provider: markers', async function () {
- // 30s listener poll + 20s reply wait + connect/LLM overhead exceeds 60s on the
- // slower macOS runner; 90s fits the working flow. The getUpdates soft-pass still
- // guards against a genuinely dead listener.
- this.timeout(90_000);
- console.log(`${LOG_PREFIX} C.10: setting up /status command scenario`);
-
- await connectTelegramBot({ botToken: BOT_TOKEN, allowedUsers: [ALICE_USERNAME] });
-
- // Wait for listener.
- const listenerDeadline = Date.now() + LISTENER_PROBE_TIMEOUT_MS;
- let listenerActive = false;
- while (Date.now() < listenerDeadline) {
- const log = getRequestLog() as Array<{ method: string; url: string }>;
- if (log.some(r => r.url.includes('getUpdates'))) {
- listenerActive = true;
- break;
- }
- await browser.pause(500);
- }
-
- if (!listenerActive) {
- // TODO(channels): Listener not active — see C.5 gap note.
- console.warn(`${LOG_PREFIX} C.10: listener not active — documenting gap`);
- expect(true).toBe(true);
- return;
- }
-
- const update = buildTelegramUpdate({
- updateId: 4001,
- chatId: CHAT_ID_ALICE,
- userId: ALICE_ID,
- username: ALICE_USERNAME,
- text: '/status',
- });
-
- await injectTelegramUpdate(update);
- console.log(`${LOG_PREFIX} C.10: /status update injected`);
-
- // The remote_control.rs build_status_response() returns a message with:
- // "**Status**\nThread: ...\nProvider: ...\nModel: ...\nIn-memory turns: ...\nTurn: ..."
- // (see remote_control.rs:140-151)
- try {
- const reply = await waitForTelegramReply({
- chatId: CHAT_ID_ALICE,
- contains: 'Provider:',
- timeoutMs: 20_000,
- });
- console.log(`${LOG_PREFIX} C.10: reply = ${JSON.stringify(reply)}`);
-
- const replyText = String(reply.text ?? reply.message ?? '');
- expect(replyText).toContain('Provider:');
- // "Thread: `(none — send /new to bind a thread)`" or with an active thread ID.
- expect(replyText).toContain('Thread:');
-
- console.log(`${LOG_PREFIX} C.10: pass — /status reply contains expected markers`);
- } catch (err) {
- // TODO(channels): /status reply not observed. The remote-control
- // command handler is invoked before the agent turn (no LLM call
- // needed), so this should work as long as the channel listener is
- // active. If the listener IS active but no reply appears, check
- // whether the mock sendMessage is recording correctly.
- console.warn(`${LOG_PREFIX} C.10: /status reply not observed — ${err}`);
- expect(listenerActive).toBe(true);
- }
- });
-});
diff --git a/app/test/playwright/specs/telegram-channel-flow.spec.ts b/app/test/playwright/specs/telegram-channel-flow.spec.ts
deleted file mode 100644
index e1a5b9d71e..0000000000
--- a/app/test/playwright/specs/telegram-channel-flow.spec.ts
+++ /dev/null
@@ -1,179 +0,0 @@
-import { expect, test } from '@playwright/test';
-
-import { bootAuthenticatedPage, callCoreRpc } from '../helpers/core-rpc';
-
-const MOCK_BASE = 'http://127.0.0.1:' + (process.env.E2E_MOCK_PORT || '18473');
-const BOT_TOKEN = 'e2e-bot-token-12345:AAFakeTokenForE2E';
-const BOT_TOKEN_2 = 'e2e-bot-token-99999:AASecondFakeTokenForE2E';
-const BOT_USERNAME = 'e2e_test_bot';
-
-type TelegramStatusEntry = {
- channelId?: string;
- channel_id?: string;
- authMode?: string;
- auth_mode?: string;
- connected?: boolean;
- hasCredentials?: boolean;
- has_credentials?: boolean;
-};
-
-async function mockFetch(path: string, init?: RequestInit) {
- const response = await fetch(MOCK_BASE + path, init);
- if (!response.ok) throw new Error('mock request failed: ' + response.status + ' ' + path);
- return response.json() as Promise<{ data?: unknown }>;
-}
-
-async function resetTelegramMock() {
- await mockFetch('/__admin/telegram/reset', { method: 'POST' });
-}
-
-async function setMockBehavior(behavior: Record<string, unknown>) {
- await mockFetch('/__admin/behavior', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ behavior }),
- });
-}
-
-async function connectTelegramBot(opts: {
- botToken: string;
- allowedUsers?: string[];
- mentionOnly?: boolean;
-}) {
- const credentials: Record<string, unknown> = { bot_token: opts.botToken };
- if (opts.allowedUsers) credentials.allowed_users = opts.allowedUsers;
- if (opts.mentionOnly !== undefined) credentials.mention_only = opts.mentionOnly;
- return callCoreRpc<{
- result?: { status?: string; restart_required?: boolean; message?: string };
- status?: string;
- restart_required?: boolean;
- message?: string;
- }>('openhuman.channels_connect', { channel: 'telegram', authMode: 'bot_token', credentials });
-}
-
-async function disconnectTelegramBot() {
- return callCoreRpc<unknown>('openhuman.channels_disconnect', {
- channel: 'telegram',
- authMode: 'bot_token',
- });
-}
-
-async function getTelegramChannelStatus(): Promise<TelegramStatusEntry | null> {
- const out = await callCoreRpc<unknown>('openhuman.channels_status', { channel: 'telegram' });
- const root = (out ?? {}) as Record<string, unknown>;
- const entries = Array.isArray(root)
- ? root
- : Array.isArray(root.entries)
- ? (root.entries as unknown[])
- : Array.isArray(root.result)
- ? (root.result as unknown[])
- : [];
- const match = entries.find(entry => {
- const record = entry as TelegramStatusEntry;
- const channelId = record.channelId ?? record.channel_id;
- const authMode = record.authMode ?? record.auth_mode;
- return channelId === 'telegram' && authMode === 'bot_token';
- });
- return (match as TelegramStatusEntry | undefined) ?? null;
-}
-
-test.describe('Telegram channel - connect / disconnect RPC flow', () => {
- test.beforeEach(async ({ page }) => {
- await bootAuthenticatedPage(page, 'pw-telegram-channel-flow', '/home');
- await setMockBehavior({ telegramBotUsername: BOT_USERNAME, telegramPollDelayMs: '0' });
- await resetTelegramMock();
- });
-
- test('channels_list includes telegram with bot_token auth mode', async () => {
- const out = await callCoreRpc<unknown>('openhuman.channels_list', {});
- const root = (out ?? {}) as Record<string, unknown>;
- const channels = Array.isArray(root)
- ? root
- : Array.isArray(root.channels)
- ? (root.channels as Array<Record<string, unknown>>)
- : Array.isArray(root.result)
- ? (root.result as Array<Record<string, unknown>>)
- : [];
- const telegram = channels.find(channel => channel?.id === 'telegram');
- expect(telegram).toBeDefined();
- const authModes = Array.isArray(telegram?.auth_modes)
- ? (telegram?.auth_modes as unknown[])
- : Array.isArray(telegram?.authModes)
- ? (telegram?.authModes as unknown[])
- : [];
- const hasBotToken = authModes.some(
- mode => (mode as Record<string, unknown>).mode === 'bot_token' || mode === 'bot_token'
- );
- expect(hasBotToken).toBe(true);
- });
-
- test('channels_describe for telegram returns auth modes and bot_token field', async () => {
- const out = await callCoreRpc<unknown>('openhuman.channels_describe', { channel: 'telegram' });
- const root = (out ?? {}) as Record<string, unknown>;
- const def =
- typeof root.result === 'object' && root.result !== null
- ? (root.result as Record<string, unknown>)
- : typeof root.definition === 'object' && root.definition !== null
- ? (root.definition as Record<string, unknown>)
- : root;
-
- expect(def.id ?? def.channel_id).toBe('telegram');
- const authModes = Array.isArray(def.auth_modes) ? (def.auth_modes as unknown[]) : [];
- const botTokenSpec = authModes.find(
- mode => (mode as Record<string, unknown>).mode === 'bot_token'
- ) as Record<string, unknown> | undefined;
- expect(botTokenSpec).toBeDefined();
- const fields = Array.isArray(botTokenSpec?.fields) ? (botTokenSpec?.fields as unknown[]) : [];
- expect(fields.some(field => (field as Record<string, unknown>).key === 'bot_token')).toBe(true);
- });
-
- test('bot-token connect happy path stores credentials and status shows connected', async () => {
- const connectResult = await connectTelegramBot({ botToken: BOT_TOKEN });
- const payload =
- typeof connectResult.result === 'object' && connectResult.result !== null
- ? connectResult.result
- : connectResult;
- expect(payload.status).toBe('connected');
- expect(payload.restart_required).toBe(true);
-
- const status = await getTelegramChannelStatus();
- expect(status).not.toBeNull();
- expect(status?.connected).toBe(true);
- expect(status?.hasCredentials ?? status?.has_credentials).toBe(true);
- });
-
- test('connect with missing token fails validation', async () => {
- await expect(
- callCoreRpc('openhuman.channels_connect', {
- channel: 'telegram',
- authMode: 'bot_token',
- credentials: { bot_token: '' },
- })
- ).rejects.toThrow();
- });
-
- test('disconnect clears channel status', async () => {
- await connectTelegramBot({ botToken: BOT_TOKEN });
- const beforeStatus = await getTelegramChannelStatus();
- expect(beforeStatus?.connected).toBe(true);
-
- await disconnectTelegramBot();
- const afterStatus = await getTelegramChannelStatus();
- expect(afterStatus === null || afterStatus.connected === false).toBe(true);
- });
-
- test('reconnect after disconnect succeeds', async () => {
- await connectTelegramBot({ botToken: BOT_TOKEN });
- await disconnectTelegramBot();
- const reconnect = await connectTelegramBot({ botToken: BOT_TOKEN_2 });
- const payload =
- typeof reconnect.result === 'object' && reconnect.result !== null
- ? reconnect.result
- : reconnect;
- expect(payload.status).toBe('connected');
-
- const status = await getTelegramChannelStatus();
- expect(status?.connected).toBe(true);
- expect(status?.hasCredentials ?? status?.has_credentials).toBe(true);
- });
-});
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index b207ee89b7..5ed62334c0 100644
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@ -440,7 +440,7 @@ The thread JSONL store moved to `tinyagents_session::threads` (`vendor/tinyagent
| ID | Feature | Layer | Test path(s) | Status | Notes |
| ------ | ---------------------------- | ----- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| 10.1.1 | Telegram Connection | WD | `telegram-flow.spec.ts` | ✅ | |
+| 10.1.1 | Telegram Connection | WD+RI | `app/test/e2e/specs/channels-smoke.spec.ts`, `tests/json_rpc_auth_security_e2e.rs::telegram_bot_token_connect_reject_disconnect_and_reconnect_over_json_rpc_e2e` | ✅ | The desktop smoke checks channel status and connect/disconnect UI wiring. The local JSON-RPC test covers bot-token connect, status, invalid-token rejection without losing prior state, disconnect, and reconnect. Telegram update polling/recovery remains unverified at the pinned TinyChannels version. |
| 10.1.2 | WhatsApp Connection | WD | `app/test/e2e/specs/whatsapp-flow.spec.ts` | 🚫 | **Corrected 2026-09-24 — this row was ✅ on evidence that does not support it.** WhatsApp has no entry in `all_channel_definitions()`, is not a Composio toolkit, and its provider sits behind the non-default `whatsapp-web` feature, which is absent from `scripts/ci/product-features.txt` — so there is no WhatsApp connect flow in the shipped build to test. The cited `whatsapp-flow.spec.ts` correctly asserts that the retired `/accounts` route redirects; it never connects anything. Manual-only until the feature ships |
| 10.1.3 | Gmail Connection | WD | `gmail-flow.spec.ts` | ✅ | |
| 10.1.4 | Slack Connection | WD | `app/test/e2e/specs/connector-composio-contract.spec.ts` (Slack row) | ✅ | **Evidence corrected 2026-09-24:** Slack is a Composio toolkit, not a native channel — it has no entry in `all_channel_definitions()`, so `channels_connect` cannot reach it. Real coverage is the 10-case connector contract (`connector-contract.ts`), which runs Slack in the gated `connectors` suite. The previously cited `slack-flow.spec.ts` is a 26-line surface smoke whose `run()` call is commented out at `e2e-run-all-flows.sh:343`, so no lane executes it Was ❌ |
diff --git a/scripts/mock-api/admin.mjs b/scripts/mock-api/admin.mjs
index 7f089db17f..373565e830 100644
--- a/scripts/mock-api/admin.mjs
+++ b/scripts/mock-api/admin.mjs
@@ -1,6 +1,5 @@
import { json } from "./http.mjs";
import { resetConversationFixturesState } from "./routes/conversations.mjs";
-import { resetCronFixturesState } from "./routes/cron.mjs";
import { resetMockMemory } from "./routes/memory.mjs";
import {
clearSocketEventLog,
@@ -9,19 +8,14 @@ import {
listSocketSessions,
getMockBehavior,
getMockConversations,
- getMockCronJobs,
getMockMessages,
listMockLlmThreads,
getMockWebhookTriggers,
- getMockTelegramSent,
getRequestLog,
- pushMockTelegramUpdate,
resetMockBehavior,
resetMockConversations,
- resetMockCronJobs,
resetMockMessages,
resetMockLlmThreads,
- resetMockTelegram,
resetSocketSessions,
resetMockTunnels,
resetMockWebhookTriggers,
@@ -52,7 +46,6 @@ export function handleAdmin(ctx) {
requestCount: getRequestLog().length,
conversations: getMockConversations(),
messages: getMockMessages(),
- cronJobs: getMockCronJobs(),
webhookTriggers: getMockWebhookTriggers(),
llmThreads: listMockLlmThreads(),
socketSessions: listSocketSessions(),
@@ -77,14 +70,11 @@ export function handleAdmin(ctx) {
resetMockTunnels();
resetMockConversations();
resetMockMessages();
- resetMockCronJobs();
resetMockMemory();
resetMockWebhookTriggers();
resetMockLlmThreads();
resetConversationFixturesState();
- resetCronFixturesState();
resetSocketSessions();
- resetMockTelegram();
json(res, 200, {
success: true,
data: {
@@ -129,30 +119,5 @@ export function handleAdmin(ctx) {
return true;
}
- // ── Telegram admin endpoints ───────────────────────────────────────────
- if (method === "POST" && /^\/__admin\/telegram\/inject-update\/?$/.test(url)) {
- const updates = Array.isArray(parsedBody?.updates)
- ? parsedBody.updates
- : parsedBody && typeof parsedBody === "object" && !Array.isArray(parsedBody)
- ? [parsedBody]
- : [];
- for (const update of updates) {
- pushMockTelegramUpdate(update);
- }
- console.log(`[telegram-mock] inject-update: queued ${updates.length} update(s)`);
- json(res, 200, { ok: true, queued: updates.length });
- return true;
- }
- if (method === "GET" && /^\/__admin\/telegram\/sent\/?$/.test(url)) {
- json(res, 200, { ok: true, messages: getMockTelegramSent() });
- return true;
- }
- if (method === "POST" && /^\/__admin\/telegram\/reset\/?$/.test(url)) {
- resetMockTelegram();
- console.log("[telegram-mock] admin reset: telegram state cleared");
- json(res, 200, { ok: true });
- return true;
- }
-
return false;
}
diff --git a/scripts/mock-api/index.mjs b/scripts/mock-api/index.mjs
index 460c23097b..f226cba30b 100644
--- a/scripts/mock-api/index.mjs
+++ b/scripts/mock-api/index.mjs
@@ -19,14 +19,11 @@ export {
clearRequestLog,
getSocketEventLog,
getMockBehavior,
- getMockTelegramSent,
listMockLlmThreads,
getRequestLog,
listSocketSessions,
- pushMockTelegramUpdate,
resetMockBehavior,
resetMockLlmThreads,
- resetMockTelegram,
setMockBehavior,
setMockBehaviors,
} from "./state.mjs";
diff --git a/scripts/mock-api/routes/__tests__/stateful.test.mjs b/scripts/mock-api/routes/__tests__/stateful.test.mjs
index 40a23ca2b5..52d75de16b 100644
--- a/scripts/mock-api/routes/__tests__/stateful.test.mjs
+++ b/scripts/mock-api/routes/__tests__/stateful.test.mjs
@@ -78,26 +78,6 @@ test("keeps server-controlled ids on create and patch routes", async () => {
}).then((response) => response.json());
assert.notEqual(createdConversation?.data?.id, "client-conv");
- const createdCron = await fetch(`${baseUrl}/settings/cron-jobs`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ id: "client-cron", name: "Client cron" }),
- }).then((response) => response.json());
- const cronId = createdCron?.data?.id;
- assert.notEqual(cronId, "client-cron");
-
- await fetch(`${baseUrl}/settings/cron-jobs/${cronId}`, {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ id: "mutated-cron", enabled: false }),
- });
-
- const cronList = await fetch(`${baseUrl}/settings/cron-jobs`).then(
- (response) => response.json(),
- );
- const patchedCron = cronList.data.find((entry) => entry.id === cronId);
- assert.equal(patchedCron.id, cronId);
- assert.equal(patchedCron.enabled, false);
});
test("serves deterministic Parallel search proxy results", async () => {
diff --git a/scripts/mock-api/routes/__tests__/telegram.test.mjs b/scripts/mock-api/routes/__tests__/telegram.test.mjs
deleted file mode 100644
index 29e2298438..0000000000
--- a/scripts/mock-api/routes/__tests__/telegram.test.mjs
+++ /dev/null
@@ -1,416 +0,0 @@
-/**
- * Unit tests for the mock Telegram Bot API route handler.
- *
- * Pattern: construct a minimal `ctx` object (matching what server.mjs
- * provides), call the handler, and assert on the captured response.
- *
- * Run via:
- * node --test scripts/mock-api/routes/__tests__/telegram.test.mjs
- * or through the project test runner:
- * pnpm debug unit scripts/mock-api/routes/__tests__/telegram.test.mjs
- */
-
-import assert from "node:assert/strict";
-import test from "node:test";
-
-import {
- resetMockBehavior,
- resetMockTelegram,
- setMockBehavior,
- pushMockTelegramUpdate,
- getMockTelegramSent,
- startMockServer,
- stopMockServer,
-} from "../../index.mjs";
-import { handleTelegram } from "../telegram.mjs";
-
-// ── Helpers ────────────────────────────────────────────────────────────────
-
-function createRes() {
- return {
- statusCode: 0,
- headers: {},
- body: "",
- writeHead(status, headers = {}) {
- this.statusCode = status;
- this.headers = { ...this.headers, ...headers };
- },
- setHeader(name, value) {
- this.headers[name] = value;
- },
- end(chunk = "") {
- this.body += String(chunk);
- },
- json() {
- return JSON.parse(this.body);
- },
- };
-}
-
-function makeCtx(method, path, body = null) {
- return {
- method,
- url: path,
- body: body ? JSON.stringify(body) : "",
- parsedBody: body,
- res: createRes(),
- };
-}
-
-// ── Setup / teardown ───────────────────────────────────────────────────────
-
-test.beforeEach(() => {
- resetMockBehavior();
- resetMockTelegram();
-});
-
-// ── getMe ──────────────────────────────────────────────────────────────────
-
-test("getMe returns default bot info", async () => {
- const ctx = makeCtx("POST", "/bot12345:TOKEN/getMe");
- const handled = await handleTelegram(ctx);
-
- assert.equal(handled, true);
- assert.equal(ctx.res.statusCode, 200);
- const payload = ctx.res.json();
- assert.equal(payload.ok, true);
- assert.equal(payload.result.is_bot, true);
- assert.equal(payload.result.username, "e2e_test_bot");
- assert.equal(payload.result.id, 123456789);
-});
-
-test("getMe returns custom username from behavior", async () => {
- setMockBehavior("telegramBotUsername", "my_custom_bot");
- const ctx = makeCtx("GET", "/bot12345:TOKEN/getMe");
- const handled = await handleTelegram(ctx);
-
- assert.equal(handled, true);
- const payload = ctx.res.json();
- assert.equal(payload.result.username, "my_custom_bot");
-});
-
-test("getMe returns 401 when telegramGetMeFails=1", async () => {
- setMockBehavior("telegramGetMeFails", "1");
- const ctx = makeCtx("POST", "/botANYTOKEN/getMe");
- const handled = await handleTelegram(ctx);
-
- assert.equal(handled, true);
- assert.equal(ctx.res.statusCode, 401);
- const payload = ctx.res.json();
- assert.equal(payload.ok, false);
- assert.equal(payload.error_code, 401);
-});
-
-// ── getUpdates ─────────────────────────────────────────────────────────────
-
-test("getUpdates returns empty array when queue is empty", async () => {
- setMockBehavior("telegramPollDelayMs", "0");
- const ctx = makeCtx("POST", "/botTOKEN/getUpdates");
- const handled = await handleTelegram(ctx);
-
- assert.equal(handled, true);
- assert.equal(ctx.res.statusCode, 200);
- const payload = ctx.res.json();
- assert.equal(payload.ok, true);
- assert.deepEqual(payload.result, []);
-});
-
-test("getUpdates returns injected update", async () => {
- setMockBehavior("telegramPollDelayMs", "0");
- const update = {
- update_id: 1,
- message: {
- message_id: 1,
- from: { id: 9999, first_name: "Alice" },
- chat: { id: 9999, type: "private" },
- text: "hello bot",
- },
- };
- pushMockTelegramUpdate(update);
-
- const ctx = makeCtx("POST", "/botTOKEN/getUpdates");
- const handled = await handleTelegram(ctx);
-
- assert.equal(handled, true);
- const payload = ctx.res.json();
- assert.equal(payload.result.length, 1);
- assert.deepEqual(payload.result[0], update);
-});
-
-test("getUpdates drains queue on each call", async () => {
- setMockBehavior("telegramPollDelayMs", "0");
- pushMockTelegramUpdate({ update_id: 1, message: { text: "first" } });
- pushMockTelegramUpdate({ update_id: 2, message: { text: "second" } });
-
- // First call — should return both
- const ctx1 = makeCtx("POST", "/botTOKEN/getUpdates");
- await handleTelegram(ctx1);
- const payload1 = ctx1.res.json();
- assert.equal(payload1.result.length, 2);
-
- // Second call — queue is now empty
- const ctx2 = makeCtx("POST", "/botTOKEN/getUpdates");
- await handleTelegram(ctx2);
- const payload2 = ctx2.res.json();
- assert.deepEqual(payload2.result, []);
-});
-
-// ── sendMessage ────────────────────────────────────────────────────────────
-
-test("sendMessage records message and returns proper shape", async () => {
- const ctx = makeCtx("POST", "/botTOKEN/sendMessage", {
- chat_id: 42,
- text: "Hello from test!",
- parse_mode: "Markdown",
- });
- const handled = await handleTelegram(ctx);
-
- assert.equal(handled, true);
- assert.equal(ctx.res.statusCode, 200);
- const payload = ctx.res.json();
- assert.equal(payload.ok, true);
- assert.equal(typeof payload.result.message_id, "number");
- assert.equal(payload.result.chat.id, 42);
- assert.equal(payload.result.text, "Hello from test!");
-
- // Verify it was recorded
- const sent = getMockTelegramSent();
- assert.equal(sent.length, 1);
- assert.equal(sent[0].method, "sendMessage");
- assert.equal(sent[0].body.text, "Hello from test!");
- assert.equal(sent[0].message_id, payload.result.message_id);
-});
-
-test("sendMessage returns 400 when telegramSendFails=1", async () => {
- setMockBehavior("telegramSendFails", "1");
- const ctx = makeCtx("POST", "/botTOKEN/sendMessage", {
- chat_id: 42,
- text: "will fail",
- });
- const handled = await handleTelegram(ctx);
-
- assert.equal(handled, true);
- assert.equal(ctx.res.statusCode, 400);
- const payload = ctx.res.json();
- assert.equal(payload.ok, false);
- assert.equal(payload.error_code, 400);
-});
-
-// ── Simple record methods ──────────────────────────────────────────────────
-
-test("sendChatAction records and returns ok", async () => {
- const ctx = makeCtx("POST", "/botTOKEN/sendChatAction", {
- chat_id: 42,
- action: "typing",
- });
- const handled = await handleTelegram(ctx);
-
- assert.equal(handled, true);
- const payload = ctx.res.json();
- assert.equal(payload.ok, true);
- assert.equal(payload.result, true);
-});
-
-test("deleteWebhook returns ok", async () => {
- const ctx = makeCtx("POST", "/botTOKEN/deleteWebhook");
- const handled = await handleTelegram(ctx);
-
- assert.equal(handled, true);
- const payload = ctx.res.json();
- assert.equal(payload.ok, true);
-});
-
-// ── Media send methods ─────────────────────────────────────────────────────
-
-test("sendPhoto records and returns message_id", async () => {
- const ctx = makeCtx("POST", "/botTOKEN/sendPhoto", { chat_id: 99 });
- const handled = await handleTelegram(ctx);
-
- assert.equal(handled, true);
- const payload = ctx.res.json();
- assert.equal(payload.ok, true);
- assert.equal(typeof payload.result.message_id, "number");
-
- const sent = getMockTelegramSent();
- assert.equal(sent.length, 1);
- assert.equal(sent[0].method, "sendPhoto");
-});
-
-// ── Token validation ───────────────────────────────────────────────────────
-
-test("rejects mismatched token when telegramBotToken is set", async () => {
- setMockBehavior("telegramBotToken", "correctToken");
- const ctx = makeCtx("POST", "/botwrongToken/getMe");
- const handled = await handleTelegram(ctx);
-
- assert.equal(handled, true);
- assert.equal(ctx.res.statusCode, 401);
- const payload = ctx.res.json();
- assert.equal(payload.ok, false);
-});
-
-test("accepts correct token when telegramBotToken is set", async () => {
- setMockBehavior("telegramBotToken", "correctToken");
- const ctx = makeCtx("POST", "/botcorrectToken/getMe");
- const handled = await handleTelegram(ctx);
-
- assert.equal(handled, true);
- assert.equal(ctx.res.statusCode, 200);
- const payload = ctx.res.json();
- assert.equal(payload.ok, true);
-});
-
-// ── Non-Telegram paths ─────────────────────────────────────────────────────
-
-test("returns false for non-bot paths", async () => {
- const ctx = makeCtx("GET", "/api/something");
- const handled = await handleTelegram(ctx);
- assert.equal(handled, false);
-});
-
-// ── Admin round-trip (stateful, uses full HTTP server) ─────────────────────
-
-test("admin inject-update + sent-list round-trip", async () => {
- const { port } = await startMockServer(18562, { retryIfInUse: true });
- const base = `http://127.0.0.1:${port}`;
-
- try {
- // Inject a single update
- const injectSingle = await fetch(`${base}/__admin/telegram/inject-update`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- update_id: 100,
- message: { text: "hello", chat: { id: 1 } },
- }),
- });
- assert.equal(injectSingle.status, 200);
- const injectBody = await injectSingle.json();
- assert.equal(injectBody.ok, true);
- assert.equal(injectBody.queued, 1);
-
- // Drain via getUpdates
- const updatesRes = await fetch(`${base}/botTEST123/getUpdates`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ timeout: 0 }),
- });
- const updatesBody = await updatesRes.json();
- assert.equal(updatesBody.ok, true);
- assert.equal(updatesBody.result.length, 1);
- assert.equal(updatesBody.result[0].update_id, 100);
-
- // Send a message
- await fetch(`${base}/botTEST123/sendMessage`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ chat_id: 1, text: "reply" }),
- });
-
- // Check sent list
- const sentRes = await fetch(`${base}/__admin/telegram/sent`);
- const sentBody = await sentRes.json();
- assert.equal(sentBody.ok, true);
- assert.equal(sentBody.messages.length, 1);
- assert.equal(sentBody.messages[0].method, "sendMessage");
- assert.equal(sentBody.messages[0].body.text, "reply");
- } finally {
- await stopMockServer();
- }
-});
-
-test("admin inject-update accepts { updates: [...] } batch form", async () => {
- const { port } = await startMockServer(18563, { retryIfInUse: true });
- const base = `http://127.0.0.1:${port}`;
-
- try {
- const injectBatch = await fetch(`${base}/__admin/telegram/inject-update`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- updates: [
- { update_id: 200, message: { text: "msg1" } },
- { update_id: 201, message: { text: "msg2" } },
- ],
- }),
- });
- const batchBody = await injectBatch.json();
- assert.equal(batchBody.queued, 2);
-
- // Drain
- const updatesRes = await fetch(`${base}/botX/getUpdates`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({}),
- });
- const updatesBody = await updatesRes.json();
- assert.equal(updatesBody.result.length, 2);
- } finally {
- await stopMockServer();
- }
-});
-
-test("admin telegram reset clears state", async () => {
- const { port } = await startMockServer(18564, { retryIfInUse: true });
- const base = `http://127.0.0.1:${port}`;
-
- try {
- // Inject an update and a sent message
- await fetch(`${base}/__admin/telegram/inject-update`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ update_id: 999, message: { text: "pre-reset" } }),
- });
- await fetch(`${base}/botX/sendMessage`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ chat_id: 1, text: "pre-reset" }),
- });
-
- // Reset telegram state only
- const resetRes = await fetch(`${base}/__admin/telegram/reset`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- });
- const resetBody = await resetRes.json();
- assert.equal(resetBody.ok, true);
-
- // Sent should be empty now
- const sentRes = await fetch(`${base}/__admin/telegram/sent`);
- const sentBody = await sentRes.json();
- assert.deepEqual(sentBody.messages, []);
-
- // Queue should be empty (getUpdates returns [])
- const updatesRes = await fetch(`${base}/botX/getUpdates`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({}),
- });
- const updatesBody = await updatesRes.json();
- assert.deepEqual(updatesBody.result, []);
- } finally {
- await stopMockServer();
- }
-});
-
-test("global admin reset also clears telegram state", async () => {
- const { port } = await startMockServer(18565, { retryIfInUse: true });
- const base = `http://127.0.0.1:${port}`;
-
- try {
- await fetch(`${base}/botX/sendMessage`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ chat_id: 1, text: "before global reset" }),
- });
-
- // Global reset
- await fetch(`${base}/__admin/reset`, { method: "POST" });
-
- const sentRes = await fetch(`${base}/__admin/telegram/sent`);
- const sentBody = await sentRes.json();
- assert.deepEqual(sentBody.messages, []);
- } finally {
- await stopMockServer();
- }
-});
diff --git a/scripts/mock-api/routes/cron.mjs b/scripts/mock-api/routes/cron.mjs
deleted file mode 100644
index 65f2499474..0000000000
--- a/scripts/mock-api/routes/cron.mjs
+++ /dev/null
@@ -1,145 +0,0 @@
-import { json } from "../http.mjs";
-import {
- createMockId,
- fuzzyNumber,
- fuzzyPick,
- fuzzyTimestamp,
- getMockCronJobs,
- getMockWebhookTriggers,
-} from "../state.mjs";
-
-let fixturesSeeded = false;
-
-export function resetCronFixturesState() {
- fixturesSeeded = false;
-}
-
-function ensureCronFixtures() {
- if (fixturesSeeded) return;
- const cronJobs = getMockCronJobs();
- const webhookTriggers = getMockWebhookTriggers();
- if (cronJobs.length === 0) {
- const count = fuzzyNumber("cron:count", 0, 2);
- for (let i = 0; i < count; i += 1) {
- cronJobs.push({
- id: createMockId("cron"),
- name: fuzzyPick(
- `cron:name:${i}`,
- ["Morning digest", "Support sweep", "Usage snapshot"],
- "Mock cron job",
- ),
- schedule: fuzzyPick(
- `cron:schedule:${i}`,
- ["0 8 * * *", "*/30 * * * *", "15 17 * * 1-5"],
- "0 8 * * *",
- ),
- enabled: i % 2 === 0,
- createdAt: fuzzyTimestamp(`cron:created:${i}`),
- });
- }
- }
- if (webhookTriggers.length === 0) {
- const count = fuzzyNumber("trg:count", 0, 2);
- for (let i = 0; i < count; i += 1) {
- webhookTriggers.push({
- id: createMockId("trg"),
- name: fuzzyPick(
- `trg:name:${i}`,
- ["Github push", "Stripe paid", "CRM sync"],
- "Mock trigger",
- ),
- enabled: true,
- createdAt: fuzzyTimestamp(`trg:created:${i}`),
- });
- }
- }
- fixturesSeeded = true;
-}
-
-export function handleCron(ctx) {
- const { method, url, parsedBody, res } = ctx;
- ensureCronFixtures();
- const cronJobs = getMockCronJobs();
- const webhookTriggers = getMockWebhookTriggers();
-
- if (method === "GET" && /^\/settings\/cron-jobs\/?(\?.*)?$/.test(url)) {
- json(res, 200, { success: true, data: cronJobs });
- return true;
- }
- if (method === "POST" && /^\/settings\/cron-jobs\/?$/.test(url)) {
- const created = {
- ...(parsedBody || {}),
- id: createMockId("cron"),
- createdAt: new Date().toISOString(),
- };
- cronJobs.unshift(created);
- json(res, 200, {
- success: true,
- data: created,
- });
- return true;
- }
- const cronItem = url.match(/^\/settings\/cron-jobs\/([^/?]+)\/?(\?.*)?$/);
- if (cronItem && (method === "PATCH" || method === "DELETE")) {
- const index = cronJobs.findIndex((entry) => entry.id === cronItem[1]);
- if (index >= 0 && method === "PATCH") {
- const { id: _ignoredId, ...patch } = parsedBody || {};
- cronJobs[index] = {
- ...cronJobs[index],
- ...patch,
- };
- }
- if (index >= 0 && method === "DELETE") {
- cronJobs.splice(index, 1);
- }
- json(res, 200, {
- success: true,
- data: { id: cronItem[1], deleted: method === "DELETE" },
- });
- return true;
- }
-
- if (
- method === "GET" &&
- /^\/settings\/webhooks-triggers\/?(\?.*)?$/.test(url)
- ) {
- json(res, 200, { success: true, data: webhookTriggers });
- return true;
- }
- if (method === "POST" && /^\/settings\/webhooks-triggers\/?$/.test(url)) {
- const created = {
- ...(parsedBody || {}),
- id: createMockId("trg"),
- createdAt: new Date().toISOString(),
- };
- webhookTriggers.unshift(created);
- json(res, 200, {
- success: true,
- data: created,
- });
- return true;
- }
- const trgItem = url.match(
- /^\/settings\/webhooks-triggers\/([^/?]+)\/?(\?.*)?$/,
- );
- if (trgItem && (method === "PATCH" || method === "DELETE")) {
- const index = webhookTriggers.findIndex((entry) => entry.id === trgItem[1]);
- if (index >= 0 && method === "PATCH") {
- const { id: _ignoredId, ...patch } = parsedBody || {};
- webhookTriggers[index] = {
- ...webhookTriggers[index],
- ...patch,
- };
- }
- if (index >= 0 && method === "DELETE") {
- webhookTriggers.splice(index, 1);
- }
- json(res, 200, {
- success: true,
- data: { id: trgItem[1], deleted: method === "DELETE" },
- });
- return true;
- }
-
- return false;
-}
diff --git a/scripts/mock-api/routes/telegram.mjs b/scripts/mock-api/routes/telegram.mjs
deleted file mode 100644
index f6f357f5be..0000000000
--- a/scripts/mock-api/routes/telegram.mjs
+++ /dev/null
@@ -1,211 +0,0 @@
-/**
- * Mock Telegram Bot API route handler.
- *
- * Intercepts all requests matching `/bot<token>/<method>` and responds with
- * realistic Telegram Bot API shapes. Behaviour is driven by the mock behavior
- * keys documented below so E2E specs can configure failure modes without
- * changing code.
- *
- * Behavior keys:
- * telegramBotUsername - bot username returned by getMe (default: "e2e_test_bot")
- * telegramBotToken - expected bot token; if set, mismatches return 401
- * telegramPollDelayMs - delay before getUpdates returns (simulates long-poll)
- * telegramGetMeFails - if "1", getMe returns HTTP 401 Unauthorized
- * telegramSendFails - if "1", sendMessage returns HTTP 400 Bad Request
- */
-
-import { json } from "../http.mjs";
-import {
- behavior,
- drainMockTelegramUpdates,
- nextMockTelegramMessageId,
- recordMockTelegramSent,
- sleep,
-} from "../state.mjs";
-
-/** Extract the bot token and method name from a Telegram Bot API path. */
-const BOT_PATH_RE = /^\/bot([^/]+)\/([^/?]+)/;
-
-/**
- * Attempt to parse a Telegram Bot API path.
- * Returns `{ token, method }` or `null` if the path does not match.
- */
-function parseBotPath(url) {
- const m = BOT_PATH_RE.exec(url);
- if (!m) return null;
- return { token: m[1], method: m[2] };
-}
-
-/**
- * Main route handler. Returns `true` when the request was handled, `false`
- * when it should fall through to the next handler.
- */
-export async function handleTelegram(ctx) {
- const { url, parsedBody, res } = ctx;
-
- const parsed = parseBotPath(url);
- if (!parsed) return false;
-
- const { token, method } = parsed;
- const b = behavior();
-
- console.log(`[telegram-mock] ${method} token=${token.slice(0, 8)}...`);
-
- // Optional token validation — only enforced when behavior key is set.
- if (b.telegramBotToken && token !== b.telegramBotToken) {
- console.warn(
- `[telegram-mock] token mismatch: got ${token.slice(0, 8)}... expected ${b.telegramBotToken.slice(0, 8)}...`,
- );
- json(res, 401, {
- ok: false,
- error_code: 401,
- description: "Unauthorized",
- });
- return true;
- }
-
- switch (method) {
- case "getMe":
- return handleGetMe(res, b);
-
- case "getUpdates":
- return handleGetUpdates(res, b);
-
- case "sendMessage":
- return handleSendMessage(res, b, parsedBody);
-
- case "sendChatAction":
- return handleSimpleRecord(res, "sendChatAction", parsedBody);
-
- case "deleteWebhook":
- return handleSimpleRecord(res, "deleteWebhook", parsedBody);
-
- case "setMessageReaction":
- return handleSimpleRecord(res, "setMessageReaction", parsedBody);
-
- case "editMessageText":
- return handleSimpleRecord(res, "editMessageText", parsedBody);
-
- case "editMessageReplyMarkup":
- return handleSimpleRecord(res, "editMessageReplyMarkup", parsedBody);
-
- case "answerCallbackQuery":
- return handleSimpleRecord(res, "answerCallbackQuery", parsedBody);
-
- case "sendPhoto":
- case "sendDocument":
- case "sendVideo":
- case "sendAudio":
- case "sendVoice":
- case "sendAnimation":
- case "sendSticker": {
- // Multipart bodies are not parsed — just record the method and any JSON
- // keys we received (body may be null for multipart).
- const messageId = nextMockTelegramMessageId();
- recordMockTelegramSent({
- method,
- body: parsedBody ?? {},
- message_id: messageId,
- });
- console.log(
- `[telegram-mock] ${method} recorded message_id=${messageId}`,
- );
- json(res, 200, { ok: true, result: { message_id: messageId } });
- return true;
- }
-
- default:
- console.log(
- `[telegram-mock] unhandled method="${method}" — returning ok:true, result:null`,
- );
- json(res, 200, { ok: true, result: null });
- return true;
- }
-}
-
-// ── Individual method handlers ─────────────────────────────────────────────
-
-function handleGetMe(res, b) {
- if (b.telegramGetMeFails === "1") {
- console.warn("[telegram-mock] getMe failing per behavior.telegramGetMeFails");
- json(res, 401, {
- ok: false,
- error_code: 401,
- description: "Unauthorized",
- });
- return true;
- }
-
- const username = b.telegramBotUsername || "e2e_test_bot";
- console.log(`[telegram-mock] getMe -> username=${username}`);
- json(res, 200, {
- ok: true,
- result: {
- id: 123456789,
- is_bot: true,
- first_name: "E2E Bot",
- username,
- },
- });
- return true;
-}
-
-async function handleGetUpdates(res, b) {
- const delayMs = Math.min(
- Number(b.telegramPollDelayMs) || 50,
- 30_000,
- );
- if (Number.isFinite(delayMs) && delayMs > 0) {
- console.log(`[telegram-mock] getUpdates: waiting ${delayMs}ms before reply`);
- await sleep(delayMs);
- }
-
- const updates = drainMockTelegramUpdates();
- console.log(`[telegram-mock] getUpdates: returning ${updates.length} update(s)`);
- json(res, 200, { ok: true, result: updates });
- return true;
-}
-
-function handleSendMessage(res, b, body) {
- if (b.telegramSendFails === "1") {
- console.warn("[telegram-mock] sendMessage failing per behavior.telegramSendFails");
- json(res, 400, {
- ok: false,
- error_code: 400,
- description: "Bad Request",
- });
- return true;
- }
-
- const messageId = nextMockTelegramMessageId();
- const chatId = body?.chat_id ?? 0;
- const text = body?.text ?? "";
-
- recordMockTelegramSent({
- method: "sendMessage",
- body: body ?? {},
- message_id: messageId,
- });
-
- console.log(
- `[telegram-mock] sendMessage chat_id=${chatId} message_id=${messageId} text="${String(text).slice(0, 80)}"`,
- );
-
- json(res, 200, {
- ok: true,
- result: {
- message_id: messageId,
- date: Math.floor(Date.now() / 1000),
- chat: { id: chatId },
- text,
- },
- });
- return true;
-}
-
-function handleSimpleRecord(res, method, body) {
- recordMockTelegramSent({ method, body: body ?? {} });
- console.log(`[telegram-mock] ${method} recorded`);
- json(res, 200, { ok: true, result: true });
- return true;
-}
diff --git a/scripts/mock-api/server.mjs b/scripts/mock-api/server.mjs
index 00cefc2bef..446142c8d3 100644
--- a/scripts/mock-api/server.mjs
+++ b/scripts/mock-api/server.mjs
@@ -12,7 +12,6 @@ import {
import { handleAuth } from "./routes/auth.mjs";
import { handleAudio } from "./routes/audio.mjs";
import { handleConversations } from "./routes/conversations.mjs";
-import { handleCron } from "./routes/cron.mjs";
import { handleIntegrations } from "./routes/integrations.mjs";
import { handleInvites } from "./routes/invites.mjs";
import { handleLlmCompletions, handleModelListing } from "./routes/llm.mjs";
@@ -20,7 +19,6 @@ import { handleMedia } from "./routes/media.mjs";
import { handleMemory } from "./routes/memory.mjs";
import { handleOAuth } from "./routes/oauth.mjs";
import { handlePayments } from "./routes/payments.mjs";
-import { handleTelegram } from "./routes/telegram.mjs";
import { handleUser } from "./routes/user.mjs";
import { handleVersion } from "./routes/version.mjs";
import { handleWebhooks } from "./routes/webhooks.mjs";
@@ -42,9 +40,6 @@ let server = null;
// Order matters: admin & socket.io short-circuit early; the rest fall through
// in domain order so the cheapest predicates run first.
const ROUTE_HANDLERS = [
- // Telegram Bot API paths start with /bot<token>/… — check before the
- // general-purpose handlers so the distinctive prefix routes cleanly.
- handleTelegram,
handleYuanbao,
handleOAuth,
handleAuth,
@@ -63,7 +58,6 @@ const ROUTE_HANDLERS = [
handleMemory,
handleIntegrations,
handleWebhooks,
- handleCron,
handleConversations,
handleVersion,
];
diff --git a/scripts/mock-api/state.mjs b/scripts/mock-api/state.mjs
index a3650f1fc6..dd2eafdb7e 100644
--- a/scripts/mock-api/state.mjs
+++ b/scripts/mock-api/state.mjs
@@ -16,17 +16,11 @@ let mockBehavior = {};
let mockTunnels = [];
let mockConversations = [];
let mockMessages = [];
-let mockCronJobs = [];
let mockWebhookTriggers = [];
let socketEventLog = [];
let mockLlmThreads = new Map();
let nextSequence = 1;
-// ── Telegram Bot API mock state ────────────────────────────────────────────
-let mockTelegramUpdates = [];
-let mockTelegramSentMessages = [];
-let mockTelegramMessageIdSeq = 1000;
-
const socketSessions = new Map();
export const openSockets = new Set();
@@ -177,18 +171,6 @@ export function resetMockMessages() {
mockMessages = [];
}
-export function getMockCronJobs() {
- return mockCronJobs;
-}
-
-export function setMockCronJobs(next) {
- mockCronJobs = Array.isArray(next) ? next : [];
-}
-
-export function resetMockCronJobs() {
- mockCronJobs = [];
-}
-
export function getMockWebhookTriggers() {
return mockWebhookTriggers;
}
@@ -504,52 +486,3 @@ export function getMockTeam() {
};
}
-// ── Telegram Bot API mock state helpers ────────────────────────────────────
-
-/**
- * Push a single Telegram Update object into the pending queue.
- * The queue is drained by each `getUpdates` poll.
- */
-export function pushMockTelegramUpdate(update) {
- mockTelegramUpdates.push(update);
-}
-
-/**
- * Drain and return all pending Telegram updates. Each `getUpdates` call
- * should call this so each update is delivered exactly once.
- */
-export function drainMockTelegramUpdates() {
- const updates = [...mockTelegramUpdates];
- mockTelegramUpdates = [];
- return updates;
-}
-
-/**
- * Record a message sent by the bot (sendMessage, sendPhoto, etc.).
- * @param {object} entry - { method, body, message_id, ... }
- */
-export function recordMockTelegramSent(entry) {
- mockTelegramSentMessages.push({
- timestamp: new Date().toISOString(),
- ...entry,
- });
-}
-
-/** Return all recorded outbound Telegram API calls (non-destructive). */
-export function getMockTelegramSent() {
- return [...mockTelegramSentMessages];
-}
-
-/** Increment and return the next mock message_id. */
-export function nextMockTelegramMessageId() {
- const id = mockTelegramMessageIdSeq;
- mockTelegramMessageIdSeq += 1;
- return id;
-}
-
-/** Reset all Telegram mock state (updates queue, sent log, id counter). */
-export function resetMockTelegram() {
- mockTelegramUpdates = [];
- mockTelegramSentMessages = [];
- mockTelegramMessageIdSeq = 1000;
-}