Merge branch 'dev' into feat/compat/pluralkit
This commit is contained in:
25 files changed
+735
-173
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
fix [accidental leaking of private nicknames](https://github.com/SableClient/Sable/issues/362) for users to be included in the message
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Tighten sliding sync memory management: stop the polling loop on client dispose, persist then prune large room timelines when leaving a room, remove adaptive timeline-limit logic, and auto-unsubscribe when the local user leaves or is banned from a room.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Fix thread drawer showing no messages when using classic sync.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Hide the redundant "Thread" indicator badge in the compose box when inside the Thread Drawer.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Reduce dead space around the root message in the thread drawer.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Reduced the opacity of mention highlight backgrounds to be less visually intrusive while remaining noticeable.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: minor
|
||||
---
|
||||
|
||||
# Update calls to have RNNoise noise suppression.
|
||||
@@ -16,7 +16,7 @@ You can also download our desktop app for windows and linux from [releases](http
|
||||
## Self-hosting
|
||||
You have a few options for self hosting, you can:
|
||||
1. Run the prebuilt docker container.
|
||||
2. Deploy on a site like GitLab Pages. Jae has a [guide here](https://docs.j4.lc/Public+documentation/Tutorials/Deploying+Sable+on+GitLab+Pages).
|
||||
2. Deploy on a site like GitLab Pages. Jae has a [guide here](https://docs.j4.lc/Tutorials/Deploying-Sable-on-GitLab-Pages).
|
||||
3. Build it yourself.
|
||||
|
||||
### Docker
|
||||
@@ -85,4 +85,4 @@ pnpm run build # Compiles the app into the dist/ directory
|
||||
|
||||
## Deployment and infrastructure
|
||||
Deployment workflows and infrastructure details live in
|
||||
[`infra/README.md`](infra/README.md).
|
||||
[`infra/README.md`](infra/README.md).
|
||||
+2
-2
@@ -95,7 +95,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@cloudflare/vite-plugin": "^1.26.0",
|
||||
"@sableclient/sable-call-embedded": "v1.1.3",
|
||||
"@sableclient/sable-call-embedded": "v1.1.4",
|
||||
"@esbuild-plugins/node-globals-polyfill": "^0.2.3",
|
||||
"@eslint/compat": "2.0.2",
|
||||
"@eslint/js": "9.39.3",
|
||||
@@ -137,4 +137,4 @@
|
||||
"vitest": "^4.1.0",
|
||||
"wrangler": "^4.70.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
+5
-5
@@ -222,8 +222,8 @@ importers:
|
||||
specifier: ^6.2.2
|
||||
version: 6.2.2([email protected])
|
||||
'@sableclient/sable-call-embedded':
|
||||
specifier: v1.1.3
|
||||
version: 1.1.3
|
||||
specifier: v1.1.4
|
||||
version: 1.1.4
|
||||
'@sentry/vite-plugin':
|
||||
specifier: ^5.1.1
|
||||
version: 5.1.1([email protected])
|
||||
@@ -2426,8 +2426,8 @@ packages:
|
||||
'@rtsao/[email protected]':
|
||||
resolution: {integrity: sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==}
|
||||
|
||||
'@sableclient/[email protected].3':
|
||||
resolution: {integrity: sha512-HNxppMEF8am6qhABbvJNc2mlkex7SntUeAMATOoNo2QkiTrutrJ9LPWy0TZskjAp++RrSpEpypKcN3MmOlZEWA==}
|
||||
'@sableclient/[email protected].4':
|
||||
resolution: {integrity: sha512-XLRcbUPcn7i3QKZAPjIfUkUEXP0E4DOr0dyRoVCWMjHWj28kq+T7jeB2fRr5lB77olBwNHMjIuoTwrv02xiepQ==}
|
||||
|
||||
'@sentry-internal/[email protected]':
|
||||
resolution: {integrity: sha512-8zYTnzhAPvNkVH1Irs62wl0J/c+0QcJ62TonKnzpSFUUD3V5qz8YDZbjIDGfxy+1EB9fO0sxtddKCzwTHF/MbQ==}
|
||||
@@ -8119,7 +8119,7 @@ snapshots:
|
||||
|
||||
'@rtsao/[email protected]': {}
|
||||
|
||||
'@sableclient/[email protected].3': {}
|
||||
'@sableclient/[email protected].4': {}
|
||||
|
||||
'@sentry-internal/[email protected]':
|
||||
dependencies:
|
||||
|
||||
@@ -17,6 +17,14 @@ export type OutputOptions = {
|
||||
allowTextFormatting?: boolean;
|
||||
allowInlineMarkdown?: boolean;
|
||||
allowBlockMarkdown?: boolean;
|
||||
/**
|
||||
* if true it will remove the nickname of the person from the message
|
||||
*/
|
||||
stripNickname?: boolean;
|
||||
/**
|
||||
* a map of regex patterns to replace nicknames with, used when stripNickname is true
|
||||
*/
|
||||
nickNameReplacement?: Map<RegExp, string>;
|
||||
};
|
||||
|
||||
const textToCustomHtml = (node: Text, opts: OutputOptions): string => {
|
||||
@@ -99,6 +107,12 @@ const ignoreHTMLParseInlineMD = (text: string): string =>
|
||||
(txt) => parseInlineMD(txt)
|
||||
).join('');
|
||||
|
||||
/**
|
||||
* convert slate internal representation to a custom HTML string that can be sent to the server
|
||||
* @param node slate node
|
||||
* @param opts options for output
|
||||
* @returns custom HTML string
|
||||
*/
|
||||
export const toMatrixCustomHTML = (
|
||||
node: Descendant | Descendant[],
|
||||
opts: OutputOptions
|
||||
@@ -106,7 +120,7 @@ export const toMatrixCustomHTML = (
|
||||
let markdownLines = '';
|
||||
const parseNode = (n: Descendant, index: number, targetNodes: Descendant[]) => {
|
||||
if (opts.allowBlockMarkdown && 'type' in n && n.type === BlockType.Paragraph) {
|
||||
const line = toMatrixCustomHTML(n, {
|
||||
let line = toMatrixCustomHTML(n, {
|
||||
...opts,
|
||||
allowInlineMarkdown: false,
|
||||
allowBlockMarkdown: false,
|
||||
@@ -114,6 +128,13 @@ export const toMatrixCustomHTML = (
|
||||
.replace(/<br\/>$/, '\n')
|
||||
.replace(/^(\\*)>/, '$1>');
|
||||
|
||||
// strip nicknames if needed
|
||||
if (opts.stripNickname && opts.nickNameReplacement) {
|
||||
opts.nickNameReplacement?.keys().forEach((key) => {
|
||||
const replacement = opts.nickNameReplacement!.get(key) ?? '';
|
||||
line = line.replaceAll(key, replacement);
|
||||
});
|
||||
}
|
||||
markdownLines += line;
|
||||
if (index === targetNodes.length - 1) {
|
||||
return parseBlockMD(markdownLines, ignoreHTMLParseInlineMD);
|
||||
@@ -175,12 +196,37 @@ const elementToPlainText = (node: CustomElement, children: string): string => {
|
||||
}
|
||||
};
|
||||
|
||||
export const toPlainText = (node: Descendant | Descendant[], isMarkdown: boolean): string => {
|
||||
if (Array.isArray(node)) return node.map((n) => toPlainText(n, isMarkdown)).join('');
|
||||
if (Text.isText(node))
|
||||
/**
|
||||
* convert slate internal representation to a plain text string that can be sent to the server
|
||||
* @param node the slate node
|
||||
* @param isMarkdown set true if it's a markdown formatted text
|
||||
* @param stripNickname whether to strip nicknames
|
||||
* @param nickNameReplacement the nickname replacement
|
||||
* @returns the plain text we want to send
|
||||
*/
|
||||
export const toPlainText = (
|
||||
node: Descendant | Descendant[],
|
||||
isMarkdown: boolean,
|
||||
stripNickname = false,
|
||||
nickNameReplacement?: Map<RegExp, string>
|
||||
): string => {
|
||||
if (Array.isArray(node))
|
||||
return node.map((n) => toPlainText(n, isMarkdown, stripNickname, nickNameReplacement)).join('');
|
||||
if (Text.isText(node)) {
|
||||
if (stripNickname && nickNameReplacement) {
|
||||
let { text } = node;
|
||||
nickNameReplacement?.keys().forEach((key) => {
|
||||
const replacement = nickNameReplacement.get(key) ?? '';
|
||||
text = text.replaceAll(key, replacement);
|
||||
});
|
||||
return isMarkdown
|
||||
? unescapeMarkdownBlockSequences(text, unescapeMarkdownInlineSequences)
|
||||
: text;
|
||||
}
|
||||
return isMarkdown
|
||||
? unescapeMarkdownBlockSequences(node.text, unescapeMarkdownInlineSequences)
|
||||
: node.text;
|
||||
}
|
||||
|
||||
const children = node.children.map((n) => toPlainText(n, isMarkdown)).join('');
|
||||
return elementToPlainText(node, children);
|
||||
@@ -208,10 +254,27 @@ export const trimCommand = (cmdName: string, str: string) => {
|
||||
return str.slice(match[0].length);
|
||||
};
|
||||
|
||||
/**
|
||||
* Type representing Mentions
|
||||
*/
|
||||
export type MentionsData = {
|
||||
/**
|
||||
* a boolean to denote if it's a room mention
|
||||
*/
|
||||
room: boolean;
|
||||
/**
|
||||
* a set of user ids that are mentioned in the message
|
||||
*/
|
||||
users: Set<string>;
|
||||
};
|
||||
|
||||
/**
|
||||
* get the mentions in a message
|
||||
* @param mx the matrix client
|
||||
* @param roomId the room id we will send the message in
|
||||
* @param editor the slate editor
|
||||
* @returns the mentions in a message {@link MentionsData}
|
||||
*/
|
||||
export const getMentions = (mx: MatrixClient, roomId: string, editor: Editor): MentionsData => {
|
||||
const mentionData: MentionsData = {
|
||||
room: false,
|
||||
|
||||
@@ -21,6 +21,7 @@ import { FALLBACK_MIMETYPE, getBlobSafeMimeType } from '$utils/mimeTypes';
|
||||
import { parseGeoUri, scaleYDimension } from '$utils/common';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import { PerMessageProfileBeeperFormat } from '$hooks/usePerMessageProfile';
|
||||
import { Attachment, AttachmentBox, AttachmentContent, AttachmentHeader } from './attachment';
|
||||
import { FileHeader, FileDownloadButton } from './FileHeader';
|
||||
import {
|
||||
@@ -109,6 +110,15 @@ export function MText({ edited, content, renderBody, renderUrlsPreview, style }:
|
||||
const forwardMeta = content['moe.sable.message.forward'];
|
||||
return typeof forwardMeta === 'object';
|
||||
}, [content]);
|
||||
|
||||
/**
|
||||
* For the unwrapping of per-message profile fallbacks, we look for <strong> tags with the data-mx-profile-fallback attribute
|
||||
*/
|
||||
const unwrappedPerMessageProfileMessage = useMemo(
|
||||
() => customBody?.replace(/<strong[^>]*data-mx-profile-fallback[^>]*>(.*?):\s*<\/strong>/i, ''),
|
||||
[customBody]
|
||||
);
|
||||
|
||||
const isJumbo = useMemo(() => {
|
||||
if (!trimmedBody || trimmedBody.length >= 500) return false;
|
||||
if (!JUMBO_EMOJI_REG.test(trimmedBody)) return false;
|
||||
@@ -126,6 +136,19 @@ export function MText({ edited, content, renderBody, renderUrlsPreview, style }:
|
||||
const urlsMatch = renderUrlsPreview && trimmedBody.match(URL_REG);
|
||||
const urls = urlsMatch ? [...new Set(urlsMatch)] : undefined;
|
||||
|
||||
if ((content['com.beeper.per_message_profile'] as PerMessageProfileBeeperFormat)?.has_fallback) {
|
||||
// unwrap per-message profile fallback if present
|
||||
return (
|
||||
<MessageTextBody preWrap={typeof customBody !== 'string'} style={style}>
|
||||
{renderBody({
|
||||
body: trimmedBody,
|
||||
customBody: unwrappedPerMessageProfileMessage,
|
||||
})}
|
||||
{edited && <MessageEditedContent />}
|
||||
</MessageTextBody>
|
||||
);
|
||||
}
|
||||
|
||||
if (isForwarded && unwrappedForwardedContent) {
|
||||
return (
|
||||
<MessageTextBody preWrap={typeof unwrappedForwardedContent !== 'string'} style={style}>
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Tests for the ThreadIndicator visibility condition in the compose strip.
|
||||
*
|
||||
* The indicator renders when a user is replying to a thread message from the
|
||||
* main timeline (no threadRootId). It must NOT appear when composing inside
|
||||
* the ThreadDrawer (threadRootId is set), because the drawer already makes the
|
||||
* thread context obvious.
|
||||
*
|
||||
* Mirrors the exact render guard in RoomInput.tsx:
|
||||
* {replyDraft.relation?.rel_type === RelationType.Thread && !threadRootId && (
|
||||
* <ThreadIndicator />
|
||||
* )}
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { RelationType } from '$types/matrix-sdk';
|
||||
import { ThreadIndicator } from './Reply';
|
||||
|
||||
function Subject({ relType, threadRootId }: { relType?: string; threadRootId?: string }) {
|
||||
return <>{relType === RelationType.Thread && !threadRootId && <ThreadIndicator />}</>;
|
||||
}
|
||||
|
||||
describe('ThreadIndicator visibility in compose strip', () => {
|
||||
it('renders in the main timeline compose box when a thread relation is active', () => {
|
||||
render(<Subject relType={RelationType.Thread} />);
|
||||
expect(screen.getByText('Thread')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('is hidden inside the ThreadDrawer when threadRootId is set', () => {
|
||||
render(<Subject relType={RelationType.Thread} threadRootId="$root:example.com" />);
|
||||
expect(screen.queryByText('Thread')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('is hidden when the draft has no relation', () => {
|
||||
render(<Subject relType={undefined} />);
|
||||
expect(screen.queryByText('Thread')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('is hidden for a non-thread relation type', () => {
|
||||
render(<Subject relType="m.in_reply_to" />);
|
||||
expect(screen.queryByText('Thread')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -204,7 +204,10 @@ export const ImageContent = as<'div', ImageContentProps>(
|
||||
src: srcState.data,
|
||||
onLoad: handleLoad,
|
||||
onError: handleError,
|
||||
onClick: () => setViewer(true),
|
||||
onClick: () => {
|
||||
setIsHovered(false);
|
||||
setViewer(true);
|
||||
},
|
||||
tabIndex: 0,
|
||||
})}
|
||||
</Box>
|
||||
|
||||
@@ -67,11 +67,11 @@ const HighlightVariant = styleVariants({
|
||||
|
||||
const NotifyHighlightVariant = styleVariants({
|
||||
silent: {
|
||||
backgroundColor: color.Secondary.Container,
|
||||
backgroundColor: `color-mix(in srgb, ${color.Secondary.Container} 25%, transparent)`,
|
||||
boxShadow: `inset ${config.borderWidth.B700} 0 0 ${color.Secondary.ContainerLine}`,
|
||||
},
|
||||
loud: {
|
||||
backgroundColor: color.Warning.Container,
|
||||
backgroundColor: `color-mix(in srgb, ${color.Warning.Container} 25%, transparent)`,
|
||||
boxShadow: `inset ${config.borderWidth.B700} 0 0 ${color.Warning.ContainerLine}`,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -445,11 +445,8 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
|
||||
Proxy: {syncDiagnostics.sliding.proxyBaseUrl}
|
||||
</Text>
|
||||
<Text size="T200">
|
||||
Room timeline: {syncDiagnostics.sliding.timelineLimit}
|
||||
{syncDiagnostics.sliding.adaptiveTimeline
|
||||
? ' (adaptive)'
|
||||
: ''}{' '}
|
||||
| page size: {syncDiagnostics.sliding.listPageSize}
|
||||
Room timeline: {syncDiagnostics.sliding.timelineLimit} | page
|
||||
size: {syncDiagnostics.sliding.listPageSize}
|
||||
</Text>
|
||||
</>
|
||||
) : (
|
||||
|
||||
@@ -159,6 +159,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 { SchedulePickerDialog } from './schedule-send';
|
||||
import * as css from './schedule-send/SchedulePickerDialog.css';
|
||||
import {
|
||||
@@ -261,6 +262,10 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
const emojiBtnRef = useRef<HTMLButtonElement>(null);
|
||||
const micBtnRef = useRef<HTMLButtonElement>(null);
|
||||
const roomToParents = useAtomValue(roomToParentsAtom);
|
||||
/**
|
||||
* Nickname someone set for another user
|
||||
* this nickname should be treated as private
|
||||
*/
|
||||
const nicknames = useAtomValue(nicknamesAtom);
|
||||
|
||||
const powerLevels = usePowerLevelsContext();
|
||||
@@ -384,6 +389,9 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
let replyBodyJSX: ReactNode = replyDraft ? trimReplyFromBody(replyDraft.body) : null;
|
||||
|
||||
if (htmlBody) {
|
||||
/**
|
||||
* message with linebreaks, etc stripped
|
||||
*/
|
||||
const strippedHtml = trimReplyFromFormattedBody(htmlBody)
|
||||
.replaceAll(/<br\s*\/?>/gi, ' ')
|
||||
.replaceAll(/<\/p>\s*<p[^>]*>/gi, ' ')
|
||||
@@ -632,12 +640,65 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
uploadBoardHandlers.current?.handleSend();
|
||||
|
||||
const commandName = getBeginCommand(editor);
|
||||
let plainText = toPlainText(editor.children, isMarkdown).trim();
|
||||
/**
|
||||
* a map of regex patterns to replace nicknames with,
|
||||
* used when stripNickname is true in toMatrixCustomHTML
|
||||
* during HTML generation for the message content.
|
||||
* This is necessary because the HTML generation needs to know
|
||||
* which nicknames to strip in order to generate the correct formatted_body,
|
||||
* and the plain text generation needs to replace those same nicknames with
|
||||
* the original user IDs so that the message content remains consistent and
|
||||
* mentions are correctly processed by the server and clients.
|
||||
*/
|
||||
const nicknameReplacement = new Map<RegExp, string>();
|
||||
if (replyEvent) {
|
||||
/**
|
||||
* the id of the user being replied to,
|
||||
* whose nickname (if any) should be stripped
|
||||
* from the message content and replaced with their
|
||||
* user ID for correct mention processing
|
||||
*/
|
||||
const senderId = replyEvent.getSender();
|
||||
if (senderId) {
|
||||
const nick = nicknames[senderId];
|
||||
if (typeof nick === 'string' && nick.length > 0) {
|
||||
nicknameReplacement.set(
|
||||
new RegExp(`@?${nick}`, 'g'),
|
||||
room.getMember(senderId)?.rawDisplayName ?? senderId
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* any other users mentioned in the message being replied to,
|
||||
* whose nicknames should also be stripped and replaced with user IDs
|
||||
*/
|
||||
const mentions = getMentions(mx, roomId, editor);
|
||||
if (mentions?.users) {
|
||||
mentions.users.forEach((id) => {
|
||||
const nick = nicknames[id];
|
||||
if (typeof nick === 'string' && nick.length > 0) {
|
||||
nicknameReplacement.set(
|
||||
new RegExp(`@?${nick}`, 'g'),
|
||||
room.getMember(id)?.rawDisplayName ?? id
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* the plain text we will send
|
||||
*/
|
||||
let plainText = toPlainText(editor.children, isMarkdown, true, nicknameReplacement).trim();
|
||||
/**
|
||||
* the html we will send
|
||||
*/
|
||||
let customHtml = trimCustomHtml(
|
||||
toMatrixCustomHTML(editor.children, {
|
||||
allowTextFormatting: true,
|
||||
allowBlockMarkdown: isMarkdown,
|
||||
allowInlineMarkdown: isMarkdown,
|
||||
stripNickname: true,
|
||||
nickNameReplacement: nicknameReplacement,
|
||||
})
|
||||
);
|
||||
let msgType = MsgType.Text;
|
||||
@@ -688,18 +749,6 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
body,
|
||||
};
|
||||
|
||||
/**
|
||||
* the currently with the room associated per-message profile, if any, so that it can be included in the message content when sending.
|
||||
* 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);
|
||||
|
||||
if (perMessageProfile) {
|
||||
content['com.beeper.per_message_profile'] =
|
||||
convertPerMessageProfileToBeeperFormat(perMessageProfile);
|
||||
}
|
||||
|
||||
if (replyDraft && !silentReply) {
|
||||
mentionData.users.add(replyDraft.userId);
|
||||
}
|
||||
@@ -710,6 +759,42 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
content.format = 'org.matrix.custom.html';
|
||||
content.formatted_body = formattedBody;
|
||||
}
|
||||
|
||||
/**
|
||||
* the currently with the room associated per-message profile, if any, so that it can be included in the message content when sending.
|
||||
* 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);
|
||||
|
||||
if (perMessageProfile) {
|
||||
content['com.beeper.per_message_profile'] =
|
||||
convertPerMessageProfileToBeeperFormat(perMessageProfile);
|
||||
|
||||
// if a per-message profile is used, it must per spec include a fallback
|
||||
const prefix = `${perMessageProfile.name}: `;
|
||||
|
||||
if (!content.body.startsWith(prefix)) {
|
||||
// to prevent double-prefixing when the fallback is already present
|
||||
content.body = prefix + content.body;
|
||||
}
|
||||
|
||||
/**
|
||||
* html escaped version of the display name
|
||||
*/
|
||||
const escapedName = sanitizeCustomHtml(perMessageProfile.name);
|
||||
|
||||
const htmlPrefix = `<strong data-mx-profile-fallback>${escapedName}: </strong>`;
|
||||
|
||||
if (content.formatted_body && !content.formatted_body.startsWith(htmlPrefix)) {
|
||||
content.formatted_body = htmlPrefix + content.formatted_body;
|
||||
} else {
|
||||
// we don't have a formatted body, but we need one
|
||||
content.format = 'org.matrix.custom.html';
|
||||
content.formatted_body = `${htmlPrefix}${plainText}`;
|
||||
}
|
||||
}
|
||||
|
||||
if (replyDraft) {
|
||||
content['m.relates_to'] = getReplyContent(replyDraft, room);
|
||||
}
|
||||
@@ -806,6 +891,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
}
|
||||
}, [
|
||||
editor,
|
||||
replyEvent,
|
||||
isMarkdown,
|
||||
canSendReaction,
|
||||
mx,
|
||||
@@ -814,6 +900,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
silentReply,
|
||||
scheduledTime,
|
||||
editingScheduledDelayId,
|
||||
nicknames,
|
||||
handleQuickReact,
|
||||
commands,
|
||||
sendTypingStatus,
|
||||
@@ -1170,7 +1257,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
grow="Yes"
|
||||
style={{ minWidth: 0 }}
|
||||
>
|
||||
{replyDraft.relation?.rel_type === RelationType.Thread && (
|
||||
{replyDraft.relation?.rel_type === RelationType.Thread && !threadRootId && (
|
||||
<ThreadIndicator />
|
||||
)}
|
||||
<ReplyLayout
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* Unit tests for getThreadReplyEvents — the function that decides which events
|
||||
* to display as replies in the thread drawer.
|
||||
*
|
||||
* The bug these tests cover (classic-sync empty thread):
|
||||
* room.createThread(id, root, [], false) creates a Thread whose .events array
|
||||
* contains only the root event. After filtering out the root, the old code
|
||||
* checked `if (fromThread.length > 0)` on the un-filtered array — which was
|
||||
* truthy — and returned an empty list instead of falling back to the live
|
||||
* timeline. The fix: filter first, then check.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { RelationType } from '$types/matrix-sdk';
|
||||
import { getThreadReplyEvents } from './ThreadDrawer';
|
||||
|
||||
// ── Minimal MatrixEvent factory ───────────────────────────────────────────────
|
||||
|
||||
type EventInit = {
|
||||
id: string;
|
||||
threadRootId?: string;
|
||||
/** When set, the event is treated as a reaction/annotation */
|
||||
relType?: string;
|
||||
};
|
||||
|
||||
function makeEvent({ id, threadRootId, relType }: EventInit) {
|
||||
return {
|
||||
getId: () => id,
|
||||
threadRootId,
|
||||
getRelation: () => (relType ? { rel_type: relType } : null),
|
||||
getContent: () => ({}),
|
||||
};
|
||||
}
|
||||
|
||||
// ── Minimal Room factory ──────────────────────────────────────────────────────
|
||||
|
||||
type RoomInit = {
|
||||
thread?: { events: ReturnType<typeof makeEvent>[] } | null;
|
||||
liveEvents?: ReturnType<typeof makeEvent>[];
|
||||
};
|
||||
|
||||
function makeRoom({ thread = null, liveEvents = [] }: RoomInit) {
|
||||
return {
|
||||
getThread: () => thread,
|
||||
getUnfilteredTimelineSet: () => ({
|
||||
getLiveTimeline: () => ({
|
||||
getEvents: () => liveEvents,
|
||||
}),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
// ── Tests ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
const ROOT_ID = '$root-event-id';
|
||||
const REPLY_ID = '$reply-event-id';
|
||||
const REACTION_ID = '$reaction-event-id';
|
||||
|
||||
describe('getThreadReplyEvents', () => {
|
||||
it('returns thread events minus the root when the Thread object has replies', () => {
|
||||
const rootEvent = makeEvent({ id: ROOT_ID, threadRootId: ROOT_ID });
|
||||
const replyEvent = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID });
|
||||
|
||||
const room = makeRoom({
|
||||
thread: { events: [rootEvent, replyEvent] as any },
|
||||
liveEvents: [],
|
||||
});
|
||||
|
||||
const result = getThreadReplyEvents(room as any, ROOT_ID);
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].getId()).toBe(REPLY_ID);
|
||||
});
|
||||
|
||||
it('excludes reactions from thread events', () => {
|
||||
const rootEvent = makeEvent({ id: ROOT_ID, threadRootId: ROOT_ID });
|
||||
const replyEvent = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID });
|
||||
const reactionEvent = makeEvent({
|
||||
id: REACTION_ID,
|
||||
threadRootId: ROOT_ID,
|
||||
relType: RelationType.Annotation,
|
||||
});
|
||||
|
||||
const room = makeRoom({
|
||||
thread: { events: [rootEvent, replyEvent, reactionEvent] as any },
|
||||
liveEvents: [],
|
||||
});
|
||||
|
||||
const result = getThreadReplyEvents(room as any, ROOT_ID);
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].getId()).toBe(REPLY_ID);
|
||||
});
|
||||
|
||||
// ── Classic-sync empty-thread regression ──────────────────────────────────
|
||||
|
||||
it('falls back to the live timeline when thread.events contains only the root (classic-sync case)', () => {
|
||||
// classic sync: thread created with no initialEvents → events = [rootEvent]
|
||||
const rootEvent = makeEvent({ id: ROOT_ID, threadRootId: ROOT_ID });
|
||||
const liveReply = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID });
|
||||
|
||||
const room = makeRoom({
|
||||
thread: { events: [rootEvent] as any },
|
||||
liveEvents: [liveReply as any],
|
||||
});
|
||||
|
||||
const result = getThreadReplyEvents(room as any, ROOT_ID);
|
||||
|
||||
// Without the fix: `fromThread.length > 0` was truthy → returned filtered
|
||||
// empty array. With the fix: filtered array is empty → falls back to live.
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].getId()).toBe(REPLY_ID);
|
||||
});
|
||||
|
||||
it('falls back to the live timeline when there is no Thread object at all', () => {
|
||||
const liveReply = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID });
|
||||
|
||||
const room = makeRoom({
|
||||
thread: null,
|
||||
liveEvents: [liveReply as any],
|
||||
});
|
||||
|
||||
const result = getThreadReplyEvents(room as any, ROOT_ID);
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].getId()).toBe(REPLY_ID);
|
||||
});
|
||||
|
||||
it('excludes events from the live timeline that belong to a different thread', () => {
|
||||
const otherReply = makeEvent({ id: '$other-reply', threadRootId: '$other-root' });
|
||||
const ourReply = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID });
|
||||
|
||||
const room = makeRoom({
|
||||
thread: null,
|
||||
liveEvents: [otherReply as any, ourReply as any],
|
||||
});
|
||||
|
||||
const result = getThreadReplyEvents(room as any, ROOT_ID);
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].getId()).toBe(REPLY_ID);
|
||||
});
|
||||
|
||||
it('returns an empty array when neither the thread nor the live timeline has replies', () => {
|
||||
const rootEvent = makeEvent({ id: ROOT_ID, threadRootId: ROOT_ID });
|
||||
|
||||
const room = makeRoom({
|
||||
thread: { events: [rootEvent] as any },
|
||||
liveEvents: [],
|
||||
});
|
||||
|
||||
const result = getThreadReplyEvents(room as any, ROOT_ID);
|
||||
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -54,6 +54,36 @@ import { RoomInput } from './RoomInput';
|
||||
import { RoomViewFollowing, RoomViewFollowingPlaceholder } from './RoomViewFollowing';
|
||||
import * as css from './ThreadDrawer.css';
|
||||
|
||||
/**
|
||||
* Resolve the list of reply events to show in the thread drawer.
|
||||
*
|
||||
* Prefers events from the SDK Thread object (authoritative, full history) but
|
||||
* falls back to scanning the main room timeline when the Thread object was
|
||||
* created without `initialEvents` (as happens with classic sync). In that
|
||||
* case `thread.events` contains only the root event, so filtering it yields an
|
||||
* empty array — we must fall back rather than showing nothing.
|
||||
*
|
||||
* Exported for unit testing.
|
||||
*/
|
||||
export function getThreadReplyEvents(room: Room, threadRootId: string): MatrixEvent[] {
|
||||
const thread = room.getThread(threadRootId);
|
||||
const fromThread = thread?.events ?? [];
|
||||
const filteredFromThread = fromThread.filter(
|
||||
(ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev)
|
||||
);
|
||||
if (filteredFromThread.length > 0) {
|
||||
return filteredFromThread;
|
||||
}
|
||||
return room
|
||||
.getUnfilteredTimelineSet()
|
||||
.getLiveTimeline()
|
||||
.getEvents()
|
||||
.filter(
|
||||
(ev) =>
|
||||
ev.threadRootId === threadRootId && ev.getId() !== threadRootId && !reactionOrEditEvent(ev)
|
||||
);
|
||||
}
|
||||
|
||||
type ForwardedMessageProps = {
|
||||
isForwarded: boolean;
|
||||
originalTimestamp: number;
|
||||
@@ -398,6 +428,33 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
|
||||
|
||||
const rootEvent = room.findEventById(threadRootId);
|
||||
|
||||
// When the drawer is opened with classic sync, room.createThread() may have
|
||||
// been called with empty initialEvents so thread.events only has the root.
|
||||
// Backfill events from the main room timeline into the Thread object so the
|
||||
// authoritative source is populated for subsequent renders and receipts.
|
||||
useEffect(() => {
|
||||
const thread = room.getThread(threadRootId);
|
||||
if (!thread) return;
|
||||
const hasRepliesInThread = thread.events.some(
|
||||
(ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev)
|
||||
);
|
||||
if (hasRepliesInThread) return; // already populated, nothing to do
|
||||
|
||||
const liveEvents = room
|
||||
.getUnfilteredTimelineSet()
|
||||
.getLiveTimeline()
|
||||
.getEvents()
|
||||
.filter(
|
||||
(ev) =>
|
||||
ev.threadRootId === threadRootId &&
|
||||
ev.getId() !== threadRootId &&
|
||||
!reactionOrEditEvent(ev)
|
||||
);
|
||||
if (liveEvents.length > 0) {
|
||||
thread.addEvents(liveEvents, false);
|
||||
}
|
||||
}, [room, threadRootId]);
|
||||
|
||||
// Re-render when new thread events arrive (including reactions via ThreadEvent.Update).
|
||||
useEffect(() => {
|
||||
const isEventInThread = (mEvent: MatrixEvent): boolean => {
|
||||
@@ -481,26 +538,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
|
||||
markThreadAsRead();
|
||||
}, [mx, room, threadRootId, forceUpdate]);
|
||||
|
||||
// Use the Thread object if available (authoritative source with full history).
|
||||
// Fall back to scanning the live room timeline for local echoes and the
|
||||
// window before the Thread object is registered by the SDK.
|
||||
const replyEvents: MatrixEvent[] = (() => {
|
||||
const thread = room.getThread(threadRootId);
|
||||
const fromThread = thread?.events ?? [];
|
||||
if (fromThread.length > 0) {
|
||||
return fromThread.filter((ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev));
|
||||
}
|
||||
return room
|
||||
.getUnfilteredTimelineSet()
|
||||
.getLiveTimeline()
|
||||
.getEvents()
|
||||
.filter(
|
||||
(ev) =>
|
||||
ev.threadRootId === threadRootId &&
|
||||
ev.getId() !== threadRootId &&
|
||||
!reactionOrEditEvent(ev)
|
||||
);
|
||||
})();
|
||||
const replyEvents = getThreadReplyEvents(room, threadRootId);
|
||||
|
||||
replyEventsRef.current = replyEvents;
|
||||
|
||||
@@ -722,7 +760,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
|
||||
variant="Background"
|
||||
visibility="Hover"
|
||||
direction="Vertical"
|
||||
hideTrack={false}
|
||||
hideTrack
|
||||
style={{
|
||||
maxHeight: '200px',
|
||||
height: 'fit-content',
|
||||
@@ -733,7 +771,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
|
||||
className={css.messageList}
|
||||
direction="Column"
|
||||
style={{
|
||||
padding: `${config.space.S400} 0 ${config.space.S200} 0`,
|
||||
padding: `${config.space.S200} 0 ${config.space.S100} 0`,
|
||||
}}
|
||||
>
|
||||
<ThreadMessage {...sharedMessageProps} mEvent={rootEvent} />
|
||||
|
||||
@@ -401,6 +401,10 @@ function MessageInternal(
|
||||
return convertBeeperFormatToOurPerMessageProfile(pmp);
|
||||
}, [pmp]);
|
||||
|
||||
/**
|
||||
* boolean to indicate wheather we should indicate to the user that it is a pmp
|
||||
*/
|
||||
const showPmPInfo = pmp !== undefined;
|
||||
// Profiles and Colors
|
||||
const profile = useUserProfile(senderId, room);
|
||||
const { color: usernameColor, font: usernameFont } = useSableCosmetics(senderId, room);
|
||||
@@ -515,6 +519,26 @@ function MessageInternal(
|
||||
{showPronouns && (
|
||||
<Pronouns pronouns={mergedPronouns} tagColor={usernameColor ?? 'currentColor'} />
|
||||
)}
|
||||
{showPmPInfo && (
|
||||
<Box>
|
||||
<Text as="span">
|
||||
<Text
|
||||
as="span"
|
||||
style={{ paddingLeft: 0, paddingRight: 5, fontWeight: 100, fontSize: 11 }}
|
||||
>
|
||||
via
|
||||
</Text>
|
||||
<Text
|
||||
as="span"
|
||||
size={messageLayout === MessageLayout.Bubble ? 'T300' : 'T400'}
|
||||
style={{ fontSize: 11 }}
|
||||
truncate
|
||||
>
|
||||
<UsernameBold>{senderDisplayName}</UsernameBold>
|
||||
</Text>
|
||||
</Text>
|
||||
</Box>
|
||||
)}
|
||||
{tagIconSrc && <PowerIcon size="100" iconSrc={tagIconSrc} />}
|
||||
</Box>
|
||||
<Box shrink="No" gap="100">
|
||||
|
||||
@@ -199,8 +199,7 @@ export function SyncDiagnostics() {
|
||||
<Box direction="Column" gap="100">
|
||||
<Text size="T300">Sliding proxy: {diagnostics.sliding.proxyBaseUrl}</Text>
|
||||
<Text size="T300">
|
||||
Room timeline limit: {diagnostics.sliding.timelineLimit} (adaptive:{' '}
|
||||
{diagnostics.sliding.adaptiveTimeline ? 'yes' : 'no'}) | page size:{' '}
|
||||
Room timeline limit: {diagnostics.sliding.timelineLimit} | page size:{' '}
|
||||
{diagnostics.sliding.listPageSize}
|
||||
</Text>
|
||||
{diagnostics.sliding.lists.map((list) => (
|
||||
|
||||
@@ -50,6 +50,7 @@ export type PerMessageProfileBeeperFormat = {
|
||||
* using the unstable prefix for pronouns, under which it is also stored in profiles
|
||||
*/
|
||||
'io.fsky.nyx.pronouns'?: PronounSet[];
|
||||
has_fallback: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -67,6 +68,7 @@ export function convertPerMessageProfileToBeeperFormat(
|
||||
displayname: profile.name,
|
||||
avatar_url: profile.avatarUrl,
|
||||
'io.fsky.nyx.pronouns': profile.pronouns,
|
||||
has_fallback: true,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,11 @@ import { useSelectedRoom } from '$hooks/router/useSelectedRoom';
|
||||
* Subscribes the currently selected room to the sliding sync "active room"
|
||||
* custom subscription (higher timeline limit) for the duration the room is open.
|
||||
*
|
||||
* Subscriptions are intentionally never removed on navigation — once a room
|
||||
* has been opened it continues receiving background updates so that returning
|
||||
* to it is instant. Explicit unsubscription (and timeline pruning) only happens
|
||||
* when the user actually leaves the room via `unsubscribeFromRoom()`.
|
||||
*
|
||||
* Safe to call unconditionally — it is a no-op when classic sync is in use
|
||||
* (i.e. when there is no SlidingSyncManager for the client).
|
||||
*/
|
||||
@@ -20,23 +25,15 @@ export const useSlidingSyncActiveRoom = (): void => {
|
||||
if (!manager) return undefined;
|
||||
|
||||
// Wait for the room to be initialized from list sync before subscribing
|
||||
// with high timeline limit. This prevents timeline ordering issues where
|
||||
// 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(() => {
|
||||
const room = mx.getRoom(roomId);
|
||||
if (room) {
|
||||
// Room exists and has been initialized from list sync
|
||||
manager.subscribeToRoom(roomId);
|
||||
} else {
|
||||
// Room not in cache yet - subscribe anyway (will use default encrypted subscription)
|
||||
manager.subscribeToRoom(roomId);
|
||||
}
|
||||
manager.subscribeToRoom(roomId);
|
||||
}, 100);
|
||||
|
||||
return () => {
|
||||
clearTimeout(timeoutId);
|
||||
manager.unsubscribeFromRoom(roomId);
|
||||
};
|
||||
}, [mx, roomId]);
|
||||
};
|
||||
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* Unit tests for SlidingSyncManager memory management:
|
||||
*
|
||||
* 1. dispose() — must call slidingSync.stop() to halt the polling loop and
|
||||
* abort in-flight requests. Without this the SDK's Promise loop keeps
|
||||
* running after the client is "stopped", leaking network traffic and
|
||||
* event listeners.
|
||||
*
|
||||
* 2. onMembershipLeave — when the MatrixClient emits a RoomMemberEvent.Membership
|
||||
* event indicating the local user left or was banned from a room that is
|
||||
* actively subscribed, unsubscribeFromRoom() should be called automatically.
|
||||
*
|
||||
* Note: navigation between rooms does not call unsubscribeFromRoom —
|
||||
* subscriptions accumulate across the session so returning to a room is
|
||||
* instant (matching Element Web's model).
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { SlidingSyncManager, type SlidingSyncConfig } from './slidingSync';
|
||||
|
||||
// ── vi.hoisted mocks ─────────────────────────────────────────────────────────
|
||||
// Must be defined via vi.hoisted so they're available before vi.mock runs
|
||||
// (vi.mock calls are hoisted above all imports by vitest's transformer).
|
||||
const mocks = vi.hoisted(() => ({
|
||||
slidingSyncInstance: {
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
stop: vi.fn(),
|
||||
modifyRoomSubscriptions: vi.fn(),
|
||||
modifyRoomSubscriptionInfo: vi.fn(),
|
||||
addCustomSubscription: vi.fn(),
|
||||
useCustomSubscription: vi.fn(),
|
||||
registerExtension: vi.fn(),
|
||||
getListData: vi.fn(() => null),
|
||||
getListParams: vi.fn(() => null),
|
||||
setList: vi.fn(),
|
||||
setListRanges: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// ── Sentry stub ──────────────────────────────────────────────────────────────
|
||||
vi.mock('@sentry/react', () => ({
|
||||
metrics: { count: vi.fn(), gauge: vi.fn(), distribution: vi.fn() },
|
||||
addBreadcrumb: vi.fn(),
|
||||
startInactiveSpan: vi.fn(() => ({
|
||||
setAttribute: vi.fn(),
|
||||
setAttributes: vi.fn(),
|
||||
end: vi.fn(),
|
||||
})),
|
||||
startSpan: vi.fn(async (_opts: unknown, fn: (span: object) => unknown) =>
|
||||
fn({ setAttributes: vi.fn(), setAttribute: vi.fn(), end: vi.fn() })
|
||||
),
|
||||
}));
|
||||
|
||||
// ── SlidingSync SDK mock ─────────────────────────────────────────────────────
|
||||
// vi.fn() wrappers are arrow functions internally and cannot be called with `new`.
|
||||
// A plain function constructor (returning an object) is the correct pattern.
|
||||
vi.mock('$types/matrix-sdk', async (importOriginal) => {
|
||||
const actual = await importOriginal<Record<string, unknown>>();
|
||||
function MockSlidingSync() {
|
||||
return mocks.slidingSyncInstance;
|
||||
}
|
||||
return { ...actual, SlidingSync: MockSlidingSync };
|
||||
});
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function makeMockMx(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
getUserId: vi.fn().mockReturnValue('@user:example.com'),
|
||||
getSafeUserId: vi.fn().mockReturnValue('@user:example.com'),
|
||||
isRoomEncrypted: vi.fn().mockReturnValue(false),
|
||||
getRoom: vi.fn().mockReturnValue(null),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
...overrides,
|
||||
} as unknown as import('$types/matrix-sdk').MatrixClient;
|
||||
}
|
||||
|
||||
function makeManager(mx: ReturnType<typeof makeMockMx>): SlidingSyncManager {
|
||||
const config: SlidingSyncConfig = {};
|
||||
return new SlidingSyncManager(mx, 'https://sliding.example.com', config);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
// ── dispose() ────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('SlidingSyncManager.dispose()', () => {
|
||||
it('calls slidingSync.stop() to halt the polling loop', () => {
|
||||
const manager = makeManager(makeMockMx());
|
||||
manager.dispose();
|
||||
expect(mocks.slidingSyncInstance.stop).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
// ── onMembershipLeave: auto-unsubscribe on leave/ban ─────────────────────────
|
||||
|
||||
describe('SlidingSyncManager — membership leave auto-unsubscribe', () => {
|
||||
/** Fire the RoomMemberEvent.Membership listener registered on mx.on */
|
||||
function fireMembershipEvent(
|
||||
mx: ReturnType<typeof makeMockMx>,
|
||||
membership: string,
|
||||
roomId = '!room:example.com',
|
||||
userId = '@user:example.com'
|
||||
) {
|
||||
const onCall = (mx.on as ReturnType<typeof vi.fn>).mock.calls.find(
|
||||
(args: unknown[]) => args[0] === 'RoomMember.membership'
|
||||
);
|
||||
if (!onCall) throw new Error('onMembershipLeave listener not registered');
|
||||
const [, handler] = onCall as [
|
||||
string,
|
||||
(e: unknown, m: { userId: string; roomId: string; membership: string }) => void,
|
||||
];
|
||||
handler(undefined, { userId, roomId, membership });
|
||||
}
|
||||
|
||||
it('unsubscribes when the local user leaves an active room', () => {
|
||||
const mx = makeMockMx();
|
||||
const manager = makeManager(mx);
|
||||
manager.attach();
|
||||
manager.subscribeToRoom('!room:example.com');
|
||||
|
||||
fireMembershipEvent(mx, 'leave');
|
||||
|
||||
// subscribeToRoom + unsubscribeFromRoom = 2 calls
|
||||
expect(mocks.slidingSyncInstance.modifyRoomSubscriptions).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('unsubscribes when the local user is banned from an active room', () => {
|
||||
const mx = makeMockMx();
|
||||
const manager = makeManager(mx);
|
||||
manager.attach();
|
||||
manager.subscribeToRoom('!room:example.com');
|
||||
|
||||
fireMembershipEvent(mx, 'ban');
|
||||
|
||||
expect(mocks.slidingSyncInstance.modifyRoomSubscriptions).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('does nothing when a different user leaves', () => {
|
||||
const mx = makeMockMx();
|
||||
const manager = makeManager(mx);
|
||||
manager.attach();
|
||||
manager.subscribeToRoom('!room:example.com');
|
||||
|
||||
fireMembershipEvent(mx, 'leave', '!room:example.com', '@other:example.com');
|
||||
|
||||
// Only the initial subscribe — no unsubscribe
|
||||
expect(mocks.slidingSyncInstance.modifyRoomSubscriptions).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does nothing when membership is join', () => {
|
||||
const mx = makeMockMx();
|
||||
const manager = makeManager(mx);
|
||||
manager.attach();
|
||||
manager.subscribeToRoom('!room:example.com');
|
||||
|
||||
fireMembershipEvent(mx, 'join');
|
||||
|
||||
expect(mocks.slidingSyncInstance.modifyRoomSubscriptions).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does nothing for a room that was never subscribed', () => {
|
||||
const mx = makeMockMx();
|
||||
const manager = makeManager(mx);
|
||||
manager.attach(); // registers the listener, but no subscribeToRoom call
|
||||
|
||||
fireMembershipEvent(mx, 'leave');
|
||||
|
||||
expect(mocks.slidingSyncInstance.modifyRoomSubscriptions).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+24
-104
@@ -3,11 +3,13 @@ import {
|
||||
ClientEvent,
|
||||
Extension,
|
||||
ExtensionState,
|
||||
KnownMembership,
|
||||
MatrixClient,
|
||||
MSC3575List,
|
||||
MSC3575RoomData,
|
||||
MSC3575RoomSubscription,
|
||||
MSC3575_WILDCARD,
|
||||
RoomMemberEvent,
|
||||
SlidingSync,
|
||||
SlidingSyncEvent,
|
||||
SlidingSyncState,
|
||||
@@ -46,13 +48,9 @@ const LIST_SORT_ORDER = ['by_recency', 'by_name'];
|
||||
// Subscription key for the room the user is actively viewing.
|
||||
// Encrypted rooms get [*,*] required_state; unencrypted rooms also request lazy members.
|
||||
const UNENCRYPTED_SUBSCRIPTION_KEY = 'unencrypted';
|
||||
// Adaptive timeline limits for the room the user is actively viewing.
|
||||
// Lower limits reduce initial bandwidth on constrained devices/connections;
|
||||
// the user can always paginate further once the room is open.
|
||||
// These values must be high enough to ensure proper timeline initialization and pagination tokens.
|
||||
const ACTIVE_ROOM_TIMELINE_LIMIT_LOW = 50;
|
||||
const ACTIVE_ROOM_TIMELINE_LIMIT_MEDIUM = 100;
|
||||
const ACTIVE_ROOM_TIMELINE_LIMIT_HIGH = 150;
|
||||
// Timeline limit for the active-room subscription (full history load).
|
||||
// List entries always use LIST_TIMELINE_LIMIT=1 for lightweight previews.
|
||||
const ACTIVE_ROOM_TIMELINE_LIMIT = 50;
|
||||
|
||||
export type PartialSlidingSyncRequest = {
|
||||
filters?: MSC3575List['filters'];
|
||||
@@ -81,7 +79,6 @@ export type SlidingSyncListDiagnostics = {
|
||||
export type SlidingSyncDiagnostics = {
|
||||
proxyBaseUrl: string;
|
||||
timelineLimit: number;
|
||||
adaptiveTimeline: boolean;
|
||||
listPageSize: number;
|
||||
lists: SlidingSyncListDiagnostics[];
|
||||
};
|
||||
@@ -91,63 +88,6 @@ const clampPositive = (value: number | undefined, fallback: number): number => {
|
||||
return Math.round(value);
|
||||
};
|
||||
|
||||
type AdaptiveSignals = {
|
||||
saveData: boolean;
|
||||
effectiveType: string | null;
|
||||
deviceMemoryGb: number | null;
|
||||
mobile: boolean;
|
||||
missingSignals: number;
|
||||
};
|
||||
|
||||
const readAdaptiveSignals = (): AdaptiveSignals => {
|
||||
const navigatorLike = typeof navigator !== 'undefined' ? navigator : undefined;
|
||||
const connection = (navigatorLike as any)?.connection;
|
||||
const effectiveType = connection?.effectiveType;
|
||||
const deviceMemory = (navigatorLike as any)?.deviceMemory;
|
||||
const uaMobile = (navigatorLike as any)?.userAgentData?.mobile;
|
||||
const fallbackMobileUA = navigatorLike?.userAgent ?? '';
|
||||
const mobileByUA =
|
||||
typeof uaMobile === 'boolean'
|
||||
? uaMobile
|
||||
: /Mobi|Android|iPhone|iPad|iPod|IEMobile|Opera Mini/i.test(fallbackMobileUA);
|
||||
const saveData = connection?.saveData === true;
|
||||
const normalizedEffectiveType = typeof effectiveType === 'string' ? effectiveType : null;
|
||||
const normalizedDeviceMemory = typeof deviceMemory === 'number' ? deviceMemory : null;
|
||||
const missingSignals =
|
||||
Number(normalizedEffectiveType === null) + Number(normalizedDeviceMemory === null);
|
||||
return {
|
||||
saveData,
|
||||
effectiveType: normalizedEffectiveType,
|
||||
deviceMemoryGb: normalizedDeviceMemory,
|
||||
mobile: mobileByUA,
|
||||
missingSignals,
|
||||
};
|
||||
};
|
||||
|
||||
// Resolve the timeline limit for the active-room subscription based on device/network.
|
||||
// The list subscription always uses LIST_TIMELINE_LIMIT=1 regardless of conditions.
|
||||
const resolveAdaptiveRoomTimelineLimit = (
|
||||
configuredLimit: number | undefined,
|
||||
signals: AdaptiveSignals
|
||||
): number => {
|
||||
if (typeof configuredLimit === 'number' && configuredLimit > 0) {
|
||||
return clampPositive(configuredLimit, ACTIVE_ROOM_TIMELINE_LIMIT_HIGH);
|
||||
}
|
||||
if (signals.saveData || signals.effectiveType === 'slow-2g' || signals.effectiveType === '2g') {
|
||||
return ACTIVE_ROOM_TIMELINE_LIMIT_LOW;
|
||||
}
|
||||
if (
|
||||
signals.effectiveType === '3g' ||
|
||||
(signals.deviceMemoryGb !== null && signals.deviceMemoryGb <= 4)
|
||||
) {
|
||||
return ACTIVE_ROOM_TIMELINE_LIMIT_MEDIUM;
|
||||
}
|
||||
if (signals.mobile && signals.missingSignals > 0) {
|
||||
return ACTIVE_ROOM_TIMELINE_LIMIT_MEDIUM;
|
||||
}
|
||||
return ACTIVE_ROOM_TIMELINE_LIMIT_HIGH;
|
||||
};
|
||||
|
||||
// Minimal required_state for list entries; enough to render the room list sidebar,
|
||||
// compute unread state, and build the space hierarchy without fetching full room history.
|
||||
// Notes:
|
||||
@@ -306,16 +246,17 @@ export class SlidingSyncManager {
|
||||
|
||||
private readonly listPageSize: number;
|
||||
|
||||
private roomTimelineLimit: number;
|
||||
|
||||
private readonly adaptiveTimeline: boolean;
|
||||
|
||||
private readonly configuredTimelineLimit?: number;
|
||||
private readonly roomTimelineLimit: number;
|
||||
|
||||
private readonly onConnectionChange: () => void;
|
||||
|
||||
private readonly onLifecycle: (state: SlidingSyncState, resp: unknown, err?: Error) => void;
|
||||
|
||||
private readonly onMembershipLeave: (
|
||||
event: unknown,
|
||||
member: { userId: string; roomId: string; membership?: string }
|
||||
) => void;
|
||||
|
||||
private presenceExtension!: ExtensionPresence;
|
||||
|
||||
private listsFullyLoaded = false;
|
||||
@@ -358,14 +299,8 @@ export class SlidingSyncManager {
|
||||
this.listPageSize = listPageSize;
|
||||
const includeInviteList = config.includeInviteList !== false;
|
||||
|
||||
const adaptiveTimeline = !(
|
||||
typeof config.timelineLimit === 'number' && config.timelineLimit > 0
|
||||
);
|
||||
const signals = readAdaptiveSignals();
|
||||
const roomTimelineLimit = resolveAdaptiveRoomTimelineLimit(config.timelineLimit, signals);
|
||||
this.adaptiveTimeline = adaptiveTimeline;
|
||||
const roomTimelineLimit = clampPositive(config.timelineLimit, ACTIVE_ROOM_TIMELINE_LIMIT);
|
||||
this.roomTimelineLimit = roomTimelineLimit;
|
||||
this.configuredTimelineLimit = config.timelineLimit;
|
||||
|
||||
const defaultSubscription = buildEncryptedSubscription(roomTimelineLimit);
|
||||
const lists = buildLists(listPageSize, includeInviteList);
|
||||
@@ -490,6 +425,14 @@ export class SlidingSyncManager {
|
||||
}
|
||||
};
|
||||
|
||||
this.onMembershipLeave = (_event, member) => {
|
||||
if (member.userId !== this.mx.getUserId()) return;
|
||||
if (member.membership !== KnownMembership.Leave && member.membership !== KnownMembership.Ban)
|
||||
return;
|
||||
if (!this.activeRoomSubscriptions.has(member.roomId)) return;
|
||||
this.unsubscribeFromRoom(member.roomId);
|
||||
};
|
||||
|
||||
this.onConnectionChange = () => {
|
||||
const isOnline = navigator.onLine;
|
||||
const connectionInfo =
|
||||
@@ -512,23 +455,6 @@ export class SlidingSyncManager {
|
||||
syncNumber: this.syncCount,
|
||||
});
|
||||
}
|
||||
|
||||
if (this.disposed || !this.adaptiveTimeline) return;
|
||||
const nextLimit = resolveAdaptiveRoomTimelineLimit(
|
||||
this.configuredTimelineLimit,
|
||||
readAdaptiveSignals()
|
||||
);
|
||||
if (nextLimit === this.roomTimelineLimit) return;
|
||||
debugLog.info('sync', `Adaptive timeline limit updated to ${nextLimit}`, {
|
||||
limit: nextLimit,
|
||||
previousLimit: this.roomTimelineLimit,
|
||||
reason: 'connection change',
|
||||
});
|
||||
this.roomTimelineLimit = nextLimit;
|
||||
this.applyRoomTimelineLimit(nextLimit);
|
||||
log.log(
|
||||
`Sliding Sync adaptive room timeline updated to ${nextLimit} for ${this.mx.getUserId()}`
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -537,7 +463,6 @@ export class SlidingSyncManager {
|
||||
proxyBaseUrl: this.proxyBaseUrl,
|
||||
listPageSize: this.listPageSize,
|
||||
roomTimelineLimit: this.roomTimelineLimit,
|
||||
adaptiveTimeline: this.adaptiveTimeline,
|
||||
maxRooms: this.maxRooms,
|
||||
lists: this.listKeys,
|
||||
});
|
||||
@@ -550,6 +475,7 @@ export class SlidingSyncManager {
|
||||
});
|
||||
|
||||
this.slidingSync.on(SlidingSyncEvent.Lifecycle, this.onLifecycle);
|
||||
this.mx.on(RoomMemberEvent.Membership, this.onMembershipLeave);
|
||||
const connection = (
|
||||
typeof navigator !== 'undefined' ? (navigator as any).connection : undefined
|
||||
) as
|
||||
@@ -585,7 +511,10 @@ export class SlidingSyncManager {
|
||||
this.pendingRoomDataListeners.clear();
|
||||
|
||||
this.disposed = true;
|
||||
// Stop the SDK's internal polling loop and abort any in-flight requests.
|
||||
this.slidingSync.stop();
|
||||
this.slidingSync.removeListener(SlidingSyncEvent.Lifecycle, this.onLifecycle);
|
||||
this.mx.removeListener(RoomMemberEvent.Membership, this.onMembershipLeave);
|
||||
const connection = (
|
||||
typeof navigator !== 'undefined' ? (navigator as any).connection : undefined
|
||||
) as
|
||||
@@ -607,14 +536,6 @@ export class SlidingSyncManager {
|
||||
});
|
||||
}
|
||||
|
||||
private applyRoomTimelineLimit(timelineLimit: number): void {
|
||||
this.slidingSync.modifyRoomSubscriptionInfo(buildEncryptedSubscription(timelineLimit));
|
||||
this.slidingSync.addCustomSubscription(
|
||||
UNENCRYPTED_SUBSCRIPTION_KEY,
|
||||
buildUnencryptedSubscription(timelineLimit)
|
||||
);
|
||||
}
|
||||
|
||||
public setPresenceEnabled(enabled: boolean): void {
|
||||
this.presenceExtension.setEnabled(enabled);
|
||||
}
|
||||
@@ -623,7 +544,6 @@ export class SlidingSyncManager {
|
||||
return {
|
||||
proxyBaseUrl: this.proxyBaseUrl,
|
||||
timelineLimit: this.roomTimelineLimit,
|
||||
adaptiveTimeline: this.adaptiveTimeline,
|
||||
listPageSize: this.listPageSize,
|
||||
lists: this.listKeys.map((key) => {
|
||||
const listData = this.slidingSync.getListData(key);
|
||||
|
||||
Reference in new issue
Block a user