Disclaimer: This write-up, analysis, patch, and all accompanying scripts were generated with the assistance of Claude, an AI language model. While care has been taken to ensure accuracy, AI-generated output can contain errors. You should independently review and verify all code, scripts, and instructions before running them, particularly the shell script (which makes authenticated API requests using your access token) and the patch (which modifies application source code that you will compile and install on your device). Do not run anything you do not understand.

Element X Android: Group DM Bug

Analysis, debugging tools, and a proposed fix for the issue where searching for a user opens a group DM instead of a 1:1 conversation.

1. How Matrix Direct Messages Work

Matrix is a federated messaging protocol. Understanding two concepts is key to this bug: rooms and the m.direct account data.

Rooms

Every conversation in Matrix is a room—whether it's a 1:1 chat, a group DM, or a public channel. Rooms have a unique ID like !abcdef:matrix.org and track their own membership list. A room doesn't inherently "know" whether it's a DM; that distinction is layered on top by clients.

The m.direct Account Data

Matrix stores a per-account blob called m.direct that tells clients which rooms the user considers to be "direct" conversations. It's a JSON object mapping user IDs to arrays of room IDs:

{
  "@alice:matrix.org": ["!room1:matrix.org", "!room2:matrix.org"],
  "@bob:matrix.org":   ["!room3:matrix.org"]
}

This is client-managed—the server doesn't enforce it. Clients write to it when creating DMs, but the data can easily become inconsistent. For instance, a group DM created with Alice and Bob might only be recorded under Alice's entry, depending on which client created it and how that client chose to update m.direct.

What makes a room a "true" 1:1 DM?

A room is a 1:1 DM when both of these are true:

A room can be flagged as "direct" but still have 3+ members—that's a group DM. The distinction matters, and the bug is about getting it wrong.

2. How Element X Implements "Start DM"

When you search for a user and tap their name, the app goes through a specific code path. Here's the chain, simplified:

User taps search result | v StartChatPresenter ──> StartDMAction.execute(userId) | v MatrixClient.startDM(userId) // StartDM.kt | ├──> findDM(userId) // Look for existing DM | | | └──> RustSDK.getDmRoom(userId) // Delegates to Rust | ├── found? ──> Open that room // BUG: may be a group DM! └── not found? ──> createDM(userId) // Create a new 1:1 room

The Kotlin layer: startDM()

In StartDM.kt, the logic first tries to find an existing DM. If one is found, it's reused. Otherwise a new room is created:

suspend fun MatrixClient.startDM(
    userId: UserId,
    createIfDmDoesNotExist: Boolean,
): StartDMResult {
    return findDM(userId)
        .fold(
            onSuccess = { existingDM ->
                if (existingDM != null) {
                    StartDMResult.Success(existingDM, isNew = false)
                } else if (createIfDmDoesNotExist) {
                    createDM(userId).fold(...)
                } else { ... }
            }, ...
        )
}

The Rust SDK: getDmRoom()

The findDM() call in Kotlin delegates to the Rust SDK's get_dm_room():

// Rust: crates/matrix-sdk/src/client/mod.rs
pub fn get_dm_room(&self, user_id: &UserId) -> Option<Room> {
    let rooms = self.joined_rooms();
    // Find the room we share with the `user_id` and only with `user_id`
    rooms.into_iter().find(|r| {
        let targets = r.direct_targets();
        targets.len() == 1 && targets.contains(user_id)
    })
}

This checks that direct_targets (derived from m.direct) has exactly one entry matching the requested user. But it does not check how many people are actually in the room.

3. The Bug BUG

Root cause

The Rust SDK's direct_targets comes from the m.direct account data—it records which user IDs the room is filed under, not how many people are in the room. These are two different things.

The trigger scenario

  1. You create a group DM with Alice and Bob.
  2. Your client writes the room to m.direct under only one user (e.g. Alice). This is common—m.direct is an imprecise client-managed signal.
  3. The Rust SDK processes m.direct and sets dm_targets = {Alice} for that room. Length is 1.
  4. You search for Alice and tap her name.
  5. getDmRoom("Alice") scans your rooms, finds the group DM where targets.len() == 1 && targets.contains(Alice) — match!
  6. The group DM (with Alice, Bob, and you) is returned as your "1:1 DM with Alice."
Result: You're taken to a 3+ person group DM instead of a private conversation with Alice. Anything you type is visible to everyone in that group.

Why the existing code almost gets it right

The codebase already has a correct DM-checking function in RoomIsDmCheck.kt:

fun isDm(isDirect: Boolean, activeMembersCount: Int): Boolean {
    return isDirect && activeMembersCount <= 2
}

This check is used elsewhere in the app (e.g. in the recent conversations list), but it is not applied in findDM(). The findDM() method blindly trusts whatever the Rust SDK returns.

The fix PATCH

The fix adds an activeMembersCount check to the Kotlin findDM() method. If the room returned by the Rust SDK has more than 2 active members, it's not a true 1:1 DM, so null is returned instead—causing the app to create a proper new DM room:

@@ libraries/matrix/impl/.../RustMatrixClient.kt @@
 override suspend fun findDM(userId: UserId): Result<RoomId?> = ...{
     runCatchingExceptions {
-        innerClient.getDmRoom(userId.value)?.use { RoomId(it.id()) }
+        innerClient.getDmRoom(userId.value)?.use { room ->
+            // getDmRoom can return group DMs where the user is a member
+            // but the room has more than 2 active participants. Only
+            // treat the room as a true 1-on-1 DM when the active member
+            // count is at most 2 (the current user + the target user).
+            val activeMemberCount = room.activeMembersCount().toLong()
+            if (activeMemberCount <= 2) RoomId(room.id()) else null
+        }
     }
 }

You can review the complete patch file: fix-findDM-group-dm.patch

4. Diagnose: Check If Your Account Is Affected TOOL

We provide a shell script that queries the Matrix API to inspect your m.direct data and cross-references it with the actual membership of each room. It will flag any rooms that would trigger the bug.

Prerequisites

Getting your access token

In Element X Android: Settings → Advanced settings → Session token. You may need to enable Developer options first in Settings.

Security warning: Your access token grants full access to your Matrix account. Running this script will place the token in your shell history. To keep it out of your shell history, use one of these approaches:
# Option 1: Read the token into a variable without echoing it
read -rs TOKEN
./inspect-mdirect.sh @you:matrix.org "$TOKEN"
unset TOKEN

# Option 2: Prefix with a space (works if your shell has
# HISTCONTROL=ignorespace or HIST_IGNORE_SPACE set)
 ./inspect-mdirect.sh @you:matrix.org YOUR_TOKEN_HERE

Download and run the script

# Download
curl -O https://<this-server>/files/inspect-mdirect.sh
chmod +x inspect-mdirect.sh

# Run
./inspect-mdirect.sh @you:matrix.org YOUR_ACCESS_TOKEN

What the script does (so you can audit it)

The script performs only read-only GET requests against the Matrix API. It does not modify any data. Here is exactly what it does, step by step:

  1. Resolves your homeserver. Extracts the domain from your user ID (the part after :) and fetches https://<domain>/.well-known/matrix/client to find the actual homeserver URL. Falls back to https://<domain> if .well-known is unavailable.
  2. Fetches m.direct. Calls GET /_matrix/client/v3/user/<your_id>/account_data/m.direct. This returns the JSON object mapping user IDs to room IDs.
  3. Fetches joined members for each room. For every room ID found in m.direct, calls GET /_matrix/client/v3/rooms/<room_id>/joined_members to get the actual member list.
  4. Compares and reports. For each room, it prints: Rooms with dm_targets == 1 but actual members > 2 are flagged as *** BUG TRIGGER.

Reading the output

# This is a true 1:1 DM — no problem
  OK (true 1:1 DM): !abc:matrix.org
      m.direct targets: 1
      Actual members:   2
      Members: @you:matrix.org, @alice:matrix.org

# This triggers the bug!
  *** BUG TRIGGER: !xyz:matrix.org
      m.direct target: @alice:matrix.org
        ^ Search for this user in Element X to reproduce the bug
      Actual members:  3 (this is really a group DM!)
      Members: @you:matrix.org, @alice:matrix.org, @bob:matrix.org

If you see any *** BUG TRIGGER lines, your account is affected. The script tells you exactly which user to search for in Element X to reproduce the bug—it's the m.direct target line. Searching for that user in the unpatched app will open the group DM instead of a 1:1 conversation.

5. Build the Patched APK PATCH

The build runs entirely inside a Docker container so you don't need to install the Android SDK or JDK on your host machine. All you need is Docker (or Podman).

Download the build files

You need three files, all in the same directory:

Dockerfile
Defines the full build environment: Arch Linux + JDK 21 + Android SDK + Gradle
fix-findDM-group-dm.patch
The 7-line patch to RustMatrixClient.kt (the actual bug fix)
build-patched-apk.sh
Convenience script that runs docker build and extracts the APKs
# Download all three into one directory
mkdir element-x-fix && cd element-x-fix
curl -O https://<this-server>/files/Dockerfile
curl -O https://<this-server>/files/fix-findDM-group-dm.patch
curl -O https://<this-server>/files/build-patched-apk.sh
chmod +x build-patched-apk.sh

What each file does (so you can audit them)

The patch (fix-findDM-group-dm.patch)

This is the only change to Element X's source code. It modifies one method in one file. You can read it in full—it's 21 lines including context:

The Dockerfile

The Dockerfile builds the APK in these stages (each is a separate layer you can inspect):

StepWhat it doesWhy
pacman -S jdk21-openjdk ... Installs JDK 21, git, curl, unzip Build toolchain requirements
curl ... commandlinetools Downloads Android SDK command-line tools from Google Needed to install SDK components
sdkmanager ... Installs Android platform 36, build-tools 35 & 36 Compile targets required by the project
git clone ... element-x-android Clones the official Element X Android repo (shallow) The source code to build
git apply fix-findDM-group-dm.patch Applies our 7-line fix The bug fix
./gradlew :app:assembleGplayDebug Compiles the app into debug APKs Produces installable APKs

The build skips lint, tests, detekt, and ktlint (-x lint -x test -x detekt -x ktlintCheck) to save time. These are code quality checks, not compilation steps.

The build script (build-patched-apk.sh)

This is a thin wrapper that runs docker build, creates a temporary container, copies the APKs out of it to an output/ directory, and cleans up. You can read it in under a minute—it's 25 lines.

Run the build

./build-patched-apk.sh

This will take 10–20 minutes depending on your internet speed and CPU. When done, the APKs will be in output/:

FileSizeUse for
app-gplay-arm64-v8a-debug.apk~142 MBMost modern phones (2017+)
app-gplay-armeabi-v7a-debug.apk~117 MBOlder 32-bit ARM phones
app-gplay-x86_64-debug.apk~148 MBx86_64 emulators
app-gplay-universal-debug.apk~350 MBAny architecture (if unsure)

6. Install and Verify the Fix

Install the APK

  1. Transfer the appropriate APK to your Android device (USB, cloud storage, etc.). For most modern phones, use app-gplay-arm64-v8a-debug.apk.
  2. On your device, open the file. Android will ask you to allow installing from unknown sources—grant it temporarily.
  3. This is a debug build with a different application ID (io.element.android.x.debug), so it installs alongside the production app. Your existing Element X installation is not affected.
Note: Because this is a debug build with a separate application ID, you will need to log in again in the patched app. Your existing Element X app and its data are untouched.

Verify the fix

  1. Log into the patched app with the same account you used for diagnosis.
  2. Look at the diagnostic script output for any *** BUG TRIGGER entries. Each one includes an m.direct target line showing the specific user to search for (e.g. @alice:matrix.org).
  3. In the patched app, tap Start Chat (the compose/new message button), search for that user, and tap their name.
  4. Expected result: A new 1:1 DM room is created (or an existing true 1:1 DM is opened). You should not be taken to the group DM.
  5. Compare with the unpatched production app: do the same search there and observe that it incorrectly opens the group DM. This confirms the fix works.
If the fix works: The patched app creates/opens a 1:1 room, while the production app opens the group DM. The bug is confirmed and the patch resolves it.

Clean up

After testing, you can uninstall the debug build normally from Android settings. Remember to:

7. Downloads

inspect-mdirect.sh
Diagnostic script — checks your account for rooms affected by the bug. Requires bash, curl, python3.
fix-findDM-group-dm.patch
The patch file (7 lines changed in RustMatrixClient.kt).
Dockerfile
Full reproducible build environment. Arch Linux + JDK 21 + Android SDK.
build-patched-apk.sh
One-command build script. Runs docker build and extracts the APKs.

Affected project: element-hq/element-x-android. Bug location: libraries/matrix/impl/.../RustMatrixClient.kt line 344. Upstream Rust SDK function: matrix-rust-sdk/crates/matrix-sdk/src/client/mod.rs get_dm_room().