Skip to content

Commit c868805

Browse files
clawsweeper[bot]Peter Steinberger
andauthored
fix(whatsapp): log terminal inbound media failures (#117717)
* fix(whatsapp): log terminal inbound media failures * fix(whatsapp): log terminal inbound media failures * fix(whatsapp): surface media enrichment failures * test(whatsapp): preserve caught media errors --------- Co-authored-by: clawsweeper <274271284+clawsweeper[bot]@users.noreply.github.com> Co-authored-by: Peter Steinberger <[email protected]>
1 parent d6aafb3 commit c868805

2 files changed

Lines changed: 235 additions & 1 deletion

File tree

‎extensions/whatsapp/src/inbound.media.test.ts‎

Lines changed: 171 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ const readAllowFromStoreMock = vi.fn().mockResolvedValue([]);
6969
const upsertPairingRequestMock = vi.fn().mockResolvedValue({ code: "PAIRCODE", created: true });
7070
const saveMediaStreamSpy = vi.fn();
7171
const downloadMediaMessageMock = vi.hoisted(() => vi.fn());
72+
const observedConsoleWarnings = vi.hoisted(() => vi.fn());
7273
let currentMockSocket:
7374
| {
7475
ev: import("node:events").EventEmitter;
@@ -83,6 +84,33 @@ let currentMockSocket:
8384
}
8485
| undefined;
8586

87+
vi.mock("openclaw/plugin-sdk/logging-core", async () => {
88+
const actual = await vi.importActual<typeof import("openclaw/plugin-sdk/logging-core")>(
89+
"openclaw/plugin-sdk/logging-core",
90+
);
91+
function observeConsoleWarnings(
92+
logger: ReturnType<typeof actual.createSubsystemLogger>,
93+
): ReturnType<typeof actual.createSubsystemLogger> {
94+
return {
95+
...logger,
96+
warn(message, meta) {
97+
if (logger.isEnabled("warn", "console")) {
98+
observedConsoleWarnings(message, meta);
99+
}
100+
logger.warn(message, meta);
101+
},
102+
child(name) {
103+
return observeConsoleWarnings(logger.child(name));
104+
},
105+
};
106+
}
107+
return {
108+
...actual,
109+
createSubsystemLogger: (subsystem: string) =>
110+
observeConsoleWarnings(actual.createSubsystemLogger(subsystem)),
111+
};
112+
});
113+
86114
vi.mock("openclaw/plugin-sdk/runtime-config-snapshot", async () => {
87115
const actual = await vi.importActual<
88116
typeof import("openclaw/plugin-sdk/runtime-config-snapshot")
@@ -226,6 +254,10 @@ vi.mock("./session.js", async () => {
226254
let monitorWebInbox: typeof import("./inbound.js").monitorWebInbox;
227255
let resetWebInboundDedupe: typeof import("./inbound.js").resetWebInboundDedupe;
228256
let createWaSocket: typeof import("./session.js").createWaSocket;
257+
let resetLogger: typeof import("openclaw/plugin-sdk/runtime-env").resetLogger;
258+
let setLoggerOverride: typeof import("openclaw/plugin-sdk/runtime-env").setLoggerOverride;
259+
260+
const LOG_PATH = path.join(os.tmpdir(), `openclaw-inbound-media-${crypto.randomUUID()}.log`);
229261

230262
async function waitForMessage(onMessage: ReturnType<typeof vi.fn>) {
231263
await vi.waitFor(() => expect(onMessage).toHaveBeenCalledTimes(1), {
@@ -250,6 +282,45 @@ function requireMediaPath(value: unknown): string {
250282
return value;
251283
}
252284

285+
async function waitForLogLine(messageId: string): Promise<string> {
286+
let matchingLine = "";
287+
await vi.waitFor(
288+
async () => {
289+
const content = await fs.readFile(LOG_PATH, "utf8").catch(() => "");
290+
matchingLine =
291+
content
292+
.split("\n")
293+
.find(
294+
(line) =>
295+
line.includes("WhatsApp inbound media materialization failed") &&
296+
line.includes(messageId),
297+
) ?? "";
298+
expect(matchingLine).not.toBe("");
299+
},
300+
{ timeout: 2_000, interval: 5 },
301+
);
302+
return matchingLine;
303+
}
304+
305+
async function createBaileysMediaHttpError(statusCode: number, details: string): Promise<Error> {
306+
const fetchSpy = vi
307+
.spyOn(globalThis, "fetch")
308+
.mockResolvedValueOnce(new Response(null, { status: statusCode }));
309+
try {
310+
const { getHttpStream } = await vi.importActual<typeof import("baileys")>("baileys");
311+
await getHttpStream("https://media.example/private");
312+
} catch (error) {
313+
if (!(error instanceof Error)) {
314+
throw new Error("expected Baileys to reject media downloads with an Error", { cause: error });
315+
}
316+
error.message = `${error.message} ${details}`;
317+
return error;
318+
} finally {
319+
fetchSpy.mockRestore();
320+
}
321+
throw new Error("expected Baileys to reject the failed media response");
322+
}
323+
253324
describe("web inbound media saves with extension", () => {
254325
async function getMockSocket() {
255326
return (await createWaSocket(false, false)) as unknown as {
@@ -261,17 +332,23 @@ describe("web inbound media saves with extension", () => {
261332
vi.useRealTimers();
262333
currentMockSocket = undefined;
263334
downloadMediaMessageMock.mockClear();
335+
observedConsoleWarnings.mockClear();
264336
saveMediaStreamSpy.mockClear();
265337
resetWebInboundDedupe();
266338
});
267339

268340
beforeAll(async () => {
269341
await fs.rm(HOME, { recursive: true, force: true });
342+
({ resetLogger, setLoggerOverride } = await import("openclaw/plugin-sdk/runtime-env"));
343+
setLoggerOverride({ level: "trace", consoleLevel: "info", file: LOG_PATH });
270344
({ monitorWebInbox, resetWebInboundDedupe } = await import("./inbound.js"));
271345
({ createWaSocket } = await import("./session.js"));
272346
});
273347

274348
afterAll(async () => {
349+
resetLogger();
350+
setLoggerOverride(null);
351+
await fs.rm(LOG_PATH, { force: true });
275352
await fs.rm(HOME, { recursive: true, force: true });
276353
if (ORIGINAL_HOME === undefined) {
277354
delete process.env.HOME;
@@ -557,7 +634,12 @@ describe("web inbound media saves with extension", () => {
557634
});
558635

559636
it("keeps a failed image fact with an unavailable notice", async () => {
560-
downloadMediaMessageMock.mockRejectedValueOnce(new Error("expired media reference"));
637+
downloadMediaMessageMock.mockRejectedValueOnce(
638+
await createBaileysMediaHttpError(
639+
410,
640+
"expired media reference +15551234567 [email protected] [email protected] [email protected]",
641+
),
642+
);
561643
const onMessage = vi.fn();
562644
const listener = await monitorWebInbox({
563645
cfg: {
@@ -596,6 +678,94 @@ describe("web inbound media saves with extension", () => {
596678
type: "media",
597679
payload: { contentType: "image/jpeg", kind: "image" },
598680
});
681+
const diagnostic = await waitForLogLine("img-failed");
682+
expect(diagnostic).toContain('"channel":"whatsapp"');
683+
expect(diagnostic).toContain('"mediaKind":"image"');
684+
expect(diagnostic).toContain('"mimeType":"image/jpeg"');
685+
expect(diagnostic).toContain('"failureStage":"direct"');
686+
expect(diagnostic).toContain('"errorClass":"Error"');
687+
expect(diagnostic).toContain('"statusCode":410');
688+
expect(diagnostic).toContain("expired media reference");
689+
expect(diagnostic).toContain("[redacted-url]");
690+
expect(diagnostic).toContain("[redacted-phone]");
691+
expect(diagnostic).toContain("[redacted-jid]");
692+
expect(diagnostic).not.toContain("media.example/private");
693+
expect(diagnostic).not.toContain("+15551234567");
694+
expect(diagnostic).not.toContain("[email protected]");
695+
expect(diagnostic).not.toContain("[email protected]");
696+
expect(diagnostic).not.toContain("[email protected]");
697+
const terminalDiagnostic = observedConsoleWarnings.mock.calls.find(
698+
([message]) => message === "WhatsApp inbound media materialization failed",
699+
)?.[1]?.consoleMessage;
700+
expect(terminalDiagnostic).toContain("stage=direct");
701+
expect(terminalDiagnostic).toContain("status=410");
702+
expect(terminalDiagnostic).toContain("[redacted-url]");
703+
expect(terminalDiagnostic).not.toContain("media.example/private");
704+
expect(terminalDiagnostic).not.toContain("[email protected]");
705+
expect(terminalDiagnostic).not.toContain("[email protected]");
706+
707+
await listener.close();
708+
});
709+
710+
it("logs quoted media failures without verbose logging", async () => {
711+
downloadMediaMessageMock.mockRejectedValueOnce(
712+
await createBaileysMediaHttpError(
713+
410,
714+
"quoted media reference expired 7@hosted 88@newsletter",
715+
),
716+
);
717+
const onMessage = vi.fn();
718+
const listener = await monitorWebInbox({
719+
cfg: {
720+
channels: { whatsapp: { allowFrom: ["*"] } },
721+
} as never,
722+
verbose: false,
723+
onMessage,
724+
accountId: "default",
725+
authDir: path.join(HOME, "wa-auth"),
726+
});
727+
const realSock = await getMockSocket();
728+
729+
realSock.ev.emit("messages.upsert", {
730+
type: "notify",
731+
messages: [
732+
{
733+
key: { id: "quoted-failed", fromMe: false, remoteJid: "[email protected]" },
734+
message: {
735+
extendedTextMessage: {
736+
text: "inspect this",
737+
contextInfo: {
738+
stanzaId: "quoted-image-failed",
739+
participant: "[email protected]",
740+
quotedMessage: { imageMessage: { mimetype: "image/jpeg" } },
741+
},
742+
},
743+
},
744+
messageTimestamp: 1_700_000_011,
745+
},
746+
],
747+
});
748+
749+
const inbound = await waitForMessage(onMessage);
750+
expect(inbound.payload.body).toBe("inspect this\n\n[whatsapp quoted attachment unavailable]");
751+
expect(inbound.payload.commandBody).toBe("inspect this");
752+
const diagnostic = await waitForLogLine("quoted-failed");
753+
expect(diagnostic).toContain('"channel":"whatsapp"');
754+
expect(diagnostic).toContain('"mediaKind":"image"');
755+
expect(diagnostic).toContain('"mimeType":"image/jpeg"');
756+
expect(diagnostic).toContain('"failureStage":"quoted"');
757+
expect(diagnostic).toContain('"errorClass":"Error"');
758+
expect(diagnostic).toContain('"statusCode":410');
759+
expect(diagnostic).toContain("quoted media reference expired");
760+
expect(diagnostic).not.toContain("7@hosted");
761+
expect(diagnostic).not.toContain("88@newsletter");
762+
const terminalDiagnostic = observedConsoleWarnings.mock.calls.find(
763+
([message]) => message === "WhatsApp inbound media materialization failed",
764+
)?.[1]?.consoleMessage;
765+
expect(terminalDiagnostic).toContain("stage=quoted");
766+
expect(terminalDiagnostic).toContain("status=410");
767+
expect(terminalDiagnostic).not.toContain("7@hosted");
768+
expect(terminalDiagnostic).not.toContain("88@newsletter");
599769

600770
await listener.close();
601771
});

‎extensions/whatsapp/src/inbound/message-enrichment.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@ import {
55
formatLocationText,
66
type MediaPlaceholderTextFact,
77
} from "openclaw/plugin-sdk/channel-inbound";
8+
import { createSubsystemLogger, redactSensitiveText } from "openclaw/plugin-sdk/logging-core";
9+
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
10+
import { getStatusCode } from "../session-errors.js";
811
import {
912
describeReplyContext,
1013
extractContactContext,
@@ -16,6 +19,53 @@ import {
1619
import { resolveInboundMediaMimetype } from "./media-mimetype.js";
1720
import { downloadInboundMedia, downloadQuotedInboundMedia } from "./media.js";
1821

22+
const inboundMediaLogger = createSubsystemLogger("gateway/channels/whatsapp").child("inbound");
23+
const MAX_MEDIA_ERROR_MESSAGE_CHARS = 256;
24+
25+
function sanitizeMediaErrorMessage(error: unknown): string {
26+
const rawMessage = error instanceof Error ? error.message : String(error);
27+
const redacted = redactSensitiveText(rawMessage)
28+
.replace(/https?:\/\/\S+/giu, "[redacted-url]")
29+
.replace(/\b[^@\s]+@[a-z][a-z\d.-]*\b/giu, "[redacted-jid]")
30+
.replace(/\+?\d[\d ().-]{6,}\d/gu, "[redacted-phone]");
31+
return truncateUtf16Safe(
32+
redacted.split("\n", 1)[0]?.trim() || "unknown error",
33+
MAX_MEDIA_ERROR_MESSAGE_CHARS,
34+
);
35+
}
36+
37+
function logMediaMaterializationFailure(params: {
38+
messageId?: string | null;
39+
mediaKind?: string;
40+
mimeType?: string;
41+
failureStage: "direct" | "quoted";
42+
error: unknown;
43+
}): void {
44+
const errorClass =
45+
params.error instanceof Error && /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/u.test(params.error.name)
46+
? params.error.name
47+
: "Error";
48+
const statusCode = getStatusCode(params.error);
49+
const errorMessage = sanitizeMediaErrorMessage(params.error);
50+
const failureDetails = [
51+
`stage=${params.failureStage}`,
52+
...(params.mediaKind ? [`kind=${params.mediaKind}`] : []),
53+
...(typeof statusCode === "number" ? [`status=${statusCode}`] : []),
54+
].join(" ");
55+
// One subsystem event keeps the Gateway console and structured file log in sync.
56+
inboundMediaLogger.warn("WhatsApp inbound media materialization failed", {
57+
channel: "whatsapp",
58+
messageId: params.messageId ?? undefined,
59+
mediaKind: params.mediaKind,
60+
mimeType: params.mimeType,
61+
failureStage: params.failureStage,
62+
errorClass,
63+
...(typeof statusCode === "number" ? { statusCode } : {}),
64+
errorMessage,
65+
consoleMessage: `WhatsApp inbound media materialization failed (${failureDetails}): ${errorMessage}`,
66+
});
67+
}
68+
1969
export type WhatsAppEnrichedInboundMessage = {
2070
body: string;
2171
commandBody: string;
@@ -77,6 +127,13 @@ export async function enrichWhatsAppInboundMessage(params: {
77127
await downloadInboundMedia(msg as proto.IWebMessageInfo, sock, maxBytes),
78128
);
79129
} catch (error) {
130+
logMediaMaterializationFailure({
131+
messageId: msg.key?.id,
132+
mediaKind,
133+
mimeType: mediaType,
134+
failureStage: "direct",
135+
error,
136+
});
80137
params.logVerbose(`Inbound media download failed: ${String(error)}`);
81138
body = formatInboundMediaUnavailableText({
82139
body,
@@ -91,6 +148,13 @@ export async function enrichWhatsAppInboundMessage(params: {
91148
mediaKind = replyContext.media.kind ?? undefined;
92149
mediaType = mediaType ?? replyContext.media.contentType ?? undefined;
93150
} catch (error) {
151+
logMediaMaterializationFailure({
152+
messageId: msg.key?.id,
153+
mediaKind: replyContext.media.kind ?? undefined,
154+
mimeType: replyContext.media.contentType ?? undefined,
155+
failureStage: "quoted",
156+
error,
157+
});
94158
params.logVerbose(`Quoted media download failed: ${String(error)}`);
95159
body = formatInboundMediaUnavailableText({
96160
body,

0 commit comments

Comments
 (0)