From a842bce6e1471536b1a99d805db353166bc2b067 Mon Sep 17 00:00:00 2001
From: Rye
Date: Wed, 18 Mar 2026 15:05:43 +0100
Subject: [PATCH 01/58] stub: add PluralKit command message handler and data
models
---
.../pluralkitImportFormat.ts | 128 ++++++++++++++++++
.../pluralkitMessageHandler.ts | 48 +++++++
.../pluralkitSyntaxAdapter.ts | 0
3 files changed, 176 insertions(+)
create mode 100644 src/app/plugins/pluralkit-handler/pluralkitImportFormat.ts
create mode 100644 src/app/plugins/pluralkit-handler/pluralkitMessageHandler.ts
create mode 100644 src/app/plugins/pluralkit-handler/pluralkitSyntaxAdapter.ts
diff --git a/src/app/plugins/pluralkit-handler/pluralkitImportFormat.ts b/src/app/plugins/pluralkit-handler/pluralkitImportFormat.ts
new file mode 100644
index 000000000..f3cbe51f8
--- /dev/null
+++ b/src/app/plugins/pluralkit-handler/pluralkitImportFormat.ts
@@ -0,0 +1,128 @@
+/**
+ * the {@link https://pluralkit.me/api/models/#system-model data model for a pluralkit system}
+ * @since 1.10.0
+ * @author Rye
+ */
+export type PluralKitSystem = {
+ /**
+ * id is freeform string
+ * @since 1.10.0
+ */
+ id: string;
+ /**
+ * uuid of a system
+ * @since 1.10.0
+ */
+ uuid: string;
+ name?: string;
+ /**
+ * description for a system
+ * @since 1.10.0
+ */
+ description?: string;
+ /**
+ * tag for a system
+ * @since 1.10.0
+ */
+ tag?: string;
+ /**
+ * the pronouns of a system
+ * @since 1.10.0
+ */
+ pronouns?: string;
+ /**
+ * Attention this is a http url not a mxc url, you need to consider that.
+ * @since 1.10.0
+ */
+ avatar_url?: string;
+ /**
+ * this is a http url, so you have to download it and upload it to your homeserver
+ * @since 1.10.0
+ */
+ banner?: string;
+ /**
+ * The color of a system
+ * @since 1.10.0
+ */
+ color?: string;
+ /**
+ * Date string in ISO 8601 format, e.g. "2024-01-01T00:00:00Z" (assumingly)
+ * @since 1.10.0
+ */
+ created: string;
+};
+
+export type PluralKitProxyTag = {
+ prefix?: string;
+ suffix?: string;
+};
+
+/**
+ * the {@link https://pluralkit.me/api/models/#member-model Data model for a system member}
+ * @since 1.10.0
+ * @author Rye
+ */
+export type PluralKitMember = {
+ /**
+ * a freeform id demarking a member of a system
+ * @since 1.10.0
+ */
+ id: string;
+ /**
+ * uuid of a member
+ * @since 1.10.0
+ */
+ uuid: string;
+ /**
+ * the name a member of a system uses
+ * @since 1.10.0
+ */
+ name: string;
+ /**
+ * the display name a member of a system uses
+ * @since 1.10.0
+ */
+ display_name?: string;
+ /**
+ * the color a member of a system uses
+ * @since 1.10.0
+ */
+ color?: string;
+ /**
+ * pronouns the member of a system uses
+ * @since 1.10.0
+ */
+ pronouns?: string;
+ /**
+ * this is a http url, so you have to download it and upload it to your homeserver
+ * @since 1.10.0
+ */
+ avatar_url?: string;
+ /**
+ * probably won't be really usable in our usecase
+ * @since 1.10.0
+ */
+ webhook_avatar_url?: string;
+ /**
+ * this is a http url, so you have to download it and upload it to your homeserver
+ * @since 1.10.0
+ */
+ banner?: string;
+ /**
+ * a description of a member of a system
+ * this could be as long as 1000 chars
+ * @since 1.10.0
+ */
+ description?: string;
+ /**
+ * date when it was created
+ * @since 1.10.0
+ */
+ created: string;
+ proxy_tags: Array;
+ /**
+ * a boolean to denote if it's a sticky proxy
+ */
+ keep_proxy: boolean;
+ autoproxy_enabled?: boolean;
+};
diff --git a/src/app/plugins/pluralkit-handler/pluralkitMessageHandler.ts b/src/app/plugins/pluralkit-handler/pluralkitMessageHandler.ts
new file mode 100644
index 000000000..07d36bf3e
--- /dev/null
+++ b/src/app/plugins/pluralkit-handler/pluralkitMessageHandler.ts
@@ -0,0 +1,48 @@
+import {
+ addOrUpdatePerMessageProfile,
+ getAllPerMessageProfiles,
+} from '$hooks/usePerMessageProfile';
+import { sendFeedback } from '$utils/sendFeedbackToUser';
+import { MatrixClient, Room } from 'matrix-js-sdk';
+
+/**
+ * a class to use as PluralKit command message handler
+ *
+ * @export
+ * @class PluralKitCommandMessageHandler
+ */
+export class PluralKitCommandMessageHandler {
+ private readonly mx: MatrixClient;
+
+ private message = '';
+
+ private readonly room: Room;
+
+ public constructor(mx: MatrixClient, room: Room) {
+ this.mx = mx;
+ this.room = room;
+ }
+
+ private async memberHandler() {
+ if (this.message.startsWith('pk;member new')) {
+ // adding a new member
+ const memberName = this.message.split('pk;member new ')[1];
+ const generatedID = crypto.randomUUID();
+ addOrUpdatePerMessageProfile(this.mx, { id: generatedID, name: memberName });
+ } else {
+ // default to looking up member info
+ const listOfProfiles = await getAllPerMessageProfiles(this.mx);
+ sendFeedback(
+ `You currently have the following profiles set up: ${listOfProfiles.join(', ')}`,
+ this.room,
+ this.mx.getSafeUserId()
+ );
+ }
+ }
+
+ public async handleMessage(message: string) {
+ this.message = message;
+ if (!this.message.startsWith('pk')) return;
+ if (this.message.startsWith('pk;member')) this.memberHandler();
+ }
+}
diff --git a/src/app/plugins/pluralkit-handler/pluralkitSyntaxAdapter.ts b/src/app/plugins/pluralkit-handler/pluralkitSyntaxAdapter.ts
new file mode 100644
index 000000000..e69de29bb
From c6b3293ecc5ef3cefcbb2e7bcac8beb6171909ae Mon Sep 17 00:00:00 2001
From: Evie Gauthier
Date: Tue, 24 Mar 2026 18:46:21 -0400
Subject: [PATCH 02/58] fix: two timeline pagination bugs affecting message
ordering
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
## 1. useTimelinePagination: finally-block resets fetchingRef prematurely
When a paginated page returns 1–4 events and more history exists, the
paginator fires a recursive continuation call (`paginate(backwards)`)
before the outer `finally` block runs. The sequence was:
1. outer try: `fetchingRef.current[dir] = false; paginate(backwards);`
→ inner paginate runs synchronously:
checks lock (false) → sets it to `true` → hits `await` → suspends
2. outer finally: `fetchingRef.current[dir] = false;`
→ overwrites the `true` that inner paginate just wrote
This left `fetchingRef.current[dir] = false` while the inner paginate
was mid-flight. The `backwardStatus === 'loading'` guard on the scroll
handler masked the problem in most cases, but for a long chain of sparse
pages each returning 1–4 events, multiple overlapping paginations could
start. If the SDK's internal per-timeline lock was also released (or a
forward-direction call raced), events could be requested from stale
pagination tokens and be inserted out of order.
Fix: add a `continuing` local boolean. When a recursive continuation is
fired, `continuing = true` is set first. The `finally` block skips the
reset when `continuing` is true, leaving the lock in the inner paginate's
hands. The inner paginate's own `finally` releases it when it finishes.
## 2. getLinkedTimelines: O(N²) array copies in recursive accumulator
The previous recursive `collectTimelines(tl, dir, [...acc, tl])` created
N intermediate arrays for an N-timeline chain (sizes 1, 2, 3, … N),
giving O(N²) total allocations. For a power user who paginates back
through hundreds of pages of history, this becomes measurable GC pressure.
Replace with a simple iterative loop (`while (current) { push; next }`)
that builds exactly one output array in O(N) time.
---
src/app/hooks/timeline/useTimelineSync.ts | 20 +++++++++++++++++++-
src/app/utils/timeline.ts | 18 +++++++-----------
2 files changed, 26 insertions(+), 12 deletions(-)
diff --git a/src/app/hooks/timeline/useTimelineSync.ts b/src/app/hooks/timeline/useTimelineSync.ts
index 395d6fc46..9c7583217 100644
--- a/src/app/hooks/timeline/useTimelineSync.ts
+++ b/src/app/hooks/timeline/useTimelineSync.ts
@@ -171,6 +171,13 @@ const useTimelinePagination = (
await to(decryptAllTimelineEvent(mx, fetchedTimeline));
}
+ // `continuing` tracks whether we hand the fetchingRef lock to a recursive
+ // continuation call below. The finally block must NOT reset the lock if
+ // the recursive call has already claimed it, otherwise there is a brief
+ // window where fetchingRef is false while the recursive paginate is in
+ // flight, allowing a third overlapping call to start on sparse pages.
+ let continuing = false;
+
if (alive()) {
recalibratePagination(lTimelines);
(backwards ? setBackwardStatus : setForwardStatus)('idle');
@@ -184,13 +191,24 @@ const useTimelinePagination = (
Direction.Backward
) === 'string';
if (stillHasToken) {
+ // Release lock so inner paginate can claim it, then mark continuing
+ // so the finally block below does NOT reset it after inner claims.
fetchingRef.current[directionKey] = false;
+ continuing = true;
paginate(backwards);
+ // At this point the inner paginate has synchronously set
+ // fetchingRef.current[directionKey] = true before hitting its own
+ // await. The finally below will skip the reset.
}
}
}
} finally {
- fetchingRef.current[directionKey] = false;
+ // Only release the lock if we did NOT hand it to a recursive continuation.
+ // If `continuing` is true the recursive call owns the lock and will release
+ // it in its own finally block.
+ if (!continuing) {
+ fetchingRef.current[directionKey] = false;
+ }
}
};
}, [mx, alive, setTimeline, limit, setBackwardStatus, setForwardStatus]);
diff --git a/src/app/utils/timeline.ts b/src/app/utils/timeline.ts
index 4ed92ab16..0934e5b02 100644
--- a/src/app/utils/timeline.ts
+++ b/src/app/utils/timeline.ts
@@ -22,18 +22,14 @@ export const getFirstLinkedTimeline = (
return current;
};
-const collectTimelines = (
- tl: EventTimeline | null,
- dir: Direction,
- acc: EventTimeline[] = []
-): EventTimeline[] => {
- if (!tl) return acc;
- return collectTimelines(tl.getNeighbouringTimeline(dir), dir, [...acc, tl]);
-};
-
export const getLinkedTimelines = (timeline: EventTimeline): EventTimeline[] => {
- const firstTimeline = getFirstLinkedTimeline(timeline, Direction.Backward);
- return collectTimelines(firstTimeline, Direction.Forward);
+ const result: EventTimeline[] = [];
+ let current: EventTimeline | null = getFirstLinkedTimeline(timeline, Direction.Backward);
+ while (current) {
+ result.push(current);
+ current = current.getNeighbouringTimeline(Direction.Forward);
+ }
+ return result;
};
export const timelineToEventsCount = (t: EventTimeline) => {
From 1fc0a0d80cc8413e58814df8b320e89d5b883421 Mon Sep 17 00:00:00 2001
From: Evie Gauthier
Date: Tue, 24 Mar 2026 18:31:38 -0400
Subject: [PATCH 03/58] fix: deduplicate concurrent URL preview requests with
module-level cache
Multiple UrlPreviewCard instances rendering simultaneously (e.g. after
a large event batch loads) each called mx.getUrlPreview(url, ts). The
SDK caches by bucketed-timestamp + URL, so identical URLs from different
messages produced N separate HTTP requests.
Add a module-level previewRequestCache (Map) that dedups
in-flight requests across all instances. Resolved promises remain cached
for the session; rejected ones are evicted so later renders can retry.
---
src/app/components/url-preview/UrlPreviewCard.tsx | 14 +++++++++++++-
1 file changed, 13 insertions(+), 1 deletion(-)
diff --git a/src/app/components/url-preview/UrlPreviewCard.tsx b/src/app/components/url-preview/UrlPreviewCard.tsx
index 62106a00a..a0f8f93b2 100644
--- a/src/app/components/url-preview/UrlPreviewCard.tsx
+++ b/src/app/components/url-preview/UrlPreviewCard.tsx
@@ -14,6 +14,13 @@ import { ImageViewer } from '../image-viewer';
const linkStyles = { color: color.Success.Main };
+// Module-level in-flight deduplication: prevents N+1 concurrent requests when a
+// large event batch renders many UrlPreviewCard instances for the same URL.
+// Keyed by URL only (not ts) — the same URL shows the same preview regardless
+// of which message referenced it. Rejected promises are evicted so a later
+// render can retry after network recovery.
+const previewRequestCache = new Map>();
+
const openMediaInNewTab = async (url: string | undefined) => {
if (!url) {
console.warn('Attempted to open an empty url');
@@ -34,7 +41,12 @@ export const UrlPreviewCard = as<'div', { url: string; ts: number; mediaType?: s
const [previewStatus, loadPreview] = useAsyncCallback(
useCallback(() => {
if (isDirect) return Promise.resolve(null);
- return mx.getUrlPreview(url, ts);
+ const cached = previewRequestCache.get(url);
+ if (cached !== undefined) return cached;
+ const promise = mx.getUrlPreview(url, ts);
+ previewRequestCache.set(url, promise);
+ promise.catch(() => previewRequestCache.delete(url));
+ return promise;
}, [url, ts, mx, isDirect])
);
From ba99ef428b488446346d372c972ff810cf0ee506 Mon Sep 17 00:00:00 2001
From: Evie Gauthier
Date: Tue, 24 Mar 2026 18:29:41 -0400
Subject: [PATCH 04/58] fix: remove redundant startSpidering call causing N+1
sync requests
---
src/client/initMatrix.ts | 3 ---
1 file changed, 3 deletions(-)
diff --git a/src/client/initMatrix.ts b/src/client/initMatrix.ts
index 18809c5d2..093093ba2 100644
--- a/src/client/initMatrix.ts
+++ b/src/client/initMatrix.ts
@@ -563,9 +563,6 @@ export const startClient = async (mx: MatrixClient, config?: StartClientConfig):
pollTimeoutMs: slidingConfig?.pollTimeoutMs ?? SLIDING_SYNC_POLL_TIMEOUT_MS,
});
manager.attach();
- // Begin background spidering so all rooms are eventually indexed.
- // Not awaited — this runs incrementally in the background.
- manager.startSpidering(100, 50);
slidingSyncByClient.set(mx, manager);
syncTransportByClient.set(mx, {
transport: 'sliding',
From 95b7d4ac5d138a0d78c3a4e2afba28a58f3eed8f Mon Sep 17 00:00:00 2001
From: Evie Gauthier
Date: Tue, 24 Mar 2026 22:03:20 -0400
Subject: [PATCH 05/58] chore: add changeset for bug fixes PR
---
.changeset/fix-bug-fixes.md | 5 +++++
1 file changed, 5 insertions(+)
create mode 100644 .changeset/fix-bug-fixes.md
diff --git a/.changeset/fix-bug-fixes.md b/.changeset/fix-bug-fixes.md
new file mode 100644
index 000000000..aea8ed44e
--- /dev/null
+++ b/.changeset/fix-bug-fixes.md
@@ -0,0 +1,5 @@
+---
+default: patch
+---
+
+Fix timeline pagination lock bug, deduplicate concurrent URL preview requests, and remove redundant sliding sync spidering call causing N+1 requests.
From 9db324f1e4ac311200faf006816c06dad21715fd Mon Sep 17 00:00:00 2001
From: Evie Gauthier
Date: Tue, 24 Mar 2026 22:11:37 -0400
Subject: [PATCH 06/58] fix: hoist 'continuing' declaration before try block
for finally scope access
---
src/app/hooks/timeline/useTimelineSync.ts | 14 +++++++-------
1 file changed, 7 insertions(+), 7 deletions(-)
diff --git a/src/app/hooks/timeline/useTimelineSync.ts b/src/app/hooks/timeline/useTimelineSync.ts
index 9c7583217..5c99bf6c2 100644
--- a/src/app/hooks/timeline/useTimelineSync.ts
+++ b/src/app/hooks/timeline/useTimelineSync.ts
@@ -147,6 +147,13 @@ const useTimelinePagination = (
(backwards ? setBackwardStatus : setForwardStatus)('loading');
}
+ // `continuing` tracks whether we hand the fetchingRef lock to a recursive
+ // continuation call below. The finally block must NOT reset the lock if
+ // the recursive call has already claimed it, otherwise there is a brief
+ // window where fetchingRef is false while the recursive paginate is in
+ // flight, allowing a third overlapping call to start on sparse pages.
+ let continuing = false;
+
try {
const countBefore = getTimelinesEventsCount(lTimelines);
@@ -171,13 +178,6 @@ const useTimelinePagination = (
await to(decryptAllTimelineEvent(mx, fetchedTimeline));
}
- // `continuing` tracks whether we hand the fetchingRef lock to a recursive
- // continuation call below. The finally block must NOT reset the lock if
- // the recursive call has already claimed it, otherwise there is a brief
- // window where fetchingRef is false while the recursive paginate is in
- // flight, allowing a third overlapping call to start on sparse pages.
- let continuing = false;
-
if (alive()) {
recalibratePagination(lTimelines);
(backwards ? setBackwardStatus : setForwardStatus)('idle');
From b7d56d28fdea68327c387fc5aee56986ca665e4a Mon Sep 17 00:00:00 2001
From: Thunder
Date: Wed, 25 Mar 2026 15:38:08 +0200
Subject: [PATCH 07/58] add click handler to open the user hero for usernames
in member and state events
---
...mber_and_state_events_to_view_user_info.md | 5 ++++
.../timeline/useTimelineEventRenderer.tsx | 23 ++++++++++++++++---
src/app/hooks/useMemberEventParser.tsx | 16 +++++++++++--
3 files changed, 39 insertions(+), 5 deletions(-)
create mode 100644 .changeset/add_ability_to_click_on_usernames_in_member_and_state_events_to_view_user_info.md
diff --git a/.changeset/add_ability_to_click_on_usernames_in_member_and_state_events_to_view_user_info.md b/.changeset/add_ability_to_click_on_usernames_in_member_and_state_events_to_view_user_info.md
new file mode 100644
index 000000000..d6f7e14ad
--- /dev/null
+++ b/.changeset/add_ability_to_click_on_usernames_in_member_and_state_events_to_view_user_info.md
@@ -0,0 +1,5 @@
+---
+default: minor
+---
+
+# Add ability to click on usernames in member and state events to view user info
diff --git a/src/app/hooks/timeline/useTimelineEventRenderer.tsx b/src/app/hooks/timeline/useTimelineEventRenderer.tsx
index fe96b7e17..f7dca411a 100644
--- a/src/app/hooks/timeline/useTimelineEventRenderer.tsx
+++ b/src/app/hooks/timeline/useTimelineEventRenderer.tsx
@@ -1,4 +1,4 @@
-import { MouseEventHandler, useMemo } from 'react';
+import { MouseEventHandler, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useAtomValue } from 'jotai';
import {
@@ -20,6 +20,7 @@ import { useMemberEventParser } from '$hooks/useMemberEventParser';
import { useMatrixClient } from '$hooks/useMatrixClient';
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
import { useMatrixEventRenderer } from '$hooks/useMatrixEventRenderer';
+import { useOpenUserRoomProfile } from '$state/hooks/userRoomProfile';
import {
EventContent,
ImageContent,
@@ -58,9 +59,25 @@ import { useSableCosmetics } from '$hooks/useSableCosmetics';
function DecoratedUser({ room, userId, userName }: DecoratedUserProps) {
const { color, font } = useSableCosmetics(userId, room ?? ({} as Room));
+
+ const openUserRoomProfile = useOpenUserRoomProfile();
+ const handleUserClick: MouseEventHandler = useCallback(
+ (evt) => {
+ evt.preventDefault();
+ evt.stopPropagation();
+ openUserRoomProfile(
+ room.roomId,
+ undefined,
+ userId,
+ evt.currentTarget.getBoundingClientRect()
+ );
+ },
+ [room, userId, openUserRoomProfile]
+ );
+
return (
-
- {userName ?? userId}
+
+ {userName ?? userId}
);
}
diff --git a/src/app/hooks/useMemberEventParser.tsx b/src/app/hooks/useMemberEventParser.tsx
index 88265ad0d..2791cef4d 100644
--- a/src/app/hooks/useMemberEventParser.tsx
+++ b/src/app/hooks/useMemberEventParser.tsx
@@ -1,9 +1,10 @@
-import { ReactNode } from 'react';
+import { MouseEventHandler, useCallback, ReactNode } from 'react';
import { IconSrc, Icons, Text } from 'folds';
import { MatrixEvent, Room } from '$types/matrix-sdk';
import { IMemberContent, Membership } from '$types/matrix/room';
import { getMxIdLocalPart } from '$utils/matrix';
import { isMembershipChanged } from '$utils/room';
+import { useOpenUserRoomProfile } from '$state/hooks/userRoomProfile';
import { useSableCosmetics } from './useSableCosmetics';
import { useMatrixClient } from './useMatrixClient';
@@ -17,8 +18,19 @@ function DecoratedUser({ roomId, userId, userName }: DecoratedUserProps) {
const mx = useMatrixClient();
const room = mx.getRoom(roomId);
const { color, font } = useSableCosmetics(userId, room ?? ({} as Room));
+
+ const openUserRoomProfile = useOpenUserRoomProfile();
+ const handleUserClick: MouseEventHandler = useCallback(
+ (evt) => {
+ evt.preventDefault();
+ evt.stopPropagation();
+ openUserRoomProfile(roomId, undefined, userId, evt.currentTarget.getBoundingClientRect());
+ },
+ [roomId, userId, openUserRoomProfile]
+ );
+
return (
-
+
{userName ?? userId}
);
From 9f45a739f688ed01c1f280b68423c509f1a7e51d Mon Sep 17 00:00:00 2001
From: Evie Gauthier
Date: Tue, 24 Mar 2026 23:56:01 -0400
Subject: [PATCH 08/58] fix: rename promise to urlPreview in UrlPreviewCard
---
src/app/components/url-preview/UrlPreviewCard.tsx | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/src/app/components/url-preview/UrlPreviewCard.tsx b/src/app/components/url-preview/UrlPreviewCard.tsx
index a0f8f93b2..edc3f0f9d 100644
--- a/src/app/components/url-preview/UrlPreviewCard.tsx
+++ b/src/app/components/url-preview/UrlPreviewCard.tsx
@@ -43,10 +43,10 @@ export const UrlPreviewCard = as<'div', { url: string; ts: number; mediaType?: s
if (isDirect) return Promise.resolve(null);
const cached = previewRequestCache.get(url);
if (cached !== undefined) return cached;
- const promise = mx.getUrlPreview(url, ts);
- previewRequestCache.set(url, promise);
- promise.catch(() => previewRequestCache.delete(url));
- return promise;
+ const urlPreview = mx.getUrlPreview(url, ts);
+ previewRequestCache.set(url, urlPreview);
+ urlPreview.catch(() => previewRequestCache.delete(url));
+ return urlPreview;
}, [url, ts, mx, isDirect])
);
From 3f706fe63a49799cfcbe78e8f6ce70e0d86d12d3 Mon Sep 17 00:00:00 2001
From: Rye
Date: Thu, 26 Mar 2026 00:59:29 +0100
Subject: [PATCH 09/58] feat(pk-integration): added some simple, member related
commands people might expect when comming from pluralkit
---
src/app/features/room/RoomInput.tsx | 20 +++-
.../pluralkitMessageHandler.ts | 99 ++++++++++++++++++-
2 files changed, 111 insertions(+), 8 deletions(-)
diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx
index ba0a5fd47..162f6f329 100644
--- a/src/app/features/room/RoomInput.tsx
+++ b/src/app/features/room/RoomInput.tsx
@@ -8,6 +8,7 @@ import {
useEffect,
useRef,
useState,
+ useMemo,
} from 'react';
import { useAtom, useAtomValue } from 'jotai';
import { isKeyHotkey } from 'is-hotkey';
@@ -160,6 +161,7 @@ import {
import { Microphone, Stop } from '@phosphor-icons/react';
import { getSupportedAudioExtension } from '$plugins/voice-recorder-kit/supportedCodec';
import { sanitizeCustomHtml } from '$utils/sanitize';
+import { PluralKitCommandMessageHandler } from '$plugins/pluralkit-handler/pluralkitMessageHandler';
import { SchedulePickerDialog } from './schedule-send';
import * as css from './schedule-send/SchedulePickerDialog.css';
import {
@@ -259,6 +261,13 @@ export const RoomInput = forwardRef(
const [isMarkdown] = useSetting(settingsAtom, 'isMarkdown');
const [hideActivity] = useSetting(settingsAtom, 'hideActivity');
const commands = useCommands(mx, room);
+ /**
+ * handle pluralkit-style messages
+ */
+ const pluralkitCmdMessageHandler = useMemo(
+ () => new PluralKitCommandMessageHandler(mx, room),
+ [mx, room]
+ );
const emojiBtnRef = useRef(null);
const micBtnRef = useRef(null);
const roomToParents = useAtomValue(roomToParentsAtom);
@@ -709,6 +718,10 @@ export const RoomInput = forwardRef(
return;
}
+ if (PluralKitCommandMessageHandler.isPKCommand(plainText)) {
+ pluralkitCmdMessageHandler.handleMessage(plainText);
+ }
+
if (commandName) {
plainText = trimCommand(commandName, plainText);
customHtml = trimCommand(commandName, customHtml);
@@ -892,19 +905,20 @@ export const RoomInput = forwardRef(
}, [
editor,
replyEvent,
- isMarkdown,
- canSendReaction,
mx,
roomId,
+ isMarkdown,
+ canSendReaction,
replyDraft,
silentReply,
scheduledTime,
editingScheduledDelayId,
nicknames,
+ room,
handleQuickReact,
+ pluralkitCmdMessageHandler,
commands,
sendTypingStatus,
- room,
queryClient,
threadRootId,
setReplyDraft,
diff --git a/src/app/plugins/pluralkit-handler/pluralkitMessageHandler.ts b/src/app/plugins/pluralkit-handler/pluralkitMessageHandler.ts
index 07d36bf3e..42062e86e 100644
--- a/src/app/plugins/pluralkit-handler/pluralkitMessageHandler.ts
+++ b/src/app/plugins/pluralkit-handler/pluralkitMessageHandler.ts
@@ -1,15 +1,24 @@
import {
addOrUpdatePerMessageProfile,
getAllPerMessageProfiles,
+ getPerMessageProfileById,
+ PerMessageProfile,
} from '$hooks/usePerMessageProfile';
import { sendFeedback } from '$utils/sendFeedbackToUser';
import { MatrixClient, Room } from 'matrix-js-sdk';
+const pkMemberRenameRegex = /^(pk;member)\s+"?([\w\s]+)"?\s*rename\s+"?([\w\s]+)"?$/;
+const pkMemberNewRegex = /^(pk;member)\s+new\s+"?([\w\s]+)"?$/;
+
+const helpTextPkMemberNew = 'To create a new persona: pk;member new Yumi';
+const helpTextPkMemberRename = 'To rename a persona: pk;member "Rain Deer" rename "Micky Mouse"';
+
/**
* a class to use as PluralKit command message handler
*
* @export
* @class PluralKitCommandMessageHandler
+ * @author Rye
*/
export class PluralKitCommandMessageHandler {
private readonly mx: MatrixClient;
@@ -23,26 +32,106 @@ export class PluralKitCommandMessageHandler {
this.room = room;
}
+ /**
+ * Handler for `pk;member` commands
+ * @async
+ */
private async memberHandler() {
- if (this.message.startsWith('pk;member new')) {
+ if (this.message.match(pkMemberNewRegex)) {
// adding a new member
- const memberName = this.message.split('pk;member new ')[1];
+ const cmdParts = pkMemberNewRegex.exec(this.message);
+ if (!cmdParts) {
+ sendFeedback(`malformed input, ${helpTextPkMemberNew}`, this.room, this.mx.getSafeUserId());
+ return;
+ }
+ const memberName = cmdParts[2];
const generatedID = crypto.randomUUID();
addOrUpdatePerMessageProfile(this.mx, { id: generatedID, name: memberName });
+ sendFeedback(
+ `new member has been created with id: ${generatedID} and name ${memberName}`,
+ this.room,
+ this.mx.getSafeUserId()
+ );
+ } else if (this.message.match(pkMemberRenameRegex)) {
+ // renaming a profile based on the name
+ const cmdParts = pkMemberRenameRegex.exec(this.message);
+ if (!cmdParts) {
+ sendFeedback(
+ `malformed input, ${helpTextPkMemberRename}`,
+ this.room,
+ this.mx.getSafeUserId()
+ );
+ return;
+ }
+ // extract from the cmd the old and the new name
+ /**
+ * The old name we want to search for in our records, is in capture group 2
+ */
+ const oldName = cmdParts[2];
+ /**
+ * The new name we want to set is in capture group 3
+ */
+ const newName = cmdParts[3];
+ /**
+ * The id of the per-message-profile
+ */
+ const pmpId = (await getAllPerMessageProfiles(this.mx)).find(
+ (pmp) => pmp.name === oldName
+ )?.id;
+ if (!pmpId) {
+ sendFeedback(
+ `Persona with name "${oldName}" doesn't exist in your records, ${helpTextPkMemberRename}`,
+ this.room,
+ this.mx.getSafeUserId()
+ );
+ return;
+ }
+ /**
+ * get the persona record we already have for the id
+ */
+ const pmp = await getPerMessageProfileById(this.mx, pmpId);
+ if (!pmp) {
+ sendFeedback(
+ "Persona record can't be retrieved, data might be corrupted",
+ this.room,
+ this.mx.getSafeUserId()
+ );
+ return;
+ }
+ // actually change the name
+ pmp.name = newName;
+ sendFeedback(
+ `renaming your profile ${pmpId} from ${oldName} to ${newName}`,
+ this.room,
+ this.mx.getSafeUserId()
+ );
+ addOrUpdatePerMessageProfile(this.mx, pmp);
} else {
// default to looking up member info
- const listOfProfiles = await getAllPerMessageProfiles(this.mx);
+ const listOfProfiles: PerMessageProfile[] = await getAllPerMessageProfiles(this.mx);
+ const stringListOfProfiles: string = listOfProfiles
+ .map((pmp: PerMessageProfile) => `${pmp.id}: ${pmp.name ? pmp.name : '(empty name)'}`)
+ .join('\n');
sendFeedback(
- `You currently have the following profiles set up: ${listOfProfiles.join(', ')}`,
+ `You currently have the following persona set up:\n${stringListOfProfiles}\n\n${helpTextPkMemberNew}\n${helpTextPkMemberRename}`,
this.room,
this.mx.getSafeUserId()
);
}
}
+ /**
+ * check if a message is a pluralkit-style command
+ * @param message the message to check
+ * @returns true if it's a pluralkit style command
+ */
+ public static isPKCommand(message: string): boolean {
+ return message.startsWith('pk;');
+ }
+
public async handleMessage(message: string) {
this.message = message;
if (!this.message.startsWith('pk')) return;
- if (this.message.startsWith('pk;member')) this.memberHandler();
+ if (this.message.startsWith('pk;member')) await this.memberHandler();
}
}
From 38057ee9ce268593a6577b2ab2ce37f36a42ab53 Mon Sep 17 00:00:00 2001
From: Evie Gauthier
Date: Wed, 25 Mar 2026 20:08:34 -0400
Subject: [PATCH 10/58] fix: reset live timeline on room navigation and
reconnect
The Matrix SDK for sliding sync deliberately does not call resetLiveTimeline()
on limited:true (the handling is in a commented-out TODO block). This means
events from a previous visit remain in the live timeline and new events get
appended after them, with the backward pagination token pointing to the gap
between old and new events rather than to before all events. The result is
that new messages appear out of order or the gap is unreachable via the UI.
Two fixes:
1. useSlidingSyncActiveRoom: reset the live timeline synchronously before
the subscription request is sent on room navigation. This ensures the
fresh initial:true response populates a clean timeline, not one polluted
with events from the previous visit. Also removes the 100ms delay that
was added as an incomplete workaround for the same issue.
2. SlidingSyncManager.onLifecycle: in RequestFinished state (fires before
any room data listeners run), reset the live timeline for active-room
subscriptions that receive initial:true or limited:true. This covers the
reconnect/background case where the pos token expires and all active rooms
get a fresh initial:true in the same sync cycle.
---
src/app/hooks/useSlidingSyncActiveRoom.ts | 13 ++-----------
src/client/slidingSync.ts | 22 ++++++++++++++++++++++
2 files changed, 24 insertions(+), 11 deletions(-)
diff --git a/src/app/hooks/useSlidingSyncActiveRoom.ts b/src/app/hooks/useSlidingSyncActiveRoom.ts
index 8468f4024..c86914d56 100644
--- a/src/app/hooks/useSlidingSyncActiveRoom.ts
+++ b/src/app/hooks/useSlidingSyncActiveRoom.ts
@@ -24,16 +24,7 @@ export const useSlidingSyncActiveRoom = (): void => {
const manager = getSlidingSyncManager(mx);
if (!manager) return undefined;
- // Wait for the room to be initialized from list sync before subscribing
- // with the full timeline limit. This prevents timeline ordering issues where
- // the room might be receiving events from list expansion while we're also
- // trying to load a large timeline, causing events to be added out of order.
- const timeoutId = setTimeout(() => {
- manager.subscribeToRoom(roomId);
- }, 100);
-
- return () => {
- clearTimeout(timeoutId);
- };
+ manager.subscribeToRoom(roomId);
+ return undefined;
}, [mx, roomId]);
};
diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts
index 84622b0e2..058b87cf1 100644
--- a/src/client/slidingSync.ts
+++ b/src/client/slidingSync.ts
@@ -8,6 +8,7 @@ import {
MSC3575List,
MSC3575RoomData,
MSC3575RoomSubscription,
+ MSC3575SlidingSyncResponse,
MSC3575_WILDCARD,
RoomMemberEvent,
SlidingSync,
@@ -350,6 +351,27 @@ export class SlidingSyncManager {
return;
}
+ // Before room data is processed, reset live timelines for active rooms that
+ // are receiving a full refresh (initial: true) or a post-gap update
+ // (limited: true). The SDK deliberately does not call resetLiveTimeline() for
+ // sliding sync, so events from previous visits accumulate in the live
+ // timeline alongside new events. Resetting here — before the SDK's
+ // onRoomData listener runs — ensures the fresh batch lands on a clean
+ // timeline with a correct backward pagination token.
+ if (state === SlidingSyncState.RequestFinished && resp && !err) {
+ const rooms = (resp as MSC3575SlidingSyncResponse).rooms ?? {};
+ Object.entries(rooms)
+ .filter(([, roomData]) => roomData.initial || roomData.limited)
+ .filter(([roomId]) => this.activeRoomSubscriptions.has(roomId))
+ .forEach(([roomId]) => {
+ const room = this.mx.getRoom(roomId);
+ if (!room) return;
+ const timelineSet = room.getUnfilteredTimelineSet();
+ if (timelineSet.getLiveTimeline().getEvents().length === 0) return;
+ timelineSet.resetLiveTimeline();
+ });
+ }
+
if (err || !resp || state !== SlidingSyncState.Complete) return;
// Track what changed in this sync cycle
From 7062f64e78935bf08a97c8b4b164964d3398b99f Mon Sep 17 00:00:00 2001
From: Evie Gauthier
Date: Wed, 25 Mar 2026 22:17:13 -0400
Subject: [PATCH 11/58] fix: always open room at bottom of timeline
---
src/app/features/room/RoomTimeline.tsx | 42 +++++++++++++++++++++-----
1 file changed, 35 insertions(+), 7 deletions(-)
diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx
index dd655deec..d4aaebbd9 100644
--- a/src/app/features/room/RoomTimeline.tsx
+++ b/src/app/features/room/RoomTimeline.tsx
@@ -207,6 +207,9 @@ export function RoomTimeline({
const topSpacerHeightRef = useRef(0);
const mountScrollWindowRef = useRef(Date.now() + 3000);
const hasInitialScrolledRef = useRef(false);
+ // Stored in a ref so eventsLength fluctuations (e.g. onLifecycle timeline reset
+ // firing within the window) cannot cancel it via useLayoutEffect cleanup.
+ const initialScrollTimerRef = useRef | undefined>(undefined);
const currentRoomIdRef = useRef(room.roomId);
const [isReady, setIsReady] = useState(false);
@@ -273,16 +276,31 @@ export function RoomTimeline({
vListRef.current
) {
vListRef.current.scrollToIndex(processedEventsRef.current.length - 1, { align: 'end' });
- const t = setTimeout(() => {
- vListRef.current?.scrollToIndex(processedEventsRef.current.length - 1, { align: 'end' });
+ // Store in a ref rather than a local so subsequent eventsLength changes
+ // (e.g. the onLifecycle timeline reset firing within 80 ms) do NOT
+ // cancel this timer through the useLayoutEffect cleanup.
+ initialScrollTimerRef.current = setTimeout(() => {
+ initialScrollTimerRef.current = undefined;
+ if (processedEventsRef.current.length > 0) {
+ vListRef.current?.scrollToIndex(processedEventsRef.current.length - 1, { align: 'end' });
+ }
setIsReady(true);
}, 80);
hasInitialScrolledRef.current = true;
- return () => clearTimeout(t);
}
- return () => {};
+ // No cleanup return — the timer must survive eventsLength fluctuations.
+ // It is cancelled on unmount by the dedicated effect below.
}, [timelineSync.eventsLength, eventId, room.roomId]);
+ // Cancel the initial-scroll timer on unmount (the useLayoutEffect above
+ // intentionally does not cancel it when deps change).
+ useEffect(
+ () => () => {
+ if (initialScrollTimerRef.current !== undefined) clearTimeout(initialScrollTimerRef.current);
+ },
+ []
+ );
+
const recalcTopSpacer = useCallback(() => {
const v = vListRef.current;
if (!v) return;
@@ -355,6 +373,11 @@ export function RoomTimeline({
useEffect(() => {
if (eventId) return;
+ // Guard: once the timeline is visible to the user, do not override their
+ // scroll position. Without this, a later timeline refresh (e.g. the
+ // onLifecycle reset delivering a new linkedTimelines reference) can fire
+ // this effect after isReady and snap the view back to the read marker.
+ if (isReady) return;
const { readUptoEventId, inLiveTimeline, scrollTo } = unreadInfo ?? {};
if (readUptoEventId && inLiveTimeline && scrollTo) {
const evtTimeline = getEventTimeline(room, readUptoEventId);
@@ -366,12 +389,16 @@ export function RoomTimeline({
)
: undefined;
- if (absoluteIndex !== undefined && vListRef.current) {
+ if (absoluteIndex !== undefined) {
const processedIndex = getRawIndexToProcessedIndex(absoluteIndex);
- if (processedIndex !== undefined) {
+ if (processedIndex !== undefined && vListRef.current) {
vListRef.current.scrollToIndex(processedIndex, { align: 'start' });
- setUnreadInfo((prev) => (prev ? { ...prev, scrollTo: false } : prev));
}
+ // Always consume the scroll intent once the event is located in the
+ // linked timelines, even if its processedIndex is undefined (filtered
+ // event). Without this, each linkedTimelines reference change retries
+ // the scroll indefinitely.
+ setUnreadInfo((prev) => (prev ? { ...prev, scrollTo: false } : prev));
}
}
}, [
@@ -379,6 +406,7 @@ export function RoomTimeline({
unreadInfo,
timelineSync.timeline.linkedTimelines,
eventId,
+ isReady,
getRawIndexToProcessedIndex,
]);
From 5f22d86a04c3fb34ee8320db27ce05ee0ca7a022 Mon Sep 17 00:00:00 2001
From: Rye
Date: Thu, 26 Mar 2026 07:38:37 +0100
Subject: [PATCH 12/58] feat(pkit-compat): some steps towards recognizing
proxies, not entirely there yet
---
src/app/features/room/RoomInput.tsx | 23 ++-
src/app/hooks/usePerMessageProfile.ts | 195 +++++++++++++++++-
...andler.ts => PKitCommandMessageHandler.ts} | 57 ++++-
.../PKitProxyMessageHandler.ts | 91 ++++++++
.../pluralkitImportFormat.ts | 22 --
src/app/state/settings.ts | 5 +
src/types/matrix/accountData.ts | 21 ++
7 files changed, 379 insertions(+), 35 deletions(-)
rename src/app/plugins/pluralkit-handler/{pluralkitMessageHandler.ts => PKitCommandMessageHandler.ts} (67%)
create mode 100644 src/app/plugins/pluralkit-handler/PKitProxyMessageHandler.ts
diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx
index 162f6f329..c6764e04f 100644
--- a/src/app/features/room/RoomInput.tsx
+++ b/src/app/features/room/RoomInput.tsx
@@ -161,7 +161,8 @@ import {
import { Microphone, Stop } from '@phosphor-icons/react';
import { getSupportedAudioExtension } from '$plugins/voice-recorder-kit/supportedCodec';
import { sanitizeCustomHtml } from '$utils/sanitize';
-import { PluralKitCommandMessageHandler } from '$plugins/pluralkit-handler/pluralkitMessageHandler';
+import { PKitCommandMessageHandler } from '$plugins/pluralkit-handler/PKitCommandMessageHandler';
+import { PKitProxyMessageHandler } from '$plugins/pluralkit-handler/PKitProxyMessageHandler';
import { SchedulePickerDialog } from './schedule-send';
import * as css from './schedule-send/SchedulePickerDialog.css';
import {
@@ -265,9 +266,15 @@ export const RoomInput = forwardRef(
* handle pluralkit-style messages
*/
const pluralkitCmdMessageHandler = useMemo(
- () => new PluralKitCommandMessageHandler(mx, room),
+ () => new PKitCommandMessageHandler(mx, room),
[mx, room]
);
+ const pluralkitProxyMessageHandler = useMemo(() => new PKitProxyMessageHandler(mx), [mx]);
+ useEffect(() => {
+ pluralkitProxyMessageHandler.init();
+ }, [pluralkitProxyMessageHandler]);
+
+ const pkCompatEnable = useSetting(settingsAtom, 'pkCompat');
const emojiBtnRef = useRef(null);
const micBtnRef = useRef(null);
const roomToParents = useAtomValue(roomToParentsAtom);
@@ -718,7 +725,8 @@ export const RoomInput = forwardRef(
return;
}
- if (PluralKitCommandMessageHandler.isPKCommand(plainText)) {
+ // check if its a pk command
+ if (pkCompatEnable && PKitCommandMessageHandler.isPKCommand(plainText)) {
pluralkitCmdMessageHandler.handleMessage(plainText);
}
@@ -778,8 +786,13 @@ export const RoomInput = forwardRef(
* This allows the server to apply the correct profile-based transformations (e.g. font size adjustments) when processing the message,
* and also allows clients to display an accurate preview of how the message will look with the profile applied while it's being composed.
*/
- const perMessageProfile = await getCurrentlyUsedPerMessageProfileForRoom(mx, roomId);
+ const perMessageProfile =
+ pkCompatEnable && pluralkitProxyMessageHandler.isAProxiedMessage(plainText)
+ ? await pluralkitProxyMessageHandler.getPmpBasedOnMessage(plainText)
+ : await getCurrentlyUsedPerMessageProfileForRoom(mx, roomId);
+ if (pkCompatEnable && pluralkitProxyMessageHandler.isAProxiedMessage(plainText))
+ plainText = pluralkitProxyMessageHandler.stripProxyFromMessage(plainText) ?? plainText;
if (perMessageProfile) {
content['com.beeper.per_message_profile'] =
convertPerMessageProfileToBeeperFormat(perMessageProfile);
@@ -909,6 +922,8 @@ export const RoomInput = forwardRef(
roomId,
isMarkdown,
canSendReaction,
+ pkCompatEnable,
+ pluralkitProxyMessageHandler,
replyDraft,
silentReply,
scheduledTime,
diff --git a/src/app/hooks/usePerMessageProfile.ts b/src/app/hooks/usePerMessageProfile.ts
index 8ef2f8d44..12c16b34b 100644
--- a/src/app/hooks/usePerMessageProfile.ts
+++ b/src/app/hooks/usePerMessageProfile.ts
@@ -1,7 +1,8 @@
+import { AccountDataCompatVersion, AccountDataEvent } from '$types/matrix/accountData';
import { PronounSet } from '$utils/pronouns';
import { MatrixClient } from 'matrix-js-sdk';
-const ACCOUNT_DATA_PREFIX = 'fyi.cisnt.permessageprofile';
+const ACCOUNT_DATA_PREFIX = AccountDataEvent.SablePerProfileMessageProfiles;
/**
* a per message profile
@@ -26,6 +27,7 @@ export type PerMessageProfile = {
* @see PronounSet for the format of the pronouns, and how to parse them from a string input
*/
pronouns?: PronounSet[];
+ compat?: AccountDataCompatVersion;
};
/**
@@ -96,6 +98,7 @@ type PerMessageProfileIndex = {
* a list of all profile ids, used to list all profiles when the user wants to manage them.
*/
profileIds: string[];
+ compat: AccountDataCompatVersion;
};
/**
@@ -106,6 +109,64 @@ type PerMessageProfileRoomAssociation = {
validUntil?: number;
};
+/**
+ * associating a profile by proxy
+ * @author Rye
+ */
+export type PerMessageProfileProxyAssociation = {
+ /**
+ * the profile associated with the proxy
+ */
+ profileId: string;
+ /**
+ * regex (string representation of it) to handle the proxy
+ */
+ regexString: string;
+ /**
+ * optional parameter to save when the proxy was added
+ */
+ setAt?: number;
+};
+
+export type InternalPerMessageProfileProxyAssociation = {
+ /**
+ * the profile associated with the proxy
+ */
+ profileId: string;
+ /**
+ * regex to handle the proxy
+ */
+ regex: RegExp;
+ /**
+ * optional parameter to save when the proxy was added
+ */
+ setAt?: number;
+};
+
+export function parsePerMessageProfileProxyAssociation(
+ assoc: PerMessageProfileProxyAssociation
+): InternalPerMessageProfileProxyAssociation {
+ return {
+ profileId: assoc.profileId,
+ // we need to remove artifacts from the toString conversion
+ regex: new RegExp(assoc.regexString.slice(1, -1)),
+ setAt: assoc.setAt,
+ } satisfies InternalPerMessageProfileProxyAssociation;
+}
+
+type PerMessageProfileProxyAssociationWrapper = {
+ /**
+ * the associations saved in the wrapper
+ */
+ associations:
+ | Map
+ | Record;
+ /**
+ * optional parameter to save compatibility information
+ */
+ compat?: AccountDataCompatVersion;
+};
+
/**
* the shape of the account data for room associations, which is a wrapper around a list of associations.
* This is used to store the associations in account data, and allows us to easily add additional fields in the future if needed without breaking the existing data structure.
@@ -120,9 +181,14 @@ type PerMessageProfileRoomAssociationWrapper = {
associations:
| Map
| Record;
+ compat?: AccountDataCompatVersion;
};
-// Helper to always get a Map from wrapper
+/**
+ * unwrap a profile-room-associations-wrapper
+ * @param wrapper the wrapper to unwrap
+ * @returns unwrapped map for profile-room-associations
+ */
function getAssociationsMap(
wrapper?: PerMessageProfileRoomAssociationWrapper
): Map {
@@ -138,6 +204,33 @@ function associationsMapToObject(
return Object.fromEntries(map);
}
+/**
+ * helper function (similar to getAssociationsMap for Room associations)
+ * @param wrapper the wrapper to unwrap
+ * @returns unwrapped map of proxy associations
+ */
+function getProxyAssociationMap(
+ wrapper?: PerMessageProfileProxyAssociationWrapper
+): Map {
+ if (!wrapper?.associations) return new Map();
+ if (wrapper.associations instanceof Map) return wrapper.associations;
+ return new Map(Object.entries(wrapper.associations));
+}
+
+function proxyAssociationsMapToObject(
+ map: Map
+): Record {
+ return Object.fromEntries(map);
+}
+
+/**
+ * getting a profile from the account data where the profile matches a given id
+ *
+ * @export
+ * @param {MatrixClient} mx the matrix client
+ * @param {string} id the profile id
+ * @return {*} {(Promise)} the profile, with the profile Id, if it exists
+ */
export async function getPerMessageProfileById(
mx: MatrixClient,
id: string
@@ -146,6 +239,13 @@ export async function getPerMessageProfileById(
return profile ? (profile.getContent() as unknown as PerMessageProfile) : undefined;
}
+/**
+ * getting an array of all PerMessageProfile's saved in the account data
+ *
+ * @export
+ * @param {MatrixClient} mx the matrix client
+ * @return {*} {Promise} a array containing all per-message-profiles saved
+ */
export async function getAllPerMessageProfiles(mx: MatrixClient): Promise {
const profileData = mx.getAccountData(`${ACCOUNT_DATA_PREFIX}.index` as any);
const profileIds = (profileData?.getContent() as PerMessageProfileIndex)?.profileIds || [];
@@ -153,17 +253,33 @@ export async function getAllPerMessageProfiles(mx: MatrixClient): Promise profile !== undefined);
}
+/**
+ * add or update a pmp
+ * @param mx the matrix client
+ * @param profile the profile to add/update
+ * @returns void
+ */
export function addOrUpdatePerMessageProfile(mx: MatrixClient, profile: PerMessageProfile) {
const profileListIndex = mx.getAccountData(`${ACCOUNT_DATA_PREFIX}.index` as any);
+ const profileWithCompat = {
+ ...profile,
+ compat: {
+ version: 1,
+ compatDate: '2026-03-26',
+ } satisfies AccountDataCompatVersion,
+ } satisfies PerMessageProfile;
if (profileListIndex?.getContent()?.profileIds.includes(profile.id)) {
// profile already exists, just update it
- return mx.setAccountData(`${ACCOUNT_DATA_PREFIX}.${profile.id}` as any, profile as any);
+ return mx.setAccountData(
+ `${ACCOUNT_DATA_PREFIX}.${profile.id}` as any,
+ profileWithCompat as any
+ );
}
// profile doesn't exist, add it to the index and then add the profile data
const newProfileIds = [...(profileListIndex?.getContent()?.profileIds || []), profile.id];
return Promise.all([
mx.setAccountData(`${ACCOUNT_DATA_PREFIX}.index` as any, { profileIds: newProfileIds } as any),
- mx.setAccountData(`${ACCOUNT_DATA_PREFIX}.${profile.id}` as any, profile as any),
+ mx.setAccountData(`${ACCOUNT_DATA_PREFIX}.${profile.id}` as any, profileWithCompat as any),
]);
}
@@ -235,6 +351,77 @@ export async function setCurrentlyUsedPerMessageProfileIdForRoom(
}
/**
+ *
+ * @param mx the matrix client
+ * @param profileId the profile id which the prefix should be attached to
+ * @param proxy the prefix to use as index
+ * @param proxyRegExp the regex we can use to match the prefix
+ * @param reset wheather to delete the prefix
+ */
+export async function associateProxyWithProfile(
+ mx: MatrixClient,
+ profileId: string | undefined,
+ proxy: string,
+ proxyRegExp: RegExp,
+ reset: boolean
+) {
+ const associations = getProxyAssociationMap(
+ mx.getAccountData(`${ACCOUNT_DATA_PREFIX}.proxyassociation` as any)?.getContent()
+ );
+
+ if (reset) associations.delete(proxy);
+
+ if (!profileId) throw new Error('profileId might not be undefined');
+ if (profileId)
+ associations.set(proxy, {
+ profileId,
+ regexString: proxyRegExp.toString(),
+ } satisfies PerMessageProfileProxyAssociation);
+ mx.setAccountData(
+ `${ACCOUNT_DATA_PREFIX}.proxyassociation` as any,
+ { associations: proxyAssociationsMapToObject(associations) } as any
+ );
+}
+
+/**
+ * get a profile based on a proxy
+ * @param mx the matrix client
+ * @param proxy the proxy to look for
+ * @returns the profile, if any, associated with the prefix
+ */
+export async function getProfileAssociatedWithProxy(
+ mx: MatrixClient,
+ proxy: string
+): Promise {
+ const profileId = getAssociationsMap(
+ mx.getAccountData(`${ACCOUNT_DATA_PREFIX}.proxyassociation` as any)?.getContent()
+ ).get(proxy)?.profileId;
+ if (!profileId) return undefined;
+ return getPerMessageProfileById(mx, profileId);
+}
+
+/**
+ *
+ *
+ * @export
+ * @param {MatrixClient} mx the matrix client
+ * @return {*} {Promise}
+ */
+export async function getAllPerMessageProfileProxies(
+ mx: MatrixClient
+): Promise {
+ const cont: PerMessageProfileProxyAssociationWrapper | undefined = mx
+ .getAccountData(`${ACCOUNT_DATA_PREFIX}.proxyassociation` as any)
+ ?.getContent();
+ if (!cont) return [];
+ const pmap = getProxyAssociationMap(cont);
+ const parr = new Array();
+ pmap.values().forEach((v) => parr.push(v));
+ return parr;
+}
+
+/**
+ *
* drops all room associations for a profile, used when deleting a profile to make sure there are no dangling associations left that point to a non existing profile, which could cause issues when trying to apply the profile to a message in a room that still has an association for the deleted profile.
*
* @param {MatrixClient} mx the matrix client
diff --git a/src/app/plugins/pluralkit-handler/pluralkitMessageHandler.ts b/src/app/plugins/pluralkit-handler/PKitCommandMessageHandler.ts
similarity index 67%
rename from src/app/plugins/pluralkit-handler/pluralkitMessageHandler.ts
rename to src/app/plugins/pluralkit-handler/PKitCommandMessageHandler.ts
index 42062e86e..c1108395d 100644
--- a/src/app/plugins/pluralkit-handler/pluralkitMessageHandler.ts
+++ b/src/app/plugins/pluralkit-handler/PKitCommandMessageHandler.ts
@@ -1,5 +1,6 @@
import {
addOrUpdatePerMessageProfile,
+ associateProxyWithProfile,
getAllPerMessageProfiles,
getPerMessageProfileById,
PerMessageProfile,
@@ -9,9 +10,24 @@ import { MatrixClient, Room } from 'matrix-js-sdk';
const pkMemberRenameRegex = /^(pk;member)\s+"?([\w\s]+)"?\s*rename\s+"?([\w\s]+)"?$/;
const pkMemberNewRegex = /^(pk;member)\s+new\s+"?([\w\s]+)"?$/;
+const pkMemberNewProxy = /^(pk;member)\s+"?([\w\s]+)"?\s+proxy\s+(.*text.*)$/;
const helpTextPkMemberNew = 'To create a new persona: pk;member new Yumi';
const helpTextPkMemberRename = 'To rename a persona: pk;member "Rain Deer" rename "Micky Mouse"';
+const helpTextPkMemberNewProxy = 'To create a persona: pk;member Yumi proxy [text]';
+
+/**
+ * build a regex to recognize proxies
+ * a template can be for example `[text]` or `f:text`
+ *
+ * @param {string} template
+ * @return {*} {RegExp}
+ */
+function buildRegex(template: string): RegExp {
+ const [before, after] = template.split('text');
+ const pattern = `${RegExp.escape(before)}(.+)${RegExp.escape(after)}`;
+ return new RegExp(`^${pattern}$`);
+}
/**
* a class to use as PluralKit command message handler
@@ -20,7 +36,7 @@ const helpTextPkMemberRename = 'To rename a persona: pk;member "Rain Deer" renam
* @class PluralKitCommandMessageHandler
* @author Rye
*/
-export class PluralKitCommandMessageHandler {
+export class PKitCommandMessageHandler {
private readonly mx: MatrixClient;
private message = '';
@@ -46,9 +62,14 @@ export class PluralKitCommandMessageHandler {
}
const memberName = cmdParts[2];
const generatedID = crypto.randomUUID();
+ sendFeedback(
+ `adding new member has been created with id: ${generatedID} and name ${memberName}`,
+ this.room,
+ this.mx.getSafeUserId()
+ );
addOrUpdatePerMessageProfile(this.mx, { id: generatedID, name: memberName });
sendFeedback(
- `new member has been created with id: ${generatedID} and name ${memberName}`,
+ `added new member has been created with id: ${generatedID} and name ${memberName}`,
this.room,
this.mx.getSafeUserId()
);
@@ -80,7 +101,7 @@ export class PluralKitCommandMessageHandler {
)?.id;
if (!pmpId) {
sendFeedback(
- `Persona with name "${oldName}" doesn't exist in your records, ${helpTextPkMemberRename}`,
+ `Persona with name "${oldName}" doesn't exist in your records, ${helpTextPkMemberNew}`,
this.room,
this.mx.getSafeUserId()
);
@@ -106,6 +127,27 @@ export class PluralKitCommandMessageHandler {
this.mx.getSafeUserId()
);
addOrUpdatePerMessageProfile(this.mx, pmp);
+ } else if (pkMemberNewProxy.test(this.message)) {
+ const cmdParts = pkMemberNewProxy.exec(this.message);
+ if (!cmdParts) return;
+ const name = cmdParts[2];
+ const matchAgainst = cmdParts[3];
+ const pmpId = (await getAllPerMessageProfiles(this.mx)).find((pmp) => pmp.name === name)?.id;
+ if (!pmpId) {
+ sendFeedback(
+ `Persona with name "${name}" doesn't exist in your records, ${helpTextPkMemberNew}`,
+ this.room,
+ this.mx.getSafeUserId()
+ );
+ return;
+ }
+ const matchAgainstRegExp = buildRegex(matchAgainst);
+ associateProxyWithProfile(this.mx, pmpId, matchAgainst, matchAgainstRegExp, false);
+ sendFeedback(
+ `Persona with 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);
@@ -113,7 +155,7 @@ export class PluralKitCommandMessageHandler {
.map((pmp: PerMessageProfile) => `${pmp.id}: ${pmp.name ? pmp.name : '(empty name)'}`)
.join('\n');
sendFeedback(
- `You currently have the following persona set up:\n${stringListOfProfiles}\n\n${helpTextPkMemberNew}\n${helpTextPkMemberRename}`,
+ `You currently have the following persona set up:\n${stringListOfProfiles}\n\n${helpTextPkMemberNew}\n${helpTextPkMemberRename}\n${helpTextPkMemberNewProxy}`,
this.room,
this.mx.getSafeUserId()
);
@@ -129,7 +171,12 @@ export class PluralKitCommandMessageHandler {
return message.startsWith('pk;');
}
- public async handleMessage(message: string) {
+ /**
+ * handle a message, which might be a pk command
+ * @param message the message we want to handle
+ * @returns void
+ */
+ public async handleMessage(message: string): Promise {
this.message = message;
if (!this.message.startsWith('pk')) return;
if (this.message.startsWith('pk;member')) await this.memberHandler();
diff --git a/src/app/plugins/pluralkit-handler/PKitProxyMessageHandler.ts b/src/app/plugins/pluralkit-handler/PKitProxyMessageHandler.ts
new file mode 100644
index 000000000..d51b674e1
--- /dev/null
+++ b/src/app/plugins/pluralkit-handler/PKitProxyMessageHandler.ts
@@ -0,0 +1,91 @@
+import {
+ getAllPerMessageProfileProxies,
+ getPerMessageProfileById,
+ InternalPerMessageProfileProxyAssociation,
+ parsePerMessageProfileProxyAssociation,
+ PerMessageProfile,
+} from '$hooks/usePerMessageProfile';
+import { MatrixClient } from 'matrix-js-sdk';
+
+/**
+ * proxy message handler
+ * @author Rye
+ */
+export class PKitProxyMessageHandler {
+ /**
+ * the matrix client we use, we init that in the constructor
+ *
+ * @private
+ * @type {MatrixClient}
+ * @memberof PKitProxyMessageHandler
+ */
+ private readonly mx: MatrixClient;
+
+ /**
+ * a list of proxies; is not initialized in the constructor
+ * @private
+ * @type {PerMessageProfileProxyAssociation[]}
+ * @memberof PKitProxyMessageHandler
+ */
+ private proxiesAssocs: InternalPerMessageProfileProxyAssociation[];
+
+ private succInit: boolean;
+
+ /**
+ * a pk proxy message handler
+ * @param mx the matrix client
+ */
+ public constructor(mx: MatrixClient) {
+ this.mx = mx;
+ this.proxiesAssocs = [];
+ this.succInit = false;
+ }
+
+ /**
+ * initialize the handler, as this is not necessarily fast, it shouldn't happen in the constructor
+ */
+ public async init(): Promise {
+ try {
+ this.proxiesAssocs = (await getAllPerMessageProfileProxies(this.mx)).map((p) =>
+ parsePerMessageProfileProxyAssociation(p)
+ );
+ this.succInit = true;
+ } catch (err) {
+ this.succInit = false;
+ throw new Error(`failed to init pmp proxy handler: ${String(err)}`);
+ }
+ }
+
+ /**
+ * you should probably check this before running `getPmpBasedOnMessage`, as this is faster
+ * @param message the message to check
+ */
+ public isAProxiedMessage(message: string): boolean {
+ if (!this.succInit) throw new Error('PK proxy message handler is not initialized');
+ return this.proxiesAssocs.some((assoc) => assoc.regex.test(message));
+ }
+
+ /**
+ * get PmP based on message
+ * @param message the message to look at
+ * @returns the matching Per-Message-Profile, if any
+ */
+ public async getPmpBasedOnMessage(message: string): Promise {
+ if (!this.succInit) await this.init();
+ // check if the message matches our formats
+ // maybe a bit unsafe, as we are evaluating regex that aren't necessarily by us, could be _maybe_ manipulated
+ const profileId = this.proxiesAssocs.find((assoc) => assoc.regex.test(message))?.profileId;
+ if (!profileId) return undefined;
+ return getPerMessageProfileById(this.mx, profileId);
+ }
+
+ public stripProxyFromMessage(message: string): string | undefined {
+ if (!this.succInit) throw new Error('PK proxy message handler is not initialized');
+ let m;
+ this.proxiesAssocs.forEach((assoc) => {
+ const match = assoc.regex.exec(message);
+ if (match?.at(1)) m = match.at(1);
+ });
+ return m;
+ }
+}
diff --git a/src/app/plugins/pluralkit-handler/pluralkitImportFormat.ts b/src/app/plugins/pluralkit-handler/pluralkitImportFormat.ts
index f3cbe51f8..9a82da6cc 100644
--- a/src/app/plugins/pluralkit-handler/pluralkitImportFormat.ts
+++ b/src/app/plugins/pluralkit-handler/pluralkitImportFormat.ts
@@ -1,53 +1,43 @@
/**
* the {@link https://pluralkit.me/api/models/#system-model data model for a pluralkit system}
- * @since 1.10.0
* @author Rye
*/
export type PluralKitSystem = {
/**
* id is freeform string
- * @since 1.10.0
*/
id: string;
/**
* uuid of a system
- * @since 1.10.0
*/
uuid: string;
name?: string;
/**
* description for a system
- * @since 1.10.0
*/
description?: string;
/**
* tag for a system
- * @since 1.10.0
*/
tag?: string;
/**
* the pronouns of a system
- * @since 1.10.0
*/
pronouns?: string;
/**
* Attention this is a http url not a mxc url, you need to consider that.
- * @since 1.10.0
*/
avatar_url?: string;
/**
* this is a http url, so you have to download it and upload it to your homeserver
- * @since 1.10.0
*/
banner?: string;
/**
* The color of a system
- * @since 1.10.0
*/
color?: string;
/**
* Date string in ISO 8601 format, e.g. "2024-01-01T00:00:00Z" (assumingly)
- * @since 1.10.0
*/
created: string;
};
@@ -59,64 +49,52 @@ export type PluralKitProxyTag = {
/**
* the {@link https://pluralkit.me/api/models/#member-model Data model for a system member}
- * @since 1.10.0
* @author Rye
*/
export type PluralKitMember = {
/**
* a freeform id demarking a member of a system
- * @since 1.10.0
*/
id: string;
/**
* uuid of a member
- * @since 1.10.0
*/
uuid: string;
/**
* the name a member of a system uses
- * @since 1.10.0
*/
name: string;
/**
* the display name a member of a system uses
- * @since 1.10.0
*/
display_name?: string;
/**
* the color a member of a system uses
- * @since 1.10.0
*/
color?: string;
/**
* pronouns the member of a system uses
- * @since 1.10.0
*/
pronouns?: string;
/**
* this is a http url, so you have to download it and upload it to your homeserver
- * @since 1.10.0
*/
avatar_url?: string;
/**
* probably won't be really usable in our usecase
- * @since 1.10.0
*/
webhook_avatar_url?: string;
/**
* this is a http url, so you have to download it and upload it to your homeserver
- * @since 1.10.0
*/
banner?: string;
/**
* a description of a member of a system
* this could be as long as 1000 chars
- * @since 1.10.0
*/
description?: string;
/**
* date when it was created
- * @since 1.10.0
*/
created: string;
proxy_tags: Array;
diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts
index 0a8e47fd3..0375631c5 100644
--- a/src/app/state/settings.ts
+++ b/src/app/state/settings.ts
@@ -99,6 +99,10 @@ export interface Settings {
alwaysShowCallButton: boolean;
faviconForMentionsOnly: boolean;
highlightMentions: boolean;
+ /**
+ * whether to enable pk compat
+ */
+ pkCompat: boolean;
// furry stuff
renderAnimals: boolean;
@@ -182,6 +186,7 @@ const defaultSettings: Settings = {
alwaysShowCallButton: false,
faviconForMentionsOnly: false,
highlightMentions: true,
+ pkCompat: false,
// furry stuff
renderAnimals: true,
diff --git a/src/types/matrix/accountData.ts b/src/types/matrix/accountData.ts
index 6d0a804e2..2153ec331 100644
--- a/src/types/matrix/accountData.ts
+++ b/src/types/matrix/accountData.ts
@@ -21,6 +21,9 @@ export enum AccountDataEvent {
// Sable account data
SableNicknames = 'moe.sable.app.nicknames',
SablePinStatus = 'moe.sable.app.pins_read_marker',
+
+ // because of a mistake hasn't been renamed in time
+ SablePerProfileMessageProfiles = 'fyi.cisnt.permessageprofile',
}
export type MDirectContent = Record;
@@ -50,6 +53,24 @@ export type SecretContent = {
mac: string;
};
+/**
+ * type to save compatibility information
+ */
+export type AccountDataCompatVersion = {
+ /**
+ * a simple version number, for example 1
+ */
+ version: number;
+ /**
+ * the date where it was added
+ */
+ compatDate: string;
+ /**
+ * version number which is the oldest compatible, this attribute is optional
+ */
+ incompatBefore?: number;
+};
+
export type SecretAccountData = {
encrypted: Record;
};
From ba18d25bc23ff6f5b879bc48685c7622098fbac4 Mon Sep 17 00:00:00 2001
From: Rye
Date: Thu, 26 Mar 2026 14:39:44 +0100
Subject: [PATCH 13/58] fix(pk-compat-proxy): extracting message from proxied
message
---
src/app/features/room/RoomInput.tsx | 2 ++
.../plugins/pluralkit-handler/PKitProxyMessageHandler.ts | 7 +++++++
2 files changed, 9 insertions(+)
diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx
index c6764e04f..f109fc066 100644
--- a/src/app/features/room/RoomInput.tsx
+++ b/src/app/features/room/RoomInput.tsx
@@ -728,6 +728,8 @@ export const RoomInput = forwardRef(
// check if its a pk command
if (pkCompatEnable && PKitCommandMessageHandler.isPKCommand(plainText)) {
pluralkitCmdMessageHandler.handleMessage(plainText);
+ resetEditor(editor); // clear the editor
+ return; // don't do anything besides handling the command
}
if (commandName) {
diff --git a/src/app/plugins/pluralkit-handler/PKitProxyMessageHandler.ts b/src/app/plugins/pluralkit-handler/PKitProxyMessageHandler.ts
index d51b674e1..ad10ee3ef 100644
--- a/src/app/plugins/pluralkit-handler/PKitProxyMessageHandler.ts
+++ b/src/app/plugins/pluralkit-handler/PKitProxyMessageHandler.ts
@@ -79,6 +79,13 @@ export class PKitProxyMessageHandler {
return getPerMessageProfileById(this.mx, profileId);
}
+ /**
+ * this runs synchronously, so it needs to be inited beforehand
+ *
+ * @param {string} message the message you want to extract from
+ * @return {*} {(string | undefined)} the message without the proxy
+ * @memberof PKitProxyMessageHandler
+ */
public stripProxyFromMessage(message: string): string | undefined {
if (!this.succInit) throw new Error('PK proxy message handler is not initialized');
let m;
From 75d014588b8d741a2bfc6153ab26093c566a57e9 Mon Sep 17 00:00:00 2001
From: Rye
Date: Thu, 26 Mar 2026 14:53:18 +0100
Subject: [PATCH 14/58] fix(pmp-command): fix usepmp command handling and
description
---
src/app/hooks/useCommands.ts | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/app/hooks/useCommands.ts b/src/app/hooks/useCommands.ts
index 2a0d45666..091224d14 100644
--- a/src/app/hooks/useCommands.ts
+++ b/src/app/hooks/useCommands.ts
@@ -562,13 +562,13 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
[Command.UsePerMessageProfile]: {
name: Command.UsePerMessageProfile,
description:
- 'Use a per message profile for this room once, or until reset. Example: /usepmp profileId [once,reset,or duration like 1h30m]',
+ 'Use a per message profile for this room once, or until reset. Example: /usepmp [profileId,reset]',
exe: async (payload) => {
// this command doesn't need to do anything, the composer will pick it up and apply the profile to the message being composed
const profileId: string = splitWithSpace(payload)[0];
const durationStr: string | undefined = splitWithSpace(payload)[1];
let validUntil: number | undefined;
- if (durationStr === 'reset') {
+ if (profileId.normalize() === 'reset') {
setCurrentlyUsedPerMessageProfileIdForRoom(mx, room.roomId, undefined, undefined, true)
.then(() => {
sendFeedback('Per message profile reset for this room.', room, mx.getSafeUserId());
From 59fcd841a1390a4c896474ea2e10e2a4a02b64c8 Mon Sep 17 00:00:00 2001
From: Evie Gauthier
Date: Thu, 26 Mar 2026 10:30:48 -0400
Subject: [PATCH 15/58] fix: fetch room/sender avatar and display name for push
notifications
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
When the pusher uses event_id_only format the SW fetches event details
itself. Previously only the display name and room name were retrieved;
the notification icon was always the default app logo.
- fetchMemberDisplayName → fetchMemberInfo: also captures avatar_url
from the m.room.member state response, so a single HTTP request gives
us both the display name and the sender avatar
- fetchRoomAvatar: fetches m.room.avatar state; used for group rooms
- mxcToNotificationUrl: converts mxc:// to a legacy unauthenticated
thumbnail URL so the OS can load the icon without an auth header
- handleMinimalPushPayload: fetch room avatar in the initial parallel
request batch; resolve notification icon as room avatar > member
avatar (DM fallback); pass room_avatar_url to all
handlePushNotificationPushData call sites
- encrypted path: prefer the server-fetched senderDisplay (authoritative)
over the relay's SDK cache value, which may be stale or absent when
the app hasn't fully synced after a cold resume
---
src/sw.ts | 86 ++++++++++++++++++++++++++++++++++++++++++++++---------
1 file changed, 72 insertions(+), 14 deletions(-)
diff --git a/src/sw.ts b/src/sw.ts
index 230a87646..bd09cd8d3 100644
--- a/src/sw.ts
+++ b/src/sw.ts
@@ -277,28 +277,73 @@ async function fetchRoomName(
}
}
+type MemberInfo = {
+ displayname: string | undefined;
+ avatarUrl: string | undefined;
+};
+
/**
- * Fetch a room member's displayname from homeserver member state.
- * Returns undefined if the member has no displayname or the request fails.
+ * Fetch a room member's state from the homeserver.
+ * Returns displayname and avatar_url (both may be undefined).
*/
-async function fetchMemberDisplayName(
+async function fetchMemberInfo(
baseUrl: string,
accessToken: string,
roomId: string,
userId: string
-): Promise {
+): Promise {
try {
const url = `${baseUrl}/_matrix/client/v3/rooms/${encodeURIComponent(roomId)}/state/m.room.member/${encodeURIComponent(userId)}`;
const res = await fetch(url, { headers: { Authorization: `Bearer ${accessToken}` } });
+ if (!res.ok) return { displayname: undefined, avatarUrl: undefined };
+ const data = (await res.json()) as Record;
+ const displayname =
+ typeof data.displayname === 'string' && data.displayname.trim()
+ ? data.displayname.trim()
+ : undefined;
+ const avatarUrl =
+ typeof data.avatar_url === 'string' && data.avatar_url.trim()
+ ? data.avatar_url.trim()
+ : undefined;
+ return { displayname, avatarUrl };
+ } catch {
+ return { displayname: undefined, avatarUrl: undefined };
+ }
+}
+
+/**
+ * Fetch the m.room.avatar state event URL from the homeserver.
+ * Returns undefined when the room has no avatar or the request fails.
+ */
+async function fetchRoomAvatar(
+ baseUrl: string,
+ accessToken: string,
+ roomId: string
+): Promise {
+ try {
+ const url = `${baseUrl}/_matrix/client/v3/rooms/${encodeURIComponent(roomId)}/state/m.room.avatar`;
+ const res = await fetch(url, { headers: { Authorization: `Bearer ${accessToken}` } });
if (!res.ok) return undefined;
const data = (await res.json()) as Record;
- const name = data.displayname;
- return typeof name === 'string' && name.trim() ? name.trim() : undefined;
+ const avatarUrl = data.url;
+ return typeof avatarUrl === 'string' && avatarUrl.trim() ? avatarUrl.trim() : undefined;
} catch {
return undefined;
}
}
+/**
+ * Convert an mxc:// URL to a legacy unauthenticated thumbnail URL.
+ * Notification icons are fetched by the OS without auth headers, so we use
+ * the pre-MSC3916 media endpoint which most homeservers still serve publicly.
+ */
+function mxcToNotificationUrl(mxcUrl: string, baseUrl: string): string | undefined {
+ const match = mxcUrl.match(/^mxc:\/\/([^/]+)\/([^?#]+)/);
+ if (!match) return undefined;
+ const [, server, mediaId] = match;
+ return `${baseUrl}/_matrix/media/v3/thumbnail/${encodeURIComponent(server)}/${encodeURIComponent(mediaId)}?width=96&height=96&method=crop`;
+}
+
/**
* Return the first any-session we have stored (used for push fetches where we
* don't have a client ID, e.g. when the app is backgrounded but still loaded).
@@ -386,10 +431,11 @@ async function handleMinimalPushPayload(
return;
}
- // Fetch the raw event and room name state in parallel — both need only roomId.
- const [rawEvent, roomNameFromState] = await Promise.all([
+ // Fetch the raw event, room name, and room avatar in parallel — all need only roomId.
+ const [rawEvent, roomNameFromState, roomAvatarMxc] = await Promise.all([
fetchRawEvent(session.baseUrl, session.accessToken, roomId, eventId),
fetchRoomName(session.baseUrl, session.accessToken, roomId),
+ fetchRoomAvatar(session.baseUrl, session.accessToken, roomId),
]);
if (!rawEvent) {
@@ -406,13 +452,20 @@ async function handleMinimalPushPayload(
const eventType = rawEvent.type as string | undefined;
const sender = rawEvent.sender as string | undefined;
- // Fetch sender's display name from room member state; fall back to MXID localpart.
- const senderDisplay =
- (sender
- ? await fetchMemberDisplayName(session.baseUrl, session.accessToken, roomId, sender)
- : undefined) ?? (sender ? mxidLocalpart(sender) : 'Someone');
+ // Fetch sender's member state — gives us both display name and avatar URL.
+ const memberInfo = sender
+ ? await fetchMemberInfo(session.baseUrl, session.accessToken, roomId, sender)
+ : { displayname: undefined, avatarUrl: undefined };
+ // Fall back to MXID localpart when the server returns no displayname.
+ const senderDisplay = memberInfo.displayname ?? (sender ? mxidLocalpart(sender) : 'Someone');
// For DMs (no m.room.name state), use the sender's display name as the room name.
const resolvedRoomName = roomNameFromState ?? senderDisplay;
+ // Room avatar takes priority (group rooms); for DMs fall back to sender's member avatar.
+ // Convert mxc:// to a legacy unauthenticated thumbnail URL so the OS can fetch it.
+ const notificationAvatarUrl =
+ (roomAvatarMxc ?? memberInfo.avatarUrl) !== undefined
+ ? mxcToNotificationUrl((roomAvatarMxc ?? memberInfo.avatarUrl)!, session.baseUrl)
+ : undefined;
const baseData = {
room_id: roomId,
event_id: eventId,
@@ -432,13 +485,16 @@ async function handleMinimalPushPayload(
if (result?.success) {
// App was backgrounded but not frozen — decryption succeeded.
+ // Prefer the server-fetched display name (authoritative) over the relay's SDK cache
+ // value, which may be stale or missing if the SDK hasn't fully synced yet.
await handlePushNotificationPushData({
...baseData,
type: result.eventType,
content: result.content,
- sender_display_name: result.sender_display_name ?? senderDisplay,
+ sender_display_name: senderDisplay,
// Prefer relay's room name (has m.direct / computed SDK name); fall back to state fetch.
room_name: result.room_name || resolvedRoomName,
+ room_avatar_url: notificationAvatarUrl,
});
} else {
// App is frozen or fully closed — show "Encrypted message" fallback.
@@ -448,6 +504,7 @@ async function handleMinimalPushPayload(
content: {},
sender_display_name: senderDisplay,
room_name: resolvedRoomName,
+ room_avatar_url: notificationAvatarUrl,
});
}
} else {
@@ -458,6 +515,7 @@ async function handleMinimalPushPayload(
content: rawEvent.content,
sender_display_name: senderDisplay,
room_name: resolvedRoomName,
+ room_avatar_url: notificationAvatarUrl,
});
}
}
From ac3814d6cb6e6116d33047142f0f6f13a2823973 Mon Sep 17 00:00:00 2001
From: Evie Gauthier
Date: Thu, 26 Mar 2026 10:58:57 -0400
Subject: [PATCH 16/58] chore: add changeset for push notification metadata fix
---
.changeset/fix-push-notification-metadata.md | 5 +++++
1 file changed, 5 insertions(+)
create mode 100644 .changeset/fix-push-notification-metadata.md
diff --git a/.changeset/fix-push-notification-metadata.md b/.changeset/fix-push-notification-metadata.md
new file mode 100644
index 000000000..571a0cdb4
--- /dev/null
+++ b/.changeset/fix-push-notification-metadata.md
@@ -0,0 +1,5 @@
+---
+default: patch
+---
+
+Fix push notifications missing sender/room avatar and showing stale display names when using event_id_only push format.
From 2a4fd48af9dd471e5014c30eb1e831ce9fe6f26f Mon Sep 17 00:00:00 2001
From: Rye
Date: Thu, 26 Mar 2026 19:47:59 +0100
Subject: [PATCH 17/58] feat(PMP-PK): added more options (removing
shorthand,...) and documentation
---
.changeset/add_limited_pk_command_support.md | 5 ++
.changeset/add_pmp_shorthands.md | 5 ++
.changeset/fix_command_handling_for_usepmp.md | 5 ++
src/app/features/room/RoomInput.tsx | 10 ++-
.../features/settings/Persona/PKCompat.tsx | 52 +++++++++++++
.../settings/Persona/ProfilesPage.tsx | 2 +
src/app/hooks/useCommands.ts | 14 ++++
src/app/hooks/usePerMessageProfile.ts | 12 +++
.../PKitCommandMessageHandler.ts | 77 ++++++++++++++++---
src/app/state/settings.ts | 2 +
10 files changed, 170 insertions(+), 14 deletions(-)
create mode 100644 .changeset/add_limited_pk_command_support.md
create mode 100644 .changeset/add_pmp_shorthands.md
create mode 100644 .changeset/fix_command_handling_for_usepmp.md
create mode 100644 src/app/features/settings/Persona/PKCompat.tsx
diff --git a/.changeset/add_limited_pk_command_support.md b/.changeset/add_limited_pk_command_support.md
new file mode 100644
index 000000000..89f1cdf73
--- /dev/null
+++ b/.changeset/add_limited_pk_command_support.md
@@ -0,0 +1,5 @@
+---
+default: minor
+---
+
+added a limited compatibility with `pk;member` commands
diff --git a/.changeset/add_pmp_shorthands.md b/.changeset/add_pmp_shorthands.md
new file mode 100644
index 000000000..e81477885
--- /dev/null
+++ b/.changeset/add_pmp_shorthands.md
@@ -0,0 +1,5 @@
+---
+default: minor
+---
+
+added option to use shorthands to send a message with a Persona, for example `✨:test`
diff --git a/.changeset/fix_command_handling_for_usepmp.md b/.changeset/fix_command_handling_for_usepmp.md
new file mode 100644
index 000000000..6cea72c0e
--- /dev/null
+++ b/.changeset/fix_command_handling_for_usepmp.md
@@ -0,0 +1,5 @@
+---
+default: patch
+---
+
+rephrased the command describtion for `/usepmp` and made `/usepmp reset` actually reset the room association of the pmp
diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx
index f109fc066..027760a3a 100644
--- a/src/app/features/room/RoomInput.tsx
+++ b/src/app/features/room/RoomInput.tsx
@@ -274,7 +274,8 @@ export const RoomInput = forwardRef(
pluralkitProxyMessageHandler.init();
}, [pluralkitProxyMessageHandler]);
- const pkCompatEnable = useSetting(settingsAtom, 'pkCompat');
+ const [pkCompatEnable] = useSetting(settingsAtom, 'pkCompat');
+ const [pmpProxyingEnable] = useSetting(settingsAtom, 'pmpProxying');
const emojiBtnRef = useRef(null);
const micBtnRef = useRef(null);
const roomToParents = useAtomValue(roomToParentsAtom);
@@ -789,11 +790,11 @@ export const RoomInput = forwardRef(
* and also allows clients to display an accurate preview of how the message will look with the profile applied while it's being composed.
*/
const perMessageProfile =
- pkCompatEnable && pluralkitProxyMessageHandler.isAProxiedMessage(plainText)
+ pmpProxyingEnable && pluralkitProxyMessageHandler.isAProxiedMessage(plainText)
? await pluralkitProxyMessageHandler.getPmpBasedOnMessage(plainText)
: await getCurrentlyUsedPerMessageProfileForRoom(mx, roomId);
- if (pkCompatEnable && pluralkitProxyMessageHandler.isAProxiedMessage(plainText))
+ if (pmpProxyingEnable && pluralkitProxyMessageHandler.isAProxiedMessage(plainText))
plainText = pluralkitProxyMessageHandler.stripProxyFromMessage(plainText) ?? plainText;
if (perMessageProfile) {
content['com.beeper.per_message_profile'] =
@@ -925,9 +926,10 @@ export const RoomInput = forwardRef(
isMarkdown,
canSendReaction,
pkCompatEnable,
- pluralkitProxyMessageHandler,
replyDraft,
silentReply,
+ pmpProxyingEnable,
+ pluralkitProxyMessageHandler,
scheduledTime,
editingScheduledDelayId,
nicknames,
diff --git a/src/app/features/settings/Persona/PKCompat.tsx b/src/app/features/settings/Persona/PKCompat.tsx
new file mode 100644
index 000000000..f69644df0
--- /dev/null
+++ b/src/app/features/settings/Persona/PKCompat.tsx
@@ -0,0 +1,52 @@
+import { SequenceCard } from '$components/sequence-card';
+import { SettingTile } from '$components/setting-tile';
+import { useSetting } from '$state/hooks/settings';
+import { settingsAtom } from '$state/settings';
+import { Box, Switch, Text } from 'folds';
+import { SequenceCardStyle } from '../styles.css';
+
+export function PKCompatSettings() {
+ const [usePKCompat, setUsePKCompat] = useSetting(settingsAtom, 'pkCompat');
+ const [usePmpProxying, setUsePmpProxying] = useSetting(settingsAtom, 'pmpProxying');
+
+ return (
+
+ Limited Compatibility with PluralKit-like functions
+
+
+ }
+ />
+
+ }
+ />
+
+
+ );
+}
diff --git a/src/app/features/settings/Persona/ProfilesPage.tsx b/src/app/features/settings/Persona/ProfilesPage.tsx
index 2fe56f51c..a090b3c63 100644
--- a/src/app/features/settings/Persona/ProfilesPage.tsx
+++ b/src/app/features/settings/Persona/ProfilesPage.tsx
@@ -1,6 +1,7 @@
import { Page, PageHeader, PageNavContent } from '$components/page';
import { Box, IconButton, Icon, Icons, Text } from 'folds';
import { PerMessageProfileOverview } from './PerMessageProfileOverview';
+import { PKCompatSettings } from './PKCompat';
type PerMessageProfilePageProps = {
requestClose: () => void;
@@ -37,6 +38,7 @@ export function PerMessageProfilePage({ requestClose }: PerMessageProfilePagePro
direction="Column"
shrink="No"
>
+
diff --git a/src/app/hooks/useCommands.ts b/src/app/hooks/useCommands.ts
index 091224d14..c80bdafa6 100644
--- a/src/app/hooks/useCommands.ts
+++ b/src/app/hooks/useCommands.ts
@@ -32,6 +32,7 @@ import { useOpenBugReportModal } from '$state/hooks/bugReportModal';
import { createRoomEncryptionState } from '$components/create-room';
import { parsePronounsInput } from '$utils/pronouns';
import { sendFeedback } from '$utils/sendFeedbackToUser';
+import { PKitCommandMessageHandler } from '$plugins/pluralkit-handler/PKitCommandMessageHandler';
import { useRoomNavigate } from './useRoomNavigate';
import { enrichWidgetUrl } from './useRoomWidgets';
import { useUserProfile } from './useUserProfile';
@@ -241,6 +242,7 @@ export enum Command {
AddPerMessageProfileToAccount = 'addpmp',
DeletePerMessageProfileFromAccount = 'delpmp',
UsePerMessageProfile = 'usepmp',
+ AssociateProxyPerMessageProfile = 'pmpproxy',
Pronoun = 'pronoun',
SPronoun = 'spronoun',
Rainbow = 'rainbow',
@@ -276,6 +278,8 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
const { navigateRoom } = useRoomNavigate();
const [developerTools] = useSetting(settingsAtom, 'developerTools');
const [enableMSC4268CMD] = useSetting(settingsAtom, 'enableMSC4268CMD');
+ // helper for pkit commands
+ const pkitcmdHandler = useMemo(() => new PKitCommandMessageHandler(mx, room), [mx, room]);
const profile = useUserProfile(mx.getSafeUserId());
const openBugReport = useOpenBugReportModal();
@@ -601,6 +605,15 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
});
},
},
+ [Command.AssociateProxyPerMessageProfile]: {
+ name: Command.AssociateProxyPerMessageProfile,
+ description: 'Associate proxy with a profile. Example /pmpproxy id ✨:text',
+ exe: async (payload) => {
+ const pid: string = splitWithSpace(payload)[0];
+ const proxy: string = splitWithSpace(payload)[1];
+ pkitcmdHandler.handleMessage(`pk;member "${pid}" proxy ${proxy}`, true);
+ },
+ },
[Command.MyRoomAvatar]: {
name: Command.MyRoomAvatar,
description: 'Change profile picture in current room. Example /myroomavatar mxc://xyzabc',
@@ -1437,6 +1450,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
room,
profile.displayName,
profile.avatarUrl,
+ pkitcmdHandler,
developerTools,
enableMSC4268CMD,
openBugReport,
diff --git a/src/app/hooks/usePerMessageProfile.ts b/src/app/hooks/usePerMessageProfile.ts
index 12c16b34b..38749090c 100644
--- a/src/app/hooks/usePerMessageProfile.ts
+++ b/src/app/hooks/usePerMessageProfile.ts
@@ -420,6 +420,18 @@ export async function getAllPerMessageProfileProxies(
return parr;
}
+export async function dropProxyAssociationForPMP(mx: MatrixClient, proxy: string) {
+ const associations = getProxyAssociationMap(
+ mx.getAccountData(`${ACCOUNT_DATA_PREFIX}.proxyassociation` as any)?.getContent()
+ );
+ if (!associations) return;
+ associations.delete(proxy);
+ mx.setAccountData(
+ `${ACCOUNT_DATA_PREFIX}.proxyassociation` as any,
+ { associations: proxyAssociationsMapToObject(associations) } as any
+ );
+}
+
/**
*
* drops all room associations for a profile, used when deleting a profile to make sure there are no dangling associations left that point to a non existing profile, which could cause issues when trying to apply the profile to a message in a room that still has an association for the deleted profile.
diff --git a/src/app/plugins/pluralkit-handler/PKitCommandMessageHandler.ts b/src/app/plugins/pluralkit-handler/PKitCommandMessageHandler.ts
index c1108395d..2920d5011 100644
--- a/src/app/plugins/pluralkit-handler/PKitCommandMessageHandler.ts
+++ b/src/app/plugins/pluralkit-handler/PKitCommandMessageHandler.ts
@@ -1,6 +1,7 @@
import {
addOrUpdatePerMessageProfile,
associateProxyWithProfile,
+ dropProxyAssociationForPMP,
getAllPerMessageProfiles,
getPerMessageProfileById,
PerMessageProfile,
@@ -10,11 +11,15 @@ import { MatrixClient, Room } from 'matrix-js-sdk';
const pkMemberRenameRegex = /^(pk;member)\s+"?([\w\s]+)"?\s*rename\s+"?([\w\s]+)"?$/;
const pkMemberNewRegex = /^(pk;member)\s+new\s+"?([\w\s]+)"?$/;
-const pkMemberNewProxy = /^(pk;member)\s+"?([\w\s]+)"?\s+proxy\s+(.*text.*)$/;
+const pkMemberNewProxy = /^(pk;member)\s+"?([\w\s]+)"?\s+proxy(\s+add)?\s+(.*text.*)$/;
+const pkMemberRemoveProxy = /^(pk;member)\s+"?([\w\s]+)"?\s+proxy\s+remove\s+(.*text.*)$/;
const helpTextPkMemberNew = 'To create a new persona: pk;member new Yumi';
const helpTextPkMemberRename = 'To rename a persona: pk;member "Rain Deer" rename "Micky Mouse"';
-const helpTextPkMemberNewProxy = 'To create a persona: pk;member Yumi proxy [text]';
+const helpTextPkMemberNewProxy = 'To add a shorthand to a persona: pk;member Yumi proxy [text]';
+const helpTextPkMemberRemoveProxy =
+ 'To remove a shorthand from a persona: pk;member Yumi proxy remove [text]';
+const helpTextPkMember = `Available 'pk;member' commands:\n${helpTextPkMemberNew}\n${helpTextPkMemberRename}\n${helpTextPkMemberNewProxy}\n${helpTextPkMemberRemoveProxy}`;
/**
* build a regex to recognize proxies
@@ -37,15 +42,32 @@ function buildRegex(template: string): RegExp {
* @author Rye
*/
export class PKitCommandMessageHandler {
+ /**
+ * the matrix client we use, is set in the constructor
+ *
+ * @private
+ * @type {MatrixClient}
+ * @memberof PKitCommandMessageHandler
+ */
private readonly mx: MatrixClient;
private message = '';
private readonly room: Room;
+ /**
+ * flag to interpret the name given as id
+ *
+ * @private
+ * @type {boolean}
+ * @memberof PKitCommandMessageHandler
+ */
+ private useIdInsteadOfNameWherePossible: boolean;
+
public constructor(mx: MatrixClient, room: Room) {
this.mx = mx;
this.room = room;
+ this.useIdInsteadOfNameWherePossible = false;
}
/**
@@ -127,15 +149,41 @@ export class PKitCommandMessageHandler {
this.mx.getSafeUserId()
);
addOrUpdatePerMessageProfile(this.mx, pmp);
+ } else if (pkMemberRemoveProxy.test(this.message)) {
+ const cmdParts = pkMemberRemoveProxy.exec(this.message);
+ if (!cmdParts) return;
+ const name = cmdParts[2];
+ const matchAgainst = cmdParts[3];
+ const pmpId = this.useIdInsteadOfNameWherePossible
+ ? name
+ : (await getAllPerMessageProfiles(this.mx)).find((pmp) => pmp.name === name)?.id;
+ if (!pmpId) {
+ sendFeedback(
+ `Persona with ${this.useIdInsteadOfNameWherePossible ? 'id' : 'name'} "${name}" doesn't exist in your records, ${helpTextPkMemberNew}`,
+ this.room,
+ this.mx.getSafeUserId()
+ );
+ return;
+ }
+
+ dropProxyAssociationForPMP(this.mx, matchAgainst);
+
+ 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;
const name = cmdParts[2];
- const matchAgainst = cmdParts[3];
- const pmpId = (await getAllPerMessageProfiles(this.mx)).find((pmp) => pmp.name === name)?.id;
+ const matchAgainst = cmdParts[4];
+ const pmpId = this.useIdInsteadOfNameWherePossible
+ ? name
+ : (await getAllPerMessageProfiles(this.mx)).find((pmp) => pmp.name === name)?.id;
if (!pmpId) {
sendFeedback(
- `Persona with name "${name}" doesn't exist in your records, ${helpTextPkMemberNew}`,
+ `Persona with ${this.useIdInsteadOfNameWherePossible ? 'id' : 'name'} "${name}" doesn't exist in your records, ${helpTextPkMemberNew}`,
this.room,
this.mx.getSafeUserId()
);
@@ -144,7 +192,7 @@ export class PKitCommandMessageHandler {
const matchAgainstRegExp = buildRegex(matchAgainst);
associateProxyWithProfile(this.mx, pmpId, matchAgainst, matchAgainstRegExp, false);
sendFeedback(
- `Persona with name "${name}" (${pmpId}) is now associated with ${matchAgainst}`,
+ `Persona with ${this.useIdInsteadOfNameWherePossible ? 'id' : 'name'} "${name}" (${pmpId}) is now associated with ${matchAgainst}`,
this.room,
this.mx.getSafeUserId()
);
@@ -155,7 +203,7 @@ export class PKitCommandMessageHandler {
.map((pmp: PerMessageProfile) => `${pmp.id}: ${pmp.name ? pmp.name : '(empty name)'}`)
.join('\n');
sendFeedback(
- `You currently have the following persona set up:\n${stringListOfProfiles}\n\n${helpTextPkMemberNew}\n${helpTextPkMemberRename}\n${helpTextPkMemberNewProxy}`,
+ `If you see this, you have messed up a command\n\nYou currently have the following persona set up:\n${stringListOfProfiles}\n\n${helpTextPkMember}`,
this.room,
this.mx.getSafeUserId()
);
@@ -176,9 +224,18 @@ export class PKitCommandMessageHandler {
* @param message the message we want to handle
* @returns void
*/
- public async handleMessage(message: string): Promise {
+ public async handleMessage(message: string, useId?: boolean): Promise {
this.message = message;
- if (!this.message.startsWith('pk')) return;
- if (this.message.startsWith('pk;member')) await this.memberHandler();
+ this.useIdInsteadOfNameWherePossible = useId ?? false;
+ if (!this.message.startsWith('pk;')) return;
+ if (this.message.startsWith('pk;member')) {
+ await this.memberHandler();
+ return;
+ }
+ sendFeedback(
+ `Command currently not supported, right now compatibility is limited and only a subset of pk;member is supported\n\n${helpTextPkMember}`,
+ this.room,
+ this.mx.getSafeUserId()
+ );
}
}
diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts
index 0375631c5..f6132b210 100644
--- a/src/app/state/settings.ts
+++ b/src/app/state/settings.ts
@@ -103,6 +103,7 @@ export interface Settings {
* whether to enable pk compat
*/
pkCompat: boolean;
+ pmpProxying: boolean;
// furry stuff
renderAnimals: boolean;
@@ -187,6 +188,7 @@ const defaultSettings: Settings = {
faviconForMentionsOnly: false,
highlightMentions: true,
pkCompat: false,
+ pmpProxying: false,
// furry stuff
renderAnimals: true,
From 155ac64c65912224ee1d0b4b1e89867c4fce79cd Mon Sep 17 00:00:00 2001
From: Rye
Date: Fri, 27 Mar 2026 01:38:05 +0100
Subject: [PATCH 18/58] fix(PMP-Command): fix the syntax handling of pmp
related command
---
src/app/hooks/useCommands.ts | 59 +++++++++++++++++++++---------------
1 file changed, 35 insertions(+), 24 deletions(-)
diff --git a/src/app/hooks/useCommands.ts b/src/app/hooks/useCommands.ts
index c80bdafa6..dd92d3614 100644
--- a/src/app/hooks/useCommands.ts
+++ b/src/app/hooks/useCommands.ts
@@ -51,6 +51,9 @@ const FLAG_PAT = String.raw`(?:^|\s)-(\w+)\b`;
const FLAG_REG = new RegExp(FLAG_PAT);
const FLAG_REG_G = new RegExp(FLAG_PAT, 'g');
+const ADDPMP_REGEX = /(\w+) (name=)?"?([\w\s]*)"? (avatar=)?([\w.:/]+)/;
+const USEPMP_REGEX = /^(\w+)\s*(-g)?(-o)?(-u)?\s*(\d+)?$/;
+
export const splitPayloadContentAndFlags = (payload: string): [string, string | undefined] => {
const flagMatch = new RegExp(FLAG_REG).exec(payload);
@@ -493,26 +496,19 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
'Add or update a per message profile to your account. Example: /addpmp profileId name=Profile Name avatar=mxc://xyzabc',
exe: async (payload) => {
// Parse key=value pairs
- const parts = payload.split(' ');
- let avatarUrl: string | undefined;
- let name: string | undefined;
- parts.forEach((part, index) => {
- const [key, value] = part.split('=');
- if (key && value) {
- if (key === 'name' || key === 'avatar') {
- if (key === 'name') {
- name = parts
- .slice(index)
- .map((p) => p.split('=')[1])
- .join(' ');
- return;
- }
- if (key === 'avatar') avatarUrl = value;
- }
- }
- });
+ const args = ADDPMP_REGEX.exec(payload);
+ if (!args) {
+ sendFeedback(`invalid payload`, room, mx.getSafeUserId());
+ return;
+ }
+ const avatarUrl: string | undefined = args[5];
+ const name: string | undefined = args[3];
+ const profileId = args[1];
- const profileId = parts[0]; // profileId is positional (before any key=)
+ if (!avatarUrl || !name || !profileId) {
+ sendFeedback(`invalid payload`, room, mx.getSafeUserId());
+ return;
+ }
const pmp: PerMessageProfile = {
id: profileId,
@@ -568,10 +564,25 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
description:
'Use a per message profile for this room once, or until reset. Example: /usepmp [profileId,reset]',
exe: async (payload) => {
- // this command doesn't need to do anything, the composer will pick it up and apply the profile to the message being composed
- const profileId: string = splitWithSpace(payload)[0];
- const durationStr: string | undefined = splitWithSpace(payload)[1];
- let validUntil: number | undefined;
+ const args = USEPMP_REGEX.exec(payload);
+ if (!args) {
+ sendFeedback(`invalid payload`, room, mx.getSafeUserId());
+ return;
+ }
+ const profileId = args[1];
+ const globalFlag = args[2] !== undefined;
+ const onceFlag = args[3] !== undefined;
+ // const untilFlag = args[4] !== undefined;
+ const validUntil = Number.parseInt(args[5], 10);
+ if (onceFlag || globalFlag) {
+ sendFeedback(
+ 'Currently not implemented, consider using shorthands, with /pmpproxy id ✨:text',
+ room,
+ mx.getSafeUserId()
+ );
+ return;
+ }
+
if (profileId.normalize() === 'reset') {
setCurrentlyUsedPerMessageProfileIdForRoom(mx, room.roomId, undefined, undefined, true)
.then(() => {
@@ -590,7 +601,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
.then(() => {
sendFeedback(
`Per message profile "${profileId}" will be used for messages in this room for the until ${
- durationStr ?? 'reset'
+ validUntil ?? 'reset'
}. Use \`/usepmp reset\` to reset it at any time.`,
room,
mx.getSafeUserId()
From bc8e9646cefe3114b9fe7f98da680408441c16e0 Mon Sep 17 00:00:00 2001
From: Rye
Date: Fri, 27 Mar 2026 01:43:33 +0100
Subject: [PATCH 19/58] docs(PMP-Command): adjusted the description of
`/usepmp` and also added a changeset
---
.changeset/fix_pmp_commands.md | 5 +++++
src/app/hooks/useCommands.ts | 2 +-
2 files changed, 6 insertions(+), 1 deletion(-)
create mode 100644 .changeset/fix_pmp_commands.md
diff --git a/.changeset/fix_pmp_commands.md b/.changeset/fix_pmp_commands.md
new file mode 100644
index 000000000..34d5a7a5d
--- /dev/null
+++ b/.changeset/fix_pmp_commands.md
@@ -0,0 +1,5 @@
+---
+default: patch
+---
+
+fixed the syntax issues regarding `/addpmp` and `usepmp` (note that the syntax for `/usepmp` has changed)
diff --git a/src/app/hooks/useCommands.ts b/src/app/hooks/useCommands.ts
index dd92d3614..7e528fa59 100644
--- a/src/app/hooks/useCommands.ts
+++ b/src/app/hooks/useCommands.ts
@@ -562,7 +562,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
[Command.UsePerMessageProfile]: {
name: Command.UsePerMessageProfile,
description:
- 'Use a per message profile for this room once, or until reset. Example: /usepmp [profileId,reset]',
+ 'Use a per message profile for this room once, or until reset. Example: /usepmp (profileId,reset) [-o,-u,-g] [ts]',
exe: async (payload) => {
const args = USEPMP_REGEX.exec(payload);
if (!args) {
From 0c7911cbf8af8153102920cbb03453adc034b091 Mon Sep 17 00:00:00 2001
From: Rye
Date: Fri, 27 Mar 2026 02:32:41 +0100
Subject: [PATCH 20/58] fix: remove unused files and added fallback for regex
escaping
---
.../PKitCommandMessageHandler.ts | 9 +-
.../pluralkitImportFormat.ts | 106 ------------------
.../pluralkitSyntaxAdapter.ts | 0
3 files changed, 8 insertions(+), 107 deletions(-)
delete mode 100644 src/app/plugins/pluralkit-handler/pluralkitImportFormat.ts
delete mode 100644 src/app/plugins/pluralkit-handler/pluralkitSyntaxAdapter.ts
diff --git a/src/app/plugins/pluralkit-handler/PKitCommandMessageHandler.ts b/src/app/plugins/pluralkit-handler/PKitCommandMessageHandler.ts
index 2920d5011..01aaf0d0b 100644
--- a/src/app/plugins/pluralkit-handler/PKitCommandMessageHandler.ts
+++ b/src/app/plugins/pluralkit-handler/PKitCommandMessageHandler.ts
@@ -21,6 +21,10 @@ const helpTextPkMemberRemoveProxy =
'To remove a shorthand from a persona: pk;member Yumi proxy remove [text]';
const helpTextPkMember = `Available 'pk;member' commands:\n${helpTextPkMemberNew}\n${helpTextPkMemberRename}\n${helpTextPkMemberNewProxy}\n${helpTextPkMemberRemoveProxy}`;
+function regexEscapeFallBackFunc(template: string): string {
+ return template.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
/**
* build a regex to recognize proxies
* a template can be for example `[text]` or `f:text`
@@ -30,7 +34,10 @@ const helpTextPkMember = `Available 'pk;member' commands:\n${helpTextPkMemberNew
*/
function buildRegex(template: string): RegExp {
const [before, after] = template.split('text');
- const pattern = `${RegExp.escape(before)}(.+)${RegExp.escape(after)}`;
+ // RegExp.escape is baseline since May 2025
+ // @ts-ignore TS2322
+ const escape = RegExp.escape ?? regexEscapeFallBackFunc;
+ const pattern = `${escape(before)}(.+)${escape(after)}`;
return new RegExp(`^${pattern}$`);
}
diff --git a/src/app/plugins/pluralkit-handler/pluralkitImportFormat.ts b/src/app/plugins/pluralkit-handler/pluralkitImportFormat.ts
deleted file mode 100644
index 9a82da6cc..000000000
--- a/src/app/plugins/pluralkit-handler/pluralkitImportFormat.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-/**
- * the {@link https://pluralkit.me/api/models/#system-model data model for a pluralkit system}
- * @author Rye
- */
-export type PluralKitSystem = {
- /**
- * id is freeform string
- */
- id: string;
- /**
- * uuid of a system
- */
- uuid: string;
- name?: string;
- /**
- * description for a system
- */
- description?: string;
- /**
- * tag for a system
- */
- tag?: string;
- /**
- * the pronouns of a system
- */
- pronouns?: string;
- /**
- * Attention this is a http url not a mxc url, you need to consider that.
- */
- avatar_url?: string;
- /**
- * this is a http url, so you have to download it and upload it to your homeserver
- */
- banner?: string;
- /**
- * The color of a system
- */
- color?: string;
- /**
- * Date string in ISO 8601 format, e.g. "2024-01-01T00:00:00Z" (assumingly)
- */
- created: string;
-};
-
-export type PluralKitProxyTag = {
- prefix?: string;
- suffix?: string;
-};
-
-/**
- * the {@link https://pluralkit.me/api/models/#member-model Data model for a system member}
- * @author Rye
- */
-export type PluralKitMember = {
- /**
- * a freeform id demarking a member of a system
- */
- id: string;
- /**
- * uuid of a member
- */
- uuid: string;
- /**
- * the name a member of a system uses
- */
- name: string;
- /**
- * the display name a member of a system uses
- */
- display_name?: string;
- /**
- * the color a member of a system uses
- */
- color?: string;
- /**
- * pronouns the member of a system uses
- */
- pronouns?: string;
- /**
- * this is a http url, so you have to download it and upload it to your homeserver
- */
- avatar_url?: string;
- /**
- * probably won't be really usable in our usecase
- */
- webhook_avatar_url?: string;
- /**
- * this is a http url, so you have to download it and upload it to your homeserver
- */
- banner?: string;
- /**
- * a description of a member of a system
- * this could be as long as 1000 chars
- */
- description?: string;
- /**
- * date when it was created
- */
- created: string;
- proxy_tags: Array;
- /**
- * a boolean to denote if it's a sticky proxy
- */
- keep_proxy: boolean;
- autoproxy_enabled?: boolean;
-};
diff --git a/src/app/plugins/pluralkit-handler/pluralkitSyntaxAdapter.ts b/src/app/plugins/pluralkit-handler/pluralkitSyntaxAdapter.ts
deleted file mode 100644
index e69de29bb..000000000
From 6e238ef94835d937bc28f3aa091d60f4240a7f38 Mon Sep 17 00:00:00 2001
From: Rye
Date: Fri, 27 Mar 2026 15:13:17 +0100
Subject: [PATCH 21/58] first implementation of MSC4440 Bios (will have to be
changed later)
---
src/app/features/settings/account/Profile.tsx | 14 +++++++++++++-
src/app/hooks/useUserProfile.ts | 12 +++++++++++-
2 files changed, 24 insertions(+), 2 deletions(-)
diff --git a/src/app/features/settings/account/Profile.tsx b/src/app/features/settings/account/Profile.tsx
index 45c66effb..935e076f6 100644
--- a/src/app/features/settings/account/Profile.tsx
+++ b/src/app/features/settings/account/Profile.tsx
@@ -29,7 +29,7 @@ import { useSetAtom } from 'jotai';
import { SequenceCard } from '$components/sequence-card';
import { SettingTile } from '$components/setting-tile';
import { useMatrixClient } from '$hooks/useMatrixClient';
-import { UserProfile, useUserProfile } from '$hooks/useUserProfile';
+import { UserProfile, useUserProfile, MSC4440Bio } from '$hooks/useUserProfile';
import { getMxIdLocalPart, mxcUrlToHttp } from '$utils/matrix';
import { UserAvatar } from '$components/user-avatar';
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
@@ -52,6 +52,7 @@ import { BioEditor } from './BioEditor';
import { NameColorEditor } from './NameColorEditor';
import { StatusEditor } from './StatusEditor';
import { AnimalCosmetics } from './AnimalCosmetics';
+import { toPlainText } from '$components/editor';
type PronounSet = {
summary: string;
@@ -576,6 +577,7 @@ function ProfileExtended({ profile, userId }: Readonly) {
>
) {
onSave={(htmlBio) => {
handleSaveField('moe.sable.app.bio', htmlBio);
+ // MSC4440
+ handleSaveField('gay.fomx.biography', {
+ body: htmlBio
+ .replaceAll('
', '\n')
+ .replaceAll('', '\n- ')
+ .replaceAll(/<[^>]*>/g, ''),
+ format: 'org.matrix.custom.html',
+ formatted_body: htmlBio,
+ } satisfies MSC4440Bio);
+
const cleanedHtml = htmlBio.replaceAll('
', '');
handleSaveField('chat.commet.profile_bio', {
format: 'org.matrix.custom.html',
diff --git a/src/app/hooks/useUserProfile.ts b/src/app/hooks/useUserProfile.ts
index 8de5da050..21f87b813 100644
--- a/src/app/hooks/useUserProfile.ts
+++ b/src/app/hooks/useUserProfile.ts
@@ -11,6 +11,12 @@ import { useMatrixClient } from './useMatrixClient';
const inFlightProfiles = new Map>();
+export type MSC4440Bio = {
+ body: string;
+ format: string;
+ formatted_body: string;
+};
+
export type UserProfile = {
avatarUrl?: string;
displayName?: string;
@@ -35,6 +41,7 @@ const normalizeInfo = (info: any): UserProfile => {
'm.tz',
'moe.sable.app.bio',
'chat.commet.profile_bio',
+ 'gay.fomx.biography',
'chat.commet.profile_banner',
'chat.commet.profile_status',
'moe.sable.app.name_color',
@@ -54,7 +61,10 @@ const normalizeInfo = (info: any): UserProfile => {
displayName: info.displayname,
pronouns: info['io.fsky.nyx.pronouns'],
timezone: info['us.cloke.msc4175.tz'] || info['m.tz'],
- bio: info['moe.sable.app.bio'] || info['chat.commet.profile_bio'],
+ bio:
+ (info['gay.fomx.biography'] satisfies MSC4440Bio).formatted_body ||
+ info['moe.sable.app.bio'] ||
+ info['chat.commet.profile_bio'],
status: info['chat.commet.profile_status'],
bannerUrl: info['chat.commet.profile_banner'],
nameColor: info['moe.sable.app.name_color'],
From 9c61f4c62e6988cb8a60cd075ed6e0563b8ab67c Mon Sep 17 00:00:00 2001
From: Rye
Date: Fri, 27 Mar 2026 16:13:26 +0100
Subject: [PATCH 22/58] fix(message forwarding): remove relation from the
forwarded message, to avoid synapse weirdness
---
.changeset/fix_forwarding_relations.md | 5 +++++
src/app/components/message/modals/MessageForward.tsx | 8 ++------
2 files changed, 7 insertions(+), 6 deletions(-)
create mode 100644 .changeset/fix_forwarding_relations.md
diff --git a/.changeset/fix_forwarding_relations.md b/.changeset/fix_forwarding_relations.md
new file mode 100644
index 000000000..7e485bba0
--- /dev/null
+++ b/.changeset/fix_forwarding_relations.md
@@ -0,0 +1,5 @@
+---
+default: patch
+---
+
+fix forwarding issue for users on synapse homeservers, by removing the relation
diff --git a/src/app/components/message/modals/MessageForward.tsx b/src/app/components/message/modals/MessageForward.tsx
index 219e41197..da428fb65 100644
--- a/src/app/components/message/modals/MessageForward.tsx
+++ b/src/app/components/message/modals/MessageForward.tsx
@@ -224,6 +224,8 @@ export function MessageForwardInternal({
}
: {};
const baseContent = { ...mEvent.getContent() };
+ delete baseContent['m.relates_to']; // remove relations from the forwarded message
+ delete baseContent['m.mentions']; // remove mentions from forwarded message
delete baseContent['com.beeper.per_message_profile']; // remove per-message profile as that could confuse clients in the target room
let content;
// handle privacy stuff
@@ -232,8 +234,6 @@ export function MessageForwardInternal({
// we can still include the original message content in the body of the message, so we'll just use a fallback text/plain content with the original message body
content = {
...baseContent,
- 'm.relates_to': null, // remove any relations to avoid confusion in the target room
- 'm.mentions': null, // remove mentions to avoid leaking information about users in the original room
...forwardedTextContent,
'moe.sable.message.forward': {
v: 1,
@@ -246,10 +246,6 @@ export function MessageForwardInternal({
content = {
...baseContent,
...forwardedTextContent,
- 'm.relates_to': {
- rel_type: 'm.reference',
- event_id: eventId,
- },
'moe.sable.message.forward': {
v: 1,
is_forwarded: true,
From 0c62e75576bd9eeece91e4bcccad9f3d625f2de3 Mon Sep 17 00:00:00 2001
From: Rye
Date: Fri, 27 Mar 2026 16:59:29 +0100
Subject: [PATCH 23/58] it now uses extensible events to format the bio, as per
msc4440
---
.changeset/feat-msc4440-bio-compat.md | 5 +++++
.../features/settings/account/BioEditor.tsx | 4 ++--
src/app/features/settings/account/Profile.tsx | 19 +++++++++++--------
src/app/hooks/useUserProfile.ts | 7 +++----
src/types/matrix/common.ts | 5 +++++
5 files changed, 26 insertions(+), 14 deletions(-)
create mode 100644 .changeset/feat-msc4440-bio-compat.md
diff --git a/.changeset/feat-msc4440-bio-compat.md b/.changeset/feat-msc4440-bio-compat.md
new file mode 100644
index 000000000..0fc8f9763
--- /dev/null
+++ b/.changeset/feat-msc4440-bio-compat.md
@@ -0,0 +1,5 @@
+---
+default: note
+---
+
+new/changed bios will now also be saved in the format MSC4440 expects
diff --git a/src/app/features/settings/account/BioEditor.tsx b/src/app/features/settings/account/BioEditor.tsx
index 49b47d7b9..b5670a22c 100644
--- a/src/app/features/settings/account/BioEditor.tsx
+++ b/src/app/features/settings/account/BioEditor.tsx
@@ -44,7 +44,7 @@ type BioEditorProps = {
value?: string | any;
isSaving?: boolean;
imagePackRooms?: any[];
- onSave: (htmlContent: string) => void;
+ onSave: (htmlContent: string, plainText: string) => void;
};
const BIO_LIMIT = 1024;
@@ -81,7 +81,7 @@ export function BioEditor({ value, isSaving, imagePackRooms, onSave }: BioEditor
})
);
- onSave(customHtml || plainText);
+ onSave(customHtml || plainText, plainText);
setHasChanged(false);
}, [editor, isMarkdown, onSave]);
diff --git a/src/app/features/settings/account/Profile.tsx b/src/app/features/settings/account/Profile.tsx
index 935e076f6..5702c0293 100644
--- a/src/app/features/settings/account/Profile.tsx
+++ b/src/app/features/settings/account/Profile.tsx
@@ -46,13 +46,13 @@ import { useCapabilities } from '$hooks/useCapabilities';
import { profilesCacheAtom } from '$state/userRoomProfile';
import { SequenceCardStyle } from '$features/settings/styles.css';
import { useUserPresence } from '$hooks/useUserPresence';
+import { MSC1767Text } from '$types/matrix/common';
import { TimezoneEditor } from './TimezoneEditor';
import { PronounEditor } from './PronounEditor';
import { BioEditor } from './BioEditor';
import { NameColorEditor } from './NameColorEditor';
import { StatusEditor } from './StatusEditor';
import { AnimalCosmetics } from './AnimalCosmetics';
-import { toPlainText } from '$components/editor';
type PronounSet = {
summary: string;
@@ -582,17 +582,20 @@ function ProfileExtended({ profile, userId }: Readonly) {
profile.extended?.['chat.commet.profile_bio'] ||
profile.bio
}
- onSave={(htmlBio) => {
+ onSave={(htmlBio, plainTextBio) => {
handleSaveField('moe.sable.app.bio', htmlBio);
// MSC4440
handleSaveField('gay.fomx.biography', {
- body: htmlBio
- .replaceAll('
', '\n')
- .replaceAll('', '\n- ')
- .replaceAll(/<[^>]*>/g, ''),
- format: 'org.matrix.custom.html',
- formatted_body: htmlBio,
+ 'm.text': [
+ {
+ body: htmlBio,
+ mimetype: 'text/html',
+ } satisfies MSC1767Text,
+ {
+ body: plainTextBio,
+ } satisfies MSC1767Text,
+ ],
} satisfies MSC4440Bio);
const cleanedHtml = htmlBio.replaceAll('
', '');
diff --git a/src/app/hooks/useUserProfile.ts b/src/app/hooks/useUserProfile.ts
index 21f87b813..d1de6e890 100644
--- a/src/app/hooks/useUserProfile.ts
+++ b/src/app/hooks/useUserProfile.ts
@@ -7,14 +7,13 @@ import colorMXID from '$utils/colorMXID';
import { profilesCacheAtom } from '$state/userRoomProfile';
import { useSetting } from '$state/hooks/settings';
import { settingsAtom } from '$state/settings';
+import { MSC1767Text } from '$types/matrix/common';
import { useMatrixClient } from './useMatrixClient';
const inFlightProfiles = new Map>();
export type MSC4440Bio = {
- body: string;
- format: string;
- formatted_body: string;
+ 'm.text': Array;
};
export type UserProfile = {
@@ -62,7 +61,7 @@ const normalizeInfo = (info: any): UserProfile => {
pronouns: info['io.fsky.nyx.pronouns'],
timezone: info['us.cloke.msc4175.tz'] || info['m.tz'],
bio:
- (info['gay.fomx.biography'] satisfies MSC4440Bio).formatted_body ||
+ (info['gay.fomx.biography'] satisfies MSC4440Bio)['m.text'][0].body ||
info['moe.sable.app.bio'] ||
info['chat.commet.profile_bio'],
status: info['chat.commet.profile_status'],
diff --git a/src/types/matrix/common.ts b/src/types/matrix/common.ts
index 8cc96d7d6..e91993578 100644
--- a/src/types/matrix/common.ts
+++ b/src/types/matrix/common.ts
@@ -14,6 +14,11 @@ export type IImageInfo = {
[MATRIX_BLUR_HASH_PROPERTY_NAME]?: string;
};
+export type MSC1767Text = {
+ body: string;
+ mimetype?: string;
+};
+
export type IVideoInfo = {
w?: number;
h?: number;
From 34924ec8f3d82c88367b29e2fde9685e11029d31 Mon Sep 17 00:00:00 2001
From: Vesper
Date: Fri, 27 Mar 2026 18:50:39 +0000
Subject: [PATCH 24/58] Add /html command
---
.../adds_a_html_command_to_send_html_messages.md | 5 +++++
src/app/hooks/useCommands.ts | 13 +++++++++++++
2 files changed, 18 insertions(+)
create mode 100644 .changeset/adds_a_html_command_to_send_html_messages.md
diff --git a/.changeset/adds_a_html_command_to_send_html_messages.md b/.changeset/adds_a_html_command_to_send_html_messages.md
new file mode 100644
index 000000000..fe116c3b6
--- /dev/null
+++ b/.changeset/adds_a_html_command_to_send_html_messages.md
@@ -0,0 +1,5 @@
+---
+default: minor
+---
+
+# Adds a `/html` command to send HTML messages
diff --git a/src/app/hooks/useCommands.ts b/src/app/hooks/useCommands.ts
index f9a23472d..1cf7c2a26 100644
--- a/src/app/hooks/useCommands.ts
+++ b/src/app/hooks/useCommands.ts
@@ -252,6 +252,7 @@ export enum Command {
SetExt = 'setext',
DelExt = 'delext',
DiscardSession = 'discardsession',
+ Html = 'html',
// Cute Events
Hug = 'hug',
Cuddle = 'cuddle',
@@ -1323,6 +1324,18 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
}
},
},
+ [Command.Html]: {
+ name: Command.Html,
+ description: 'Send a message with HTML content',
+ exe: async (payload) => {
+ await mx.sendMessage(room.roomId, {
+ msgtype: MsgType.Text,
+ body: payload,
+ format: 'org.matrix.custom.html',
+ formatted_body: payload,
+ });
+ },
+ },
// Sharing E2EE History of a room with a user
[Command.ShareE2EEHistory]: {
name: Command.ShareE2EEHistory,
From 05de0d6b34060e8df5daf10b641cb8a9e6b9b08a Mon Sep 17 00:00:00 2001
From: Vesper
Date: Fri, 27 Mar 2026 20:17:51 +0000
Subject: [PATCH 25/58] Add example
---
src/app/hooks/useCommands.ts | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/src/app/hooks/useCommands.ts b/src/app/hooks/useCommands.ts
index 1cf7c2a26..a1c90f173 100644
--- a/src/app/hooks/useCommands.ts
+++ b/src/app/hooks/useCommands.ts
@@ -1326,7 +1326,8 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
},
[Command.Html]: {
name: Command.Html,
- description: 'Send a message with HTML content',
+ description:
+ 'Send a message with HTML content. Example: /html Red',
exe: async (payload) => {
await mx.sendMessage(room.roomId, {
msgtype: MsgType.Text,
From 5f62b92ffe1cf28c1133a65fed6e5cd52bfe1a8a Mon Sep 17 00:00:00 2001
From: Vesper
Date: Fri, 27 Mar 2026 21:30:06 +0000
Subject: [PATCH 26/58] Try to strip HTML from the plain text body field
---
src/app/hooks/useCommands.ts | 9 ++++++++-
1 file changed, 8 insertions(+), 1 deletion(-)
diff --git a/src/app/hooks/useCommands.ts b/src/app/hooks/useCommands.ts
index a1c90f173..edd901d98 100644
--- a/src/app/hooks/useCommands.ts
+++ b/src/app/hooks/useCommands.ts
@@ -1331,7 +1331,14 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
exe: async (payload) => {
await mx.sendMessage(room.roomId, {
msgtype: MsgType.Text,
- body: payload,
+ body: payload
+ .replaceAll('
', '\n')
+ .replaceAll('', '\n- ')
+ .replaceAll(
+ /(.*?))"(.*?)>(?(.*?))<\/a>/g,
+ '[$]($)'
+ )
+ .replaceAll(/<[^>]*>/g, ''),
format: 'org.matrix.custom.html',
formatted_body: payload,
});
From 69bae5cb6645fed30a615dcac4098a62a63a516c Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Fri, 27 Mar 2026 21:49:32 +0000
Subject: [PATCH 27/58] chore: bump picomatch from 2.3.1 to 2.3.2
Bumps [picomatch](https://github.com/micromatch/picomatch) from 2.3.1 to 2.3.2.
- [Release notes](https://github.com/micromatch/picomatch/releases)
- [Changelog](https://github.com/micromatch/picomatch/blob/master/CHANGELOG.md)
- [Commits](https://github.com/micromatch/picomatch/compare/2.3.1...2.3.2)
---
updated-dependencies:
- dependency-name: picomatch
dependency-version: 2.3.2
dependency-type: indirect
...
Signed-off-by: dependabot[bot]
---
pnpm-lock.yaml | 174 +++++++++++++++++++++++++------------------------
1 file changed, 88 insertions(+), 86 deletions(-)
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c0a9719bc..ad8544f09 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -59,7 +59,7 @@ importers:
version: 0.5.7(@vanilla-extract/css@1.18.0)
'@vanilla-extract/vite-plugin':
specifier: ^5.1.4
- version: 5.1.4(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2))(yaml@2.8.2)
+ version: 5.1.4(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2))(yaml@2.8.2)
await-to-js:
specifier: ^3.0.0
version: 3.0.0
@@ -207,7 +207,7 @@ importers:
devDependencies:
'@cloudflare/vite-plugin':
specifier: ^1.26.0
- version: 1.27.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2))(workerd@1.20260310.1)(wrangler@4.72.0)
+ version: 1.27.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2))(workerd@1.20260310.1)(wrangler@4.72.0)
'@esbuild-plugins/node-globals-polyfill':
specifier: ^0.2.3
version: 0.2.3(esbuild@0.27.3)
@@ -270,7 +270,7 @@ importers:
version: 0.7.39
'@vitejs/plugin-react':
specifier: ^5.1.4
- version: 5.1.4(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2))
+ version: 5.1.4(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2))
'@vitest/coverage-v8':
specifier: ^4.1.0
version: 4.1.0(vitest@4.1.0)
@@ -312,25 +312,25 @@ importers:
version: 5.9.3
vite:
specifier: ^7.3.1
- version: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2)
+ version: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)
vite-plugin-compression2:
specifier: 2.5.0
version: 2.5.0(rollup@4.59.0)
vite-plugin-pwa:
specifier: ^1.2.0
- version: 1.2.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2))(workbox-build@7.4.0(@types/babel__core@7.20.5))(workbox-window@7.4.0)
+ version: 1.2.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2))(workbox-build@7.4.0(@types/babel__core@7.20.5))(workbox-window@7.4.0)
vite-plugin-static-copy:
specifier: ^3.2.0
- version: 3.2.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2))
+ version: 3.2.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2))
vite-plugin-svgr:
specifier: 4.5.0
- version: 4.5.0(rollup@4.59.0)(typescript@5.9.3)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2))
+ version: 4.5.0(rollup@4.59.0)(typescript@5.9.3)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2))
vite-plugin-top-level-await:
specifier: ^1.6.0
- version: 1.6.0(@swc/helpers@0.5.19)(rollup@4.59.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2))
+ version: 1.6.0(@swc/helpers@0.5.19)(rollup@4.59.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2))
vitest:
specifier: ^4.1.0
- version: 4.1.0(@types/node@24.10.13)(@vitest/ui@4.1.0)(jsdom@29.0.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2))
+ version: 4.1.0(@types/node@24.10.13)(@vitest/ui@4.1.0)(jsdom@29.0.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2))
wrangler:
specifier: ^4.70.0
version: 4.72.0
@@ -402,8 +402,8 @@ packages:
peerDependencies:
'@babel/core': ^7.0.0
- '@babel/helper-define-polyfill-provider@0.6.7':
- resolution: {integrity: sha512-6Fqi8MtQ/PweQ9xvux65emkLQ83uB+qAVtfHkC9UodyHMIZdxNI01HjLCLUtybElp2KY2XNE0nOgyP1E1vXw9w==}
+ '@babel/helper-define-polyfill-provider@0.6.8':
+ resolution: {integrity: sha512-47UwBLPpQi1NoWzLuHNjRoHlYXMwIJoBf7MFou6viC/sIHWYygpvr0B6IAyh5sBdA2nr2LPIRww8lfaUVQINBA==}
peerDependencies:
'@babel/core': ^7.4.0 || ^8.0.0-0 <8.0.0
@@ -852,8 +852,8 @@ packages:
peerDependencies:
'@babel/core': ^7.0.0
- '@babel/preset-env@7.29.0':
- resolution: {integrity: sha512-fNEdfc0yi16lt6IZo2Qxk3knHVdfMYX33czNb4v8yWhemoBhibCpQK/uYHtSKIiO+p/zd3+8fYVXhQdOVV608w==}
+ '@babel/preset-env@7.29.2':
+ resolution: {integrity: sha512-DYD23veRYGvBFhcTY1iUvJnDNpuqNd/BzBwCvzOTKUnJjKg5kpUBh3/u9585Agdkgj+QuygG7jLfOPWMa2KVNw==}
engines: {node: '>=6.9.0'}
peerDependencies:
'@babel/core': ^7.0.0-0
@@ -867,6 +867,10 @@ packages:
resolution: {integrity: sha512-05WQkdpL9COIMz4LjTxGpPNCdlpyimKppYNoJ5Di5EUObifl8t4tuLuUBBZEpoLYOmfvIWrsp9fCl0HoPRVTdA==}
engines: {node: '>=6.9.0'}
+ '@babel/runtime@7.29.2':
+ resolution: {integrity: sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==}
+ engines: {node: '>=6.9.0'}
+
'@babel/template@7.28.6':
resolution: {integrity: sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==}
engines: {node: '>=6.9.0'}
@@ -3203,18 +3207,18 @@ packages:
resolution: {integrity: sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==}
engines: {node: '>= 0.4'}
- babel-plugin-polyfill-corejs2@0.4.16:
- resolution: {integrity: sha512-xaVwwSfebXf0ooE11BJovZYKhFjIvQo7TsyVpETuIeH2JHv0k/T6Y5j22pPTvqYqmpkxdlPAJlyJ0tfOJAoMxw==}
+ babel-plugin-polyfill-corejs2@0.4.17:
+ resolution: {integrity: sha512-aTyf30K/rqAsNwN76zYrdtx8obu0E4KoUME29B1xj+B3WxgvWkp943vYQ+z8Mv3lw9xHXMHpvSPOBxzAkIa94w==}
peerDependencies:
'@babel/core': ^7.4.0 || ^8.0.0-0 <8.0.0
- babel-plugin-polyfill-corejs3@0.14.1:
- resolution: {integrity: sha512-ENp89vM9Pw4kv/koBb5N2f9bDZsR0hpf3BdPMOg/pkS3pwO4dzNnQZVXtBbeyAadgm865DmQG2jMMLqmZXvuCw==}
+ babel-plugin-polyfill-corejs3@0.14.2:
+ resolution: {integrity: sha512-coWpDLJ410R781Npmn/SIBZEsAetR4xVi0SxLMXPaMO4lSf1MwnkGYMtkFxew0Dn8B3/CpbpYxN0JCgg8mn67g==}
peerDependencies:
'@babel/core': ^7.4.0 || ^8.0.0-0 <8.0.0
- babel-plugin-polyfill-regenerator@0.6.7:
- resolution: {integrity: sha512-OTYbUlSwXhNgr4g6efMZgsO8//jA61P7ZbRX3iTT53VON8l+WQS8IAUEVo4a4cWknrg2W8Cj4gQhRYNCJ8GkAA==}
+ babel-plugin-polyfill-regenerator@0.6.8:
+ resolution: {integrity: sha512-M762rNHfSF1EV3SLtnCJXFoQbbIIz0OyRwnCmV0KPC7qosSfCO0QLTSuJX3ayAebubhE6oYBAYPrBA5ljowaZg==}
peerDependencies:
'@babel/core': ^7.4.0 || ^8.0.0-0 <8.0.0
@@ -3322,10 +3326,6 @@ packages:
classnames@2.5.1:
resolution: {integrity: sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==}
- cliui@8.0.1:
- resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==}
- engines: {node: '>=12'}
-
cloudflared@0.7.1:
resolution: {integrity: sha512-jJn1Gu9Tf4qnIu8tfiHZ25Hs8rNcRYSVf8zAd97wvYdOCzftm1CTs1S/RPhijjGi8gUT1p9yzfDi9zYlU/0RwA==}
hasBin: true
@@ -3372,8 +3372,8 @@ packages:
resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==}
engines: {node: '>=18'}
- core-js-compat@3.48.0:
- resolution: {integrity: sha512-OM4cAF3D6VtH/WkLtWvyNC56EZVXsZdU3iqaMG2B4WvYrlqU831pc4UtG5yp0sE9z8Y02wVN7PjW5Zf9Gt0f1Q==}
+ core-js-compat@3.49.0:
+ resolution: {integrity: sha512-VQXt1jr9cBz03b331DFDCCP90b3fanciLkgiOoy8SBHy06gNf+vQ1A3WFLqG7I8TipYIKeYK9wxd0tUrvHcOZA==}
cosmiconfig@8.3.6:
resolution: {integrity: sha512-kcZ6+W5QzcJ3P1Mt+83OUv/oHFqZHIx8DuxG6eZ5RGMERoLqp4BuGjhHLYGK+Kf5XVkQvqBSmAy/nGWN3qDgEA==}
@@ -4731,6 +4731,10 @@ packages:
resolution: {integrity: sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==}
engines: {node: '>=8.6'}
+ picomatch@2.3.2:
+ resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==}
+ engines: {node: '>=8.6'}
+
picomatch@4.0.3:
resolution: {integrity: sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==}
engines: {node: '>=12'}
@@ -4993,8 +4997,8 @@ packages:
engines: {node: '>=10'}
hasBin: true
- serialize-javascript@7.0.4:
- resolution: {integrity: sha512-DuGdB+Po43Q5Jxwpzt1lhyFSYKryqoNjQSA9M92tyw0lyHIOur+XCalOUe0KTJpyqzT8+fQ5A0Jf7vCx/NKmIg==}
+ serialize-javascript@7.0.5:
+ resolution: {integrity: sha512-F4LcB0UqUl1zErq+1nYEEzSHJnIwb3AF2XWB94b+afhrekOUijwooAYqFyRbjYkm2PAKBabx6oYv/xDxNi8IBw==}
engines: {node: '>=20.0.0'}
set-function-length@1.2.2:
@@ -5207,8 +5211,8 @@ packages:
resolution: {integrity: sha512-G13vtMYPT/J8A4X2SjdtBTphZlrp1gKv6hZiOjw14RCWg6GbHuQBGtjlx75xLbYV/wEc0D7G5K4rxKP/cXk8Bw==}
engines: {node: '>=10'}
- terser@5.46.0:
- resolution: {integrity: sha512-jTwoImyr/QbOWFFso3YoU3ik0jBBDJ6JTOQiy/J2YxVJdZCc+5u7skhNwiOR3FQIygFqVUPHl7qbbxtjW2K3Qg==}
+ terser@5.46.1:
+ resolution: {integrity: sha512-vzCjQO/rgUuK9sf8VJZvjqiqiHFaZLnOiimmUuOKODxWL8mm/xua7viT7aqX7dgPY60otQjUotzFMmCB4VdmqQ==}
engines: {node: '>=10'}
hasBin: true
@@ -5809,7 +5813,7 @@ snapshots:
regexpu-core: 6.4.0
semver: 6.3.1
- '@babel/helper-define-polyfill-provider@0.6.7(@babel/core@7.29.0)':
+ '@babel/helper-define-polyfill-provider@0.6.8(@babel/core@7.29.0)':
dependencies:
'@babel/core': 7.29.0
'@babel/helper-compilation-targets': 7.28.6
@@ -6302,7 +6306,7 @@ snapshots:
'@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/core@7.29.0)
'@babel/helper-plugin-utils': 7.28.6
- '@babel/preset-env@7.29.0(@babel/core@7.29.0)':
+ '@babel/preset-env@7.29.2(@babel/core@7.29.0)':
dependencies:
'@babel/compat-data': 7.29.0
'@babel/core': 7.29.0
@@ -6370,10 +6374,10 @@ snapshots:
'@babel/plugin-transform-unicode-regex': 7.27.1(@babel/core@7.29.0)
'@babel/plugin-transform-unicode-sets-regex': 7.28.6(@babel/core@7.29.0)
'@babel/preset-modules': 0.1.6-no-external-plugins(@babel/core@7.29.0)
- babel-plugin-polyfill-corejs2: 0.4.16(@babel/core@7.29.0)
- babel-plugin-polyfill-corejs3: 0.14.1(@babel/core@7.29.0)
- babel-plugin-polyfill-regenerator: 0.6.7(@babel/core@7.29.0)
- core-js-compat: 3.48.0
+ babel-plugin-polyfill-corejs2: 0.4.17(@babel/core@7.29.0)
+ babel-plugin-polyfill-corejs3: 0.14.2(@babel/core@7.29.0)
+ babel-plugin-polyfill-regenerator: 0.6.8(@babel/core@7.29.0)
+ core-js-compat: 3.49.0
semver: 6.3.1
transitivePeerDependencies:
- supports-color
@@ -6387,6 +6391,8 @@ snapshots:
'@babel/runtime@7.28.6': {}
+ '@babel/runtime@7.29.2': {}
+
'@babel/template@7.28.6':
dependencies:
'@babel/code-frame': 7.29.0
@@ -6424,12 +6430,12 @@ snapshots:
optionalDependencies:
workerd: 1.20260310.1
- '@cloudflare/vite-plugin@1.27.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2))(workerd@1.20260310.1)(wrangler@4.72.0)':
+ '@cloudflare/vite-plugin@1.27.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2))(workerd@1.20260310.1)(wrangler@4.72.0)':
dependencies:
'@cloudflare/unenv-preset': 2.15.0(unenv@2.0.0-rc.24)(workerd@1.20260310.1)
miniflare: 4.20260310.0
unenv: 2.0.0-rc.24
- vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2)
+ vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)
wrangler: 4.72.0
ws: 8.18.0
transitivePeerDependencies:
@@ -7990,9 +7996,9 @@ snapshots:
'@rollup/plugin-terser@0.4.4(rollup@4.59.0)':
dependencies:
- serialize-javascript: 7.0.4
+ serialize-javascript: 7.0.5
smob: 1.6.1
- terser: 5.46.0
+ terser: 5.46.1
optionalDependencies:
rollup: 4.59.0
@@ -8010,7 +8016,7 @@ snapshots:
dependencies:
'@types/estree': 0.0.39
estree-walker: 1.0.1
- picomatch: 2.3.1
+ picomatch: 2.3.2
rollup: 4.59.0
'@rollup/pluginutils@5.3.0(rollup@4.59.0)':
@@ -8389,7 +8395,7 @@ snapshots:
'@testing-library/dom@10.4.1':
dependencies:
'@babel/code-frame': 7.29.0
- '@babel/runtime': 7.28.6
+ '@babel/runtime': 7.29.2
'@types/aria-query': 5.0.4
aria-query: 5.3.0
dom-accessibility-api: 0.5.16
@@ -8665,12 +8671,12 @@ snapshots:
transitivePeerDependencies:
- supports-color
- '@vanilla-extract/compiler@0.3.4(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2)':
+ '@vanilla-extract/compiler@0.3.4(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)':
dependencies:
'@vanilla-extract/css': 1.18.0
'@vanilla-extract/integration': 8.0.7
- vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2)
- vite-node: 3.2.4(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2)
+ vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)
+ vite-node: 3.2.4(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)
transitivePeerDependencies:
- '@types/node'
- babel-plugin-macros
@@ -8725,11 +8731,11 @@ snapshots:
dependencies:
'@vanilla-extract/css': 1.18.0
- '@vanilla-extract/vite-plugin@5.1.4(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2))(yaml@2.8.2)':
+ '@vanilla-extract/vite-plugin@5.1.4(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2))(yaml@2.8.2)':
dependencies:
- '@vanilla-extract/compiler': 0.3.4(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2)
+ '@vanilla-extract/compiler': 0.3.4(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)
'@vanilla-extract/integration': 8.0.7
- vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2)
+ vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)
transitivePeerDependencies:
- '@types/node'
- babel-plugin-macros
@@ -8745,7 +8751,7 @@ snapshots:
- tsx
- yaml
- '@vitejs/plugin-react@5.1.4(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2))':
+ '@vitejs/plugin-react@5.1.4(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2))':
dependencies:
'@babel/core': 7.29.0
'@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.29.0)
@@ -8753,7 +8759,7 @@ snapshots:
'@rolldown/pluginutils': 1.0.0-rc.3
'@types/babel__core': 7.20.5
react-refresh: 0.18.0
- vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2)
+ vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)
transitivePeerDependencies:
- supports-color
@@ -8769,7 +8775,7 @@ snapshots:
obug: 2.1.1
std-env: 4.0.0
tinyrainbow: 3.1.0
- vitest: 4.1.0(@types/node@24.10.13)(@vitest/ui@4.1.0)(jsdom@29.0.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2))
+ vitest: 4.1.0(@types/node@24.10.13)(@vitest/ui@4.1.0)(jsdom@29.0.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2))
'@vitest/expect@4.1.0':
dependencies:
@@ -8780,13 +8786,13 @@ snapshots:
chai: 6.2.2
tinyrainbow: 3.1.0
- '@vitest/mocker@4.1.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2))':
+ '@vitest/mocker@4.1.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2))':
dependencies:
'@vitest/spy': 4.1.0
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
- vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2)
+ vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)
'@vitest/pretty-format@4.1.0':
dependencies:
@@ -8815,7 +8821,7 @@ snapshots:
sirv: 3.0.2
tinyglobby: 0.2.15
tinyrainbow: 3.1.0
- vitest: 4.1.0(@types/node@24.10.13)(@vitest/ui@4.1.0)(jsdom@29.0.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2))
+ vitest: 4.1.0(@types/node@24.10.13)(@vitest/ui@4.1.0)(jsdom@29.0.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2))
'@vitest/utils@4.1.0':
dependencies:
@@ -8965,27 +8971,27 @@ snapshots:
axobject-query@4.1.0: {}
- babel-plugin-polyfill-corejs2@0.4.16(@babel/core@7.29.0):
+ babel-plugin-polyfill-corejs2@0.4.17(@babel/core@7.29.0):
dependencies:
'@babel/compat-data': 7.29.0
'@babel/core': 7.29.0
- '@babel/helper-define-polyfill-provider': 0.6.7(@babel/core@7.29.0)
+ '@babel/helper-define-polyfill-provider': 0.6.8(@babel/core@7.29.0)
semver: 6.3.1
transitivePeerDependencies:
- supports-color
- babel-plugin-polyfill-corejs3@0.14.1(@babel/core@7.29.0):
+ babel-plugin-polyfill-corejs3@0.14.2(@babel/core@7.29.0):
dependencies:
'@babel/core': 7.29.0
- '@babel/helper-define-polyfill-provider': 0.6.7(@babel/core@7.29.0)
- core-js-compat: 3.48.0
+ '@babel/helper-define-polyfill-provider': 0.6.8(@babel/core@7.29.0)
+ core-js-compat: 3.49.0
transitivePeerDependencies:
- supports-color
- babel-plugin-polyfill-regenerator@0.6.7(@babel/core@7.29.0):
+ babel-plugin-polyfill-regenerator@0.6.8(@babel/core@7.29.0):
dependencies:
'@babel/core': 7.29.0
- '@babel/helper-define-polyfill-provider': 0.6.7(@babel/core@7.29.0)
+ '@babel/helper-define-polyfill-provider': 0.6.8(@babel/core@7.29.0)
transitivePeerDependencies:
- supports-color
@@ -9088,12 +9094,6 @@ snapshots:
classnames@2.5.1: {}
- cliui@8.0.1:
- dependencies:
- string-width: 4.2.3
- strip-ansi: 6.0.1
- wrap-ansi: 7.0.0
-
cloudflared@0.7.1: {}
clsx@2.1.1: {}
@@ -9122,7 +9122,7 @@ snapshots:
cookie@1.1.1: {}
- core-js-compat@3.48.0:
+ core-js-compat@3.49.0:
dependencies:
browserslist: 4.28.1
@@ -10676,6 +10676,8 @@ snapshots:
picomatch@2.3.1: {}
+ picomatch@2.3.2: {}
+
picomatch@4.0.3: {}
pkg-types@1.3.1:
@@ -11004,7 +11006,7 @@ snapshots:
semver@7.7.4: {}
- serialize-javascript@7.0.4: {}
+ serialize-javascript@7.0.5: {}
set-function-length@1.2.2:
dependencies:
@@ -11276,7 +11278,7 @@ snapshots:
type-fest: 0.16.0
unique-string: 2.0.0
- terser@5.46.0:
+ terser@5.46.1:
dependencies:
'@jridgewell/source-map': 0.3.11
acorn: 8.16.0
@@ -11479,13 +11481,13 @@ snapshots:
react: 18.3.1
react-dom: 18.3.1(react@18.3.1)
- vite-node@3.2.4(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2):
+ vite-node@3.2.4(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2):
dependencies:
cac: 6.7.14
debug: 4.4.3
es-module-lexer: 1.7.0
pathe: 2.0.3
- vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2)
+ vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)
transitivePeerDependencies:
- '@types/node'
- jiti
@@ -11507,48 +11509,48 @@ snapshots:
transitivePeerDependencies:
- rollup
- vite-plugin-pwa@1.2.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2))(workbox-build@7.4.0(@types/babel__core@7.20.5))(workbox-window@7.4.0):
+ vite-plugin-pwa@1.2.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2))(workbox-build@7.4.0(@types/babel__core@7.20.5))(workbox-window@7.4.0):
dependencies:
debug: 4.4.3
pretty-bytes: 6.1.1
tinyglobby: 0.2.15
- vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2)
+ vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)
workbox-build: 7.4.0(@types/babel__core@7.20.5)
workbox-window: 7.4.0
transitivePeerDependencies:
- supports-color
- vite-plugin-static-copy@3.2.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2)):
+ vite-plugin-static-copy@3.2.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)):
dependencies:
chokidar: 3.6.0
p-map: 7.0.4
picocolors: 1.1.1
tinyglobby: 0.2.15
- vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2)
+ vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)
- vite-plugin-svgr@4.5.0(rollup@4.59.0)(typescript@5.9.3)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2)):
+ vite-plugin-svgr@4.5.0(rollup@4.59.0)(typescript@5.9.3)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)):
dependencies:
'@rollup/pluginutils': 5.3.0(rollup@4.59.0)
'@svgr/core': 8.1.0(typescript@5.9.3)
'@svgr/plugin-jsx': 8.1.0(@svgr/core@8.1.0(typescript@5.9.3))
- vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2)
+ vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)
transitivePeerDependencies:
- rollup
- supports-color
- typescript
- vite-plugin-top-level-await@1.6.0(@swc/helpers@0.5.19)(rollup@4.59.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2)):
+ vite-plugin-top-level-await@1.6.0(@swc/helpers@0.5.19)(rollup@4.59.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)):
dependencies:
'@rollup/plugin-virtual': 3.0.2(rollup@4.59.0)
'@swc/core': 1.15.18(@swc/helpers@0.5.19)
'@swc/wasm': 1.15.18
uuid: 10.0.0
- vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2)
+ vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)
transitivePeerDependencies:
- '@swc/helpers'
- rollup
- vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2):
+ vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2):
dependencies:
esbuild: 0.27.3
fdir: 6.5.0(picomatch@4.0.3)
@@ -11560,13 +11562,13 @@ snapshots:
'@types/node': 24.10.13
fsevents: 2.3.3
jiti: 2.6.1
- terser: 5.46.0
+ terser: 5.46.1
yaml: 2.8.2
- vitest@4.1.0(@types/node@24.10.13)(@vitest/ui@4.1.0)(jsdom@29.0.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2)):
+ vitest@4.1.0(@types/node@24.10.13)(@vitest/ui@4.1.0)(jsdom@29.0.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)):
dependencies:
'@vitest/expect': 4.1.0
- '@vitest/mocker': 4.1.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2))
+ '@vitest/mocker': 4.1.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2))
'@vitest/pretty-format': 4.1.0
'@vitest/runner': 4.1.0
'@vitest/snapshot': 4.1.0
@@ -11583,7 +11585,7 @@ snapshots:
tinyexec: 1.0.4
tinyglobby: 0.2.15
tinyrainbow: 3.1.0
- vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.0)(yaml@2.8.2)
+ vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)
why-is-node-running: 2.3.0
optionalDependencies:
'@types/node': 24.10.13
@@ -11692,8 +11694,8 @@ snapshots:
dependencies:
'@apideck/better-ajv-errors': 0.3.6(ajv@8.18.0)
'@babel/core': 7.29.0
- '@babel/preset-env': 7.29.0(@babel/core@7.29.0)
- '@babel/runtime': 7.28.6
+ '@babel/preset-env': 7.29.2(@babel/core@7.29.0)
+ '@babel/runtime': 7.29.2
'@rollup/plugin-babel': 5.3.1(@babel/core@7.29.0)(@types/babel__core@7.20.5)(rollup@4.59.0)
'@rollup/plugin-node-resolve': 15.3.1(rollup@4.59.0)
'@rollup/plugin-replace': 2.4.2(rollup@4.59.0)
From f707acc713f0db7c19883533f1584d8d737f000e Mon Sep 17 00:00:00 2001
From: Evie Gauthier
Date: Fri, 27 Mar 2026 22:10:24 -0400
Subject: [PATCH 28/58] fix: scroll-to-bottom race and stale lTimelines after
pagination
RoomTimeline.tsx:
- Add liveTimelineLinked guard to the initial-scroll useLayoutEffect.
Without this, a render with stale data from the previous room (before
the room-change reset propagates) fires scrollToIndex at the wrong
index and marks hasInitialScrolledRef = true, blocking the correct scroll
when the right data arrives.
- Add pendingReadyRef to defer setIsReady(true) when the 80 ms timer fires
but processedEvents is empty (e.g. the onLifecycle reset cleared the
timeline within the window). A recovery useLayoutEffect watches for
processedEvents.length becoming non-empty and performs the final scroll +
setIsReady when the flag is set. Previously setIsReady(true) was called
unconditionally from the timer, revealing the room at position 0 when
events had not yet arrived.
- Reset pendingReadyRef on room change so dangling recovery state from a
previous room cannot fire in the new room context.
useTimelineSync.ts:
- After await paginateEventTimeline, re-read from timelineRef.current
instead of using the pre-await lTimelines capture. A sliding sync reset
(resetLiveTimeline) during pagination replaces lTimelines[0] with a new
EventTimeline object; the stale reference causes getLinkedTimelines to
traverse the wrong chain, making countAfter/countBefore comparisons wrong
and triggering incorrect pagination decisions.
- Add room-change useEffect that resets the timeline state to the new room's
initial linked timelines when room.roomId changes. Without this, the
component retains stale data from the previous room, keeping
liveTimelineLinked false until a TimelineReset event fires -- which may
never happen for revisited rooms where the sliding sync response does not
include initial:true.
---
src/app/features/room/RoomTimeline.tsx | 34 +++++++++++++++++++++--
src/app/hooks/timeline/useTimelineSync.ts | 30 ++++++++++++++++++--
2 files changed, 59 insertions(+), 5 deletions(-)
diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx
index d4aaebbd9..95e3f105a 100644
--- a/src/app/features/room/RoomTimeline.tsx
+++ b/src/app/features/room/RoomTimeline.tsx
@@ -210,6 +210,11 @@ export function RoomTimeline({
// Stored in a ref so eventsLength fluctuations (e.g. onLifecycle timeline reset
// firing within the window) cannot cancel it via useLayoutEffect cleanup.
const initialScrollTimerRef = useRef | undefined>(undefined);
+ // Set to true when the 80 ms timer fires but processedEvents is still empty
+ // (e.g. the onLifecycle reset cleared the timeline before events refilled it).
+ // A recovery useLayoutEffect watches for processedEvents becoming non-empty
+ // and performs the final scroll + setIsReady when this flag is set.
+ const pendingReadyRef = useRef(false);
const currentRoomIdRef = useRef(room.roomId);
const [isReady, setIsReady] = useState(false);
@@ -218,6 +223,7 @@ export function RoomTimeline({
hasInitialScrolledRef.current = false;
mountScrollWindowRef.current = Date.now() + 3000;
currentRoomIdRef.current = room.roomId;
+ pendingReadyRef.current = false;
setIsReady(false);
}
@@ -273,6 +279,12 @@ export function RoomTimeline({
!eventId &&
!hasInitialScrolledRef.current &&
timelineSync.eventsLength > 0 &&
+ // Guard: only scroll once the timeline reflects the current room's live
+ // timeline. Without this, a render with stale data from the previous room
+ // (before the room-change reset propagates) fires the scroll at the wrong
+ // position and marks hasInitialScrolledRef = true, preventing the correct
+ // scroll when the right data arrives.
+ timelineSync.liveTimelineLinked &&
vListRef.current
) {
vListRef.current.scrollToIndex(processedEventsRef.current.length - 1, { align: 'end' });
@@ -283,14 +295,20 @@ export function RoomTimeline({
initialScrollTimerRef.current = undefined;
if (processedEventsRef.current.length > 0) {
vListRef.current?.scrollToIndex(processedEventsRef.current.length - 1, { align: 'end' });
+ // Only mark ready once we've successfully scrolled. If processedEvents
+ // was empty when the timer fired (e.g. the onLifecycle reset cleared the
+ // timeline within the 80 ms window), defer setIsReady until the recovery
+ // effect below fires once events repopulate.
+ setIsReady(true);
+ } else {
+ pendingReadyRef.current = true;
}
- setIsReady(true);
}, 80);
hasInitialScrolledRef.current = true;
}
// No cleanup return — the timer must survive eventsLength fluctuations.
// It is cancelled on unmount by the dedicated effect below.
- }, [timelineSync.eventsLength, eventId, room.roomId]);
+ }, [timelineSync.eventsLength, timelineSync.liveTimelineLinked, eventId, room.roomId]);
// Cancel the initial-scroll timer on unmount (the useLayoutEffect above
// intentionally does not cancel it when deps change).
@@ -696,6 +714,18 @@ export function RoomTimeline({
processedEventsRef.current = processedEvents;
+ // Recovery: if the 80 ms initial-scroll timer fired while processedEvents was
+ // empty (timeline was mid-reset), scroll to bottom and reveal the timeline once
+ // events repopulate. Fires on every processedEvents.length change but is
+ // guarded by pendingReadyRef so it only acts once per initial-scroll attempt.
+ useLayoutEffect(() => {
+ if (!pendingReadyRef.current) return;
+ if (processedEvents.length === 0) return;
+ pendingReadyRef.current = false;
+ vListRef.current?.scrollToIndex(processedEvents.length - 1, { align: 'end' });
+ setIsReady(true);
+ }, [processedEvents.length]);
+
useEffect(() => {
if (!onEditLastMessageRef) return;
const ref = onEditLastMessageRef;
diff --git a/src/app/hooks/timeline/useTimelineSync.ts b/src/app/hooks/timeline/useTimelineSync.ts
index 5c99bf6c2..07abffb10 100644
--- a/src/app/hooks/timeline/useTimelineSync.ts
+++ b/src/app/hooks/timeline/useTimelineSync.ts
@@ -179,15 +179,21 @@ const useTimelinePagination = (
}
if (alive()) {
- recalibratePagination(lTimelines);
+ // Re-read linkedTimelines after the await: a sliding sync reset may have
+ // replaced lTimelines[0] (via resetLiveTimeline) while pagination was in
+ // flight, making the captured lTimelines stale. Using the fresh ref
+ // ensures recalibratePagination rebuilds from the current live chain and
+ // that countAfter/stillHasToken comparisons are meaningful.
+ const freshLTimelines = timelineRef.current.linkedTimelines;
+ recalibratePagination(freshLTimelines);
(backwards ? setBackwardStatus : setForwardStatus)('idle');
- const countAfter = getTimelinesEventsCount(getLinkedTimelines(lTimelines[0]));
+ const countAfter = getTimelinesEventsCount(getLinkedTimelines(freshLTimelines[0]));
const fetched = countAfter - countBefore;
if (fetched > 0 && fetched < 5) {
const stillHasToken =
- typeof getLinkedTimelines(lTimelines[0])[0]?.getPaginationToken(
+ typeof getLinkedTimelines(freshLTimelines[0])[0]?.getPaginationToken(
Direction.Backward
) === 'string';
if (stillHasToken) {
@@ -566,6 +572,24 @@ export function useTimelineSync({
setTimeline({ linkedTimelines: getInitialTimeline(room).linkedTimelines });
}, [eventId, room, timeline.linkedTimelines.length]);
+ // When navigating between rooms, reset the timeline state to the new room's
+ // initial linked timelines. Without this, the component's timeline state
+ // retains stale data from the previous room, causing liveTimelineLinked to be
+ // false until a TimelineReset event fires. For revisited rooms with up-to-date
+ // data (no initial:true in the sliding sync response), that event may never
+ // arrive — leaving the initial-scroll guard permanently blocked and the room
+ // invisible.
+ const prevRoomIdRef = useRef(room.roomId);
+ useEffect(() => {
+ if (prevRoomIdRef.current === room.roomId) return;
+ prevRoomIdRef.current = room.roomId;
+ if (eventId) return;
+ setTimeline({ linkedTimelines: getInitialTimeline(room).linkedTimelines });
+ // Intentionally only depends on room: we want this to fire when the room
+ // identity changes, not on every eventId change.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [room]);
+
return {
timeline,
setTimeline,
From 676478435ea938c97ab9a6725ea38c8ff33954d8 Mon Sep 17 00:00:00 2001
From: Evie Gauthier
Date: Fri, 27 Mar 2026 22:12:36 -0400
Subject: [PATCH 29/58] chore: update changeset for scroll-to-bottom and
pagination fixes
---
.changeset/fix-bug-fixes.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/.changeset/fix-bug-fixes.md b/.changeset/fix-bug-fixes.md
index aea8ed44e..a031ad911 100644
--- a/.changeset/fix-bug-fixes.md
+++ b/.changeset/fix-bug-fixes.md
@@ -2,4 +2,4 @@
default: patch
---
-Fix timeline pagination lock bug, deduplicate concurrent URL preview requests, and remove redundant sliding sync spidering call causing N+1 requests.
+Fix timeline pagination lock bug, deduplicate concurrent URL preview requests, remove redundant sliding sync spidering call causing N+1 requests, fix scroll-to-bottom not working after room navigation (stale-room liveTimelineLinked guard + deferred ready on empty processedEvents), and fix wrong timeline chain used for pagination count comparisons after a sliding sync reset.
From e1c8c64cda76d9aa7a0dcc1fd3f9edb084327bf5 Mon Sep 17 00:00:00 2001
From: Evie Gauthier
Date: Fri, 27 Mar 2026 22:40:15 -0400
Subject: [PATCH 30/58] chore: shorten changeset to one-line end-user summary
---
.changeset/fix-bug-fixes.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/.changeset/fix-bug-fixes.md b/.changeset/fix-bug-fixes.md
index a031ad911..8a1dd4ffa 100644
--- a/.changeset/fix-bug-fixes.md
+++ b/.changeset/fix-bug-fixes.md
@@ -2,4 +2,4 @@
default: patch
---
-Fix timeline pagination lock bug, deduplicate concurrent URL preview requests, remove redundant sliding sync spidering call causing N+1 requests, fix scroll-to-bottom not working after room navigation (stale-room liveTimelineLinked guard + deferred ready on empty processedEvents), and fix wrong timeline chain used for pagination count comparisons after a sliding sync reset.
+Fix scroll-to-bottom after room navigation, timeline pagination reliability, and URL preview deduplication.
From 1114c047d5c0dd2e8f5dcaa234fbdafdabe333ee Mon Sep 17 00:00:00 2001
From: Evie Gauthier
Date: Fri, 27 Mar 2026 23:17:03 -0400
Subject: [PATCH 31/58] fix: resolve Copilot code review comments on PR #529
- Clear initialScrollTimerRef when room changes to prevent stale timer
from firing in a new room after navigation (RoomTimeline.tsx)
- Scope URL preview cache by MatrixClient to prevent cross-account
deduplication when multiple clients/sessions exist (UrlPreviewCard.tsx)
- Delete cache entries after promise settles (both success/rejection)
to prevent unbounded cache growth over long sessions (UrlPreviewCard.tsx)
- Fix pagination token direction check: use appropriate timeline end
and token direction based on pagination direction (forward/backward)
instead of always checking first timeline's backward token
(useTimelineSync.ts)
---
.../components/url-preview/UrlPreviewCard.tsx | 28 ++++++++++++++-----
src/app/features/room/RoomTimeline.tsx | 4 +++
src/app/hooks/timeline/useTimelineSync.ts | 6 ++--
3 files changed, 29 insertions(+), 9 deletions(-)
diff --git a/src/app/components/url-preview/UrlPreviewCard.tsx b/src/app/components/url-preview/UrlPreviewCard.tsx
index edc3f0f9d..2b5d6b87b 100644
--- a/src/app/components/url-preview/UrlPreviewCard.tsx
+++ b/src/app/components/url-preview/UrlPreviewCard.tsx
@@ -16,10 +16,23 @@ const linkStyles = { color: color.Success.Main };
// Module-level in-flight deduplication: prevents N+1 concurrent requests when a
// large event batch renders many UrlPreviewCard instances for the same URL.
-// Keyed by URL only (not ts) — the same URL shows the same preview regardless
-// of which message referenced it. Rejected promises are evicted so a later
-// render can retry after network recovery.
-const previewRequestCache = new Map>();
+// Scoped by MatrixClient to avoid cross-account dedup if multiple clients exist.
+// Inner cache keyed by URL only (not ts) — the same URL shows the same preview
+// regardless of which message referenced it. Promises are evicted after settling
+// so a later render can retry after network recovery.
+const previewRequestCache = new WeakMap<
+ any,
+ Map>
+>();
+
+const getClientCache = (mx: any): Map> => {
+ let clientCache = previewRequestCache.get(mx);
+ if (!clientCache) {
+ clientCache = new Map();
+ previewRequestCache.set(mx, clientCache);
+ }
+ return clientCache;
+};
const openMediaInNewTab = async (url: string | undefined) => {
if (!url) {
@@ -41,11 +54,12 @@ export const UrlPreviewCard = as<'div', { url: string; ts: number; mediaType?: s
const [previewStatus, loadPreview] = useAsyncCallback(
useCallback(() => {
if (isDirect) return Promise.resolve(null);
- const cached = previewRequestCache.get(url);
+ const clientCache = getClientCache(mx);
+ const cached = clientCache.get(url);
if (cached !== undefined) return cached;
const urlPreview = mx.getUrlPreview(url, ts);
- previewRequestCache.set(url, urlPreview);
- urlPreview.catch(() => previewRequestCache.delete(url));
+ clientCache.set(url, urlPreview);
+ urlPreview.finally(() => clientCache.delete(url));
return urlPreview;
}, [url, ts, mx, isDirect])
);
diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx
index 95e3f105a..63af8c960 100644
--- a/src/app/features/room/RoomTimeline.tsx
+++ b/src/app/features/room/RoomTimeline.tsx
@@ -224,6 +224,10 @@ export function RoomTimeline({
mountScrollWindowRef.current = Date.now() + 3000;
currentRoomIdRef.current = room.roomId;
pendingReadyRef.current = false;
+ if (initialScrollTimerRef.current !== undefined) {
+ clearTimeout(initialScrollTimerRef.current);
+ initialScrollTimerRef.current = undefined;
+ }
setIsReady(false);
}
diff --git a/src/app/hooks/timeline/useTimelineSync.ts b/src/app/hooks/timeline/useTimelineSync.ts
index 07abffb10..16127b6e5 100644
--- a/src/app/hooks/timeline/useTimelineSync.ts
+++ b/src/app/hooks/timeline/useTimelineSync.ts
@@ -192,9 +192,11 @@ const useTimelinePagination = (
const fetched = countAfter - countBefore;
if (fetched > 0 && fetched < 5) {
+ const checkTimeline = backwards ? freshLTimelines[0] : freshLTimelines[freshLTimelines.length - 1];
+ const checkDirection = backwards ? Direction.Backward : Direction.Forward;
const stillHasToken =
- typeof getLinkedTimelines(freshLTimelines[0])[0]?.getPaginationToken(
- Direction.Backward
+ typeof getLinkedTimelines(checkTimeline)[0]?.getPaginationToken(
+ checkDirection
) === 'string';
if (stillHasToken) {
// Release lock so inner paginate can claim it, then mark continuing
From f9c725e0ab249115005aa0160572aaf63797dc39 Mon Sep 17 00:00:00 2001
From: Evie Gauthier
Date: Fri, 27 Mar 2026 23:33:47 -0400
Subject: [PATCH 32/58] Add tests
---
.../hooks/timeline/useTimelineSync.test.ts | 172 ++++++++++++++++++
1 file changed, 172 insertions(+)
create mode 100644 src/app/hooks/timeline/useTimelineSync.test.ts
diff --git a/src/app/hooks/timeline/useTimelineSync.test.ts b/src/app/hooks/timeline/useTimelineSync.test.ts
new file mode 100644
index 000000000..7b8a27b2c
--- /dev/null
+++ b/src/app/hooks/timeline/useTimelineSync.test.ts
@@ -0,0 +1,172 @@
+// Tests for useTimelineSync: focus on room-change timeline reset behavior
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { renderHook, act } from '@testing-library/react';
+import { useTimelineSync } from './useTimelineSync';
+import { getInitialTimeline } from '$utils/timeline';
+
+// Mock the dependencies
+vi.mock('$hooks/useAlive', () => ({
+ useAlive: () => () => true,
+}));
+
+vi.mock('$utils/notifications', () => ({
+ markAsRead: vi.fn(),
+}));
+
+vi.mock('$utils/room', () => ({
+ decryptAllTimelineEvent: vi.fn(),
+}));
+
+vi.mock('$utils/timeline', () => ({
+ getInitialTimeline: vi.fn(),
+ getEmptyTimeline: vi.fn(),
+ getLinkedTimelines: vi.fn(() => []),
+ getTimelinesEventsCount: vi.fn(() => 0),
+ getEventIdAbsoluteIndex: vi.fn(),
+ getLiveTimeline: vi.fn(),
+ getRoomUnreadInfo: vi.fn(),
+ PAGINATION_LIMIT: 30,
+}));
+
+vi.mock('$types/matrix-sdk', () => ({
+ Direction: { Backward: 0, Forward: 1 },
+}));
+
+vi.mock('@sentry/react', () => ({
+ startSpan: vi.fn((config, fn) => fn()),
+ metrics: {
+ distribution: vi.fn(),
+ },
+}));
+
+// Create mock room and client
+const createMockRoom = (roomId: string) => ({
+ roomId,
+ getUnfilteredTimelineSet: vi.fn(() => ({
+ getTimelineForEvent: vi.fn(() => null),
+ })),
+});
+
+const createMockClient = () => ({
+ getUserId: vi.fn(() => '@user:example.com'),
+});
+
+describe('useTimelineSync', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('resets timeline state when room.roomId changes and eventId is not set', () => {
+ const room1 = createMockRoom('!room1:example.com');
+ const room2 = createMockRoom('!room2:example.com');
+ const mx = createMockClient();
+
+ const mockTimeline = { linkedTimelines: [] };
+ const getInitialTimelineMock = vi.mocked(getInitialTimeline);
+ getInitialTimelineMock.mockReturnValue(mockTimeline);
+
+ // Render with first room
+ const { rerender } = renderHook(
+ ({ room, eventId }) =>
+ useTimelineSync({
+ mx,
+ room,
+ eventId,
+ }),
+ {
+ initialProps: {
+ room: room1,
+ eventId: undefined,
+ },
+ }
+ );
+
+ // Verify initial timeline was set
+ expect(getInitialTimelineMock).toHaveBeenCalledWith(room1);
+
+ // Clear the mock to track new calls
+ getInitialTimelineMock.mockClear();
+
+ // Change to room2
+ act(() => {
+ rerender({ room: room2, eventId: undefined });
+ });
+
+ // Should reset timeline for the new room
+ expect(getInitialTimelineMock).toHaveBeenCalledWith(room2);
+ });
+
+ it('does not reset timeline when eventId is set during room change', () => {
+ const room1 = createMockRoom('!room1:example.com');
+ const room2 = createMockRoom('!room2:example.com');
+ const mx = createMockClient();
+
+ const mockTimeline = { linkedTimelines: [] };
+ const getInitialTimelineMock = vi.mocked(getInitialTimeline);
+ getInitialTimelineMock.mockReturnValue(mockTimeline);
+
+ // Render with first room
+ const { rerender } = renderHook(
+ ({ room, eventId }) =>
+ useTimelineSync({
+ mx,
+ room,
+ eventId,
+ }),
+ {
+ initialProps: {
+ room: room1,
+ eventId: undefined,
+ },
+ }
+ );
+
+ // Clear the mock to track new calls during room change
+ getInitialTimelineMock.mockClear();
+
+ // Change to room2 WITH eventId set (should NOT reset)
+ act(() => {
+ rerender({ room: room2, eventId: '$event123' });
+ });
+
+ // Should NOT reset timeline when eventId is set
+ expect(getInitialTimelineMock).not.toHaveBeenCalledWith(room2);
+ });
+
+ it('does not reset timeline when room.roomId stays the same', () => {
+ const room = createMockRoom('!room1:example.com');
+ const mx = createMockClient();
+
+ const mockTimeline = { linkedTimelines: [] };
+ const getInitialTimelineMock = vi.mocked(getInitialTimeline);
+ getInitialTimelineMock.mockReturnValue(mockTimeline);
+
+ // Render hook
+ const { rerender } = renderHook(
+ ({ room, eventId }) =>
+ useTimelineSync({
+ mx,
+ room,
+ eventId,
+ }),
+ {
+ initialProps: {
+ room,
+ eventId: undefined,
+ },
+ }
+ );
+
+ // Clear the mock to track new calls
+ getInitialTimelineMock.mockClear();
+
+ // Rerender with same room (different prop but same roomId)
+ const sameRoom = createMockRoom(room.roomId);
+ act(() => {
+ rerender({ room: sameRoom, eventId: undefined });
+ });
+
+ // Should NOT reset timeline since roomId is the same
+ expect(getInitialTimelineMock).not.toHaveBeenCalledWith(sameRoom);
+ });
+});
From 6ccb85f96bb154dafd75de728b35015e5d31283c Mon Sep 17 00:00:00 2001
From: Evie Gauthier
Date: Fri, 27 Mar 2026 23:52:45 -0400
Subject: [PATCH 33/58] fix: resolve PR #529 quality check failures
---
.../components/url-preview/UrlPreviewCard.tsx | 5 +-
.../hooks/timeline/useTimelineSync.test.ts | 172 ------------------
.../hooks/timeline/useTimelineSync.test.tsx | 118 +++++++++++-
src/app/hooks/timeline/useTimelineSync.ts | 9 +-
4 files changed, 121 insertions(+), 183 deletions(-)
delete mode 100644 src/app/hooks/timeline/useTimelineSync.test.ts
diff --git a/src/app/components/url-preview/UrlPreviewCard.tsx b/src/app/components/url-preview/UrlPreviewCard.tsx
index 2b5d6b87b..3ac780f74 100644
--- a/src/app/components/url-preview/UrlPreviewCard.tsx
+++ b/src/app/components/url-preview/UrlPreviewCard.tsx
@@ -20,10 +20,7 @@ const linkStyles = { color: color.Success.Main };
// Inner cache keyed by URL only (not ts) — the same URL shows the same preview
// regardless of which message referenced it. Promises are evicted after settling
// so a later render can retry after network recovery.
-const previewRequestCache = new WeakMap<
- any,
- Map>
->();
+const previewRequestCache = new WeakMap>>();
const getClientCache = (mx: any): Map> => {
let clientCache = previewRequestCache.get(mx);
diff --git a/src/app/hooks/timeline/useTimelineSync.test.ts b/src/app/hooks/timeline/useTimelineSync.test.ts
deleted file mode 100644
index 7b8a27b2c..000000000
--- a/src/app/hooks/timeline/useTimelineSync.test.ts
+++ /dev/null
@@ -1,172 +0,0 @@
-// Tests for useTimelineSync: focus on room-change timeline reset behavior
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { renderHook, act } from '@testing-library/react';
-import { useTimelineSync } from './useTimelineSync';
-import { getInitialTimeline } from '$utils/timeline';
-
-// Mock the dependencies
-vi.mock('$hooks/useAlive', () => ({
- useAlive: () => () => true,
-}));
-
-vi.mock('$utils/notifications', () => ({
- markAsRead: vi.fn(),
-}));
-
-vi.mock('$utils/room', () => ({
- decryptAllTimelineEvent: vi.fn(),
-}));
-
-vi.mock('$utils/timeline', () => ({
- getInitialTimeline: vi.fn(),
- getEmptyTimeline: vi.fn(),
- getLinkedTimelines: vi.fn(() => []),
- getTimelinesEventsCount: vi.fn(() => 0),
- getEventIdAbsoluteIndex: vi.fn(),
- getLiveTimeline: vi.fn(),
- getRoomUnreadInfo: vi.fn(),
- PAGINATION_LIMIT: 30,
-}));
-
-vi.mock('$types/matrix-sdk', () => ({
- Direction: { Backward: 0, Forward: 1 },
-}));
-
-vi.mock('@sentry/react', () => ({
- startSpan: vi.fn((config, fn) => fn()),
- metrics: {
- distribution: vi.fn(),
- },
-}));
-
-// Create mock room and client
-const createMockRoom = (roomId: string) => ({
- roomId,
- getUnfilteredTimelineSet: vi.fn(() => ({
- getTimelineForEvent: vi.fn(() => null),
- })),
-});
-
-const createMockClient = () => ({
- getUserId: vi.fn(() => '@user:example.com'),
-});
-
-describe('useTimelineSync', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it('resets timeline state when room.roomId changes and eventId is not set', () => {
- const room1 = createMockRoom('!room1:example.com');
- const room2 = createMockRoom('!room2:example.com');
- const mx = createMockClient();
-
- const mockTimeline = { linkedTimelines: [] };
- const getInitialTimelineMock = vi.mocked(getInitialTimeline);
- getInitialTimelineMock.mockReturnValue(mockTimeline);
-
- // Render with first room
- const { rerender } = renderHook(
- ({ room, eventId }) =>
- useTimelineSync({
- mx,
- room,
- eventId,
- }),
- {
- initialProps: {
- room: room1,
- eventId: undefined,
- },
- }
- );
-
- // Verify initial timeline was set
- expect(getInitialTimelineMock).toHaveBeenCalledWith(room1);
-
- // Clear the mock to track new calls
- getInitialTimelineMock.mockClear();
-
- // Change to room2
- act(() => {
- rerender({ room: room2, eventId: undefined });
- });
-
- // Should reset timeline for the new room
- expect(getInitialTimelineMock).toHaveBeenCalledWith(room2);
- });
-
- it('does not reset timeline when eventId is set during room change', () => {
- const room1 = createMockRoom('!room1:example.com');
- const room2 = createMockRoom('!room2:example.com');
- const mx = createMockClient();
-
- const mockTimeline = { linkedTimelines: [] };
- const getInitialTimelineMock = vi.mocked(getInitialTimeline);
- getInitialTimelineMock.mockReturnValue(mockTimeline);
-
- // Render with first room
- const { rerender } = renderHook(
- ({ room, eventId }) =>
- useTimelineSync({
- mx,
- room,
- eventId,
- }),
- {
- initialProps: {
- room: room1,
- eventId: undefined,
- },
- }
- );
-
- // Clear the mock to track new calls during room change
- getInitialTimelineMock.mockClear();
-
- // Change to room2 WITH eventId set (should NOT reset)
- act(() => {
- rerender({ room: room2, eventId: '$event123' });
- });
-
- // Should NOT reset timeline when eventId is set
- expect(getInitialTimelineMock).not.toHaveBeenCalledWith(room2);
- });
-
- it('does not reset timeline when room.roomId stays the same', () => {
- const room = createMockRoom('!room1:example.com');
- const mx = createMockClient();
-
- const mockTimeline = { linkedTimelines: [] };
- const getInitialTimelineMock = vi.mocked(getInitialTimeline);
- getInitialTimelineMock.mockReturnValue(mockTimeline);
-
- // Render hook
- const { rerender } = renderHook(
- ({ room, eventId }) =>
- useTimelineSync({
- mx,
- room,
- eventId,
- }),
- {
- initialProps: {
- room,
- eventId: undefined,
- },
- }
- );
-
- // Clear the mock to track new calls
- getInitialTimelineMock.mockClear();
-
- // Rerender with same room (different prop but same roomId)
- const sameRoom = createMockRoom(room.roomId);
- act(() => {
- rerender({ room: sameRoom, eventId: undefined });
- });
-
- // Should NOT reset timeline since roomId is the same
- expect(getInitialTimelineMock).not.toHaveBeenCalledWith(sameRoom);
- });
-});
diff --git a/src/app/hooks/timeline/useTimelineSync.test.tsx b/src/app/hooks/timeline/useTimelineSync.test.tsx
index 71fde31c2..d53d74143 100644
--- a/src/app/hooks/timeline/useTimelineSync.test.tsx
+++ b/src/app/hooks/timeline/useTimelineSync.test.tsx
@@ -40,12 +40,18 @@ function createTimeline(events: unknown[] = [{}]): FakeTimeline {
};
}
-function createRoom(events: unknown[] = [{}]): {
+function createRoom(
+ roomId = '!room:test',
+ events: unknown[] = [{}]
+): {
room: FakeRoom;
timelineSet: FakeTimelineSet;
events: unknown[];
} {
- const timeline = createTimeline(events);
+ const timeline = {
+ ...createTimeline(events),
+ getRoomId: () => roomId,
+ };
const timelineSet = new EventEmitter() as FakeTimelineSet;
timelineSet.getLiveTimeline = () => timeline;
timelineSet.getTimelineForEvent = () => undefined;
@@ -55,7 +61,7 @@ function createRoom(events: unknown[] = [{}]): {
on: roomEmitter.on.bind(roomEmitter),
removeListener: roomEmitter.removeListener.bind(roomEmitter),
emit: roomEmitter.emit.bind(roomEmitter),
- roomId: '!room:test',
+ roomId,
getUnfilteredTimelineSet: () => timelineSet as never,
getEventReadUpTo: () => null,
getThread: () => null,
@@ -125,4 +131,110 @@ describe('useTimelineSync', () => {
expect(scrollToBottom).toHaveBeenCalledWith('instant');
});
+
+ it('resets timeline state when room.roomId changes and eventId is not set', async () => {
+ const roomOne = createRoom('!room:one');
+ const roomTwo = createRoom('!room:two');
+ const scrollToBottom = vi.fn();
+
+ const { result, rerender } = renderHook(
+ ({ room, eventId }) =>
+ useTimelineSync({
+ room,
+ mx: { getUserId: () => '@alice:test' } as never,
+ eventId,
+ isAtBottom: false,
+ isAtBottomRef: { current: false },
+ scrollToBottom,
+ unreadInfo: undefined,
+ setUnreadInfo: vi.fn(),
+ hideReadsRef: { current: false },
+ readUptoEventIdRef: { current: undefined },
+ }),
+ {
+ initialProps: {
+ room: roomOne.room as Room,
+ eventId: undefined as string | undefined,
+ },
+ }
+ );
+
+ expect(result.current.timeline.linkedTimelines[0]).toBe(roomOne.timelineSet.getLiveTimeline());
+
+ await act(async () => {
+ rerender({ room: roomTwo.room as Room, eventId: undefined });
+ await Promise.resolve();
+ });
+
+ expect(result.current.timeline.linkedTimelines[0]).toBe(roomTwo.timelineSet.getLiveTimeline());
+ });
+
+ it('does not reset timeline when eventId is set during a room change', async () => {
+ const roomOne = createRoom('!room:one');
+ const roomTwo = createRoom('!room:two');
+ const scrollToBottom = vi.fn();
+
+ const { result, rerender } = renderHook(
+ ({ room, eventId }) =>
+ useTimelineSync({
+ room,
+ mx: { getUserId: () => '@alice:test' } as never,
+ eventId,
+ isAtBottom: false,
+ isAtBottomRef: { current: false },
+ scrollToBottom,
+ unreadInfo: undefined,
+ setUnreadInfo: vi.fn(),
+ hideReadsRef: { current: false },
+ readUptoEventIdRef: { current: undefined },
+ }),
+ {
+ initialProps: {
+ room: roomOne.room as Room,
+ eventId: undefined as string | undefined,
+ },
+ }
+ );
+
+ await act(async () => {
+ rerender({ room: roomTwo.room as Room, eventId: '$event:one' });
+ await Promise.resolve();
+ });
+
+ expect(result.current.timeline.linkedTimelines[0]).toBe(roomOne.timelineSet.getLiveTimeline());
+ });
+
+ it('does not reset timeline when the roomId stays the same', async () => {
+ const roomOne = createRoom('!room:one');
+ const sameRoomId = createRoom('!room:one');
+ const scrollToBottom = vi.fn();
+
+ const { result, rerender } = renderHook(
+ ({ room }) =>
+ useTimelineSync({
+ room,
+ mx: { getUserId: () => '@alice:test' } as never,
+ eventId: undefined,
+ isAtBottom: false,
+ isAtBottomRef: { current: false },
+ scrollToBottom,
+ unreadInfo: undefined,
+ setUnreadInfo: vi.fn(),
+ hideReadsRef: { current: false },
+ readUptoEventIdRef: { current: undefined },
+ }),
+ {
+ initialProps: {
+ room: roomOne.room as Room,
+ },
+ }
+ );
+
+ await act(async () => {
+ rerender({ room: sameRoomId.room as Room });
+ await Promise.resolve();
+ });
+
+ expect(result.current.timeline.linkedTimelines[0]).toBe(roomOne.timelineSet.getLiveTimeline());
+ });
});
diff --git a/src/app/hooks/timeline/useTimelineSync.ts b/src/app/hooks/timeline/useTimelineSync.ts
index 16127b6e5..51c85dda8 100644
--- a/src/app/hooks/timeline/useTimelineSync.ts
+++ b/src/app/hooks/timeline/useTimelineSync.ts
@@ -192,12 +192,13 @@ const useTimelinePagination = (
const fetched = countAfter - countBefore;
if (fetched > 0 && fetched < 5) {
- const checkTimeline = backwards ? freshLTimelines[0] : freshLTimelines[freshLTimelines.length - 1];
+ const checkTimeline = backwards
+ ? freshLTimelines[0]
+ : freshLTimelines[freshLTimelines.length - 1];
const checkDirection = backwards ? Direction.Backward : Direction.Forward;
const stillHasToken =
- typeof getLinkedTimelines(checkTimeline)[0]?.getPaginationToken(
- checkDirection
- ) === 'string';
+ typeof getLinkedTimelines(checkTimeline)[0]?.getPaginationToken(checkDirection) ===
+ 'string';
if (stillHasToken) {
// Release lock so inner paginate can claim it, then mark continuing
// so the finally block below does NOT reset it after inner claims.
From fe3900a657568fbf514e7009761ff1652bfe0bd4 Mon Sep 17 00:00:00 2001
From: Evie Gauthier
Date: Sat, 28 Mar 2026 01:12:49 -0400
Subject: [PATCH 34/58] fix: recover profile and avatar loading
---
src/app/components/room-avatar/RoomAvatar.tsx | 6 +++++-
src/app/components/user-avatar/UserAvatar.tsx | 6 +++++-
src/app/hooks/useUserProfile.ts | 15 +++++++++++++--
3 files changed, 23 insertions(+), 4 deletions(-)
diff --git a/src/app/components/room-avatar/RoomAvatar.tsx b/src/app/components/room-avatar/RoomAvatar.tsx
index 356d9dbc2..33f9f6881 100644
--- a/src/app/components/room-avatar/RoomAvatar.tsx
+++ b/src/app/components/room-avatar/RoomAvatar.tsx
@@ -1,6 +1,6 @@
import { JoinRule } from '$types/matrix-sdk';
import { AvatarFallback, Icon, Icons, color } from 'folds';
-import { ComponentProps, ReactNode, forwardRef, useState } from 'react';
+import { ComponentProps, ReactNode, forwardRef, useEffect, useState } from 'react';
import { getRoomIconSrc } from '$utils/room';
import colorMXID from '$utils/colorMXID';
import * as css from './RoomAvatar.css';
@@ -17,6 +17,10 @@ type RoomAvatarProps = {
export function RoomAvatar({ roomId, src, alt, renderFallback, uniformIcons }: RoomAvatarProps) {
const [error, setError] = useState(false);
+ useEffect(() => {
+ setError(false);
+ }, [src]);
+
if (!src || error) {
return (
{
+ setError(false);
+ }, [src]);
+
const handleLoad: ReactEventHandler = (evt) => {
evt.currentTarget.setAttribute('data-image-loaded', 'true');
};
diff --git a/src/app/hooks/useUserProfile.ts b/src/app/hooks/useUserProfile.ts
index 8de5da050..b50a42960 100644
--- a/src/app/hooks/useUserProfile.ts
+++ b/src/app/hooks/useUserProfile.ts
@@ -7,10 +7,15 @@ import colorMXID from '$utils/colorMXID';
import { profilesCacheAtom } from '$state/userRoomProfile';
import { useSetting } from '$state/hooks/settings';
import { settingsAtom } from '$state/settings';
+import { MSC1767Text } from '$types/matrix/common';
import { useMatrixClient } from './useMatrixClient';
const inFlightProfiles = new Map>();
+export type MSC4440Bio = {
+ 'm.text': Array;
+};
+
export type UserProfile = {
avatarUrl?: string;
displayName?: string;
@@ -27,6 +32,7 @@ export type UserProfile = {
};
const normalizeInfo = (info: any): UserProfile => {
+ const msc4440Bio = info['gay.fomx.biography'] as MSC4440Bio | undefined;
const knownKeys = new Set([
'avatar_url',
'displayname',
@@ -35,6 +41,7 @@ const normalizeInfo = (info: any): UserProfile => {
'm.tz',
'moe.sable.app.bio',
'chat.commet.profile_bio',
+ 'gay.fomx.biography',
'chat.commet.profile_banner',
'chat.commet.profile_status',
'moe.sable.app.name_color',
@@ -54,7 +61,7 @@ const normalizeInfo = (info: any): UserProfile => {
displayName: info.displayname,
pronouns: info['io.fsky.nyx.pronouns'],
timezone: info['us.cloke.msc4175.tz'] || info['m.tz'],
- bio: info['moe.sable.app.bio'] || info['chat.commet.profile_bio'],
+ bio: msc4440Bio?.['m.text']?.[0]?.body || info['moe.sable.app.bio'] || info['chat.commet.profile_bio'],
status: info['chat.commet.profile_status'],
bannerUrl: info['chat.commet.profile_banner'],
nameColor: info['moe.sable.app.name_color'],
@@ -94,7 +101,11 @@ export const useUserProfile = (
const cached = useAtomValue(userSelector);
const setGlobalProfiles = useSetAtom(profilesCacheAtom);
- const needsFetch = !!userId && userId !== 'undefined' && !cached?._fetched;
+ const hasOnlyFetchedMarker =
+ cached?._fetched === true && Object.keys(cached).every((key) => key === '_fetched');
+
+ const needsFetch =
+ !!userId && userId !== 'undefined' && (!cached?._fetched || hasOnlyFetchedMarker);
useEffect(() => {
if (!needsFetch) return undefined;
From 282de15601283833d875d55856497da945543eac Mon Sep 17 00:00:00 2001
From: Evie Gauthier
Date: Sat, 28 Mar 2026 01:12:49 -0400
Subject: [PATCH 35/58] fix: recover profile and avatar loading
---
src/app/components/room-avatar/RoomAvatar.tsx | 6 +++++-
src/app/components/user-avatar/UserAvatar.tsx | 6 +++++-
src/app/hooks/useUserProfile.ts | 12 +++++++-----
3 files changed, 17 insertions(+), 7 deletions(-)
diff --git a/src/app/components/room-avatar/RoomAvatar.tsx b/src/app/components/room-avatar/RoomAvatar.tsx
index 356d9dbc2..33f9f6881 100644
--- a/src/app/components/room-avatar/RoomAvatar.tsx
+++ b/src/app/components/room-avatar/RoomAvatar.tsx
@@ -1,6 +1,6 @@
import { JoinRule } from '$types/matrix-sdk';
import { AvatarFallback, Icon, Icons, color } from 'folds';
-import { ComponentProps, ReactNode, forwardRef, useState } from 'react';
+import { ComponentProps, ReactNode, forwardRef, useEffect, useState } from 'react';
import { getRoomIconSrc } from '$utils/room';
import colorMXID from '$utils/colorMXID';
import * as css from './RoomAvatar.css';
@@ -17,6 +17,10 @@ type RoomAvatarProps = {
export function RoomAvatar({ roomId, src, alt, renderFallback, uniformIcons }: RoomAvatarProps) {
const [error, setError] = useState(false);
+ useEffect(() => {
+ setError(false);
+ }, [src]);
+
if (!src || error) {
return (
{
+ setError(false);
+ }, [src]);
+
const handleLoad: ReactEventHandler = (evt) => {
evt.currentTarget.setAttribute('data-image-loaded', 'true');
};
diff --git a/src/app/hooks/useUserProfile.ts b/src/app/hooks/useUserProfile.ts
index d1de6e890..b50a42960 100644
--- a/src/app/hooks/useUserProfile.ts
+++ b/src/app/hooks/useUserProfile.ts
@@ -32,6 +32,7 @@ export type UserProfile = {
};
const normalizeInfo = (info: any): UserProfile => {
+ const msc4440Bio = info['gay.fomx.biography'] as MSC4440Bio | undefined;
const knownKeys = new Set([
'avatar_url',
'displayname',
@@ -60,10 +61,7 @@ const normalizeInfo = (info: any): UserProfile => {
displayName: info.displayname,
pronouns: info['io.fsky.nyx.pronouns'],
timezone: info['us.cloke.msc4175.tz'] || info['m.tz'],
- bio:
- (info['gay.fomx.biography'] satisfies MSC4440Bio)['m.text'][0].body ||
- info['moe.sable.app.bio'] ||
- info['chat.commet.profile_bio'],
+ bio: msc4440Bio?.['m.text']?.[0]?.body || info['moe.sable.app.bio'] || info['chat.commet.profile_bio'],
status: info['chat.commet.profile_status'],
bannerUrl: info['chat.commet.profile_banner'],
nameColor: info['moe.sable.app.name_color'],
@@ -103,7 +101,11 @@ export const useUserProfile = (
const cached = useAtomValue(userSelector);
const setGlobalProfiles = useSetAtom(profilesCacheAtom);
- const needsFetch = !!userId && userId !== 'undefined' && !cached?._fetched;
+ const hasOnlyFetchedMarker =
+ cached?._fetched === true && Object.keys(cached).every((key) => key === '_fetched');
+
+ const needsFetch =
+ !!userId && userId !== 'undefined' && (!cached?._fetched || hasOnlyFetchedMarker);
useEffect(() => {
if (!needsFetch) return undefined;
From 5865c4cc71432420983f372397519de3001f9f48 Mon Sep 17 00:00:00 2001
From: Evie Gauthier
Date: Sat, 28 Mar 2026 01:19:57 -0400
Subject: [PATCH 36/58] chore: add changeset for profile/avatar loading fix
---
.changeset/fix-profile-avatar-loading.md | 5 +++++
1 file changed, 5 insertions(+)
create mode 100644 .changeset/fix-profile-avatar-loading.md
diff --git a/.changeset/fix-profile-avatar-loading.md b/.changeset/fix-profile-avatar-loading.md
new file mode 100644
index 000000000..39bcf0471
--- /dev/null
+++ b/.changeset/fix-profile-avatar-loading.md
@@ -0,0 +1,5 @@
+---
+default: patch
+---
+
+Fix profile data loading when MSC4440 bio data is absent or malformed, and recover avatar rendering after transient image load failures.
\ No newline at end of file
From 7ac19354248ded7043a9339f059723bf0dea0a1f Mon Sep 17 00:00:00 2001
From: Evie Gauthier
Date: Sat, 28 Mar 2026 01:21:45 -0400
Subject: [PATCH 37/58] Revert "fix: recover profile and avatar loading"
This reverts commit fe3900a657568fbf514e7009761ff1652bfe0bd4.
---
src/app/components/room-avatar/RoomAvatar.tsx | 6 +-----
src/app/components/user-avatar/UserAvatar.tsx | 6 +-----
src/app/hooks/useUserProfile.ts | 15 ++-------------
3 files changed, 4 insertions(+), 23 deletions(-)
diff --git a/src/app/components/room-avatar/RoomAvatar.tsx b/src/app/components/room-avatar/RoomAvatar.tsx
index 33f9f6881..356d9dbc2 100644
--- a/src/app/components/room-avatar/RoomAvatar.tsx
+++ b/src/app/components/room-avatar/RoomAvatar.tsx
@@ -1,6 +1,6 @@
import { JoinRule } from '$types/matrix-sdk';
import { AvatarFallback, Icon, Icons, color } from 'folds';
-import { ComponentProps, ReactNode, forwardRef, useEffect, useState } from 'react';
+import { ComponentProps, ReactNode, forwardRef, useState } from 'react';
import { getRoomIconSrc } from '$utils/room';
import colorMXID from '$utils/colorMXID';
import * as css from './RoomAvatar.css';
@@ -17,10 +17,6 @@ type RoomAvatarProps = {
export function RoomAvatar({ roomId, src, alt, renderFallback, uniformIcons }: RoomAvatarProps) {
const [error, setError] = useState(false);
- useEffect(() => {
- setError(false);
- }, [src]);
-
if (!src || error) {
return (
{
- setError(false);
- }, [src]);
-
const handleLoad: ReactEventHandler = (evt) => {
evt.currentTarget.setAttribute('data-image-loaded', 'true');
};
diff --git a/src/app/hooks/useUserProfile.ts b/src/app/hooks/useUserProfile.ts
index b50a42960..8de5da050 100644
--- a/src/app/hooks/useUserProfile.ts
+++ b/src/app/hooks/useUserProfile.ts
@@ -7,15 +7,10 @@ import colorMXID from '$utils/colorMXID';
import { profilesCacheAtom } from '$state/userRoomProfile';
import { useSetting } from '$state/hooks/settings';
import { settingsAtom } from '$state/settings';
-import { MSC1767Text } from '$types/matrix/common';
import { useMatrixClient } from './useMatrixClient';
const inFlightProfiles = new Map>();
-export type MSC4440Bio = {
- 'm.text': Array;
-};
-
export type UserProfile = {
avatarUrl?: string;
displayName?: string;
@@ -32,7 +27,6 @@ export type UserProfile = {
};
const normalizeInfo = (info: any): UserProfile => {
- const msc4440Bio = info['gay.fomx.biography'] as MSC4440Bio | undefined;
const knownKeys = new Set([
'avatar_url',
'displayname',
@@ -41,7 +35,6 @@ const normalizeInfo = (info: any): UserProfile => {
'm.tz',
'moe.sable.app.bio',
'chat.commet.profile_bio',
- 'gay.fomx.biography',
'chat.commet.profile_banner',
'chat.commet.profile_status',
'moe.sable.app.name_color',
@@ -61,7 +54,7 @@ const normalizeInfo = (info: any): UserProfile => {
displayName: info.displayname,
pronouns: info['io.fsky.nyx.pronouns'],
timezone: info['us.cloke.msc4175.tz'] || info['m.tz'],
- bio: msc4440Bio?.['m.text']?.[0]?.body || info['moe.sable.app.bio'] || info['chat.commet.profile_bio'],
+ bio: info['moe.sable.app.bio'] || info['chat.commet.profile_bio'],
status: info['chat.commet.profile_status'],
bannerUrl: info['chat.commet.profile_banner'],
nameColor: info['moe.sable.app.name_color'],
@@ -101,11 +94,7 @@ export const useUserProfile = (
const cached = useAtomValue(userSelector);
const setGlobalProfiles = useSetAtom(profilesCacheAtom);
- const hasOnlyFetchedMarker =
- cached?._fetched === true && Object.keys(cached).every((key) => key === '_fetched');
-
- const needsFetch =
- !!userId && userId !== 'undefined' && (!cached?._fetched || hasOnlyFetchedMarker);
+ const needsFetch = !!userId && userId !== 'undefined' && !cached?._fetched;
useEffect(() => {
if (!needsFetch) return undefined;
From e7fd523759a89bc39282db94b41eeff666488391 Mon Sep 17 00:00:00 2001
From: Evie Gauthier
Date: Sat, 28 Mar 2026 01:25:41 -0400
Subject: [PATCH 38/58] chore: format profile avatar fix files
---
.changeset/fix-profile-avatar-loading.md | 2 +-
src/app/hooks/useUserProfile.ts | 5 ++++-
2 files changed, 5 insertions(+), 2 deletions(-)
diff --git a/.changeset/fix-profile-avatar-loading.md b/.changeset/fix-profile-avatar-loading.md
index 39bcf0471..3629a6c9f 100644
--- a/.changeset/fix-profile-avatar-loading.md
+++ b/.changeset/fix-profile-avatar-loading.md
@@ -2,4 +2,4 @@
default: patch
---
-Fix profile data loading when MSC4440 bio data is absent or malformed, and recover avatar rendering after transient image load failures.
\ No newline at end of file
+Fix profile data loading when MSC4440 bio data is absent or malformed, and recover avatar rendering after transient image load failures.
diff --git a/src/app/hooks/useUserProfile.ts b/src/app/hooks/useUserProfile.ts
index b50a42960..cfa960542 100644
--- a/src/app/hooks/useUserProfile.ts
+++ b/src/app/hooks/useUserProfile.ts
@@ -61,7 +61,10 @@ const normalizeInfo = (info: any): UserProfile => {
displayName: info.displayname,
pronouns: info['io.fsky.nyx.pronouns'],
timezone: info['us.cloke.msc4175.tz'] || info['m.tz'],
- bio: msc4440Bio?.['m.text']?.[0]?.body || info['moe.sable.app.bio'] || info['chat.commet.profile_bio'],
+ bio:
+ msc4440Bio?.['m.text']?.[0]?.body ||
+ info['moe.sable.app.bio'] ||
+ info['chat.commet.profile_bio'],
status: info['chat.commet.profile_status'],
bannerUrl: info['chat.commet.profile_banner'],
nameColor: info['moe.sable.app.name_color'],
From 2a30a22c2408857761eda4001bd87e3300b96cd8 Mon Sep 17 00:00:00 2001
From: Evie Gauthier
Date: Sat, 28 Mar 2026 01:28:15 -0400
Subject: [PATCH 39/58] Update src/app/hooks/useUserProfile.ts
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
---
src/app/hooks/useUserProfile.ts | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/src/app/hooks/useUserProfile.ts b/src/app/hooks/useUserProfile.ts
index cfa960542..9a1c8464e 100644
--- a/src/app/hooks/useUserProfile.ts
+++ b/src/app/hooks/useUserProfile.ts
@@ -105,7 +105,8 @@ export const useUserProfile = (
const setGlobalProfiles = useSetAtom(profilesCacheAtom);
const hasOnlyFetchedMarker =
- cached?._fetched === true && Object.keys(cached).every((key) => key === '_fetched');
+ cached?._fetched === true &&
+ Object.keys(cached ?? {}).every((key) => key === '_fetched');
const needsFetch =
!!userId && userId !== 'undefined' && (!cached?._fetched || hasOnlyFetchedMarker);
From 3ffbbb53fec14eed0953ec2e743f2be4ea671ba4 Mon Sep 17 00:00:00 2001
From: Rose
Date: Sat, 28 Mar 2026 12:40:09 +0100
Subject: [PATCH 40/58] Delete .changeset/fix-profile-avatar-loading.md
---
.changeset/fix-profile-avatar-loading.md | 5 -----
1 file changed, 5 deletions(-)
delete mode 100644 .changeset/fix-profile-avatar-loading.md
diff --git a/.changeset/fix-profile-avatar-loading.md b/.changeset/fix-profile-avatar-loading.md
deleted file mode 100644
index 3629a6c9f..000000000
--- a/.changeset/fix-profile-avatar-loading.md
+++ /dev/null
@@ -1,5 +0,0 @@
----
-default: patch
----
-
-Fix profile data loading when MSC4440 bio data is absent or malformed, and recover avatar rendering after transient image load failures.
From cd4b4c7651a9180fd7e87625dc2375d04dc43500 Mon Sep 17 00:00:00 2001
From: Rose
Date: Sat, 28 Mar 2026 13:27:27 +0100
Subject: [PATCH 41/58] Add CodeQL analysis workflow configuration
This workflow file sets up CodeQL analysis for the repository, specifying languages and build modes for scanning.
---
.github/workflows/codeql.yml | 101 +++++++++++++++++++++++++++++++++++
1 file changed, 101 insertions(+)
create mode 100644 .github/workflows/codeql.yml
diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml
new file mode 100644
index 000000000..f528a1127
--- /dev/null
+++ b/.github/workflows/codeql.yml
@@ -0,0 +1,101 @@
+# For most projects, this workflow file will not need changing; you simply need
+# to commit it to your repository.
+#
+# You may wish to alter this file to override the set of languages analyzed,
+# or to provide custom queries or build logic.
+#
+# ******** NOTE ********
+# We have attempted to detect the languages in your repository. Please check
+# the `language` matrix defined below to confirm you have the correct set of
+# supported CodeQL languages.
+#
+name: "CodeQL Advanced"
+
+on:
+ push:
+ branches: [ "dev" ]
+ pull_request:
+ branches: [ "dev" ]
+ schedule:
+ - cron: '29 1 * * 2'
+
+jobs:
+ analyze:
+ name: Analyze (${{ matrix.language }})
+ # Runner size impacts CodeQL analysis time. To learn more, please see:
+ # - https://gh.io/recommended-hardware-resources-for-running-codeql
+ # - https://gh.io/supported-runners-and-hardware-resources
+ # - https://gh.io/using-larger-runners (GitHub.com only)
+ # Consider using larger runners or machines with greater resources for possible analysis time improvements.
+ runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }}
+ permissions:
+ # required for all workflows
+ security-events: write
+
+ # required to fetch internal or private CodeQL packs
+ packages: read
+
+ # only required for workflows in private repositories
+ actions: read
+ contents: read
+
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - language: actions
+ build-mode: none
+ - language: javascript-typescript
+ build-mode: none
+ # CodeQL supports the following values keywords for 'language': 'actions', 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'rust', 'swift'
+ # Use `c-cpp` to analyze code written in C, C++ or both
+ # Use 'java-kotlin' to analyze code written in Java, Kotlin or both
+ # Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both
+ # To learn more about changing the languages that are analyzed or customizing the build mode for your analysis,
+ # see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning.
+ # If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how
+ # your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v4
+
+ # Add any setup steps before running the `github/codeql-action/init` action.
+ # This includes steps like installing compilers or runtimes (`actions/setup-node`
+ # or others). This is typically only required for manual builds.
+ # - name: Setup runtime (example)
+ # uses: actions/setup-example@v1
+
+ # Initializes the CodeQL tools for scanning.
+ - name: Initialize CodeQL
+ uses: github/codeql-action/init@v4
+ with:
+ languages: ${{ matrix.language }}
+ build-mode: ${{ matrix.build-mode }}
+ # If you wish to specify custom queries, you can do so here or in a config file.
+ # By default, queries listed here will override any specified in a config file.
+ # Prefix the list here with "+" to use these queries and those in the config file.
+
+ # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
+ # queries: security-extended,security-and-quality
+
+ # If the analyze step fails for one of the languages you are analyzing with
+ # "We were unable to automatically build your code", modify the matrix above
+ # to set the build mode to "manual" for that language. Then modify this step
+ # to build your code.
+ # ℹ️ Command-line programs to run using the OS shell.
+ # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
+ - name: Run manual build steps
+ if: matrix.build-mode == 'manual'
+ shell: bash
+ run: |
+ echo 'If you are using a "manual" build mode for one or more of the' \
+ 'languages you are analyzing, replace this with the commands to build' \
+ 'your code, for example:'
+ echo ' make bootstrap'
+ echo ' make release'
+ exit 1
+
+ - name: Perform CodeQL Analysis
+ uses: github/codeql-action/analyze@v4
+ with:
+ category: "/language:${{matrix.language}}"
From 04fd0fd76e138eeb0a4b53cad322fbc51ba69191 Mon Sep 17 00:00:00 2001
From: Evie Gauthier
Date: Sat, 28 Mar 2026 10:29:35 -0400
Subject: [PATCH 42/58] Fix reply HTML sanitization and add regression test
---
src/app/components/message/Reply.tsx | 23 ++++++++++------
.../message/ThreadIndicator.test.tsx | 26 ++++++++++++++++++-
2 files changed, 40 insertions(+), 9 deletions(-)
diff --git a/src/app/components/message/Reply.tsx b/src/app/components/message/Reply.tsx
index 3342b0d52..a7e10729b 100644
--- a/src/app/components/message/Reply.tsx
+++ b/src/app/components/message/Reply.tsx
@@ -25,6 +25,7 @@ import { useMatrixClient } from '$hooks/useMatrixClient';
import { useMemberEventParser } from '$hooks/useMemberEventParser';
import { StateEvent, MessageEvent } from '$types/matrix/room';
import { useMentionClickHandler } from '$hooks/useMentionClickHandler';
+import { sanitizeCustomHtml } from '$utils/sanitize';
import { useTranslation } from 'react-i18next';
import * as customHtmlCss from '$styles/CustomHtml.css';
import {
@@ -91,6 +92,18 @@ type ReplyProps = {
replyIcon?: JSX.Element;
};
+export const sanitizeReplyFormattedPreview = (formattedBody: string): string => {
+ const strippedHtml = trimReplyFromFormattedBody(formattedBody)
+ .replaceAll(/
/gi, ' ')
+ .replaceAll(/<\/p>\s*]*>/gi, ' ')
+ .replaceAll(/<\/?p[^>]*>/gi, '')
+ .replaceAll(/<\/li>\s*
]*>/gi, ' ')
+ .replaceAll(/<\/?(ul|ol|li|blockquote|h[1-6]|pre|div)[^>]*>/gi, '')
+ .replaceAll(/(?:\r\n|\r|\n)/g, ' ');
+
+ return sanitizeCustomHtml(strippedHtml);
+};
+
export const Reply = as<'div', ReplyProps>(
(
{ room, timelineSet, replyEventId, threadRootId, mentions, onClick, replyIcon, ...props },
@@ -158,20 +171,14 @@ export const Reply = as<'div', ReplyProps>(
);
if (format === 'org.matrix.custom.html' && formattedBody) {
- const strippedHtml = trimReplyFromFormattedBody(formattedBody)
- .replaceAll(/
/gi, ' ')
- .replaceAll(/<\/p>\s*]*>/gi, ' ')
- .replaceAll(/<\/?p[^>]*>/gi, '')
- .replaceAll(/<\/li>\s*
]*>/gi, ' ')
- .replaceAll(/<\/?(ul|ol|li|blockquote|h[1-6]|pre|div)[^>]*>/gi, '')
- .replaceAll(/(?:\r\n|\r|\n)/g, ' ');
+ const sanitizedHtml = sanitizeReplyFormattedPreview(formattedBody);
const parserOpts = getReactCustomHtmlParser(mx, room.roomId, {
linkifyOpts: replyLinkifyOpts,
useAuthentication,
nicknames,
handleMentionClick: mentionClickHandler,
});
- bodyJSX = parse(strippedHtml, parserOpts) as JSX.Element;
+ bodyJSX = parse(sanitizedHtml, parserOpts) as JSX.Element;
} else if (body) {
const strippedBody = trimReplyFromBody(body).replaceAll(/(?:\r\n|\r|\n)/g, ' ');
bodyJSX = scaleSystemEmoji(strippedBody);
diff --git a/src/app/components/message/ThreadIndicator.test.tsx b/src/app/components/message/ThreadIndicator.test.tsx
index d06e1f15e..e94478194 100644
--- a/src/app/components/message/ThreadIndicator.test.tsx
+++ b/src/app/components/message/ThreadIndicator.test.tsx
@@ -14,7 +14,7 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { RelationType } from '$types/matrix-sdk';
-import { ThreadIndicator } from './Reply';
+import { sanitizeReplyFormattedPreview, ThreadIndicator } from './Reply';
function Subject({ relType, threadRootId }: { relType?: string; threadRootId?: string }) {
return <>{relType === RelationType.Thread && !threadRootId && }>;
@@ -41,3 +41,27 @@ describe('ThreadIndicator visibility in compose strip', () => {
expect(screen.queryByText('Thread')).not.toBeInTheDocument();
});
});
+
+describe('sanitizeReplyFormattedPreview', () => {
+ it('removes mx-reply quote block content and keeps message text', () => {
+ const html =
+ 'quoted
Visible message
';
+
+ const result = sanitizeReplyFormattedPreview(html);
+
+ expect(result).not.toContain('quoted');
+ expect(result).toContain('Visible message');
+ });
+
+ it('sanitizes dangerous HTML before parse', () => {
+ const html =
+ 'old
safe
x';
+
+ const result = sanitizeReplyFormattedPreview(html);
+
+ expect(result).not.toContain('
x';
+ 'old
safe
x';
const result = sanitizeReplyFormattedPreview(html);
expect(result).not.toContain('' +
+ 'visible' +
+ '
'
+ )
+ );
+
+ render(
+ undefined } as any}
+ replyEventId="$reply:example.com"
+ />
+ );
+
+ expect(screen.getByText('visible')).toBeInTheDocument();
+ expect(screen.queryByText('quoted')).not.toBeInTheDocument();
+ expect(screen.queryByText('alert(1)')).not.toBeInTheDocument();
+ expect(screen.queryByAltText('blocked image')).not.toBeInTheDocument();
+ });
+});
diff --git a/src/app/components/message/Reply.tsx b/src/app/components/message/Reply.tsx
index 3342b0d52..9063d3471 100644
--- a/src/app/components/message/Reply.tsx
+++ b/src/app/components/message/Reply.tsx
@@ -8,6 +8,7 @@ import { useAtomValue } from 'jotai';
import { getMemberDisplayName, trimReplyFromBody, trimReplyFromFormattedBody } from '$utils/room';
import { getMxIdLocalPart } from '$utils/matrix';
import { randomNumberBetween } from '$utils/common';
+import { sanitizeCustomHtml } from '$utils/sanitize';
import {
getReactCustomHtmlParser,
scaleSystemEmoji,
@@ -158,7 +159,8 @@ export const Reply = as<'div', ReplyProps>(
);
if (format === 'org.matrix.custom.html' && formattedBody) {
- const strippedHtml = trimReplyFromFormattedBody(formattedBody)
+ const safeFormattedBody = sanitizeCustomHtml(formattedBody);
+ const strippedHtml = trimReplyFromFormattedBody(safeFormattedBody)
.replaceAll(/
/gi, ' ')
.replaceAll(/<\/p>\s*]*>/gi, ' ')
.replaceAll(/<\/?p[^>]*>/gi, '')
diff --git a/src/app/components/message/modals/MessageForward.tsx b/src/app/components/message/modals/MessageForward.tsx
index 7e29f3d49..133dc940e 100644
--- a/src/app/components/message/modals/MessageForward.tsx
+++ b/src/app/components/message/modals/MessageForward.tsx
@@ -23,7 +23,7 @@ import { allRoomsAtom } from '$state/room-list/roomList';
import { useAllJoinedRoomsSet, useGetRoom } from '$hooks/useGetRoom';
import { factoryRoomIdByActivity } from '$utils/sort';
import * as css from '$features/room/message/styles.css';
-import { sanitizeCustomHtml } from '$utils/sanitize';
+import { sanitizeCustomHtml, sanitizeText } from '$utils/sanitize';
import { getStateEvents } from '$utils/room';
import { StateEvent } from '$types/matrix/room';
import { createDebugLogger } from '$utils/debugLogger';
@@ -206,12 +206,12 @@ export function MessageForwardInternal({
const safeHtml =
originalFormattedBody === undefined
- ? sanitizeCustomHtml(originalBody).replaceAll('\n', '
')
+ ? sanitizeText(originalBody).replaceAll('\n', '
')
: sanitizeCustomHtml(originalFormattedBody);
newBodyHtml =
`
` +
- `
${sanitizeCustomHtml(bodyModifText)}
` +
+ `
${sanitizeText(bodyModifText)}
` +
`
${safeHtml}
` +
`
`;
}
diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx
index 3b36b0d7f..3b2859e5c 100644
--- a/src/app/features/room/RoomInput.tsx
+++ b/src/app/features/room/RoomInput.tsx
@@ -143,7 +143,7 @@ import {
} from '$hooks/usePerMessageProfile';
import { Microphone, Stop } from '@phosphor-icons/react';
import { getSupportedAudioExtension } from '$plugins/voice-recorder-kit/supportedCodec';
-import { sanitizeCustomHtml } from '$utils/sanitize';
+import { sanitizeText } from '$utils/sanitize';
import { SchedulePickerDialog } from './schedule-send';
import * as css from './schedule-send/SchedulePickerDialog.css';
import {
@@ -783,7 +783,7 @@ export const RoomInput = forwardRef(
/**
* html escaped version of the display name
*/
- const escapedName = sanitizeCustomHtml(perMessageProfile.name);
+ const escapedName = sanitizeText(perMessageProfile.name);
const htmlPrefix = `${escapedName}: `;
diff --git a/src/app/features/room/message/MessageEditor.tsx b/src/app/features/room/message/MessageEditor.tsx
index 22c63ce26..ad25ba45f 100644
--- a/src/app/features/room/message/MessageEditor.tsx
+++ b/src/app/features/room/message/MessageEditor.tsx
@@ -72,7 +72,7 @@ import { HTMLReactParserOptions } from 'html-react-parser';
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
import { Opts as LinkifyOpts } from 'linkifyjs';
import { GetContentCallback } from '$types/matrix/room';
-import { sanitizeCustomHtml } from '$utils/sanitize';
+import { sanitizeText } from '$utils/sanitize';
type MessageEditorProps = {
roomId: string;
@@ -204,7 +204,7 @@ export const MessageEditor = as<'div', MessageEditorProps>(
plainText = bodyPrefix + plainText;
}
- const escapedName = sanitizeCustomHtml(pmpDisplayname);
+ const escapedName = sanitizeText(pmpDisplayname);
const htmlPrefix = `${escapedName}: `;
if (!customHtml.startsWith(htmlPrefix)) {
customHtml = htmlPrefix + customHtml;
diff --git a/src/app/plugins/react-custom-html-parser.test.tsx b/src/app/plugins/react-custom-html-parser.test.tsx
new file mode 100644
index 000000000..c72d1b4a6
--- /dev/null
+++ b/src/app/plugins/react-custom-html-parser.test.tsx
@@ -0,0 +1,58 @@
+import { render, screen } from '@testing-library/react';
+import parse from 'html-react-parser';
+import { describe, expect, it } from 'vitest';
+import { sanitizeCustomHtml } from '$utils/sanitize';
+import { getReactCustomHtmlParser, LINKIFY_OPTS } from './react-custom-html-parser';
+
+const createMatrixClient = () =>
+ ({
+ getRoom: () => undefined,
+ getUserId: () => '@me:example.com',
+ mxcUrlToHttp: () => null,
+ }) as any;
+
+describe('getReactCustomHtmlParser', () => {
+ it('translates Matrix color data attributes into rendered styles', () => {
+ const sanitizedHtml = sanitizeCustomHtml(
+ 'colored'
+ );
+
+ render(
+
+ {parse(
+ sanitizedHtml,
+ getReactCustomHtmlParser(createMatrixClient(), '!room:example.com', {
+ linkifyOpts: LINKIFY_OPTS,
+ })
+ )}
+
+ );
+
+ expect(screen.getByText('colored')).toHaveStyle({
+ color: 'rgb(255, 0, 0)',
+ backgroundColor: 'rgb(0, 255, 0)',
+ });
+ });
+
+ it('drops incoming style attributes even if unsanitized html reaches the parser', () => {
+ render(
+
+ {parse(
+ 'styled',
+ getReactCustomHtmlParser(createMatrixClient(), '!room:example.com', {
+ linkifyOpts: LINKIFY_OPTS,
+ })
+ )}
+
+ );
+
+ const styled = screen.getByText('styled');
+
+ expect(styled).toHaveStyle({
+ color: 'rgb(255, 0, 0)',
+ });
+ expect(styled).not.toHaveStyle({
+ backgroundColor: 'rgb(0, 255, 0)',
+ });
+ });
+});
diff --git a/src/app/plugins/react-custom-html-parser.tsx b/src/app/plugins/react-custom-html-parser.tsx
index 968850480..e583f7cab 100644
--- a/src/app/plugins/react-custom-html-parser.tsx
+++ b/src/app/plugins/react-custom-html-parser.tsx
@@ -1,5 +1,6 @@
/* eslint-disable jsx-a11y/alt-text */
import {
+ CSSProperties,
ComponentPropsWithoutRef,
lazy,
ReactEventHandler,
@@ -35,6 +36,7 @@ import { EMOJI_PATTERN, sanitizeForRegex, URL_NEG_LB } from '$utils/regex';
import { findAndReplace } from '$utils/findAndReplace';
import { onEnterOrSpace } from '$utils/keyboard';
import { copyToClipboard } from '$utils/dom';
+import { isMatrixHexColor } from '$utils/matrixHtml';
import { useTimeoutToggle } from '$hooks/useTimeoutToggle';
import { ClientSideHoverFreeze } from '$components/ClientSideHoverFreeze';
import {
@@ -68,6 +70,42 @@ export const safeDecodeUrl = (url: string) => {
}
};
+const getMatrixColorStyle = (attribs: Record): CSSProperties | undefined => {
+ const color = attribs['data-mx-color'];
+ const backgroundColor = attribs['data-mx-bg-color'];
+
+ const style: CSSProperties = {};
+
+ if (typeof color === 'string' && isMatrixHexColor(color)) {
+ style.color = color;
+ }
+
+ if (typeof backgroundColor === 'string' && isMatrixHexColor(backgroundColor)) {
+ style.backgroundColor = backgroundColor;
+ }
+
+ return Object.keys(style).length > 0 ? style : undefined;
+};
+
+const stripIncomingStyle = (
+ attribs: Record
+): Omit, 'style'> => {
+ const { style, ...props } = attributesToProps(attribs);
+
+ return props;
+};
+
+const ensureNoopenerRel = (rel: unknown): string => {
+ if (typeof rel !== 'string') return 'noopener';
+
+ const parts = rel.split(/\s+/).filter(Boolean);
+ if (!parts.includes('noopener')) {
+ parts.push('noopener');
+ }
+
+ return parts.join(' ');
+};
+
export const makeMentionCustomProps = (
handleMentionClick?: ReactEventHandler,
content?: string
@@ -363,7 +401,8 @@ export const getReactCustomHtmlParser = (
if (domNode instanceof Element && 'name' in domNode) {
const { name, attribs, children, parent } = domNode;
const renderChildren = () => domToReact(children as any, opts);
- const props = attributesToProps(attribs);
+ const props = stripIncomingStyle(attribs);
+ const matrixColorStyle = getMatrixColorStyle(attribs);
if (name === 'h1') {
return (
@@ -494,8 +533,13 @@ export const getReactCustomHtmlParser = (
if (name === 'a' && typeof props.href === 'string') {
const encodedHref = props.href;
const decodedHref = encodedHref && safeDecodeUrl(encodedHref);
+ const anchorProps = {
+ ...props,
+ rel: ensureNoopenerRel(props.rel),
+ };
+
if (!decodedHref || !testMatrixTo(decodedHref)) {
- return undefined;
+ return {renderChildren()};
}
const content = children.find((child) => !(child instanceof DOMText))
@@ -523,13 +567,21 @@ export const getReactCustomHtmlParser = (
onClick={params.handleSpoilerClick}
className={css.Spoiler()}
aria-pressed
- style={{ cursor: 'pointer' }}
+ style={{ ...matrixColorStyle, cursor: 'pointer' }}
>
{renderChildren()}
);
}
+ if (name === 'span' && matrixColorStyle) {
+ return (
+
+ {renderChildren()}
+
+ );
+ }
+
if (name === 'img') {
// Guard: img without a src survives sanitisation (fix for crash #1731)
// but we can't convert it — skip rendering rather than passing
diff --git a/src/app/utils/matrixHtml.ts b/src/app/utils/matrixHtml.ts
new file mode 100644
index 000000000..0176c804d
--- /dev/null
+++ b/src/app/utils/matrixHtml.ts
@@ -0,0 +1,5 @@
+export const MATRIX_HEX_COLOR_REGEX = /^#[0-9a-fA-F]{6}$/;
+
+export function isMatrixHexColor(value: string): boolean {
+ return MATRIX_HEX_COLOR_REGEX.test(value);
+}
diff --git a/src/app/utils/sanitize.test.ts b/src/app/utils/sanitize.test.ts
index 52c668e6b..5484e0ecb 100644
--- a/src/app/utils/sanitize.test.ts
+++ b/src/app/utils/sanitize.test.ts
@@ -1,124 +1,117 @@
-// Tests for sanitizeCustomHtml — security-critical: strips dangerous content from
-// user-supplied Matrix message HTML before rendering.
-import { describe, it, expect } from 'vitest';
+import { describe, expect, it } from 'vitest';
import { sanitizeCustomHtml } from './sanitize';
-describe('sanitizeCustomHtml – tag allowlist', () => {
- it('passes through permitted tags', () => {
- expect(sanitizeCustomHtml('bold')).toBe('bold');
- expect(sanitizeCustomHtml('italic')).toBe('italic');
- expect(sanitizeCustomHtml('snippet')).toBe('snippet');
- });
-
- it('strips disallowed tags but keeps their text content', () => {
- const result = sanitizeCustomHtml('');
- expect(result).not.toContain('