Skip to content

Commit c8db5d7

Browse files
TimmyTimmy
authored andcommitted
fix(discord): support CJK @mention rewriting in bot-to-bot message chains
1 parent f17fd73 commit c8db5d7

10 files changed

Lines changed: 351 additions & 20 deletions

‎extensions/discord/src/directory-cache.ts‎

Lines changed: 34 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -92,23 +92,46 @@ export function resolveDiscordDirectoryUserId(params: {
9292
accountId?: string | null;
9393
handle: string;
9494
}): string | undefined {
95-
const cache = DIRECTORY_HANDLE_CACHE.get(normalizeAccountCacheKey(params.accountId));
96-
if (!cache) {
97-
return undefined;
98-
}
9995
const handle = normalizeHandleKey(params.handle);
10096
if (!handle) {
10197
return undefined;
10298
}
103-
const direct = cache.get(handle);
104-
if (direct) {
105-
return direct;
106-
}
10799
const withoutDiscriminator = handle.replace(DISCORD_DISCRIMINATOR_SUFFIX, "");
108-
if (!withoutDiscriminator || withoutDiscriminator === handle) {
109-
return undefined;
100+
const altHandle =
101+
withoutDiscriminator && withoutDiscriminator !== handle ? withoutDiscriminator : null;
102+
103+
// First: check the account-specific sub-map.
104+
const cache = DIRECTORY_HANDLE_CACHE.get(normalizeAccountCacheKey(params.accountId));
105+
if (cache) {
106+
const direct = cache.get(handle);
107+
if (direct) {
108+
return direct;
109+
}
110+
if (altHandle) {
111+
const alt = cache.get(altHandle);
112+
if (alt) {
113+
return alt;
114+
}
115+
}
110116
}
111-
return cache.get(withoutDiscriminator);
117+
118+
// Fallback: check ALL account sub-maps. In a multi-bot gateway where all
119+
// bots run in the same process, another account's preflight may have already
120+
// cached the target handle. This cross-account fallback enables bot→bot
121+
// @mention rewriting even when the sending bot hasn't directly processed a
122+
// message from the target user.
123+
const ownKey = normalizeAccountCacheKey(params.accountId);
124+
for (const [key, subMap] of DIRECTORY_HANDLE_CACHE) {
125+
if (key === ownKey) {
126+
continue;
127+
}
128+
const found = subMap.get(handle) ?? (altHandle ? subMap.get(altHandle) : undefined);
129+
if (found) {
130+
return found;
131+
}
132+
}
133+
134+
return undefined;
112135
}
113136

114137
export function __resetDiscordDirectoryCacheForTest(): void {

‎extensions/discord/src/mentions.test.ts‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -71,15 +71,30 @@ describe("rewriteDiscordKnownMentions", () => {
7171
expect(rewritten).toBe("inline `@alice` fence ```\n@alice\n``` text <@123456789>");
7272
});
7373

74-
it("is account-scoped", () => {
74+
it("rewrites mentions after CJK/fullwidth punctuation", () => {
75+
rememberDiscordDirectoryUser({
76+
accountId: "default",
77+
userId: "111222333",
78+
handles: ["后端工程师"],
79+
});
80+
// fullwidth colon : (U+FF1A) before @
81+
const rewritten = rewriteDiscordKnownMentions("提及:@后端工程师 确认", {
82+
accountId: "default",
83+
});
84+
expect(rewritten).toBe("提及:<@111222333> 确认");
85+
});
86+
87+
it("prefers account-specific cache but falls back to cross-account", () => {
7588
rememberDiscordDirectoryUser({
7689
accountId: "ops",
7790
userId: "999888777",
7891
handles: ["alice"],
7992
});
80-
const defaultRewrite = rewriteDiscordKnownMentions("@alice", { accountId: "default" });
93+
// "ops" resolves from its own cache
8194
const opsRewrite = rewriteDiscordKnownMentions("@alice", { accountId: "ops" });
82-
expect(defaultRewrite).toBe("@alice");
8395
expect(opsRewrite).toBe("<@999888777>");
96+
// "default" also resolves via cross-account fallback (multi-bot gateway)
97+
const defaultRewrite = rewriteDiscordKnownMentions("@alice", { accountId: "default" });
98+
expect(defaultRewrite).toBe("<@999888777>");
8499
});
85100
});

‎extensions/discord/src/mentions.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import {
66
import { resolveDiscordDirectoryUserId } from "./directory-cache.js";
77

88
const MARKDOWN_CODE_SEGMENT_PATTERN = /```[\s\S]*?```|`[^`\n]*`/g;
9-
const MENTION_CANDIDATE_PATTERN = /(^|[\s([{"'.,;:!?])@([a-z0-9_.-]{2,32}(?:#[0-9]{4})?)/gi;
9+
const MENTION_CANDIDATE_PATTERN = /(^|[^\p{L}\p{N}])@([\p{L}\p{N}_.-]{1,32}(?:#[0-9]{4})?)/giu;
1010
const DISCORD_RESERVED_MENTIONS = new Set(["everyone", "here"]);
1111

1212
function normalizeSnowflake(value: string | number | bigint): string | null {
Lines changed: 199 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,199 @@
1+
/**
2+
* Tests that preflightDiscordMessage passively populates the directory cache
3+
* from the message author and mentionedUsers, enabling outbound
4+
* rewriteDiscordKnownMentions() to resolve @name → <@ID> for bot→bot @mention
5+
* chains without prompt-level ID injection.
6+
*/
7+
import { beforeEach, describe, expect, it } from "vitest";
8+
import {
9+
__resetDiscordDirectoryCacheForTest,
10+
rememberDiscordDirectoryUser,
11+
resolveDiscordDirectoryUserId,
12+
} from "../directory-cache.js";
13+
import { rewriteDiscordKnownMentions } from "../mentions.js";
14+
import { preflightDiscordMessage } from "./message-handler.preflight.js";
15+
import {
16+
createDiscordMessage,
17+
createDiscordPreflightArgs,
18+
createGuildEvent,
19+
createGuildTextClient,
20+
DEFAULT_PREFLIGHT_CFG,
21+
} from "./message-handler.preflight.test-helpers.js";
22+
23+
const GUILD_ID = "guild-1";
24+
const CHANNEL_ID = "channel-1";
25+
const BOT_USER_ID = "bot-self";
26+
27+
function makeAllowedGuildEntries() {
28+
return {
29+
[GUILD_ID]: {
30+
id: GUILD_ID,
31+
channels: {
32+
[CHANNEL_ID]: { allow: true, enabled: true, requireMention: false },
33+
},
34+
},
35+
};
36+
}
37+
38+
function makeBaseParams(author: {
39+
id: string;
40+
bot: boolean;
41+
username: string;
42+
globalName?: string;
43+
}) {
44+
const carbonAuthor = author as unknown as import("@buape/carbon").Message["author"];
45+
const message = createDiscordMessage({
46+
id: "m-1",
47+
channelId: CHANNEL_ID,
48+
content: "hello",
49+
author,
50+
});
51+
return createDiscordPreflightArgs({
52+
cfg: DEFAULT_PREFLIGHT_CFG,
53+
discordConfig: { allowBots: true } as NonNullable<
54+
import("openclaw/plugin-sdk/config-runtime").OpenClawConfig["channels"]
55+
>["discord"],
56+
data: createGuildEvent({
57+
channelId: CHANNEL_ID,
58+
guildId: GUILD_ID,
59+
author: carbonAuthor,
60+
message,
61+
}),
62+
client: createGuildTextClient(CHANNEL_ID),
63+
botUserId: BOT_USER_ID,
64+
});
65+
}
66+
67+
describe("preflightDiscordMessage: directory cache population", () => {
68+
beforeEach(() => {
69+
__resetDiscordDirectoryCacheForTest();
70+
});
71+
72+
it("caches the message author username so outbound rewrite resolves @name → <@ID>", async () => {
73+
const author = { id: "1488478869458780280", bot: true, username: "架构师" };
74+
const params = makeBaseParams(author);
75+
76+
await preflightDiscordMessage({ ...params, guildEntries: makeAllowedGuildEntries() });
77+
78+
const resolved = resolveDiscordDirectoryUserId({
79+
accountId: "default",
80+
handle: "架构师",
81+
});
82+
expect(resolved).toBe("1488478869458780280");
83+
});
84+
85+
it("rewrites @name in outbound text after author passes through preflight", async () => {
86+
// Simulate bot A's message arriving — bot A is the architect
87+
const author = { id: "1488478869458780280", bot: true, username: "架构师" };
88+
const params = makeBaseParams(author);
89+
90+
await preflightDiscordMessage({ ...params, guildEntries: makeAllowedGuildEntries() });
91+
92+
// Now another bot tries to mention the architect by display name
93+
const rewritten = rewriteDiscordKnownMentions("@架构师 请复核确认", { accountId: "default" });
94+
expect(rewritten).toBe("<@1488478869458780280> 请复核确认");
95+
});
96+
97+
it("caches globalName as an additional resolvable handle", async () => {
98+
const author = {
99+
id: "1488480784422535208",
100+
bot: true,
101+
username: "backend_eng",
102+
globalName: "后端工程师",
103+
};
104+
const message = createDiscordMessage({
105+
id: "m-2",
106+
channelId: CHANNEL_ID,
107+
content: "api done",
108+
author,
109+
});
110+
const params = createDiscordPreflightArgs({
111+
cfg: DEFAULT_PREFLIGHT_CFG,
112+
discordConfig: { allowBots: true } as NonNullable<
113+
import("openclaw/plugin-sdk/config-runtime").OpenClawConfig["channels"]
114+
>["discord"],
115+
data: {
116+
...createGuildEvent({
117+
channelId: CHANNEL_ID,
118+
guildId: GUILD_ID,
119+
author: author as unknown as import("@buape/carbon").Message["author"],
120+
message,
121+
}),
122+
// Inject globalName via the author object (as Carbon exposes it)
123+
author: {
124+
...author,
125+
globalName: "后端工程师",
126+
} as unknown as import("@buape/carbon").Message["author"],
127+
} as import("./listeners.js").DiscordMessageEvent,
128+
client: createGuildTextClient(CHANNEL_ID),
129+
botUserId: BOT_USER_ID,
130+
});
131+
132+
await preflightDiscordMessage({ ...params, guildEntries: makeAllowedGuildEntries() });
133+
134+
// Both the username and globalName should resolve
135+
expect(resolveDiscordDirectoryUserId({ accountId: "default", handle: "backend_eng" })).toBe(
136+
"1488480784422535208",
137+
);
138+
expect(resolveDiscordDirectoryUserId({ accountId: "default", handle: "后端工程师" })).toBe(
139+
"1488480784422535208",
140+
);
141+
});
142+
143+
it("caches users listed in mentionedUsers so the receiver learns their IDs", async () => {
144+
const botSelf = { id: BOT_USER_ID, bot: true, username: "director_bot" };
145+
const mentionedBot = { id: "1488479656549158922", username: "前端工程师" };
146+
const message = {
147+
id: "m-3",
148+
content: "<@" + BOT_USER_ID + "> check this",
149+
channelId: CHANNEL_ID,
150+
timestamp: new Date().toISOString(),
151+
attachments: [],
152+
mentionedUsers: [{ ...mentionedBot }],
153+
mentionedRoles: [],
154+
mentionedEveryone: false,
155+
author: botSelf,
156+
} as unknown as import("@buape/carbon").Message;
157+
158+
const params = createDiscordPreflightArgs({
159+
cfg: DEFAULT_PREFLIGHT_CFG,
160+
discordConfig: { allowBots: true } as NonNullable<
161+
import("openclaw/plugin-sdk/config-runtime").OpenClawConfig["channels"]
162+
>["discord"],
163+
data: createGuildEvent({
164+
channelId: CHANNEL_ID,
165+
guildId: GUILD_ID,
166+
author: botSelf as unknown as import("@buape/carbon").Message["author"],
167+
message,
168+
}),
169+
client: createGuildTextClient(CHANNEL_ID),
170+
botUserId: BOT_USER_ID,
171+
});
172+
173+
await preflightDiscordMessage({ ...params, guildEntries: makeAllowedGuildEntries() });
174+
175+
// The mentioned bot's username should now be resolvable
176+
expect(resolveDiscordDirectoryUserId({ accountId: "default", handle: "前端工程师" })).toBe(
177+
"1488479656549158922",
178+
);
179+
});
180+
181+
it("cross-account fallback resolves handles cached by another account", () => {
182+
// Simulate bot A (accountId="architect") caching a user during preflight
183+
rememberDiscordDirectoryUser({
184+
accountId: "architect",
185+
userId: "1488480784422535208",
186+
handles: ["后端工程师"],
187+
});
188+
189+
// Bot B (accountId="qa") should also be able to resolve the handle
190+
// via the cross-account fallback
191+
expect(resolveDiscordDirectoryUserId({ accountId: "qa", handle: "后端工程师" })).toBe(
192+
"1488480784422535208",
193+
);
194+
195+
// Rewrite should also work from a different account
196+
const rewritten = rewriteDiscordKnownMentions("@后端工程师 请确认", { accountId: "qa" });
197+
expect(rewritten).toBe("<@1488480784422535208> 请确认");
198+
});
199+
});

‎extensions/discord/src/monitor/message-handler.preflight.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import { getChildLogger, logVerbose, shouldLogVerbose } from "openclaw/plugin-sd
2222
import { logDebug, normalizeOptionalString } from "openclaw/plugin-sdk/text-runtime";
2323
import { resolveDefaultDiscordAccountId } from "../accounts.js";
2424
import { resolveDiscordConversationIdentity } from "../conversation-identity.js";
25+
import { rememberDiscordDirectoryUser } from "../directory-cache.js";
2526
import {
2627
isDiscordGroupAllowedByPolicy,
2728
normalizeDiscordSlug,
@@ -377,6 +378,64 @@ export async function preflightDiscordMessage(
377378
const allowBotsSetting = params.discordConfig?.allowBots;
378379
const allowBotsMode =
379380
allowBotsSetting === "mentions" ? "mentions" : allowBotsSetting === true ? "all" : "off";
381+
382+
// Passively populate the directory cache from the message author so that
383+
// outbound rewriteDiscordKnownMentions() can resolve @name → <@ID> for
384+
// any user (including bots) seen in this channel — enabling bot→bot @mention
385+
// chains without prompt-level ID injection.
386+
if (author.id && author.username) {
387+
rememberDiscordDirectoryUser({
388+
accountId: params.accountId,
389+
userId: author.id,
390+
handles: [
391+
author.username,
392+
(author as { globalName?: string }).globalName,
393+
params.data.member?.nick,
394+
],
395+
});
396+
}
397+
// Also cache from the raw author data (snake_case fields) as a belt-and-suspenders fallback.
398+
const rawAuthor = (
399+
params.data as { rawAuthor?: { id?: string; username?: string; global_name?: string | null } }
400+
).rawAuthor;
401+
if (rawAuthor?.id && rawAuthor.username) {
402+
rememberDiscordDirectoryUser({
403+
accountId: params.accountId,
404+
userId: rawAuthor.id,
405+
handles: [rawAuthor.username, rawAuthor.global_name ?? undefined],
406+
});
407+
}
408+
// Also cache any explicitly-mentioned users from the inbound message so that
409+
// their handles are resolvable immediately, even before they speak.
410+
for (const mentioned of message.mentionedUsers ?? []) {
411+
const u = mentioned as { id?: string; username?: string; globalName?: string };
412+
if (u.id && u.username) {
413+
rememberDiscordDirectoryUser({
414+
accountId: params.accountId,
415+
userId: u.id,
416+
handles: [u.username, u.globalName],
417+
});
418+
}
419+
}
420+
const rawMessage = (
421+
params.data as {
422+
rawMessage?: {
423+
mentions?: Array<{ id?: string; username?: string; global_name?: string | null }>;
424+
};
425+
}
426+
).rawMessage;
427+
if (rawMessage?.mentions) {
428+
for (const mention of rawMessage.mentions) {
429+
if (mention.id && mention.username) {
430+
rememberDiscordDirectoryUser({
431+
accountId: params.accountId,
432+
userId: mention.id,
433+
handles: [mention.username, mention.global_name ?? undefined],
434+
});
435+
}
436+
}
437+
}
438+
380439
if (params.botUserId && author.id === params.botUserId) {
381440
// Always ignore own messages to prevent self-reply loops
382441
return null;

‎extensions/discord/src/monitor/message-handler.process.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ import { createDiscordRestClient } from "../client.js";
4949
import { resolveDiscordConversationIdentity } from "../conversation-identity.js";
5050
import { resolveDiscordDraftStreamingChunking } from "../draft-chunking.js";
5151
import { createDiscordDraftStream } from "../draft-stream.js";
52+
import { rewriteDiscordKnownMentions } from "../mentions.js";
5253
import { resolveDiscordPreviewStreamMode } from "../preview-streaming.js";
5354
import { removeReactionDiscord } from "../send.js";
5455
import { editMessageDiscord } from "../send.messages.js";
@@ -740,7 +741,9 @@ export async function processDiscordMessage(
740741
const reply = resolveSendableOutboundReplyParts(payload);
741742
const hasMedia = reply.hasMedia;
742743
const finalText = payload.text;
743-
const previewFinalText = resolvePreviewFinalText(finalText);
744+
const previewFinalText = resolvePreviewFinalText(
745+
finalText ? rewriteDiscordKnownMentions(finalText, { accountId }) : finalText,
746+
);
744747
const hasExplicitReplyDirective =
745748
Boolean(payload.replyToTag || payload.replyToCurrent) ||
746749
(typeof finalText === "string" && /\[\[\s*reply_to(?:_current|\s*:)/i.test(finalText));

0 commit comments

Comments
 (0)