Impl MSC4461: Storing per-message profiles for users (#1589)

<!-- Please read
https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before
submitting your pull request -->

### Description

<!-- Please include a summary of the change. Please also include
relevant motivation and context. List any dependencies that are required
for this change. -->

Migrates PMP account data to the format described in
[MSC4461](https://github.com/matrix-org/matrix-spec-proposals/pull/4461).
Extensions to the format are defined in my informal
[MSCF002](https://github.com/j0lol/matrix-spec-proposals/blob/mscf/proposals/F0002-PK-proxy-tags.md).
(Though ambiguity behavior defined in this spec have not been
implemented just yet.)

Part of #1279

#### Type of change
breaking change on an experimental feature, with migrations

- [ ] Bug fix (non-breaking change which fixes an issue)
- [x] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [ ] This change requires a documentation update

### Checklist:

- [x] My code follows the style guidelines of this project
- [x] I have performed a self-review of my own code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings

### AI disclosure:

- [ ] Partially AI assisted (clarify which code was AI assisted and
briefly explain what it does).
- [ ] Fully AI generated (explain what all the generated code does in
moderate detail).
<!-- Write any explanation required here, but do not generate the
explanation using AI!! You must prove you understand what the code in
this PR does. -->
This commit is contained in:
Erwan Leboucher authored and GitHub committed 2026-08-03 19:46:44 +00:00
commit 4a735be2ba
21 files changed
+664 -523

No files matched your search

@@ -1,11 +1,10 @@
import type {
PerMessageProfile,
PerMessageProfileMsc4461,
PerMessageProfileProxyAssociationV2,
ProfileTrigger,
} from '$hooks/usePerMessageProfile';
import {
addOrUpdatePerMessageProfile,
associateProxyWithProfile,
dropProxyAssociationForPMP,
extractCircumfixProxyTagsFromKey,
getAllPerMessageProfiles,
getPerMessageProfileById,
@@ -13,6 +12,10 @@ import {
import { sendFeedback } from '$utils/sendFeedbackToUser';
import type { MatrixClient, Room } from '$types/matrix-sdk';
import { generateShortId } from '$utils/shortIdGen';
import {
MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_CIRCUMFIX_PROPERTY_NAME,
MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_SUFFIX_PROPERTY_NAME,
} from '$unstable/prefixes';
const pkMemberRenameRegex = /^(pk;member)\s+"?([\w\s]+)"?\s*rename\s+"?([\w\s]+)"?$/;
const pkMemberNewRegex = /^(pk;member)\s+new\s+"?([\w\s]+)"?$/;
@@ -47,6 +50,27 @@ export function buildProxyRegex({ prefix, suffix }: PerMessageProfileProxyAssoci
return new RegExp(`^${pattern}$`);
}
export function testTriggers(triggers: ProfileTrigger, input: string): boolean {
const matchesPrefix = triggers.prefix.some((prefix) => input.startsWith(prefix));
if (matchesPrefix) return true;
const matchesSuffix = triggers[MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_SUFFIX_PROPERTY_NAME]?.some(
(suffix) => input.startsWith(suffix)
);
if (matchesSuffix) return true;
const matchesCircumfix = triggers[
MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_CIRCUMFIX_PROPERTY_NAME
]?.some(({ prefix, suffix }) => {
const casePrefix = prefix ? input.startsWith(prefix) : true;
const caseSuffix = suffix ? input.endsWith(suffix) : true;
return casePrefix && caseSuffix;
});
return !!matchesCircumfix;
}
export function testProxy(
{ prefix, suffix }: PerMessageProfileProxyAssociationV2,
input: string
@@ -56,8 +80,26 @@ export function testProxy(
return matchesPrefix && matchesSuffix;
}
export function stripTrigger(triggers: ProfileTrigger, input: string): string {
const prefix = triggers.prefix.find((value) => input.startsWith(value));
if (prefix !== undefined) return stripProxy({ prefix }, input);
const suffix = triggers[MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_SUFFIX_PROPERTY_NAME]?.find(
(value) => input.endsWith(value)
);
if (suffix !== undefined) return stripProxy({ suffix }, input);
const circumfix = triggers[MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_CIRCUMFIX_PROPERTY_NAME]?.find(
(trigger) => input.startsWith(trigger.prefix) && input.endsWith(trigger.suffix)
);
if (circumfix) return stripProxy(circumfix, input);
return input;
}
export function stripProxy(
{ prefix, suffix }: PerMessageProfileProxyAssociationV2,
{ prefix, suffix }: { prefix?: string; suffix?: string },
input: string
): string {
let message = input;
@@ -128,7 +170,8 @@ export class PKitCommandMessageHandler {
);
await addOrUpdatePerMessageProfile(this.mx, {
id: generatedID,
name: memberName,
displayname: memberName,
trigger: { prefix: [] },
});
sendFeedback(
`added new member has been created with id: ${generatedID} and name ${memberName}`,
@@ -159,7 +202,7 @@ export class PKitCommandMessageHandler {
* The id of the per-message-profile
*/
const pmpId = (await getAllPerMessageProfiles(this.mx)).find(
(pmp) => pmp.name === oldName
(pmp) => pmp.displayname === oldName
)?.id;
if (!pmpId) {
sendFeedback(
@@ -190,7 +233,7 @@ export class PKitCommandMessageHandler {
);
return;
}
pmp.name = newName;
pmp.displayname = newName;
sendFeedback(
`renaming your profile ${pmpId} from ${oldName} to ${newName}`,
this.room,
@@ -204,7 +247,7 @@ export class PKitCommandMessageHandler {
const matchAgainst = cmdParts[3];
const pmpId = this.useIdInsteadOfNameWherePossible
? name
: (await getAllPerMessageProfiles(this.mx)).find((pmp) => pmp.name === name)?.id;
: (await getAllPerMessageProfiles(this.mx)).find((pmp) => pmp.displayname === name)?.id;
if (!pmpId) {
sendFeedback(
`Persona with ${this.useIdInsteadOfNameWherePossible ? 'id' : 'name'} "${name}" doesn't exist in your records, ${helpTextPkMemberNew}`,
@@ -222,13 +265,33 @@ export class PKitCommandMessageHandler {
);
return;
}
await dropProxyAssociationForPMP(this.mx, matchAgainst);
const proxyTags = extractCircumfixProxyTagsFromKey(matchAgainst);
const pmp = await getPerMessageProfileById(this.mx, pmpId);
sendFeedback(
`Persona with ${this.useIdInsteadOfNameWherePossible ? 'id' : 'name'} "${name}" (${pmpId}) is now no longer associated with ${matchAgainst}`,
this.room,
this.mx.getSafeUserId()
);
if (pmp && proxyTags) {
const { prefix, suffix } = proxyTags;
if (prefix && suffix) {
pmp.trigger[MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_CIRCUMFIX_PROPERTY_NAME] ??= [];
pmp.trigger[MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_CIRCUMFIX_PROPERTY_NAME] = pmp.trigger[
MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_CIRCUMFIX_PROPERTY_NAME
].filter((trigger) => trigger.prefix !== prefix && trigger.suffix !== suffix);
} else if (prefix && !suffix) {
pmp.trigger.prefix = pmp.trigger.prefix.filter((trigger) => trigger !== prefix);
} else if (!prefix && suffix) {
pmp.trigger[MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_SUFFIX_PROPERTY_NAME] ??= [];
pmp.trigger[MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_SUFFIX_PROPERTY_NAME] = pmp.trigger[
MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_SUFFIX_PROPERTY_NAME
].filter((trigger) => trigger !== suffix);
}
await addOrUpdatePerMessageProfile(this.mx, pmp);
sendFeedback(
`Persona with ${this.useIdInsteadOfNameWherePossible ? 'id' : 'name'} "${name}" (${pmpId}) is now no longer associated with ${matchAgainst}`,
this.room,
this.mx.getSafeUserId()
);
}
} else if (pkMemberNewProxy.test(this.message)) {
const cmdParts = pkMemberNewProxy.exec(this.message);
if (!cmdParts) return;
@@ -236,7 +299,7 @@ export class PKitCommandMessageHandler {
const matchAgainst = cmdParts[4];
const pmpId = this.useIdInsteadOfNameWherePossible
? name
: (await getAllPerMessageProfiles(this.mx)).find((pmp) => pmp.name === name)?.id;
: (await getAllPerMessageProfiles(this.mx)).find((pmp) => pmp.displayname === name)?.id;
if (!pmpId) {
sendFeedback(
`Persona with ${this.useIdInsteadOfNameWherePossible ? 'id' : 'name'} "${name}" doesn't exist in your records, ${helpTextPkMemberNew}`,
@@ -263,17 +326,37 @@ export class PKitCommandMessageHandler {
);
return;
}
await associateProxyWithProfile(this.mx, pmpId, proxyTags.prefix, proxyTags.suffix, false);
sendFeedback(
`Persona with ${this.useIdInsteadOfNameWherePossible ? 'id' : 'name'} "${name}" (${pmpId}) is now associated with ${matchAgainst}`,
this.room,
this.mx.getSafeUserId()
);
let pmp = await getPerMessageProfileById(this.mx, pmpId);
if (pmp) {
const { prefix, suffix } = proxyTags;
if (prefix && suffix) {
(pmp.trigger[MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_CIRCUMFIX_PROPERTY_NAME] ??= []).push({
prefix: prefix,
suffix: suffix,
});
} else if (!prefix && suffix) {
(pmp.trigger[MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_SUFFIX_PROPERTY_NAME] ??= []).push(
suffix
);
} else if (prefix && !suffix) {
pmp.trigger.prefix.push(prefix);
}
await addOrUpdatePerMessageProfile(this.mx, pmp);
sendFeedback(
`Persona with ${this.useIdInsteadOfNameWherePossible ? 'id' : 'name'} "${name}" (${pmpId}) is now associated with ${matchAgainst}`,
this.room,
this.mx.getSafeUserId()
);
}
} else {
// default to looking up member info
const listOfProfiles: PerMessageProfile[] = await getAllPerMessageProfiles(this.mx);
const listOfProfiles: PerMessageProfileMsc4461[] = await getAllPerMessageProfiles(this.mx);
const stringListOfProfiles: string = listOfProfiles
.map((pmp: PerMessageProfile) => `${pmp.id}: ${pmp.name ? pmp.name : '(empty name)'}`)
.map(
(pmp: PerMessageProfileMsc4461) =>
`${pmp.id}: ${pmp.displayname ? pmp.displayname : '(empty name)'}`
)
.join('\n');
sendFeedback(
`If you see this, you have messed up a command\n\nYou currently have the following persona set up:\n${stringListOfProfiles}\n\n${helpTextPkMember}`,
@@ -6,7 +6,7 @@ import type { MatrixClient } from '$types/matrix-sdk';
// Mock the hook module that provides proxy associations + profile lookup
vi.mock('$hooks/usePerMessageProfile', () => ({
getAllPerMessageProfileProxies: vi.fn<() => Promise<unknown[]>>(),
getAllPerMessageProfiles: vi.fn<() => Promise<unknown[]>>(),
getPerMessageProfileById: vi.fn<() => Promise<unknown>>(),
parsePerMessageProfileProxyAssociation: vi.fn<() => unknown>(),
}));
@@ -24,18 +24,36 @@ describe('PKitProxyMessageHandler', () => {
});
it('matches a proxied message, returns pmp, and strips content', async () => {
(mocked.getAllPerMessageProfileProxies as unknown as Mock).mockResolvedValueOnce([
{ profileId: 'p1', prefix: '[', suffix: ']' },
(mocked.getAllPerMessageProfiles as unknown as Mock).mockResolvedValueOnce([
{
id: 'p1',
name: 'Test',
trigger: {
prefix: [],
'net.f0rest.circumfix': [{ prefix: '[', suffix: ']' }],
},
},
]);
(mocked.getPerMessageProfileById as unknown as Mock).mockResolvedValueOnce({
id: 'p1',
name: 'Test',
trigger: {
prefix: [],
'net.f0rest.circumfix': [{ prefix: '[', suffix: ']' }],
},
});
const handler = new PKitProxyMessageHandler({} as unknown as MatrixClient);
const pmp = await handler.getPmpBasedOnMessage('[hello]');
expect(pmp).toEqual({ id: 'p1', name: 'Test' });
expect(pmp).toEqual({
id: 'p1',
name: 'Test',
trigger: {
prefix: [],
'net.f0rest.circumfix': [{ prefix: '[', suffix: ']' }],
},
});
// getPmpBasedOnMessage refreshes/init() so we should be inited now
expect(handler.isAProxiedMessage('[hello]')).toBe(true);
@@ -1,13 +1,7 @@
import type {
PerMessageProfile,
PerMessageProfileProxyAssociationV2,
} from '$hooks/usePerMessageProfile';
import {
getAllPerMessageProfileProxies,
getPerMessageProfileById,
} from '$hooks/usePerMessageProfile';
import type { PerMessageProfileMsc4461 } from '$hooks/usePerMessageProfile';
import { getAllPerMessageProfiles, getPerMessageProfileById } from '$hooks/usePerMessageProfile';
import type { MatrixClient } from '$types/matrix-sdk';
import { stripProxy, testProxy } from './PKitCommandMessageHandler';
import { stripTrigger, testTriggers } from './PKitCommandMessageHandler';
/**
* proxy message handler
@@ -24,12 +18,12 @@ export class PKitProxyMessageHandler {
private readonly mx: MatrixClient;
/**
* a list of proxies; is not initialized in the constructor
* a list of profiles; is not initialized in the constructor
* @private
* @type {PerMessageProfileProxyAssociation[]}
* @type {PerMessageProfileMsc4461[]}
* @memberof PKitProxyMessageHandler
*/
private proxiesAssocs: PerMessageProfileProxyAssociationV2[];
private profiles: PerMessageProfileMsc4461[];
private succInit: boolean;
@@ -39,7 +33,7 @@ export class PKitProxyMessageHandler {
*/
public constructor(mx: MatrixClient) {
this.mx = mx;
this.proxiesAssocs = [];
this.profiles = [];
this.succInit = false;
}
@@ -48,7 +42,7 @@ export class PKitProxyMessageHandler {
*/
public async init(): Promise<void> {
try {
this.proxiesAssocs = await getAllPerMessageProfileProxies(this.mx);
this.profiles = await getAllPerMessageProfiles(this.mx);
this.succInit = true;
} catch (err) {
this.succInit = false;
@@ -64,7 +58,7 @@ export class PKitProxyMessageHandler {
*/
public isAProxiedMessage(message: string): boolean {
if (!this.succInit) return false;
return this.proxiesAssocs.some((assoc) => testProxy(assoc, message));
return this.profiles.some((profile) => testTriggers(profile.trigger, message));
}
/**
@@ -72,11 +66,13 @@ export class PKitProxyMessageHandler {
* @param message the message to look at
* @returns the matching Per-Message-Profile, if any
*/
public async getPmpBasedOnMessage(message: string): Promise<PerMessageProfile | undefined> {
public async getPmpBasedOnMessage(
message: string
): Promise<PerMessageProfileMsc4461 | undefined> {
// Always refresh so newly-added proxies apply immediately.
await this.init();
// check if the message matches our formats
const profileId = this.proxiesAssocs.find((assoc) => testProxy(assoc, message))?.profileId;
const profileId = this.profiles.find((profile) => testTriggers(profile.trigger, message))?.id;
if (!profileId) return undefined;
return getPerMessageProfileById(this.mx, profileId);
}
@@ -91,8 +87,8 @@ export class PKitProxyMessageHandler {
public stripProxyFromMessage(message: string): string | undefined {
if (!this.succInit) return undefined;
let m;
this.proxiesAssocs.forEach((assoc) => {
if (testProxy(assoc, message)) m = stripProxy(assoc, message);
this.profiles.forEach((profile) => {
if (testTriggers(profile.trigger, message)) m = stripTrigger(profile.trigger, message);
});
return m;
}