From 726129f9ddd3d7bfcbe82e304ebcfe0de8c8fc8b Mon Sep 17 00:00:00 2001 From: melogale Date: Tue, 10 Mar 2026 02:08:52 -0400 Subject: [PATCH 001/146] sable call and avatar fix --- knip.json | 2 +- package-lock.json | 30 +++++++++++++++--------------- package.json | 2 +- src/app/plugins/call/utils.ts | 2 ++ src/sw.ts | 14 ++++++++++++++ vite.config.ts | 2 +- 6 files changed, 34 insertions(+), 18 deletions(-) diff --git a/knip.json b/knip.json index 8fec7f86..bdecc79c 100644 --- a/knip.json +++ b/knip.json @@ -5,7 +5,7 @@ "interface": true, "type": true }, - "ignoreDependencies": ["buffer", "@element-hq/element-call-embedded", "workbox-precaching"], + "ignoreDependencies": ["buffer", "@sableclient/sable-call-embedded", "workbox-precaching"], "ignoreBinaries": ["knope"], "rules": { "exports": "off", diff --git a/package-lock.json b/package-lock.json index 5683a6d1..cb788db9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -71,12 +71,12 @@ }, "devDependencies": { "@cloudflare/vite-plugin": "^1.26.0", - "@element-hq/element-call-embedded": "0.16.3", "@esbuild-plugins/node-globals-polyfill": "^0.2.3", "@eslint/compat": "2.0.2", "@eslint/js": "9.39.3", "@rollup/plugin-inject": "^5.0.5", "@rollup/plugin-wasm": "^6.2.2", + "@sableclient/sable-call-embedded": "1.0.2", "@types/chroma-js": "^3.1.2", "@types/file-saver": "^2.0.7", "@types/is-hotkey": "^0.1.10", @@ -1911,12 +1911,6 @@ "@jridgewell/sourcemap-codec": "^1.4.10" } }, - "node_modules/@element-hq/element-call-embedded": { - "version": "0.16.3", - "resolved": "https://registry.npmjs.org/@element-hq/element-call-embedded/-/element-call-embedded-0.16.3.tgz", - "integrity": "sha512-OViKJonDaDNVBUW9WdV9mk78/Ruh34C7XsEgt3O8D9z+64C39elbIgllHSoH5S12IRlv9RYrrV37FZLo6QWsDQ==", - "dev": true - }, "node_modules/@emnapi/core": { "version": "1.8.1", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.8.1.tgz", @@ -6270,6 +6264,12 @@ "dev": true, "license": "MIT" }, + "node_modules/@sableclient/sable-call-embedded": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@sableclient/sable-call-embedded/-/sable-call-embedded-1.0.2.tgz", + "integrity": "sha512-pvf2BxMx/57EnOs7NWf1/2UtchiBoMGdkzDH4Ivl0D0HSXIMO5z9DuHizk2bnHDJxcSSLY0wEl0XMl7ro0zqDA==", + "dev": true + }, "node_modules/@sindresorhus/is": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz", @@ -17883,12 +17883,6 @@ } } }, - "@element-hq/element-call-embedded": { - "version": "0.16.3", - "resolved": "https://registry.npmjs.org/@element-hq/element-call-embedded/-/element-call-embedded-0.16.3.tgz", - "integrity": "sha512-OViKJonDaDNVBUW9WdV9mk78/Ruh34C7XsEgt3O8D9z+64C39elbIgllHSoH5S12IRlv9RYrrV37FZLo6QWsDQ==", - "dev": true - }, "@emnapi/core": { "version": "1.8.1", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.8.1.tgz", @@ -20486,6 +20480,12 @@ "integrity": "sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==", "dev": true }, + "@sableclient/sable-call-embedded": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@sableclient/sable-call-embedded/-/sable-call-embedded-1.0.2.tgz", + "integrity": "sha512-pvf2BxMx/57EnOs7NWf1/2UtchiBoMGdkzDH4Ivl0D0HSXIMO5z9DuHizk2bnHDJxcSSLY0wEl0XMl7ro0zqDA==", + "dev": true + }, "@sindresorhus/is": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz", @@ -24408,7 +24408,7 @@ "jwt-decode": "^4.0.0", "loglevel": "^1.9.2", "matrix-events-sdk": "0.0.1", - "matrix-widget-api": "^1.10.0", + "matrix-widget-api": "1.13.0", "oidc-client-ts": "^3.0.1", "p-retry": "7", "sdp-transform": "^2.14.1", @@ -26905,4 +26905,4 @@ "dev": true } } -} \ No newline at end of file +} diff --git a/package.json b/package.json index 2667d148..7850f3de 100644 --- a/package.json +++ b/package.json @@ -87,7 +87,7 @@ }, "devDependencies": { "@cloudflare/vite-plugin": "^1.26.0", - "@element-hq/element-call-embedded": "0.16.3", + "@sableclient/sable-call-embedded": "1.0.2", "@esbuild-plugins/node-globals-polyfill": "^0.2.3", "@eslint/compat": "2.0.2", "@eslint/js": "9.39.3", diff --git a/src/app/plugins/call/utils.ts b/src/app/plugins/call/utils.ts index 0ea72b3c..8c4955b4 100644 --- a/src/app/plugins/call/utils.ts +++ b/src/app/plugins/call/utils.ts @@ -18,6 +18,8 @@ export function getCallCapabilities( capabilities.add(MatrixCapabilities.MSC3846TurnServers); capabilities.add(MatrixCapabilities.MSC4157SendDelayedEvent); capabilities.add(MatrixCapabilities.MSC4157UpdateDelayedEvent); + capabilities.add('moe.sable.thumbnails'); + capabilities.add('moe.sable.media_proxy'); capabilities.add(`org.matrix.msc2762.timeline:${roomId}`); capabilities.add(`org.matrix.msc2762.state:${roomId}`); diff --git a/src/sw.ts b/src/sw.ts index a7fd738e..4d7e0a03 100644 --- a/src/sw.ts +++ b/src/sw.ts @@ -269,6 +269,20 @@ self.addEventListener('fetch', (event: FetchEvent) => { return; } + // Since widgets like element call have their own client ids, + // we need this logic. We just go through the sessions list and get a session + // with the right base url. Media requests to a homeserver simply are fine with any account + // on the homeserver authenticating it, so this is fine. But it can be technically wrong. + // If you have two tabs for different users on the same homeserver, it might authenticate + // as the wrong one. + // Thus any logic in the future which cares about which user is authenticating the request + // might break this. Also, again, it is technically wrong. + const byBaseUrl = [...sessions.values()].find((s) => validMediaRequest(url, s.baseUrl)); + if (byBaseUrl) { + event.respondWith(fetch(url, { ...fetchConfig(byBaseUrl.accessToken), redirect })); + return; + } + event.respondWith( requestSessionWithTimeout(clientId).then((s) => { if (s && validMediaRequest(url, s.baseUrl)) { diff --git a/vite.config.ts b/vite.config.ts index 907f330d..c4e5fa3e 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -62,7 +62,7 @@ const isReleaseTag = (() => { const copyFiles = { targets: [ { - src: 'node_modules/@element-hq/element-call-embedded/dist/*', + src: 'node_modules/@sableclient/sable-call-embedded/dist/*', dest: 'public/element-call', }, { From 882c6d55cc8666e145b268461b52e4a46ad8b181 Mon Sep 17 00:00:00 2001 From: melogale Date: Tue, 10 Mar 2026 02:09:03 -0400 Subject: [PATCH 002/146] gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 1c110441..5cc8aa47 100644 --- a/.gitignore +++ b/.gitignore @@ -18,3 +18,4 @@ devAssets *.tfbackend !*.tfbackend.example crash.log +build.sh From 1c5314dd5511e31ae216fc082ee5c23ef672c391 Mon Sep 17 00:00:00 2001 From: Rye Date: Sat, 14 Mar 2026 16:37:02 +0100 Subject: [PATCH 003/146] fix maintainability issues raised by sonarqube fixed sonarqube issues: - React props should be read-only (typescript:S6759) - Spacing between inline elements should be explicit (typescript:S6772) --- src/app/features/settings/experimental/Experimental.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/app/features/settings/experimental/Experimental.tsx b/src/app/features/settings/experimental/Experimental.tsx index d8375271..5f29102e 100644 --- a/src/app/features/settings/experimental/Experimental.tsx +++ b/src/app/features/settings/experimental/Experimental.tsx @@ -7,7 +7,7 @@ import { Sync } from '../general'; type ExperimentalProps = { requestClose: () => void; }; -export function Experimental({ requestClose }: ExperimentalProps) { +export function Experimental({ requestClose }: Readonly) { return ( @@ -32,8 +32,8 @@ export function Experimental({ requestClose }: ExperimentalProps) { variant="Warning" description={ <> - The features listed below may be unstable or incomplete, - use at your own risk. + The features listed below may be unstable or incomplete,{' '} + use at your own risk.
Please report any new issues potentially caused by these features! From 7c4decd4e90d6997a48ff939d8daa8437f96b331 Mon Sep 17 00:00:00 2001 From: Rye Date: Sat, 14 Mar 2026 16:41:44 +0100 Subject: [PATCH 004/146] fix reliability/maintainability issues raised by sonarqube fixed issues: - typescript:S7781 - typescript:S6759 --- src/app/components/DeviceVerificationSetup.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/app/components/DeviceVerificationSetup.tsx b/src/app/components/DeviceVerificationSetup.tsx index 83c7187c..78fe8ded 100644 --- a/src/app/components/DeviceVerificationSetup.tsx +++ b/src/app/components/DeviceVerificationSetup.tsx @@ -70,7 +70,7 @@ function makeUIAAction( type SetupVerificationProps = { onComplete: (recoveryKey: string) => void; }; -function SetupVerification({ onComplete }: SetupVerificationProps) { +function SetupVerification({ onComplete }: Readonly) { const mx = useMatrixClient(); const alive = useAlive(); @@ -227,7 +227,7 @@ function SetupVerification({ onComplete }: SetupVerificationProps) { type RecoveryKeyDisplayProps = { recoveryKey: string; }; -function RecoveryKeyDisplay({ recoveryKey }: RecoveryKeyDisplayProps) { +function RecoveryKeyDisplay({ recoveryKey }: Readonly) { const [show, setShow] = useState(false); const handleCopy = () => { @@ -241,7 +241,7 @@ function RecoveryKeyDisplay({ recoveryKey }: RecoveryKeyDisplayProps) { FileSaver.saveAs(blob, 'recovery-key.txt'); }; - const safeToDisplayKey = show ? recoveryKey : recoveryKey.replace(/[^\s]/g, '*'); + const safeToDisplayKey = show ? recoveryKey : recoveryKey.replaceAll(/[^\s]/g, '*'); return ( From b5b1766bd6ce518946a2d373d5fd072f3c0d8143 Mon Sep 17 00:00:00 2001 From: Rye Date: Sat, 14 Mar 2026 17:12:15 +0100 Subject: [PATCH 005/146] fix sonarqube maintainability/reliability issues - typescript:S7773 - typescript:S4158 --- src/app/components/Pdf-viewer/PdfViewer.tsx | 2 +- .../editor/autocomplete/EmoticonAutocomplete.tsx | 13 +++++-------- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/src/app/components/Pdf-viewer/PdfViewer.tsx b/src/app/components/Pdf-viewer/PdfViewer.tsx index e3072e6f..71ab77ef 100644 --- a/src/app/components/Pdf-viewer/PdfViewer.tsx +++ b/src/app/components/Pdf-viewer/PdfViewer.tsx @@ -85,7 +85,7 @@ export const PdfViewer = as<'div', PdfViewerProps>( if (docState.status !== AsyncStatus.Success) return; const jumpInput = evt.currentTarget.jumpInput as HTMLInputElement; if (!jumpInput) return; - const jumpTo = parseInt(jumpInput.value, 10); + const jumpTo = Number.parseInt(jumpInput.value, 10); setPageNo(Math.max(1, Math.min(docState.data.numPages, jumpTo))); setJumpAnchor(undefined); }; diff --git a/src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx b/src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx index c8466ae9..71dac490 100644 --- a/src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx +++ b/src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx @@ -57,13 +57,10 @@ export function EmoticonAutocomplete({ const [emojiThreshold] = useSetting(settingsAtom, 'emojiSuggestThreshold'); - const searchList = useMemo(() => { - const list: Array = []; - return list.concat( - imagePacks.flatMap((pack) => pack.getImages(ImageUsage.Emoticon)), - emojis - ); - }, [imagePacks]); + const searchList = useMemo>( + () => [...imagePacks.flatMap((pack) => pack.getImages(ImageUsage.Emoticon)), ...emojis], + [imagePacks] + ); const [result, search, resetSearch] = useAsyncSearch( searchList, @@ -94,7 +91,7 @@ export function EmoticonAutocomplete({ requestClose(); }); - useKeyDown(window, (evt: KeyboardEvent) => { + useKeyDown(globalThis as Window, (evt: KeyboardEvent) => { onTabPress(evt, () => { if (autoCompleteEmoticon.length === 0) return; const emoticon = autoCompleteEmoticon[0]; From 9363bee20805ad1f6f97b8beacde85d8130e5b4b Mon Sep 17 00:00:00 2001 From: Rye Date: Sat, 14 Mar 2026 17:12:30 +0100 Subject: [PATCH 006/146] replace globalThis with window in useKeyDown for consistency --- src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx b/src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx index 71dac490..1f590235 100644 --- a/src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx +++ b/src/app/components/editor/autocomplete/EmoticonAutocomplete.tsx @@ -91,7 +91,7 @@ export function EmoticonAutocomplete({ requestClose(); }); - useKeyDown(globalThis as Window, (evt: KeyboardEvent) => { + useKeyDown(window, (evt: KeyboardEvent) => { onTabPress(evt, () => { if (autoCompleteEmoticon.length === 0) return; const emoticon = autoCompleteEmoticon[0]; From 7b3ea2b9c003187f4b7e21d22f0972a28c75eb72 Mon Sep 17 00:00:00 2001 From: Rye Date: Sat, 14 Mar 2026 17:32:19 +0100 Subject: [PATCH 007/146] fix sonarqube maintainability issues - Number static methods and properties should be preferred over global equivalents (typescript:S7773) - Function references should not be passed directly to iterator methods (typescript:S7727) - Strings should use "replaceAll()" instead of "replace()" with global regex (typescript:S7781) - "RegExp.exec()" should be preferred over "String.match()" (typescript:S6594) - React props should be read-only (typescript:S6759) - Prefer `Math.min()` to simplify ternary expressions (typescript:S7766) - Optional property declarations should not use both '?' and 'undefined' syntax (typescript:S4782) - Built-in constructors should be called consistently with or without "new" (typescript:S7723) --- src/app/components/RenderMessageContent.tsx | 2 +- src/app/components/editor/input.ts | 4 ++-- src/app/components/editor/output.ts | 12 +++++++----- src/app/components/emoji-board/EmojiBoard.tsx | 10 +++++----- .../components/event-history/EventHistory.tsx | 4 ++-- src/app/components/message/RenderBody.tsx | 2 +- src/app/components/message/Reply.tsx | 16 ++++++++-------- src/app/components/time-date/DatePicker.tsx | 8 ++++---- .../upload-card/UploadCardRenderer.tsx | 6 +++--- .../upload-card/UploadDescriptionEditor.tsx | 2 +- .../components/user-profile/UserRoomProfile.tsx | 12 ++++++------ 11 files changed, 40 insertions(+), 38 deletions(-) diff --git a/src/app/components/RenderMessageContent.tsx b/src/app/components/RenderMessageContent.tsx index 1a1a5376..50279924 100644 --- a/src/app/components/RenderMessageContent.tsx +++ b/src/app/components/RenderMessageContent.tsx @@ -71,7 +71,7 @@ function RenderMessageContentInternal({ htmlReactParserOptions, linkifyOpts, outlineAttachment, -}: RenderMessageContentProps) { +}: Readonly) { const content = useMemo(() => getContent(), [getContent]); const [autoplayGifs] = useSetting(settingsAtom, 'autoplayGifs'); diff --git a/src/app/components/editor/input.ts b/src/app/components/editor/input.ts index 017c33b8..27a6b68f 100644 --- a/src/app/components/editor/input.ts +++ b/src/app/components/editor/input.ts @@ -322,7 +322,7 @@ const parseHeadingNode = ( const headingMatch = node.name.match(/^h([123456])$/); const [, g1AsLevel] = headingMatch ?? ['h3', '3']; - const level = parseInt(g1AsLevel, 10); + const level = Number.parseInt(g1AsLevel, 10); const mdSequence = node.attribs['data-md']; if (mdSequence !== undefined) { @@ -334,7 +334,7 @@ const parseHeadingNode = ( return { type: BlockType.Heading, - level: (level <= 3 ? level : 3) as HeadingLevel, + level: Math.min(level, 3) as HeadingLevel, children, }; }; diff --git a/src/app/components/editor/output.ts b/src/app/components/editor/output.ts index 2f797e04..6ded4b22 100644 --- a/src/app/components/editor/output.ts +++ b/src/app/components/editor/output.ts @@ -128,10 +128,12 @@ export const toMatrixCustomHTML = ( return `${parsedMarkdown}${toMatrixCustomHTML(n, { ...opts, allowBlockMarkdown: false })}`; }; - if (Array.isArray(node)) return node.map(parseNode).join(''); + if (Array.isArray(node)) return node.map((element, index, array) => parseNode(element, index, array)).join(''); if (Text.isText(node)) return textToCustomHtml(node, opts); - const children = node.children.map(parseNode).join(''); + const children = node.children + .map((element, index, array) => parseNode(element, index, array)) + .join(''); return elementToCustomHtml(node, children); }; @@ -193,14 +195,14 @@ export const toPlainText = (node: Descendant | Descendant[], isMarkdown: boolean * @returns boolean */ export const customHtmlEqualsPlainText = (customHtml: string, plain: string): boolean => - customHtml.replace(//g, '\n') === sanitizeText(plain); + customHtml.replaceAll('
', '\n') === sanitizeText(plain); -export const trimCustomHtml = (customHtml: string) => customHtml.replace(/$/g, '').trim(); +export const trimCustomHtml = (customHtml: string) => customHtml.replaceAll(/$/g, '').trim(); export const trimCommand = (cmdName: string, str: string) => { const cmdRegX = new RegExp(`^(\\s+)?(\\/${sanitizeForRegex(cmdName)})([^\\S\n]+)?`); - const match = str.match(cmdRegX); + const match = new RegExp(cmdRegX).exec(str); if (!match) return str; return str.slice(match[0].length); }; diff --git a/src/app/components/emoji-board/EmojiBoard.tsx b/src/app/components/emoji-board/EmojiBoard.tsx index 83804b96..bebb6ef2 100644 --- a/src/app/components/emoji-board/EmojiBoard.tsx +++ b/src/app/components/emoji-board/EmojiBoard.tsx @@ -169,7 +169,7 @@ type EmojiSidebarProps = { packs: ImagePack[]; onScrollToGroup: (groupId: string) => void; }; -function EmojiSidebar({ activeGroupAtom, packs, onScrollToGroup }: EmojiSidebarProps) { +function EmojiSidebar({ activeGroupAtom, packs, onScrollToGroup }: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); @@ -245,7 +245,7 @@ type StickerSidebarProps = { packs: ImagePack[]; onScrollToGroup: (groupId: string) => void; }; -function StickerSidebar({ activeGroupAtom, packs, onScrollToGroup }: StickerSidebarProps) { +function StickerSidebar({ activeGroupAtom, packs, onScrollToGroup }: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); @@ -294,7 +294,7 @@ function EmojiGroupHolder({ previewAtom, onGroupItemClick, children, -}: EmojiGroupHolderProps) { +}: Readonly) { const setPreviewData = useSetAtom(previewAtom); const handleEmojiPreview = useCallback( @@ -375,7 +375,7 @@ export function EmojiBoard({ onStickerSelect, allowTextCustomEmoji, addToRecentEmoji = true, -}: EmojiBoardProps) { +}: Readonly) { const mx = useMatrixClient(); const emojiTab = tab === EmojiBoardTab.Emoji; @@ -543,7 +543,7 @@ export function EmojiBoard({ id={SEARCH_GROUP_ID} label={searchedItems.length ? 'Search Results' : 'No Results found'} > - {searchedItems.map(renderItem)} + {searchedItems.map((element, index) => renderItem(element, index))} )}
( [room, setReplyDraft] ); - function MenuOptions({ mEvent }: { mEvent: MatrixEvent }) { + function MenuOptions({ mEvent }: Readonly<{ mEvent: MatrixEvent }>) { const setModal = useSetAtom(modalAtom); return ( @@ -177,7 +177,7 @@ export const EventHistory = as<'div', EventHistoryProps>( ); } - function EventItem({ mEvent, EventContent }: { mEvent: MatrixEvent; EventContent: IContent }) { + function EventItem({ mEvent, EventContent }: Readonly<{ mEvent: MatrixEvent; EventContent: IContent }>) { const [isHovered, setIsHovered] = useState(false); return ( ) { if (body === '') return ; if (customBody) { if (customBody === '') return ; diff --git a/src/app/components/message/Reply.tsx b/src/app/components/message/Reply.tsx index eddc13e2..2afd2aae 100644 --- a/src/app/components/message/Reply.tsx +++ b/src/app/components/message/Reply.tsx @@ -68,10 +68,10 @@ export const ThreadIndicator = as<'div'>(({ ...props }, ref) => ( type ReplyProps = { room: Room; - timelineSet?: EventTimelineSet | undefined; + timelineSet?: EventTimelineSet; replyEventId: string; - threadRootId?: string | undefined; - onClick?: MouseEventHandler | undefined; + threadRootId?: string; + onClick?: MouseEventHandler; }; export const Reply = as<'div', ReplyProps>( @@ -119,10 +119,10 @@ export const Reply = as<'div', ReplyProps>( if (format === 'org.matrix.custom.html' && formattedBody) { const strippedHtml = trimReplyFromFormattedBody(formattedBody) - .replace(//gi, ' ') - .replace(/<\/p>\s*]*>/gi, ' ') - .replace(/<\/?p[^>]*>/gi, '') - .replace(/(?:\r\n|\r|\n)/g, ' '); + .replaceAll(//gi, ' ') + .replaceAll(/<\/p>\s*]*>/gi, ' ') + .replaceAll(/<\/?p[^>]*>/gi, '') + .replaceAll(/(?:\r\n|\r|\n)/g, ' '); const parserOpts = getReactCustomHtmlParser(mx, room.roomId, { linkifyOpts: LINKIFY_OPTS, useAuthentication, @@ -130,7 +130,7 @@ export const Reply = as<'div', ReplyProps>( }); bodyJSX = parse(strippedHtml, parserOpts) as JSX.Element; } else if (body) { - const strippedBody = trimReplyFromBody(body).replace(/(?:\r\n|\r|\n)/g, ' '); + const strippedBody = trimReplyFromBody(body).replaceAll(/(?:\r\n|\r|\n)/g, ' '); bodyJSX = scaleSystemEmoji(strippedBody); } diff --git a/src/app/components/time-date/DatePicker.tsx b/src/app/components/time-date/DatePicker.tsx index c2daca42..078d91d8 100644 --- a/src/app/components/time-date/DatePicker.tsx +++ b/src/app/components/time-date/DatePicker.tsx @@ -33,7 +33,7 @@ export const DatePicker = forwardRef( const currentDate = dateFor(selectedYear, selectedMonth, selectedDay); const time = value - currentDate; - const newDate = dateFor(year, month, mDays < selectedDay ? mDays : selectedDay); + const newDate = dateFor(year, month, Math.min(mDays, selectedDay)); const newValue = newDate + time; handleSubmit(newValue); @@ -60,7 +60,7 @@ export const DatePicker = forwardRef( - {Array.from(Array(daysInMonth(selectedMonth, selectedYear)).keys()) + {Array.from(new Array(daysInMonth(selectedMonth, selectedYear)).keys()) .map((i) => i + 1) .map((day) => ( ( ))} - {Array.from(Array(12).keys()) + {Array.from(new Array(12).keys()) .map((i) => i + 1) .map((month) => ( ( ))} - {Array.from(Array(yearsRange).keys()) + {Array.from(new Array(yearsRange).keys()) .map((i) => minYear + i) .map((year) => ( ) { const { originalFile, metadata } = fileItem; const fileUrl = useObjectURL(originalFile); @@ -53,7 +53,7 @@ function PreviewImage({ fileItem }: PreviewImageProps) { type PreviewVideoProps = { fileItem: TUploadItem; }; -function PreviewVideo({ fileItem }: PreviewVideoProps) { +function PreviewVideo({ fileItem }: Readonly) { const { originalFile, metadata } = fileItem; const fileUrl = useObjectURL(originalFile); @@ -131,7 +131,7 @@ export function UploadCardRenderer({ onRemove, onComplete, roomId, -}: UploadCardRendererProps) { +}: Readonly) { const mx = useMatrixClient(); const mediaConfig = useMediaConfig(); const allowSize = mediaConfig['m.upload.size'] || Infinity; diff --git a/src/app/components/upload-card/UploadDescriptionEditor.tsx b/src/app/components/upload-card/UploadDescriptionEditor.tsx index 447f0243..563f06ed 100644 --- a/src/app/components/upload-card/UploadDescriptionEditor.tsx +++ b/src/app/components/upload-card/UploadDescriptionEditor.tsx @@ -53,7 +53,7 @@ export function DescriptionEditor({ imagePackRooms, onSave, onCancel, -}: DescriptionEditorProps) { +}: Readonly) { const editor = useEditor(); const [enterForNewline] = useSetting(settingsAtom, 'enterForNewline'); const [isMarkdown] = useSetting(settingsAtom, 'isMarkdown'); diff --git a/src/app/components/user-profile/UserRoomProfile.tsx b/src/app/components/user-profile/UserRoomProfile.tsx index 09e2ab97..5d0f9e7e 100644 --- a/src/app/components/user-profile/UserRoomProfile.tsx +++ b/src/app/components/user-profile/UserRoomProfile.tsx @@ -65,7 +65,7 @@ function UserExtendedSection({ profile, htmlReactParserOptions, linkifyOpts, -}: UserExtendedSectionProps) { +}: Readonly) { const clamp = (str: any, len: number) => { const stringified = String(str ?? ''); return stringified.length > len ? `${stringified.slice(0, len)}...` : stringified; @@ -108,7 +108,7 @@ function UserExtendedSection({ return new Intl.DateTimeFormat([], { hour: 'numeric', minute: '2-digit', - timeZone: profile.timezone.replace(/^["']|["']$/g, ''), + timeZone: profile.timezone.replaceAll(/^["']|["']$/g, ''), }).format(new Date()); } catch { return null; @@ -133,7 +133,7 @@ function UserExtendedSection({ const safetyTrim = rawBio.length > 2048 ? rawBio.slice(0, 2048) : rawBio; - const visibleText = safetyTrim.replace(/<[^>]*>?/gm, ''); + const visibleText = safetyTrim.replaceAll(/<[^>]*>?/gm, ''); const VISIBLE_LIMIT = 1024; if (visibleText.length <= VISIBLE_LIMIT) { @@ -163,7 +163,7 @@ function UserExtendedSection({ - {localTime} ({profile.timezone.replace(/^["']|["']$/g, '')}) + {localTime} ({profile.timezone.replaceAll(/^["']|["']$/g, '')}) )} @@ -252,7 +252,7 @@ type UserRoomProfileProps = { userId: string; initialProfile?: Partial; }; -export function UserRoomProfile({ userId, initialProfile }: UserRoomProfileProps) { +export function UserRoomProfile({ userId, initialProfile }: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const navigate = useNavigate(); @@ -296,7 +296,7 @@ export function UserRoomProfile({ userId, initialProfile }: UserRoomProfileProps const parsedBanner = typeof extendedProfile.bannerUrl === 'string' - ? extendedProfile.bannerUrl.replace(/^"|"$/g, '') + ? extendedProfile.bannerUrl.replaceAll(/^"|"$/g, '') : undefined; const bannerHttpUrl = parsedBanner From 412c5284beb9ae02f50349c9f049b0f01f7f4868 Mon Sep 17 00:00:00 2001 From: Rye Date: Sat, 14 Mar 2026 18:14:24 +0100 Subject: [PATCH 008/146] fix maintainability issues raised by sonarqube - Built-in constructors should be called consistently with or without "new" (typescript:S7723) - Negated conditions should be avoided when an else clause is present (typescript:S7735) - Strings should use "replaceAll()" instead of "replace()" with global regex (typescript:S7781) - Use ".some()" instead of ".filter().length" checks or ".find()" for existence testing (typescript:S7754) - React props should be read-only (typescript:S6759) - Number static methods and properties should be preferred over global equivalents (typescript:S7773) - The return value of "useState" should be destructured and named symmetrically (typescript:S6754) - Optional chaining should be preferred (typescript:S6582) - Arrays used only for existence checks should be Sets (typescript:S7776) - Unicode-aware string methods should be used for proper character handling (typescript:S7758) --- src/app/components/time-date/TimePicker.tsx | 8 +++---- .../emojis-stickers/RoomPacks.tsx | 10 ++++----- .../permissions/PowersEditor.tsx | 6 ++--- src/app/features/lobby/DnD.tsx | 14 ++++++------ src/app/features/lobby/Lobby.tsx | 7 +++--- .../features/message-search/MessageSearch.tsx | 6 ++--- src/app/features/room/RoomTimeline.tsx | 16 ++++++++++---- src/app/features/room/RoomViewHeader.tsx | 12 +++++----- src/app/features/settings/about/About.tsx | 6 ++--- .../settings/account/NameColorEditor.tsx | 4 ++-- src/app/features/settings/account/Profile.tsx | 16 +++++++------- .../features/settings/cosmetics/Themes.tsx | 8 +++---- src/app/features/settings/general/General.tsx | 20 ++++++++--------- src/app/hooks/useCommands.ts | 17 +++++++------- src/app/hooks/useRoomWidgets.ts | 22 +++++++++---------- src/app/hooks/useUserProfile.ts | 10 ++++----- src/app/pages/client/explore/Server.tsx | 16 +++++++------- src/app/pages/client/inbox/Notifications.tsx | 10 ++++----- src/app/pages/client/sidebar/SpaceTabs.tsx | 20 ++++++++--------- src/app/utils/ASCIILexicalTable.ts | 4 ++-- 20 files changed, 119 insertions(+), 113 deletions(-) diff --git a/src/app/components/time-date/TimePicker.tsx b/src/app/components/time-date/TimePicker.tsx index b90b7834..c16ad7ca 100644 --- a/src/app/components/time-date/TimePicker.tsx +++ b/src/app/components/time-date/TimePicker.tsx @@ -64,7 +64,7 @@ export const TimePicker = forwardRef( {hour24Clock - ? Array.from(Array(24).keys()).map((hour) => ( + ? Array.from(new Array(24).keys()).map((hour) => ( ( {hour < 10 ? `0${hour}` : hour} )) - : Array.from(Array(12).keys()) + : Array.from(new Array(12).keys()) .map((i) => { if (i === 0) return 12; return i; @@ -102,7 +102,7 @@ export const TimePicker = forwardRef( ))} - {Array.from(Array(60).keys()).map((minute) => ( + {Array.from(new Array(60).keys()).map((minute) => ( ( ) { const mx = useMatrixClient(); const alive = useAlive(); @@ -75,9 +75,9 @@ function CreatePackTile({ packs, roomId }: CreatePackTileProps) { const name = nameInput?.value.trim(); if (!name) return; - let packKey = name.replace(/\s/g, '-'); + let packKey = name.replaceAll(/\s/g, '-'); - const hasPack = (k: string): boolean => !!packs.find((pack) => pack.address?.stateKey === k); + const hasPack = (k: string): boolean => packs.some((pack) => pack.address?.stateKey === k); if (hasPack(packKey)) { packKey = suffixRename(packKey, hasPack); } @@ -141,7 +141,7 @@ function CreatePackTile({ packs, roomId }: CreatePackTileProps) { type RoomPacksProps = { onViewPack: (imagePack: ImagePack) => void; }; -export function RoomPacks({ onViewPack }: RoomPacksProps) { +export function RoomPacks({ onViewPack }: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const room = useRoom(); @@ -193,7 +193,7 @@ export function RoomPacks({ onViewPack }: RoomPacksProps) { const avatarUrl = avatarMxc ? mxcUrlToHttp(mx, avatarMxc, useAuthentication) : undefined; const { address } = pack; if (!address) return null; - const removed = !!removedPacks.find((addr) => packAddressEqual(addr, address)); + const removed = removedPacks.some((addr) => packAddressEqual(addr, address)); return ( void; onClose: () => void; }; -function EditPower({ maxPower, power, tag, onSave, onClose }: EditPowerProps) { +function EditPower({ maxPower, power, tag, onSave, onClose }: Readonly) { const mx = useMatrixClient(); const room = useRoom(); const roomToParents = useAtomValue(roomToParentsAtom); @@ -103,7 +103,7 @@ function EditPower({ maxPower, power, tag, onSave, onClose }: EditPowerProps) { const nameInput = target?.nameInput as HTMLInputElement | undefined; if (!powerInput || !nameInput) return; - const tagPower = parseInt(powerInput.value, 10); + const tagPower = Number.parseInt(powerInput.value, 10); if (Number.isNaN(tagPower)) return; const tagName = nameInput.value.trim(); @@ -307,7 +307,7 @@ type PowersEditorProps = { powerLevels: IPowerLevels; requestClose: () => void; }; -export function PowersEditor({ powerLevels, requestClose }: PowersEditorProps) { +export function PowersEditor({ powerLevels, requestClose }: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const room = useRoom(); diff --git a/src/app/features/lobby/DnD.tsx b/src/app/features/lobby/DnD.tsx index 71c6bf8e..fa4584a4 100644 --- a/src/app/features/lobby/DnD.tsx +++ b/src/app/features/lobby/DnD.tsx @@ -29,9 +29,8 @@ export const useDraggableItem = ( const target = targetRef.current; const dragHandle = dragHandleRef?.current ?? undefined; - return !target - ? undefined - : draggable({ + return target + ? draggable({ element: target, dragHandle, getInitialData: () => item, @@ -43,7 +42,8 @@ export const useDraggableItem = ( setDragging(false); onDragging(undefined); }, - }); + }) + : undefined; }, [targetRef, dragHandleRef, item, onDragging]); return dragging; @@ -72,14 +72,14 @@ export function AfterItemDropTarget({ afterSpace, nextRoomId, canDrop, -}: AfterItemDropTargetProps) { +}: Readonly) { const targetRef = useRef(null); const [dropState, setDropState] = useState<'idle' | 'allow' | 'not-allow'>('idle'); useEffect(() => { const target = targetRef.current; if (!target) { - throw Error('drop target ref is not set properly'); + throw new Error('drop target ref is not set properly'); } return dropTargetForElements({ @@ -126,7 +126,7 @@ export const useDnDMonitor = ( useEffect(() => { const scrollElement = scrollRef.current; if (!scrollElement) { - throw Error('Scroll element ref not configured'); + throw new Error('Scroll element ref not configured'); } return combine( diff --git a/src/app/features/lobby/Lobby.tsx b/src/app/features/lobby/Lobby.tsx index 0bc47426..180e0d81 100644 --- a/src/app/features/lobby/Lobby.tsx +++ b/src/app/features/lobby/Lobby.tsx @@ -179,7 +179,7 @@ export function Lobby() { return new Set(sideSpaces); }, [sidebarItems]); - const [spacesItems, setSpacesItem] = useState>(() => new Map()); + const [spacesItems, setSpacesItems] = useState>(() => new Map()); useElementSizeObserver( useCallback(() => heroSectionRef.current, []), @@ -302,8 +302,7 @@ export function Lobby() { } if ( - itemRoom && - itemRoom.getJoinRule() === JoinRule.Restricted && + itemRoom?.getJoinRule() === JoinRule.Restricted && item.parentId !== containerParentId ) { // change join rule allow parameter when dragging @@ -394,7 +393,7 @@ export function Lobby() { const handleSpacesFound = useCallback( (sItems: IHierarchyRoom[]) => { setSpaceRooms({ type: 'PUT', roomIds: sItems.map((i) => i.room_id) }); - setSpacesItem((current) => { + setSpacesItems((current) => { const newItems = produce(current, (draft) => { sItems.forEach((item) => draft.set(item.room_id, item)); }); diff --git a/src/app/features/message-search/MessageSearch.tsx b/src/app/features/message-search/MessageSearch.tsx index 46c948f6..db919172 100644 --- a/src/app/features/message-search/MessageSearch.tsx +++ b/src/app/features/message-search/MessageSearch.tsx @@ -49,7 +49,7 @@ export function MessageSearch({ rooms, senders, scrollRef, -}: MessageSearchProps) { +}: Readonly) { const mx = useMatrixClient(); const mDirects = useAtomValue(mDirectAtom); const allRooms = useRooms(mx, allRoomsAtom, mDirects); @@ -175,7 +175,7 @@ export function MessageSearch({ }); }; - const lastVItem = vItems[vItems.length - 1]; + const lastVItem = vItems.at(-1); const lastVItemIndex: number | undefined = lastVItem?.index; const lastGroupIndex = groups.length - 1; useEffect(() => { @@ -253,7 +253,7 @@ export function MessageSearch({ {((msgSearchParams.term && status === 'pending') || (groups.length > 0 && vItems.length === 0)) && ( - {[...Array(8).keys()].map((key) => ( + {[...new Array(8).keys()].map((key) => ( ))} diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index 6365f851..495cdd57 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -205,7 +205,9 @@ export const timelineToEventsCount = (t: EventTimeline) => { export const getTimelinesEventsCount = (timelines: EventTimeline[]): number => { const timelineEventCountReducer = (count: number, tm: EventTimeline) => count + timelineToEventsCount(tm); - return (timelines || []).filter(Boolean).reduce(timelineEventCountReducer, 0); + return (timelines || []) + .filter(Boolean) + .reduce((accumulator, element) => timelineEventCountReducer(accumulator, element), 0); }; export const getTimelineAndBaseIndex = ( @@ -576,7 +578,12 @@ type ThreadReplyChipProps = { onToggle: () => void; }; -function ThreadReplyChip({ room, mEventId, openThreadId, onToggle }: ThreadReplyChipProps) { +function ThreadReplyChip({ + room, + mEventId, + openThreadId, + onToggle, +}: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const nicknames = useAtomValue(nicknamesAtom); @@ -602,7 +609,7 @@ function ThreadReplyChip({ room, mEventId, openThreadId, onToggle }: ThreadReply } }); - const latestReply = replyEvents[replyEvents.length - 1]; + const latestReply = replyEvents.at(-1); const latestSenderId = latestReply?.getSender() ?? ''; const latestSenderName = getMemberDisplayName(room, latestSenderId, nicknames) ?? @@ -706,7 +713,7 @@ export function RoomTimeline({ roomInputRef, editor, onEditorReset, -}: RoomTimelineProps) { +}: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const pushProcessor = useMemo(() => new PushProcessor(mx), [mx]); @@ -772,6 +779,7 @@ export function RoomTimeline({ const atBottomAnchorRef = useRef(null); + // TODO: The return value of "useState" should be destructured and named symmetrically (typescript:S6754) const [atBottom, setAtBottomState] = useState(true); const atBottomRef = useRef(atBottom); const setAtBottom = useCallback((val: boolean) => { diff --git a/src/app/features/room/RoomViewHeader.tsx b/src/app/features/room/RoomViewHeader.tsx index a73df787..55719e42 100644 --- a/src/app/features/room/RoomViewHeader.tsx +++ b/src/app/features/room/RoomViewHeader.tsx @@ -340,7 +340,7 @@ const RoomMenu = forwardRef(({ room, requestClose }); RoomMenu.displayName = 'RoomMenu'; -export function RoomViewHeader({ callView }: { callView?: boolean }) { +export function RoomViewHeader({ callView }: Readonly<{ callView?: boolean }>) { const navigate = useNavigate(); const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); @@ -408,14 +408,14 @@ export function RoomViewHeader({ callView }: { callView?: boolean }) { } const lastSeenIndex = pinnedIds.indexOf(pinMarker?.last_seen_id); - if (lastSeenIndex !== -1) { - const newPins = pinnedIds.slice(lastSeenIndex + 1); - setUnreadPinsCount(newPins.length); - } else { + if (lastSeenIndex === -1) { const oldCount = pinMarker?.count ?? 0; const startIndex = Math.max(0, oldCount - 1); const newCount = pinnedIds.length > 0 ? pinnedIds.length - startIndex : 0; setUnreadPinsCount(Math.max(0, newCount)); + } else { + const newPins = pinnedIds.slice(lastSeenIndex + 1); + setUnreadPinsCount(newPins.length); } }; checkUnreads().catch((err) => { @@ -557,7 +557,7 @@ export function RoomViewHeader({ callView }: { callView?: boolean }) { await mx.setRoomAccountData(room.roomId, AccountDataEvent.SablePinStatus, { hash, count: pinnedIds.length, - last_seen_id: pinnedIds[pinnedIds.length - 1], + last_seen_id: pinnedIds.at(-1), }); }; diff --git a/src/app/features/settings/about/About.tsx b/src/app/features/settings/about/About.tsx index be541815..1f399991 100644 --- a/src/app/features/settings/about/About.tsx +++ b/src/app/features/settings/about/About.tsx @@ -35,7 +35,7 @@ export function HomeserverInfo() { setFederationUrl(newUrl); } }) - .catch((error2) => setVersion({ error: error2 })); + .catch((error_) => setVersion({ error: error_ })); } else { setVersion({ error }); } @@ -144,7 +144,7 @@ export function HomeserverInfo() { type AboutProps = { requestClose: () => void; }; -export function About({ requestClose }: AboutProps) { +export function About({ requestClose }: Readonly) { const mx = useMatrixClient(); const devLabel = IS_RELEASE_TAG ? '' : '-dev'; const buildLabel = BUILD_HASH ? ` (${BUILD_HASH})` : ''; @@ -293,7 +293,7 @@ export function About({ requestClose }: AboutProps) { target="_blank" > Cinny - {' '} + is ©{' '} ) { const stripQuotes = (str?: string) => { if (!str) return ''; // to solve the silly tuwunel - return str.replace(/^["']|["']$/g, ''); + return str.replaceAll(/^["']|["']$/g, ''); }; const [tempColor, setTempColor] = useState(stripQuotes(current) || '#FFFFFF'); diff --git a/src/app/features/settings/account/Profile.tsx b/src/app/features/settings/account/Profile.tsx index 42204d17..68daf9bf 100644 --- a/src/app/features/settings/account/Profile.tsx +++ b/src/app/features/settings/account/Profile.tsx @@ -64,7 +64,7 @@ type ProfileProps = { profile: UserProfile; userId: string; }; -function ProfileAvatar({ profile, userId }: ProfileProps) { +function ProfileAvatar({ profile, userId }: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const capabilities = useCapabilities(); @@ -218,7 +218,7 @@ function ProfileAvatar({ profile, userId }: ProfileProps) { } // eslint-disable-next-line @typescript-eslint/no-unused-vars -function ProfileBanner({ profile, userId }: ProfileProps) { +function ProfileBanner({ profile, userId }: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const [alertRemove, setAlertRemove] = useState(false); @@ -387,7 +387,7 @@ function ProfileBanner({ profile, userId }: ProfileProps) { ); } -function ProfileDisplayName({ profile, userId }: ProfileProps) { +function ProfileDisplayName({ profile, userId }: Readonly) { const mx = useMatrixClient(); const capabilities = useCapabilities(); const disableSetDisplayname = capabilities['m.set_displayname']?.enabled === false; @@ -479,7 +479,7 @@ function ProfileDisplayName({ profile, userId }: ProfileProps) { ); } -function ProfileExtended({ profile, userId }: ProfileProps) { +function ProfileExtended({ profile, userId }: Readonly) { const mx = useMatrixClient(); const setGlobalProfiles = useSetAtom(profilesCacheAtom); @@ -488,12 +488,12 @@ function ProfileExtended({ profile, userId }: ProfileProps) { const currentStatus = presence?.status || ''; // Keys we don't render here nor handle seperately but still need to exclude - const EXCLUDED_KEYS = ['kitty.meow.is_cat', 'kitty.meow.has_cats']; + const EXCLUDED_KEYS = new Set(['kitty.meow.is_cat', 'kitty.meow.has_cats']); // Unknown fields / unimplemented non-matrix-spec fields // Only renders them, can't edit or set const extendedFields = Object.entries(profile.extended || {}).filter( - ([key]) => !EXCLUDED_KEYS.includes(key) + ([key]) => !EXCLUDED_KEYS.has(key) ); const handleSaveField = useCallback( @@ -585,7 +585,7 @@ function ProfileExtended({ profile, userId }: ProfileProps) { onSave={(htmlBio) => { handleSaveField('moe.sable.app.bio', htmlBio); - const cleanedHtml = htmlBio.replace(/<\/blockquote>/g, ''); + const cleanedHtml = htmlBio.replaceAll('
', ''); handleSaveField('chat.commet.profile_bio', { format: 'org.matrix.custom.html', formatted_body: cleanedHtml, @@ -642,7 +642,7 @@ type AnimalCosmeticsProps = { profile: UserProfile; userId: string; }; -function AnimalCosmetics({ profile, userId }: AnimalCosmeticsProps) { +function AnimalCosmetics({ profile, userId }: Readonly) { const mx = useMatrixClient(); const setGlobalProfiles = useSetAtom(profilesCacheAtom); const [renderAnimals, setRenderAnimals] = useSetting(settingsAtom, 'renderAnimals'); diff --git a/src/app/features/settings/cosmetics/Themes.tsx b/src/app/features/settings/cosmetics/Themes.tsx index a57af34a..8d0f75e7 100644 --- a/src/app/features/settings/cosmetics/Themes.tsx +++ b/src/app/features/settings/cosmetics/Themes.tsx @@ -60,7 +60,7 @@ export const ThemeSelector = as<'div', ThemeSelectorProps>( ) ); -function SelectTheme({ disabled }: { disabled?: boolean }) { +function SelectTheme({ disabled }: Readonly<{ disabled?: boolean }>) { const themes = useThemes(); const themeNames = useThemeNames(); const [themeId, setThemeId] = useSetting(settingsAtom, 'themeId'); @@ -288,7 +288,7 @@ function ThemeSettings() { max="100" step="1" value={saturation} - onChange={(e) => setSaturation(parseInt(e.target.value, 10))} + onChange={(e) => setSaturation(Number.parseInt(e.target.value, 10))} style={{ width: toRem(160), cursor: 'pointer', @@ -361,7 +361,7 @@ function PageZoomInput() { 'value' in evt.target && typeof evt.target.value === 'string' ) { - const newZoom = parseInt(evt.target.value, 10); + const newZoom = Number.parseInt(evt.target.value, 10); if (Number.isNaN(newZoom)) return; const safeZoom = Math.max(Math.min(newZoom, 150), 75); setPageZoom(safeZoom); @@ -372,7 +372,7 @@ function PageZoomInput() { return ( void; }; -function DateHint({ hasChanges, handleReset }: DateHintProps) { +function DateHint({ hasChanges, handleReset }: Readonly) { const [anchor, setAnchor] = useState(); const categoryPadding = { padding: config.space.S200, paddingTop: 0 }; @@ -223,7 +223,7 @@ type CustomDateFormatProps = { value: string; onChange: (format: string) => void; }; -function CustomDateFormat({ value, onChange }: CustomDateFormatProps) { +function CustomDateFormat({ value, onChange }: Readonly) { const [dateFormatCustom, setDateFormatCustom] = useState(value); useEffect(() => { @@ -288,12 +288,12 @@ type PresetDateFormatProps = { value: string; onChange: (format: string) => void; }; -function PresetDateFormat({ value, onChange }: PresetDateFormatProps) { +function PresetDateFormat({ value, onChange }: Readonly) { const [menuCords, setMenuCords] = useState(); const dateFormatItems = useDateFormatItems(); const getDisplayDate = (format: string): string => - format !== '' ? dayjs().format(format) : 'Custom'; + format === '' ? 'Custom' : dayjs().format(format); const handleMenu: MouseEventHandler = (evt) => { setMenuCords(evt.currentTarget.getBoundingClientRect()); @@ -415,7 +415,7 @@ function DateAndTime() { ); } -function Editor({ isMobile }: { isMobile: boolean }) { +function Editor({ isMobile }: Readonly<{ isMobile: boolean }>) { const [enterForNewline, setEnterForNewline] = useSetting(settingsAtom, 'enterForNewline'); const [isMarkdown, setIsMarkdown] = useSetting(settingsAtom, 'isMarkdown'); const [hideActivity, setHideActivity] = useSetting(settingsAtom, 'hideActivity'); @@ -681,7 +681,7 @@ function SelectMessageSpacing() { ); } -function SelectRightSwipeAction({ disabled }: { disabled?: boolean }) { +function SelectRightSwipeAction({ disabled }: Readonly<{ disabled?: boolean }>) { const [menuCords, setMenuCords] = useState(); const [action, setAction] = useSetting(settingsAtom, 'rightSwipeAction'); @@ -749,7 +749,7 @@ function SelectRightSwipeAction({ disabled }: { disabled?: boolean }) { ); } -function Gestures({ isMobile }: { isMobile: boolean }) { +function Gestures({ isMobile }: Readonly<{ isMobile: boolean }>) { const [mobileGestures, setMobileGestures] = useSetting(settingsAtom, 'mobileGestures'); return ( @@ -788,7 +788,7 @@ function EmojiSelectorThresholdInput() { const val = evt.target.value; setInputValue(val); - const parsed = parseInt(val, 10); + const parsed = Number.parseInt(val, 10); if (!Number.isNaN(parsed) && parsed >= 1 && parsed <= 10) { setEmojiThreshold(parsed); } @@ -809,7 +809,7 @@ function EmojiSelectorThresholdInput() { return ( void; }; -export function General({ requestClose }: GeneralProps) { +export function General({ requestClose }: Readonly) { return ( diff --git a/src/app/hooks/useCommands.ts b/src/app/hooks/useCommands.ts index 0c2008c0..3a9b2a1c 100644 --- a/src/app/hooks/useCommands.ts +++ b/src/app/hooks/useCommands.ts @@ -36,16 +36,16 @@ import { useRoomNavigate } from './useRoomNavigate'; import { enrichWidgetUrl } from './useRoomWidgets'; import { useUserProfile } from './useUserProfile'; -export const SHRUG = '¯\\_(ツ)_/¯'; +export const SHRUG = String.raw`¯\_(ツ)_/¯`; export const TABLEFLIP = '(╯°□°)╯︵ ┻━┻'; export const UNFLIP = '┬─┬ノ( º_ºノ)'; -const FLAG_PAT = '(?:^|\\s)-(\\w+)\\b'; +const FLAG_PAT = String.raw`(?:^|\s)-(\w+)\b`; const FLAG_REG = new RegExp(FLAG_PAT); const FLAG_REG_G = new RegExp(FLAG_PAT, 'g'); export const splitPayloadContentAndFlags = (payload: string): [string, string | undefined] => { - const flagMatch = payload.match(FLAG_REG); + const flagMatch = new RegExp(FLAG_REG).exec(payload); if (!flagMatch) { return [payload, undefined]; @@ -116,7 +116,7 @@ export const parseTimestampFlag = (input: string): number | undefined => { return undefined; } - const value = parseFloat(match[1]); // supports decimal values + const value = Number.parseFloat(match[1]); // supports decimal values const unit = match[2]; const now = Date.now(); // in milliseconds @@ -282,7 +282,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { }, [Command.Shrug]: { name: Command.Shrug, - description: 'Send ¯\\_(ツ)_/¯ as message', + description: String.raw`Send ¯\_(ツ)_/¯ as message`, exe: async () => undefined, }, [Command.TableFlip]: { @@ -559,8 +559,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { room.roomId, token, 20, - Direction.Forward, - undefined + Direction.Forward ); const { end, chunk } = response; // remove until the latest event; @@ -749,7 +748,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { exe: async (payload) => { const input = payload .trim() - .replace(/[;{}<>]/g, '') + .replaceAll(/[;{}<>]/g, '') .slice(0, 32); const userId = mx.getSafeUserId(); @@ -793,7 +792,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { exe: async (payload) => { const input = payload .trim() - .replace(/[;{}<>]/g, '') + .replaceAll(/[;{}<>]/g, '') .slice(0, 32); const userId = mx.getSafeUserId(); diff --git a/src/app/hooks/useRoomWidgets.ts b/src/app/hooks/useRoomWidgets.ts index a424e2ec..65381ddd 100644 --- a/src/app/hooks/useRoomWidgets.ts +++ b/src/app/hooks/useRoomWidgets.ts @@ -27,16 +27,16 @@ export const resolveWidgetUrl = ( const theme = document.body.classList.contains('dark-theme') ? 'dark' : 'light'; let resolved = url - .replace(/\$matrix_user_id/g, encodeURIComponent(userId)) - .replace(/\$matrix_room_id/g, encodeURIComponent(roomId)) - .replace(/\$matrix_display_name/g, encodeURIComponent(displayName)) - .replace(/\$matrix_avatar_url/g, encodeURIComponent(avatarUrl)) - .replace(/\$matrix_widget_id/g, encodeURIComponent(widgetId)) - .replace(/\$org\.matrix\.msc2873\.client_id/g, encodeURIComponent(clientId)) - .replace(/\$org\.matrix\.msc2873\.client_theme/g, encodeURIComponent(theme)) - .replace(/\$org\.matrix\.msc2873\.client_language/g, encodeURIComponent(lang)) - .replace(/\$org\.matrix\.msc3819\.matrix_device_id/g, encodeURIComponent(deviceId)) - .replace(/\$org\.matrix\.msc4039\.matrix_base_url/g, encodeURIComponent(baseUrl)); + .replaceAll('$matrix_user_id', encodeURIComponent(userId)) + .replaceAll('$matrix_room_id', encodeURIComponent(roomId)) + .replaceAll('$matrix_display_name', encodeURIComponent(displayName)) + .replaceAll('$matrix_avatar_url', encodeURIComponent(avatarUrl)) + .replaceAll('$matrix_widget_id', encodeURIComponent(widgetId)) + .replaceAll('$org.matrix.msc2873.client_id', encodeURIComponent(clientId)) + .replaceAll('$org.matrix.msc2873.client_theme', encodeURIComponent(theme)) + .replaceAll('$org.matrix.msc2873.client_language', encodeURIComponent(lang)) + .replaceAll('$org.matrix.msc3819.matrix_device_id', encodeURIComponent(deviceId)) + .replaceAll('$org.matrix.msc4039.matrix_base_url', encodeURIComponent(baseUrl)); try { const u = new URL(resolved); @@ -112,7 +112,7 @@ export const useRoomWidgets = (room: Room): RoomWidget[] => { return events.reduce((widgets, event) => { const content = event.getContent(); - if (!content || !content.url || Object.keys(content).length === 0) return widgets; + if (!content?.url || Object.keys(content).length === 0) return widgets; const stateKey = event.getStateKey(); if (!stateKey) return widgets; diff --git a/src/app/hooks/useUserProfile.ts b/src/app/hooks/useUserProfile.ts index e5f1a013..22ffa5b2 100644 --- a/src/app/hooks/useUserProfile.ts +++ b/src/app/hooks/useUserProfile.ts @@ -27,7 +27,7 @@ export type UserProfile = { }; const normalizeInfo = (info: any): UserProfile => { - const knownKeys = [ + const knownKeys = new Set([ 'avatar_url', 'displayname', 'io.fsky.nyx.pronouns', @@ -40,11 +40,11 @@ const normalizeInfo = (info: any): UserProfile => { 'moe.sable.app.name_color', 'kitty.meow.has_cats', 'kitty.meow.is_cat', - ]; + ]); const extended: Record = {}; Object.entries(info).forEach(([key, value]) => { - if (!knownKeys.includes(key)) { + if (!knownKeys.has(key)) { extended[key] = value; } }); @@ -68,10 +68,10 @@ const normalizeInfo = (info: any): UserProfile => { const isValidHex = (c: any): string | undefined => { if (typeof c !== 'string') return undefined; // silly tuwunel smh - const cleaned = c.replace(/["']/g, '').trim(); + const cleaned = c.replaceAll(/["']/g, '').trim(); return /^#([0-9A-F]{3,6})$/i.test(cleaned) ? cleaned : undefined; }; -const sanitizeFont = (f: string) => f.replace(/[;{}<>]/g, '').slice(0, 32); +const sanitizeFont = (f: string) => f.replaceAll(/[;{}<>]/g, '').slice(0, 32); export const useUserProfile = ( userId: string, diff --git a/src/app/pages/client/explore/Server.tsx b/src/app/pages/client/explore/Server.tsx index 84fd8f36..0ff06dd5 100644 --- a/src/app/pages/client/explore/Server.tsx +++ b/src/app/pages/client/explore/Server.tsx @@ -90,7 +90,7 @@ type SearchProps = { onSearch: (term: string) => void; onReset: () => void; }; -function Search({ active, loading, searchInputRef, onSearch, onReset }: SearchProps) { +function Search({ active, loading, searchInputRef, onSearch, onReset }: Readonly) { const handleSearchSubmit: FormEventHandler = (evt) => { evt.preventDefault(); const { searchInput } = evt.target as HTMLFormElement & { @@ -149,10 +149,10 @@ const DEFAULT_INSTANCE_NAME = 'Matrix'; function ThirdPartyProtocolsSelector({ instanceId, onChange, -}: { +}: Readonly<{ instanceId?: string; onChange: (instanceId?: string) => void; -}) { +}>) { const mx = useMatrixClient(); const [menuAnchor, setMenuAnchor] = useState(); @@ -251,7 +251,7 @@ type LimitButtonProps = { limit: number; onLimitChange: (limit: string) => void; }; -function LimitButton({ limit, onLimitChange }: LimitButtonProps) { +function LimitButton({ limit, onLimitChange }: Readonly) { const [menuAnchor, setMenuAnchor] = useState(); const handleLimitSubmit: FormEventHandler = (evt) => { @@ -360,7 +360,7 @@ export function PublicRooms() { const currentLimit: number = useMemo(() => { const limitParam = serverSearchParams.limit; if (!limitParam) return FALLBACK_ROOMS_LIMIT; - return parseInt(limitParam, 10) || FALLBACK_ROOMS_LIMIT; + return Number.parseInt(limitParam, 10) || FALLBACK_ROOMS_LIMIT; }, [serverSearchParams.limit]); const resetScroll = useCallback(() => { @@ -371,7 +371,7 @@ export function PublicRooms() { const fetchPublicRooms = useCallback(() => { const limit = typeof serverSearchParams.limit === 'string' - ? parseInt(serverSearchParams.limit, 10) + ? Number.parseInt(serverSearchParams.limit, 10) : FALLBACK_ROOMS_LIMIT; const roomType: string | null | undefined = serverSearchParams.type === 'null' ? null : serverSearchParams.type; @@ -387,7 +387,7 @@ export function PublicRooms() { since: serverSearchParams.since, filter: { generic_search_term: serverSearchParams.term, - room_types: roomType !== undefined ? [roomType] : undefined, + room_types: roomType === undefined ? undefined : [roomType], }, third_party_instance_id: serverSearchParams.instance, } @@ -574,7 +574,7 @@ export function PublicRooms() {
{isLoading && ( - {[...Array(currentLimit).keys()].map((item) => ( + {[...new Array(currentLimit).keys()].map((item) => ( ))} diff --git a/src/app/pages/client/inbox/Notifications.tsx b/src/app/pages/client/inbox/Notifications.tsx index adc79ed2..7543720d 100644 --- a/src/app/pages/client/inbox/Notifications.tsx +++ b/src/app/pages/client/inbox/Notifications.tsx @@ -121,7 +121,7 @@ const groupNotifications = ( const groupIndex = groups.length - 1; const lastAddedGroup: RoomNotificationsGroup | undefined = groups[groupIndex]; - if (lastAddedGroup && notification.room_id === lastAddedGroup.roomId) { + if (notification.room_id === lastAddedGroup?.roomId) { lastAddedGroup.notifications.push(notification); return; } @@ -223,7 +223,7 @@ function RoomNotificationsGroupComp({ legacyUsernameColor, hour24Clock, dateFormatString, -}: RoomNotificationsGroupProps) { +}: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const unread = useRoomUnread(room.roomId, roomToUnreadAtom); @@ -623,7 +623,7 @@ export function Notifications() { loadTimeline(); }, [loadTimeline]); - const lastVItem = vItems[vItems.length - 1]; + const lastVItem = vItems.at(-1); const lastVItemIndex: number | undefined = lastVItem?.index; useEffect(() => { if ( @@ -671,7 +671,7 @@ export function Notifications() { setOnlyHighlighted(false)} - variant={!onlyHighlight ? 'Success' : 'Surface'} + variant={onlyHighlight ? 'Surface' : 'Success'} aria-pressed={!onlyHighlight} before={!onlyHighlight && } outlined @@ -758,7 +758,7 @@ export function Notifications() { {timelineState.status === AsyncStatus.Loading && ( - {[...Array(8).keys()].map((key) => ( + {[...new Array(8).keys()].map((key) => ( ({ item }), @@ -258,7 +257,8 @@ const useDraggableItem = ( setDragging(false); onDragging?.(undefined); }, - }); + }) + : undefined; }, [targetRef, dragHandleRef, item, onDragging]); return dragging; @@ -357,7 +357,7 @@ const useDnDMonitor = ( useEffect(() => { const scrollElement = scrollRef.current; if (!scrollElement) { - throw Error('Scroll element ref not configured'); + throw new Error('Scroll element ref not configured'); } return combine( @@ -399,7 +399,7 @@ function SpaceTab({ onDragging, disabled, onUnpin, -}: SpaceTabProps) { +}: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const targetRef = useRef(null); @@ -515,7 +515,7 @@ type OpenedSpaceFolderProps = { onClose: MouseEventHandler; children?: ReactNode; }; -function OpenedSpaceFolder({ folder, onClose, children }: OpenedSpaceFolderProps) { +function OpenedSpaceFolder({ folder, onClose, children }: Readonly) { const aboveTargetRef = useRef(null); const belowTargetRef = useRef(null); @@ -555,7 +555,7 @@ function ClosedSpaceFolder({ onOpen, onDragging, disabled, -}: ClosedSpaceFolderProps) { +}: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const handlerRef = useRef(null); @@ -628,7 +628,7 @@ function ClosedSpaceFolder({ type SpaceTabsProps = { scrollRef: RefObject; }; -export function SpaceTabs({ scrollRef }: SpaceTabsProps) { +export function SpaceTabs({ scrollRef }: Readonly) { const navigate = useNavigate(); const mx = useMatrixClient(); const screenSize = useScreenSizeContext(); @@ -786,7 +786,7 @@ export function SpaceTabs({ scrollRef }: SpaceTabsProps) { } const activePath = navToActivePath.get(targetSpaceId); - if (activePath && activePath.pathname.startsWith(spacePath)) { + if (activePath?.pathname.startsWith(spacePath)) { navigate(joinPathComponent(activePath)); return; } diff --git a/src/app/utils/ASCIILexicalTable.ts b/src/app/utils/ASCIILexicalTable.ts index 3dcd43d0..dc97b412 100644 --- a/src/app/utils/ASCIILexicalTable.ts +++ b/src/app/utils/ASCIILexicalTable.ts @@ -61,13 +61,13 @@ export class ASCIILexicalTable { } first(): string { - return String.fromCharCode(this.startCode); + return String.fromCodePoint(this.startCode); } last(): string { let str = ''; for (let i = 0; i < this.maxStrWidth; i += 1) { - str += String.fromCharCode(this.endCode); + str += String.fromCodePoint(this.endCode); } return str; } From aa6a764732f56158eef52be8187bedaef1d0bc4c Mon Sep 17 00:00:00 2001 From: Rye Date: Sat, 14 Mar 2026 18:18:57 +0100 Subject: [PATCH 009/146] fix maintainability issues raised by sonarqube - Unicode-aware string methods should be used for proper character handling (typescript:S7758) --- src/app/utils/ASCIILexicalTable.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/utils/ASCIILexicalTable.ts b/src/app/utils/ASCIILexicalTable.ts index dc97b412..46c35c39 100644 --- a/src/app/utils/ASCIILexicalTable.ts +++ b/src/app/utils/ASCIILexicalTable.ts @@ -164,7 +164,7 @@ export class ASCIILexicalTable { prev += String.fromCharCode(lastCode - 1); while (prev.length < this.maxStrWidth) { - prev += String.fromCharCode(this.endCode); + prev += String.fromCodePoint(this.endCode); } return prev; } From b44796ad0c5448327c738a563b13d4b1f73e747d Mon Sep 17 00:00:00 2001 From: Rye Date: Sat, 14 Mar 2026 18:20:55 +0100 Subject: [PATCH 010/146] fix maintainability issues raised by sonarqube - Strings should use "replaceAll()" instead of "replace()" with global regex (typescript:S7781) - Existence checks should use ".includes()" instead of ".indexOf()" or ".lastIndexOf()" (typescript:S7765) - Use "globalThis" instead of "window", "self", or "global" (typescript:S7764) --- src/app/utils/AsyncSearch.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/app/utils/AsyncSearch.ts b/src/app/utils/AsyncSearch.ts index 26dd9204..c799c60b 100644 --- a/src/app/utils/AsyncSearch.ts +++ b/src/app/utils/AsyncSearch.ts @@ -27,12 +27,12 @@ export type TerminateAsyncSearch = () => void; export const normalize = (str: string, options?: NormalizeOption) => { let nStr = str.normalize((options?.normalizeUnicode ?? true) ? 'NFKC' : 'NFC'); if (!options?.caseSensitive) nStr = nStr.toLocaleLowerCase(); - if (options?.ignoreWhitespace ?? true) nStr = nStr.replace(/\s/g, ''); + if (options?.ignoreWhitespace ?? true) nStr = nStr.replaceAll(/\s/g, ''); return nStr; }; export const matchQuery = (item: string, query: string, options?: MatchQueryOption): boolean => { - if (options?.contain) return item.indexOf(query) !== -1; + if (options?.contain) return item.includes(query); return item.startsWith(query); }; @@ -46,7 +46,7 @@ export const AsyncSearch = ( let searchIndex = 0; let sessionStartTimestamp = 0; - let sessionScheduleId: number | undefined; + let sessionScheduleId: ReturnType | undefined; const terminateSearch: TerminateAsyncSearch = () => { resultList = []; @@ -62,7 +62,7 @@ export const AsyncSearch = ( // return if find session got reset if (sessionTimestamp !== sessionStartTimestamp) return; - sessionStartTimestamp = window.performance.now(); + sessionStartTimestamp = globalThis.performance.now(); for (; searchIndex < list.length; searchIndex += 1) { if (match(list[searchIndex], query)) { resultList.push(list[searchIndex]); @@ -71,14 +71,14 @@ export const AsyncSearch = ( } } - const matchFinishTime = window.performance.now(); + const matchFinishTime = globalThis.performance.now(); if (matchFinishTime - sessionStartTimestamp > 8) { const currentFindingCount = resultList.length; const thisSessionTimestamp = sessionStartTimestamp; if (findingCount !== currentFindingCount) onResult(resultList, query); searchIndex += 1; - sessionScheduleId = window.setTimeout(() => find(query, thisSessionTimestamp), 1); + sessionScheduleId = globalThis.setTimeout(() => find(query, thisSessionTimestamp), 1); return; } } From c7ebd49e107539e15602ff94548d6bc16b0fe16e Mon Sep 17 00:00:00 2001 From: Rye Date: Sat, 14 Mar 2026 18:22:32 +0100 Subject: [PATCH 011/146] fix maintainability issues raised by sonarqube - Use "globalThis" instead of "window", "self", or "global" (typescript:S7764) - Unicode-aware string methods should be used for proper character handling (typescript:S7758) --- src/app/utils/MegolmExportEncryption.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/app/utils/MegolmExportEncryption.ts b/src/app/utils/MegolmExportEncryption.ts index 896a8d9d..96250e5b 100644 --- a/src/app/utils/MegolmExportEncryption.ts +++ b/src/app/utils/MegolmExportEncryption.ts @@ -5,7 +5,7 @@ import { createLogger } from './debug'; const logger = createLogger('MegolmExportEncryption'); -const subtleCrypto = window.crypto.subtle; +const subtleCrypto = globalThis.crypto.subtle; export type FriendlyError = { message: string; @@ -43,9 +43,9 @@ function toArrayBufferView(data: Uint8Array): Uint8Array { function encodeBase64(uint8Array: Uint8Array): string { // Misinterpt the Uint8Array as Latin-1. // window.btoa expects a unicode string with codepoints in the range 0-255. - const latin1String = String.fromCharCode.apply(null, Array.from(uint8Array)); + const latin1String = String.fromCodePoint.apply(null, Array.from(uint8Array)); // Use the builtin base64 encoder. - return window.btoa(latin1String); + return globalThis.btoa(latin1String); } /** @@ -55,7 +55,7 @@ function encodeBase64(uint8Array: Uint8Array): string { */ function decodeBase64(base64: string): Uint8Array { // window.atob returns a unicode string with codepoints in the range 0-255. - const latin1String = window.atob(base64); + const latin1String = globalThis.atob(base64); // Encode the string as a Uint8Array const uint8Array = new Uint8Array(new ArrayBuffer(latin1String.length)); for (let i = 0; i < latin1String.length; i += 1) { @@ -303,10 +303,10 @@ export async function encryptMegolmKeyFile( const kdfRounds = normalizedOptions.kdf_rounds || 500000; const salt = new Uint8Array(new ArrayBuffer(16)); - window.crypto.getRandomValues(salt); + globalThis.crypto.getRandomValues(salt); const iv = new Uint8Array(new ArrayBuffer(16)); - window.crypto.getRandomValues(iv); + globalThis.crypto.getRandomValues(iv); // clear bit 63 of the IV to stop us hitting the 64-bit counter boundary // (which would mean we wouldn't be able to decrypt on Android). The loss From afd5a5d488bb793e1c545b5411988056fb7e9445 Mon Sep 17 00:00:00 2001 From: Rye Date: Sat, 14 Mar 2026 18:23:46 +0100 Subject: [PATCH 012/146] fix maintainability issues raised by sonarqube - Unicode-aware string methods should be used for proper character handling (typescript:S7758) --- src/app/utils/colorMXID.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/app/utils/colorMXID.ts b/src/app/utils/colorMXID.ts index 6b40b959..c94a19d4 100644 --- a/src/app/utils/colorMXID.ts +++ b/src/app/utils/colorMXID.ts @@ -6,11 +6,11 @@ function hashCode(str?: string): number { return hash; } for (let i = 0; i < str.length; i += 1) { - const chr = str.charCodeAt(i); + const chr = str.codePointAt(i) ?? 0; // eslint-disable-next-line no-bitwise hash = (hash << 5) - hash + chr; // eslint-disable-next-line no-bitwise - hash |= 0; + hash = Math.trunc(hash); } return Math.abs(hash); } From c5d194576f202278485e6b12c38fd56f969a913b Mon Sep 17 00:00:00 2001 From: Rye Date: Sat, 14 Mar 2026 18:45:04 +0100 Subject: [PATCH 013/146] fix formatting --- src/app/components/editor/output.ts | 3 ++- src/app/components/emoji-board/EmojiBoard.tsx | 6 +++++- src/app/components/event-history/EventHistory.tsx | 5 ++++- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/app/components/editor/output.ts b/src/app/components/editor/output.ts index 6ded4b22..9e390192 100644 --- a/src/app/components/editor/output.ts +++ b/src/app/components/editor/output.ts @@ -128,7 +128,8 @@ export const toMatrixCustomHTML = ( return `${parsedMarkdown}${toMatrixCustomHTML(n, { ...opts, allowBlockMarkdown: false })}`; }; - if (Array.isArray(node)) return node.map((element, index, array) => parseNode(element, index, array)).join(''); + if (Array.isArray(node)) + return node.map((element, index, array) => parseNode(element, index, array)).join(''); if (Text.isText(node)) return textToCustomHtml(node, opts); const children = node.children diff --git a/src/app/components/emoji-board/EmojiBoard.tsx b/src/app/components/emoji-board/EmojiBoard.tsx index bebb6ef2..ff407fdd 100644 --- a/src/app/components/emoji-board/EmojiBoard.tsx +++ b/src/app/components/emoji-board/EmojiBoard.tsx @@ -245,7 +245,11 @@ type StickerSidebarProps = { packs: ImagePack[]; onScrollToGroup: (groupId: string) => void; }; -function StickerSidebar({ activeGroupAtom, packs, onScrollToGroup }: Readonly) { +function StickerSidebar({ + activeGroupAtom, + packs, + onScrollToGroup, +}: Readonly) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); diff --git a/src/app/components/event-history/EventHistory.tsx b/src/app/components/event-history/EventHistory.tsx index 29f9ca16..955a2846 100644 --- a/src/app/components/event-history/EventHistory.tsx +++ b/src/app/components/event-history/EventHistory.tsx @@ -177,7 +177,10 @@ export const EventHistory = as<'div', EventHistoryProps>( ); } - function EventItem({ mEvent, EventContent }: Readonly<{ mEvent: MatrixEvent; EventContent: IContent }>) { + function EventItem({ + mEvent, + EventContent, + }: Readonly<{ mEvent: MatrixEvent; EventContent: IContent }>) { const [isHovered, setIsHovered] = useState(false); return ( Date: Sat, 14 Mar 2026 23:57:41 +0100 Subject: [PATCH 014/146] fix: align workflows to v* tags and support manual release deploys --- .github/actions/prepare-tofu/action.yml | 6 ++++++ .github/workflows/cloudflare-web-deploy.yml | 12 ++++++++++- .github/workflows/docker-publish.yml | 24 +++++++++++++++------ vite.config.ts | 2 +- 4 files changed, 36 insertions(+), 8 deletions(-) diff --git a/.github/actions/prepare-tofu/action.yml b/.github/actions/prepare-tofu/action.yml index 409a50ee..ba818c54 100644 --- a/.github/actions/prepare-tofu/action.yml +++ b/.github/actions/prepare-tofu/action.yml @@ -6,12 +6,18 @@ inputs: description: The OpenTofu version to install. required: false default: '1.11.5' + is_release_tag: + description: Whether the build is for a release tag. Passed through to VITE_IS_RELEASE_TAG. + required: false + default: 'false' runs: using: composite steps: - name: Setup app and build uses: ./.github/actions/setup + env: + VITE_IS_RELEASE_TAG: ${{ inputs.is_release_tag }} with: build: 'true' diff --git a/.github/workflows/cloudflare-web-deploy.yml b/.github/workflows/cloudflare-web-deploy.yml index 83f7f836..3af285f7 100644 --- a/.github/workflows/cloudflare-web-deploy.yml +++ b/.github/workflows/cloudflare-web-deploy.yml @@ -11,6 +11,11 @@ on: tags: - 'v*' workflow_dispatch: + inputs: + git_tag: + description: 'Git tag to deploy (e.g. v1.2.3). Leave empty to deploy current HEAD.' + required: false + type: string env: CLOUDFLARE_API_TOKEN: ${{ secrets.TF_CLOUDFLARE_API_TOKEN }} @@ -49,6 +54,8 @@ jobs: - name: Prepare OpenTofu deployment uses: ./.github/actions/prepare-tofu + with: + is_release_tag: ${{ startsWith(github.ref, 'refs/tags/v') || (github.event_name == 'workflow_dispatch' && inputs.git_tag != '') }} - name: Comment PR plan uses: dflook/tofu-plan@3f5dc358343fb58cd60f83b019e810315aa8258f # v2.2.3 @@ -57,7 +64,7 @@ jobs: label: production apply: - if: (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/sable/v')) || github.event_name == 'workflow_dispatch' + if: (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')) || github.event_name == 'workflow_dispatch' runs-on: ubuntu-latest permissions: contents: read @@ -69,9 +76,12 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: persist-credentials: false + ref: ${{ github.event_name == 'workflow_dispatch' && inputs.git_tag || '' }} - name: Prepare OpenTofu deployment uses: ./.github/actions/prepare-tofu + with: + is_release_tag: ${{ startsWith(github.ref, 'refs/tags/v') || (github.event_name == 'workflow_dispatch' && inputs.git_tag != '') }} - name: Plan infrastructure run: tofu plan -input=false -no-color diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml index b5f9bff2..03a63ef9 100644 --- a/.github/workflows/docker-publish.yml +++ b/.github/workflows/docker-publish.yml @@ -9,6 +9,12 @@ on: paths: - 'Dockerfile' - '.github/workflows/docker-publish.yml' + workflow_dispatch: + inputs: + git_tag: + description: 'Git tag to build and publish (e.g. v1.2.3). Leave empty to build current HEAD as a dev image.' + required: false + type: string env: REGISTRY: ghcr.io @@ -29,6 +35,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: persist-credentials: false + ref: ${{ github.event_name == 'workflow_dispatch' && inputs.git_tag || '' }} - name: Log in to GitHub Container Registry if: github.event_name != 'pull_request' @@ -42,8 +49,13 @@ jobs: id: release_tag shell: bash run: | - if [[ "${GITHUB_REF}" == refs/tags/sable/v* ]]; then - echo "value=${GITHUB_REF#refs/tags/sable/}" >> "$GITHUB_OUTPUT" + if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then + TAG="${{ inputs.git_tag }}" + else + TAG="${GITHUB_REF#refs/tags/}" + fi + if [[ "${TAG}" == v* ]]; then + echo "value=${TAG}" >> "$GITHUB_OUTPUT" echo "is_release=true" >> "$GITHUB_OUTPUT" else echo "value=" >> "$GITHUB_OUTPUT" @@ -58,11 +70,11 @@ jobs: flavor: | latest=false tags: | - # dev branch: short commit SHA + latest - type=sha,prefix=,format=short,enable=${{ github.ref == 'refs/heads/dev' }} - type=raw,value=latest,enable=${{ github.ref == 'refs/heads/dev' }} + # dev branch or manual dispatch without a tag: short commit SHA + latest + type=sha,prefix=,format=short,enable=${{ github.ref == 'refs/heads/dev' || (github.event_name == 'workflow_dispatch' && inputs.git_tag == '') }} + type=raw,value=latest,enable=${{ github.ref == 'refs/heads/dev' || (github.event_name == 'workflow_dispatch' && inputs.git_tag == '') }} - # git tags: semver breakdown + # git tags (push or manual dispatch with a tag): semver breakdown type=semver,pattern={{version}},value=${{ steps.release_tag.outputs.value }},enable=${{ steps.release_tag.outputs.is_release == 'true' }} type=semver,pattern={{major}}.{{minor}},value=${{ steps.release_tag.outputs.value }},enable=${{ steps.release_tag.outputs.is_release == 'true' }} type=semver,pattern={{major}},value=${{ steps.release_tag.outputs.value }},enable=${{ steps.release_tag.outputs.is_release == 'true' && !startsWith(steps.release_tag.outputs.value, 'v0.') }} diff --git a/vite.config.ts b/vite.config.ts index 4f38d92a..d2813304 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -54,7 +54,7 @@ const isReleaseTag = (() => { if (envVal !== undefined && envVal !== '') return envVal === 'true'; try { const tag = execSync('git describe --exact-match --tags HEAD 2>/dev/null').toString().trim(); - return tag.startsWith('sable/v'); + return tag.startsWith('v'); } catch { return false; } From 70e6660224dc8b430c163f3bcc6a55d37dce2109 Mon Sep 17 00:00:00 2001 From: Shea Duma Date: Sun, 15 Mar 2026 05:56:17 +0200 Subject: [PATCH 015/146] improved image loading logic --- .../message/content/ImageContent.tsx | 110 +++++++++++++----- 1 file changed, 79 insertions(+), 31 deletions(-) diff --git a/src/app/components/message/content/ImageContent.tsx b/src/app/components/message/content/ImageContent.tsx index 01756966..f618d434 100644 --- a/src/app/components/message/content/ImageContent.tsx +++ b/src/app/components/message/content/ImageContent.tsx @@ -6,6 +6,8 @@ import { Chip, Icon, Icons, + Menu, + MenuItem, Modal, Overlay, OverlayBackdrop, @@ -15,6 +17,7 @@ import { Tooltip, TooltipProvider, as, + config, } from 'folds'; import classNames from 'classnames'; import { BlurhashCanvas } from 'react-blurhash'; @@ -84,6 +87,7 @@ export const ImageContent = as<'div', ImageContentProps>( const [error, setError] = useState(false); const [viewer, setViewer] = useState(false); const [blurred, setBlurred] = useState(markedAsSpoiler ?? false); + const [isHovered, setIsHovered] = useState(false); const [srcState, loadSrc] = useAsyncCallback( useCallback(async () => { @@ -119,7 +123,14 @@ export const ImageContent = as<'div', ImageContentProps>( }, [autoPlay, loadSrc]); return ( - + setIsHovered(true)} + onPointerLeave={() => setIsHovered(false)} + > + {' '} {srcState.status === AsyncStatus.Success && ( }> @@ -156,7 +167,12 @@ export const ImageContent = as<'div', ImageContentProps>( /> )} {!autoPlay && !markedAsSpoiler && srcState.status === AsyncStatus.Idle && ( - + + {reportedToSentry ? ( + + + + + ) : ( + + )} { + if (phase === VerificationPhase.Done) { + Sentry.metrics.count('sable.crypto.verification_outcome', 1, { + attributes: { outcome: 'completed' }, + }); + } else if (phase === VerificationPhase.Cancelled) { + Sentry.metrics.count('sable.crypto.verification_outcome', 1, { + attributes: { outcome: 'cancelled' }, + }); + } + }, [phase]); + return ( }> diff --git a/src/app/features/bug-report/BugReportModal.tsx b/src/app/features/bug-report/BugReportModal.tsx index 2f90fda3..1babed97 100644 --- a/src/app/features/bug-report/BugReportModal.tsx +++ b/src/app/features/bug-report/BugReportModal.tsx @@ -18,9 +18,12 @@ import { Spinner, Text, TextArea, + Checkbox, } from 'folds'; +import * as Sentry from '@sentry/react'; import { useCloseBugReportModal, useBugReportModalOpen } from '$state/hooks/bugReportModal'; import { stopPropagation } from '$utils/keyboard'; +import { getDebugLogger } from '$utils/debugLogger'; type ReportType = 'bug' | 'feature'; @@ -84,6 +87,7 @@ export function buildGitHubUrl( function BugReportModal() { const close = useCloseBugReportModal(); + const sentryEnabled = Sentry.isInitialized(); const [type, setType] = useState('bug'); const [title, setTitle] = useState(''); @@ -100,6 +104,12 @@ function BugReportModal() { // Shared optional field const [context, setContext] = useState(''); + // Sentry integration options + const [sendToSentry, setSendToSentry] = useState(true); + const [includeDebugLogs, setIncludeDebugLogs] = useState(true); + // When Sentry is enabled, GitHub is opt-in; when disabled, GitHub is always used + const [openOnGitHub, setOpenOnGitHub] = useState(!sentryEnabled); + const [similarIssues, setSimilarIssues] = useState([]); const [searching, setSearching] = useState(false); @@ -141,12 +151,74 @@ function BugReportModal() { const handleSubmit = () => { if (!canSubmit) return; + const fields: Record = type === 'bug' ? { description, reproduction, 'expected-behavior': expectedBehavior, context } : { problem, solution, alternatives, context }; - const url = buildGitHubUrl(type, title.trim(), fields); - window.open(url, '_blank', 'noopener,noreferrer'); + + // Send to Sentry if bug report and option is enabled + if (sendToSentry && type === 'bug') { + const debugLogger = getDebugLogger(); + + // Attach recent logs if user opted in + if (includeDebugLogs) { + debugLogger.attachLogsToSentry(100); + } + + const version = `v${APP_VERSION}${IS_RELEASE_TAG ? '' : '-dev'}${BUILD_HASH ? ` (${BUILD_HASH})` : ''}`; + + // Build a fully self-contained message so all fields are visible + // directly in the Sentry issue detail without digging into sub-sections. + const sentryMessage = [ + `[Bug Report] ${title.trim()}`, + '', + `Description:\n${description}`, + reproduction ? `\nSteps to Reproduce:\n${reproduction}` : '', + expectedBehavior ? `\nExpected Behavior:\n${expectedBehavior}` : '', + context ? `\nAdditional Context:\n${context}` : '', + `\nEnvironment: ${version} · ${navigator.platform}`, + ] + .filter(Boolean) + .join('\n'); + + const eventId = Sentry.captureMessage(sentryMessage, { + level: 'info', + // Group all user bug reports together in Sentry Issues + fingerprint: ['bug-report-modal'], + tags: { + source: 'bug-report-modal', + reportType: type, + }, + extra: { + title: title.trim(), + description, + reproduction: reproduction || '(not provided)', + expectedBehavior: expectedBehavior || '(not provided)', + context: context || '(not provided)', + userAgent: navigator.userAgent, + platform: navigator.platform, + version, + }, + }); + + // Also send as User Feedback so it appears in the Sentry Feedback section + if (eventId) { + Sentry.captureFeedback({ + message: sentryMessage, + name: 'User Bug Report', + associatedEventId: eventId, + }); + } + } + + // Feature requests always go to GitHub; bugs go to GitHub only when Sentry + // is unavailable or the user explicitly opts in. + const shouldOpenGitHub = type === 'feature' || !sentryEnabled || openOnGitHub; + if (shouldOpenGitHub) { + const url = buildGitHubUrl(type, title.trim(), fields); + window.open(url, '_blank', 'noopener,noreferrer'); + } close(); }; @@ -352,6 +424,63 @@ function BugReportModal() { /> + {/* Sentry integration options (only for bug reports when Sentry is configured) */} + {type === 'bug' && sentryEnabled && ( + + Error Tracking + + setSendToSentry((v) => !v)} + /> + + + Send anonymous report to Sentry for error tracking + + + Helps developers identify and fix issues faster. No personal data is + sent. + + + + {sendToSentry && ( + + setIncludeDebugLogs((v) => !v)} + /> + + Include recent debug logs (last 100 entries) + + Provides additional context to help diagnose the issue. Logs are + filtered for sensitive data. + + + + )} + + setOpenOnGitHub((v) => !v)} + /> + + Also create a GitHub issue + + Opens a pre-filled GitHub issue in addition to the Sentry report. + + + + + )} + {/* Actions */} diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 1b0e6f5f..611cf492 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -14,7 +14,6 @@ import { isKeyHotkey } from 'is-hotkey'; import { EventType, IContent, - MatrixEvent, MsgType, RelationType, Room, @@ -115,7 +114,6 @@ import { settingsAtom } from '$state/settings'; import { getMemberDisplayName, getMentionContent, - reactionOrEditEvent, trimReplyFromBody, trimReplyFromFormattedBody, } from '$utils/room'; @@ -153,6 +151,7 @@ import { useRoomPermissions } from '$hooks/useRoomPermissions'; import { AutocompleteNotice } from '$components/editor/autocomplete/AutocompleteNotice'; import { SchedulePickerDialog } from './schedule-send'; import * as css from './schedule-send/SchedulePickerDialog.css'; +import * as Sentry from '@sentry/react'; import { getAudioMsgContent, getFileMsgContent, @@ -162,33 +161,7 @@ import { import { CommandAutocomplete } from './CommandAutocomplete'; import { AudioMessageRecorder } from './AudioMessageRecorder'; -// Returns the event ID of the most recent non-reaction/non-edit event in a thread, -// falling back to the thread root if no replies exist yet. -const getLatestThreadEventId = (room: Room, threadRootId: string): string => { - const thread = room.getThread(threadRootId); - const threadEvents: MatrixEvent[] = thread?.events ?? []; - const filtered = threadEvents.filter( - (ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev) - ); - if (filtered.length > 0) { - return filtered[filtered.length - 1].getId() ?? threadRootId; - } - // Fall back to the live timeline if the Thread object hasn't been registered yet - const liveEvents = room - .getUnfilteredTimelineSet() - .getLiveTimeline() - .getEvents() - .filter( - (ev) => - ev.threadRootId === threadRootId && ev.getId() !== threadRootId && !reactionOrEditEvent(ev) - ); - if (liveEvents.length > 0) { - return liveEvents[liveEvents.length - 1].getId() ?? threadRootId; - } - return threadRootId; -}; - -const getReplyContent = (replyDraft: IReplyDraft | undefined, room?: Room): IEventRelation => { +const getReplyContent = (replyDraft: IReplyDraft | undefined): IEventRelation => { if (!replyDraft) return {}; const relatesTo: IEventRelation = {}; @@ -201,19 +174,13 @@ const getReplyContent = (replyDraft: IReplyDraft | undefined, room?: Room): IEve // Check if this is a reply to a specific message in the thread // (replyDraft.body being empty means it's just a seeded thread draft) if (replyDraft.body && replyDraft.eventId !== replyDraft.relation.event_id) { - // Explicit reply to a specific message — per spec, is_falling_back must be false + // This is a reply to a message within the thread relatesTo['m.in_reply_to'] = { event_id: replyDraft.eventId, }; relatesTo.is_falling_back = false; } else { - // Regular thread message — per spec, include fallback m.in_reply_to pointing to the - // most recent thread message so unthreaded clients can display it as a reply chain - const threadRootId = replyDraft.relation.event_id ?? replyDraft.eventId; - const latestEventId = room ? getLatestThreadEventId(room, threadRootId) : threadRootId; - relatesTo['m.in_reply_to'] = { - event_id: latestEventId, - }; + // This is just a regular thread message relatesTo.is_falling_back = true; } } else { @@ -495,8 +462,7 @@ export const RoomInput = forwardRef( const contents = fulfilledPromiseSettledResult(await Promise.allSettled(contentsPromises)); if (contents.length > 0) { - const replyContent = - plainText?.length === 0 ? getReplyContent(replyDraft, room) : undefined; + const replyContent = plainText?.length === 0 ? getReplyContent(replyDraft) : undefined; if (replyContent) contents[0]['m.relates_to'] = replyContent; if (threadRootId) { setReplyDraft({ @@ -640,7 +606,7 @@ export const RoomInput = forwardRef( content.formatted_body = formattedBody; } if (replyDraft) { - content['m.relates_to'] = getReplyContent(replyDraft, room); + content['m.relates_to'] = getReplyContent(replyDraft); } const invalidate = () => queryClient.invalidateQueries({ queryKey: ['delayedEvents', roomId] }); @@ -700,20 +666,32 @@ export const RoomInput = forwardRef( // Cancel failed — leave state intact for retry } } else { + const msgSendStart = performance.now(); resetInput(); debugLog.info('message', 'Sending message', { roomId, msgtype: (content as any).msgtype }); - mx.sendMessage(roomId, threadRootId ?? null, content as any) + Sentry.startSpan( + { name: 'message.send', op: 'matrix.message', attributes: { encrypted: String(isEncrypted) } }, + () => mx.sendMessage(roomId, threadRootId ?? null, content as any) + ) .then((res) => { debugLog.info('message', 'Message sent successfully', { roomId, eventId: res.event_id, }); + Sentry.metrics.distribution( + 'sable.message.send_latency_ms', + performance.now() - msgSendStart, + { attributes: { encrypted: String(isEncrypted) } } + ); }) .catch((error: unknown) => { debugLog.error('message', 'Failed to send message', { roomId, error: error instanceof Error ? error.message : String(error), }); + Sentry.metrics.count('sable.message.send_error', 1, { + attributes: { encrypted: String(isEncrypted) }, + }); log.error('failed to send message', { roomId }, error); }); } @@ -827,7 +805,7 @@ export const RoomInput = forwardRef( info, }; if (replyDraft) { - content['m.relates_to'] = getReplyContent(replyDraft, room); + content['m.relates_to'] = getReplyContent(replyDraft); if (threadRootId) { setReplyDraft({ userId: mx.getUserId() ?? '', diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index 748162cb..05553039 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -36,6 +36,7 @@ import { ReactEditor } from 'slate-react'; import { Editor } from 'slate'; import { SessionMembershipData } from 'matrix-js-sdk/lib/matrixrtc/CallMembership'; import to from 'await-to-js'; +import * as Sentry from '@sentry/react'; import { useAtomValue, useSetAtom } from 'jotai'; import { as, @@ -290,54 +291,60 @@ const useEventTimelineLoader = ( onError: (err: Error | null) => void ) => useCallback( - async (eventId: string) => { - const withTimeout = async (promise: Promise, timeoutMs: number): Promise => - new Promise((resolve, reject) => { - const timeoutId = globalThis.setTimeout(() => { - reject(new Error('Timed out loading event timeline')); - }, timeoutMs); + async (eventId: string) => + Sentry.startSpan({ name: 'timeline.jump_load', op: 'matrix.timeline' }, async () => { + const jumpLoadStart = performance.now(); + const withTimeout = async (promise: Promise, timeoutMs: number): Promise => + new Promise((resolve, reject) => { + const timeoutId = globalThis.setTimeout(() => { + reject(new Error('Timed out loading event timeline')); + }, timeoutMs); - promise - .then((value) => { - globalThis.clearTimeout(timeoutId); - resolve(value); - }) - .catch((error) => { - globalThis.clearTimeout(timeoutId); - reject(error); - }); - }); + promise + .then((value) => { + globalThis.clearTimeout(timeoutId); + resolve(value); + }) + .catch((error) => { + globalThis.clearTimeout(timeoutId); + reject(error); + }); + }); - if (!room.getUnfilteredTimelineSet().getTimelineForEvent(eventId)) { - await withTimeout( - mx.roomInitialSync(room.roomId, PAGINATION_LIMIT), - EVENT_TIMELINE_LOAD_TIMEOUT_MS + if (!room.getUnfilteredTimelineSet().getTimelineForEvent(eventId)) { + await withTimeout( + mx.roomInitialSync(room.roomId, PAGINATION_LIMIT), + EVENT_TIMELINE_LOAD_TIMEOUT_MS + ); + await withTimeout( + mx.getLatestTimeline(room.getUnfilteredTimelineSet()), + EVENT_TIMELINE_LOAD_TIMEOUT_MS + ); + } + const [err, replyEvtTimeline] = await to( + withTimeout( + mx.getEventTimeline(room.getUnfilteredTimelineSet(), eventId), + EVENT_TIMELINE_LOAD_TIMEOUT_MS + ) ); - await withTimeout( - mx.getLatestTimeline(room.getUnfilteredTimelineSet()), - EVENT_TIMELINE_LOAD_TIMEOUT_MS + if (!replyEvtTimeline) { + onError(err ?? null); + return; + } + const linkedTimelines = getLinkedTimelines(replyEvtTimeline); + const absIndex = getEventIdAbsoluteIndex(linkedTimelines, replyEvtTimeline, eventId); + + if (absIndex === undefined) { + onError(err ?? null); + return; + } + + Sentry.metrics.distribution( + 'sable.timeline.jump_load_ms', + performance.now() - jumpLoadStart ); - } - const [err, replyEvtTimeline] = await to( - withTimeout( - mx.getEventTimeline(room.getUnfilteredTimelineSet(), eventId), - EVENT_TIMELINE_LOAD_TIMEOUT_MS - ) - ); - if (!replyEvtTimeline) { - onError(err ?? null); - return; - } - const linkedTimelines = getLinkedTimelines(replyEvtTimeline); - const absIndex = getEventIdAbsoluteIndex(linkedTimelines, replyEvtTimeline, eventId); - - if (absIndex === undefined) { - onError(err ?? null); - return; - } - - onLoad(eventId, linkedTimelines, absIndex); - }, + onLoad(eventId, linkedTimelines, absIndex); + }), // end startSpan [mx, room, onLoad, onError] ); @@ -414,6 +421,7 @@ const useTimelinePagination = ( }); } try { + const paginateStart = performance.now(); const [err] = await to( mx.paginateEventTimeline(timelineToPaginate, { backwards, @@ -423,6 +431,9 @@ const useTimelinePagination = ( if (err) { if (alive()) { (backwards ? setBackwardStatus : setForwardStatus)('error'); + Sentry.metrics.count('sable.pagination.error', 1, { + attributes: { direction: backwards ? 'backward' : 'forward' }, + }); debugLog.error('timeline', 'Timeline pagination failed', { direction: backwards ? 'backward' : 'forward', error: err instanceof Error ? err.message : String(err), @@ -445,6 +456,16 @@ const useTimelinePagination = ( if (alive()) { recalibratePagination(lTimelines, timelinesEventsCount, backwards); (backwards ? setBackwardStatus : setForwardStatus)('idle'); + Sentry.metrics.distribution( + 'sable.pagination.latency_ms', + performance.now() - paginateStart, + { + attributes: { + direction: backwards ? 'backward' : 'forward', + encrypted: String(!!room?.hasEncryptionStateEvent()), + }, + } + ); debugLog.info('timeline', 'Timeline pagination completed', { direction: backwards ? 'backward' : 'forward', totalEventsNow: getTimelinesEventsCount(lTimelines), @@ -460,12 +481,6 @@ const useTimelinePagination = ( }; const useLiveEventArrive = (room: Room, onArrive: (mEvent: MatrixEvent) => void) => { - // Stable ref so the effect dep array only contains `room`. The listener is - // registered once per room mount; onArrive can change freely without causing - // listener churn during rapid re-renders (e.g. sync error/retry cycles). - const onArriveRef = useRef(onArrive); - onArriveRef.current = onArrive; - useEffect(() => { // Capture the live timeline and registration time. Events appended to the // live timeline AFTER this point can be genuinely new even when @@ -492,14 +507,14 @@ const useLiveEventArrive = (room: Room, onArrive: (mEvent: MatrixEvent) => void) data.timeline === liveTimeline && mEvent.getTs() >= registeredAt - 60_000); if (!isLive) return; - onArriveRef.current(mEvent); + onArrive(mEvent); }; const handleRedaction: RoomEventHandlerMap[RoomEvent.Redaction] = ( mEvent: MatrixEvent, eventRoom: Room | undefined ) => { if (eventRoom?.roomId !== room.roomId) return; - onArriveRef.current(mEvent); + onArrive(mEvent); }; room.on(RoomEvent.Timeline, handleTimelineEvent); @@ -508,13 +523,10 @@ const useLiveEventArrive = (room: Room, onArrive: (mEvent: MatrixEvent) => void) room.removeListener(RoomEvent.Timeline, handleTimelineEvent); room.removeListener(RoomEvent.Redaction, handleRedaction); }; - }, [room]); // stable: re-register only when room changes, not on callback identity changes + }, [room, onArrive]); }; const useRelationUpdate = (room: Room, onRelation: () => void) => { - const onRelationRef = useRef(onRelation); - onRelationRef.current = onRelation; - useEffect(() => { const handleTimelineEvent: EventTimelineSetHandlerMap[RoomEvent.Timeline] = ( mEvent: MatrixEvent, @@ -528,61 +540,42 @@ const useRelationUpdate = (room: Room, onRelation: () => void) => { // also need to trigger a re-render so makeReplaced state is reflected. if (eventRoom?.roomId !== room.roomId || data.liveEvent) return; if (mEvent.getRelation()?.rel_type === RelationType.Replace) { - onRelationRef.current(); + onRelation(); } }; room.on(RoomEvent.Timeline, handleTimelineEvent); return () => { room.removeListener(RoomEvent.Timeline, handleTimelineEvent); }; - }, [room]); + }, [room, onRelation]); }; const useLiveTimelineRefresh = (room: Room, onRefresh: () => void) => { - const onRefreshRef = useRef(onRefresh); - onRefreshRef.current = onRefresh; - useEffect(() => { const handleTimelineRefresh: RoomEventHandlerMap[RoomEvent.TimelineRefresh] = (r: Room) => { if (r.roomId !== room.roomId) return; - onRefreshRef.current(); + onRefresh(); }; - // The SDK fires RoomEvent.TimelineReset on the EventTimelineSet (not the Room) - // when a limited sliding-sync response replaces the live EventTimeline with a - // fresh one. Without this handler, the stored linkedTimelines reference the old - // detached chain and back-pagination silently no-ops, freezing the room. - const handleTimelineReset: EventTimelineSetHandlerMap[RoomEvent.TimelineReset] = () => { - onRefreshRef.current(); - }; - const unfilteredTimelineSet = room.getUnfilteredTimelineSet(); room.on(RoomEvent.TimelineRefresh, handleTimelineRefresh); - unfilteredTimelineSet.on(RoomEvent.TimelineReset, handleTimelineReset); return () => { room.removeListener(RoomEvent.TimelineRefresh, handleTimelineRefresh); - unfilteredTimelineSet.removeListener(RoomEvent.TimelineReset, handleTimelineReset); }; - }, [room]); + }, [room, onRefresh]); }; // Trigger re-render when thread reply counts change so the thread chip updates. const useThreadUpdate = (room: Room, onUpdate: () => void) => { - const onUpdateRef = useRef(onUpdate); - onUpdateRef.current = onUpdate; - useEffect(() => { - // Stable wrapper: the same function identity is kept for the lifetime of - // the room so add/removeListener calls always match. - const handler = () => onUpdateRef.current(); - room.on(ThreadEvent.New, handler); - room.on(ThreadEvent.Update, handler); - room.on(ThreadEvent.NewReply, handler); + room.on(ThreadEvent.New, onUpdate); + room.on(ThreadEvent.Update, onUpdate); + room.on(ThreadEvent.NewReply, onUpdate); return () => { - room.removeListener(ThreadEvent.New, handler); - room.removeListener(ThreadEvent.Update, handler); - room.removeListener(ThreadEvent.NewReply, handler); + room.removeListener(ThreadEvent.New, onUpdate); + room.removeListener(ThreadEvent.Update, onUpdate); + room.removeListener(ThreadEvent.NewReply, onUpdate); }; - }, [room]); + }, [room, onUpdate]); }; // Returns the number of replies in a thread, counting actual reply events @@ -793,10 +786,6 @@ export function RoomTimeline({ const imagePackRooms: Room[] = useImagePackRooms(room.roomId, roomToParents); const [unreadInfo, setUnreadInfo] = useState(() => getRoomUnreadInfo(room, true)); - // Stable ref so listeners that only need to *read* unreadInfo don't force - // effect re-registration (and listener churn) every time a new message arrives. - const unreadInfoRef = useRef(unreadInfo); - unreadInfoRef.current = unreadInfo; const readUptoEventIdRef = useRef(); if (unreadInfo) { readUptoEventIdRef.current = unreadInfo.readUptoEventId; @@ -811,12 +800,6 @@ export function RoomTimeline({ atBottomRef.current = val; }, []); - // Set to true by the useLiveTimelineRefresh callback when the timeline is - // re-initialised (TimelineRefresh or TimelineReset). Allows the range self-heal - // effect below to run even when atBottom=false, so the virtual paginator window - // is restored to the live end without forcing a viewport scroll. - const timelineJustResetRef = useRef(false); - const scrollRef = useRef(null); const scrollToBottomRef = useRef({ count: 0, @@ -879,6 +862,14 @@ export function RoomTimeline({ // Log timeline component mount/unmount useEffect(() => { + const mode = eventId ? 'jump' : 'live'; + Sentry.metrics.count('sable.timeline.open', 1, { attributes: { mode } }); + const initialWindowSize = timeline.range.end - timeline.range.start; + if (initialWindowSize > 0) { + Sentry.metrics.distribution('sable.timeline.render_window', initialWindowSize, { + attributes: { encrypted: String(room.hasEncryptionStateEvent()), mode }, + }); + } debugLog.info('timeline', 'Timeline mounted', { roomId: room.roomId, eventId, @@ -995,17 +986,14 @@ export function RoomTimeline({ // otherwise we update timeline without paginating // so timeline can be updated with evt like: edits, reactions etc if (atBottomRef.current && atLiveEndRef.current) { - if ( - document.hasFocus() && - (!unreadInfoRef.current || mEvt.getSender() === mx.getUserId()) - ) { + if (document.hasFocus() && (!unreadInfo || mEvt.getSender() === mx.getUserId())) { // Check if the document is in focus (user is actively viewing the app), // and either there are no unread messages or the latest message is from the current user. // If either condition is met, trigger the markAsRead function to send a read receipt. requestAnimationFrame(() => markAsRead(mx, mEvt.getRoomId()!, hideReads)); } - if (!document.hasFocus() && !unreadInfoRef.current) { + if (!document.hasFocus() && !unreadInfo) { setUnreadInfo(getRoomUnreadInfo(room)); } @@ -1024,11 +1012,11 @@ export function RoomTimeline({ return; } setTimeline((ct) => ({ ...ct })); - if (!unreadInfoRef.current) { + if (!unreadInfo) { setUnreadInfo(getRoomUnreadInfo(room)); } }, - [mx, room, hideReads] + [mx, room, unreadInfo, hideReads] ) ); @@ -1038,8 +1026,11 @@ export function RoomTimeline({ eventRoom: Room | undefined ) => { if (eventRoom?.roomId !== room.roomId) return; + if (_mEvent.getAssociatedStatus() === EventStatus.NOT_SENT) { + Sentry.metrics.count('sable.message.send_failed', 1); + } setTimeline((ct) => ({ ...ct })); - if (!unreadInfoRef.current) { + if (!unreadInfo) { setUnreadInfo(getRoomUnreadInfo(room)); } }; @@ -1048,7 +1039,7 @@ export function RoomTimeline({ return () => { room.removeListener(RoomEvent.LocalEchoUpdated, handleLocalEchoUpdated); }; - }, [room, setTimeline, setUnreadInfo]); + }, [room, unreadInfo, setTimeline, setUnreadInfo]); const handleOpenEvent = useCallback( async ( @@ -1099,33 +1090,34 @@ export function RoomTimeline({ useLiveTimelineRefresh( room, useCallback(() => { - // Always reinitialize on TimelineRefresh/TimelineReset. With sliding sync, - // a limited response replaces the room's live EventTimeline with a brand-new - // object. At that moment liveTimelineLinked is stale-false (stored - // linkedTimelines reference the old detached chain), so any guard on that - // flag would skip reinit, causing back-pagination to no-op silently and the - // room to appear frozen. Unconditional reinit is correct: both events signal - // that stored range/indices against the old chain are invalid. + // Always reinitialize on TimelineRefresh. With sliding sync, a limited + // response replaces the room's live EventTimeline with a brand-new object, + // firing TimelineRefresh. At that moment liveTimelineLinked is stale-false + // (the stored linkedTimelines still reference the old detached object), + // so the previous guard `if (liveTimelineLinked || ...)` would silently + // skip reinit. Back-pagination then calls paginateEventTimeline against + // the dead old timeline, which no-ops, and the IntersectionObserver never + // re-fires because intersection state didn't change — causing a permanent + // hang at the top of the timeline with no spinner and no history loaded. + // Unconditionally reinitializing is correct: TimelineRefresh signals that + // the SDK has replaced the timeline chain, so any stored range/indices + // against the old chain are invalid anyway. // - // Only force the viewport to the bottom if the user was already there. - // When the user has scrolled up to read history and a sync gap fires, we - // must still reinit (the old timeline is gone), but scrolling them back to - // the bottom is jarring. Instead we set timelineJustResetRef=true so the - // self-heal effect below can advance the range as events arrive on the fresh - // timeline, without atBottom=true being required. - // - // When the user WAS at the bottom we still call setAtBottom(true) so a - // transient isIntersecting=false from the IntersectionObserver during the - // DOM transition cannot stick the "Jump to Latest" button on-screen. + // Also force atBottom=true and queue a scroll-to-bottom. The SDK fires + // TimelineRefresh before adding new events to the fresh live timeline, so + // getInitialTimeline captures range.end=0. Once events arrive the + // rangeAtEnd self-heal useEffect needs atBottom=true to run; the + // IntersectionObserver may have transiently fired isIntersecting=false + // during the render transition, leaving atBottom=false and causing the + // "Jump to Latest" button to stick permanently. Forcing atBottom here is + // correct: TimelineRefresh always reinits to the live end, so the user + // should be repositioned to the bottom regardless. + Sentry.metrics.count('sable.timeline.reinit', 1); debugLog.info('timeline', 'Live timeline refresh triggered', { roomId: room.roomId }); - const wasAtBottom = atBottomRef.current; - timelineJustResetRef.current = true; setTimeline(getInitialTimeline(room)); - if (wasAtBottom) { - setAtBottom(true); - scrollToBottomRef.current.count += 1; - scrollToBottomRef.current.smooth = false; - } + setAtBottom(true); + scrollToBottomRef.current.count += 1; + scrollToBottomRef.current.smooth = false; }, [room, setAtBottom]) ); @@ -1152,17 +1144,9 @@ export function RoomTimeline({ // position we want to display. Without this, loading more history makes it look // like we've scrolled up because the range (0, 10) is now showing the old events // instead of the latest ones. - // - // Also runs after a timeline reset (timelineJustResetRef=true) even when - // atBottom=false. After TimelineReset the SDK fires the event before populating - // the fresh timeline, so getInitialTimeline sees range.end=0. When events - // arrive eventsLength grows and we need to heal the range back to the live end - // regardless of the user's scroll position. useEffect(() => { - const resetPending = timelineJustResetRef.current; - if ((atBottom || resetPending) && liveTimelineLinked && eventsLength > timeline.range.end) { - if (resetPending) timelineJustResetRef.current = false; - // More events exist than our current range shows. Adjust to the live end. + if (atBottom && liveTimelineLinked && eventsLength > timeline.range.end) { + // More events exist than our current range shows. Adjust to stay at bottom. setTimeline((ct) => ({ ...ct, range: { diff --git a/src/app/features/room/message/EncryptedContent.tsx b/src/app/features/room/message/EncryptedContent.tsx index ddd82db4..33955b6e 100644 --- a/src/app/features/room/message/EncryptedContent.tsx +++ b/src/app/features/room/message/EncryptedContent.tsx @@ -2,6 +2,7 @@ import { MatrixEvent, MatrixEventEvent, MatrixEventHandlerMap } from '$types/mat import { ReactNode, useEffect, useState } from 'react'; import { MessageEvent } from '$types/matrix/room'; import { useMatrixClient } from '$hooks/useMatrixClient'; +import * as Sentry from '@sentry/react'; type EncryptedContentProps = { mEvent: MatrixEvent; @@ -14,12 +15,27 @@ export function EncryptedContent({ mEvent, children }: EncryptedContentProps) { useEffect(() => { if (mEvent.getType() !== MessageEvent.RoomMessageEncrypted) return; - mx.decryptEventIfNeeded(mEvent).catch(() => undefined); + // Sample 5% of events for per-event decryption latency profiling + if (Math.random() < 0.05) { + const start = performance.now(); + Sentry.startSpan({ name: 'decrypt.event', op: 'matrix.crypto' }, () => + mx.decryptEventIfNeeded(mEvent).then(() => { + Sentry.metrics.distribution('sable.decryption.event_ms', performance.now() - start); + }) + ).catch(() => undefined); + } else { + mx.decryptEventIfNeeded(mEvent).catch(() => undefined); + } }, [mx, mEvent]); useEffect(() => { toggleEncrypted(mEvent.getType() === MessageEvent.RoomMessageEncrypted); const handleDecrypted: MatrixEventHandlerMap[MatrixEventEvent.Decrypted] = (event) => { + if (event.isDecryptionFailure()) { + Sentry.metrics.count('sable.decryption.failure', 1, { + attributes: { reason: event.decryptionFailureReason ?? 'UNKNOWN_ERROR' }, + }); + } toggleEncrypted(event.getType() === MessageEvent.RoomMessageEncrypted); }; mEvent.on(MatrixEventEvent.Decrypted, handleDecrypted); diff --git a/src/app/features/settings/developer-tools/DevelopTools.tsx b/src/app/features/settings/developer-tools/DevelopTools.tsx index d230620a..b717f226 100644 --- a/src/app/features/settings/developer-tools/DevelopTools.tsx +++ b/src/app/features/settings/developer-tools/DevelopTools.tsx @@ -12,6 +12,7 @@ import { SequenceCardStyle } from '$features/settings/styles.css'; import { AccountData } from './AccountData'; import { SyncDiagnostics } from './SyncDiagnostics'; import { DebugLogViewer } from './DebugLogViewer'; +import { SentrySettings } from './SentrySettings'; type DeveloperToolsProps = { requestClose: () => void; @@ -126,6 +127,11 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) { )} + {developerTools && ( + + + + )} diff --git a/src/app/features/settings/developer-tools/SentrySettings.tsx b/src/app/features/settings/developer-tools/SentrySettings.tsx new file mode 100644 index 00000000..0bb51a98 --- /dev/null +++ b/src/app/features/settings/developer-tools/SentrySettings.tsx @@ -0,0 +1,240 @@ +import { useState, useEffect } from 'react'; +import { Box, Text, Switch, Button } from 'folds'; +import { SequenceCard } from '$components/sequence-card'; +import { SettingTile } from '$components/setting-tile'; +import { SequenceCardStyle } from '$features/settings/styles.css'; +import { getDebugLogger, LogCategory } from '$utils/debugLogger'; + +const ALL_CATEGORIES: LogCategory[] = [ + 'sync', + 'network', + 'notification', + 'message', + 'call', + 'ui', + 'timeline', + 'error', + 'general', +]; + +export function SentrySettings() { + const [sentryEnabled, setSentryEnabled] = useState( + localStorage.getItem('sable_sentry_enabled') !== 'false' + ); + const [sessionReplayEnabled, setSessionReplayEnabled] = useState( + localStorage.getItem('sable_sentry_replay_enabled') === 'true' + ); + const [needsRefresh, setNeedsRefresh] = useState(false); + const [categoryEnabled, setCategoryEnabled] = useState>(() => { + const logger = getDebugLogger(); + return Object.fromEntries( + ALL_CATEGORIES.map((c) => [c, logger.getBreadcrumbCategoryEnabled(c)]) + ) as Record; + }); + const [sentryStats, setSentryStats] = useState(() => getDebugLogger().getSentryStats()); + + useEffect(() => { + const interval = setInterval(() => { + setSentryStats(getDebugLogger().getSentryStats()); + }, 5000); + return () => clearInterval(interval); + }, []); + + const handleSentryToggle = (enabled: boolean) => { + setSentryEnabled(enabled); + if (enabled) { + localStorage.removeItem('sable_sentry_enabled'); + } else { + localStorage.setItem('sable_sentry_enabled', 'false'); + } + setNeedsRefresh(true); + }; + + const handleReplayToggle = (enabled: boolean) => { + setSessionReplayEnabled(enabled); + if (enabled) { + localStorage.setItem('sable_sentry_replay_enabled', 'true'); + } else { + localStorage.removeItem('sable_sentry_replay_enabled'); + } + setNeedsRefresh(true); + }; + + const handleCategoryToggle = (category: LogCategory, enabled: boolean) => { + getDebugLogger().setBreadcrumbCategoryEnabled(category, enabled); + setCategoryEnabled((prev) => ({ ...prev, [category]: enabled })); + }; + + const handleExportLogs = () => { + const data = getDebugLogger().exportLogs(); + const blob = new Blob([data], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = `sable-debug-logs-${Date.now()}.json`; + a.click(); + URL.revokeObjectURL(url); + }; + + const isSentryConfigured = Boolean(import.meta.env.VITE_SENTRY_DSN); + const environment = import.meta.env.VITE_SENTRY_ENVIRONMENT || import.meta.env.MODE; + const isProd = environment === 'production'; + const traceSampleRate = isProd ? '10%' : '100%'; + const replaySampleRate = isProd ? '10%' : '100%'; + + return ( + + Error Tracking (Sentry) + {needsRefresh && ( + + + Please refresh the page for Sentry settings to take effect. + + + )} + {!isSentryConfigured && ( + + + Sentry is not configured. Set VITE_SENTRY_DSN to enable error tracking. + + + )} + + + } + /> + {sentryEnabled && isSentryConfigured && ( + <> + + } + /> + + )} + + {isSentryConfigured && ( + + + All data sent to Sentry is filtered for sensitive information like passwords and access + tokens. You can opt out at any time. + + + Session Replay Privacy: When enabled, all text content, media + (images/video/audio), and form inputs are completely masked or blocked. Only UI + structure and interactions are recorded. + + + )} + + {isSentryConfigured && sentryEnabled && ( + <> + Performance Metrics + + + + + + + Breadcrumb Categories + + Control which log categories are included as breadcrumbs in Sentry error reports. + Disabling a category reduces noise without affecting error capture. + + + {ALL_CATEGORIES.map((cat) => ( + handleCategoryToggle(cat, v)} + /> + } + /> + ))} + + + Debug Logs + + + + Export JSON + + } + /> + + + )} + + ); +} diff --git a/src/app/hooks/useBlobCache.ts b/src/app/hooks/useBlobCache.ts index 7b40e292..96ac18f7 100644 --- a/src/app/hooks/useBlobCache.ts +++ b/src/app/hooks/useBlobCache.ts @@ -3,6 +3,10 @@ import { useState, useEffect } from 'react'; const imageBlobCache = new Map(); const inflightRequests = new Map>(); +export function getBlobCacheStats(): { cacheSize: number; inflightCount: number } { + return { cacheSize: imageBlobCache.size, inflightCount: inflightRequests.size }; +} + export function useBlobCache(url?: string): string | undefined { const [cacheState, setCacheState] = useState<{ sourceUrl?: string; blobUrl?: string }>({ sourceUrl: url, diff --git a/src/app/hooks/useCallSignaling.ts b/src/app/hooks/useCallSignaling.ts index 1e8a7dfe..cd657e47 100644 --- a/src/app/hooks/useCallSignaling.ts +++ b/src/app/hooks/useCallSignaling.ts @@ -29,13 +29,6 @@ export function useCallSignaling() { const mutedRoomId = useAtomValue(mutedCallRoomIdAtom); const setMutedRoomId = useSetAtom(mutedCallRoomIdAtom); - // Stable refs so volatile values (mutedRoomId, ring callbacks) don't force - // the listener registration effect to re-run — which would cause the - // SessionEnded and RoomState.events listeners to accumulate when muting - // or when call state changes rapidly during a sync retry cycle. - const mutedRoomIdRef = useRef(mutedRoomId); - mutedRoomIdRef.current = mutedRoomId; - useEffect(() => { const inc = new Audio(RingtoneSound); inc.loop = true; @@ -79,16 +72,6 @@ export function useCallSignaling() { [setIncomingCall] ); - // Must be declared after the callbacks above so the initial useRef(value) call - // sees their current identity. Updated on every render so the effect closure - // always calls the latest version without needing them in the dep array. - const playRingingRef = useRef(playRinging); - playRingingRef.current = playRinging; - const stopRingingRef = useRef(stopRinging); - stopRingingRef.current = stopRinging; - const playOutgoingRingingRef = useRef(playOutgoingRinging); - playOutgoingRingingRef.current = playOutgoingRinging; - useEffect(() => { if (!mx || !mx.matrixRTC) return undefined; @@ -98,7 +81,7 @@ export function useCallSignaling() { const signal = Array.from(mDirects).reduce( (acc, roomId) => { - if (acc.incoming || mutedRoomIdRef.current === roomId) return acc; + if (acc.incoming || mutedRoomId === roomId) return acc; const room = mx.getRoom(roomId); if (!room) return acc; @@ -158,11 +141,11 @@ export function useCallSignaling() { ); if (signal.incoming) { - playRingingRef.current(signal.incoming); + playRinging(signal.incoming); } else if (signal.outgoing) { - playOutgoingRingingRef.current(signal.outgoing); + playOutgoingRinging(signal.outgoing); } else { - stopRingingRef.current(); + stopRinging(); if (!signal.outgoing) outgoingStartRef.current = null; } }; @@ -172,7 +155,7 @@ export function useCallSignaling() { const handleUpdate = () => checkDMsForActiveCalls(); const handleSessionEnded = (roomId: string) => { - if (mutedRoomIdRef.current === roomId) setMutedRoomId(null); + if (mutedRoomId === roomId) setMutedRoomId(null); callPhaseRef.current[roomId] = 'IDLE'; checkDMsForActiveCalls(); }; @@ -188,9 +171,9 @@ export function useCallSignaling() { mx.matrixRTC.off(MatrixRTCSessionManagerEvents.SessionStarted, handleUpdate); mx.matrixRTC.off(MatrixRTCSessionManagerEvents.SessionEnded, handleSessionEnded); mx.off(RoomStateEvent.Events, handleUpdate); - stopRingingRef.current(); + stopRinging(); }; - }, [mx, mDirects, setMutedRoomId]); // stable: volatile deps accessed via refs above + }, [mx, mDirects, playRinging, stopRinging, mutedRoomId, setMutedRoomId, playOutgoingRinging]); return null; } diff --git a/src/app/hooks/useKeyBackup.ts b/src/app/hooks/useKeyBackup.ts index 1cc531ed..3714ec6b 100644 --- a/src/app/hooks/useKeyBackup.ts +++ b/src/app/hooks/useKeyBackup.ts @@ -6,6 +6,7 @@ import { KeyBackupInfo, } from '$types/matrix-sdk'; import { useCallback, useEffect, useState } from 'react'; +import * as Sentry from '@sentry/react'; import { useMatrixClient } from './useMatrixClient'; import { useAlive } from './useAlive'; @@ -92,6 +93,15 @@ export const useKeyBackupSync = (): [number, string | undefined] => { useKeyBackupFailedChange( useCallback((f) => { if (typeof f === 'string') { + Sentry.addBreadcrumb({ + category: 'crypto', + message: 'Key backup failed', + level: 'error', + data: { errcode: f }, + }); + Sentry.metrics.count('sable.crypto.key_backup_failures', 1, { + attributes: { errcode: f }, + }); setFailure(f); setRemaining(0); } diff --git a/src/app/pages/App.tsx b/src/app/pages/App.tsx index 0408f38e..87687fd8 100644 --- a/src/app/pages/App.tsx +++ b/src/app/pages/App.tsx @@ -3,7 +3,7 @@ import { OverlayContainerProvider, PopOutContainerProvider, TooltipContainerProv import { RouterProvider } from 'react-router-dom'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { ReactQueryDevtools } from '@tanstack/react-query-devtools'; -import { ErrorBoundary } from 'react-error-boundary'; +import * as Sentry from '@sentry/react'; import { ClientConfigLoader } from '$components/ClientConfigLoader'; import { ClientConfigProvider } from '$hooks/useClientConfig'; @@ -23,7 +23,14 @@ function App() { const portalContainer = document.getElementById('portalContainer') ?? undefined; return ( - + ( + + )} + > @@ -51,7 +58,7 @@ function App() { - + ); } diff --git a/src/app/pages/Router.tsx b/src/app/pages/Router.tsx index f14567f7..71b72157 100644 --- a/src/app/pages/Router.tsx +++ b/src/app/pages/Router.tsx @@ -6,8 +6,10 @@ import { createRoutesFromElements, redirect, } from 'react-router-dom'; +import * as Sentry from '@sentry/react'; import { ClientConfig } from '$hooks/useClientConfig'; +import { ErrorPage } from '$components/DefaultErrorPage'; import { Room } from '$features/room'; import { Lobby } from '$features/lobby'; import { PageRoot } from '$components/page'; @@ -117,10 +119,20 @@ export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize) return null; }} element={ - <> - - - + ( + + )} + beforeCapture={(scope) => scope.setTag('section', 'auth')} + > + <> + + + + } > } /> @@ -142,7 +154,16 @@ export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize) return null; }} element={ - + ( + + )} + beforeCapture={(scope) => scope.setTag('section', 'client')} + > + {/* HandleNotificationClick must live outside ClientRoot's loading gate so SW notification-click postMessages are never dropped during client reloads (e.g., account switches). It only needs navigate + Jotai atoms. */} @@ -196,6 +217,7 @@ export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize) + } > (mx.loginRequest(data)); - if (err) { - if (err.httpStatus === 400) { - debugLog.error('general', 'Login failed - invalid request', { httpStatus: 400 }); - throw new MatrixError({ - errcode: LoginError.InvalidRequest, - }); - } - if (err.httpStatus === 429) { - debugLog.error('general', 'Login failed - rate limited', { httpStatus: 429 }); - throw new MatrixError({ - errcode: LoginError.RateLimited, - }); - } - if (err.errcode === ErrorCode.M_USER_DEACTIVATED) { - debugLog.error('general', 'Login failed - user deactivated', { errcode: err.errcode }); - throw new MatrixError({ - errcode: LoginError.UserDeactivated, - }); - } + return Sentry.startSpan( + { name: 'auth.login', op: 'auth', attributes: { 'auth.method': data.type } }, + async (span) => { + const [err, res] = await to(mx.loginRequest(data)); - if (err.httpStatus === 403) { - debugLog.error('general', 'Login failed - forbidden', { httpStatus: 403 }); - throw new MatrixError({ - errcode: LoginError.Forbidden, - }); - } + if (err) { + span.setAttribute('auth.error', err.errcode ?? 'unknown'); + Sentry.metrics.count('sable.auth.login_failed', 1, { + attributes: { errcode: err.errcode ?? 'unknown' }, + }); + if (err.httpStatus === 400) { + debugLog.error('general', 'Login failed - invalid request', { httpStatus: 400 }); + throw new MatrixError({ + errcode: LoginError.InvalidRequest, + }); + } + if (err.httpStatus === 429) { + debugLog.error('general', 'Login failed - rate limited', { httpStatus: 429 }); + throw new MatrixError({ + errcode: LoginError.RateLimited, + }); + } + if (err.errcode === ErrorCode.M_USER_DEACTIVATED) { + debugLog.error('general', 'Login failed - user deactivated', { errcode: err.errcode }); + throw new MatrixError({ + errcode: LoginError.UserDeactivated, + }); + } - debugLog.error('general', 'Login failed - unknown error', { - error: err.message, - httpStatus: err.httpStatus, - }); - throw new MatrixError({ - errcode: LoginError.Unknown, - }); - } - debugLog.info('general', 'Login successful', { userId: res.user_id, deviceId: res.device_id }); - return { - baseUrl: url, - response: res, - }; + if (err.httpStatus === 403) { + debugLog.error('general', 'Login failed - forbidden', { httpStatus: 403 }); + throw new MatrixError({ + errcode: LoginError.Forbidden, + }); + } + + debugLog.error('general', 'Login failed - unknown error', { + error: err.message, + httpStatus: err.httpStatus, + }); + throw new MatrixError({ + errcode: LoginError.Unknown, + }); + } + + span.setAttribute('auth.success', true); + debugLog.info('general', 'Login successful', { + userId: res.user_id, + deviceId: res.device_id, + }); + return { + baseUrl: url, + response: res, + }; + } + ); }; export const useLoginComplete = (data?: CustomLoginResponse) => { diff --git a/src/app/pages/client/BackgroundNotifications.tsx b/src/app/pages/client/BackgroundNotifications.tsx index 0a00fcc1..2d382fcc 100644 --- a/src/app/pages/client/BackgroundNotifications.tsx +++ b/src/app/pages/client/BackgroundNotifications.tsx @@ -39,6 +39,7 @@ import { buildRoomMessageNotification, resolveNotificationPreviewText, } from '$utils/notificationStyle'; +import * as Sentry from '@sentry/react'; import { startClient, stopClient } from '$client/initMatrix'; import { useClientConfig } from '$hooks/useClientConfig'; import { mobileOrTablet } from '$utils/user-agent'; @@ -214,6 +215,7 @@ export function BackgroundNotifications() { clientCleanupRef.current.delete(userId); stopClient(mx); current.delete(userId); + Sentry.metrics.gauge('sable.background.client_count', current.size); // Clear the background unread badge when this session is no longer a background account. setBackgroundUnreads((prev) => { const next = { ...prev }; @@ -232,6 +234,7 @@ export function BackgroundNotifications() { .then(async (mx) => { sessionMx = mx; current.set(session.userId, mx); + Sentry.metrics.gauge('sable.background.client_count', current.size); await waitForSync(mx); @@ -505,6 +508,7 @@ export function BackgroundNotifications() { userId: session.userId, error: err, }); + Sentry.captureException(err, { tags: { component: 'BackgroundNotifications' } }); // Remove the stuck/failed client from current so future runs (or the // retry below) can attempt a fresh start. diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx index 5ec5d880..fab2261e 100644 --- a/src/app/pages/client/ClientNonUIFeatures.tsx +++ b/src/app/pages/client/ClientNonUIFeatures.tsx @@ -1,4 +1,5 @@ import { useAtomValue, useSetAtom } from 'jotai'; +import * as Sentry from '@sentry/react'; import { ReactNode, useCallback, useEffect, useRef } from 'react'; import { useNavigate } from 'react-router-dom'; import { @@ -48,6 +49,8 @@ import { useSlidingSyncActiveRoom } from '$hooks/useSlidingSyncActiveRoom'; import { getSlidingSyncManager } from '$client/initMatrix'; import { NotificationBanner } from '$components/notification-banner'; import { useCallSignaling } from '$hooks/useCallSignaling'; +import { getBlobCacheStats } from '$hooks/useBlobCache'; +import { lastVisitedRoomIdAtom } from '$state/room/lastRoom'; import { getInboxInvitesPath } from '../pathUtils'; import { BackgroundNotifications } from './BackgroundNotifications'; @@ -263,6 +266,8 @@ function MessageNotifications() { // already checked focus when the encrypted event arrived, and want to use that // original state rather than re-checking after decryption completes). const skipFocusCheckEvents = new Set(); + // Tracks when each event first arrived so we can measure notification delivery latency + const notifyTimerMap = new Map(); const handleTimelineEvent: RoomEventHandlerMap[RoomEvent.Timeline] = ( mEvent, @@ -274,6 +279,10 @@ function MessageNotifications() { if (mx.getSyncState() !== 'SYNCING') return; const eventId = mEvent.getId(); + // Record event arrival time once per eventId (re-entry via handleDecrypted must not reset it) + if (eventId && !notifyTimerMap.has(eventId)) { + notifyTimerMap.set(eventId, performance.now()); + } const shouldSkipFocusCheck = eventId && skipFocusCheckEvents.has(eventId); if (!shouldSkipFocusCheck) { if (document.hasFocus() && (selectedRoomId === room?.roomId || notificationSelected)) @@ -334,6 +343,17 @@ function MessageNotifications() { // Check if this is a DM using multiple signals for robustness const isDM = isDMRoom(room, mDirectsRef.current); + + // Measure total notification delivery latency (includes decryption wait for E2EE events) + const arrivalMs = notifyTimerMap.get(eventId); + if (arrivalMs !== undefined) { + Sentry.metrics.distribution( + 'sable.notification.delivery_ms', + performance.now() - arrivalMs, + { attributes: { encrypted: String(mEvent.isEncrypted()), dm: String(isDM) } } + ); + notifyTimerMap.delete(eventId); + } const pushActions = pushProcessor.actionsForEvent(mEvent); // For DMs with "All Messages" or "Default" notification settings: @@ -528,6 +548,30 @@ function PrivacyBlurFeature() { return null; } +// Periodically emits memory-health gauges so Sentry dashboards can surface +// unbounded growth (e.g. blob cache never evicted, stale inflight requests). +function HealthMonitor() { + useEffect(() => { + const id = window.setInterval(() => { + const { cacheSize, inflightCount } = getBlobCacheStats(); + Sentry.metrics.gauge('sable.media.blob_cache_size', cacheSize); + if (inflightCount > 0) { + Sentry.metrics.gauge('sable.media.inflight_requests', inflightCount); + if (inflightCount >= 10) { + Sentry.addBreadcrumb({ + category: 'media', + message: `High inflight request count: ${inflightCount}`, + level: 'warning', + data: { inflight_count: inflightCount }, + }); + } + } + }, 60_000); + return () => window.clearInterval(id); + }, []); + return null; +} + type ClientNonUIFeaturesProps = { children: ReactNode; }; @@ -619,6 +663,80 @@ function SlidingSyncActiveRoomSubscriber() { return null; } +/** + * Tracks the currently-viewed room and writes sanitised room metadata to the Sentry scope. + * This context appears on every subsequent error/transaction captured while the room is open, + * making room-specific bugs much easier to triage. + */ +function SentryRoomContextFeature() { + const mx = useMatrixClient(); + const mDirect = useAtomValue(mDirectAtom); + const roomId = useAtomValue(lastVisitedRoomIdAtom); + + useEffect(() => { + if (!roomId) { + Sentry.setContext('room', null); + Sentry.setTag('room_type', ''); + Sentry.setTag('room_encrypted', ''); + return; + } + const room = mx.getRoom(roomId); + if (!room) return; + + const isDm = mDirect.has(roomId); + const encrypted = mx.isRoomEncrypted(roomId); + const memberCount = room.getJoinedMemberCount(); + // Bucket member count so we can correlate issues with room scale + // without leaking precise membership numbers of private rooms. + const memberCountRange = + memberCount <= 2 ? '1-2' : + memberCount <= 10 ? '3-10' : + memberCount <= 50 ? '11-50' : + memberCount <= 200 ? '51-200' : '200+'; + + Sentry.setContext('room', { + type: isDm ? 'dm' : 'group', + encrypted, + member_count_range: memberCountRange, + }); + // Also set as tags so they can be used to filter events in Sentry + Sentry.setTag('room_type', isDm ? 'dm' : 'group'); + Sentry.setTag('room_encrypted', String(encrypted)); + }, [mx, mDirect, roomId]); + + return null; +} + +function SentryTagsFeature() { + const settings = useAtomValue(settingsAtom); + + useEffect(() => { + // Core rendering tags — indexed in Sentry for filtering/search + Sentry.setTag('message_layout', String(settings.messageLayout)); + Sentry.setTag('message_spacing', String(settings.messageSpacing)); + Sentry.setTag('twitter_emoji', String(settings.twitterEmoji)); + Sentry.setTag('is_markdown', String(settings.isMarkdown)); + Sentry.setTag('page_zoom', String(settings.pageZoom)); + if (settings.themeId) Sentry.setTag('theme_id', settings.themeId); + // Additional high-value tags for bug reproduction + Sentry.setTag('use_right_bubbles', String(settings.useRightBubbles)); + Sentry.setTag('reduced_motion', String(settings.reducedMotion)); + Sentry.setTag('send_presence', String(settings.sendPresence)); + Sentry.setTag('enter_for_newline', String(settings.enterForNewline)); + Sentry.setTag('media_auto_load', String(settings.mediaAutoLoad)); + Sentry.setTag('url_preview', String(settings.urlPreview)); + Sentry.setTag('use_system_theme', String(settings.useSystemTheme)); + Sentry.setTag('uniform_icons', String(settings.uniformIcons)); + Sentry.setTag('jumbo_emoji_size', String(settings.jumboEmojiSize)); + Sentry.setTag('caption_position', String(settings.captionPosition)); + Sentry.setTag('right_swipe_action', String(settings.rightSwipeAction)); + // Full settings snapshot as structured Additional Data on every event + Sentry.setContext('settings', { ...settings }); + }, [settings]); + + return null; +} + function PresenceFeature() { const mx = useMatrixClient(); const [sendPresence] = useSetting(settingsAtom, 'sendPresence'); @@ -649,6 +767,9 @@ export function ClientNonUIFeatures({ children }: ClientNonUIFeaturesProps) { + + + {children} ); diff --git a/src/app/pages/client/ClientRoot.tsx b/src/app/pages/client/ClientRoot.tsx index 8a9f2305..69ef8534 100644 --- a/src/app/pages/client/ClientRoot.tsx +++ b/src/app/pages/client/ClientRoot.tsx @@ -16,6 +16,7 @@ import { import { HttpApiEvent, HttpApiEventHandlerMap, MatrixClient } from '$types/matrix-sdk'; import FocusTrap from 'focus-trap-react'; import { useRef, MouseEventHandler, ReactNode, useCallback, useEffect, useState } from 'react'; +import * as Sentry from '@sentry/react'; import { useNavigate } from 'react-router-dom'; import { useAtom, useAtomValue, useSetAtom } from 'jotai'; import { @@ -150,6 +151,11 @@ function ClientRootOptions({ mx, onLogout }: ClientRootOptionsProps) { const useLogoutListener = (mx?: MatrixClient) => { useEffect(() => { const handleLogout: HttpApiEventHandlerMap[HttpApiEvent.SessionLoggedOut] = async () => { + Sentry.addBreadcrumb({ + category: 'auth', + message: 'Session forcibly logged out by server', + level: 'warning', + }); if (mx) stopClient(mx); await mx?.clearStores(); window.localStorage.clear(); @@ -180,6 +186,8 @@ export function ClientRoot({ children }: ClientRootProps) { const { baseUrl, userId } = activeSession ?? {}; const loadedUserIdRef = useRef(undefined); + const syncStartTimeRef = useRef(performance.now()); + const firstSyncReadyRef = useRef(false); const [loadState, loadMatrix, setLoadState] = useAsyncCallback( useCallback(async () => { @@ -281,11 +289,68 @@ export function ClientRoot({ children }: ClientRootProps) { mx, useCallback((state: string) => { if (isClientReady(state)) { + if (!firstSyncReadyRef.current) { + firstSyncReadyRef.current = true; + Sentry.metrics.distribution( + 'sable.sync.time_to_ready_ms', + performance.now() - syncStartTimeRef.current + ); + } setLoading(false); } }, []) ); + // Set matrix client context: homeserver and sync type (not PII) + useEffect(() => { + if (!activeSession?.baseUrl) return undefined; + Sentry.setContext('client', { + homeserver: activeSession.baseUrl, + sliding_sync: clientConfig.slidingSync, + }); + return () => { + Sentry.setContext('client', null); + }; + }, [activeSession?.baseUrl, clientConfig.slidingSync]); + + // Set a pseudonymous hashed user ID for error grouping — never sends raw Matrix ID + useEffect(() => { + if (!mx) return undefined; + const matrixUserId = mx.getUserId(); + if (!matrixUserId) return undefined; + (async () => { + const hashBuffer = await crypto.subtle.digest( + 'SHA-256', + new TextEncoder().encode(matrixUserId) + ); + const hashHex = Array.from(new Uint8Array(hashBuffer)) + .map((b) => b.toString(16).padStart(2, '0')) + .join('') + .slice(0, 16); + // Include the homeserver domain as `username` — it is not PII (it is the server + // domain, not a personal identifier) and helps segment issues by deployment. + const serverDomain = matrixUserId.split(':')[1] ?? 'unknown'; + Sentry.setUser({ id: hashHex, username: serverDomain }); + })(); + return () => { + Sentry.setUser(null); + }; + }, [mx]); + + // Capture fatal client failures — useAsyncCallback swallows these into state so + // they never reach the React ErrorBoundary; explicit capture is required. + useEffect(() => { + if (loadState.status === AsyncStatus.Error) { + Sentry.captureException(loadState.error, { tags: { phase: 'load' } }); + } + }, [loadState]); + + useEffect(() => { + if (startState.status === AsyncStatus.Error) { + Sentry.captureException(startState.error, { tags: { phase: 'start' } }); + } + }, [startState]); + return ( diff --git a/src/app/pages/client/SyncStatus.tsx b/src/app/pages/client/SyncStatus.tsx index 818d7700..f55fe5e5 100644 --- a/src/app/pages/client/SyncStatus.tsx +++ b/src/app/pages/client/SyncStatus.tsx @@ -1,6 +1,7 @@ import { MatrixClient, SyncState } from '$types/matrix-sdk'; import { useCallback, useState } from 'react'; import { Box, config, Line, Text } from 'folds'; +import * as Sentry from '@sentry/react'; import { useSyncState } from '$hooks/useSyncState'; import { ContainerColor } from '$styles/ContainerColor.css'; @@ -27,6 +28,18 @@ export function SyncStatus({ mx }: SyncStatusProps) { } return { current, previous }; }); + + if (current === SyncState.Reconnecting || current === SyncState.Error) { + Sentry.addBreadcrumb({ + category: 'sync', + message: `Sync state changed to ${current}`, + level: current === SyncState.Error ? 'error' : 'warning', + data: { previous }, + }); + Sentry.metrics.count('sable.sync.degraded', 1, { + attributes: { state: current }, + }); + } }, []) ); diff --git a/src/app/pages/client/sidebar/DirectDMsList.tsx b/src/app/pages/client/sidebar/DirectDMsList.tsx index f2573b61..7a6718b5 100644 --- a/src/app/pages/client/sidebar/DirectDMsList.tsx +++ b/src/app/pages/client/sidebar/DirectDMsList.tsx @@ -1,9 +1,13 @@ -import { useMemo } from 'react'; +import { useMemo, useState, useCallback, useRef, useEffect } from 'react'; +import * as Sentry from '@sentry/react'; import { useNavigate } from 'react-router-dom'; import { Avatar, Text, Box, toRem } from 'folds'; import { useAtomValue } from 'jotai'; -import { Room } from '$types/matrix-sdk'; +import { Room, SyncState } from '$types/matrix-sdk'; +import { useDirects } from '$state/hooks/roomList'; import { useMatrixClient } from '$hooks/useMatrixClient'; +import { mDirectAtom } from '$state/mDirectList'; +import { allRoomsAtom } from '$state/room-list/roomList'; import { roomToUnreadAtom } from '$state/room/roomToUnread'; import { getDirectRoomPath } from '$pages/pathUtils'; import { @@ -18,12 +22,14 @@ import { UserAvatar } from '$components/user-avatar'; import { getDirectRoomAvatarUrl } from '$utils/room'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { nameInitials } from '$utils/common'; +import { factoryRoomIdByActivity } from '$utils/sort'; import { getCanonicalAliasOrRoomId, mxcUrlToHttp } from '$utils/matrix'; import { useSelectedRoom } from '$hooks/router/useSelectedRoom'; import { useGroupDMMembers } from '$hooks/useGroupDMMembers'; -import { useSidebarDirectRoomIds } from './useSidebarDirectRoomIds'; +import { useSyncState } from '$hooks/useSyncState'; import * as css from './DirectDMsList.css'; +const MAX_DM_AVATARS = 3; const MAX_GROUP_MEMBERS = 3; type DMItemProps = { @@ -158,17 +164,63 @@ function DMItem({ room, selected }: DMItemProps) { export function DirectDMsList() { const mx = useMatrixClient(); + const mDirects = useAtomValue(mDirectAtom); + const directs = useDirects(mx, allRoomsAtom, mDirects); + const roomToUnread = useAtomValue(roomToUnreadAtom); const selectedRoomId = useSelectedRoom(); - const sidebarRoomIds = useSidebarDirectRoomIds(); - const recentDMs = useMemo( - () => - sidebarRoomIds - .map((roomId) => mx.getRoom(roomId)) - .filter((room): room is Room => room !== null), - [sidebarRoomIds, mx] + // Track sync state to wait for initial sync completion + const [syncReady, setSyncReady] = useState(false); + const mountTimeRef = useRef(performance.now()); + const firstReadyRef = useRef(false); + + useSyncState( + mx, + useCallback((state, prevState) => { + // Consider ready after initial sync reaches Syncing state + // This ensures m.direct and unread counts are populated + if (state === SyncState.Syncing && prevState !== SyncState.Syncing) { + setSyncReady(true); + } + // Also set ready if we're already syncing (e.g., after a refresh while still online) + if (state === SyncState.Syncing || state === SyncState.Catchup) { + setSyncReady(true); + } + }, []) ); + useEffect(() => { + if (syncReady && !firstReadyRef.current) { + firstReadyRef.current = true; + Sentry.metrics.distribution( + 'sable.roomlist.time_to_ready_ms', + performance.now() - mountTimeRef.current + ); + } + }, [syncReady]); + + // Get up to MAX_DM_AVATARS recent DMs that have unread messages + const recentDMs = useMemo(() => { + // Don't show DMs until initial sync completes + if (!syncReady) { + return []; + } + + // Filter to only DMs with unread messages + const withUnread = directs.filter((roomId) => { + const unread = roomToUnread.get(roomId); + return unread && (unread.total > 0 || unread.highlight > 0); + }); + + // Sort by activity + const sorted = withUnread.sort(factoryRoomIdByActivity(mx)); + + return sorted + .slice(0, MAX_DM_AVATARS) + .map((roomId) => mx.getRoom(roomId)) + .filter((room): room is Room => room !== null); + }, [directs, mx, roomToUnread, syncReady]); + if (recentDMs.length === 0) { return null; } diff --git a/src/app/pages/client/sidebar/DirectTab.tsx b/src/app/pages/client/sidebar/DirectTab.tsx index 3503c7f9..dd2a7d6e 100644 --- a/src/app/pages/client/sidebar/DirectTab.tsx +++ b/src/app/pages/client/sidebar/DirectTab.tsx @@ -1,4 +1,4 @@ -import { MouseEventHandler, forwardRef, useMemo, useState } from 'react'; +import { MouseEventHandler, forwardRef, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { Box, Icon, Icons, Menu, MenuItem, PopOut, RectCords, Text, config, toRem } from 'folds'; import FocusTrap from 'focus-trap-react'; @@ -25,7 +25,6 @@ import { stopPropagation } from '$utils/keyboard'; import { settingsAtom } from '$state/settings'; import { useSetting } from '$state/hooks/settings'; import { useDirectRooms } from '$pages/client/direct/useDirectRooms'; -import { useSidebarDirectRoomIds } from './useSidebarDirectRoomIds'; type DirectMenuProps = { requestClose: () => void; @@ -69,14 +68,7 @@ export function DirectTab() { const mDirects = useAtomValue(mDirectAtom); const directs = useDirects(mx, allRoomsAtom, mDirects); - const sidebarRoomIds = useSidebarDirectRoomIds(); - // Only count unread for DMs not already shown as individual avatars in the - // sidebar — prevents double-badging (issue #235). - const overflowDirects = useMemo(() => { - const sidebarSet = new Set(sidebarRoomIds); - return directs.filter((id) => !sidebarSet.has(id)); - }, [directs, sidebarRoomIds]); - const directUnread = useRoomsUnread(overflowDirects, roomToUnreadAtom); + const directUnread = useRoomsUnread(directs, roomToUnreadAtom); const [menuAnchor, setMenuAnchor] = useState(); const directSelected = useDirectSelected(); diff --git a/src/app/pages/client/sidebar/useSidebarDirectRoomIds.ts b/src/app/pages/client/sidebar/useSidebarDirectRoomIds.ts deleted file mode 100644 index 8c62d3af..00000000 --- a/src/app/pages/client/sidebar/useSidebarDirectRoomIds.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { useMemo, useState, useCallback } from 'react'; -import { useAtomValue } from 'jotai'; -import { SyncState } from '$types/matrix-sdk'; -import { useDirects } from '$state/hooks/roomList'; -import { useMatrixClient } from '$hooks/useMatrixClient'; -import { mDirectAtom } from '$state/mDirectList'; -import { allRoomsAtom } from '$state/room-list/roomList'; -import { roomToUnreadAtom } from '$state/room/roomToUnread'; -import { factoryRoomIdByActivity } from '$utils/sort'; -import { useSyncState } from '$hooks/useSyncState'; - -/** Maximum number of individual DM avatars shown in the sidebar. */ -export const MAX_SIDEBAR_DMS = 3; - -/** - * Returns the room IDs of DMs currently displayed as individual avatars in the - * sidebar `DirectDMsList`. These are the first `MAX_SIDEBAR_DMS` unread DMs - * sorted by recent activity, available only after initial sync completes. - * - * Used by `DirectDMsList` to decide which rooms to render, and by `DirectTab` - * to exclude those rooms from its own badge count (prevents double-badging). - */ -export const useSidebarDirectRoomIds = (): string[] => { - const mx = useMatrixClient(); - const mDirects = useAtomValue(mDirectAtom); - const directs = useDirects(mx, allRoomsAtom, mDirects); - const roomToUnread = useAtomValue(roomToUnreadAtom); - - const [syncReady, setSyncReady] = useState(false); - - useSyncState( - mx, - useCallback((state, prevState) => { - if (state === SyncState.Syncing && prevState !== SyncState.Syncing) { - setSyncReady(true); - } - if (state === SyncState.Syncing || state === SyncState.Catchup) { - setSyncReady(true); - } - }, []) - ); - - return useMemo(() => { - if (!syncReady) return []; - - const withUnread = directs.filter((roomId) => { - const unread = roomToUnread.get(roomId); - return unread && (unread.total > 0 || unread.highlight > 0); - }); - - const sorted = withUnread.sort(factoryRoomIdByActivity(mx)); - return sorted.slice(0, MAX_SIDEBAR_DMS); - }, [directs, mx, roomToUnread, syncReady]); -}; diff --git a/src/app/plugins/call/CallEmbed.ts b/src/app/plugins/call/CallEmbed.ts index 960f21ce..570b66f7 100644 --- a/src/app/plugins/call/CallEmbed.ts +++ b/src/app/plugins/call/CallEmbed.ts @@ -218,24 +218,11 @@ export class CallEmbed { this.readUpToMap[room.roomId] = roomEvent.getId()!; }); - // Attach listeners for feeding events - the underlying widget classes handle permissions for us. - // Bind once and store via disposables so the same function reference is used for removal. - // Using .bind(this) at call-site would create a new function every time, making .off() a no-op - // and causing MaxListeners warnings when the embed is recreated during sync retries. - const boundOnEvent = this.onEvent.bind(this); - const boundOnEventDecrypted = this.onEventDecrypted.bind(this); - const boundOnStateUpdate = this.onStateUpdate.bind(this); - const boundOnToDeviceEvent = this.onToDeviceEvent.bind(this); - this.mx.on(ClientEvent.Event, boundOnEvent); - this.mx.on(MatrixEventEvent.Decrypted, boundOnEventDecrypted); - this.mx.on(RoomStateEvent.Events, boundOnStateUpdate); - this.mx.on(ClientEvent.ToDeviceEvent, boundOnToDeviceEvent); - this.disposables.push(() => { - this.mx.off(ClientEvent.Event, boundOnEvent); - this.mx.off(MatrixEventEvent.Decrypted, boundOnEventDecrypted); - this.mx.off(RoomStateEvent.Events, boundOnStateUpdate); - this.mx.off(ClientEvent.ToDeviceEvent, boundOnToDeviceEvent); - }); + // Attach listeners for feeding events - the underlying widget classes handle permissions for us + this.mx.on(ClientEvent.Event, this.onEvent.bind(this)); + this.mx.on(MatrixEventEvent.Decrypted, this.onEventDecrypted.bind(this)); + this.mx.on(RoomStateEvent.Events, this.onStateUpdate.bind(this)); + this.mx.on(ClientEvent.ToDeviceEvent, this.onToDeviceEvent.bind(this)); } /** @@ -252,7 +239,11 @@ export class CallEmbed { this.container.removeChild(this.iframe); this.control.dispose(); - // Listener removal is handled by the disposables pushed in start(). + this.mx.off(ClientEvent.Event, this.onEvent.bind(this)); + this.mx.off(MatrixEventEvent.Decrypted, this.onEventDecrypted.bind(this)); + this.mx.off(RoomStateEvent.Events, this.onStateUpdate.bind(this)); + this.mx.off(ClientEvent.ToDeviceEvent, this.onToDeviceEvent.bind(this)); + // Clear internal state this.readUpToMap = {}; this.eventsToFeed = new WeakSet(); diff --git a/src/app/state/callEmbed.ts b/src/app/state/callEmbed.ts index 1452fb97..b05055c4 100644 --- a/src/app/state/callEmbed.ts +++ b/src/app/state/callEmbed.ts @@ -1,8 +1,12 @@ import { atom } from 'jotai'; +import * as Sentry from '@sentry/react'; import { CallEmbed } from '../plugins/call'; const baseCallEmbedAtom = atom(undefined); +// Tracks when the active call embed was created, for lifetime measurement. +let embedCreatedAt: number | null = null; + export const callEmbedAtom = atom( (get) => get(baseCallEmbedAtom), (get, set, callEmbed) => { @@ -10,9 +14,21 @@ export const callEmbedAtom = atom void; +const BREADCRUMB_DISABLED_KEY = 'sable_sentry_breadcrumb_disabled'; + class DebugLoggerService { private logs: LogEntry[] = []; @@ -38,9 +42,22 @@ class DebugLoggerService { private listeners: Set = new Set(); + private disabledBreadcrumbCategories: Set; + + private sentryStats = { errors: 0, warnings: 0 }; + constructor() { // Check if debug logging is enabled from localStorage this.enabled = localStorage.getItem('sable_internal_debug') === '1'; + // Load disabled breadcrumb categories + try { + const stored = localStorage.getItem(BREADCRUMB_DISABLED_KEY); + this.disabledBreadcrumbCategories = new Set( + stored ? (JSON.parse(stored) as LogCategory[]) : [] + ); + } catch { + this.disabledBreadcrumbCategories = new Set(); + } } public isEnabled(): boolean { @@ -99,6 +116,9 @@ class DebugLoggerService { // Notify listeners this.notifyListeners(entry); + // Send to Sentry + this.sendToSentry(entry); + // Also log to console for developer convenience const prefix = `[sable:${category}:${namespace}]`; const consoleLevel = level === 'debug' ? 'log' : level; @@ -106,6 +126,127 @@ class DebugLoggerService { console[consoleLevel](prefix, message, data !== undefined ? data : ''); } + public getBreadcrumbCategoryEnabled(category: LogCategory): boolean { + return !this.disabledBreadcrumbCategories.has(category); + } + + public setBreadcrumbCategoryEnabled(category: LogCategory, enabled: boolean): void { + if (enabled) { + this.disabledBreadcrumbCategories.delete(category); + } else { + this.disabledBreadcrumbCategories.add(category); + } + const disabledArray = Array.from(this.disabledBreadcrumbCategories); + if (disabledArray.length > 0) { + localStorage.setItem(BREADCRUMB_DISABLED_KEY, JSON.stringify(disabledArray)); + } else { + localStorage.removeItem(BREADCRUMB_DISABLED_KEY); + } + } + + public getSentryStats(): { errors: number; warnings: number } { + return { ...this.sentryStats }; + } + + /** + * Send log entries to Sentry for error tracking and breadcrumbs + */ + private sendToSentry(entry: LogEntry): void { + // Map log levels to Sentry severity + const sentryLevelMap: Record = { + debug: 'debug', + info: 'info', + warn: 'warning', + error: 'error', + }; + const sentryLevel: Sentry.SeverityLevel = sentryLevelMap[entry.level] ?? 'error'; + + // Add breadcrumb for all logs (helps with debugging in Sentry), unless category is disabled + if (!this.disabledBreadcrumbCategories.has(entry.category)) Sentry.addBreadcrumb({ + category: `${entry.category}.${entry.namespace}`, + message: entry.message, + level: sentryLevel, + data: entry.data ? { data: entry.data } : undefined, + timestamp: entry.timestamp / 1000, // Sentry expects seconds + }); + + // Send as structured log to the Sentry Logs product (requires enableLogs: true) + const logMsg = `[${entry.category}:${entry.namespace}] ${entry.message}`; + // Flatten primitive values from entry.data so they become searchable attributes in Sentry Logs + const logDataAttrs: Record = {}; + if (entry.data && typeof entry.data === 'object' && !(entry.data instanceof Error)) { + for (const [k, v] of Object.entries(entry.data)) { + if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') { + logDataAttrs[k] = v; + } + } + } + const logAttrs = { category: entry.category, namespace: entry.namespace, ...logDataAttrs }; + if (entry.level === 'debug') Sentry.logger.debug(logMsg, logAttrs); + else if (entry.level === 'info') Sentry.logger.info(logMsg, logAttrs); + else if (entry.level === 'warn') Sentry.logger.warn(logMsg, logAttrs); + else Sentry.logger.error(logMsg, logAttrs); + + // Track error/warn rates as metrics, tagged by category for filtering in Sentry dashboards + if (entry.level === 'error' || entry.level === 'warn') { + Sentry.metrics.count(`sable.${entry.level}s`, 1, { + attributes: { category: entry.category, namespace: entry.namespace }, + }); + } + + // Capture errors and warnings as Sentry events + if (entry.level === 'error') { + this.sentryStats.errors += 1; + // If data is an Error object, capture it as an exception + if (entry.data instanceof Error) { + Sentry.captureException(entry.data, { + level: 'error', + tags: { + category: entry.category, + namespace: entry.namespace, + }, + contexts: { + debugLog: { + message: entry.message, + timestamp: new Date(entry.timestamp).toISOString(), + }, + }, + }); + } else { + // Otherwise capture as a message + Sentry.captureMessage(`[${entry.category}:${entry.namespace}] ${entry.message}`, { + level: 'error', + tags: { + category: entry.category, + namespace: entry.namespace, + }, + contexts: { + debugLog: { + data: entry.data, + timestamp: new Date(entry.timestamp).toISOString(), + }, + }, + }); + } + } else if (entry.level === 'warn' && Math.random() < 0.1) { + // Capture 10% of warnings to avoid overwhelming Sentry + this.sentryStats.warnings += 1; + Sentry.captureMessage(`[${entry.category}:${entry.namespace}] ${entry.message}`, { + level: 'warning', + tags: { + category: entry.category, + namespace: entry.namespace, + }, + contexts: { + debugLog: { + data: entry.data, + timestamp: new Date(entry.timestamp).toISOString(), + }, + }, + }); + } + } + public getLogs(): LogEntry[] { return [...this.logs]; } @@ -152,6 +293,54 @@ class DebugLoggerService { 2 ); } + + /** + * Export logs in a format suitable for attaching to Sentry reports + */ + public exportLogsForSentry(): Record[] { + return this.logs.map((log) => ({ + timestamp: new Date(log.timestamp).toISOString(), + level: log.level, + category: log.category, + namespace: log.namespace, + message: log.message, + data: log.data, + })); + } + + /** + * Attach recent logs to the next Sentry event + * Useful for bug reports to include context + */ + public attachLogsToSentry(limit = 100): void { + const recentLogs = this.logs.slice(-limit); + const logsData = recentLogs.map((log) => ({ + time: new Date(log.timestamp).toISOString(), + level: log.level, + category: log.category, + namespace: log.namespace, + message: log.message, + // Only include data for errors/warnings to avoid excessive payload + ...(log.level === 'error' || log.level === 'warn' ? { data: log.data } : {}), + })); + + // Add to context + Sentry.setContext('recentLogs', { + count: recentLogs.length, + logs: logsData, + }); + + // Also add as extra data for better visibility in Sentry UI + Sentry.getCurrentScope().setExtra('debugLogs', logsData); + + // Add as attachment for download + const logsText = JSON.stringify(logsData, null, 2); + Sentry.getCurrentScope().addAttachment({ + filename: 'debug-logs.json', + data: logsText, + contentType: 'application/json', + }); + } } // Singleton instance diff --git a/src/app/utils/matrix.ts b/src/app/utils/matrix.ts index 69fadc02..abc15597 100644 --- a/src/app/utils/matrix.ts +++ b/src/app/utils/matrix.ts @@ -19,6 +19,7 @@ import { IImageInfo, IThumbnailContent, IVideoInfo } from '$types/matrix/common' import { AccountDataEvent } from '$types/matrix/accountData'; import { Membership, MessageEvent, StateEvent } from '$types/matrix/room'; import { getEventReactions, getReactionContent, getStateEvent } from './room'; +import * as Sentry from '@sentry/react'; const DOMAIN_REGEX = /\b(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}\b/; @@ -163,6 +164,7 @@ export const uploadContent = async ( ) => { const { name, fileType, hideFilename, onProgress, onPromise, onSuccess, onError } = options; + const uploadStart = performance.now(); const uploadPromise = mx.uploadContent(file, { name, type: fileType, @@ -173,9 +175,21 @@ export const uploadContent = async ( try { const data = await uploadPromise; const mxc = data.content_uri; - if (mxc) onSuccess(mxc); - else onError(new MatrixError(data)); + if (mxc) { + const mediaType = file.type.split('/')[0] || 'unknown'; + Sentry.metrics.distribution('sable.media.upload_latency_ms', performance.now() - uploadStart, { + attributes: { type: mediaType }, + }); + Sentry.metrics.distribution('sable.media.upload_bytes', file.size, { + attributes: { type: mediaType }, + }); + onSuccess(mxc); + } else { + Sentry.metrics.count('sable.media.upload_error', 1, { attributes: { reason: 'no_uri' } }); + onError(new MatrixError(data)); + } } catch (e: any) { + Sentry.metrics.count('sable.media.upload_error', 1, { attributes: { reason: 'exception' } }); const error = typeof e?.message === 'string' ? e.message : undefined; const errcode = typeof e?.name === 'string' ? e.message : undefined; onError(new MatrixError({ error, errcode })); diff --git a/src/app/utils/room.ts b/src/app/utils/room.ts index 21fa6e29..4a421b81 100644 --- a/src/app/utils/room.ts +++ b/src/app/utils/room.ts @@ -30,6 +30,7 @@ import { StateEvent, UnreadInfo, } from '$types/matrix/room'; +import * as Sentry from '@sentry/react'; export const getStateEvent = ( room: Room, @@ -557,7 +558,22 @@ export const decryptAllTimelineEvent = async (mx: MatrixClient, timeline: EventT .filter((event) => event.isEncrypted()) .reverse() .map((event) => event.attemptDecryption(crypto as CryptoBackend, { isRetry: true })); - await Promise.allSettled(decryptionPromises); + const decryptStart = performance.now(); + await Sentry.startSpan( + { + name: 'decrypt.bulk', + op: 'matrix.crypto', + attributes: { event_count: decryptionPromises.length }, + }, + () => Promise.allSettled(decryptionPromises) + ); + if (decryptionPromises.length > 0) { + Sentry.metrics.distribution( + 'sable.decryption.bulk_latency_ms', + performance.now() - decryptStart, + { attributes: { event_count: String(decryptionPromises.length) } } + ); + } }; export const getReactionContent = (eventId: string, key: string, shortcode?: string) => ({ diff --git a/src/client/initMatrix.ts b/src/client/initMatrix.ts index 71bbc316..ea9b9e87 100644 --- a/src/client/initMatrix.ts +++ b/src/client/initMatrix.ts @@ -17,6 +17,7 @@ import { import { getLocalStorageItem } from '$state/utils/atomWithLocalStorage'; import { createLogger } from '$utils/debug'; import { createDebugLogger } from '$utils/debugLogger'; +import * as Sentry from '@sentry/react'; import { pushSessionToSW } from '../sw-session'; import { cryptoCallbacks } from './secretStorageKeys'; import { SlidingSyncConfig, SlidingSyncDiagnostics, SlidingSyncManager } from './slidingSync'; @@ -144,12 +145,17 @@ const isClientReadyForUi = (syncState: string | null): boolean => const waitForClientReady = (mx: MatrixClient, timeoutMs: number): Promise => new Promise((resolve) => { + const waitStart = performance.now(); if (isClientReadyForUi(mx.getSyncState())) { + Sentry.metrics.distribution('sable.sync.client_ready_ms', 0, { + attributes: { timed_out: 'false' }, + }); resolve(); return; } let timer = 0; + let timedOut = false; let finish = () => {}; const onSync = (state: string) => { debugLog.info('sync', `Sync state changed: ${state}`, { @@ -165,10 +171,25 @@ const waitForClientReady = (mx: MatrixClient, timeoutMs: number): Promise settled = true; mx.removeListener(ClientEvent.Sync, onSync); clearTimeout(timer); + const waitMs = performance.now() - waitStart; + Sentry.metrics.distribution('sable.sync.client_ready_ms', waitMs, { + attributes: { timed_out: String(timedOut) }, + }); + if (timedOut) { + Sentry.addBreadcrumb({ + category: 'sync', + message: 'waitForClientReady timed out — client may be stuck', + level: 'warning', + data: { timeout_ms: timeoutMs }, + }); + } resolve(); }; - timer = window.setTimeout(finish, timeoutMs); + timer = window.setTimeout(() => { + timedOut = true; + finish(); + }, timeoutMs); mx.on(ClientEvent.Sync, onSync); }); @@ -287,6 +308,12 @@ export const initClient = async (session: Session): Promise => { const wipeAllStores = async () => { log.warn('initClient: wiping all stores for', session.userId); debugLog.warn('sync', 'Wiping all stores due to mismatch', { userId: session.userId }); + Sentry.addBreadcrumb({ + category: 'crypto', + message: 'Crypto store mismatch — wiping local stores and retrying', + level: 'warning', + }); + Sentry.metrics.count('sable.crypto.store_wipe', 1); await deleteSessionStores(storeName); try { const allDbs = await window.indexedDB.databases(); @@ -390,6 +417,9 @@ export const startClient = async (mx: MatrixClient, config?: StartClientConfig): fallbackFromSliding, reason, }); + Sentry.metrics.count('sable.sync.transport', 1, { + attributes: { transport: 'classic', reason, fallback: String(fallbackFromSliding) }, + }); await mx.startClient({ lazyLoadMembers: true, pollTimeout: FAST_SYNC_POLL_TIMEOUT_MS, @@ -487,6 +517,9 @@ export const startClient = async (mx: MatrixClient, config?: StartClientConfig): fallbackFromSliding: false, reason: 'sliding_active', }); + Sentry.metrics.count('sable.sync.transport', 1, { + attributes: { transport: 'sliding', reason: 'sliding_active', fallback: 'false' }, + }); try { await mx.startClient({ diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index 7cd01cab..d403dd1e 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -17,6 +17,7 @@ import { } from '$types/matrix-sdk'; import { createLogger } from '$utils/debug'; import { createDebugLogger } from '$utils/debugLogger'; +import * as Sentry from '@sentry/react'; const log = createLogger('slidingSync'); const debugLog = createDebugLogger('slidingSync'); @@ -324,6 +325,12 @@ export class SlidingSyncManager { private previousListCounts: Map = new Map(); + /** Wall-clock time recorded in attach() — used to compute true initial-sync latency. */ + private attachTime: number | null = null; + + /** Span covering the period from attach() to the first successful complete cycle. */ + private initialSyncSpan: ReturnType | null = null; + public readonly slidingSync: SlidingSync; public readonly probeTimeoutMs: number; @@ -369,6 +376,9 @@ export class SlidingSyncManager { this.onLifecycle = (state, resp, err) => { const syncStartTime = performance.now(); this.syncCount += 1; + Sentry.metrics.count('sable.sync.cycle', 1, { + attributes: { transport: 'sliding', state }, + }); debugLog.info('sync', `Sliding sync lifecycle: ${state} (cycle #${this.syncCount})`, { state, @@ -384,6 +394,9 @@ export class SlidingSyncManager { syncNumber: this.syncCount, state, }); + Sentry.metrics.count('sable.sync.error', 1, { + attributes: { transport: 'sliding', state }, + }); } if (this.disposed) { @@ -425,22 +438,38 @@ export class SlidingSyncManager { }); } + const syncDuration = performance.now() - syncStartTime; + // Mark initial sync as complete after first successful cycle if (!this.initialSyncCompleted) { this.initialSyncCompleted = true; + // Wall-clock ms from attach() — the actual user-perceived wait for first data. + const initialElapsed = + this.attachTime != null ? performance.now() - this.attachTime : syncDuration; debugLog.info('sync', 'Initial sync completed', { syncNumber: this.syncCount, totalRoomCount, listCounts: Object.fromEntries( this.listKeys.map((key) => [key, this.slidingSync.getListData(key)?.joinedCount ?? 0]) ), - timeElapsed: `${(performance.now() - syncStartTime).toFixed(2)}ms`, + timeElapsed: `${initialElapsed.toFixed(2)}ms`, }); + Sentry.metrics.distribution('sable.sync.initial_ms', initialElapsed, { + attributes: { transport: 'sliding' }, + }); + this.initialSyncSpan?.setAttributes({ + 'sync.cycles_to_ready': this.syncCount, + 'sync.rooms_at_ready': totalRoomCount, + }); + this.initialSyncSpan?.end(); + this.initialSyncSpan = null; } this.expandListsToKnownCount(); - const syncDuration = performance.now() - syncStartTime; + Sentry.metrics.distribution('sable.sync.processing_ms', syncDuration, { + attributes: { transport: 'sliding' }, + }); if (syncDuration > 1000) { debugLog.warn('sync', 'Slow sync cycle detected', { syncNumber: this.syncCount, @@ -502,6 +531,13 @@ export class SlidingSyncManager { lists: this.listKeys, }); + this.attachTime = performance.now(); + this.initialSyncSpan = Sentry.startInactiveSpan({ + name: 'sync.initial', + op: 'matrix.sync', + attributes: { 'sync.transport': 'sliding', 'sync.proxy': this.proxyBaseUrl }, + }); + this.slidingSync.on(SlidingSyncEvent.Lifecycle, this.onLifecycle); const connection = ( typeof navigator !== 'undefined' ? (navigator as any).connection : undefined @@ -674,6 +710,18 @@ export class SlidingSyncManager { if (allListsComplete) { this.listsFullyLoaded = true; log.log(`Sliding Sync all lists fully loaded for ${this.mx.getUserId()}`); + const totalRooms = this.listKeys.reduce( + (sum, key) => sum + (this.slidingSync.getListData(key)?.joinedCount ?? 0), + 0 + ); + const listsLoadedMs = + this.attachTime != null ? Math.round(performance.now() - this.attachTime) : 0; + Sentry.metrics.distribution('sable.sync.lists_loaded_ms', listsLoadedMs, { + attributes: { transport: 'sliding' }, + }); + Sentry.metrics.gauge('sable.sync.total_rooms', totalRooms, { + attributes: { transport: 'sliding' }, + }); } else if (expandedAny) { log.log(`Sliding Sync lists expanding... for ${this.mx.getUserId()}`); } @@ -763,52 +811,64 @@ export class SlidingSyncManager { let endIndex = batchSize - 1; let hasMore = true; let firstTime = true; + let batchCount = 0; - const spideringRequiredState: MSC3575List['required_state'] = [ - [EventType.RoomJoinRules, ''], - [EventType.RoomAvatar, ''], - [EventType.RoomTombstone, ''], - [EventType.RoomEncryption, ''], - [EventType.RoomCreate, ''], - [EventType.RoomTopic, ''], - [EventType.RoomCanonicalAlias, ''], - [EventType.RoomMember, MSC3575_STATE_KEY_ME], - ['m.space.child', MSC3575_WILDCARD], - ['im.ponies.room_emotes', MSC3575_WILDCARD], - ]; + await Sentry.startSpan( + { name: 'sync.spidering', op: 'matrix.sync', attributes: { 'sync.transport': 'sliding' } }, + async (span) => { + const spideringRequiredState: MSC3575List['required_state'] = [ + [EventType.RoomJoinRules, ''], + [EventType.RoomAvatar, ''], + [EventType.RoomTombstone, ''], + [EventType.RoomEncryption, ''], + [EventType.RoomCreate, ''], + [EventType.RoomTopic, ''], + [EventType.RoomCanonicalAlias, ''], + [EventType.RoomMember, MSC3575_STATE_KEY_ME], + ['m.space.child', MSC3575_WILDCARD], + ['im.ponies.room_emotes', MSC3575_WILDCARD], + ]; - while (hasMore) { - if (this.disposed) return; - const ranges: [number, number][] = [[0, endIndex]]; - try { - if (firstTime) { - // Full setList on first call to register the list with all params. - this.slidingSync.setList(LIST_SEARCH, { - ranges, - sort: ['by_recency'], - timeline_limit: 0, - required_state: spideringRequiredState, - }); - } else { - // Cheaper range-only update for subsequent pages; sticky params are preserved. - this.slidingSync.setListRanges(LIST_SEARCH, ranges); + while (hasMore) { + if (this.disposed) return; + batchCount += 1; + const ranges: [number, number][] = [[0, endIndex]]; + try { + if (firstTime) { + // Full setList on first call to register the list with all params. + this.slidingSync.setList(LIST_SEARCH, { + ranges, + sort: ['by_recency'], + timeline_limit: 0, + required_state: spideringRequiredState, + }); + } else { + // Cheaper range-only update for subsequent pages; sticky params are preserved. + this.slidingSync.setListRanges(LIST_SEARCH, ranges); + } + } catch { + // Swallow errors — the next iteration will retry with updated ranges. + } finally { + // eslint-disable-next-line no-await-in-loop + await new Promise((res) => { + setTimeout(res, gapBetweenRequestsMs); + }); + } + + if (this.disposed) return; + const listData = this.slidingSync.getListData(LIST_SEARCH); + hasMore = endIndex + 1 < (listData?.joinedCount ?? 0); + endIndex += batchSize; + firstTime = false; } - } catch { - // Swallow errors — the next iteration will retry with updated ranges. - } finally { - // eslint-disable-next-line no-await-in-loop - await new Promise((res) => { - setTimeout(res, gapBetweenRequestsMs); + const finalCount = this.slidingSync.getListData(LIST_SEARCH)?.joinedCount ?? 0; + span.setAttributes({ + 'spidering.batches': batchCount, + 'spidering.total_rooms': finalCount, }); + log.log(`Sliding Sync spidering complete for ${this.mx.getUserId()}`); } - - if (this.disposed) return; - const listData = this.slidingSync.getListData(LIST_SEARCH); - hasMore = endIndex + 1 < (listData?.joinedCount ?? 0); - endIndex += batchSize; - firstTime = false; - } - log.log(`Sliding Sync spidering complete for ${this.mx.getUserId()}`); + ); } /** @@ -873,6 +933,9 @@ export class SlidingSyncManager { } this.activeRoomSubscriptions.add(roomId); this.slidingSync.modifyRoomSubscriptions(new Set(this.activeRoomSubscriptions)); + Sentry.metrics.gauge('sable.sync.active_subscriptions', this.activeRoomSubscriptions.size, { + attributes: { transport: 'sliding' }, + }); log.log(`Sliding Sync active room subscription added: ${roomId}`); } @@ -885,6 +948,9 @@ export class SlidingSyncManager { if (this.disposed) return; this.activeRoomSubscriptions.delete(roomId); this.slidingSync.modifyRoomSubscriptions(new Set(this.activeRoomSubscriptions)); + Sentry.metrics.gauge('sable.sync.active_subscriptions', this.activeRoomSubscriptions.size, { + attributes: { transport: 'sliding' }, + }); log.log(`Sliding Sync active room subscription removed: ${roomId}`); } @@ -893,25 +959,33 @@ export class SlidingSyncManager { proxyBaseUrl: string, probeTimeoutMs: number ): Promise { - try { - const response = await mx.slidingSync( - { - lists: { - probe: { - ranges: [[0, 0]], - timeline_limit: 1, - required_state: [], + return Sentry.startSpan( + { name: 'sync.probe', op: 'matrix.sync', attributes: { 'sync.proxy': proxyBaseUrl } }, + async (span) => { + try { + const response = await mx.slidingSync( + { + lists: { + probe: { + ranges: [[0, 0]], + timeline_limit: 1, + required_state: [], + }, + }, + timeout: 0, + clientTimeout: probeTimeoutMs, }, - }, - timeout: 0, - clientTimeout: probeTimeoutMs, - }, - proxyBaseUrl - ); + proxyBaseUrl + ); - return typeof response.pos === 'string' && response.pos.length > 0; - } catch { - return false; - } + const supported = typeof response.pos === 'string' && response.pos.length > 0; + span.setAttribute('probe.supported', supported); + return supported; + } catch { + span.setAttribute('probe.supported', false); + return false; + } + } + ); } } diff --git a/src/index.tsx b/src/index.tsx index 3248458b..f11c7ef5 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -1,3 +1,4 @@ +import './instrument'; import { createRoot } from 'react-dom/client'; import { enableMapSet } from 'immer'; import '@fontsource-variable/nunito'; diff --git a/src/instrument.ts b/src/instrument.ts new file mode 100644 index 00000000..e7121da0 --- /dev/null +++ b/src/instrument.ts @@ -0,0 +1,245 @@ +/** + * Sentry instrumentation - MUST be imported first in the application lifecycle + * + * Configure via environment variables: + * - VITE_SENTRY_DSN: Your Sentry DSN (required to enable Sentry) + * - VITE_SENTRY_ENVIRONMENT: Environment name (defaults to MODE) + * - VITE_APP_VERSION: Release version for tracking + */ +import * as Sentry from '@sentry/react'; +import React from 'react'; +import { + useLocation, + useNavigationType, + createRoutesFromChildren, + matchRoutes, +} from 'react-router-dom'; + +const dsn = import.meta.env.VITE_SENTRY_DSN; +const environment = import.meta.env.VITE_SENTRY_ENVIRONMENT || import.meta.env.MODE; +const release = import.meta.env.VITE_APP_VERSION; + +// Per-session error event counter for rate limiting +let sessionErrorCount = 0; +const SESSION_ERROR_LIMIT = 50; + +// Check user preferences +const sentryEnabled = localStorage.getItem('sable_sentry_enabled') !== 'false'; +const replayEnabled = localStorage.getItem('sable_sentry_replay_enabled') === 'true'; + +// Only initialize if DSN is provided and user hasn't opted out +if (dsn && sentryEnabled) { + Sentry.init({ + dsn, + environment, + release, + + // Do not send PII (IP addresses, user identifiers) to protect privacy + sendDefaultPii: false, + + integrations: [ + // React Router v6 browser tracing integration + Sentry.reactRouterV6BrowserTracingIntegration({ + useEffect: React.useEffect, + useLocation, + useNavigationType, + createRoutesFromChildren, + matchRoutes, + }), + // Session replay with privacy settings (only if user opted in) + ...(replayEnabled + ? [ + Sentry.replayIntegration({ + maskAllText: true, // Mask all text for privacy + blockAllMedia: true, // Block images/video/audio for privacy + maskAllInputs: true, // Mask form inputs + }), + ] + : []), + // Capture console.error/warn as structured logs in the Sentry Logs product + Sentry.consoleLoggingIntegration({ levels: ['error', 'warn'] }), + // Browser profiling — captures JS call stacks during Sentry transactions + Sentry.browserProfilingIntegration(), + ], + + // Performance Monitoring - Tracing + // 100% in development and preview, lower in production for cost control + tracesSampleRate: environment === 'development' || environment === 'preview' ? 1.0 : 0.1, + + // Browser profiling — profiles every sampled session (requires Document-Policy: js-profiling response header) + profileSessionSampleRate: environment === 'development' || environment === 'preview' ? 1.0 : 0.1, + + // Control which URLs get distributed tracing headers + tracePropagationTargets: [ + 'localhost', + /^https:\/\/[^/]*\.sable\.chat/, + // Add your Matrix homeserver domains here if needed + ], + + // Session Replay sampling + // Record 100% in development and preview for testing, 10% in production + // Always record 100% of sessions with errors + replaysSessionSampleRate: + environment === 'development' || environment === 'preview' ? 1.0 : 0.1, + replaysOnErrorSampleRate: 1.0, + + // Enable structured logging to Sentry + enableLogs: true, + + // Scrub sensitive data from structured logs before sending to Sentry + beforeSendLog(log) { + // Drop debug-level logs in production to reduce noise and quota usage + if (log.level === 'debug' && environment === 'production') return null; + // Redact Matrix IDs and tokens from log messages + if (typeof log.message === 'string') { + // eslint-disable-next-line no-param-reassign + log.message = log.message + .replace( + /(access_token|password|token|refresh_token|session_id|sync_token|next_batch)([=:\s]+)([^\s&]+)/gi, + '$1$2[REDACTED]' + ) + .replace(/@[^:]+:[^\s]+/g, '@[USER_ID]') + .replace(/![^:]+:[^\s]+/g, '![ROOM_ID]') + .replace(/\$[^:\s]+/g, '$[EVENT_ID]'); + } + return log; + }, + + // Rate limiting: cap error events per page-load session to avoid quota exhaustion. + // Separate counters for errors and transactions so perf traces do not drain the error budget. + beforeSendTransaction(event) { + return event; + }, + + // Sanitize sensitive data from all breadcrumb messages before sending to Sentry + beforeBreadcrumb(breadcrumb) { + if (!breadcrumb.message) return breadcrumb; + // Always apply redaction — both token values and Matrix entity IDs. + // Do NOT use single-character patterns like '@', '!', '$' as they are far too broad. + const redacted = breadcrumb.message + // Redact token key=value pairs (e.g. access_token=abc123) + .replace( + /(access_token|password|refresh_token|device_id|session_id|sync_token|next_batch)([=:\s]+)([^\s&"']+)/gi, + '$1$2[REDACTED]' + ) + // Redact full Matrix user IDs: @localpart:server.tld + .replace(/@[^\s:@]+:[^\s,'"(){}\[\]]+/g, '@[USER_ID]') + // Redact full Matrix room IDs: !opaque:server.tld + .replace(/![^\s:]+:[^\s,'"(){}\[\]]+/g, '![ROOM_ID]') + // Redact Matrix event IDs: $base64Url (at least 10 chars to avoid false positives) + .replace(/\$[A-Za-z0-9\-_+/]{10,}/g, '$[EVENT_ID]'); + return redacted === breadcrumb.message ? breadcrumb : { ...breadcrumb, message: redacted }; + }, + + beforeSend(event, hint) { + sessionErrorCount += 1; + if (sessionErrorCount > SESSION_ERROR_LIMIT) { + return null; // Drop event — session limit reached + } + + // Improve grouping for Matrix API errors. + // MatrixError objects carry an `errcode` (e.g. M_FORBIDDEN, M_NOT_FOUND) — use it to + // split errors into meaningful issue groups rather than merging them all by stack trace. + const originalException = hint?.originalException; + if ( + originalException !== null && + typeof originalException === 'object' && + 'errcode' in originalException && + typeof (originalException as Record).errcode === 'string' + ) { + const errcode = (originalException as Record).errcode as string; + // Preserve default grouping AND split by errcode + // eslint-disable-next-line no-param-reassign + event.fingerprint = ['{{ default }}', errcode]; + } + + // Scrub sensitive data from error messages + if (event.message) { + if ( + event.message.includes('access_token') || + event.message.includes('password') || + event.message.includes('token') + ) { + // eslint-disable-next-line no-param-reassign + event.message = event.message.replace( + /(access_token|password|token|refresh_token|session_id|sync_token|next_batch)([=:]\s*)([^\s&]+)/gi, + '$1$2[REDACTED]' + ); + } + // Redact Matrix IDs to protect user privacy + // eslint-disable-next-line no-param-reassign + event.message = event.message.replace(/@[^:]+:[^\s]+/g, '@[USER_ID]'); + // eslint-disable-next-line no-param-reassign + event.message = event.message.replace(/![^:]+:[^\s]+/g, '![ROOM_ID]'); + // eslint-disable-next-line no-param-reassign + event.message = event.message.replace(/\$[^:\s]+/g, '$[EVENT_ID]'); + } + + // Scrub sensitive data from exception values + if (event.exception?.values) { + event.exception.values.forEach((exception) => { + if (exception.value) { + // eslint-disable-next-line no-param-reassign + exception.value = exception.value.replace( + /(access_token|password|token|refresh_token|session_id|sync_token|next_batch)([=:]\s*)([^\s&]+)/gi, + '$1$2[REDACTED]' + ); + // Redact Matrix IDs + // eslint-disable-next-line no-param-reassign + exception.value = exception.value.replace(/@[^:]+:[^\s]+/g, '@[USER_ID]'); + // eslint-disable-next-line no-param-reassign + exception.value = exception.value.replace(/![^:]+:[^\s]+/g, '![ROOM_ID]'); + // eslint-disable-next-line no-param-reassign + exception.value = exception.value.replace(/\$[^:\s]+/g, '$[EVENT_ID]'); + } + }); + } + + // Scrub request data + if (event.request?.url) { + // eslint-disable-next-line no-param-reassign + event.request.url = event.request.url.replace( + /(access_token|password|token)([=:]\s*)([^\s&]+)/gi, + '$1$2[REDACTED]' + ); + } + + if (event.request?.headers) { + const headers = event.request.headers as Record; + if (headers.Authorization) { + headers.Authorization = '[REDACTED]'; + } + } + + return event; + }, + }); + + // Expose Sentry globally for debugging and console testing + // Set app-wide attributes on the global scope so they appear on all events and logs + Sentry.getGlobalScope().setAttributes({ + 'app.name': 'sable', + 'app.version': release ?? 'unknown', + }); + + // @ts-expect-error - Adding to window for debugging + window.Sentry = Sentry; + + // eslint-disable-next-line no-console + console.info( + `[Sentry] Initialized for ${environment} environment${replayEnabled ? ' with Session Replay' : ''}` + ); + // eslint-disable-next-line no-console + console.info(`[Sentry] DSN configured: ${dsn?.substring(0, 30)}...`); + // eslint-disable-next-line no-console + console.info(`[Sentry] Release: ${release || 'not set'}`); +} else if (!sentryEnabled) { + // eslint-disable-next-line no-console + console.info('[Sentry] Disabled by user preference'); +} else { + // eslint-disable-next-line no-console + console.info('[Sentry] Disabled - no DSN provided'); +} + +// Export Sentry for use in other parts of the application +export { Sentry }; diff --git a/vite.config.ts b/vite.config.ts index d2813304..bfca2edc 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -16,6 +16,7 @@ import fs from 'fs'; import path from 'path'; import { cloudflare } from '@cloudflare/vite-plugin'; import { createRequire } from 'module'; +import { sentryVitePlugin } from '@sentry/vite-plugin'; import buildConfig from './build.config'; const packageJson = JSON.parse( @@ -189,6 +190,26 @@ export default defineConfig({ ], include: /\.(html|xml|css|json|js|mjs|svg|yaml|yml|toml|wasm|txt|map)$/, }), + // Sentry source map upload — only active when credentials are provided at build time + ...(process.env.SENTRY_AUTH_TOKEN && process.env.SENTRY_ORG && process.env.SENTRY_PROJECT + ? [ + sentryVitePlugin({ + org: process.env.SENTRY_ORG, + project: process.env.SENTRY_PROJECT, + authToken: process.env.SENTRY_AUTH_TOKEN, + sourcemaps: { + filesToDeleteAfterUpload: ['dist/**/*.map'], + }, + release: { + name: appVersion, + }, + // Annotate React components with data-sentry-* attributes at build + // time so Sentry can show component names in breadcrumbs, spans, + // and replay search instead of raw CSS selectors. + reactComponentAnnotation: { enabled: true }, + }), + ] + : []), ], optimizeDeps: { // Rebuild dep optimizer cache on each dev start to avoid stale API shapes. From 36c4e0591b3ec89e83ace6fed30f0818bc44ae98 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Sun, 15 Mar 2026 23:40:58 -0400 Subject: [PATCH 043/146] =?UTF-8?q?feat:=20add=20Sentry=E2=86=92GitHub=20I?= =?UTF-8?q?ssues=20triage=20for=20PR=20preview=20builds?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Tag all Sentry events with PR number via VITE_SENTRY_PR env var (instrument.ts: setTag('pr', prNumber) on global scope) - cloudflare-web-preview.yml: inject Sentry DSN, environment=preview, PR number, and source-map secrets into build env for PR runs - New workflow sentry-preview-issues.yml: on every PR push, query Sentry for unresolved issues tagged with the PR number and environment=preview; create a GitHub issue per unique error (deduplicated by sentry-id marker), labelled 'sentry-preview' + 'pr-{N}'; maintain a sticky PR comment with a summary table; reopen closed issues on regression - Labels allow filtering: -label:sentry-preview hides all automated issues --- .github/workflows/cloudflare-web-preview.yml | 16 ++ .github/workflows/sentry-preview-issues.yml | 231 +++++++++++++++++++ src/instrument.ts | 6 + 3 files changed, 253 insertions(+) create mode 100644 .github/workflows/sentry-preview-issues.yml diff --git a/.github/workflows/cloudflare-web-preview.yml b/.github/workflows/cloudflare-web-preview.yml index 5ddfe5a0..8b93a4bb 100644 --- a/.github/workflows/cloudflare-web-preview.yml +++ b/.github/workflows/cloudflare-web-preview.yml @@ -54,6 +54,22 @@ jobs: echo EOF } >> "$GITHUB_OUTPUT" + - name: Set Sentry build environment for PR preview + if: github.event_name == 'pull_request' + env: + VITE_SENTRY_DSN: ${{ secrets.VITE_SENTRY_DSN }} + SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} + SENTRY_ORG: ${{ secrets.SENTRY_ORG }} + SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }} + shell: bash + run: | + echo "VITE_SENTRY_DSN=$VITE_SENTRY_DSN" >> "$GITHUB_ENV" + echo "VITE_SENTRY_ENVIRONMENT=preview" >> "$GITHUB_ENV" + echo "VITE_SENTRY_PR=${{ github.event.pull_request.number }}" >> "$GITHUB_ENV" + echo "SENTRY_AUTH_TOKEN=$SENTRY_AUTH_TOKEN" >> "$GITHUB_ENV" + echo "SENTRY_ORG=$SENTRY_ORG" >> "$GITHUB_ENV" + echo "SENTRY_PROJECT=$SENTRY_PROJECT" >> "$GITHUB_ENV" + - name: Setup app and build uses: ./.github/actions/setup with: diff --git a/.github/workflows/sentry-preview-issues.yml b/.github/workflows/sentry-preview-issues.yml new file mode 100644 index 00000000..c81787e7 --- /dev/null +++ b/.github/workflows/sentry-preview-issues.yml @@ -0,0 +1,231 @@ +name: Sentry Preview Error Triage + +on: + pull_request: + types: [opened, synchronize, reopened] + paths: + - 'src/**' + - 'index.html' + - 'package.json' + - 'vite.config.ts' + - 'tsconfig.json' + workflow_dispatch: + inputs: + pr_number: + description: 'PR number to triage' + required: true + type: number + +jobs: + triage: + # Only run for PRs from the same repo (not forks) or manual dispatch + if: > + (github.event_name == 'pull_request' && + github.event.pull_request.head.repo.full_name == github.repository) || + github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + permissions: + issues: write + pull-requests: write + steps: + - name: Triage Sentry preview errors + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + env: + SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} + SENTRY_ORG: ${{ secrets.SENTRY_ORG }} + SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }} + PR_NUMBER: ${{ github.event.pull_request.number || github.event.inputs.pr_number }} + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const sentryToken = process.env.SENTRY_AUTH_TOKEN; + const sentryOrg = process.env.SENTRY_ORG; + const sentryProject = process.env.SENTRY_PROJECT; + const prNumber = Number(process.env.PR_NUMBER); + + if (!prNumber) { + core.info('No PR number available — skipping triage.'); + return; + } + if (!sentryToken || !sentryOrg || !sentryProject) { + core.warning('Sentry credentials not configured — skipping triage.'); + return; + } + + const COMMENT_MARKER = ''; + const { owner, repo } = context.repo; + + // Create a label if it doesn't already exist + async function ensureLabel(name, description, color) { + try { + await github.rest.issues.getLabel({ owner, repo, name }); + } catch { + try { + await github.rest.issues.createLabel({ owner, repo, name, description, color }); + } catch (err) { + core.warning(`Could not create label "${name}": ${err.message}`); + } + } + } + + // Find an existing GitHub issue that tracks a given Sentry issue ID + async function findExistingGhIssue(sentryIssueId) { + const marker = `sentry-id:${sentryIssueId}`; + const result = await github.rest.search.issuesAndPullRequests({ + q: `repo:${owner}/${repo} is:issue label:sentry-preview "${marker}" in:body`, + }); + return result.data.total_count > 0 ? result.data.items[0] : null; + } + + // Create or update the sticky PR comment with the triage summary table + async function upsertPrComment(rows) { + const now = new Date().toUTCString().replace(':00 GMT', ' UTC'); + let body; + + if (rows.length === 0) { + body = [ + COMMENT_MARKER, + '## Sentry Preview Error Triage', + '', + `No Sentry errors found for this PR's preview deployment as of ${now}.`, + '', + '_This comment updates automatically after each push._', + ].join('\n'); + } else { + const tableRows = rows.map( + (r) => + `| [${r.title.slice(0, 70)}](${r.permalink}) | ${r.count} | ${new Date(r.firstSeen).toLocaleDateString()} | #${r.ghIssueNumber} |` + ); + body = [ + COMMENT_MARKER, + '## Sentry Preview Error Triage', + '', + `**${rows.length} error type(s)** detected in this PR's preview deployment:`, + '', + '| Error | Events | First seen | Issue |', + '| ----- | ------ | ---------- | ----- |', + ...tableRows, + '', + `_Last checked: ${now}. Exclude these from your issues view with \`-label:sentry-preview\`._`, + ].join('\n'); + } + + const comments = await github.paginate(github.rest.issues.listComments, { + owner, + repo, + issue_number: prNumber, + }); + const existing = comments.find( + (c) => c.user.type === 'Bot' && c.body.includes(COMMENT_MARKER) + ); + + if (existing) { + await github.rest.issues.updateComment({ + owner, + repo, + comment_id: existing.id, + body, + }); + } else { + await github.rest.issues.createComment({ + owner, + repo, + issue_number: prNumber, + body, + }); + } + } + + // Query Sentry for unresolved issues tagged with this PR number in the preview env + const query = encodeURIComponent(`is:unresolved pr:${prNumber}`); + const sentryUrl = + `https://sentry.io/api/0/projects/${sentryOrg}/${sentryProject}/issues/` + + `?query=${query}&environment=preview&limit=100`; + + let sentryIssues; + try { + const resp = await fetch(sentryUrl, { + headers: { Authorization: `Bearer ${sentryToken}` }, + }); + if (!resp.ok) { + const msg = await resp.text(); + core.warning(`Sentry API returned ${resp.status}: ${msg.slice(0, 200)}`); + return; + } + sentryIssues = await resp.json(); + } catch (err) { + core.warning(`Sentry API unreachable: ${err.message}`); + return; + } + + if (!Array.isArray(sentryIssues) || sentryIssues.length === 0) { + await upsertPrComment([]); + return; + } + + // Ensure the shared and PR-specific labels exist + await ensureLabel('sentry-preview', 'Automated Sentry preview error', 'e4e669'); + await ensureLabel(`pr-${prNumber}`, `Preview errors from PR #${prNumber}`, 'fbca04'); + + const rows = []; + for (const issue of sentryIssues) { + const { + id: sentryId, + title, + culprit, + permalink, + count, + userCount, + firstSeen, + lastSeen, + } = issue; + const displayTitle = (title || culprit || 'Unknown error').trim(); + const sentryMarker = `sentry-id:${sentryId}`; + + const existing = await findExistingGhIssue(sentryId); + let ghIssueNumber; + + if (existing) { + ghIssueNumber = existing.number; + // Reopen if it was closed (e.g. after a previous fix that regressed) + if (existing.state === 'closed') { + await github.rest.issues.update({ + owner, + repo, + issue_number: ghIssueNumber, + state: 'open', + }); + core.info(`Reopened GH issue #${ghIssueNumber} for Sentry issue ${sentryId}`); + } + } else { + const issueBody = [ + ``, + `## Sentry Error — PR #${prNumber} Preview`, + '', + `**Error:** [${displayTitle}](${permalink})`, + `**First seen:** ${new Date(firstSeen).toUTCString()}`, + `**Last seen:** ${new Date(lastSeen).toUTCString()}`, + `**Events:** ${count} | **Affected users:** ${userCount}`, + '', + `This issue was automatically created from a Sentry error detected in the preview deployment for PR #${prNumber}.`, + '', + '> [!NOTE]', + '> To exclude automated preview issues from your issues view, filter with: `-label:sentry-preview`', + ].join('\n'); + + const created = await github.rest.issues.create({ + owner, + repo, + title: `[Sentry] ${displayTitle.slice(0, 120)}`, + body: issueBody, + labels: ['sentry-preview', `pr-${prNumber}`], + }); + ghIssueNumber = created.data.number; + core.info(`Created GH issue #${ghIssueNumber} for Sentry issue ${sentryId}`); + } + + rows.push({ title: displayTitle, permalink, count, firstSeen, ghIssueNumber }); + } + + await upsertPrComment(rows); + core.info(`Triage complete: ${rows.length} Sentry issue(s) processed for PR #${prNumber}.`); diff --git a/src/instrument.ts b/src/instrument.ts index e7121da0..9efec360 100644 --- a/src/instrument.ts +++ b/src/instrument.ts @@ -222,6 +222,12 @@ if (dsn && sentryEnabled) { 'app.version': release ?? 'unknown', }); + // Tag all events with the PR number when running in a PR preview deployment + const prNumber = import.meta.env.VITE_SENTRY_PR; + if (prNumber) { + Sentry.getGlobalScope().setTag('pr', prNumber); + } + // @ts-expect-error - Adding to window for debugging window.Sentry = Sentry; From 4e539b91caf83c23373a0bd29757d8896a9601e6 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Sun, 15 Mar 2026 23:40:58 -0400 Subject: [PATCH 044/146] feat(sentry): comprehensive data scrubbing, settings UI, and privacy policy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Before-send scrubbing in instrument.ts covers: - Matrix user IDs (@user:server → @[USER_ID]) - Room IDs (!room:server → ![ROOM_ID]) - Event IDs ($event → $[EVENT_ID]) - Percent-encoded sigils (%40, %21, %24, %23) - Hybrid-encoded forms (decoded sigil + %3A colon) - Tokens, credentials, and query params (access_token, next_batch, etc.) - All span data string values (not just http.url) - Profile URLs, key backup paths, media paths in span data - preview_url query params and exception values - 'none' sentinel for unset room tags Privacy policy added to docs/PRIVACY.md (linked from General settings). DiagnosticsAndPrivacy component added to General settings with error reporting and session replay toggles. TS2367 redundant phase guard removed from useCallSignaling.ts. --- .changeset/fix-direct-tab-double-badge.md | 5 + .changeset/fix-thread-fallback-reply-spec.md | 5 + .changeset/fix-timeline-refresh-scroll.md | 5 + docs/PRIVACY_POLICY.md | 116 ++++++++++++ docs/SENTRY_INTEGRATION.md | 94 ++++++++-- docs/SENTRY_PRIVACY.md | 176 +++++++++--------- src/app/components/DefaultErrorPage.tsx | 8 +- src/app/features/room/RoomInput.tsx | 55 +++++- src/app/features/room/RoomTimeline.tsx | 133 +++++++++---- .../developer-tools/SentrySettings.tsx | 97 +--------- src/app/features/settings/general/General.tsx | 104 +++++++++++ src/app/hooks/useCallSignaling.ts | 31 ++- src/app/pages/Router.tsx | 102 +++++----- src/app/pages/client/ClientNonUIFeatures.tsx | 15 +- .../pages/client/sidebar/DirectDMsList.tsx | 62 ++---- src/app/pages/client/sidebar/DirectTab.tsx | 12 +- .../client/sidebar/useSidebarDirectRoomIds.ts | 54 ++++++ src/app/plugins/call/CallEmbed.ts | 29 ++- src/app/utils/debugLogger.ts | 19 +- src/app/utils/matrix.ts | 12 +- src/instrument.ts | 161 ++++++++++++++-- 21 files changed, 896 insertions(+), 399 deletions(-) create mode 100644 .changeset/fix-direct-tab-double-badge.md create mode 100644 .changeset/fix-thread-fallback-reply-spec.md create mode 100644 .changeset/fix-timeline-refresh-scroll.md create mode 100644 docs/PRIVACY_POLICY.md create mode 100644 src/app/pages/client/sidebar/useSidebarDirectRoomIds.ts diff --git a/.changeset/fix-direct-tab-double-badge.md b/.changeset/fix-direct-tab-double-badge.md new file mode 100644 index 00000000..6d050636 --- /dev/null +++ b/.changeset/fix-direct-tab-double-badge.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fix duplicate unread badges on the /direct/ icon for DM rooms already shown as individual sidebar avatars diff --git a/.changeset/fix-thread-fallback-reply-spec.md b/.changeset/fix-thread-fallback-reply-spec.md new file mode 100644 index 00000000..6eecf251 --- /dev/null +++ b/.changeset/fix-thread-fallback-reply-spec.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fix thread messages to include the required `m.in_reply_to` fallback pointing to the latest thread event, so unthreaded clients can display the reply chain correctly per the Matrix spec. diff --git a/.changeset/fix-timeline-refresh-scroll.md b/.changeset/fix-timeline-refresh-scroll.md new file mode 100644 index 00000000..d042bd01 --- /dev/null +++ b/.changeset/fix-timeline-refresh-scroll.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fix spurious scroll-to-bottom and MaxListeners warnings on sync gap: stable callback refs and prevEventsLength guard in RoomTimeline, correct CallEmbed .bind(this) listener leak, stable refs in useCallSignaling, and unreadInfoRef to stop per-message listener churn diff --git a/docs/PRIVACY_POLICY.md b/docs/PRIVACY_POLICY.md new file mode 100644 index 00000000..73685e52 --- /dev/null +++ b/docs/PRIVACY_POLICY.md @@ -0,0 +1,116 @@ +# Privacy Policy + +**Effective date:** 2026-03-15 + +Sable is an open-source Matrix client developed by 7w1. + +It is designed to keep data collection to a minimum. Most of the app works on your device and communicates directly with the Matrix homeserver you choose. + +## Who is responsible + +For official Sable builds distributed by the project, the data controller is **7w1**. + +Contact: **security@sable.moe** +Project website: [**https://sable.moe**](https://sable.moe) + +If you use a self-hosted, modified, or third-party build of Sable, that operator may use different diagnostics settings and may be responsible for their own privacy practices. + +## What we collect + +We only collect limited diagnostic data to help find bugs and improve the stability and security of the app. + +Diagnostic data is sent only when error reporting is enabled. + +This data may include: + +- Crash and error details, such as exception type, stack trace, and error message +- Device, browser, or operating system name and version +- Application version and environment +- Anonymous performance information, such as page load, sync, or message-send timing + +Before any diagnostic data is sent, sensitive values are scrubbed in the browser on your device. + +## What we do not collect + +Sable is designed not to collect or transmit: + +- Matrix message content +- Room names or aliases +- User display names or avatars +- Contact lists or room member lists +- Authentication tokens or passwords +- Encryption keys or cryptographic session data +- IP addresses +- Precise or approximate location data + +## Optional features + +### Session replay + +Session replay may be available for debugging, but it is **disabled by default** and must be turned on by the user. + +When session replay is enabled, all text is masked, media is blocked, and form inputs are masked before any data leaves the device. + +This is intended to ensure that Matrix messages, room names, user names, and other personal content are not visible in replays. + +### Bug reports + +You may choose to submit a bug report from within the app. + +A bug report may include the description you write, platform and app version details, and optional diagnostic logs that you choose to attach. + +Submitting a bug report is voluntary, and the app shows what will be sent before submission. + +## Third-party services + +Sable uses **Sentry** for crash reporting and performance diagnostics. + +Sentry receives only the diagnostic data described in this policy. + +Sentry handles that data under its own privacy policy: +[**https://sentry.io/privacy/**](https://sentry.io/privacy/) + +Technical details about Sable's Sentry integration are documented here: +[**https://github.com/SableClient/Sable/blob/feat/sentry-pr/docs/SENTRY_PRIVACY.md**](https://github.com/SableClient/Sable/blob/feat/sentry-pr/docs/SENTRY_PRIVACY.md) + +If a Sentry DSN is not configured, Sentry is inactive and no Sentry data is sent. + +Self-hosted deployments may use a different Sentry instance or disable diagnostics entirely. + +## Your controls + +You can manage diagnostic features in: **Settings → General → Diagnostics & Privacy** + +Depending on the build, you can disable error reporting, enable or disable session replay, and adjust breadcrumb categories. + +You can also stop all app-based data transmission by uninstalling the app. + +## Legal basis + +For users in the European Economic Area, diagnostic data is processed on the basis of legitimate interest for app reliability and security, and on the basis of consent where optional features such as session replay are explicitly enabled. + +## Retention and transfers + +Diagnostic data is stored by Sentry according to the retention settings of the Sentry project. + +The Sable project does not keep a separate copy of that diagnostic data. + +Because Sentry is a cloud service, diagnostic data may be processed outside your country of residence. Sentry states that it provides safeguards such as Standard Contractual Clauses where required. + +## Children + +Sable is not directed to children under 13. + +We do not knowingly collect personal information from children through the app. + +If you believe a child has submitted information through Sable, contact **security@sable.moe** so it can be removed. + +## Changes to this policy + +We may update this Privacy Policy from time to time. + +When we do, we will publish the updated version at [**https://sable.moe**](https://sable.moe). + +## Contact + +If you have questions about this Privacy Policy or want to request deletion of data connected to a bug report, contact **security@sable.moe**. diff --git a/docs/SENTRY_INTEGRATION.md b/docs/SENTRY_INTEGRATION.md index 3227e211..e71f417e 100644 --- a/docs/SENTRY_INTEGRATION.md +++ b/docs/SENTRY_INTEGRATION.md @@ -86,7 +86,7 @@ New Sentry settings panel in Developer Tools: - **Export debug logs**: Download the in-memory log buffer as JSON for offline analysis - **Attach debug logs**: Manually attach recent logs to next error -Access via: Settings → Developer Tools → Error Tracking (Sentry) +Access via: Settings → General → Diagnostics & Privacy ## Configuration @@ -113,6 +113,76 @@ SENTRY_ORG=your-org-slug SENTRY_PROJECT=your-project-slug ``` +### Self-Hosting with Docker + +Sable is compiled at build time, so `VITE_*` variables must be passed as Docker +**build arguments** — they cannot be injected at container runtime via a plain +`docker run -e` flag. The easiest way for self-hosters to supply them is with +a `.env` file and `docker-compose`. + +#### 1. Create a `.env` file + +```env +# .env — never commit this file +VITE_SENTRY_DSN=https://your-key@oXXXXX.ingest.sentry.io/XXXXXXX +VITE_SENTRY_ENVIRONMENT=production +``` + +The `VITE_SENTRY_ENVIRONMENT` value controls sampling rates (see table below). +Leave it as `production` for a live deployment. + +#### 2. Reference it in `docker-compose.yml` + +The `args` block forwards the variables from `.env` into the Docker build +stage so Vite can embed them in the bundle: + +```yaml +services: + sable: + build: + context: . + args: + - VITE_SENTRY_DSN=${VITE_SENTRY_DSN} + - VITE_SENTRY_ENVIRONMENT=${VITE_SENTRY_ENVIRONMENT} + ports: + - '8080:8080' +``` + +Then build and start with: + +```bash +docker compose --env-file .env up --build +``` + +#### 3. Verify it worked + +Open the browser console after loading your instance — you should see: + +``` +[Sentry] Initialized for production environment +[Sentry] DSN configured: https://your-key@o... +``` + +If you see `[Sentry] Disabled - no DSN provided`, the build arg was not +picked up — double-check the `args` block and that your `.env` file is in the +same directory as `docker-compose.yml`. + +#### Building without Compose + +If you use plain `docker build`, pass build args directly: + +```bash +docker build \ + --build-arg VITE_SENTRY_DSN="https://your-key@oXXXXX.ingest.sentry.io/XXXXXXX" \ + --build-arg VITE_SENTRY_ENVIRONMENT="production" \ + -t sable . +``` + +> **Security note:** DSN values embedded in the JavaScript bundle are visible +> to any user who opens DevTools. This is normal and expected for Sentry DSNs — +> they are designed to be public-facing ingest keys. Rate-limiting and origin +> restrictions on the Sentry project side are the correct controls. + ### Deployment Configuration **Production deployment (from `dev` branch):** @@ -161,7 +231,7 @@ localStorage.setItem('sable_sentry_enabled', 'false'); localStorage.setItem('sable_sentry_replay_enabled', 'false'); ``` -Or use the UI in Settings → Developer Tools → Error Tracking (Sentry). +Or use the UI in Settings → General → Diagnostics & Privacy. ## Custom Instrumentation @@ -169,15 +239,15 @@ Beyond automatic error capture, Sable has hand-crafted monitoring at key lifecycle points. See [SENTRY_PRIVACY.md](./SENTRY_PRIVACY.md) for the full metrics reference. Key areas: -| Area | What's tracked | -|------|----------------| -| **Auth** | Login failures (by `errcode`), forced server logouts | -| **Sync** | Transport type, degraded states, cycle stats, time-to-ready | -| **Cryptography** | Decryption failures (by failure reason), key backup errors, store wipes, E2E verification outcomes | -| **Messaging** | Send latency, send errors, local-echo `NOT_SENT` events | -| **Timeline** | Opens, virtual window size, jump-load latency, re-initialisations | -| **Media** | Upload latency, upload size, cache stats | -| **Background clients** | Per-account notification client count, startup failures | +| Area | What's tracked | +| ---------------------- | -------------------------------------------------------------------------------------------------- | +| **Auth** | Login failures (by `errcode`), forced server logouts | +| **Sync** | Transport type, degraded states, cycle stats, time-to-ready | +| **Cryptography** | Decryption failures (by failure reason), key backup errors, store wipes, E2E verification outcomes | +| **Messaging** | Send latency, send errors, local-echo `NOT_SENT` events | +| **Timeline** | Opens, virtual window size, jump-load latency, re-initialisations | +| **Media** | Upload latency, upload size, cache stats | +| **Background clients** | Per-account notification client count, startup failures | Fatal errors that are caught by `useAsyncCallback` state (and therefore never reach React's ErrorBoundary) are explicitly forwarded with `captureException`: @@ -301,7 +371,7 @@ No message content, room conversations, or personal information is ever sent to To test the integration: 1. **Test error reporting**: - - Go to Settings → Developer Tools → Error Tracking + - Go to Settings → General → Diagnostics & Privacy - Check that Sentry is enabled and `VITE_SENTRY_DSN` is set - Open the browser console and run: `window.Sentry?.captureMessage('Test message')` - Check the Sentry dashboard for the event diff --git a/docs/SENTRY_PRIVACY.md b/docs/SENTRY_PRIVACY.md index 93877a7d..265ef57e 100644 --- a/docs/SENTRY_PRIVACY.md +++ b/docs/SENTRY_PRIVACY.md @@ -9,7 +9,7 @@ configuration details see [SENTRY_INTEGRATION.md](./SENTRY_INTEGRATION.md). ## What Is Collected Sentry is **disabled by default when no DSN is configured** and can be **opted -out by users** at any time via Settings → Developer Tools → Error Tracking. +out by users** at any time via Settings → General → Diagnostics & Privacy. When enabled, the following categories of data are sent: @@ -48,14 +48,14 @@ browser. In addition to automatic navigation/console breadcrumbs, the following named events are explicitly recorded as breadcrumbs: -| Event | Category | Level | Source | -|-------|----------|-------|--------| -| Session forcibly logged out by server | `auth` | warning | `ClientRoot.tsx` | -| Sync state changed to Reconnecting/Error | `sync` | warning/error | `SyncStatus.tsx` | -| Sliding sync first run completed | `sync` | info | `initMatrix.ts` | -| Crypto store mismatch — wiping local stores | `crypto` | warning | `initMatrix.ts` | -| Key backup failed | `crypto` | error | `useKeyBackup.ts` | -| High media inflight request count | `media` | warning | `ClientNonUIFeatures.tsx` | +| Event | Category | Level | Source | +| ------------------------------------------- | -------- | ------------- | ------------------------- | +| Session forcibly logged out by server | `auth` | warning | `ClientRoot.tsx` | +| Sync state changed to Reconnecting/Error | `sync` | warning/error | `SyncStatus.tsx` | +| Sliding sync first run completed | `sync` | info | `initMatrix.ts` | +| Crypto store mismatch — wiping local stores | `crypto` | warning | `initMatrix.ts` | +| Key backup failed | `crypto` | error | `useKeyBackup.ts` | +| High media inflight request count | `media` | warning | `ClientNonUIFeatures.tsx` | **Code:** `src/app/pages/client/ClientRoot.tsx`, `src/app/pages/client/SyncStatus.tsx`, `src/client/initMatrix.ts`, `src/app/hooks/useKeyBackup.ts`, @@ -66,10 +66,10 @@ events are explicitly recorded as breadcrumbs: The following failure paths use explicit `captureException` because they are caught by state management hooks and never propagate to React's ErrorBoundary: -| Failure | Tag | Source | -|---------|-----|--------| -| Client failed to load (fetch/init) | `phase: load` | `ClientRoot.tsx` | -| Client failed to start (sync start) | `phase: start` | `ClientRoot.tsx` | +| Failure | Tag | Source | +| ---------------------------------------------- | ------------------------------------ | ----------------------------- | +| Client failed to load (fetch/init) | `phase: load` | `ClientRoot.tsx` | +| Client failed to start (sync start) | `phase: start` | `ClientRoot.tsx` | | Background notification client failed to start | `component: BackgroundNotifications` | `BackgroundNotifications.tsx` | **Code:** `src/app/pages/client/ClientRoot.tsx`, @@ -84,21 +84,21 @@ caught by state management hooks and never propagate to React's ErrorBoundary: Performance data contains **no message content, no room names, and no user identifiers**. Spans are labelled with operation names only. -| Span name | Operation | Source | -|-----------|-----------|--------| -| `auth.login` | `auth` | `loginUtil.ts` | -| `decrypt.event` | `matrix.crypto` | `EncryptedContent.tsx` | -| `decrypt.bulk` | `matrix.crypto` | `room.ts` | -| `timeline.jump_load` | `matrix.timeline` | `RoomTimeline.tsx` | -| `message.send` | `matrix.message` | `RoomInput.tsx` | -| Sliding sync processing | `matrix.sync` | `slidingSync.ts` | +| Span name | Operation | Source | +| ----------------------- | ----------------- | ---------------------- | +| `auth.login` | `auth` | `loginUtil.ts` | +| `decrypt.event` | `matrix.crypto` | `EncryptedContent.tsx` | +| `decrypt.bulk` | `matrix.crypto` | `room.ts` | +| `timeline.jump_load` | `matrix.timeline` | `RoomTimeline.tsx` | +| `message.send` | `matrix.message` | `RoomInput.tsx` | +| Sliding sync processing | `matrix.sync` | `slidingSync.ts` | **Sample rates:** -| Environment | Traces | Profiles | -|---------------------|--------|----------| -| `production` | 10% | 10% | -| `preview` / `development` | 100% | 100% | +| Environment | Traces | Profiles | +| ------------------------- | ------ | -------- | +| `production` | 10% | 10% | +| `preview` / `development` | 100% | 100% | **Code:** `src/instrument.ts` — `tracesSampleRate`, `profilesSampleRate` **Code:** `src/app/features/room/RoomInput.tsx` — message send span @@ -112,22 +112,22 @@ or numeric measurements. #### Authentication -| Metric | Type | Attributes | What it tracks | -|--------|------|-----------|----------------| -| `sable.auth.login_failed` | count | `errcode` | Login attempt failures by error code | +| Metric | Type | Attributes | What it tracks | +| ------------------------- | ----- | ---------- | ------------------------------------ | +| `sable.auth.login_failed` | count | `errcode` | Login attempt failures by error code | **Code:** `src/app/pages/auth/login/loginUtil.ts` #### Cryptography -| Metric | Type | Attributes | What it tracks | -|--------|------|-----------|----------------| -| `sable.decryption.failure` | count | `reason` | Unable-to-decrypt events by failure reason | -| `sable.decryption.event_ms` | distribution | — | Per-event decryption latency | -| `sable.decryption.bulk_latency_ms` | distribution | `event_count` | Bulk re-decryption time on room open | -| `sable.crypto.key_backup_failures` | count | `errcode` | Key backup errors by code | -| `sable.crypto.store_wipe` | count | — | Crypto store mismatch wipe-and-retry occurrences | -| `sable.crypto.verification_outcome` | count | `outcome` (`completed`/`cancelled`) | E2E device verification outcomes | +| Metric | Type | Attributes | What it tracks | +| ----------------------------------- | ------------ | ----------------------------------- | ------------------------------------------------ | +| `sable.decryption.failure` | count | `reason` | Unable-to-decrypt events by failure reason | +| `sable.decryption.event_ms` | distribution | — | Per-event decryption latency | +| `sable.decryption.bulk_latency_ms` | distribution | `event_count` | Bulk re-decryption time on room open | +| `sable.crypto.key_backup_failures` | count | `errcode` | Key backup errors by code | +| `sable.crypto.store_wipe` | count | — | Crypto store mismatch wipe-and-retry occurrences | +| `sable.crypto.verification_outcome` | count | `outcome` (`completed`/`cancelled`) | E2E device verification outcomes | **Code:** `src/app/features/room/message/EncryptedContent.tsx`, `src/app/utils/room.ts`, `src/app/hooks/useKeyBackup.ts`, @@ -135,70 +135,70 @@ or numeric measurements. #### Messaging -| Metric | Type | Attributes | What it tracks | -|--------|------|-----------|----------------| -| `sable.message.send_latency_ms` | distribution | `encrypted` | Message send round-trip time | -| `sable.message.send_error` | count | — | Send errors from message composer | -| `sable.message.send_failed` | count | — | Local-echo `NOT_SENT` status events | +| Metric | Type | Attributes | What it tracks | +| ------------------------------- | ------------ | ----------- | ----------------------------------- | +| `sable.message.send_latency_ms` | distribution | `encrypted` | Message send round-trip time | +| `sable.message.send_error` | count | — | Send errors from message composer | +| `sable.message.send_failed` | count | — | Local-echo `NOT_SENT` status events | **Code:** `src/app/features/room/RoomInput.tsx`, `src/app/features/room/RoomTimeline.tsx` #### Timeline -| Metric | Type | Attributes | What it tracks | -|--------|------|-----------|----------------| -| `sable.timeline.open` | count | `mode` | Timeline render initiations | -| `sable.timeline.render_window` | distribution | `mode` | Initial virtual window size | -| `sable.timeline.jump_load_ms` | distribution | — | Event-jump timeline load latency | -| `sable.timeline.reinit` | count | — | Full timeline re-initialisations | -| `sable.pagination.error` | count | `direction` | Pagination errors by direction | +| Metric | Type | Attributes | What it tracks | +| ------------------------------ | ------------ | ----------- | -------------------------------- | +| `sable.timeline.open` | count | `mode` | Timeline render initiations | +| `sable.timeline.render_window` | distribution | `mode` | Initial virtual window size | +| `sable.timeline.jump_load_ms` | distribution | — | Event-jump timeline load latency | +| `sable.timeline.reinit` | count | — | Full timeline re-initialisations | +| `sable.pagination.error` | count | `direction` | Pagination errors by direction | **Code:** `src/app/features/room/RoomTimeline.tsx` #### Sync -| Metric | Type | Attributes | What it tracks | -|--------|------|-----------|----------------| -| `sable.sync.transport` | count | `type` (`sliding`/`classic`) | Sync transport type used | -| `sable.sync.cycle` | count | (various) | Completed sliding sync cycles | -| `sable.sync.error` | count | `errcode` | Sliding sync errors | -| `sable.sync.initial_ms` | distribution | — | Initial sync completion time | -| `sable.sync.processing_ms` | distribution | — | Per-cycle sync processing time | -| `sable.sync.lists_loaded_ms` | distribution | — | Time for room lists to fully load | -| `sable.sync.total_rooms` | gauge | `sync_type` | Total rooms known at list load | -| `sable.sync.active_subscriptions` | gauge | — | Active room subscription count | -| `sable.sync.client_ready_ms` | distribution | `type` | Time from init to client ready | -| `sable.sync.time_to_ready_ms` | distribution | — | Wall-clock time to first sync ready | -| `sable.sync.degraded` | count | `state` | Sync reconnect/error state transitions | +| Metric | Type | Attributes | What it tracks | +| --------------------------------- | ------------ | ---------------------------- | -------------------------------------- | +| `sable.sync.transport` | count | `type` (`sliding`/`classic`) | Sync transport type used | +| `sable.sync.cycle` | count | (various) | Completed sliding sync cycles | +| `sable.sync.error` | count | `errcode` | Sliding sync errors | +| `sable.sync.initial_ms` | distribution | — | Initial sync completion time | +| `sable.sync.processing_ms` | distribution | — | Per-cycle sync processing time | +| `sable.sync.lists_loaded_ms` | distribution | — | Time for room lists to fully load | +| `sable.sync.total_rooms` | gauge | `sync_type` | Total rooms known at list load | +| `sable.sync.active_subscriptions` | gauge | — | Active room subscription count | +| `sable.sync.client_ready_ms` | distribution | `type` | Time from init to client ready | +| `sable.sync.time_to_ready_ms` | distribution | — | Wall-clock time to first sync ready | +| `sable.sync.degraded` | count | `state` | Sync reconnect/error state transitions | **Code:** `src/client/initMatrix.ts`, `src/client/slidingSync.ts`, `src/app/pages/client/ClientRoot.tsx`, `src/app/pages/client/SyncStatus.tsx` #### Media -| Metric | Type | Attributes | What it tracks | -|--------|------|-----------|----------------| +| Metric | Type | Attributes | What it tracks | +| ------------------------------- | ------------ | ---------- | ---------------------------- | | `sable.media.upload_latency_ms` | distribution | `mimetype` | Media upload round-trip time | -| `sable.media.upload_bytes` | distribution | `mimetype` | Upload size distribution | -| `sable.media.upload_error` | count | `reason` | Upload failures by reason | -| `sable.media.blob_cache_size` | gauge | — | Blob URL cache entry count | -| `sable.media.inflight_requests` | gauge | — | Concurrent media requests | +| `sable.media.upload_bytes` | distribution | `mimetype` | Upload size distribution | +| `sable.media.upload_error` | count | `reason` | Upload failures by reason | +| `sable.media.blob_cache_size` | gauge | — | Blob URL cache entry count | +| `sable.media.inflight_requests` | gauge | — | Concurrent media requests | **Code:** `src/app/utils/matrix.ts`, `src/app/pages/client/ClientNonUIFeatures.tsx` #### Background clients & debug telemetry -| Metric | Type | Attributes | What it tracks | -|--------|------|-----------|----------------| -| `sable.background.client_count` | gauge | — | Active background notification clients | -| `sable.errors` | count | `category` | Error-level debug log entries | -| `sable.warnings` | count | `category` | Warning-level debug log entries | +| Metric | Type | Attributes | What it tracks | +| ------------------------------- | ----- | ---------- | -------------------------------------- | +| `sable.background.client_count` | gauge | — | Active background notification clients | +| `sable.errors` | count | `category` | Error-level debug log entries | +| `sable.warnings` | count | `category` | Warning-level debug log entries | **Code:** `src/app/pages/client/BackgroundNotifications.tsx`, `src/app/utils/debugLogger.ts` -### Session Replay *(opt-in, disabled by default)* +### Session Replay _(opt-in, disabled by default)_ When session replay is explicitly enabled by the user, Sentry records UI interactions to help reproduce bugs. **All content is masked at the browser @@ -213,15 +213,15 @@ media are ever visible in a replay**. Sample rates for replay: -| Trigger | Production | Preview / Dev | -|-----------------------|------------|---------------| -| Regular sessions | 10% | 100% | -| Sessions with errors | 100% | 100% | +| Trigger | Production | Preview / Dev | +| -------------------- | ---------- | ------------- | +| Regular sessions | 10% | 100% | +| Sessions with errors | 100% | 100% | **Code:** `src/instrument.ts` — `replayIntegration` call with `maskAllText`, `blockAllMedia`, `maskAllInputs` -### Bug Reports *(manual, opt-in per report)* +### Bug Reports _(manual, opt-in per report)_ When a user submits a bug report via `/bugreport` or the "Bug Report" button: @@ -272,11 +272,11 @@ Regex: `/(access_token|password|token|refresh_token|session_id|sync_token|next_b Matrix IDs are replaced with placeholder tokens before sending: -| Original form | Replaced with | -|-------------------|---------------| -| `@user:server` | `@[USER_ID]` | -| `!room:server` | `![ROOM_ID]` | -| `$event_id` | `$[EVENT_ID]` | +| Original form | Replaced with | +| -------------- | ------------- | +| `@user:server` | `@[USER_ID]` | +| `!room:server` | `![ROOM_ID]` | +| `$event_id` | `$[EVENT_ID]` | **Code:** `src/instrument.ts` — `beforeSend` callback (applied to `event.message` and all `event.exception.values`) @@ -287,11 +287,11 @@ and all `event.exception.values`) Users can adjust Sentry behaviour without restarting the app: -| Setting | Location | `localStorage` key | Default | -|---------|----------|--------------------|---------| -| Disable Sentry entirely | Settings → Developer Tools → Error Tracking | `sable_sentry_enabled` | Enabled | -| Enable session replay | Settings → Developer Tools → Error Tracking | `sable_sentry_replay_enabled` | Disabled (opt-in) | -| Disable breadcrumb categories | Settings → Developer Tools → Error Tracking → Breadcrumb Categories | `sable_sentry_breadcrumb_disabled` | All enabled | +| Setting | Location | `localStorage` key | Default | +| ----------------------------- | ---------------------------------------------------------------------------- | ---------------------------------- | ----------------- | +| Disable Sentry entirely | Settings → General → Diagnostics & Privacy | `sable_sentry_enabled` | Enabled | +| Enable session replay | Settings → General → Diagnostics & Privacy | `sable_sentry_replay_enabled` | Disabled (opt-in) | +| Disable breadcrumb categories | Settings → Developer Tools → Error Tracking (Sentry) → Breadcrumb Categories | `sable_sentry_breadcrumb_disabled` | All enabled | **Rate limiting:** A maximum of 50 error events are forwarded to Sentry per page load (session). Subsequent errors are silently dropped, protecting against quota exhaustion without affecting diff --git a/src/app/components/DefaultErrorPage.tsx b/src/app/components/DefaultErrorPage.tsx index 54ac642e..62042cef 100644 --- a/src/app/components/DefaultErrorPage.tsx +++ b/src/app/components/DefaultErrorPage.tsx @@ -75,7 +75,9 @@ export function ErrorPage({ error, eventId }: ErrorPageProps) { + + + ); +} + export function General({ requestClose }: GeneralProps) { return ( @@ -1078,6 +1181,7 @@ export function General({ requestClose }: GeneralProps) { + diff --git a/src/app/hooks/useCallSignaling.ts b/src/app/hooks/useCallSignaling.ts index cd657e47..1e8a7dfe 100644 --- a/src/app/hooks/useCallSignaling.ts +++ b/src/app/hooks/useCallSignaling.ts @@ -29,6 +29,13 @@ export function useCallSignaling() { const mutedRoomId = useAtomValue(mutedCallRoomIdAtom); const setMutedRoomId = useSetAtom(mutedCallRoomIdAtom); + // Stable refs so volatile values (mutedRoomId, ring callbacks) don't force + // the listener registration effect to re-run — which would cause the + // SessionEnded and RoomState.events listeners to accumulate when muting + // or when call state changes rapidly during a sync retry cycle. + const mutedRoomIdRef = useRef(mutedRoomId); + mutedRoomIdRef.current = mutedRoomId; + useEffect(() => { const inc = new Audio(RingtoneSound); inc.loop = true; @@ -72,6 +79,16 @@ export function useCallSignaling() { [setIncomingCall] ); + // Must be declared after the callbacks above so the initial useRef(value) call + // sees their current identity. Updated on every render so the effect closure + // always calls the latest version without needing them in the dep array. + const playRingingRef = useRef(playRinging); + playRingingRef.current = playRinging; + const stopRingingRef = useRef(stopRinging); + stopRingingRef.current = stopRinging; + const playOutgoingRingingRef = useRef(playOutgoingRinging); + playOutgoingRingingRef.current = playOutgoingRinging; + useEffect(() => { if (!mx || !mx.matrixRTC) return undefined; @@ -81,7 +98,7 @@ export function useCallSignaling() { const signal = Array.from(mDirects).reduce( (acc, roomId) => { - if (acc.incoming || mutedRoomId === roomId) return acc; + if (acc.incoming || mutedRoomIdRef.current === roomId) return acc; const room = mx.getRoom(roomId); if (!room) return acc; @@ -141,11 +158,11 @@ export function useCallSignaling() { ); if (signal.incoming) { - playRinging(signal.incoming); + playRingingRef.current(signal.incoming); } else if (signal.outgoing) { - playOutgoingRinging(signal.outgoing); + playOutgoingRingingRef.current(signal.outgoing); } else { - stopRinging(); + stopRingingRef.current(); if (!signal.outgoing) outgoingStartRef.current = null; } }; @@ -155,7 +172,7 @@ export function useCallSignaling() { const handleUpdate = () => checkDMsForActiveCalls(); const handleSessionEnded = (roomId: string) => { - if (mutedRoomId === roomId) setMutedRoomId(null); + if (mutedRoomIdRef.current === roomId) setMutedRoomId(null); callPhaseRef.current[roomId] = 'IDLE'; checkDMsForActiveCalls(); }; @@ -171,9 +188,9 @@ export function useCallSignaling() { mx.matrixRTC.off(MatrixRTCSessionManagerEvents.SessionStarted, handleUpdate); mx.matrixRTC.off(MatrixRTCSessionManagerEvents.SessionEnded, handleSessionEnded); mx.off(RoomStateEvent.Events, handleUpdate); - stopRinging(); + stopRingingRef.current(); }; - }, [mx, mDirects, playRinging, stopRinging, mutedRoomId, setMutedRoomId, playOutgoingRinging]); + }, [mx, mDirects, setMutedRoomId]); // stable: volatile deps accessed via refs above return null; } diff --git a/src/app/pages/Router.tsx b/src/app/pages/Router.tsx index 71b72157..d81890da 100644 --- a/src/app/pages/Router.tsx +++ b/src/app/pages/Router.tsx @@ -164,59 +164,59 @@ export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize) beforeCapture={(scope) => scope.setTag('section', 'client')} > - {/* HandleNotificationClick must live outside ClientRoot's loading gate so + {/* HandleNotificationClick must live outside ClientRoot's loading gate so SW notification-click postMessages are never dropped during client reloads (e.g., account switches). It only needs navigate + Jotai atoms. */} - - - - - - - - - - - - } - > - - - - - - - - - - - - - {/* Screen reader live region — populated by announce() in utils/announce.ts */} -
- - - - - - - - + + + + + + + + + + + + } + > + + + + + + + + + + + + + {/* Screen reader live region — populated by announce() in utils/announce.ts */} +
+ + + + + + + + } > diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx index fab2261e..a5e78e60 100644 --- a/src/app/pages/client/ClientNonUIFeatures.tsx +++ b/src/app/pages/client/ClientNonUIFeatures.tsx @@ -676,8 +676,8 @@ function SentryRoomContextFeature() { useEffect(() => { if (!roomId) { Sentry.setContext('room', null); - Sentry.setTag('room_type', ''); - Sentry.setTag('room_encrypted', ''); + Sentry.setTag('room_type', 'none'); + Sentry.setTag('room_encrypted', 'none'); return; } const room = mx.getRoom(roomId); @@ -688,11 +688,12 @@ function SentryRoomContextFeature() { const memberCount = room.getJoinedMemberCount(); // Bucket member count so we can correlate issues with room scale // without leaking precise membership numbers of private rooms. - const memberCountRange = - memberCount <= 2 ? '1-2' : - memberCount <= 10 ? '3-10' : - memberCount <= 50 ? '11-50' : - memberCount <= 200 ? '51-200' : '200+'; + let memberCountRange: string; + if (memberCount <= 2) memberCountRange = '1-2'; + else if (memberCount <= 10) memberCountRange = '3-10'; + else if (memberCount <= 50) memberCountRange = '11-50'; + else if (memberCount <= 200) memberCountRange = '51-200'; + else memberCountRange = '200+'; Sentry.setContext('room', { type: isDm ? 'dm' : 'group', diff --git a/src/app/pages/client/sidebar/DirectDMsList.tsx b/src/app/pages/client/sidebar/DirectDMsList.tsx index 7a6718b5..5823ea45 100644 --- a/src/app/pages/client/sidebar/DirectDMsList.tsx +++ b/src/app/pages/client/sidebar/DirectDMsList.tsx @@ -1,13 +1,10 @@ -import { useMemo, useState, useCallback, useRef, useEffect } from 'react'; +import { useMemo, useRef, useEffect } from 'react'; import * as Sentry from '@sentry/react'; import { useNavigate } from 'react-router-dom'; import { Avatar, Text, Box, toRem } from 'folds'; import { useAtomValue } from 'jotai'; -import { Room, SyncState } from '$types/matrix-sdk'; -import { useDirects } from '$state/hooks/roomList'; +import { Room } from '$types/matrix-sdk'; import { useMatrixClient } from '$hooks/useMatrixClient'; -import { mDirectAtom } from '$state/mDirectList'; -import { allRoomsAtom } from '$state/room-list/roomList'; import { roomToUnreadAtom } from '$state/room/roomToUnread'; import { getDirectRoomPath } from '$pages/pathUtils'; import { @@ -22,14 +19,12 @@ import { UserAvatar } from '$components/user-avatar'; import { getDirectRoomAvatarUrl } from '$utils/room'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { nameInitials } from '$utils/common'; -import { factoryRoomIdByActivity } from '$utils/sort'; import { getCanonicalAliasOrRoomId, mxcUrlToHttp } from '$utils/matrix'; import { useSelectedRoom } from '$hooks/router/useSelectedRoom'; import { useGroupDMMembers } from '$hooks/useGroupDMMembers'; -import { useSyncState } from '$hooks/useSyncState'; +import { useSidebarDirectRoomIds } from './useSidebarDirectRoomIds'; import * as css from './DirectDMsList.css'; -const MAX_DM_AVATARS = 3; const MAX_GROUP_MEMBERS = 3; type DMItemProps = { @@ -164,62 +159,29 @@ function DMItem({ room, selected }: DMItemProps) { export function DirectDMsList() { const mx = useMatrixClient(); - const mDirects = useAtomValue(mDirectAtom); - const directs = useDirects(mx, allRoomsAtom, mDirects); - const roomToUnread = useAtomValue(roomToUnreadAtom); const selectedRoomId = useSelectedRoom(); + const sidebarRoomIds = useSidebarDirectRoomIds(); - // Track sync state to wait for initial sync completion - const [syncReady, setSyncReady] = useState(false); const mountTimeRef = useRef(performance.now()); const firstReadyRef = useRef(false); - useSyncState( - mx, - useCallback((state, prevState) => { - // Consider ready after initial sync reaches Syncing state - // This ensures m.direct and unread counts are populated - if (state === SyncState.Syncing && prevState !== SyncState.Syncing) { - setSyncReady(true); - } - // Also set ready if we're already syncing (e.g., after a refresh while still online) - if (state === SyncState.Syncing || state === SyncState.Catchup) { - setSyncReady(true); - } - }, []) + const recentDMs = useMemo( + () => + sidebarRoomIds + .map((roomId) => mx.getRoom(roomId)) + .filter((room): room is Room => room !== null), + [sidebarRoomIds, mx] ); useEffect(() => { - if (syncReady && !firstReadyRef.current) { + if (recentDMs.length > 0 && !firstReadyRef.current) { firstReadyRef.current = true; Sentry.metrics.distribution( 'sable.roomlist.time_to_ready_ms', performance.now() - mountTimeRef.current ); } - }, [syncReady]); - - // Get up to MAX_DM_AVATARS recent DMs that have unread messages - const recentDMs = useMemo(() => { - // Don't show DMs until initial sync completes - if (!syncReady) { - return []; - } - - // Filter to only DMs with unread messages - const withUnread = directs.filter((roomId) => { - const unread = roomToUnread.get(roomId); - return unread && (unread.total > 0 || unread.highlight > 0); - }); - - // Sort by activity - const sorted = withUnread.sort(factoryRoomIdByActivity(mx)); - - return sorted - .slice(0, MAX_DM_AVATARS) - .map((roomId) => mx.getRoom(roomId)) - .filter((room): room is Room => room !== null); - }, [directs, mx, roomToUnread, syncReady]); + }, [recentDMs]); if (recentDMs.length === 0) { return null; diff --git a/src/app/pages/client/sidebar/DirectTab.tsx b/src/app/pages/client/sidebar/DirectTab.tsx index dd2a7d6e..3503c7f9 100644 --- a/src/app/pages/client/sidebar/DirectTab.tsx +++ b/src/app/pages/client/sidebar/DirectTab.tsx @@ -1,4 +1,4 @@ -import { MouseEventHandler, forwardRef, useState } from 'react'; +import { MouseEventHandler, forwardRef, useMemo, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { Box, Icon, Icons, Menu, MenuItem, PopOut, RectCords, Text, config, toRem } from 'folds'; import FocusTrap from 'focus-trap-react'; @@ -25,6 +25,7 @@ import { stopPropagation } from '$utils/keyboard'; import { settingsAtom } from '$state/settings'; import { useSetting } from '$state/hooks/settings'; import { useDirectRooms } from '$pages/client/direct/useDirectRooms'; +import { useSidebarDirectRoomIds } from './useSidebarDirectRoomIds'; type DirectMenuProps = { requestClose: () => void; @@ -68,7 +69,14 @@ export function DirectTab() { const mDirects = useAtomValue(mDirectAtom); const directs = useDirects(mx, allRoomsAtom, mDirects); - const directUnread = useRoomsUnread(directs, roomToUnreadAtom); + const sidebarRoomIds = useSidebarDirectRoomIds(); + // Only count unread for DMs not already shown as individual avatars in the + // sidebar — prevents double-badging (issue #235). + const overflowDirects = useMemo(() => { + const sidebarSet = new Set(sidebarRoomIds); + return directs.filter((id) => !sidebarSet.has(id)); + }, [directs, sidebarRoomIds]); + const directUnread = useRoomsUnread(overflowDirects, roomToUnreadAtom); const [menuAnchor, setMenuAnchor] = useState(); const directSelected = useDirectSelected(); diff --git a/src/app/pages/client/sidebar/useSidebarDirectRoomIds.ts b/src/app/pages/client/sidebar/useSidebarDirectRoomIds.ts new file mode 100644 index 00000000..8c62d3af --- /dev/null +++ b/src/app/pages/client/sidebar/useSidebarDirectRoomIds.ts @@ -0,0 +1,54 @@ +import { useMemo, useState, useCallback } from 'react'; +import { useAtomValue } from 'jotai'; +import { SyncState } from '$types/matrix-sdk'; +import { useDirects } from '$state/hooks/roomList'; +import { useMatrixClient } from '$hooks/useMatrixClient'; +import { mDirectAtom } from '$state/mDirectList'; +import { allRoomsAtom } from '$state/room-list/roomList'; +import { roomToUnreadAtom } from '$state/room/roomToUnread'; +import { factoryRoomIdByActivity } from '$utils/sort'; +import { useSyncState } from '$hooks/useSyncState'; + +/** Maximum number of individual DM avatars shown in the sidebar. */ +export const MAX_SIDEBAR_DMS = 3; + +/** + * Returns the room IDs of DMs currently displayed as individual avatars in the + * sidebar `DirectDMsList`. These are the first `MAX_SIDEBAR_DMS` unread DMs + * sorted by recent activity, available only after initial sync completes. + * + * Used by `DirectDMsList` to decide which rooms to render, and by `DirectTab` + * to exclude those rooms from its own badge count (prevents double-badging). + */ +export const useSidebarDirectRoomIds = (): string[] => { + const mx = useMatrixClient(); + const mDirects = useAtomValue(mDirectAtom); + const directs = useDirects(mx, allRoomsAtom, mDirects); + const roomToUnread = useAtomValue(roomToUnreadAtom); + + const [syncReady, setSyncReady] = useState(false); + + useSyncState( + mx, + useCallback((state, prevState) => { + if (state === SyncState.Syncing && prevState !== SyncState.Syncing) { + setSyncReady(true); + } + if (state === SyncState.Syncing || state === SyncState.Catchup) { + setSyncReady(true); + } + }, []) + ); + + return useMemo(() => { + if (!syncReady) return []; + + const withUnread = directs.filter((roomId) => { + const unread = roomToUnread.get(roomId); + return unread && (unread.total > 0 || unread.highlight > 0); + }); + + const sorted = withUnread.sort(factoryRoomIdByActivity(mx)); + return sorted.slice(0, MAX_SIDEBAR_DMS); + }, [directs, mx, roomToUnread, syncReady]); +}; diff --git a/src/app/plugins/call/CallEmbed.ts b/src/app/plugins/call/CallEmbed.ts index 570b66f7..960f21ce 100644 --- a/src/app/plugins/call/CallEmbed.ts +++ b/src/app/plugins/call/CallEmbed.ts @@ -218,11 +218,24 @@ export class CallEmbed { this.readUpToMap[room.roomId] = roomEvent.getId()!; }); - // Attach listeners for feeding events - the underlying widget classes handle permissions for us - this.mx.on(ClientEvent.Event, this.onEvent.bind(this)); - this.mx.on(MatrixEventEvent.Decrypted, this.onEventDecrypted.bind(this)); - this.mx.on(RoomStateEvent.Events, this.onStateUpdate.bind(this)); - this.mx.on(ClientEvent.ToDeviceEvent, this.onToDeviceEvent.bind(this)); + // Attach listeners for feeding events - the underlying widget classes handle permissions for us. + // Bind once and store via disposables so the same function reference is used for removal. + // Using .bind(this) at call-site would create a new function every time, making .off() a no-op + // and causing MaxListeners warnings when the embed is recreated during sync retries. + const boundOnEvent = this.onEvent.bind(this); + const boundOnEventDecrypted = this.onEventDecrypted.bind(this); + const boundOnStateUpdate = this.onStateUpdate.bind(this); + const boundOnToDeviceEvent = this.onToDeviceEvent.bind(this); + this.mx.on(ClientEvent.Event, boundOnEvent); + this.mx.on(MatrixEventEvent.Decrypted, boundOnEventDecrypted); + this.mx.on(RoomStateEvent.Events, boundOnStateUpdate); + this.mx.on(ClientEvent.ToDeviceEvent, boundOnToDeviceEvent); + this.disposables.push(() => { + this.mx.off(ClientEvent.Event, boundOnEvent); + this.mx.off(MatrixEventEvent.Decrypted, boundOnEventDecrypted); + this.mx.off(RoomStateEvent.Events, boundOnStateUpdate); + this.mx.off(ClientEvent.ToDeviceEvent, boundOnToDeviceEvent); + }); } /** @@ -239,11 +252,7 @@ export class CallEmbed { this.container.removeChild(this.iframe); this.control.dispose(); - this.mx.off(ClientEvent.Event, this.onEvent.bind(this)); - this.mx.off(MatrixEventEvent.Decrypted, this.onEventDecrypted.bind(this)); - this.mx.off(RoomStateEvent.Events, this.onStateUpdate.bind(this)); - this.mx.off(ClientEvent.ToDeviceEvent, this.onToDeviceEvent.bind(this)); - + // Listener removal is handled by the disposables pushed in start(). // Clear internal state this.readUpToMap = {}; this.eventsToFeed = new WeakSet(); diff --git a/src/app/utils/debugLogger.ts b/src/app/utils/debugLogger.ts index c00db022..1e1c7e74 100644 --- a/src/app/utils/debugLogger.ts +++ b/src/app/utils/debugLogger.ts @@ -162,24 +162,25 @@ class DebugLoggerService { const sentryLevel: Sentry.SeverityLevel = sentryLevelMap[entry.level] ?? 'error'; // Add breadcrumb for all logs (helps with debugging in Sentry), unless category is disabled - if (!this.disabledBreadcrumbCategories.has(entry.category)) Sentry.addBreadcrumb({ - category: `${entry.category}.${entry.namespace}`, - message: entry.message, - level: sentryLevel, - data: entry.data ? { data: entry.data } : undefined, - timestamp: entry.timestamp / 1000, // Sentry expects seconds - }); + if (!this.disabledBreadcrumbCategories.has(entry.category)) + Sentry.addBreadcrumb({ + category: `${entry.category}.${entry.namespace}`, + message: entry.message, + level: sentryLevel, + data: entry.data ? { data: entry.data } : undefined, + timestamp: entry.timestamp / 1000, // Sentry expects seconds + }); // Send as structured log to the Sentry Logs product (requires enableLogs: true) const logMsg = `[${entry.category}:${entry.namespace}] ${entry.message}`; // Flatten primitive values from entry.data so they become searchable attributes in Sentry Logs const logDataAttrs: Record = {}; if (entry.data && typeof entry.data === 'object' && !(entry.data instanceof Error)) { - for (const [k, v] of Object.entries(entry.data)) { + Object.entries(entry.data).forEach(([k, v]) => { if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') { logDataAttrs[k] = v; } - } + }); } const logAttrs = { category: entry.category, namespace: entry.namespace, ...logDataAttrs }; if (entry.level === 'debug') Sentry.logger.debug(logMsg, logAttrs); diff --git a/src/app/utils/matrix.ts b/src/app/utils/matrix.ts index abc15597..f04f71d9 100644 --- a/src/app/utils/matrix.ts +++ b/src/app/utils/matrix.ts @@ -18,8 +18,8 @@ import to from 'await-to-js'; import { IImageInfo, IThumbnailContent, IVideoInfo } from '$types/matrix/common'; import { AccountDataEvent } from '$types/matrix/accountData'; import { Membership, MessageEvent, StateEvent } from '$types/matrix/room'; -import { getEventReactions, getReactionContent, getStateEvent } from './room'; import * as Sentry from '@sentry/react'; +import { getEventReactions, getReactionContent, getStateEvent } from './room'; const DOMAIN_REGEX = /\b(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}\b/; @@ -177,9 +177,13 @@ export const uploadContent = async ( const mxc = data.content_uri; if (mxc) { const mediaType = file.type.split('/')[0] || 'unknown'; - Sentry.metrics.distribution('sable.media.upload_latency_ms', performance.now() - uploadStart, { - attributes: { type: mediaType }, - }); + Sentry.metrics.distribution( + 'sable.media.upload_latency_ms', + performance.now() - uploadStart, + { + attributes: { type: mediaType }, + } + ); Sentry.metrics.distribution('sable.media.upload_bytes', file.size, { attributes: { type: mediaType }, }); diff --git a/src/instrument.ts b/src/instrument.ts index 9efec360..29e599de 100644 --- a/src/instrument.ts +++ b/src/instrument.ts @@ -27,6 +27,55 @@ const SESSION_ERROR_LIMIT = 50; const sentryEnabled = localStorage.getItem('sable_sentry_enabled') !== 'false'; const replayEnabled = localStorage.getItem('sable_sentry_replay_enabled') === 'true'; +/** + * Scrub Matrix-specific identifiers from URLs that appear in Sentry spans, breadcrumbs, + * transaction names, and page URLs. Covers both Matrix API paths and client-side app routes. + * Room IDs, user IDs, event IDs, media paths, and deep-link parameters are replaced with + * safe placeholders so no PII leaks into Sentry. + */ +function scrubMatrixUrl(url: string): string { + return ( + url + // ── Matrix Client-Server API paths ────────────────────────────────────────────── + // /rooms/!roomId:server/... + .replace(/\/rooms\/![^/?#\s]*/g, '/rooms/![ROOM_ID]') + // /event/$eventId and /relations/$eventId + .replace(/\/event\/(?:\$|%24)[^/?#\s]*/g, '/event/$[EVENT_ID]') + .replace(/\/relations\/(?:\$|%24)[^/?#\s]*/g, '/relations/$[EVENT_ID]') + // /profile/@user:server or /profile/%40user%3Aserver + .replace(/\/profile\/(?:%40|@)[^/?#\s]*/gi, '/profile/[USER_ID]') + // /user/@user:server/... and /presence/@user:server/status + .replace(/\/(user|presence)\/(?:%40|@)[^/?#\s]*/gi, '/$1/[USER_ID]') + // /room_keys/keys/{version}/{roomId}/{sessionId} + .replace(/\/room_keys\/keys\/[^/?#\s]*/gi, '/room_keys/keys/[REDACTED]') + // /sendToDevice/{eventType}/{txnId} + .replace(/\/sendToDevice\/([^/?#\s]+)\/[^/?#\s]+/gi, '/sendToDevice/$1/[TXN_ID]') + // Media – MSC3916 (/media/thumbnail|download/{server}/{mediaId}) and legacy (v1/v3) + .replace( + /(\/media\/(?:thumbnail|download)\/)(?:[^/?#\s]+)\/(?:[^/?#\s]+)/gi, + '$1[SERVER]/[MEDIA_ID]' + ) + .replace( + /(\/media\/v\d+\/(?:thumbnail|download)\/)(?:[^/?#\s]+)\/(?:[^/?#\s]+)/gi, + '$1[SERVER]/[MEDIA_ID]' + ) + // ── App route path segments ───────────────────────────────────────────────────── + // Bare Matrix room/space IDs in URL segments: /!roomId:server/ + .replace(/\/![^/?#\s:]+:[^/?#\s]*/g, '/![ROOM_ID]') + // Bare Matrix user IDs in URL segments: /@user:server/ + .replace(/\/@[^/?#\s:]+:[^/?#\s]*/g, '/@[USER_ID]') + // ── Deep-link push notification URLs (percent-encoded) ───────────────────────── + // URL-encoded user IDs: /%40user%3Aserver (%40 = @) + .replace(/\/%40[^/?#\s]*/gi, '/[USER_ID]') + // URL-encoded room IDs: /%21room%3Aserver (%21 = !) + .replace(/\/%21[^/?#\s]*/gi, '/![ROOM_ID]') + // ── Preview URL endpoint ──────────────────────────────────────────────────────── + // The ?url= query parameter on preview_url contains the full external URL being + // previewed — strip the entire query string so browsing habits cannot be inferred. + .replace(/(\/preview_url)\?[^#\s]*/gi, '$1') + ); +} + // Only initialize if DSN is provided and user hasn't opted out if (dsn && sentryEnabled) { Sentry.init({ @@ -67,7 +116,8 @@ if (dsn && sentryEnabled) { tracesSampleRate: environment === 'development' || environment === 'preview' ? 1.0 : 0.1, // Browser profiling — profiles every sampled session (requires Document-Policy: js-profiling response header) - profileSessionSampleRate: environment === 'development' || environment === 'preview' ? 1.0 : 0.1, + profileSessionSampleRate: + environment === 'development' || environment === 'preview' ? 1.0 : 0.1, // Control which URLs get distributed tracing headers tracePropagationTargets: [ @@ -108,27 +158,84 @@ if (dsn && sentryEnabled) { // Rate limiting: cap error events per page-load session to avoid quota exhaustion. // Separate counters for errors and transactions so perf traces do not drain the error budget. beforeSendTransaction(event) { + // Scrub Matrix identifiers from the transaction name (the matched route or page URL). + // React Router normally parameterises routes (e.g. /home/:roomIdOrAlias/) but falls + // back to the raw URL when matching fails, so we scrub defensively here. + if (event.transaction) { + // eslint-disable-next-line no-param-reassign + event.transaction = scrubMatrixUrl(event.transaction); + } + + // Scrub Matrix identifiers from HTTP span descriptions and data URLs + if (event.spans) { + // eslint-disable-next-line no-param-reassign + event.spans = event.spans.map((span) => { + const newDesc = span.description ? scrubMatrixUrl(span.description) : span.description; + const spanData = span.data as Record | undefined; + const spanHttpUrl = spanData?.['http.url']; + const rawHttpUrl = typeof spanHttpUrl === 'string' ? spanHttpUrl : undefined; + const newHttpUrl = rawHttpUrl ? scrubMatrixUrl(rawHttpUrl) : undefined; + + const descChanged = newDesc !== span.description; + const urlChanged = newHttpUrl !== undefined && newHttpUrl !== rawHttpUrl; + + if (!descChanged && !urlChanged) return span; + return { + ...span, + ...(descChanged ? { description: newDesc } : {}), + ...(urlChanged ? { data: { ...spanData, 'http.url': newHttpUrl } } : {}), + }; + }); + } return event; }, - // Sanitize sensitive data from all breadcrumb messages before sending to Sentry + // Sanitize sensitive data from all breadcrumb messages and HTTP data URLs before sending to Sentry beforeBreadcrumb(breadcrumb) { - if (!breadcrumb.message) return breadcrumb; - // Always apply redaction — both token values and Matrix entity IDs. + // Scrub Matrix paths from HTTP breadcrumb data.url (captures full request URLs) + const bData = breadcrumb.data as Record | undefined; + const rawUrl = typeof bData?.url === 'string' ? bData.url : undefined; + const scrubbedUrl = rawUrl ? scrubMatrixUrl(rawUrl) : undefined; + const urlChanged = scrubbedUrl !== undefined && scrubbedUrl !== rawUrl; + + // Scrub Matrix paths from navigation breadcrumb data.from / data.to (page URLs that + // may contain room IDs or user IDs as path segments in the app's client-side routes) + const rawFrom = typeof bData?.from === 'string' ? bData.from : undefined; + const rawTo = typeof bData?.to === 'string' ? bData.to : undefined; + const scrubbedFrom = rawFrom ? scrubMatrixUrl(rawFrom) : undefined; + const scrubbedTo = rawTo ? scrubMatrixUrl(rawTo) : undefined; + const fromChanged = scrubbedFrom !== undefined && scrubbedFrom !== rawFrom; + const toChanged = scrubbedTo !== undefined && scrubbedTo !== rawTo; + + // Scrub message text — token values and Matrix entity IDs // Do NOT use single-character patterns like '@', '!', '$' as they are far too broad. - const redacted = breadcrumb.message - // Redact token key=value pairs (e.g. access_token=abc123) - .replace( - /(access_token|password|refresh_token|device_id|session_id|sync_token|next_batch)([=:\s]+)([^\s&"']+)/gi, - '$1$2[REDACTED]' - ) - // Redact full Matrix user IDs: @localpart:server.tld - .replace(/@[^\s:@]+:[^\s,'"(){}\[\]]+/g, '@[USER_ID]') - // Redact full Matrix room IDs: !opaque:server.tld - .replace(/![^\s:]+:[^\s,'"(){}\[\]]+/g, '![ROOM_ID]') - // Redact Matrix event IDs: $base64Url (at least 10 chars to avoid false positives) - .replace(/\$[A-Za-z0-9\-_+/]{10,}/g, '$[EVENT_ID]'); - return redacted === breadcrumb.message ? breadcrumb : { ...breadcrumb, message: redacted }; + const message = breadcrumb.message + ? breadcrumb.message + .replace( + /(access_token|password|refresh_token|device_id|session_id|sync_token|next_batch)([=:\s]+)([^\s&"']+)/gi, + '$1$2[REDACTED]' + ) + .replace(/@[^\s:@]+:[^\s,'"(){}[\]]+/g, '@[USER_ID]') + .replace(/![^\s:]+:[^\s,'"(){}[\]]+/g, '![ROOM_ID]') + .replace(/\$[A-Za-z0-9_+/-]{10,}/g, '$[EVENT_ID]') + : breadcrumb.message; + const messageChanged = message !== breadcrumb.message; + + if (!messageChanged && !urlChanged && !fromChanged && !toChanged) return breadcrumb; + return { + ...breadcrumb, + ...(messageChanged ? { message } : {}), + ...(urlChanged || fromChanged || toChanged + ? { + data: { + ...bData, + ...(urlChanged ? { url: scrubbedUrl } : {}), + ...(fromChanged ? { from: scrubbedFrom } : {}), + ...(toChanged ? { to: scrubbedTo } : {}), + }, + } + : {}), + }; }, beforeSend(event, hint) { @@ -191,6 +298,11 @@ if (dsn && sentryEnabled) { exception.value = exception.value.replace(/![^:]+:[^\s]+/g, '![ROOM_ID]'); // eslint-disable-next-line no-param-reassign exception.value = exception.value.replace(/\$[^:\s]+/g, '$[EVENT_ID]'); + // Scrub Matrix URL patterns embedded in error message strings + // (e.g. MatrixError: "Got error 403 (https://.../preview_url?url=https://...)" + // or paths containing room/user/event IDs) + // eslint-disable-next-line no-param-reassign + exception.value = scrubMatrixUrl(exception.value); } }); } @@ -198,12 +310,21 @@ if (dsn && sentryEnabled) { // Scrub request data if (event.request?.url) { // eslint-disable-next-line no-param-reassign - event.request.url = event.request.url.replace( - /(access_token|password|token)([=:]\s*)([^\s&]+)/gi, - '$1$2[REDACTED]' + event.request.url = scrubMatrixUrl( + event.request.url.replace( + /(access_token|password|token)([=:]\s*)([^\s&]+)/gi, + '$1$2[REDACTED]' + ) ); } + // Scrub the transaction name on error events (set when the error occurred during a + // page-load or navigation transaction — raw URL leaks here when route matching fails) + if (event.transaction) { + // eslint-disable-next-line no-param-reassign + event.transaction = scrubMatrixUrl(event.transaction); + } + if (event.request?.headers) { const headers = event.request.headers as Record; if (headers.Authorization) { From d57ebdd4a3b8ac0e0d0749cc134a9ad578a5787d Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Sun, 15 Mar 2026 23:40:58 -0400 Subject: [PATCH 045/146] feat(sentry): detailed timeline and scroll instrumentation, sync batch monitoring, and anomaly detection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RoomTimeline.tsx: - atBottom transition breadcrumbs (ui.scroll) with rapid-flip detection: true→false within 200ms captures warning (IntersectionObserver false-positive) - Virtual paginator window shift breadcrumbs (ui.timeline) - scroll-to-bottom trigger breadcrumb; captures warning when fired while user is scrolled up without a pending reset - eventsLength batch monitoring: breadcrumb on every batch with delta, batchSize label (single/small/medium/large), rangeGap, atBottom - Large batch warning (>50 events, liveTimelineLinked=true) for sliding sync adaptive load detection slidingSync.ts / initMatrix.ts: - sync.sliding breadcrumb in onFirstRoomData with latency + event count - sable.sync.room_sub_event_count distribution metric Message interaction metrics (IncomingCallModal, MessageDelete, MessageForward, MessageReport, RoomTimeline reaction handler): - sable.call.answered/declined, sable.message.delete/forward/report/reaction.* --- docs/{PRIVACY_POLICY.md => PRIVACY.md} | 0 src/app/components/IncomingCallModal.tsx | 18 ++ .../message/modals/MessageDelete.tsx | 14 +- .../message/modals/MessageForward.tsx | 29 ++- .../message/modals/MessageReport.tsx | 19 +- src/app/features/room/RoomTimeline.tsx | 194 +++++++++++++++++- src/app/features/settings/general/General.tsx | 2 +- src/app/hooks/useCallEmbed.ts | 28 ++- src/app/hooks/useCallSignaling.ts | 43 ++++ src/app/pages/client/ClientRoot.tsx | 6 +- src/client/initMatrix.ts | 64 ++++++ src/client/slidingSync.ts | 62 +++++- src/instrument.ts | 167 ++++++++------- 13 files changed, 555 insertions(+), 91 deletions(-) rename docs/{PRIVACY_POLICY.md => PRIVACY.md} (100%) diff --git a/docs/PRIVACY_POLICY.md b/docs/PRIVACY.md similarity index 100% rename from docs/PRIVACY_POLICY.md rename to docs/PRIVACY.md diff --git a/src/app/components/IncomingCallModal.tsx b/src/app/components/IncomingCallModal.tsx index da17db4f..3ab4e845 100644 --- a/src/app/components/IncomingCallModal.tsx +++ b/src/app/components/IncomingCallModal.tsx @@ -19,14 +19,18 @@ import { getRoomAvatarUrl } from '$utils/room'; import { useRoomNavigate } from '$hooks/useRoomNavigate'; import FocusTrap from 'focus-trap-react'; import { stopPropagation } from '$utils/keyboard'; +import * as Sentry from '@sentry/react'; import { useAtom, useSetAtom } from 'jotai'; import { autoJoinCallIntentAtom, incomingCallRoomIdAtom, mutedCallRoomIdAtom, } from '$state/callEmbed'; +import { createDebugLogger } from '$utils/debugLogger'; import { RoomAvatar } from './room-avatar'; +const debugLog = createDebugLogger('IncomingCall'); + type IncomingCallInternalProps = { room: any; onClose: () => void; @@ -41,6 +45,13 @@ export function IncomingCallInternal({ room, onClose }: IncomingCallInternalProp const setMutedRoomId = useSetAtom(mutedCallRoomIdAtom); const handleAnswer = () => { + debugLog.info('call', 'Incoming call answered', { roomId: room.roomId }); + Sentry.addBreadcrumb({ + category: 'call.signal', + message: 'Incoming call answered', + data: { roomId: room.roomId }, + }); + Sentry.metrics.count('sable.call.answered', 1); setMutedRoomId(room.roomId); setAutoJoinIntent(room.roomId); onClose(); @@ -48,6 +59,13 @@ export function IncomingCallInternal({ room, onClose }: IncomingCallInternalProp }; const handleDecline = async () => { + debugLog.info('call', 'Incoming call declined', { roomId: room.roomId }); + Sentry.addBreadcrumb({ + category: 'call.signal', + message: 'Incoming call declined', + data: { roomId: room.roomId }, + }); + Sentry.metrics.count('sable.call.declined', 1); setMutedRoomId(room.roomId); onClose(); }; diff --git a/src/app/components/message/modals/MessageDelete.tsx b/src/app/components/message/modals/MessageDelete.tsx index 6637c97b..66689510 100644 --- a/src/app/components/message/modals/MessageDelete.tsx +++ b/src/app/components/message/modals/MessageDelete.tsx @@ -20,6 +20,10 @@ import { useMatrixClient } from '$hooks/useMatrixClient'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import { modalAtom, ModalType } from '$state/modal'; import * as css from '$features/room/message/styles.css'; +import { createDebugLogger } from '$utils/debugLogger'; +import * as Sentry from '@sentry/react'; + +const debugLog = createDebugLogger('MessageDelete'); export function MessageDeleteItem({ room, mEvent }: { room: Room; mEvent: MatrixEvent }) { const setModal = useSetAtom(modalAtom); @@ -67,9 +71,15 @@ export function MessageDeleteInternal({ room, mEvent, onClose }: MessageDeleteIn useEffect(() => { if (deleteState.status === AsyncStatus.Success) { + debugLog.info('ui', 'Message deleted successfully', { roomId: room.roomId }); + Sentry.metrics.count('sable.message.delete.success', 1); onClose(); } - }, [deleteState.status, onClose]); + if (deleteState.status === AsyncStatus.Error) { + debugLog.error('ui', 'Message delete failed', { roomId: room.roomId }); + Sentry.metrics.count('sable.message.delete.error', 1); + } + }, [deleteState.status, room.roomId, onClose]); const handleSubmit: FormEventHandler = (evt) => { evt.preventDefault(); @@ -85,6 +95,8 @@ export function MessageDeleteInternal({ room, mEvent, onClose }: MessageDeleteIn const reasonInput = target?.reasonInput as HTMLInputElement | undefined; const reason = reasonInput && reasonInput.value.trim(); + debugLog.info('ui', 'Deleting message', { eventId, hasReason: !!reason }); + Sentry.metrics.count('sable.message.delete.attempt', 1); deleteMessage(eventId, reason); }; diff --git a/src/app/components/message/modals/MessageForward.tsx b/src/app/components/message/modals/MessageForward.tsx index dbce8b29..219e4119 100644 --- a/src/app/components/message/modals/MessageForward.tsx +++ b/src/app/components/message/modals/MessageForward.tsx @@ -26,6 +26,10 @@ import * as css from '$features/room/message/styles.css'; import { sanitizeCustomHtml } from '$utils/sanitize'; import { getStateEvents } from '$utils/room'; import { StateEvent } from '$types/matrix/room'; +import { createDebugLogger } from '$utils/debugLogger'; +import * as Sentry from '@sentry/react'; + +const debugLog = createDebugLogger('MessageForward'); // Message forwarding component export const MessageForwardItem = as<'button', MessageForwardItemProps>( @@ -263,9 +267,30 @@ export function MessageForwardInternal({ }; } + const msgtype = String(originalContent.msgtype ?? 'unknown'); + debugLog.info('ui', 'Forwarding message', { + sourceRoomId: room.roomId, + targetRoomId: targetRoom.roomId, + msgtype, + isPrivate, + }); + Sentry.metrics.count('sable.message.forward.attempt', 1, { attributes: { msgtype } }); mx.sendEvent(targetRoom.roomId, null, eventType, content as unknown as SendEventContent) - .then(() => setIsForwardSuccess(true)) - .catch(() => { + .then(() => { + debugLog.info('ui', 'Message forwarded successfully', { + sourceRoomId: room.roomId, + targetRoomId: targetRoom.roomId, + }); + Sentry.metrics.count('sable.message.forward.success', 1); + setIsForwardSuccess(true); + }) + .catch((err: unknown) => { + debugLog.error('ui', 'Message forward failed', { + sourceRoomId: room.roomId, + targetRoomId: targetRoom.roomId, + error: err instanceof Error ? err.message : String(err), + }); + Sentry.metrics.count('sable.message.forward.error', 1); setIsForwarding(false); setIsForwardSuccess(false); setIsForwardError(true); diff --git a/src/app/components/message/modals/MessageReport.tsx b/src/app/components/message/modals/MessageReport.tsx index cf8aacc5..71cf03cc 100644 --- a/src/app/components/message/modals/MessageReport.tsx +++ b/src/app/components/message/modals/MessageReport.tsx @@ -1,4 +1,4 @@ -import { FormEventHandler, MouseEvent, useCallback } from 'react'; +import { FormEventHandler, MouseEvent, useCallback, useEffect } from 'react'; import { Room, MatrixEvent } from '$types/matrix-sdk'; import { useSetAtom } from 'jotai'; import { @@ -20,6 +20,10 @@ import { useMatrixClient } from '$hooks/useMatrixClient'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import * as css from '$features/room/message/styles.css'; import { modalAtom, ModalType } from '$state/modal'; +import { createDebugLogger } from '$utils/debugLogger'; +import * as Sentry from '@sentry/react'; + +const debugLog = createDebugLogger('MessageReport'); export function MessageReportItem({ room, mEvent }: { room: Room; mEvent: MatrixEvent }) { const setModal = useSetAtom(modalAtom); @@ -65,6 +69,17 @@ export function MessageReportInternal({ room, mEvent, onClose }: MessageReportIn ) ); + useEffect(() => { + if (reportState.status === AsyncStatus.Success) { + debugLog.info('ui', 'Message reported successfully', { roomId: room.roomId }); + Sentry.metrics.count('sable.message.report.success', 1); + } + if (reportState.status === AsyncStatus.Error) { + debugLog.error('ui', 'Message report failed', { roomId: room.roomId }); + Sentry.metrics.count('sable.message.report.error', 1); + } + }, [reportState.status, room.roomId]); + const handleSubmit: FormEventHandler = (evt) => { evt.preventDefault(); const eventId = mEvent.getId(); @@ -79,6 +94,8 @@ export function MessageReportInternal({ room, mEvent, onClose }: MessageReportIn const reasonInput = target?.reasonInput as HTMLInputElement | undefined; const reason = reasonInput && reasonInput.value.trim(); + debugLog.info('ui', 'Reporting message', { eventId, hasReason: !!reason }); + Sentry.metrics.count('sable.message.report.attempt', 1); reportMessage(eventId, reason ? -100 : -50, reason || 'No reason provided'); }; diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index a829ba39..1b887cca 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -566,13 +566,30 @@ const useLiveTimelineRefresh = (room: Room, onRefresh: () => void) => { useEffect(() => { const handleTimelineRefresh: RoomEventHandlerMap[RoomEvent.TimelineRefresh] = (r: Room) => { if (r.roomId !== room.roomId) return; + // App-initiated full reinit (e.g. from refreshLiveTimeline()). Rare in normal usage. + debugLog.debug('timeline', 'TimelineRefresh: app-initiated live timeline reinit', { + roomId: room.roomId, + trigger: 'TimelineRefresh', + }); onRefreshRef.current(); }; // The SDK fires RoomEvent.TimelineReset on the EventTimelineSet (not the Room) - // when a limited sliding-sync response replaces the live EventTimeline with a - // fresh one. Without this handler, the stored linkedTimelines reference the old - // detached chain and back-pagination silently no-ops, freezing the room. + // when a limited sync response replaces the live EventTimeline with a fresh one. + // This happens in classic /sync on limited=true (gap after idle/reconnect) AND in + // sliding sync when the proxy sends a limited room update. const handleTimelineReset: EventTimelineSetHandlerMap[RoomEvent.TimelineReset] = () => { + debugLog.info('timeline', 'TimelineReset: SDK-initiated (limited sync / sync gap)', { + roomId: room.roomId, + trigger: 'TimelineReset', + liveTimelineEvents: room.getUnfilteredTimelineSet().getLiveTimeline().getEvents().length, + }); + Sentry.metrics.count('sable.timeline.limited_reset', 1); + Sentry.addBreadcrumb({ + category: 'timeline.sync', + message: 'TimelineReset: limited sync gap', + level: 'info', + data: { roomId: room.roomId }, + }); onRefreshRef.current(); }; const unfilteredTimelineSet = room.getUnfilteredTimelineSet(); @@ -827,10 +844,35 @@ export function RoomTimeline({ const [atBottom, setAtBottomState] = useState(true); const atBottomRef = useRef(atBottom); - const setAtBottom = useCallback((val: boolean) => { - setAtBottomState(val); - atBottomRef.current = val; - }, []); + // Tracks when atBottom last changed so we can detect rapid true→false flips + // (characteristic of the IO false-positive on bulk event loads). + const atBottomLastChangedRef = useRef(0); + const setAtBottom = useCallback( + (val: boolean) => { + setAtBottomState(val); + const now = Date.now(); + const msSincePrevious = now - atBottomLastChangedRef.current; + atBottomLastChangedRef.current = now; + Sentry.addBreadcrumb({ + category: 'ui.scroll', + message: val ? 'Timeline: scrolled to bottom' : 'Timeline: scrolled away from bottom', + level: 'info', + data: { roomId: room.roomId, msSincePrevious }, + }); + // Rapid flip: bottom→away within 200 ms is characteristic of the known + // IntersectionObserver false-positive triggered by bulk event loads causing + // a DOM layout shift (see memory: "RoomTimeline Stay at Bottom False-Positive"). + if (!val && msSincePrevious < 200) { + Sentry.captureMessage('Timeline: rapid atBottom flip (possible spurious scroll reset)', { + level: 'warning', + extra: { roomId: room.roomId, msSincePrevious }, + tags: { feature: 'timeline' }, + }); + } + atBottomRef.current = val; + }, + [room.roomId] + ); // Set to true by the useLiveTimelineRefresh callback when the timeline is // re-initialised (TimelineRefresh or TimelineReset). Allows the range self-heal @@ -898,6 +940,53 @@ export function RoomTimeline({ const eventsLength = getTimelinesEventsCount(timeline.linkedTimelines); const liveTimelineLinked = timeline.linkedTimelines.at(-1) === getLiveTimeline(room); + // Track previous eventsLength so we can calculate batch sizes. + const prevEventsLengthRef = useRef(eventsLength); + + // Breadcrumb every time the timeline gains events so we can correlate message + // batches (sliding sync chunks) with scroll state changes in Sentry Replay. + useEffect(() => { + const prev = prevEventsLengthRef.current; + const delta = eventsLength - prev; + prevEventsLengthRef.current = eventsLength; + + if (delta === 0) return; + + const isBatch = delta > 1; + // Classify by size: single new message vs small batch vs large catch-up load + const batchSize = delta === 1 ? 'single' : delta <= 20 ? 'small' : delta <= 100 ? 'medium' : 'large'; + + Sentry.addBreadcrumb({ + category: 'timeline.events', + message: `Timeline: ${delta} event${delta === 1 ? '' : 's'} added (${batchSize})`, + level: isBatch ? 'info' : 'debug', + data: { + delta, + batchSize, + eventsLength, + prevEventsLength: prev, + liveTimelineLinked, + rangeEnd: timeline.range.end, + atBottom: atBottomRef.current, + // Gap between live end and visible window — non-zero while user is scrolled back + rangeGap: eventsLength - timeline.range.end, + }, + }); + + // A large batch (> 50) while liveTimelineLinked is the sliding-sync + // adaptive load pattern that can trigger the IO false-positive scroll reset. + // Capture a warning so it's searchable in Sentry even when no reset fires. + if (delta > 50 && liveTimelineLinked) { + Sentry.captureMessage('Timeline: large event batch from sliding sync', { + level: 'warning', + extra: { delta, eventsLength, rangeEnd: timeline.range.end, atBottom: atBottomRef.current }, + tags: { feature: 'timeline', batchSize }, + }); + } + // atBottomRef and timeline.range.end are intentionally read at effect time, not as deps + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [eventsLength, liveTimelineLinked]); + // Log timeline component mount/unmount useEffect(() => { const mode = eventId ? 'jump' : 'live'; @@ -957,6 +1046,34 @@ export function RoomTimeline({ return currentTimeline; } + // Log range changes with scroll state so we can correlate visible-content + // jumps with paginator window shifts. scrollRef is a stable ref — safe here. + const scrollEl = scrollRef.current; + const ds = newRange.start - currentTimeline.range.start; + const de = newRange.end - currentTimeline.range.end; + debugLog.debug('timeline', 'Virtual paginator range changed', { + prevRange: { start: currentTimeline.range.start, end: currentTimeline.range.end }, + newRange, + deltaStart: ds, + deltaEnd: de, + scrollTop: scrollEl?.scrollTop, + scrollHeight: scrollEl?.scrollHeight, + clientHeight: scrollEl?.clientHeight, + }); + Sentry.addBreadcrumb({ + category: 'ui.timeline', + message: 'Timeline window shifted', + level: 'debug', + data: { + prevStart: currentTimeline.range.start, + prevEnd: currentTimeline.range.end, + newStart: newRange.start, + newEnd: newRange.end, + deltaStart: ds, + deltaEnd: de, + }, + }); + return { ...currentTimeline, range: newRange }; }); }, []), @@ -1346,7 +1463,24 @@ export function RoomTimeline({ useLayoutEffect(() => { const scrollEl = scrollRef.current; if (scrollEl) { + const preScrollTop = scrollEl.scrollTop; + const preScrollHeight = scrollEl.scrollHeight; + const { clientHeight } = scrollEl; scrollToBottom(scrollEl); + // Log whether we were actually away from bottom at mount — useful for diagnosing + // rooms that open with the wrong scroll position. + const distanceFromBottom = preScrollHeight - preScrollTop - clientHeight; + debugLog.debug('timeline', 'Initial scroll to bottom (mount)', { + preScrollTop, + preScrollHeight, + clientHeight, + postScrollTop: scrollEl.scrollTop, + distanceFromBottom, + alreadyAtBottom: distanceFromBottom <= 2, + }); + if (distanceFromBottom > 0) { + Sentry.metrics.distribution('sable.timeline.initial_scroll_offset_px', distanceFromBottom); + } } }, []); @@ -1358,7 +1492,19 @@ export function RoomTimeline({ const forceScroll = () => { // if the user isn't scrolling jump down to latest content - if (!atBottomRef.current) return; + const wasAtBottom = atBottomRef.current; + const preScrollTop = scrollEl?.scrollTop ?? 0; + const preScrollHeight = scrollEl?.scrollHeight ?? 0; + // Log every resize so we can see when media loads move the timeline and whether + // we corrected it (atBottom=true) or left it (atBottom=false, user is scrolled up). + debugLog.debug('timeline', 'Content resized (image/media load)', { + atBottom: wasAtBottom, + preScrollTop, + preScrollHeight, + clientHeight: scrollEl?.clientHeight, + distanceFromBottom: preScrollHeight - preScrollTop - (scrollEl?.clientHeight ?? 0), + }); + if (!wasAtBottom) return; scrollToBottom(scrollEl, 'instant'); }; @@ -1418,11 +1564,36 @@ export function RoomTimeline({ const scrollEl = scrollRef.current; if (scrollEl) { const behavior = scrollToBottomRef.current.smooth && !reducedMotion ? 'smooth' : 'instant'; + const wasAtBottom = atBottomRef.current; + Sentry.addBreadcrumb({ + category: 'ui.scroll', + message: 'Timeline: scroll-to-bottom triggered', + level: 'info', + data: { roomId: room.roomId, behavior, wasAtBottom }, + }); + // A scroll-to-bottom while the user was NOT at the bottom and no timeline + // reset is expected is a sign of an unexpected scroll jump. + if (!wasAtBottom && !timelineJustResetRef.current) { + Sentry.captureMessage('Timeline: scroll-to-bottom fired while user was scrolled up', { + level: 'warning', + extra: { roomId: room.roomId, behavior }, + tags: { feature: 'timeline' }, + }); + } // Use requestAnimationFrame to ensure the virtual paginator has finished // updating the DOM before we scroll. This prevents scroll position from // being stale when new messages arrive while at the bottom. requestAnimationFrame(() => { + const preScrollTop = scrollEl.scrollTop; + const { scrollHeight } = scrollEl; scrollToBottom(scrollEl, behavior); + debugLog.debug('timeline', 'scrollToBottom fired', { + behavior, + preScrollTop, + scrollHeight, + postScrollTop: scrollEl.scrollTop, + remainingOffset: scrollEl.scrollHeight - scrollEl.scrollTop - scrollEl.clientHeight, + }); // On Android WebView, layout may still settle after the initial scroll. // Fire a second instant scroll after a short delay to guarantee we // reach the true bottom (e.g. after images finish loading or the @@ -1614,8 +1785,11 @@ export function RoomTimeline({ ); const handleReactionToggle = useCallback( - (targetEventId: string, key: string, shortcode?: string) => - toggleReaction(mx, room, targetEventId, key, shortcode), + (targetEventId: string, key: string, shortcode?: string) => { + debugLog.info('ui', 'Reaction toggled', { roomId: room.roomId, targetEventId, key }); + Sentry.metrics.count('sable.message.reaction.toggle', 1); + toggleReaction(mx, room, targetEventId, key, shortcode); + }, [mx, room] ); diff --git a/src/app/features/settings/general/General.tsx b/src/app/features/settings/general/General.tsx index 4facb2cc..5a802eed 100644 --- a/src/app/features/settings/general/General.tsx +++ b/src/app/features/settings/general/General.tsx @@ -1140,7 +1140,7 @@ function DiagnosticsAndPrivacy() { + + +
+
+ ); +} diff --git a/src/app/components/telemetry-consent/index.ts b/src/app/components/telemetry-consent/index.ts new file mode 100644 index 00000000..644d8bda --- /dev/null +++ b/src/app/components/telemetry-consent/index.ts @@ -0,0 +1 @@ +export * from './TelemetryConsentBanner'; diff --git a/src/app/features/settings/general/General.tsx b/src/app/features/settings/general/General.tsx index 5a802eed..446ce37d 100644 --- a/src/app/features/settings/general/General.tsx +++ b/src/app/features/settings/general/General.tsx @@ -1068,7 +1068,7 @@ function DiagnosticsAndPrivacy() { const handleSentryToggle = (enabled: boolean) => { setSentryEnabled(enabled); if (enabled) { - localStorage.removeItem('sable_sentry_enabled'); + localStorage.setItem('sable_sentry_enabled', 'true'); } else { localStorage.setItem('sable_sentry_enabled', 'false'); } diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx index a5e78e60..9a5e89d5 100644 --- a/src/app/pages/client/ClientNonUIFeatures.tsx +++ b/src/app/pages/client/ClientNonUIFeatures.tsx @@ -48,6 +48,7 @@ import { mobileOrTablet } from '$utils/user-agent'; import { useSlidingSyncActiveRoom } from '$hooks/useSlidingSyncActiveRoom'; import { getSlidingSyncManager } from '$client/initMatrix'; import { NotificationBanner } from '$components/notification-banner'; +import { TelemetryConsentBanner } from '$components/telemetry-consent'; import { useCallSignaling } from '$hooks/useCallSignaling'; import { getBlobCacheStats } from '$hooks/useBlobCache'; import { lastVisitedRoomIdAtom } from '$state/room/lastRoom'; @@ -766,6 +767,7 @@ export function ClientNonUIFeatures({ children }: ClientNonUIFeaturesProps) { + diff --git a/src/instrument.ts b/src/instrument.ts index b79a414a..cd3f5586 100644 --- a/src/instrument.ts +++ b/src/instrument.ts @@ -23,7 +23,7 @@ const release = import.meta.env.VITE_APP_VERSION; let sessionErrorCount = 0; const SESSION_ERROR_LIMIT = 50; -// Check user preferences +// Default on: Sentry runs unless the user has opted out via the banner or Settings. const sentryEnabled = localStorage.getItem('sable_sentry_enabled') !== 'false'; const replayEnabled = localStorage.getItem('sable_sentry_replay_enabled') === 'true'; From a11179862f64dd5ea1fc64faaadca0e5fd691d56 Mon Sep 17 00:00:00 2001 From: melogale Date: Mon, 16 Mar 2026 00:57:00 -0400 Subject: [PATCH 050/146] 1.1.2 sable call! --- package.json | 2 +- pnpm-lock.yaml | 10 +++++----- pnpm-workspace.yaml | 2 ++ 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index e36c3f42..a4b5dc3e 100644 --- a/package.json +++ b/package.json @@ -89,7 +89,7 @@ }, "devDependencies": { "@cloudflare/vite-plugin": "^1.26.0", - "@sableclient/sable-call-embedded": "1.1.0", + "@sableclient/sable-call-embedded": "1.1.2", "@esbuild-plugins/node-globals-polyfill": "^0.2.3", "@eslint/compat": "2.0.2", "@eslint/js": "9.39.3", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6abfbdb5..830c03ac 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -216,8 +216,8 @@ importers: specifier: ^6.2.2 version: 6.2.2(rollup@4.59.0) '@sableclient/sable-call-embedded': - specifier: 1.1.0 - version: 1.1.0 + specifier: 1.1.2 + version: 1.1.2 '@types/chroma-js': specifier: ^3.1.2 version: 3.1.2 @@ -2319,8 +2319,8 @@ packages: '@rtsao/scc@1.1.0': resolution: {integrity: sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==} - '@sableclient/sable-call-embedded@1.1.0': - resolution: {integrity: sha512-MiMfCtYhFQNjF5H8tDC3CpX004Cmg05sms1QgGYE00aoQsxQKUpuMhkU3utj9kXVl6Xxs/7qZ6to+a6Hhsic/A==} + '@sableclient/sable-call-embedded@1.1.2': + resolution: {integrity: sha512-Gr7spm+pZHkGGT/oR+f+Sam3CkDhn6pXjsiKPyfwSBu2ZCSdpDGzxMiEDcVRXvUjc3VV2TdRn+xB/xCdF3mv7A==} '@sindresorhus/is@7.2.0': resolution: {integrity: sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==} @@ -7482,7 +7482,7 @@ snapshots: '@rtsao/scc@1.1.0': {} - '@sableclient/sable-call-embedded@1.1.0': {} + '@sableclient/sable-call-embedded@1.1.2': {} '@sindresorhus/is@7.2.0': {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 875f7e44..392ed805 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -6,6 +6,8 @@ allowBuilds: workerd: true engineStrict: true minimumReleaseAge: 1440 +minimumReleaseAgeExclude: + - '@sableclient/sable-call-embedded' overrides: brace-expansion: '>=1.1.12' From b88d77329e4b8cab4119dcb79b4b180d062920b9 Mon Sep 17 00:00:00 2001 From: melogale Date: Mon, 16 Mar 2026 01:01:41 -0400 Subject: [PATCH 051/146] changeset --- .changeset/bring-in-sable-call.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .changeset/bring-in-sable-call.md diff --git a/.changeset/bring-in-sable-call.md b/.changeset/bring-in-sable-call.md new file mode 100644 index 00000000..173e258c --- /dev/null +++ b/.changeset/bring-in-sable-call.md @@ -0,0 +1,6 @@ +--- +default: minor +--- + +Bring in wriggle's element call fork as sable call! +Also: update widget api to match wriggle, and fix obvious breakages. From 75c128831fa9b6a310701f7be3900307dfaea16e Mon Sep 17 00:00:00 2001 From: Shea Duma Date: Mon, 16 Mar 2026 07:38:14 +0200 Subject: [PATCH 052/146] overspecified the width of the texteditor to make sure it doesnt shrink for no reason --- src/app/components/editor/Editor.css.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/app/components/editor/Editor.css.ts b/src/app/components/editor/Editor.css.ts index d128ed07..32e5753f 100644 --- a/src/app/components/editor/Editor.css.ts +++ b/src/app/components/editor/Editor.css.ts @@ -9,6 +9,7 @@ export const Editor = style([ boxShadow: `inset 0 0 0 ${config.borderWidth.B300} ${color.SurfaceVariant.ContainerLine}`, borderRadius: config.radii.R400, overflow: 'hidden', + width: '100%' }, ]); From 55d92c6610635d2db8601db353a67c670155744e Mon Sep 17 00:00:00 2001 From: Shea Duma Date: Mon, 16 Mar 2026 08:16:45 +0200 Subject: [PATCH 053/146] making formatter happy :smile: --- src/app/components/editor/Editor.css.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/components/editor/Editor.css.ts b/src/app/components/editor/Editor.css.ts index 32e5753f..290f7596 100644 --- a/src/app/components/editor/Editor.css.ts +++ b/src/app/components/editor/Editor.css.ts @@ -9,7 +9,7 @@ export const Editor = style([ boxShadow: `inset 0 0 0 ${config.borderWidth.B300} ${color.SurfaceVariant.ContainerLine}`, borderRadius: config.radii.R400, overflow: 'hidden', - width: '100%' + width: '100%', }, ]); From 643ace6f605dba1533e5797bcbf5fe7249cd7b1b Mon Sep 17 00:00:00 2001 From: melogale Date: Mon, 16 Mar 2026 02:37:21 -0400 Subject: [PATCH 054/146] update sable call --- package.json | 2 +- pnpm-lock.yaml | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index a4b5dc3e..694ca77f 100644 --- a/package.json +++ b/package.json @@ -89,7 +89,7 @@ }, "devDependencies": { "@cloudflare/vite-plugin": "^1.26.0", - "@sableclient/sable-call-embedded": "1.1.2", + "@sableclient/sable-call-embedded": "v1.1.3", "@esbuild-plugins/node-globals-polyfill": "^0.2.3", "@eslint/compat": "2.0.2", "@eslint/js": "9.39.3", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 830c03ac..873d0db2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -216,8 +216,8 @@ importers: specifier: ^6.2.2 version: 6.2.2(rollup@4.59.0) '@sableclient/sable-call-embedded': - specifier: 1.1.2 - version: 1.1.2 + specifier: v1.1.3 + version: 1.1.3 '@types/chroma-js': specifier: ^3.1.2 version: 3.1.2 @@ -2319,8 +2319,8 @@ packages: '@rtsao/scc@1.1.0': resolution: {integrity: sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==} - '@sableclient/sable-call-embedded@1.1.2': - resolution: {integrity: sha512-Gr7spm+pZHkGGT/oR+f+Sam3CkDhn6pXjsiKPyfwSBu2ZCSdpDGzxMiEDcVRXvUjc3VV2TdRn+xB/xCdF3mv7A==} + '@sableclient/sable-call-embedded@1.1.3': + resolution: {integrity: sha512-HNxppMEF8am6qhABbvJNc2mlkex7SntUeAMATOoNo2QkiTrutrJ9LPWy0TZskjAp++RrSpEpypKcN3MmOlZEWA==} '@sindresorhus/is@7.2.0': resolution: {integrity: sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==} @@ -7482,7 +7482,7 @@ snapshots: '@rtsao/scc@1.1.0': {} - '@sableclient/sable-call-embedded@1.1.2': {} + '@sableclient/sable-call-embedded@1.1.3': {} '@sindresorhus/is@7.2.0': {} From 597d00d59b440938b43e77ab2b32f74c1cc3da47 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 09:01:08 -0400 Subject: [PATCH 055/146] feat(push): encrypted push notifications via event_id_only and decryption relay --- .../notifications/PushNotifications.tsx | 5 +- src/app/pages/client/ClientNonUIFeatures.tsx | 61 +++++ src/index.tsx | 2 +- src/sw-session.ts | 3 +- src/sw.ts | 234 +++++++++++++++++- 5 files changed, 296 insertions(+), 9 deletions(-) diff --git a/src/app/features/settings/notifications/PushNotifications.tsx b/src/app/features/settings/notifications/PushNotifications.tsx index eb1f775e..46c0ebb0 100644 --- a/src/app/features/settings/notifications/PushNotifications.tsx +++ b/src/app/features/settings/notifications/PushNotifications.tsx @@ -62,8 +62,7 @@ export async function enablePushNotifications( lang: navigator.language || 'en', data: { url: clientConfig.pushNotificationDetails?.pushNotifyUrl, - // format: 'event_id_only' as const, - events_only: true, + format: 'event_id_only' as const, endpoint: pushSubAtom.endpoint, p256dh: keys.p256dh, auth: keys.auth, @@ -111,7 +110,7 @@ export async function enablePushNotifications( lang: navigator.language || 'en', data: { url: clientConfig.pushNotificationDetails?.pushNotifyUrl, - // format: 'event_id_only' as const, + format: 'event_id_only' as const, endpoint: newSubscription.endpoint, p256dh: keys.p256dh, auth: keys.auth, diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx index 5ec5d880..f617fb82 100644 --- a/src/app/pages/client/ClientNonUIFeatures.tsx +++ b/src/app/pages/client/ClientNonUIFeatures.tsx @@ -2,6 +2,7 @@ import { useAtomValue, useSetAtom } from 'jotai'; import { ReactNode, useCallback, useEffect, useRef } from 'react'; import { useNavigate } from 'react-router-dom'; import { + MatrixEvent, MatrixEventEvent, PushProcessor, RoomEvent, @@ -619,6 +620,65 @@ function SlidingSyncActiveRoomSubscriber() { return null; } +/** + * Listens for decryptPushEvent messages from the service worker, decrypts the + * event using the local Olm/Megolm session, then replies with pushDecryptResult + * so the SW can show a notification with the real message content. + * Falls back gracefully (success: false) on any error or if keys are missing. + */ +function HandleDecryptPushEvent() { + const mx = useMatrixClient(); + + useEffect(() => { + if (!('serviceWorker' in navigator)) return undefined; + + const handleMessage = async (ev: MessageEvent) => { + const { data } = ev; + if (!data || data.type !== 'decryptPushEvent') return; + + const { rawEvent } = data as { rawEvent: Record }; + const eventId = rawEvent.event_id as string; + const roomId = rawEvent.room_id as string; + + try { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const mxEvent = new MatrixEvent(rawEvent as any); + await mx.decryptEventIfNeeded(mxEvent); + + const room = mx.getRoom(roomId); + const sender = mxEvent.getSender(); + const senderName = sender + ? (room + ? getMemberDisplayName(room, sender) ?? getMxIdLocalPart(sender) + : getMxIdLocalPart(sender)) + : 'Someone'; + + navigator.serviceWorker.controller?.postMessage({ + type: 'pushDecryptResult', + eventId, + success: true, + eventType: mxEvent.getType(), + content: mxEvent.getContent(), + sender_display_name: senderName, + room_name: room?.name ?? '', + }); + } catch (err) { + console.warn('[app] HandleDecryptPushEvent: failed to decrypt push event', err); + navigator.serviceWorker.controller?.postMessage({ + type: 'pushDecryptResult', + eventId, + success: false, + }); + } + }; + + navigator.serviceWorker.addEventListener('message', handleMessage); + return () => navigator.serviceWorker.removeEventListener('message', handleMessage); + }, [mx]); + + return null; +} + function PresenceFeature() { const mx = useMatrixClient(); const [sendPresence] = useSetting(settingsAtom, 'sendPresence'); @@ -646,6 +706,7 @@ export function ClientNonUIFeatures({ children }: ClientNonUIFeaturesProps) { + diff --git a/src/index.tsx b/src/index.tsx index 3248458b..7720db1e 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -80,7 +80,7 @@ if ('serviceWorker' in navigator) { const activeId = getLocalStorageItem(ACTIVE_SESSION_KEY, undefined); const active = sessions.find((s) => s.userId === activeId) ?? sessions[0] ?? getFallbackSession(); - pushSessionToSW(active?.baseUrl, active?.accessToken); + pushSessionToSW(active?.baseUrl, active?.accessToken, active?.userId); }; navigator.serviceWorker diff --git a/src/sw-session.ts b/src/sw-session.ts index 4b2ec055..e4d2672d 100644 --- a/src/sw-session.ts +++ b/src/sw-session.ts @@ -1,4 +1,4 @@ -export function pushSessionToSW(baseUrl?: string, accessToken?: string) { +export function pushSessionToSW(baseUrl?: string, accessToken?: string, userId?: string) { if (!('serviceWorker' in navigator)) return; if (!navigator.serviceWorker.controller) return; @@ -6,5 +6,6 @@ export function pushSessionToSW(baseUrl?: string, accessToken?: string) { type: 'setSession', accessToken, baseUrl, + userId, }); } diff --git a/src/sw.ts b/src/sw.ts index 4486f418..b115a936 100644 --- a/src/sw.ts +++ b/src/sw.ts @@ -65,6 +65,8 @@ async function loadPersistedSettings() { type SessionInfo = { accessToken: string; baseUrl: string; + /** Matrix user ID of the account, used to identify which account a push belongs to. */ + userId?: string; }; /** @@ -88,9 +90,13 @@ async function cleanupDeadClients() { }); } -function setSession(clientId: string, accessToken: unknown, baseUrl: unknown) { +function setSession(clientId: string, accessToken: unknown, baseUrl: unknown, userId?: unknown) { if (typeof accessToken === 'string' && typeof baseUrl === 'string') { - sessions.set(clientId, { accessToken, baseUrl }); + sessions.set(clientId, { + accessToken, + baseUrl, + userId: typeof userId === 'string' ? userId : undefined, + }); console.debug('[SW] setSession: stored', clientId, baseUrl); } else { // Logout or invalid session @@ -143,6 +149,195 @@ async function requestSessionWithTimeout( return Promise.race([sessionPromise, timeout]); } +// --------------------------------------------------------------------------- +// Encrypted push — decryption relay +// --------------------------------------------------------------------------- + +/** + * The shape returned by the client tab after decrypting an encrypted push event. + * Also used as a partial pushData object for handlePushNotificationPushData. + */ +type DecryptionResult = { + eventId: string; + success: boolean; + eventType?: string; + content?: unknown; + sender_display_name?: string; + room_name?: string; +}; + +/** Pending decryption requests keyed by event_id. */ +const decryptionPendingMap = new Map void>(); + +/** + * Fetch a single raw Matrix event from the homeserver. + * Returns undefined on error (e.g. network failure, auth error, redacted event). + */ +async function fetchRawEvent( + baseUrl: string, + accessToken: string, + roomId: string, + eventId: string +): Promise | undefined> { + try { + const url = `${baseUrl}/_matrix/client/v3/rooms/${encodeURIComponent(roomId)}/event/${encodeURIComponent(eventId)}`; + const res = await fetch(url, { + headers: { Authorization: `Bearer ${accessToken}` }, + }); + if (!res.ok) { + console.warn('[SW fetchRawEvent] HTTP', res.status, 'for', eventId); + return undefined; + } + return (await res.json()) as Record; + } catch (err) { + console.warn('[SW fetchRawEvent] error', err); + return undefined; + } +} + +/** + * 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). + */ +function getAnyStoredSession(): SessionInfo | undefined { + for (const session of sessions.values()) { + return session; + } + return undefined; +} + +/** + * Extract the MXID localpart (@user:server → user) for fallback display names. + */ +function mxidLocalpart(userId: string): string { + return userId.match(/^@([^:]+):/)?.[1] ?? userId; +} + +/** + * Post a decryptPushEvent request to one of the open window clients and wait + * up to 5 s for the pushDecryptResult reply. + */ +async function requestDecryptionFromClient( + windowClients: readonly Client[], + rawEvent: Record +): Promise { + const eventId = rawEvent.event_id as string; + + for (const client of windowClients) { + const promise = new Promise((resolve) => { + decryptionPendingMap.set(eventId, resolve); + }); + + const timeout = new Promise((resolve) => { + setTimeout(() => { + decryptionPendingMap.delete(eventId); + console.warn('[SW decryptRelay] timed out waiting for client', client.id); + resolve(undefined); + }, 5000); + }); + + try { + (client as WindowClient).postMessage({ type: 'decryptPushEvent', rawEvent }); + } catch (err) { + decryptionPendingMap.delete(eventId); + console.warn('[SW decryptRelay] postMessage error', err); + continue; + } + + const result = await Promise.race([promise, timeout]); + if (result?.success) return result; + } + + return undefined; +} + +/** + * Handle a minimal push payload (event_id_only format). + * Fetches the event from the homeserver and shows a notification. + * For encrypted events, attempts to relay decryption to an open app tab. + */ +async function handleMinimalPushPayload( + roomId: string, + eventId: string, + windowClients: readonly Client[] +): Promise { + const session = getAnyStoredSession(); + + if (!session) { + // App is fully closed — no session in memory. Show a minimal actionable notification + // so the user can tap through to the room. + console.debug('[SW push] minimal payload: no session, showing generic notification'); + await self.registration.showNotification('New Message', { + body: undefined, + icon: '/public/res/apple/apple-touch-icon-180x180.png', + badge: '/public/res/apple/apple-touch-icon-72x72.png', + tag: `room-${roomId}`, + renotify: true, + data: { room_id: roomId, event_id: eventId }, + } as NotificationOptions); + return; + } + + const rawEvent = await fetchRawEvent(session.baseUrl, session.accessToken, roomId, eventId); + + if (!rawEvent) { + await self.registration.showNotification('New Message', { + body: undefined, + icon: '/public/res/apple/apple-touch-icon-180x180.png', + badge: '/public/res/apple/apple-touch-icon-72x72.png', + tag: `room-${roomId}`, + renotify: true, + data: { room_id: roomId, event_id: eventId, user_id: session.userId }, + } as NotificationOptions); + return; + } + + const eventType = rawEvent.type as string | undefined; + const sender = rawEvent.sender as string | undefined; + const senderDisplay = sender ? mxidLocalpart(sender) : 'Someone'; + const baseData = { + room_id: roomId, + event_id: eventId, + user_id: session.userId, + }; + + if (eventType === 'm.room.encrypted') { + // Try to relay decryption to an open tab + const result = windowClients.length > 0 + ? await requestDecryptionFromClient(windowClients, rawEvent) + : undefined; + + if (result) { + // Use decrypted content — reconstruct a pushData object + await handlePushNotificationPushData({ + ...baseData, + type: result.eventType, + content: result.content, + sender_display_name: result.sender_display_name ?? senderDisplay, + room_name: result.room_name ?? '', + }); + } else { + // Fallback: show generic "Encrypted message" + await handlePushNotificationPushData({ + ...baseData, + type: 'm.room.encrypted', + content: {}, + sender_display_name: senderDisplay, + room_name: '', + }); + } + } else { + // Unencrypted event — we have the plaintext, show it + await handlePushNotificationPushData({ + ...baseData, + type: eventType, + content: rawEvent.content, + sender_display_name: senderDisplay, + room_name: '', + }); + } +} + self.addEventListener('install', (event: ExtendableEvent) => { event.waitUntil(self.skipWaiting()); }); @@ -165,12 +360,23 @@ self.addEventListener('message', (event: ExtendableMessageEvent) => { const { data } = event; if (!data || typeof data !== 'object') return; - const { type, accessToken, baseUrl } = data as Record; + const { type, accessToken, baseUrl, userId } = data as Record; if (type === 'setSession') { - setSession(client.id, accessToken, baseUrl); + setSession(client.id, accessToken, baseUrl, userId); event.waitUntil(cleanupDeadClients()); } + if (type === 'pushDecryptResult') { + // Resolve a pending decryption request from handleMinimalPushPayload + const { eventId } = data as { eventId?: string }; + if (typeof eventId === 'string') { + const resolve = decryptionPendingMap.get(eventId); + if (resolve) { + decryptionPendingMap.delete(eventId); + resolve(data as DecryptionResult); + } + } + } if (type === 'setAppVisible') { if (typeof (data as { visible?: unknown }).visible === 'boolean') { appIsVisible = (data as { visible: boolean }).visible; @@ -346,9 +552,29 @@ const onPushNotification = async (event: PushEvent) => { // Badging API absent (Firefox/Gecko) — continue to show the notification. } + // event_id_only format: fetch the event ourselves and (for E2EE rooms) try + // to relay decryption to an open app tab. + if (isMinimalPushPayload(pushData)) { + console.debug('[SW push] minimal payload detected — fetching event', pushData.event_id); + await handleMinimalPushPayload(pushData.room_id, pushData.event_id, clients); + return; + } + await handlePushNotificationPushData(pushData); }; +// --------------------------------------------------------------------------- +// Push handler +// --------------------------------------------------------------------------- + +// Detect a minimal (event_id_only) payload: has room_id + event_id but no +// event type field — meaning the homeserver stripped the event content. +function isMinimalPushPayload(data: unknown): data is { room_id: string; event_id: string } { + if (!data || typeof data !== 'object') return false; + const d = data as Record; + return typeof d.room_id === 'string' && typeof d.event_id === 'string' && !d.type; +} + self.addEventListener('push', (event: PushEvent) => event.waitUntil(onPushNotification(event))); self.addEventListener('notificationclick', (event: NotificationEvent) => { From 9ecfb84dd1be9bccc769744e4929c4f57031049d Mon Sep 17 00:00:00 2001 From: Rye Date: Mon, 16 Mar 2026 14:03:05 +0100 Subject: [PATCH 056/146] fixes for iOS (hopefully) --- .../voice-recorder-kit/supportedCodec.ts | 51 ++++++--- .../voice-recorder-kit/useVoiceRecorder.ts | 100 ++++++++++++++---- 2 files changed, 115 insertions(+), 36 deletions(-) diff --git a/src/app/plugins/voice-recorder-kit/supportedCodec.ts b/src/app/plugins/voice-recorder-kit/supportedCodec.ts index e8f3dece..fd848e95 100644 --- a/src/app/plugins/voice-recorder-kit/supportedCodec.ts +++ b/src/app/plugins/voice-recorder-kit/supportedCodec.ts @@ -1,25 +1,37 @@ -/** Codecs to test for */ -const codecs = [ - // silly webkit-prefixed codecs for Safari support, because safari, apparently lies when asked what it supports +const safariPreferredCodecs = [ + // Safari works best with MP4/AAC but fails when strict codecs are defined on iOS. + // Prioritize the plain container to avoid NotSupportedError during MediaRecorder initialization. + 'audio/mp4', 'audio/mp4;codecs=mp4a.40.2', 'audio/mp4;codecs=mp4a.40.5', + 'audio/mp4;codecs=aac', 'audio/aac', + // Fallbacks + 'audio/wav;codecs=1', + 'audio/wav', + 'audio/mpeg', +]; + +const defaultPreferredCodecs = [ + // Chromium / Firefox stable path. + 'audio/webm;codecs=opus', + 'audio/webm', // Firefox 'audio/ogg;codecs=opus', 'audio/ogg;codecs=vorbis', 'audio/ogg', - // Chromium / Firefox - 'audio/webm;codecs=opus', - 'audio/webm', - // fallback + // Fallbacks 'audio/wav;codecs=1', 'audio/wav', - // other Codecs - 'audio/ogg;codecs=speex', - 'audio/webm;codecs=vorbis', + 'audio/mpeg', + // Keep MP4/AAC as late fallback for non-Safari browsers. + 'audio/mp4;codecs=mp4a.40.2', + 'audio/mp4;codecs=mp4a.40.5', 'audio/mp4;codecs=aac', 'audio/mp4', - 'audio/mpeg', + 'audio/aac', + 'audio/ogg;codecs=speex', + 'audio/webm;codecs=vorbis', ]; /** @@ -27,12 +39,19 @@ const codecs = [ * If no supported codec is found, it returns null. */ export function getSupportedAudioCodec(): string | null { - const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); - - if (isSafari && MediaRecorder.isTypeSupported('audio/mp4')) { - return 'audio/mp4'; + if (!('MediaRecorder' in globalThis) || !globalThis.MediaRecorder) { + return null; } - const supportedCodec = codecs.find((codec) => MediaRecorder.isTypeSupported(codec)); + + const userAgent = globalThis.navigator?.userAgent ?? ''; + const isIOS = + /iPad|iPhone|iPod/.test(userAgent) || + // eslint-disable-next-line @typescript-eslint/no-deprecated + (globalThis.navigator?.platform === 'MacIntel' && globalThis.navigator?.maxTouchPoints > 1); + const isSafari = /^((?!chrome|android|crios|fxios|edgios).)*safari/i.test(userAgent) || isIOS; + + const preferredCodecs = isSafari ? safariPreferredCodecs : defaultPreferredCodecs; + const supportedCodec = preferredCodecs.find((codec) => MediaRecorder.isTypeSupported(codec)); return supportedCodec || null; } diff --git a/src/app/plugins/voice-recorder-kit/useVoiceRecorder.ts b/src/app/plugins/voice-recorder-kit/useVoiceRecorder.ts index f3fa291a..a1eab6dd 100644 --- a/src/app/plugins/voice-recorder-kit/useVoiceRecorder.ts +++ b/src/app/plugins/voice-recorder-kit/useVoiceRecorder.ts @@ -209,7 +209,7 @@ export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoic }, []); const setupAudioGraph = useCallback( - (stream: MediaStream) => { + (stream: MediaStream): MediaStream => { const audioContext = new AudioContext(); audioContextRef.current = audioContext; const source = audioContext.createMediaStreamSource(stream); @@ -220,9 +220,17 @@ export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoic const dataArray = new Uint8Array(bufferLength); analyserRef.current = analyser; dataArrayRef.current = dataArray; + + // Fix for iOS Safari: routing the stream through a MediaStreamDestination + // prevents the AudioContext from "stealing" the track from the MediaRecorder + const destination = audioContext.createMediaStreamDestination(); source.connect(analyser); + analyser.connect(destination); + audioContext.resume().catch(() => {}); animateLevels(); + + return destination.stream; }, [animateLevels] ); @@ -270,10 +278,10 @@ export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoic previousChunksRef.current = []; waveformSamplesRef.current = []; isCollectingWaveformRef.current = true; - setupAudioGraph(stream); + const recordedStream = setupAudioGraph(stream); startRecordingTimer(); - const mediaRecorder = new MediaRecorder(stream, { mimeType: codec }); + const mediaRecorder = new MediaRecorder(recordedStream, { mimeType: codec }); mediaRecorderRef.current = mediaRecorder; mediaRecorder.ondataavailable = (event: BlobEvent) => { @@ -304,9 +312,20 @@ export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoic return; } - if (chunksRef.current.length === 0) return; + if (chunksRef.current.length === 0) { + if (isTemporaryStopRef.current) { + setIsTemporaryStopped(true); + setIsStopped(true); + isTemporaryStopRef.current = false; + } else { + setIsStopped(true); + setIsTemporaryStopped(false); + } + return; + } - const blob = new Blob(chunksRef.current, { type: codec }); + const actualType = chunksRef.current[0]?.type || codec || 'audio/webm'; + const blob = new Blob(chunksRef.current, { type: actualType }); if (lastUrlRef.current) { URL.revokeObjectURL(lastUrlRef.current); } @@ -314,9 +333,13 @@ export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoic lastUrlRef.current = url; setAudioUrl(url); - const file = new File([blob], `voice-${Date.now()}.${getSupportedAudioExtension(codec)}`, { - type: codec, - }); + const file = new File( + [blob], + `voice-${Date.now()}.${getSupportedAudioExtension(actualType)}`, + { + type: actualType, + } + ); setAudioFile(file); const waveformData = downsampleWaveform(waveformSamplesRef.current, WAVEFORM_POINT_COUNT); @@ -333,7 +356,9 @@ export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoic } }; - mediaRecorder.start(); + // Pass a timeslice to ensure Safari iOS periodically flushes chunks + // Otherwise Safari might fail to emit any chunks when stopped abruptly + mediaRecorder.start(1000); setIsRecording(true); setIsPaused(false); setIsStopped(false); @@ -393,11 +418,21 @@ export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoic isTemporaryStopRef.current = false; if (mediaRecorder.state === 'recording') { - mediaRecorder.requestData(); + try { + mediaRecorder.requestData(); + } catch { + // ignore + } } - mediaRecorder.stop(); - cleanupStream(); + try { + mediaRecorder.stop(); + } catch { + // ignore + } + + // Let cleanupStream() be handled by mediaRecorder.onstop + // Calling it synchronously here can kill the stream before Safari finishes emitting data setIsStopped(true); setIsTemporaryStopped(false); setIsPaused(false); @@ -434,8 +469,23 @@ export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoic if (mediaRecorder && mediaRecorder.state !== 'inactive') { previousChunksRef.current = [...chunksRef.current]; isTemporaryStopRef.current = false; - mediaRecorder.stop(); - cleanupStream(); + + if (mediaRecorder.state === 'recording') { + try { + mediaRecorder.requestData(); + } catch { + // ignore + } + } + + try { + mediaRecorder.stop(); + } catch { + // ignore + } + + // Let cleanupStream() be handled by mediaRecorder.onstop + // Calling it synchronously here can kill the stream before Safari finishes emitting data setIsStopped(true); setIsTemporaryStopped(false); setIsPaused(false); @@ -478,7 +528,8 @@ export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoic chunksRef.current.length > 0 ? chunksRef.current : previousChunksRef.current; if (allChunks.length > 0) { - const blob = new Blob(allChunks, { type: audioCodec || 'audio/webm' }); + const actualType = allChunks[0]?.type || audioCodec || 'audio/webm'; + const blob = new Blob(allChunks, { type: actualType }); urlToPlay = URL.createObjectURL(blob); temporaryPreviewUrlRef.current = urlToPlay; } @@ -596,13 +647,16 @@ export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoic try { const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); streamRef.current = stream; - setupAudioGraph(stream); + const recordedStream = setupAudioGraph(stream); // Force update seconds to the correct total time before starting timer setSeconds(pausedTimeRef.current); startRecordingTimer(); - const mediaRecorder = new MediaRecorder(stream); + const codec = getSupportedAudioCodec() || audioCodec; + const mediaRecorder = codec + ? new MediaRecorder(recordedStream, { mimeType: codec }) + : new MediaRecorder(recordedStream); mediaRecorderRef.current = mediaRecorder; mediaRecorder.ondataavailable = (event: BlobEvent) => { @@ -623,9 +677,13 @@ export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoic isCollectingWaveformRef.current = false; - if (chunksRef.current.length === 0) return; + if (chunksRef.current.length === 0) { + setIsStopped(true); + return; + } - const blob = new Blob(chunksRef.current, { type: audioCodec || 'audio/webm' }); + const actualType = chunksRef.current[0]?.type || audioCodec || 'audio/webm'; + const blob = new Blob(chunksRef.current, { type: actualType }); if (lastUrlRef.current) { URL.revokeObjectURL(lastUrlRef.current); } @@ -646,7 +704,9 @@ export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoic emitStopPayload(file, url, waveformData, audioLength); }; - mediaRecorder.start(); + // Pass a timeslice to ensure Safari iOS periodically flushes chunks + // Otherwise Safari might fail to emit any chunks when stopped abruptly + mediaRecorder.start(1000); setIsRecording(true); setIsPaused(false); setIsStopped(false); From 293ab69a40d51ab687ed15271aa25536fdc0c2bf Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 09:08:50 -0400 Subject: [PATCH 057/146] fix(push): resolve lint and type errors in encrypted push implementation --- src/app/pages/client/ClientNonUIFeatures.tsx | 11 ++- src/sw.ts | 78 ++++++++++---------- 2 files changed, 45 insertions(+), 44 deletions(-) diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx index f617fb82..6eb70ebb 100644 --- a/src/app/pages/client/ClientNonUIFeatures.tsx +++ b/src/app/pages/client/ClientNonUIFeatures.tsx @@ -641,17 +641,16 @@ function HandleDecryptPushEvent() { const roomId = rawEvent.room_id as string; try { - // eslint-disable-next-line @typescript-eslint/no-explicit-any const mxEvent = new MatrixEvent(rawEvent as any); await mx.decryptEventIfNeeded(mxEvent); const room = mx.getRoom(roomId); const sender = mxEvent.getSender(); - const senderName = sender - ? (room - ? getMemberDisplayName(room, sender) ?? getMxIdLocalPart(sender) - : getMxIdLocalPart(sender)) - : 'Someone'; + let senderName = 'Someone'; + if (sender) { + senderName = getMxIdLocalPart(sender) ?? sender; + if (room) senderName = getMemberDisplayName(room, sender) ?? senderName; + } navigator.serviceWorker.controller?.postMessage({ type: 'pushDecryptResult', diff --git a/src/sw.ts b/src/sw.ts index b115a936..9e5a3697 100644 --- a/src/sw.ts +++ b/src/sw.ts @@ -200,10 +200,7 @@ async function fetchRawEvent( * don't have a client ID, e.g. when the app is backgrounded but still loaded). */ function getAnyStoredSession(): SessionInfo | undefined { - for (const session of sessions.values()) { - return session; - } - return undefined; + return sessions.values().next().value; } /** @@ -223,32 +220,36 @@ async function requestDecryptionFromClient( ): Promise { const eventId = rawEvent.event_id as string; - for (const client of windowClients) { - const promise = new Promise((resolve) => { - decryptionPendingMap.set(eventId, resolve); - }); + // Chain clients sequentially using reduce to avoid await-in-loop and for-of. + return Array.from(windowClients).reduce( + async (prevPromise, client) => { + const prev = await prevPromise; + if (prev?.success) return prev; - const timeout = new Promise((resolve) => { - setTimeout(() => { + const promise = new Promise((resolve) => { + decryptionPendingMap.set(eventId, resolve); + }); + + const timeout = new Promise((resolve) => { + setTimeout(() => { + decryptionPendingMap.delete(eventId); + console.warn('[SW decryptRelay] timed out waiting for client', client.id); + resolve(undefined); + }, 5000); + }); + + try { + (client as WindowClient).postMessage({ type: 'decryptPushEvent', rawEvent }); + } catch (err) { decryptionPendingMap.delete(eventId); - console.warn('[SW decryptRelay] timed out waiting for client', client.id); - resolve(undefined); - }, 5000); - }); + console.warn('[SW decryptRelay] postMessage error', err); + return undefined; + } - try { - (client as WindowClient).postMessage({ type: 'decryptPushEvent', rawEvent }); - } catch (err) { - decryptionPendingMap.delete(eventId); - console.warn('[SW decryptRelay] postMessage error', err); - continue; - } - - const result = await Promise.race([promise, timeout]); - if (result?.success) return result; - } - - return undefined; + return Promise.race([promise, timeout]); + }, + Promise.resolve(undefined) as Promise + ); } /** @@ -303,9 +304,10 @@ async function handleMinimalPushPayload( if (eventType === 'm.room.encrypted') { // Try to relay decryption to an open tab - const result = windowClients.length > 0 - ? await requestDecryptionFromClient(windowClients, rawEvent) - : undefined; + const result = + windowClients.length > 0 + ? await requestDecryptionFromClient(windowClients, rawEvent) + : undefined; if (result) { // Use decrypted content — reconstruct a pushData object @@ -498,6 +500,14 @@ self.addEventListener('fetch', (event: FetchEvent) => { ); }); +// Detect a minimal (event_id_only) payload: has room_id + event_id but no +// event type field — meaning the homeserver stripped the event content. +function isMinimalPushPayload(data: unknown): data is { room_id: string; event_id: string } { + if (!data || typeof data !== 'object') return false; + const d = data as Record; + return typeof d.room_id === 'string' && typeof d.event_id === 'string' && !d.type; +} + const onPushNotification = async (event: PushEvent) => { if (!event?.data) return; @@ -567,14 +577,6 @@ const onPushNotification = async (event: PushEvent) => { // Push handler // --------------------------------------------------------------------------- -// Detect a minimal (event_id_only) payload: has room_id + event_id but no -// event type field — meaning the homeserver stripped the event content. -function isMinimalPushPayload(data: unknown): data is { room_id: string; event_id: string } { - if (!data || typeof data !== 'object') return false; - const d = data as Record; - return typeof d.room_id === 'string' && typeof d.event_id === 'string' && !d.type; -} - self.addEventListener('push', (event: PushEvent) => event.waitUntil(onPushNotification(event))); self.addEventListener('notificationclick', (event: NotificationEvent) => { From 042d441046e08a3c24697be9f81be8ecea2edd26 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 09:09:10 -0400 Subject: [PATCH 058/146] chore: add changeset for encrypted push --- .changeset/feat-encrypted-push.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/feat-encrypted-push.md diff --git a/.changeset/feat-encrypted-push.md b/.changeset/feat-encrypted-push.md new file mode 100644 index 00000000..4bbbf8f4 --- /dev/null +++ b/.changeset/feat-encrypted-push.md @@ -0,0 +1,5 @@ +--- +default: minor +--- + +Push notifications now use `event_id_only` format — Sygnal never sees message content or sender metadata, and encrypted messages are decrypted client-side when the app tab is open From 166c8f4835d10e0ab10b209736c5b4da69980e6a Mon Sep 17 00:00:00 2001 From: Rye Date: Mon, 16 Mar 2026 14:10:56 +0100 Subject: [PATCH 059/146] fix file extension mapping --- .../plugins/voice-recorder-kit/supportedCodec.ts | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/src/app/plugins/voice-recorder-kit/supportedCodec.ts b/src/app/plugins/voice-recorder-kit/supportedCodec.ts index fd848e95..99481bde 100644 --- a/src/app/plugins/voice-recorder-kit/supportedCodec.ts +++ b/src/app/plugins/voice-recorder-kit/supportedCodec.ts @@ -60,27 +60,18 @@ export function getSupportedAudioCodec(): string | null { * This is used to ensure that the recorded audio file has the correct extension based on the codec used for recording. */ export function getSupportedAudioExtension(codec: string): string { - switch (codec) { - case 'audio/ogg;codecs=opus': - case 'audio/ogg;codecs=vorbis': - case 'audio/ogg;codecs=speex': + const baseType = codec.split(';')[0].trim(); + switch (baseType) { case 'audio/ogg': return 'ogg'; - case 'audio/webm;codecs=opus': case 'audio/webm': return 'webm'; case 'audio/mp4': - case 'audio/mp4;codecs=aac': return 'm4a'; case 'audio/mpeg': return 'mp3'; - case 'audio/wav;codecs=1': case 'audio/wav': return 'wav'; - // silly webkit stuff - case 'audio/mp4;codecs=mp4a.40.2': - case 'audio/mp4;codecs=mp4a.40.5': - return 'm4a'; case 'audio/aac': return 'aac'; default: From a96e0e90b5068432cecc283d08263fe8cffe6505 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 09:29:32 -0400 Subject: [PATCH 060/146] fix(push): persist session to Cache Storage so iOS SW restart survives --- src/sw.ts | 64 +++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 58 insertions(+), 6 deletions(-) diff --git a/src/sw.ts b/src/sw.ts index 9e5a3697..04372518 100644 --- a/src/sw.ts +++ b/src/sw.ts @@ -24,6 +24,10 @@ const { handlePushNotificationPushData } = createPushNotifications(self, () => ( const SW_SETTINGS_CACHE = 'sable-sw-settings-v1'; const SW_SETTINGS_URL = '/sw-settings-meta'; +/** Cache key used to persist the active session so push-event fetches work after SW restart. */ +const SW_SESSION_CACHE = 'sable-sw-session-v1'; +const SW_SESSION_URL = '/sw-session-meta'; + async function persistSettings() { try { const cache = await self.caches.open(SW_SETTINGS_CACHE); @@ -62,6 +66,46 @@ async function loadPersistedSettings() { } } +async function persistSession(session: SessionInfo): Promise { + try { + const cache = await self.caches.open(SW_SESSION_CACHE); + await cache.put( + SW_SESSION_URL, + new Response(JSON.stringify(session), { headers: { 'Content-Type': 'application/json' } }) + ); + } catch { + // Ignore — caches may be unavailable in some environments. + } +} + +async function clearPersistedSession(): Promise { + try { + const cache = await self.caches.open(SW_SESSION_CACHE); + await cache.delete(SW_SESSION_URL); + } catch { + // Ignore. + } +} + +async function loadPersistedSession(): Promise { + try { + const cache = await self.caches.open(SW_SESSION_CACHE); + const response = await cache.match(SW_SESSION_URL); + if (!response) return undefined; + const s = await response.json(); + if (typeof s.accessToken === 'string' && typeof s.baseUrl === 'string') { + return { + accessToken: s.accessToken, + baseUrl: s.baseUrl, + userId: typeof s.userId === 'string' ? s.userId : undefined, + }; + } + return undefined; + } catch { + return undefined; + } +} + type SessionInfo = { accessToken: string; baseUrl: string; @@ -92,16 +136,20 @@ async function cleanupDeadClients() { function setSession(clientId: string, accessToken: unknown, baseUrl: unknown, userId?: unknown) { if (typeof accessToken === 'string' && typeof baseUrl === 'string') { - sessions.set(clientId, { + const info: SessionInfo = { accessToken, baseUrl, userId: typeof userId === 'string' ? userId : undefined, - }); + }; + sessions.set(clientId, info); console.debug('[SW] setSession: stored', clientId, baseUrl); + // Persist so push-event fetches work after iOS restarts the SW. + persistSession(info).catch(() => undefined); } else { // Logout or invalid session sessions.delete(clientId); console.debug('[SW] setSession: removed', clientId); + clearPersistedSession().catch(() => undefined); } const resolveSession = clientToResolve.get(clientId); @@ -262,11 +310,14 @@ async function handleMinimalPushPayload( eventId: string, windowClients: readonly Client[] ): Promise { - const session = getAnyStoredSession(); + // On iOS the SW is killed and restarted for every push, clearing the in-memory sessions + // Map. Fall back to the Cache Storage copy that was written when the user last opened + // the app (same pattern as settings persistence). + const session = getAnyStoredSession() ?? (await loadPersistedSession()); if (!session) { - // App is fully closed — no session in memory. Show a minimal actionable notification - // so the user can tap through to the room. + // No session anywhere — app was never opened since install, or the user logged out. + // Show a minimal actionable notification so the user can tap through to the room. console.debug('[SW push] minimal payload: no session, showing generic notification'); await self.registration.showNotification('New Message', { body: undefined, @@ -514,8 +565,9 @@ const onPushNotification = async (event: PushEvent) => { // The SW may have been restarted by the OS (iOS is aggressive about this), // so in-memory settings would be at their defaults. Reload from cache and // match active clients in parallel — they are independent operations. - const [, clients] = await Promise.all([ + const [, , clients] = await Promise.all([ loadPersistedSettings(), + loadPersistedSession(), self.clients.matchAll({ type: 'window', includeUncontrolled: true }), ]); From fd9a1fa526530759af839d35294b010594b25985 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 09:50:42 -0400 Subject: [PATCH 061/146] fix(push): resolve room/sender names; suppress notification when app is visible --- src/app/pages/client/ClientNonUIFeatures.tsx | 2 + src/sw.ts | 80 +++++++++++++++++--- 2 files changed, 72 insertions(+), 10 deletions(-) diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx index 6eb70ebb..c4179c1b 100644 --- a/src/app/pages/client/ClientNonUIFeatures.tsx +++ b/src/app/pages/client/ClientNonUIFeatures.tsx @@ -660,6 +660,7 @@ function HandleDecryptPushEvent() { content: mxEvent.getContent(), sender_display_name: senderName, room_name: room?.name ?? '', + visibilityState: document.visibilityState, }); } catch (err) { console.warn('[app] HandleDecryptPushEvent: failed to decrypt push event', err); @@ -667,6 +668,7 @@ function HandleDecryptPushEvent() { type: 'pushDecryptResult', eventId, success: false, + visibilityState: document.visibilityState, }); } }; diff --git a/src/sw.ts b/src/sw.ts index 04372518..b374d6ff 100644 --- a/src/sw.ts +++ b/src/sw.ts @@ -212,6 +212,8 @@ type DecryptionResult = { content?: unknown; sender_display_name?: string; room_name?: string; + /** document.visibilityState reported by the responding app tab. */ + visibilityState?: string; }; /** Pending decryption requests keyed by event_id. */ @@ -243,6 +245,49 @@ async function fetchRawEvent( } } +/** + * Fetch the m.room.name state event from the homeserver. + * Returns undefined when not set (DMs and many encrypted rooms have no explicit name). + */ +async function fetchRoomName( + baseUrl: string, + accessToken: string, + roomId: string +): Promise { + try { + const url = `${baseUrl}/_matrix/client/v3/rooms/${encodeURIComponent(roomId)}/state/m.room.name`; + const res = await fetch(url, { headers: { Authorization: `Bearer ${accessToken}` } }); + if (!res.ok) return undefined; + const data = (await res.json()) as Record; + const { name } = data; + return typeof name === 'string' && name.trim() ? name.trim() : undefined; + } catch { + return undefined; + } +} + +/** + * Fetch a room member's displayname from homeserver member state. + * Returns undefined if the member has no displayname or the request fails. + */ +async function fetchMemberDisplayName( + baseUrl: string, + accessToken: string, + roomId: string, + userId: string +): 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 undefined; + const data = (await res.json()) as Record; + const name = data.displayname; + return typeof name === 'string' && name.trim() ? name.trim() : undefined; + } catch { + return undefined; + } +} + /** * 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). @@ -330,7 +375,11 @@ async function handleMinimalPushPayload( return; } - const rawEvent = await fetchRawEvent(session.baseUrl, session.accessToken, roomId, eventId); + // Fetch the raw event and room name state in parallel — both need only roomId. + const [rawEvent, roomNameFromState] = await Promise.all([ + fetchRawEvent(session.baseUrl, session.accessToken, roomId, eventId), + fetchRoomName(session.baseUrl, session.accessToken, roomId), + ]); if (!rawEvent) { await self.registration.showNotification('New Message', { @@ -346,7 +395,13 @@ async function handleMinimalPushPayload( const eventType = rawEvent.type as string | undefined; const sender = rawEvent.sender as string | undefined; - const senderDisplay = sender ? mxidLocalpart(sender) : 'Someone'; + // 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'); + // For DMs (no m.room.name state), use the sender's display name as the room name. + const resolvedRoomName = roomNameFromState ?? senderDisplay; const baseData = { room_id: roomId, event_id: eventId, @@ -354,39 +409,44 @@ async function handleMinimalPushPayload( }; if (eventType === 'm.room.encrypted') { - // Try to relay decryption to an open tab + // Try to relay decryption to an open app tab. const result = windowClients.length > 0 ? await requestDecryptionFromClient(windowClients, rawEvent) : undefined; - if (result) { - // Use decrypted content — reconstruct a pushData object + // If the relay responded and the app is currently visible, the in-app UI is already + // displaying the message — skip the OS notification entirely. + if (result?.visibilityState === 'visible') return; + + if (result?.success) { + // App was backgrounded but not frozen — decryption succeeded. await handlePushNotificationPushData({ ...baseData, type: result.eventType, content: result.content, sender_display_name: result.sender_display_name ?? senderDisplay, - room_name: result.room_name ?? '', + // Prefer relay's room name (has m.direct / computed SDK name); fall back to state fetch. + room_name: result.room_name || resolvedRoomName, }); } else { - // Fallback: show generic "Encrypted message" + // App is frozen or fully closed — show "Encrypted message" fallback. await handlePushNotificationPushData({ ...baseData, type: 'm.room.encrypted', content: {}, sender_display_name: senderDisplay, - room_name: '', + room_name: resolvedRoomName, }); } } else { - // Unencrypted event — we have the plaintext, show it + // Unencrypted event — we have the plaintext, show it. await handlePushNotificationPushData({ ...baseData, type: eventType, content: rawEvent.content, sender_display_name: senderDisplay, - room_name: '', + room_name: resolvedRoomName, }); } } From 0b9c6879c90eceb9792ca09a1cfe8e937d2fd206 Mon Sep 17 00:00:00 2001 From: hazre Date: Sun, 15 Mar 2026 00:59:34 +0100 Subject: [PATCH 062/146] fix: improve ux on voice memos --- .../features/room/AudioAttachmentPreview.tsx | 194 +++++++++++++++ .../features/room/AudioMessageRecorder.tsx | 222 ++++++++++++------ src/app/features/room/RoomInput.tsx | 184 ++++++++++----- src/app/utils/debug.ts | 3 +- 4 files changed, 472 insertions(+), 131 deletions(-) create mode 100644 src/app/features/room/AudioAttachmentPreview.tsx diff --git a/src/app/features/room/AudioAttachmentPreview.tsx b/src/app/features/room/AudioAttachmentPreview.tsx new file mode 100644 index 00000000..e054eb0b --- /dev/null +++ b/src/app/features/room/AudioAttachmentPreview.tsx @@ -0,0 +1,194 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import { Box, Chip, Icon, Icons, IconButton, Text, color, config, toRem } from 'folds'; + +type AudioAttachmentPreviewProps = { + audioUrl: string; + waveform: number[]; + duration: number; // seconds + onDelete: () => void; +}; + +function formatTime(s: number): string { + const m = Math.floor(s / 60); + const sec = Math.floor(s % 60); + return `${m}:${sec.toString().padStart(2, '0')}`; +} + +const BAR_COUNT = 44; + +/** + * Attachment-area chip for a just-recorded voice message. + * + * Shows a play/pause button, a clickable waveform scrubber that fills + * with Primary colour as playback advances, a duration counter, and a + * delete button that matches the UploadBoard cancel chip style. + */ +export function AudioAttachmentPreview({ + audioUrl, + waveform, + duration, + onDelete, +}: AudioAttachmentPreviewProps) { + const [isPlaying, setIsPlaying] = useState(false); + const [currentTime, setCurrentTime] = useState(0); + const audioRef = useRef(null); + const rafRef = useRef(null); + + // Downsample waveform to BAR_COUNT display bars + const bars = Array.from({ length: BAR_COUNT }, (_, i) => { + const src = waveform.length > 0 ? waveform : Array(BAR_COUNT).fill(0.3); + const step = src.length / BAR_COUNT; + return src[Math.floor(i * step)] ?? 0; + }); + + const progress = duration > 0 ? Math.min(currentTime / duration, 1) : 0; + + // Animate current-time with rAF while playing for a smooth scrubber + const startRaf = useCallback((audio: HTMLAudioElement) => { + const tick = () => { + setCurrentTime(audio.currentTime); + rafRef.current = requestAnimationFrame(tick); + }; + rafRef.current = requestAnimationFrame(tick); + }, []); + + const stopRaf = useCallback(() => { + if (rafRef.current !== null) { + cancelAnimationFrame(rafRef.current); + rafRef.current = null; + } + }, []); + + useEffect(() => { + const audio = new Audio(audioUrl); + audioRef.current = audio; + + audio.onended = () => { + setIsPlaying(false); + setCurrentTime(0); + stopRaf(); + }; + + return () => { + audio.pause(); + stopRaf(); + }; + }, [audioUrl, stopRaf]); + + const handlePlayPause = useCallback(() => { + const audio = audioRef.current; + if (!audio) return; + + if (isPlaying) { + audio.pause(); + setIsPlaying(false); + stopRaf(); + } else { + audio.play().catch(() => {}); + setIsPlaying(true); + startRaf(audio); + } + }, [isPlaying, startRaf, stopRaf]); + + const handleScrubClick = useCallback( + (e: React.MouseEvent) => { + const audio = audioRef.current; + if (!audio || !duration) return; + const rect = e.currentTarget.getBoundingClientRect(); + const ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width)); + audio.currentTime = ratio * duration; + setCurrentTime(audio.currentTime); + }, + [duration] + ); + + return ( + + {/* Play / Pause */} + + + + + {/* Waveform scrubber */} + + {bars.map((level, i) => { + const barRatio = i / BAR_COUNT; + const played = barRatio <= progress; + return ( +
+ ); + })} + + + {/* Time display: shows current position while playing, total when paused */} + + {formatTime(isPlaying ? currentTime : duration)} + + + {/* Delete — matches UploadBoardHeader "Remove" chip style */} + } + title="Remove voice message" + aria-label="Remove voice message" + /> + + ); +} diff --git a/src/app/features/room/AudioMessageRecorder.tsx b/src/app/features/room/AudioMessageRecorder.tsx index f324d444..dd5d3bab 100644 --- a/src/app/features/room/AudioMessageRecorder.tsx +++ b/src/app/features/room/AudioMessageRecorder.tsx @@ -1,7 +1,12 @@ -import { VoiceRecorder } from '$plugins/voice-recorder-kit'; -import FocusTrap from 'focus-trap-react'; -import { Box, Icon, Icons, Text, color, config } from 'folds'; -import { useRef } from 'react'; +import { forwardRef, useCallback, useImperativeHandle, useRef } from 'react'; +import { useVoiceRecorder } from '$plugins/voice-recorder-kit'; +import type { VoiceRecorderStopPayload } from '$plugins/voice-recorder-kit'; +import { Box, Text, color, config, toRem } from 'folds'; + +export type AudioMessageRecorderHandle = { + stop: () => void; + cancel: () => void; +}; type AudioMessageRecorderProps = { onRecordingComplete: (audioBlob: Blob) => void; @@ -10,83 +15,148 @@ type AudioMessageRecorderProps = { onAudioLengthUpdate: (length: number) => void; }; -// We use a react voice recorder library to handle the recording of audio messages, as it provides a simple API and handles the complexities of recording audio in the browser. -// The component is wrapped in a focus trap to ensure that keyboard users can easily navigate and interact with the recorder without accidentally losing focus or interacting with other parts of the UI. -// The styling is kept simple and consistent with the rest of the app, using Folds' design tokens for colors, spacing, and typography. -// we use a modified version of https://www.npmjs.com/package/react-voice-recorder-kit for the recording -export function AudioMessageRecorder({ - onRecordingComplete, - onRequestClose, - onWaveformUpdate, - onAudioLengthUpdate, -}: AudioMessageRecorderProps) { - const containerRef = useRef(null); +function formatTime(seconds: number): string { + const m = Math.floor(seconds / 60); + const s = seconds % 60; + return `${m}:${s.toString().padStart(2, '0')}`; +} + +const KEYFRAMES = ` +@keyframes recDotPulse { + 0%, 100% { opacity: 1; } + 50% { opacity: 0.25; } +} +`; +if (typeof document !== 'undefined') { + const styleId = '__audio-recorder-keyframes'; + if (!document.getElementById(styleId)) { + const style = document.createElement('style'); + style.id = styleId; + style.textContent = KEYFRAMES; + document.head.appendChild(style); + } +} + +export const AudioMessageRecorder = forwardRef< + AudioMessageRecorderHandle, + AudioMessageRecorderProps +>(({ onRecordingComplete, onRequestClose, onWaveformUpdate, onAudioLengthUpdate }, ref) => { const isDismissedRef = useRef(false); + // Guard against React Strict Mode's double-invoke of the autoStart effect, + // which fires onstop with a ~110-byte blob before the user does anything. + const userRequestedStopRef = useRef(false); + + // Keep stable refs for prop callbacks so useVoiceRecorder's internal + // useCallbacks never need to be recreated (which would reset the timer). + const onRecordingCompleteRef = useRef(onRecordingComplete); + onRecordingCompleteRef.current = onRecordingComplete; + const onRequestCloseRef = useRef(onRequestClose); + onRequestCloseRef.current = onRequestClose; + const onWaveformUpdateRef = useRef(onWaveformUpdate); + onWaveformUpdateRef.current = onWaveformUpdate; + const onAudioLengthUpdateRef = useRef(onAudioLengthUpdate); + onAudioLengthUpdateRef.current = onAudioLengthUpdate; + + // Stable stop handler — empty dep array intentional; live values via refs. + + const stableOnStop = useCallback((payload: VoiceRecorderStopPayload) => { + if (!userRequestedStopRef.current) return; + if (isDismissedRef.current) return; + onRecordingCompleteRef.current(payload.audioFile); + onWaveformUpdateRef.current(payload.waveform); + onAudioLengthUpdateRef.current(payload.audioLength); + }, []); + + // Stable delete handler — empty dep array intentional; live values via refs. + + const stableOnDelete = useCallback(() => { + isDismissedRef.current = true; + onRequestCloseRef.current(); + }, []); + + const { levels, seconds, handleStop, handleDelete } = useVoiceRecorder({ + autoStart: true, + onStop: stableOnStop, + onDelete: stableOnDelete, + }); + + const doStop = useCallback(() => { + if (isDismissedRef.current) return; + userRequestedStopRef.current = true; + handleStop(); + }, [handleStop]); + + const doCancel = useCallback(() => { + if (isDismissedRef.current) return; + isDismissedRef.current = true; + handleDelete(); + }, [handleDelete]); + + useImperativeHandle(ref, () => ({ stop: doStop, cancel: doCancel }), [doStop, doCancel]); + + const BAR_COUNT = 28; + const step = Math.max(1, levels.length / BAR_COUNT); + const bars = Array.from( + { length: BAR_COUNT }, + (_, i) => levels[Math.min(Math.floor(i * step), levels.length - 1)] ?? 0.15 + ); - // uses default styling, we use at other places return ( - { - isDismissedRef.current = true; - onRequestClose(); - }, - clickOutsideDeactivates: true, - allowOutsideClick: true, - fallbackFocus: () => containerRef.current!, - }} + -
- - Audio Message Recorder - { - if (isDismissedRef.current) return; - // closes the recorder and sends the audio file back to the parent component to be uploaded and sent as a message - onRecordingComplete(audioFile); - onWaveformUpdate(waveform); - onAudioLengthUpdate(audioLength); - }} - buttonBackgroundColor={color.SurfaceVariant.Container} - buttonHoverBackgroundColor={color.SurfaceVariant.ContainerHover} - iconColor={color.Primary.Main} - // icons for the recorder, we use Folds' icon library to keep the styling consistent with the rest of the app - customPauseIcon={} - customPlayIcon={} - customDeleteIcon={} - customStopIcon={} - customRepeatIcon={} - customResumeIcon={} + {/* Pulsing red dot */} +
+ + {/* Live waveform bars */} + + {bars.map((level, i) => ( +
- -
- + ))} +
+ + {/* Timer */} + + {formatTime(seconds)} + + ); -} +}); diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index b280cf5d..a531f173 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -24,6 +24,7 @@ import { ReactEditor } from 'slate-react'; import { Editor, Point, Range, Transforms } from 'slate'; import { Box, + color, config, Dialog, Icon, @@ -158,7 +159,8 @@ import { getVideoMsgContent, } from './msgContent'; import { CommandAutocomplete } from './CommandAutocomplete'; -import { AudioMessageRecorder } from './AudioMessageRecorder'; +import { AudioMessageRecorder, AudioMessageRecorderHandle } from './AudioMessageRecorder'; +import { AudioAttachmentPreview } from './AudioAttachmentPreview'; const getReplyContent = (replyDraft: IReplyDraft | undefined): IEventRelation => { if (!replyDraft) return {}; @@ -251,6 +253,18 @@ export const RoomInput = forwardRef( const [showAudioRecorder, setShowAudioRecorder] = useState(false); const [audioMsgWaveform, setAudioMsgWaveform] = useState(undefined); const [audioMsgLength, setAudioMsgLength] = useState(undefined); + // pendingAudioFileRef is a ref (not state) so its value is set synchronously + // before handleFiles → setSelectedFiles (Jotai) can trigger a render. + // Using useState here caused a render window where selectedFiles already contained + // the file but pendingAudioFile state was still null, letting UploadCardRenderer + // render for the audio file and trigger an upload-during-render state dispatch. + const pendingAudioFileRef = useRef(null); + const [pendingAudioUrl, setPendingAudioUrl] = useState(null); + const audioRecorderRef = useRef(null); + // Tracks when the mic button was pressed on mobile so we can distinguish + // a quick tap (toggle — user stops manually) from a long hold (send on release). + const micHoldStartRef = useRef(0); + const HOLD_THRESHOLD_MS = 400; const [autocompleteQuery, setAutocompleteQuery] = useState>(); const [isQuickTextReact, setQuickTextReact] = useState(false); @@ -421,6 +435,19 @@ export const RoomInput = forwardRef( const handleRemoveUpload = useCallback( (upload: TUploadContent | TUploadContent[]) => { const uploads = Array.isArray(upload) ? upload : [upload]; + // If the pending audio file is being removed (via UploadBoard's Remove button), + // clean up the object URL and reset audio preview state. + uploads.forEach((u) => { + if (u === pendingAudioFileRef.current) { + setPendingAudioUrl((url) => { + if (url) URL.revokeObjectURL(url); + return null; + }); + pendingAudioFileRef.current = null; + setAudioMsgWaveform(undefined); + setAudioMsgLength(undefined); + } + }); setSelectedFiles({ type: 'DELETE', item: selectedFiles.filter((f) => uploads.find((u) => u === f.file)), @@ -827,18 +854,35 @@ export const RoomInput = forwardRef( {Array.from(selectedFiles) .reverse() - .map((fileItem, index) => ( - - ))} + .map((fileItem, index) => { + // pendingAudioFileRef is a ref so it's available synchronously + // even in Jotai-triggered renders — UploadCardRenderer never + // renders for the audio file, preventing the upload-during-render + // setState warning on UploadBoardHeader. + if (fileItem.file === pendingAudioFileRef.current && pendingAudioUrl) { + return ( + + ); + } + return ( + + ); + })} )} @@ -1059,6 +1103,79 @@ export const RoomInput = forwardRef( } after={ <> + {/* ── Recording pill: grows into available space left of mic button ── */} + {showAudioRecorder && ( + setShowAudioRecorder(false)} + onRecordingComplete={(audioBlob) => { + const file = new File([audioBlob], `sable-audio-message-${Date.now()}.ogg`, { + type: audioBlob.type, + }); + // Set ref synchronously BEFORE handleFiles so the Jotai render + // that follows immediately sees it and skips UploadCardRenderer. + pendingAudioFileRef.current = file; + setPendingAudioUrl(URL.createObjectURL(audioBlob)); + handleFiles([file]); + setShowAudioRecorder(false); + }} + onAudioLengthUpdate={(len) => setAudioMsgLength(len)} + onWaveformUpdate={(w) => setAudioMsgWaveform(w)} + /> + )} + + {/* ── Mic button — always present; icon swaps to Stop while recording ── */} + { + if (mobileOrTablet()) return; // mobile handled via pointerdown/up + if (showAudioRecorder) { + audioRecorderRef.current?.stop(); + } else { + setShowAudioRecorder(true); + } + }} + onPointerDown={() => { + if (!mobileOrTablet()) return; + if (showAudioRecorder) return; // already recording — onClick will stop it + micHoldStartRef.current = Date.now(); + setShowAudioRecorder(true); + + // One-shot global listeners: the mic button stays mounted now but + // the ref is already populated by the time pointerup fires. + const cleanup = () => { + window.removeEventListener('pointerup', onUp); + window.removeEventListener('pointercancel', onCancel); + }; + const onUp = () => { + cleanup(); + const held = Date.now() - micHoldStartRef.current; + if (held >= HOLD_THRESHOLD_MS) { + audioRecorderRef.current?.stop(); + } + // Short tap → recorder stays open; tap stop-icon to finish + }; + const onCancel = () => { + cleanup(); + audioRecorderRef.current?.cancel(); + }; + window.addEventListener('pointerup', onUp); + window.addEventListener('pointercancel', onCancel); + }} + > + + + + {/* ── Toolbar toggle — always visible ── */} ( > - setShowAudioRecorder(!showAudioRecorder)} - > - - - {showAudioRecorder && ( - { - setShowAudioRecorder(false); - }} - onRecordingComplete={(audioBlob) => { - const file = new File( - [audioBlob], - `sable-audio-message-${Date.now()}.ogg`, - { - type: audioBlob.type, - } - ); - handleFiles([file]); - // Close the recorder after handling the file, to give some feedback that the recording was successful - setShowAudioRecorder(false); - }} - onAudioLengthUpdate={(len) => setAudioMsgLength(len)} - onWaveformUpdate={(w) => setAudioMsgWaveform(w)} - /> - } - /> - )} {(emojiBoardTab: EmojiBoardTab | undefined, setEmojiBoardTab) => ( localStorage.getItem('sable_debug') === '1'; +export const isDebug = (): boolean => + import.meta.env.DEV || localStorage.getItem('sable_debug') === '1'; type LogLevel = 'log' | 'warn' | 'error'; From 05e1d810a90279e85f42d5362be2f2aa1c54caa2 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 10:16:17 -0400 Subject: [PATCH 063/146] feat(push): instrument decryption relay with debugLogger for Sentry forwarding --- src/app/pages/client/ClientNonUIFeatures.tsx | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx index c4179c1b..541545da 100644 --- a/src/app/pages/client/ClientNonUIFeatures.tsx +++ b/src/app/pages/client/ClientNonUIFeatures.tsx @@ -45,6 +45,7 @@ import { resolveNotificationPreviewText, } from '$utils/notificationStyle'; import { mobileOrTablet } from '$utils/user-agent'; +import { createDebugLogger } from '$utils/debugLogger'; import { useSlidingSyncActiveRoom } from '$hooks/useSlidingSyncActiveRoom'; import { getSlidingSyncManager } from '$client/initMatrix'; import { NotificationBanner } from '$components/notification-banner'; @@ -52,6 +53,8 @@ import { useCallSignaling } from '$hooks/useCallSignaling'; import { getInboxInvitesPath } from '../pathUtils'; import { BackgroundNotifications } from './BackgroundNotifications'; +const pushRelayLog = createDebugLogger('push-relay'); + function clearMediaSessionQuickly(): void { if (!('mediaSession' in navigator)) return; // iOS registers the lock screen media player as a side-effect of @@ -639,6 +642,7 @@ function HandleDecryptPushEvent() { const { rawEvent } = data as { rawEvent: Record }; const eventId = rawEvent.event_id as string; const roomId = rawEvent.room_id as string; + const decryptStart = performance.now(); try { const mxEvent = new MatrixEvent(rawEvent as any); @@ -652,6 +656,14 @@ function HandleDecryptPushEvent() { if (room) senderName = getMemberDisplayName(room, sender) ?? senderName; } + const decryptMs = Math.round(performance.now() - decryptStart); + const visible = document.visibilityState === 'visible'; + pushRelayLog.info('notification', 'Push relay decryption succeeded', { + eventType: mxEvent.getType(), + decryptMs, + appVisible: visible, + }); + navigator.serviceWorker.controller?.postMessage({ type: 'pushDecryptResult', eventId, @@ -664,6 +676,11 @@ function HandleDecryptPushEvent() { }); } catch (err) { console.warn('[app] HandleDecryptPushEvent: failed to decrypt push event', err); + pushRelayLog.error( + 'notification', + 'Push relay decryption failed', + err instanceof Error ? err : new Error(String(err)) + ); navigator.serviceWorker.controller?.postMessage({ type: 'pushDecryptResult', eventId, From bf6d7ce4a6b3232900267a662363f70984d2ee59 Mon Sep 17 00:00:00 2001 From: hazre Date: Sun, 15 Mar 2026 00:59:34 +0100 Subject: [PATCH 064/146] fix: a lot more polish on voice messages --- package.json | 1 + pnpm-lock.yaml | 15 + .../components/upload-card/UploadCard.css.ts | 64 +- .../upload-card/UploadCardRenderer.tsx | 177 ++++- .../features/room/AudioAttachmentPreview.tsx | 194 ------ .../features/room/AudioMessageRecorder.css.ts | 121 ++++ .../features/room/AudioMessageRecorder.tsx | 242 ++++--- src/app/features/room/RoomInput.tsx | 130 ++-- src/app/features/room/msgContent.ts | 14 +- src/app/plugins/voice-recorder-kit/README.md | 492 -------------- .../voice-recorder-kit/VoiceRecorder.tsx | 620 ------------------ src/app/plugins/voice-recorder-kit/icons.tsx | 76 --- src/app/plugins/voice-recorder-kit/index.ts | 2 - src/app/plugins/voice-recorder-kit/types.ts | 41 -- .../voice-recorder-kit/useVoiceRecorder.ts | 25 +- src/app/state/room/roomInputDrafts.ts | 2 + 16 files changed, 613 insertions(+), 1603 deletions(-) delete mode 100644 src/app/features/room/AudioAttachmentPreview.tsx create mode 100644 src/app/features/room/AudioMessageRecorder.css.ts delete mode 100644 src/app/plugins/voice-recorder-kit/README.md delete mode 100644 src/app/plugins/voice-recorder-kit/VoiceRecorder.tsx delete mode 100644 src/app/plugins/voice-recorder-kit/icons.tsx diff --git a/package.json b/package.json index 371e7a97..14cd7c17 100644 --- a/package.json +++ b/package.json @@ -31,6 +31,7 @@ "@atlaskit/pragmatic-drag-and-drop-hitbox": "^1.1.0", "@fontsource-variable/nunito": "5.2.7", "@fontsource/space-mono": "5.2.9", + "@phosphor-icons/react": "^2.1.10", "@tanstack/react-query": "^5.90.21", "@tanstack/react-query-devtools": "^5.91.3", "@tanstack/react-virtual": "^3.13.19", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e0d64afd..a1c45c6d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -31,6 +31,9 @@ importers: '@fontsource/space-mono': specifier: 5.2.9 version: 5.2.9 + '@phosphor-icons/react': + specifier: ^2.1.10 + version: 2.1.10(react-dom@18.3.1(react@18.3.1))(react@18.3.1) '@tanstack/react-query': specifier: ^5.90.21 version: 5.90.21(react@18.3.1) @@ -1549,6 +1552,13 @@ packages: cpu: [x64] os: [win32] + '@phosphor-icons/react@2.1.10': + resolution: {integrity: sha512-vt8Tvq8GLjheAZZYa+YG/pW7HDbov8El/MANW8pOAz4eGxrwhnbfrQZq0Cp4q8zBEu8NIhHdnr+r8thnfRSNYA==} + engines: {node: '>=10'} + peerDependencies: + react: '>= 16.8' + react-dom: '>= 16.8' + '@pkgr/core@0.2.9': resolution: {integrity: sha512-QNqXyfVS2wm9hweSYD2O7F0G06uurj9kZ96TRQE5Y9hU7+tgdZwIkbAKc5Ocy1HxEY2kuDQa6cQ1WRs/O5LFKA==} engines: {node: ^12.20.0 || ^14.18.0 || >=16.0.0} @@ -6360,6 +6370,11 @@ snapshots: '@oxc-resolver/binding-win32-x64-msvc@11.19.1': optional: true + '@phosphor-icons/react@2.1.10(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + '@pkgr/core@0.2.9': {} '@poppinss/colors@4.1.6': diff --git a/src/app/components/upload-card/UploadCard.css.ts b/src/app/components/upload-card/UploadCard.css.ts index ad3caf10..d02cbe3f 100644 --- a/src/app/components/upload-card/UploadCard.css.ts +++ b/src/app/components/upload-card/UploadCard.css.ts @@ -1,6 +1,6 @@ import { style } from '@vanilla-extract/css'; import { RecipeVariants, recipe } from '@vanilla-extract/recipes'; -import { RadiiVariant, color, config } from 'folds'; +import { DefaultReset, RadiiVariant, color, config, toRem } from 'folds'; export const UploadCard = recipe({ base: { @@ -34,3 +34,65 @@ export const UploadCardError = style({ padding: `0 ${config.space.S100}`, color: color.Critical.Main, }); + +export const AudioPreviewContainer = style([ + DefaultReset, + { + backgroundColor: color.SurfaceVariant.Container, + border: `${config.borderWidth.B300} solid ${color.SurfaceVariant.ContainerLine}`, + borderRadius: config.radii.R400, + padding: config.space.S300, + width: '100%', + maxWidth: toRem(400), + boxSizing: 'border-box', + }, +]); + +export const AudioWaveformContainer = style([ + DefaultReset, + { + minHeight: 44, + cursor: 'pointer', + userSelect: 'none', + overflow: 'hidden', + }, +]); + +export const AudioWaveformBar = style([ + DefaultReset, + { + width: 2, + height: 3, + borderRadius: 1, + flexShrink: 0, + transition: 'background-color 40ms, opacity 40ms', + pointerEvents: 'none', + }, +]); + +export const AudioWaveformBarPlayed = style([ + DefaultReset, + { + backgroundColor: color.Secondary.Main, + opacity: 1, + }, +]); + +export const AudioWaveformBarUnplayed = style([ + DefaultReset, + { + backgroundColor: color.SurfaceVariant.OnContainer, + opacity: 0.5, + }, +]); + +export const AudioTimeDisplay = style([ + DefaultReset, + { + fontVariantNumeric: 'tabular-nums', + color: color.SurfaceVariant.OnContainer, + minWidth: toRem(30), + textAlign: 'right', + flexShrink: 0, + }, +]); diff --git a/src/app/components/upload-card/UploadCardRenderer.tsx b/src/app/components/upload-card/UploadCardRenderer.tsx index 55dbba3c..aa060835 100644 --- a/src/app/components/upload-card/UploadCardRenderer.tsx +++ b/src/app/components/upload-card/UploadCardRenderer.tsx @@ -1,4 +1,4 @@ -import { ReactNode, useEffect, useMemo, useState } from 'react'; +import { ReactNode, useEffect, useMemo, useRef, useState } from 'react'; import { Box, Chip, @@ -14,6 +14,7 @@ import { toRem, } from 'folds'; import { HTMLReactParserOptions } from 'html-react-parser'; +import { Play, Pause } from '@phosphor-icons/react'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { Opts as LinkifyOpts } from 'linkifyjs'; import { getReactCustomHtmlParser, LINKIFY_OPTS } from '$plugins/react-custom-html-parser'; @@ -27,6 +28,7 @@ import { roomUploadAtomFamily, TUploadItem, TUploadMetadata } from '$state/room/ import { useObjectURL } from '$hooks/useObjectURL'; import { useMediaConfig } from '$hooks/useMediaConfig'; import { UploadCard, UploadCardError, UploadCardProgress } from './UploadCard'; +import * as css from './UploadCard.css'; import { DescriptionEditor } from './UploadDescriptionEditor'; type PreviewImageProps = { @@ -71,6 +73,178 @@ function PreviewVideo({ fileItem }: PreviewVideoProps) { ); } +const BAR_COUNT = 44; + +function formatAudioTime(s: number): string { + const m = Math.floor(s / 60); + const sec = Math.floor(s % 60); + return `${m}:${sec.toString().padStart(2, '0')}`; +} + +type PreviewAudioProps = { + fileItem: TUploadItem; +}; +function PreviewAudio({ fileItem }: PreviewAudioProps) { + const { originalFile, metadata } = fileItem; + const audioUrl = useObjectURL(originalFile); + const { waveform, audioDuration } = metadata; + const duration = audioDuration ?? 0; + + const [isPlaying, setIsPlaying] = useState(false); + const [currentTime, setCurrentTime] = useState(0); + const audioRef = useRef(null); + const rafRef = useRef(null); + + const bars = useMemo(() => { + if (!waveform || waveform.length === 0) { + return Array(BAR_COUNT).fill(0.3); + } + const step = waveform.length / BAR_COUNT; + return Array.from({ length: BAR_COUNT }, (_, i) => waveform[Math.floor(i * step)] ?? 0); + }, [waveform]); + + const progress = duration > 0 ? Math.min(currentTime / duration, 1) : 0; + + useEffect(() => { + if (!audioUrl) { + return undefined; + } + const audio = new Audio(audioUrl); + audioRef.current = audio; + + audio.onended = () => { + setIsPlaying(false); + setCurrentTime(0); + if (rafRef.current !== null) { + cancelAnimationFrame(rafRef.current); + rafRef.current = null; + } + }; + + return () => { + audio.pause(); + if (rafRef.current !== null) { + cancelAnimationFrame(rafRef.current); + } + }; + }, [audioUrl]); + + const startRaf = (audio: HTMLAudioElement) => { + const tick = () => { + setCurrentTime(audio.currentTime); + rafRef.current = requestAnimationFrame(tick); + }; + rafRef.current = requestAnimationFrame(tick); + }; + + const stopRaf = () => { + if (rafRef.current !== null) { + cancelAnimationFrame(rafRef.current); + rafRef.current = null; + } + }; + + const handlePlayPause = () => { + const audio = audioRef.current; + if (!audio) return; + + if (isPlaying) { + audio.pause(); + setIsPlaying(false); + stopRaf(); + } else { + audio.play().catch(() => {}); + setIsPlaying(true); + startRaf(audio); + } + }; + + const handleScrubClick = (e: React.MouseEvent) => { + const audio = audioRef.current; + if (!audio || !duration) return; + const rect = e.currentTarget.getBoundingClientRect(); + const ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width)); + audio.currentTime = ratio * duration; + setCurrentTime(audio.currentTime); + }; + + const handleKeyDown = (e: React.KeyboardEvent) => { + const audio = audioRef.current; + if (!audio || !duration) return; + + const SEEK_STEP = 5; + let newTime = currentTime; + + if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') { + e.preventDefault(); + newTime = Math.max(0, currentTime - SEEK_STEP); + } else if (e.key === 'ArrowRight' || e.key === 'ArrowUp') { + e.preventDefault(); + newTime = Math.min(duration, currentTime + SEEK_STEP); + } else if (e.key === 'Home') { + e.preventDefault(); + newTime = 0; + } else if (e.key === 'End') { + e.preventDefault(); + newTime = duration; + } else { + return; + } + + audio.currentTime = newTime; + setCurrentTime(newTime); + }; + + return ( + + + {isPlaying ? : } + + + + {bars.map((level, i) => { + const barRatio = i / BAR_COUNT; + const played = barRatio <= progress; + return ( +
+ ); + })} + + + + {formatAudioTime(isPlaying ? currentTime : duration)} + + + ); +} + type MediaPreviewProps = { fileItem: TUploadItem; onSpoiler: (marked: boolean) => void; @@ -247,6 +421,7 @@ export function UploadCardRenderer({ )} + {fileItem.metadata.waveform && } {upload.status === UploadStatus.Idle && !fileSizeExceeded && ( )} diff --git a/src/app/features/room/AudioAttachmentPreview.tsx b/src/app/features/room/AudioAttachmentPreview.tsx deleted file mode 100644 index e054eb0b..00000000 --- a/src/app/features/room/AudioAttachmentPreview.tsx +++ /dev/null @@ -1,194 +0,0 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; -import { Box, Chip, Icon, Icons, IconButton, Text, color, config, toRem } from 'folds'; - -type AudioAttachmentPreviewProps = { - audioUrl: string; - waveform: number[]; - duration: number; // seconds - onDelete: () => void; -}; - -function formatTime(s: number): string { - const m = Math.floor(s / 60); - const sec = Math.floor(s % 60); - return `${m}:${sec.toString().padStart(2, '0')}`; -} - -const BAR_COUNT = 44; - -/** - * Attachment-area chip for a just-recorded voice message. - * - * Shows a play/pause button, a clickable waveform scrubber that fills - * with Primary colour as playback advances, a duration counter, and a - * delete button that matches the UploadBoard cancel chip style. - */ -export function AudioAttachmentPreview({ - audioUrl, - waveform, - duration, - onDelete, -}: AudioAttachmentPreviewProps) { - const [isPlaying, setIsPlaying] = useState(false); - const [currentTime, setCurrentTime] = useState(0); - const audioRef = useRef(null); - const rafRef = useRef(null); - - // Downsample waveform to BAR_COUNT display bars - const bars = Array.from({ length: BAR_COUNT }, (_, i) => { - const src = waveform.length > 0 ? waveform : Array(BAR_COUNT).fill(0.3); - const step = src.length / BAR_COUNT; - return src[Math.floor(i * step)] ?? 0; - }); - - const progress = duration > 0 ? Math.min(currentTime / duration, 1) : 0; - - // Animate current-time with rAF while playing for a smooth scrubber - const startRaf = useCallback((audio: HTMLAudioElement) => { - const tick = () => { - setCurrentTime(audio.currentTime); - rafRef.current = requestAnimationFrame(tick); - }; - rafRef.current = requestAnimationFrame(tick); - }, []); - - const stopRaf = useCallback(() => { - if (rafRef.current !== null) { - cancelAnimationFrame(rafRef.current); - rafRef.current = null; - } - }, []); - - useEffect(() => { - const audio = new Audio(audioUrl); - audioRef.current = audio; - - audio.onended = () => { - setIsPlaying(false); - setCurrentTime(0); - stopRaf(); - }; - - return () => { - audio.pause(); - stopRaf(); - }; - }, [audioUrl, stopRaf]); - - const handlePlayPause = useCallback(() => { - const audio = audioRef.current; - if (!audio) return; - - if (isPlaying) { - audio.pause(); - setIsPlaying(false); - stopRaf(); - } else { - audio.play().catch(() => {}); - setIsPlaying(true); - startRaf(audio); - } - }, [isPlaying, startRaf, stopRaf]); - - const handleScrubClick = useCallback( - (e: React.MouseEvent) => { - const audio = audioRef.current; - if (!audio || !duration) return; - const rect = e.currentTarget.getBoundingClientRect(); - const ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width)); - audio.currentTime = ratio * duration; - setCurrentTime(audio.currentTime); - }, - [duration] - ); - - return ( - - {/* Play / Pause */} - - - - - {/* Waveform scrubber */} - - {bars.map((level, i) => { - const barRatio = i / BAR_COUNT; - const played = barRatio <= progress; - return ( -
- ); - })} - - - {/* Time display: shows current position while playing, total when paused */} - - {formatTime(isPlaying ? currentTime : duration)} - - - {/* Delete — matches UploadBoardHeader "Remove" chip style */} - } - title="Remove voice message" - aria-label="Remove voice message" - /> - - ); -} diff --git a/src/app/features/room/AudioMessageRecorder.css.ts b/src/app/features/room/AudioMessageRecorder.css.ts new file mode 100644 index 00000000..44c7bcd0 --- /dev/null +++ b/src/app/features/room/AudioMessageRecorder.css.ts @@ -0,0 +1,121 @@ +import { keyframes, style } from '@vanilla-extract/css'; +import { DefaultReset, color, config, toRem } from 'folds'; + +const RecDotPulse = keyframes({ + '0%, 100%': { opacity: 1 }, + '50%': { opacity: 0.25 }, +}); + +const SlideOutLeft = keyframes({ + '0%': { transform: 'translateX(0)', opacity: 1 }, + '100%': { transform: 'translateX(-100%)', opacity: 0 }, +}); + +const Shake = keyframes({ + '0%, 100%': { transform: 'translateX(0)' }, + '20%': { transform: 'translateX(-4px)' }, + '40%': { transform: 'translateX(4px)' }, + '60%': { transform: 'translateX(-4px)' }, + '80%': { transform: 'translateX(4px)' }, +}); + +export const Container = style([ + DefaultReset, + { + minWidth: 0, + overflow: 'hidden', + padding: `0 ${config.space.S200}`, + touchAction: 'pan-y', + userSelect: 'none', + }, +]); + +export const ContainerCanceling = style({ + animation: `${SlideOutLeft} 200ms ease-out forwards`, +}); + +export const ContainerShake = style({ + animation: `${Shake} 300ms ease-out`, +}); + +export const RecDot = style([ + DefaultReset, + { + width: 7, + height: 7, + borderRadius: '50%', + backgroundColor: color.Critical.Main, + flexShrink: 0, + animation: `${RecDotPulse} 1.4s ease-in-out infinite`, + }, +]); + +export const WaveformContainer = style([ + DefaultReset, + { + height: 22, + overflow: 'hidden', + minWidth: 0, + }, +]); + +export const WaveformBar = style([ + DefaultReset, + { + width: 2, + height: 3, + borderRadius: 1, + backgroundColor: color.Primary.Main, + transition: 'height 70ms ease-out', + flexShrink: 0, + }, +]); + +export const Timer = style([ + DefaultReset, + { + fontVariantNumeric: 'tabular-nums', + color: color.Critical.Main, + minWidth: config.space.S300, + flexShrink: 0, + fontWeight: 600, + }, +]); + +export const CancelHint = style([ + DefaultReset, + { + position: 'absolute', + left: 0, + top: 0, + bottom: 0, + display: 'flex', + alignItems: 'center', + paddingLeft: config.space.S200, + color: color.Critical.Main, + fontSize: toRem(12), + fontWeight: 600, + opacity: 0, + transition: 'opacity 100ms ease-out', + pointerEvents: 'none', + }, +]); + +export const CancelHintVisible = style({ + opacity: 1, +}); + +export const SrOnly = style([ + DefaultReset, + { + position: 'absolute', + width: 1, + height: 1, + padding: 0, + margin: -1, + overflow: 'hidden', + clip: 'rect(0, 0, 0, 0)', + whiteSpace: 'nowrap', + borderWidth: 0, + }, +]); diff --git a/src/app/features/room/AudioMessageRecorder.tsx b/src/app/features/room/AudioMessageRecorder.tsx index dd5d3bab..7ac2e18c 100644 --- a/src/app/features/room/AudioMessageRecorder.tsx +++ b/src/app/features/room/AudioMessageRecorder.tsx @@ -1,7 +1,23 @@ -import { forwardRef, useCallback, useImperativeHandle, useRef } from 'react'; +import { + forwardRef, + useCallback, + useEffect, + useImperativeHandle, + useMemo, + useRef, + useState, +} from 'react'; import { useVoiceRecorder } from '$plugins/voice-recorder-kit'; import type { VoiceRecorderStopPayload } from '$plugins/voice-recorder-kit'; -import { Box, Text, color, config, toRem } from 'folds'; +import { mobileOrTablet } from '$utils/user-agent'; +import { Box, Text, IconButton, Icon, Icons } from 'folds'; +import * as css from './AudioMessageRecorder.css'; + +export type AudioRecordingCompletePayload = { + audioBlob: Blob; + waveform: number[]; + audioLength: number; +}; export type AudioMessageRecorderHandle = { stop: () => void; @@ -9,7 +25,7 @@ export type AudioMessageRecorderHandle = { }; type AudioMessageRecorderProps = { - onRecordingComplete: (audioBlob: Blob) => void; + onRecordingComplete: (payload: AudioRecordingCompletePayload) => void; onRequestClose: () => void; onWaveformUpdate: (waveform: number[]) => void; onAudioLengthUpdate: (length: number) => void; @@ -21,33 +37,20 @@ function formatTime(seconds: number): string { return `${m}:${s.toString().padStart(2, '0')}`; } -const KEYFRAMES = ` -@keyframes recDotPulse { - 0%, 100% { opacity: 1; } - 50% { opacity: 0.25; } -} -`; -if (typeof document !== 'undefined') { - const styleId = '__audio-recorder-keyframes'; - if (!document.getElementById(styleId)) { - const style = document.createElement('style'); - style.id = styleId; - style.textContent = KEYFRAMES; - document.head.appendChild(style); - } -} - export const AudioMessageRecorder = forwardRef< AudioMessageRecorderHandle, AudioMessageRecorderProps >(({ onRecordingComplete, onRequestClose, onWaveformUpdate, onAudioLengthUpdate }, ref) => { const isDismissedRef = useRef(false); - // Guard against React Strict Mode's double-invoke of the autoStart effect, - // which fires onstop with a ~110-byte blob before the user does anything. const userRequestedStopRef = useRef(false); + const [isCanceling, setIsCanceling] = useState(false); + const [isShaking, setIsShaking] = useState(false); + const [swipeX, setSwipeX] = useState(0); + const [showCancelHint, setShowCancelHint] = useState(false); + const [announcedTime, setAnnouncedTime] = useState(0); + const touchStartXRef = useRef(0); + const isSwipingRef = useRef(false); - // Keep stable refs for prop callbacks so useVoiceRecorder's internal - // useCallbacks never need to be recreated (which would reset the timer). const onRecordingCompleteRef = useRef(onRecordingComplete); onRecordingCompleteRef.current = onRecordingComplete; const onRequestCloseRef = useRef(onRequestClose); @@ -57,24 +60,24 @@ export const AudioMessageRecorder = forwardRef< const onAudioLengthUpdateRef = useRef(onAudioLengthUpdate); onAudioLengthUpdateRef.current = onAudioLengthUpdate; - // Stable stop handler — empty dep array intentional; live values via refs. - const stableOnStop = useCallback((payload: VoiceRecorderStopPayload) => { if (!userRequestedStopRef.current) return; if (isDismissedRef.current) return; - onRecordingCompleteRef.current(payload.audioFile); + onRecordingCompleteRef.current({ + audioBlob: payload.audioFile, + waveform: payload.waveform, + audioLength: payload.audioLength, + }); onWaveformUpdateRef.current(payload.waveform); onAudioLengthUpdateRef.current(payload.audioLength); }, []); - // Stable delete handler — empty dep array intentional; live values via refs. - const stableOnDelete = useCallback(() => { isDismissedRef.current = true; onRequestCloseRef.current(); }, []); - const { levels, seconds, handleStop, handleDelete } = useVoiceRecorder({ + const { levels, seconds, error, handleStop, handleDelete } = useVoiceRecorder({ autoStart: true, onStop: stableOnStop, onDelete: stableOnDelete, @@ -88,75 +91,140 @@ export const AudioMessageRecorder = forwardRef< const doCancel = useCallback(() => { if (isDismissedRef.current) return; - isDismissedRef.current = true; - handleDelete(); + setIsCanceling(true); + setTimeout(() => { + isDismissedRef.current = true; + handleDelete(); + }, 180); }, [handleDelete]); useImperativeHandle(ref, () => ({ stop: doStop, cancel: doCancel }), [doStop, doCancel]); - const BAR_COUNT = 28; - const step = Math.max(1, levels.length / BAR_COUNT); - const bars = Array.from( - { length: BAR_COUNT }, - (_, i) => levels[Math.min(Math.floor(i * step), levels.length - 1)] ?? 0.15 + useEffect(() => { + if (seconds > 0 && seconds % 30 === 0 && seconds !== announcedTime) { + setAnnouncedTime(seconds); + } + }, [seconds, announcedTime]); + + const CANCEL_THRESHOLD = 80; + + const handlePointerDown = useCallback((e: React.PointerEvent) => { + if (!mobileOrTablet()) return; + touchStartXRef.current = e.clientX; + isSwipingRef.current = true; + (e.target as HTMLElement).setPointerCapture(e.pointerId); + }, []); + + const handlePointerMove = useCallback((e: React.PointerEvent) => { + if (!isSwipingRef.current || !mobileOrTablet()) return; + const deltaX = e.clientX - touchStartXRef.current; + if (deltaX < 0) { + setSwipeX(Math.max(deltaX, -CANCEL_THRESHOLD - 20)); + setShowCancelHint(deltaX < -30); + } else { + setSwipeX(0); + setShowCancelHint(false); + } + }, []); + + const handlePointerUp = useCallback( + (e: React.PointerEvent) => { + if (!isSwipingRef.current || !mobileOrTablet()) return; + isSwipingRef.current = false; + (e.target as HTMLElement).releasePointerCapture(e.pointerId); + + const deltaX = e.clientX - touchStartXRef.current; + if (deltaX < -CANCEL_THRESHOLD) { + doCancel(); + } else if (deltaX < -30) { + setIsShaking(true); + setTimeout(() => setIsShaking(false), 300); + } + setSwipeX(0); + setShowCancelHint(false); + }, + [doCancel] ); - return ( - - {/* Pulsing red dot */} -
+ const BAR_COUNT = 28; + const bars = useMemo(() => { + const step = Math.max(1, levels.length / BAR_COUNT); + return Array.from( + { length: BAR_COUNT }, + (_, i) => levels[Math.min(Math.floor(i * step), levels.length - 1)] ?? 0.15 + ); + }, [levels]); - {/* Live waveform bars */} + const containerClassName = [ + css.Container, + isCanceling ? css.ContainerCanceling : null, + isShaking ? css.ContainerShake : null, + ] + .filter(Boolean) + .join(' '); + + return ( + <> + {error && ( + + {error} + + )} - {bars.map((level, i) => ( -
- ))} - +
- {/* Timer */} - - {formatTime(seconds)} - - + + {bars.map((level, i) => ( +
+ ))} + + + + {formatTime(seconds)} + + {announcedTime > 0 && announcedTime === seconds && ( + + Recording duration: {formatTime(announcedTime)} + + )} + + + + + + {showCancelHint && ( +
+ Release to cancel +
+ )} + + ); }); diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index a531f173..6b30f685 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -150,6 +150,7 @@ import { usePowerLevelsContext } from '$hooks/usePowerLevels'; import { useRoomCreators } from '$hooks/useRoomCreators'; import { useRoomPermissions } from '$hooks/useRoomPermissions'; import { AutocompleteNotice } from '$components/editor/autocomplete/AutocompleteNotice'; +import { Microphone, Stop } from '@phosphor-icons/react'; import { SchedulePickerDialog } from './schedule-send'; import * as css from './schedule-send/SchedulePickerDialog.css'; import { @@ -160,7 +161,6 @@ import { } from './msgContent'; import { CommandAutocomplete } from './CommandAutocomplete'; import { AudioMessageRecorder, AudioMessageRecorderHandle } from './AudioMessageRecorder'; -import { AudioAttachmentPreview } from './AudioAttachmentPreview'; const getReplyContent = (replyDraft: IReplyDraft | undefined): IEventRelation => { if (!replyDraft) return {}; @@ -251,18 +251,7 @@ export const RoomInput = forwardRef( const [toolbar, setToolbar] = useSetting(settingsAtom, 'editorToolbar'); const [showAudioRecorder, setShowAudioRecorder] = useState(false); - const [audioMsgWaveform, setAudioMsgWaveform] = useState(undefined); - const [audioMsgLength, setAudioMsgLength] = useState(undefined); - // pendingAudioFileRef is a ref (not state) so its value is set synchronously - // before handleFiles → setSelectedFiles (Jotai) can trigger a render. - // Using useState here caused a render window where selectedFiles already contained - // the file but pendingAudioFile state was still null, letting UploadCardRenderer - // render for the audio file and trigger an upload-during-render state dispatch. - const pendingAudioFileRef = useRef(null); - const [pendingAudioUrl, setPendingAudioUrl] = useState(null); const audioRecorderRef = useRef(null); - // Tracks when the mic button was pressed on mobile so we can distinguish - // a quick tap (toggle — user stops manually) from a long hold (send on release). const micHoldStartRef = useRef(0); const HOLD_THRESHOLD_MS = 400; const [autocompleteQuery, setAutocompleteQuery] = @@ -274,7 +263,7 @@ export const RoomInput = forwardRef( const [inputKey, setInputKey] = useState(0); const handleFiles = useCallback( - async (files: File[]) => { + async (files: File[], audioMeta?: { waveform: number[]; audioDuration: number }) => { setUploadBoard(true); const safeFiles = files.map(safeFile); const fileItems: TUploadItem[] = []; @@ -288,6 +277,8 @@ export const RoomInput = forwardRef( ...ef, metadata: { markedAsSpoiler: false, + waveform: audioMeta?.waveform, + audioDuration: audioMeta?.audioDuration, }, }) ); @@ -299,6 +290,8 @@ export const RoomInput = forwardRef( encInfo: undefined, metadata: { markedAsSpoiler: false, + waveform: audioMeta?.waveform, + audioDuration: audioMeta?.audioDuration, }, }) ); @@ -435,19 +428,6 @@ export const RoomInput = forwardRef( const handleRemoveUpload = useCallback( (upload: TUploadContent | TUploadContent[]) => { const uploads = Array.isArray(upload) ? upload : [upload]; - // If the pending audio file is being removed (via UploadBoard's Remove button), - // clean up the object URL and reset audio preview state. - uploads.forEach((u) => { - if (u === pendingAudioFileRef.current) { - setPendingAudioUrl((url) => { - if (url) URL.revokeObjectURL(url); - return null; - }); - pendingAudioFileRef.current = null; - setAudioMsgWaveform(undefined); - setAudioMsgLength(undefined); - } - }); setSelectedFiles({ type: 'DELETE', item: selectedFiles.filter((f) => uploads.find((u) => u === f.file)), @@ -480,7 +460,7 @@ export const RoomInput = forwardRef( return getVideoMsgContent(mx, fileItem, upload.mxc); } if (fileItem.file.type.startsWith('audio')) { - return getAudioMsgContent(fileItem, upload.mxc, audioMsgWaveform, audioMsgLength); + return getAudioMsgContent(fileItem, upload.mxc); } return getFileMsgContent(fileItem, upload.mxc); }); @@ -744,6 +724,10 @@ export const RoomInput = forwardRef( } if (isKeyHotkey('escape', evt)) { evt.preventDefault(); + if (showAudioRecorder) { + audioRecorderRef.current?.cancel(); + return; + } if (autocompleteQuery) { setAutocompleteQuery(undefined); return; @@ -751,7 +735,15 @@ export const RoomInput = forwardRef( setReplyDraft(undefined); } }, - [submit, roomId, setReplyDraft, enterForNewline, autocompleteQuery, isComposing] + [ + submit, + roomId, + setReplyDraft, + enterForNewline, + autocompleteQuery, + isComposing, + showAudioRecorder, + ] ); const handleKeyUp: KeyboardEventHandler = useCallback( @@ -854,35 +846,18 @@ export const RoomInput = forwardRef( {Array.from(selectedFiles) .reverse() - .map((fileItem, index) => { - // pendingAudioFileRef is a ref so it's available synchronously - // even in Jotai-triggered renders — UploadCardRenderer never - // renders for the audio file, preventing the upload-during-render - // setState warning on UploadBoardHeader. - if (fileItem.file === pendingAudioFileRef.current && pendingAudioUrl) { - return ( - - ); - } - return ( - - ); - })} + .map((fileItem, index) => ( + + ))} )} @@ -1108,19 +1083,22 @@ export const RoomInput = forwardRef( setShowAudioRecorder(false)} - onRecordingComplete={(audioBlob) => { - const file = new File([audioBlob], `sable-audio-message-${Date.now()}.ogg`, { - type: audioBlob.type, + onRecordingComplete={(payload) => { + const file = new File( + [payload.audioBlob], + `sable-audio-message-${Date.now()}.ogg`, + { + type: payload.audioBlob.type, + } + ); + handleFiles([file], { + waveform: payload.waveform, + audioDuration: payload.audioLength, }); - // Set ref synchronously BEFORE handleFiles so the Jotai render - // that follows immediately sees it and skips UploadCardRenderer. - pendingAudioFileRef.current = file; - setPendingAudioUrl(URL.createObjectURL(audioBlob)); - handleFiles([file]); setShowAudioRecorder(false); }} - onAudioLengthUpdate={(len) => setAudioMsgLength(len)} - onWaveformUpdate={(w) => setAudioMsgWaveform(w)} + onAudioLengthUpdate={() => {}} + onWaveformUpdate={() => {}} /> )} @@ -1149,10 +1127,7 @@ export const RoomInput = forwardRef( // One-shot global listeners: the mic button stays mounted now but // the ref is already populated by the time pointerup fires. - const cleanup = () => { - window.removeEventListener('pointerup', onUp); - window.removeEventListener('pointercancel', onCancel); - }; + let cleanup: () => void; const onUp = () => { cleanup(); const held = Date.now() - micHoldStartRef.current; @@ -1165,14 +1140,19 @@ export const RoomInput = forwardRef( cleanup(); audioRecorderRef.current?.cancel(); }; + cleanup = () => { + window.removeEventListener('pointerup', onUp); + window.removeEventListener('pointercancel', onCancel); + }; window.addEventListener('pointerup', onUp); window.addEventListener('pointercancel', onCancel); }} > - + {showAudioRecorder ? ( + + ) : ( + + )} {/* ── Toolbar toggle — always visible ── */} diff --git a/src/app/features/room/msgContent.ts b/src/app/features/room/msgContent.ts index 5536f7d0..7da6d955 100644 --- a/src/app/features/room/msgContent.ts +++ b/src/app/features/room/msgContent.ts @@ -148,13 +148,9 @@ export type AudioMsgContent = IContent & { audioLength?: number; }; -export const getAudioMsgContent = ( - item: TUploadItem, - mxc: string, - waveform?: number[], - audioLength?: number -): AudioMsgContent => { - const { file, encInfo } = item; +export const getAudioMsgContent = (item: TUploadItem, mxc: string): AudioMsgContent => { + const { file, encInfo, metadata } = item; + const { waveform, audioDuration, markedAsSpoiler } = metadata; const content: IContent = { msgtype: MsgType.Audio, filename: file.name, @@ -166,8 +162,8 @@ export const getAudioMsgContent = ( size: file.size, }, 'org.matrix.msc1767.audio': { - waveform: waveform?.map((v) => Math.round(v * 1024)), // scale waveform values to fit in 10 bits (0-1024) for more efficient storage, as per MSC1767 spec - duration: item.metadata.markedAsSpoiler || !audioLength ? 0 : audioLength * 1000, // if marked as spoiler, set duration to 0 to hide it in clients that support msc1767 + waveform: waveform?.map((v) => Math.round(v * 1024)), + duration: markedAsSpoiler || !audioDuration ? 0 : audioDuration * 1000, }, }; if (encInfo) { diff --git a/src/app/plugins/voice-recorder-kit/README.md b/src/app/plugins/voice-recorder-kit/README.md deleted file mode 100644 index 49b9edd3..00000000 --- a/src/app/plugins/voice-recorder-kit/README.md +++ /dev/null @@ -1,492 +0,0 @@ -# react-voice-recorder-kit - -A lightweight React library for voice recording with audio waveform visualization and no UI framework dependencies - -* No UI framework dependencies (Pure React + Inline CSS) -* Animated audio waveform visualization (40 bars) -* Ready-to-use component -* Fully customizable hook -* TypeScript support -* Compatible with Next.js, Vite, CRA, and more - ---- - -## Screenshots - -### Initial State (Ready to Record) -

- Initial State -

- -### Recording in Progress -![Recording](assets/Screenshot%202025-12-05%20173347.png) - -### Paused State -![Paused](assets/Screenshot%202025-12-05%20173407.png) - -### Recorded Audio Ready to Play (Custom Styled) -![Completed Recording Custom](assets/Screenshot%202025-12-05%20173519.png) - ---- - -## Installation - -```bash -npm install react-voice-recorder-kit -# or -pnpm add react-voice-recorder-kit -# or -yarn add react-voice-recorder-kit -``` - -Requires **React 18+** - ---- - -## Quick Start (Using Component) - -```tsx -'use client' - -import { useState } from 'react' -import { VoiceRecorder } from 'react-voice-recorder-kit' - -export default function Page() { - const [file, setFile] = useState(null) - const [url, setUrl] = useState(null) - const [waveform, setWaveform] = useState([]) - const [audioLength, setAudioLength] = useState(0) - - return ( -
-

React Voice Recorder Kit

- - { - setFile(audioFile) - setUrl(audioUrl) - setWaveform(waveform) - setAudioLength(audioLength) - }} - onDelete={() => { - setFile(null) - setUrl(null) - setWaveform([]) - setAudioLength(0) - }} - /> - - {url && ( -
-
- )} -
- ) -} -``` - ---- - -## Usage in Next.js (App Router) - -```tsx -'use client' - -import { VoiceRecorder } from 'react-voice-recorder-kit' - -export default function VoicePage() { - return ( -
- -
- ) -} -``` - ---- - -## Component API - -### Main Props - -| Prop | Type | Default | Description | -| --------- | --------------------------------- | --------- | ---------------------------------------------- | -| autoStart | boolean | true | Auto-start recording on mount | -| onStop | (payload: { audioFile: Blob; audioUrl: string; waveform: number[]; audioLength: number }) => void | undefined | Callback after recording stops (all values batched) | -| onDelete | () => void | undefined | Callback after recording is deleted | -| width | string \| number | '100%' | Component width | -| height | string \| number | undefined | Component height | -| style | CSSProperties | undefined | Additional styles for container | - -### Styling Props - -| Prop | Type | Default | Description | -| --------------------------- | --------------------------------------- | ------------------------------------------------------------ | ------------------------------------ | -| backgroundColor | string | '#ffffff' | Background color | -| borderColor | string | '#e5e7eb' | Border color | -| borderRadius | string \| number | 4 | Border radius | -| padding | string \| number | '6px 10px' | Internal padding | -| gap | string \| number | 8 | Gap between elements | -| recordingIndicatorColor | string | '#ef4444' | Recording indicator color | -| idleIndicatorColor | string | '#9ca3af' | Idle indicator color | -| timeTextColor | string | undefined | Time text color | -| timeFontSize | string \| number | 12 | Time font size | -| timeFontWeight | string \| number | 500 | Time font weight | -| timeFontFamily | string | 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif' | Time font family | -| visualizerBarColor | string \| (level: number, index: number) => string | '#4b5563' | Waveform bar color | -| visualizerBarWidth | number | 3 | Waveform bar width | -| visualizerBarGap | number | 4 | Gap between bars | -| visualizerBarHeight | number | 40 | Waveform bar height | -| visualizerHeight | number | 40 | Total waveform height | -| buttonSize | number | 28 | Button size | -| buttonBackgroundColor | string | '#ffffff' | Button background color | -| buttonBorderColor | string | '#e5e7eb' | Button border color | -| buttonBorderRadius | string \| number | 999 | Button border radius | -| buttonHoverBackgroundColor | string | undefined | Button hover background color | -| buttonGap | number | 4 | Gap between buttons | -| errorTextColor | string | '#dc2626' | Error text color | -| errorFontSize | string \| number | 10 | Error font size | -| errorFontFamily | string | 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif' | Error font family | -| iconSize | number | 18 | Icon size | -| iconColor | string | undefined | Icon color | - -### Custom Icon Props - -| Prop | Type | Default | Description | -| --------------- | --------- | --------- | ------------------------ | -| customPlayIcon | ReactNode | undefined | Custom play icon | -| customPauseIcon | ReactNode | undefined | Custom pause icon | -| customStopIcon | ReactNode | undefined | Custom stop icon | -| customResumeIcon| ReactNode | undefined | Custom resume icon | -| customDeleteIcon| ReactNode | undefined | Custom delete icon | -| customRepeatIcon| ReactNode | undefined | Custom repeat icon | - ---- - -## Component Usage Examples - -### Example 1: Simple Usage - -```tsx -import { VoiceRecorder } from 'react-voice-recorder-kit' - -function SimpleRecorder() { - return -} -``` - -### Example 2: Custom Styling - -```tsx -import { VoiceRecorder } from 'react-voice-recorder-kit' - -function CustomStyledRecorder() { - return ( - - ) -} -``` - -### Example 3: Using with Callbacks - -```tsx -import { useState } from 'react' -import { VoiceRecorder } from 'react-voice-recorder-kit' - -function RecorderWithCallbacks() { - const [audioFile, setAudioFile] = useState(null) - - return ( - { - if (audioFile instanceof File) { - console.log('Recording stopped:', audioFile.name) - } - console.log('Audio length (s):', audioLength) - console.log('Waveform points:', waveform.length) - setAudioFile(audioFile) - }} - onDelete={() => { - console.log('Recording deleted') - setAudioFile(null) - }} - /> - ) -} -``` - -### Example 4: Dynamic Color Waveform - -```tsx -import { VoiceRecorder } from 'react-voice-recorder-kit' - -function DynamicColorRecorder() { - return ( - { - const hue = (level * 120).toString() - return `hsl(${hue}, 70%, 50%)` - }} - /> - ) -} -``` - ---- - -## Using the Hook (useVoiceRecorder) - -For full control over the UI, you can use the hook directly. - -### Import - -```ts -import { useVoiceRecorder } from 'react-voice-recorder-kit' -``` - -### Options - -```ts -type UseVoiceRecorderOptions = { - autoStart?: boolean - onStop?: (payload: { audioFile: Blob; audioUrl: string; waveform: number[]; audioLength: number }) => void - onDelete?: () => void -} -``` - -### Return Values - -```ts -type UseVoiceRecorderReturn = { - state: RecorderState - isRecording: boolean - isStopped: boolean - isTemporaryStopped: boolean - isPlaying: boolean - isPaused: boolean - seconds: number - levels: number[] - error: string | null - audioUrl: string | null - audioFile: File | null - waveform: number[] | null - start: () => void - handlePause: () => void - handleStopTemporary: () => void - handleStop: () => void - handleResume: () => void - handlePreviewPlay: () => void - handlePlay: () => void - handleRestart: () => void - handleDelete: () => void - handleRecordAgain: () => void -} -``` - -| Property | Type | Description | -| ----------------- | -------------- | ---------------------------------------------- | -| state | RecorderState | Current state: 'idle' \| 'recording' \| 'paused' \| 'reviewing' \| 'playing' | -| isRecording | boolean | Is currently recording | -| isStopped | boolean | Is recording stopped | -| isTemporaryStopped| boolean | Is recording temporarily stopped | -| isPlaying | boolean | Is currently playing | -| isPaused | boolean | Is recording paused | -| seconds | number | Time in seconds | -| levels | number[] | Array of 40 audio levels (0 to 1) | -| error | string \| null | Error message if any | -| audioUrl | string \| null | URL of recorded audio file | -| audioFile | File \| null | Recorded audio file | -| waveform | number[] \| null | Downsampled waveform points for the recording | -| start | () => void | Start recording | -| handlePause | () => void | Pause recording | -| handleStopTemporary| () => void | Temporary stop and review | -| handleStop | () => void | Stop and save recording | -| handleResume | () => void | Resume recording after pause | -| handlePreviewPlay | () => void | Play preview (in paused state) | -| handlePlay | () => void | Play recorded file | -| handleRestart | () => void | Restart recording | -| handleDelete | () => void | Delete recording and return to initial state | -| handleRecordAgain | () => void | Record again (same as handleRestart) | - ---- - -## Complete Hook Usage Example - -```tsx -'use client' - -import { useVoiceRecorder } from 'react-voice-recorder-kit' - -export default function CustomRecorder() { - const { - state, - isRecording, - isPaused, - isStopped, - isPlaying, - seconds, - levels, - audioUrl, - audioFile, - error, - start, - handlePause, - handleResume, - handleStop, - handlePlay, - handleDelete, - handleRestart - } = useVoiceRecorder({ autoStart: false }) - - const formatTime = (secs: number) => { - const minutes = Math.floor(secs / 60) - const sec = secs % 60 - return `${minutes}:${sec.toString().padStart(2, '0')}` - } - - return ( -
-

Custom Voice Recorder

- -
- Status: {state} | Time: {formatTime(seconds)} -
- -
- {!isRecording && !isStopped && ( - - )} - - {isRecording && !isPaused && ( - <> - - - - - )} - - {isPaused && ( - <> - - - - - )} - - {isStopped && audioUrl && ( - <> - - - - - )} -
- - {error && ( -
- {error} -
- )} - -
- {levels.map((level, index) => { - const height = 5 + level * 35 - return ( -
- ) - })} -
- - {audioUrl && ( -
-
- )} -
- ) -} -``` - ---- - -## Recording States (RecorderState) - -The component and hook have 5 different states: - -- **idle**: Initial state, ready to start -- **recording**: Currently recording -- **paused**: Recording paused (can be resumed) -- **reviewing**: Recording completed and under review -- **playing**: Playing recorded file - ---- - -## Features - -* Voice recording using MediaRecorder API -* Animated audio waveform visualization during recording and playback -* Support for pause and resume -* Support for playing recorded files -* Time display in MM:SS format -* Error handling and error message display -* Ready-to-use UI with control buttons -* Fully customizable styling and sizing -* No external dependencies -* Support for custom icons -* Dynamic color waveforms - ---- - -## Important Notes - -1. Requires microphone access in the browser -2. Recorded files are saved in WebM format -3. In paused state, you can play a preview of the recording -4. You can dynamically set bar colors using `visualizerBarColor` -5. All created URLs are automatically cleaned up - ---- - -## License - -MIT - -(orignal by Mohammadreza Fallahfaal: https://github.com/mohamad-fallah/react-voice-recorder-kit) diff --git a/src/app/plugins/voice-recorder-kit/VoiceRecorder.tsx b/src/app/plugins/voice-recorder-kit/VoiceRecorder.tsx deleted file mode 100644 index a51f634a..00000000 --- a/src/app/plugins/voice-recorder-kit/VoiceRecorder.tsx +++ /dev/null @@ -1,620 +0,0 @@ -import type { CSSProperties } from 'react'; -import { useMemo, useRef, useEffect, useState } from 'react'; -import { useVoiceRecorder } from './useVoiceRecorder'; -import type { VoiceRecorderProps } from './types'; -import { PlayIcon, PauseIcon, StopIcon, RepeatIcon, DeleteIcon, ResumeIcon } from './icons'; - -function VoiceRecorder(props: VoiceRecorderProps) { - const { - width, - height, - style, - backgroundColor = '#ffffff', - borderColor = '#e5e7eb', - borderRadius = 4, - padding = '6px 10px', - gap = 8, - recordingIndicatorColor = '#ef4444', - idleIndicatorColor = '#9ca3af', - timeTextColor, - timeFontSize = 12, - timeFontWeight = 500, - timeFontFamily = 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif', - visualizerBarColor = '#4b5563', - visualizerBarWidth = 3, - visualizerBarGap = 4, - visualizerBarHeight = 40, - visualizerHeight = 40, - buttonSize = 28, - buttonBackgroundColor = '#ffffff', - buttonBorderColor = '#e5e7eb', - buttonBorderRadius = 999, - buttonHoverBackgroundColor, - buttonGap = 4, - errorTextColor = '#dc2626', - errorFontSize = 10, - errorFontFamily = 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif', - customPlayIcon, - customPauseIcon, - customStopIcon, - customResumeIcon, - customDeleteIcon, - customRepeatIcon, - iconSize = 18, - iconColor, - ...recorderOptions - } = props; - - const { - state, - isRecording, - isStopped, - isPlaying, - seconds, - levels, - error, - handlePause, - handleStopTemporary, - handleStop, - handleResume, - handlePreviewPlay, - handlePlay, - handleRestart, - handleDelete, - } = useVoiceRecorder(recorderOptions); - - const containerRef = useRef(null); - const [visualizerWidth, setVisualizerWidth] = useState(0); - const visualizerRef = useRef(null); - - useEffect(() => { - const updateWidth = () => { - if (visualizerRef.current) { - const availableWidth = visualizerRef.current.offsetWidth; - setVisualizerWidth(Math.max(0, availableWidth)); - } - }; - - updateWidth(); - const resizeObserver = new ResizeObserver(updateWidth); - if (visualizerRef.current) { - resizeObserver.observe(visualizerRef.current); - } - - return () => { - resizeObserver.disconnect(); - }; - }, [width, isStopped, error]); - - const formattedTime = useMemo(() => { - const minutes = Math.floor(seconds / 60); - const secs = seconds % 60; - return `${minutes}:${secs.toString().padStart(2, '0')}`; - }, [seconds]); - - const barWidth = visualizerBarWidth; - const barGap = visualizerBarGap; - - const maxBars = useMemo(() => { - if (visualizerWidth <= 0) { - return Math.max(levels.length, 40); - } - const calculatedBars = Math.floor(visualizerWidth / (barWidth + barGap)); - return Math.max(calculatedBars, 1); - }, [visualizerWidth, levels.length, barWidth, barGap]); - - const displayedLevels = useMemo(() => { - if (maxBars <= 0 || levels.length === 0) { - return Array.from({ length: Math.max(maxBars, 40) }, () => 0.15); - } - - if (maxBars <= levels.length) { - const step = levels.length / maxBars; - return Array.from({ length: maxBars }, (_, i) => { - const start = Math.floor(i * step); - const end = Math.floor((i + 1) * step); - const slice = levels.slice(start, end); - return slice.length > 0 ? Math.max(...slice) : 0.15; - }); - } - - const step = (levels.length - 1) / (maxBars - 1); - return Array.from({ length: maxBars }, (_, i) => { - const position = i * step; - const lowerIndex = Math.floor(position); - const upperIndex = Math.min(Math.ceil(position), levels.length - 1); - const fraction = position - lowerIndex; - - if (lowerIndex === upperIndex) { - return levels[lowerIndex] || 0.15; - } - - return ( - (levels[lowerIndex] || 0.15) * (1 - fraction) + (levels[upperIndex] || 0.15) * fraction - ); - }); - }, [levels, maxBars]); - - const containerStyle: CSSProperties = useMemo( - () => ({ - display: 'flex', - alignItems: 'center', - gap: typeof gap === 'number' ? `${gap}px` : gap, - backgroundColor, - borderRadius: typeof borderRadius === 'number' ? `${borderRadius}px` : borderRadius, - border: `1px solid ${borderColor}`, - padding: typeof padding === 'number' ? `${padding}px` : padding, - width: width ?? '100%', - height, - boxSizing: 'border-box', - ...style, - }), - [width, height, style, backgroundColor, borderColor, borderRadius, padding, gap] - ); - - return ( -
- - - {formattedTime} - -
- {displayedLevels.map((level) => ( - - ))} -
- - {state === 'recording' && ( -
- - - -
- )} - - {state === 'paused' && ( -
- - - - -
- )} - - {state === 'reviewing' && ( -
- - - -
- )} - - {state === 'playing' && ( -
- -
- )} - - {error && ( - - {error} - - )} -
- ); -} - -export default VoiceRecorder; diff --git a/src/app/plugins/voice-recorder-kit/icons.tsx b/src/app/plugins/voice-recorder-kit/icons.tsx deleted file mode 100644 index 29248a00..00000000 --- a/src/app/plugins/voice-recorder-kit/icons.tsx +++ /dev/null @@ -1,76 +0,0 @@ -import type { FC } from 'react'; - -export const PlayIcon: FC<{ size?: number }> = function ({ size = 18 }) { - return ( - - - - - ); -}; - -export const ResumeIcon: FC<{ size?: number }> = function ({ size = 18 }) { - return ( - - - - ); -}; - -export const PauseIcon: FC<{ size?: number }> = function ({ size = 18 }) { - return ( - - - - - ); -}; - -export const StopIcon: FC<{ size?: number }> = function ({ size = 18 }) { - return ( - - - - ); -}; - -export const DeleteIcon: FC<{ size?: number }> = function ({ size = 18 }) { - return ( - - - - - - - - ); -}; - -export const RepeatIcon: FC<{ size?: number }> = function ({ size = 18 }) { - return ( - - - - ); -}; diff --git a/src/app/plugins/voice-recorder-kit/index.ts b/src/app/plugins/voice-recorder-kit/index.ts index 00564f2b..00e2e4d7 100644 --- a/src/app/plugins/voice-recorder-kit/index.ts +++ b/src/app/plugins/voice-recorder-kit/index.ts @@ -1,9 +1,7 @@ export { useVoiceRecorder } from './useVoiceRecorder'; -export { default as VoiceRecorder } from './VoiceRecorder'; export type { UseVoiceRecorderOptions, UseVoiceRecorderReturn, RecorderState, - VoiceRecorderProps, VoiceRecorderStopPayload, } from './types'; diff --git a/src/app/plugins/voice-recorder-kit/types.ts b/src/app/plugins/voice-recorder-kit/types.ts index 42cccd27..95d42877 100644 --- a/src/app/plugins/voice-recorder-kit/types.ts +++ b/src/app/plugins/voice-recorder-kit/types.ts @@ -1,5 +1,3 @@ -import type { CSSProperties, ReactNode } from 'react'; - export type RecorderState = 'idle' | 'recording' | 'paused' | 'reviewing' | 'playing'; export type VoiceRecorderStopPayload = { @@ -39,42 +37,3 @@ export type UseVoiceRecorderReturn = { handleDelete: () => void; handleRecordAgain: () => void; }; - -export type VoiceRecorderProps = UseVoiceRecorderOptions & { - width?: string | number; - height?: string | number; - style?: CSSProperties; - backgroundColor?: string; - borderColor?: string; - borderRadius?: string | number; - padding?: string | number; - gap?: string | number; - recordingIndicatorColor?: string; - idleIndicatorColor?: string; - timeTextColor?: string; - timeFontSize?: string | number; - timeFontWeight?: string | number; - timeFontFamily?: string; - visualizerBarColor?: string | ((level: number, index: number) => string); - visualizerBarWidth?: number; - visualizerBarGap?: number; - visualizerBarHeight?: number; - visualizerHeight?: number; - buttonSize?: number; - buttonBackgroundColor?: string; - buttonBorderColor?: string; - buttonBorderRadius?: string | number; - buttonHoverBackgroundColor?: string; - buttonGap?: number; - errorTextColor?: string; - errorFontSize?: string | number; - errorFontFamily?: string; - customPlayIcon?: ReactNode; - customPauseIcon?: ReactNode; - customStopIcon?: ReactNode; - customResumeIcon?: ReactNode; - customDeleteIcon?: ReactNode; - customRepeatIcon?: ReactNode; - iconSize?: number; - iconColor?: string; -}; diff --git a/src/app/plugins/voice-recorder-kit/useVoiceRecorder.ts b/src/app/plugins/voice-recorder-kit/useVoiceRecorder.ts index 45476246..1b3ea8a1 100644 --- a/src/app/plugins/voice-recorder-kit/useVoiceRecorder.ts +++ b/src/app/plugins/voice-recorder-kit/useVoiceRecorder.ts @@ -9,6 +9,15 @@ import type { const BAR_COUNT = 40; const WAVEFORM_POINT_COUNT = 100; +let sharedAudioContext: AudioContext | null = null; + +function getSharedAudioContext(): AudioContext { + if (!sharedAudioContext || sharedAudioContext.state === 'closed') { + sharedAudioContext = new AudioContext(); + } + return sharedAudioContext; +} + // downsample an array of samples to a target count by averaging blocks of samples together function downsampleWaveform(samples: number[], targetCount: number): number[] { if (samples.length === 0) return Array.from({ length: targetCount }, () => 0); @@ -86,7 +95,9 @@ export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoic } frameCountRef.current = 0; if (audioContextRef.current) { - audioContextRef.current.close().catch(() => {}); + if (audioContextRef.current.state !== 'closed') { + audioContextRef.current.suspend().catch(() => {}); + } audioContextRef.current = null; } analyserRef.current = null; @@ -188,7 +199,7 @@ export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoic const setupAudioGraph = useCallback( (stream: MediaStream) => { - const audioContext = new AudioContext(); + const audioContext = getSharedAudioContext(); audioContextRef.current = audioContext; const source = audioContext.createMediaStreamSource(stream); const analyser = audioContext.createAnalyser(); @@ -199,7 +210,9 @@ export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoic analyserRef.current = analyser; dataArrayRef.current = dataArray; source.connect(analyser); - audioContext.resume().catch(() => {}); + if (audioContext.state === 'suspended') { + audioContext.resume().catch(() => {}); + } animateLevels(); }, [animateLevels] @@ -207,7 +220,7 @@ export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoic const setupPlaybackGraph = useCallback( (audio: HTMLAudioElement) => { - const audioContext = new AudioContext(); + const audioContext = getSharedAudioContext(); audioContextRef.current = audioContext; const source = audioContext.createMediaElementSource(audio); const analyser = audioContext.createAnalyser(); @@ -219,7 +232,9 @@ export function useVoiceRecorder(options: UseVoiceRecorderOptions = {}): UseVoic dataArrayRef.current = dataArray; source.connect(analyser); analyser.connect(audioContext.destination); - audioContext.resume().catch(() => {}); + if (audioContext.state === 'suspended') { + audioContext.resume().catch(() => {}); + } animateLevels(); }, [animateLevels] diff --git a/src/app/state/room/roomInputDrafts.ts b/src/app/state/room/roomInputDrafts.ts index 51c3cfaf..4b167f22 100644 --- a/src/app/state/room/roomInputDrafts.ts +++ b/src/app/state/room/roomInputDrafts.ts @@ -9,6 +9,8 @@ import { createListAtom } from '$state/list'; export type TUploadMetadata = { markedAsSpoiler: boolean; + waveform?: number[]; + audioDuration?: number; }; export type TUploadItem = { From 7e76985ebd806d8336747e89c023a68a8e904192 Mon Sep 17 00:00:00 2001 From: hazre Date: Sun, 15 Mar 2026 00:59:34 +0100 Subject: [PATCH 065/146] fix: more polish on voice messages --- .../features/room/AudioMessageRecorder.css.ts | 5 ++- .../features/room/AudioMessageRecorder.tsx | 14 +------- src/app/features/room/RoomInput.tsx | 32 +++++++++++-------- 3 files changed, 21 insertions(+), 30 deletions(-) diff --git a/src/app/features/room/AudioMessageRecorder.css.ts b/src/app/features/room/AudioMessageRecorder.css.ts index 44c7bcd0..47b16584 100644 --- a/src/app/features/room/AudioMessageRecorder.css.ts +++ b/src/app/features/room/AudioMessageRecorder.css.ts @@ -22,9 +22,9 @@ const Shake = keyframes({ export const Container = style([ DefaultReset, { + flexGrow: 1, minWidth: 0, overflow: 'hidden', - padding: `0 ${config.space.S200}`, touchAction: 'pan-y', userSelect: 'none', }, @@ -86,12 +86,11 @@ export const CancelHint = style([ DefaultReset, { position: 'absolute', - left: 0, + left: config.space.S200, top: 0, bottom: 0, display: 'flex', alignItems: 'center', - paddingLeft: config.space.S200, color: color.Critical.Main, fontSize: toRem(12), fontWeight: 600, diff --git a/src/app/features/room/AudioMessageRecorder.tsx b/src/app/features/room/AudioMessageRecorder.tsx index 7ac2e18c..95c130f1 100644 --- a/src/app/features/room/AudioMessageRecorder.tsx +++ b/src/app/features/room/AudioMessageRecorder.tsx @@ -10,7 +10,7 @@ import { import { useVoiceRecorder } from '$plugins/voice-recorder-kit'; import type { VoiceRecorderStopPayload } from '$plugins/voice-recorder-kit'; import { mobileOrTablet } from '$utils/user-agent'; -import { Box, Text, IconButton, Icon, Icons } from 'folds'; +import { Box, Text } from 'folds'; import * as css from './AudioMessageRecorder.css'; export type AudioRecordingCompletePayload = { @@ -203,18 +203,6 @@ export const AudioMessageRecorder = forwardRef< )} - - - - {showCancelHint && (
( editableName="RoomInput" editor={editor} key={inputKey} - placeholder="Send a message..." + placeholder={showAudioRecorder && mobileOrTablet() ? '' : 'Send a message...'} onKeyDown={handleKeyDown} onKeyUp={handleKeyUp} onPaste={handlePaste} @@ -1065,20 +1065,21 @@ export const RoomInput = forwardRef( } before={ - pickFile('*')} - variant="SurfaceVariant" - size="300" - radii="300" - title="Upload File" - aria-label="Upload and attach a File" - > - - + !(showAudioRecorder && mobileOrTablet()) && ( + pickFile('*')} + variant="SurfaceVariant" + size="300" + radii="300" + title="Upload File" + aria-label="Upload and attach a File" + > + + + ) } after={ <> - {/* ── Recording pill: grows into available space left of mic button ── */} {showAudioRecorder && ( ( aria-label={showAudioRecorder ? 'Stop recording' : 'Record audio message'} aria-pressed={showAudioRecorder} onClick={() => { - if (mobileOrTablet()) return; // mobile handled via pointerdown/up + if (mobileOrTablet() && showAudioRecorder) { + audioRecorderRef.current?.stop(); + return; + } + if (mobileOrTablet()) return; if (showAudioRecorder) { audioRecorderRef.current?.stop(); } else { @@ -1155,7 +1160,6 @@ export const RoomInput = forwardRef( )} - {/* ── Toolbar toggle — always visible ── */} Date: Mon, 16 Mar 2026 15:40:22 +0100 Subject: [PATCH 066/146] extracted sendFeedback utility for user notifications in rooms --- src/app/hooks/useCommands.ts | 104 ++++++++-------------------- src/app/utils/sendFeedbackToUser.ts | 12 ++++ 2 files changed, 42 insertions(+), 74 deletions(-) create mode 100644 src/app/utils/sendFeedbackToUser.ts diff --git a/src/app/hooks/useCommands.ts b/src/app/hooks/useCommands.ts index 0c2008c0..43638692 100644 --- a/src/app/hooks/useCommands.ts +++ b/src/app/hooks/useCommands.ts @@ -35,6 +35,7 @@ import { parsePronounsInput } from '$utils/pronouns'; import { useRoomNavigate } from './useRoomNavigate'; import { enrichWidgetUrl } from './useRoomWidgets'; import { useUserProfile } from './useUserProfile'; +import { sendFeedback } from '$utils/sendFeedbackToUser'; export const SHRUG = '¯\\_(ツ)_/¯'; export const TABLEFLIP = '(╯°□°)╯︵ ┻━┻'; @@ -641,17 +642,6 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { const input = payload.trim().toLowerCase(); const userId = mx.getSafeUserId(); - const sendFeedback = (msg: string) => { - const localNotice = new MatrixEvent({ - type: 'm.room.message', - content: { msgtype: 'm.notice', body: msg }, - event_id: `~sable-${Date.now()}`, - room_id: room.roomId, - sender: userId, - }); - (room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any); - }; - try { if (input === 'reset' || input === 'clear') { await mx.sendStateEvent( @@ -660,7 +650,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { {}, userId ); - sendFeedback('Room color has been reset.'); + sendFeedback('Room color has been reset.', room, userId); return; } @@ -671,14 +661,16 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { { color: input }, userId ); - sendFeedback(`Room color set to ${input}.`); + sendFeedback(`Room color set to ${input}.`, room, userId); } else { - sendFeedback('Invalid format. Use #RRGGBB.'); + sendFeedback('Invalid format. Use #RRGGBB.', room, userId); } } catch (e: any) { if (e.errcode === 'M_FORBIDDEN') { sendFeedback( - 'Permission Denied. An admin must enable "Room Colors" in Settings > Cosmetics in app.sable.moe or another supported client.' + 'Permission Denied. An admin must enable "Room Colors" in Settings > Cosmetics in app.sable.moe or another supported client.', + room, + userId ); } } @@ -692,17 +684,6 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { const input = payload.trim().toLowerCase(); const userId = mx.getSafeUserId(); - const sendFeedback = (msg: string) => { - const localNotice = new MatrixEvent({ - type: 'm.room.message', - content: { msgtype: 'm.notice', body: msg }, - event_id: `~sable-g-${Date.now()}`, - room_id: room.roomId, - sender: userId, - }); - (room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any); - }; - const parents = room .getLiveTimeline() .getState(EventTimeline.FORWARDS) @@ -719,7 +700,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { {}, userId ); - sendFeedback('Global space color reset.'); + sendFeedback('Global space color reset.', room, userId); return; } @@ -730,14 +711,16 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { { color: input }, userId ); - sendFeedback(`Global space color set to ${input}.`); + sendFeedback(`Global space color set to ${input}.`, room, userId); } else { - sendFeedback('Invalid format. Use #RRGGBB.'); + sendFeedback('Invalid format. Use #RRGGBB.', room, userId); } } catch (e: any) { if (e.errcode === 'M_FORBIDDEN') { sendFeedback( - 'Permission Denied. An admin must enable "Space-Wide Colors" in Settings > Cosmetics in app.sable.moe or another supported client.' + 'Permission Denied. An admin must enable "Space-Wide Colors" in Settings > Cosmetics in app.sable.moe or another supported client.', + room, + userId ); } } @@ -753,21 +736,10 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { .slice(0, 32); const userId = mx.getSafeUserId(); - const sendFeedback = (msg: string) => { - const localNotice = new MatrixEvent({ - type: 'm.room.message', - content: { msgtype: 'm.notice', body: msg }, - event_id: `~font-${Date.now()}`, - room_id: room.roomId, - sender: userId, - }); - (room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any); - }; - try { if (input.toLowerCase() === 'reset' || input === '') { await mx.sendStateEvent(room.roomId, StateEvent.RoomCosmeticsFont as any, {}, userId); - sendFeedback('Room font reset.'); + sendFeedback('Room font reset.', room, userId); return; } @@ -777,11 +749,13 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { { font: input }, userId ); - sendFeedback(`Room font set to "${input}".`); + sendFeedback(`Room font set to "${input}".`, room, userId); } catch (e: any) { if (e.errcode === 'M_FORBIDDEN') { sendFeedback( - 'Permission Denied. An admin must enable "Room Fonts" in Settings > Cosmetics in app.sable.moe or another supported client.' + 'Permission Denied. An admin must enable "Room Fonts" in Settings > Cosmetics in app.sable.moe or another supported client.', + room, + userId ); } } @@ -797,17 +771,6 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { .slice(0, 32); const userId = mx.getSafeUserId(); - const sendFeedback = (msg: string) => { - const localNotice = new MatrixEvent({ - type: 'm.room.message', - content: { msgtype: 'm.notice', body: msg }, - event_id: `~sfont-${Date.now()}`, - room_id: room.roomId, - sender: userId, - }); - (room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any); - }; - const parents = room .getLiveTimeline() .getState(EventTimeline.FORWARDS) @@ -824,7 +787,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { {}, userId ); - sendFeedback('Space font reset.'); + sendFeedback('Space font reset.', room, userId); return; } @@ -834,11 +797,13 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { { font: input }, userId ); - sendFeedback(`Space font set to "${input}".`); + sendFeedback(`Space font set to "${input}".`, room, userId); } catch (e: any) { if (e.errcode === 'M_FORBIDDEN') { sendFeedback( - 'Permission Denied. An admin must enable "Space-Wide Fonts" in Settings > Cosmetics in app.sable.moe or another supported client.' + 'Permission Denied. An admin must enable "Space-Wide Fonts" in Settings > Cosmetics in app.sable.moe or another supported client.', + room, + userId ); } } @@ -850,23 +815,12 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { exe: async (payload) => { const userId = mx.getSafeUserId(); - const sendFeedback = (msg: string) => { - const localNotice = new MatrixEvent({ - type: 'm.room.message', - content: { msgtype: 'm.notice', body: msg }, - event_id: `~nullptr-widget-${Date.now()}`, - room_id: room.roomId, - sender: userId, - }); - (room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any); - }; - const parts = payload.trim().split(/\s+/); const url = parts[0]; const name = parts.slice(1).join(' ') || 'Widget'; if (!url) { - sendFeedback('Usage: /addwidget [name]'); + sendFeedback('Usage: /addwidget [name]', room, userId); return; } @@ -874,7 +828,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { try { parsedUrl = new URL(url); } catch { - sendFeedback('Invalid URL. Please provide a valid widget URL.'); + sendFeedback('Invalid URL. Please provide a valid widget URL.', room, userId); return; } @@ -892,14 +846,16 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { } as any, widgetId ); - sendFeedback(`Widget "${name}" added.`); + sendFeedback(`Widget "${name}" added.`, room, userId); } catch (e: any) { if (e.errcode === 'M_FORBIDDEN') { sendFeedback( - 'Permission denied. You need permission to manage widgets in this room.' + 'Permission denied. You need permission to manage widgets in this room.', + room, + userId ); } else { - sendFeedback(`Failed to add widget: ${e.message || 'Unknown error'}`); + sendFeedback(`Failed to add widget: ${e.message || 'Unknown error'}`, room, userId); } } }, diff --git a/src/app/utils/sendFeedbackToUser.ts b/src/app/utils/sendFeedbackToUser.ts new file mode 100644 index 00000000..c1fa7ab4 --- /dev/null +++ b/src/app/utils/sendFeedbackToUser.ts @@ -0,0 +1,12 @@ +import { MatrixEvent, Room } from 'matrix-js-sdk'; + +export function sendFeedback(msg: string, room: Room, userId: string) { + const localNotice = new MatrixEvent({ + type: 'm.room.message', + content: { msgtype: 'm.notice', body: msg }, + event_id: `~sable-feedback-${Date.now()}`, + room_id: room.roomId, + sender: userId, + }); + room.addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any); +} From c92c8181e8e10cb32f77c40aa0b935fc16daa25a Mon Sep 17 00:00:00 2001 From: Rye Date: Mon, 16 Mar 2026 15:45:39 +0100 Subject: [PATCH 067/146] refactor: streamline sendFeedback utility and add ShareE2EEHistory command --- src/app/hooks/useCommands.ts | 201 +++++++++++++---------------------- 1 file changed, 71 insertions(+), 130 deletions(-) diff --git a/src/app/hooks/useCommands.ts b/src/app/hooks/useCommands.ts index 43638692..c8ee9fb2 100644 --- a/src/app/hooks/useCommands.ts +++ b/src/app/hooks/useCommands.ts @@ -10,7 +10,6 @@ import { Visibility, RoomServerAclEventContent, MsgType, - MatrixEvent, } from '$types/matrix-sdk'; import { useMemo } from 'react'; import { Membership, StateEvent } from '$types/matrix/room'; @@ -32,10 +31,10 @@ import { settingsAtom } from '$state/settings'; import { useOpenBugReportModal } from '$state/hooks/bugReportModal'; import { createRoomEncryptionState } from '$components/create-room'; import { parsePronounsInput } from '$utils/pronouns'; +import { sendFeedback } from '$utils/sendFeedbackToUser'; import { useRoomNavigate } from './useRoomNavigate'; import { enrichWidgetUrl } from './useRoomWidgets'; import { useUserProfile } from './useUserProfile'; -import { sendFeedback } from '$utils/sendFeedbackToUser'; export const SHRUG = '¯\\_(ツ)_/¯'; export const TABLEFLIP = '(╯°□°)╯︵ ┻━┻'; @@ -252,6 +251,8 @@ export enum Command { Headpat = 'headpat', // Meta Report = 'bugreport', + // Experimental + ShareE2EEHistory = 'sharehistory', } export type CommandContent = { @@ -869,17 +870,6 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { const rawInput = match ? match[1].trim() : payload.trim(); const userId = mx.getSafeUserId(); - const sendFeedback = (msg: string) => { - const localNotice = new MatrixEvent({ - type: 'm.room.message', - content: { msgtype: 'm.notice', body: msg }, - event_id: `~pronoun-${Date.now()}`, - room_id: room.roomId, - sender: userId, - }); - (room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any); - }; - try { if (['reset', 'clear', ''].includes(rawInput.toLowerCase())) { await mx.sendStateEvent( @@ -888,7 +878,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { {}, userId ); - sendFeedback('Room pronouns have been reset.'); + sendFeedback('Room pronouns have been reset.', room, userId); return; } @@ -905,10 +895,10 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { .map((p) => (p.language ? `for ${p.language} "${p.summary}" was set` : p.summary)) .join(', '); - sendFeedback(`Room pronouns set: ${feedbackString}`); + sendFeedback(`Room pronouns set: ${feedbackString}`, room, userId); } catch (e: any) { if (e.errcode === 'M_FORBIDDEN') { - sendFeedback('Permission Denied. Could not update room pronouns.'); + sendFeedback('Permission Denied. Could not update room pronouns.', room, userId); } } }, @@ -922,17 +912,6 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { const rawInput = match ? match[1].trim() : payload.trim(); const userId = mx.getSafeUserId(); - const sendFeedback = (msg: string) => { - const localNotice = new MatrixEvent({ - type: 'm.room.message', - content: { msgtype: 'm.notice', body: msg }, - event_id: `~gpronoun-${Date.now()}`, - room_id: room.roomId, - sender: userId, - }); - (room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any); - }; - const parents = room .getLiveTimeline() .getState(EventTimeline.FORWARDS) @@ -949,7 +928,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { {}, userId ); - sendFeedback('Global space pronouns reset.'); + sendFeedback('Global space pronouns reset.', room, userId); return; } @@ -966,10 +945,10 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { .map((p) => (p.language ? `for ${p.language} "${p.summary}" was set` : p.summary)) .join(', '); - sendFeedback(`Global space pronouns set: ${feedbackString}`); + sendFeedback(`Global space pronouns set: ${feedbackString}`, room, userId); } catch (e: any) { if (e.errcode === 'M_FORBIDDEN') { - sendFeedback('Permission Denied. Could not update space pronouns.'); + sendFeedback('Permission Denied. Could not update space pronouns.', room, userId); } } }, @@ -995,25 +974,15 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { '[Dev only] Send raw message event. Example: /rawmsg {"msgtype":"m.text", "body":"hello"}', exe: async (payload) => { const userId = mx.getSafeUserId(); - const sendFeedback = (msg: string) => { - const localNotice = new MatrixEvent({ - type: 'm.room.message', - content: { msgtype: 'm.notice', body: msg }, - event_id: `~rawmsg-${Date.now()}`, - room_id: room.roomId, - sender: userId, - }); - (room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any); - }; if (!developerTools) { - sendFeedback('Command available in Developer Mode only.'); + sendFeedback('Command available in Developer Mode only.', room, userId); return; } try { const content = JSON.parse(payload); await mx.sendMessage(room.roomId, content); } catch (e: any) { - sendFeedback(`Invalid JSON: ${e.message}`); + sendFeedback(`Invalid JSON: ${e.message}`, room, userId); } }, }, @@ -1022,19 +991,9 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { description: '[Dev only] Send any raw event. Usage: /raw [-s stateKey]', exe: async (payload) => { const userId = mx.getSafeUserId(); - const sendFeedback = (msg: string) => { - const localNotice = new MatrixEvent({ - type: 'm.room.message', - content: { msgtype: 'm.notice', body: msg }, - event_id: `~rawevent-${Date.now()}`, - room_id: room.roomId, - sender: userId, - }); - room.addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any); - }; if (!developerTools) { - sendFeedback('Command available in Developer Mode only.'); + sendFeedback('Command available in Developer Mode only.', room, userId); return; } @@ -1046,7 +1005,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { const jsonString = mainPayload.trim().substring(eventType.length).trim(); if (!eventType || !jsonString) { - sendFeedback('Usage: /rawevent [-s stateKey]'); + sendFeedback('Usage: /rawevent [-s stateKey]', room, userId); return; } @@ -1055,13 +1014,17 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { if (typeof stateKey === 'string') { await mx.sendStateEvent(room.roomId, eventType as any, content, stateKey); - sendFeedback(`State event "${eventType}" sent with state key "${stateKey}".`); + sendFeedback( + `State event "${eventType}" sent with state key "${stateKey}".`, + room, + userId + ); } else { await mx.sendEvent(room.roomId, eventType as any, content); - sendFeedback(`Event "${eventType}" sent.`); + sendFeedback(`Event "${eventType}" sent.`, room, userId); } } catch (e: any) { - sendFeedback(`Error: ${e.message}`); + sendFeedback(`Error: ${e.message}`, room, userId); } }, }, @@ -1070,26 +1033,16 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { description: '[Dev only] Merge global account data. Usage: /rawacc ', exe: async (payload) => { const userId = mx.getSafeUserId(); - const sendFeedback = (msg: string) => { - const localNotice = new MatrixEvent({ - type: 'm.room.message', - content: { msgtype: 'm.notice', body: msg }, - event_id: `~rawacc-${Date.now()}`, - room_id: room.roomId, - sender: userId, - }); - (room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any); - }; if (!developerTools) { - sendFeedback('Command available in Developer Mode only.'); + sendFeedback('Command available in Developer Mode only.', room, userId); return; } const trimmed = payload.trim(); const firstSpaceIndex = trimmed.indexOf(' '); if (firstSpaceIndex === -1) { - sendFeedback('Usage: /rawacc '); + sendFeedback('Usage: /rawacc ', room, userId); return; } @@ -1105,9 +1058,9 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { const mergedContent = { ...existingContent, ...newContent }; await mx.setAccountData(type as any, mergedContent); - sendFeedback(`Account data "${type}" merged successfully.`); + sendFeedback(`Account data "${type}" merged successfully.`, room, userId); } catch (e: any) { - sendFeedback(`Error: ${e.message}`); + sendFeedback(`Error: ${e.message}`, room, userId); } }, }, @@ -1116,38 +1069,28 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { description: '[Dev Only] Remove a key from account data. Usage: /delacc ', exe: async (payload) => { const userId = mx.getSafeUserId(); - const sendFeedback = (msg: string) => { - const localNotice = new MatrixEvent({ - type: 'm.room.message', - content: { msgtype: 'm.notice', body: msg }, - event_id: `~removeacc-${Date.now()}`, - room_id: room.roomId, - sender: userId, - }); - room.addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any); - }; const parts = payload.trim().split(/\s+/); if (parts.length < 2) { - sendFeedback('Usage: /delacc '); + sendFeedback('Usage: /delacc ', room, userId); return; } const [type, key] = parts; try { const existingEvent = mx.getAccountData(type as any); if (!existingEvent) { - sendFeedback(`No account data found for type "${type}".`); + sendFeedback(`No account data found for type "${type}".`, room, userId); return; } const content = { ...existingEvent.getContent() }; if (!(key in content)) { - sendFeedback(`Key "${key}" not found in "${type}".`); + sendFeedback(`Key "${key}" not found in "${type}".`, room, userId); return; } delete content[key]; await mx.setAccountData(type as any, content as any); - sendFeedback(`Key "${key}" removed from "${type}".`); + sendFeedback(`Key "${key}" removed from "${type}".`, room, userId); } catch (e: any) { - sendFeedback(`Error: ${e.message}`); + sendFeedback(`Error: ${e.message}`, room, userId); } }, }, @@ -1156,23 +1099,13 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { description: '[Dev Only] Set an extended profile property. Usage: /setext ', exe: async (payload) => { const userId = mx.getSafeUserId(); - const sendFeedback = (msg: string) => { - const localNotice = new MatrixEvent({ - type: 'm.room.message', - content: { msgtype: 'm.notice', body: msg }, - event_id: `~setext-${Date.now()}`, - room_id: room.roomId, - sender: userId, - }); - room.addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any); - }; if (!developerTools) { - sendFeedback('Command available in Developer Mode only.'); + sendFeedback('Command available in Developer Mode only.', room, userId); return; } const parts = payload.trim().split(/\s+/); if (parts.length < 2) { - sendFeedback('Usage: /setext '); + sendFeedback('Usage: /setext ', room, userId); return; } const key = parts[0]; @@ -1184,12 +1117,16 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { try { if (typeof mx.setExtendedProfileProperty === 'function') { await mx.setExtendedProfileProperty(key, finalValue); - sendFeedback(`Extended profile property "${key}" set to: ${finalValue}`); + sendFeedback( + `Extended profile property "${key}" set to: ${finalValue}`, + room, + userId + ); } else { - sendFeedback('Error: setExtendedProfileProperty is not supported.'); + sendFeedback('Error: setExtendedProfileProperty is not supported.', room, userId); } } catch (e: any) { - sendFeedback(`Failed to set extended profile: ${e.message}`); + sendFeedback(`Failed to set extended profile: ${e.message}`, room, userId); } }, }, @@ -1200,36 +1137,25 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { const userId = mx.getSafeUserId(); const key = payload.trim(); - const sendFeedback = (msg: string) => { - const localNotice = new MatrixEvent({ - type: 'm.room.message', - content: { msgtype: 'm.notice', body: msg }, - event_id: `~removeext-${Date.now()}`, - room_id: room.roomId, - sender: userId, - }); - room.addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any); - }; - if (!developerTools) { - sendFeedback('Command available in Developer Mode only.'); + sendFeedback('Command available in Developer Mode only.', room, userId); return; } if (!key) { - sendFeedback('Usage: /delext '); + sendFeedback('Usage: /delext ', room, userId); return; } try { if (typeof mx.deleteExtendedProfileProperty === 'function') { await mx.deleteExtendedProfileProperty(key); - sendFeedback(`Extended profile property "${key}" removed.`); + sendFeedback(`Extended profile property "${key}" removed.`, room, userId); } else { - sendFeedback('Error: setExtendedProfileProperty is not supported.'); + sendFeedback('Error: setExtendedProfileProperty is not supported.', room, userId); } } catch (e: any) { - sendFeedback(`Failed to remove property: ${e.message}`); + sendFeedback(`Failed to remove property: ${e.message}`, room, userId); } }, }, @@ -1238,27 +1164,42 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { description: 'Force discard the current outbound E2EE session in this room.', exe: async () => { const userId = mx.getSafeUserId(); - const sendFeedback = (msg: string) => { - const localNotice = new MatrixEvent({ - type: 'm.room.message', - content: { msgtype: 'm.notice', body: msg }, - event_id: `~discard-${Date.now()}`, - room_id: room.roomId, - sender: userId, - }); - room.addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any); - }; try { const crypto = mx.getCrypto(); if (!crypto) { - sendFeedback('Encryption is not enabled on this client.'); + sendFeedback('Encryption is not enabled on this client.', room, userId); return; } await crypto.forceDiscardSession(room.roomId); - sendFeedback('Outbound encryption session discarded.'); + sendFeedback('Outbound encryption session discarded.', room, userId); } catch (e: any) { - sendFeedback(`Failed to discard session: ${e.message}`); + sendFeedback(`Failed to discard session: ${e.message}`, room, userId); + } + }, + }, + // Sharing E2EE History of a room with a user + [Command.ShareE2EEHistory]: { + name: Command.ShareE2EEHistory, + description: + 'Share E2EE history of this room with a user. Example: /sharee2eehistory @user:example.org', + exe: async (payload) => { + const targetUserId = payload.trim(); + const { roomId } = room; + if (!targetUserId) { + sendFeedback('Usage: /sharee2eehistory @user:example.org', room, mx.getSafeUserId()); + return; + } + const crypto = mx.getCrypto(); + if (!crypto) { + sendFeedback('Encryption is not enabled on this client.', room, mx.getSafeUserId()); + return; + } + try { + await crypto.shareRoomHistoryWithUser(roomId, targetUserId); + sendFeedback(`E2EE history shared with ${targetUserId}.`, room, mx.getSafeUserId()); + } catch (e: any) { + sendFeedback(`Failed to share E2EE history: ${e.message}`, room, mx.getSafeUserId()); } }, }, From d2a05f280ead8cac0bf4839d9cdbbb38034bd179 Mon Sep 17 00:00:00 2001 From: Rye Date: Mon, 16 Mar 2026 15:48:55 +0100 Subject: [PATCH 068/146] feat: update ShareE2EEHistory command description to clarify limitations --- src/app/hooks/useCommands.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/app/hooks/useCommands.ts b/src/app/hooks/useCommands.ts index c8ee9fb2..ba048e1f 100644 --- a/src/app/hooks/useCommands.ts +++ b/src/app/hooks/useCommands.ts @@ -1182,7 +1182,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { [Command.ShareE2EEHistory]: { name: Command.ShareE2EEHistory, description: - 'Share E2EE history of this room with a user. Example: /sharee2eehistory @user:example.org', + 'Share E2EE history (MSC4268) of this room with a user. Example: /sharee2eehistory @user:example.org', exe: async (payload) => { const targetUserId = payload.trim(); const { roomId } = room; @@ -1197,7 +1197,11 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { } try { await crypto.shareRoomHistoryWithUser(roomId, targetUserId); - sendFeedback(`E2EE history shared with ${targetUserId}.`, room, mx.getSafeUserId()); + sendFeedback( + `E2EE history shared with ${targetUserId}. (Their client needs to support MSC4268)`, + room, + mx.getSafeUserId() + ); } catch (e: any) { sendFeedback(`Failed to share E2EE history: ${e.message}`, room, mx.getSafeUserId()); } From 2c808046aba499ac71cf7f40682d9feedb306575 Mon Sep 17 00:00:00 2001 From: Rye Date: Mon, 16 Mar 2026 15:59:47 +0100 Subject: [PATCH 069/146] refactor: convert shareRoomHistoryWithUser to promise-based handling for improved error management --- src/app/hooks/useCommands.ts | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/app/hooks/useCommands.ts b/src/app/hooks/useCommands.ts index ba048e1f..ef09847b 100644 --- a/src/app/hooks/useCommands.ts +++ b/src/app/hooks/useCommands.ts @@ -1195,16 +1195,18 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { sendFeedback('Encryption is not enabled on this client.', room, mx.getSafeUserId()); return; } - try { - await crypto.shareRoomHistoryWithUser(roomId, targetUserId); - sendFeedback( - `E2EE history shared with ${targetUserId}. (Their client needs to support MSC4268)`, - room, - mx.getSafeUserId() - ); - } catch (e: any) { - sendFeedback(`Failed to share E2EE history: ${e.message}`, room, mx.getSafeUserId()); - } + crypto + .shareRoomHistoryWithUser(roomId, targetUserId) + .then(() => { + sendFeedback( + `E2EE history shared with ${targetUserId}. (Their client needs to support MSC4268)`, + room, + mx.getSafeUserId() + ); + }) + .catch((e) => { + sendFeedback(`Failed to share E2EE history: ${e.message}`, room, mx.getSafeUserId()); + }); }, }, // Cute Events From 210d34030a15cc09ae52754acafb1e7bfab2a91a Mon Sep 17 00:00:00 2001 From: Rye Date: Mon, 16 Mar 2026 16:07:18 +0100 Subject: [PATCH 070/146] add changeset for my pr relating the addition of `/sharehistory` --- .changeset/add_command_for_msc4268_e2ee_history_sharing.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/add_command_for_msc4268_e2ee_history_sharing.md diff --git a/.changeset/add_command_for_msc4268_e2ee_history_sharing.md b/.changeset/add_command_for_msc4268_e2ee_history_sharing.md new file mode 100644 index 00000000..5ef3a5f5 --- /dev/null +++ b/.changeset/add_command_for_msc4268_e2ee_history_sharing.md @@ -0,0 +1,5 @@ +--- +default: minor +--- + +added a `/sharehistory` command to [share encrypted history with a user](https://github.com/matrix-org/matrix-spec-proposals/blob/rav/proposal/encrypted_history_sharing/proposals/4268-encrypted-history-sharing.md) From 2ac73d0aa9932f760edc884a91a17755343341df Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 11:20:37 -0400 Subject: [PATCH 071/146] feat(testing): add Vitest testing infrastructure with example tests --- .changeset/feat-testing-setup.md | 5 + .github/workflows/quality-checks.yml | 18 + .gitignore | 1 + CONTRIBUTING.md | 5 +- docs/TESTING.md | 137 +++++ knip.json | 4 +- package.json | 11 + pnpm-lock.yaml | 850 +++++++++++++++++++++++++++ src/app/utils/colorMXID.test.ts | 36 ++ src/app/utils/common.test.ts | 37 ++ src/app/utils/findAndReplace.test.ts | 59 ++ src/app/utils/sort.test.ts | 99 ++++ src/test/setup.ts | 1 + tsconfig.json | 2 +- vitest.config.ts | 51 ++ 15 files changed, 1313 insertions(+), 3 deletions(-) create mode 100644 .changeset/feat-testing-setup.md create mode 100644 docs/TESTING.md create mode 100644 src/app/utils/colorMXID.test.ts create mode 100644 src/app/utils/common.test.ts create mode 100644 src/app/utils/findAndReplace.test.ts create mode 100644 src/app/utils/sort.test.ts create mode 100644 src/test/setup.ts create mode 100644 vitest.config.ts diff --git a/.changeset/feat-testing-setup.md b/.changeset/feat-testing-setup.md new file mode 100644 index 00000000..51f7ad57 --- /dev/null +++ b/.changeset/feat-testing-setup.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Add Vitest testing infrastructure with example tests and contributor documentation diff --git a/.github/workflows/quality-checks.yml b/.github/workflows/quality-checks.yml index 6928af6e..a9ac4370 100644 --- a/.github/workflows/quality-checks.yml +++ b/.github/workflows/quality-checks.yml @@ -79,6 +79,24 @@ jobs: - name: Run Knip run: pnpm run knip + tests: + name: Tests + runs-on: ubuntu-latest + if: github.head_ref != 'release' + permissions: + contents: read + steps: + - name: Checkout repository + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + + - name: Setup app + uses: ./.github/actions/setup + + - name: Run tests + run: pnpm run test:run + build: name: Build runs-on: ubuntu-latest diff --git a/.gitignore b/.gitignore index 414b4a31..3e561c64 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ experiment dist +coverage node_modules devAssets diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9bf1e3ca..c417e207 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -37,12 +37,15 @@ It is not always possible to phrase every change in such a manner, but it is des Also, we use [ESLint](https://eslint.org/) for clean and stylistically consistent code syntax, so make sure your pull request follow it. -**Pull requests are not merged unless all quality checks are passing.** At minimum, `format`, `lint`, `typecheck`, and `knip` must all be green before a pull request can be merged. Run these locally before opening or updating a pull request: +**Pull requests are not merged unless all quality checks are passing.** At minimum, `format`, `lint`, `typecheck`, `knip`, and `tests` must all be green before a pull request can be merged. Run these locally before opening or updating a pull request: - `pnpm run fmt:check` - `pnpm run lint` - `pnpm run typecheck` - `pnpm run knip` +- `pnpm run test:run` + +If your change touches logic with testable behaviour, please include tests. See [docs/TESTING.md](./docs/TESTING.md) for a guide on how to write them. ## Restrictions on Generative AI Usage diff --git a/docs/TESTING.md b/docs/TESTING.md new file mode 100644 index 00000000..c5907c05 --- /dev/null +++ b/docs/TESTING.md @@ -0,0 +1,137 @@ +# Testing Guide + +Sable uses [Vitest](https://vitest.dev/) as its test runner and [React Testing Library](https://testing-library.com/docs/react-testing-library/intro/) for component tests. Tests run in a [jsdom](https://github.com/jsdom/jsdom) environment and coverage is collected via V8. + +--- + +## Running tests + +```sh +# Watch mode — reruns affected tests on file save (recommended during development) +pnpm test + +# Single run — equivalent to what CI runs +pnpm test:run + +# With browser UI (interactive results viewer) +pnpm test:ui + +# With coverage report +pnpm test:coverage +``` + +Coverage reports are written to `coverage/`. Open `coverage/index.html` in your browser for the full HTML report. + +--- + +## Writing tests + +### Where to put test files + +Place test files next to the source file they cover, with a `.test.ts` or `.test.tsx` suffix: + +``` +src/app/utils/colorMXID.ts +src/app/utils/colorMXID.test.ts + +src/app/features/room/RoomTimeline.tsx +src/app/features/room/RoomTimeline.test.tsx +``` + +### Testing plain utility functions + +For pure functions in `src/app/utils/`, no special setup is needed — just import and assert: + +```ts +import { describe, it, expect } from 'vitest'; +import { bytesToSize } from './common'; + +describe('bytesToSize', () => { + it('converts bytes to KB', () => { + expect(bytesToSize(1500)).toBe('1.5 KB'); + }); +}); +``` + +### Testing React components + +Use `@testing-library/react` to render components inside the jsdom environment. Query by accessible role/text rather than CSS classes or implementation details: + +```tsx +import { describe, it, expect } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { MyButton } from './MyButton'; + +describe('MyButton', () => { + it('calls onClick when pressed', async () => { + const user = userEvent.setup(); + const onClick = vi.fn(); + + render(Click me); + + await user.click(screen.getByRole('button', { name: 'Click me' })); + + expect(onClick).toHaveBeenCalledOnce(); + }); +}); +``` + +### Testing hooks + +Use `renderHook` from `@testing-library/react`: + +```ts +import { describe, it, expect } from 'vitest'; +import { renderHook, act } from '@testing-library/react'; +import { useMyHook } from './useMyHook'; + +describe('useMyHook', () => { + it('returns the expected initial value', () => { + const { result } = renderHook(() => useMyHook()); + expect(result.current.value).toBe(0); + }); +}); +``` + +### Mocking + +Vitest has Jest-compatible mocking APIs: + +```ts +import { vi } from 'vitest'; + +// Mock a module +vi.mock('./someModule', () => ({ doThing: vi.fn(() => 'mocked') })); + +// Spy on a method +const spy = vi.spyOn(console, 'error').mockImplementation(() => {}); + +// Restore after test +afterEach(() => vi.restoreAllMocks()); +``` + +### Path aliases + +All the project's path aliases work inside tests — you can import using `$utils/`, `$components/`, `$features/`, etc., just like in application code. + +--- + +## What to test + +Not every file needs tests. Focus on logic that would be painful to debug when broken: + +| Worth testing | Less valuable | +| ----------------------------------------------- | ---------------------------------------------- | +| Pure utility functions (`src/app/utils/`) | Purely presentational components with no logic | +| Custom hooks with non-trivial state transitions | Thin wrappers around third-party APIs | +| State atoms and reducers | Generated or declarative config | +| Data transformation / formatting functions | | + +When you fix a bug, consider adding a regression test that would have caught it — the description in the test is useful documentation. + +--- + +## CI + +`pnpm test:run` is part of the required quality checks and runs on every pull request alongside `lint`, `typecheck`, and `knip`. A PR with failing tests cannot be merged. diff --git a/knip.json b/knip.json index 3f415d94..02c8ee9f 100644 --- a/knip.json +++ b/knip.json @@ -8,7 +8,9 @@ "ignoreDependencies": [ "buffer", "@element-hq/element-call-embedded", - "@matrix-org/matrix-sdk-crypto-wasm" + "@matrix-org/matrix-sdk-crypto-wasm", + "@testing-library/react", + "@testing-library/user-event" ], "ignoreBinaries": ["knope"], "rules": { diff --git a/package.json b/package.json index 371e7a97..3304ddef 100644 --- a/package.json +++ b/package.json @@ -17,6 +17,10 @@ "fmt": "prettier --write .", "fmt:check": "prettier --check .", "typecheck": "tsc", + "test": "vitest", + "test:ui": "vitest --ui", + "test:run": "vitest run", + "test:coverage": "vitest run --coverage", "knip": "knip", "knope": "knope", "document-change": "knope document-change", @@ -95,6 +99,9 @@ "@eslint/js": "9.39.3", "@rollup/plugin-inject": "^5.0.5", "@rollup/plugin-wasm": "^6.2.2", + "@testing-library/jest-dom": "^6.9.1", + "@testing-library/react": "^16.3.2", + "@testing-library/user-event": "^14.6.1", "@types/chroma-js": "^3.1.2", "@types/file-saver": "^2.0.7", "@types/is-hotkey": "^0.1.10", @@ -106,12 +113,15 @@ "@types/sanitize-html": "^2.16.0", "@types/ua-parser-js": "^0.7.39", "@vitejs/plugin-react": "^5.1.4", + "@vitest/coverage-v8": "^4.1.0", + "@vitest/ui": "^4.1.0", "buffer": "^6.0.3", "eslint": "9.39.3", "eslint-config-airbnb-extended": "3.0.1", "eslint-config-prettier": "10.1.8", "eslint-plugin-prettier": "5.5.5", "globals": "17.3.0", + "jsdom": "^29.0.0", "knip": "5.85.0", "prettier": "3.8.1", "typescript": "^5.9.3", @@ -121,6 +131,7 @@ "vite-plugin-static-copy": "^3.2.0", "vite-plugin-svgr": "4.5.0", "vite-plugin-top-level-await": "^1.6.0", + "vitest": "^4.1.0", "wrangler": "^4.70.0" } } \ No newline at end of file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e0d64afd..19dcb85e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -218,6 +218,15 @@ importers: '@rollup/plugin-wasm': specifier: ^6.2.2 version: 6.2.2(rollup@4.59.0) + '@testing-library/jest-dom': + specifier: ^6.9.1 + version: 6.9.1 + '@testing-library/react': + specifier: ^16.3.2 + version: 16.3.2(@testing-library/dom@10.4.1)(@types/react-dom@18.3.7(@types/react@18.3.28))(@types/react@18.3.28)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@testing-library/user-event': + specifier: ^14.6.1 + version: 14.6.1(@testing-library/dom@10.4.1) '@types/chroma-js': specifier: ^3.1.2 version: 3.1.2 @@ -251,6 +260,12 @@ importers: '@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)) + '@vitest/coverage-v8': + specifier: ^4.1.0 + version: 4.1.0(vitest@4.1.0) + '@vitest/ui': + specifier: ^4.1.0 + version: 4.1.0(vitest@4.1.0) buffer: specifier: ^6.0.3 version: 6.0.3 @@ -269,6 +284,9 @@ importers: globals: specifier: 17.3.0 version: 17.3.0 + jsdom: + specifier: ^29.0.0 + version: 29.0.0 knip: specifier: 5.85.0 version: 5.85.0(@types/node@24.10.13)(typescript@5.9.3) @@ -296,18 +314,35 @@ importers: 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)) + 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)) wrangler: specifier: ^4.70.0 version: 4.72.0 packages: + '@adobe/css-tools@4.4.4': + resolution: {integrity: sha512-Elp+iwUx5rN5+Y8xLt5/GRoG20WGoDCQ/1Fb+1LiGtvwbDavuSk0jhD/eZdckHAuzcDzccnkv+rEjyWfRx18gg==} + '@apideck/better-ajv-errors@0.3.6': resolution: {integrity: sha512-P+ZygBLZtkp0qqOAJJVX4oX/sFo5JR3eBWwwuqHHhK0GIgQOKWrAfiAaWX0aArHkRWHMuggFEgAZNxVPwPZYaA==} engines: {node: '>=10'} peerDependencies: ajv: '>=8' + '@asamuzakjp/css-color@5.0.1': + resolution: {integrity: sha512-2SZFvqMyvboVV1d15lMf7XiI3m7SDqXUuKaTymJYLN6dSGadqp+fVojqJlVoMlbZnlTmu3S0TLwLTJpvBMO1Aw==} + engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + + '@asamuzakjp/dom-selector@7.0.3': + resolution: {integrity: sha512-Q6mU0Z6bfj6YvnX2k9n0JxiIwrCFN59x/nWmYQnAqP000ruX/yV+5bp/GRcF5T8ncvfwJQ7fgfP74DlpKExILA==} + engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + + '@asamuzakjp/nwsapi@2.3.9': + resolution: {integrity: sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==} + '@atlaskit/pragmatic-drag-and-drop-auto-scroll@1.4.0': resolution: {integrity: sha512-5GoikoTSW13UX76F9TDeWB8x3jbbGlp/Y+3aRkHe1MOBMkrWkwNpJ42MIVhhX/6NSeaZiPumP0KbGJVs2tOWSQ==} @@ -830,6 +865,14 @@ packages: resolution: {integrity: sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==} engines: {node: '>=6.9.0'} + '@bcoe/v8-coverage@1.0.2': + resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==} + engines: {node: '>=18'} + + '@bramus/specificity@2.4.2': + resolution: {integrity: sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==} + hasBin: true + '@cloudflare/kv-asset-handler@0.4.2': resolution: {integrity: sha512-SIOD2DxrRRwQ+jgzlXCqoEFiKOFqaPjhnNTGKXSRLvp1HiOvapLaFG2kEr9dYQTYe8rKrd9uvDUzmAITeNyaHQ==} engines: {node: '>=18.0.0'} @@ -883,6 +926,42 @@ packages: resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==} engines: {node: '>=12'} + '@csstools/color-helpers@6.0.2': + resolution: {integrity: sha512-LMGQLS9EuADloEFkcTBR3BwV/CGHV7zyDxVRtVDTwdI2Ca4it0CCVTT9wCkxSgokjE5Ho41hEPgb8OEUwoXr6Q==} + engines: {node: '>=20.19.0'} + + '@csstools/css-calc@3.1.1': + resolution: {integrity: sha512-HJ26Z/vmsZQqs/o3a6bgKslXGFAungXGbinULZO3eMsOyNJHeBBZfup5FiZInOghgoM4Hwnmw+OgbJCNg1wwUQ==} + engines: {node: '>=20.19.0'} + peerDependencies: + '@csstools/css-parser-algorithms': ^4.0.0 + '@csstools/css-tokenizer': ^4.0.0 + + '@csstools/css-color-parser@4.0.2': + resolution: {integrity: sha512-0GEfbBLmTFf0dJlpsNU7zwxRIH0/BGEMuXLTCvFYxuL1tNhqzTbtnFICyJLTNK4a+RechKP75e7w42ClXSnJQw==} + engines: {node: '>=20.19.0'} + peerDependencies: + '@csstools/css-parser-algorithms': ^4.0.0 + '@csstools/css-tokenizer': ^4.0.0 + + '@csstools/css-parser-algorithms@4.0.0': + resolution: {integrity: sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w==} + engines: {node: '>=20.19.0'} + peerDependencies: + '@csstools/css-tokenizer': ^4.0.0 + + '@csstools/css-syntax-patches-for-csstree@1.1.1': + resolution: {integrity: sha512-BvqN0AMWNAnLk9G8jnUT77D+mUbY/H2b3uDTvg2isJkHaOufUE2R3AOwxWo7VBQKT1lOdwdvorddo2B/lk64+w==} + peerDependencies: + css-tree: ^3.2.1 + peerDependenciesMeta: + css-tree: + optional: true + + '@csstools/css-tokenizer@4.0.0': + resolution: {integrity: sha512-QxULHAm7cNu72w97JUNCBFODFaXpbDg+dP8b/oWFAZ2MTRppA3U00Y2L1HqaS4J6yBqxwa/Y3nMBaxVKbB/NsA==} + engines: {node: '>=20.19.0'} + '@element-hq/element-call-embedded@0.16.3': resolution: {integrity: sha512-OViKJonDaDNVBUW9WdV9mk78/Ruh34C7XsEgt3O8D9z+64C39elbIgllHSoH5S12IRlv9RYrrV37FZLo6QWsDQ==} @@ -1110,6 +1189,15 @@ packages: resolution: {integrity: sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@exodus/bytes@1.15.0': + resolution: {integrity: sha512-UY0nlA+feH81UGSHv92sLEPLCeZFjXOuHhrIo0HQydScuQc8s0A7kL/UdgwgDq8g8ilksmuoF35YVTNphV2aBQ==} + engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + peerDependencies: + '@noble/hashes': ^1.8.0 || ^2.0.0 + peerDependenciesMeta: + '@noble/hashes': + optional: true + '@fontsource-variable/nunito@5.2.7': resolution: {integrity: sha512-2N8QhatkyKgSUbAGZO2FYLioxA32+RyI1EplVLawbpkGjUeui9Qg9VMrpkCaik1ydjFjfLV+kzQ0cGEsMrMenQ==} @@ -1553,6 +1641,9 @@ packages: resolution: {integrity: sha512-QNqXyfVS2wm9hweSYD2O7F0G06uurj9kZ96TRQE5Y9hU7+tgdZwIkbAKc5Ocy1HxEY2kuDQa6cQ1WRs/O5LFKA==} engines: {node: ^12.20.0 || ^14.18.0 || >=16.0.0} + '@polka/url@1.0.0-next.29': + resolution: {integrity: sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==} + '@poppinss/colors@4.1.6': resolution: {integrity: sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==} @@ -2329,6 +2420,9 @@ packages: '@speed-highlight/core@1.2.14': resolution: {integrity: sha512-G4ewlBNhUtlLvrJTb88d2mdy2KRijzs4UhnlrOSRT4bmjh/IqNElZa3zkrZ+TC47TwtlDWzVLFADljF1Ijp5hA==} + '@standard-schema/spec@1.1.0': + resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + '@stylistic/eslint-plugin@5.10.0': resolution: {integrity: sha512-nPK52ZHvot8Ju/0A4ucSX1dcPV2/1clx0kLcH5wDmrE4naKso7TUC/voUyU1O9OTKTrR6MYip6LP0ogEMQ9jPQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -2517,9 +2611,41 @@ packages: '@tanstack/virtual-core@3.13.21': resolution: {integrity: sha512-ww+fmLHyCbPSf7JNbWZP3g7wl6SdNo3ah5Aiw+0e9FDErkVHLKprYUrwTm7dF646FtEkN/KkAKPYezxpmvOjxw==} + '@testing-library/dom@10.4.1': + resolution: {integrity: sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==} + engines: {node: '>=18'} + + '@testing-library/jest-dom@6.9.1': + resolution: {integrity: sha512-zIcONa+hVtVSSep9UT3jZ5rizo2BsxgyDYU7WFD5eICBE7no3881HGeb/QkGfsJs6JTkY1aQhT7rIPC7e+0nnA==} + engines: {node: '>=14', npm: '>=6', yarn: '>=1'} + + '@testing-library/react@16.3.2': + resolution: {integrity: sha512-XU5/SytQM+ykqMnAnvB2umaJNIOsLF3PVv//1Ew4CTcpz0/BRyy/af40qqrt7SjKpDdT1saBMc42CUok5gaw+g==} + engines: {node: '>=18'} + peerDependencies: + '@testing-library/dom': ^10.0.0 + '@types/react': ^18.0.0 || ^19.0.0 + '@types/react-dom': ^18.0.0 || ^19.0.0 + react: ^18.0.0 || ^19.0.0 + react-dom: ^18.0.0 || ^19.0.0 + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@testing-library/user-event@14.6.1': + resolution: {integrity: sha512-vq7fv0rnt+QTXgPxr5Hjc210p6YKq2kmdziLgnsZGgLJ9e6VAShx1pACLuRjd/AS/sr7phAR58OIIpf0LlmQNw==} + engines: {node: '>=12', npm: '>=6'} + peerDependencies: + '@testing-library/dom': '>=7.21.4' + '@tybys/wasm-util@0.10.1': resolution: {integrity: sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==} + '@types/aria-query@5.0.4': + resolution: {integrity: sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==} + '@types/babel__core@7.20.5': resolution: {integrity: sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==} @@ -2532,9 +2658,15 @@ packages: '@types/babel__traverse@7.28.0': resolution: {integrity: sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==} + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + '@types/chroma-js@3.1.2': resolution: {integrity: sha512-YBTQqArPN8A0niHXCwrO1z5x++a+6l0mLBykncUpr23oIPW7L4h39s6gokdK/bDrPmSh8+TjMmrhBPnyiaWPmQ==} + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + '@types/estree@0.0.39': resolution: {integrity: sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw==} @@ -2789,6 +2921,49 @@ packages: peerDependencies: vite: ^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 + '@vitest/coverage-v8@4.1.0': + resolution: {integrity: sha512-nDWulKeik2bL2Va/Wl4x7DLuTKAXa906iRFooIRPR+huHkcvp9QDkPQ2RJdmjOFrqOqvNfoSQLF68deE3xC3CQ==} + peerDependencies: + '@vitest/browser': 4.1.0 + vitest: 4.1.0 + peerDependenciesMeta: + '@vitest/browser': + optional: true + + '@vitest/expect@4.1.0': + resolution: {integrity: sha512-EIxG7k4wlWweuCLG9Y5InKFwpMEOyrMb6ZJ1ihYu02LVj/bzUwn2VMU+13PinsjRW75XnITeFrQBMH5+dLvCDA==} + + '@vitest/mocker@4.1.0': + resolution: {integrity: sha512-evxREh+Hork43+Y4IOhTo+h5lGmVRyjqI739Rz4RlUPqwrkFFDF6EMvOOYjTx4E8Tl6gyCLRL8Mu7Ry12a13Tw==} + peerDependencies: + msw: ^2.4.9 + vite: ^6.0.0 || ^7.0.0 || ^8.0.0-0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/pretty-format@4.1.0': + resolution: {integrity: sha512-3RZLZlh88Ib0J7NQTRATfc/3ZPOnSUn2uDBUoGNn5T36+bALixmzphN26OUD3LRXWkJu4H0s5vvUeqBiw+kS0A==} + + '@vitest/runner@4.1.0': + resolution: {integrity: sha512-Duvx2OzQ7d6OjchL+trw+aSrb9idh7pnNfxrklo14p3zmNL4qPCDeIJAK+eBKYjkIwG96Bc6vYuxhqDXQOWpoQ==} + + '@vitest/snapshot@4.1.0': + resolution: {integrity: sha512-0Vy9euT1kgsnj1CHttwi9i9o+4rRLEaPRSOJ5gyv579GJkNpgJK+B4HSv/rAWixx2wdAFci1X4CEPjiu2bXIMg==} + + '@vitest/spy@4.1.0': + resolution: {integrity: sha512-pz77k+PgNpyMDv2FV6qmk5ZVau6c3R8HC8v342T2xlFxQKTrSeYw9waIJG8KgV9fFwAtTu4ceRzMivPTH6wSxw==} + + '@vitest/ui@4.1.0': + resolution: {integrity: sha512-sTSDtVM1GOevRGsCNhp1mBUHKo9Qlc55+HCreFT4fe99AHxl1QQNXSL3uj4Pkjh5yEuWZIx8E2tVC94nnBZECQ==} + peerDependencies: + vitest: 4.1.0 + + '@vitest/utils@4.1.0': + resolution: {integrity: sha512-XfPXT6a8TZY3dcGY8EdwsBulFCIw+BeeX0RZn2x/BtiY/75YGh8FeWGG8QISN/WhaqSrE2OrlDgtF8q5uhOTmw==} + acorn-jsx@5.3.2: resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} peerDependencies: @@ -2816,6 +2991,10 @@ packages: resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} engines: {node: '>=8'} + ansi-styles@5.2.0: + resolution: {integrity: sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==} + engines: {node: '>=10'} + anymatch@3.1.3: resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==} engines: {node: '>= 8'} @@ -2823,6 +3002,9 @@ packages: argparse@2.0.1: resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} + aria-query@5.3.0: + resolution: {integrity: sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==} + aria-query@5.3.2: resolution: {integrity: sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==} engines: {node: '>= 0.4'} @@ -2859,9 +3041,16 @@ packages: resolution: {integrity: sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==} engines: {node: '>= 0.4'} + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + ast-types-flow@0.0.8: resolution: {integrity: sha512-OH/2E5Fg20h2aPrbe+QL8JZQFko0YZaF+j4mnQ7BGhfavO7OpSLa8a0y9sBwomHdSbkhTS8TQNayBfnW5DwbvQ==} + ast-v8-to-istanbul@1.0.0: + resolution: {integrity: sha512-1fSfIwuDICFA4LKkCzRPO7F0hzFf0B7+Xqrl27ynQaa+Rh0e1Es0v6kWHPott3lU10AyAr7oKHa65OppjLn3Rg==} + async-function@1.0.0: resolution: {integrity: sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==} engines: {node: '>= 0.4'} @@ -2922,6 +3111,9 @@ packages: engines: {node: '>=6.0.0'} hasBin: true + bidi-js@1.0.3: + resolution: {integrity: sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==} + binary-extensions@2.3.0: resolution: {integrity: sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==} engines: {node: '>=8'} @@ -2987,6 +3179,10 @@ packages: caniuse-lite@1.0.30001777: resolution: {integrity: sha512-tmN+fJxroPndC74efCdp12j+0rk0RHwV5Jwa1zWaFVyw2ZxAuPeG8ZgWC3Wz7uSjT3qMRQ5XHZ4COgQmsCMJAQ==} + chai@6.2.2: + resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==} + engines: {node: '>=18'} + chalk@4.1.2: resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} engines: {node: '>=10'} @@ -3070,10 +3266,17 @@ packages: resolution: {integrity: sha512-v1plID3y9r/lPhviJ1wrXpLeyUIGAZ2SHNYTEapm7/8A9nLPoyvVp3RK/EPFqn5kEznyWgYZNsRtYYIWbuG8KA==} engines: {node: '>=8'} + css-tree@3.2.1: + resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==} + engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0} + css-what@6.2.2: resolution: {integrity: sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA==} engines: {node: '>= 6'} + css.escape@1.5.1: + resolution: {integrity: sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==} + cssesc@3.0.0: resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==} engines: {node: '>=4'} @@ -3085,6 +3288,10 @@ packages: damerau-levenshtein@1.0.8: resolution: {integrity: sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA==} + data-urls@7.0.0: + resolution: {integrity: sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==} + engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + data-view-buffer@1.0.2: resolution: {integrity: sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==} engines: {node: '>= 0.4'} @@ -3146,6 +3353,10 @@ packages: resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==} engines: {node: '>= 0.4'} + dequal@2.0.3: + resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} + engines: {node: '>=6'} + detect-libc@2.1.2: resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} engines: {node: '>=8'} @@ -3158,6 +3369,12 @@ packages: resolution: {integrity: sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==} engines: {node: '>=0.10.0'} + dom-accessibility-api@0.5.16: + resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==} + + dom-accessibility-api@0.6.3: + resolution: {integrity: sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==} + dom-serializer@2.0.0: resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==} @@ -3208,6 +3425,10 @@ packages: resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==} engines: {node: '>=0.12'} + entities@6.0.1: + resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==} + engines: {node: '>=0.12'} + entities@7.0.1: resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==} engines: {node: '>=0.12'} @@ -3237,6 +3458,9 @@ packages: es-module-lexer@1.7.0: resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==} + es-module-lexer@2.0.0: + resolution: {integrity: sha512-5POEcUuZybH7IdmGsD8wlf0AI55wMecM9rVBTI/qEAy2c1kTOm3DjFYjrBdI2K3BaJjJYfYFeRtM0t9ssnRuxw==} + es-object-atoms@1.1.1: resolution: {integrity: sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==} engines: {node: '>= 0.4'} @@ -3445,6 +3669,9 @@ packages: estree-walker@2.0.2: resolution: {integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==} + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + esutils@2.0.3: resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} engines: {node: '>=0.10.0'} @@ -3460,6 +3687,10 @@ packages: resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==} engines: {node: '>=0.8.x'} + expect-type@1.3.0: + resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==} + engines: {node: '>=12.0.0'} + fast-deep-equal@3.1.3: resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} @@ -3498,6 +3729,9 @@ packages: picomatch: optional: true + fflate@0.8.2: + resolution: {integrity: sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==} + file-entry-cache@8.0.0: resolution: {integrity: sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==} engines: {node: '>=16.0.0'} @@ -3520,6 +3754,9 @@ packages: resolution: {integrity: sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==} engines: {node: '>=16'} + flatted@3.4.0: + resolution: {integrity: sha512-kC6Bb+ooptOIvWj5B63EQWkF0FEnNjV2ZNkLMLZRDDduIiWeFF4iKnslwhiWxjAdbg4NzTNo6h0qLuvFrcx+Sw==} + flatted@3.4.1: resolution: {integrity: sha512-IxfVbRFVlV8V/yRaGzk0UVIcsKKHMSfYw66T/u4nTwlWteQePsxe//LjudR1AMX4tZW3WFCh3Zqa/sjlqpbURQ==} @@ -3700,6 +3937,13 @@ packages: html-dom-parser@5.1.8: resolution: {integrity: sha512-MCIUng//mF2qTtGHXJWr6OLfHWmg3Pm8ezpfiltF83tizPWY17JxT4dRLE8lykJ5bChJELoY3onQKPbufJHxYA==} + html-encoding-sniffer@6.0.0: + resolution: {integrity: sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==} + engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + + html-escaper@2.0.2: + resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==} + html-parse-stringify@3.0.1: resolution: {integrity: sha512-KknJ50kTInJ7qIScF3jeaFRpMpE8/lfiTdzf/twXyPBLAGrLRTmkz3AdTnKeh40X8k9L2fdYwEp/42WGXIRGcg==} @@ -3756,6 +4000,10 @@ packages: resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} engines: {node: '>=0.8.19'} + indent-string@4.0.0: + resolution: {integrity: sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==} + engines: {node: '>=8'} + inline-style-parser@0.2.2: resolution: {integrity: sha512-EcKzdTHVe8wFVOGEYXiW9WmJXPjqi1T+234YpJr98RiFYKHV3cdy1+3mkTE+KHTHxFFLH51SfaGOoUdW+v7ViQ==} @@ -3862,6 +4110,9 @@ packages: resolution: {integrity: sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==} engines: {node: '>=0.10.0'} + is-potential-custom-element-name@1.0.1: + resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==} + is-regex@1.2.1: resolution: {integrity: sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==} engines: {node: '>= 0.4'} @@ -3912,6 +4163,18 @@ packages: isexe@2.0.0: resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + istanbul-lib-coverage@3.2.2: + resolution: {integrity: sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==} + engines: {node: '>=8'} + + istanbul-lib-report@3.0.1: + resolution: {integrity: sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==} + engines: {node: '>=10'} + + istanbul-reports@3.2.0: + resolution: {integrity: sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==} + engines: {node: '>=8'} + iterator.prototype@1.1.5: resolution: {integrity: sha512-H0dkQoCa3b2VEeKQBOxFph+JAbcrQdE7KC0UkqwpLmv2EC4P41QXP+rqo9wYodACiG5/WM5s9oDApTU8utwj9g==} engines: {node: '>= 0.4'} @@ -3950,6 +4213,9 @@ packages: react: optional: true + js-tokens@10.0.0: + resolution: {integrity: sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==} + js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} @@ -3957,6 +4223,15 @@ packages: resolution: {integrity: sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==} hasBin: true + jsdom@29.0.0: + resolution: {integrity: sha512-9FshNB6OepopZ08unmmGpsF7/qCjxGPbo3NbgfJAnPeHXnsODE9WWffXZtRFRFe0ntzaAOcSKNJFz8wiyvF1jQ==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24.0.0} + peerDependencies: + canvas: ^3.0.0 + peerDependenciesMeta: + canvas: + optional: true + jsesc@3.1.0: resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==} engines: {node: '>=6'} @@ -4080,15 +4355,30 @@ packages: resolution: {integrity: sha512-ESL2CrkS/2wTPfuend7Zhkzo2u0daGJ/A2VucJOgQ/C48S/zB8MMeMHSGKYpXhIjbPxfuezITkaBH1wqv00DDQ==} engines: {node: 20 || >=22} + lru-cache@11.2.7: + resolution: {integrity: sha512-aY/R+aEsRelme17KGQa/1ZSIpLpNYYrhcrepKTZgE+W3WM16YMCaPwOHLHsmopZHELU0Ojin1lPVxKR0MihncA==} + engines: {node: 20 || >=22} + lru-cache@5.1.1: resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==} + lz-string@1.5.0: + resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==} + hasBin: true + magic-string@0.25.9: resolution: {integrity: sha512-RmF0AsMzgt25qzqqLc1+MbHmhdx0ojF2Fvs4XnOqz2ZOBXzzkEwc/dJQZCYHAn7v1jbVOjAZfK8msRn4BxO4VQ==} magic-string@0.30.21: resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + magicast@0.5.2: + resolution: {integrity: sha512-E3ZJh4J3S9KfwdjZhe2afj6R9lGIN5Pher1pF39UGrXRqq/VDaGVIGN13BjHd2u8B61hArAGOnso7nBOouW3TQ==} + + make-dir@4.0.0: + resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==} + engines: {node: '>=10'} + math-intrinsics@1.1.0: resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} engines: {node: '>= 0.4'} @@ -4103,6 +4393,9 @@ packages: matrix-widget-api@1.13.0: resolution: {integrity: sha512-+LrvwkR1izL4h2euX8PDrvG/3PZZDEd6As+lmnR3jAVwbFJtU5iTnwmZGnCca9ddngCvXvAHkcpJBEPyPTZneQ==} + mdn-data@2.27.1: + resolution: {integrity: sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==} + media-query-parser@2.0.2: resolution: {integrity: sha512-1N4qp+jE0pL5Xv4uEcwVUhIkwdUO3S/9gML90nqKA7v7FcOS5vUtatfzok9S9U1EJU8dHWlcv95WLnKmmxZI9w==} @@ -4118,6 +4411,10 @@ packages: resolution: {integrity: sha512-H/E3J6t+DQs/F2YgfDhxUVZz/dF8JXPPKTLHL/yHCcLZLtCXJDUaqvhJXQwqOVBvbyNn4T0WjLpIHd7PAw7fBA==} hasBin: true + min-indent@1.0.1: + resolution: {integrity: sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==} + engines: {node: '>=4'} + miniflare@4.20260310.0: resolution: {integrity: sha512-uC5vNPenFpDSj5aUU3wGSABG6UUqMr+Xs1m4AkCrTHo37F4Z6xcQw5BXqViTfPDVT/zcYH1UgTVoXhr1l6ZMXw==} engines: {node: '>=18.0.0'} @@ -4146,6 +4443,10 @@ packages: motion-utils@12.29.2: resolution: {integrity: sha512-G3kc34H2cX2gI63RqU+cZq+zWRRPSsNIOjpdl9TN4AQwC4sgwYPl/Q/Obf/d53nOm569T0fYK+tcoSV50BWx8A==} + mrmime@2.0.1: + resolution: {integrity: sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==} + engines: {node: '>=10'} + ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} @@ -4220,6 +4521,9 @@ packages: resolution: {integrity: sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA==} engines: {node: '>= 0.4'} + obug@2.1.1: + resolution: {integrity: sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==} + oidc-client-ts@3.4.1: resolution: {integrity: sha512-jNdst/U28Iasukx/L5MP6b274Vr7ftQs6qAhPBCvz6Wt5rPCA+Q/tUmCzfCHHWweWw5szeMy2Gfrm1rITwUKrw==} engines: {node: '>=18'} @@ -4265,6 +4569,9 @@ packages: parse-srcset@1.0.2: resolution: {integrity: sha512-/2qh0lav6CmI15FzA3i/2Bzk2zCgQhGMkvhOhKNcBVQ1ldgpbfiNTVslmooUmWJcADi1f1kIeynbDRVzNlfR6Q==} + parse5@8.0.0: + resolution: {integrity: sha512-9m4m5GSgXjL4AjumKzq1Fgfp3Z8rsvjRNbnkVwfu2ImRqE5D0LnY2QfDen18FSY9C573YU5XxSapdHZTZ2WolA==} + path-exists@4.0.0: resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} engines: {node: '>=8'} @@ -4337,6 +4644,10 @@ packages: resolution: {integrity: sha512-mQUvGU6aUFQ+rNvTIAcZuWGRT9a6f6Yrg9bHs4ImKF+HZCEK+plBvnAZYSIQztknZF2qnzNtr6F8s0+IuptdlQ==} engines: {node: ^14.13.1 || >=16.0.0} + pretty-format@27.5.1: + resolution: {integrity: sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==} + engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0} + prismjs@1.30.0: resolution: {integrity: sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw==} engines: {node: '>=6'} @@ -4411,6 +4722,9 @@ packages: react-is@16.13.1: resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==} + react-is@17.0.2: + resolution: {integrity: sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==} + react-property@2.0.2: resolution: {integrity: sha512-+PbtI3VuDV0l6CleQMsx2gtK0JZbZKbpdu5ynr+lbsuvtmgbNcS3VM0tuY2QjFNOcWxvXeHjDpy42RO+4U2rug==} @@ -4445,6 +4759,10 @@ packages: resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==} engines: {node: '>=8.10.0'} + redent@3.0.0: + resolution: {integrity: sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==} + engines: {node: '>=8'} + reflect.getprototypeof@1.0.10: resolution: {integrity: sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==} engines: {node: '>= 0.4'} @@ -4526,6 +4844,10 @@ packages: sanitize-html@2.17.1: resolution: {integrity: sha512-ehFCW+q1a4CSOWRAdX97BX/6/PDEkCqw7/0JXZAGQV57FQB3YOkTa/rrzHPeJ+Aghy4vZAFfWMYyfxIiB7F/gw==} + saxes@6.0.0: + resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==} + engines: {node: '>=v12.22.7'} + scheduler@0.23.2: resolution: {integrity: sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==} @@ -4589,10 +4911,17 @@ packages: resolution: {integrity: sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==} engines: {node: '>= 0.4'} + siginfo@2.0.0: + resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + signal-exit@4.1.0: resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} engines: {node: '>=14'} + sirv@3.0.2: + resolution: {integrity: sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g==} + engines: {node: '>=18'} + slate-dom@0.123.0: resolution: {integrity: sha512-OUinp4tvSrAlt64JL9y20Xin08jgnnj1gJmIuPdGvU5MELKXRNZh17a7EKKNOS6OZPAE8Dk9NI1MAIS/Qz0YBw==} peerDependencies: @@ -4649,6 +4978,12 @@ packages: resolution: {integrity: sha512-o3yWv49B/o4QZk5ZcsALc6t0+eCelPc44zZsLtCQnZPDwFpDYSWcDnrv2TtMmMbQ7uKo3J0HTURCqckw23czNQ==} engines: {node: '>=12.0.0'} + stackback@0.0.2: + resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + + std-env@4.0.0: + resolution: {integrity: sha512-zUMPtQ/HBY3/50VbpkupYHbRroTRZJPRLvreamgErJVys0ceuzMkD44J/QjqhHjOzK42GQ3QZIeFG1OYfOtKqQ==} + stop-iteration-iterator@1.1.0: resolution: {integrity: sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==} engines: {node: '>= 0.4'} @@ -4696,6 +5031,10 @@ packages: resolution: {integrity: sha512-ZprKx+bBLXv067WTCALv8SSz5l2+XhpYCsVtSqlMnkAXMWDq+/ekVbl1ghqP9rUHTzv6sm/DwCOiYutU/yp1fw==} engines: {node: '>=10'} + strip-indent@3.0.0: + resolution: {integrity: sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==} + engines: {node: '>=8'} + strip-json-comments@3.1.1: resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==} engines: {node: '>=8'} @@ -4725,6 +5064,9 @@ packages: svg-parser@2.0.4: resolution: {integrity: sha512-e4hG1hRwoOdRb37cIMSgzNsxyzKfayW6VOflrwvR+/bzrkyxY/31WkbgnQpgtrNp1SdpJvpUAGTa/ZoiPNDuRQ==} + symbol-tree@3.2.4: + resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==} + synckit@0.11.12: resolution: {integrity: sha512-Bh7QjT8/SuKUIfObSXNHNSK6WHo6J1tHCqJsuaFDP7gP0fkzSfTxI8y85JrppZ0h8l0maIgc2tfuZQ6/t3GtnQ==} engines: {node: ^14.18.0 || >=16.0.0} @@ -4755,20 +5097,50 @@ packages: tiny-invariant@1.3.1: resolution: {integrity: sha512-AD5ih2NlSssTCwsMznbvwMZpJ1cbhkGd2uueNxzv2jDlEeZdU04JQfRnggJQ8DrcVBGjAsCKwFBbDlVNtEMlzw==} + tinybench@2.9.0: + resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + + tinyexec@1.0.4: + resolution: {integrity: sha512-u9r3uZC0bdpGOXtlxUIdwf9pkmvhqJdrVCH9fapQtgy/OeTTMZ1nqH7agtvEfmGui6e1XxjcdrlxvxJvc3sMqw==} + engines: {node: '>=18'} + tinyglobby@0.2.15: resolution: {integrity: sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==} engines: {node: '>=12.0.0'} + tinyrainbow@3.1.0: + resolution: {integrity: sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==} + engines: {node: '>=14.0.0'} + + tldts-core@7.0.25: + resolution: {integrity: sha512-ZjCZK0rppSBu7rjHYDYsEaMOIbbT+nWF57hKkv4IUmZWBNrBWBOjIElc0mKRgLM8bm7x/BBlof6t2gi/Oq/Asw==} + + tldts@7.0.25: + resolution: {integrity: sha512-keinCnPbwXEUG3ilrWQZU+CqcTTzHq9m2HhoUP2l7Xmi8l1LuijAXLpAJ5zRW+ifKTNscs4NdCkfkDCBYm352w==} + hasBin: true + to-regex-range@5.0.1: resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==} engines: {node: '>=8.0'} + totalist@3.0.1: + resolution: {integrity: sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==} + engines: {node: '>=6'} + + tough-cookie@6.0.1: + resolution: {integrity: sha512-LktZQb3IeoUWB9lqR5EWTHgW/VTITCXg4D21M+lvybRVdylLrRMnqaIONLVb5mav8vM19m44HIcGq4qASeu2Qw==} + engines: {node: '>=16'} + tr46@0.0.3: resolution: {integrity: sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==} tr46@1.0.1: resolution: {integrity: sha512-dTpowEjclQ7Kgx5SdBkqRzVhERQXov8/l9Ft9dVM9fmg0W0KQSVaXX9T4i6twCPNtYiZM53lpSSUAwJbFPOHxA==} + tr46@6.0.0: + resolution: {integrity: sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==} + engines: {node: '>=20'} + ts-api-utils@2.4.0: resolution: {integrity: sha512-3TaVTaAv2gTiMB35i3FiGJaRfwb3Pyn/j3m/bfAvGe8FB7CF6u+LMYqYlDh7reQf7UNvoTvdfAqHGmPGOSsPmA==} engines: {node: '>=18.12'} @@ -4840,6 +5212,10 @@ packages: resolution: {integrity: sha512-y+8YjDFzWdQlSE9N5nzKMT3g4a5UBX1HKowfdXh0uvAnTaqqwqB92Jt4UXBAeKekDs5IaDKyJFR4X1gYVCgXcw==} engines: {node: '>=20.18.1'} + undici@7.24.3: + resolution: {integrity: sha512-eJdUmK/Wrx2d+mnWWmwwLRyA7OQCkLap60sk3dOK4ViZR7DKwwptwuIvFBg2HaiP9ESaEdhtpSymQPvytpmkCA==} + engines: {node: '>=20.18.1'} + unenv@2.0.0-rc.24: resolution: {integrity: sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==} @@ -4975,10 +5351,49 @@ packages: yaml: optional: true + vitest@4.1.0: + resolution: {integrity: sha512-YbDrMF9jM2Lqc++2530UourxZHmkKLxrs4+mYhEwqWS97WJ7wOYEkcr+QfRgJ3PW9wz3odRijLZjHEaRLTNbqw==} + engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@opentelemetry/api': ^1.9.0 + '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0 + '@vitest/browser-playwright': 4.1.0 + '@vitest/browser-preview': 4.1.0 + '@vitest/browser-webdriverio': 4.1.0 + '@vitest/ui': 4.1.0 + happy-dom: '*' + jsdom: '*' + vite: ^6.0.0 || ^7.0.0 || ^8.0.0-0 + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@opentelemetry/api': + optional: true + '@types/node': + optional: true + '@vitest/browser-playwright': + optional: true + '@vitest/browser-preview': + optional: true + '@vitest/browser-webdriverio': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + void-elements@3.1.0: resolution: {integrity: sha512-Dhxzh5HZuiHQhbvTW9AMetFfBHDMYpo23Uo9btPXgdYP+3T5S+p+jgNy7spra+veYhBP2dCSgxR/i2Y02h5/6w==} engines: {node: '>=0.10.0'} + w3c-xmlserializer@5.0.0: + resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==} + engines: {node: '>=18'} + walk-up-path@4.0.0: resolution: {integrity: sha512-3hu+tD8YzSLGuFYtPRb48vdhKMi0KQV5sn+uWr8+7dMEq/2G/dtLrdDinkLjqq5TIbIBjYJ4Ax/n3YiaW7QM8A==} engines: {node: 20 || >=22} @@ -4989,6 +5404,18 @@ packages: webidl-conversions@4.0.2: resolution: {integrity: sha512-YQ+BmxuTgd6UXZW3+ICGfyqRyHXVlD5GtQr5+qjiNW7bF0cqrzX500HVXPBOvgXb5YnzDd+h0zqyv61KUD7+Sg==} + webidl-conversions@8.0.1: + resolution: {integrity: sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==} + engines: {node: '>=20'} + + whatwg-mimetype@5.0.0: + resolution: {integrity: sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==} + engines: {node: '>=20'} + + whatwg-url@16.0.1: + resolution: {integrity: sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==} + engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + whatwg-url@5.0.0: resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==} @@ -5016,6 +5443,11 @@ packages: engines: {node: '>= 8'} hasBin: true + why-is-node-running@2.3.0: + resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} + engines: {node: '>=8'} + hasBin: true + word-wrap@1.2.5: resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} engines: {node: '>=0.10.0'} @@ -5100,6 +5532,13 @@ packages: utf-8-validate: optional: true + xml-name-validator@5.0.0: + resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==} + engines: {node: '>=18'} + + xmlchars@2.2.0: + resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==} + y18n@5.0.8: resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} engines: {node: '>=10'} @@ -5141,6 +5580,8 @@ packages: snapshots: + '@adobe/css-tools@4.4.4': {} + '@apideck/better-ajv-errors@0.3.6(ajv@8.18.0)': dependencies: ajv: 8.18.0 @@ -5148,6 +5589,24 @@ snapshots: jsonpointer: 5.0.1 leven: 3.1.0 + '@asamuzakjp/css-color@5.0.1': + dependencies: + '@csstools/css-calc': 3.1.1(@csstools/css-parser-algorithms@4.0.0(@csstools/css-tokenizer@4.0.0))(@csstools/css-tokenizer@4.0.0) + '@csstools/css-color-parser': 4.0.2(@csstools/css-parser-algorithms@4.0.0(@csstools/css-tokenizer@4.0.0))(@csstools/css-tokenizer@4.0.0) + '@csstools/css-parser-algorithms': 4.0.0(@csstools/css-tokenizer@4.0.0) + '@csstools/css-tokenizer': 4.0.0 + lru-cache: 11.2.7 + + '@asamuzakjp/dom-selector@7.0.3': + dependencies: + '@asamuzakjp/nwsapi': 2.3.9 + bidi-js: 1.0.3 + css-tree: 3.2.1 + is-potential-custom-element-name: 1.0.1 + lru-cache: 11.2.7 + + '@asamuzakjp/nwsapi@2.3.9': {} + '@atlaskit/pragmatic-drag-and-drop-auto-scroll@1.4.0': dependencies: '@atlaskit/pragmatic-drag-and-drop': 1.7.9 @@ -5833,6 +6292,12 @@ snapshots: '@babel/helper-string-parser': 7.27.1 '@babel/helper-validator-identifier': 7.28.5 + '@bcoe/v8-coverage@1.0.2': {} + + '@bramus/specificity@2.4.2': + dependencies: + css-tree: 3.2.1 + '@cloudflare/kv-asset-handler@0.4.2': {} '@cloudflare/unenv-preset@2.15.0(unenv@2.0.0-rc.24)(workerd@1.20260310.1)': @@ -5873,6 +6338,30 @@ snapshots: dependencies: '@jridgewell/trace-mapping': 0.3.9 + '@csstools/color-helpers@6.0.2': {} + + '@csstools/css-calc@3.1.1(@csstools/css-parser-algorithms@4.0.0(@csstools/css-tokenizer@4.0.0))(@csstools/css-tokenizer@4.0.0)': + dependencies: + '@csstools/css-parser-algorithms': 4.0.0(@csstools/css-tokenizer@4.0.0) + '@csstools/css-tokenizer': 4.0.0 + + '@csstools/css-color-parser@4.0.2(@csstools/css-parser-algorithms@4.0.0(@csstools/css-tokenizer@4.0.0))(@csstools/css-tokenizer@4.0.0)': + dependencies: + '@csstools/color-helpers': 6.0.2 + '@csstools/css-calc': 3.1.1(@csstools/css-parser-algorithms@4.0.0(@csstools/css-tokenizer@4.0.0))(@csstools/css-tokenizer@4.0.0) + '@csstools/css-parser-algorithms': 4.0.0(@csstools/css-tokenizer@4.0.0) + '@csstools/css-tokenizer': 4.0.0 + + '@csstools/css-parser-algorithms@4.0.0(@csstools/css-tokenizer@4.0.0)': + dependencies: + '@csstools/css-tokenizer': 4.0.0 + + '@csstools/css-syntax-patches-for-csstree@1.1.1(css-tree@3.2.1)': + optionalDependencies: + css-tree: 3.2.1 + + '@csstools/css-tokenizer@4.0.0': {} + '@element-hq/element-call-embedded@0.16.3': {} '@emnapi/core@1.8.1': @@ -6031,6 +6520,8 @@ snapshots: '@eslint/core': 0.17.0 levn: 0.4.1 + '@exodus/bytes@1.15.0': {} + '@fontsource-variable/nunito@5.2.7': {} '@fontsource/space-mono@5.2.9': {} @@ -6362,6 +6853,8 @@ snapshots: '@pkgr/core@0.2.9': {} + '@polka/url@1.0.0-next.29': {} + '@poppinss/colors@4.1.6': dependencies: kleur: 4.1.5 @@ -7488,6 +7981,8 @@ snapshots: '@speed-highlight/core@1.2.14': {} + '@standard-schema/spec@1.1.0': {} + '@stylistic/eslint-plugin@5.10.0(eslint@9.39.3(jiti@2.6.1))': dependencies: '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.3(jiti@2.6.1)) @@ -7657,11 +8152,47 @@ snapshots: '@tanstack/virtual-core@3.13.21': {} + '@testing-library/dom@10.4.1': + dependencies: + '@babel/code-frame': 7.29.0 + '@babel/runtime': 7.28.6 + '@types/aria-query': 5.0.4 + aria-query: 5.3.0 + dom-accessibility-api: 0.5.16 + lz-string: 1.5.0 + picocolors: 1.1.1 + pretty-format: 27.5.1 + + '@testing-library/jest-dom@6.9.1': + dependencies: + '@adobe/css-tools': 4.4.4 + aria-query: 5.3.2 + css.escape: 1.5.1 + dom-accessibility-api: 0.6.3 + picocolors: 1.1.1 + redent: 3.0.0 + + '@testing-library/react@16.3.2(@testing-library/dom@10.4.1)(@types/react-dom@18.3.7(@types/react@18.3.28))(@types/react@18.3.28)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)': + dependencies: + '@babel/runtime': 7.28.6 + '@testing-library/dom': 10.4.1 + react: 18.3.1 + react-dom: 18.3.1(react@18.3.1) + optionalDependencies: + '@types/react': 18.3.28 + '@types/react-dom': 18.3.7(@types/react@18.3.28) + + '@testing-library/user-event@14.6.1(@testing-library/dom@10.4.1)': + dependencies: + '@testing-library/dom': 10.4.1 + '@tybys/wasm-util@0.10.1': dependencies: tslib: 2.8.1 optional: true + '@types/aria-query@5.0.4': {} + '@types/babel__core@7.20.5': dependencies: '@babel/parser': 7.29.0 @@ -7683,8 +8214,15 @@ snapshots: dependencies: '@babel/types': 7.29.0 + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + '@types/chroma-js@3.1.2': {} + '@types/deep-eql@4.0.2': {} + '@types/estree@0.0.39': {} '@types/estree@1.0.8': {} @@ -7985,6 +8523,72 @@ snapshots: transitivePeerDependencies: - supports-color + '@vitest/coverage-v8@4.1.0(vitest@4.1.0)': + dependencies: + '@bcoe/v8-coverage': 1.0.2 + '@vitest/utils': 4.1.0 + ast-v8-to-istanbul: 1.0.0 + istanbul-lib-coverage: 3.2.2 + istanbul-lib-report: 3.0.1 + istanbul-reports: 3.2.0 + magicast: 0.5.2 + 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/expect@4.1.0': + dependencies: + '@standard-schema/spec': 1.1.0 + '@types/chai': 5.2.3 + '@vitest/spy': 4.1.0 + '@vitest/utils': 4.1.0 + 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))': + 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) + + '@vitest/pretty-format@4.1.0': + dependencies: + tinyrainbow: 3.1.0 + + '@vitest/runner@4.1.0': + dependencies: + '@vitest/utils': 4.1.0 + pathe: 2.0.3 + + '@vitest/snapshot@4.1.0': + dependencies: + '@vitest/pretty-format': 4.1.0 + '@vitest/utils': 4.1.0 + magic-string: 0.30.21 + pathe: 2.0.3 + + '@vitest/spy@4.1.0': {} + + '@vitest/ui@4.1.0(vitest@4.1.0)': + dependencies: + '@vitest/utils': 4.1.0 + fflate: 0.8.2 + flatted: 3.4.0 + pathe: 2.0.3 + 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/utils@4.1.0': + dependencies: + '@vitest/pretty-format': 4.1.0 + convert-source-map: 2.0.0 + tinyrainbow: 3.1.0 + acorn-jsx@5.3.2(acorn@8.16.0): dependencies: acorn: 8.16.0 @@ -8013,6 +8617,8 @@ snapshots: dependencies: color-convert: 2.0.1 + ansi-styles@5.2.0: {} + anymatch@3.1.3: dependencies: normalize-path: 3.0.0 @@ -8020,6 +8626,10 @@ snapshots: argparse@2.0.1: {} + aria-query@5.3.0: + dependencies: + dequal: 2.0.3 + aria-query@5.3.2: {} array-buffer-byte-length@1.0.2: @@ -8089,8 +8699,16 @@ snapshots: get-intrinsic: 1.3.0 is-array-buffer: 3.0.5 + assertion-error@2.0.1: {} + ast-types-flow@0.0.8: {} + ast-v8-to-istanbul@1.0.0: + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + estree-walker: 3.0.3 + js-tokens: 10.0.0 + async-function@1.0.0: {} async@3.2.6: {} @@ -8141,6 +8759,10 @@ snapshots: baseline-browser-mapping@2.10.0: {} + bidi-js@1.0.3: + dependencies: + require-from-string: 2.0.2 + binary-extensions@2.3.0: {} bind-event-listener@3.0.0: {} @@ -8203,6 +8825,8 @@ snapshots: caniuse-lite@1.0.30001777: {} + chai@6.2.2: {} + chalk@4.1.2: dependencies: ansi-styles: 4.3.0 @@ -8283,14 +8907,28 @@ snapshots: crypto-random-string@2.0.0: {} + css-tree@3.2.1: + dependencies: + mdn-data: 2.27.1 + source-map-js: 1.2.1 + css-what@6.2.2: {} + css.escape@1.5.1: {} + cssesc@3.0.0: {} csstype@3.2.3: {} damerau-levenshtein@1.0.8: {} + data-urls@7.0.0: + dependencies: + whatwg-mimetype: 5.0.0 + whatwg-url: 16.0.1 + transitivePeerDependencies: + - '@noble/hashes' + data-view-buffer@1.0.2: dependencies: call-bound: 1.0.4 @@ -8341,6 +8979,8 @@ snapshots: has-property-descriptors: 1.0.2 object-keys: 1.1.1 + dequal@2.0.3: {} + detect-libc@2.1.2: {} direction@1.0.4: {} @@ -8349,6 +8989,10 @@ snapshots: dependencies: esutils: 2.0.3 + dom-accessibility-api@0.5.16: {} + + dom-accessibility-api@0.6.3: {} + dom-serializer@2.0.0: dependencies: domelementtype: 2.3.0 @@ -8401,6 +9045,8 @@ snapshots: entities@4.5.0: {} + entities@6.0.1: {} + entities@7.0.1: {} error-ex@1.3.4: @@ -8491,6 +9137,8 @@ snapshots: es-module-lexer@1.7.0: {} + es-module-lexer@2.0.0: {} + es-object-atoms@1.1.1: dependencies: es-errors: 1.3.0 @@ -8821,6 +9469,10 @@ snapshots: estree-walker@2.0.2: {} + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.8 + esutils@2.0.3: {} eval@0.1.8: @@ -8832,6 +9484,8 @@ snapshots: events@3.3.0: {} + expect-type@1.3.0: {} + fast-deep-equal@3.1.3: {} fast-diff@1.3.0: {} @@ -8870,6 +9524,8 @@ snapshots: optionalDependencies: picomatch: 4.0.3 + fflate@0.8.2: {} + file-entry-cache@8.0.0: dependencies: flat-cache: 4.0.1 @@ -8894,6 +9550,8 @@ snapshots: flatted: 3.4.1 keyv: 4.5.4 + flatted@3.4.0: {} + flatted@3.4.1: {} focus-trap-react@10.3.1(prop-types@15.8.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1): @@ -9073,6 +9731,14 @@ snapshots: domhandler: 5.0.3 htmlparser2: 10.1.0 + html-encoding-sniffer@6.0.0: + dependencies: + '@exodus/bytes': 1.15.0 + transitivePeerDependencies: + - '@noble/hashes' + + html-escaper@2.0.2: {} + html-parse-stringify@3.0.1: dependencies: void-elements: 3.1.0 @@ -9139,6 +9805,8 @@ snapshots: imurmurhash@0.1.4: {} + indent-string@4.0.0: {} + inline-style-parser@0.2.2: {} internal-slot@1.1.0: @@ -9245,6 +9913,8 @@ snapshots: is-plain-object@5.0.0: {} + is-potential-custom-element-name@1.0.1: {} + is-regex@1.2.1: dependencies: call-bound: 1.0.4 @@ -9292,6 +9962,19 @@ snapshots: isexe@2.0.0: {} + istanbul-lib-coverage@3.2.2: {} + + istanbul-lib-report@3.0.1: + dependencies: + istanbul-lib-coverage: 3.2.2 + make-dir: 4.0.0 + supports-color: 7.2.0 + + istanbul-reports@3.2.0: + dependencies: + html-escaper: 2.0.2 + istanbul-lib-report: 3.0.1 + iterator.prototype@1.1.5: dependencies: define-data-property: 1.1.4 @@ -9322,12 +10005,40 @@ snapshots: '@types/react': 18.3.28 react: 18.3.1 + js-tokens@10.0.0: {} + js-tokens@4.0.0: {} js-yaml@4.1.1: dependencies: argparse: 2.0.1 + jsdom@29.0.0: + dependencies: + '@asamuzakjp/css-color': 5.0.1 + '@asamuzakjp/dom-selector': 7.0.3 + '@bramus/specificity': 2.4.2 + '@csstools/css-syntax-patches-for-csstree': 1.1.1(css-tree@3.2.1) + '@exodus/bytes': 1.15.0 + css-tree: 3.2.1 + data-urls: 7.0.0 + decimal.js: 10.6.0 + html-encoding-sniffer: 6.0.0 + is-potential-custom-element-name: 1.0.1 + lru-cache: 11.2.7 + parse5: 8.0.0 + saxes: 6.0.0 + symbol-tree: 3.2.4 + tough-cookie: 6.0.1 + undici: 7.24.3 + w3c-xmlserializer: 5.0.0 + webidl-conversions: 8.0.1 + whatwg-mimetype: 5.0.0 + whatwg-url: 16.0.1 + xml-name-validator: 5.0.0 + transitivePeerDependencies: + - '@noble/hashes' + jsesc@3.1.0: {} json-buffer@3.0.1: {} @@ -9436,10 +10147,14 @@ snapshots: lru-cache@11.2.6: {} + lru-cache@11.2.7: {} + lru-cache@5.1.1: dependencies: yallist: 3.1.1 + lz-string@1.5.0: {} + magic-string@0.25.9: dependencies: sourcemap-codec: 1.4.8 @@ -9448,6 +10163,16 @@ snapshots: dependencies: '@jridgewell/sourcemap-codec': 1.5.5 + magicast@0.5.2: + dependencies: + '@babel/parser': 7.29.0 + '@babel/types': 7.29.0 + source-map-js: 1.2.1 + + make-dir@4.0.0: + dependencies: + semver: 7.7.4 + math-intrinsics@1.1.0: {} matrix-events-sdk@0.0.1: {} @@ -9474,6 +10199,8 @@ snapshots: '@types/events': 3.0.3 events: 3.3.0 + mdn-data@2.27.1: {} + media-query-parser@2.0.2: dependencies: '@babel/runtime': 7.28.6 @@ -9489,6 +10216,8 @@ snapshots: dependencies: yargs: 17.7.2 + min-indent@1.0.1: {} + miniflare@4.20260310.0: dependencies: '@cspotcode/source-map-support': 0.8.1 @@ -9524,6 +10253,8 @@ snapshots: motion-utils@12.29.2: {} + mrmime@2.0.1: {} + ms@2.1.3: {} nanoid@3.3.11: {} @@ -9597,6 +10328,8 @@ snapshots: define-properties: 1.2.1 es-object-atoms: 1.1.1 + obug@2.1.1: {} + oidc-client-ts@3.4.1: dependencies: jwt-decode: 4.0.0 @@ -9668,6 +10401,10 @@ snapshots: parse-srcset@1.0.2: {} + parse5@8.0.0: + dependencies: + entities: 6.0.1 + path-exists@4.0.0: {} path-key@3.1.1: {} @@ -9722,6 +10459,12 @@ snapshots: pretty-bytes@6.1.1: {} + pretty-format@27.5.1: + dependencies: + ansi-regex: 5.0.1 + ansi-styles: 5.2.0 + react-is: 17.0.2 + prismjs@1.30.0: {} prop-types@15.8.1: @@ -9829,6 +10572,8 @@ snapshots: react-is@16.13.1: {} + react-is@17.0.2: {} + react-property@2.0.2: {} react-range@1.10.0(react-dom@18.3.1(react@18.3.1))(react@18.3.1): @@ -9858,6 +10603,11 @@ snapshots: dependencies: picomatch: 2.3.1 + redent@3.0.0: + dependencies: + indent-string: 4.0.0 + strip-indent: 3.0.0 + reflect.getprototypeof@1.0.10: dependencies: call-bind: 1.0.8 @@ -9989,6 +10739,10 @@ snapshots: parse-srcset: 1.0.2 postcss: 8.5.8 + saxes@6.0.0: + dependencies: + xmlchars: 2.2.0 + scheduler@0.23.2: dependencies: loose-envify: 1.4.0 @@ -10092,8 +10846,16 @@ snapshots: side-channel-map: 1.0.1 side-channel-weakmap: 1.0.2 + siginfo@2.0.0: {} + signal-exit@4.1.0: {} + sirv@3.0.2: + dependencies: + '@polka/url': 1.0.0-next.29 + mrmime: 2.0.1 + totalist: 3.0.1 + slate-dom@0.123.0(slate@0.123.0): dependencies: '@juggle/resize-observer': 3.4.0 @@ -10151,6 +10913,10 @@ snapshots: stable-hash-x@0.2.0: {} + stackback@0.0.2: {} + + std-env@4.0.0: {} + stop-iteration-iterator@1.1.0: dependencies: es-errors: 1.3.0 @@ -10226,6 +10992,10 @@ snapshots: strip-comments@2.0.1: {} + strip-indent@3.0.0: + dependencies: + min-indent: 1.0.1 + strip-json-comments@3.1.1: {} strip-json-comments@5.0.3: {} @@ -10248,6 +11018,8 @@ snapshots: svg-parser@2.0.4: {} + symbol-tree@3.2.4: {} + synckit@0.11.12: dependencies: '@pkgr/core': 0.2.9 @@ -10276,21 +11048,43 @@ snapshots: tiny-invariant@1.3.1: {} + tinybench@2.9.0: {} + + tinyexec@1.0.4: {} + tinyglobby@0.2.15: dependencies: fdir: 6.5.0(picomatch@4.0.3) picomatch: 4.0.3 + tinyrainbow@3.1.0: {} + + tldts-core@7.0.25: {} + + tldts@7.0.25: + dependencies: + tldts-core: 7.0.25 + to-regex-range@5.0.1: dependencies: is-number: 7.0.0 + totalist@3.0.1: {} + + tough-cookie@6.0.1: + dependencies: + tldts: 7.0.25 + tr46@0.0.3: {} tr46@1.0.1: dependencies: punycode: 2.3.1 + tr46@6.0.0: + dependencies: + punycode: 2.3.1 + ts-api-utils@2.4.0(typescript@5.9.3): dependencies: typescript: 5.9.3 @@ -10376,6 +11170,8 @@ snapshots: undici@7.18.2: {} + undici@7.24.3: {} + unenv@2.0.0-rc.24: dependencies: pathe: 2.0.3 @@ -10527,14 +11323,59 @@ snapshots: 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.0)(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/pretty-format': 4.1.0 + '@vitest/runner': 4.1.0 + '@vitest/snapshot': 4.1.0 + '@vitest/spy': 4.1.0 + '@vitest/utils': 4.1.0 + es-module-lexer: 2.0.0 + expect-type: 1.3.0 + magic-string: 0.30.21 + obug: 2.1.1 + pathe: 2.0.3 + picomatch: 4.0.3 + std-env: 4.0.0 + tinybench: 2.9.0 + 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) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 24.10.13 + '@vitest/ui': 4.1.0(vitest@4.1.0) + jsdom: 29.0.0 + transitivePeerDependencies: + - msw + void-elements@3.1.0: {} + w3c-xmlserializer@5.0.0: + dependencies: + xml-name-validator: 5.0.0 + walk-up-path@4.0.0: {} webidl-conversions@3.0.1: {} webidl-conversions@4.0.2: {} + webidl-conversions@8.0.1: {} + + whatwg-mimetype@5.0.0: {} + + whatwg-url@16.0.1: + dependencies: + '@exodus/bytes': 1.15.0 + tr46: 6.0.0 + webidl-conversions: 8.0.1 + transitivePeerDependencies: + - '@noble/hashes' + whatwg-url@5.0.0: dependencies: tr46: 0.0.3 @@ -10591,6 +11432,11 @@ snapshots: dependencies: isexe: 2.0.0 + why-is-node-running@2.3.0: + dependencies: + siginfo: 2.0.0 + stackback: 0.0.2 + word-wrap@1.2.5: {} workbox-background-sync@7.4.0: @@ -10738,6 +11584,10 @@ snapshots: ws@8.18.0: {} + xml-name-validator@5.0.0: {} + + xmlchars@2.2.0: {} + y18n@5.0.8: {} yallist@3.1.1: {} diff --git a/src/app/utils/colorMXID.test.ts b/src/app/utils/colorMXID.test.ts new file mode 100644 index 00000000..c73e04fa --- /dev/null +++ b/src/app/utils/colorMXID.test.ts @@ -0,0 +1,36 @@ +// Example: testing pure utility functions. +// These are the simplest tests to write — no mocking or DOM needed. +import { describe, it, expect } from 'vitest'; +import colorMXID, { cssColorMXID } from './colorMXID'; + +describe('colorMXID', () => { + it('returns a valid hsl() string', () => { + expect(colorMXID('@alice:example.com')).toMatch(/^hsl\(\d+, 65%, 80%\)$/); + }); + + it('is deterministic', () => { + expect(colorMXID('@alice:example.com')).toBe(colorMXID('@alice:example.com')); + }); + + it('produces different colors for different users', () => { + expect(colorMXID('@alice:example.com')).not.toBe(colorMXID('@bob:example.com')); + }); + + it('handles undefined without throwing', () => { + expect(colorMXID(undefined)).toBe('hsl(0, 65%, 80%)'); + }); +}); + +describe('cssColorMXID', () => { + it('returns a CSS variable in the --mx-uc-1 to --mx-uc-8 range', () => { + // Run many users through it so we cover the full 0-7 modulo range + const results = ['@a', '@b', '@c', '@d', '@e', '@f', '@g', '@h'].map(cssColorMXID); + results.forEach((v) => { + expect(v).toMatch(/^--mx-uc-[1-8]$/); + }); + }); + + it('handles undefined without throwing', () => { + expect(cssColorMXID(undefined)).toBe('--mx-uc-1'); + }); +}); diff --git a/src/app/utils/common.test.ts b/src/app/utils/common.test.ts new file mode 100644 index 00000000..2a391670 --- /dev/null +++ b/src/app/utils/common.test.ts @@ -0,0 +1,37 @@ +// Example: testing a utility file with multiple related exports. +// Uses it.each for table-driven tests — good for exhaustive format coverage. +import { describe, it, expect } from 'vitest'; +import { bytesToSize, millisecondsToMinutesAndSeconds, secondsToMinutesAndSeconds } from './common'; + +describe('bytesToSize', () => { + it.each([ + [0, '0KB'], + [1_500, '1.5 KB'], + [2_500_000, '2.5 MB'], + [3_200_000_000, '3.2 GB'], + ])('bytesToSize(%i) → %s', (input, expected) => { + expect(bytesToSize(input)).toBe(expected); + }); +}); + +describe('millisecondsToMinutesAndSeconds', () => { + it.each([ + [0, '0:00'], + [5_000, '0:05'], + [60_000, '1:00'], + [90_000, '1:30'], + [3_661_000, '61:01'], + ])('%ims → %s', (ms, expected) => { + expect(millisecondsToMinutesAndSeconds(ms)).toBe(expected); + }); +}); + +describe('secondsToMinutesAndSeconds', () => { + it.each([ + [0, '0:00'], + [9, '0:09'], + [125, '2:05'], + ])('%is → %s', (s, expected) => { + expect(secondsToMinutesAndSeconds(s)).toBe(expected); + }); +}); diff --git a/src/app/utils/findAndReplace.test.ts b/src/app/utils/findAndReplace.test.ts new file mode 100644 index 00000000..6eda8e37 --- /dev/null +++ b/src/app/utils/findAndReplace.test.ts @@ -0,0 +1,59 @@ +// Example: testing an algorithmic utility with multiple interaction scenarios. +// Shows how to test functions that return arrays, and how to test edge cases +// like empty input, no matches, and back-to-back matches. +import { describe, it, expect } from 'vitest'; +import { findAndReplace } from './findAndReplace'; + +// Helpers that mirror what a real caller would pass +const asText = (text: string) => ({ type: 'text', text }) as const; +const asMatch = (match: string) => ({ type: 'match', match }) as const; + +describe('findAndReplace', () => { + it('returns the original text when there are no matches', () => { + const result = findAndReplace('hello world', /xyz/g, (m) => asMatch(m[0]), asText); + expect(result).toEqual([asText('hello world')]); + }); + + it('splits text around a single match', () => { + const result = findAndReplace('say hello there', /hello/g, (m) => asMatch(m[0]), asText); + expect(result).toEqual([asText('say '), asMatch('hello'), asText(' there')]); + }); + + it('handles multiple matches in sequence', () => { + const result = findAndReplace('a b a', /a/g, (m) => asMatch(m[0]), asText); + expect(result).toEqual([asText(''), asMatch('a'), asText(' b '), asMatch('a'), asText('')]); + }); + + it('handles a match at the very start', () => { + const result = findAndReplace('helloworld', /hello/g, (m) => asMatch(m[0]), asText); + expect(result).toEqual([asText(''), asMatch('hello'), asText('world')]); + }); + + it('handles a match at the very end', () => { + const result = findAndReplace('worldhello', /hello/g, (m) => asMatch(m[0]), asText); + expect(result).toEqual([asText('world'), asMatch('hello'), asText('')]); + }); + + it('handles an empty input string', () => { + const result = findAndReplace('', /hello/g, (m) => asMatch(m[0]), asText); + expect(result).toEqual([asText('')]); + }); + + it('passes the correct pushIndex to callbacks', () => { + const indices: number[] = []; + findAndReplace( + 'a b', + /[ab]/g, + (m, i) => { + indices.push(i); + return asMatch(m[0]); + }, + (t, i) => { + indices.push(i); + return asText(t); + } + ); + // indices are assigned in push order: text(''), match('a'), text(' '), match('b'), text('') + expect(indices).toEqual([0, 1, 2, 3, 4]); + }); +}); diff --git a/src/app/utils/sort.test.ts b/src/app/utils/sort.test.ts new file mode 100644 index 00000000..bda66e23 --- /dev/null +++ b/src/app/utils/sort.test.ts @@ -0,0 +1,99 @@ +// Example: testing factory functions (functions that return functions). +// Shows how to build lightweight fakes/stubs instead of using a full mock library — +// for factoryRoomIdByActivity and factoryRoomIdByAtoZ the MatrixClient is stubbed +// with a plain object, keeping tests readable without heavy setup. +import { describe, it, expect } from 'vitest'; +import type { MatrixClient } from '$types/matrix-sdk'; +import { + byOrderKey, + byTsOldToNew, + factoryRoomIdByActivity, + factoryRoomIdByAtoZ, + factoryRoomIdByUnreadCount, +} from './sort'; + +// Minimal stub that satisfies the MatrixClient shape needed by these sort functions. +function makeClient(rooms: Record): MatrixClient { + return { + getRoom: (id: string) => { + const r = rooms[id]; + if (!r) return null; + return { name: r.name, getLastActiveTimestamp: () => r.ts } as any; + }, + } as unknown as MatrixClient; +} + +describe('byTsOldToNew', () => { + it('sorts ascending by timestamp', () => { + expect([300, 100, 200].sort(byTsOldToNew)).toEqual([100, 200, 300]); + }); +}); + +describe('byOrderKey', () => { + it('sorts defined keys lexicographically', () => { + expect(['c', 'a', 'b'].sort(byOrderKey)).toEqual(['a', 'b', 'c']); + }); + + it('puts undefined keys after defined keys', () => { + expect([undefined, 'a', undefined, 'b'].sort(byOrderKey)).toEqual([ + 'a', + 'b', + undefined, + undefined, + ]); + }); +}); + +describe('factoryRoomIdByActivity', () => { + it('sorts rooms most-recently-active first', () => { + const mx = makeClient({ + '!old:h': { name: 'Old', ts: 1000 }, + '!new:h': { name: 'New', ts: 9000 }, + '!mid:h': { name: 'Mid', ts: 5000 }, + }); + const sort = factoryRoomIdByActivity(mx); + expect(['!old:h', '!new:h', '!mid:h'].sort(sort)).toEqual(['!new:h', '!mid:h', '!old:h']); + }); + + it('places unknown room IDs last', () => { + const mx = makeClient({ '!known:h': { name: 'Known', ts: 1000 } }); + const sort = factoryRoomIdByActivity(mx); + expect(['!unknown:h', '!known:h'].sort(sort)).toEqual(['!known:h', '!unknown:h']); + }); +}); + +describe('factoryRoomIdByAtoZ', () => { + it('sorts room names case-insensitively A→Z', () => { + const mx = makeClient({ + '!c:h': { name: 'Charlie', ts: 0 }, + '!a:h': { name: 'Alice', ts: 0 }, + '!b:h': { name: 'bob', ts: 0 }, + }); + const sort = factoryRoomIdByAtoZ(mx); + expect(['!c:h', '!a:h', '!b:h'].sort(sort)).toEqual(['!a:h', '!b:h', '!c:h']); + }); + + it('strips leading # before comparing', () => { + const mx = makeClient({ + '!hash:h': { name: '#alpha', ts: 0 }, + '!plain:h': { name: 'beta', ts: 0 }, + }); + const sort = factoryRoomIdByAtoZ(mx); + // #alpha → "alpha" sorts before "beta" + expect(['!plain:h', '!hash:h'].sort(sort)).toEqual(['!hash:h', '!plain:h']); + }); +}); + +describe('factoryRoomIdByUnreadCount', () => { + it('sorts rooms with more unreads first', () => { + const counts: Record = { '!a:h': 5, '!b:h': 20, '!c:h': 1 }; + const sort = factoryRoomIdByUnreadCount((id) => counts[id] ?? 0); + expect(['!a:h', '!b:h', '!c:h'].sort(sort)).toEqual(['!b:h', '!a:h', '!c:h']); + }); + + it('treats missing counts as 0', () => { + const sort = factoryRoomIdByUnreadCount(() => 0); + const result = ['!a:h', '!b:h'].sort(sort); + expect(result).toHaveLength(2); + }); +}); diff --git a/src/test/setup.ts b/src/test/setup.ts new file mode 100644 index 00000000..7b0828bf --- /dev/null +++ b/src/test/setup.ts @@ -0,0 +1 @@ +import '@testing-library/jest-dom'; diff --git a/tsconfig.json b/tsconfig.json index 839ef9d3..a18b41f9 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -32,5 +32,5 @@ "lib": ["ES2022", "DOM"] }, "exclude": ["node_modules", "dist"], - "include": ["src", "vite.config.ts"] + "include": ["src", "vite.config.ts", "vitest.config.ts"] } diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 00000000..fedea115 --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,51 @@ +import { defineConfig } from 'vitest/config'; +import react from '@vitejs/plugin-react'; +import { vanillaExtractPlugin } from '@vanilla-extract/vite-plugin'; +import path from 'path'; + +// Standalone Vitest config — intentionally excludes Cloudflare, PWA, compression, +// and other production-only Vite plugins that don't apply to unit tests. +export default defineConfig({ + plugins: [react(), vanillaExtractPlugin()], + resolve: { + alias: { + $hooks: path.resolve(__dirname, 'src/app/hooks'), + $plugins: path.resolve(__dirname, 'src/app/plugins'), + $components: path.resolve(__dirname, 'src/app/components'), + $features: path.resolve(__dirname, 'src/app/features'), + $state: path.resolve(__dirname, 'src/app/state'), + $styles: path.resolve(__dirname, 'src/app/styles'), + $utils: path.resolve(__dirname, 'src/app/utils'), + $pages: path.resolve(__dirname, 'src/app/pages'), + $types: path.resolve(__dirname, 'src/types'), + $public: path.resolve(__dirname, 'public'), + $client: path.resolve(__dirname, 'src/client'), + }, + }, + define: { + APP_VERSION: JSON.stringify('test'), + BUILD_HASH: JSON.stringify(''), + IS_RELEASE_TAG: JSON.stringify(false), + }, + test: { + environment: 'jsdom', + globals: true, + setupFiles: ['./src/test/setup.ts'], + include: ['src/**/*.{test,spec}.{ts,tsx}'], + coverage: { + provider: 'v8', + reporter: ['text', 'html', 'lcov'], + include: ['src/**/*.{ts,tsx}'], + exclude: [ + 'src/**/*.d.ts', + 'src/index.tsx', + 'src/sw.ts', + 'src/sw-session.ts', + 'src/instrument.ts', + 'src/test/**', + 'src/**/*.test.{ts,tsx}', + 'src/**/*.spec.{ts,tsx}', + ], + }, + }, +}); From bfe766ead95567be77cc9bbb4a23351aa53435a3 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 13:34:02 -0400 Subject: [PATCH 072/146] test: add unit and integration tests for utils and hooks --- knip.json | 1 - src/app/hooks/useAsyncCallback.test.tsx | 126 ++++++++++++++++++++++ src/app/hooks/usePreviousValue.test.tsx | 51 +++++++++ src/app/hooks/useTimeoutToggle.test.tsx | 101 +++++++++++++++++ src/app/utils/common.test.ts | 138 +++++++++++++++++++++++- src/app/utils/sanitize.test.ts | 125 +++++++++++++++++++++ src/app/utils/time.test.ts | 99 +++++++++++++++++ 7 files changed, 639 insertions(+), 2 deletions(-) create mode 100644 src/app/hooks/useAsyncCallback.test.tsx create mode 100644 src/app/hooks/usePreviousValue.test.tsx create mode 100644 src/app/hooks/useTimeoutToggle.test.tsx create mode 100644 src/app/utils/sanitize.test.ts create mode 100644 src/app/utils/time.test.ts diff --git a/knip.json b/knip.json index 02c8ee9f..eb88c8d6 100644 --- a/knip.json +++ b/knip.json @@ -9,7 +9,6 @@ "buffer", "@element-hq/element-call-embedded", "@matrix-org/matrix-sdk-crypto-wasm", - "@testing-library/react", "@testing-library/user-event" ], "ignoreBinaries": ["knope"], diff --git a/src/app/hooks/useAsyncCallback.test.tsx b/src/app/hooks/useAsyncCallback.test.tsx new file mode 100644 index 00000000..c27d0647 --- /dev/null +++ b/src/app/hooks/useAsyncCallback.test.tsx @@ -0,0 +1,126 @@ +// Integration tests: renderHook exercises the full React lifecycle including +// useAlive (cleanup on unmount) and retry-race-condition logic. +import { describe, it, expect } from 'vitest'; +import { renderHook, act } from '@testing-library/react'; +import { useAsyncCallback, AsyncStatus } from './useAsyncCallback'; + +describe('useAsyncCallback', () => { + it('starts in Idle state', () => { + const { result } = renderHook(() => useAsyncCallback(async () => 'value')); + const [state] = result.current; + expect(state.status).toBe(AsyncStatus.Idle); + }); + + it('transitions to Success with returned data', async () => { + const { result } = renderHook(() => useAsyncCallback(async () => 42)); + + await act(async () => { + await result.current[1](); + }); + + expect(result.current[0]).toEqual({ status: AsyncStatus.Success, data: 42 }); + }); + + it('transitions to Error when the async function throws', async () => { + const boom = new Error('boom'); + const { result } = renderHook(() => + useAsyncCallback(async () => { + throw boom; + }) + ); + + await act(async () => { + await result.current[1]().catch(() => {}); + }); + + expect(result.current[0]).toEqual({ status: AsyncStatus.Error, error: boom }); + }); + + it('ignores the result of a stale (superseded) request', async () => { + // Two calls are made. The first resolves AFTER the second — its result should + // be discarded so the final state reflects only the second call. + let resolveFirst!: (v: string) => void; + let resolveSecond!: (v: string) => void; + let callCount = 0; + + const { result } = renderHook(() => + useAsyncCallback(async () => { + callCount += 1; + if (callCount === 1) { + return new Promise((res) => { + resolveFirst = res; + }); + } + return new Promise((res) => { + resolveSecond = res; + }); + }) + ); + + // Fire both requests before either resolves + act(() => { + result.current[1](); + }); + act(() => { + result.current[1](); + }); + + // Resolve the stale first request — its result should be ignored + await act(async () => { + resolveFirst('stale'); + await Promise.resolve(); + }); + + // Resolve the fresh second request — this should be the final state + await act(async () => { + resolveSecond('fresh'); + await Promise.resolve(); + }); + + const successStates = result.current[0]; + expect(successStates.status).toBe(AsyncStatus.Success); + if (successStates.status === AsyncStatus.Success) { + expect(successStates.data).toBe('fresh'); + } + }); + + it('does not call setState after the component unmounts', async () => { + let resolveAfterUnmount!: (v: string) => void; + const stateChanges: string[] = []; + + const { result, unmount } = renderHook(() => + useAsyncCallback( + async () => + new Promise((res) => { + resolveAfterUnmount = res; + }) + ) + ); + + // Track state changes via the third returned setter + const [, callback, setState] = result.current; + const originalSetState = setState; + // Patch setState to record calls + result.current[2] = (s) => { + stateChanges.push(typeof s === 'function' ? 'fn' : s.status); + originalSetState(s); + }; + + act(() => { + callback(); + }); + + unmount(); + + // Resolve after unmount — alive() returns false, so state should NOT be updated + await act(async () => { + resolveAfterUnmount('late'); + await Promise.resolve(); + }); + + // Only the Loading state (queued before unmount) may have been emitted; + // Success must not appear after unmount. + const successCalls = stateChanges.filter((s) => s === AsyncStatus.Success); + expect(successCalls).toHaveLength(0); + }); +}); diff --git a/src/app/hooks/usePreviousValue.test.tsx b/src/app/hooks/usePreviousValue.test.tsx new file mode 100644 index 00000000..9c347975 --- /dev/null +++ b/src/app/hooks/usePreviousValue.test.tsx @@ -0,0 +1,51 @@ +// Integration tests: renders a real React component tree via renderHook. +import { describe, it, expect } from 'vitest'; +import { renderHook } from '@testing-library/react'; +import { usePreviousValue } from './usePreviousValue'; + +describe('usePreviousValue', () => { + it('returns the initial value on the first render', () => { + const { result } = renderHook(() => usePreviousValue('current', 'initial')); + expect(result.current).toBe('initial'); + }); + + it('returns the previous value after a prop update', () => { + const { result, rerender } = renderHook( + ({ value }: { value: string }) => usePreviousValue(value, 'initial'), + { initialProps: { value: 'first' } } + ); + + // Before any update: returns initial + expect(result.current).toBe('initial'); + + rerender({ value: 'second' }); + expect(result.current).toBe('first'); + + rerender({ value: 'third' }); + expect(result.current).toBe('second'); + }); + + it('works with numeric values', () => { + const { result, rerender } = renderHook(({ n }: { n: number }) => usePreviousValue(n, 0), { + initialProps: { n: 1 }, + }); + + expect(result.current).toBe(0); + rerender({ n: 42 }); + expect(result.current).toBe(1); + }); + + it('works with object values (reference equality)', () => { + const a = { x: 1 }; + const b = { x: 2 }; + + const { result, rerender } = renderHook( + ({ obj }: { obj: { x: number } }) => usePreviousValue(obj, a), + { initialProps: { obj: a } } + ); + + expect(result.current).toBe(a); + rerender({ obj: b }); + expect(result.current).toBe(a); + }); +}); diff --git a/src/app/hooks/useTimeoutToggle.test.tsx b/src/app/hooks/useTimeoutToggle.test.tsx new file mode 100644 index 00000000..9fa3a657 --- /dev/null +++ b/src/app/hooks/useTimeoutToggle.test.tsx @@ -0,0 +1,101 @@ +// Integration tests: uses fake timers to control setTimeout behaviour. +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { renderHook, act } from '@testing-library/react'; +import { useTimeoutToggle } from './useTimeoutToggle'; + +describe('useTimeoutToggle', () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it('starts with the default initial value of false', () => { + const { result } = renderHook(() => useTimeoutToggle()); + expect(result.current[0]).toBe(false); + }); + + it('becomes true after trigger() is called', () => { + const { result } = renderHook(() => useTimeoutToggle()); + act(() => { + result.current[1](); + }); + expect(result.current[0]).toBe(true); + }); + + it('resets to false after the default 1500ms duration', () => { + const { result } = renderHook(() => useTimeoutToggle()); + + act(() => { + result.current[1](); + }); + expect(result.current[0]).toBe(true); + + act(() => { + vi.advanceTimersByTime(1500); + }); + expect(result.current[0]).toBe(false); + }); + + it('does not reset before the duration has elapsed', () => { + const { result } = renderHook(() => useTimeoutToggle(500)); + + act(() => { + result.current[1](); + }); + + act(() => { + vi.advanceTimersByTime(499); + }); + expect(result.current[0]).toBe(true); + + act(() => { + vi.advanceTimersByTime(1); + }); + expect(result.current[0]).toBe(false); + }); + + it('re-triggering before timeout resets the countdown', () => { + const { result } = renderHook(() => useTimeoutToggle(1000)); + + act(() => { + result.current[1](); // t=0: trigger + }); + + act(() => { + vi.advanceTimersByTime(800); // t=800 + }); + + act(() => { + result.current[1](); // t=800: re-trigger, timer resets + }); + + act(() => { + vi.advanceTimersByTime(800); // t=1600 — only 800ms since re-trigger + }); + expect(result.current[0]).toBe(true); // still active + + act(() => { + vi.advanceTimersByTime(200); // t=1800 — 1000ms since re-trigger + }); + expect(result.current[0]).toBe(false); + }); + + it('supports a custom initial value of true (inverted toggle)', () => { + const { result } = renderHook(() => useTimeoutToggle(1500, true)); + + expect(result.current[0]).toBe(true); + + act(() => { + result.current[1](); // trigger → false + }); + expect(result.current[0]).toBe(false); + + act(() => { + vi.advanceTimersByTime(1500); // resets back to true + }); + expect(result.current[0]).toBe(true); + }); +}); diff --git a/src/app/utils/common.test.ts b/src/app/utils/common.test.ts index 2a391670..073181a1 100644 --- a/src/app/utils/common.test.ts +++ b/src/app/utils/common.test.ts @@ -1,7 +1,19 @@ // Example: testing a utility file with multiple related exports. // Uses it.each for table-driven tests — good for exhaustive format coverage. import { describe, it, expect } from 'vitest'; -import { bytesToSize, millisecondsToMinutesAndSeconds, secondsToMinutesAndSeconds } from './common'; +import { + binarySearch, + bytesToSize, + millisecondsToMinutesAndSeconds, + nameInitials, + parseGeoUri, + secondsToMinutesAndSeconds, + splitWithSpace, + suffixRename, + trimLeadingSlash, + trimSlash, + trimTrailingSlash, +} from './common'; describe('bytesToSize', () => { it.each([ @@ -35,3 +47,127 @@ describe('secondsToMinutesAndSeconds', () => { expect(secondsToMinutesAndSeconds(s)).toBe(expected); }); }); + +// binarySearch: match fn returns 0=found, 1=go left (item too large), -1=go right (item too small) +describe('binarySearch', () => { + const nums = [1, 3, 5, 7, 9, 11, 13]; + const matcherFor = + (target: number) => + (n: number): -1 | 0 | 1 => { + if (n === target) return 0; + if (n > target) return 1; + return -1; + }; + + it('finds a value in the middle', () => { + expect(binarySearch(nums, matcherFor(7))).toBe(7); + }); + + it('finds the first element', () => { + expect(binarySearch(nums, matcherFor(1))).toBe(1); + }); + + it('finds the last element', () => { + expect(binarySearch(nums, matcherFor(13))).toBe(13); + }); + + it('returns undefined when value is not present', () => { + expect(binarySearch(nums, matcherFor(6))).toBeUndefined(); + }); + + it('returns undefined for an empty array', () => { + expect(binarySearch([], matcherFor(1))).toBeUndefined(); + }); +}); + +describe('parseGeoUri', () => { + it('parses a basic geo URI', () => { + expect(parseGeoUri('geo:51.5074,-0.1278')).toEqual({ + latitude: '51.5074', + longitude: '-0.1278', + }); + }); + + it('ignores the uncertainty parameter after the semicolon', () => { + expect(parseGeoUri('geo:48.8566,2.3522;u=20')).toEqual({ + latitude: '48.8566', + longitude: '2.3522', + }); + }); + + it('returns undefined for an empty string', () => { + expect(parseGeoUri('')).toBeUndefined(); + }); + + it('returns undefined when there is no colon separator', () => { + expect(parseGeoUri('no-colon-here')).toBeUndefined(); + }); + + it('returns undefined when coordinates are missing', () => { + expect(parseGeoUri('geo:')).toBeUndefined(); + }); +}); + +describe('nameInitials', () => { + it.each<[string | null | undefined, number, string]>([ + ['Alice', 1, 'A'], + ['Bob Smith', 2, 'Bo'], + ['', 1, ''], + [null, 1, ''], + [undefined, 1, ''], + ['😀Emoji', 1, '😀'], + ])('nameInitials(%s, %i) → %s', (str, len, expected) => { + expect(nameInitials(str, len)).toBe(expected); + }); +}); + +describe('suffixRename', () => { + it('appends suffix 1 when the name is immediately valid', () => { + expect(suffixRename('room', () => false)).toBe('room1'); + }); + + it('increments the suffix until the validator returns false', () => { + const taken = new Set(['room1', 'room2', 'room3']); + expect(suffixRename('room', (n) => taken.has(n))).toBe('room4'); + }); +}); + +describe('splitWithSpace', () => { + it.each([ + ['hello world', ['hello', 'world']], + [' leading', ['leading']], + ['trailing ', ['trailing']], + ['', []], + [' ', []], + ['one', ['one']], + ])('splitWithSpace(%s)', (input, expected) => { + expect(splitWithSpace(input)).toEqual(expected); + }); +}); + +describe('trimLeadingSlash / trimTrailingSlash / trimSlash', () => { + it.each([ + ['///foo/bar', 'foo/bar'], + ['foo/bar', 'foo/bar'], + ['/', ''], + ])('trimLeadingSlash(%s) → %s', (input, expected) => { + expect(trimLeadingSlash(input)).toBe(expected); + }); + + it.each([ + ['foo/bar///', 'foo/bar'], + ['foo/bar', 'foo/bar'], + ['/', ''], + ])('trimTrailingSlash(%s) → %s', (input, expected) => { + expect(trimTrailingSlash(input)).toBe(expected); + }); + + it.each([ + ['///foo/bar///', 'foo/bar'], + ['/a/', 'a'], + ['', ''], + ['/', ''], + ])('trimSlash(%s) → %s', (input, expected) => { + expect(trimSlash(input)).toBe(expected); + }); +}); diff --git a/src/app/utils/sanitize.test.ts b/src/app/utils/sanitize.test.ts new file mode 100644 index 00000000..f957b56e --- /dev/null +++ b/src/app/utils/sanitize.test.ts @@ -0,0 +1,125 @@ +// Tests for sanitizeCustomHtml — security-critical: strips dangerous content from +// user-supplied Matrix message HTML before rendering. +import { describe, it, expect } 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('text'); + expect(result).not.toContain(' and its content entirely', () => { + const result = sanitizeCustomHtml('quoted messageremaining'); + expect(result).not.toContain('quoted message'); + expect(result).toContain('remaining'); + }); +}); + +describe('sanitizeCustomHtml – XSS prevention', () => { + it('strips "); + expect(result).not.toContain(' { + const result = sanitizeCustomHtml('click me'); + expect(result).not.toContain('onclick'); + expect(result).toContain('click me'); + }); + + it('strips javascript: href on anchor tags', () => { + // eslint-disable-next-line no-script-url + const result = sanitizeCustomHtml('link'); + expect(result).not.toMatch(/javascript:/); + }); + + it('strips data: href on anchor tags', () => { + const result = sanitizeCustomHtml( + 'link' + ); + expect(result).not.toContain('data:'); + }); + + it('strips vbscript: href', () => { + const result = sanitizeCustomHtml('link'); + expect(result).not.toContain('vbscript:'); + }); +}); + +describe('sanitizeCustomHtml – link transformer', () => { + it('adds rel and target to http links', () => { + const result = sanitizeCustomHtml('link'); + expect(result).toContain('rel="noreferrer noopener"'); + expect(result).toContain('target="_blank"'); + }); + + it('passes through existing href for http links', () => { + const result = sanitizeCustomHtml('link'); + expect(result).toContain('href="https://example.com"'); + }); +}); + +describe('sanitizeCustomHtml – image transformer', () => { + it('keeps tags with mxc:// src', () => { + const result = sanitizeCustomHtml('img'); + expect(result).toContain(' with https:// src to a safe link', () => { + const result = sanitizeCustomHtml('photo'); + expect(result).not.toContain(' { + // The span transformer unconditionally overwrites the style attribute with + // values derived from data-mx-color / data-mx-bg-color. Inline CSS is always + // discarded; colors must come from the data-mx-* attributes. + it('converts data-mx-color to a CSS color style on span', () => { + const result = sanitizeCustomHtml('text'); + // sanitize-html may normalise whitespace around the colon + expect(result).toMatch(/color:\s*#ff0000/); + }); + + it('discards plain inline style on span (use data-mx-color instead)', () => { + const result = sanitizeCustomHtml('text'); + // The transformer replaces style with data-mx-* values; no data-mx-color + // present here, so style ends up stripped by the allowedStyles check. + expect(result).not.toContain('color: #ff0000'); + }); + + it('strips non-hex values from data-mx-color', () => { + const result = sanitizeCustomHtml('text'); + expect(result).not.toContain('color: red'); + }); + + it('strips disallowed CSS properties', () => { + const result = sanitizeCustomHtml('text'); + expect(result).not.toContain('position'); + }); +}); + +describe('sanitizeCustomHtml – code block class handling', () => { + it('preserves language class on code blocks', () => { + const result = sanitizeCustomHtml('const x = 1;'); + expect(result).toContain('class="language-typescript"'); + }); + + it('strips arbitrary classes not matching language-*', () => { + const result = sanitizeCustomHtml('code'); + expect(result).not.toContain('evil-class'); + }); +}); diff --git a/src/app/utils/time.test.ts b/src/app/utils/time.test.ts new file mode 100644 index 00000000..2f2418bf --- /dev/null +++ b/src/app/utils/time.test.ts @@ -0,0 +1,99 @@ +import { describe, it, expect } from 'vitest'; +import { + daysToMs, + hour12to24, + hour24to12, + hoursToMs, + inSameDay, + minuteDifference, + minutesToMs, + secondsToMs, +} from './time'; + +describe('hour24to12', () => { + it.each([ + [0, 12], // midnight → 12 AM + [1, 1], + [11, 11], + [12, 12], // noon → 12 PM + [13, 1], + [23, 11], + ])('hour24to12(%i) → %i', (input, expected) => { + expect(hour24to12(input)).toBe(expected); + }); +}); + +describe('hour12to24', () => { + it.each([ + [12, true, 12], // 12 PM → 12 + [12, false, 0], // 12 AM → 0 (midnight) + [1, true, 13], // 1 PM → 13 + [1, false, 1], // 1 AM → 1 + [11, true, 23], // 11 PM → 23 + [11, false, 11], // 11 AM → 11 + ])('hour12to24(%i, pm=%s) → %i', (hour, pm, expected) => { + expect(hour12to24(hour, pm)).toBe(expected); + }); +}); + +describe('inSameDay', () => { + // Use noon UTC for all timestamps so the local calendar date is unambiguous + // in any timezone (avoids midnight UTC being the previous day locally). + const base = new Date('2024-01-15T12:00:00Z').getTime(); + const sameDay = new Date('2024-01-15T14:00:00Z').getTime(); + const nextDay = new Date('2024-01-16T12:00:00Z').getTime(); + + it('returns true for two timestamps on the same day', () => { + expect(inSameDay(base, sameDay)).toBe(true); + }); + + it('returns false for timestamps on different days', () => { + expect(inSameDay(base, nextDay)).toBe(false); + }); + + it('returns true when both timestamps are identical', () => { + expect(inSameDay(base, base)).toBe(true); + }); +}); + +describe('minuteDifference', () => { + it.each([ + [0, 60_000, 1], // 1 minute + [0, 3_600_000, 60], // 1 hour = 60 minutes + [0, 90_000, 2], // 1.5 minutes rounds to 2 + [5_000, 0, 0], // less than a minute → 0 + [0, 0, 0], // same timestamp + ])('minuteDifference(%i, %i) → %i', (ts1, ts2, expected) => { + expect(minuteDifference(ts1, ts2)).toBe(expected); + }); + + it('is symmetric (absolute difference)', () => { + expect(minuteDifference(3_600_000, 0)).toBe(minuteDifference(0, 3_600_000)); + }); +}); + +describe('unit conversion helpers', () => { + it('secondsToMs converts seconds to milliseconds', () => { + expect(secondsToMs(1)).toBe(1_000); + expect(secondsToMs(60)).toBe(60_000); + }); + + it('minutesToMs converts minutes to milliseconds', () => { + expect(minutesToMs(1)).toBe(60_000); + expect(minutesToMs(60)).toBe(3_600_000); + }); + + it('hoursToMs converts hours to milliseconds', () => { + expect(hoursToMs(1)).toBe(3_600_000); + expect(hoursToMs(24)).toBe(86_400_000); + }); + + it('daysToMs converts days to milliseconds', () => { + expect(daysToMs(1)).toBe(86_400_000); + expect(daysToMs(7)).toBe(604_800_000); + }); + + it('conversion chain is consistent: daysToMs(1) === hoursToMs(24)', () => { + expect(daysToMs(1)).toBe(hoursToMs(24)); + }); +}); From 02b7f199097dd7bed45a96d91984efdb7af8f2b6 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 13:45:25 -0400 Subject: [PATCH 073/146] Integrate Sentry for error tracking Add Sentry integration for error tracking and bug reporting --- .changeset/feat-sentry-integration.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/feat-sentry-integration.md b/.changeset/feat-sentry-integration.md index ff50d8ff..fe2f0cab 100644 --- a/.changeset/feat-sentry-integration.md +++ b/.changeset/feat-sentry-integration.md @@ -1,5 +1,5 @@ --- -'default': minor +default: minor --- Add Sentry integration for error tracking and bug reporting From b2696f4f31198397c8b9666deb7eee73ba269b04 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 13:46:44 -0400 Subject: [PATCH 074/146] test: add tests for regex, mimeTypes, pronouns, useDebounce, useThrottle --- src/app/hooks/useDebounce.test.tsx | 100 +++++++++++++++++++++++++++++ src/app/hooks/useThrottle.test.tsx | 92 ++++++++++++++++++++++++++ src/app/utils/mimeTypes.test.ts | 78 ++++++++++++++++++++++ src/app/utils/pronouns.test.ts | 89 +++++++++++++++++++++++++ src/app/utils/regex.test.ts | 95 +++++++++++++++++++++++++++ 5 files changed, 454 insertions(+) create mode 100644 src/app/hooks/useDebounce.test.tsx create mode 100644 src/app/hooks/useThrottle.test.tsx create mode 100644 src/app/utils/mimeTypes.test.ts create mode 100644 src/app/utils/pronouns.test.ts create mode 100644 src/app/utils/regex.test.ts diff --git a/src/app/hooks/useDebounce.test.tsx b/src/app/hooks/useDebounce.test.tsx new file mode 100644 index 00000000..5287f4b1 --- /dev/null +++ b/src/app/hooks/useDebounce.test.tsx @@ -0,0 +1,100 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { renderHook, act } from '@testing-library/react'; +import { useDebounce } from './useDebounce'; + +beforeEach(() => { + vi.useFakeTimers(); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe('useDebounce', () => { + it('does not call callback before wait time elapses', () => { + const fn = vi.fn(); + const { result } = renderHook(() => useDebounce(fn, { wait: 200 })); + + act(() => { + result.current('a'); + }); + + act(() => { + vi.advanceTimersByTime(199); + }); + + expect(fn).not.toHaveBeenCalled(); + }); + + it('calls callback after wait time elapses', () => { + const fn = vi.fn(); + const { result } = renderHook(() => useDebounce(fn, { wait: 200 })); + + act(() => { + result.current('a'); + }); + + act(() => { + vi.advanceTimersByTime(200); + }); + + expect(fn).toHaveBeenCalledOnce(); + expect(fn).toHaveBeenCalledWith('a'); + }); + + it('resets the timer on each successive call', () => { + const fn = vi.fn(); + const { result } = renderHook(() => useDebounce(fn, { wait: 200 })); + + act(() => { + result.current('first'); + }); + + act(() => { + vi.advanceTimersByTime(150); + result.current('second'); + }); + + // 150ms into the reset timer — should not have fired yet + act(() => { + vi.advanceTimersByTime(150); + }); + + expect(fn).not.toHaveBeenCalled(); + + // Complete the 200ms wait after the second call + act(() => { + vi.advanceTimersByTime(50); + }); + + expect(fn).toHaveBeenCalledOnce(); + expect(fn).toHaveBeenCalledWith('second'); + }); + + it('only fires once after rapid successive calls', () => { + const fn = vi.fn(); + const { result } = renderHook(() => useDebounce(fn, { wait: 100 })); + + act(() => { + result.current(1); + result.current(2); + result.current(3); + vi.advanceTimersByTime(100); + }); + + expect(fn).toHaveBeenCalledOnce(); + expect(fn).toHaveBeenCalledWith(3); + }); + + it('fires immediately on first call when immediate option is set', () => { + const fn = vi.fn(); + const { result } = renderHook(() => useDebounce(fn, { wait: 200, immediate: true })); + + act(() => { + result.current('go'); + }); + + expect(fn).toHaveBeenCalledOnce(); + expect(fn).toHaveBeenCalledWith('go'); + }); +}); diff --git a/src/app/hooks/useThrottle.test.tsx b/src/app/hooks/useThrottle.test.tsx new file mode 100644 index 00000000..db7a15d3 --- /dev/null +++ b/src/app/hooks/useThrottle.test.tsx @@ -0,0 +1,92 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { renderHook, act } from '@testing-library/react'; +import { useThrottle } from './useThrottle'; + +beforeEach(() => { + vi.useFakeTimers(); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe('useThrottle', () => { + it('fires once after the wait period even when called multiple times', () => { + const fn = vi.fn(); + const { result } = renderHook(() => useThrottle(fn, { wait: 200 })); + + act(() => { + result.current('a'); + result.current('b'); + result.current('c'); + }); + + expect(fn).not.toHaveBeenCalled(); + + act(() => { + vi.advanceTimersByTime(200); + }); + + expect(fn).toHaveBeenCalledOnce(); + }); + + it('fires with the latest args when called multiple times within the wait', () => { + const fn = vi.fn(); + const { result } = renderHook(() => useThrottle(fn, { wait: 200 })); + + act(() => { + result.current('first'); + result.current('second'); + result.current('third'); + }); + + act(() => { + vi.advanceTimersByTime(200); + }); + + expect(fn).toHaveBeenCalledWith('third'); + }); + + it('does not fire before the wait period ends', () => { + const fn = vi.fn(); + const { result } = renderHook(() => useThrottle(fn, { wait: 300 })); + + act(() => { + result.current('x'); + vi.advanceTimersByTime(299); + }); + + expect(fn).not.toHaveBeenCalled(); + }); + + it('allows a new invocation after the wait period resets', () => { + const fn = vi.fn(); + const { result } = renderHook(() => useThrottle(fn, { wait: 100 })); + + act(() => { + result.current('first-burst'); + vi.advanceTimersByTime(100); + }); + + act(() => { + result.current('second-burst'); + vi.advanceTimersByTime(100); + }); + + expect(fn).toHaveBeenCalledTimes(2); + expect(fn).toHaveBeenNthCalledWith(1, 'first-burst'); + expect(fn).toHaveBeenNthCalledWith(2, 'second-burst'); + }); + + it('fires immediately on first call when immediate option is set', () => { + const fn = vi.fn(); + const { result } = renderHook(() => useThrottle(fn, { wait: 200, immediate: true })); + + act(() => { + result.current('now'); + }); + + expect(fn).toHaveBeenCalledOnce(); + expect(fn).toHaveBeenCalledWith('now'); + }); +}); diff --git a/src/app/utils/mimeTypes.test.ts b/src/app/utils/mimeTypes.test.ts new file mode 100644 index 00000000..0feaf839 --- /dev/null +++ b/src/app/utils/mimeTypes.test.ts @@ -0,0 +1,78 @@ +import { describe, it, expect } from 'vitest'; +import { + getBlobSafeMimeType, + mimeTypeToExt, + getFileNameExt, + getFileNameWithoutExt, + FALLBACK_MIMETYPE, +} from './mimeTypes'; + +describe('getBlobSafeMimeType', () => { + it('passes through known image types', () => { + expect(getBlobSafeMimeType('image/jpeg')).toBe('image/jpeg'); + expect(getBlobSafeMimeType('image/png')).toBe('image/png'); + expect(getBlobSafeMimeType('image/webp')).toBe('image/webp'); + }); + + it('passes through known video and audio types', () => { + expect(getBlobSafeMimeType('video/mp4')).toBe('video/mp4'); + expect(getBlobSafeMimeType('audio/mpeg')).toBe('audio/mpeg'); + }); + + it('converts video/quicktime to video/mp4', () => { + expect(getBlobSafeMimeType('video/quicktime')).toBe('video/mp4'); + }); + + it('returns fallback for unknown mime types', () => { + expect(getBlobSafeMimeType('application/x-unknown')).toBe(FALLBACK_MIMETYPE); + expect(getBlobSafeMimeType('image/bmp')).toBe(FALLBACK_MIMETYPE); + }); + + it('strips charset parameter before checking allowlist', () => { + expect(getBlobSafeMimeType('text/plain; charset=utf-8')).toBe('text/plain'); + }); + + it('returns fallback for non-string input', () => { + // @ts-expect-error — testing runtime safety for external data + expect(getBlobSafeMimeType(null)).toBe(FALLBACK_MIMETYPE); + // @ts-expect-error + expect(getBlobSafeMimeType(42)).toBe(FALLBACK_MIMETYPE); + }); +}); + +describe('mimeTypeToExt', () => { + it.each([ + ['image/jpeg', 'jpeg'], + ['image/png', 'png'], + ['video/mp4', 'mp4'], + ['audio/ogg', 'ogg'], + ['application/pdf', 'pdf'], + ['text/plain', 'plain'], + ])('%s → %s', (mimeType, expected) => { + expect(mimeTypeToExt(mimeType)).toBe(expected); + }); +}); + +describe('getFileNameExt', () => { + it.each([ + ['photo.jpg', 'jpg'], + ['archive.tar.gz', 'gz'], + ['readme.MD', 'MD'], + // No dot: lastIndexOf returns -1, slice(0) returns the full string + ['noextension', 'noextension'], + ])('%s → "%s"', (filename, expected) => { + expect(getFileNameExt(filename)).toBe(expected); + }); +}); + +describe('getFileNameWithoutExt', () => { + it.each([ + ['photo.jpg', 'photo'], + ['archive.tar.gz', 'archive.tar'], + ['noextension', 'noextension'], + ['.gitignore', '.gitignore'], + ['.hidden.txt', '.hidden'], + ])('%s → "%s"', (filename, expected) => { + expect(getFileNameWithoutExt(filename)).toBe(expected); + }); +}); diff --git a/src/app/utils/pronouns.test.ts b/src/app/utils/pronouns.test.ts new file mode 100644 index 00000000..e0471ce6 --- /dev/null +++ b/src/app/utils/pronouns.test.ts @@ -0,0 +1,89 @@ +import { describe, it, expect } from 'vitest'; +import { parsePronounsInput, filterPronounsByLanguage } from './pronouns'; + +describe('parsePronounsInput', () => { + it('parses a single pronoun without a language prefix', () => { + expect(parsePronounsInput('he/him')).toEqual([{ summary: 'he/him', language: 'en' }]); + }); + + it('parses multiple comma-separated pronouns', () => { + expect(parsePronounsInput('he/him,she/her')).toEqual([ + { summary: 'he/him', language: 'en' }, + { summary: 'she/her', language: 'en' }, + ]); + }); + + it('parses a pronoun with a language prefix', () => { + expect(parsePronounsInput('de:er/ihm')).toEqual([{ language: 'de', summary: 'er/ihm' }]); + }); + + it('trims whitespace around entries', () => { + expect(parsePronounsInput(' he/him , she/her ')).toEqual([ + { summary: 'he/him', language: 'en' }, + { summary: 'she/her', language: 'en' }, + ]); + }); + + it('truncates summary to 16 characters', () => { + const longSummary = 'this/is/way/too/long'; + const result = parsePronounsInput(longSummary); + expect(result[0]?.summary).toHaveLength(16); + expect(result[0]?.summary).toBe('this/is/way/too/'); + }); + + it('falls back to "en" when language prefix is empty', () => { + expect(parsePronounsInput(':he/him')).toEqual([{ language: 'en', summary: 'he/him' }]); + }); + + it('returns empty array for empty string', () => { + expect(parsePronounsInput('')).toEqual([]); + }); + + it.each([null, undefined, 42 as unknown as string])( + 'returns empty array for non-string input: %s', + (input) => { + expect(parsePronounsInput(input as string)).toEqual([]); + } + ); +}); + +describe('filterPronounsByLanguage', () => { + const pronouns = [ + { summary: 'he/him', language: 'en' }, + { summary: 'er/ihm', language: 'de' }, + { summary: 'il/lui', language: 'fr' }, + ]; + + it('returns all pronouns when filtering is disabled', () => { + const result = filterPronounsByLanguage(pronouns, false, ['en']); + expect(result).toHaveLength(3); + }); + + it('filters to matching language when enabled', () => { + const result = filterPronounsByLanguage(pronouns, true, ['de']); + expect(result).toHaveLength(1); + expect(result[0]?.language).toBe('de'); + }); + + it('returns all pronouns when no entries match (fallthrough)', () => { + const result = filterPronounsByLanguage(pronouns, true, ['ja']); + expect(result).toHaveLength(3); + }); + + it('matches multiple languages', () => { + const result = filterPronounsByLanguage(pronouns, true, ['en', 'fr']); + expect(result).toHaveLength(2); + expect(result.map((p) => p.language)).toEqual(['en', 'fr']); + }); + + it('is case-insensitive for language matching', () => { + const result = filterPronounsByLanguage(pronouns, true, ['EN']); + expect(result).toHaveLength(1); + expect(result[0]?.language).toBe('en'); + }); + + it('returns empty array for non-array input', () => { + // @ts-expect-error — testing runtime safety + expect(filterPronounsByLanguage(null, true, ['en'])).toEqual([]); + }); +}); diff --git a/src/app/utils/regex.test.ts b/src/app/utils/regex.test.ts new file mode 100644 index 00000000..80c65876 --- /dev/null +++ b/src/app/utils/regex.test.ts @@ -0,0 +1,95 @@ +import { describe, it, expect } from 'vitest'; +import { sanitizeForRegex, EMAIL_REGEX, URL_REG } from './regex'; + +describe('sanitizeForRegex', () => { + it('returns normal alphanumeric strings unchanged', () => { + expect(sanitizeForRegex('hello123')).toBe('hello123'); + }); + + it.each([ + ['|', '\\|'], + ['\\', '\\\\'], + ['{', '\\{'], + ['}', '\\}'], + ['(', '\\('], + [')', '\\)'], + ['[', '\\['], + [']', '\\]'], + ['^', '\\^'], + ['$', '\\$'], + ['+', '\\+'], + ['*', '\\*'], + ['?', '\\?'], + ['.', '\\.'], + ['-', '\\x2d'], + ])('escapes special char %s', (input, expected) => { + expect(sanitizeForRegex(input)).toBe(expected); + }); + + it('escapes all special chars in a complex string', () => { + const result = sanitizeForRegex('a.b+c?d'); + expect(result).toBe('a\\.b\\+c\\?d'); + }); + + it('produces a valid regex that matches the original string literally', () => { + const input = 'foo.bar (baz)+'; + const safePattern = sanitizeForRegex(input); + const reg = new RegExp(safePattern); + expect(reg.test(input)).toBe(true); + // Without escaping, `.` would match any char — make sure it's literal + expect(reg.test('fooXbar (baz)+')).toBe(false); + }); + + it('handles empty string', () => { + expect(sanitizeForRegex('')).toBe(''); + }); +}); + +describe('EMAIL_REGEX', () => { + it.each([ + 'user@example.com', + 'user.name+tag@subdomain.example.org', + 'x@y.io', + 'user123@domain.co.uk', + ])('matches valid email: %s', (email) => { + expect(EMAIL_REGEX.test(email)).toBe(true); + }); + + it.each(['notanemail', '@nodomain.com', 'missing-at-sign.com', 'two@@at.com'])( + 'rejects invalid email: %s', + (email) => { + expect(EMAIL_REGEX.test(email)).toBe(false); + } + ); +}); + +describe('URL_REG', () => { + it('matches a simple http URL', () => { + const matches = 'visit http://example.com today'.match(URL_REG); + expect(matches).not.toBeNull(); + expect(matches?.[0]).toBe('http://example.com'); + }); + + it('matches a simple https URL', () => { + const matches = 'go to https://example.com/path?q=1'.match(URL_REG); + expect(matches?.[0]).toBe('https://example.com/path?q=1'); + }); + + it('finds multiple URLs in a string', () => { + const matches = 'https://one.com and https://two.org'.match(URL_REG); + expect(matches).toHaveLength(2); + expect(matches?.[0]).toBe('https://one.com'); + expect(matches?.[1]).toBe('https://two.org'); + }); + + it('does not match plain text without a scheme', () => { + const matches = 'just some text without a link'.match(URL_REG); + expect(matches).toBeNull(); + }); + + it('strips trailing punctuation from matched URL', () => { + // The pattern uses a negative lookbehind to exclude trailing punctuation + const matches = 'see https://example.com.'.match(URL_REG); + expect(matches?.[0]).not.toMatch(/\.$/); + }); +}); From 0e216564516aa550ba9bd0ae10cb05108beeed04 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 14:54:13 -0400 Subject: [PATCH 075/146] fix(url-preview): replace IntersectionObserver with scroll/resize measurement for arrows The old code used IntersectionObserver anchors to determine whether scroll arrows should be shown. This caused false positives in two scenarios: 1. When a UrlPreviewCard renders null (fetch error), the empty anchor div was sometimes not detected as intersecting, leaving a stale arrow visible. 2. When loading (Spinner makes card 400px wide), the IO would mark the front anchor as not visible, showing the arrow; after load failure the arrow stayed stuck. Replace with direct scrollWidth/clientWidth measurement via ResizeObserver (fires on container and content resize) plus a scroll event listener. Arrows now only appear when the horizontal scroll area actually has overflowed content. Fixes #220 --- .../components/url-preview/UrlPreviewCard.tsx | 68 +++++++------------ 1 file changed, 26 insertions(+), 42 deletions(-) diff --git a/src/app/components/url-preview/UrlPreviewCard.tsx b/src/app/components/url-preview/UrlPreviewCard.tsx index 5fc3ee61..86c4698a 100644 --- a/src/app/components/url-preview/UrlPreviewCard.tsx +++ b/src/app/components/url-preview/UrlPreviewCard.tsx @@ -3,10 +3,6 @@ import { IPreviewUrlResponse } from '$types/matrix-sdk'; import { Box, Icon, IconButton, Icons, Scroll, Spinner, Text, as, color, config } from 'folds'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import { useMatrixClient } from '$hooks/useMatrixClient'; -import { - getIntersectionObserverEntry, - useIntersectionObserver, -} from '$hooks/useIntersectionObserver'; import { mxcUrlToHttp, downloadMedia } from '$utils/matrix'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import * as css from './UrlPreviewCard.css'; @@ -242,43 +238,34 @@ export const UrlPreviewCard = as<'div', { url: string; ts: number; mediaType?: s export const UrlPreviewHolder = as<'div'>(({ children, ...props }, ref) => { const scrollRef = useRef(null); - const backAnchorRef = useRef(null); - const frontAnchorRef = useRef(null); - const [backVisible, setBackVisible] = useState(true); - const [frontVisible, setFrontVisible] = useState(true); + const innerBoxRef = useRef(null); + const [canScrollLeft, setCanScrollLeft] = useState(false); + const [canScrollRight, setCanScrollRight] = useState(false); - const intersectionObserver = useIntersectionObserver( - useCallback((entries) => { - const backAnchor = backAnchorRef.current; - const frontAnchor = frontAnchorRef.current; - const backEntry = backAnchor && getIntersectionObserverEntry(backAnchor, entries); - const frontEntry = frontAnchor && getIntersectionObserverEntry(frontAnchor, entries); - if (backEntry) { - setBackVisible(backEntry.isIntersecting); - } - if (frontEntry) { - setFrontVisible(frontEntry.isIntersecting); - } - }, []), - useCallback( - () => ({ - root: scrollRef.current, - rootMargin: '10px', - }), - [] - ) - ); + const updateArrows = useCallback(() => { + const scroll = scrollRef.current; + if (!scroll) return; + const { scrollLeft, scrollWidth, clientWidth } = scroll; + setCanScrollLeft(scrollLeft > 1); + setCanScrollRight(scrollLeft + clientWidth < scrollWidth - 1); + }, []); useEffect(() => { - const backAnchor = backAnchorRef.current; - const frontAnchor = frontAnchorRef.current; - if (backAnchor) intersectionObserver?.observe(backAnchor); - if (frontAnchor) intersectionObserver?.observe(frontAnchor); + const scroll = scrollRef.current; + if (!scroll) return; + + updateArrows(); + scroll.addEventListener('scroll', updateArrows, { passive: true }); + + const resizeObserver = new ResizeObserver(updateArrows); + resizeObserver.observe(scroll); + if (innerBoxRef.current) resizeObserver.observe(innerBoxRef.current); + return () => { - if (backAnchor) intersectionObserver?.unobserve(backAnchor); - if (frontAnchor) intersectionObserver?.unobserve(frontAnchor); + scroll.removeEventListener('scroll', updateArrows); + resizeObserver.disconnect(); }; - }, [intersectionObserver]); + }, [updateArrows]); const handleScrollBack = () => { const scroll = scrollRef.current; @@ -308,8 +295,7 @@ export const UrlPreviewHolder = as<'div'>(({ children, ...props }, ref) => { > -
- {!backVisible && ( + {canScrollLeft && ( <>
(({ children, ...props }, ref) => { )} - + {children} - - {!frontVisible && ( + {canScrollRight && ( <>
(({ children, ...props }, ref) => { )} -
From 3dbfc6950522036486db8888f76beba473b0e412 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 14:55:37 -0400 Subject: [PATCH 076/146] fix(thread): reduce excessive gap between root message and replies MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The thread drawer had padding: S600 0 (24px top+bottom) on both the root message box and the reply messages box, plus S200 padding on the reply count label. This stacked up to ~84px of empty space between the root message and the first reply, especially noticeable in newly created threads. Fix: - Root message box: change bottom padding S600→S200 (top kept at S400) - Reply messages box: remove top padding (reply count label already provides visual separation) Fixes #294 --- src/app/features/room/ThreadDrawer.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/app/features/room/ThreadDrawer.tsx b/src/app/features/room/ThreadDrawer.tsx index 31af1897..d136e237 100644 --- a/src/app/features/room/ThreadDrawer.tsx +++ b/src/app/features/room/ThreadDrawer.tsx @@ -726,7 +726,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra className={css.messageList} direction="Column" style={{ - padding: `${config.space.S600} 0`, + padding: `${config.space.S400} 0 ${config.space.S200} 0`, }} > @@ -772,7 +772,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra {replyEvents.map((mEvent, i) => { const prevEvent = i > 0 ? replyEvents[i - 1] : undefined; From 68c1ca19fa3e65eac3cfef9c4a617cb5038f0630 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 14:57:13 -0400 Subject: [PATCH 077/146] fix(read-receipts): prevent emoji color bleed in follower names MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit WebKit (Safari/iOS) has a rendering quirk where colorful emoji inside tags can contaminate the paint color of adjacent sibling text nodes. This caused display names following a user with an emoji (e.g. '🔴 Alice') to render with the emoji's color instead of the expected text color. Apply -webkit-text-fill-color: inherit on name tags and -webkit-text-fill-color: currentColor on the following elements. This explicitly resets the WebKit fill color chain at each step, preventing emoji paint properties from cascading into sibling spans. Fixes #267 --- src/app/features/room/RoomViewFollowing.tsx | 40 ++++++++++----------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/src/app/features/room/RoomViewFollowing.tsx b/src/app/features/room/RoomViewFollowing.tsx index c7285ace..4e7fee48 100644 --- a/src/app/features/room/RoomViewFollowing.tsx +++ b/src/app/features/room/RoomViewFollowing.tsx @@ -89,56 +89,56 @@ export const RoomViewFollowing = as<'div', RoomViewFollowingProps>( {names.length === 1 && ( <> - {names[0]} - + {names[0]} + {' is following the conversation.'} )} {names.length === 2 && ( <> - {names[0]} - + {names[0]} + {' and '} - {names[1]} - + {names[1]} + {' are following the conversation.'} )} {names.length === 3 && ( <> - {names[0]} - + {names[0]} + {', '} - {names[1]} - + {names[1]} + {' and '} - {names[2]} - + {names[2]} + {' are following the conversation.'} )} {names.length > 3 && ( <> - {names[0]} - + {names[0]} + {', '} - {names[1]} - + {names[1]} + {', '} - {names[2]} - + {names[2]} + {' and '} - {names.length - 3} others - + {names.length - 3} others + {' are following the conversation.'} From 012c9a0c34dca8b6d258b6041f088621858823d1 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 15:00:48 -0400 Subject: [PATCH 078/146] feat(search): add Ctrl+F / Cmd+F as search hotkey Overrides browser find-in-page (Ctrl+F) to open Sable's search modal instead, matching the behavior users expect from chat applications. The existing Ctrl+K hotkey remains functional. Fixes #179 --- src/app/features/search/Search.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/app/features/search/Search.tsx b/src/app/features/search/Search.tsx index 9d4ea351..9ec8f150 100644 --- a/src/app/features/search/Search.tsx +++ b/src/app/features/search/Search.tsx @@ -407,6 +407,8 @@ export function Search({ requestClose }: SearchProps) { Type # for rooms, @ for DMs and * for spaces. Hotkey:{' '} {isMacOS() ? KeySymbol.Command : 'Ctrl'} + k + {' / '} + {isMacOS() ? KeySymbol.Command : 'Ctrl'} + f @@ -423,7 +425,7 @@ export function SearchModalRenderer() { window, useCallback( (event) => { - if (isKeyHotkey('mod+k', event)) { + if (isKeyHotkey('mod+k', event) || isKeyHotkey('mod+f', event)) { event.preventDefault(); if (opened) { setOpen(false); From 3a446a192104d5c56eaab94947b7c335c6b5eab0 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 15:02:08 -0400 Subject: [PATCH 079/146] fix(call): respect user camera/mic preferences when starting call from room header RoomCallButton was calling startCall(room) without passing preferences, which caused Element Call to use its own defaults (camera on) instead of the user's saved settings. Now reads preferences via useCallPreferences() and passes them to startCall(), matching the behavior of PrescreenControls. Fixes #285 --- src/app/features/room/RoomCallButton.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/app/features/room/RoomCallButton.tsx b/src/app/features/room/RoomCallButton.tsx index 379842eb..ad3c7916 100644 --- a/src/app/features/room/RoomCallButton.tsx +++ b/src/app/features/room/RoomCallButton.tsx @@ -4,6 +4,7 @@ import { Room } from '$types/matrix-sdk'; import { useCallStart, useCallJoined } from '$hooks/useCallEmbed'; import { callEmbedAtom } from '$state/callEmbed'; import { useMatrixClient } from '$hooks/useMatrixClient'; +import { useCallPreferences } from '$state/hooks/callPreferences'; interface RoomCallButtonProps { room: Room; @@ -14,13 +15,14 @@ export function RoomCallButton({ room }: RoomCallButtonProps) { const callEmbed = useAtomValue(callEmbedAtom); const joined = useCallJoined(callEmbed); const mx = useMatrixClient(); + const { microphone, video, sound } = useCallPreferences(); const isJoinedInThisRoom = joined && callEmbed?.roomId === room.roomId; if (isJoinedInThisRoom) return null; const handleStartCall = async () => { - startCall(room); + startCall(room, { microphone, video, sound }); try { const now = Date.now(); // TODO not use as any one day someday i swear From 85aac4ff649ecfe36f90aad04f16e867b11f7fd8 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 15:07:37 -0400 Subject: [PATCH 080/146] fix(sidebar): center notification dot on avatar corner The dot badge (8px circle) was positioned at top:-2px, left:-2px which placed its CENTER 2px inside the avatar corner rather than on the corner itself. Changed to top:-4px, left:-4px so the dot is centered exactly on the top-left corner of the avatar, matching how the count badge (top:-6px for ~12px height) is positioned. Also updated the folder compound variant dot position from +2px to 0px for consistency. Fixes #293 --- src/app/components/sidebar/Sidebar.css.ts | 8 ++++---- src/app/pages/client/sidebar/DirectDMsList.tsx | 2 +- src/app/pages/client/sidebar/DirectTab.tsx | 2 +- src/app/pages/client/sidebar/HomeTab.tsx | 2 +- src/app/pages/client/sidebar/SpaceTabs.tsx | 4 ++-- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/app/components/sidebar/Sidebar.css.ts b/src/app/components/sidebar/Sidebar.css.ts index b96307ae..457ceecb 100644 --- a/src/app/components/sidebar/Sidebar.css.ts +++ b/src/app/components/sidebar/Sidebar.css.ts @@ -134,8 +134,8 @@ export const SidebarItemBadge = recipe({ left: toRem(-6), }, false: { - top: toRem(-2), - left: toRem(-2), + top: toRem(-4), + left: toRem(-4), }, }, }, @@ -167,9 +167,9 @@ export const SidebarItemBadge = recipe({ style: { selectors: { 'div:has(> button[data-id]) &': { - top: toRem(2), + top: toRem(0), left: 'auto', - right: toRem(2), + right: toRem(0), }, }, }, diff --git a/src/app/pages/client/sidebar/DirectDMsList.tsx b/src/app/pages/client/sidebar/DirectDMsList.tsx index f2573b61..14d93eb7 100644 --- a/src/app/pages/client/sidebar/DirectDMsList.tsx +++ b/src/app/pages/client/sidebar/DirectDMsList.tsx @@ -141,7 +141,7 @@ function DMItem({ room, selected }: DMItemProps) { 0} style={{ - left: unread.total > 0 ? toRem(-6) : toRem(-2), + left: unread.total > 0 ? toRem(-6) : toRem(-4), right: 'auto', }} > diff --git a/src/app/pages/client/sidebar/DirectTab.tsx b/src/app/pages/client/sidebar/DirectTab.tsx index 3503c7f9..a1ff6ff5 100644 --- a/src/app/pages/client/sidebar/DirectTab.tsx +++ b/src/app/pages/client/sidebar/DirectTab.tsx @@ -118,7 +118,7 @@ export function DirectTab() { 0} style={{ - left: directUnread.total > 0 ? toRem(-6) : toRem(-2), + left: directUnread.total > 0 ? toRem(-6) : toRem(-4), right: 'auto', }} > diff --git a/src/app/pages/client/sidebar/HomeTab.tsx b/src/app/pages/client/sidebar/HomeTab.tsx index 611957f3..7401e423 100644 --- a/src/app/pages/client/sidebar/HomeTab.tsx +++ b/src/app/pages/client/sidebar/HomeTab.tsx @@ -112,7 +112,7 @@ export function HomeTab() { 0} style={{ - left: homeUnread.total > 0 ? toRem(-6) : toRem(-2), + left: homeUnread.total > 0 ? toRem(-6) : toRem(-4), right: 'auto', }} > diff --git a/src/app/pages/client/sidebar/SpaceTabs.tsx b/src/app/pages/client/sidebar/SpaceTabs.tsx index a758cc1f..670f60b8 100644 --- a/src/app/pages/client/sidebar/SpaceTabs.tsx +++ b/src/app/pages/client/sidebar/SpaceTabs.tsx @@ -468,7 +468,7 @@ function SpaceTab({ 0} style={{ - left: unread.total > 0 ? toRem(-6) : toRem(-2), + left: unread.total > 0 ? toRem(-6) : toRem(-4), right: 'auto', }} > @@ -609,7 +609,7 @@ function ClosedSpaceFolder({ 0} style={{ - left: unread.total > 0 ? toRem(-6) : toRem(-2), + left: unread.total > 0 ? toRem(-6) : toRem(-4), right: 'auto', }} > From 293dee7b348044e8b56e17a44c317d4b70bc9d27 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 15:16:54 -0400 Subject: [PATCH 081/146] fix(lint): use return undefined for consistent-return in useEffect --- src/app/components/url-preview/UrlPreviewCard.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/components/url-preview/UrlPreviewCard.tsx b/src/app/components/url-preview/UrlPreviewCard.tsx index 86c4698a..947cd67b 100644 --- a/src/app/components/url-preview/UrlPreviewCard.tsx +++ b/src/app/components/url-preview/UrlPreviewCard.tsx @@ -252,7 +252,7 @@ export const UrlPreviewHolder = as<'div'>(({ children, ...props }, ref) => { useEffect(() => { const scroll = scrollRef.current; - if (!scroll) return; + if (!scroll) return undefined; updateArrows(); scroll.addEventListener('scroll', updateArrows, { passive: true }); From 97d28324aa874fe3024c3ba39b61c145ea7d1cc5 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 15:20:08 -0400 Subject: [PATCH 082/146] fix(fmt): reformat RoomViewFollowing to satisfy prettier --- src/app/features/room/RoomViewFollowing.tsx | 70 ++++++++++++++++++--- 1 file changed, 60 insertions(+), 10 deletions(-) diff --git a/src/app/features/room/RoomViewFollowing.tsx b/src/app/features/room/RoomViewFollowing.tsx index 4e7fee48..6d9a60c6 100644 --- a/src/app/features/room/RoomViewFollowing.tsx +++ b/src/app/features/room/RoomViewFollowing.tsx @@ -90,7 +90,12 @@ export const RoomViewFollowing = as<'div', RoomViewFollowingProps>( {names.length === 1 && ( <> {names[0]} - + {' is following the conversation.'} @@ -98,11 +103,21 @@ export const RoomViewFollowing = as<'div', RoomViewFollowingProps>( {names.length === 2 && ( <> {names[0]} - + {' and '} {names[1]} - + {' are following the conversation.'} @@ -110,15 +125,30 @@ export const RoomViewFollowing = as<'div', RoomViewFollowingProps>( {names.length === 3 && ( <> {names[0]} - + {', '} {names[1]} - + {' and '} {names[2]} - + {' are following the conversation.'} @@ -126,19 +156,39 @@ export const RoomViewFollowing = as<'div', RoomViewFollowingProps>( {names.length > 3 && ( <> {names[0]} - + {', '} {names[1]} - + {', '} {names[2]} - + {' and '} {names.length - 3} others - + {' are following the conversation.'} From 8802476670f8e32374162f3a1a1323ad077f26aa Mon Sep 17 00:00:00 2001 From: Rye Date: Mon, 16 Mar 2026 20:21:53 +0100 Subject: [PATCH 083/146] added settings toggle --- .../settings/experimental/Experimental.tsx | 2 + .../experimental/MSC4268HistoryShare.tsx | 42 +++++++++++++++++++ src/app/hooks/useCommands.ts | 20 ++++++++- src/app/state/settings.ts | 3 ++ 4 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 src/app/features/settings/experimental/MSC4268HistoryShare.tsx diff --git a/src/app/features/settings/experimental/Experimental.tsx b/src/app/features/settings/experimental/Experimental.tsx index 1760bc9c..5516afbf 100644 --- a/src/app/features/settings/experimental/Experimental.tsx +++ b/src/app/features/settings/experimental/Experimental.tsx @@ -4,6 +4,7 @@ import { InfoCard } from '$components/info-card'; import { LanguageSpecificPronouns } from '../cosmetics/LanguageSpecificPronouns'; import { Sync } from '../general'; import { BandwidthSavingEmojis } from './BandwithSavingEmojis'; +import { MSC4268HistoryShare } from './MSC4268HistoryShare'; type ExperimentalProps = { requestClose: () => void; @@ -43,6 +44,7 @@ export function Experimental({ requestClose }: ExperimentalProps) {
+ diff --git a/src/app/features/settings/experimental/MSC4268HistoryShare.tsx b/src/app/features/settings/experimental/MSC4268HistoryShare.tsx new file mode 100644 index 00000000..d93a4103 --- /dev/null +++ b/src/app/features/settings/experimental/MSC4268HistoryShare.tsx @@ -0,0 +1,42 @@ +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 MSC4268HistoryShare() { + const [enabledMSC4268Command, setEnabledMSC4268Command] = useSetting( + settingsAtom, + 'enableMSC4268CMD' + ); + + return ( + + Enable Sharing of Encrypted History + + + } + /> + + + ); +} diff --git a/src/app/hooks/useCommands.ts b/src/app/hooks/useCommands.ts index ef09847b..b74daf70 100644 --- a/src/app/hooks/useCommands.ts +++ b/src/app/hooks/useCommands.ts @@ -266,6 +266,7 @@ export type CommandRecord = Record; export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { const { navigateRoom } = useRoomNavigate(); const [developerTools] = useSetting(settingsAtom, 'developerTools'); + const [enableMSC4268CMD] = useSetting(settingsAtom, 'enableMSC4268CMD'); const profile = useUserProfile(mx.getSafeUserId()); const openBugReport = useOpenBugReportModal(); @@ -1186,6 +1187,14 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { exe: async (payload) => { const targetUserId = payload.trim(); const { roomId } = room; + if (!enableMSC4268CMD) { + sendFeedback( + 'This command is disabled. Enable it under experimental settings to use it.', + room, + mx.getSafeUserId() + ); + return; + } if (!targetUserId) { sendFeedback('Usage: /sharee2eehistory @user:example.org', room, mx.getSafeUserId()); return; @@ -1296,7 +1305,16 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { }, }, }), - [mx, navigateRoom, room, profile.displayName, profile.avatarUrl, developerTools, openBugReport] + [ + mx, + navigateRoom, + room, + profile.displayName, + profile.avatarUrl, + developerTools, + enableMSC4268CMD, + openBugReport, + ] ); return commands; diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index a5e373a1..ee09b3e2 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -64,6 +64,7 @@ export interface Settings { dateFormatString: string; developerTools: boolean; + enableMSC4268CMD: boolean; // Cosmetics! jumboEmojiSize: JumboEmojiSize; @@ -129,6 +130,8 @@ const defaultSettings: Settings = { legacyUsernameColor: false, allowPipVideos: false, + enableMSC4268CMD: false, + // Push notifications (SW/Sygnal): default on for mobile, opt-in on desktop. // In-app pill banner: default on for mobile (primary foreground alert), opt-in on desktop. // System (OS) notifications: desktop-only; hidden and disabled on mobile. From f7afb8da2658fbd5672757a485e48712b04ab847 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 15:25:11 -0400 Subject: [PATCH 084/146] chore: add changeset --- .changeset/fix-url-preview-scroll-arrows.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/fix-url-preview-scroll-arrows.md diff --git a/.changeset/fix-url-preview-scroll-arrows.md b/.changeset/fix-url-preview-scroll-arrows.md new file mode 100644 index 00000000..d5e24158 --- /dev/null +++ b/.changeset/fix-url-preview-scroll-arrows.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fix URL preview scroll arrows appearing when there is no content to scroll From 8a34be8a2aafbe64f3a39f83adbce97ab6f3c3d7 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 15:26:42 -0400 Subject: [PATCH 085/146] chore: add changeset --- .changeset/fix-thread-empty-space.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/fix-thread-empty-space.md diff --git a/.changeset/fix-thread-empty-space.md b/.changeset/fix-thread-empty-space.md new file mode 100644 index 00000000..fffeeaa5 --- /dev/null +++ b/.changeset/fix-thread-empty-space.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fix excessive whitespace between the thread root message and replies in the thread drawer From 44e87e7a6b07eb387137953f972a390696b59296 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 15:27:48 -0400 Subject: [PATCH 086/146] chore: add changeset --- .changeset/fix-emoji-display-name-color.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/fix-emoji-display-name-color.md diff --git a/.changeset/fix-emoji-display-name-color.md b/.changeset/fix-emoji-display-name-color.md new file mode 100644 index 00000000..667b20a2 --- /dev/null +++ b/.changeset/fix-emoji-display-name-color.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fix emoji color bleeding into adjacent text in read receipt display names on Safari/WebKit From 26e9d10b2bb86f2de322b938971ebddfa13f2751 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 15:28:06 -0400 Subject: [PATCH 087/146] chore: add changeset --- .changeset/feat-ctrl-f-search.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/feat-ctrl-f-search.md diff --git a/.changeset/feat-ctrl-f-search.md b/.changeset/feat-ctrl-f-search.md new file mode 100644 index 00000000..540ec063 --- /dev/null +++ b/.changeset/feat-ctrl-f-search.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Add Ctrl+F / Cmd+F keyboard shortcut to open Sable search instead of browser find-in-page From cd1f7efc7c6f800dc99bd11488ddbfa12c53e966 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 15:28:24 -0400 Subject: [PATCH 088/146] chore: add changeset --- .changeset/fix-call-camera-default.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/fix-call-camera-default.md diff --git a/.changeset/fix-call-camera-default.md b/.changeset/fix-call-camera-default.md new file mode 100644 index 00000000..a1a93ccd --- /dev/null +++ b/.changeset/fix-call-camera-default.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fix camera turning on by default when starting a call from the room header button From bbec983eb60b3cd3995440f65ed02364169551dc Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 15:28:37 -0400 Subject: [PATCH 089/146] chore: add changeset --- .changeset/fix-notification-dot-alignment.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/fix-notification-dot-alignment.md diff --git a/.changeset/fix-notification-dot-alignment.md b/.changeset/fix-notification-dot-alignment.md new file mode 100644 index 00000000..3896b3b1 --- /dev/null +++ b/.changeset/fix-notification-dot-alignment.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fix notification dot badge appearing off-center on sidebar avatars From 1124ba173e304e8199ce8d17bf03fc8db630d500 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 15:35:41 -0400 Subject: [PATCH 090/146] fix(thread): override height:100% from folds Scroll base class to allow content-sized root message --- src/app/features/room/ThreadDrawer.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/src/app/features/room/ThreadDrawer.tsx b/src/app/features/room/ThreadDrawer.tsx index d136e237..fd7075bf 100644 --- a/src/app/features/room/ThreadDrawer.tsx +++ b/src/app/features/room/ThreadDrawer.tsx @@ -719,6 +719,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra hideTrack={false} style={{ maxHeight: '200px', + height: 'fit-content', flexShrink: 0, }} > From 84ce6d7572ab8cd0fa1941cb01e7c10e3973fb87 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Mon, 16 Mar 2026 14:59:36 -0500 Subject: [PATCH 091/146] there had to have been a better way to do this --- .changeset/fix-animated-avatars.md | 5 ++ .../components/room-avatar/AvatarImage.tsx | 55 +++++++++++++++++-- 2 files changed, 56 insertions(+), 4 deletions(-) create mode 100644 .changeset/fix-animated-avatars.md diff --git a/.changeset/fix-animated-avatars.md b/.changeset/fix-animated-avatars.md new file mode 100644 index 00000000..9f3dc679 --- /dev/null +++ b/.changeset/fix-animated-avatars.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fix animated avatars not looping. diff --git a/src/app/components/room-avatar/AvatarImage.tsx b/src/app/components/room-avatar/AvatarImage.tsx index e9072fb0..1e4cb0d0 100644 --- a/src/app/components/room-avatar/AvatarImage.tsx +++ b/src/app/components/room-avatar/AvatarImage.tsx @@ -1,5 +1,5 @@ import { AvatarImage as FoldsAvatarImage } from 'folds'; -import { ReactEventHandler, useState } from 'react'; +import { ReactEventHandler, useState, useEffect } from 'react'; import bgColorImg from '$utils/bgColorImg'; import { settingsAtom } from '$state/settings'; import { useSetting } from '$state/hooks/settings'; @@ -15,20 +15,67 @@ type AvatarImageProps = { export function AvatarImage({ src, alt, uniformIcons, onError }: AvatarImageProps) { const [uniformIconsSetting] = useSetting(settingsAtom, 'uniformIcons'); const [image, setImage] = useState(undefined); - const normalizedBg = image ? bgColorImg(image) : undefined; + const [processedSrc, setProcessedSrc] = useState(src); + const useUniformIcons = uniformIconsSetting && uniformIcons === true; + const normalizedBg = useUniformIcons && image ? bgColorImg(image) : undefined; + + useEffect(() => { + let isMounted = true; + let objectUrl: string | null = null; + + const processImage = async () => { + try { + const res = await fetch(src, { mode: 'cors' }); + const contentType = res.headers.get('content-type'); + + if (contentType && contentType.includes('image/svg+xml')) { + const text = await res.text(); + const parser = new DOMParser(); + const doc = parser.parseFromString(text, 'image/svg+xml'); + + const animations = doc.querySelectorAll('animate, animateTransform, animateMotion'); + animations.forEach((anim) => anim.setAttribute('repeatCount', 'indefinite')); + + const style = doc.createElementNS('http://www.w3.org/2000/svg', 'style'); + style.textContent = '* { animation-iteration-count: infinite !important; }'; + doc.documentElement.appendChild(style); + + const serializer = new XMLSerializer(); + const newSvgString = serializer.serializeToString(doc); + const blob = new Blob([newSvgString], { type: 'image/svg+xml' }); + + objectUrl = URL.createObjectURL(blob); + if (isMounted) setProcessedSrc(objectUrl); + } else if (isMounted) setProcessedSrc(src); + } catch { + if (isMounted) setProcessedSrc(src); + } + }; + + processImage(); + + return () => { + isMounted = false; + if (objectUrl) { + URL.revokeObjectURL(objectUrl); + } + }; + }, [src]); const handleLoad: ReactEventHandler = (evt) => { evt.currentTarget.setAttribute('data-image-loaded', 'true'); setImage(evt.currentTarget); }; + const isBlobUrl = processedSrc.startsWith('blob:'); + return ( { setImage(undefined); From 2e94050719878654bb04a5c2f030512ec0d611a4 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Mon, 16 Mar 2026 15:21:58 -0500 Subject: [PATCH 092/146] add toggle to show call button for large rooms --- .changeset/feat-large-room-call-button.md | 5 ++++ src/app/features/room/RoomViewHeader.tsx | 4 ++- src/app/features/settings/general/General.tsx | 26 +++++++++++++++++++ src/app/state/settings.ts | 2 ++ 4 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 .changeset/feat-large-room-call-button.md diff --git a/.changeset/feat-large-room-call-button.md b/.changeset/feat-large-room-call-button.md new file mode 100644 index 00000000..e28ce21e --- /dev/null +++ b/.changeset/feat-large-room-call-button.md @@ -0,0 +1,5 @@ +--- +default: minor +--- + +Added a toggle to enable/disable showing the call button for large (> 10 member) rooms. diff --git a/src/app/features/room/RoomViewHeader.tsx b/src/app/features/room/RoomViewHeader.tsx index a73df787..a358e30b 100644 --- a/src/app/features/room/RoomViewHeader.tsx +++ b/src/app/features/room/RoomViewHeader.tsx @@ -361,6 +361,8 @@ export function RoomViewHeader({ callView }: { callView?: boolean }) { .getLiveTimeline() .getState(EventTimeline.FORWARDS) ?.maySendStateEvent('org.matrix.msc3401.call.member', mx.getUserId()!); + const [alwaysShowCallButton] = useSetting(settingsAtom, 'alwaysShowCallButton'); + const shouldShowCallButton = alwaysShowCallButton || room.getJoinedMemberCount() <= 10; const encryptionEvent = useStateEvent(room, StateEvent.RoomEncryption); const encryptedRoom = !!encryptionEvent; @@ -708,7 +710,7 @@ export function RoomViewHeader({ callView }: { callView?: boolean }) { )} - {canUseCalls && } + {canUseCalls && shouldShowCallButton && } + Calls + + + } + /> + + + ); +} + function Messages() { const [hideMembershipEvents, setHideMembershipEvents] = useSetting( settingsAtom, @@ -1078,6 +1103,7 @@ export function General({ requestClose }: GeneralProps) { + diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index ee09b3e2..350f8e12 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -96,6 +96,7 @@ export interface Settings { autoplayStickers: boolean; autoplayEmojis: boolean; saveStickerEmojiBandwidth: boolean; + alwaysShowCallButton: boolean; // furry stuff renderAnimals: boolean; @@ -176,6 +177,7 @@ const defaultSettings: Settings = { autoplayStickers: true, autoplayEmojis: true, saveStickerEmojiBandwidth: false, + alwaysShowCallButton: false, // furry stuff renderAnimals: true, From ec5e9812aa3d9ef746b26ca7ce1fd9c5906b9098 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 17:16:04 -0400 Subject: [PATCH 093/146] fix: quick issues batch 1 (#2 #44 #45 #52 #66 #67 #69 #79 #35 #103 #120 #168) --- .changeset/quick-issues-batch-1.md | 19 ++++++++ index.html | 3 +- public/manifest.json | 4 +- src/app/components/RenderMessageContent.tsx | 4 +- src/app/components/editor/Editor.tsx | 2 + .../autocomplete/BaseAutocompleteMenu.tsx | 4 +- .../autocomplete/EmoticonAutocomplete.tsx | 2 + .../autocomplete/RoomMentionAutocomplete.tsx | 2 + .../autocomplete/UserMentionAutocomplete.tsx | 2 + src/app/components/media/Video.tsx | 30 +++++++++++- src/app/features/room/RoomInput.tsx | 7 +++ .../notifications/SystemNotification.tsx | 22 +++++++++ src/app/hooks/useClientConfig.ts | 2 + src/app/pages/App.tsx | 24 ++++++---- src/app/pages/auth/AuthLayout.tsx | 18 +++++-- src/app/pages/auth/ServerPicker.tsx | 25 +++++++++- src/app/pages/client/ClientNonUIFeatures.tsx | 9 ++-- .../client/sidebar/AccountSwitcherTab.tsx | 48 ++++++++++++++++++- src/app/plugins/matrix-to.ts | 10 +++- .../voice-recorder-kit/supportedCodec.ts | 1 - src/app/state/settings.ts | 2 + src/app/utils/sanitize.test.ts | 1 - src/index.css | 1 + 23 files changed, 212 insertions(+), 30 deletions(-) create mode 100644 .changeset/quick-issues-batch-1.md diff --git a/.changeset/quick-issues-batch-1.md b/.changeset/quick-issues-batch-1.md new file mode 100644 index 00000000..783ae784 --- /dev/null +++ b/.changeset/quick-issues-batch-1.md @@ -0,0 +1,19 @@ +--- +default: patch +--- + +Fix several small UI/UX issues: + +- **#2**: Reduced-motion: add `animation-iteration-count: 1` so spinners stop after one cycle instead of running indefinitely at near-zero speed +- **#44**: Account switcher: show a confirmation dialog before signing out of an account +- **#45**: Server picker: prevent iOS from restoring the old server name while the user is actively editing the input +- **#52**: Message editor: add `autoCapitalize="sentences"` to respect the OS/keyboard setting on mobile +- **#66**: Adding account: show a "Cancel" button next to the "Adding account" label so users can abort the flow +- **#67**: Support `matrixToBaseUrl` in `config.json` to override the default matrix.to link base +- **#79/#35**: Autocomplete: pressing Enter now selects the top item instead of sending the message +- **#69**: Autocomplete: focus returns to the message editor after completing a mention or emoji +- **#103**: Browser tab/PWA theme-color: use the correct light (`#ffffff`) and dark (`#1b1a21`) colours via media-query meta tags +- **#120**: Video messages: volume is persisted across page loads via `localStorage` +- **#168**: Notifications: add "Favicon Dot: Mentions Only" setting — when enabled, the favicon only changes for mentions/keywords, not plain unreads + +Closes #2, #44, #45, #52, #66, #67, #79, #35, #69, #103, #120, #168 diff --git a/index.html b/index.html index 21c34e6d..62ce1dab 100644 --- a/index.html +++ b/index.html @@ -23,7 +23,8 @@ property="og:description" content="A Matrix client where you can enjoy the conversation using (not) simple, elegant and secure interface protected by e2ee with the power of open source. And colorful cosmetics. Because yes." /> - + + diff --git a/public/manifest.json b/public/manifest.json index 67deb47a..696b875e 100644 --- a/public/manifest.json +++ b/public/manifest.json @@ -7,8 +7,8 @@ "display": "standalone", "orientation": "portrait", "start_url": "./", - "background_color": "#fff", - "theme_color": "#fff", + "background_color": "#1b1a21", + "theme_color": "#1b1a21", "icons": [ { "src": "./public/android/android-chrome-36x36.png", diff --git a/src/app/components/RenderMessageContent.tsx b/src/app/components/RenderMessageContent.tsx index f235b758..b892f769 100644 --- a/src/app/components/RenderMessageContent.tsx +++ b/src/app/components/RenderMessageContent.tsx @@ -28,7 +28,7 @@ import { VideoContent, } from './message'; import { UrlPreviewCard, UrlPreviewHolder } from './url-preview'; -import { Image, MediaControl, Video } from './media'; +import { Image, MediaControl, PersistedVolumeVideo } from './media'; import { ImageViewer } from './image-viewer'; import { PdfViewer } from './Pdf-viewer'; import { TextViewer } from './text-viewer'; @@ -323,7 +323,7 @@ function RenderMessageContentInternal({ ) : undefined } - renderVideo={(p) =>
link'); expect(result).not.toMatch(/javascript:/); }); diff --git a/src/index.css b/src/index.css index 453dc7f0..1c32c917 100755 --- a/src/index.css +++ b/src/index.css @@ -187,6 +187,7 @@ pre { body.reduced-motion * { animation-duration: 0.001ms !important; + animation-iteration-count: 1 !important; transition-duration: 0.001ms !important; } From e252a1242bc4dad4bff01e1c599b23ce0186ebf8 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 17:29:49 -0400 Subject: [PATCH 094/146] fix: highlight first autocomplete item to indicate Enter selection --- .../editor/autocomplete/AutocompleteMenu.css.tsx | 8 +++++++- .../components/editor/autocomplete/AutocompleteMenu.tsx | 4 +++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx b/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx index a160b600..96a7dc16 100644 --- a/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx +++ b/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx @@ -1,4 +1,4 @@ -import { style } from '@vanilla-extract/css'; +import { globalStyle, style } from '@vanilla-extract/css'; import { DefaultReset, color, config } from 'folds'; export const AutocompleteMenuBase = style([ @@ -38,3 +38,9 @@ export const AutocompleteNotice = style([ AutocompleteMenuHeader, { color: color.SurfaceVariant.OnContainer }, ]); + +export const AutocompleteMenuItems = style({}); + +globalStyle(`${AutocompleteMenuItems} button:first-child`, { + backgroundColor: color.SurfaceVariant.ContainerHover, +}); diff --git a/src/app/components/editor/autocomplete/AutocompleteMenu.tsx b/src/app/components/editor/autocomplete/AutocompleteMenu.tsx index cda3b5e1..54543792 100644 --- a/src/app/components/editor/autocomplete/AutocompleteMenu.tsx +++ b/src/app/components/editor/autocomplete/AutocompleteMenu.tsx @@ -42,7 +42,9 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto {headerContent} -
{children}
+
+ {children} +
From ee01f9a9522294c205e63d3710e5bd3125cf401b Mon Sep 17 00:00:00 2001 From: 7w1 Date: Mon, 16 Mar 2026 17:14:49 -0500 Subject: [PATCH 095/146] add codeowners --- .github/CODEOWNERS | 1 + 1 file changed, 1 insertion(+) create mode 100644 .github/CODEOWNERS diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 00000000..696e9679 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @7w1 @Just-Insane @hazre From abf0848aa6af644dca42179923890abf04d89e44 Mon Sep 17 00:00:00 2001 From: melogale Date: Mon, 16 Mar 2026 19:23:46 -0400 Subject: [PATCH 096/146] fix delayed events --- src/app/features/widgets/GenericWidgetDriver.ts | 12 ++++++++++++ src/app/plugins/call/CallEmbed.ts | 10 ++++++++++ src/app/plugins/call/CallWidgetDriver.ts | 14 +++++++++++++- 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/app/features/widgets/GenericWidgetDriver.ts b/src/app/features/widgets/GenericWidgetDriver.ts index d6f1ec71..ee143b4f 100644 --- a/src/app/features/widgets/GenericWidgetDriver.ts +++ b/src/app/features/widgets/GenericWidgetDriver.ts @@ -164,6 +164,18 @@ export class GenericWidgetDriver extends WidgetDriver { await this.mxClient._unstable_updateDelayedEvent(delayId, action); } + public async cancelScheduledDelayedEvent(delayId: string): Promise { + await this.updateDelayedEvent(delayId, UpdateDelayedEventAction.Cancel); + } + + public async restartScheduledDelayedEvent(delayId: string): Promise { + await this.updateDelayedEvent(delayId, UpdateDelayedEventAction.Restart); + } + + public async sendScheduledDelayedEvent(delayId: string): Promise { + await this.updateDelayedEvent(delayId, UpdateDelayedEventAction.Send); + } + public async sendToDevice( eventType: string, encrypted: boolean, diff --git a/src/app/plugins/call/CallEmbed.ts b/src/app/plugins/call/CallEmbed.ts index 960f21ce..61aef868 100644 --- a/src/app/plugins/call/CallEmbed.ts +++ b/src/app/plugins/call/CallEmbed.ts @@ -9,9 +9,11 @@ import { } from 'matrix-js-sdk'; import { ClientWidgetApi, + type IWidgetApiRequest, IRoomEvent, IWidget, Widget, + WidgetApiFromWidgetAction, WidgetApiToWidgetAction, WidgetDriver, } from 'matrix-widget-api'; @@ -149,6 +151,14 @@ export class CallEmbed { const controlState = initialControlState ?? new CallControlState(true, false, true); this.control = new CallControl(controlState, call, iframe); + // acknowledge always on screen request to silence error + this.disposables.push( + this.listenAction(WidgetApiFromWidgetAction.UpdateAlwaysOnScreen, (evt) => { + evt.preventDefault(); + this.call.transport.reply(evt.detail as IWidgetApiRequest, { success: true }); + }) + ); + let initialMediaEvent = true; this.disposables.push( this.listenAction(ElementWidgetActions.DeviceMute, (evt) => { diff --git a/src/app/plugins/call/CallWidgetDriver.ts b/src/app/plugins/call/CallWidgetDriver.ts index ba1b170e..6d94891f 100644 --- a/src/app/plugins/call/CallWidgetDriver.ts +++ b/src/app/plugins/call/CallWidgetDriver.ts @@ -8,7 +8,7 @@ import { type IWidgetApiErrorResponseDataDetails, type ISearchUserDirectoryResult, type IGetMediaConfigResult, - type UpdateDelayedEventAction, + UpdateDelayedEventAction, OpenIDRequestState, SimpleObservable, IOpenIDUpdate, @@ -165,6 +165,18 @@ export class CallWidgetDriver extends WidgetDriver { await client._unstable_updateDelayedEvent(delayId, action); } + public async cancelScheduledDelayedEvent(delayId: string): Promise { + await this.updateDelayedEvent(delayId, UpdateDelayedEventAction.Cancel); + } + + public async restartScheduledDelayedEvent(delayId: string): Promise { + await this.updateDelayedEvent(delayId, UpdateDelayedEventAction.Restart); + } + + public async sendScheduledDelayedEvent(delayId: string): Promise { + await this.updateDelayedEvent(delayId, UpdateDelayedEventAction.Send); + } + public async sendToDevice( eventType: string, encrypted: boolean, From c7063690f00049a67ea8e01a9aa9f99b6196363a Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 19:52:20 -0400 Subject: [PATCH 097/146] fix: focus first autocomplete item on menu open --- .../editor/autocomplete/AutocompleteMenu.css.tsx | 6 +----- .../components/editor/autocomplete/AutocompleteMenu.tsx | 7 ++++--- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx b/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx index 96a7dc16..149f1010 100644 --- a/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx +++ b/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx @@ -1,4 +1,4 @@ -import { globalStyle, style } from '@vanilla-extract/css'; +import { style } from '@vanilla-extract/css'; import { DefaultReset, color, config } from 'folds'; export const AutocompleteMenuBase = style([ @@ -39,8 +39,4 @@ export const AutocompleteNotice = style([ { color: color.SurfaceVariant.OnContainer }, ]); -export const AutocompleteMenuItems = style({}); -globalStyle(`${AutocompleteMenuItems} button:first-child`, { - backgroundColor: color.SurfaceVariant.ContainerHover, -}); diff --git a/src/app/components/editor/autocomplete/AutocompleteMenu.tsx b/src/app/components/editor/autocomplete/AutocompleteMenu.tsx index 54543792..73e36f6e 100644 --- a/src/app/components/editor/autocomplete/AutocompleteMenu.tsx +++ b/src/app/components/editor/autocomplete/AutocompleteMenu.tsx @@ -1,4 +1,4 @@ -import { ReactNode } from 'react'; +import { ReactNode, useRef } from 'react'; import FocusTrap from 'focus-trap-react'; import { isKeyHotkey } from 'is-hotkey'; import { Header, Menu, Scroll, config } from 'folds'; @@ -15,6 +15,7 @@ type AutocompleteMenuProps = { }; export function AutocompleteMenu({ headerContent, requestClose, children }: AutocompleteMenuProps) { const alive = useAlive(); + const itemsRef = useRef(null); const handleDeactivate = () => { if (alive()) { @@ -27,7 +28,7 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto itemsRef.current?.querySelector('button') ?? false, onPostDeactivate: handleDeactivate, returnFocusOnDeactivate: false, clickOutsideDeactivates: true, @@ -42,7 +43,7 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto {headerContent} -
+
{children}
From b6db65c33b8aa70fd9e14b04014f56c268b7eb0c Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 20:14:46 -0400 Subject: [PATCH 098/146] =?UTF-8?q?fix:=20virtual=20autocomplete=20selecti?= =?UTF-8?q?on=20=E2=80=94=20typing=20preserved,=20arrow=20keys=20navigate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../autocomplete/AutocompleteMenu.css.tsx | 10 +++- .../editor/autocomplete/AutocompleteMenu.tsx | 50 ++++++++++++++++--- src/app/features/room/RoomInput.tsx | 23 +++++++-- 3 files changed, 72 insertions(+), 11 deletions(-) diff --git a/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx b/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx index 149f1010..821fd65d 100644 --- a/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx +++ b/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx @@ -1,4 +1,4 @@ -import { style } from '@vanilla-extract/css'; +import { globalStyle, style } from '@vanilla-extract/css'; import { DefaultReset, color, config } from 'folds'; export const AutocompleteMenuBase = style([ @@ -39,4 +39,12 @@ export const AutocompleteNotice = style([ { color: color.SurfaceVariant.OnContainer }, ]); +export const AutocompleteMenuItems = style({}); + +globalStyle(`${AutocompleteMenuItems} button[data-selected]`, { + backgroundColor: color.SurfaceVariant.ContainerHover, + outline: `2px solid ${color.Primary.Main}`, + outlineOffset: -2, +}); + diff --git a/src/app/components/editor/autocomplete/AutocompleteMenu.tsx b/src/app/components/editor/autocomplete/AutocompleteMenu.tsx index 73e36f6e..ef30e497 100644 --- a/src/app/components/editor/autocomplete/AutocompleteMenu.tsx +++ b/src/app/components/editor/autocomplete/AutocompleteMenu.tsx @@ -1,6 +1,5 @@ -import { ReactNode, useRef } from 'react'; +import { ReactNode, useEffect, useLayoutEffect, useRef, useState } from 'react'; import FocusTrap from 'focus-trap-react'; -import { isKeyHotkey } from 'is-hotkey'; import { Header, Menu, Scroll, config } from 'folds'; import { preventScrollWithArrowKey, stopPropagation } from '$utils/keyboard'; @@ -8,6 +7,9 @@ import { useAlive } from '$hooks/useAlive'; import * as css from './AutocompleteMenu.css'; import { BaseAutocompleteMenu } from './BaseAutocompleteMenu'; +export const AUTOCOMPLETE_NAVIGATE_EVENT = 'autocomplete-navigate'; +export type AutocompleteNavigateDetail = { direction: 1 | -1 }; + type AutocompleteMenuProps = { requestClose: () => void; headerContent: ReactNode; @@ -16,6 +18,8 @@ type AutocompleteMenuProps = { export function AutocompleteMenu({ headerContent, requestClose, children }: AutocompleteMenuProps) { const alive = useAlive(); const itemsRef = useRef(null); + const [selectedIndex, setSelectedIndex] = useState(0); + const prevButtonCountRef = useRef(-1); const handleDeactivate = () => { if (alive()) { @@ -24,17 +28,51 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto } }; + // Sync data-selected to DOM; reset to index 0 when the item list changes + useLayoutEffect(() => { + const buttons = Array.from( + itemsRef.current?.querySelectorAll('button') ?? [] + ); + const count = buttons.length; + + let idx = selectedIndex; + if (count !== prevButtonCountRef.current) { + prevButtonCountRef.current = count; + idx = 0; + if (selectedIndex !== 0) setSelectedIndex(0); + } + + const safeIdx = Math.max(0, Math.min(idx, count - 1)); + buttons.forEach((btn, i) => { + if (i === safeIdx) btn.dataset.selected = 'true'; + else delete btn.dataset.selected; + }); + }); + + // Listen for navigation events dispatched by the editor key handler + useEffect(() => { + const container = itemsRef.current?.closest('[data-autocomplete-menu]'); + if (!container) return; + const handler = (e: Event) => { + const { direction } = (e as CustomEvent).detail; + setSelectedIndex((prev) => { + const buttons = itemsRef.current?.querySelectorAll('button') ?? []; + return Math.max(0, Math.min(prev + direction, buttons.length - 1)); + }); + }; + container.addEventListener(AUTOCOMPLETE_NAVIGATE_EVENT, handler); + return () => container.removeEventListener(AUTOCOMPLETE_NAVIGATE_EVENT, handler); + }, []); + return ( itemsRef.current?.querySelector('button') ?? false, + initialFocus: false, onPostDeactivate: handleDeactivate, returnFocusOnDeactivate: false, clickOutsideDeactivates: true, allowOutsideClick: true, - isKeyForward: (evt: KeyboardEvent) => isKeyHotkey('arrowdown', evt), - isKeyBackward: (evt: KeyboardEvent) => isKeyHotkey('arrowup', evt), escapeDeactivates: stopPropagation, }} > @@ -43,7 +81,7 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto {headerContent} -
+
{children}
diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index c55f0e32..193f48c2 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -742,16 +742,31 @@ export const RoomInput = forwardRef( const handleKeyDown: KeyboardEventHandler = useCallback( (evt) => { + if (autocompleteQuery && isKeyHotkey('arrowdown', evt)) { + evt.preventDefault(); + document.querySelector('[data-autocomplete-menu]')?.dispatchEvent( + new CustomEvent('autocomplete-navigate', { detail: { direction: 1 } }) + ); + return; + } + if (autocompleteQuery && isKeyHotkey('arrowup', evt)) { + evt.preventDefault(); + document.querySelector('[data-autocomplete-menu]')?.dispatchEvent( + new CustomEvent('autocomplete-navigate', { detail: { direction: -1 } }) + ); + return; + } if ( (isKeyHotkey('mod+enter', evt) || (!enterForNewline && isKeyHotkey('enter', evt))) && !isComposing(evt) ) { evt.preventDefault(); if (autocompleteQuery) { - const firstItem = document.querySelector( - '[data-autocomplete-menu] button' - ); - firstItem?.click(); + const selectedItem = + document.querySelector( + '[data-autocomplete-menu] button[data-selected]' + ) ?? document.querySelector('[data-autocomplete-menu] button'); + selectedItem?.click(); return; } submit().catch((error) => { From d33776869331cd478766e1f6a2d20d4383a3767f Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 20:27:08 -0400 Subject: [PATCH 099/146] Update quick-issues-batch-1.md to remove closed issues Removed closed issue references from the changeset. --- .changeset/quick-issues-batch-1.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/.changeset/quick-issues-batch-1.md b/.changeset/quick-issues-batch-1.md index 783ae784..38065fca 100644 --- a/.changeset/quick-issues-batch-1.md +++ b/.changeset/quick-issues-batch-1.md @@ -15,5 +15,3 @@ Fix several small UI/UX issues: - **#103**: Browser tab/PWA theme-color: use the correct light (`#ffffff`) and dark (`#1b1a21`) colours via media-query meta tags - **#120**: Video messages: volume is persisted across page loads via `localStorage` - **#168**: Notifications: add "Favicon Dot: Mentions Only" setting — when enabled, the favicon only changes for mentions/keywords, not plain unreads - -Closes #2, #44, #45, #52, #66, #67, #79, #35, #69, #103, #120, #168 From d7ede9532cdfaab63a1b98e9a7ee57d604670647 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 20:30:21 -0400 Subject: [PATCH 100/146] fix: resolve lint/format errors in autocomplete virtual selection --- .changeset/quick-issues-batch-1.md | 2 +- .../editor/autocomplete/AutocompleteMenu.css.tsx | 4 +--- .../editor/autocomplete/AutocompleteMenu.tsx | 13 ++++++++----- src/app/features/room/RoomInput.tsx | 14 ++++++++------ 4 files changed, 18 insertions(+), 15 deletions(-) diff --git a/.changeset/quick-issues-batch-1.md b/.changeset/quick-issues-batch-1.md index 38065fca..3a0a5ab5 100644 --- a/.changeset/quick-issues-batch-1.md +++ b/.changeset/quick-issues-batch-1.md @@ -10,7 +10,7 @@ Fix several small UI/UX issues: - **#52**: Message editor: add `autoCapitalize="sentences"` to respect the OS/keyboard setting on mobile - **#66**: Adding account: show a "Cancel" button next to the "Adding account" label so users can abort the flow - **#67**: Support `matrixToBaseUrl` in `config.json` to override the default matrix.to link base -- **#79/#35**: Autocomplete: pressing Enter now selects the top item instead of sending the message +- **#79/#35**: Autocomplete: pressing Enter now selects the highlighted item instead of sending the message; the first item is highlighted on open and Arrow Up/Down navigate the list while keeping typing focus in the editor - **#69**: Autocomplete: focus returns to the message editor after completing a mention or emoji - **#103**: Browser tab/PWA theme-color: use the correct light (`#ffffff`) and dark (`#1b1a21`) colours via media-query meta tags - **#120**: Video messages: volume is persisted across page loads via `localStorage` diff --git a/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx b/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx index 821fd65d..fb36858c 100644 --- a/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx +++ b/src/app/components/editor/autocomplete/AutocompleteMenu.css.tsx @@ -41,10 +41,8 @@ export const AutocompleteNotice = style([ export const AutocompleteMenuItems = style({}); -globalStyle(`${AutocompleteMenuItems} button[data-selected]`, { +globalStyle(`${AutocompleteMenuItems} button[data-selected='true']`, { backgroundColor: color.SurfaceVariant.ContainerHover, outline: `2px solid ${color.Primary.Main}`, outlineOffset: -2, }); - - diff --git a/src/app/components/editor/autocomplete/AutocompleteMenu.tsx b/src/app/components/editor/autocomplete/AutocompleteMenu.tsx index ef30e497..0b82001b 100644 --- a/src/app/components/editor/autocomplete/AutocompleteMenu.tsx +++ b/src/app/components/editor/autocomplete/AutocompleteMenu.tsx @@ -44,15 +44,14 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto const safeIdx = Math.max(0, Math.min(idx, count - 1)); buttons.forEach((btn, i) => { - if (i === safeIdx) btn.dataset.selected = 'true'; - else delete btn.dataset.selected; + btn.setAttribute('data-selected', String(i === safeIdx)); }); - }); + }, [selectedIndex]); // Listen for navigation events dispatched by the editor key handler useEffect(() => { const container = itemsRef.current?.closest('[data-autocomplete-menu]'); - if (!container) return; + if (!container) return undefined; const handler = (e: Event) => { const { direction } = (e as CustomEvent).detail; setSelectedIndex((prev) => { @@ -81,7 +80,11 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto {headerContent} -
+
{children}
diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 193f48c2..1be4b84f 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -744,16 +744,18 @@ export const RoomInput = forwardRef( (evt) => { if (autocompleteQuery && isKeyHotkey('arrowdown', evt)) { evt.preventDefault(); - document.querySelector('[data-autocomplete-menu]')?.dispatchEvent( - new CustomEvent('autocomplete-navigate', { detail: { direction: 1 } }) - ); + document + .querySelector('[data-autocomplete-menu]') + ?.dispatchEvent(new CustomEvent('autocomplete-navigate', { detail: { direction: 1 } })); return; } if (autocompleteQuery && isKeyHotkey('arrowup', evt)) { evt.preventDefault(); - document.querySelector('[data-autocomplete-menu]')?.dispatchEvent( - new CustomEvent('autocomplete-navigate', { detail: { direction: -1 } }) - ); + document + .querySelector('[data-autocomplete-menu]') + ?.dispatchEvent( + new CustomEvent('autocomplete-navigate', { detail: { direction: -1 } }) + ); return; } if ( From 1a4af27d4910b7801f315b2d79c8ef4d4a771308 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 16 Mar 2026 20:51:22 -0400 Subject: [PATCH 101/146] fix: persist volume for audio+video; split changesets; revert matrix.to (#120) --- .changeset/fix-account-signout-confirm.md | 7 ++++++ .changeset/fix-autocomplete-selection.md | 7 ++++++ .changeset/fix-cancel-add-account.md | 7 ++++++ .changeset/fix-editor-autocapitalize.md | 7 ++++++ .changeset/fix-favicon-mentions-only.md | 7 ++++++ .changeset/fix-media-volume-persist.md | 7 ++++++ .changeset/fix-reduced-motion-animation.md | 7 ++++++ .changeset/fix-server-picker-ios-autofill.md | 7 ++++++ .changeset/fix-theme-color-meta.md | 7 ++++++ .changeset/quick-issues-batch-1.md | 17 ------------- src/app/components/media/Video.tsx | 4 ++-- .../message/content/AudioContent.tsx | 18 +++++++++++++- src/app/hooks/useClientConfig.ts | 2 -- src/app/pages/App.tsx | 24 ++++++++----------- src/app/plugins/matrix-to.ts | 10 +------- 15 files changed, 93 insertions(+), 45 deletions(-) create mode 100644 .changeset/fix-account-signout-confirm.md create mode 100644 .changeset/fix-autocomplete-selection.md create mode 100644 .changeset/fix-cancel-add-account.md create mode 100644 .changeset/fix-editor-autocapitalize.md create mode 100644 .changeset/fix-favicon-mentions-only.md create mode 100644 .changeset/fix-media-volume-persist.md create mode 100644 .changeset/fix-reduced-motion-animation.md create mode 100644 .changeset/fix-server-picker-ios-autofill.md create mode 100644 .changeset/fix-theme-color-meta.md delete mode 100644 .changeset/quick-issues-batch-1.md diff --git a/.changeset/fix-account-signout-confirm.md b/.changeset/fix-account-signout-confirm.md new file mode 100644 index 00000000..52a09d17 --- /dev/null +++ b/.changeset/fix-account-signout-confirm.md @@ -0,0 +1,7 @@ +--- +default: patch +--- + +Account switcher: show a confirmation dialog before signing out of an account. + +Closes #44 diff --git a/.changeset/fix-autocomplete-selection.md b/.changeset/fix-autocomplete-selection.md new file mode 100644 index 00000000..ffacbd70 --- /dev/null +++ b/.changeset/fix-autocomplete-selection.md @@ -0,0 +1,7 @@ +--- +default: patch +--- + +Autocomplete: pressing Enter now selects the highlighted item instead of sending the message. The first item is highlighted on open and ArrowUp/Down navigate the list while keeping typing focus in the editor. Focus returns to the message editor after completing a mention or emoji. + +Closes #35, #69, #79 diff --git a/.changeset/fix-cancel-add-account.md b/.changeset/fix-cancel-add-account.md new file mode 100644 index 00000000..ef027e09 --- /dev/null +++ b/.changeset/fix-cancel-add-account.md @@ -0,0 +1,7 @@ +--- +default: patch +--- + +Adding account: show a "Cancel" button next to the "Adding account" label so users can abort the flow. + +Closes #66 diff --git a/.changeset/fix-editor-autocapitalize.md b/.changeset/fix-editor-autocapitalize.md new file mode 100644 index 00000000..b122b49c --- /dev/null +++ b/.changeset/fix-editor-autocapitalize.md @@ -0,0 +1,7 @@ +--- +default: patch +--- + +Message editor: add `autoCapitalize="sentences"` to respect the OS/keyboard capitalisation setting on mobile. + +Closes #52 diff --git a/.changeset/fix-favicon-mentions-only.md b/.changeset/fix-favicon-mentions-only.md new file mode 100644 index 00000000..ba8ce5d9 --- /dev/null +++ b/.changeset/fix-favicon-mentions-only.md @@ -0,0 +1,7 @@ +--- +default: patch +--- + +Notifications: add "Favicon Dot: Mentions Only" setting — when enabled, the favicon badge only changes for mentions/keywords, not plain unreads. + +Closes #168 diff --git a/.changeset/fix-media-volume-persist.md b/.changeset/fix-media-volume-persist.md new file mode 100644 index 00000000..00790b8d --- /dev/null +++ b/.changeset/fix-media-volume-persist.md @@ -0,0 +1,7 @@ +--- +default: patch +--- + +Video and audio messages: volume level is now persisted across page loads via `localStorage` and shared between all media players. + +Closes #120 diff --git a/.changeset/fix-reduced-motion-animation.md b/.changeset/fix-reduced-motion-animation.md new file mode 100644 index 00000000..804c456c --- /dev/null +++ b/.changeset/fix-reduced-motion-animation.md @@ -0,0 +1,7 @@ +--- +default: patch +--- + +Reduced-motion: add `animation-iteration-count: 1` so spinners stop after one cycle instead of running indefinitely at near-zero speed. + +Closes #2 diff --git a/.changeset/fix-server-picker-ios-autofill.md b/.changeset/fix-server-picker-ios-autofill.md new file mode 100644 index 00000000..52f8df4c --- /dev/null +++ b/.changeset/fix-server-picker-ios-autofill.md @@ -0,0 +1,7 @@ +--- +default: patch +--- + +Server picker: prevent iOS from restoring the old server name while the user is actively editing the input. + +Closes #45 diff --git a/.changeset/fix-theme-color-meta.md b/.changeset/fix-theme-color-meta.md new file mode 100644 index 00000000..ce316079 --- /dev/null +++ b/.changeset/fix-theme-color-meta.md @@ -0,0 +1,7 @@ +--- +default: patch +--- + +Browser tab/PWA: use the correct light (`#ffffff`) and dark (`#1b1a21`) theme-color values via `media` attribute on the meta tags. + +Closes #103 diff --git a/.changeset/quick-issues-batch-1.md b/.changeset/quick-issues-batch-1.md deleted file mode 100644 index 3a0a5ab5..00000000 --- a/.changeset/quick-issues-batch-1.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -default: patch ---- - -Fix several small UI/UX issues: - -- **#2**: Reduced-motion: add `animation-iteration-count: 1` so spinners stop after one cycle instead of running indefinitely at near-zero speed -- **#44**: Account switcher: show a confirmation dialog before signing out of an account -- **#45**: Server picker: prevent iOS from restoring the old server name while the user is actively editing the input -- **#52**: Message editor: add `autoCapitalize="sentences"` to respect the OS/keyboard setting on mobile -- **#66**: Adding account: show a "Cancel" button next to the "Adding account" label so users can abort the flow -- **#67**: Support `matrixToBaseUrl` in `config.json` to override the default matrix.to link base -- **#79/#35**: Autocomplete: pressing Enter now selects the highlighted item instead of sending the message; the first item is highlighted on open and Arrow Up/Down navigate the list while keeping typing focus in the editor -- **#69**: Autocomplete: focus returns to the message editor after completing a mention or emoji -- **#103**: Browser tab/PWA theme-color: use the correct light (`#ffffff`) and dark (`#1b1a21`) colours via media-query meta tags -- **#120**: Video messages: volume is persisted across page loads via `localStorage` -- **#168**: Notifications: add "Favicon Dot: Mentions Only" setting — when enabled, the favicon only changes for mentions/keywords, not plain unreads diff --git a/src/app/components/media/Video.tsx b/src/app/components/media/Video.tsx index a2a371df..6c08aca8 100644 --- a/src/app/components/media/Video.tsx +++ b/src/app/components/media/Video.tsx @@ -9,7 +9,7 @@ export const Video = forwardRef { - localStorage.setItem(VIDEO_VOLUME_KEY, String((e.target as HTMLVideoElement).volume)); + localStorage.setItem(MEDIA_VOLUME_KEY, String((e.target as HTMLVideoElement).volume)); onVolumeChange?.(e); }} /> diff --git a/src/app/components/message/content/AudioContent.tsx b/src/app/components/message/content/AudioContent.tsx index 6ef9349b..1153ffae 100644 --- a/src/app/components/message/content/AudioContent.tsx +++ b/src/app/components/message/content/AudioContent.tsx @@ -18,6 +18,7 @@ import { useThrottle } from '$hooks/useThrottle'; import { secondsToMinutesAndSeconds } from '$utils/common'; import { decryptFile, downloadEncryptedMedia, downloadMedia, mxcUrlToHttp } from '$utils/matrix'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; +import { MEDIA_VOLUME_KEY } from '$components/media'; const PLAY_TIME_THROTTLE_OPS = { wait: 500, @@ -60,6 +61,14 @@ export function AudioContent({ const audioRef = useRef(null); + useEffect(() => { + const stored = localStorage.getItem(MEDIA_VOLUME_KEY); + if (audioRef.current && stored !== null) { + const parsed = parseFloat(stored); + if (!Number.isNaN(parsed)) audioRef.current.volume = parsed; + } + }, []); + const [currentTime, setCurrentTime] = useState(0); // duration in seconds. (NOTE: info.duration is in milliseconds) const infoDuration = info.duration ?? 0; @@ -197,7 +206,14 @@ export function AudioContent({ ), children: ( -
- - -