Repository navigation
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c73fe4f513
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| for (const [key, subMap] of DIRECTORY_HANDLE_CACHE) { | ||
| if (key === ownKey) { | ||
| continue; | ||
| } | ||
| const found = subMap.get(handle) ?? (altHandle ? subMap.get(altHandle) : undefined); | ||
| if (found) { |
There was a problem hiding this comment.
Prevent ambiguous cross-account handle fallback
The new global fallback in resolveDiscordDirectoryUserId returns the first matching handle from any other account cache, so duplicate handles across accounts (for example two different @alice users) are resolved nondeterministically based on map insertion order. In multi-bot gateways this can rewrite a mention to the wrong Discord user ID, causing wrong-user pings or failed mentions in the current guild; the fallback should only be used when the match is unambiguous (or scoped to known bot identities).
Useful? React with 👍 / 👎.
| @@ -1,7 +1,7 @@ | |||
| import { resolveDiscordDirectoryUserId } from "./directory-cache.js"; | |||
|
|
|||
| const MARKDOWN_CODE_SEGMENT_PATTERN = /```[\s\S]*?```|`[^`\n]*`/g; | |||
| const MENTION_CANDIDATE_PATTERN = /(^|[\s([{"'.,;:!?])@([a-z0-9_.-]{2,32}(?:#[0-9]{4})?)/gi; | |||
| const MENTION_CANDIDATE_PATTERN = /(^|[^\p{L}\p{N}])@([\p{L}\p{N}_.-]{1,32}(?:#[0-9]{4})?)/giu; | |||
There was a problem hiding this comment.
Restrict mention matching to true mention boundaries
Changing the prefix boundary to (^|[^\p{L}\p{N}]) makes @name inside URL paths match (for example https://x.com/@alice), so cached handles can now be rewritten inside links and other non-mention contexts. This is a behavior regression from the previous tighter boundary and can silently corrupt outbound URLs/messages when a username is present in path-like text.
Useful? React with 👍 / 👎.
Greptile SummaryThis PR fixes CJK Key changes:
Issues found:
Confidence Score: 3/5
Prompt To Fix All With AIThis is a comment left during a code review.
Path: extensions/discord/src/directory-cache.ts
Line: 113-127
Comment:
**Cross-account fallback has no guild scope — can resolve wrong user in multi-guild setups**
The fallback iterates over every account sub-map in the process. This is correct when all bots share one Discord server, but in a deployment where a single process runs bots for *multiple distinct Discord servers*, two guilds can have different users who share the same display name (e.g. `alice`). The first one cached wins, and the sending bot ends up mentioning the wrong person.
The cache key is `accountId` (= bot token identity), not `(accountId, guildId)`. Because the fallback ignores account boundaries entirely, guild isolation is lost once the cross-account path fires.
Consider scoping the directory cache key to `(accountId, guildId)` or, at minimum, documenting that this system is only safe for single-guild multi-bot deployments and adding an assertion or warning when the same handle appears under two different accounts with different user IDs.
How can I resolve this? If you propose a fix, please make it concise.
---
This is a comment left during a code review.
Path: extensions/discord/src/monitor/message-handler.preflight.ts
Line: 292-332
Comment:
**Belt-and-suspenders fallback relies on undocumented internal fields**
Both `rawAuthor` and `rawMessage` are accessed via unsafe type assertions against fields that aren't part of the typed Carbon API. If the internal shape of the event object changes in a future Carbon upgrade, these fallbacks will silently stop working with no type error:
```ts
const rawAuthor = (
params.data as { rawAuthor?: { ... } }
).rawAuthor;
// ...
const rawMessage = (
params.data as { rawMessage?: { mentions?: ... } }
).rawMessage;
```
Because the primary path (`author.username`, `message.mentionedUsers`) already covers the Carbon-typed surface, and the `globalName` assertion on the primary author (`(author as { globalName?: string }).globalName`) also targets an untyped field, this pattern adds silent failure modes. Consider either:
- Filing an issue/PR against Carbon to expose `globalName` and `global_name` in the typed API, or
- Adding a comment noting the specific Carbon version these fields were verified against, so a future bump can be audited.
How can I resolve this? If you propose a fix, please make it concise.
---
This is a comment left during a code review.
Path: extensions/discord/src/mentions.ts
Line: 4
Comment:
**Negative-class prefix `[^\p{L}\p{N}]` is broader than the previous allowlist**
Old prefix: `[\s([{"'.,;:!?]` (explicit allowlist of safe separators)
New prefix: `[^\p{L}\p{N}]` (any non-letter / non-digit — including `<`, `/`, `\`, `|`, control chars, etc.)
The practical implication: a text fragment like `<@1234567890>` (an already-formatted Discord mention) now has `<` matched as a valid prefix. If a numeric string matching an already-stored snowflake-as-handle ever ends up in the cache, the mention could be double-wrapped as `<<@id>`. While that scenario is unlikely today (the cache only stores `username`/`globalName` strings), widening the prefix class removes a lightweight guard that previously prevented matches in unexpected positions.
Narrowing to something like `[^\p{L}\p{N}<]` or keeping an explicit allowlist that adds CJK punctuation would preserve the intent without the added exposure.
How can I resolve this? If you propose a fix, please make it concise.Reviews (1): Last reviewed commit: "fix(discord): support CJK @mention rewri..." | Re-trigger Greptile |
| // Fallback: check ALL account sub-maps. In a multi-bot gateway where all | ||
| // bots run in the same process, another account's preflight may have already | ||
| // cached the target handle. This cross-account fallback enables bot→bot | ||
| // @mention rewriting even when the sending bot hasn't directly processed a | ||
| // message from the target user. | ||
| const ownKey = normalizeAccountCacheKey(params.accountId); | ||
| for (const [key, subMap] of DIRECTORY_HANDLE_CACHE) { | ||
| if (key === ownKey) { | ||
| continue; | ||
| } | ||
| const found = subMap.get(handle) ?? (altHandle ? subMap.get(altHandle) : undefined); | ||
| if (found) { | ||
| return found; | ||
| } | ||
| } |
There was a problem hiding this comment.
Cross-account fallback has no guild scope — can resolve wrong user in multi-guild setups
The fallback iterates over every account sub-map in the process. This is correct when all bots share one Discord server, but in a deployment where a single process runs bots for multiple distinct Discord servers, two guilds can have different users who share the same display name (e.g. alice). The first one cached wins, and the sending bot ends up mentioning the wrong person.
The cache key is accountId (= bot token identity), not (accountId, guildId). Because the fallback ignores account boundaries entirely, guild isolation is lost once the cross-account path fires.
Consider scoping the directory cache key to (accountId, guildId) or, at minimum, documenting that this system is only safe for single-guild multi-bot deployments and adding an assertion or warning when the same handle appears under two different accounts with different user IDs.
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/discord/src/directory-cache.ts
Line: 113-127
Comment:
**Cross-account fallback has no guild scope — can resolve wrong user in multi-guild setups**
The fallback iterates over every account sub-map in the process. This is correct when all bots share one Discord server, but in a deployment where a single process runs bots for *multiple distinct Discord servers*, two guilds can have different users who share the same display name (e.g. `alice`). The first one cached wins, and the sending bot ends up mentioning the wrong person.
The cache key is `accountId` (= bot token identity), not `(accountId, guildId)`. Because the fallback ignores account boundaries entirely, guild isolation is lost once the cross-account path fires.
Consider scoping the directory cache key to `(accountId, guildId)` or, at minimum, documenting that this system is only safe for single-guild multi-bot deployments and adding an assertion or warning when the same handle appears under two different accounts with different user IDs.
How can I resolve this? If you propose a fix, please make it concise.| // Also cache from the raw author data (snake_case fields) as a belt-and-suspenders fallback. | ||
| const rawAuthor = ( | ||
| params.data as { rawAuthor?: { id?: string; username?: string; global_name?: string | null } } | ||
| ).rawAuthor; | ||
| if (rawAuthor?.id && rawAuthor.username) { | ||
| rememberDiscordDirectoryUser({ | ||
| accountId: params.accountId, | ||
| userId: rawAuthor.id, | ||
| handles: [rawAuthor.username, rawAuthor.global_name ?? undefined], | ||
| }); | ||
| } | ||
| // Also cache any explicitly-mentioned users from the inbound message so that | ||
| // their handles are resolvable immediately, even before they speak. | ||
| for (const mentioned of message.mentionedUsers ?? []) { | ||
| const u = mentioned as { id?: string; username?: string; globalName?: string }; | ||
| if (u.id && u.username) { | ||
| rememberDiscordDirectoryUser({ | ||
| accountId: params.accountId, | ||
| userId: u.id, | ||
| handles: [u.username, u.globalName], | ||
| }); | ||
| } | ||
| } | ||
| const rawMessage = ( | ||
| params.data as { | ||
| rawMessage?: { | ||
| mentions?: Array<{ id?: string; username?: string; global_name?: string | null }>; | ||
| }; | ||
| } | ||
| ).rawMessage; | ||
| if (rawMessage?.mentions) { | ||
| for (const mention of rawMessage.mentions) { | ||
| if (mention.id && mention.username) { | ||
| rememberDiscordDirectoryUser({ | ||
| accountId: params.accountId, | ||
| userId: mention.id, | ||
| handles: [mention.username, mention.global_name ?? undefined], | ||
| }); | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
Belt-and-suspenders fallback relies on undocumented internal fields
Both rawAuthor and rawMessage are accessed via unsafe type assertions against fields that aren't part of the typed Carbon API. If the internal shape of the event object changes in a future Carbon upgrade, these fallbacks will silently stop working with no type error:
const rawAuthor = (
params.data as { rawAuthor?: { ... } }
).rawAuthor;
// ...
const rawMessage = (
params.data as { rawMessage?: { mentions?: ... } }
).rawMessage;Because the primary path (author.username, message.mentionedUsers) already covers the Carbon-typed surface, and the globalName assertion on the primary author ((author as { globalName?: string }).globalName) also targets an untyped field, this pattern adds silent failure modes. Consider either:
- Filing an issue/PR against Carbon to expose
globalNameandglobal_namein the typed API, or - Adding a comment noting the specific Carbon version these fields were verified against, so a future bump can be audited.
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/discord/src/monitor/message-handler.preflight.ts
Line: 292-332
Comment:
**Belt-and-suspenders fallback relies on undocumented internal fields**
Both `rawAuthor` and `rawMessage` are accessed via unsafe type assertions against fields that aren't part of the typed Carbon API. If the internal shape of the event object changes in a future Carbon upgrade, these fallbacks will silently stop working with no type error:
```ts
const rawAuthor = (
params.data as { rawAuthor?: { ... } }
).rawAuthor;
// ...
const rawMessage = (
params.data as { rawMessage?: { mentions?: ... } }
).rawMessage;
```
Because the primary path (`author.username`, `message.mentionedUsers`) already covers the Carbon-typed surface, and the `globalName` assertion on the primary author (`(author as { globalName?: string }).globalName`) also targets an untyped field, this pattern adds silent failure modes. Consider either:
- Filing an issue/PR against Carbon to expose `globalName` and `global_name` in the typed API, or
- Adding a comment noting the specific Carbon version these fields were verified against, so a future bump can be audited.
How can I resolve this? If you propose a fix, please make it concise.| @@ -1,7 +1,7 @@ | |||
| import { resolveDiscordDirectoryUserId } from "./directory-cache.js"; | |||
|
|
|||
| const MARKDOWN_CODE_SEGMENT_PATTERN = /```[\s\S]*?```|`[^`\n]*`/g; | |||
| const MENTION_CANDIDATE_PATTERN = /(^|[\s([{"'.,;:!?])@([a-z0-9_.-]{2,32}(?:#[0-9]{4})?)/gi; | |||
| const MENTION_CANDIDATE_PATTERN = /(^|[^\p{L}\p{N}])@([\p{L}\p{N}_.-]{1,32}(?:#[0-9]{4})?)/giu; | |||
There was a problem hiding this comment.
Negative-class prefix
[^\p{L}\p{N}] is broader than the previous allowlist
Old prefix: [\s([{"'.,;:!?] (explicit allowlist of safe separators)
New prefix: [^\p{L}\p{N}] (any non-letter / non-digit — including <, /, \, |, control chars, etc.)
The practical implication: a text fragment like <@1234567890> (an already-formatted Discord mention) now has < matched as a valid prefix. If a numeric string matching an already-stored snowflake-as-handle ever ends up in the cache, the mention could be double-wrapped as <<@id>. While that scenario is unlikely today (the cache only stores username/globalName strings), widening the prefix class removes a lightweight guard that previously prevented matches in unexpected positions.
Narrowing to something like [^\p{L}\p{N}<] or keeping an explicit allowlist that adds CJK punctuation would preserve the intent without the added exposure.
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/discord/src/mentions.ts
Line: 4
Comment:
**Negative-class prefix `[^\p{L}\p{N}]` is broader than the previous allowlist**
Old prefix: `[\s([{"'.,;:!?]` (explicit allowlist of safe separators)
New prefix: `[^\p{L}\p{N}]` (any non-letter / non-digit — including `<`, `/`, `\`, `|`, control chars, etc.)
The practical implication: a text fragment like `<@1234567890>` (an already-formatted Discord mention) now has `<` matched as a valid prefix. If a numeric string matching an already-stored snowflake-as-handle ever ends up in the cache, the mention could be double-wrapped as `<<@id>`. While that scenario is unlikely today (the cache only stores `username`/`globalName` strings), widening the prefix class removes a lightweight guard that previously prevented matches in unexpected positions.
Narrowing to something like `[^\p{L}\p{N}<]` or keeping an explicit allowlist that adds CJK punctuation would preserve the intent without the added exposure.
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
Pull request overview
This PR fixes Discord outbound @mention rewriting in multi-bot gateways by expanding mention matching to Unicode (CJK) handles and improving how user handle→ID mappings are learned and resolved across bot accounts.
Changes:
- Update mention-candidate detection to support Unicode letters/numbers and fullwidth/CJK punctuation boundaries.
- Extend the directory cache to support cross-account handle resolution and seed/populate it from bot identity + inbound message authors/mentions.
- Apply outbound mention rewriting in reply delivery and draft finalization paths; add unit tests for CJK and cache population behavior.
Reviewed changes
Copilot reviewed 9 out of 9 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| extensions/discord/src/mentions.ts | Updates mention-candidate regex to Unicode-aware matching for CJK handles. |
| extensions/discord/src/directory-cache.ts | Adds cross-account fallback when resolving handle→userId mappings. |
| extensions/discord/src/monitor/message-handler.preflight.ts | Populates directory cache from inbound author + mentions during preflight. |
| extensions/discord/src/monitor/reply-delivery.ts | Rewrites known mentions on outbound chunks prior to sending. |
| extensions/discord/src/monitor/message-handler.process.ts | Rewrites known mentions for the “finalize via preview edit” path. |
| extensions/discord/src/monitor/provider.ts | Seeds directory cache from the bot’s own identity at startup. |
| extensions/discord/src/monitor/provider.startup.ts | Adds proxy-aware REST fetch wiring; bot identity fetch falls back to applicationId. |
| extensions/discord/src/mentions.test.ts | Adds tests for CJK/fullwidth punctuation + cross-account resolution behavior. |
| extensions/discord/src/monitor/message-handler.preflight.directory-cache.test.ts | New tests ensuring preflight seeds cache from author/mentions and enables outbound rewriting. |
| @@ -1,7 +1,7 @@ | |||
| import { resolveDiscordDirectoryUserId } from "./directory-cache.js"; | |||
|
|
|||
| const MARKDOWN_CODE_SEGMENT_PATTERN = /```[\s\S]*?```|`[^`\n]*`/g; | |||
| const MENTION_CANDIDATE_PATTERN = /(^|[\s([{"'.,;:!?])@([a-z0-9_.-]{2,32}(?:#[0-9]{4})?)/gi; | |||
| const MENTION_CANDIDATE_PATTERN = /(^|[^\p{L}\p{N}])@([\p{L}\p{N}_.-]{1,32}(?:#[0-9]{4})?)/giu; | |||
There was a problem hiding this comment.
The new mention-candidate regex will also match inside already-canonical Discord mentions like <@123> (prefix < satisfies [^\p{L}\p{N}]). If a cached handle is numeric (or otherwise overlaps), this can corrupt existing mentions (e.g., <@123> becoming <<@resolved>>). Consider explicitly excluding < from the allowed prefix (or add a guard in the replacer when prefix === "<") so already-formatted mentions are never rewritten.
| const MENTION_CANDIDATE_PATTERN = /(^|[^\p{L}\p{N}])@([\p{L}\p{N}_.-]{1,32}(?:#[0-9]{4})?)/giu; | |
| const MENTION_CANDIDATE_PATTERN = /(^|[^\p{L}\p{N}<])@([\p{L}\p{N}_.-]{1,32}(?:#[0-9]{4})?)/giu; |
| if (!params.text.trim()) { | ||
| return; | ||
| } | ||
| const text = params.text; | ||
| const text = rewriteDiscordKnownMentions(params.text, { accountId: params.accountId }); | ||
| const binding = params.binding; |
There was a problem hiding this comment.
rewriteDiscordKnownMentions is currently applied per already-chunked message (params.text). Because chunkDiscordTextWithMode can split long lines at arbitrary character boundaries, an @handle near a chunk boundary can be split into two chunks and will then never be rewritten. Consider rewriting the full outbound text before chunking (e.g., in deliverDiscordReply before chunkDiscordTextWithMode/resolveTextChunksWithFallback) and pass the rewritten text into the chunker, rather than rewriting each chunk here.
| const allowBotsSetting = params.discordConfig?.allowBots; | ||
| const allowBotsMode = | ||
| allowBotsSetting === "mentions" ? "mentions" : allowBotsSetting === true ? "all" : "off"; | ||
|
|
||
| // Passively populate the directory cache from the message author so that | ||
| // outbound rewriteDiscordKnownMentions() can resolve @name → <@ID> for | ||
| // any user (including bots) seen in this channel — enabling bot→bot @mention | ||
| // chains without prompt-level ID injection. | ||
| if (author.id && author.username) { | ||
| rememberDiscordDirectoryUser({ | ||
| accountId: params.accountId, | ||
| userId: author.id, | ||
| handles: [ | ||
| author.username, | ||
| (author as { globalName?: string }).globalName, | ||
| params.data.member?.nick, | ||
| ], | ||
| }); | ||
| } | ||
| // Also cache from the raw author data (snake_case fields) as a belt-and-suspenders fallback. | ||
| const rawAuthor = ( | ||
| params.data as { rawAuthor?: { id?: string; username?: string; global_name?: string | null } } | ||
| ).rawAuthor; | ||
| if (rawAuthor?.id && rawAuthor.username) { | ||
| rememberDiscordDirectoryUser({ | ||
| accountId: params.accountId, | ||
| userId: rawAuthor.id, | ||
| handles: [rawAuthor.username, rawAuthor.global_name ?? undefined], | ||
| }); | ||
| } | ||
| // Also cache any explicitly-mentioned users from the inbound message so that | ||
| // their handles are resolvable immediately, even before they speak. | ||
| for (const mentioned of message.mentionedUsers ?? []) { |
There was a problem hiding this comment.
Directory-cache seeding is done before the early-return drops (own-message, guild/channel allowlist/group policy, allowBots, etc.). This means a message that is ultimately ignored/blocked can still populate the handle→ID cache, which can then affect outbound mention rewriting in allowed contexts (potentially resolving the wrong user when handles collide across guilds). Consider moving the cache population to after the message has passed the relevant allow/ignore checks, or scoping the cache entries to the validated context.
| expect(opsRewrite).toBe("<@999888777>"); | ||
| // "default" also resolves via cross-account fallback (multi-bot gateway) | ||
| const defaultRewrite = rewriteDiscordKnownMentions("@alice", { accountId: "default" }); | ||
| expect(defaultRewrite).toBe("<@999888777>"); | ||
| }); |
There was a problem hiding this comment.
Given the broader prefix match in MENTION_CANDIDATE_PATTERN, it would be good to add a regression test ensuring already-formatted mentions like <@123> are not rewritten (especially if a cached handle could be numeric or otherwise overlap). This will help catch accidental corruption of existing Discord mention markup when adjusting the regex in the future.
| }); | |
| }); | |
| it("does not rewrite already-formatted user mentions", () => { | |
| rememberDiscordDirectoryUser({ | |
| accountId: "default", | |
| userId: "123456789", | |
| handles: ["123456789"], | |
| }); | |
| const rewritten = rewriteDiscordKnownMentions("user <@123456789> and @123456789", { | |
| accountId: "default", | |
| }); | |
| expect(rewritten).toBe("user <@123456789> and <@123456789>"); | |
| }); |
c73fe4f to
d5b0e91
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d5b0e9116a
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| // Passively populate the directory cache from the message author so that | ||
| // outbound rewriteDiscordKnownMentions() can resolve @name → <@ID> for | ||
| // any user (including bots) seen in this channel — enabling bot→bot @mention | ||
| // chains without prompt-level ID injection. | ||
| if (author.id && author.username) { |
There was a problem hiding this comment.
Defer directory cache writes until message is policy-allowed
preflightDiscordMessage stores author handles in the shared directory cache before any guild/channel allowlist decisions are applied, so even messages that are later dropped can mutate mention resolution state. Since outbound rewriting consumes this cache without channel context, traffic from blocked channels can poison @handle -> userId mappings and cause replies in allowed channels to ping the wrong user. Cache population should happen only after policy gates pass (or be scoped by guild/channel) to prevent rejected messages from affecting outbound mention rewriting.
Useful? React with 👍 / 👎.
d5b0e91 to
baca86b
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: baca86bed1
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| rememberDiscordDirectoryUser({ | ||
| accountId: account.accountId, | ||
| userId: botUserId, | ||
| handles: [botUserName].filter(Boolean), | ||
| }); |
There was a problem hiding this comment.
Seed bot cache with both username and display name
The startup cache seed only stores botUserName, which is computed as username ?? globalName; since Discord bot users always have a username, the globalName path is effectively never cached. In multi-bot setups where agents mention peers by display name (for example a CJK display name while the canonical username is ASCII), cross-account rewrite still fails on first contact because @displayName cannot resolve until that bot later appears in inbound preflight traffic. Cache both handles at startup so mention rewriting works before any inbound message from the target bot.
Useful? React with 👍 / 👎.
ea7f01e to
c8db5d7
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c8db5d714b
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| handles: [ | ||
| author.username, | ||
| (author as { globalName?: string }).globalName, | ||
| params.data.member?.nick, |
There was a problem hiding this comment.
Stop caching guild nicknames in account-global handle map
Adding params.data.member?.nick to rememberDiscordDirectoryUser stores guild-scoped nicknames in an account-wide cache, while outbound rewriting (rewriteDiscordKnownMentions) resolves only by accountId and has no guild/channel context. In a multi-guild bot, two different users can share the same nickname, so the most recent inbound message overwrites the mapping and a later @nickname in another guild can be rewritten to the wrong <@userId>, causing wrong-user pings. Nicknames should be scoped by guild (or excluded from this global cache).
Useful? React with 👍 / 👎.
|
Thanks for the context here. I swept through the related work, and this is now duplicate or superseded. Close: this PR is superseded by the related Unicode Discord mention PR, which was closed after a member stated the existing ASCII mention behavior is correct. Current main and docs still steer agents toward canonical Discord mention IDs or configured Canonical path: Keep the current canonical So I’m closing this here because the remaining work is already tracked in the canonical issue. Review detailsBest possible solution: Keep the current canonical Do we have a high-confidence way to reproduce the issue? Yes for the observed behavior: current main's regex does not rewrite CJK handles. That behavior is not a confirmed bug now because current docs and the related maintainer decision keep Discord plain mention rewriting tied to canonical IDs or configured aliases. Is this the best way to solve the issue? No. The PR's Unicode rewrite direction is superseded by #43357, and its cache/identity changes are broader than a safe Discord mention fix. Security review: Security review needs attention: The diff has concrete Discord identity and mention-isolation risks, though no dependency or workflow supply-chain concern was found.
What I checked:
Likely related people:
Codex review notes: model gpt-5.5, reasoning high; reviewed against aef93881af5f. |
|
ClawSweeper applied the proposed close for this PR.
|
Summary
@mentionrewriting fails because the mention candidate regex only matches ASCII characters[a-z0-9_.-]. When Bot A tells Bot B to mention@架构师, the text is sent as plain text instead of being converted to<@user_id>.MENTION_CANDIDATE_PATTERNregex updated from ASCII to Unicode ([\p{L}\p{N}_.-]with/uflag)resolveDiscordDirectoryUserIdnow falls back across all account caches (cross-account resolution for multi-bot gateways)rewriteDiscordKnownMentionson outbound textChange Type (select all)
Scope (select all touched areas)
Linked Issue/PR
Root Cause / Regression History (if applicable)
[a-z0-9_.-].resolveDiscordDirectoryUserIdwas scoped to a single account's cache, preventing cross-account resolution needed for multi-bot gateways.Regression Test Plan (if applicable)
extensions/discord/src/mentions.test.ts,extensions/discord/src/monitor/message-handler.preflight.directory-cache.test.tsUser-visible / Behavior Changes
@架构师is correctly rewritten to<@user_id>)Diagram (if applicable)
Security Impact (required)
Repro + Verification
Environment
Steps
@架构师Expected
The mention is rewritten to
<@bot_user_id>and the target bot receives a mention notification.Actual
Before fix: plain text
@架构师sent, no notification. After fix:<@id>sent, bot notified.Evidence
pnpm test -- extensions/discord/src/mentions.test.ts(10 tests),pnpm test -- extensions/discord/src/monitor/message-handler.preflight.directory-cache.test.ts(5 tests),pnpm test -- extensions/discord/src/monitor/message-handler.preflight.test.ts(25 tests) — all pass.Human Verification (required)