WhatsApp: honor outbound mediaMaxMb (#38097)

* WhatsApp: add media cap helper

* WhatsApp: cap outbound media loads

* WhatsApp: align auto-reply media caps

* WhatsApp: add outbound media cap test

* WhatsApp: update auto-reply cap tests

* Docs: update WhatsApp media caps

* Changelog: note WhatsApp media cap fix
This commit is contained in:
Vincent Koc
2026-03-06 11:08:15 -05:00
committed by GitHub
parent 20038fb955
commit 222d635aee
7 changed files with 121 additions and 10 deletions

View File

@@ -199,6 +199,7 @@ Docs: https://docs.openclaw.ai
- Telegram/Discord media upload caps: make outbound uploads honor channel `mediaMaxMb` config, raise Telegram's default media cap to 100MB, and remove MIME fallback limits that kept some Telegram uploads at 16MB. Thanks @vincentkoc.
- Skills/nano-banana-pro resolution override: respect explicit `--resolution` values during image editing and only auto-detect output size from input images when the flag is omitted. (#36880) Thanks @shuofengzhang and @vincentkoc.
- Skills/openai-image-gen CLI validation: validate `--background` and `--style` inputs early, normalize supported values, and warn when those flags are ignored for incompatible models. (#36762) Thanks @shuofengzhang and @vincentkoc.
- WhatsApp media upload caps: make outbound media sends and auto-replies honor `channels.whatsapp.mediaMaxMb` with per-account overrides so inbound and outbound limits use the same channel config. Thanks @vincentkoc.
## 2026.3.2

View File

@@ -308,7 +308,8 @@ When the linked self number is also present in `allowFrom`, WhatsApp self-chat s
<Accordion title="Media size limits and fallback behavior">
- inbound media save cap: `channels.whatsapp.mediaMaxMb` (default `50`)
- outbound media cap for auto-replies: `agents.defaults.mediaMaxMb` (default `5MB`)
- outbound media send cap: `channels.whatsapp.mediaMaxMb` (default `50`)
- per-account overrides use `channels.whatsapp.accounts.<accountId>.mediaMaxMb`
- images are auto-optimized (resize/quality sweep) to fit limits
- on media send failure, first-item fallback sends text warning instead of dropping the response silently
</Accordion>

View File

@@ -31,6 +31,8 @@ export type ResolvedWhatsAppAccount = {
debounceMs?: number;
};
export const DEFAULT_WHATSAPP_MEDIA_MAX_MB = 50;
const { listConfiguredAccountIds, listAccountIds, resolveDefaultAccountId } =
createAccountListHelpers("whatsapp");
export const listWhatsAppAccountIds = listAccountIds;
@@ -147,6 +149,16 @@ export function resolveWhatsAppAccount(params: {
};
}
export function resolveWhatsAppMediaMaxBytes(
account: Pick<ResolvedWhatsAppAccount, "mediaMaxMb">,
): number {
const mediaMaxMb =
typeof account.mediaMaxMb === "number" && account.mediaMaxMb > 0
? account.mediaMaxMb
: DEFAULT_WHATSAPP_MEDIA_MAX_MB;
return mediaMaxMb * 1024 * 1024;
}
export function listEnabledWhatsAppAccounts(cfg: OpenClawConfig): ResolvedWhatsAppAccount[] {
return listWhatsAppAccountIds(cfg)
.map((accountId) => resolveWhatsAppAccount({ cfg, accountId }))

View File

@@ -73,7 +73,14 @@ describe("web auto-reply", () => {
}
async function withMediaCap<T>(mediaMaxMb: number, run: () => Promise<T>): Promise<T> {
setLoadConfigMock(() => ({ agents: { defaults: { mediaMaxMb } } }));
setLoadConfigMock(() => ({
channels: {
whatsapp: {
allowFrom: ["*"],
mediaMaxMb,
},
},
}));
try {
return await run();
} finally {
@@ -215,7 +222,7 @@ describe("web auto-reply", () => {
});
});
it("honors mediaMaxMb from config", async () => {
it("honors channels.whatsapp.mediaMaxMb for outbound auto-replies", async () => {
const bigPng = await sharp({
create: {
width: 256,
@@ -235,6 +242,53 @@ describe("web auto-reply", () => {
mediaMaxMb: SMALL_MEDIA_CAP_MB,
});
});
it("prefers per-account WhatsApp media caps for outbound auto-replies", async () => {
const bigPng = await sharp({
create: {
width: 256,
height: 256,
channels: 3,
background: { r: 255, g: 0, b: 0 },
},
})
.png({ compressionLevel: 0 })
.toBuffer();
expect(bigPng.length).toBeGreaterThan(SMALL_MEDIA_CAP_BYTES);
setLoadConfigMock(() => ({
channels: {
whatsapp: {
allowFrom: ["*"],
mediaMaxMb: 1,
accounts: {
work: {
mediaMaxMb: SMALL_MEDIA_CAP_MB,
},
},
},
},
}));
try {
const sendMedia = vi.fn();
const { reply, dispatch } = await setupSingleInboundMessage({
resolverValue: { text: "hi", mediaUrl: "https://example.com/account-big.png" },
sendMedia,
});
const fetchMock = mockFetchMediaBuffer(bigPng, "image/png");
await dispatch("msg-account-cap", { accountId: "work" });
const payload = getSingleImagePayload(sendMedia);
expect(payload.image.length).toBeLessThanOrEqual(SMALL_MEDIA_CAP_BYTES);
expect(payload.mimetype).toBe("image/jpeg");
expect(reply).not.toHaveBeenCalled();
fetchMock.mockRestore();
} finally {
resetLoadConfigMock();
}
});
it("falls back to text when media is unsupported", async () => {
const sendMedia = vi.fn();
const { reply, dispatch } = await setupSingleInboundMessage({

View File

@@ -12,7 +12,7 @@ import { registerUnhandledRejectionHandler } from "../../infra/unhandled-rejecti
import { getChildLogger } from "../../logging.js";
import { resolveAgentRoute } from "../../routing/resolve-route.js";
import { defaultRuntime, type RuntimeEnv } from "../../runtime.js";
import { resolveWhatsAppAccount } from "../accounts.js";
import { resolveWhatsAppAccount, resolveWhatsAppMediaMaxBytes } from "../accounts.js";
import { setActiveWebListener } from "../active-listener.js";
import { monitorWebInbox } from "../inbound.js";
import {
@@ -23,7 +23,6 @@ import {
sleepWithAbort,
} from "../reconnect.js";
import { formatError, getWebAuthAgeMs, readWebSelfId } from "../session.js";
import { DEFAULT_WEB_MEDIA_BYTES } from "./constants.js";
import { whatsappHeartbeatLog, whatsappLog } from "./loggers.js";
import { buildMentionConfig } from "./mentions.js";
import { createEchoTracker } from "./monitor/echo.js";
@@ -93,11 +92,7 @@ export async function monitorWebChannel(
},
} satisfies ReturnType<typeof loadConfig>;
const configuredMaxMb = cfg.agents?.defaults?.mediaMaxMb;
const maxMediaBytes =
typeof configuredMaxMb === "number" && configuredMaxMb > 0
? configuredMaxMb * 1024 * 1024
: DEFAULT_WEB_MEDIA_BYTES;
const maxMediaBytes = resolveWhatsAppMediaMaxBytes(account);
const heartbeatSeconds = resolveHeartbeatSeconds(cfg, tuning.heartbeatSeconds);
const reconnectPolicy = resolveReconnectPolicy(cfg, tuning.reconnect);
const baseMentionConfig = buildMentionConfig(cfg);

View File

@@ -3,6 +3,7 @@ import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { OpenClawConfig } from "../config/config.js";
import { resetLogger, setLoggerOverride } from "../logging.js";
import { redactIdentifier } from "../logging/redact-identifier.js";
import { setActiveWebListener } from "./active-listener.js";
@@ -34,6 +35,7 @@ describe("web outbound", () => {
resetLogger();
setLoggerOverride(null);
setActiveWebListener(null);
setActiveWebListener("work", null);
});
it("sends message via active listener", async () => {
@@ -140,6 +142,46 @@ describe("web outbound", () => {
});
});
it("uses account-aware WhatsApp media caps for outbound uploads", async () => {
setActiveWebListener("work", {
sendComposingTo,
sendMessage,
sendPoll,
sendReaction,
});
loadWebMediaMock.mockResolvedValueOnce({
buffer: Buffer.from("img"),
contentType: "image/jpeg",
kind: "image",
});
const cfg = {
channels: {
whatsapp: {
mediaMaxMb: 25,
accounts: {
work: {
mediaMaxMb: 100,
},
},
},
},
} as OpenClawConfig;
await sendMessageWhatsApp("+1555", "pic", {
verbose: false,
accountId: "work",
cfg,
mediaUrl: "/tmp/pic.jpg",
mediaLocalRoots: ["/tmp/workspace"],
});
expect(loadWebMediaMock).toHaveBeenCalledWith("/tmp/pic.jpg", {
maxBytes: 100 * 1024 * 1024,
localRoots: ["/tmp/workspace"],
});
});
it("sends polls via active listener", async () => {
const result = await sendPollWhatsApp(
"+1555",

View File

@@ -8,6 +8,7 @@ import { convertMarkdownTables } from "../markdown/tables.js";
import { markdownToWhatsApp } from "../markdown/whatsapp.js";
import { normalizePollInput, type PollInput } from "../polls.js";
import { toWhatsappJid } from "../utils.js";
import { resolveWhatsAppAccount, resolveWhatsAppMediaMaxBytes } from "./accounts.js";
import { type ActiveWebSendOptions, requireActiveWebListener } from "./active-listener.js";
import { loadWebMedia } from "./media.js";
@@ -32,6 +33,10 @@ export async function sendMessageWhatsApp(
options.accountId,
);
const cfg = options.cfg ?? loadConfig();
const account = resolveWhatsAppAccount({
cfg,
accountId: resolvedAccountId ?? options.accountId,
});
const tableMode = resolveMarkdownTableMode({
cfg,
channel: "whatsapp",
@@ -53,6 +58,7 @@ export async function sendMessageWhatsApp(
let documentFileName: string | undefined;
if (options.mediaUrl) {
const media = await loadWebMedia(options.mediaUrl, {
maxBytes: resolveWhatsAppMediaMaxBytes(account),
localRoots: options.mediaLocalRoots,
});
const caption = text || undefined;