Skip to content

Commit caf5d2d

Browse files
emontyclaude
authored andcommitted
feat(matrix): Add multi-account support to Matrix channel
The Matrix channel previously hardcoded `listMatrixAccountIds` to always return only `DEFAULT_ACCOUNT_ID`, ignoring any accounts configured in `channels.matrix.accounts`. This prevented running multiple Matrix bot accounts simultaneously. Changes: - Update `listMatrixAccountIds` to read from `channels.matrix.accounts` config, falling back to `DEFAULT_ACCOUNT_ID` for legacy single-account configurations - Add `resolveMatrixConfigForAccount` to resolve config for a specific account ID, merging account-specific values with top-level defaults - Update `resolveMatrixAccount` to use account-specific config when available - The multi-account config structure (channels.matrix.accounts) was not defined in the MatrixConfig type, causing TypeScript to not recognize the field. Added the accounts field to properly type the multi-account configuration. - Add stopSharedClientForAccount() to stop only the specific account's client instead of all clients when an account shuts down - Wrap dynamic import in try/finally to prevent startup mutex deadlock if the import fails - Pass accountId to resolveSharedMatrixClient(), resolveMatrixAuth(), and createMatrixClient() to ensure the correct account's credentials are used for outbound messages - Add accountId parameter to resolveMediaMaxBytes to check account-specific config before falling back to top-level config - Maintain backward compatibility with existing single-account setups This follows the same pattern already used by the WhatsApp channel for multi-account support. Fixes #3165 Fixes #3085 Co-Authored-By: Claude Opus 4.5 <[email protected]>
1 parent 607b625 commit caf5d2d

17 files changed

Lines changed: 367 additions & 103 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,10 @@ Docs: https://docs.openclaw.ai
236236
- Memory/QMD: add `memory.qmd.searchMode` to choose `query`, `search`, or `vsearch` recall mode. (#9967, #10084)
237237
- Media understanding: recognize `.caf` audio attachments for transcription. (#10982) Thanks @succ985.
238238
- State dir: honor `OPENCLAW_STATE_DIR` for default device identity and canvas storage paths. (#4824) Thanks @kossoy.
239+
- Doctor/State dir: suppress repeated legacy migration warnings only for valid symlink mirrors, while keeping warnings for empty or invalid legacy trees. (#11709) Thanks @gumadeiras.
240+
- Tests: harden flaky hotspots by removing timer sleeps, consolidating onboarding provider-auth coverage, and improving memory test realism. (#11598) Thanks @gumadeiras.
241+
- macOS: honor Nix-managed defaults suite (`ai.openclaw.mac`) for nixMode to prevent onboarding from reappearing after bundle-id churn. (#12205) Thanks @joshp123.
242+
- Matrix: add multi-account support via `channels.matrix.accounts`; use per-account config for dm policy, allowFrom, groups, and other settings; serialize account startup to avoid race condition. (#3165, #3085) Thanks @emonty.
239243

240244
## 2026.2.6
241245

@@ -332,6 +336,7 @@ Docs: https://docs.openclaw.ai
332336
- macOS: fix cron payload summary rendering and ISO 8601 formatter concurrency safety.
333337
- Discord: enforce DM allowlists for agent components (buttons/select menus), honoring pairing store approvals and tag matches. (#11254) Thanks @thedudeabidesai.
334338

339+
335340
## 2026.2.2-3
336341

337342
### Fixes

‎docs/channels/matrix.md‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,47 @@ When E2EE is enabled, the bot will request verification from your other sessions
136136
Open Element (or another client) and approve the verification request to establish trust.
137137
Once verified, the bot can decrypt messages in encrypted rooms.
138138

139+
## Multi-account
140+
141+
Multi-account support: use `channels.matrix.accounts` with per-account credentials and optional `name`. See [`gateway/configuration`](/gateway/configuration#telegramaccounts--discordaccounts--slackaccounts--signalaccounts--imessageaccounts) for the shared pattern.
142+
143+
Each account runs as a separate Matrix user on any homeserver. Per-account config
144+
inherits from the top-level `channels.matrix` settings and can override any option
145+
(DM policy, groups, encryption, etc.).
146+
147+
```json5
148+
{
149+
channels: {
150+
matrix: {
151+
enabled: true,
152+
dm: { policy: "pairing" },
153+
accounts: {
154+
assistant: {
155+
name: "Main assistant",
156+
homeserver: "https://matrix.example.org",
157+
accessToken: "syt_assistant_***",
158+
encryption: true,
159+
},
160+
alerts: {
161+
name: "Alerts bot",
162+
homeserver: "https://matrix.example.org",
163+
accessToken: "syt_alerts_***",
164+
dm: { policy: "allowlist", allowFrom: ["@admin:example.org"] },
165+
},
166+
},
167+
},
168+
},
169+
}
170+
```
171+
172+
Notes:
173+
174+
- Account startup is serialized to avoid race conditions with concurrent module imports.
175+
- Env variables (`MATRIX_HOMESERVER`, `MATRIX_ACCESS_TOKEN`, etc.) only apply to the **default** account.
176+
- Base channel settings (DM policy, group policy, mention gating, etc.) apply to all accounts unless overridden per account.
177+
- Use `bindings[].match.accountId` to route each account to a different agent.
178+
- Crypto state is stored per account + access token (separate key stores per account).
179+
139180
## Routing model
140181

141182
- Replies always go back to Matrix.
@@ -256,4 +297,5 @@ Provider options:
256297
- `channels.matrix.mediaMaxMb`: inbound/outbound media cap (MB).
257298
- `channels.matrix.autoJoin`: invite handling (`always | allowlist | off`, default: always).
258299
- `channels.matrix.autoJoinAllowlist`: allowed room IDs/aliases for auto-join.
300+
- `channels.matrix.accounts`: multi-account configuration keyed by account ID (each account inherits top-level settings).
259301
- `channels.matrix.actions`: per-action tool gating (reactions/messages/pins/memberInfo/channelInfo).

‎extensions/matrix/src/channel.ts‎

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@ import { matrixOnboardingAdapter } from "./onboarding.js";
3131
import { matrixOutbound } from "./outbound.js";
3232
import { resolveMatrixTargets } from "./resolve-targets.js";
3333

34+
// Mutex for serializing account startup (workaround for concurrent dynamic import race condition)
35+
let matrixStartupLock: Promise<void> = Promise.resolve();
36+
3437
const meta = {
3538
id: "matrix",
3639
label: "Matrix",
@@ -383,9 +386,12 @@ export const matrixPlugin: ChannelPlugin<ResolvedMatrixAccount> = {
383386
probe: snapshot.probe,
384387
lastProbeAt: snapshot.lastProbeAt ?? null,
385388
}),
386-
probeAccount: async ({ timeoutMs, cfg }) => {
389+
probeAccount: async ({ account, timeoutMs, cfg }) => {
387390
try {
388-
const auth = await resolveMatrixAuth({ cfg: cfg as CoreConfig });
391+
const auth = await resolveMatrixAuth({
392+
cfg: cfg as CoreConfig,
393+
accountId: account.accountId,
394+
});
389395
return await probeMatrix({
390396
homeserver: auth.homeserver,
391397
accessToken: auth.accessToken,
@@ -424,8 +430,32 @@ export const matrixPlugin: ChannelPlugin<ResolvedMatrixAccount> = {
424430
baseUrl: account.homeserver,
425431
});
426432
ctx.log?.info(`[${account.accountId}] starting provider (${account.homeserver ?? "matrix"})`);
433+
434+
// Serialize startup: wait for any previous startup to complete import phase.
435+
// This works around a race condition with concurrent dynamic imports.
436+
//
437+
// INVARIANT: The import() below cannot hang because:
438+
// 1. It only loads local ESM modules with no circular awaits
439+
// 2. Module initialization is synchronous (no top-level await in ./matrix/index.js)
440+
// 3. The lock only serializes the import phase, not the provider startup
441+
const previousLock = matrixStartupLock;
442+
let releaseLock: () => void = () => {};
443+
matrixStartupLock = new Promise<void>((resolve) => {
444+
releaseLock = resolve;
445+
});
446+
await previousLock;
447+
427448
// Lazy import: the monitor pulls the reply pipeline; avoid ESM init cycles.
428-
const { monitorMatrixProvider } = await import("./matrix/index.js");
449+
// Wrap in try/finally to ensure lock is released even if import fails.
450+
let monitorMatrixProvider: typeof import("./matrix/index.js").monitorMatrixProvider;
451+
try {
452+
const module = await import("./matrix/index.js");
453+
monitorMatrixProvider = module.monitorMatrixProvider;
454+
} finally {
455+
// Release lock after import completes or fails
456+
releaseLock();
457+
}
458+
429459
return monitorMatrixProvider({
430460
runtime: ctx.runtime,
431461
abortSignal: ctx.abortSignal,

‎extensions/matrix/src/matrix/accounts.ts‎

Lines changed: 35 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { DEFAULT_ACCOUNT_ID, normalizeAccountId } from "openclaw/plugin-sdk";
22
import type { CoreConfig, MatrixConfig } from "../types.js";
3-
import { resolveMatrixConfig } from "./client.js";
3+
import { resolveMatrixConfigForAccount } from "./client.js";
44
import { credentialsMatchConfig, loadMatrixCredentials } from "./credentials.js";
55

66
export type ResolvedMatrixAccount = {
@@ -13,8 +13,21 @@ export type ResolvedMatrixAccount = {
1313
config: MatrixConfig;
1414
};
1515

16-
export function listMatrixAccountIds(_cfg: CoreConfig): string[] {
17-
return [DEFAULT_ACCOUNT_ID];
16+
function listConfiguredAccountIds(cfg: CoreConfig): string[] {
17+
const accounts = cfg.channels?.matrix?.accounts;
18+
if (!accounts || typeof accounts !== "object") {
19+
return [];
20+
}
21+
return Object.keys(accounts).filter(Boolean);
22+
}
23+
24+
export function listMatrixAccountIds(cfg: CoreConfig): string[] {
25+
const ids = listConfiguredAccountIds(cfg);
26+
if (ids.length === 0) {
27+
// Fall back to default if no accounts configured (legacy top-level config)
28+
return [DEFAULT_ACCOUNT_ID];
29+
}
30+
return ids.toSorted((a, b) => a.localeCompare(b));
1831
}
1932

2033
export function resolveDefaultMatrixAccountId(cfg: CoreConfig): string {
@@ -25,20 +38,35 @@ export function resolveDefaultMatrixAccountId(cfg: CoreConfig): string {
2538
return ids[0] ?? DEFAULT_ACCOUNT_ID;
2639
}
2740

41+
function resolveAccountConfig(cfg: CoreConfig, accountId: string): MatrixConfig | undefined {
42+
const accounts = cfg.channels?.matrix?.accounts;
43+
if (!accounts || typeof accounts !== "object") {
44+
return undefined;
45+
}
46+
return accounts[accountId] as MatrixConfig | undefined;
47+
}
48+
2849
export function resolveMatrixAccount(params: {
2950
cfg: CoreConfig;
3051
accountId?: string | null;
3152
}): ResolvedMatrixAccount {
3253
const accountId = normalizeAccountId(params.accountId);
33-
const base = params.cfg.channels?.matrix ?? {};
34-
const enabled = base.enabled !== false;
35-
const resolved = resolveMatrixConfig(params.cfg, process.env);
54+
const matrixBase = params.cfg.channels?.matrix ?? {};
55+
56+
// Check if this account exists in accounts structure
57+
const accountConfig = resolveAccountConfig(params.cfg, accountId);
58+
59+
// Use account-specific config if available, otherwise fall back to top-level
60+
const base: MatrixConfig = accountConfig ?? matrixBase;
61+
const enabled = base.enabled !== false && matrixBase.enabled !== false;
62+
63+
const resolved = resolveMatrixConfigForAccount(params.cfg, accountId, process.env);
3664
const hasHomeserver = Boolean(resolved.homeserver);
3765
const hasUserId = Boolean(resolved.userId);
3866
const hasAccessToken = Boolean(resolved.accessToken);
3967
const hasPassword = Boolean(resolved.password);
4068
const hasPasswordAuth = hasUserId && hasPassword;
41-
const stored = loadMatrixCredentials(process.env);
69+
const stored = loadMatrixCredentials(process.env, accountId);
4270
const hasStored =
4371
stored && resolved.homeserver
4472
? credentialsMatchConfig(stored, {

‎extensions/matrix/src/matrix/actions/client.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { normalizeAccountId } from "openclaw/plugin-sdk";
12
import type { CoreConfig } from "../../types.js";
23
import type { MatrixActionClient, MatrixActionClientOpts } from "./types.js";
34
import { getMatrixRuntime } from "../../runtime.js";
@@ -22,7 +23,9 @@ export async function resolveActionClient(
2223
if (opts.client) {
2324
return { client: opts.client, stopOnDone: false };
2425
}
25-
const active = getActiveMatrixClient();
26+
// Normalize accountId early to ensure consistent keying across all lookups
27+
const accountId = normalizeAccountId(opts.accountId);
28+
const active = getActiveMatrixClient(accountId);
2629
if (active) {
2730
return { client: active, stopOnDone: false };
2831
}
@@ -31,18 +34,21 @@ export async function resolveActionClient(
3134
const client = await resolveSharedMatrixClient({
3235
cfg: getMatrixRuntime().config.loadConfig() as CoreConfig,
3336
timeoutMs: opts.timeoutMs,
37+
accountId,
3438
});
3539
return { client, stopOnDone: false };
3640
}
3741
const auth = await resolveMatrixAuth({
3842
cfg: getMatrixRuntime().config.loadConfig() as CoreConfig,
43+
accountId,
3944
});
4045
const client = await createMatrixClient({
4146
homeserver: auth.homeserver,
4247
userId: auth.userId,
4348
accessToken: auth.accessToken,
4449
encryption: auth.encryption,
4550
localTimeoutMs: opts.timeoutMs,
51+
accountId,
4652
});
4753
if (auth.encryption && client.crypto) {
4854
try {

‎extensions/matrix/src/matrix/actions/types.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ export type MatrixRawEvent = {
5757
export type MatrixActionClientOpts = {
5858
client?: MatrixClient;
5959
timeoutMs?: number;
60+
accountId?: string | null;
6061
};
6162

6263
export type MatrixMessageSummary = {
Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,32 @@
11
import type { MatrixClient } from "@vector-im/matrix-bot-sdk";
2+
import { DEFAULT_ACCOUNT_ID } from "openclaw/plugin-sdk";
23

3-
let activeClient: MatrixClient | null = null;
4+
// Support multiple active clients for multi-account
5+
const activeClients = new Map<string, MatrixClient>();
46

5-
export function setActiveMatrixClient(client: MatrixClient | null): void {
6-
activeClient = client;
7+
export function setActiveMatrixClient(
8+
client: MatrixClient | null,
9+
accountId?: string | null,
10+
): void {
11+
const key = accountId ?? DEFAULT_ACCOUNT_ID;
12+
if (client) {
13+
activeClients.set(key, client);
14+
} else {
15+
activeClients.delete(key);
16+
}
717
}
818

9-
export function getActiveMatrixClient(): MatrixClient | null {
10-
return activeClient;
19+
export function getActiveMatrixClient(accountId?: string | null): MatrixClient | null {
20+
const key = accountId ?? DEFAULT_ACCOUNT_ID;
21+
return activeClients.get(key) ?? null;
22+
}
23+
24+
export function getAnyActiveMatrixClient(): MatrixClient | null {
25+
// Return any available client (for backward compatibility)
26+
const first = activeClients.values().next();
27+
return first.done ? null : first.value;
28+
}
29+
30+
export function clearAllActiveMatrixClients(): void {
31+
activeClients.clear();
1132
}
Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,14 @@
11
export type { MatrixAuth, MatrixResolvedConfig } from "./client/types.js";
22
export { isBunRuntime } from "./client/runtime.js";
3-
export { resolveMatrixConfig, resolveMatrixAuth } from "./client/config.js";
3+
export {
4+
resolveMatrixConfig,
5+
resolveMatrixConfigForAccount,
6+
resolveMatrixAuth,
7+
} from "./client/config.js";
48
export { createMatrixClient } from "./client/create-client.js";
5-
export { resolveSharedMatrixClient, waitForMatrixSync, stopSharedClient } from "./client/shared.js";
9+
export {
10+
resolveSharedMatrixClient,
11+
waitForMatrixSync,
12+
stopSharedClient,
13+
stopSharedClientForAccount,
14+
} from "./client/shared.js";

0 commit comments

Comments
 (0)