Files
adolf/extensions/telegram/src/network-errors.test.ts
alvis bedb527145
Some checks failed
ClawSweeper Dispatch / dispatch (push) Has been cancelled
CodeQL / Security High (actions) (push) Has been cancelled
CodeQL / Security High (channel-runtime-boundary) (push) Has been cancelled
CodeQL / Security High (core-auth-secrets) (push) Has been cancelled
CodeQL / Security High (mcp-process-tool-boundary) (push) Has been cancelled
CodeQL / Security High (network-ssrf-boundary) (push) Has been cancelled
CodeQL / Security High (plugin-trust-boundary) (push) Has been cancelled
CodeQL / Security High (process-exec-boundary) (push) Has been cancelled
Docs Sync Publish Repo / sync-publish-repo (push) Has been cancelled
Docs / docs (push) Has been cancelled
OpenClaw Stable Main Closeout / Resolve stable release closeout inputs (push) Has been cancelled
OpenClaw Stable Main Closeout / Verify stable main closeout (push) Has been cancelled
Workflow Sanity / no-tabs (push) Has been cancelled
Workflow Sanity / actionlint (push) Has been cancelled
Workflow Sanity / generated-doc-baselines (push) Has been cancelled
CI / runner-admission (push) Has been cancelled
CI / preflight (push) Has been cancelled
CI / security-fast (push) Has been cancelled
CI / pnpm-store-warmup (push) Has been cancelled
CI / build-artifacts (push) Has been cancelled
CI / native-i18n (push) Has been cancelled
CI / ${{ matrix.check_name }} (push) Has been cancelled
CI / ${{ matrix.checkName }} (push) Has been cancelled
CI / checks-node-compat-node22 (push) Has been cancelled
CI / check-bundled-channel-config-metadata (push) Has been cancelled
CI / check-dependencies (push) Has been cancelled
CI / check-guards (push) Has been cancelled
CI / check-lint (push) Has been cancelled
CI / check-prod-types (push) Has been cancelled
CI / check-shrinkwrap (push) Has been cancelled
CI / check-test-types (push) Has been cancelled
CI / check-additional-boundaries-a (push) Has been cancelled
CI / check-additional-boundaries-bcd (push) Has been cancelled
CI / check-additional-extension-bundled (push) Has been cancelled
CI / check-additional-extension-channels (push) Has been cancelled
CI / check-additional-extension-package-boundary (push) Has been cancelled
CI / check-additional-runtime-topology-architecture (push) Has been cancelled
CI / check-session-accessor-boundary (push) Has been cancelled
CI / check-session-transcript-reader-boundary (push) Has been cancelled
CI / check-docs (push) Has been cancelled
CI / skills-python (push) Has been cancelled
CI / macos-swift (push) Has been cancelled
CI / ios-build (push) Has been cancelled
CI / ci-timings-summary (push) Has been cancelled
Native App Locale Refresh / Refresh native fa (push) Has been cancelled
Native App Locale Refresh / Refresh native fr (push) Has been cancelled
Native App Locale Refresh / Refresh native hi (push) Has been cancelled
Native App Locale Refresh / Refresh native id (push) Has been cancelled
Native App Locale Refresh / Refresh native it (push) Has been cancelled
Native App Locale Refresh / Refresh native ja-JP (push) Has been cancelled
Control UI Locale Refresh / plan (push) Has been cancelled
Control UI Locale Refresh / Refresh ${{ matrix.locale }} (push) Has been cancelled
Control UI Locale Refresh / Commit control UI locale refresh (push) Has been cancelled
Live Media Runner Image / Build live media runner image (push) Has been cancelled
Native App Locale Refresh / Refresh native ar (push) Has been cancelled
Native App Locale Refresh / Refresh native de (push) Has been cancelled
Native App Locale Refresh / Refresh native es (push) Has been cancelled
Native App Locale Refresh / Refresh native ko (push) Has been cancelled
Native App Locale Refresh / Refresh native nl (push) Has been cancelled
Native App Locale Refresh / Refresh native pl (push) Has been cancelled
Native App Locale Refresh / Refresh native pt-BR (push) Has been cancelled
Native App Locale Refresh / Refresh native ru (push) Has been cancelled
Native App Locale Refresh / Refresh native sv (push) Has been cancelled
Native App Locale Refresh / Refresh native th (push) Has been cancelled
Native App Locale Refresh / Refresh native tr (push) Has been cancelled
Native App Locale Refresh / Refresh native uk (push) Has been cancelled
Native App Locale Refresh / Refresh native vi (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-CN (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-TW (push) Has been cancelled
Native App Locale Refresh / Commit native locale refresh (push) Has been cancelled
Plugin Init Scaffold Validation / Validate provider scaffold (push) Has been cancelled
Plugin NPM Release / preview_plugins_npm (push) Has been cancelled
Plugin NPM Release / Validate release publish approval (push) Has been cancelled
Plugin NPM Release / preview_plugin_pack (push) Has been cancelled
Plugin NPM Release / publish_plugins_npm (push) Has been cancelled
Sandbox Common Smoke / sandbox-common-smoke (push) Has been cancelled
Website Installer Sync / static (push) Has been cancelled
Website Installer Sync / linux-docker (push) Has been cancelled
Website Installer Sync / macos-installer (push) Has been cancelled
Website Installer Sync / windows-installer (push) Has been cancelled
Website Installer Sync / sync-website (push) Has been cancelled
Vendor OpenClaw source as Adolf fork baseline
Adolf is a fork/vendored clone of github.com/openclaw/openclaw (v2026.6.11),
free to diverge. Tree copied sans upstream .git; upstream remote added for
future syncs. Node pinned to 24 (.nvmrc); engines already require >=22.19.
Preserves docs/ARCHITECTURE.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LeqyaxJF2nbRXJtae2kNB2
2026-07-05 09:36:54 +00:00

348 lines
13 KiB
TypeScript

// Telegram tests cover network errors plugin behavior.
import { describe, expect, it } from "vitest";
import {
getTelegramNetworkErrorOrigin,
isRecoverableTelegramNetworkError,
isRetryableTelegramApiError,
isTelegramRateLimitError,
isSafeToRetrySendError,
isTelegramClientRejection,
isTelegramPollingNetworkError,
isTelegramServerError,
tagTelegramNetworkError,
} from "./network-errors.js";
const errorWithCode = (message: string, code: string) =>
Object.assign(new Error(message), { code });
const errorWithTelegramCode = (message: string, error_code: number) =>
Object.assign(new Error(message), { error_code });
const plainErrorPredicateCases = [
{
name: "isTelegramServerError",
predicate: isTelegramServerError,
error: new Error("500: Internal Server Error"),
},
{
name: "isTelegramClientRejection",
predicate: isTelegramClientRejection,
error: new Error("400: Bad Request"),
},
];
const nestedErrorCodePredicateCases = [
{
name: "isTelegramRateLimitError",
predicate: isTelegramRateLimitError,
inner: Object.assign(new Error("Too Many Requests"), { error_code: 429 }),
},
{
name: "isTelegramClientRejection",
predicate: isTelegramClientRejection,
inner: Object.assign(new Error("Forbidden"), { error_code: 403 }),
},
];
describe("Telegram error_code predicate contracts", () => {
it.each(plainErrorPredicateCases)(
"$name returns false for plain Error",
({ error, predicate }) => {
expect(predicate(error)).toBe(false);
},
);
it.each(nestedErrorCodePredicateCases)(
"$name detects error_code in nested cause",
({ inner, predicate }) => {
const outer = Object.assign(new Error("wrapped"), { cause: inner });
expect(predicate(outer)).toBe(true);
},
);
});
describe("isRecoverableTelegramNetworkError", () => {
it("tracks Telegram polling origin separately from generic network matching", () => {
const slackDnsError = Object.assign(
new Error("A request error occurred: getaddrinfo ENOTFOUND slack.com"),
{
code: "ENOTFOUND",
hostname: "slack.com",
},
);
expect(isRecoverableTelegramNetworkError(slackDnsError)).toBe(true);
expect(isTelegramPollingNetworkError(slackDnsError)).toBe(false);
tagTelegramNetworkError(slackDnsError, {
method: "getUpdates",
url: "https://api.telegram.org/bot123456:ABC/getUpdates",
});
expect(getTelegramNetworkErrorOrigin(slackDnsError)).toEqual({
method: "getupdates",
url: "https://api.telegram.org/bot123456:ABC/getUpdates",
});
expect(isTelegramPollingNetworkError(slackDnsError)).toBe(true);
});
it.each([
["ETIMEDOUT", "timeout"],
["ENETDOWN", "network down"],
["ECONNABORTED", "aborted"],
["ERR_NETWORK", "network"],
])("detects recoverable error code %s", (code, message) => {
expect(isRecoverableTelegramNetworkError(errorWithCode(message, code))).toBe(true);
});
it("detects AbortError names", () => {
const err = Object.assign(new Error("The operation was aborted"), { name: "AbortError" });
expect(isRecoverableTelegramNetworkError(err)).toBe(true);
});
it("detects nested causes", () => {
const cause = Object.assign(new Error("socket hang up"), { code: "ECONNRESET" });
const err = Object.assign(new TypeError("fetch failed"), { cause });
expect(isRecoverableTelegramNetworkError(err)).toBe(true);
});
it("detects expanded message patterns", () => {
expect(isRecoverableTelegramNetworkError(new Error("TypeError: fetch failed"))).toBe(true);
expect(isRecoverableTelegramNetworkError(new Error("Undici: socket failure"))).toBe(true);
});
it("treats undici fetch failed errors as recoverable in send context", () => {
const err = new TypeError("fetch failed");
expect(isRecoverableTelegramNetworkError(err, { context: "send" })).toBe(true);
expect(
isRecoverableTelegramNetworkError(new Error("TypeError: fetch failed"), { context: "send" }),
).toBe(true);
expect(isRecoverableTelegramNetworkError(err, { context: "polling" })).toBe(true);
});
it("honors allowMessageMatch=false for broad snippet matches", () => {
expect(
isRecoverableTelegramNetworkError(new Error("Undici: socket failure"), {
allowMessageMatch: false,
}),
).toBe(false);
expect(
isRecoverableTelegramNetworkError(new Error("TypeError: fetch failed"), {
allowMessageMatch: false,
}),
).toBe(true);
});
it("skips broad message matches for send context", () => {
const networkRequestErr = new Error("Network request for 'sendMessage' failed!");
expect(isRecoverableTelegramNetworkError(networkRequestErr, { context: "send" })).toBe(false);
expect(isRecoverableTelegramNetworkError(networkRequestErr, { context: "polling" })).toBe(true);
const undiciSnippetErr = new Error("Undici: socket failure");
expect(isRecoverableTelegramNetworkError(undiciSnippetErr, { context: "send" })).toBe(false);
expect(isRecoverableTelegramNetworkError(undiciSnippetErr, { context: "polling" })).toBe(true);
});
it("treats delete/react (idempotent) contexts like polling, not send", () => {
const undiciSnippetErr = new Error("Undici: socket failure");
// delete and react are idempotent Telegram operations; a transient
// snippet-only error must be retried (allowMessageMatch defaults true),
// matching polling/webhook. send stays strict as the regression guard.
expect(isRecoverableTelegramNetworkError(undiciSnippetErr, { context: "delete" })).toBe(true);
expect(isRecoverableTelegramNetworkError(undiciSnippetErr, { context: "react" })).toBe(true);
expect(isRecoverableTelegramNetworkError(undiciSnippetErr, { context: "send" })).toBe(false);
});
it("treats grammY failed-after envelope errors as recoverable in send context", () => {
expect(
isRecoverableTelegramNetworkError(
new Error("Network request for 'sendMessage' failed after 2 attempts."),
{ context: "send" },
),
).toBe(true);
});
it("returns false for unrelated errors", () => {
expect(isRecoverableTelegramNetworkError(new Error("invalid token"))).toBe(false);
});
it("detects grammY 'timed out' long-poll errors (#7239)", () => {
const err = new Error("Request to 'getUpdates' timed out after 500 seconds");
expect(isRecoverableTelegramNetworkError(err)).toBe(true);
});
it("normalizes blank tagged origins to null and finds nested tags", () => {
const inner = new Error("inner");
tagTelegramNetworkError(inner, { method: " ", url: " " });
const outer = Object.assign(new Error("outer"), { cause: inner });
expect(getTelegramNetworkErrorOrigin(outer)).toEqual({ method: null, url: null });
expect(isTelegramPollingNetworkError(outer)).toBe(false);
});
// Grammy HttpError tests (issue #3815)
// Grammy wraps fetch errors in .error property, not .cause
describe("Grammy HttpError", () => {
class MockHttpError extends Error {
constructor(
message: string,
public readonly error: unknown,
) {
super(message);
this.name = "HttpError";
}
}
it("detects network error wrapped in HttpError", () => {
const fetchError = new TypeError("fetch failed");
const httpError = new MockHttpError(
"Network request for 'setMyCommands' failed!",
fetchError,
);
expect(isRecoverableTelegramNetworkError(httpError)).toBe(true);
});
it("detects network error with cause wrapped in HttpError", () => {
const cause = Object.assign(new Error("socket hang up"), { code: "ECONNRESET" });
const fetchError = Object.assign(new TypeError("fetch failed"), { cause });
const httpError = new MockHttpError("Network request for 'getUpdates' failed!", fetchError);
expect(isRecoverableTelegramNetworkError(httpError)).toBe(true);
});
it("returns false for non-network errors wrapped in HttpError", () => {
const authError = new Error("Unauthorized: bot token is invalid");
const httpError = new MockHttpError("Bad Request: invalid token", authError);
expect(isRecoverableTelegramNetworkError(httpError)).toBe(false);
});
});
});
describe("isSafeToRetrySendError", () => {
class MockHttpError extends Error {
constructor(
message: string,
public readonly error: unknown,
) {
super(message);
this.name = "HttpError";
}
}
it.each([
["ECONNREFUSED", "connect ECONNREFUSED", true],
["ENOTFOUND", "getaddrinfo ENOTFOUND", true],
["EAI_AGAIN", "getaddrinfo EAI_AGAIN", true],
["ENETDOWN", "connect ENETDOWN", true],
["ENETUNREACH", "connect ENETUNREACH", true],
["EHOSTUNREACH", "connect EHOSTUNREACH", true],
["ECONNRESET", "read ECONNRESET", false],
["ETIMEDOUT", "connect ETIMEDOUT", false],
["EPIPE", "write EPIPE", false],
["UND_ERR_CONNECT_TIMEOUT", "connect timeout", false],
])("returns %s => %s", (code, message, expected) => {
expect(isSafeToRetrySendError(errorWithCode(message, code))).toBe(expected);
});
it("does NOT allow retry for non-network errors", () => {
expect(isSafeToRetrySendError(new Error("400: Bad Request"))).toBe(false);
expect(isSafeToRetrySendError(null)).toBe(false);
});
it("detects pre-connect error nested in cause chain", () => {
const root = Object.assign(new Error("ECONNREFUSED"), { code: "ECONNREFUSED" });
const wrapped = Object.assign(new Error("fetch failed"), { cause: root });
expect(isSafeToRetrySendError(wrapped)).toBe(true);
});
it("detects pre-connect error wrapped in grammY HttpError", () => {
const root = Object.assign(new Error("connect ECONNREFUSED"), { code: "ECONNREFUSED" });
const fetchError = Object.assign(new TypeError("fetch failed"), { cause: root });
const wrapped = new MockHttpError("Network request for 'sendMessage' failed!", fetchError);
expect(isSafeToRetrySendError(wrapped)).toBe(true);
});
it("does not infer safe send retry from a plain grammY network envelope", () => {
const wrapped = new MockHttpError(
"Network request for 'sendMessage' failed!",
new TypeError("fetch failed"),
);
expect(isSafeToRetrySendError(wrapped)).toBe(false);
});
it.each([
["status", Object.assign(new Error("Misdirected Request"), { status: 421 })],
["statusCode", Object.assign(new Error("Misdirected Request"), { statusCode: "421" })],
["error_code", errorWithTelegramCode("Misdirected Request", 421)],
["message", new Error("421 Misdirected Request")],
[
"nested cause",
Object.assign(new Error("Network request for 'sendMessage' failed!"), {
cause: Object.assign(new Error("Misdirected Request"), { status: 421 }),
}),
],
[
"grammY HttpError",
new MockHttpError(
"Network request for 'sendMessage' failed!",
Object.assign(new Error("Misdirected Request"), { status: 421 }),
),
],
])("treats Telegram 421 Misdirected Request as safe to retry via %s", (_name, err) => {
expect(isSafeToRetrySendError(err)).toBe(true);
});
it("does not parse malformed status strings as Telegram 421", () => {
expect(
isSafeToRetrySendError(
Object.assign(new Error("Misdirected Request"), { statusCode: "421abc" }),
),
).toBe(false);
});
});
describe("isTelegramServerError", () => {
it.each([
["Internal Server Error", 500, true],
["Bad Gateway", 502, true],
["Forbidden", 403, false],
])("returns %s for error_code %s", (message, errorCode, expected) => {
expect(isTelegramServerError(errorWithTelegramCode(message, errorCode))).toBe(expected);
});
});
describe("isTelegramRateLimitError", () => {
it("returns true for Telegram 429 errors", () => {
expect(isTelegramRateLimitError(errorWithTelegramCode("Too Many Requests", 429))).toBe(true);
});
it("detects wrapped 429 retry_after errors without error_code", () => {
const wrapped = {
message: "429 Too Many Requests",
response: { parameters: { retry_after: 1 } },
};
expect(isTelegramRateLimitError(wrapped)).toBe(true);
});
});
describe("isRetryableTelegramApiError", () => {
it.each([
["Too Many Requests", 429, true],
["Internal Server Error", 500, true],
["Bad Gateway", 502, true],
["Conflict", 409, false],
["Unauthorized", 401, false],
["Not Found", 404, false],
])("returns %s for error_code %s", (message, errorCode, expected) => {
expect(isRetryableTelegramApiError(errorWithTelegramCode(message, errorCode))).toBe(expected);
});
});
describe("isTelegramClientRejection", () => {
it.each([
["Bad Request", 400, true],
["Forbidden", 403, true],
["Bad Gateway", 502, false],
])("returns %s for error_code %s", (message, errorCode, expected) => {
expect(isTelegramClientRejection(errorWithTelegramCode(message, errorCode))).toBe(expected);
});
});