Skip to content

Commit 1929599

Browse files
vincentkocsteipete
authored andcommitted
fix(ci): stabilize whatsapp extension checks
1 parent 6f5df14 commit 1929599

13 files changed

Lines changed: 27621 additions & 1977 deletions

File tree

‎docs/.generated/config-baseline.json‎

Lines changed: 25198 additions & 1942 deletions
Large diffs are not rendered by default.

‎docs/.generated/config-baseline.jsonl‎

Lines changed: 2150 additions & 16 deletions
Large diffs are not rendered by default.

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,14 @@ import fs from "node:fs/promises";
33
import os from "node:os";
44
import path from "node:path";
55
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
6+
import {
7+
mockExtractMessageContent,
8+
mockGetContentType,
9+
mockIsJidGroup,
10+
mockNormalizeMessageContent,
11+
} from "../../../test/mocks/baileys.js";
12+
13+
type MockMessageInput = Parameters<typeof mockNormalizeMessageContent>[0];
614

715
const readAllowFromStoreMock = vi.fn().mockResolvedValue([]);
816
const upsertPairingRequestMock = vi.fn().mockResolvedValue({ code: "PAIRCODE", created: true });
@@ -71,7 +79,14 @@ vi.mock("@whiskeysockets/baileys", async (importOriginal) => {
7179
]);
7280
return {
7381
...actual,
82+
DisconnectReason: actual.DisconnectReason ?? { loggedOut: 401 },
7483
downloadMediaMessage: vi.fn().mockResolvedValue(jpegBuffer),
84+
extractMessageContent: vi.fn((message: MockMessageInput) => mockExtractMessageContent(message)),
85+
getContentType: vi.fn((message: MockMessageInput) => mockGetContentType(message)),
86+
isJidGroup: vi.fn((jid: string | undefined | null) => mockIsJidGroup(jid)),
87+
normalizeMessageContent: vi.fn((message: MockMessageInput) =>
88+
mockNormalizeMessageContent(message),
89+
),
7590
};
7691
});
7792

‎extensions/whatsapp/src/inbound/extract.ts‎

Lines changed: 103 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,114 @@ import { logVerbose } from "openclaw/plugin-sdk/runtime-env";
99
import { jidToE164 } from "openclaw/plugin-sdk/text-runtime";
1010
import { parseVcard } from "../vcard.js";
1111

12+
const MESSAGE_WRAPPER_KEYS = [
13+
"ephemeralMessage",
14+
"viewOnceMessage",
15+
"viewOnceMessageV2",
16+
"viewOnceMessageV2Extension",
17+
"documentWithCaptionMessage",
18+
] as const;
19+
20+
const MESSAGE_CONTENT_KEYS = [
21+
"conversation",
22+
"extendedTextMessage",
23+
"imageMessage",
24+
"videoMessage",
25+
"audioMessage",
26+
"documentMessage",
27+
"stickerMessage",
28+
"locationMessage",
29+
"liveLocationMessage",
30+
"contactMessage",
31+
"contactsArrayMessage",
32+
"buttonsResponseMessage",
33+
"listResponseMessage",
34+
"templateButtonReplyMessage",
35+
"interactiveResponseMessage",
36+
"buttonsMessage",
37+
"listMessage",
38+
] as const;
39+
40+
function fallbackNormalizeMessageContent(
41+
message: proto.IMessage | undefined,
42+
): proto.IMessage | undefined {
43+
let current = message as unknown;
44+
while (current && typeof current === "object") {
45+
let unwrapped = false;
46+
for (const key of MESSAGE_WRAPPER_KEYS) {
47+
const candidate = (current as Record<string, unknown>)[key];
48+
if (
49+
candidate &&
50+
typeof candidate === "object" &&
51+
"message" in (candidate as Record<string, unknown>) &&
52+
(candidate as { message?: unknown }).message
53+
) {
54+
current = (candidate as { message: unknown }).message;
55+
unwrapped = true;
56+
break;
57+
}
58+
}
59+
if (!unwrapped) {
60+
break;
61+
}
62+
}
63+
return current as proto.IMessage | undefined;
64+
}
65+
66+
function normalizeMessage(message: proto.IMessage | undefined): proto.IMessage | undefined {
67+
if (typeof normalizeMessageContent === "function") {
68+
return normalizeMessageContent(message);
69+
}
70+
return fallbackNormalizeMessageContent(message);
71+
}
72+
73+
function fallbackGetContentType(
74+
message: proto.IMessage | undefined,
75+
): keyof proto.IMessage | undefined {
76+
const normalized = fallbackNormalizeMessageContent(message);
77+
if (!normalized || typeof normalized !== "object") {
78+
return undefined;
79+
}
80+
for (const key of MESSAGE_CONTENT_KEYS) {
81+
if ((normalized as Record<string, unknown>)[key] != null) {
82+
return key as keyof proto.IMessage;
83+
}
84+
}
85+
return undefined;
86+
}
87+
88+
function getMessageContentType(
89+
message: proto.IMessage | undefined,
90+
): keyof proto.IMessage | undefined {
91+
if (typeof getContentType === "function") {
92+
return getContentType(message);
93+
}
94+
return fallbackGetContentType(message);
95+
}
96+
97+
function extractMessage(message: proto.IMessage | undefined): proto.IMessage | undefined {
98+
if (typeof extractMessageContent === "function") {
99+
return extractMessageContent(message) as proto.IMessage | undefined;
100+
}
101+
const normalized = fallbackNormalizeMessageContent(message);
102+
const contentType = fallbackGetContentType(normalized);
103+
if (!normalized || !contentType || contentType === "conversation") {
104+
return normalized;
105+
}
106+
const candidate = (normalized as Record<string, unknown>)[contentType];
107+
return candidate && typeof candidate === "object" ? (candidate as proto.IMessage) : normalized;
108+
}
109+
12110
function unwrapMessage(message: proto.IMessage | undefined): proto.IMessage | undefined {
13-
const normalized = normalizeMessageContent(message);
111+
const normalized = normalizeMessage(message);
14112
return normalized;
15113
}
16114

17115
function extractContextInfo(message: proto.IMessage | undefined): proto.IContextInfo | undefined {
18116
if (!message) {
19117
return undefined;
20118
}
21-
const contentType = getContentType(message);
119+
const contentType = getMessageContentType(message);
22120
const candidate = contentType ? (message as Record<string, unknown>)[contentType] : undefined;
23121
const contextInfo =
24122
candidate && typeof candidate === "object" && "contextInfo" in candidate
@@ -89,7 +187,7 @@ export function extractText(rawMessage: proto.IMessage | undefined): string | un
89187
if (!message) {
90188
return undefined;
91189
}
92-
const extracted = extractMessageContent(message);
190+
const extracted = extractMessage(message);
93191
const candidates = [message, extracted && extracted !== message ? extracted : undefined];
94192
for (const candidate of candidates) {
95193
if (!candidate) {
@@ -300,7 +398,7 @@ export function describeReplyContext(rawMessage: proto.IMessage | undefined): {
300398
return null;
301399
}
302400
const contextInfo = extractContextInfo(message);
303-
const quoted = normalizeMessageContent(contextInfo?.quotedMessage as proto.IMessage | undefined);
401+
const quoted = normalizeMessage(contextInfo?.quotedMessage as proto.IMessage | undefined);
304402
if (!quoted) {
305403
return null;
306404
}
@@ -312,7 +410,7 @@ export function describeReplyContext(rawMessage: proto.IMessage | undefined): {
312410
body = extractMediaPlaceholder(quoted);
313411
}
314412
if (!body) {
315-
const quotedType = quoted ? getContentType(quoted) : undefined;
413+
const quotedType = quoted ? getMessageContentType(quoted) : undefined;
316414
logVerbose(
317415
`Quoted message missing extractable body${quotedType ? ` (type ${quotedType})` : ""}`,
318416
);

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

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,30 @@
11
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
import {
3+
mockExtractMessageContent,
4+
mockGetContentType,
5+
mockIsJidGroup,
6+
mockNormalizeMessageContent,
7+
} from "../../../../test/mocks/baileys.js";
8+
9+
type MockMessageInput = Parameters<typeof mockNormalizeMessageContent>[0];
210

311
const { normalizeMessageContent, downloadMediaMessage } = vi.hoisted(() => ({
4-
normalizeMessageContent: vi.fn((msg: unknown) => msg),
12+
normalizeMessageContent: vi.fn((msg: MockMessageInput) => mockNormalizeMessageContent(msg)),
513
downloadMediaMessage: vi.fn().mockResolvedValue(Buffer.from("fake-media-data")),
614
}));
715

8-
vi.mock("@whiskeysockets/baileys", () => ({
9-
normalizeMessageContent,
10-
downloadMediaMessage,
11-
}));
16+
vi.mock("@whiskeysockets/baileys", async (importOriginal) => {
17+
const actual = await importOriginal<typeof import("@whiskeysockets/baileys")>();
18+
return {
19+
...actual,
20+
DisconnectReason: actual.DisconnectReason ?? { loggedOut: 401 },
21+
extractMessageContent: vi.fn((message: MockMessageInput) => mockExtractMessageContent(message)),
22+
getContentType: vi.fn((message: MockMessageInput) => mockGetContentType(message)),
23+
isJidGroup: vi.fn((jid: string | undefined | null) => mockIsJidGroup(jid)),
24+
normalizeMessageContent,
25+
downloadMediaMessage,
26+
};
27+
});
1228

1329
let downloadInboundMedia: typeof import("./media.js").downloadInboundMedia;
1430

‎extensions/whatsapp/src/inbound/monitor.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,12 @@ import { downloadInboundMedia } from "./media.js";
2222
import { createWebSendApi } from "./send-api.js";
2323
import type { WebInboundMessage, WebListenerCloseReason } from "./types.js";
2424

25+
const LOGGED_OUT_STATUS = DisconnectReason?.loggedOut ?? 401;
26+
27+
function isGroupJid(jid: string): boolean {
28+
return (typeof isJidGroup === "function" ? isJidGroup(jid) : jid.endsWith("@g.us")) === true;
29+
}
30+
2531
export async function monitorWebInbox(options: {
2632
verbose: boolean;
2733
accountId: string;
@@ -176,7 +182,7 @@ export async function monitorWebInbox(options: {
176182
return null;
177183
}
178184

179-
const group = isJidGroup(remoteJid) === true;
185+
const group = isGroupJid(remoteJid);
180186
if (id) {
181187
const dedupeKey = `${options.accountId}:${remoteJid}:${id}`;
182188
if (isRecentInboundMessage(dedupeKey)) {
@@ -438,7 +444,7 @@ export async function monitorWebInbox(options: {
438444
const status = getStatusCode(update.lastDisconnect?.error);
439445
resolveClose({
440446
status,
441-
isLoggedOut: status === DisconnectReason.loggedOut,
447+
isLoggedOut: status === LOGGED_OUT_STATUS,
442448
error: update.lastDisconnect?.error,
443449
});
444450
}

‎extensions/whatsapp/src/login-qr.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ import {
77
waitForWaConnection,
88
} from "./session.js";
99

10-
vi.mock("./session.js", () => {
10+
vi.mock("./session.js", async () => {
11+
const actual = await vi.importActual<typeof import("./session.js")>("./session.js");
1112
const createWaSocket = vi.fn(
1213
async (_printQr: boolean, _verbose: boolean, opts?: { onQr?: (qr: string) => void }) => {
1314
const sock = { ws: { close: vi.fn() } };
@@ -30,6 +31,7 @@ vi.mock("./session.js", () => {
3031
const logoutWeb = vi.fn(async () => true);
3132
const waitForCredsSaveQueueWithTimeout = vi.fn(async () => {});
3233
return {
34+
...actual,
3335
createWaSocket,
3436
waitForWaConnection,
3537
formatError,

‎extensions/whatsapp/src/login-qr.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ import {
1717
webAuthExists,
1818
} from "./session.js";
1919

20+
const LOGGED_OUT_STATUS = DisconnectReason?.loggedOut ?? 401;
21+
2022
type WaSocket = Awaited<ReturnType<typeof createWaSocket>>;
2123

2224
type ActiveLogin = {
@@ -261,7 +263,7 @@ export async function waitForWebLogin(
261263
}
262264

263265
if (login.error) {
264-
if (login.errorStatus === DisconnectReason.loggedOut) {
266+
if (login.errorStatus === LOGGED_OUT_STATUS) {
265267
await logoutWeb({
266268
authDir: login.authDir,
267269
isLegacyAuthDir: login.isLegacyAuthDir,

‎extensions/whatsapp/src/login.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
55
import { resetLogger, setLoggerOverride } from "../../../src/logging.js";
66
import { renderQrPngBase64 } from "./qr-image.js";
77

8-
vi.mock("./session.js", () => {
8+
vi.mock("./session.js", async () => {
9+
const actual = await vi.importActual<typeof import("./session.js")>("./session.js");
910
const ev = new EventEmitter();
1011
const sock = {
1112
ev,
@@ -14,6 +15,7 @@ vi.mock("./session.js", () => {
1415
sendMessage: vi.fn(),
1516
};
1617
return {
18+
...actual,
1719
createWaSocket: vi.fn().mockResolvedValue(sock),
1820
waitForWaConnection: vi.fn().mockResolvedValue(undefined),
1921
};

‎extensions/whatsapp/src/login.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ import {
1414
waitForWaConnection,
1515
} from "./session.js";
1616

17+
const LOGGED_OUT_STATUS = DisconnectReason?.loggedOut ?? 401;
18+
1719
export async function loginWeb(
1820
verbose: boolean,
1921
waitForConnection?: typeof waitForWaConnection,
@@ -53,7 +55,7 @@ export async function loginWeb(
5355
setTimeout(() => retry.ws?.close(), 500);
5456
}
5557
}
56-
if (code === DisconnectReason.loggedOut) {
58+
if (code === LOGGED_OUT_STATUS) {
5759
await logoutWeb({
5860
authDir: account.authDir,
5961
isLegacyAuthDir: account.isLegacyAuthDir,

0 commit comments

Comments
 (0)