fix(whatsapp): respond to linked-account group messages

This commit is contained in:
xmanrui 2026-08-25 01:12:55 +08:00
parent 9657107a21
commit 2cc3a42d45
11 changed files with 150 additions and 34 deletions

View file

@ -6,6 +6,11 @@ This file records the notable changes in each dsh-im release. Its format follows
## [Unreleased]
### Fixed / 修复
- WhatsApp 开放响应模式现在会处理已绑定账号自己在群聊中发出的消息,包括只有自己的群;出站文本消息会在发送前预留消息 ID,避免机器人回复的本地回显再次触发 Harness。
WhatsApp Open responses now handles group messages sent by the linked account, including owner-only groups; outbound text message IDs are reserved before sending so local reply echoes cannot trigger Harness again.
## [2.2.0] - 2026-08-25
### Added / 新增

View file

@ -128,7 +128,7 @@ Use the proxy URL required by your network and restart the Host after changing i
Each Telegram bot has its own access-mode control on its bot card. Existing and newly connected bots both default to **Compatible mode**: DMs receive replies, while group messages require a mention of or reply to the bot. Restrictions apply only after explicitly switching that bot to **Safe mode (private-chat allowlist)**. Safe mode ignores every group message and admits only numeric User IDs in that bot's allowlist. Enter one ID per line. Switching back to Compatible mode retains the allowlist without enforcing it, so it is available when Safe mode is enabled again. An empty allowlist in Safe mode rejects all inbound messages for that bot.
Each WhatsApp bot also has its own access mode. Existing bots migrate to **Only me**, which is also the default for newly linked bots and accepts only self-chat messages from the linked account. **Selected contacts** additionally accepts direct messages from allowlisted phone numbers and ignores groups. Enter one number with its country or region code per line; a leading `+` is optional. **Open responses** preserves the previous behavior: all direct messages are accepted, together with group mentions or replies. Switching modes retains the allowlist. An empty Selected contacts allowlist behaves like Only me, and rejected messages are ignored silently.
Each WhatsApp bot also has its own access mode. Existing bots migrate to **Only me**, which is also the default for newly linked bots and accepts only self-chat messages from the linked account. **Selected contacts** additionally accepts direct messages from allowlisted phone numbers and ignores groups. Enter one number with its country or region code per line; a leading `+` is optional. **Open responses** accepts all direct messages, group messages sent by the linked account, and mentions of or replies to that account from other group members; this also lets an owner-only group act as a separate conversation. Switching modes retains the allowlist. An empty Selected contacts allowlist behaves like Only me, and rejected messages are ignored silently.
## Bot commands
@ -185,7 +185,7 @@ If the Slack desktop app has no native Slash Command registered with the same na
- `/session` accepts exactly one Session ID obtained from `/sessionlist`. It neither creates a session nor immediately prompts the model; later messages in the current chat continue the bound session. Regular archived sessions can be bound without being unarchived, while subagent sessions cannot be bound.
- `/session` locates the session's unique workspace automatically. Binding inside the current workspace replaces only this chat's mapping. A cross-workspace binding switches the bot workspace, clears the old session mappings for all of that bot's chats, and then binds this chat, so it affects the bot's other chats. A reply already being generated may still finish.
- Workspace switches and session bindings only clear or replace dsh-im chat mappings. They never delete, empty, or archive old Session contents; an old Session can still be listed and bound again.
- Any user admitted by the current channel access policy can run these commands; there is no separate administrator role. Telegram Compatible mode follows the original DM and group mention/reply rules, while Safe mode admits only allowlisted private users. WhatsApp Only me accepts self-chat only, Selected contacts accepts self-chat plus allowlisted direct messages, and Open responses accepts every direct message plus group mentions or replies.
- Any user admitted by the current channel access policy can run these commands; there is no separate administrator role. Telegram Compatible mode follows the original DM and group mention/reply rules, while Safe mode admits only allowlisted private users. WhatsApp Only me accepts self-chat only, Selected contacts accepts self-chat plus allowlisted direct messages, and Open responses accepts every direct message, group messages from the linked account, and mentions or replies from other group members.
- Agent Preset names and IDs come from the same Harness Host, and any command-authorized user can change the Preset used by all future new Sessions across this bot's chats. Expose `/presetlist` and `/preset` only to trusted users.
- The list comes from the Harness Host's global registry and can include local absolute paths for other bots, other channels, or non-IM projects. Restrict the bot's visibility to trusted users.
- Session results also come from the global Harness Host. Session IDs and titles can belong to other bots, other channels, or non-IM projects, and may contain sensitive metadata. Enable these commands only when every user in the bot's visibility scope is trusted.

View file

@ -131,7 +131,7 @@ dsh web
每个 Telegram 机器人都可以在自己的卡片中切换访问模式。旧机器人和新接入机器人均默认使用**兼容模式**:私聊直接响应,群聊仅在提及机器人或回复机器人消息时响应。只有主动切换到**安全模式(私聊白名单)**后,机器人才会忽略全部群聊,并只接受该机器人白名单中的数字 User ID。白名单每行一个 ID、按机器人独立保存;切回兼容模式时会保留但不使用,再切回安全模式即可继续使用。安全模式的空白名单会拒绝该机器人的所有入站消息。
每个 WhatsApp 机器人也有独立的访问模式。旧机器人升级后和新接入机器人都默认使用**仅自己模式**,只响应已绑定账号的自聊消息。**指定联系人模式**额外接受白名单电话号码的私聊并忽略群聊;号码需包含国家或地区代码,每行一个,可带开头的 `+`。**开放响应模式**保留原有行为:响应所有私聊,以及群聊中的提及或回复。切换模式会保留白名单;指定联系人模式的空白名单等同于仅自己模式。未授权消息会被静默忽略。
每个 WhatsApp 机器人也有独立的访问模式。旧机器人升级后和新接入机器人都默认使用**仅自己模式**,只响应已绑定账号的自聊消息。**指定联系人模式**额外接受白名单电话号码的私聊并忽略群聊;号码需包含国家或地区代码,每行一个,可带开头的 `+`。**开放响应模式**响应所有私聊、已绑定账号自己发出的群聊消息,以及其他群成员对该账号的提及或回复;因此也可以把“仅自己”的群当作独立会话使用。切换模式会保留白名单;指定联系人模式的空白名单等同于仅自己模式。未授权消息会被静默忽略。
## 机器人命令
@ -188,7 +188,7 @@ Slack 桌面端若未注册同名的原生 Slash Command,会拦截直接以 `/
- `/session` 只接受一个由 `/sessionlist` 获得的 Session ID。它不会新建会话或立即向模型发送消息;绑定成功后,当前聊天的后续消息会继续该会话。普通归档会话可以绑定但不会自动取消归档,子代理会话不能绑定。
- `/session` 会自动定位会话唯一所属的工作区。同工作区绑定只替换当前聊天的映射;跨工作区绑定会切换该机器人的工作区、清除该机器人所有聊天的旧会话映射,再绑定当前聊天,因此会影响该机器人的其他聊天。已经开始生成的回复仍可完成。
- 工作区切换和会话绑定只会清除或替换 dsh-im 的聊天映射,不会删除、清空或归档任何旧 Session 内容;旧 Session 仍可再次列出和绑定。
- 任何通过当前渠道访问策略的用户都可以执行这些命令,不另行区分管理员和普通用户。Telegram 兼容模式遵循原有私聊及群聊提及/回复规则;安全模式只允许当前机器人白名单中的私聊用户执行。WhatsApp 仅自己模式只接受自聊,指定联系人模式接受自聊和白名单私聊,开放响应模式接受所有私聊及群聊中的提及或回复。
- 任何通过当前渠道访问策略的用户都可以执行这些命令,不另行区分管理员和普通用户。Telegram 兼容模式遵循原有私聊及群聊提及/回复规则;安全模式只允许当前机器人白名单中的私聊用户执行。WhatsApp 仅自己模式只接受自聊,指定联系人模式接受自聊和白名单私聊,开放响应模式接受所有私聊、已绑定账号自己发出的群聊消息,以及其他群成员的提及或回复。
- Agent Preset 名称和 ID 来自同一个 Harness Host,且任何有命令权限的用户都能修改该机器人所有聊天未来新 Session 的 Preset;请只向可信用户开放 `/presetlist` 和 `/preset`。
- 工作区列表来自 Harness Host 的全局登记信息,可能包含其他机器人、其他渠道或非 IM 项目的本机绝对路径。请将机器人可见范围限制给可信用户。
- 会话列表同样来自该全局 Harness Host;会话 ID 和标题可能属于其他机器人、其他渠道或非 IM 项目,并可能包含敏感元数据。开放命令前请确保所有可见用户都可信。

View file

@ -564,7 +564,7 @@ var EN = Object.freeze({
"\u5DF2\u751F\u6548\uFF1A": "Active: ",
"\u53EA\u54CD\u5E94\u5DF2\u7ED1\u5B9A WhatsApp \u8D26\u53F7\u7684\u81EA\u804A\u6D88\u606F\u3002": "Only respond to self-chat messages from the linked WhatsApp account.",
"\u54CD\u5E94\u81EA\u804A\u548C\u767D\u540D\u5355\u8054\u7CFB\u4EBA\u7684\u79C1\u804A\uFF0C\u5FFD\u7565\u7FA4\u804A\u3002": "Respond to self-chat and allowlisted direct messages; ignore group messages.",
"\u54CD\u5E94\u6240\u6709\u79C1\u804A\uFF0C\u4EE5\u53CA\u7FA4\u804A\u4E2D\u7684\u63D0\u53CA\u6216\u56DE\u590D\u3002": "Respond to all direct messages and to group mentions or replies.",
"\u54CD\u5E94\u6240\u6709\u79C1\u804A\u3001\u5DF2\u7ED1\u5B9A\u8D26\u53F7\u81EA\u5DF1\u53D1\u51FA\u7684\u7FA4\u804A\u6D88\u606F\uFF0C\u4EE5\u53CA\u5176\u4ED6\u7FA4\u6210\u5458\u7684\u63D0\u53CA\u6216\u56DE\u590D\u3002": "Respond to all direct messages, group messages sent by the linked account, and mentions or replies from other group members.",
"\u5141\u8BB8\u79C1\u804A\u7684 WhatsApp \u7535\u8BDD\u53F7\u7801": "WhatsApp phone numbers allowed to send direct messages",
"\u6BCF\u884C\u4E00\u4E2A\u542B\u56FD\u5BB6\u6216\u5730\u533A\u4EE3\u7801\u7684\u53F7\u7801": "One number with country or region code per line",
"\u53EF\u4EE5\u5305\u542B\u5F00\u5934\u7684 +\uFF0C\u4FDD\u5B58\u65F6\u4F1A\u81EA\u52A8\u79FB\u9664\u3002": "A leading + is allowed and removed when saved.",
@ -9351,7 +9351,7 @@ function WhatsappAccessSettings({ account, busy = false, onSave }) {
"span",
{ className: "dwa-accessTooltipItem" },
h2("strong", null, "\u5F00\u653E\u54CD\u5E94\u6A21\u5F0F"),
h2("span", null, "\u54CD\u5E94\u6240\u6709\u79C1\u804A\uFF0C\u4EE5\u53CA\u7FA4\u804A\u4E2D\u7684\u63D0\u53CA\u6216\u56DE\u590D\u3002")
h2("span", null, "\u54CD\u5E94\u6240\u6709\u79C1\u804A\u3001\u5DF2\u7ED1\u5B9A\u8D26\u53F7\u81EA\u5DF1\u53D1\u51FA\u7684\u7FA4\u804A\u6D88\u606F\uFF0C\u4EE5\u53CA\u5176\u4ED6\u7FA4\u6210\u5458\u7684\u63D0\u53CA\u6216\u56DE\u590D\u3002")
)
)
)

File diff suppressed because one or more lines are too long

View file

@ -99,7 +99,7 @@ export function WhatsappAccessSettings({ account, busy = false, onSave }) {
h('span', null, '响应自聊和白名单联系人的私聊,忽略群聊。')),
h('span', { className: 'dwa-accessTooltipItem' },
h('strong', null, '开放响应模式'),
h('span', null, '响应所有私聊,以及群聊中的提及或回复。')))))),
h('span', null, '响应所有私聊、已绑定账号自己发出的群聊消息,以及其他群成员的提及或回复。')))))),
h('label', { className: 'dwa-accessField' },
h('span', null, '模式'),
h('select', {

View file

@ -373,7 +373,7 @@ const EN = Object.freeze({
'已生效:': 'Active: ',
'只响应已绑定 WhatsApp 账号的自聊消息。': 'Only respond to self-chat messages from the linked WhatsApp account.',
'响应自聊和白名单联系人的私聊,忽略群聊。': 'Respond to self-chat and allowlisted direct messages; ignore group messages.',
'响应所有私聊,以及群聊中的提及或回复。': 'Respond to all direct messages and to group mentions or replies.',
'响应所有私聊、已绑定账号自己发出的群聊消息,以及其他群成员的提及或回复。': 'Respond to all direct messages, group messages sent by the linked account, and mentions or replies from other group members.',
'允许私聊的 WhatsApp 电话号码': 'WhatsApp phone numbers allowed to send direct messages',
'每行一个含国家或地区代码的号码': 'One number with country or region code per line',
'可以包含开头的 +,保存时会自动移除。': 'A leading + is allowed and removed when saved.',

View file

@ -1,4 +1,4 @@
import { createHash } from 'node:crypto';
import { createHash, randomBytes } from 'node:crypto';
import {
areJidsSameUser,
@ -217,9 +217,9 @@ export function normalizeWhatsappMessage(message, accountJid, {
const fromMe = message.key.fromMe === true;
const selfChat = fromMe && !group
&& [remoteJid, alternateRemoteJid].some((jid) => jid && areJidsSameUser(jid, accountJid));
if (fromMe && !selfChat) return null;
const senderJid = selfChat ? accountJid : group ? message.key.participant : remoteJid;
const senderAlternateJid = group ? message.key.participantAlt : alternateRemoteJid;
if (fromMe && !selfChat && !group) return null;
const senderJid = fromMe ? accountJid : group ? message.key.participant : remoteJid;
const senderAlternateJid = group && !fromMe ? message.key.participantAlt : alternateRemoteJid;
if (typeof senderJid !== 'string' || !senderJid) return null;
const viewOnce = hasViewOnceWrapper(message.message);
const content = normalizeMessageContent(message.message);
@ -241,7 +241,7 @@ export function normalizeWhatsappMessage(message, accountJid, {
content: messageText(content),
images: image ? [image] : [],
files: file ? [file] : [],
addressed: !group || mentioned || replyToSelf,
addressed: !group || fromMe || mentioned || replyToSelf,
selfChat,
replyTarget: { jid: remoteJid, quoted: message, selfChat },
};
@ -272,6 +272,14 @@ class RecentWhatsappOutboundIds {
}
remember(id) {
this.#store(id);
}
reserve(id) {
this.#store(id);
}
#store(id) {
if (typeof id !== 'string' || !id) return;
this.#purge();
this.#ids.set(id, Date.now() + 5 * 60_000);
@ -360,10 +368,23 @@ export class WhatsappBotClient {
await this.#stopTyping(target.jid);
const providerMessageIds = [];
for (const [index, chunk] of splitMessageText(text, 4_000).entries()) {
const messageId = randomBytes(10).toString('hex').toUpperCase();
const options = {
...(index === 0 && target.quoted ? { quoted: target.quoted } : {}),
messageId,
};
// Linked-account group messages are valid inbound prompts in open mode.
// Reserve our own id before dispatch so an early local echo cannot loop
// back through the bridge as another owner-authored group prompt.
if (typeof this.#outboundIds.reserve === 'function') {
this.#outboundIds.reserve(messageId);
} else {
this.#outboundIds.remember(messageId);
}
const result = await this.#socket.sendMessage(
target.jid,
{ text: chunk },
index === 0 && target.quoted ? { quoted: target.quoted } : undefined,
options,
);
this.#outboundIds.remember(result?.key?.id);
if (typeof result?.key?.id === 'string' && result.key.id) {

View file

@ -119,11 +119,13 @@ test('plain Slack, Telegram, Discord, and WhatsApp receipts retain every split m
let whatsappId = 0;
const remembered = [];
const reserved = [];
const whatsapp = new WhatsappBotClient({
sendPresenceUpdate: async () => {},
sendMessage: async () => ({ key: { id: `whatsapp-${++whatsappId}` } }),
}, {
remember: (messageId) => remembered.push(messageId),
reserve: (messageId) => reserved.push(messageId),
});
const whatsappReceipt = await textReceipt({
key: 'whatsapp',
@ -133,6 +135,9 @@ test('plain Slack, Telegram, Discord, and WhatsApp receipts retain every split m
});
assert.deepEqual(whatsappReceipt.providerMessageIds, ['whatsapp-1', 'whatsapp-2']);
assert.deepEqual(remembered, ['whatsapp-1', 'whatsapp-2']);
assert.equal(reserved.length, 2);
assert.equal(reserved.every((messageId) => /^[0-9A-F]{20}$/.test(messageId)), true);
assert.notEqual(reserved[0], reserved[1]);
});
test('Slack, Telegram, and Discord stream receipts retain the initial and remainder ids', async () => {

View file

@ -75,6 +75,7 @@ test('WhatsApp account card uses the unified compact channel layout', () => {
assert.match(markup, /仅自己模式(默认)/);
assert.match(markup, /指定联系人模式/);
assert.match(markup, /开放响应模式/);
assert.match(markup, /已绑定账号自己发出的群聊消息/);
assert.match(markup, /role="status"[^>]*>测试消息已发送/);
});

View file

@ -322,7 +322,7 @@ test('WhatsApp media downloader supplies Baileys reupload context', async () =>
assert.deepEqual(reuploaded, [{ key: { id: 'expired-media' } }]);
});
test('WhatsApp normalizes direct and explicitly mentioned group messages', () => {
test('WhatsApp normalizes direct, linked-account, and explicitly mentioned group messages', () => {
const direct = normalizeWhatsappMessage({
key: { remoteJid: '16505550999@s.whatsapp.net', id: 'direct-1', fromMe: false },
message: { conversation: 'hello' },
@ -358,6 +358,20 @@ test('WhatsApp normalizes direct and explicitly mentioned group messages', () =>
}, ACCOUNT_JID);
assert.equal(selfChat.selfChat, true);
assert.equal(selfChat.addressed, true);
const linkedAccountGroup = normalizeWhatsappMessage({
key: {
remoteJid: '120363000000000001@g.us',
id: 'owner-group-1',
fromMe: true,
},
message: { conversation: 'message from linked account in a group' },
}, ACCOUNT_JID);
assert.equal(linkedAccountGroup.kind, 'group');
assert.equal(linkedAccountGroup.senderId, ACCOUNT_JID);
assert.equal(linkedAccountGroup.addressed, true);
assert.equal(linkedAccountGroup.selfChat, false);
assert.equal(normalizeWhatsappMessage({
key: { remoteJid: '16505550999@s.whatsapp.net', id: 'outbound-1', fromMe: true },
message: { conversation: 'ordinary outbound message' },
@ -387,10 +401,19 @@ test('WhatsApp access modes allow self-chat, selected contacts, or the existing
key: { remoteJid: ACCOUNT_JID, id: 'access-self', fromMe: true },
message: { conversation: 'hello' },
}, ACCOUNT_JID);
const linkedAccountGroup = normalizeWhatsappMessage({
key: {
remoteJid: '120363000000000001@g.us',
id: 'access-owner-group',
fromMe: true,
},
message: { conversation: 'hello from the linked account' },
}, ACCOUNT_JID);
assert.equal(whatsappInboundAllowed(selfChat), true);
assert.equal(whatsappInboundAllowed(direct), false);
assert.equal(whatsappInboundAllowed(group), false);
assert.equal(whatsappInboundAllowed(linkedAccountGroup), false);
assert.equal(whatsappInboundAllowed(direct, {
accessMode: WHATSAPP_ACCESS_MODES.privateAllowlist,
allowedNumbers: new Set(['16505550999']),
@ -402,6 +425,9 @@ test('WhatsApp access modes allow self-chat, selected contacts, or the existing
assert.equal(whatsappInboundAllowed(group, {
accessMode: WHATSAPP_ACCESS_MODES.open,
}), true);
assert.equal(whatsappInboundAllowed(linkedAccountGroup, {
accessMode: WHATSAPP_ACCESS_MODES.open,
}), true);
});
test('WhatsApp keeps native and document images as images and exposes ordinary documents as files', async () => {
@ -623,6 +649,64 @@ test('WhatsApp runtime filters messages before the bridge and applies policy upd
await runtime.stop();
});
test('WhatsApp open mode answers linked-account group messages without processing reply echoes', async (t) => {
const groupJid = '120363000000000001@g.us';
let callbacks;
let replyEchoTask;
let askCount = 0;
const sent = [];
const socket = {
sendPresenceUpdate: async () => {},
readMessages: async () => {},
sendMessage: async (jid, content, options = {}) => {
sent.push({ jid, content, options });
replyEchoTask = callbacks.onMessage({
key: { remoteJid: groupJid, id: options.messageId, fromMe: true },
message: { conversation: content.text },
});
return { key: { id: options.messageId } };
},
};
const runtime = new WhatsappRuntime({
config: linkedConfig({ accessMode: WHATSAPP_ACCESS_MODES.open }),
authDir: '/tmp/test-whatsapp-linked-account-group',
harness: {
ensureRunning: async () => {},
sessionExists: async () => true,
ask: async () => {
askCount += 1;
return 'Harness group answer';
},
},
state: artifactState('session-linked-account-group'),
createSession: async (options) => {
callbacks = options;
return {
socket,
ready: Promise.resolve({ accountJid: ACCOUNT_JID, name: 'Harness WhatsApp' }),
close: async () => {},
logout: async () => {},
};
},
});
t.after(() => runtime.stop());
await runtime.start();
const inbound = {
key: { remoteJid: groupJid, id: 'linked-account-group-1', fromMe: true },
message: { conversation: 'hello from my group' },
};
await callbacks.onMessage(inbound);
await replyEchoTask;
assert.equal(askCount, 1);
assert.equal(sent.length, 1);
assert.equal(sent[0].jid, groupJid);
assert.equal(sent[0].content.text, 'Harness group answer');
assert.equal(sent[0].options.quoted, inbound);
assert.match(sent[0].options.messageId, /^[0-9A-F]{20}$/);
});
test('WhatsApp runtime sends result files with native metadata, quote, stable id, and upload timeout', async (t) => {
const { artifact, deliveryKey } = await committedArtifact(t, {
suffix: 'native-file',