Skip to content

fix(matrix): mentions should work with displayName labels (with help from Antigravity) - #55393

Merged
gumadeiras merged 6 commits into
openclaw:mainfrom
nickludlam:fix-matrix-mentions
Mar 27, 2026
Merged

gumadeiras merged 6 commits into
openclaw:mainfrom
nickludlam:fix-matrix-mentions

Conversation

@nickludlam

@nickludlam nickludlam commented Mar 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Matrix direct mentions are parsed from HTML like <a href="https://matrix.to/#/@botname:example.org">label</a>

  • The current system expects direct mentions to use localpart (botname) or MXID (@botName:example.org) as the anchor's label

  • Newer Matrix clients will format mentions using the displayName (Bot Name) as the label

  • This bug prevented Matrix groups where a setting of requireMention: true was used from working correctly

  • The checkFormattedBodyMention() method now takes an additional displayName parameter to allow for this to match correctly

  • Problem:

  • Why it matters: Without this you cannot talk to bots in shared rooms correctly on Matrix where requireMention is set

  • What changed: displayName has been added as a parameter to include it in the detection system

  • What did NOT change (scope boundary): Nothing else in Matrix was touched

I've attached a file which logged out the variables as they are seen when a message with a mention comes through which I used during debugging.

matrix_mention_detection_failure.txt

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

  • Closes #
  • Related #
  • This PR fixes a bug or regression

Root Cause / Regression History (if applicable)

  • Root cause: The previous mention detection system did not cover modern formatting of mentions in Matrix clients
  • Missing detection / guardrail: checkFormattedBodyMention() did not have access to displayName
  • Prior context (git blame, prior PR, issue, or refactor if known):
  • Why this regressed now:
  • If unknown, what was ruled out:

Regression Test Plan (if applicable)

N/A

  • Coverage level that should have caught this:
    • Unit test
    • Seam / integration test
    • End-to-end test
    • Existing coverage already sufficient
  • Target test or file:
  • Scenario the test should lock in:
  • Why this is the smallest reliable guardrail:
  • Existing test that already covers this (if any):
  • If no new test is added, why not:

User-visible / Behavior Changes

None

Security Impact (required)

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? No
  • New/changed network calls? No
  • Command/tool execution surface changed? No
  • Data access scope changed? No
  • If any Yes, explain risk + mitigation:

Repro + Verification

Environment

  • OS: MacOS
  • Runtime/container: Docker
  • Model/provider: Kimi-K2.5
  • Integration/channel (if any): Matrix
  • Relevant config (redacted): None

Steps

  1. Invite a bot into a shared room with 3 or more people, and configure that room to require requireMention: true
  2. Try to address the bot using Element Desktop or Element X on iOS
  3. Observe the bot ignore your messages even when mentioned directly

Expected

  • The bot should respond when mentioned

Actual

  • The bot ignores the message because displayName was not factored into mention detection

Evidence

Attach at least one:

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Human Verification (required)

What you personally verified (not just CI), and how:

  • Verified scenarios: Verified using my instance when integrated with Matrix
  • Edge cases checked: There is no edge case for this simple change
  • What you did not verify: There are other outstanding issues with Matrix, namely the assumption that a two-person room is a direct conversation. There are separate PRs filed for this (not by me)

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

If a bot review conversation is addressed by this PR, resolve that conversation yourself. Do not leave bot review conversation cleanup for maintainers.

Compatibility / Migration

  • Backward compatible? Yes
  • Config/env changes? No
  • Migration needed? No
  • If yes, exact upgrade steps:

Risks and Mitigations

None

@openclaw-barnacle openclaw-barnacle Bot added channel: matrix Channel integration: matrix size: XS labels Mar 26, 2026
@greptile-apps

greptile-apps Bot commented Mar 26, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a real bug in the Matrix integration's mention-detection logic: modern Matrix clients (Element Desktop, Element X) format <a> anchor labels using the user's display name rather than their localpart or MXID, causing requireMention: true rooms to silently drop messages directed at the bot. The fix is well-scoped — it adds an optional displayName parameter threaded through resolveMentions → checkFormattedBodyMention → isVisibleMentionLabel, and fetches the bot's own display name in the handler only when formatted_body is present (a sensible performance guard).

Key observations:

  • Correctness: The MXID href check still runs first in checkFormattedBodyMention; the display name is only an additional label candidate after the link target is confirmed to be the bot. No security regression introduced.
  • Missing tests: mentions.test.ts has no coverage for the new displayName path. At minimum, a positive case (label = display name, href = bot MXID → detected) and a gate case (same label but wrong MXID → not detected) should be added to lock in the fix.
  • Minor: extractVisibleMentionText already lowercases its output, so the subsequent .map((v) => v.toLowerCase()) in the candidates chain is redundant for that one entry — harmless but worth cleaning up.

Confidence Score: 4/5

Safe to merge; the fix is correctly scoped and introduces no security regression, but unit test coverage for the new path is missing.

The logic change is minimal and correct — the MXID href gate still enforces the real security boundary, and the display name is only used as an additional label match after that check passes. The conditional fetch in the handler avoids unnecessary async calls for plain-text messages, and existing tests that assert getMemberDisplayName is not called remain valid. The only gap is the absence of unit tests for the new displayName matching scenario, which lowers confidence slightly from 5.

extensions/matrix/src/matrix/monitor/mentions.ts — the new displayName code path has no unit test coverage in mentions.test.ts.

Important Files Changed

Filename Overview
extensions/matrix/src/matrix/monitor/mentions.ts Adds optional displayName parameter threaded through resolveMentions → checkFormattedBodyMention → isVisibleMentionLabel. Logic is correct; MXID href check still runs first. Minor redundant toLowerCase on the display name candidate. No unit tests for the new path.
extensions/matrix/src/matrix/monitor/handler.ts Conditionally fetches selfDisplayName via getMemberDisplayName only when formatted_body is present, then passes it into resolveMentions. Guard prevents unnecessary async call for plain-text messages; existing tests remain valid.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: extensions/matrix/src/matrix/monitor/mentions.ts
Line: 47

Comment:
**Redundant `.toLowerCase()` on already-normalized value**

`extractVisibleMentionText` calls `normalizeVisibleMentionText`, which already applies `.toLowerCase()` before returning. The value is then lowercased a second time by the `.map((value) => value.toLowerCase())` at the end of the `candidates` chain. This is harmless but redundant and may be mildly confusing to future readers. Since the other candidates need the map, consider documenting that this entry is already normalized.

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/matrix/src/matrix/monitor/mentions.ts
Line: 105-110

Comment:
**No unit tests added for the new `displayName` matching path**

`mentions.test.ts` has good coverage for the existing mention strategies (MXID, localpart, regex, room mentions), but has no tests at all for the new `displayName` parameter introduced in this PR. Without a test, the core scenario this PR fixes — a modern Matrix client formatting the mention anchor label as the bot's display name — has no regression guardrail.

Consider adding at minimum two tests to `mentions.test.ts`:

1. A positive case: `formatted_body` with a matrix.to link pointing to the bot's MXID whose visible label equals the bot's `displayName` → `wasMentioned` should be `true`.
2. A negative/security case: same label matching `displayName`, but the `href` targets a *different* user's MXID → `wasMentioned` should be `false` (to confirm the MXID gate still holds).

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "Fixed testing issue:" | Re-trigger Greptile

@@ -43,6 +44,7 @@ function isVisibleMentionLabel(params: {
params.userId.trim().toLowerCase(),
localpart,
localpart ? `@${localpart}` : null,
params.displayName ? extractVisibleMentionText(params.displayName) : null,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Redundant .toLowerCase() on already-normalized value

extractVisibleMentionText calls normalizeVisibleMentionText, which already applies .toLowerCase() before returning. The value is then lowercased a second time by the .map((value) => value.toLowerCase()) at the end of the candidates chain. This is harmless but redundant and may be mildly confusing to future readers. Since the other candidates need the map, consider documenting that this entry is already normalized.

Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/matrix/src/matrix/monitor/mentions.ts
Line: 47

Comment:
**Redundant `.toLowerCase()` on already-normalized value**

`extractVisibleMentionText` calls `normalizeVisibleMentionText`, which already applies `.toLowerCase()` before returning. The value is then lowercased a second time by the `.map((value) => value.toLowerCase())` at the end of the `candidates` chain. This is harmless but redundant and may be mildly confusing to future readers. Since the other candidates need the map, consider documenting that this entry is already normalized.

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines 105 to 110
export function resolveMentions(params: {
content: RoomMessageEventContent;
userId?: string | null;
displayName?: string | null;
text?: string;
mentionRegexes: RegExp[];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 No unit tests added for the new displayName matching path

mentions.test.ts has good coverage for the existing mention strategies (MXID, localpart, regex, room mentions), but has no tests at all for the new displayName parameter introduced in this PR. Without a test, the core scenario this PR fixes — a modern Matrix client formatting the mention anchor label as the bot's display name — has no regression guardrail.

Consider adding at minimum two tests to mentions.test.ts:

  1. A positive case: formatted_body with a matrix.to link pointing to the bot's MXID whose visible label equals the bot's displayName → wasMentioned should be true.
  2. A negative/security case: same label matching displayName, but the href targets a different user's MXID → wasMentioned should be false (to confirm the MXID gate still holds).
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/matrix/src/matrix/monitor/mentions.ts
Line: 105-110

Comment:
**No unit tests added for the new `displayName` matching path**

`mentions.test.ts` has good coverage for the existing mention strategies (MXID, localpart, regex, room mentions), but has no tests at all for the new `displayName` parameter introduced in this PR. Without a test, the core scenario this PR fixes — a modern Matrix client formatting the mention anchor label as the bot's display name — has no regression guardrail.

Consider adding at minimum two tests to `mentions.test.ts`:

1. A positive case: `formatted_body` with a matrix.to link pointing to the bot's MXID whose visible label equals the bot's `displayName` → `wasMentioned` should be `true`.
2. A negative/security case: same label matching `displayName`, but the `href` targets a *different* user's MXID → `wasMentioned` should be `false` (to confirm the MXID gate still holds).

How can I resolve this? If you propose a fix, please make it concise.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This coverage has now been implemented

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 06d6195dbd

ℹ️ 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".

@@ -43,6 +44,7 @@ function isVisibleMentionLabel(params: {
params.userId.trim().toLowerCase(),
localpart,
localpart ? `@${localpart}` : null,
params.displayName ? extractVisibleMentionText(params.displayName) : null,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Decode HTML entities in display-name mention matching

The new display-name candidate path compares extractVisibleMentionText(params.displayName) against anchor text without decoding HTML entities, so mentions fail when a display name contains escapable characters. In Matrix formatted HTML, a label like R&D Bot is typically rendered as R&amp;D Bot; this now normalizes to r&amp;d bot for the visible label but r&d bot for the room display name, causing resolveMentions to miss real mentions in requireMention rooms for those users.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel this is out of scope for this patch. Bots with HTML entities in their display name can be addressed in future work.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6be782a4eb

ℹ️ 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".

Comment on lines +549 to +551
const selfDisplayName = content.formatted_body
? await getMemberDisplayName(roomId, selfUserId).catch(() => undefined)
: undefined;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid per-message self profile lookups for formatted_body mentions

The new selfDisplayName assignment now awaits getMemberDisplayName(roomId, selfUserId) for every event that has formatted_body, even before mention gating. In extensions/matrix/src/matrix/monitor/room-info.ts, getMemberDisplayName only caches when displayname exists and returns userId without caching on missing state or errors, so rooms where the bot has no room display name (or state reads fail) will trigger a remote member-state lookup on every formatted message. This adds avoidable network latency and can throttle message processing in busy rooms.

Useful? React with 👍 / 👎.

@nickludlam
nickludlam force-pushed the fix-matrix-mentions branch from 6be782a to e12b024 Compare March 26, 2026 22:32
@nickludlam nickludlam changed the title Fix matrix mentions to work with displayName labels (with help from Antigravity) fix(matrix): mentions should work with displayName labels (with help from Antigravity) Mar 27, 2026
@gumadeiras gumadeiras self-assigned this Mar 27, 2026
@gumadeiras
gumadeiras force-pushed the fix-matrix-mentions branch from e12b024 to 8a4520a Compare March 27, 2026 22:43
gumadeiras added a commit to nickludlam/openclaw that referenced this pull request Mar 27, 2026
nickludlam and others added 6 commits March 27, 2026 19:15
- Newer matrix clients use displayName inside the anchor text
- Previously it only checked for a match on MXID or localpart
- We previously triggered expect(getMemberDisplayName).not.toHaveBeenCalled();
- We now only fetch the displayName when the message contains a formatted_body, as we only need to search those messages for mentions using displayName
@gumadeiras
gumadeiras force-pushed the fix-matrix-mentions branch from d76614a to c6df37c Compare March 27, 2026 23:16
@gumadeiras
gumadeiras merged commit 5d82534 into openclaw:main Mar 27, 2026
9 checks passed
@gumadeiras

Copy link
Copy Markdown
Member

Merged via squash.

Thanks @nickludlam!

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c6df37ce14

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

johnkhagler pushed a commit to johnkhagler/openclaw that referenced this pull request Mar 29, 2026
…from Antigravity) (openclaw#55393)

Merged via squash.

Prepared head SHA: c6df37c
Co-authored-by: nickludlam <[email protected]>
Co-authored-by: gumadeiras <[email protected]>
Reviewed-by: @gumadeiras
alexcode-cc pushed a commit to alexcode-cc/clawdbot that referenced this pull request Mar 30, 2026
…from Antigravity) (openclaw#55393)

Merged via squash.

Prepared head SHA: c6df37c
Co-authored-by: nickludlam <[email protected]>
Co-authored-by: gumadeiras <[email protected]>
Reviewed-by: @gumadeiras
lovewanwan pushed a commit to lovewanwan/openclaw that referenced this pull request Apr 28, 2026
…from Antigravity) (openclaw#55393)

Merged via squash.

Prepared head SHA: c6df37c
Co-authored-by: nickludlam <[email protected]>
Co-authored-by: gumadeiras <[email protected]>
Reviewed-by: @gumadeiras
ogt-redknie pushed a commit to ogt-redknie/OPENX that referenced this pull request May 2, 2026
…from Antigravity) (openclaw#55393)

Merged via squash.

Prepared head SHA: c6df37c
Co-authored-by: nickludlam <[email protected]>
Co-authored-by: gumadeiras <[email protected]>
Reviewed-by: @gumadeiras
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
…from Antigravity) (openclaw#55393)

Merged via squash.

Prepared head SHA: c6df37c
Co-authored-by: nickludlam <[email protected]>
Co-authored-by: gumadeiras <[email protected]>
Reviewed-by: @gumadeiras
Nachx639 pushed a commit to Nachx639/clawdbot that referenced this pull request Jun 17, 2026
…from Antigravity) (openclaw#55393)

Merged via squash.

Prepared head SHA: c6df37c
Co-authored-by: nickludlam <[email protected]>
Co-authored-by: gumadeiras <[email protected]>
Reviewed-by: @gumadeiras
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
…from Antigravity) (openclaw#55393)

Merged via squash.

Prepared head SHA: c6df37c
Co-authored-by: nickludlam <[email protected]>
Co-authored-by: gumadeiras <[email protected]>
Reviewed-by: @gumadeiras
zooqueen pushed a commit to zooqueen/openclaw that referenced this pull request Sep 11, 2026
zooqueen pushed a commit to zooqueen/openclaw that referenced this pull request Sep 11, 2026
zooqueen pushed a commit to zooqueen/openclaw that referenced this pull request Sep 11, 2026
globalcaos pushed a commit to globalcaos/tinkerclaw that referenced this pull request Sep 29, 2026
…from Antigravity) (openclaw#55393)

Merged via squash.

Prepared head SHA: c6df37c
Co-authored-by: nickludlam <[email protected]>
Co-authored-by: gumadeiras <[email protected]>
Reviewed-by: @gumadeiras
lhfer pushed a commit to lhfer/openclaw that referenced this pull request Oct 11, 2026
…from Antigravity) (openclaw#55393)

Merged via squash.

Prepared head SHA: c6df37c
Co-authored-by: nickludlam <[email protected]>
Co-authored-by: gumadeiras <[email protected]>
Reviewed-by: @gumadeiras
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: matrix Channel integration: matrix size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants