From da29ea46d9078df2ca41b5be33ed44a8adc3014a Mon Sep 17 00:00:00 2001 From: Nadia Liliana Kulczycka Date: Thu, 23 Jul 2026 22:50:33 +0200 Subject: [PATCH 001/135] Add guide for getting Sable from Obtainium. --- .vscode/settings.json | 2 +- README.md | 31 +++++++++++++++++++++++++++++++ obtainium-source-nightly.json | 11 +++++++++++ obtainium-source-stable.json | 11 +++++++++++ 4 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 obtainium-source-nightly.json create mode 100644 obtainium-source-stable.json diff --git a/.vscode/settings.json b/.vscode/settings.json index 78a3d23b9..6c391fa53 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -11,7 +11,7 @@ "editor.defaultFormatter": "oxc.oxc-vscode" }, "[json]": { - "editor.defaultFormatter": "oxc.oxc-vscode" + "editor.defaultFormatter": "vscode.json-language-features" }, "[rust]": { "editor.defaultFormatter": "rust-lang.rust-analyzer" diff --git a/README.md b/README.md index bc361d5b6..e715a2501 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,37 @@ Sable iOS builds are distributed as unsigned IPAs through [AltStore](https://alt iOS builds are produced by the `ios` job in [`tauri-build.yml`](.github/workflows/tauri-build.yml) and track the same `dev`/`v*` triggers as desktop builds. +## Android (Obtainium) + +### Nightly Source + +Add to Obtainium +  + +### Stable Source + +Add to Obtainium +  + +### Setup and install + +1. Set up [Obtainium](https://wiki.obtainium.imranr.dev/) on your device. +2. Add the Sable source by either: + - Tapping one of the buttons above. + - Importing one of the JSON files: + - [Nightly](https://raw.githubusercontent.com/SableClient/Sable/refs/heads/dev/obtainium-source-nightly.json) + - [Stable](https://raw.githubusercontent.com/SableClient/Sable/refs/heads/dev/obtainium-source-stable.json) + - Adding it manually - use as the GitHub link and follow the section below with regards to setting app variables +3. Install Sable from the source. + +### Relevant variables and switching between Nightly and Stable + +Relevant variable differences between Nightly and Stable: +- *Include prereleases* - `true` for Nightly, `false` for Stable +- *Fallback to older releases* - `false` for Nightly, `true` for Stable +- *Use latest asset upload as release date* - `true` for Nightly, `false` for Stable (this is due to Nightly builds being uploaded to one release instead of creating new ones) +- *Use release date as version string (pseudo-version)* - `true` for Nightly, `false` for Stable (this is due to Nightly builds being uploaded to one release instead of creating new ones) + ## Self-hosting You have a few options for self hosting, you can: 1. Run the prebuilt docker container. diff --git a/obtainium-source-nightly.json b/obtainium-source-nightly.json new file mode 100644 index 000000000..9d4e3bdd0 --- /dev/null +++ b/obtainium-source-nightly.json @@ -0,0 +1,11 @@ +{ + "apps": [ + { + "id": "moe.sable.client", + "url": "https://github.com/SableClient/Sable", + "author": "SableClient", + "name": "Sable", + "additionalSettings": "{\"includePrereleases\":true,\"fallbackToOlderReleases\":false,\"filterReleaseTitlesByRegEx\":\"\",\"filterReleaseNotesByRegEx\":\"\",\"verifyLatestTag\":false,\"dontSortReleasesList\":false,\"useLatestAssetDateAsReleaseDate\":true,\"trackOnly\":false,\"versionExtractionRegEx\":\"\",\"matchGroupToUse\":\"\",\"versionDetection\":true,\"releaseDateAsVersion\":true,\"useVersionCodeAsOSVersion\":false,\"apkFilterRegEx\":\"\",\"invertAPKFilter\":false,\"autoApkFilterByArch\":true,\"appName\":\"Sable\",\"shizukuPretendToBeGooglePlay\":false,\"exemptFromBackgroundUpdates\":false,\"skipUpdateNotifications\":false,\"about\":\"An almost stable Matrix client\",\"appAuthor\":\"SableClient\"}" + } + ] +} \ No newline at end of file diff --git a/obtainium-source-stable.json b/obtainium-source-stable.json new file mode 100644 index 000000000..9d4e3bdd0 --- /dev/null +++ b/obtainium-source-stable.json @@ -0,0 +1,11 @@ +{ + "apps": [ + { + "id": "moe.sable.client", + "url": "https://github.com/SableClient/Sable", + "author": "SableClient", + "name": "Sable", + "additionalSettings": "{\"includePrereleases\":true,\"fallbackToOlderReleases\":false,\"filterReleaseTitlesByRegEx\":\"\",\"filterReleaseNotesByRegEx\":\"\",\"verifyLatestTag\":false,\"dontSortReleasesList\":false,\"useLatestAssetDateAsReleaseDate\":true,\"trackOnly\":false,\"versionExtractionRegEx\":\"\",\"matchGroupToUse\":\"\",\"versionDetection\":true,\"releaseDateAsVersion\":true,\"useVersionCodeAsOSVersion\":false,\"apkFilterRegEx\":\"\",\"invertAPKFilter\":false,\"autoApkFilterByArch\":true,\"appName\":\"Sable\",\"shizukuPretendToBeGooglePlay\":false,\"exemptFromBackgroundUpdates\":false,\"skipUpdateNotifications\":false,\"about\":\"An almost stable Matrix client\",\"appAuthor\":\"SableClient\"}" + } + ] +} \ No newline at end of file From 8b7410df29c095da799872c688eb59e866995b82 Mon Sep 17 00:00:00 2001 From: Nadia Liliana Kulczycka Date: Thu, 23 Jul 2026 22:57:10 +0200 Subject: [PATCH 002/135] Fix docker tags in README --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e715a2501..df433fabf 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,8 @@ You have a few options for self hosting, you can: Prebuilt images are published to `ghcr.io/sableclient/sable`. -- `latest` tracks the current `dev` branch image. +- `latest` tracks the current latest version release. +- `dev` tracks the current `dev` branch image. - `X.Y.Z` tags are versioned releases. - `X.Y` tags float within a release line. - Pushes to `dev` also publish a short commit SHA tag. From 987a5dabf4970c9a67e815606d574e6c54f0121f Mon Sep 17 00:00:00 2001 From: Nadia Liliana Kulczycka Date: Thu, 23 Jul 2026 23:06:34 +0200 Subject: [PATCH 003/135] Attempt to adjust image size --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index df433fabf..0c609d111 100644 --- a/README.md +++ b/README.md @@ -49,12 +49,12 @@ iOS builds are produced by the `ios` job in [`tauri-build.yml`](.github/workflow ### Nightly Source -Add to Obtainium +Add to Obtainium   ### Stable Source -Add to Obtainium +Add to Obtainium   ### Setup and install From e47cb02ab04c519264c9992774d2e11ed78547e6 Mon Sep 17 00:00:00 2001 From: Nadia Liliana Kulczycka Date: Thu, 23 Jul 2026 23:17:55 +0200 Subject: [PATCH 004/135] Reset the json default formatter --- .vscode/settings.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 6c391fa53..78a3d23b9 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -11,7 +11,7 @@ "editor.defaultFormatter": "oxc.oxc-vscode" }, "[json]": { - "editor.defaultFormatter": "vscode.json-language-features" + "editor.defaultFormatter": "oxc.oxc-vscode" }, "[rust]": { "editor.defaultFormatter": "rust-lang.rust-analyzer" From 201f800fd0c67e7f2f7188a2f8cadfd875d44927 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Thu, 30 Jul 2026 14:15:39 -0500 Subject: [PATCH 005/135] Update CODE_OF_CONDUCT.md --- CODE_OF_CONDUCT.md | 164 ++++++++++++++++----------------------------- 1 file changed, 57 insertions(+), 107 deletions(-) diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index adbdab882..863f6835e 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,128 +1,78 @@ -# Contributor Covenant Code of Conduct +# Sable Community Code of Conduct -## Our Pledge +## Welcome! -We as members, contributors, and leaders pledge to make participation in our -community a harassment-free experience for everyone, regardless of age, body -size, visible or invisible disability, ethnicity, sex characteristics, gender -identity and expression, level of experience, education, socio-economic status, -nationality, personal appearance, race, religion, or sexual identity -and orientation. +We're excited to have you here. Sable is a Matrix client meant for everyone. +Because of that we're committed to keeping this community open and welcoming to all. -We pledge to act and interact in ways that contribute to an open, welcoming, -diverse, inclusive, and healthy community. +We ask all of our community—the people who build it, use it, break it, suggest things for it, help each other with it, and +occasionally meow—to abide by some general rules when in official Sable spaces. -## Our Standards +## The rules -Examples of behavior that contributes to a positive environment for our -community include: +Conversation here is casual. You can disagree, joke around, swear, be weird, +and criticize Sable or its decisions. Just remember that other people share the room with you. -- Demonstrating empathy and kindness toward other people -- Being respectful of differing opinions, viewpoints, and experiences -- Giving and gracefully accepting constructive feedback -- Accepting responsibility and apologizing to those affected by our mistakes, - and learning from the experience -- Focusing on what is best not just for us as individuals, but for the - overall community +The following are not allowed: -Examples of unacceptable behavior include: +* **Do not harass people.** This includes targeted insults, dogpiling, repeatedly +provoking someone, unwelcome sexual advances or attention, or continuing to contact someone after they ask you to +stop. +* **Do not use hate speech or attack someone based on their identity**, including but not +limited to race, ethnicity, nationality, religion, disability, age, body size or +appearance, sex, sex characteristics, sexuality, gender identity, gender +expression, and socioeconomic status. +* **Do not make threats, encourage violence or self-harm, or doxx anyone.** Doxxing includes +sharing or threatening to share someone's private information. +* **Do not post explicit sexual content.** This includes graphic NSFW media, pornography, +and explicit sexual comments or jokes. +* **Do not abuse the shared spaces.** This includes impersonation, scams, malicious links or +files, spam, flooding, ban evasion, or retaliation against someone for making +a report or setting a boundary. -- The use of sexualized language or imagery, and sexual attention or - advances of any kind -- Trolling, insulting or derogatory comments, and personal or political attacks -- Public or private harassment -- Publishing others' private information, such as a physical or email - address, without their explicit permission -- Other conduct which could reasonably be considered inappropriate in a - professional setting +Context and patterns matter. Being blunt, disagreeing about politics or project +direction, or criticizing a maintainer is not automatically a violation. These +rules cannot cover every situation, so moderators have final say on how they +apply. -## Enforcement Responsibilities +## Where this applies -Community leaders are responsible for clarifying and enforcing our standards of -acceptable behavior and will take appropriate and fair corrective action in -response to any behavior that they deem inappropriate, threatening, offensive, -or harmful. +These rules apply to Sable's official GitHub repositories and Matrix space and +rooms. -Community leaders have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions that are -not aligned to this Code of Conduct, and will communicate reasons for moderation -decisions when appropriate. +We do not police people's unrelated private lives. We may act on credible +threats, doxxing, or targeted harassment outside these spaces when it is +connected to Sable. -## Scope +## Moderation -This Code of Conduct applies within all community spaces, and also applies when -an individual is officially representing the community in public spaces. -Examples of representing our community include using an official e-mail address, -posting via an official social media account, or acting as an appointed -representative at an online or offline event. +If a moderator asks you to stop, stop. -## Enforcement +When this code of conduct is not followed, +moderators may remove content, issue a warning, kick, or ban someone from Sable's Matrix +rooms or block them from its GitHub repositories. -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported to the community leaders responsible for enforcement at -executioner@sable.moe. -All complaints will be reviewed and investigated promptly and fairly. +When practical, moderators will explain the problem and what needs to happen next. +Moderators will step back from handling reports that involve them directly, provided another moderator is available. You may request a review by emailing the address listed in the Reporting section below if you believe a decision was mistaken. -All community leaders are obligated to respect the privacy and security of the -reporter of any incident. +## Reporting -## Enforcement Guidelines +Message a moderator (anyone with an Admin or Moderator power level) in the relevant Matrix room or email +[conduct@sable.moe](mailto:conduct@sable.moe). Reports +will be handled thoughtfully and as privately as we reasonably can. -Community leaders will follow these Community Impact Guidelines in determining -the consequences for any action they deem in violation of this Code of Conduct: +If your report is about a moderator, email +[conduct@sable.moe](mailto:conduct@sable.moe) or contact 7w1 directly at +[`@seven:sable.moe`](https://matrix.to/#/@seven:sable.moe). -### 1. Correction +Send whatever context you have. You do not need to build a case first. +We will limit access to people who need it to handle the report. We will not +identify you to the reported person without your permission, though details of +the report may need to be discussed to investigate or act on it. +Knowingly false reports or using reports to harass someone are not allowed. -**Community Impact**: Use of inappropriate language or other behavior deemed -unprofessional or unwelcome in the community. +## Other stuff -**Consequence**: A private, written warning from community leaders, providing -clarity around the nature of the violation and an explanation of why the -behavior was inappropriate. A public apology may be requested. - -### 2. Warning - -**Community Impact**: A violation through a single incident or series -of actions. - -**Consequence**: A warning with consequences for continued behavior. No -interaction with the people involved, including unsolicited interaction with -those enforcing the Code of Conduct, for a specified period of time. This -includes avoiding interactions in community spaces as well as external channels -like social media. Violating these terms may lead to a temporary or -permanent ban. - -### 3. Temporary Ban - -**Community Impact**: A serious violation of community standards, including -sustained inappropriate behavior. - -**Consequence**: A temporary ban from any sort of interaction or public -communication with the community for a specified period of time. No public or -private interaction with the people involved, including unsolicited interaction -with those enforcing the Code of Conduct, is allowed during this period. -Violating these terms may lead to a permanent ban. - -### 4. Permanent Ban - -**Community Impact**: Demonstrating a pattern of violation of community -standards, including sustained inappropriate behavior, harassment of an -individual, or aggression toward or disparagement of classes of individuals. - -**Consequence**: A permanent ban from any sort of public interaction within -the community. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], -version 2.0, available at -https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. - -Community Impact Guidelines were inspired by [Mozilla's code of conduct -enforcement ladder](https://github.com/mozilla/diversity). - -[homepage]: https://www.contributor-covenant.org - -For answers to common questions about this code of conduct, see the FAQ at -https://www.contributor-covenant.org/faq. Translations are available at -https://www.contributor-covenant.org/translations. +These rules may change as Sable and its community change. +By continuing to participate in official Sable spaces, you agree to continue abiding by these rules. +If something is unclear, missing, or badly written, please tell us and we will update this document. From fb84ea17c9594c3d50b5d4faf0004753e8dd12c3 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Thu, 30 Jul 2026 14:21:10 -0500 Subject: [PATCH 006/135] formatting --- CODE_OF_CONDUCT.md | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 863f6835e..820903120 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -15,20 +15,20 @@ and criticize Sable or its decisions. Just remember that other people share the The following are not allowed: -* **Do not harass people.** This includes targeted insults, dogpiling, repeatedly -provoking someone, unwelcome sexual advances or attention, or continuing to contact someone after they ask you to -stop. -* **Do not use hate speech or attack someone based on their identity**, including but not -limited to race, ethnicity, nationality, religion, disability, age, body size or -appearance, sex, sex characteristics, sexuality, gender identity, gender -expression, and socioeconomic status. -* **Do not make threats, encourage violence or self-harm, or doxx anyone.** Doxxing includes -sharing or threatening to share someone's private information. -* **Do not post explicit sexual content.** This includes graphic NSFW media, pornography, -and explicit sexual comments or jokes. -* **Do not abuse the shared spaces.** This includes impersonation, scams, malicious links or -files, spam, flooding, ban evasion, or retaliation against someone for making -a report or setting a boundary. +- **Do not harass people.** This includes targeted insults, dogpiling, repeatedly + provoking someone, unwelcome sexual advances or attention, or continuing to contact someone after they ask you to + stop. +- **Do not use hate speech or attack someone based on their identity**, including but not + limited to race, ethnicity, nationality, religion, disability, age, body size or + appearance, sex, sex characteristics, sexuality, gender identity, gender + expression, and socioeconomic status. +- **Do not make threats, encourage violence or self-harm, or doxx anyone.** Doxxing includes + sharing or threatening to share someone's private information. +- **Do not post explicit sexual content.** This includes graphic NSFW media, pornography, + and explicit sexual comments or jokes. +- **Do not abuse the shared spaces.** This includes impersonation, scams, malicious links or + files, spam, flooding, ban evasion, or retaliation against someone for making + a report or setting a boundary. Context and patterns matter. Being blunt, disagreeing about politics or project direction, or criticizing a maintainer is not automatically a violation. These From 26b55f7fb4f04ca98943e8ae6ceb277ff047b345 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sat, 1 Aug 2026 14:27:06 +0200 Subject: [PATCH 007/135] fix(android): align back navigation with UI --- src/app/components/BackRouteHandler.tsx | 14 ++++++++++++-- src/app/components/page/SettingsSectionPage.tsx | 5 +++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/app/components/BackRouteHandler.tsx b/src/app/components/BackRouteHandler.tsx index 65ff218c5..cf727bfdb 100644 --- a/src/app/components/BackRouteHandler.tsx +++ b/src/app/components/BackRouteHandler.tsx @@ -6,16 +6,18 @@ import { resolveSection } from '$pages/pathUtils'; import { HOME_ROOM_PATH, DIRECT_ROOM_PATH, SPACE_ROOM_PATH } from '$pages/paths'; import { lastVisitedRoomAtom } from '$state/room/lastRoom'; import { isRoomAlias, isRoomId } from '$utils/matrix'; +import { useAndroidBackHandler } from '$utils/androidBack'; type BackRouteHandlerProps = { children: (onBack: () => void) => ReactNode; }; -export function BackRouteHandler({ children }: BackRouteHandlerProps) { + +export function useBackRoute(): () => void { const navigate = useNavigate(); const location = useLocation(); const setLastRoom = useSetAtom(lastVisitedRoomAtom); - const goBack = useCallback(() => { + return useCallback(() => { const section = resolveSection(location.pathname); if (!section) return; @@ -32,6 +34,14 @@ export function BackRouteHandler({ children }: BackRouteHandlerProps) { navigate(section.listPath); }, [navigate, location, setLastRoom]); +} + +export function BackRouteHandler({ children }: BackRouteHandlerProps) { + const goBack = useBackRoute(); + useAndroidBackHandler(() => { + goBack(); + return true; + }); return children(goBack); } diff --git a/src/app/components/page/SettingsSectionPage.tsx b/src/app/components/page/SettingsSectionPage.tsx index 84c46860f..e023bf6ee 100644 --- a/src/app/components/page/SettingsSectionPage.tsx +++ b/src/app/components/page/SettingsSectionPage.tsx @@ -2,6 +2,7 @@ import type { ReactNode } from 'react'; import { Box, IconButton, Text } from 'folds'; import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize'; import { ArrowLeft, composerIcon, X } from '$components/icons/phosphor'; +import { useAndroidBackHandler } from '$utils/androidBack'; import { Page, PageHeader } from './Page'; import { SettingsSectionBody, SettingsSectionHeader } from './style.css'; @@ -27,6 +28,10 @@ export function SettingsSectionPage({ const screenSize = useScreenSizeContext(); const closeLabel = actionLabel ?? 'Close'; const showBack = screenSize === ScreenSize.Mobile && requestBack; + useAndroidBackHandler(() => { + requestBack?.(); + return true; + }, !!showBack); return ( From fc0bad50e20e56e4cecccbb494997e5a2cc4877b Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sat, 1 Aug 2026 14:45:25 +0200 Subject: [PATCH 008/135] fix(media): restore cached range responses --- src-tauri/src/network/media_protocol.rs | 181 +++++++++++++++++++++++- 1 file changed, 175 insertions(+), 6 deletions(-) diff --git a/src-tauri/src/network/media_protocol.rs b/src-tauri/src/network/media_protocol.rs index 2d9f399fd..94a74f865 100644 --- a/src-tauri/src/network/media_protocol.rs +++ b/src-tauri/src/network/media_protocol.rs @@ -1,7 +1,7 @@ use std::{ collections::HashMap, fs, - io::Read, + io::{Read, Seek, SeekFrom}, path::{Path, PathBuf}, sync::{ atomic::{AtomicBool, AtomicU64, Ordering}, @@ -50,6 +50,7 @@ const MAX_CONCURRENT_DOWNLOAD_REQUESTS: usize = 6; const SESSION_WAIT: Duration = Duration::from_secs(5); const SESSION_REFRESH_WAIT: Duration = Duration::from_millis(2500); const MAX_CACHE_BYTES: u64 = 512 * 1024 * 1024; +const MAX_RANGE_CHUNK: u64 = 2 * 1024 * 1024; // Short: a 4xx stops being true once an unreachable remote server comes back. const NEGATIVE_CACHE_TTL: Duration = Duration::from_secs(600); const MAX_NEGATIVE_CACHE_ENTRIES: usize = 512; @@ -475,9 +476,10 @@ pub fn respond( .and_then(|value| value.to_str().ok()) .map(str::to_owned) }; + let range = header_value(header::RANGE); let origin = header_value(header::ORIGIN); tauri::async_runtime::spawn(async move { - let mut response = handle_request(&app, uri) + let mut response = handle_request(&app, uri, range) .await .unwrap_or_else(error_response); apply_cors_headers(&mut response, origin.as_deref()); @@ -488,6 +490,7 @@ pub fn respond( async fn handle_request( app: &AppHandle, uri: Uri, + range: Option, ) -> Result>, StatusCode> { let target = percent_encoding::percent_decode_str(uri.path().trim_start_matches('/')) .decode_utf8() @@ -529,12 +532,16 @@ async fn handle_request( let (content_type, in_memory_body, disk_path) = ensure_cached(&state, &session, &key, media_url, dir, temp_dir).await?; - match in_memory_body { - Some(body) => { + match (range, in_memory_body) { + (Some(range_header), Some(body)) => { + Ok(serve_range_memory(&body, &content_type, &range_header)) + } + (Some(range_header), None) => serve_range(disk_path, content_type, range_header).await, + (None, Some(body)) => { let vec_body = Arc::try_unwrap(body).unwrap_or_else(|b| (*b).clone()); Ok(ok_response(vec_body, &content_type)) } - None => Ok(ok_response(read_full(disk_path).await?, &content_type)), + (None, None) => Ok(ok_response(read_full(disk_path).await?, &content_type)), } } @@ -1087,6 +1094,72 @@ async fn read_full(body_path: PathBuf) -> Result, StatusCode> { .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR) } +async fn serve_range( + body_path: PathBuf, + content_type: String, + range_header: String, +) -> Result>, StatusCode> { + tokio::task::spawn_blocking(move || { + let mut file = fs::File::open(&body_path).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let total = file + .metadata() + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .len(); + let Some((start, end)) = parse_range(&range_header, total) else { + return Ok(range_not_satisfiable(total)); + }; + let end = end.min(start.saturating_add(MAX_RANGE_CHUNK - 1)); + let length = end - start + 1; + let mut body = vec![0; length as usize]; + file.seek(SeekFrom::Start(start)) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + file.read_exact(&mut body) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(partial_response(body, &content_type, start, end, total)) + }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? +} + +fn serve_range_memory(body: &[u8], content_type: &str, range_header: &str) -> Response> { + let total = body.len() as u64; + let Some((start, end)) = parse_range(range_header, total) else { + return range_not_satisfiable(total); + }; + let end = end.min(start.saturating_add(MAX_RANGE_CHUNK - 1)); + partial_response( + body[start as usize..=end as usize].to_vec(), + content_type, + start, + end, + total, + ) +} + +fn parse_range(range_header: &str, total: u64) -> Option<(u64, u64)> { + if total == 0 { + return None; + } + let spec = range_header.strip_prefix("bytes=")?; + let (start, end) = spec.split(',').next()?.trim().split_once('-')?; + let (start, end) = if start.is_empty() { + let suffix = end.parse::().ok()?; + if suffix == 0 { + return None; + } + (total.saturating_sub(suffix), total - 1) + } else { + let start = start.parse::().ok()?; + let end = if end.is_empty() { + total - 1 + } else { + end.parse::().ok()?.min(total - 1) + }; + (start, end) + }; + (start <= end && start < total).then_some((start, end)) +} + // Trim oldest-first when the cache exceeds its byte budget. fn evict_directory_if_needed(dir: &Path, max_bytes: u64) { let Ok(entries) = fs::read_dir(dir) else { @@ -1123,7 +1196,7 @@ fn evict_directory_if_needed(dir: &Path, max_bytes: u64) { } // Shared response headers. Media is content-addressed and the URL is session-scoped, so -// it is safe to let the webview cache it as immutable. +// it is safe to let the webview cache it as immutable and advertise byte-range support. fn media_response_builder(status: StatusCode, content_type: &str) -> ResponseBuilder { let cache_control = if content_type == "application/octet-stream" { "no-store" @@ -1133,6 +1206,7 @@ fn media_response_builder(status: StatusCode, content_type: &str) -> ResponseBui Response::builder() .status(status) .header(header::CONTENT_TYPE, content_type) + .header(header::ACCEPT_RANGES, "bytes") .header(header::CACHE_CONTROL, cache_control) .header(header::X_CONTENT_TYPE_OPTIONS, "nosniff") .header( @@ -1149,6 +1223,32 @@ fn ok_response(body: Vec, content_type: &str) -> Response> { .expect("failed to build media response") } +fn partial_response( + body: Vec, + content_type: &str, + start: u64, + end: u64, + total: u64, +) -> Response> { + let content_length = body.len(); + media_response_builder(StatusCode::PARTIAL_CONTENT, content_type) + .header(header::CONTENT_LENGTH, content_length) + .header( + header::CONTENT_RANGE, + format!("bytes {start}-{end}/{total}"), + ) + .body(body) + .expect("failed to build partial media response") +} + +fn range_not_satisfiable(total: u64) -> Response> { + Response::builder() + .status(StatusCode::RANGE_NOT_SATISFIABLE) + .header(header::CONTENT_RANGE, format!("bytes */{total}")) + .body(Vec::new()) + .expect("failed to build 416 response") +} + fn session_unavailable_response() -> Response> { Response::builder() .status(StatusCode::SERVICE_UNAVAILABLE) @@ -1725,6 +1825,75 @@ mod tests { response.headers().get(header::CACHE_CONTROL).unwrap(), "private, max-age=31536000, immutable" ); + assert_eq!( + response.headers().get(header::ACCEPT_RANGES).unwrap(), + "bytes" + ); + } + + #[test] + fn parse_range_supports_video_metadata_and_seek_requests() { + assert_eq!(super::parse_range("bytes=0-499", 1000), Some((0, 499))); + assert_eq!(super::parse_range("bytes=500-", 1000), Some((500, 999))); + assert_eq!(super::parse_range("bytes=-200", 1000), Some((800, 999))); + assert_eq!(super::parse_range("bytes=990-5000", 1000), Some((990, 999))); + } + + #[test] + fn malformed_or_unsatisfiable_range_is_rejected() { + for range in [ + "bytes=1000-1001", + "bytes=500-400", + "bytes=abc-def", + "items=0-1", + ] { + assert_eq!(super::parse_range(range, 1000), None, "{range}"); + } + assert_eq!(super::parse_range("bytes=0-0", 0), None); + } + + #[test] + fn in_memory_ranges_are_partial_and_capped() { + let body: Vec = (0..200u8).collect(); + let response = super::serve_range_memory(&body, "video/mp4", "bytes=10-19"); + assert_eq!(response.status(), StatusCode::PARTIAL_CONTENT); + assert_eq!(response.body(), &body[10..=19]); + assert_eq!( + response.headers().get(header::CONTENT_RANGE).unwrap(), + "bytes 10-19/200" + ); + + let body = vec![7_u8; (super::MAX_RANGE_CHUNK * 2) as usize]; + let response = super::serve_range_memory(&body, "video/mp4", "bytes=0-"); + assert_eq!(response.body().len() as u64, super::MAX_RANGE_CHUNK); + assert_eq!( + response + .headers() + .get(header::CONTENT_RANGE) + .unwrap() + .to_str() + .unwrap(), + format!("bytes 0-{}/{}", super::MAX_RANGE_CHUNK - 1, body.len()) + ); + } + + #[tokio::test] + async fn disk_range_reads_only_the_requested_cached_bytes() { + let path = std::env::temp_dir().join(format!( + "sable-media-range-test-{}-{}", + std::process::id(), + TEST_CACHE_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + )); + let body: Vec = (0..200u8).collect(); + fs::write(&path, &body).unwrap(); + + let response = super::serve_range(path.clone(), "video/mp4".into(), "bytes=10-19".into()) + .await + .unwrap(); + fs::remove_file(path).ok(); + + assert_eq!(response.status(), StatusCode::PARTIAL_CONTENT); + assert_eq!(response.body(), &body[10..=19]); } #[test] From aab91e678f635a210d6545277870f09eeeafb057 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sat, 1 Aug 2026 17:14:56 +0200 Subject: [PATCH 009/135] fix(sidebar): scope hierarchy virtualizer keys by parent --- src/app/features/lobby/Lobby.tsx | 4 ++-- src/app/hooks/useSpaceHierarchy.test.ts | 22 ++++++++++++++++++++++ src/app/hooks/useSpaceHierarchy.ts | 3 +++ src/app/pages/client/space/Space.tsx | 4 ++-- 4 files changed, 29 insertions(+), 4 deletions(-) create mode 100644 src/app/hooks/useSpaceHierarchy.test.ts diff --git a/src/app/features/lobby/Lobby.tsx b/src/app/features/lobby/Lobby.tsx index 4c3514f83..c43fae671 100644 --- a/src/app/features/lobby/Lobby.tsx +++ b/src/app/features/lobby/Lobby.tsx @@ -17,7 +17,7 @@ import { produce } from 'immer'; import { useSpace } from '$hooks/useSpace'; import { Page, PageContent, PageContentCenter, PageHeroSection } from '$components/page'; import type { HierarchyItem, HierarchyItemSpace } from '$hooks/useSpaceHierarchy'; -import { useSpaceHierarchy } from '$hooks/useSpaceHierarchy'; +import { getSpaceHierarchyItemKey, useSpaceHierarchy } from '$hooks/useSpaceHierarchy'; import { VirtualTile } from '$components/virtualizer'; import { spaceRoomsAtom } from '$state/spaceRooms'; import { useSetting } from '$state/hooks/settings'; @@ -301,7 +301,7 @@ export function Lobby() { (index: number) => { const item = hierarchy[index]; if (!item) return index; - return `${space.roomId}:${item.space.roomId}:${item.space.depth}`; + return getSpaceHierarchyItemKey(space.roomId, item.space); }, [hierarchy, space.roomId] ); diff --git a/src/app/hooks/useSpaceHierarchy.test.ts b/src/app/hooks/useSpaceHierarchy.test.ts new file mode 100644 index 000000000..6b67d91cf --- /dev/null +++ b/src/app/hooks/useSpaceHierarchy.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest'; +import { getSpaceHierarchyItemKey } from './useSpaceHierarchy'; + +describe('getSpaceHierarchyItemKey', () => { + it('distinguishes hierarchy entries included through separate parents at the same depth', () => { + const firstHierarchyItem = { + roomId: '!child:example.com', + parentId: '!first-subspace:example.com', + content: { via: [] }, + ts: 0, + depth: 1, + }; + const secondHierarchyItem = { + ...firstHierarchyItem, + parentId: '!second-subspace:example.com', + }; + + expect(getSpaceHierarchyItemKey('!space:example.com', firstHierarchyItem)).not.toBe( + getSpaceHierarchyItemKey('!space:example.com', secondHierarchyItem) + ); + }); +}); diff --git a/src/app/hooks/useSpaceHierarchy.ts b/src/app/hooks/useSpaceHierarchy.ts index 81d51d1a2..b4ab4faab 100644 --- a/src/app/hooks/useSpaceHierarchy.ts +++ b/src/app/hooks/useSpaceHierarchy.ts @@ -35,6 +35,9 @@ export type HierarchyItemRoom = { export type HierarchyItem = HierarchyItemSpace | HierarchyItemRoom; +export const getSpaceHierarchyItemKey = (spaceId: string, item: HierarchyItem): string => + `${spaceId}:${item.parentId ?? ''}:${item.roomId}:${item.depth}`; + type GetRoomCallback = (roomId: string) => Room | undefined; const hierarchyItemSort: SortFunc = (a, b) => { diff --git a/src/app/pages/client/space/Space.tsx b/src/app/pages/client/space/Space.tsx index 744530b5e..80e0a9de3 100644 --- a/src/app/pages/client/space/Space.tsx +++ b/src/app/pages/client/space/Space.tsx @@ -36,7 +36,7 @@ import { useCategoryHandler } from '$hooks/useCategoryHandler'; import { useNavToActivePathMapper } from '$hooks/useNavToActivePathMapper'; import { useRoomName } from '$hooks/useRoomMeta'; import type { HierarchyItem } from '$hooks/useSpaceHierarchy'; -import { useSpaceJoinedHierarchy } from '$hooks/useSpaceHierarchy'; +import { getSpaceHierarchyItemKey, useSpaceJoinedHierarchy } from '$hooks/useSpaceHierarchy'; import { allRoomsAtom } from '$state/room-list/roomList'; import { PageNavContent, PageNavHeader } from '$components/page'; import { PageNavShell } from '$components/page/PageNavShell'; @@ -779,7 +779,7 @@ export function Space() { (index: number) => { const item = hierarchy[index]; if (!item) return index; - return `${space.roomId}:${item.roomId}:${item.depth}`; + return getSpaceHierarchyItemKey(space.roomId, item); }, [hierarchy, space.roomId] ); From a8547c81990752e03a523dd44258c63622a2c69e Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sat, 1 Aug 2026 18:47:15 +0200 Subject: [PATCH 010/135] fix(call): hydrate the member roster before the call widget reads it --- .../call/CallWidgetDriver.roster.test.ts | 45 +++++++++++++++++++ src/app/plugins/call/CallWidgetDriver.ts | 28 ++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 src/app/plugins/call/CallWidgetDriver.roster.test.ts diff --git a/src/app/plugins/call/CallWidgetDriver.roster.test.ts b/src/app/plugins/call/CallWidgetDriver.roster.test.ts new file mode 100644 index 000000000..54fdb6ef4 --- /dev/null +++ b/src/app/plugins/call/CallWidgetDriver.roster.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { Room } from '$types/matrix-sdk'; +import { hydrateWidgetRoster } from './CallWidgetDriver'; + +type RoomStub = { + loadMembersIfNeeded: () => Promise; + joinedInState?: number; + joinedCount?: number; +}; + +const makeRoom = ({ loadMembersIfNeeded, joinedInState = 4, joinedCount = 4 }: RoomStub): Room => + ({ + roomId: '!room:example.org', + loadMembersIfNeeded, + getMembersWithMembership: () => Array.from({ length: joinedInState }, () => ({})), + getJoinedMemberCount: () => joinedCount, + }) as unknown as Room; + +describe('hydrateWidgetRoster', () => { + it('fetches the roster before the widget reads member state', async () => { + const loadMembersIfNeeded = vi.fn<() => Promise>().mockResolvedValue(true); + + await hydrateWidgetRoster(makeRoom({ loadMembersIfNeeded })); + + expect(loadMembersIfNeeded).toHaveBeenCalledOnce(); + }); + + it('still serves state when the roster request fails', async () => { + const loadMembersIfNeeded = vi + .fn<() => Promise>() + .mockRejectedValue(new Error('roster request failed')); + + await expect(hydrateWidgetRoster(makeRoom({ loadMembersIfNeeded }))).resolves.toBeUndefined(); + }); + + it('does not throw when the hydrated roster is still short', async () => { + const room = makeRoom({ + loadMembersIfNeeded: () => Promise.resolve(false), + joinedInState: 2, + joinedCount: 7, + }); + + await expect(hydrateWidgetRoster(room)).resolves.toBeUndefined(); + }); +}); diff --git a/src/app/plugins/call/CallWidgetDriver.ts b/src/app/plugins/call/CallWidgetDriver.ts index 5d71098b5..4ded2826f 100644 --- a/src/app/plugins/call/CallWidgetDriver.ts +++ b/src/app/plugins/call/CallWidgetDriver.ts @@ -16,8 +16,10 @@ import type { MatrixClient } from '$types/matrix-sdk'; import { EventType, type IContent, + KnownMembership, MatrixError, type MatrixEvent, + type Room, Direction, type SendDelayedEventResponse, type StateEvents, @@ -29,6 +31,29 @@ import { createDebugLogger } from '../../utils/debugLogger'; const debugLog = createDebugLogger('CallWidgetDriver'); +export const hydrateWidgetRoster = async (room: Room): Promise => { + try { + await room.loadMembersIfNeeded(); + } catch (error) { + // A partial roster still beats failing the read and stalling state sync. + debugLog.warn('call', 'Failed to load room members for the call widget', { + roomId: room.roomId, + error: error instanceof Error ? error.message : String(error), + }); + return; + } + + const joinedInState = room.getMembersWithMembership(KnownMembership.Join).length; + const joinedCount = room.getJoinedMemberCount(); + if (joinedInState < joinedCount) { + debugLog.warn('call', 'Call widget roster is short of the joined member count', { + roomId: room.roomId, + joinedInState, + joinedCount, + }); + } +}; + export class CallWidgetDriver extends WidgetDriver { private allowedCapabilities: Set; @@ -295,6 +320,9 @@ export class CallWidgetDriver extends WidgetDriver { ): Promise { const room = this.mx.getRoom(roomId); if (room === null) return []; + + if (eventType === (EventType.RoomMember as string)) await hydrateWidgetRoster(room); + const state = room.getLiveTimeline().getState(Direction.Forward); if (state === undefined) return []; From b4f5568ed974c844477c6f55b83ef3a9ea7c6157 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sat, 1 Aug 2026 20:42:48 +0200 Subject: [PATCH 011/135] fix: layer mobile sheets above overlays --- src/app/features/room/message/styles.css.ts | 7 +++++-- src/app/styles/edgeToEdgeInsets.test.ts | 7 +++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/app/features/room/message/styles.css.ts b/src/app/features/room/message/styles.css.ts index bb815f2f8..fa10d7e08 100644 --- a/src/app/features/room/message/styles.css.ts +++ b/src/app/features/room/message/styles.css.ts @@ -1,6 +1,9 @@ import { style } from '@vanilla-extract/css'; import { DefaultReset, FocusOutline, color, config, toRem } from 'folds'; +// Sheets can be opened from an existing Folds overlay, whose maximum layer is Z9999. +const mobileSheetZIndex = `calc(${config.zIndex.Max} + 1)`; + export const MessageBase = style({ position: 'relative', maxWidth: '100%', @@ -102,7 +105,7 @@ export const MessageMobileOptionsWrapped = style({ left: 0, right: 0, bottom: 0, - zIndex: 1004, + zIndex: mobileSheetZIndex, width: '100vw', height: '100%', backgroundColor: color.Other.Overlay, @@ -118,7 +121,7 @@ export const MessageMobileOptionsContainer = style({ bottom: 0, left: 0, right: 0, - zIndex: 1005, + zIndex: mobileSheetZIndex, width: '100%', maxHeight: '85vh', display: 'flex', diff --git a/src/app/styles/edgeToEdgeInsets.test.ts b/src/app/styles/edgeToEdgeInsets.test.ts index 83627f466..5e4b65d1c 100644 --- a/src/app/styles/edgeToEdgeInsets.test.ts +++ b/src/app/styles/edgeToEdgeInsets.test.ts @@ -48,6 +48,13 @@ describe('android edge-to-edge inset contract', () => { expect(systemBarShell).toContain('ref={onPortalContainerChange}'); }); + it('keeps mobile sheets above Folds overlays', () => { + const messageStyles = readWorkspaceFile('src/app/features/room/message/styles.css.ts'); + + expect(messageStyles).toContain('const mobileSheetZIndex = `calc(${config.zIndex.Max} + 1)`;'); + expect(messageStyles.match(/zIndex: mobileSheetZIndex/g)).toHaveLength(2); + }); + it('uses the App shell as the only safe-area owner', () => { const appShell = readWorkspaceFile('src/app/components/app-shell/AppShell.tsx'); const systemBarShell = readWorkspaceFile('src/app/components/app-shell/SystemBarShell.tsx'); From 1af625a3647cc90b9a4093720f7e7469b7ecb6c6 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sat, 1 Aug 2026 20:48:16 +0200 Subject: [PATCH 012/135] fix(mobile): save JSON exports natively --- .../developer-tools/DebugLogViewer.tsx | 15 ++-- .../developer-tools/SentrySettings.tsx | 9 ++- src/app/utils/settingsSync.test.ts | 68 ++++++++----------- src/app/utils/settingsSync.ts | 13 ++-- 4 files changed, 47 insertions(+), 58 deletions(-) diff --git a/src/app/features/settings/developer-tools/DebugLogViewer.tsx b/src/app/features/settings/developer-tools/DebugLogViewer.tsx index d9846d6aa..deaca59c3 100644 --- a/src/app/features/settings/developer-tools/DebugLogViewer.tsx +++ b/src/app/features/settings/developer-tools/DebugLogViewer.tsx @@ -9,6 +9,7 @@ import { debugLoggerEnabledAtom, debugLogsAtom, clearDebugLogsAtom } from '$stat import type { LogEntry, LogLevel, LogCategory } from '$utils/debugLogger'; import { getDebugLogger } from '$utils/debugLogger'; import { copyToClipboard } from '$utils/dom'; +import { saveFileToDevice } from '$utils/download'; const formatTimestamp = (timestamp: number): string => { const date = new Date(timestamp); @@ -219,19 +220,15 @@ export function DebugLogViewer() { jsonData = debugLogger.exportLogs(); } - const blob = new Blob([jsonData], { type: 'application/json' }); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; const filterSuffix = filtered && (filterLevel !== 'all' || filterCategory !== 'all') ? `-${filterCategory !== 'all' ? filterCategory : 'all'}-${filterLevel !== 'all' ? filterLevel : 'all'}` : ''; - a.download = `sable-debug-logs${filterSuffix}-${new Date().toISOString()}.json`; - document.body.appendChild(a); - a.click(); - document.body.removeChild(a); - URL.revokeObjectURL(url); + void saveFileToDevice( + new Blob([jsonData], { type: 'application/json' }), + `sable-debug-logs${filterSuffix}-${Date.now()}.json`, + 'application/json' + ); }, [filterLevel, filterCategory] ); diff --git a/src/app/features/settings/developer-tools/SentrySettings.tsx b/src/app/features/settings/developer-tools/SentrySettings.tsx index 03a213ac7..4848c6809 100644 --- a/src/app/features/settings/developer-tools/SentrySettings.tsx +++ b/src/app/features/settings/developer-tools/SentrySettings.tsx @@ -5,6 +5,7 @@ import { SettingTile } from '$components/setting-tile'; import { toSettingsFocusIdPart } from '$features/settings/settingsLink'; import type { LogCategory } from '$utils/debugLogger'; import { getDebugLogger } from '$utils/debugLogger'; +import { saveFileToDevice } from '$utils/download'; const ALL_CATEGORIES: LogCategory[] = [ 'sync', @@ -18,10 +19,12 @@ const ALL_CATEGORIES: LogCategory[] = [ 'general', ]; -import { downloadJsonFile } from '$utils/common'; - const handleExportLogs = () => { - downloadJsonFile(getDebugLogger().exportLogs(), 'sable-debug-logs'); + void saveFileToDevice( + new Blob([getDebugLogger().exportLogs()], { type: 'application/json' }), + `sable-debug-logs-${Date.now()}.json`, + 'application/json' + ); }; export function SentrySettings() { diff --git a/src/app/utils/settingsSync.test.ts b/src/app/utils/settingsSync.test.ts index 6a96b7a76..965873ad4 100644 --- a/src/app/utils/settingsSync.test.ts +++ b/src/app/utils/settingsSync.test.ts @@ -1,4 +1,18 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; + +const { saveFileToDevice } = vi.hoisted(() => ({ + saveFileToDevice: + vi.fn< + ( + input: Blob | string, + filename: string, + mimeType?: string + ) => Promise<'saved' | 'cancelled' | 'failed'> + >(), +})); + +vi.mock('$utils/download', () => ({ saveFileToDevice })); + import { getSettings, resetRuntimeSettingsDefaults } from '$state/settings'; import { NON_SYNCABLE_KEYS, @@ -384,46 +398,28 @@ describe('deserializeFromSync', () => { // exportSettingsAsJson describe('exportSettingsAsJson', () => { - let fakeUrl: string; - let anchorClick: ReturnType; - beforeEach(() => { - fakeUrl = 'blob:fake-url'; - anchorClick = vi.fn<() => void>(); - vi.stubGlobal('URL', { - createObjectURL: vi.fn<() => string>().mockReturnValue(fakeUrl), - revokeObjectURL: vi.fn<() => void>(), - }); - - // Intercept anchor element creation to capture click calls. - const realCreate = document.createElement.bind(document); - vi.spyOn(document, 'createElement').mockImplementation((tag: string, ...args) => { - const el = realCreate(tag, ...args); - if (tag === 'a') { - vi.spyOn(el, 'click').mockImplementation(anchorClick as () => void); - } - return el; - }); + saveFileToDevice.mockResolvedValue('saved'); }); afterEach(() => { - vi.unstubAllGlobals(); - vi.restoreAllMocks(); + vi.clearAllMocks(); }); - it('calls URL.createObjectURL with a JSON Blob', () => { + it('saves a JSON file through the cross-platform downloader', () => { exportSettingsAsJson(base); - expect(URL.createObjectURL).toHaveBeenCalledOnce(); - const blob: Blob | undefined = (URL.createObjectURL as ReturnType).mock - .calls[0]?.[0]; + expect(saveFileToDevice).toHaveBeenCalledWith( + expect.any(Blob), + expect.stringMatching(/^sable-settings-\d+\.json$/), + 'application/json' + ); + }); + + it('saves valid JSON with the correct schema version and all settings', async () => { + exportSettingsAsJson(base); + const blob = saveFileToDevice.mock.calls[0]?.[0] as Blob; expect(blob).toBeInstanceOf(Blob); expect(blob!.type).toBe('application/json'); - }); - - it('Blob content is valid JSON with the correct schema version and all settings', async () => { - exportSettingsAsJson(base); - const blob: Blob | undefined = (URL.createObjectURL as ReturnType).mock - .calls[0]?.[0]; const text = await blob!.text(); const parsed = JSON.parse(text); expect(parsed.v).toBe(SETTINGS_SYNC_VERSION); @@ -431,16 +427,6 @@ describe('exportSettingsAsJson', () => { // non-syncable keys ARE present in the export (full snapshot, not filtered) expect(parsed.settings.pageZoom).toBeDefined(); }); - - it('creates an anchor with a .json download attribute and clicks it', () => { - exportSettingsAsJson(base); - expect(anchorClick).toHaveBeenCalledOnce(); - }); - - it('revokes the object URL after triggering the download', () => { - exportSettingsAsJson(base); - expect(URL.revokeObjectURL).toHaveBeenCalledWith(fakeUrl); - }); }); // importSettingsFromJson diff --git a/src/app/utils/settingsSync.ts b/src/app/utils/settingsSync.ts index f09cc405d..135f31ea1 100644 --- a/src/app/utils/settingsSync.ts +++ b/src/app/utils/settingsSync.ts @@ -1,7 +1,7 @@ import { sanitizeThemeRemoteTweakFavorites, type Settings } from '$state/settings'; import { isLocalImportTweakUrl } from '../theme/localImportUrls'; import { sanitizeShortcutOverrides } from '../keyboard/shortcuts'; -import { downloadJsonFile } from './common'; +import { saveFileToDevice } from './download'; /** * Keys excluded from cross-device sync. @@ -152,11 +152,14 @@ export const deserializeFromSync = (data: unknown, currentSettings: Settings): S return merged; }; -/** Trigger a browser download of the current settings as a JSON file. */ +/** Save the current settings as a JSON file. */ export const exportSettingsAsJson = (settings: Settings): void => { - downloadJsonFile( - JSON.stringify({ v: SETTINGS_SYNC_VERSION, settings }, null, 2), - 'sable-settings' + void saveFileToDevice( + new Blob([JSON.stringify({ v: SETTINGS_SYNC_VERSION, settings }, null, 2)], { + type: 'application/json', + }), + `sable-settings-${Date.now()}.json`, + 'application/json' ); }; From c5d27ed3419021a29678c23af100d7efa39da4b7 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sat, 1 Aug 2026 21:42:53 +0200 Subject: [PATCH 013/135] feat: add gif slash command --- src/app/features/room/CommandAutocomplete.tsx | 17 +++++++++++++++-- src/app/features/room/RoomInput.tsx | 6 ++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/app/features/room/CommandAutocomplete.tsx b/src/app/features/room/CommandAutocomplete.tsx index 0dc0d2e9c..2c43d00f8 100644 --- a/src/app/features/room/CommandAutocomplete.tsx +++ b/src/app/features/room/CommandAutocomplete.tsx @@ -19,12 +19,14 @@ import { useKeyDown } from '$hooks/useKeyDown'; import { onTabPress } from '$utils/keyboard'; type CommandAutoCompleteHandler = (commandName: string) => void; +const GIF_COMMAND = 'gif'; type CommandAutocompleteProps = { room: Room; editor: Editor; query: AutocompleteQuery; requestClose: () => void; + onGifSelect: () => void; }; const SEARCH_OPTIONS: UseAsyncSearchOptions = { @@ -38,10 +40,14 @@ export function CommandAutocomplete({ editor, query, requestClose, + onGifSelect, }: CommandAutocompleteProps) { const mx = useMatrixClient(); const commands = useCommands(mx, room); - const commandNames = useMemo(() => Object.keys(commands) as Command[], [commands]); + const commandNames = useMemo( + () => [GIF_COMMAND, ...(Object.keys(commands) as Command[])], + [commands] + ); const [result, search, resetSearch] = useAsyncSearch( commandNames, @@ -57,6 +63,11 @@ export function CommandAutocomplete({ }, [query.text, search, resetSearch]); const handleAutocomplete: CommandAutoCompleteHandler = (commandName) => { + if (commandName === GIF_COMMAND) { + onGifSelect(); + requestClose(); + return; + } const cmdEl = createCommandElement(commandName); replaceWithElement(editor, query.range, cmdEl); moveCursor(editor, true); @@ -106,7 +117,9 @@ export function CommandAutocomplete({ {`/${commandName}`} - {commands[commandName].description} + {commandName === GIF_COMMAND + ? 'Search and send a GIF' + : commands[commandName as Command].description} diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index d081c7e22..09e39dcbf 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -1831,6 +1831,12 @@ export const RoomInput = forwardRef( editor={editor} query={autocompleteQuery} requestClose={handleCloseAutocomplete} + onGifSelect={() => { + resetEditor(editor); + resetEditorHistory(editor); + sendTypingStatus(false); + setEmojiBoardTab(EmojiBoardTab.Gif); + }} /> )} {isQuickTextReact && From 1c2ca406a13cfabbf8d1d01cade74f145cb43969 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sat, 1 Aug 2026 21:48:19 +0200 Subject: [PATCH 014/135] feat: support gif slash command searches --- .changeset/add-gif-slash-command.md | 5 ++++ src/app/components/emoji-board/EmojiBoard.tsx | 12 ++++++++- .../emoji-board/components/SearchInput.tsx | 3 +++ src/app/features/room/CommandAutocomplete.tsx | 9 +------ src/app/features/room/RoomInput.tsx | 25 +++++++++++++------ 5 files changed, 38 insertions(+), 16 deletions(-) create mode 100644 .changeset/add-gif-slash-command.md diff --git a/.changeset/add-gif-slash-command.md b/.changeset/add-gif-slash-command.md new file mode 100644 index 000000000..472c7f028 --- /dev/null +++ b/.changeset/add-gif-slash-command.md @@ -0,0 +1,5 @@ +--- +sable: minor +--- + +Add a `/gif` composer command that opens the GIF picker. diff --git a/src/app/components/emoji-board/EmojiBoard.tsx b/src/app/components/emoji-board/EmojiBoard.tsx index 6c8d78a04..a9f6864fa 100644 --- a/src/app/components/emoji-board/EmojiBoard.tsx +++ b/src/app/components/emoji-board/EmojiBoard.tsx @@ -455,6 +455,7 @@ type EmojiBoardProps = { onCustomEmojiSelect?: (mxc: string, shortcode: string) => void; onStickerSelect?: (mxc: string, shortcode: string, label: string) => void; onGifSelect?: (gif: GifData, spoiler?: boolean) => void; + initialGifSearch?: string; allowTextCustomEmoji?: boolean; addToRecentEmoji?: boolean; isFullWidth?: boolean; @@ -474,6 +475,7 @@ export function EmojiBoard({ onCustomEmojiSelect, onStickerSelect, onGifSelect, + initialGifSearch, allowTextCustomEmoji, addToRecentEmoji = true, isFullWidth, @@ -576,6 +578,13 @@ export function EmojiBoard({ { wait: 200 } ); + useEffect(() => { + if (!gifTab || initialGifSearch === undefined) return; + setShowFavoritesOnly(initialGifSearch.length === 0); + if (initialGifSearch) searchGifs(initialGifSearch); + else resetGifSearch(); + }, [gifTab, initialGifSearch, searchGifs, resetGifSearch]); + const contentScrollRef = useRef(null); const virtualBaseRef = useRef(null); const virtualizer = useVirtualizer({ @@ -677,10 +686,11 @@ export function EmojiBoard({ {onTabChange && } diff --git a/src/app/components/emoji-board/components/SearchInput.tsx b/src/app/components/emoji-board/components/SearchInput.tsx index cabcab0fa..bcf072dc7 100644 --- a/src/app/components/emoji-board/components/SearchInput.tsx +++ b/src/app/components/emoji-board/components/SearchInput.tsx @@ -7,6 +7,7 @@ import { EmojiBoardTab } from '../types'; type SearchInputProps = { query?: string; + defaultValue?: string; onChange: ChangeEventHandler; allowTextCustomEmoji?: boolean; onTextCustomEmojiSelect?: (text: string) => void; @@ -14,6 +15,7 @@ type SearchInputProps = { }; export function SearchInput({ query, + defaultValue, onChange, allowTextCustomEmoji, onTextCustomEmojiSelect, @@ -40,6 +42,7 @@ export function SearchInput({ : 'Search' } maxLength={50} + defaultValue={defaultValue} after={ allowTextCustomEmoji && query && tab !== EmojiBoardTab.Gif ? ( ; requestClose: () => void; - onGifSelect: () => void; }; const SEARCH_OPTIONS: UseAsyncSearchOptions = { @@ -40,7 +39,6 @@ export function CommandAutocomplete({ editor, query, requestClose, - onGifSelect, }: CommandAutocompleteProps) { const mx = useMatrixClient(); const commands = useCommands(mx, room); @@ -63,11 +61,6 @@ export function CommandAutocomplete({ }, [query.text, search, resetSearch]); const handleAutocomplete: CommandAutoCompleteHandler = (commandName) => { - if (commandName === GIF_COMMAND) { - onGifSelect(); - requestClose(); - return; - } const cmdEl = createCommandElement(commandName); replaceWithElement(editor, query.range, cmdEl); moveCursor(editor, true); @@ -118,7 +111,7 @@ export function CommandAutocomplete({ {commandName === GIF_COMMAND - ? 'Search and send a GIF' + ? 'Search and send a GIF: /gif ' : commands[commandName as Command].description} diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 09e39dcbf..26fc9ba85 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -521,11 +521,13 @@ export const RoomInput = forwardRef( const [sendError, setSendError] = useState(); const isEncrypted = room.hasEncryptionStateEvent(); const [emojiBoardTab, setEmojiBoardTab] = useState(undefined); + const [initialGifSearch, setInitialGifSearch] = useState(); const closeEmojiBoard = useCallback(() => { if (isMobileOrTablet()) { const activeElement = document.activeElement; if (activeElement instanceof HTMLElement) activeElement.blur(); } + setInitialGifSearch(undefined); setEmojiBoardTab(undefined); }, []); const toggleEmojiBoardTab = useCallback((tab: EmojiBoardTab) => { @@ -1212,6 +1214,8 @@ export const RoomInput = forwardRef( room, }) ); + const rawGifCommand = + commandName === undefined ? plainText.match(/^\/gif(?:\s+(.*))?$/i) : undefined; let msgType = MsgType.Text; @@ -1228,6 +1232,15 @@ export const RoomInput = forwardRef( return; // don't do anything besides handling the command } + if (rawGifCommand) { + setInitialGifSearch(rawGifCommand[1] ?? ''); + setEmojiBoardTab(EmojiBoardTab.Gif); + resetEditor(editor); + resetEditorHistory(editor); + sendTypingStatus(false); + return; + } + if (commandName) { plainText = trimCommand(commandName, plainText); customHtml = trimCommand(commandName, customHtml); @@ -1249,7 +1262,10 @@ export const RoomInput = forwardRef( if ((commandName as Command) === Command.Poll) setShowPollPicker(true); else if ((commandName as Command) === Command.Location && plainText.trim().length === 0) setShowLocationPicker(true); - else { + else if (commandName === 'gif') { + setInitialGifSearch(plainText); + setEmojiBoardTab(EmojiBoardTab.Gif); + } else { const commandContent = commands[commandName as Command]; if (commandContent) { commandContent.exe(plainText, customHtml); @@ -1831,12 +1847,6 @@ export const RoomInput = forwardRef( editor={editor} query={autocompleteQuery} requestClose={handleCloseAutocomplete} - onGifSelect={() => { - resetEditor(editor); - resetEditorHistory(editor); - sendTypingStatus(false); - setEmojiBoardTab(EmojiBoardTab.Gif); - }} /> )} {isQuickTextReact && @@ -2227,6 +2237,7 @@ export const RoomInput = forwardRef( onCustomEmojiSelect={handleEmoticonSelect} onStickerSelect={handleStickerSelect} onGifSelect={handleGifSelect} + initialGifSearch={initialGifSearch} requestClose={closeEmojiBoard} /> ); From 95054677eb16f470c6bc4e3597d0a276aefc55c0 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sun, 2 Aug 2026 11:38:24 +0200 Subject: [PATCH 015/135] fix(timeline): refresh rows whose event decrypted after they were cached --- .../timeline/useProcessedTimeline.test.tsx | 91 +++++++++++++++++++ .../hooks/timeline/useProcessedTimeline.ts | 26 +++++- .../hooks/timeline/useTimelineSync.test.tsx | 90 +++++++++++++++++- src/app/hooks/timeline/useTimelineSync.ts | 21 ++++- 4 files changed, 221 insertions(+), 7 deletions(-) diff --git a/src/app/hooks/timeline/useProcessedTimeline.test.tsx b/src/app/hooks/timeline/useProcessedTimeline.test.tsx index aa636988a..4143ba2b9 100644 --- a/src/app/hooks/timeline/useProcessedTimeline.test.tsx +++ b/src/app/hooks/timeline/useProcessedTimeline.test.tsx @@ -834,3 +834,94 @@ describe('append-only fast path vs full reprocess (fuzz)', () => { } }); }); + +function createEncryptedEvent(id: string, ts: number) { + const state = { + type: EventType.RoomMessageEncrypted as string, + content: { algorithm: 'm.megolm.v1.aes-sha2', ciphertext: 'AwgAEnB' } as Record< + string, + unknown + >, + }; + const mEvent = { + getId: () => id, + getType: () => state.type, + getSender: () => OTHER_USER, + getContent: () => state.content, + getPrevContent: () => ({}), + getWireContent: () => state.content, + getTs: () => ts, + isRedacted: () => false, + isRedaction: () => false, + isEncrypted: () => true, + getRelation: () => null, + threadRootId: undefined, + } as unknown as MatrixEvent; + const decrypt = () => { + state.type = EventType.RoomMessage as string; + state.content = { msgtype: 'm.text', body: 'the secret' }; + }; + return { mEvent, decrypt }; +} + +const bodyOf = (processed: ProcessedEvent[], id: string) => + (processed.find((e) => e.id === id)?.content as Record | undefined)?.body; + +describe('useProcessedTimeline decryption', () => { + // Stable so the append-only fast path is reachable. + const ignoredUsersSet = new Set(); + const renderTimeline = (getEvents: () => MatrixEvent[]) => + renderHook(() => + useProcessedTimeline({ + items: getEvents().map((_, i) => i), + linkedTimelines: [createTimeline(getEvents())], + ignoredUsersSet, + hiddenEvents, + mxUserId: MY_USER, + readUptoEventId: undefined, + hideMembershipEvents: true, + hideNickAvatarEvents: true, + isReadOnly: false, + hideMemberInReadOnly: false, + }) + ); + + it('refreshes a row whose event decrypted since it was cached', () => { + const { mEvent: encrypted, decrypt } = createEncryptedEvent('$enc', 1_000_000); + let events: MatrixEvent[] = [createEvent({ id: '$a', ts: 999_000 }), encrypted]; + + const { result, rerender } = renderTimeline(() => events); + expect(renderedIds(result.current)).toEqual(['$a', '$enc']); + + decrypt(); + rerender(); + + expect(bodyOf(result.current, '$enc')).toBe('the secret'); + }); + + it('does not carry a stale encrypted row through the append-only fast path', () => { + const { mEvent: encrypted, decrypt } = createEncryptedEvent('$enc', 1_000_000); + let events: MatrixEvent[] = [createEvent({ id: '$a', ts: 999_000 }), encrypted]; + + const { result, rerender } = renderTimeline(() => events); + + decrypt(); + events = [...events, createEvent({ id: '$live', ts: 1_001_000 })]; + rerender(); + + expect(renderedIds(result.current)).toEqual(['$a', '$enc', '$live']); + expect(bodyOf(result.current, '$enc')).toBe('the secret'); + }); + + it('keeps the append-only fast path for unencrypted events', () => { + let events: MatrixEvent[] = [createEvent({ id: '$a', ts: 999_000 })]; + const { result, rerender } = renderTimeline(() => events); + const firstRow = result.current[0]; + + events = [...events, createEvent({ id: '$b', ts: 1_000_000 })]; + rerender(); + + expect(renderedIds(result.current)).toEqual(['$a', '$b']); + expect(result.current[0]).toBe(firstRow); + }); +}); diff --git a/src/app/hooks/timeline/useProcessedTimeline.ts b/src/app/hooks/timeline/useProcessedTimeline.ts index 8b8689e47..ef3ab9a5c 100644 --- a/src/app/hooks/timeline/useProcessedTimeline.ts +++ b/src/app/hooks/timeline/useProcessedTimeline.ts @@ -110,17 +110,37 @@ type ProcessedEventDraft = Omit< type TimelineEventEntry = { mEvent: MatrixEvent; timelineSet: EventTimelineSet; + // Decryption rewrites a MatrixEvent in place, so identity alone does not prove a cached + // row still matches it. Undefined for unencrypted events. + clearType: string | undefined; + clearContent: unknown; }; const flattenTimelineEvents = (linkedTimelines: EventTimeline[]): TimelineEventEntry[] => { const entries: TimelineEventEntry[] = []; linkedTimelines.forEach((timeline) => { const timelineSet = timeline.getTimelineSet(); - timeline.getEvents().forEach((mEvent) => entries.push({ mEvent, timelineSet })); + timeline.getEvents().forEach((mEvent) => { + const encrypted = mEvent.isEncrypted(); + entries.push({ + mEvent, + timelineSet, + clearType: encrypted ? mEvent.getType() : undefined, + clearContent: encrypted ? mEvent.getContent() : undefined, + }); + }); }); return entries; }; +const isCachedEntryCurrent = ( + cached: TimelineEventEntry, + current: TimelineEventEntry | undefined +): boolean => + cached.mEvent === current?.mEvent && + cached.clearType === current.clearType && + cached.clearContent === current.clearContent; + const computeCollapseAndDividers = ( drafts: ProcessedEventDraft[], mxUserId: string | null, @@ -648,8 +668,8 @@ export function useProcessedTimeline({ items.every((item, index) => item === index) && // Cached rows are reused verbatim, so anchoring on the first and last event // alone would accept a run that both inserted and removed within the prefix. - previous.timelineEvents.every( - (entry, index) => entry.mEvent === timelineEvents[index]?.mEvent + previous.timelineEvents.every((entry, index) => + isCachedEntryCurrent(entry, timelineEvents[index]) ) && (appendedEntries.length === 0 || (previous.timelineEvents.at(-1)?.mEvent.getTs() ?? 0) <= diff --git a/src/app/hooks/timeline/useTimelineSync.test.tsx b/src/app/hooks/timeline/useTimelineSync.test.tsx index 664aabbad..fadc47677 100644 --- a/src/app/hooks/timeline/useTimelineSync.test.tsx +++ b/src/app/hooks/timeline/useTimelineSync.test.tsx @@ -987,7 +987,9 @@ describe('live-arrive edge cases', () => { await act(async () => { mxEmitter.emit(MatrixEventEvent.Decrypted, { getRoomId: () => room.roomId }); - await Promise.resolve(); + await new Promise((resolve) => { + requestAnimationFrame(() => resolve(undefined)); + }); }); expect(result.current.timeline).not.toBe(before); @@ -1000,7 +1002,9 @@ describe('live-arrive edge cases', () => { await act(async () => { mxEmitter.emit(MatrixEventEvent.Decrypted, { getRoomId: () => '!other:test' }); - await Promise.resolve(); + await new Promise((resolve) => { + requestAnimationFrame(() => resolve(undefined)); + }); }); expect(result.current.timeline).toBe(before); @@ -1244,3 +1248,85 @@ describe('sync transport fuzz', () => { } ); }); + +const flushFrame = async () => { + await act(async () => { + await new Promise((resolve) => { + requestAnimationFrame(() => resolve(undefined)); + }); + }); +}; + +describe('decryption refresh coalescing', () => { + // Counts distinct timeline objects, not renders: unrelated re-renders reuse the object. + const renderTrackingHook = (room: FakeRoom) => { + const seen: unknown[] = []; + renderHook(() => { + const sync = useTimelineSync({ + room: room as Room, + mx: makeMx(), + isAtBottom: true, + isAtBottomRef: { current: true }, + scrollToBottom: vi.fn<() => void>(), + unreadInfo: undefined, + setUnreadInfo: vi.fn<() => void>(), + hideReadsRef: { current: false }, + readUptoEventIdRef: { current: undefined }, + }); + if (!seen.includes(sync.timeline)) seen.push(sync.timeline); + return sync; + }); + return seen; + }; + + // One act() per event mirrors decryptions landing in separate tasks. + const emitDecryptedAcrossTasks = async (room: FakeRoom, eventCount: number) => { + for (let i = 0; i < eventCount; i += 1) { + // eslint-disable-next-line no-await-in-loop + await act(async () => { + mxEmitter.emit(MatrixEventEvent.Decrypted, { getRoomId: () => room.roomId }); + }); + } + }; + + it('collapses a backlog decryption burst into a single timeline update', async () => { + const { room } = createRoom(); + const seen = renderTrackingHook(room); + const initial = seen.length; + + await emitDecryptedAcrossTasks(room, 25); + await flushFrame(); + + // Uncoalesced this is 25. A frame boundary may split the burst, so allow a small range. + expect(seen.length - initial).toBeGreaterThan(0); + expect(seen.length - initial).toBeLessThan(5); + }); + + it('re-arms for the next burst', async () => { + const { room } = createRoom(); + const seen = renderTrackingHook(room); + const initial = seen.length; + + await emitDecryptedAcrossTasks(room, 5); + await flushFrame(); + const afterFirstBurst = seen.length; + await emitDecryptedAcrossTasks(room, 5); + await flushFrame(); + + expect(afterFirstBurst).toBeGreaterThan(initial); + expect(seen.length).toBeGreaterThan(afterFirstBurst); + }); + + it('ignores decryption bursts from another room', async () => { + const { room } = createRoom(); + const seen = renderTrackingHook(room); + const initial = seen.length; + + await act(async () => { + mxEmitter.emit(MatrixEventEvent.Decrypted, { getRoomId: () => '!other:test' }); + }); + await flushFrame(); + + expect(seen.length).toBe(initial); + }); +}); diff --git a/src/app/hooks/timeline/useTimelineSync.ts b/src/app/hooks/timeline/useTimelineSync.ts index b7f1475a9..85aa4a66f 100644 --- a/src/app/hooks/timeline/useTimelineSync.ts +++ b/src/app/hooks/timeline/useTimelineSync.ts @@ -580,12 +580,29 @@ export function useTimelineSync({ useMatrixEvent(room, RoomEvent.LocalEchoUpdated, handleLocalEchoUpdated); + // A cached room decrypts its whole backlog, one event per task, so batching does not + // collapse it. One reprocess a frame instead of one per event. + const decryptedFrameRef = useRef(); const handleDecrypted = useCallback( (mEvent: MatrixEvent) => { if (mEvent.getRoomId() !== room.roomId) return; - setTimeline((ct) => ({ ...ct })); + if (decryptedFrameRef.current !== undefined) return; + decryptedFrameRef.current = requestAnimationFrame(() => { + decryptedFrameRef.current = undefined; + if (!alive()) return; + setTimeline((ct) => ({ ...ct })); + }); }, - [room, setTimeline] + [alive, room, setTimeline] + ); + + useEffect( + () => () => { + if (decryptedFrameRef.current !== undefined) { + cancelAnimationFrame(decryptedFrameRef.current); + } + }, + [] ); useMatrixEvent(mx, MatrixEventEvent.Decrypted, handleDecrypted); From 3e3ae9a59fff45bb23d244c80f22c4fa780d4bec Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sat, 1 Aug 2026 10:51:50 +0200 Subject: [PATCH 016/135] fix(members): refill the member roster when sliding sync only lazy-loaded it --- .changeset/fix-lazy-loaded-member-roster.md | 5 + src/app/hooks/useRoomMembers.ts | 7 +- src/client/roomMemberHydration.test.ts | 101 +++++++++++++++++++- src/client/roomMemberHydration.ts | 46 ++++++++- 4 files changed, 155 insertions(+), 4 deletions(-) create mode 100644 .changeset/fix-lazy-loaded-member-roster.md diff --git a/.changeset/fix-lazy-loaded-member-roster.md b/.changeset/fix-lazy-loaded-member-roster.md new file mode 100644 index 000000000..c577a1195 --- /dev/null +++ b/.changeset/fix-lazy-loaded-member-roster.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Refill the room member list from the server when sliding sync only delivered lazy-loaded members, so mention autocomplete and the members panel are complete. diff --git a/src/app/hooks/useRoomMembers.ts b/src/app/hooks/useRoomMembers.ts index 31e04867f..4469680d6 100644 --- a/src/app/hooks/useRoomMembers.ts +++ b/src/app/hooks/useRoomMembers.ts @@ -1,6 +1,7 @@ import type { MatrixClient, MatrixEvent, RoomMember } from '$types/matrix-sdk'; import { EventType, RoomMemberEvent, RoomStateEvent } from '$types/matrix-sdk'; import { useEffect, useState } from 'react'; +import { hydrateAllRoomMembers } from '$client/roomMemberHydration'; export const useRoomMembers = (mx: MatrixClient, roomId: string, enabled = true): RoomMember[] => { const [members, setMembers] = useState([]); @@ -23,11 +24,13 @@ export const useRoomMembers = (mx: MatrixClient, roomId: string, enabled = true) if (room) { setMembers(room.getMembers()); - room.loadMembersIfNeeded().then(() => { + const stopLoading = () => { loadingMembers = false; if (disposed) return; updateMemberList(); - }); + void hydrateAllRoomMembers(mx, roomId).then(() => updateMemberList()); + }; + room.loadMembersIfNeeded().then(stopLoading, stopLoading); } const handleStateEvent = (event: MatrixEvent) => { diff --git a/src/client/roomMemberHydration.test.ts b/src/client/roomMemberHydration.test.ts index 7a6c4ebd4..d447e5bae 100644 --- a/src/client/roomMemberHydration.test.ts +++ b/src/client/roomMemberHydration.test.ts @@ -2,7 +2,11 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import type { MatrixClient, Room, RoomMember } from '$types/matrix-sdk'; import { EventType } from '$types/matrix-sdk'; -import { hydrateRoomMember, hydrateRoomMembers } from './roomMemberHydration'; +import { + hydrateAllRoomMembers, + hydrateRoomMember, + hydrateRoomMembers, +} from './roomMemberHydration'; const ROOM_ID = '!room:server'; const USER_ID = '@ghost:server'; @@ -151,6 +155,101 @@ describe('hydrateRoomMember (force)', () => { }); }); +type BulkFakeSetup = { + mx: MatrixClient; + members: ReturnType; + setStateEvents: ReturnType; +}; + +const makeBulkFakes = ( + joinedMembers: number, + joinedCount: number, + knownMemberIds: string[] = [] +): BulkFakeSetup => { + const setStateEvents = vi.fn<() => void>(); + const room = { + roomId: ROOM_ID, + getJoinedMembers: () => Array.from({ length: joinedMembers }, () => ({}) as RoomMember), + getJoinedMemberCount: () => joinedCount, + getMember: (userId: string) => (knownMemberIds.includes(userId) ? ({} as RoomMember) : null), + currentState: { setStateEvents }, + } as unknown as Room; + const members = vi.fn<() => Promise>(() => + Promise.resolve({ + chunk: [ + { + type: EventType.RoomMember, + state_key: USER_ID, + room_id: ROOM_ID, + sender: USER_ID, + content: { membership: 'join' }, + }, + ], + }) + ); + const mx = { + getRoom: () => room, + members, + } as unknown as MatrixClient; + return { mx, members, setStateEvents }; +}; + +describe('hydrateAllRoomMembers', () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it('fetches the full member list when the roster is short of the joined count', async () => { + const { mx, members, setStateEvents } = makeBulkFakes(2, 20); + + await hydrateAllRoomMembers(mx, ROOM_ID); + + expect(members).toHaveBeenCalledWith(ROOM_ID, undefined, 'leave'); + const [events] = setStateEvents.mock.calls[0] as [Array<{ getType: () => string }>]; + expect(events[0]?.getType()).toBe(EventType.RoomMember); + }); + + it('skips members the room already knows', async () => { + const { mx, setStateEvents } = makeBulkFakes(2, 20, [USER_ID]); + + await hydrateAllRoomMembers(mx, ROOM_ID); + + expect(setStateEvents).not.toHaveBeenCalled(); + }); + + it('does nothing when the roster already matches the joined count', async () => { + const { mx, members } = makeBulkFakes(20, 20); + + await hydrateAllRoomMembers(mx, ROOM_ID); + + expect(members).not.toHaveBeenCalled(); + }); + + it('does not refetch within the TTL and retries after it', async () => { + const { mx, members } = makeBulkFakes(2, 20); + + await hydrateAllRoomMembers(mx, ROOM_ID); + await hydrateAllRoomMembers(mx, ROOM_ID); + expect(members).toHaveBeenCalledTimes(1); + + vi.advanceTimersByTime(5 * 60_000 + 1); + await hydrateAllRoomMembers(mx, ROOM_ID); + expect(members).toHaveBeenCalledTimes(2); + }); + + it('swallows a failed fetch', async () => { + const { mx, members, setStateEvents } = makeBulkFakes(2, 20); + members.mockRejectedValueOnce(new Error('403')); + + await expect(hydrateAllRoomMembers(mx, ROOM_ID)).resolves.toBeUndefined(); + expect(setStateEvents).not.toHaveBeenCalled(); + }); +}); + describe('hydrateRoomMembers', () => { it('dedups user ids and filters non-user ids', async () => { const { mx, getStateEvent } = makeFakes(); diff --git a/src/client/roomMemberHydration.ts b/src/client/roomMemberHydration.ts index cc4374566..ef5493d27 100644 --- a/src/client/roomMemberHydration.ts +++ b/src/client/roomMemberHydration.ts @@ -1,5 +1,5 @@ import type { MatrixClient } from '$types/matrix-sdk'; -import { EventType, MatrixEvent } from '$types/matrix-sdk'; +import { EventType, KnownMembership, MatrixEvent } from '$types/matrix-sdk'; const inFlight = new WeakMap>>(); @@ -103,6 +103,50 @@ export const hydrateRoomMember = ( return request; }; +// The SDK only fetches /members when the sync store holds no out-of-band member +// set for the room. Sliding sync sends $LAZY members, so a room whose stored set +// predates most joins keeps a short roster forever. Refill it from the server. +const BULK_TTL_MS = 5 * 60_000; +const bulkInFlight = new WeakMap>>(); +const bulkAttemptedAt = new WeakMap>(); + +export const hydrateAllRoomMembers = (mx: MatrixClient, roomId: string): Promise => { + const room = mx.getRoom(roomId); + if (!room) return Promise.resolve(); + if (room.getJoinedMembers().length >= room.getJoinedMemberCount()) return Promise.resolve(); + + const attemptedTs = bulkAttemptedAt.get(mx)?.get(roomId); + if (attemptedTs !== undefined && Date.now() - attemptedTs < BULK_TTL_MS) return Promise.resolve(); + + const pending = bulkInFlight.get(mx) ?? new Map>(); + bulkInFlight.set(mx, pending); + const existing = pending.get(roomId); + if (existing) return existing; + + const attempts = bulkAttemptedAt.get(mx) ?? new Map(); + bulkAttemptedAt.set(mx, attempts); + attempts.set(roomId, Date.now()); + + const request = mx + .members(roomId, undefined, KnownMembership.Leave) + .then(({ chunk }) => { + const currentRoom = mx.getRoom(roomId); + if (!currentRoom || !chunk) return; + // The response is current state, which may be ahead of our sync position, + // so only fill in members we are missing rather than overwriting known ones. + const missing = chunk.filter( + (event) => event.state_key && !currentRoom.getMember(event.state_key) + ); + if (missing.length === 0) return; + currentRoom.currentState.setStateEvents(missing.map((event) => new MatrixEvent(event))); + }) + .catch(() => undefined) + .finally(() => pending.delete(roomId)); + + pending.set(roomId, request); + return request; +}; + export const hydrateRoomMembers = ( mx: MatrixClient, roomId: string, From aaf4c7a7f52effe2ffefcd35f492915e126b2db1 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sun, 2 Aug 2026 23:27:40 +0200 Subject: [PATCH 017/135] fix(mobile): don't block message swipe on inline ignored elements --- .../components/page/MobileNavDrawer.test.tsx | 48 ++++++++++++++++++- src/app/components/page/MobileNavDrawer.tsx | 7 ++- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/src/app/components/page/MobileNavDrawer.test.tsx b/src/app/components/page/MobileNavDrawer.test.tsx index 1f4c45167..4de18989d 100644 --- a/src/app/components/page/MobileNavDrawer.test.tsx +++ b/src/app/components/page/MobileNavDrawer.test.tsx @@ -1,7 +1,9 @@ -import { render, screen } from '@testing-library/react'; +import { useLayoutEffect, useRef } from 'react'; +import { fireEvent, render, screen } from '@testing-library/react'; import { beforeAll, describe, expect, it, vi } from 'vitest'; import { MemoryRouter } from 'react-router-dom'; import { MobileNavDrawer } from './MobileNavDrawer'; +import { useMobileNavDrawer } from './MobileNavDrawerContext'; vi.mock('$state/hooks/settings', () => ({ useSetting: () => [true, vi.fn<() => void>()], @@ -36,6 +38,11 @@ const renderDrawer = () => ); +const touchList = (target: HTMLElement, clientX: number, clientY: number) => { + const point = { identifier: 0, target, clientX, clientY, pageX: clientX, pageY: clientY }; + return { touches: [point], targetTouches: [point], changedTouches: [point] }; +}; + describe('MobileNavDrawer', () => { // The panels sit side by side in a track twice the viewport wide, moved by transform. // `hidden` leaves a scrollport that focus or scrollIntoView scrolls a full panel width, @@ -48,4 +55,43 @@ describe('MobileNavDrawer', () => { expect(viewport.style.overflow).toBe('clip'); expect(viewport.style.overflow).not.toBe('hidden'); }); + + it('still drives message swipe when the gesture starts on a nested ignored element (e.g. an image)', () => { + const move = vi.fn<(distanceX: number) => void>(); + + function MessageProbe() { + const drawer = useMobileNavDrawer(); + const containerRef = useRef(null); + useLayoutEffect(() => { + const el = containerRef.current; + if (!el || !drawer) return undefined; + return drawer.registerMessageSwipe(el, { + move, + end: vi.fn<(gesture: { distanceX: number; velocityX: number }) => void>(), + cancel: vi.fn<() => void>(), + }); + }, [drawer]); + return ( +
+
+ image +
+
+ ); + } + + render( + + }> +
content
+
+
+ ); + + const image = screen.getByTestId('image'); + fireEvent.touchStart(image, touchList(image, 260, 100)); + fireEvent.touchMove(image, touchList(image, 200, 100)); + + expect(move).toHaveBeenCalled(); + }); }); diff --git a/src/app/components/page/MobileNavDrawer.tsx b/src/app/components/page/MobileNavDrawer.tsx index 9d4d2c117..440fb4316 100644 --- a/src/app/components/page/MobileNavDrawer.tsx +++ b/src/app/components/page/MobileNavDrawer.tsx @@ -353,7 +353,12 @@ export function MobileNavDrawer({ nav, rail, bottomNav, children }: MobileNavDra const ignoredElement = target.closest('[data-gestures="ignore"]'); const message = messageElement ? messageTargetsRef.current.get(messageElement) : undefined; const chat = chatElement ? chatTargetsRef.current.get(chatElement) : undefined; - const blocked = ignoredElement !== null && ignoredElement !== messageElement; + // Nested ignore markers (e.g. inline media) don't block swipe if they're part of + // this message/chat's own surface, only if they sit outside it. + const blocked = + ignoredElement !== null && + !(messageElement && messageElement.contains(ignoredElement)) && + !(chatElement && chatElement.contains(ignoredElement)); gestureRef.current = { startX: touch.clientX, From b50b10f6967f4afac511398694edede81a90aedf Mon Sep 17 00:00:00 2001 From: Daisy Date: Wed, 29 Jul 2026 12:40:41 +0100 Subject: [PATCH 018/135] Impl MSC4461: Storing per-message profiles for users --- ..._storing_per_message_profiles_for_users.md | 5 + package.json | 1 + pnpm-lock.yaml | 10 + .../message-preview/MessagePreview.tsx | 12 +- src/app/components/message/Reply.tsx | 2 +- src/app/components/message/modals/Options.tsx | 4 +- src/app/features/room/RoomInput.tsx | 12 +- .../features/room/buildReplacementContent.ts | 8 +- src/app/features/room/message/Message.tsx | 8 +- .../room/persona-picker/PersonaPicker.tsx | 53 ++- .../Persona/PerMessageProfileEditor.tsx | 375 +++++++--------- .../Persona/PerMessageProfileEditorView.tsx | 36 +- .../Persona/PerMessageProfileOverview.tsx | 27 +- .../settings/Persona/ProfilesPage.tsx | 15 +- src/app/hooks/commands/pmp.ts | 13 +- src/app/hooks/usePerMessageProfile.ts | 399 +++++++++++------- .../PKitCommandMessageHandler.ts | 129 +++++- .../PKitProxyMessageHandler.test.ts | 26 +- .../PKitProxyMessageHandler.ts | 34 +- src/unstable/prefixes/msc/profile.ts | 4 +- src/unstable/prefixes/sable/accountdata.ts | 2 + 21 files changed, 652 insertions(+), 523 deletions(-) create mode 100644 .changeset/impl_msc4461_storing_per_message_profiles_for_users.md diff --git a/.changeset/impl_msc4461_storing_per_message_profiles_for_users.md b/.changeset/impl_msc4461_storing_per_message_profiles_for_users.md new file mode 100644 index 000000000..814ed7a7f --- /dev/null +++ b/.changeset/impl_msc4461_storing_per_message_profiles_for_users.md @@ -0,0 +1,5 @@ +--- +default: minor +--- + +# Impl MSC4461: Storing per-message profiles for users diff --git a/package.json b/package.json index 2660b32fb..1cc987ce9 100644 --- a/package.json +++ b/package.json @@ -99,6 +99,7 @@ "marked": "^18.0.5", "matrix-js-sdk": "42.0.0", "matrix-widget-api": "^1.17.0", + "nanoid": "^6.0.0", "pdfjs-dist": "^6.1.200", "react": "^18.3.1", "react-aria": "^3.50.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 834f3a991..3ca5c9473 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -202,6 +202,9 @@ importers: matrix-widget-api: specifier: ^1.17.0 version: 1.17.0 + nanoid: + specifier: ^6.0.0 + version: 6.0.0 pdfjs-dist: specifier: ^6.1.200 version: 6.1.200 @@ -4634,6 +4637,11 @@ packages: engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} hasBin: true + nanoid@6.0.0: + resolution: {integrity: sha512-mkUH+rPkwU2qPadJ0oJZOjeZ5Mxn8Q1UhevwkTRWNuUZzyia3h4rhzK39hxaHTk0o2OxB8W2SQ6A8k23ZDi1pQ==} + engines: {node: ^22 || ^24 || >=26} + hasBin: true + no-case@3.0.4: resolution: {integrity: sha512-fgAN3jGAh+RoxUGZHTSOLJIqUc2wmoBwGR4tbpNAKmmovFoWq0OdRkb0VkldReO2a2iBT/OEulG9XSUc10r3zg==} @@ -9824,6 +9832,8 @@ snapshots: nanoid@3.3.12: {} + nanoid@6.0.0: {} + no-case@3.0.4: dependencies: lower-case: 2.0.2 diff --git a/src/app/components/message-preview/MessagePreview.tsx b/src/app/components/message-preview/MessagePreview.tsx index 34017482a..f78a64a12 100644 --- a/src/app/components/message-preview/MessagePreview.tsx +++ b/src/app/components/message-preview/MessagePreview.tsx @@ -415,11 +415,13 @@ export function MessagePreview({ const [showPronouns] = useSetting(settingsAtom, 'showPronouns'); const [parsePronouns] = useSetting(settingsAtom, 'parsePronouns'); const { cleanedDisplayName: displayName, inlinePronoun } = useMemo( - () => getParsedPronouns(perMessageProfile?.name || fallbackDisplayName, parsePronouns), - [perMessageProfile?.name, fallbackDisplayName, parsePronouns] + () => getParsedPronouns(perMessageProfile?.displayname || fallbackDisplayName, parsePronouns), + [perMessageProfile?.displayname, fallbackDisplayName, parsePronouns] ); const pronouns = useMemo(() => { - const resolved = [...(perMessageProfile?.pronouns ?? userProfile.pronouns ?? [])]; + const resolved = [ + ...(perMessageProfile?.['io.fsky.nyx.pronouns'] ?? userProfile.pronouns ?? []), + ]; if ( inlinePronoun && !resolved.some((item) => item.summary?.toLowerCase() === inlinePronoun.toLowerCase()) @@ -427,9 +429,9 @@ export function MessagePreview({ resolved.push({ summary: inlinePronoun, language: 'en' }); } return resolved; - }, [perMessageProfile?.pronouns, userProfile.pronouns, inlinePronoun]); + }, [perMessageProfile, userProfile.pronouns, inlinePronoun]); const avatarMxc = - perMessageProfile?.avatarUrl ?? + perMessageProfile?.avatar_url ?? getMemberAvatarMxc(room, sender) ?? userProfile.avatarUrl ?? profile?.avatarUrl; diff --git a/src/app/components/message/Reply.tsx b/src/app/components/message/Reply.tsx index 66cf450c2..7939ef854 100644 --- a/src/app/components/message/Reply.tsx +++ b/src/app/components/message/Reply.tsx @@ -512,7 +512,7 @@ export const Reply = as<'div', ReplyProps>( eventType !== EventType.RoomMember && ( - {pmp?.name ?? + {pmp?.displayname ?? getMemberDisplayName(room, sender, nicknames) ?? cachedProfiles[sender]?.displayName ?? getMxIdLocalPart(sender)} diff --git a/src/app/components/message/modals/Options.tsx b/src/app/components/message/modals/Options.tsx index 823e10139..ce12ac770 100644 --- a/src/app/components/message/modals/Options.tsx +++ b/src/app/components/message/modals/Options.tsx @@ -67,7 +67,7 @@ import { useFavoriteGifs } from '$hooks/useFavoriteGifs'; import type { IImageInfo } from '$types/matrix/common'; import { getIncomingMediaMxcUrl } from '../MsgTypeRenderers'; import { TemporaryPersonaPicker } from '$features/room/persona-picker/PersonaPicker'; -import { type PerMessageProfile } from '$hooks/usePerMessageProfile'; +import { type PerMessageProfileMsc4461 } from '$hooks/usePerMessageProfile'; import { buildReplacementPmpContent } from '$features/room/buildReplacementContent'; import { settingsAtom } from '$state/settings'; import { useSetting } from '$state/hooks/settings'; @@ -414,7 +414,7 @@ function OptionsReproxyPersonaPicker({ closeMenu, anchor, }: OptionsReproxyPersonaPickerProps) { - const reproxyMessage = async (profile: PerMessageProfile | undefined) => { + const reproxyMessage = async (profile: PerMessageProfileMsc4461 | undefined) => { const content = buildReplacementPmpContent(mEvent.getContent(), mEvent.getId()!, profile); await mx.sendMessage(roomId, content as RoomMessageEventContent); diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 34e511469..2758e9ffd 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -150,7 +150,7 @@ import { convertPerMessageProfileToBeeperFormat, getCurrentlyUsedPerMessageProfileForAccount, getCurrentlyUsedPerMessageProfileForRoom, - type PerMessageProfile, + type PerMessageProfileMsc4461, setCurrentlyUsedPerMessageProfileIdForRoom, } from '$hooks/usePerMessageProfile'; import { @@ -342,7 +342,7 @@ export const RoomInput = forwardRef( const [pmpLatchingEnable] = useSetting(settingsAtom, 'pmpLatching'); const [pmpPickerEnable] = useSetting(settingsAtom, 'pmpPicker'); - const [latchedPersona, setLatchedPersona] = useState(); + const [latchedPersona, setLatchedPersona] = useState(); const emojiBtnRef = useRef(null); const gifBtnRef = useRef(null); @@ -1361,12 +1361,12 @@ export const RoomInput = forwardRef( content[prefix.MATRIX_UNSTABLE_PER_MESSAGE_PROFILE_PROPERTY_NAME] = convertPerMessageProfileToBeeperFormat( perMessageProfile, - perMessageProfile.name.trim() !== '' + perMessageProfile.displayname.trim() !== '' ); - if (perMessageProfile.name.trim() !== '') { + if (perMessageProfile.displayname.trim() !== '') { // if a per-message profile is used, it must per spec include a fallback - const pmpPrefix = `${perMessageProfile.name}: `; + const pmpPrefix = `${perMessageProfile.displayname}: `; if (!content.body.startsWith(pmpPrefix)) { // to prevent double-prefixing when the fallback is already present @@ -1376,7 +1376,7 @@ export const RoomInput = forwardRef( /** * html escaped version of the display name */ - const escapedName = sanitizeText(perMessageProfile.name); + const escapedName = sanitizeText(perMessageProfile.displayname); const htmlPrefix = `${escapedName}: `; diff --git a/src/app/features/room/buildReplacementContent.ts b/src/app/features/room/buildReplacementContent.ts index 2b3e24fa8..011ba3b3d 100644 --- a/src/app/features/room/buildReplacementContent.ts +++ b/src/app/features/room/buildReplacementContent.ts @@ -2,7 +2,7 @@ import type { IContent, IMentions } from '$types/matrix-sdk'; import { MsgType, RelationType } from '$types/matrix-sdk'; import { customHtmlEqualsPlainText } from '$components/editor'; import { sanitizeText } from '$utils/sanitize'; -import type { PerMessageProfile } from '$hooks/usePerMessageProfile'; +import type { PerMessageProfileMsc4461 } from '$hooks/usePerMessageProfile'; import { convertPerMessageProfileToBeeperFormat } from '$hooks/usePerMessageProfile'; import { MATRIX_UNSTABLE_PER_MESSAGE_PROFILE_PROPERTY_NAME } from '$unstable/prefixes'; @@ -100,7 +100,7 @@ export function buildReplacementContent( export function buildReplacementPmpContent( oldContent: IContent, eventId: string, - newProfile: PerMessageProfile | undefined + newProfile: PerMessageProfileMsc4461 | undefined ) { const profileBeeperFormat = newProfile && convertPerMessageProfileToBeeperFormat(newProfile, true); @@ -121,7 +121,7 @@ export function buildReplacementPmpContent( } if (newProfile) { - const escapedName = sanitizeText(newProfile.name); + const escapedName = sanitizeText(newProfile.displayname); const htmlPrefix = `${escapedName}: `; if (oldContent.formatted_body) { @@ -133,7 +133,7 @@ export function buildReplacementPmpContent( oldContent.formatted_body = `${htmlPrefix}${escapedBody}`; } - const pmpPrefix = `${newProfile.name}: `; + const pmpPrefix = `${newProfile.displayname}: `; oldContent.body = pmpPrefix + oldContent.body; } diff --git a/src/app/features/room/message/Message.tsx b/src/app/features/room/message/Message.tsx index c3e13c960..d4698fd58 100644 --- a/src/app/features/room/message/Message.tsx +++ b/src/app/features/room/message/Message.tsx @@ -458,8 +458,8 @@ function MessageInternal( const pmpNameColor = useMemo(() => { if (!renderPersonaColors) return undefined; - const pmpNameColorLight = parsedPMPContent?.colors?.on_light; - const pmpNameColorDark = parsedPMPContent?.colors?.on_dark; + const pmpNameColorLight = parsedPMPContent?.['eu.she-a.color']?.on_light; + const pmpNameColorDark = parsedPMPContent?.['eu.she-a.color']?.on_dark; return activeTheme.kind === ThemeKind.Dark ? pmpNameColorDark : pmpNameColorLight; }, [parsedPMPContent, activeTheme, renderPersonaColors]); @@ -468,7 +468,7 @@ function MessageInternal( * boolean to indicate wheather we should indicate to the user that it is a pmp * We want to not show it, when the name is unset, or whitespace only */ - const showPmPInfo = parsedPMPContent?.name && parsedPMPContent.name?.trim() !== ''; + const showPmPInfo = parsedPMPContent?.displayname && parsedPMPContent.displayname?.trim() !== ''; // Profiles and Colors const profile = useUserProfile(senderId, room, undefined, true, isVisible); const { color: usernameColor, font: usernameFont } = useSableCosmetics( @@ -488,7 +488,7 @@ function MessageInternal( * otherwise we fall back to the profile pronouns. * This allows users to set pronouns on a per-message basis, while still falling back to their profile pronouns if they don't set any for a specific message. */ - const pronouns = parsedPMPContent?.pronouns ?? profile.pronouns; + const pronouns = parsedPMPContent?.['io.fsky.nyx.pronouns'] ?? profile.pronouns; const [highlightMentions] = useSetting(settingsAtom, 'highlightMentions'); diff --git a/src/app/features/room/persona-picker/PersonaPicker.tsx b/src/app/features/room/persona-picker/PersonaPicker.tsx index a5173d294..6a747f2cb 100644 --- a/src/app/features/room/persona-picker/PersonaPicker.tsx +++ b/src/app/features/room/persona-picker/PersonaPicker.tsx @@ -10,7 +10,7 @@ import { useMediaAuthentication } from '$hooks/useMediaAuthentication.ts'; import { getCurrentlyUsedPerMessageProfileForRoom, getAllPerMessageProfiles, - type PerMessageProfile, + type PerMessageProfileMsc4461, setCurrentlyUsedPerMessageProfileIdForRoom, getCurrentlyUsedPerMessageProfileForAccount, setCurrentlyUsedPerMessageProfileIdForAccount, @@ -58,9 +58,9 @@ type PersonaPickerProps = { roomId?: string; suppressEditorRefocus?: () => void; onTabChange?: (tab: PersonaPickerTab) => void; - latchedPersona?: PerMessageProfile; + latchedPersona?: PerMessageProfileMsc4461; hideTabs?: boolean; - onPersonaSelect?: (persona: PerMessageProfile | undefined) => void; + onPersonaSelect?: (persona: PerMessageProfileMsc4461 | undefined) => void; requestClose?: () => void; showNoneOption?: boolean; hideButton?: boolean; @@ -126,22 +126,26 @@ function PersonaPicker({ onTabChange, }: PersonaPickerProps & { presentation: PersonaPickerPresentation }) { const useAuthentication = useMediaAuthentication(); - const persistent = presentation === PersonaPickerPresentation.PersistentPicker; - const [tab, setTab] = useState(tabProp); const [AddPersonaMenuAnchor, setAddPersonaMenuAnchor] = useState(anchor); - const [profiles, setProfiles] = useState(undefined); - const [selectedGlobalPersona, setSelectedGlobalPersona] = useState( - null - ); - const [selectedRoomPersona, setSelectedRoomPersona] = useState( + const activeTheme = useActiveTheme(); + const [profiles, setProfiles] = useState(undefined); + const [selectedGlobalPersona, setSelectedGlobalPersona] = + useState(null); + const [selectedRoomPersona, setSelectedRoomPersona] = useState( latchedPersona ?? null ); - const defactoPersona = () => selectedRoomPersona ?? selectedGlobalPersona; + const nameColor = useCallback( + (persona: PerMessageProfileMsc4461) => + activeTheme.kind === ThemeKind.Dark + ? persona['eu.she-a.color']?.on_dark + : persona['eu.she-a.color']?.on_light, + [activeTheme] + ); - const activeTheme = useActiveTheme(); + const defactoPersona = () => selectedRoomPersona ?? selectedGlobalPersona; useEffect(() => { const syncProfile = async () => { @@ -172,7 +176,7 @@ function PersonaPicker({ const filtered = term ? profiles?.filter((profile) => searchInputRef.current - ? profile.name.toLocaleLowerCase().includes(searchInputRef.current?.value) || + ? profile.displayname.toLocaleLowerCase().includes(searchInputRef.current?.value) || profile.id.toLocaleLowerCase().includes(searchInputRef.current?.value) : true ) @@ -182,13 +186,8 @@ function PersonaPicker({ }, [profiles] ); - const nameColor = useCallback( - (persona: PerMessageProfile) => - activeTheme.kind === ThemeKind.Dark ? persona.colors?.on_dark : persona.colors?.on_light, - [activeTheme] - ); - const isSelected = (persona: PerMessageProfile | undefined) => { + const isSelected = (persona: PerMessageProfileMsc4461 | undefined) => { if (!persona) return undefined; const selected = tab === PersonaPickerTab.Global ? selectedGlobalPersona : selectedRoomPersona; return persona.id === selected?.id ? true : undefined; @@ -201,9 +200,9 @@ function PersonaPicker({ }, [mx]); const avatarUrl = useCallback( - (profile: PerMessageProfile) => { - if (profile.avatarUrl !== undefined) { - return mxcUrlToHttp(mx, profile.avatarUrl, useAuthentication, 96, 96, 'crop') ?? undefined; + (profile: PerMessageProfileMsc4461) => { + if (profile.avatar_url !== undefined) { + return mxcUrlToHttp(mx, profile.avatar_url, useAuthentication, 96, 96, 'crop') ?? undefined; } else { return undefined; } @@ -212,7 +211,7 @@ function PersonaPicker({ ); const handleSelect = useCallback( - async (profile: PerMessageProfile | undefined) => { + async (profile: PerMessageProfileMsc4461 | undefined) => { if (onPersonaSelect) { onPersonaSelect(profile); return; @@ -320,10 +319,10 @@ function PersonaPicker({ ( - {nameInitials(profile.name)} + {nameInitials(profile.displayname)} )} alt={`Avatar for profile ${profile.id}`} @@ -335,7 +334,7 @@ function PersonaPicker({ truncate style={{ color: nameColor(profile) ?? undefined, maxWidth: toRem(150) }} > - {profile.name} + {profile.displayname} ))} @@ -422,7 +421,7 @@ function PersonaPicker({ src={avatarUrl(defactoPersona()!)} renderFallback={() => ( - {nameInitials(defactoPersona()!.name)} + {nameInitials(defactoPersona()!.displayname)} )} alt={`Avatar for profile ${defactoPersona()!.id}`} diff --git a/src/app/features/settings/Persona/PerMessageProfileEditor.tsx b/src/app/features/settings/Persona/PerMessageProfileEditor.tsx index 5463cdcb3..9677ec821 100644 --- a/src/app/features/settings/Persona/PerMessageProfileEditor.tsx +++ b/src/app/features/settings/Persona/PerMessageProfileEditor.tsx @@ -1,4 +1,5 @@ import { SequenceCard, SequenceCardStyle } from '$components/sequence-card'; +import { nanoid } from 'nanoid'; import { Box, Button, Text, Avatar, config, IconButton, Input, toRem, Spinner, color } from 'folds'; import { menuIcon, Trash, X } from '$components/icons/phosphor'; import type { MatrixClient } from '$types/matrix-sdk'; @@ -11,67 +12,60 @@ import { useObjectURL } from '$hooks/useObjectURL'; import { createUploadAtom } from '$state/upload'; import { UserAvatar } from '$components/user-avatar'; import { CompactUploadCardRenderer } from '$components/upload-card'; +import type { ProfileTrigger } from '$hooks/usePerMessageProfile'; import { addOrUpdatePerMessageProfile, - associateProxyWithProfile, - createProxyKey, deletePerMessageProfile, - dropProxyAssociationForPMP, - getAllPerMessageProfileProxies, - getAllProxiesForPMP, - getPerMessageProfileById, - type PerMessageProfileProxyAssociationV2, renamePerMessageProfile, } from '$hooks/usePerMessageProfile'; import type { PronounSet } from '$utils/pronouns'; import { parsePronounsStringToPronounsSetArray } from '$utils/pronouns'; -import { generateShortId } from '$utils/shortIdGen'; import { SettingTile } from '$components/setting-tile'; -import { type AsyncState, AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; +import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import { NameColorEditor } from '../account/NameColorEditor'; +import { + MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_CIRCUMFIX_PROPERTY_NAME, + MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_SUFFIX_PROPERTY_NAME, + MATRIX_UNSTABLE_COLORS, + MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME, +} from '$unstable/prefixes'; -const constructProxyString = (s: Shorthand) => { - return `${s.prefix ?? ''}text${s.suffix ?? ''}`; -}; +type Shorthand = { prefix?: string; suffix?: string }; +type ShorthandRow = Shorthand & { id: string }; -type Shorthand = { id: string; prefix?: string; suffix?: string }; -type ShorthandRow = Shorthand & { rowId: string }; - -type ShorthandListItemProps = Shorthand & { +type ShorthandListItemProps = ShorthandRow & { onDelete: (shorthandId: string) => void; - onSave: (shorthandId: string, shorthand: Shorthand) => void; - deleteState: AsyncState; - saveState: AsyncState; + onChange: (shorthandId: string, shorthand: Shorthand) => void; }; -function ShorthandListItem({ - id, - prefix, - suffix, - onDelete, - onSave, - deleteState, - saveState, -}: ShorthandListItemProps) { - const [currentPrefix] = useState(prefix); - const [currentSuffix] = useState(suffix); +function ShorthandListItem({ id, prefix, suffix, onDelete, onChange }: ShorthandListItemProps) { const [newPrefix, setNewPrefix] = useState(prefix); const [newSuffix, setNewSuffix] = useState(suffix); const [prefixWarn, setPrefixWarn] = useState(false); const [suffixWarn, setSuffixWarn] = useState(false); - const handlePrefixChange = useCallback((e: React.ChangeEvent) => { - setNewPrefix(e.target.value); - }, []); - const handleSuffixChange = useCallback((e: React.ChangeEvent) => { - setNewSuffix(e.target.value); - }, []); - - const hasChanges = useMemo( - () => - (newPrefix ?? '') !== (currentPrefix ?? '') || (newSuffix ?? '') !== (currentSuffix ?? ''), - [newPrefix, newSuffix, currentPrefix, currentSuffix] + const handlePrefixChange = useCallback( + (e: React.ChangeEvent) => { + onChange(id, { + prefix: e.target.value.trimStart(), + suffix: newSuffix?.trimEnd(), + }); + setNewPrefix(e.target.value); + }, + [newSuffix, id, onChange] ); + const handleSuffixChange = useCallback( + (e: React.ChangeEvent) => { + // if you call setNewSuffix then use newSuffix you get race conditioned lol + onChange(id, { + prefix: newPrefix?.trimStart(), + suffix: e.target.value.trimEnd(), + }); + setNewSuffix(e.target.value); + }, + [newPrefix, id, onChange] + ); + const isBlank = useMemo(() => !newPrefix && !newSuffix, [newPrefix, newSuffix]); useEffect(() => { @@ -79,13 +73,6 @@ function ShorthandListItem({ setSuffixWarn((newSuffix ?? '').startsWith(' ')); }, [newPrefix, newSuffix]); - const handleSave = () => - onSave(id, { - id: createProxyKey(newPrefix, newSuffix), - prefix: newPrefix?.trimStart(), - suffix: newSuffix?.trimEnd(), - }); - return ( - {deleteState.status === AsyncStatus.Loading ? ( - - ) : ( - menuIcon(Trash) - )} - - @@ -167,154 +134,51 @@ function ShorthandListItem({ ); } -type ShorthandEditorProps = { - mx: MatrixClient; - profileId: string; -}; -function ShorthandEditor({ mx, profileId }: ShorthandEditorProps) { - const [shorthands, setShorthands] = useState(); - - const containsBlankShorthand = useMemo( - () => shorthands && shorthands.some((shorthand) => !shorthand.prefix && !shorthand.suffix), - [shorthands] - ); - - const handleAddShorthand = () => { - if (shorthands !== undefined) { - setShorthands([...shorthands, { id: 'blank', rowId: generateShortId(16) }]); +function triggersToShorthandRows(trigger: ProfileTrigger): ShorthandRow[] { + const prefixes: ShorthandRow[] = trigger.prefix.map((str) => { + return { prefix: str, id: nanoid() }; + }); + const suffixes: ShorthandRow[] | undefined = trigger['net.f0rest.suffix']?.map((str) => { + return { suffix: str, id: nanoid() }; + }); + const circumfixes: ShorthandRow[] | undefined = trigger['net.f0rest.circumfix']?.map( + ({ prefix, suffix }) => { + return { prefix: prefix, suffix: suffix, id: nanoid() }; } - }; - - const [deleteShorthandState, handleDeleteShorthand] = useAsyncCallback( - useCallback( - async (id: string) => { - if (shorthands === undefined) return; - - const shorthandToDelete = shorthands.find((shorthand) => shorthand.id === id); - if (!shorthandToDelete) return; - - const proxy = constructProxyString(shorthandToDelete); - - await dropProxyAssociationForPMP(mx, proxy); - - setShorthands((s) => s?.filter((shorthand) => shorthand.id !== id)); - }, - [mx, shorthands] - ) ); - const [saveShorthandState, handleSaveShorthand] = useAsyncCallback< - void, - Error, - [string, Shorthand] - >( - useCallback( - async (oldId: string, shorthand: Shorthand) => { - if (shorthands === undefined) return; - - const shorthandAssociation = (await getAllPerMessageProfileProxies(mx)).find( - (association) => createProxyKey(association.prefix, association.suffix) === shorthand.id - ); - const shorthandAssociatedProfile = shorthandAssociation - ? await getPerMessageProfileById(mx, shorthandAssociation.profileId) - : undefined; - if (shorthandAssociatedProfile) { - throw new Error( - `Shorthand is already associated with profile ${shorthandAssociatedProfile.name} (${shorthandAssociatedProfile.id})` - ); - } - - if (oldId !== 'blank') { - await dropProxyAssociationForPMP(mx, oldId); - } - await associateProxyWithProfile(mx, profileId, shorthand.prefix, shorthand.suffix, false); - - setShorthands((currentShorthands) => { - if (currentShorthands === undefined) return currentShorthands; - - const oldShorthandIdx = currentShorthands.findIndex((s) => s.id === oldId); - if (oldShorthandIdx < 0) return currentShorthands; - const oldShorthand = currentShorthands[oldShorthandIdx]; - if (oldShorthand === undefined) return currentShorthands; - - return currentShorthands.with(oldShorthandIdx, { - ...shorthand, - rowId: oldShorthand.rowId, - }); - }); - }, - [mx, shorthands, profileId] - ) - ); - - useEffect(() => { - const fetchShorthands = async () => { - const fetchedShorthands: PerMessageProfileProxyAssociationV2[] = await getAllProxiesForPMP( - mx, - profileId - ); - const enumeratedShorthands: ShorthandRow[] = fetchedShorthands.map((v) => { - return { id: createProxyKey(v.prefix, v.suffix), rowId: generateShortId(16), ...v }; - }); - setShorthands(enumeratedShorthands); - }; - fetchShorthands(); - }, [mx, profileId]); - - return ( - <> - - - {saveShorthandState.status === AsyncStatus.Error && ( - - {saveShorthandState.error.toString()} - - )} - {shorthands === undefined ? ( - - ) : ( - shorthands.map((shorthand: ShorthandRow) => ( - - )) - )} - - - - - ); + return prefixes.concat(suffixes ?? [], circumfixes ?? []); } +function shorthandRowsToTriggers(rows: ShorthandRow[]): ProfileTrigger { + const prefix: string[] = []; + const suffix: string[] = []; + const circumfix: { prefix: string; suffix: string }[] = []; + + rows.forEach((row) => { + if (row.prefix && row.suffix) { + circumfix.push({ prefix: row.prefix, suffix: row.suffix }); + } else if (row.prefix) { + prefix.push(row.prefix); + } else if (row.suffix) { + suffix.push(row.suffix); + } + }); + + return { + prefix, + ...(suffix.length > 0 + ? { [MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_SUFFIX_PROPERTY_NAME]: suffix } + : {}), + ...(circumfix.length > 0 + ? { [MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_CIRCUMFIX_PROPERTY_NAME]: circumfix } + : {}), + }; +} /** * the props we use for the per-message profile editor, which is used to edit a per-message profile. This is used in the settings page when the user wants to edit a profile. */ -type PerMessageProfileEditorProps = { +export type PerMessageProfileEditorProps = { mx: MatrixClient; profileId: string; avatarMxcUrl?: string; @@ -322,7 +186,7 @@ type PerMessageProfileEditorProps = { pronouns?: PronounSet[]; nameColorLightTheme?: string; nameColorDarkTheme?: string; - shorthands?: Shorthand[]; + shorthands?: ProfileTrigger; onDelete?: (profileId: string) => void; }; @@ -334,6 +198,7 @@ export function PerMessageProfileEditor({ pronouns = Array(), nameColorLightTheme, nameColorDarkTheme, + shorthands, onDelete, }: Readonly) { const useAuthentication = useMediaAuthentication(); @@ -364,6 +229,44 @@ export function PerMessageProfileEditor({ const [currentNameColorDark, setCurrentNameColorDark] = useState(nameColorDarkTheme ?? null); const [newNameColorDark, setNewNameColorDark] = useState(nameColorDarkTheme ?? null); + // shorthands + const shorthandProp = shorthands ? triggersToShorthandRows(shorthands) : undefined; + const [currentShorthands, setCurrentShorthands] = useState( + shorthandProp + ); + const [newShorthands, setNewShorthands] = useState(shorthandProp); + + const containsBlankShorthand = useMemo( + () => + newShorthands && newShorthands.some((shorthand) => !shorthand.prefix && !shorthand.suffix), + [newShorthands] + ); + + const handleAddShorthand = () => { + if (newShorthands !== undefined) { + setNewShorthands([...newShorthands, { id: nanoid() }]); + } + }; + + const handleDeleteShorthand = (id: string) => { + if (newShorthands === undefined) return; + setNewShorthands((s) => s?.filter((shorthand) => shorthand.id !== id)); + }; + + const handleSaveShorthand = (oldId: string, shorthand: Shorthand) => { + setNewShorthands((rows = []) => { + const index = rows.findIndex((row) => row.id === oldId); + if (index === -1) return rows; + const oldShorthand = rows[index]; + if (oldShorthand === undefined) return rows; + + return rows.with(index, { + ...shorthand, + id: oldShorthand.id, + }); + }); + }; + const [newDisplayName, setNewDisplayName] = useState(currentDisplayName); const [imageFile, setImageFile] = useState(); const [imageHasChanges, setImageHasChanges] = useState(false); @@ -409,6 +312,7 @@ export function PerMessageProfileEditor({ newPronounsString !== currentPronounsString || newNameColorLight !== currentNameColorLight || newNameColorDark !== currentNameColorDark || + newShorthands !== currentShorthands || hasIdChange || imageHasChanges, [ @@ -420,6 +324,8 @@ export function PerMessageProfileEditor({ currentNameColorLight, newNameColorDark, currentNameColorDark, + newShorthands, + currentShorthands, hasIdChange, imageHasChanges, ] @@ -447,10 +353,11 @@ export function PerMessageProfileEditor({ useCallback(async () => { await addOrUpdatePerMessageProfile(mx, { id: profileId, - name: newDisplayName, - avatarUrl: avatarMxc, - pronouns: newPronouns, - colors: { + displayname: newDisplayName, + avatar_url: avatarMxc, + [MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME]: newPronouns, + trigger: shorthandRowsToTriggers(newShorthands ?? []), + [MATRIX_UNSTABLE_COLORS]: { on_light: newNameColorLight ?? undefined, on_dark: newNameColorDark ?? undefined, }, @@ -460,6 +367,7 @@ export function PerMessageProfileEditor({ setCurrentPronouns(newPronouns); setCurrentNameColorLight(newNameColorLight); setCurrentNameColorDark(newNameColorDark); + setCurrentShorthands(newShorthands); setImageHasChanges(false); setChangingDisplayName(false); setDisableSetDisplayname(false); @@ -476,6 +384,7 @@ export function PerMessageProfileEditor({ newPronouns, newNameColorLight, newNameColorDark, + newShorthands, hasIdChange, newId, ]) @@ -753,7 +662,43 @@ export function PerMessageProfileEditor({ Shorthands - + + + {newShorthands === undefined ? ( + + ) : ( + newShorthands.map((shorthand: ShorthandRow) => ( + + )) + )} + + + ); } diff --git a/src/app/features/settings/Persona/PerMessageProfileEditorView.tsx b/src/app/features/settings/Persona/PerMessageProfileEditorView.tsx index 9ef6c505b..623b5dabe 100644 --- a/src/app/features/settings/Persona/PerMessageProfileEditorView.tsx +++ b/src/app/features/settings/Persona/PerMessageProfileEditorView.tsx @@ -1,32 +1,13 @@ import { Box, IconButton, Text, Scroll, Chip } from 'folds'; import { ArrowLeft, composerIcon, sizedIcon, X } from '$components/icons/phosphor'; import { Page, PageHeader, PageContent } from '$components/page'; -import type { MatrixClient } from 'matrix-js-sdk'; -import type { PronounSet } from '$utils/pronouns'; +import type { PerMessageProfileEditorProps } from './PerMessageProfileEditor'; import { PerMessageProfileEditor } from './PerMessageProfileEditor'; -type PerMessageProfileEditorViewProps = { - mx: MatrixClient; - profileId: string; - avatarMxcUrl?: string; - displayName?: string; - pronouns?: PronounSet[]; - nameColorLightTheme?: string; - nameColorDarkTheme?: string; - onChange?: (profile: { id: string; name: string; avatarUrl?: string }) => void; - onDelete?: (profileId: string) => void; - requestClose: () => void; -}; export function PerMessageProfileEditorView({ - mx, - profileId, - avatarMxcUrl, - displayName, - pronouns = Array(), - nameColorLightTheme, - nameColorDarkTheme, requestClose, -}: Readonly) { + ...editorProps +}: Readonly void }>) { return ( @@ -51,16 +32,7 @@ export function PerMessageProfileEditorView({ - + diff --git a/src/app/features/settings/Persona/PerMessageProfileOverview.tsx b/src/app/features/settings/Persona/PerMessageProfileOverview.tsx index 2ab2b53d3..5f329b7a5 100644 --- a/src/app/features/settings/Persona/PerMessageProfileOverview.tsx +++ b/src/app/features/settings/Persona/PerMessageProfileOverview.tsx @@ -1,5 +1,5 @@ import { useMatrixClient } from '$hooks/useMatrixClient'; -import type { PerMessageProfile } from '$hooks/usePerMessageProfile'; +import type { PerMessageProfileMsc4461 } from '$hooks/usePerMessageProfile'; import { addOrUpdatePerMessageProfile, getAllPerMessageProfiles, @@ -12,10 +12,14 @@ import { SequenceCard, SequenceCardStyle } from '$components/sequence-card'; import { PerMessageProfileListItem } from './PerMessageProfileListItem'; import { SettingTile } from '$components/setting-tile'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; +import { + MATRIX_UNSTABLE_COLORS, + MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME, +} from '$unstable/prefixes'; type PerMessageProfileOverviewProps = { - onCreateProfile: (profile: PerMessageProfile) => void; - onEditProfile: (profile: PerMessageProfile) => void; + onCreateProfile: (profile: PerMessageProfileMsc4461) => void; + onEditProfile: (profile: PerMessageProfileMsc4461) => void; }; /** * Renders a list of per-message profiles along with an editor. @@ -26,7 +30,7 @@ export function PerMessageProfileOverview({ onEditProfile, }: PerMessageProfileOverviewProps) { const mx = useMatrixClient(); - const [profiles, setProfiles] = useState([]); + const [profiles, setProfiles] = useState([]); useEffect(() => { const fetchProfiles = async () => { @@ -43,9 +47,10 @@ export function PerMessageProfileOverview({ const [addState, handleAdd] = useAsyncCallback( useCallback(async () => { - const newProfile: PerMessageProfile = { + const newProfile: PerMessageProfileMsc4461 = { id: generateShortId(5), - name: 'New Profile', + displayname: 'New Profile', + trigger: { prefix: [] }, }; await addOrUpdatePerMessageProfile(mx, newProfile); onCreateProfile(newProfile); @@ -92,12 +97,12 @@ export function PerMessageProfileOverview({ > diff --git a/src/app/features/settings/Persona/ProfilesPage.tsx b/src/app/features/settings/Persona/ProfilesPage.tsx index 0b47aebf3..60512ac98 100644 --- a/src/app/features/settings/Persona/ProfilesPage.tsx +++ b/src/app/features/settings/Persona/ProfilesPage.tsx @@ -3,7 +3,7 @@ import { Box, Scroll } from 'folds'; import { PerMessageProfileOverview } from './PerMessageProfileOverview'; import { PKCompatSettings } from './PKCompat'; import { PickerPageSettings } from './PickerPage'; -import type { PerMessageProfile } from '$hooks/usePerMessageProfile'; +import type { PerMessageProfileMsc4461 } from '$hooks/usePerMessageProfile'; import { useState } from 'react'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { PerMessageProfileEditorView } from './PerMessageProfileEditorView'; @@ -15,7 +15,7 @@ type PerMessageProfilePageProps = { export function PerMessageProfilePage({ requestBack, requestClose }: PerMessageProfilePageProps) { const mx = useMatrixClient(); - const [editingProfile, setEditingProfile] = useState(); + const [editingProfile, setEditingProfile] = useState(); const handleEditorClose = () => { setEditingProfile(undefined); @@ -26,11 +26,12 @@ export function PerMessageProfilePage({ requestBack, requestClose }: PerMessageP ); diff --git a/src/app/hooks/commands/pmp.ts b/src/app/hooks/commands/pmp.ts index 21a1f6d54..7af7046df 100644 --- a/src/app/hooks/commands/pmp.ts +++ b/src/app/hooks/commands/pmp.ts @@ -1,6 +1,6 @@ import { splitWithSpace } from '$utils/common'; import { sendFeedback } from '$utils/sendFeedbackToUser'; -import type { PerMessageProfile } from '../usePerMessageProfile'; +import type { PerMessageProfileMsc4461 } from '../usePerMessageProfile'; import { addOrUpdatePerMessageProfile, deletePerMessageProfile, @@ -26,19 +26,20 @@ export const createPmpCommands = (ctx: CommandContext): Partial = sendFeedback(`invalid payload`, room, mx.getSafeUserId()); return; } - const avatarUrl: string | undefined = args[5]; + const avatar_url: string | undefined = args[5]; const name: string | undefined = args[3]; const profileId = args[1]; - if (!avatarUrl || !name || !profileId) { + if (!avatar_url || !name || !profileId) { sendFeedback(`invalid payload`, room, mx.getSafeUserId()); return; } - const pmp: PerMessageProfile = { + const pmp: PerMessageProfileMsc4461 = { id: profileId, - name: name || '', - avatarUrl, + displayname: name || '', + avatar_url, + trigger: { prefix: [] }, }; await addOrUpdatePerMessageProfile(mx, pmp) .then(() => { diff --git a/src/app/hooks/usePerMessageProfile.ts b/src/app/hooks/usePerMessageProfile.ts index 3b18de237..07a4ce53b 100644 --- a/src/app/hooks/usePerMessageProfile.ts +++ b/src/app/hooks/usePerMessageProfile.ts @@ -3,16 +3,22 @@ import type { AccountDataCompatVersion } from '$types/matrix/accountData'; import type { PronounSet } from '$utils/pronouns'; import type { MatrixClient } from '$types/matrix-sdk'; import { CustomAccountDataEvent } from '$types/matrix/accountData'; -import { MATRIX_UNSTABLE_COLORS } from '$unstable/prefixes'; -import { MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME } from '$unstable/prefixes'; import type { ColorSet } from './useUserProfile'; +import { MATRIX_UNSTABLE_COLORS } from '$unstable/prefixes'; +import { + MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_CIRCUMFIX_PROPERTY_NAME, + MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_SUFFIX_PROPERTY_NAME, + MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME, + MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME, +} from '$unstable/prefixes'; const ACCOUNT_DATA_PREFIX = CustomAccountDataEvent.SablePerProfileMessageProfiles; /** + * @deprecated in favour if {@link PerMessageProfileMsc4461} * a per message profile */ -export type PerMessageProfile = { +type PerMessageProfile = { /** * a unique id for this profile, can be generated using something like nanoid. * This is used to identify the profile when applying it to a message, and also used as the key when storing the profile in account data. @@ -36,6 +42,116 @@ export type PerMessageProfile = { colors?: ColorSet; }; +export type ProfileTrigger = { + prefix: string[]; + [MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_SUFFIX_PROPERTY_NAME]?: string[]; + [MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_CIRCUMFIX_PROPERTY_NAME]?: { + prefix: string; + suffix: string; + }[]; +}; + +/** + * a per message profile + */ +export type PerMessageProfileIndexMsc4461 = { + type: 'm.per_message_profiles'; + content: { + profiles: PerMessageProfileMsc4461[]; + }; +}; + +/** + * a per message profile + */ +export type PerMessageProfileMsc4461 = { + /** + * a unique id for this profile, can be generated using something like nanoid. + * This is used to identify the profile when applying it to a message, and also used as the key when storing the profile in account data. + */ + id: string; + /** + * the display name to use for messages using this profile. + * This is required because otherwise the profile would have no effect on the message. + */ + displayname: string; + /** + * the avatar url to use for messages using this profile. + */ + avatar_url?: string; + /** + * a per message profile can also include pronouns + * @see PronounSet for the format of the pronouns, and how to parse them from a string input + */ + [MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME]?: PronounSet[]; + + /** + * following spec MSC4522 + */ + [MATRIX_UNSTABLE_COLORS]?: ColorSet; + + trigger: ProfileTrigger; + + compat?: AccountDataCompatVersion; +}; + +export function convertPmpToMsc4461( + mx: MatrixClient, + profile: PerMessageProfile +): PerMessageProfileMsc4461 { + const triggers: ProfileTrigger = { + prefix: [], + [MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_SUFFIX_PROPERTY_NAME]: [], + [MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_CIRCUMFIX_PROPERTY_NAME]: [], + }; + + // lookup old proxyAssociations + getProxyAssociationMap( + mx + .getAccountData( + `${ACCOUNT_DATA_PREFIX}.proxyassociation` as Parameters[0] + ) + ?.getContent() + /* oxlint-disable no-unused-vars */ + ) + .entries() + .filter(([_k, assoc]) => assoc.profileId === profile.id) + .forEach(([k, assoc]) => { + const migratedAssoc = migratePmpProxyAssociation(k, assoc); + if (!migratedAssoc) return; + + if (migratedAssoc.prefix && !migratedAssoc.suffix) { + triggers.prefix.push(migratedAssoc.prefix); + } else if (!migratedAssoc.prefix && migratedAssoc.suffix) { + triggers[MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_SUFFIX_PROPERTY_NAME]!.push( + migratedAssoc.suffix + ); + } else if (migratedAssoc.prefix && migratedAssoc.suffix) { + triggers[MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_CIRCUMFIX_PROPERTY_NAME]!.push({ + prefix: migratedAssoc.prefix, + suffix: migratedAssoc.suffix, + }); + } + }); + + const newPmp: PerMessageProfileMsc4461 = { + id: profile.id, + displayname: profile.name, + avatar_url: profile.avatarUrl, + [MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME]: profile.pronouns, + [MATRIX_UNSTABLE_COLORS]: profile.colors, + trigger: triggers, + }; + + // delete empty fields + // to-do maybe find a better way of doing it + if (!profile.avatarUrl) delete newPmp.avatar_url; + if (!profile.pronouns || profile.pronouns?.length === 0) + delete newPmp[MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME]; + if (!profile.colors) delete newPmp[MATRIX_UNSTABLE_COLORS]; + return newPmp; +} + /** * the format used by Beeper for per message profiles * This is the format that Beeper expects when applying a profile to a message before sending it @@ -71,23 +187,28 @@ export type PerMessageProfileBeeperFormat = { * @return {*} {PerMessageProfileBeeperFormat} the per message profile in Beeper's format, which can be applied to a message before sending it */ export function convertPerMessageProfileToBeeperFormat( - profile: PerMessageProfile, + profile: PerMessageProfileMsc4461, has_fallback: boolean ): PerMessageProfileBeeperFormat { const beeperPMP: PerMessageProfileBeeperFormat = { id: profile.id, - displayname: profile.name, - avatar_url: profile.avatarUrl, - [MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME]: profile.pronouns, - [MATRIX_UNSTABLE_COLORS]: profile.colors, + displayname: profile.displayname, + avatar_url: profile.avatar_url, + [MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME]: + profile[MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME], + [MATRIX_UNSTABLE_COLORS]: profile[MATRIX_UNSTABLE_COLORS], has_fallback, }; // delete empty fields // to-do maybe find a better way of doing it - if (!profile.name || profile?.name.trim().length === 0) delete beeperPMP.displayname; - if (!profile.avatarUrl) delete beeperPMP.avatar_url; - if (!profile.pronouns || profile.pronouns?.length === 0) - delete beeperPMP[MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME]; + if (!profile.displayname || profile?.displayname.trim().length === 0) + delete beeperPMP.displayname; + if (!profile.avatar_url) delete beeperPMP.avatar_url; + if ( + !profile[MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME] || + profile[MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME]?.length === 0 + ) + if (!profile[MATRIX_UNSTABLE_COLORS]) delete beeperPMP[MATRIX_UNSTABLE_COLORS]; if (!has_fallback) delete beeperPMP.has_fallback; return beeperPMP; } @@ -102,13 +223,15 @@ export function convertPerMessageProfileToBeeperFormat( */ export function convertBeeperFormatToOurPerMessageProfile( beeperProfile: PerMessageProfileBeeperFormat -): PerMessageProfile { +): PerMessageProfileMsc4461 { return { id: beeperProfile.id, - name: beeperProfile.displayname ?? '', - avatarUrl: beeperProfile.avatar_url, - pronouns: beeperProfile[MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME], - colors: beeperProfile[MATRIX_UNSTABLE_COLORS], + displayname: beeperProfile.displayname ?? '', + avatar_url: beeperProfile.avatar_url, + [MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME]: + beeperProfile[MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME], + [MATRIX_UNSTABLE_COLORS]: beeperProfile[MATRIX_UNSTABLE_COLORS], + trigger: { prefix: [] }, }; } @@ -335,6 +458,31 @@ function proxyAssociationsMapToObject( } /** + * helper function: getting a profile from the account data where the profile matches a given id + * + * @export + * @param {MatrixClient} mx the matrix client + * @param {string} id the profile id + * @return {*} {(Promise)} the profile, with the profile Id, if it exists + */ +export async function getPerMessageProfileById( + mx: MatrixClient, + id: string +): Promise { + let index = mx.getAccountData( + MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME as Parameters< + typeof mx.getAccountData + >[0] + ); + + return index + ? (index.getContent() as PerMessageProfileIndexMsc4461).content.profiles.find((p) => p.id == id) + : undefined; +} + +/** + * @deprecated + * * getting a profile from the account data where the profile matches a given id * * @export @@ -342,7 +490,7 @@ function proxyAssociationsMapToObject( * @param {string} id the profile id * @return {*} {(Promise)} the profile, with the profile Id, if it exists */ -export async function getPerMessageProfileById( +async function getPerMessageProfileByIdDeprecated( mx: MatrixClient, id: string ): Promise { @@ -359,13 +507,56 @@ export async function getPerMessageProfileById( * @param {MatrixClient} mx the matrix client * @return {*} {Promise} a array containing all per-message-profiles saved */ -export async function getAllPerMessageProfiles(mx: MatrixClient): Promise { - const profileData = mx.getAccountData( - `${ACCOUNT_DATA_PREFIX}.index` as Parameters[0] +export async function getAllPerMessageProfiles( + mx: MatrixClient +): Promise { + let profileListIndex = mx.getAccountData( + MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME as Parameters< + typeof mx.getAccountData + >[0] ); - const profileIds = (profileData?.getContent() as PerMessageProfileIndex)?.profileIds || []; - const profiles = await Promise.all(profileIds.map((id) => getPerMessageProfileById(mx, id))); - return profiles.filter((profile): profile is PerMessageProfile => profile !== undefined); + + if (!profileListIndex) { + const profileData = mx.getAccountData( + `${ACCOUNT_DATA_PREFIX}.index` as Parameters[0] + ); + if (!profileData) return []; + + const msc4461Index: PerMessageProfileIndexMsc4461 = { + type: 'm.per_message_profiles', + content: { + profiles: [], + }, + }; + + const profileIds = (profileData?.getContent() as PerMessageProfileIndex)?.profileIds || []; + const profiles = await Promise.all( + profileIds.map((id) => getPerMessageProfileByIdDeprecated(mx, id)) + ); + + profiles.forEach((profile) => { + if (!profile) return; + + const migratedProfile = convertPmpToMsc4461(mx, profile); + msc4461Index.content.profiles.push(migratedProfile); + }); + + await mx.setAccountData( + MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME as Parameters< + typeof mx.setAccountData + >[0], + msc4461Index as Parameters[1] + ); + + profileListIndex = mx.getAccountData( + MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME as Parameters< + typeof mx.getAccountData + >[0] + ); + } + + if (!profileListIndex) return []; + return (profileListIndex.getContent() as PerMessageProfileIndexMsc4461).content.profiles; } /** @@ -374,34 +565,32 @@ export async function getAllPerMessageProfiles(mx: MatrixClient): Promise[0] +export async function addOrUpdatePerMessageProfile( + mx: MatrixClient, + profile: PerMessageProfileMsc4461 +) { + let profileListIndex = mx.getAccountData( + MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME as Parameters< + typeof mx.getAccountData + >[0] ); - const profileWithCompat = { - ...profile, - compat: { - version: 1, - compatDate: '2026-03-26', - } satisfies AccountDataCompatVersion, - } satisfies PerMessageProfile; - if (profileListIndex?.getContent()?.profileIds.includes(profile.id)) { - return await mx.setAccountData( - `${ACCOUNT_DATA_PREFIX}.${profile.id}` as Parameters[0], - profileWithCompat as Parameters[1] - ); + + const newIndex = (profileListIndex?.getContent() as + | PerMessageProfileIndexMsc4461 + | undefined) || { type: 'm.per_message_profiles', content: { profiles: [] } }; + + const foundProfile = newIndex.content.profiles.findIndex((p) => p.id === profile.id); + if (foundProfile !== -1) { + newIndex.content.profiles[foundProfile] = profile; + } else { + newIndex.content.profiles.push(profile); } - const newProfileIds = [...(profileListIndex?.getContent()?.profileIds || []), profile.id]; - return await Promise.all([ - mx.setAccountData( - `${ACCOUNT_DATA_PREFIX}.index` as Parameters[0], - { profileIds: newProfileIds } as Parameters[1] - ), - mx.setAccountData( - `${ACCOUNT_DATA_PREFIX}.${profile.id}` as Parameters[0], - profileWithCompat as Parameters[1] - ), - ]); + mx.setAccountData( + MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME as Parameters< + typeof mx.getAccountData + >[0], + newIndex as Parameters[1] + ); } /** @@ -508,93 +697,9 @@ export async function setCurrentlyUsedPerMessageProfileIdForAccount( ); } -/** - * - * @param mx the matrix client - * @param profileId the profile id which the prefix should be attached to - * @param proxy the prefix to use as index - * @param proxyRegExp the regex we can use to match the prefix - * @param reset wheather to delete the prefix +/* + * @deprecated in favor of Msc4461 format triggers */ -export async function associateProxyWithProfile( - mx: MatrixClient, - profileId: string | undefined, - prefix: string | undefined, - suffix: string | undefined, - reset: boolean -) { - if (!(prefix || suffix)) throw new Error('Proxy must have either a prefix, suffix, or both.'); - - const associations = getProxyAssociationMap( - mx - .getAccountData( - `${ACCOUNT_DATA_PREFIX}.proxyassociation` as Parameters[0] - ) - ?.getContent() - ); - - const proxy = createProxyKey(prefix, suffix); - - if (reset) associations.delete(proxy); - - if (!profileId) throw new Error('profileId might not be undefined'); - if (profileId) - associations.set(proxy, { - profileId, - prefix, - suffix, - } satisfies PerMessageProfileProxyAssociationV2); - await mx.setAccountData( - `${ACCOUNT_DATA_PREFIX}.proxyassociation` as Parameters[0], - { associations: proxyAssociationsMapToObject(associations) } as Parameters< - typeof mx.setAccountData - >[1] - ); -} - -/** - * - * - * @export - * @param {MatrixClient} mx the matrix client - * @return {*} {Promise} - */ -export async function getAllPerMessageProfileProxies( - mx: MatrixClient -): Promise { - const cont: PerMessageProfileProxyAssociationWrapper | undefined = mx - .getAccountData( - `${ACCOUNT_DATA_PREFIX}.proxyassociation` as Parameters[0] - ) - ?.getContent(); - if (!cont) return []; - const pmap = getProxyAssociationMap(cont); - const parr = new Array(); - let needsMigration = false; - pmap.entries().forEach(([k, v]) => { - if (proxyNeedsMigration(v)) { - needsMigration = true; - v = migratePmpProxyAssociation(k, v) ?? v; - } - return parr.push(v as PerMessageProfileProxyAssociationV2); - }); - - if (needsMigration) { - const newPmap = new Map( - pmap.entries().map(([k, v]) => [k, migratePmpProxyAssociation(k, v) ?? v]) - ); - - await mx.setAccountData( - `${ACCOUNT_DATA_PREFIX}.proxyassociation` as Parameters[0], - { associations: proxyAssociationsMapToObject(newPmap) } as Parameters< - typeof mx.setAccountData - >[1] - ); - } - - return parr; -} - export async function getAllProxiesForPMP( mx: MatrixClient, profileId: string @@ -616,24 +721,6 @@ export async function getAllProxiesForPMP( return parr; } -export async function dropProxyAssociationForPMP(mx: MatrixClient, proxy: string) { - const associations = getProxyAssociationMap( - mx - .getAccountData( - `${ACCOUNT_DATA_PREFIX}.proxyassociation` as Parameters[0] - ) - ?.getContent() - ); - if (!associations) return; - associations.delete(proxy); - await mx.setAccountData( - `${ACCOUNT_DATA_PREFIX}.proxyassociation` as Parameters[0], - { associations: proxyAssociationsMapToObject(associations) } as Parameters< - typeof mx.setAccountData - >[1] - ); -} - /** * * drops all room associations for a profile, used when deleting a profile to make sure there are no dangling associations left that point to a non existing profile, which could cause issues when trying to apply the profile to a message in a room that still has an association for the deleted profile. @@ -701,7 +788,7 @@ export async function renamePerMessageProfile(mx: MatrixClient, oldId: string, n export async function getCurrentlyUsedPerMessageProfileForRoom( mx: MatrixClient, roomId: string -): Promise { +): Promise { const accountData = mx.getAccountData( `${ACCOUNT_DATA_PREFIX}.roomassociation` as Parameters[0] ); @@ -717,7 +804,7 @@ export async function getCurrentlyUsedPerMessageProfileForRoom( */ export async function getCurrentlyUsedPerMessageProfileForAccount( mx: MatrixClient -): Promise { +): Promise { const accountData = mx.getAccountData( `${ACCOUNT_DATA_PREFIX}.globalassociation` as Parameters[0] ); diff --git a/src/app/plugins/pluralkit-handler/PKitCommandMessageHandler.ts b/src/app/plugins/pluralkit-handler/PKitCommandMessageHandler.ts index 0eeb69132..8315448bb 100644 --- a/src/app/plugins/pluralkit-handler/PKitCommandMessageHandler.ts +++ b/src/app/plugins/pluralkit-handler/PKitCommandMessageHandler.ts @@ -1,11 +1,10 @@ import type { - PerMessageProfile, + PerMessageProfileMsc4461, PerMessageProfileProxyAssociationV2, + ProfileTrigger, } from '$hooks/usePerMessageProfile'; import { addOrUpdatePerMessageProfile, - associateProxyWithProfile, - dropProxyAssociationForPMP, extractCircumfixProxyTagsFromKey, getAllPerMessageProfiles, getPerMessageProfileById, @@ -13,6 +12,10 @@ import { import { sendFeedback } from '$utils/sendFeedbackToUser'; import type { MatrixClient, Room } from '$types/matrix-sdk'; import { generateShortId } from '$utils/shortIdGen'; +import { + MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_CIRCUMFIX_PROPERTY_NAME, + MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_SUFFIX_PROPERTY_NAME, +} from '$unstable/prefixes'; const pkMemberRenameRegex = /^(pk;member)\s+"?([\w\s]+)"?\s*rename\s+"?([\w\s]+)"?$/; const pkMemberNewRegex = /^(pk;member)\s+new\s+"?([\w\s]+)"?$/; @@ -47,6 +50,27 @@ export function buildProxyRegex({ prefix, suffix }: PerMessageProfileProxyAssoci return new RegExp(`^${pattern}$`); } +export function testTriggers(triggers: ProfileTrigger, input: string): boolean { + const matchesPrefix = triggers.prefix.some((prefix) => input.startsWith(prefix)); + if (matchesPrefix) return true; + + const matchesSuffix = triggers[MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_SUFFIX_PROPERTY_NAME]?.some( + (suffix) => input.startsWith(suffix) + ); + if (matchesSuffix) return true; + + const matchesCircumfix = triggers[ + MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_CIRCUMFIX_PROPERTY_NAME + ]?.some(({ prefix, suffix }) => { + const casePrefix = prefix ? input.startsWith(prefix) : true; + const caseSuffix = suffix ? input.endsWith(suffix) : true; + + return casePrefix && caseSuffix; + }); + + return !!matchesCircumfix; +} + export function testProxy( { prefix, suffix }: PerMessageProfileProxyAssociationV2, input: string @@ -56,8 +80,26 @@ export function testProxy( return matchesPrefix && matchesSuffix; } + +export function stripTrigger(triggers: ProfileTrigger, input: string): string { + const prefix = triggers.prefix.find((value) => input.startsWith(value)); + if (prefix !== undefined) return stripProxy({ prefix }, input); + + const suffix = triggers[MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_SUFFIX_PROPERTY_NAME]?.find( + (value) => input.endsWith(value) + ); + if (suffix !== undefined) return stripProxy({ suffix }, input); + + const circumfix = triggers[MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_CIRCUMFIX_PROPERTY_NAME]?.find( + (trigger) => input.startsWith(trigger.prefix) && input.endsWith(trigger.suffix) + ); + if (circumfix) return stripProxy(circumfix, input); + + return input; +} + export function stripProxy( - { prefix, suffix }: PerMessageProfileProxyAssociationV2, + { prefix, suffix }: { prefix?: string; suffix?: string }, input: string ): string { let message = input; @@ -128,7 +170,8 @@ export class PKitCommandMessageHandler { ); await addOrUpdatePerMessageProfile(this.mx, { id: generatedID, - name: memberName, + displayname: memberName, + trigger: { prefix: [] }, }); sendFeedback( `added new member has been created with id: ${generatedID} and name ${memberName}`, @@ -159,7 +202,7 @@ export class PKitCommandMessageHandler { * The id of the per-message-profile */ const pmpId = (await getAllPerMessageProfiles(this.mx)).find( - (pmp) => pmp.name === oldName + (pmp) => pmp.displayname === oldName )?.id; if (!pmpId) { sendFeedback( @@ -190,7 +233,7 @@ export class PKitCommandMessageHandler { ); return; } - pmp.name = newName; + pmp.displayname = newName; sendFeedback( `renaming your profile ${pmpId} from ${oldName} to ${newName}`, this.room, @@ -204,7 +247,7 @@ export class PKitCommandMessageHandler { const matchAgainst = cmdParts[3]; const pmpId = this.useIdInsteadOfNameWherePossible ? name - : (await getAllPerMessageProfiles(this.mx)).find((pmp) => pmp.name === name)?.id; + : (await getAllPerMessageProfiles(this.mx)).find((pmp) => pmp.displayname === name)?.id; if (!pmpId) { sendFeedback( `Persona with ${this.useIdInsteadOfNameWherePossible ? 'id' : 'name'} "${name}" doesn't exist in your records, ${helpTextPkMemberNew}`, @@ -222,13 +265,33 @@ export class PKitCommandMessageHandler { ); return; } - await dropProxyAssociationForPMP(this.mx, matchAgainst); + const proxyTags = extractCircumfixProxyTagsFromKey(matchAgainst); + const pmp = await getPerMessageProfileById(this.mx, pmpId); - sendFeedback( - `Persona with ${this.useIdInsteadOfNameWherePossible ? 'id' : 'name'} "${name}" (${pmpId}) is now no longer associated with ${matchAgainst}`, - this.room, - this.mx.getSafeUserId() - ); + if (pmp && proxyTags) { + const { prefix, suffix } = proxyTags; + + if (prefix && suffix) { + pmp.trigger[MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_CIRCUMFIX_PROPERTY_NAME] ??= []; + pmp.trigger[MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_CIRCUMFIX_PROPERTY_NAME] = pmp.trigger[ + MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_CIRCUMFIX_PROPERTY_NAME + ].filter((trigger) => trigger.prefix !== prefix && trigger.suffix !== suffix); + } else if (prefix && !suffix) { + pmp.trigger.prefix = pmp.trigger.prefix.filter((trigger) => trigger !== prefix); + } else if (!prefix && suffix) { + pmp.trigger[MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_SUFFIX_PROPERTY_NAME] ??= []; + pmp.trigger[MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_SUFFIX_PROPERTY_NAME] = pmp.trigger[ + MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_SUFFIX_PROPERTY_NAME + ].filter((trigger) => trigger !== suffix); + } + await addOrUpdatePerMessageProfile(this.mx, pmp); + + sendFeedback( + `Persona with ${this.useIdInsteadOfNameWherePossible ? 'id' : 'name'} "${name}" (${pmpId}) is now no longer associated with ${matchAgainst}`, + this.room, + this.mx.getSafeUserId() + ); + } } else if (pkMemberNewProxy.test(this.message)) { const cmdParts = pkMemberNewProxy.exec(this.message); if (!cmdParts) return; @@ -236,7 +299,7 @@ export class PKitCommandMessageHandler { const matchAgainst = cmdParts[4]; const pmpId = this.useIdInsteadOfNameWherePossible ? name - : (await getAllPerMessageProfiles(this.mx)).find((pmp) => pmp.name === name)?.id; + : (await getAllPerMessageProfiles(this.mx)).find((pmp) => pmp.displayname === name)?.id; if (!pmpId) { sendFeedback( `Persona with ${this.useIdInsteadOfNameWherePossible ? 'id' : 'name'} "${name}" doesn't exist in your records, ${helpTextPkMemberNew}`, @@ -263,17 +326,37 @@ export class PKitCommandMessageHandler { ); return; } - await associateProxyWithProfile(this.mx, pmpId, proxyTags.prefix, proxyTags.suffix, false); - sendFeedback( - `Persona with ${this.useIdInsteadOfNameWherePossible ? 'id' : 'name'} "${name}" (${pmpId}) is now associated with ${matchAgainst}`, - this.room, - this.mx.getSafeUserId() - ); + let pmp = await getPerMessageProfileById(this.mx, pmpId); + if (pmp) { + const { prefix, suffix } = proxyTags; + + if (prefix && suffix) { + (pmp.trigger[MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_CIRCUMFIX_PROPERTY_NAME] ??= []).push({ + prefix: prefix, + suffix: suffix, + }); + } else if (!prefix && suffix) { + (pmp.trigger[MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_SUFFIX_PROPERTY_NAME] ??= []).push( + suffix + ); + } else if (prefix && !suffix) { + pmp.trigger.prefix.push(prefix); + } + await addOrUpdatePerMessageProfile(this.mx, pmp); + sendFeedback( + `Persona with ${this.useIdInsteadOfNameWherePossible ? 'id' : 'name'} "${name}" (${pmpId}) is now associated with ${matchAgainst}`, + this.room, + this.mx.getSafeUserId() + ); + } } else { // default to looking up member info - const listOfProfiles: PerMessageProfile[] = await getAllPerMessageProfiles(this.mx); + const listOfProfiles: PerMessageProfileMsc4461[] = await getAllPerMessageProfiles(this.mx); const stringListOfProfiles: string = listOfProfiles - .map((pmp: PerMessageProfile) => `${pmp.id}: ${pmp.name ? pmp.name : '(empty name)'}`) + .map( + (pmp: PerMessageProfileMsc4461) => + `${pmp.id}: ${pmp.displayname ? pmp.displayname : '(empty name)'}` + ) .join('\n'); sendFeedback( `If you see this, you have messed up a command\n\nYou currently have the following persona set up:\n${stringListOfProfiles}\n\n${helpTextPkMember}`, diff --git a/src/app/plugins/pluralkit-handler/PKitProxyMessageHandler.test.ts b/src/app/plugins/pluralkit-handler/PKitProxyMessageHandler.test.ts index d3e5f4dc7..68f859b4c 100644 --- a/src/app/plugins/pluralkit-handler/PKitProxyMessageHandler.test.ts +++ b/src/app/plugins/pluralkit-handler/PKitProxyMessageHandler.test.ts @@ -6,7 +6,7 @@ import type { MatrixClient } from '$types/matrix-sdk'; // Mock the hook module that provides proxy associations + profile lookup vi.mock('$hooks/usePerMessageProfile', () => ({ - getAllPerMessageProfileProxies: vi.fn<() => Promise>(), + getAllPerMessageProfiles: vi.fn<() => Promise>(), getPerMessageProfileById: vi.fn<() => Promise>(), parsePerMessageProfileProxyAssociation: vi.fn<() => unknown>(), })); @@ -24,18 +24,36 @@ describe('PKitProxyMessageHandler', () => { }); it('matches a proxied message, returns pmp, and strips content', async () => { - (mocked.getAllPerMessageProfileProxies as unknown as Mock).mockResolvedValueOnce([ - { profileId: 'p1', prefix: '[', suffix: ']' }, + (mocked.getAllPerMessageProfiles as unknown as Mock).mockResolvedValueOnce([ + { + id: 'p1', + name: 'Test', + trigger: { + prefix: [], + 'net.f0rest.circumfix': [{ prefix: '[', suffix: ']' }], + }, + }, ]); (mocked.getPerMessageProfileById as unknown as Mock).mockResolvedValueOnce({ id: 'p1', name: 'Test', + trigger: { + prefix: [], + 'net.f0rest.circumfix': [{ prefix: '[', suffix: ']' }], + }, }); const handler = new PKitProxyMessageHandler({} as unknown as MatrixClient); const pmp = await handler.getPmpBasedOnMessage('[hello]'); - expect(pmp).toEqual({ id: 'p1', name: 'Test' }); + expect(pmp).toEqual({ + id: 'p1', + name: 'Test', + trigger: { + prefix: [], + 'net.f0rest.circumfix': [{ prefix: '[', suffix: ']' }], + }, + }); // getPmpBasedOnMessage refreshes/init() so we should be inited now expect(handler.isAProxiedMessage('[hello]')).toBe(true); diff --git a/src/app/plugins/pluralkit-handler/PKitProxyMessageHandler.ts b/src/app/plugins/pluralkit-handler/PKitProxyMessageHandler.ts index df6613e62..bfb3eaa65 100644 --- a/src/app/plugins/pluralkit-handler/PKitProxyMessageHandler.ts +++ b/src/app/plugins/pluralkit-handler/PKitProxyMessageHandler.ts @@ -1,13 +1,7 @@ -import type { - PerMessageProfile, - PerMessageProfileProxyAssociationV2, -} from '$hooks/usePerMessageProfile'; -import { - getAllPerMessageProfileProxies, - getPerMessageProfileById, -} from '$hooks/usePerMessageProfile'; +import type { PerMessageProfileMsc4461 } from '$hooks/usePerMessageProfile'; +import { getAllPerMessageProfiles, getPerMessageProfileById } from '$hooks/usePerMessageProfile'; import type { MatrixClient } from '$types/matrix-sdk'; -import { stripProxy, testProxy } from './PKitCommandMessageHandler'; +import { stripTrigger, testTriggers } from './PKitCommandMessageHandler'; /** * proxy message handler @@ -24,12 +18,12 @@ export class PKitProxyMessageHandler { private readonly mx: MatrixClient; /** - * a list of proxies; is not initialized in the constructor + * a list of profiles; is not initialized in the constructor * @private - * @type {PerMessageProfileProxyAssociation[]} + * @type {PerMessageProfileMsc4461[]} * @memberof PKitProxyMessageHandler */ - private proxiesAssocs: PerMessageProfileProxyAssociationV2[]; + private profiles: PerMessageProfileMsc4461[]; private succInit: boolean; @@ -39,7 +33,7 @@ export class PKitProxyMessageHandler { */ public constructor(mx: MatrixClient) { this.mx = mx; - this.proxiesAssocs = []; + this.profiles = []; this.succInit = false; } @@ -48,7 +42,7 @@ export class PKitProxyMessageHandler { */ public async init(): Promise { try { - this.proxiesAssocs = await getAllPerMessageProfileProxies(this.mx); + this.profiles = await getAllPerMessageProfiles(this.mx); this.succInit = true; } catch (err) { this.succInit = false; @@ -64,7 +58,7 @@ export class PKitProxyMessageHandler { */ public isAProxiedMessage(message: string): boolean { if (!this.succInit) return false; - return this.proxiesAssocs.some((assoc) => testProxy(assoc, message)); + return this.profiles.some((profile) => testTriggers(profile.trigger, message)); } /** @@ -72,11 +66,13 @@ export class PKitProxyMessageHandler { * @param message the message to look at * @returns the matching Per-Message-Profile, if any */ - public async getPmpBasedOnMessage(message: string): Promise { + public async getPmpBasedOnMessage( + message: string + ): Promise { // Always refresh so newly-added proxies apply immediately. await this.init(); // check if the message matches our formats - const profileId = this.proxiesAssocs.find((assoc) => testProxy(assoc, message))?.profileId; + const profileId = this.profiles.find((profile) => testTriggers(profile.trigger, message))?.id; if (!profileId) return undefined; return getPerMessageProfileById(this.mx, profileId); } @@ -91,8 +87,8 @@ export class PKitProxyMessageHandler { public stripProxyFromMessage(message: string): string | undefined { if (!this.succInit) return undefined; let m; - this.proxiesAssocs.forEach((assoc) => { - if (testProxy(assoc, message)) m = stripProxy(assoc, message); + this.profiles.forEach((profile) => { + if (testTriggers(profile.trigger, message)) m = stripTrigger(profile.trigger, message); }); return m; } diff --git a/src/unstable/prefixes/msc/profile.ts b/src/unstable/prefixes/msc/profile.ts index b7b969893..94da45319 100644 --- a/src/unstable/prefixes/msc/profile.ts +++ b/src/unstable/prefixes/msc/profile.ts @@ -24,5 +24,7 @@ export const MATRIX_UNSTABLE_MSC4466_PROPAGATE_TO = 'computer.gingershaped.msc44 /** * Unstable prefix for username colors. defined in https://github.com/matrix-org/matrix-spec-proposals/pull/4522 */ - export const MATRIX_UNSTABLE_COLORS = 'eu.she-a.color'; + +export const MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_SUFFIX_PROPERTY_NAME = 'net.f0rest.suffix'; +export const MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_CIRCUMFIX_PROPERTY_NAME = 'net.f0rest.circumfix'; diff --git a/src/unstable/prefixes/sable/accountdata.ts b/src/unstable/prefixes/sable/accountdata.ts index 001404ec5..7d33034e4 100644 --- a/src/unstable/prefixes/sable/accountdata.ts +++ b/src/unstable/prefixes/sable/accountdata.ts @@ -11,6 +11,8 @@ export const MATRIX_SABLE_UNSTABLE_ACCOUNT_SETTINGS_PROPERTY_NAME = 'moe.sable.a */ export const MATRIX_SABLE_UNSTABLE_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME = 'fyi.cisnt.permessageprofile'; +export const MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME = + 'fi.mau.msc4461.per_message_profiles.v2'; export const MATRIX_SABLE_UNSTABLE_DISMISSED_INVITES = 'moe.sable.dismissed_invites'; export const MATRIX_SABLE_UNSTABLE_ACCOUNT_ADDED_SERVERS_PROPERTY_NAME = 'moe.sable.added_servers'; From afe64da018bc11159af28ec7fcd3b326d91a7feb Mon Sep 17 00:00:00 2001 From: Josie Date: Mon, 3 Aug 2026 17:55:52 +0100 Subject: [PATCH 019/135] msc4461 delete old records --- src/app/hooks/usePerMessageProfile.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/app/hooks/usePerMessageProfile.ts b/src/app/hooks/usePerMessageProfile.ts index 07a4ce53b..5fdf4d7f4 100644 --- a/src/app/hooks/usePerMessageProfile.ts +++ b/src/app/hooks/usePerMessageProfile.ts @@ -553,6 +553,18 @@ export async function getAllPerMessageProfiles( typeof mx.getAccountData >[0] ); + + // delete old records + await mx.deleteAccountData( + 'fyi.cisnt.permessageprofile.index' as Parameters[0] + ); + + profiles.forEach(async (profile) => { + if (!profile) return; + await mx.deleteAccountData( + `fyi.cisnt.permessageprofile.${profile.id}` as Parameters[0] + ); + }); } if (!profileListIndex) return []; From 19d101df5ec914293dc12f93d51b1d8149197ee3 Mon Sep 17 00:00:00 2001 From: lunar-seal Date: Mon, 3 Aug 2026 19:20:21 +0200 Subject: [PATCH 020/135] fix: drop cef resize workaround --- src-tauri/src/lib.rs | 26 -------------------------- 1 file changed, 26 deletions(-) diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 7fcfe176c..0d51c14d8 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -98,29 +98,6 @@ fn resolve_webview_permission( allowed } -#[cfg(all(feature = "cef", target_os = "linux"))] -fn setup_cef_resize_workaround( - webview_window: &tauri::WebviewWindow, -) -> tauri::Result<()> { - let webview = webview_window.as_ref().clone(); - webview.set_auto_resize(false)?; - webview_window.on_window_event(move |event| { - let size = match event { - tauri::WindowEvent::Resized(size) => *size, - tauri::WindowEvent::ScaleFactorChanged { new_inner_size, .. } => *new_inner_size, - _ => return, - }; - - if let Err(error) = webview.set_bounds(tauri::Rect { - position: tauri::Position::Physical(tauri::PhysicalPosition::new(0, 0)), - size: tauri::Size::Physical(size), - }) { - log::warn!("failed to resize CEF webview: {error}"); - } - }); - Ok(()) -} - /// Routes in-app notification sounds to the native volume stream on mobile. /// `kind` is "notification" or "invite". #[cfg(any(target_os = "android", target_os = "ios"))] @@ -212,9 +189,6 @@ pub fn show_or_create_main_window(app: &AppHandle) -> taur #[cfg(not(desktop))] builder.build()?; - #[cfg(all(feature = "cef", target_os = "linux"))] - setup_cef_resize_workaround(&webview_window)?; - #[cfg(desktop)] desktop::tray::setup_close_to_background(&webview_window); From f3ae3873e2f10000ffa99cc5987e611a4bb5f4e5 Mon Sep 17 00:00:00 2001 From: "sable-actions[bot]" <268226691+sable-actions[bot]@users.noreply.github.com> Date: Mon, 3 Aug 2026 18:24:25 +0000 Subject: [PATCH 021/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index 39579c499..15c2caf7f 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -21,11 +21,11 @@ "versions": [ { "version": "1.20.1", - "buildVersion": "1.20.1.260803112751", - "date": "2026-08-03T11:40:25Z", - "size": 18914950, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260803112751-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260803112751" + "buildVersion": "1.20.1.260803181041", + "date": "2026-08-03T18:24:23Z", + "size": 18915020, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260803181041-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260803181041" } ], "appPermissions": { From 5ad4276bf0b4e8151d284aade70281539242eb6f Mon Sep 17 00:00:00 2001 From: Josie Date: Mon, 3 Aug 2026 19:23:34 +0100 Subject: [PATCH 022/135] Escape blockquote data-md=">" because that's good practice --- .../escape_blockquote_data_md_because_thats_good_practice.md | 5 +++++ src/app/plugins/markdown/injectDataMd.test.ts | 2 +- src/app/plugins/markdown/injectDataMd.ts | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) create mode 100644 .changeset/escape_blockquote_data_md_because_thats_good_practice.md diff --git a/.changeset/escape_blockquote_data_md_because_thats_good_practice.md b/.changeset/escape_blockquote_data_md_because_thats_good_practice.md new file mode 100644 index 000000000..2ea0316c9 --- /dev/null +++ b/.changeset/escape_blockquote_data_md_because_thats_good_practice.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +# Escape blockquote data-md=">" because that's good practice diff --git a/src/app/plugins/markdown/injectDataMd.test.ts b/src/app/plugins/markdown/injectDataMd.test.ts index c29f30196..77a7abfd8 100644 --- a/src/app/plugins/markdown/injectDataMd.test.ts +++ b/src/app/plugins/markdown/injectDataMd.test.ts @@ -16,7 +16,7 @@ describe('injectDataMd', () => { it('injects data-md into blockquotes', () => { const result = injectDataMd('
Quote
'); - expect(result).toContain('data-md=">"'); + expect(result).toContain('data-md=">"'); }); it('injects data-md into code blocks', () => { diff --git a/src/app/plugins/markdown/injectDataMd.ts b/src/app/plugins/markdown/injectDataMd.ts index 059b054bf..1db18bd73 100644 --- a/src/app/plugins/markdown/injectDataMd.ts +++ b/src/app/plugins/markdown/injectDataMd.ts @@ -19,7 +19,7 @@ export function injectDataMd(html: string): string { // Inject blockquote data-md html = html.replace(/]*)>/g, (_, attrs) => { if (attrs.includes('data-md')) return ``; - return `
`; + return `
`; }); // Inject code block data-md From 24748e576ea26f434076dcb1832ee832785f0a30 Mon Sep 17 00:00:00 2001 From: "sable-actions[bot]" <268226691+sable-actions[bot]@users.noreply.github.com> Date: Mon, 3 Aug 2026 18:53:27 +0000 Subject: [PATCH 023/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index 15c2caf7f..28c08578e 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -21,11 +21,11 @@ "versions": [ { "version": "1.20.1", - "buildVersion": "1.20.1.260803181041", - "date": "2026-08-03T18:24:23Z", - "size": 18915020, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260803181041-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260803181041" + "buildVersion": "1.20.1.260803184150", + "date": "2026-08-03T18:53:25Z", + "size": 18914839, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260803184150-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260803184150" } ], "appPermissions": { From f9f7a468e671806b9a8e08910b2df9654786a8ac Mon Sep 17 00:00:00 2001 From: Josie Date: Mon, 3 Aug 2026 19:23:34 +0100 Subject: [PATCH 024/135] Fix jumbo emoji on pmp messages --- .../components/message/MsgTypeRenderers.tsx | 34 +++++++++++++++---- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/src/app/components/message/MsgTypeRenderers.tsx b/src/app/components/message/MsgTypeRenderers.tsx index 976a88aa8..0d1e23efc 100644 --- a/src/app/components/message/MsgTypeRenderers.tsx +++ b/src/app/components/message/MsgTypeRenderers.tsx @@ -217,29 +217,49 @@ export function MText({ /** * For the unwrapping of per-message profile fallbacks, we look for tags with the data-mx-profile-fallback attribute */ - const unwrappedPerMessageProfileMessage = useMemo( + const hadPerMessageProfileFallback = useMemo( + () => cleanedMessage?.match(/]*data-mx-profile-fallback[^>]*>(.*?):\s*<\/strong>/i), + [cleanedMessage] + ); + // the html body, with PMP fallback removed + const unwrappedPmpCustomBody = useMemo( () => cleanedMessage?.replace(/]*data-mx-profile-fallback[^>]*>(.*?):\s*<\/strong>/i, ''), [cleanedMessage] ); + // the plain body, with PMP fallback removed + const unwrappedPmpBody = useMemo( + () => (hadPerMessageProfileFallback ? trimmedBody?.replace(/(.*?):/i, '') : trimmedBody), + [trimmedBody, hadPerMessageProfileFallback] + ); const isJumbo = useMemo(() => { if (!trimmedBody || trimmedBody.length >= 500) return false; if ( - (unwrappedPerMessageProfileMessage ?? cleanedMessage ?? customBody)?.match( + (unwrappedPmpCustomBody ?? cleanedMessage ?? customBody)?.match( /^(]*data-mx-emoticon[^>]*\/>){1,20}$/i ) ) return true; - if (!isJumboEmojiText(trimmedBody)) return false; + if (!isJumboEmojiText(unwrappedPmpBody)) return false; - if (trimmedBody.includes(':')) { - const hasImage = customBody && /]*>/i.test(customBody); + // we need to strip the plainbody fallback because it contains a colon + if (unwrappedPmpBody.includes(':')) { + const newCustomBody = hadPerMessageProfileFallback ? unwrappedPmpCustomBody : customBody; + + const hasImage = newCustomBody && /]*>/i.test(newCustomBody); if (!hasImage) return false; } return true; - }, [unwrappedPerMessageProfileMessage, cleanedMessage, trimmedBody, customBody]); + }, [ + unwrappedPmpCustomBody, + cleanedMessage, + trimmedBody, + customBody, + unwrappedPmpBody, + hadPerMessageProfileFallback, + ]); const { urls, bundleContent } = getUrlsFromContent(content, renderUrlsPreview); @@ -260,7 +280,7 @@ export function MText({ > {renderBody({ body: trimmedBody, - customBody: unwrappedPerMessageProfileMessage, + customBody: unwrappedPmpCustomBody, })} {edited && } From 8b6f032f25676cd0651137708776b7febbc2cbfd Mon Sep 17 00:00:00 2001 From: Florian Date: Mon, 3 Aug 2026 21:40:56 +0200 Subject: [PATCH 025/135] Fix bundled URL Preview Rendering: remove theming check that broke the preview for bundled embeds --- src/app/components/RenderMessageContent.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/components/RenderMessageContent.tsx b/src/app/components/RenderMessageContent.tsx index d29f6333e..e62b96713 100644 --- a/src/app/components/RenderMessageContent.tsx +++ b/src/app/components/RenderMessageContent.tsx @@ -209,7 +209,7 @@ function RenderMessageContentInternal({ ), [urlPreview] ); - const messageUrlsPreview = urlPreview || themeChatSableWidgets ? renderUrlsPreview : undefined; + const messageUrlsPreview = urlPreview ? renderUrlsPreview : undefined; const messageBundlePreview = bundledPreview ? renderBundledPreviews : undefined; const renderCaption = () => { From 900d810c54155d32357629b7fbbd7a8fa75cb167 Mon Sep 17 00:00:00 2001 From: "sable-actions[bot]" <268226691+sable-actions[bot]@users.noreply.github.com> Date: Mon, 3 Aug 2026 19:46:11 +0000 Subject: [PATCH 026/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index 28c08578e..0a1377cd6 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -21,11 +21,11 @@ "versions": [ { "version": "1.20.1", - "buildVersion": "1.20.1.260803184150", - "date": "2026-08-03T18:53:25Z", - "size": 18914839, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260803184150-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260803184150" + "buildVersion": "1.20.1.260803193307", + "date": "2026-08-03T19:46:09Z", + "size": 18915013, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260803193307-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260803193307" } ], "appPermissions": { From 643f48ce508a1cb3e9633e66409fb69341c65edc Mon Sep 17 00:00:00 2001 From: "sable-actions[bot]" <268226691+sable-actions[bot]@users.noreply.github.com> Date: Mon, 3 Aug 2026 20:01:35 +0000 Subject: [PATCH 027/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index 0a1377cd6..f54331a8a 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -21,11 +21,11 @@ "versions": [ { "version": "1.20.1", - "buildVersion": "1.20.1.260803193307", - "date": "2026-08-03T19:46:09Z", - "size": 18915013, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260803193307-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260803193307" + "buildVersion": "1.20.1.260803194644", + "date": "2026-08-03T20:01:33Z", + "size": 18915076, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260803194644-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260803194644" } ], "appPermissions": { From a9ac09e56af56a9d801886f030e5efae844c4af5 Mon Sep 17 00:00:00 2001 From: "sable-actions[bot]" <268226691+sable-actions[bot]@users.noreply.github.com> Date: Mon, 3 Aug 2026 20:30:17 +0000 Subject: [PATCH 028/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index f54331a8a..6d0dd9e48 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -21,11 +21,11 @@ "versions": [ { "version": "1.20.1", - "buildVersion": "1.20.1.260803194644", - "date": "2026-08-03T20:01:33Z", - "size": 18915076, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260803194644-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260803194644" + "buildVersion": "1.20.1.260803201911", + "date": "2026-08-03T20:30:15Z", + "size": 18915177, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260803201911-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260803201911" } ], "appPermissions": { From 6e3ffe501c17c7607f906370cb97e4e26c429eb2 Mon Sep 17 00:00:00 2001 From: Josie Date: Mon, 3 Aug 2026 23:28:17 +0100 Subject: [PATCH 029/135] Fix pmp replies not respecting pmp name color --- src/app/components/message/Reply.tsx | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/app/components/message/Reply.tsx b/src/app/components/message/Reply.tsx index 7939ef854..4368e9a70 100644 --- a/src/app/components/message/Reply.tsx +++ b/src/app/components/message/Reply.tsx @@ -64,6 +64,7 @@ import { ReactionKeyInline } from './ReactionKeyInline'; import { M_POLL_START, M_TEXT } from 'matrix-js-sdk'; import type { PerMessageProfileBeeperFormat } from '$hooks/usePerMessageProfile'; import { convertBeeperFormatToOurPerMessageProfile } from '$hooks/usePerMessageProfile'; +import { ThemeKind, useActiveTheme } from '$hooks/useTheme'; const ROOM_REPLY_TIMELINE_EVENT_TYPES = new Set([ EventType.RoomMessage as string, @@ -291,6 +292,11 @@ export const Reply = as<'div', ReplyProps>( const parseMemberEvent = useMemberEventParser(); const { color: usernameColor, font: usernameFont } = useSableCosmetics(sender ?? '', room); + const activeTheme = useActiveTheme(); + const pmpNameColor = + activeTheme.kind === ThemeKind.Dark + ? pmp?.['eu.she-a.color']?.on_dark + : pmp?.['eu.she-a.color']?.on_light; const nicknames = useAtomValue(nicknamesAtom); const cachedProfiles = useAtomValue(profilesCacheAtom); useRoomMemberHydration(room, sender ?? ''); @@ -503,7 +509,7 @@ export const Reply = as<'div', ReplyProps>( )} Date: Tue, 4 Aug 2026 00:07:25 +0100 Subject: [PATCH 030/135] Fix pmp messages showing fallback in copy --- src/app/components/message/modals/Options.tsx | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/app/components/message/modals/Options.tsx b/src/app/components/message/modals/Options.tsx index ce12ac770..25def1c85 100644 --- a/src/app/components/message/modals/Options.tsx +++ b/src/app/components/message/modals/Options.tsx @@ -62,7 +62,10 @@ import { } from '$features/bookmarks'; import { CopyIcon } from '@phosphor-icons/react'; import * as OptionsCss from './Options.css'; -import { MATRIX_SABLE_UNSTABLE_FAVORITE_GIFS } from '$unstable/prefixes'; +import { + MATRIX_SABLE_UNSTABLE_FAVORITE_GIFS, + MATRIX_UNSTABLE_PER_MESSAGE_PROFILE_PROPERTY_NAME, +} from '$unstable/prefixes'; import { useFavoriteGifs } from '$hooks/useFavoriteGifs'; import type { IImageInfo } from '$types/matrix/common'; import { getIncomingMediaMxcUrl } from '../MsgTypeRenderers'; @@ -172,7 +175,8 @@ const MessageCopyTextItem = as< >(({ room, mEvent, onClose, ...props }, ref) => { const handleCopy = () => { const content = mEvent.getContent(); - const body = content?.body; + const pmp = content[MATRIX_UNSTABLE_PER_MESSAGE_PROFILE_PROPERTY_NAME]; + const body = pmp ? content?.body?.replace(`${pmp.displayname}: `, '') : content?.body; if (body) copyToClipboard(body); onClose(); From 8b1e7c058e66f357dffbc9e499bdacfbf9e1e04c Mon Sep 17 00:00:00 2001 From: Josie Date: Mon, 3 Aug 2026 23:13:12 +0100 Subject: [PATCH 031/135] Fix pmp /me rendering --- src/app/components/RenderMessageContent.tsx | 27 ++++++++++++++++--- .../components/message/MsgTypeRenderers.tsx | 14 +++++++--- src/app/components/message/Reply.tsx | 7 +++-- src/app/features/room/RoomInput.tsx | 3 ++- .../features/room/buildReplacementContent.ts | 12 +++++---- .../features/room/message/MessageEditor.tsx | 6 ++--- src/app/hooks/usePerMessageProfile.ts | 17 ++++++++++++ 7 files changed, 67 insertions(+), 19 deletions(-) diff --git a/src/app/components/RenderMessageContent.tsx b/src/app/components/RenderMessageContent.tsx index e62b96713..175215164 100644 --- a/src/app/components/RenderMessageContent.tsx +++ b/src/app/components/RenderMessageContent.tsx @@ -54,6 +54,12 @@ import { PollEvent } from './message/PollEvent'; import { M_POLL_START, M_TEXT } from 'matrix-js-sdk'; import type { IImageInfo, IGalleryContent } from '$types/matrix/common'; import { GALLERY_MSGTYPE } from '$types/matrix/common'; +import { + convertBeeperFormatToOurPerMessageProfile, + type PerMessageProfileBeeperFormat, + stripPerMessageProfileFormattedBody, + stripPerMessageProfilePlainBody, +} from '$hooks/usePerMessageProfile'; type RenderMessageContentProps = { displayName: string; @@ -209,7 +215,7 @@ function RenderMessageContentInternal({ ), [urlPreview] ); - const messageUrlsPreview = urlPreview ? renderUrlsPreview : undefined; + const messageUrlsPreview = urlPreview || themeChatSableWidgets ? renderUrlsPreview : undefined; const messageBundlePreview = bundledPreview ? renderBundledPreviews : undefined; const renderCaption = () => { @@ -339,6 +345,21 @@ function RenderMessageContentInternal({ } if (msgType === (MsgType.Emote as string)) { + const beeperProfile = content['com.beeper.per_message_profile'] as + | PerMessageProfileBeeperFormat + | undefined; + const pmp = beeperProfile + ? convertBeeperFormatToOurPerMessageProfile(beeperProfile) + : undefined; + + const strippedContent = pmp + ? { + ...content, + formatted_body: stripPerMessageProfileFormattedBody(content['formatted_body'] as string), + body: stripPerMessageProfilePlainBody(content['body'] as string), + } + : content; + if ((content as { 'fyi.cisnt.headpat'?: boolean })['fyi.cisnt.headpat']) { return ( - cleanedMessage?.replace(/]*data-mx-profile-fallback[^>]*>(.*?):\s*<\/strong>/i, ''), + () => (cleanedMessage ? stripPerMessageProfileFormattedBody(cleanedMessage) : undefined), [cleanedMessage] ); // the plain body, with PMP fallback removed const unwrappedPmpBody = useMemo( - () => (hadPerMessageProfileFallback ? trimmedBody?.replace(/(.*?):/i, '') : trimmedBody), + () => + hadPerMessageProfileFallback + ? stripPerMessageProfilePlainBody(trimmedBody ?? '') + : trimmedBody, [trimmedBody, hadPerMessageProfileFallback] ); diff --git a/src/app/components/message/Reply.tsx b/src/app/components/message/Reply.tsx index 7939ef854..bc3b0397f 100644 --- a/src/app/components/message/Reply.tsx +++ b/src/app/components/message/Reply.tsx @@ -63,7 +63,10 @@ import { LinePlaceholder } from './placeholder'; import { ReactionKeyInline } from './ReactionKeyInline'; import { M_POLL_START, M_TEXT } from 'matrix-js-sdk'; import type { PerMessageProfileBeeperFormat } from '$hooks/usePerMessageProfile'; -import { convertBeeperFormatToOurPerMessageProfile } from '$hooks/usePerMessageProfile'; +import { + convertBeeperFormatToOurPerMessageProfile, + stripPerMessageProfileFormattedBody, +} from '$hooks/usePerMessageProfile'; const ROOM_REPLY_TIMELINE_EVENT_TYPES = new Set([ EventType.RoomMessage as string, @@ -272,7 +275,7 @@ export const Reply = as<'div', ReplyProps>( // strip the PMP fallback if it's there, to avoid displaying the PMP name twice const formattedBodyStripped: string = pmp - ? formattedBody?.replace(/^]*>.*?<\/strong>/, '') + ? stripPerMessageProfileFormattedBody(formattedBody ?? '') : formattedBody; const extensibleContent = contentForPreview[M_TEXT.name] as diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 2758e9ffd..6adb44390 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -152,6 +152,7 @@ import { getCurrentlyUsedPerMessageProfileForRoom, type PerMessageProfileMsc4461, setCurrentlyUsedPerMessageProfileIdForRoom, + stripPerMessageProfileFormattedBody, } from '$hooks/usePerMessageProfile'; import { Bell, @@ -640,7 +641,7 @@ export const RoomInput = forwardRef( } } const editableHtml = pmpDisplayname - ? customHtml?.replace(/^]*>.*?<\/strong>/, '') + ? stripPerMessageProfileFormattedBody(customHtml ?? '') : customHtml; const mentionOptions = { diff --git a/src/app/features/room/buildReplacementContent.ts b/src/app/features/room/buildReplacementContent.ts index 011ba3b3d..ce325933d 100644 --- a/src/app/features/room/buildReplacementContent.ts +++ b/src/app/features/room/buildReplacementContent.ts @@ -3,7 +3,10 @@ import { MsgType, RelationType } from '$types/matrix-sdk'; import { customHtmlEqualsPlainText } from '$components/editor'; import { sanitizeText } from '$utils/sanitize'; import type { PerMessageProfileMsc4461 } from '$hooks/usePerMessageProfile'; -import { convertPerMessageProfileToBeeperFormat } from '$hooks/usePerMessageProfile'; +import { + convertPerMessageProfileToBeeperFormat, + stripPerMessageProfileFormattedBody, +} from '$hooks/usePerMessageProfile'; import { MATRIX_UNSTABLE_PER_MESSAGE_PROFILE_PROPERTY_NAME } from '$unstable/prefixes'; /** @@ -111,10 +114,9 @@ export function buildReplacementPmpContent( let newPlainBody = plainBody?.replace(/^.*?: /, ''); const formattedBody = oldContent.formatted_body; - let newFormattedBody = formattedBody?.replace( - /^]*>.*?<\/strong>/, - '' - ); + let newFormattedBody = formattedBody + ? stripPerMessageProfileFormattedBody(formattedBody) + : undefined; oldContent.formatted_body = newFormattedBody; oldContent.body = newPlainBody; diff --git a/src/app/features/room/message/MessageEditor.tsx b/src/app/features/room/message/MessageEditor.tsx index 7829440f4..09253cfd1 100644 --- a/src/app/features/room/message/MessageEditor.tsx +++ b/src/app/features/room/message/MessageEditor.tsx @@ -81,6 +81,7 @@ import { readdAngleBracketsForHiddenPreviews, stripMarkdownEscapesForHiddenPreviews, } from './hiddenLinkPreviews'; +import { stripPerMessageProfileFormattedBody } from '$hooks/usePerMessageProfile'; // Wraps the mobile emoji-board overlay so the Android back action closes it // instead of navigating away. Hooks can't run inside the UseStateProvider @@ -164,10 +165,7 @@ export const MessageEditor = as<'div', MessageEditorProps>( } if (pmpDisplayname && typeof customHtml === 'string') { - customHtml = customHtml.replace( - /^]*>.*?<\/strong>/, - '' - ); + customHtml = stripPerMessageProfileFormattedBody(customHtml); } const bundleContent = diff --git a/src/app/hooks/usePerMessageProfile.ts b/src/app/hooks/usePerMessageProfile.ts index 5fdf4d7f4..b0673f31c 100644 --- a/src/app/hooks/usePerMessageProfile.ts +++ b/src/app/hooks/usePerMessageProfile.ts @@ -825,3 +825,20 @@ export async function getCurrentlyUsedPerMessageProfileForAccount( const pmp = profileId ? await getPerMessageProfileById(mx, profileId) : undefined; return profileId ? pmp : undefined; } + +/* + * If you don't supply a profile, it may fail if the displayname has a colon. + */ +export function stripPerMessageProfilePlainBody( + formatted_body: string, + profile?: PerMessageProfileMsc4461 +): string { + if (profile) { + return formatted_body.replace(`${profile.displayname}: `, ''); + } else { + return formatted_body.replace(/^.*?: /, ''); + } +} +export function stripPerMessageProfileFormattedBody(formatted_body: string): string { + return formatted_body.replace(/^]*>.*?<\/strong>/, ''); +} From d4a20587d8aad2c42dd011438de20b11042b6d5e Mon Sep 17 00:00:00 2001 From: Josie Date: Tue, 4 Aug 2026 00:00:01 +0100 Subject: [PATCH 032/135] Add the option to remove the fallback from PMPs --- ...option_to_remove_the_fallback_from_pmps.md | 5 + src/app/features/room/RoomInput.tsx | 7 +- .../features/room/buildReplacementContent.ts | 5 +- .../features/room/message/MessageEditor.tsx | 6 +- .../features/settings/Persona/PKCompat.tsx | 172 ++++++++++-------- src/app/features/settings/settingsLink.ts | 1 + src/app/state/settings.ts | 2 + 7 files changed, 121 insertions(+), 77 deletions(-) create mode 100644 .changeset/add_the_option_to_remove_the_fallback_from_pmps.md diff --git a/.changeset/add_the_option_to_remove_the_fallback_from_pmps.md b/.changeset/add_the_option_to_remove_the_fallback_from_pmps.md new file mode 100644 index 000000000..689c102da --- /dev/null +++ b/.changeset/add_the_option_to_remove_the_fallback_from_pmps.md @@ -0,0 +1,5 @@ +--- +default: minor +--- + +# Add the option to remove the fallback from PMPs diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 2758e9ffd..8c5583efe 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -341,6 +341,7 @@ export const RoomInput = forwardRef( const [pmpProxyingEnable] = useSetting(settingsAtom, 'pmpProxying'); const [pmpLatchingEnable] = useSetting(settingsAtom, 'pmpLatching'); const [pmpPickerEnable] = useSetting(settingsAtom, 'pmpPicker'); + const [pmpNoFallback] = useSetting(settingsAtom, 'pmpNoFallback'); const [latchedPersona, setLatchedPersona] = useState(); @@ -1100,7 +1101,8 @@ export const RoomInput = forwardRef( eventId, mMentions, linkPreviews, - rawPmp + rawPmp, + pmpNoFallback ); await mx.sendMessage(roomId, content as RoomMessageEventContent); @@ -1364,7 +1366,7 @@ export const RoomInput = forwardRef( perMessageProfile.displayname.trim() !== '' ); - if (perMessageProfile.displayname.trim() !== '') { + if (!pmpNoFallback && perMessageProfile.displayname.trim() !== '') { // if a per-message profile is used, it must per spec include a fallback const pmpPrefix = `${perMessageProfile.displayname}: `; @@ -1513,6 +1515,7 @@ export const RoomInput = forwardRef( silentReply, pmpProxyingEnable, pmpLatchingEnable, + pmpNoFallback, pluralkitProxyMessageHandler, scheduledTime, editingScheduledDelayId, diff --git a/src/app/features/room/buildReplacementContent.ts b/src/app/features/room/buildReplacementContent.ts index 011ba3b3d..8d793eada 100644 --- a/src/app/features/room/buildReplacementContent.ts +++ b/src/app/features/room/buildReplacementContent.ts @@ -17,7 +17,8 @@ export function buildReplacementContent( eventId: string, mMentions: IMentions, linkPreviews: { matched_url: string }[], - perMessageProfile: unknown + perMessageProfile: unknown, + pmpNoFallback: boolean ): IContent { const pmpDisplayname = perMessageProfile !== null && @@ -31,7 +32,7 @@ export function buildReplacementContent( let adjustedPlainText = plainText; let adjustedCustomHtml = customHtml; - if (pmpDisplayname) { + if (!pmpNoFallback && pmpDisplayname) { const bodyPrefix = `${pmpDisplayname}: `; if (!adjustedPlainText.startsWith(bodyPrefix)) adjustedPlainText = bodyPrefix + adjustedPlainText; diff --git a/src/app/features/room/message/MessageEditor.tsx b/src/app/features/room/message/MessageEditor.tsx index 7829440f4..1436eeb69 100644 --- a/src/app/features/room/message/MessageEditor.tsx +++ b/src/app/features/room/message/MessageEditor.tsx @@ -126,6 +126,7 @@ export const MessageEditor = as<'div', MessageEditorProps>( const nicknames = useAtomValue(nicknamesAtom); const editor = useEditor(); const [enterForNewline] = useSetting(settingsAtom, 'enterForNewline'); + const [pmpNoFallback] = useSetting(settingsAtom, 'pmpNoFallback'); const isComposing = useComposingCheck(); const [autocompleteQuery, setAutocompleteQuery] = @@ -292,11 +293,12 @@ export const MessageEditor = as<'div', MessageEditorProps>( eventId, mMentions, linkPreviews, - rawPmp + rawPmp, + pmpNoFallback ); return mx.sendMessage(roomId, content as RoomMessageEventContent); - }, [mx, editor, roomId, mEvent, getPrevBodyAndFormattedBody, room]) + }, [mx, editor, roomId, mEvent, getPrevBodyAndFormattedBody, room, pmpNoFallback]) ); const handleSave = useCallback(() => { diff --git a/src/app/features/settings/Persona/PKCompat.tsx b/src/app/features/settings/Persona/PKCompat.tsx index 86df62eba..e0dc2dc04 100644 --- a/src/app/features/settings/Persona/PKCompat.tsx +++ b/src/app/features/settings/Persona/PKCompat.tsx @@ -8,78 +8,108 @@ export function PKCompatSettings() { const [usePKCompat, setUsePKCompat] = useSetting(settingsAtom, 'pkCompat'); const [usePmpProxying, setUsePmpProxying] = useSetting(settingsAtom, 'pmpProxying'); const [usePmpLatching, setUsePmpLatching] = useSetting(settingsAtom, 'pmpLatching'); + const [usePmpNoFallback, setUsePmpNoFallback] = useSetting(settingsAtom, 'pmpNoFallback'); return ( - - Limited Compatibility with PluralKit-like functions - - - } - /> - - - - } - /> - - - - } - /> - - + <> + + Limited Compatibility with PluralKit-like functions + + + } + /> + + + + } + /> + + + + } + /> + + + + General Behavior + + + } + /> + + + ); } diff --git a/src/app/features/settings/settingsLink.ts b/src/app/features/settings/settingsLink.ts index 4d85fd0d8..6b1395d43 100644 --- a/src/app/features/settings/settingsLink.ts +++ b/src/app/features/settings/settingsLink.ts @@ -108,6 +108,7 @@ export const settingsLinkFocusIdsBySection: Record Date: Tue, 4 Aug 2026 01:14:42 +0000 Subject: [PATCH 033/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index 6d0dd9e48..ee3d8dba5 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -21,11 +21,11 @@ "versions": [ { "version": "1.20.1", - "buildVersion": "1.20.1.260803201911", - "date": "2026-08-03T20:30:15Z", - "size": 18915177, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260803201911-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260803201911" + "buildVersion": "1.20.1.260804010057", + "date": "2026-08-04T01:14:39Z", + "size": 18915143, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260804010057-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260804010057" } ], "appPermissions": { From 49cef3745afcee2429886301d51bad60281656ca Mon Sep 17 00:00:00 2001 From: Shea Date: Tue, 4 Aug 2026 05:27:59 +0300 Subject: [PATCH 034/135] make fallback tag more reliable --- src/app/features/room/RoomInput.tsx | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 8c5583efe..e40769a89 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -1361,10 +1361,7 @@ export const RoomInput = forwardRef( } if (perMessageProfile) { content[prefix.MATRIX_UNSTABLE_PER_MESSAGE_PROFILE_PROPERTY_NAME] = - convertPerMessageProfileToBeeperFormat( - perMessageProfile, - perMessageProfile.displayname.trim() !== '' - ); + convertPerMessageProfileToBeeperFormat(perMessageProfile, !pmpNoFallback); if (!pmpNoFallback && perMessageProfile.displayname.trim() !== '') { // if a per-message profile is used, it must per spec include a fallback From ad0ddcb40f88a9cedadd6115d65e65ead41ff220 Mon Sep 17 00:00:00 2001 From: "sable-actions[bot]" <268226691+sable-actions[bot]@users.noreply.github.com> Date: Tue, 4 Aug 2026 02:43:21 +0000 Subject: [PATCH 035/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index ee3d8dba5..1ac40d9e4 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -21,11 +21,11 @@ "versions": [ { "version": "1.20.1", - "buildVersion": "1.20.1.260804010057", - "date": "2026-08-04T01:14:39Z", - "size": 18915143, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260804010057-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260804010057" + "buildVersion": "1.20.1.260804023310", + "date": "2026-08-04T02:43:19Z", + "size": 18915899, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260804023310-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260804023310" } ], "appPermissions": { From 1402a6b34322499fbbaa834bf3b45771da9301b8 Mon Sep 17 00:00:00 2001 From: "sable-actions[bot]" <268226691+sable-actions[bot]@users.noreply.github.com> Date: Tue, 4 Aug 2026 06:04:10 +0000 Subject: [PATCH 036/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index 1ac40d9e4..bdac51970 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -21,11 +21,11 @@ "versions": [ { "version": "1.20.1", - "buildVersion": "1.20.1.260804023310", - "date": "2026-08-04T02:43:19Z", - "size": 18915899, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260804023310-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260804023310" + "buildVersion": "1.20.1.260804055032", + "date": "2026-08-04T06:04:08Z", + "size": 18915734, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260804055032-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260804055032" } ], "appPermissions": { From 259f8b7e060657f6aed4de94adeb08e57a720749 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Tue, 4 Aug 2026 09:36:43 +0200 Subject: [PATCH 037/135] Fix Reply preview tests --- src/app/components/message/Reply.test.tsx | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/app/components/message/Reply.test.tsx b/src/app/components/message/Reply.test.tsx index c41422eee..8338ded51 100644 --- a/src/app/components/message/Reply.test.tsx +++ b/src/app/components/message/Reply.test.tsx @@ -44,6 +44,11 @@ vi.mock('$hooks/useSableCosmetics', () => ({ useSableCosmetics: () => ({ color: undefined, font: undefined }), })); +vi.mock('$hooks/useTheme', () => ({ + ThemeKind: { Light: 'light', Dark: 'dark' }, + useActiveTheme: () => ({ kind: 'light' }), +})); + vi.mock('$hooks/useMediaAuthentication', () => ({ useMediaAuthentication: () => false, })); From b0874287713319a8caad7876aff10f90f029c329 Mon Sep 17 00:00:00 2001 From: "sable-actions[bot]" <268226691+sable-actions[bot]@users.noreply.github.com> Date: Tue, 4 Aug 2026 07:54:03 +0000 Subject: [PATCH 038/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index bdac51970..8da9f6137 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -21,11 +21,11 @@ "versions": [ { "version": "1.20.1", - "buildVersion": "1.20.1.260804055032", - "date": "2026-08-04T06:04:08Z", - "size": 18915734, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260804055032-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260804055032" + "buildVersion": "1.20.1.260804074029", + "date": "2026-08-04T07:54:01Z", + "size": 18915703, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260804074029-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260804074029" } ], "appPermissions": { From e3aef05f8b594db9939c6169308ce4d2794872fe Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Tue, 4 Aug 2026 09:58:47 +0200 Subject: [PATCH 039/135] fix: make iOS nightly builds visible as updates in AltStore/SideStore --- .github/scripts/set-tauri-version.mjs | 22 +++++++++++++++++----- .github/scripts/update-altstore-source.mjs | 13 ++++++++++--- .github/workflows/tauri-build.yml | 11 ++++++++++- 3 files changed, 37 insertions(+), 9 deletions(-) diff --git a/.github/scripts/set-tauri-version.mjs b/.github/scripts/set-tauri-version.mjs index dea0f0e56..11d21e552 100644 --- a/.github/scripts/set-tauri-version.mjs +++ b/.github/scripts/set-tauri-version.mjs @@ -7,11 +7,12 @@ import { readFileSync, writeFileSync } from 'node:fs'; import process from 'node:process'; -const version = process.argv[2]; -const updaterEndpoint = process.argv[3]; +const args = process.argv.slice(2); +const foldNightlyIntoPatch = args.includes('--apple-short-version'); +const [version, updaterEndpoint] = args.filter((arg) => !arg.startsWith('--')); if (!version || !/^\d+\.\d+\.\d+/.test(version)) { console.error( - `Usage: set-tauri-version.mjs [updater-endpoint] (got: ${version ?? ''})` + `Usage: set-tauri-version.mjs [updater-endpoint] [--apple-short-version] (got: ${version ?? ''})` ); process.exit(1); } @@ -33,10 +34,21 @@ const sanitizedVersion = version.replace(/^(\d+\.\d+\.\d+-nightly)\.(.+)$/, (_, return `${prefix}.${sanitizedBuild}`; }); -config.version = sanitizedVersion; +// AltStore/SideStore only compare CFBundleShortVersionString, which Tauri fills with +// major.minor.patch, so the nightly stamp has to go in patch to be seen as a new version. +let stampedVersion = sanitizedVersion; +if (foldNightlyIntoPatch) { + stampedVersion = sanitizedVersion.replace(/^(\d+\.\d+)\.\d+-nightly\.(\d+)$/, '$1.$2'); + if (stampedVersion === sanitizedVersion) { + console.error(`--apple-short-version needs a nightly version (got: ${sanitizedVersion})`); + process.exit(1); + } +} + +config.version = stampedVersion; if (updaterEndpoint) { config.plugins.updater.endpoints = [updaterEndpoint]; } writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`); -console.log(`Set ${file} version to ${version}`); +console.log(`Set ${file} version to ${stampedVersion}`); if (updaterEndpoint) console.log(`Set ${file} updater endpoint to ${updaterEndpoint}`); diff --git a/.github/scripts/update-altstore-source.mjs b/.github/scripts/update-altstore-source.mjs index 770c8e75e..01ac0ac69 100644 --- a/.github/scripts/update-altstore-source.mjs +++ b/.github/scripts/update-altstore-source.mjs @@ -5,7 +5,7 @@ // IPA asset, then prints the updated file. Used by .github/workflows/tauri-build.yml. // // Usage: update-altstore-source.mjs [description] -// Env: none +// Env: ALTSTORE_MAX_VERSIONS - how many version entries to keep (default 20) import { readFileSync, writeFileSync } from 'node:fs'; import process from 'node:process'; @@ -60,8 +60,15 @@ const idx = versions.findIndex((v) => v.version === normalizedVersion); if (idx >= 0) versions[idx] = entry; else versions.unshift(entry); -// Keep only the most recent 20 versions in the manifest. -app.versions = versions.slice(0, 20); +// Keep only the most recent versions in the manifest. +const maxVersions = Number(process.env.ALTSTORE_MAX_VERSIONS ?? 20); +if (!Number.isInteger(maxVersions) || maxVersions <= 0) { + console.error( + `ALTSTORE_MAX_VERSIONS must be a positive integer (got: ${process.env.ALTSTORE_MAX_VERSIONS})` + ); + process.exit(1); +} +app.versions = versions.slice(0, maxVersions); writeFileSync(sourcePath, `${JSON.stringify(source, null, 2)}\n`); console.log( diff --git a/.github/workflows/tauri-build.yml b/.github/workflows/tauri-build.yml index 3d976d462..44943bdd0 100644 --- a/.github/workflows/tauri-build.yml +++ b/.github/workflows/tauri-build.yml @@ -455,7 +455,14 @@ jobs: - name: Stamp release version into tauri.conf.json shell: bash - run: node .github/scripts/set-tauri-version.mjs "$VERSION" + env: + IS_NIGHTLY: ${{ needs.setup-release.outputs.nightly }} + run: | + if [ "$IS_NIGHTLY" = "true" ]; then + node .github/scripts/set-tauri-version.mjs "$VERSION" --apple-short-version + else + node .github/scripts/set-tauri-version.mjs "$VERSION" + fi - name: Set up iOS shell: bash @@ -541,6 +548,8 @@ jobs: set -euo pipefail if [ "$NIGHTLY" = "true" ]; then SOURCE_FILE="altstore-source-nightly.json" + # Superseded nightly IPAs get deleted, so older entries would be dead links. + export ALTSTORE_MAX_VERSIONS=1 else SOURCE_FILE="altstore-source.json" fi From 15a723f45a9772ee0f3a9e61fd7f9ac46b26403f Mon Sep 17 00:00:00 2001 From: Josie Date: Tue, 4 Aug 2026 08:59:34 +0100 Subject: [PATCH 040/135] fix pmp add/update not persisting --- src/app/hooks/usePerMessageProfile.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/hooks/usePerMessageProfile.ts b/src/app/hooks/usePerMessageProfile.ts index b0673f31c..608c6c14a 100644 --- a/src/app/hooks/usePerMessageProfile.ts +++ b/src/app/hooks/usePerMessageProfile.ts @@ -599,7 +599,7 @@ export async function addOrUpdatePerMessageProfile( } mx.setAccountData( MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME as Parameters< - typeof mx.getAccountData + typeof mx.setAccountData >[0], newIndex as Parameters[1] ); From 14d0f75d0fc2c3536fd4d1f9a245021ad06d6f40 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sun, 2 Aug 2026 22:30:37 +0200 Subject: [PATCH 041/135] fix(dm): filter bridge bots from DM name/avatar resolution Fixes #1585 --- src/app/features/room-nav/RoomNavItem.tsx | 4 +- src/app/hooks/useGroupDMMembers.ts | 14 +------ src/app/hooks/useRoomMeta.test.tsx | 21 ++++++---- src/app/hooks/useRoomMeta.ts | 25 ++++++++++-- .../pages/client/sidebar/DirectDMsList.tsx | 40 ++++--------------- src/app/utils/room/display.ts | 16 +++++++- 6 files changed, 60 insertions(+), 60 deletions(-) diff --git a/src/app/features/room-nav/RoomNavItem.tsx b/src/app/features/room-nav/RoomNavItem.tsx index daa4bf162..2ea6ec7a1 100644 --- a/src/app/features/room-nav/RoomNavItem.tsx +++ b/src/app/features/room-nav/RoomNavItem.tsx @@ -22,7 +22,7 @@ import { useNavigate } from 'react-router-dom'; import { NavButton, NavItem, NavItemContent, NavItemOptions } from '$components/nav'; import { UnreadBadge, UnreadBadgeCenter } from '$components/unread-badge'; import { RoomAvatar, RoomIcon } from '$components/room-avatar'; -import { getDirectRoomAvatarUrl, getRoomAvatarUrl } from '$utils/room/display'; +import { getDirectRoomAvatarUrl, getDmOtherMember, getRoomAvatarUrl } from '$utils/room/display'; import { roomHaveUnread } from '$utils/room/unread'; import { nameInitials } from '$utils/common'; import { useMatrixClient } from '$hooks/useMatrixClient'; @@ -335,7 +335,7 @@ export function RoomNavItem({ const [roomIconOverlay] = useSetting(settingsAtom, 'roomIconOverlay'); const nicknames = useAtomValue(nicknamesAtom); - const dmUserId = direct ? room.getAvatarFallbackMember()?.userId : undefined; + const dmUserId = direct ? getDmOtherMember(mx, room)?.userId : undefined; const matrixRoomName = useRoomName(room); const roomName = (dmUserId && nicknames[dmUserId]) || matrixRoomName; const presence = useUserPresence(dmUserId ?? ''); diff --git a/src/app/hooks/useGroupDMMembers.ts b/src/app/hooks/useGroupDMMembers.ts index da5532e7d..f8015727b 100644 --- a/src/app/hooks/useGroupDMMembers.ts +++ b/src/app/hooks/useGroupDMMembers.ts @@ -1,5 +1,5 @@ import type { MatrixClient, Room } from '$types/matrix-sdk'; -import { getMemberDisplayName } from '$utils/room/display'; +import { getMemberDisplayName, isBridgeBot } from '$utils/room/display'; export type GroupMemberInfo = { userId: string; @@ -7,18 +7,6 @@ export type GroupMemberInfo = { avatarUrl?: string; }; -// Filter out bridge bots (not bridged users) -const isBridgeBot = (userId: string): boolean => { - const localpart = userId.split(':')[0]?.substring(1) ?? ''; - const lowerLocalpart = localpart.toLowerCase(); - - // Only filter out users ending with 'bot' (e.g., discordbot, blueskybot) - // Don't filter bridge users with IDs like discord_378405164077547520 - if (lowerLocalpart.endsWith('bot')) return true; - - return false; -}; - /** * Fetches member information for a group DM. * Gets all joined members from room state and fetches their profiles. diff --git a/src/app/hooks/useRoomMeta.test.tsx b/src/app/hooks/useRoomMeta.test.tsx index 7721813f2..1150b55b4 100644 --- a/src/app/hooks/useRoomMeta.test.tsx +++ b/src/app/hooks/useRoomMeta.test.tsx @@ -1,8 +1,10 @@ import { describe, it, expect } from 'vitest'; import { renderHook, act } from '@testing-library/react'; import { EventEmitter } from 'events'; -import type { MatrixEvent, Room } from '$types/matrix-sdk'; +import type { PropsWithChildren } from 'react'; +import type { MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk'; import { RoomStateEvent } from '$types/matrix-sdk'; +import { MatrixClientProvider } from './useMatrixClient'; import { useRoomAvatar } from './useRoomMeta'; const AVATAR_MXC = 'mxc://server/abc'; @@ -28,6 +30,11 @@ const makeRoom = (roomId: string) => { return { room, client, + wrapper: ({ children }: PropsWithChildren) => ( + + {children} + + ), setAvatarEvent: (event: MatrixEvent) => { avatarEvent = event; }, @@ -36,14 +43,14 @@ const makeRoom = (roomId: string) => { describe('useRoomAvatar', () => { it('returns undefined when no avatar state is loaded', () => { - const { room } = makeRoom('!space:server'); - const { result } = renderHook(() => useRoomAvatar(room)); + const { room, wrapper } = makeRoom('!space:server'); + const { result } = renderHook(() => useRoomAvatar(room), { wrapper }); expect(result.current).toBeUndefined(); }); it('updates when the avatar state event arrives after mount', () => { - const { room, client, setAvatarEvent } = makeRoom('!space:server'); - const { result } = renderHook(() => useRoomAvatar(room)); + const { room, client, setAvatarEvent, wrapper } = makeRoom('!space:server'); + const { result } = renderHook(() => useRoomAvatar(room), { wrapper }); expect(result.current).toBeUndefined(); const avatarEvent = makeAvatarEvent('!space:server', AVATAR_MXC); @@ -56,8 +63,8 @@ describe('useRoomAvatar', () => { }); it('ignores avatar state events from other rooms', () => { - const { room, client } = makeRoom('!space:server'); - const { result } = renderHook(() => useRoomAvatar(room)); + const { room, client, wrapper } = makeRoom('!space:server'); + const { result } = renderHook(() => useRoomAvatar(room), { wrapper }); act(() => { client.emit(RoomStateEvent.Events, makeAvatarEvent('!other:server', AVATAR_MXC)); diff --git a/src/app/hooks/useRoomMeta.ts b/src/app/hooks/useRoomMeta.ts index 1c7387a54..fdf8d8d93 100644 --- a/src/app/hooks/useRoomMeta.ts +++ b/src/app/hooks/useRoomMeta.ts @@ -4,6 +4,8 @@ import type { RoomJoinRulesEventContent, Room } from '$types/matrix-sdk'; import { RoomEvent, RoomStateEvent, EventType } from '$types/matrix-sdk'; import { mDirectAtom } from '$state/mDirectList'; +import { getDmOtherMember, getMemberDisplayName } from '$utils/room/display'; +import { useMatrixClient } from './useMatrixClient'; import { useStateEvent } from './useStateEvent'; import { useNickname } from './useNickname'; @@ -11,18 +13,21 @@ const getRoomDisplayName = ( roomName: string, stateName: unknown, isDmTagged: boolean, - dmNickname?: string + dmNickname?: string, + dmOtherMemberName?: string ): string => { if (isDmTagged && dmNickname) return dmNickname; if (typeof stateName === 'string' && stateName) return stateName; + if (isDmTagged && dmOtherMemberName) return dmOtherMemberName; return roomName; }; export const useRoomAvatar = (room: Room, dm?: boolean): string | undefined => { + const mx = useMatrixClient(); const avatarEvent = useStateEvent(room, EventType.RoomAvatar); if (dm) { - return room.getAvatarFallbackMember()?.getMxcAvatarUrl(); + return getDmOtherMember(mx, room)?.getMxcAvatarUrl(); } const content = avatarEvent?.getContent(); const avatarMxc = content && typeof content.url === 'string' ? content.url : undefined; @@ -31,6 +36,7 @@ export const useRoomAvatar = (room: Room, dm?: boolean): string | undefined => { }; export const useRoomName = (room: Room): string => { + const mx = useMatrixClient(); const dmUserId = room.guessDMUserId(); const dmNickname = useNickname(dmUserId || ''); const mDirects = useAtomValue(mDirectAtom); @@ -45,7 +51,18 @@ export const useRoomName = (room: Room): string => { room.recalculate(); } - const nextName = getRoomDisplayName(room.name, stateName, isDmTagged, dmNickname); + const otherMember = isDmTagged ? getDmOtherMember(mx, room) : undefined; + const dmOtherMemberName = otherMember + ? (getMemberDisplayName(room, otherMember.userId) ?? otherMember.userId) + : undefined; + + const nextName = getRoomDisplayName( + room.name, + stateName, + isDmTagged, + dmNickname, + dmOtherMemberName + ); setName((prev) => (prev !== nextName ? nextName : prev)); }; @@ -58,7 +75,7 @@ export const useRoomName = (room: Room): string => { room.removeListener(RoomEvent.Name, updateName); room.removeListener(RoomStateEvent.Members, updateName); }; - }, [room, stateName, dmNickname, isDmTagged]); + }, [room, mx, stateName, dmNickname, isDmTagged]); return name; }; diff --git a/src/app/pages/client/sidebar/DirectDMsList.tsx b/src/app/pages/client/sidebar/DirectDMsList.tsx index ac836775e..e2ded23c2 100644 --- a/src/app/pages/client/sidebar/DirectDMsList.tsx +++ b/src/app/pages/client/sidebar/DirectDMsList.tsx @@ -21,6 +21,7 @@ import { nameInitials } from '$utils/common'; import { getCanonicalAliasOrRoomId, mxcUrlToHttp } from '$utils/matrix'; import { useSelectedOrLastRoom } from '$hooks/router/useSelectedRoom'; import { useGroupDMMembers } from '$hooks/useGroupDMMembers'; +import { useRoomName } from '$hooks/useRoomMeta'; import { useSidebarDirectRoomIds } from './useSidebarDirectRoomIds'; import * as css from './DirectDMsList.css'; @@ -41,24 +42,16 @@ function DMItem({ room, selected }: DMItemProps) { navigate(getDirectRoomPath(getCanonicalAliasOrRoomId(mx, room.roomId))); }; - // Check if this is a group DM (more than 2 members) - const isGroupDM = room.getJoinedMemberCount() > 2; + const roomName = useRoomName(room); // Use already-synced room state only; sidebar rendering must not trigger member/profile requests. const groupMembers = useGroupDMMembers(mx, room, MAX_GROUP_MEMBERS); + const isGroupDM = groupMembers.length > 1; + // Get unread info for badge const unread = roomToUnread.get(room.roomId); - // Determine avatar src for single group DM member to avoid nested ternary - const getSingleMemberAvatarSrc = () => { - const member = groupMembers[0]; - if (groupMembers.length !== 1 || !member?.avatarUrl) { - return undefined; - } - return mxcUrlToHttp(mx, member.avatarUrl, useAuthentication, 96, 96, 'crop') ?? undefined; - }; - // Render appropriate avatar based on DM type const renderAvatar = () => { if (!isGroupDM) { @@ -71,29 +64,10 @@ function DMItem({ room, selected }: DMItemProps) { getRoomAvatarUrl(mx, room, 96, useAuthentication) || getDirectRoomAvatarUrl(mx, room, 96, useAuthentication) } - alt={room.name} + alt={roomName} renderFallback={() => ( - {nameInitials(room.name)} - - )} - /> - - ); - } - - if (groupMembers.length === 1) { - const member = groupMembers[0]; - if (!member) return null; - return ( - - ( - - {nameInitials(member.displayName || member.userId)} + {nameInitials(roomName)} )} /> @@ -132,7 +106,7 @@ function DMItem({ room, selected }: DMItemProps) { return ( - + {(triggerRef) => ( {renderAvatar()} diff --git a/src/app/utils/room/display.ts b/src/app/utils/room/display.ts index 5bbaffa64..afe92e0b9 100644 --- a/src/app/utils/room/display.ts +++ b/src/app/utils/room/display.ts @@ -24,13 +24,27 @@ export const getRoomAvatarUrl = ( useAuthentication = false ): string | undefined => getAvatarUrl(mx, room.getMxcAvatarUrl(), size, useAuthentication); +// Bridges add a persistent bot member to 1:1 DM portals that the SDK counts as a real participant. +export const isBridgeBot = (userId: string): boolean => { + const localpart = userId.split(':')[0]?.substring(1) ?? ''; + return localpart.toLowerCase().endsWith('bot'); +}; + +export const getDmOtherMember = (mx: MatrixClient, room: Room): RoomMember | undefined => { + const currentUserId = mx.getUserId(); + const others = room + .getJoinedMembers() + .filter((member) => member.userId !== currentUserId && !isBridgeBot(member.userId)); + return others.length === 1 ? others[0] : undefined; +}; + export const getDirectRoomAvatarUrl = ( mx: MatrixClient, room: Room, size: 32 | 96 = 32, useAuthentication = false ): string | undefined => { - const mxcUrl = room.getAvatarFallbackMember()?.getMxcAvatarUrl(); + const mxcUrl = getDmOtherMember(mx, room)?.getMxcAvatarUrl(); if (!mxcUrl) { return getRoomAvatarUrl(mx, room, size, useAuthentication); From 92e868890eca3baa28de72b5db93ade503e3b0c3 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Tue, 4 Aug 2026 10:19:43 +0200 Subject: [PATCH 042/135] feat(android): publish an Obtainium app config with each release --- .changeset/add-obtainium-app-config.md | 5 ++ .github/workflows/tauri-build.yml | 27 +++++++++++ README.md | 26 +++++++++++ scripts/obtainium-generate.js | 63 ++++++++++++++++++++++++++ 4 files changed, 121 insertions(+) create mode 100644 .changeset/add-obtainium-app-config.md create mode 100644 scripts/obtainium-generate.js diff --git a/.changeset/add-obtainium-app-config.md b/.changeset/add-obtainium-app-config.md new file mode 100644 index 000000000..40ad03bcf --- /dev/null +++ b/.changeset/add-obtainium-app-config.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Publish an `obtainium.json` app config with every release so Android builds can be installed and auto-updated through Obtainium. diff --git a/.github/workflows/tauri-build.yml b/.github/workflows/tauri-build.yml index 3d976d462..6d24d0820 100644 --- a/.github/workflows/tauri-build.yml +++ b/.github/workflows/tauri-build.yml @@ -408,6 +408,33 @@ jobs: gh release upload "$TAG" "$f" --clobber done + obtainium: + name: Publish Obtainium config + needs: [setup-release, android] + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: write + env: + TAG: ${{ needs.setup-release.outputs.tag }} + VERSION: ${{ needs.setup-release.outputs.version }} + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ needs.setup-release.outputs.ref }} + persist-credentials: false + + - name: Generate obtainium.json + shell: bash + run: node scripts/obtainium-generate.js "$VERSION" "$TAG" obtainium.json + + - name: Attach Obtainium config to release + shell: bash + env: + GH_TOKEN: ${{ github.token }} + run: gh release upload "$TAG" obtainium.json --clobber + ios: name: Build iOS (AltStore/SideStore) needs: setup-release diff --git a/README.md b/README.md index 787f27bee..a839b7e57 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,32 @@ The stable web app is available at [app.sable.moe](https://app.sable.moe/) and t You can also download our desktop app for Windows and Linux from [releases](https://github.com/SableClient/Sable/releases/latest). Release artifacts include build attestations, and desktop installations update automatically. +## Android (Obtainium) + +Android APKs are published to every release, and [Obtainium](https://obtainium.imranr.dev) keeps them updated straight from GitHub. Each release also ships an `obtainium.json` app config. Use it for the nightly channel, where prereleases and date-based version tracking have to be enabled to follow the rolling `nightly` tag. + +### Stable + +Add to Obtainium +  +App config +  +Download APK + +### Nightly + +App config +  +Download APK + +### Setup & install + +1. Install [Obtainium](https://github.com/ImranR98/Obtainium/releases/latest). +2. For stable, tap the button above, or add `https://github.com/SableClient/Sable` by hand under **Add App**. +3. For nightly, download the `obtainium.json` above and import it with **Import/Export → Import from file**. + +Android builds are produced by the `android` job in [`tauri-build.yml`](.github/workflows/tauri-build.yml), and the config by the `obtainium` job in the same workflow. + ## iOS (AltStore / SideStore) Sable iOS builds are distributed as unsigned IPAs through [AltStore](https://altstore.io) and [SideStore](https://sidestore.io). Each release publishes both the IPA and an `altstore-source.json` manifest — stable builds to the [latest GitHub release](https://github.com/SableClient/Sable/releases/latest), nightly builds to the [`nightly` GitHub release](https://github.com/SableClient/Sable/releases/tag/nightly). diff --git a/scripts/obtainium-generate.js b/scripts/obtainium-generate.js new file mode 100644 index 000000000..bd7ec703c --- /dev/null +++ b/scripts/obtainium-generate.js @@ -0,0 +1,63 @@ +#!/usr/bin/env node +//MISE hide=true +//MISE description="Generate obtainium.json for one-click app import" +/* oxlint-disable no-console */ + +import { writeFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import process from 'node:process'; + +const version = process.argv[2]; +const tag = process.argv[3] || `v${version}`; +const outputPath = process.argv[4] || 'obtainium.json'; + +if (!version) { + console.error('Usage: node scripts/obtainium-generate.js [tag] [output-path]'); + process.exit(1); +} + +const GITHUB_REPO = 'SableClient/Sable'; +const APK_NAME = `Sable-${version}-android-universal.apk`; +const APK_URL = `https://github.com/${GITHUB_REPO}/releases/download/${tag}/${APK_NAME}`; +const isNightly = tag === 'nightly'; + +// Obtainium fills in the rest from its own defaults on import. +const additionalSettings = { + about: 'An almost stable Matrix client', + ...(isNightly && { + includePrereleases: true, + // The nightly tag name never changes, so the re-uploaded APK's date is the + // only usable version, which in turn needs pseudo-versioning. + useLatestAssetDateAsReleaseDate: true, + releaseDateAsVersion: true, + versionDetection: false, + }), +}; + +const config = { + apps: [ + { + id: 'moe.sable.client', + url: `https://github.com/${GITHUB_REPO}`, + author: 'SableClient', + name: 'Sable', + installedVersion: null, + latestVersion: version, + apkUrls: JSON.stringify([[APK_NAME, APK_URL]]), + otherAssetUrls: '[]', + preferredApkIndex: 0, + additionalSettings: JSON.stringify(additionalSettings), + lastUpdateCheck: null, + pinned: false, + categories: ['Communication'], + releaseDate: null, + changeLog: null, + overrideSource: 'GitHub', + allowIdChange: false, + pendingRepoRenameUrl: null, + }, + ], +}; + +writeFileSync(resolve(outputPath), JSON.stringify(config, null, 2) + '\n'); +console.log(`Generated ${outputPath}`); From 04365c3313f7d28910eaa2592a1e63773d65fbdb Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Tue, 4 Aug 2026 10:28:47 +0200 Subject: [PATCH 043/135] fix: persist MSC4461 profiles --- src/app/hooks/usePerMessageProfile.test.ts | 101 ++++++++++++++ src/app/hooks/usePerMessageProfile.ts | 147 +++++++++------------ 2 files changed, 162 insertions(+), 86 deletions(-) create mode 100644 src/app/hooks/usePerMessageProfile.test.ts diff --git a/src/app/hooks/usePerMessageProfile.test.ts b/src/app/hooks/usePerMessageProfile.test.ts new file mode 100644 index 000000000..5b0058c37 --- /dev/null +++ b/src/app/hooks/usePerMessageProfile.test.ts @@ -0,0 +1,101 @@ +import { describe, expect, it, vi } from 'vitest'; + +import type { MatrixClient } from '$types/matrix-sdk'; +import { MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME } from '$unstable/prefixes'; +import { + addOrUpdatePerMessageProfile, + deletePerMessageProfile, + getAllPerMessageProfiles, + renamePerMessageProfile, + type PerMessageProfileIndexMsc4461, + type PerMessageProfileMsc4461, +} from './usePerMessageProfile'; + +function createMatrixClient(profiles: PerMessageProfileMsc4461[] = []) { + const accountData = new Map(); + accountData.set(MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME, { + type: 'm.per_message_profiles', + content: { profiles }, + } satisfies PerMessageProfileIndexMsc4461); + + const mx = { + getAccountData: vi.fn<(eventType: string) => { getContent: () => unknown } | undefined>( + (eventType) => { + const content = accountData.get(eventType); + return content === undefined ? undefined : { getContent: () => content }; + } + ), + setAccountData: vi.fn<(eventType: string, content: unknown) => Promise>( + async (eventType, content) => { + accountData.set(eventType, content); + } + ), + deleteAccountData: vi.fn<(eventType: string) => Promise>(async (eventType) => { + accountData.delete(eventType); + }), + } as unknown as MatrixClient; + + return { accountData, mx }; +} + +const profile = (id: string): PerMessageProfileMsc4461 => ({ + id, + displayname: `Profile ${id}`, + trigger: { prefix: [] }, +}); + +describe('profile persistence', () => { + it('creates and updates profiles', async () => { + const original = profile('first'); + const { mx } = createMatrixClient([original]); + const replacement = { ...original, displayname: 'Replacement' }; + + await addOrUpdatePerMessageProfile(mx, replacement); + await addOrUpdatePerMessageProfile(mx, profile('second')); + + await expect(getAllPerMessageProfiles(mx)).resolves.toEqual([replacement, profile('second')]); + expect(original.displayname).toBe('Profile first'); + }); + + it('awaits account-data writes', async () => { + let completeWrite!: () => void; + const mx = { + getAccountData: vi.fn<() => undefined>(() => undefined), + setAccountData: vi.fn<() => Promise>( + () => + new Promise((resolve) => { + completeWrite = resolve; + }) + ), + } as unknown as MatrixClient; + const saving = addOrUpdatePerMessageProfile(mx, profile('profile-id')); + let saved = false; + void saving.then(() => { + saved = true; + }); + + await Promise.resolve(); + expect(saved).toBe(false); + + completeWrite(); + await saving; + }); + + it('deletes profiles', async () => { + const { mx } = createMatrixClient([profile('first'), profile('second')]); + + await deletePerMessageProfile(mx, 'first'); + + await expect(getAllPerMessageProfiles(mx)).resolves.toEqual([profile('second')]); + }); + + it('renames profiles', async () => { + const { mx } = createMatrixClient([profile('old-id')]); + + await renamePerMessageProfile(mx, 'old-id', 'new-id'); + + await expect(getAllPerMessageProfiles(mx)).resolves.toEqual([ + { ...profile('old-id'), id: 'new-id' }, + ]); + }); +}); diff --git a/src/app/hooks/usePerMessageProfile.ts b/src/app/hooks/usePerMessageProfile.ts index 608c6c14a..dace4f4bb 100644 --- a/src/app/hooks/usePerMessageProfile.ts +++ b/src/app/hooks/usePerMessageProfile.ts @@ -95,6 +95,27 @@ export type PerMessageProfileMsc4461 = { compat?: AccountDataCompatVersion; }; +function getPerMessageProfileIndex(mx: MatrixClient): PerMessageProfileIndexMsc4461 | undefined { + return mx + .getAccountData( + MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME as Parameters< + typeof mx.getAccountData + >[0] + ) + ?.getContent() as PerMessageProfileIndexMsc4461 | undefined; +} + +async function savePerMessageProfileIndex(mx: MatrixClient, profiles: PerMessageProfileMsc4461[]) { + await mx.setAccountData( + MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME as Parameters< + typeof mx.setAccountData + >[0], + { type: 'm.per_message_profiles', content: { profiles } } as Parameters< + typeof mx.setAccountData + >[1] + ); +} + export function convertPmpToMsc4461( mx: MatrixClient, profile: PerMessageProfile @@ -469,15 +490,7 @@ export async function getPerMessageProfileById( mx: MatrixClient, id: string ): Promise { - let index = mx.getAccountData( - MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME as Parameters< - typeof mx.getAccountData - >[0] - ); - - return index - ? (index.getContent() as PerMessageProfileIndexMsc4461).content.profiles.find((p) => p.id == id) - : undefined; + return getPerMessageProfileIndex(mx)?.content.profiles.find((profile) => profile.id === id); } /** @@ -510,11 +523,7 @@ async function getPerMessageProfileByIdDeprecated( export async function getAllPerMessageProfiles( mx: MatrixClient ): Promise { - let profileListIndex = mx.getAccountData( - MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME as Parameters< - typeof mx.getAccountData - >[0] - ); + let profileListIndex = getPerMessageProfileIndex(mx); if (!profileListIndex) { const profileData = mx.getAccountData( @@ -541,34 +550,28 @@ export async function getAllPerMessageProfiles( msc4461Index.content.profiles.push(migratedProfile); }); - await mx.setAccountData( - MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME as Parameters< - typeof mx.setAccountData - >[0], - msc4461Index as Parameters[1] - ); + await savePerMessageProfileIndex(mx, msc4461Index.content.profiles); - profileListIndex = mx.getAccountData( - MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME as Parameters< - typeof mx.getAccountData - >[0] - ); + profileListIndex = getPerMessageProfileIndex(mx) ?? msc4461Index; // delete old records await mx.deleteAccountData( 'fyi.cisnt.permessageprofile.index' as Parameters[0] ); - profiles.forEach(async (profile) => { - if (!profile) return; - await mx.deleteAccountData( - `fyi.cisnt.permessageprofile.${profile.id}` as Parameters[0] - ); - }); + await Promise.all( + profiles + .filter((profile): profile is PerMessageProfile => profile !== undefined) + .map((profile) => + mx.deleteAccountData( + `fyi.cisnt.permessageprofile.${profile.id}` as Parameters[0] + ) + ) + ); } if (!profileListIndex) return []; - return (profileListIndex.getContent() as PerMessageProfileIndexMsc4461).content.profiles; + return profileListIndex.content.profiles; } /** @@ -581,48 +584,16 @@ export async function addOrUpdatePerMessageProfile( mx: MatrixClient, profile: PerMessageProfileMsc4461 ) { - let profileListIndex = mx.getAccountData( - MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME as Parameters< - typeof mx.getAccountData - >[0] - ); + const profiles = getPerMessageProfileIndex(mx)?.content.profiles ?? []; + const existingIndex = profiles.findIndex((existingProfile) => existingProfile.id === profile.id); + const updatedProfiles = + existingIndex === -1 + ? [...profiles, profile] + : profiles.map((existingProfile) => + existingProfile.id === profile.id ? profile : existingProfile + ); - const newIndex = (profileListIndex?.getContent() as - | PerMessageProfileIndexMsc4461 - | undefined) || { type: 'm.per_message_profiles', content: { profiles: [] } }; - - const foundProfile = newIndex.content.profiles.findIndex((p) => p.id === profile.id); - if (foundProfile !== -1) { - newIndex.content.profiles[foundProfile] = profile; - } else { - newIndex.content.profiles.push(profile); - } - mx.setAccountData( - MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME as Parameters< - typeof mx.setAccountData - >[0], - newIndex as Parameters[1] - ); -} - -/** - * remove a id from the index of profile ids, used when deleting a profile to - * remove the id from the list of profiles, so it doesn't show up in the list of profiles to manage anymore. - * The actual profile data is also removed when deleting a profile, but this function is only responsible - * for removing the id from the index. - * @param mx the matrix client - * @param id the id to drop from the index - */ -async function dropIdFromIndex(mx: MatrixClient, id: string) { - const profileListIndex = mx.getAccountData( - `${ACCOUNT_DATA_PREFIX}.index` as Parameters[0] - ); - const profileIds = profileListIndex?.getContent()?.profileIds || []; - const newProfileIds = profileIds.filter((profileId: string) => profileId !== id); - await mx.setAccountData( - `${ACCOUNT_DATA_PREFIX}.index` as Parameters[0], - { profileIds: newProfileIds } as Parameters[1] - ); + await savePerMessageProfileIndex(mx, updatedProfiles); } async function getRoomsUsingProfile(mx: MatrixClient, profileId: string): Promise { @@ -662,7 +633,7 @@ export async function setCurrentlyUsedPerMessageProfileIdForRoom( if (reset) { associations.delete(roomId); - mx.setAccountData( + await mx.setAccountData( `${ACCOUNT_DATA_PREFIX}.roomassociation` as Parameters[0], { associations: associationsMapToObject(associations) } as Parameters< typeof mx.setAccountData @@ -674,7 +645,7 @@ export async function setCurrentlyUsedPerMessageProfileIdForRoom( throw new Error("profile Id is empty, yet it isn't a reset"); } associations.set(roomId, { profileId, validUntil }); - mx.setAccountData( + await mx.setAccountData( `${ACCOUNT_DATA_PREFIX}.roomassociation` as Parameters[0], { associations: associationsMapToObject(associations) } as Parameters< typeof mx.setAccountData @@ -692,7 +663,7 @@ export async function setCurrentlyUsedPerMessageProfileIdForAccount( reset?: boolean ) { if (reset) { - mx.deleteAccountData( + await mx.deleteAccountData( `${ACCOUNT_DATA_PREFIX}.globalassociation` as Parameters[0] ); return; @@ -703,7 +674,7 @@ export async function setCurrentlyUsedPerMessageProfileIdForAccount( const association: PerMessageProfileRoomAssociation = { profileId, validUntil }; - mx.setAccountData( + await mx.setAccountData( `${ACCOUNT_DATA_PREFIX}.globalassociation` as Parameters[0], { association: association } as Parameters[1] ); @@ -767,11 +738,13 @@ async function dropPerMessageProfileRoomAssociations(mx: MatrixClient, id: strin */ export async function deletePerMessageProfile(mx: MatrixClient, id: string) { await dropPerMessageProfileRoomAssociations(mx, id); - await mx.setAccountData( - `${ACCOUNT_DATA_PREFIX}.${id}` as Parameters[0], - {} + const profiles = getPerMessageProfileIndex(mx)?.content.profiles; + if (!profiles) return; + + await savePerMessageProfileIndex( + mx, + profiles.filter((profile) => profile.id !== id) ); - await dropIdFromIndex(mx, id); } /** @@ -782,13 +755,15 @@ export async function deletePerMessageProfile(mx: MatrixClient, id: string) { * @param newId the id it will be moved to */ export async function renamePerMessageProfile(mx: MatrixClient, oldId: string, newId: string) { - const profile = await getPerMessageProfileById(mx, oldId); - if (!profile) { + const profiles = getPerMessageProfileIndex(mx)?.content.profiles; + if (!profiles?.some((profile) => profile.id === oldId)) { throw new Error('Profile not found'); } - const newProfile = { ...profile, id: newId }; - await addOrUpdatePerMessageProfile(mx, newProfile); - await deletePerMessageProfile(mx, oldId); + + await savePerMessageProfileIndex( + mx, + profiles.map((profile) => (profile.id === oldId ? { ...profile, id: newId } : profile)) + ); } /** From 17ab045ce172002c0c9b1ff123ec812d859fccd2 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Tue, 4 Aug 2026 11:03:46 +0200 Subject: [PATCH 044/135] fix: correct MSC4461 account data --- src/app/hooks/usePerMessageProfile.test.ts | 42 +++++++- src/app/hooks/usePerMessageProfile.ts | 119 ++++++++++----------- 2 files changed, 96 insertions(+), 65 deletions(-) diff --git a/src/app/hooks/usePerMessageProfile.test.ts b/src/app/hooks/usePerMessageProfile.test.ts index 5b0058c37..7b31cace8 100644 --- a/src/app/hooks/usePerMessageProfile.test.ts +++ b/src/app/hooks/usePerMessageProfile.test.ts @@ -7,16 +7,14 @@ import { deletePerMessageProfile, getAllPerMessageProfiles, renamePerMessageProfile, - type PerMessageProfileIndexMsc4461, type PerMessageProfileMsc4461, } from './usePerMessageProfile'; function createMatrixClient(profiles: PerMessageProfileMsc4461[] = []) { const accountData = new Map(); accountData.set(MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME, { - type: 'm.per_message_profiles', - content: { profiles }, - } satisfies PerMessageProfileIndexMsc4461); + profiles, + }); const mx = { getAccountData: vi.fn<(eventType: string) => { getContent: () => unknown } | undefined>( @@ -81,6 +79,42 @@ describe('profile persistence', () => { await saving; }); + it('reads nested payloads', async () => { + const nestedProfile = profile('nested'); + const { accountData, mx } = createMatrixClient(); + accountData.set(MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME, { + type: 'm.per_message_profiles', + content: { profiles: [nestedProfile] }, + }); + + await expect(getAllPerMessageProfiles(mx)).resolves.toEqual([nestedProfile]); + }); + + it('migrates legacy profiles', async () => { + const { accountData, mx } = createMatrixClient(); + accountData.delete(MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME); + accountData.set('fyi.cisnt.permessageprofile.index', { profileIds: ['legacy'] }); + accountData.set('fyi.cisnt.permessageprofile.legacy', { + id: 'legacy', + name: 'Legacy profile', + }); + + const migratedProfile = { + id: 'legacy', + displayname: 'Legacy profile', + trigger: { prefix: [], 'net.f0rest.suffix': [], 'net.f0rest.circumfix': [] }, + }; + + await expect(getAllPerMessageProfiles(mx)).resolves.toEqual([migratedProfile]); + expect( + accountData.get(MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME) + ).toEqual({ + profiles: [migratedProfile], + }); + expect(accountData.has('fyi.cisnt.permessageprofile.index')).toBe(false); + expect(accountData.has('fyi.cisnt.permessageprofile.legacy')).toBe(false); + }); + it('deletes profiles', async () => { const { mx } = createMatrixClient([profile('first'), profile('second')]); diff --git a/src/app/hooks/usePerMessageProfile.ts b/src/app/hooks/usePerMessageProfile.ts index dace4f4bb..4914aa7ef 100644 --- a/src/app/hooks/usePerMessageProfile.ts +++ b/src/app/hooks/usePerMessageProfile.ts @@ -55,10 +55,7 @@ export type ProfileTrigger = { * a per message profile */ export type PerMessageProfileIndexMsc4461 = { - type: 'm.per_message_profiles'; - content: { - profiles: PerMessageProfileMsc4461[]; - }; + profiles: PerMessageProfileMsc4461[]; }; /** @@ -95,14 +92,28 @@ export type PerMessageProfileMsc4461 = { compat?: AccountDataCompatVersion; }; +function isPerMessageProfileIndex(content: unknown): content is PerMessageProfileIndexMsc4461 { + return ( + typeof content === 'object' && + content !== null && + 'profiles' in content && + Array.isArray(content.profiles) + ); +} + function getPerMessageProfileIndex(mx: MatrixClient): PerMessageProfileIndexMsc4461 | undefined { - return mx + const content = mx .getAccountData( MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME as Parameters< typeof mx.getAccountData >[0] ) - ?.getContent() as PerMessageProfileIndexMsc4461 | undefined; + ?.getContent(); + + if (isPerMessageProfileIndex(content)) return content; + if (typeof content !== 'object' || content === null || !('content' in content)) return undefined; + + return isPerMessageProfileIndex(content.content) ? content.content : undefined; } async function savePerMessageProfileIndex(mx: MatrixClient, profiles: PerMessageProfileMsc4461[]) { @@ -110,9 +121,7 @@ async function savePerMessageProfileIndex(mx: MatrixClient, profiles: PerMessage MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME as Parameters< typeof mx.setAccountData >[0], - { type: 'm.per_message_profiles', content: { profiles } } as Parameters< - typeof mx.setAccountData - >[1] + { profiles } as Parameters[1] ); } @@ -490,7 +499,7 @@ export async function getPerMessageProfileById( mx: MatrixClient, id: string ): Promise { - return getPerMessageProfileIndex(mx)?.content.profiles.find((profile) => profile.id === id); + return getPerMessageProfileIndex(mx)?.profiles.find((profile) => profile.id === id); } /** @@ -513,6 +522,39 @@ async function getPerMessageProfileByIdDeprecated( return profile ? (profile.getContent() as unknown as PerMessageProfile) : undefined; } +async function migrateLegacyPerMessageProfiles( + mx: MatrixClient +): Promise { + const profileIndex = mx.getAccountData( + `${ACCOUNT_DATA_PREFIX}.index` as Parameters[0] + ); + if (!profileIndex) return undefined; + + const profileIds = (profileIndex.getContent() as PerMessageProfileIndex).profileIds ?? []; + const legacyProfiles = await Promise.all( + profileIds.map((id) => getPerMessageProfileByIdDeprecated(mx, id)) + ); + const profiles = legacyProfiles + .filter((profile): profile is PerMessageProfile => profile !== undefined) + .map((profile) => convertPmpToMsc4461(mx, profile)); + + await savePerMessageProfileIndex(mx, profiles); + await Promise.all([ + mx.deleteAccountData( + `${ACCOUNT_DATA_PREFIX}.index` as Parameters[0] + ), + ...legacyProfiles + .filter((profile): profile is PerMessageProfile => profile !== undefined) + .map((profile) => + mx.deleteAccountData( + `${ACCOUNT_DATA_PREFIX}.${profile.id}` as Parameters[0] + ) + ), + ]); + + return profiles; +} + /** * getting an array of all PerMessageProfile's saved in the account data * @@ -523,55 +565,10 @@ async function getPerMessageProfileByIdDeprecated( export async function getAllPerMessageProfiles( mx: MatrixClient ): Promise { - let profileListIndex = getPerMessageProfileIndex(mx); + const profiles = getPerMessageProfileIndex(mx)?.profiles; + if (profiles) return profiles; - if (!profileListIndex) { - const profileData = mx.getAccountData( - `${ACCOUNT_DATA_PREFIX}.index` as Parameters[0] - ); - if (!profileData) return []; - - const msc4461Index: PerMessageProfileIndexMsc4461 = { - type: 'm.per_message_profiles', - content: { - profiles: [], - }, - }; - - const profileIds = (profileData?.getContent() as PerMessageProfileIndex)?.profileIds || []; - const profiles = await Promise.all( - profileIds.map((id) => getPerMessageProfileByIdDeprecated(mx, id)) - ); - - profiles.forEach((profile) => { - if (!profile) return; - - const migratedProfile = convertPmpToMsc4461(mx, profile); - msc4461Index.content.profiles.push(migratedProfile); - }); - - await savePerMessageProfileIndex(mx, msc4461Index.content.profiles); - - profileListIndex = getPerMessageProfileIndex(mx) ?? msc4461Index; - - // delete old records - await mx.deleteAccountData( - 'fyi.cisnt.permessageprofile.index' as Parameters[0] - ); - - await Promise.all( - profiles - .filter((profile): profile is PerMessageProfile => profile !== undefined) - .map((profile) => - mx.deleteAccountData( - `fyi.cisnt.permessageprofile.${profile.id}` as Parameters[0] - ) - ) - ); - } - - if (!profileListIndex) return []; - return profileListIndex.content.profiles; + return (await migrateLegacyPerMessageProfiles(mx)) ?? []; } /** @@ -584,7 +581,7 @@ export async function addOrUpdatePerMessageProfile( mx: MatrixClient, profile: PerMessageProfileMsc4461 ) { - const profiles = getPerMessageProfileIndex(mx)?.content.profiles ?? []; + const profiles = getPerMessageProfileIndex(mx)?.profiles ?? []; const existingIndex = profiles.findIndex((existingProfile) => existingProfile.id === profile.id); const updatedProfiles = existingIndex === -1 @@ -738,7 +735,7 @@ async function dropPerMessageProfileRoomAssociations(mx: MatrixClient, id: strin */ export async function deletePerMessageProfile(mx: MatrixClient, id: string) { await dropPerMessageProfileRoomAssociations(mx, id); - const profiles = getPerMessageProfileIndex(mx)?.content.profiles; + const profiles = getPerMessageProfileIndex(mx)?.profiles; if (!profiles) return; await savePerMessageProfileIndex( @@ -755,7 +752,7 @@ export async function deletePerMessageProfile(mx: MatrixClient, id: string) { * @param newId the id it will be moved to */ export async function renamePerMessageProfile(mx: MatrixClient, oldId: string, newId: string) { - const profiles = getPerMessageProfileIndex(mx)?.content.profiles; + const profiles = getPerMessageProfileIndex(mx)?.profiles; if (!profiles?.some((profile) => profile.id === oldId)) { throw new Error('Profile not found'); } From 3867b924a543c0e0c8898547ffcfec34974679b2 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Tue, 4 Aug 2026 11:09:23 +0200 Subject: [PATCH 045/135] fix: keep the iOS nightly patch version inside u32 --- .github/scripts/set-tauri-version.mjs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/.github/scripts/set-tauri-version.mjs b/.github/scripts/set-tauri-version.mjs index 11d21e552..79d7ab02e 100644 --- a/.github/scripts/set-tauri-version.mjs +++ b/.github/scripts/set-tauri-version.mjs @@ -34,15 +34,24 @@ const sanitizedVersion = version.replace(/^(\d+\.\d+\.\d+-nightly)\.(.+)$/, (_, return `${prefix}.${sanitizedBuild}`; }); -// AltStore/SideStore only compare CFBundleShortVersionString, which Tauri fills with -// major.minor.patch, so the nightly stamp has to go in patch to be seen as a new version. +// The nightly stamp goes into patch as a Unix timestamp, since the YYMMDDHHMMSS form +// overflows the u32 Tauri parses each version part into. let stampedVersion = sanitizedVersion; if (foldNightlyIntoPatch) { - stampedVersion = sanitizedVersion.replace(/^(\d+\.\d+)\.\d+-nightly\.(\d+)$/, '$1.$2'); - if (stampedVersion === sanitizedVersion) { + const nightly = /^(\d+\.\d+)\.\d+-nightly\.(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/.exec( + sanitizedVersion + ); + if (!nightly) { console.error(`--apple-short-version needs a nightly version (got: ${sanitizedVersion})`); process.exit(1); } + const [, base, yy, mm, dd, hh, min, sec] = nightly; + const patch = Date.UTC(2000 + +yy, mm - 1, +dd, +hh, +min, +sec) / 1000; + if (!Number.isInteger(patch) || patch <= 0 || patch > 0xffffffff) { + console.error(`Nightly stamp does not map to a u32 patch version: ${sanitizedVersion}`); + process.exit(1); + } + stampedVersion = `${base}.${patch}`; } config.version = stampedVersion; From 5595ed14c1d5fff20f3c71c35d8bb49f07701f9b Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Tue, 4 Aug 2026 11:10:04 +0200 Subject: [PATCH 046/135] feat(android): add a one-tap Obtainium button for the nightly channel --- README.md | 8 +++++--- scripts/obtainium-generate.js | 5 ++--- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index a839b7e57..1a91de73e 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ Android APKs are published to every release, and [Obtainium](https://obtainium.i ### Stable -Add to Obtainium +Add to Obtainium   App config   @@ -27,6 +27,8 @@ Android APKs are published to every release, and [Obtainium](https://obtainium.i ### Nightly +Add to Obtainium +  App config   Download APK @@ -34,8 +36,8 @@ Android APKs are published to every release, and [Obtainium](https://obtainium.i ### Setup & install 1. Install [Obtainium](https://github.com/ImranR98/Obtainium/releases/latest). -2. For stable, tap the button above, or add `https://github.com/SableClient/Sable` by hand under **Add App**. -3. For nightly, download the `obtainium.json` above and import it with **Import/Export → Import from file**. +2. Tap **Add to Obtainium** above. Stable opens the **Add App** page prefilled with `https://github.com/SableClient/Sable`; nightly opens an import prompt, since it carries the prerelease and version-tracking settings the rolling `nightly` tag needs. +3. Or download the `obtainium.json` for either channel and import it with **Import/Export → Import from file**. Android builds are produced by the `android` job in [`tauri-build.yml`](.github/workflows/tauri-build.yml), and the config by the `obtainium` job in the same workflow. diff --git a/scripts/obtainium-generate.js b/scripts/obtainium-generate.js index bd7ec703c..dd669a7c0 100644 --- a/scripts/obtainium-generate.js +++ b/scripts/obtainium-generate.js @@ -21,13 +21,12 @@ const APK_NAME = `Sable-${version}-android-universal.apk`; const APK_URL = `https://github.com/${GITHUB_REPO}/releases/download/${tag}/${APK_NAME}`; const isNightly = tag === 'nightly'; -// Obtainium fills in the rest from its own defaults on import. +// Obtainium fills in every other setting from its own defaults on import. const additionalSettings = { about: 'An almost stable Matrix client', + // The nightly tag name never changes, so the version has to come from the date instead. ...(isNightly && { includePrereleases: true, - // The nightly tag name never changes, so the re-uploaded APK's date is the - // only usable version, which in turn needs pseudo-versioning. useLatestAssetDateAsReleaseDate: true, releaseDateAsVersion: true, versionDetection: false, From 26fa607cdc7cdbf052338e023b8e9e9bb68f6b35 Mon Sep 17 00:00:00 2001 From: Nadia Kulczycka Date: Tue, 4 Aug 2026 09:22:27 +0000 Subject: [PATCH 047/135] Remove old, non-generated obtainium scripts --- obtainium-source-nightly.json | 11 ----------- obtainium-source-stable.json | 11 ----------- 2 files changed, 22 deletions(-) delete mode 100644 obtainium-source-nightly.json delete mode 100644 obtainium-source-stable.json diff --git a/obtainium-source-nightly.json b/obtainium-source-nightly.json deleted file mode 100644 index 9d4e3bdd0..000000000 --- a/obtainium-source-nightly.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "apps": [ - { - "id": "moe.sable.client", - "url": "https://github.com/SableClient/Sable", - "author": "SableClient", - "name": "Sable", - "additionalSettings": "{\"includePrereleases\":true,\"fallbackToOlderReleases\":false,\"filterReleaseTitlesByRegEx\":\"\",\"filterReleaseNotesByRegEx\":\"\",\"verifyLatestTag\":false,\"dontSortReleasesList\":false,\"useLatestAssetDateAsReleaseDate\":true,\"trackOnly\":false,\"versionExtractionRegEx\":\"\",\"matchGroupToUse\":\"\",\"versionDetection\":true,\"releaseDateAsVersion\":true,\"useVersionCodeAsOSVersion\":false,\"apkFilterRegEx\":\"\",\"invertAPKFilter\":false,\"autoApkFilterByArch\":true,\"appName\":\"Sable\",\"shizukuPretendToBeGooglePlay\":false,\"exemptFromBackgroundUpdates\":false,\"skipUpdateNotifications\":false,\"about\":\"An almost stable Matrix client\",\"appAuthor\":\"SableClient\"}" - } - ] -} \ No newline at end of file diff --git a/obtainium-source-stable.json b/obtainium-source-stable.json deleted file mode 100644 index 9d4e3bdd0..000000000 --- a/obtainium-source-stable.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "apps": [ - { - "id": "moe.sable.client", - "url": "https://github.com/SableClient/Sable", - "author": "SableClient", - "name": "Sable", - "additionalSettings": "{\"includePrereleases\":true,\"fallbackToOlderReleases\":false,\"filterReleaseTitlesByRegEx\":\"\",\"filterReleaseNotesByRegEx\":\"\",\"verifyLatestTag\":false,\"dontSortReleasesList\":false,\"useLatestAssetDateAsReleaseDate\":true,\"trackOnly\":false,\"versionExtractionRegEx\":\"\",\"matchGroupToUse\":\"\",\"versionDetection\":true,\"releaseDateAsVersion\":true,\"useVersionCodeAsOSVersion\":false,\"apkFilterRegEx\":\"\",\"invertAPKFilter\":false,\"autoApkFilterByArch\":true,\"appName\":\"Sable\",\"shizukuPretendToBeGooglePlay\":false,\"exemptFromBackgroundUpdates\":false,\"skipUpdateNotifications\":false,\"about\":\"An almost stable Matrix client\",\"appAuthor\":\"SableClient\"}" - } - ] -} \ No newline at end of file From 9f3e6120087eba2e0f16c94e9e74a34406b0a8f9 Mon Sep 17 00:00:00 2001 From: Nadia Kulczycka Date: Tue, 4 Aug 2026 09:25:59 +0000 Subject: [PATCH 048/135] Test nightly button --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index c524157a2..e1a5bd6c5 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,8 @@ Android APKs are published to every release, and [Obtainium](https://obtainium.i ### Nightly +Add to Obtainium +  App config   Download APK From f3031a692babe7883f86de651deba581544d3bf6 Mon Sep 17 00:00:00 2001 From: Nadia Kulczycka Date: Tue, 4 Aug 2026 09:33:11 +0000 Subject: [PATCH 049/135] Remove old Obtainium docs --- README.md | 39 ++++++++------------------------------- 1 file changed, 8 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index e1a5bd6c5..b4c66d24c 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,14 @@ Android APKs are published to every release, and [Obtainium](https://obtainium.i Android builds are produced by the `android` job in [`tauri-build.yml`](.github/workflows/tauri-build.yml), and the config by the `obtainium` job in the same workflow. +### Relevant variables and switching between Nightly and Stable + +Relevant variable differences between Nightly and Stable: +- *Include prereleases* - `true` for Nightly, `false` for Stable +- *Fallback to older releases* - `false` for Nightly, `true` for Stable +- *Use latest asset upload as release date* - `true` for Nightly, `false` for Stable (this is due to Nightly builds being uploaded to one release instead of creating new ones) +- *Use release date as version string (pseudo-version)* - `true` for Nightly, `false` for Stable (this is due to Nightly builds being uploaded to one release instead of creating new ones) + ## iOS (AltStore / SideStore) Sable iOS builds are distributed as unsigned IPAs through [AltStore](https://altstore.io) and [SideStore](https://sidestore.io). Each release publishes both the IPA and an `altstore-source.json` manifest — stable builds to the [latest GitHub release](https://github.com/SableClient/Sable/releases/latest), nightly builds to the [`nightly` GitHub release](https://github.com/SableClient/Sable/releases/tag/nightly). @@ -73,37 +81,6 @@ Sable iOS builds are distributed as unsigned IPAs through [AltStore](https://alt iOS builds are produced by the `ios` job in [`tauri-build.yml`](.github/workflows/tauri-build.yml) and track the same `dev`/`v*` triggers as desktop builds. -## Android (Obtainium) - -### Nightly Source - -Add to Obtainium -  - -### Stable Source - -Add to Obtainium -  - -### Setup and install - -1. Set up [Obtainium](https://wiki.obtainium.imranr.dev/) on your device. -2. Add the Sable source by either: - - Tapping one of the buttons above. - - Importing one of the JSON files: - - [Nightly](https://raw.githubusercontent.com/SableClient/Sable/refs/heads/dev/obtainium-source-nightly.json) - - [Stable](https://raw.githubusercontent.com/SableClient/Sable/refs/heads/dev/obtainium-source-stable.json) - - Adding it manually - use as the GitHub link and follow the section below with regards to setting app variables -3. Install Sable from the source. - -### Relevant variables and switching between Nightly and Stable - -Relevant variable differences between Nightly and Stable: -- *Include prereleases* - `true` for Nightly, `false` for Stable -- *Fallback to older releases* - `false` for Nightly, `true` for Stable -- *Use latest asset upload as release date* - `true` for Nightly, `false` for Stable (this is due to Nightly builds being uploaded to one release instead of creating new ones) -- *Use release date as version string (pseudo-version)* - `true` for Nightly, `false` for Stable (this is due to Nightly builds being uploaded to one release instead of creating new ones) - ## Self-hosting You have a few options for self hosting, you can: 1. Run the prebuilt docker container. From 48ce6fad80ba2ff2847d450732f9f80e73616a47 Mon Sep 17 00:00:00 2001 From: "sable-actions[bot]" <268226691+sable-actions[bot]@users.noreply.github.com> Date: Tue, 4 Aug 2026 09:49:33 +0000 Subject: [PATCH 050/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index 8da9f6137..c8a890c60 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -20,12 +20,12 @@ "screenshots": [], "versions": [ { - "version": "1.20.1", - "buildVersion": "1.20.1.260804074029", - "date": "2026-08-04T07:54:01Z", - "size": 18915703, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260804074029-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260804074029" + "version": "1.20.1785835654", + "buildVersion": "1.20.1785835654", + "date": "2026-08-04T09:49:30Z", + "size": 18915483, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260804092734-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260804092734" } ], "appPermissions": { From 64bea056056460aeb4960e226363fcaab7cac706 Mon Sep 17 00:00:00 2001 From: "sable-actions[bot]" <268226691+sable-actions[bot]@users.noreply.github.com> Date: Tue, 4 Aug 2026 10:16:29 +0000 Subject: [PATCH 051/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index c8a890c60..973b390cf 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -20,12 +20,12 @@ "screenshots": [], "versions": [ { - "version": "1.20.1785835654", - "buildVersion": "1.20.1785835654", - "date": "2026-08-04T09:49:30Z", - "size": 18915483, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260804092734-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260804092734" + "version": "1.20.1785837863", + "buildVersion": "1.20.1785837863", + "date": "2026-08-04T10:16:27Z", + "size": 18915503, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260804100423-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260804100423" } ], "appPermissions": { From e41569b31d23dce2bff1bd9a7da0ea2fc8b4dbdb Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Tue, 4 Aug 2026 14:51:53 +0200 Subject: [PATCH 052/135] revert: bundle PulseAudio for CEF --- flake.nix | 2 -- mise.tauri.toml | 1 - nfpm.yaml | 2 -- scripts/cef/package.sh | 30 ------------------------------ 4 files changed, 35 deletions(-) diff --git a/flake.nix b/flake.nix index c476cc8cc..7960c6dbe 100644 --- a/flake.nix +++ b/flake.nix @@ -173,8 +173,6 @@ openssl dbus dbus.dev - libpulseaudio - alsa-lib libayatana-appindicator gst_all_1.gstreamer gst_all_1.gst-plugins-base diff --git a/mise.tauri.toml b/mise.tauri.toml index 273eca6d9..116c3f729 100644 --- a/mise.tauri.toml +++ b/mise.tauri.toml @@ -18,7 +18,6 @@ android-sdk = "22.0" "apt:build-essential" = "latest" "apt:file" = "latest" "apt:libayatana-appindicator3-dev" = "latest" -"apt:libpulse0" = "latest" "apt:libgtk-3-dev" = "latest" "apt:librsvg2-dev" = "latest" "apt:libsoup-3.0-dev" = "latest" diff --git a/nfpm.yaml b/nfpm.yaml index 1ce757bce..e6b78751e 100644 --- a/nfpm.yaml +++ b/nfpm.yaml @@ -31,7 +31,6 @@ overrides: - libdrm2 - libxkbcommon0 - libasound2 - - libpulse0 - libcups2 - xdg-utils - xwayland @@ -45,7 +44,6 @@ overrides: - libdrm - libxkbcommon - alsa-lib - - pulseaudio-libs - cups-libs - xdg-utils - xorg-x11-server-Xwayland diff --git a/scripts/cef/package.sh b/scripts/cef/package.sh index 8c8e101e9..d1be2d9ab 100755 --- a/scripts/cef/package.sh +++ b/scripts/cef/package.sh @@ -74,35 +74,6 @@ stage_appindicator() { done } -# Bundle the PulseAudio client and its audio dependencies for CEF. -stage_pulseaudio() { - local dest="$1" main - mkdir -p "$dest" - main="$(ldconfig -p 2>/dev/null | awk '$1=="libpulse.so.0"{v=$NF} END{print v}')" - [ -n "$main" ] || main="$(find /usr/lib /usr/lib64 /lib -name libpulse.so.0 2>/dev/null | sort | tail -n1)" - if [ -z "$main" ] || [ ! -e "$main" ]; then - echo "warning: libpulse.so.0 not found; PulseAudio disabled in the AppImage" >&2 - return 0 - fi - local -A seen=() - local -a queue=("$main") - local lib dep - while [ "${#queue[@]}" -gt 0 ]; do - lib="${queue[-1]}" - queue=("${queue[@]:0:${#queue[@]}-1}") - [ -n "$lib" ] && [ -e "$lib" ] || continue - seen["$lib"]=1 - while read -r dep; do - [ -n "$dep" ] && [ -z "${seen[$dep]:-}" ] || continue - seen["$dep"]=1 - queue+=("$dep") - done < <(ldd "$lib" 2>/dev/null | awk '/=>/ {print $3}' | grep -iE 'pulse|sndfile|asyncns|FLAC|ogg|vorbis|opus|mpg123|mp3lame|lame|speexdsp' || true) - done - for lib in "${!seen[@]}"; do - cp -Lf "$lib" "$dest/$(basename "$lib")" - done -} - write_desktop() { cat > "$1" < Date: Tue, 4 Aug 2026 14:52:35 +0200 Subject: [PATCH 053/135] fix(linux): use updated CEF media permissions --- src-tauri/Cargo.lock | 2 +- src-tauri/src/main.rs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index f58607f69..5eb62202e 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -6957,7 +6957,7 @@ dependencies = [ [[package]] name = "tauri-runtime-cef" version = "0.1.0" -source = "git+https://github.com/SableClient/tauri-runtime-cef?branch=main#23464067ddcfe61239e41faeb26e1ce200ff3242" +source = "git+https://github.com/SableClient/tauri-runtime-cef?branch=main#4f83d8c428bf5560f402c5d2b10aecaad8f244cd" dependencies = [ "base64 0.22.1", "cef", diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 8fdd89c9e..32206257c 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -5,7 +5,7 @@ fn prompt_cef_permission(message: String, tx: std::sync::mpsc::Sender) { use gtk::glib; use gtk::prelude::*; - use gtk::{ButtonsType, DialogFlags, MessageDialog, MessageType, ResponseType}; + use gtk::{ButtonsType, DialogFlags, MessageDialog, MessageType, ResponseType, WindowPosition}; // Non-blocking: show() + response signal instead of run(). // dialog.run() blocks the GLib main loop, which CEF's message pump @@ -19,6 +19,7 @@ fn prompt_cef_permission(message: String, tx: std::sync::mpsc::Sender) { &message, ); dialog.set_title("Permission request"); + dialog.set_position(WindowPosition::CenterAlways); let tx = std::cell::RefCell::new(Some(tx)); dialog.connect_response(move |dlg, response| { From 1ab717f9a33807f1ee37fb90d9eefc9f59e76080 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Tue, 4 Aug 2026 14:49:16 +0200 Subject: [PATCH 054/135] fix(dm): refresh direct chat avatars --- src/app/hooks/useGroupDMMembers.ts | 16 ++------ src/app/hooks/useRoomMeta.test.tsx | 32 ++++++++++++++++ src/app/hooks/useRoomMeta.ts | 12 ++++++ .../pages/client/sidebar/DirectDMsList.tsx | 13 +++---- src/app/utils/room/display.test.ts | 38 +++++++++++++++++++ src/app/utils/room/display.ts | 25 +++++++----- 6 files changed, 106 insertions(+), 30 deletions(-) create mode 100644 src/app/utils/room/display.test.ts diff --git a/src/app/hooks/useGroupDMMembers.ts b/src/app/hooks/useGroupDMMembers.ts index f8015727b..c0ad51694 100644 --- a/src/app/hooks/useGroupDMMembers.ts +++ b/src/app/hooks/useGroupDMMembers.ts @@ -1,5 +1,5 @@ import type { MatrixClient, Room } from '$types/matrix-sdk'; -import { getMemberDisplayName, isBridgeBot } from '$utils/room/display'; +import { getMemberDisplayName } from '$utils/room/display'; export type GroupMemberInfo = { userId: string; @@ -20,23 +20,13 @@ export const useGroupDMMembers = ( const currentUserId = mx.getUserId(); const members = room .getMembers() - .filter( - (member) => - member.membership === 'join' && - member.userId !== currentUserId && - !isBridgeBot(member.userId) - ); + .filter((member) => member.membership === 'join' && member.userId !== currentUserId); const recentSenderRank = new Map(); const events = room.getLiveTimeline().getEvents(); for (let index = events.length - 1; index >= 0; index -= 1) { const sender = events[index]?.getSender(); - if ( - sender && - sender !== currentUserId && - !isBridgeBot(sender) && - !recentSenderRank.has(sender) - ) { + if (sender && sender !== currentUserId && !recentSenderRank.has(sender)) { recentSenderRank.set(sender, recentSenderRank.size); } } diff --git a/src/app/hooks/useRoomMeta.test.tsx b/src/app/hooks/useRoomMeta.test.tsx index 1150b55b4..6e13a4300 100644 --- a/src/app/hooks/useRoomMeta.test.tsx +++ b/src/app/hooks/useRoomMeta.test.tsx @@ -72,4 +72,36 @@ describe('useRoomAvatar', () => { expect(result.current).toBeUndefined(); }); + + it('updates a DM avatar when its member state arrives after the sidebar rendered', () => { + const member = { + getMxcAvatarUrl: () => AVATAR_MXC, + membership: 'join', + userId: '@alice:server', + }; + const { room, client, wrapper } = makeRoom('!dm:server'); + const roomEvents = new EventEmitter(); + let members = [{ membership: 'join', userId: '@me:server' }]; + Object.assign(room, { + getMember: (userId: string) => members.find((roomMember) => roomMember.userId === userId), + getMembers: () => members, + getAvatarFallbackMember: () => undefined, + on: roomEvents.on.bind(roomEvents), + removeListener: roomEvents.removeListener.bind(roomEvents), + }); + Object.assign(client, { + getAccountData: () => ({ getContent: () => ({ '@alice:server': [room.roomId] }) }), + getUserId: () => '@me:server', + }); + + const { result } = renderHook(() => useRoomAvatar(room, true), { wrapper }); + expect(result.current).toBeUndefined(); + + members = [{ membership: 'join', userId: '@me:server' }, member]; + act(() => { + roomEvents.emit(RoomStateEvent.Members); + }); + + expect(result.current).toBe(AVATAR_MXC); + }); }); diff --git a/src/app/hooks/useRoomMeta.ts b/src/app/hooks/useRoomMeta.ts index fdf8d8d93..c7fc53eba 100644 --- a/src/app/hooks/useRoomMeta.ts +++ b/src/app/hooks/useRoomMeta.ts @@ -25,6 +25,18 @@ const getRoomDisplayName = ( export const useRoomAvatar = (room: Room, dm?: boolean): string | undefined => { const mx = useMatrixClient(); const avatarEvent = useStateEvent(room, EventType.RoomAvatar); + const [, refreshDmAvatar] = useState(0); + + useEffect(() => { + if (!dm) return undefined; + + const updateAvatar = () => refreshDmAvatar((version) => version + 1); + room.on(RoomStateEvent.Members, updateAvatar); + + return () => { + room.removeListener(RoomStateEvent.Members, updateAvatar); + }; + }, [room, dm]); if (dm) { return getDmOtherMember(mx, room)?.getMxcAvatarUrl(); diff --git a/src/app/pages/client/sidebar/DirectDMsList.tsx b/src/app/pages/client/sidebar/DirectDMsList.tsx index e2ded23c2..9b35447e2 100644 --- a/src/app/pages/client/sidebar/DirectDMsList.tsx +++ b/src/app/pages/client/sidebar/DirectDMsList.tsx @@ -15,13 +15,13 @@ import { } from '$components/sidebar'; import { RoomAvatar } from '$components/room-avatar'; import { UserAvatar } from '$components/user-avatar'; -import { getDirectRoomAvatarUrl, getRoomAvatarUrl } from '$utils/room/display'; +import { getAvatarUrl, getDmOtherMember, getRoomAvatarUrl } from '$utils/room/display'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { nameInitials } from '$utils/common'; import { getCanonicalAliasOrRoomId, mxcUrlToHttp } from '$utils/matrix'; import { useSelectedOrLastRoom } from '$hooks/router/useSelectedRoom'; import { useGroupDMMembers } from '$hooks/useGroupDMMembers'; -import { useRoomName } from '$hooks/useRoomMeta'; +import { useRoomAvatar, useRoomName } from '$hooks/useRoomMeta'; import { useSidebarDirectRoomIds } from './useSidebarDirectRoomIds'; import * as css from './DirectDMsList.css'; @@ -43,11 +43,13 @@ function DMItem({ room, selected }: DMItemProps) { }; const roomName = useRoomName(room); + const dmAvatarMxc = useRoomAvatar(room, true); + const dmAvatarUrl = getAvatarUrl(mx, dmAvatarMxc, 96, useAuthentication); // Use already-synced room state only; sidebar rendering must not trigger member/profile requests. const groupMembers = useGroupDMMembers(mx, room, MAX_GROUP_MEMBERS); - const isGroupDM = groupMembers.length > 1; + const isGroupDM = !getDmOtherMember(mx, room) && groupMembers.length > 1; // Get unread info for badge const unread = roomToUnread.get(room.roomId); @@ -60,10 +62,7 @@ function DMItem({ room, selected }: DMItemProps) { ( diff --git a/src/app/utils/room/display.test.ts b/src/app/utils/room/display.test.ts new file mode 100644 index 000000000..5830acc08 --- /dev/null +++ b/src/app/utils/room/display.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from 'vitest'; +import type { MatrixClient, Room, RoomMember } from '$types/matrix-sdk'; +import { getDmOtherMember } from './display'; + +const makeMember = (userId: string, membership: 'join' | 'invite'): RoomMember => + ({ userId, membership }) as RoomMember; + +describe('getDmOtherMember', () => { + it('resolves an invited direct-chat participant from m.direct', () => { + const invitedMember = makeMember('@alice:example.org', 'invite'); + const room = { + getMember: (userId: string) => (userId === invitedMember.userId ? invitedMember : undefined), + getAvatarFallbackMember: () => undefined, + roomId: '!dm:example.org', + } as unknown as Room; + const mx = { + getAccountData: () => ({ getContent: () => ({ '@alice:example.org': [room.roomId] }) }), + getUserId: () => '@me:example.org', + } as unknown as MatrixClient; + + expect(getDmOtherMember(mx, room)).toBe(invitedMember); + }); + + it('uses the m.direct counterpart even when a bridge bot is also in the room', () => { + const counterpart = makeMember('@alice:example.org', 'join'); + const room = { + getMember: (userId: string) => (userId === counterpart.userId ? counterpart : undefined), + getAvatarFallbackMember: () => makeMember('@bridgebot:example.org', 'join'), + roomId: '!dm:example.org', + } as unknown as Room; + const mx = { + getAccountData: () => ({ getContent: () => ({ '@alice:example.org': [room.roomId] }) }), + getUserId: () => '@me:example.org', + } as unknown as MatrixClient; + + expect(getDmOtherMember(mx, room)).toBe(counterpart); + }); +}); diff --git a/src/app/utils/room/display.ts b/src/app/utils/room/display.ts index afe92e0b9..f4a7ac5cd 100644 --- a/src/app/utils/room/display.ts +++ b/src/app/utils/room/display.ts @@ -1,3 +1,4 @@ +import { EventType } from '$types/matrix-sdk'; import type { MatrixClient, Room, RoomMember } from '$types/matrix-sdk'; import { getMxIdLocalPart } from '$utils/matrix'; @@ -24,18 +25,22 @@ export const getRoomAvatarUrl = ( useAuthentication = false ): string | undefined => getAvatarUrl(mx, room.getMxcAvatarUrl(), size, useAuthentication); -// Bridges add a persistent bot member to 1:1 DM portals that the SDK counts as a real participant. -export const isBridgeBot = (userId: string): boolean => { - const localpart = userId.split(':')[0]?.substring(1) ?? ''; - return localpart.toLowerCase().endsWith('bot'); -}; - export const getDmOtherMember = (mx: MatrixClient, room: Room): RoomMember | undefined => { const currentUserId = mx.getUserId(); - const others = room - .getJoinedMembers() - .filter((member) => member.userId !== currentUserId && !isBridgeBot(member.userId)); - return others.length === 1 ? others[0] : undefined; + const mDirect = mx.getAccountData(EventType.Direct)?.getContent>(); + const directUserIds = Object.entries(mDirect ?? {}) + .filter( + ([userId, roomIds]) => + userId !== currentUserId && Array.isArray(roomIds) && roomIds.includes(room.roomId) + ) + .map(([userId]) => userId); + + if (directUserIds.length === 1) { + const member = room.getMember(directUserIds[0]!); + if (member?.membership === 'join' || member?.membership === 'invite') return member; + } + + return room.getAvatarFallbackMember(); }; export const getDirectRoomAvatarUrl = ( From ed6e3343e811d041b434daf48abaffef7129c1fe Mon Sep 17 00:00:00 2001 From: "sable-actions[bot]" <268226691+sable-actions[bot]@users.noreply.github.com> Date: Tue, 4 Aug 2026 13:10:54 +0000 Subject: [PATCH 055/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index 973b390cf..8d184d502 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -20,12 +20,12 @@ "screenshots": [], "versions": [ { - "version": "1.20.1785837863", - "buildVersion": "1.20.1785837863", - "date": "2026-08-04T10:16:27Z", - "size": 18915503, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260804100423-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260804100423" + "version": "1.20.1785848293", + "buildVersion": "1.20.1785848293", + "date": "2026-08-04T13:10:52Z", + "size": 18915660, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260804125813-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260804125813" } ], "appPermissions": { From 5f71e9e6b0bf1aa0f16199bcec2b1dc1ea9f0870 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Tue, 4 Aug 2026 16:24:36 +0200 Subject: [PATCH 056/135] fix(linux): update CEF custom protocol handling --- src-tauri/Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 5eb62202e..04e12cacc 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -6957,7 +6957,7 @@ dependencies = [ [[package]] name = "tauri-runtime-cef" version = "0.1.0" -source = "git+https://github.com/SableClient/tauri-runtime-cef?branch=main#4f83d8c428bf5560f402c5d2b10aecaad8f244cd" +source = "git+https://github.com/SableClient/tauri-runtime-cef?branch=main#7fee65dae5ebe19f4f9868226bdb75df0f678aac" dependencies = [ "base64 0.22.1", "cef", From 04ab99ae6a35c7e6285da12983236db6eb181308 Mon Sep 17 00:00:00 2001 From: "sable-actions[bot]" <268226691+sable-actions[bot]@users.noreply.github.com> Date: Tue, 4 Aug 2026 14:56:04 +0000 Subject: [PATCH 057/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index 8d184d502..4442af240 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -20,12 +20,12 @@ "screenshots": [], "versions": [ { - "version": "1.20.1785848293", - "buildVersion": "1.20.1785848293", - "date": "2026-08-04T13:10:52Z", - "size": 18915660, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260804125813-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260804125813" + "version": "1.20.1785854583", + "buildVersion": "1.20.1785854583", + "date": "2026-08-04T14:56:02Z", + "size": 18915560, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260804144303-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260804144303" } ], "appPermissions": { From 1a07373c2ed4a359e2ca401902ad778b4fa6d393 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Tue, 4 Aug 2026 16:59:14 +0200 Subject: [PATCH 058/135] Fix cached media range handling --- src-tauri/src/network/media_protocol.rs | 204 ++++++++++++++++++++---- 1 file changed, 175 insertions(+), 29 deletions(-) diff --git a/src-tauri/src/network/media_protocol.rs b/src-tauri/src/network/media_protocol.rs index 94a74f865..2fcf96f92 100644 --- a/src-tauri/src/network/media_protocol.rs +++ b/src-tauri/src/network/media_protocol.rs @@ -50,6 +50,8 @@ const MAX_CONCURRENT_DOWNLOAD_REQUESTS: usize = 6; const SESSION_WAIT: Duration = Duration::from_secs(5); const SESSION_REFRESH_WAIT: Duration = Duration::from_millis(2500); const MAX_CACHE_BYTES: u64 = 512 * 1024 * 1024; +// WRY's Android adapter copies custom-protocol bodies into a JNI byte array, so range +// responses must stay bounded even when WebView asks for the rest of a large video. const MAX_RANGE_CHUNK: u64 = 2 * 1024 * 1024; // Short: a 4xx stops being true once an unreachable remote server comes back. const NEGATIVE_CACHE_TTL: Duration = Duration::from_secs(600); @@ -1105,10 +1107,16 @@ async fn serve_range( .metadata() .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? .len(); - let Some((start, end)) = parse_range(&range_header, total) else { - return Ok(range_not_satisfiable(total)); + let (start, end) = match select_range(&range_header, total) { + RangeSelection::Partial { start, end } => (start, end), + RangeSelection::Ignore => { + let mut body = Vec::new(); + file.read_to_end(&mut body) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + return Ok(ok_response(body, &content_type)); + } + RangeSelection::Unsatisfiable => return Ok(range_not_satisfiable(total)), }; - let end = end.min(start.saturating_add(MAX_RANGE_CHUNK - 1)); let length = end - start + 1; let mut body = vec![0; length as usize]; file.seek(SeekFrom::Start(start)) @@ -1123,10 +1131,11 @@ async fn serve_range( fn serve_range_memory(body: &[u8], content_type: &str, range_header: &str) -> Response> { let total = body.len() as u64; - let Some((start, end)) = parse_range(range_header, total) else { - return range_not_satisfiable(total); + let (start, end) = match select_range(range_header, total) { + RangeSelection::Partial { start, end } => (start, end), + RangeSelection::Ignore => return ok_response(body.to_vec(), content_type), + RangeSelection::Unsatisfiable => return range_not_satisfiable(total), }; - let end = end.min(start.saturating_add(MAX_RANGE_CHUNK - 1)); partial_response( body[start as usize..=end as usize].to_vec(), content_type, @@ -1136,28 +1145,54 @@ fn serve_range_memory(body: &[u8], content_type: &str, range_header: &str) -> Re ) } -fn parse_range(range_header: &str, total: u64) -> Option<(u64, u64)> { +enum RangeSelection { + Partial { start: u64, end: u64 }, + Ignore, + Unsatisfiable, +} + +fn select_range(range_header: &str, total: u64) -> RangeSelection { if total == 0 { - return None; + return RangeSelection::Unsatisfiable; } - let spec = range_header.strip_prefix("bytes=")?; - let (start, end) = spec.split(',').next()?.trim().split_once('-')?; + let Some(spec) = range_header.strip_prefix("bytes=") else { + return RangeSelection::Unsatisfiable; + }; + if spec.contains(',') { + return RangeSelection::Ignore; + } + let Some((start, end)) = spec.trim().split_once('-') else { + return RangeSelection::Unsatisfiable; + }; let (start, end) = if start.is_empty() { - let suffix = end.parse::().ok()?; + let Ok(suffix) = end.parse::() else { + return RangeSelection::Unsatisfiable; + }; if suffix == 0 { - return None; + return RangeSelection::Unsatisfiable; } - (total.saturating_sub(suffix), total - 1) + let length = suffix.min(total).min(MAX_RANGE_CHUNK); + (total - length, total - 1) } else { - let start = start.parse::().ok()?; - let end = if end.is_empty() { + let Ok(start) = start.parse::() else { + return RangeSelection::Unsatisfiable; + }; + let requested_end = if end.is_empty() { total - 1 } else { - end.parse::().ok()?.min(total - 1) + let Ok(end) = end.parse::() else { + return RangeSelection::Unsatisfiable; + }; + end.min(total - 1) }; + let end = requested_end.min(start.saturating_add(MAX_RANGE_CHUNK - 1)); (start, end) }; - (start <= end && start < total).then_some((start, end)) + if start <= end && start < total { + RangeSelection::Partial { start, end } + } else { + RangeSelection::Unsatisfiable + } } // Trim oldest-first when the cache exceeds its byte budget. @@ -1242,11 +1277,22 @@ fn partial_response( } fn range_not_satisfiable(total: u64) -> Response> { - Response::builder() - .status(StatusCode::RANGE_NOT_SATISFIABLE) - .header(header::CONTENT_RANGE, format!("bytes */{total}")) - .body(Vec::new()) - .expect("failed to build 416 response") + let mut response = error_response(StatusCode::RANGE_NOT_SATISFIABLE); + let headers = response.headers_mut(); + headers.insert( + header::CONTENT_RANGE, + header::HeaderValue::from_str(&format!("bytes */{total}")) + .expect("valid 416 content range"), + ); + headers.insert( + header::CONTENT_LENGTH, + header::HeaderValue::from_static("0"), + ); + headers.insert( + header::ACCEPT_RANGES, + header::HeaderValue::from_static("bytes"), + ); + response } fn session_unavailable_response() -> Response> { @@ -1309,6 +1355,13 @@ mod tests { static TEST_CACHE_ID: AtomicU64 = AtomicU64::new(0); + fn selected_range(header: &str, total: u64) -> Option<(u64, u64)> { + match super::select_range(header, total) { + super::RangeSelection::Partial { start, end } => Some((start, end)), + _ => None, + } + } + fn test_session(origin: &str, token: &str, scope: &str, generation: u64) -> MediaSession { MediaSession { origin: origin.to_owned(), @@ -1832,11 +1885,28 @@ mod tests { } #[test] - fn parse_range_supports_video_metadata_and_seek_requests() { - assert_eq!(super::parse_range("bytes=0-499", 1000), Some((0, 499))); - assert_eq!(super::parse_range("bytes=500-", 1000), Some((500, 999))); - assert_eq!(super::parse_range("bytes=-200", 1000), Some((800, 999))); - assert_eq!(super::parse_range("bytes=990-5000", 1000), Some((990, 999))); + fn select_range_supports_video_metadata_and_seek_requests() { + assert_eq!(selected_range("bytes=0-499", 1000), Some((0, 499))); + assert_eq!(selected_range("bytes=500-", 1000), Some((500, 999))); + assert_eq!(selected_range("bytes=-200", 1000), Some((800, 999))); + assert_eq!(selected_range("bytes=990-5000", 1000), Some((990, 999))); + } + + #[test] + fn open_ended_ranges_are_capped_from_the_requested_offset() { + let total = super::MAX_RANGE_CHUNK * 2 + 100; + assert_eq!( + selected_range("bytes=0-", total), + Some((0, super::MAX_RANGE_CHUNK - 1)) + ); + assert_eq!( + selected_range(&format!("bytes={}-", super::MAX_RANGE_CHUNK), total), + Some((super::MAX_RANGE_CHUNK, super::MAX_RANGE_CHUNK * 2 - 1)) + ); + assert_eq!( + selected_range(&format!("bytes={}-", super::MAX_RANGE_CHUNK * 2), total), + Some((super::MAX_RANGE_CHUNK * 2, total - 1)) + ); } #[test] @@ -1847,9 +1917,27 @@ mod tests { "bytes=abc-def", "items=0-1", ] { - assert_eq!(super::parse_range(range, 1000), None, "{range}"); + assert!( + matches!( + super::select_range(range, 1000), + super::RangeSelection::Unsatisfiable + ), + "{range}" + ); } - assert_eq!(super::parse_range("bytes=0-0", 0), None); + assert!(matches!( + super::select_range("bytes=0-0", 0), + super::RangeSelection::Unsatisfiable + )); + } + + #[test] + fn multi_range_requests_fall_back_to_the_full_response() { + let body = [1_u8, 2, 3]; + let response = super::serve_range_memory(&body, "video/mp4", "bytes=0-0,2-2"); + + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.body(), &body); } #[test] @@ -1875,6 +1963,64 @@ mod tests { .unwrap(), format!("bytes 0-{}/{}", super::MAX_RANGE_CHUNK - 1, body.len()) ); + + let requested_suffix = super::MAX_RANGE_CHUNK + 100; + let response = + super::serve_range_memory(&body, "video/mp4", &format!("bytes=-{requested_suffix}")); + assert_eq!(response.body().len() as u64, super::MAX_RANGE_CHUNK); + let expected = format!( + "bytes {}-{}/{}", + body.len() as u64 - super::MAX_RANGE_CHUNK, + body.len() - 1, + body.len() + ); + assert_eq!( + response + .headers() + .get(header::CONTENT_RANGE) + .unwrap() + .to_str() + .unwrap(), + expected + ); + } + + #[test] + fn unsatisfiable_ranges_are_not_cacheable() { + let response = super::range_not_satisfiable(1000); + assert_eq!(response.status(), StatusCode::RANGE_NOT_SATISFIABLE); + assert_eq!( + response.headers().get(header::CONTENT_RANGE).unwrap(), + "bytes */1000" + ); + assert_eq!( + response.headers().get(header::CACHE_CONTROL).unwrap(), + "no-store" + ); + assert_eq!(response.headers().get(header::CONTENT_LENGTH).unwrap(), "0"); + } + + #[test] + fn partial_responses_include_webview_range_metadata() { + let response = super::serve_range_memory(&[0_u8; 100], "video/mp4", "bytes=10-19"); + + assert_eq!(response.status(), StatusCode::PARTIAL_CONTENT); + assert_eq!( + response.headers().get(header::CONTENT_TYPE).unwrap(), + "video/mp4" + ); + assert_eq!( + response.headers().get(header::CONTENT_LENGTH).unwrap(), + "10" + ); + assert_eq!( + response.headers().get(header::CONTENT_RANGE).unwrap(), + "bytes 10-19/100" + ); + assert_eq!( + response.headers().get(header::ACCEPT_RANGES).unwrap(), + "bytes" + ); } #[tokio::test] From 8183ab7b72658d725e61f3f0ead62c07d3bf860f Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Tue, 4 Aug 2026 17:59:12 +0200 Subject: [PATCH 059/135] fix(linux): pin corrected CEF protocol handling --- src-tauri/Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 04e12cacc..73883e1da 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -6957,7 +6957,7 @@ dependencies = [ [[package]] name = "tauri-runtime-cef" version = "0.1.0" -source = "git+https://github.com/SableClient/tauri-runtime-cef?branch=main#7fee65dae5ebe19f4f9868226bdb75df0f678aac" +source = "git+https://github.com/SableClient/tauri-runtime-cef?branch=main#73303ea183092837354819e828268efb6ffeb09e" dependencies = [ "base64 0.22.1", "cef", From 6ca2cdc4c761edff75a1299073209d90c19330ee Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Tue, 4 Aug 2026 18:09:53 +0200 Subject: [PATCH 060/135] fix(linux): pin HTTPS CEF media origin handling --- src-tauri/Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 73883e1da..570f200e5 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -6957,7 +6957,7 @@ dependencies = [ [[package]] name = "tauri-runtime-cef" version = "0.1.0" -source = "git+https://github.com/SableClient/tauri-runtime-cef?branch=main#73303ea183092837354819e828268efb6ffeb09e" +source = "git+https://github.com/SableClient/tauri-runtime-cef?branch=main#92d67142bf830fd983905da65a60a44665eee52d" dependencies = [ "base64 0.22.1", "cef", From db3b48838079cb7de1271e3e063f016278ca7755 Mon Sep 17 00:00:00 2001 From: "sable-actions[bot]" <268226691+sable-actions[bot]@users.noreply.github.com> Date: Tue, 4 Aug 2026 16:25:40 +0000 Subject: [PATCH 061/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index 4442af240..bc1c15b4a 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -20,12 +20,12 @@ "screenshots": [], "versions": [ { - "version": "1.20.1785854583", - "buildVersion": "1.20.1785854583", - "date": "2026-08-04T14:56:02Z", - "size": 18915560, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260804144303-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260804144303" + "version": "1.20.1785859899", + "buildVersion": "1.20.1785859899", + "date": "2026-08-04T16:25:37Z", + "size": 18915781, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260804161139-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260804161139" } ], "appPermissions": { From e155fdb1dc5c76e49c70ade51d47196536fb5c6a Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Tue, 4 Aug 2026 19:51:51 +0200 Subject: [PATCH 062/135] fix: use Alloy CEF media permissions --- scripts/cef/copy-libs.sh | 21 ++++++++++++--------- src-tauri/Cargo.lock | 2 +- src-tauri/src/main.rs | 2 +- 3 files changed, 14 insertions(+), 11 deletions(-) diff --git a/scripts/cef/copy-libs.sh b/scripts/cef/copy-libs.sh index e044e1133..d3a7f3dea 100755 --- a/scripts/cef/copy-libs.sh +++ b/scripts/cef/copy-libs.sh @@ -12,15 +12,6 @@ PROFILE="${1:-debug}" ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" DEST="${2:-$ROOT/src-tauri/target/$PROFILE}" -CEF_DIR="$( - find "$ROOT/src-tauri/target/$PROFILE/build" \ - -type d -name cef_linux_x86_64 -print -quit 2>/dev/null || true -)" -if [ -z "$CEF_DIR" ]; then - echo "❌ CEF dist not found under target/$PROFILE/build — build with --features cef first." >&2 - exit 1 -fi - CEF_VERSION="$(awk ' /^\[\[package\]\]$/ { in_cef=0 } /^name = "cef"$/ { in_cef=1 } @@ -36,6 +27,18 @@ if [ -z "$CEF_VERSION" ]; then fi CEF_MAJOR="${CEF_VERSION%%.*}" +CEF_DIR="" +while IFS= read -r candidate; do + if grep -q "^#define CEF_VERSION_MAJOR $CEF_MAJOR$" "$candidate/include/cef_version.h" 2>/dev/null; then + CEF_DIR="$candidate" + break + fi +done < <(find "$ROOT/src-tauri/target/$PROFILE/build" -type d -name cef_linux_x86_64 2>/dev/null) +if [ -z "$CEF_DIR" ]; then + echo "❌ CEF $CEF_MAJOR dist not found under target/$PROFILE/build — build with --features cef first." >&2 + exit 1 +fi + CEF_LIB="$CEF_DIR/libcef.so" if [ ! -f "$CEF_LIB" ]; then echo "❌ libcef.so not found in $CEF_DIR." >&2 diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 570f200e5..1b20ed318 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -6957,7 +6957,7 @@ dependencies = [ [[package]] name = "tauri-runtime-cef" version = "0.1.0" -source = "git+https://github.com/SableClient/tauri-runtime-cef?branch=main#92d67142bf830fd983905da65a60a44665eee52d" +source = "git+https://github.com/SableClient/tauri-runtime-cef?branch=main#c0d9ff8ecf0eac8504c1947932274e7fe7d9fb8c" dependencies = [ "base64 0.22.1", "cef", diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 32206257c..34d6e6d07 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -131,7 +131,7 @@ fn main() { .cloned() .collect(); - if permission_kinds.is_empty() { + if permission_kinds.is_empty() || permission_kinds.len() != request.kinds.len() { return responder.deny(DenyReason::NoPolicy); } From 5cfed8ac52bc02053eb51e55d253af777353fba2 Mon Sep 17 00:00:00 2001 From: illuc Date: Tue, 4 Aug 2026 21:07:02 +0300 Subject: [PATCH 063/135] Ran `nix fmt` to make treefmt happy --- flake.nix | 474 +++++++++++++++++++++++++++--------------------------- 1 file changed, 240 insertions(+), 234 deletions(-) diff --git a/flake.nix b/flake.nix index 7960c6dbe..f16db7134 100644 --- a/flake.nix +++ b/flake.nix @@ -13,8 +13,9 @@ }; }; - outputs = inputs @ {flake-parts, ...}: - flake-parts.lib.mkFlake {inherit inputs;} { + outputs = + inputs@{ flake-parts, ... }: + flake-parts.lib.mkFlake { inherit inputs; } { imports = [ inputs.git-hooks.flakeModule inputs.treefmt-nix.flakeModule @@ -27,24 +28,26 @@ "aarch64-darwin" ]; - perSystem = { - inputs', - config, - system, - lib, - ... - }: let - pkgs = import inputs.nixpkgs { - inherit system; + perSystem = + { + inputs', + config, + system, + lib, + ... + }: + let + pkgs = import inputs.nixpkgs { + inherit system; - config = { - allowUnfree = true; - android_sdk.accept_license = true; + config = { + allowUnfree = true; + android_sdk.accept_license = true; + }; }; - }; - rust = ( - with inputs'.fenix.packages; + rust = ( + with inputs'.fenix.packages; combine [ stable.toolchain targets.aarch64-linux-android.stable.rust-std @@ -52,138 +55,140 @@ targets.armv7-linux-androideabi.stable.rust-std targets.i686-linux-android.stable.rust-std ] - ); + ); - platformVersion = "36"; - systemImageType = "default"; - currentPath = builtins.getEnv "PWD"; - androidEnv = pkgs.androidenv.override {licenseAccepted = true;}; - androidComp = ( - androidEnv.composeAndroidPackages { - cmdLineToolsVersion = "8.0"; - includeNDK = true; - buildToolsVersions = ["35.0.0"]; + platformVersion = "36"; + systemImageType = "default"; + currentPath = builtins.getEnv "PWD"; + androidEnv = pkgs.androidenv.override { licenseAccepted = true; }; + androidComp = ( + androidEnv.composeAndroidPackages { + cmdLineToolsVersion = "8.0"; + includeNDK = true; + buildToolsVersions = [ "35.0.0" ]; - platformVersions = [ - "30" - platformVersion - ]; - includeEmulator = true; - includeSystemImages = true; - systemImageTypes = [ - systemImageType - ]; - abiVersions = [ - "x86" - "x86_64" - "armeabi-v7a" - "arm64-v8a" - ]; - cmakeVersions = ["3.10.2"]; - } - ); - android-sdk = pkgs.android-studio.withSdk androidComp.androidsdk; + platformVersions = [ + "30" + platformVersion + ]; + includeEmulator = true; + includeSystemImages = true; + systemImageTypes = [ + systemImageType + ]; + abiVersions = [ + "x86" + "x86_64" + "armeabi-v7a" + "arm64-v8a" + ]; + cmakeVersions = [ "3.10.2" ]; + } + ); + android-sdk = pkgs.android-studio.withSdk androidComp.androidsdk; - self = inputs.self; + self = inputs.self; - packageJson = builtins.fromJSON (builtins.readFile ./package.json); + packageJson = builtins.fromJSON (builtins.readFile ./package.json); - nodejs = pkgs.nodejs_24; - pnpm = pkgs.pnpm_10; - pnpmConfigHook = pkgs.pnpmConfigHook.override {inherit pnpm;}; + nodejs = pkgs.nodejs_24; + pnpm = pkgs.pnpm_10; + pnpmConfigHook = pkgs.pnpmConfigHook.override { inherit pnpm; }; - pnpmNativeBuildInputs = [ - pkgs.pkg-config - nodejs - pnpm - pnpmConfigHook - ]; + pnpmNativeBuildInputs = [ + pkgs.pkg-config + nodejs + pnpm + pnpmConfigHook + ]; - mkPnpmDeps = { - src, - version, - pnpmInstallFlags, - }: - pkgs.fetchPnpmDeps { - inherit - pnpm - src - version - pnpmInstallFlags - ; - pname = "sable"; - fetcherVersion = 3; - hash = "sha256-9lHy7/+hVET5c9Mt3F9DvrkW97DMxTISJsrklK/Ls2c="; - }; - - mkPnpmCheck = name: script: - pkgs.stdenv.mkDerivation (finalAttrs: { - pname = "sable-${name}"; - inherit (packageJson) version; - src = lib.cleanSource ./.; - - pnpmInstallFlags = ["--ignore-scripts"]; - - pnpmDeps = mkPnpmDeps { - inherit (finalAttrs) src version pnpmInstallFlags; + mkPnpmDeps = + { + src, + version, + pnpmInstallFlags, + }: + pkgs.fetchPnpmDeps { + inherit + pnpm + src + version + pnpmInstallFlags + ; + pname = "sable"; + fetcherVersion = 3; + hash = "sha256-9lHy7/+hVET5c9Mt3F9DvrkW97DMxTISJsrklK/Ls2c="; }; - nativeBuildInputs = pnpmNativeBuildInputs; + mkPnpmCheck = + name: script: + pkgs.stdenv.mkDerivation (finalAttrs: { + pname = "sable-${name}"; + inherit (packageJson) version; + src = lib.cleanSource ./.; - buildPhase = '' - runHook preBuild - pnpm run ${script} - runHook postBuild - ''; + pnpmInstallFlags = [ "--ignore-scripts" ]; - installPhase = '' - runHook preInstall - touch $out - runHook postInstall - ''; + pnpmDeps = mkPnpmDeps { + inherit (finalAttrs) src version pnpmInstallFlags; + }; - doCheck = false; - }); + nativeBuildInputs = pnpmNativeBuildInputs; - nativeBuildInputs = with pkgs; [ - pkg-config - gobject-introspection - cargo - cargo-tauri - nodejs - xdg-utils - desktop-file-utils - wrapGAppsHook3 - ]; + buildPhase = '' + runHook preBuild + pnpm run ${script} + runHook postBuild + ''; - buildInputs = with pkgs; [ - at-spi2-atk - atkmm - cairo - gdk-pixbuf - glib - glib-networking - gtk3 - gsettings-desktop-schemas - harfbuzz - librsvg - libsoup_3 - pango - webkitgtk_4_1 - openssl - dbus - dbus.dev - libayatana-appindicator - gst_all_1.gstreamer - gst_all_1.gst-plugins-base - gst_all_1.gst-plugins-good - gst_all_1.gst-plugins-bad - gst_all_1.gst-plugins-ugly - gst_all_1.gst-libav - android-sdk - ]; + installPhase = '' + runHook preInstall + touch $out + runHook postInstall + ''; - defaultPackages = [ + doCheck = false; + }); + + nativeBuildInputs = with pkgs; [ + pkg-config + gobject-introspection + cargo + cargo-tauri + nodejs + xdg-utils + desktop-file-utils + wrapGAppsHook3 + ]; + + buildInputs = with pkgs; [ + at-spi2-atk + atkmm + cairo + gdk-pixbuf + glib + glib-networking + gtk3 + gsettings-desktop-schemas + harfbuzz + librsvg + libsoup_3 + pango + webkitgtk_4_1 + openssl + dbus + dbus.dev + libayatana-appindicator + gst_all_1.gstreamer + gst_all_1.gst-plugins-base + gst_all_1.gst-plugins-good + gst_all_1.gst-plugins-bad + gst_all_1.gst-plugins-ugly + gst_all_1.gst-libav + android-sdk + ]; + + defaultPackages = [ nodejs pnpm rust @@ -200,112 +205,113 @@ pkgs.nixd pkgs.jdk ]; - in { - treefmt = { - projectRootFile = "flake.nix"; - programs = { - nixfmt.enable = true; - oxfmt.enable = true; - }; - settings.global.excludes = [ - "dist" - "node_modules" - "pnpm-lock.yaml" - "pnpm-workspace.yaml" - "package.json" - "LICENSE" - "CHANGELOG.md" - "./changeset" - ]; - }; - pre-commit.settings.hooks = { + in + { treefmt = { - enable = true; - package = config.treefmt.build.wrapper; - }; - }; - - packages.sable = pkgs.stdenv.mkDerivation (finalAttrs: { - pname = "sable"; - inherit (packageJson) version; - src = lib.cleanSource ./.; - - # ignoring knope for building - pnpmInstallFlags = ["--ignore-scripts"]; - - pnpmDeps = mkPnpmDeps { - inherit (finalAttrs) src version pnpmInstallFlags; - }; - - nativeBuildInputs = pnpmNativeBuildInputs; - - env.VITE_BUILD_HASH = self.shortRev or self.dirtyShortRev or ""; - env.SABLE_BUILD_FLAVOR = "stable"; - - buildPhase = '' - runHook preBuild - pnpm run build - runHook postBuild - ''; - - installPhase = '' - runHook preInstall - cp -r dist $out - runHook postInstall - ''; - }); - - packages.android-emulator = androidEnv.emulateApp { - name = "emulate-sable"; - platformVersion = platformVersion; - abiVersion = "x86_64"; # arm64-v8a - systemImageType = systemImageType; - }; - - packages.default = config.packages.sable; - - checks = { - build = config.packages.sable; - lint = mkPnpmCheck "lint" "lint"; - fmt = mkPnpmCheck "fmt" "fmt:check"; - test = mkPnpmCheck "test" "test:run"; - typecheck = mkPnpmCheck "typecheck" "typecheck"; - knip = mkPnpmCheck "knip" "knip"; - }; - - devShells = { - default = pkgs.mkShell { - inherit buildInputs nativeBuildInputs; - - packages = defaultPackages; - - LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath (nativeBuildInputs ++ buildInputs); - - GIO_EXTRA_MODULES = "${pkgs.glib-networking}/lib/gio/modules"; - GST_PLUGIN_SYSTEM_PATH = "${pkgs.gst_all_1.gst-plugins-base}/lib/gstreamer-1.0:${pkgs.gst_all_1.gst-plugins-good}/lib/gstreamer-1.0:${pkgs.gst_all_1.gst-plugins-bad}/lib/gstreamer-1.0"; - - RUST_SRC_PATH = "${pkgs.rust.packages.stable.rustPlatform.rustLibSrc}"; - }; - - android = pkgs.mkShell { - inherit buildInputs nativeBuildInputs; - - packages = defaultPackages ++ [ - android-sdk + projectRootFile = "flake.nix"; + programs = { + nixfmt.enable = true; + oxfmt.enable = true; + }; + settings.global.excludes = [ + "dist" + "node_modules" + "pnpm-lock.yaml" + "pnpm-workspace.yaml" + "package.json" + "LICENSE" + "CHANGELOG.md" + "./changeset" ]; + }; + pre-commit.settings.hooks = { + treefmt = { + enable = true; + package = config.treefmt.build.wrapper; + }; + }; - LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath (nativeBuildInputs ++ buildInputs); + packages.sable = pkgs.stdenv.mkDerivation (finalAttrs: { + pname = "sable"; + inherit (packageJson) version; + src = lib.cleanSource ./.; - ANDROID_HOME = "${androidComp.androidsdk}/libexec/android-sdk"; - ANDROID_SDK_ROOT = "${androidComp.androidsdk}/libexec/android-sdk"; - ANDROID_NDK_ROOT = "${androidComp.androidsdk}/libexec/android-sdk/ndk-bundle"; + # ignoring knope for building + pnpmInstallFlags = [ "--ignore-scripts" ]; - GIO_EXTRA_MODULES = "${pkgs.glib-networking}/lib/gio/modules"; - GST_PLUGIN_SYSTEM_PATH = "${pkgs.gst_all_1.gst-plugins-base}/lib/gstreamer-1.0:${pkgs.gst_all_1.gst-plugins-good}/lib/gstreamer-1.0:${pkgs.gst_all_1.gst-plugins-bad}/lib/gstreamer-1.0"; - - RUST_SRC_PATH = "${pkgs.rust.packages.stable.rustPlatform.rustLibSrc}"; + pnpmDeps = mkPnpmDeps { + inherit (finalAttrs) src version pnpmInstallFlags; + }; + + nativeBuildInputs = pnpmNativeBuildInputs; + + env.VITE_BUILD_HASH = self.shortRev or self.dirtyShortRev or ""; + env.SABLE_BUILD_FLAVOR = "stable"; + + buildPhase = '' + runHook preBuild + pnpm run build + runHook postBuild + ''; + + installPhase = '' + runHook preInstall + cp -r dist $out + runHook postInstall + ''; + }); + + packages.android-emulator = androidEnv.emulateApp { + name = "emulate-sable"; + platformVersion = platformVersion; + abiVersion = "x86_64"; # arm64-v8a + systemImageType = systemImageType; + }; + + packages.default = config.packages.sable; + + checks = { + build = config.packages.sable; + lint = mkPnpmCheck "lint" "lint"; + fmt = mkPnpmCheck "fmt" "fmt:check"; + test = mkPnpmCheck "test" "test:run"; + typecheck = mkPnpmCheck "typecheck" "typecheck"; + knip = mkPnpmCheck "knip" "knip"; + }; + + devShells = { + default = pkgs.mkShell { + inherit buildInputs nativeBuildInputs; + + packages = defaultPackages; + + LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath (nativeBuildInputs ++ buildInputs); + + GIO_EXTRA_MODULES = "${pkgs.glib-networking}/lib/gio/modules"; + GST_PLUGIN_SYSTEM_PATH = "${pkgs.gst_all_1.gst-plugins-base}/lib/gstreamer-1.0:${pkgs.gst_all_1.gst-plugins-good}/lib/gstreamer-1.0:${pkgs.gst_all_1.gst-plugins-bad}/lib/gstreamer-1.0"; + + RUST_SRC_PATH = "${pkgs.rust.packages.stable.rustPlatform.rustLibSrc}"; + }; + + android = pkgs.mkShell { + inherit buildInputs nativeBuildInputs; + + packages = defaultPackages ++ [ + android-sdk + ]; + + LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath (nativeBuildInputs ++ buildInputs); + + ANDROID_HOME = "${androidComp.androidsdk}/libexec/android-sdk"; + ANDROID_SDK_ROOT = "${androidComp.androidsdk}/libexec/android-sdk"; + ANDROID_NDK_ROOT = "${androidComp.androidsdk}/libexec/android-sdk/ndk-bundle"; + + GIO_EXTRA_MODULES = "${pkgs.glib-networking}/lib/gio/modules"; + GST_PLUGIN_SYSTEM_PATH = "${pkgs.gst_all_1.gst-plugins-base}/lib/gstreamer-1.0:${pkgs.gst_all_1.gst-plugins-good}/lib/gstreamer-1.0:${pkgs.gst_all_1.gst-plugins-bad}/lib/gstreamer-1.0"; + + RUST_SRC_PATH = "${pkgs.rust.packages.stable.rustPlatform.rustLibSrc}"; + }; }; }; - }; }; } From 828d538ea84985fd4f2093fd97b08decfa8eb6c1 Mon Sep 17 00:00:00 2001 From: illuc Date: Tue, 4 Aug 2026 21:17:04 +0300 Subject: [PATCH 064/135] nix: updated the pnpm deps hash --- flake.nix | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flake.nix b/flake.nix index f16db7134..7c7ae9b96 100644 --- a/flake.nix +++ b/flake.nix @@ -117,7 +117,7 @@ ; pname = "sable"; fetcherVersion = 3; - hash = "sha256-9lHy7/+hVET5c9Mt3F9DvrkW97DMxTISJsrklK/Ls2c="; + hash = "sha256-1siT4fB6ty2azmWXe5L40EFUdk0th59qIdARUB0cVOc="; }; mkPnpmCheck = From 27957acbb835b1615ae8f36a68bb3ebb94716b5a Mon Sep 17 00:00:00 2001 From: "sable-actions[bot]" <268226691+sable-actions[bot]@users.noreply.github.com> Date: Tue, 4 Aug 2026 21:53:53 +0000 Subject: [PATCH 065/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index bc1c15b4a..dad708dcf 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -20,12 +20,12 @@ "screenshots": [], "versions": [ { - "version": "1.20.1785859899", - "buildVersion": "1.20.1785859899", - "date": "2026-08-04T16:25:37Z", - "size": 18915781, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260804161139-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260804161139" + "version": "1.20.1785879693", + "buildVersion": "1.20.1785879693", + "date": "2026-08-04T21:53:51Z", + "size": 18915857, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260804214133-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260804214133" } ], "appPermissions": { From 86ae35751676bb763404eeaf7d4fb93da5a546da Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Wed, 5 Aug 2026 08:16:44 +0200 Subject: [PATCH 066/135] fix: avoid member hydration after failed load --- src/app/hooks/useRoomMembers.test.tsx | 35 +++++++++++++++++++++++++++ src/app/hooks/useRoomMembers.ts | 6 +++-- 2 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 src/app/hooks/useRoomMembers.test.tsx diff --git a/src/app/hooks/useRoomMembers.test.tsx b/src/app/hooks/useRoomMembers.test.tsx new file mode 100644 index 000000000..162126c2e --- /dev/null +++ b/src/app/hooks/useRoomMembers.test.tsx @@ -0,0 +1,35 @@ +import { renderHook, waitFor } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; +import type { MatrixClient, Room, RoomMember } from '$types/matrix-sdk'; + +const { hydrateAllRoomMembers } = vi.hoisted(() => ({ + hydrateAllRoomMembers: vi.fn<() => Promise>().mockResolvedValue(undefined), +})); + +vi.mock('$client/roomMemberHydration', () => ({ hydrateAllRoomMembers })); + +import { useRoomMembers } from './useRoomMembers'; + +describe('useRoomMembers', () => { + it('does not retry with a full roster request when the SDK member load fails', async () => { + const room = { + roomId: '!room:example.org', + getMembers: () => [] as RoomMember[], + loadMembersIfNeeded: vi + .fn<() => Promise>() + .mockRejectedValue(new Error('NetworkError')), + } as unknown as Room; + const mx = { + getRoom: () => room, + on: vi.fn<() => void>(), + removeListener: vi.fn<() => void>(), + } as unknown as MatrixClient; + + renderHook(() => useRoomMembers(mx, room.roomId)); + + await waitFor(() => expect(room.loadMembersIfNeeded).toHaveBeenCalledOnce()); + await Promise.resolve(); + + expect(hydrateAllRoomMembers).not.toHaveBeenCalled(); + }); +}); diff --git a/src/app/hooks/useRoomMembers.ts b/src/app/hooks/useRoomMembers.ts index 4469680d6..f953e3ea2 100644 --- a/src/app/hooks/useRoomMembers.ts +++ b/src/app/hooks/useRoomMembers.ts @@ -28,9 +28,11 @@ export const useRoomMembers = (mx: MatrixClient, roomId: string, enabled = true) loadingMembers = false; if (disposed) return; updateMemberList(); - void hydrateAllRoomMembers(mx, roomId).then(() => updateMemberList()); }; - room.loadMembersIfNeeded().then(stopLoading, stopLoading); + room.loadMembersIfNeeded().then(() => { + stopLoading(); + void hydrateAllRoomMembers(mx, roomId).then(() => updateMemberList()); + }, stopLoading); } const handleStateEvent = (event: MatrixEvent) => { From 1c31c9a9d1aefe94524cb4b43d847bedabb3cc76 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Wed, 5 Aug 2026 10:52:32 +0200 Subject: [PATCH 067/135] fix(e2ee): Prepare room encryption before sending --- src/app/features/room/RoomInput.tsx | 11 ++++++++++- src/app/features/room/message/EncryptedContent.tsx | 9 +++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 27126a362..ed8b3ae4c 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -274,6 +274,7 @@ export const getReplyContent = ( const log = createLogger('RoomInput'); const debugLog = createDebugLogger('RoomInput'); +const ENCRYPTION_PREPARATION_INTERVAL_MS = 60_000; interface ReplyEventContent { 'm.relates_to'?: IEventRelation; } @@ -497,9 +498,17 @@ export const RoomInput = forwardRef( const handlePaste = useFilePasteHandler(handleFiles); const dropZoneVisible = useFileDropZone(fileDropContainerRef, handleFiles); const [hasText, setHasText] = useState(false); + const lastEncryptionPreparationAt = useRef(0); const handleEditorChange = useCallback(() => { setHasText(!isEmptyEditor(editor)); - }, [editor]); + if (!room.hasEncryptionStateEvent()) return; + + const now = Date.now(); + if (now - lastEncryptionPreparationAt.current < ENCRYPTION_PREPARATION_INTERVAL_MS) return; + + lastEncryptionPreparationAt.current = now; + mx.getCrypto()?.prepareToEncrypt(room); + }, [editor, mx, room]); const hasContent = hasText || selectedFiles.length > 0; const isComposing = useComposingCheck(); diff --git a/src/app/features/room/message/EncryptedContent.tsx b/src/app/features/room/message/EncryptedContent.tsx index 2ac498318..99261956d 100644 --- a/src/app/features/room/message/EncryptedContent.tsx +++ b/src/app/features/room/message/EncryptedContent.tsx @@ -5,8 +5,11 @@ import { useEffect, useState } from 'react'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { scheduleDecrypt } from '$utils/decryptScheduler'; +import { createDebugLogger } from '$utils/debugLogger'; import * as Sentry from '@sentry/react'; +const debugLog = createDebugLogger('EncryptedContent'); + type EncryptedContentProps = { mEvent: MatrixEvent; children: () => ReactNode; @@ -39,6 +42,12 @@ export function EncryptedContent({ mEvent, children }: EncryptedContentProps) { toggleEncrypted(mEvent.getType() === (EventType.RoomMessageEncrypted as string)); const handleDecrypted: MatrixEventHandlerMap[MatrixEventEvent.Decrypted] = (event) => { if (event.isDecryptionFailure()) { + debugLog.error('error', 'Failed to decrypt room event', { + eventId: event.getId(), + roomId: event.getRoomId(), + sender: event.getSender(), + reason: event.decryptionFailureReason ?? 'UNKNOWN_ERROR', + }); Sentry.metrics.count('sable.decryption.failure', 1, { attributes: { reason: event.decryptionFailureReason ?? 'UNKNOWN_ERROR' }, }); From 213689fdef7068085c20a62c6f823156d31fc35e Mon Sep 17 00:00:00 2001 From: "sable-actions[bot]" <268226691+sable-actions[bot]@users.noreply.github.com> Date: Wed, 5 Aug 2026 09:11:48 +0000 Subject: [PATCH 068/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index dad708dcf..79ca30963 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -20,12 +20,12 @@ "screenshots": [], "versions": [ { - "version": "1.20.1785879693", - "buildVersion": "1.20.1785879693", - "date": "2026-08-04T21:53:51Z", - "size": 18915857, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260804214133-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260804214133" + "version": "1.20.1785920392", + "buildVersion": "1.20.1785920392", + "date": "2026-08-05T09:11:46Z", + "size": 18915504, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260805085952-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260805085952" } ], "appPermissions": { From d8c72e17c12337c190f16b1442d11723fd1769df Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Wed, 5 Aug 2026 11:26:52 +0200 Subject: [PATCH 069/135] fix(android): update notification icon logo --- .../main/res/mipmap-hdpi/ic_notification.png | Bin 745 -> 1031 bytes .../main/res/mipmap-mdpi/ic_notification.png | Bin 516 -> 773 bytes .../main/res/mipmap-xhdpi/ic_notification.png | Bin 1036 -> 1305 bytes .../res/mipmap-xxhdpi/ic_notification.png | Bin 1492 -> 1911 bytes .../res/mipmap-xxxhdpi/ic_notification.png | Bin 2269 -> 2608 bytes .../android/drawable/ic_notification.xml | 3 +-- .../android/drawable/notification_icon.xml | 3 +-- .../android/mipmap-hdpi/ic_notification.png | Bin 508 -> 1031 bytes .../android/mipmap-mdpi/ic_notification.png | Bin 442 -> 773 bytes .../android/mipmap-xhdpi/ic_notification.png | Bin 601 -> 1305 bytes .../android/mipmap-xxhdpi/ic_notification.png | Bin 785 -> 1911 bytes .../mipmap-xxxhdpi/ic_notification.png | Bin 969 -> 2608 bytes 12 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src-tauri/gen/android/app/src/main/res/mipmap-hdpi/ic_notification.png b/src-tauri/gen/android/app/src/main/res/mipmap-hdpi/ic_notification.png index 9e7178aa75a592b67e03de6128e4d0a3f4c2c736..1663c86a45ec56e9b9314c670496875a84511a75 100644 GIT binary patch literal 1031 zcmeAS@N?(olHy`uVBq!ia0vp^Dj>|k1|%Oc%$NbB6p}rHd>I(3)EF2VS{N990fib~ zFff!FFfhDIU|_HUsu3@kvn$XBD8ZKG?d}4kf#9d}?s_1_UgGKN%KnOjl~ao>z%ybPbbPY^H3@ojTOsx#ewG9lc3=BR#+Qo#TAvZrI zGp!Q0hKBu2`+yoW;5L+G=B5^xB<2?2)^mN8av}o*({oQ3$B>A_Z>RfagoI19&6f~% z?!BrJrL$H&1h4LP${JZt~2#k;)ciWct@SitwS z^X0C^cD@<%!TZC*MVLgHYC;k>+U$~g6w*3tO5Rh$s$=ALyi{D9+ww-t}G9Skp-Ets6MdqbEnvmK+9aN{YXTHy_8 zOoWBA(He$}_ZPsyj|wm&J)-e1kBlsY|k^ER%J@y21Tl?$b=*1ihxTk!5sg3y9lSM^E_lzsMZ zblMj%)$;1fduJHF#QqRI$~@I^p`P)s@})bsRv${xa@e}!_0`L6483MBjgQu&X J%Q~loCID!8uXg|d delta 722 zcmV;@0xkWA2|YePWvK z3+P#24%FjXHYOlojuGSqx>)1IcJut^rYElIL1*DD*GqxYk4qh1AYimj>X<&X5iKxO zsh^}<4W$(cJ5-{i>7#>u78qHovE$vW!jan|H1uX)Qz29 z`te}_8o+v!p(?J48bFoN*120&wzTW^F-G4Ce^pXRj?^)`o00L$%mih>~=blhDwfDz3p0?<^FVF-aVCLZP1kLg}de+tU z=TW=m57mt|4g|~!76y?{e0j!moL2(!EhNYvAYgVd>5!!(Xr7_N{VHI7h6X7Ebr3*Z zm1n3T%YYfl6QoF>lfWFx10&y}fK;7@0I98WjZ30{27uX|izId~3TP)l=jsW_do;De z7EvJ`OXuflbr-e_)XYOEWDEgwDa0|&$9rNdDv>qL7?DQLC4nx=UH||907*qoM6N<$ Ef;ehng8%>k diff --git a/src-tauri/gen/android/app/src/main/res/mipmap-mdpi/ic_notification.png b/src-tauri/gen/android/app/src/main/res/mipmap-mdpi/ic_notification.png index 805fe1c8e2d1cece50fa18e89baab91312b66d0b..aa597d6aea9ecd79156a0590ebb61ca74605de0d 100644 GIT binary patch literal 773 zcmeAS@N?(olHy`uVBq!ia0vp^5+KaM1|%Pp+x`Gj3dtTpz6=aiY77hwEes65fI&pI$gOyW~y-Yx_ z87QP$;u=wsl30>zm0Xkxq!^40jLdWmEOZS_Lkujfj7+Tz%(V>+tPBi3KH9~Eq9Hdw zB{QuOw}yuOO#6TuG~hOrWag$8mn7yE;MQ|}m2x5j1LIRq7sn8f<6EctclZX%9Jhb} zQR1>mZ{R2O$PWfH zmwh*o?=H`qTYi7<_qpEtO2wZ4sr&x>@87!T<#po!jHOogWf?jyp0y~jT_-`=fNKx4 zkD#Oi|LT=~E7`BgKFsl|U9>Okd-}f6h}cAHz8E$$hWQQI2h0;Be=x}~$Q_kbPZe5p zYl+=qUFw@xzw)@> z>i*>Mt2_1+R@a4oPknOsj;jxIb=&@FK_v~d4{Tm^>CLw9Uayl}|K_|;l@Gms?CHt0 zi!24QH=>kpnH7l7V2xwoJ`i+IQ}_q#maGZ;SH%#5LG5>|Ds@0M@e~pvurTJfC zKUHL`dVb}cKqI&35mlw^E1zE_asHHEd@_=Irw`w1f9LiiJ4D}nJ;Cj=Y5uv)uW>7W xZ>n0B_oY{9qKsRk?g148{ynlUrf~gXWIr_H&>sJ-vw?|(!PC{xWt~$(69Cg~GLirQ delta 491 zcmVDn{6-pMimNxcxVId3QE+h-(>rX(k zQ7nXobn8Y^wo(dZgF+URLb5^FC|M~a3tyoe&wHDr({;|AnWRkpn(oZ|{+^ll%*=IS zf83lu_K*E9fa|)lpfVJ99Ou$x_u3s`Sc^$Lx90dslU|vn~1}ao0 zC-h^e9DSfG0E@o?jFLQ{Rx3U(IzW}m^oD*JrF7-e?O=lB-mDdV@;k>jCeR0g0=Wp< zjSkR7!X(O#Dg*PYs1?X-cB~H2NbmwG3IRMZeuS#jHyH$wG6JaMxJB?iYC?GdkRA-D zh&^O3p}tX?K7Y;ltrs7-1CnY8*i?YhkTUHuzJ!KRi84H+?*JetF4KMhFpo37r&bkG zozUSOX4(N<>i|h6*Mr~&v^Qc}0IUQ8SbZ@Qa$_3|%={s8T%XY_>hqtb?-F4y$8kgg zP`)AHg}75yQn~fpn7{jTGXTux^7JFQy{1iWai_oDL1c*@V1~&yRAAsPr5Hlvm`iE2 z%>&32VEW%6x3(E`dGI2e2Z&sWa+0SYf%$o)vkI^UtYL0-!fXJt%WeSErmL4Y8^9y+ hNdWuS0GkBc*e^^~j~NZfNId`m002ovPDHLkV1l#5-<1FW diff --git a/src-tauri/gen/android/app/src/main/res/mipmap-xhdpi/ic_notification.png b/src-tauri/gen/android/app/src/main/res/mipmap-xhdpi/ic_notification.png index f3d89b5bf99f93397c1178f40d9a19e305cc5d74..047324fff6247d97981a34cd80c58317a35c4220 100644 GIT binary patch literal 1305 zcmeAS@N?(olHy`uVBq!ia0vp^1|ZDA1|-9oezpTCg=CK)Uj~LMH3o);76yi2K%s^g z3=E|}g|8AA7_4S6Fo+k-*%fF5lweEpc6R~NK=9LfcRi3|FY)wsWq-xN$|=cSCZN|0 z6jCj5jVMV;EJ?LWE=mPb3`Pb9 znO2EgL&JWieLxKwa2rZ8b5n~;5_1c1>$$#4Igx>Z`KPCgV@Srmw=-iqLPJH4*Dp2> zi&C_>d4^@Ffs&w*n@fkU?ZySsc|(EgC= z$C75dF0{DjyNhE7a|G8Mwlaq3#={fOb{}|s#qF2!gU%=Ry3t;)w)Ok1(sb3X1Lg-- zKld~dY(3ZXE%w0X%M;jVu&?p=&}V3n^E~nU>fdLF zcl_G+tNhgN%dgD7vTj{&*Bz?);2V!qq(pGP*@mA{vTI^ojDGBWb(4wdQ&LQ9teeZl z<~RBYi@qhOxWlXvn_4qpsDD0_Mawl8mNv{CBfs*tIe5OCh4S)YUb4#NgE zi=gjyii!4jB)T=GCM~{lZTUMdzJ<@PuJ>AYM)+0kwQFI@lH01UDwg_%b?FK#N;D2Tf%@hb`u32%o~0Xtk?hs%0)e zV{%Fe!^~=hpeoT10o*6Wk9sBOK8%|f@6htQA^Wz*gP;exhgdUCb$N;kRPLW$P(OEJ zcea{U!`&7hv%L+wd_QqqOuXc_hdU=L!_>$~D1Dx4Tl4C<7ReqvKc6iYa)0uCrTmtO zKbAZ^^>c<|ZQ3-UxrRS8B5m2%%zK!s^uc-q?+=zAA{G+TOJaY$F8`YIKr_MOXRK)* z^FDQxqh$=Y8*Q(IuDD#PeQv*}(gv;{5;NirKkhy7o5laV+TJDSuBNT*Kfw4PqLoQa zn0>F)v9s$+@-=R092U(z!}*o>tI^zB7xSbpHr##njEg15WTjfPmyPog-B*oblkP9l zTQj9*F2fad-q@#Ug+6;X7k$!HN?WZjdF$cXgvqxom7fH=oC&-hxkg^LX40v1C0qS|-ZRbk=yzn-wh8myJoW^+B_$BgRjG1qXwttDnm{r-UW|j*Km8 delta 1015 zcmV)ZPz@;bOBIynElP66#bf}JDKIRX)Tz<>D^N+y$I;W!WU0d>Ng#0p$ndTNoz*HhAv&3az2vh}X5%JSDXcz$_XyhKS zel`m^O{+DUa<@WhBmTjF)$d>g3Dh@s4+{bLt?IuA5k z0pp3J-hUeeP65r?m6ie;AT_P!8APa-I_(qV2fy6{s+*KFe9cyXhFd+>^4ulPB}%o9 zscDK7LFzW-wVUq;a|0e$!KbyR?DWyk$5?=uKGh?mO_^r#Q;#-+p`Z{bHT&5{epGea zi~ue0R%RnW3s%!7msSRGRlR{`Bp_w+PR}KK+JAZk7J;ilm8+?M83fS|soFl*rmA*S zq&2_@=;dS~FcKWI!mY$xA9@WyehLBVLARKRnS|3jLkZ-+203T#QOK+EyaOY^LYZzkcxh5v`wF1vRqLpr3R5cB48$9pAA$$q2GGXX zWPkIn+)4oCHP_dI4IpTPu_5W_tBq_sxD50a;{&AC`_`5w0P+KgpgMmY&?v-d`T`-c z$G{c{tM?<@e*us$AleR43S49y)iTS#iJ+7iMop>!efCpr;=+^$DZDz*Z1Awc!aY{)Cq#BR9|pm377$|g11sB|shJ!A?X|JjC=jjw9~yCJVn zhtABU0KL diff --git a/src-tauri/gen/android/app/src/main/res/mipmap-xxhdpi/ic_notification.png b/src-tauri/gen/android/app/src/main/res/mipmap-xxhdpi/ic_notification.png index 854e9e43a9099e569386c70acd8ed11027ae8322..facf5d62d3ba34f8717d731fc7b4c3f6ad411060 100644 GIT binary patch literal 1911 zcmZ{lX;jjQ8pi*B2vJeATq<)*ami&w%?-P`G6IfkxKTE^=Z=DkX$2XhQJSGJmX>B# z8k(foq^5FB!*RLeV77SGY;s@Ha!bv++%NZ>`(d7Q-uHLT^PcCt@3;4|ueXPyyoNjg z0E&2=yT6pU|CX$bv0_EXAQ z{EkTnGU1*c?ovv%<<@#Z3OEh#g@w<{!sHIZ)0Kb7ky-{cY%nb{j24B7NR5&LutHne znxpN_(KbZ11IEe*gSIn8qcLdor@vYt{})J1j*N}Y{QCf-1JW)H82@hrEjBTVN()P* z{C(#2L;W!6sVT>w=+M&GpS0 z)4k`z$jgg2tY@-6E|)oUyxSUJA=9eewB~(tF*K%$S_bqKzIS|rm|0qO!1=g+DASYy zI;#j^XB=M7TDh6vV;Z#%Pl@p)qq)4QMos~Nq*oJkKi-sZ(76hgRz$R@F_bM{&3sm+ z)mzKrV7Q0;BcII2({#vsltXCEY7hxJLCV2W#!$P-Hppjw0)Mjye*$ftS&G)>0jG@S zJd^2>k`z4uS?b3$DmQciHOw7i>uqV2y%-0~#I=T{NWcP2KD$JR9LNbdnNguVyP&o1 zY(v@C*q>Z+EReXSrD?w(%9qvFyFrto9}EUg$t!>(j1%MEM;MsJSlbu;EUlHeW+06% zcm)4^2|5U)YumF!UbdFNY$B*H!zPp_>=M3h?|D<+ZofN)I(z){bk1!~`#=~{PI4H( z=}9WTH~RDV*Nx(;>tUX`T|M!m!T1aNK^(`HaMOH_Rxq`RBk9J{D_t`4TYUWEuQNta zb;U1>XVN+dH%(&li;Z!obD~w{jOqem7D}Boe~Brl#Y3^iM9N&P`{UO*H`6xhSpz_=c4QiYt>||A2_0@d9{drS9QgH zg}m)iRvyn zj>j`|8TvDr({b?EA&-&8Ec`V>ONhFLIhTYQ_?5UY+R<8t<&3yJivLyUDj{?GlBr2n z!zoIyJX=W9I$YOxeRAWDVqKWHAvBRk^Eh6}zLkT4W~`QHQQ*;^5syo}UyiW53%U#Gthpvkh2;-+A9hWfGNj zm+2T$v63gr6fx*g+P-~eN0i9o8&OLG zjRi}b>7MjJjZR={x0Y(sg7_k9y`0KdTityq*cE2GqQs2fBZIeM&aTa<2{R^$5vBAL z5m=flqe@?jCHri*o>34k5T>CT@| zJyKSr*_*?}r))OhY=C;GPWT}n)1>R7Vc0@BA!xrDd@dpQP8s0vYDmW@+xLAO^fWY` zrPeFoW5@J@{U{!5%o9TB7ANmy|MCV${&BR8jpGXvD~pu1w`F0I!9I%U+))XMQyZO- zdK+6%s=!2aE4amzM%zsNJIJxNroZbSKKkLpIm(MHF7j$?E(|9^E~d0=#=veNG<(P{ z$L;k6OQVE~Lj{WE10r#-_n(=ia$A>9{sEoLp~?vkJT?5N9ph)sBQ_xr)w>h_jP2Sl zG({n`j>6aBJn|L;PjnP0eo_6>xwGQ~dD3x3ZV(RMM2;S^V*!aEFYNh)Bh|jdR&^JK zZTLx4+lTw_XAi8%2vm)HEaP?JbJ#FkMlex+fIwn~)tjzA= z#yj;r5OCK5`)^#awv5wxGQW#Cr^h99mv1a&pIGO->WXyuj=QOzJ3NVq6~;_Yy$bJM zN%uL-D5PCWsOO*B4v`dgb;>c;s;f>!F{pu(pA6E@u$<>nb0PQv0~sOS{~eoA1p4P! z%@7js*8)^Ebt;4g1H85q8ciAoihO(LgSz)nUOb_7xN~w=ns{ui$2p%Xbb0?awD}=+ zgFu`L@lnUMMHOv+(*u`^i}Zp%eRd&qEPrEGslXs4^O{u{Xtak|X9lMB`NdHoJXLMp69DK$98lnDgrIeIwuKF+6S1h z+MrGfp0}SV9AGCR7opJ*anYU!k&IJO2d##Kd04fLA(hJw+IjD1QW^#<@z6DkS9Qvk USHIGE(zgWQvEJ^FT*(*z1I}GS`~Uy| delta 1475 zcmV;!1w8uq4%7>fBYy>(Nkl5~Q-Vky!?%L)^sAo~zOMvy%;Ev%>{N=mG>jHH)oMOIK~4@$+l{r)f)#$K zfvSSi_*Lhis)7!&3hL?U89+*ppfgbY|9P!e8I=#NN2{U z89%aAKqRcB?m{m@4@WnmtI=0UxTiU6>|f`-@h#Gk?Q+J;!#GurDs3Qo zB03a32R*C7&pd3GdiXUnDFe`hM0ZC(gr8!2DXR0%<>=q&Z|FDZ_WElC7cLR}jf@xP3lj24}!8(r__#qH<{K>Zgvr*oJ!ppTgG zLg%dQ4Zh=0^BTzIZXE{Gfu!@6xmW{I`42OX((O=-%ZWhx)@>SQVGT$N!I5Dhm|5?@ z(>NggV1MQjN7jIz#itgB-4a0>4x~S<0jCxJa+6cnjgXbi!<7nzvl zuvq|l+`^$LAO*x?@eBT(Z4q384}HZh0g_JMNm2%&`9!oNDJq-68v!&r)s-nAs^?w; zdKA^&x|&_x6y2ui=2l&UXfXo>oO6jn_eokPPJclcL`PLTa4d&6qv|hRfWCpYyZ772 zu`xi>0yau40X;?pvr*kt-he8oAyHAa9;Dle$s~Kwtq32?RNjB4V4i@R=+rR*$o`Ego7jrP`$*}MeGl9 zfFP#;DJb4lKp!yasQy5w9-|;lM^^(%S6Zh;1EP9P#k0-T^-mw#YD zRL?XfTG5RR6X$#hI9hcFNf03548pr^LXQiYrMt#jAl`;*C$`TcH?Gh^0cm6JG?&wi zj;|pWZ7N3Za(DxxdY)%8m8kcaE`j=$c^9KE0!9x$B#BqDz|kJ~vZR^H8~i)2_2H>n zw6ps?V6@L~B2GZS$ziXnIa#%K)qhISUHMLcXoXyg6avZ+j<%F;LErajRag*f38>!V zxrYhnSWIHzLoJFWKv`tqE67D3K)^W#54z(`-ct&Sq`k3vKUV>#D?7Fa0RoQ7S5J5~ zJ_cu$XOtUVo<{>mC*Q6}GoavwREbe*fv5h>YbDO%be%JxrNEiz%%Eh0Tz>)SGOm72 zX_s$bt~mnI&c*nUy(`~jW9)JSq#aN_Se}LC21pl)2>^N}3pxam8=$SgIX@RTiX%5b z+78xMbvBY4ppgLDlntHCD(EZX8P=(rP~Q(BrwY<yi;~L0n&3jPj@PD-+6KZ zq?PlBzJYhjE*C)hY10`g%{=w8faL-xYR{@HD2;w|0i@rd>W47diL+^+UBn#@r~>2w dUIB6d`X56p002ovPDHLkV1h_nx)J~Y diff --git a/src-tauri/gen/android/app/src/main/res/mipmap-xxxhdpi/ic_notification.png b/src-tauri/gen/android/app/src/main/res/mipmap-xxxhdpi/ic_notification.png index e6d61da79ff4d9f4cdd6bbbca4fae64ec3472ac0..5f39b5f1a475e27187f307545eeef3b31c91777f 100644 GIT binary patch literal 2608 zcmZ{mXHb&~6UU!~5+Kq+KnN|N6AYFBp(#ZOMT#w0LINWF2wp@$NYs<*wnGXO+t0s!p}0Br9|wC@0L0|NkmkpKXf0|0WA{17~RJ^k->@Oh!VFg&2gu(57NrP%jpk5_YeQ@5_ef9wy!5qP& zF~(@j@v|5c+>zrrjFBD&gTr7}zPy0`!w?*D)&E+=zZ+<6(AIr}_WvhP{eyjer;>vy z|Lz$rN0I?RSORZz@@)9Wg@Rj^O6L&WmKy`z!3(#oo;>rq6qJr_5GZM}O&~a0`9Tug zGvn1;)!mMjy~>f-kQBBU91$|qzIeani33vmgAK&-P^qm9GTJqc7%D*_Na57GpOjZ>426H(4mEl0gGQ-QP3-*UHP*vH- z%C@;oYBV7-_#|Q`%sx-ozm;_qh0a`y#CzYBe!VfSjc?S+|HSAI2!uepl#u>(mZ^rh zhW`T=Q)40HsWV#;UzB~Ux=^TfgBhV=CStjfSH3Q-M(QwO#K;d&_R^>oERP!j9WwZ~ z2YylbznE0F31JD$$0rPIH|Ani6(jpiUS+_=x2RngwwlL|Cq1nn=TV>a%p-t;!>;;- zY1W7t*Y~o1!J`y5#V|te)`#BDyh`3Z&anicBpHg#cLAc{c1v4g+yF@B^nv4`2RIiF{VL$w32K28G|$LW zL0J%vCZ`*8iCZ;<2pT@x@P1Y*HzsH%8U$(JvuokCp7o|B2gV0NaI|62PReO}8r-2N zlh7E=uiLl5Rqz_85nQ5uqviFh2C7MQ&+9*SjQo?HYLtv-9K>(mc(;Ve>Px$T$6a!7 zRCnTu(3!=JdfNnZg9_9Yy*Wz8^d6J7^!Ai*F8#xt@vaFNZs+eQpakdo|JXT03ykxG z6hSo4?jfBeFT*i?o)bk8-DEGSx(Q$P8b>P-hp;;x}l;&Si!MgXk~mK2Ts z9mAkIi0O9O$IxjY^=5?hDAWwr@_kd;zyms&yp^9n1RaHPJEIJ3XRXJCgzbrcPZ3bo zXF!g~sW-Dh5cKB7Oyj-8IG zDZc_AOF}2}phaz^4|xiN`zec3q2%VEcwC$~RD};qjy|a@-=RK>g~WD_z)R|YO{Ip9 z*)DPo@2gB5*k@FmW)3^E0RFJcVkX2DI%0X-kM zDuc>ojoQC3wVr8Hy;M{thYDk`EIaKhT-Zz$B12CyO8lq;JGvD%wUqVr4C-Z0I?%|U zA}c{IWg!jO6+Q7ir_T`24@ZgDo^TK0#5LOIq31MhlVs#xdR3~@>XTVz*J*ca1UwD}q`>7wX0 zIf_Qy4bP%DT%0W7vwyVb`oG&%Dtq03)Uoq z|0^6P?5k5tyxdLo>`dU(m^P9wU!ZXBZ*H?#2_(dALGRs@&2O8jOeBs5q67La`TMk9Q zDy`_V_SxzaW_*((lea^V4wpS$QNH=_H#2Gx^9w;dVo=U=!K7`)lH3zju8^p%rLK5J zwoh=}fihAT@qt3DUMu~)p5*m*5edHy%j7C0+0IXsy2D4cv3wie>Cw&ca?cJGjxA3> zW;|2RJwM-gXEyitSYbl}m@)R_i;Cf+wt#xFyPe{Yvj&NmWT-W`R*BBU$P!Jgzlam+ z>!c?}!yZn_UC!5%9D(U~PF5m&H+MmALKOQ{`WTt(RA~LgB3&_zv|`Wn_O(8s(DvxjquH$e69oAy%MI|my^I-1&}Pds z%^4FDm9pPNm(4G$ETfk~2FggLQ`KF*yh?{iWXWc{a@S;~ZArZ7A0ZtL_K+=|pXn6;1lDw^^a5fO?z|Z4}e_1KO4Ffy0}ROBr6(QLvCkbBJV@AU+f}rX~0vZa+x9oXk-Exi~o0=VA_hR&2+XWhf8oeSr|f#dHo@)wsghY)$ZO3V@hZ44@Tj6GiKKU zvUJUK2T`j!oXYln%10m#o#Ij+Hv&swSi$?wm_k;?$?LJbuL-BQjQ{p2W^#nb4lng} zr_!UOmj#1Ve%R>ytxIuM(lOh;wqjO!3B|4#vU+tW7xu_DF)4<-emL;wH) delta 2258 zcmV;@2rc)p6x|V!BYy~_Nkl-b;)Pi7obEi+}Kkih!aJK~#h& zDiK@2hFBsY#sa7WLcl1f4=V^NDk>-fqF`4{jABC|_TIqG^Y`IC^2)vM&d%)2zPap4 zzAU+K=ggV!o1NXAIkVKXDJ)k8YI3c;sJu-fK+c_@5TFnsXMYBAuD-Ye3ITFvAm{3f zE1(b{X9jYvzPJJk0di&_=jw|qpb#Ku26C>xxB?0RvSFaEu5J@N9S-&Y3ucE3hy47Ayt7gB1{`o?Ox>yD@*L1*f(^&no_QHh%8)N1>bN+ysEY zBMAKxa1_`DtOrEc_uy0TK9~k(L*O4xn@Raz{B}3c5Y&==$sgO}<106+{FDwZ0K|!C z5r2z8lj=C<8PKz-2>5x0-;Xr#p;K<4{B?%s20bmP0Dq9SF0C7p2%vwP+IO5d5KMu{ zRruLD@v}b1b&{(79xhOl-wmf`y#^gzJm=SfEvNe*pnPIHxrA!L!jLdK`(vYETjOJ(hAMr#A5#t z=mZ3~&}YCQ1!zk{<^V04$6`Md=y_nOuP39B0%-a1L2z;`>?d*R-ld_)%S>tz0T}-^ z3HL5I7Ca1s)SHpeS|+^>0j|u*Un4i(iGN5IP9CCG-ORKsxDXuTqcH|PHAVdt(7N+J zKr^Z)rg^8+5#d>rlhd3NLV$Jzq-kI!PIUo0BqV4^3T2v#ei8J5M3K4L=o|+ovF*gM z5*NBDcc8r1qBFBfl{!~MBm3dxcCbNm9Kx{{oZ{@<+`;RddK%;@+oF*XpB9P~kALE; zWV#Ow12gcY8?>{95I_qc5~1FdhN5-b1!-nf$nK@@vR}w z%6to;0IzQnnS!4Mx&qzQB!q7}6MvHKD?`5WltgBGiy*W#1lY6gKp41Z3fPD4_Mi>65`yC-(CYsWwA9~K|}GsB&`FV0vtmy%0^HEZ8=je zsFJMI3w@f1zZilvb~iEvn8FWAbF}5+2g+(~dLsVyh?~l6E3H@w4O8mj6@L{^40nRY zX(e?j-&BvHni4r5n5H*2jZ`<_(LgV0datlDF9JaRZbYNur>#{~ehVq%T3L1)a`Xgb zYg%9$0Qq`Twl-e^^e3VT)=|Y#P)nE2>)e?OK<`&#>^!h%96VY_srQ(Z8opWEc=91Y zUjk9yewImCHf;-0M(;5r5r4sY8& z)7i`c)jM|Vn+ zldAyQ9;Bg1Z@<-Un#@}S#(>F?Uv?LN8X~L(p!aKIgcej>c0HzvHP3T3d#brDZLwWq z^R!bgcq;)QUrUUd>wiBwPgXqFt?6dX^*;vm)fMOArc}JP0%#RWxt=DO1fF@y)V*%5 zN~2fql2*xHhIs8a_GYOCp!aK$#pF8=-h$59vGxP#YMu^e**?$P#*|6`$R9>U+He>1 zT#xn#Ydu=I|4Nr!4CyOu33M%IBml%~_2^ol-XH5Uvt}-JBYzzSmfOr+x{_V0d_@70 z&&!B>Ax84`xTyWW;~_m{GMJHGEeZhnd*Nj$P#R&#Tu!6l4NlU>J8lG%vdCgHs4w*? zWd(qIZLHI`7?esFqb(+A?QWUxlDX!);mrg{#(OQQYl>B$n5j5S`3};;zcQiwL%h-= zTeX!EK(05h|kF7OcN8kf~1fEL7+ zhThsgiO@*TY7*c%TBgm_%2}CziQ$_a(_!@V;5jL0FRL zh|v)NnoE6rDMmqJyaJSwtu - diff --git a/src-tauri/icons/android/drawable/notification_icon.xml b/src-tauri/icons/android/drawable/notification_icon.xml index afa6af354..29b2f4cde 100644 --- a/src-tauri/icons/android/drawable/notification_icon.xml +++ b/src-tauri/icons/android/drawable/notification_icon.xml @@ -1,7 +1,6 @@ - diff --git a/src-tauri/icons/android/mipmap-hdpi/ic_notification.png b/src-tauri/icons/android/mipmap-hdpi/ic_notification.png index e2d71f7d2a6e1c9d7b4454d55d02c25d2a979ef4..1663c86a45ec56e9b9314c670496875a84511a75 100644 GIT binary patch delta 940 zcmeyv+|Dr}vz~*MQ=o*-Y7+6{v znOYf`Ya19?85n$gw2KKvLvDUbW?Cg~4GsI5_5n3$z-=hW%uOvWNvzK;z^&=}D&<55 z2BznpE{-7)hu=>3%?JsXXqzt~?A&`*BT8qjh?bP&NA~|7x~-R{#)fFGUEt*4Sg=%D zoXz~vvEIh6cRu2Je{M$J>DY2%ir%iwsb*PgIc_!GV)^fDYIySTqj?*zpPXB7{r%jX zH#La~&;HarpZUG+`JML%q?fK<*rD+1#{u50t?Q&UIG4$-SY>=kOsD&^hI{=@2;8D|883}gK>mgVc1`Wyc@dFLKDyW{d!wW^)YpRY)V zU32~#a%Qi1*8X3McX`hhE#4)tfbVPP%Uz4@d^6;O_lJjzFo`nNgd}dX*(LQTq;=Mm z#?|r_A@i?qVLsl_dX+7W@fZ7x)xsPJngt9MtDn^AEx6H=wm@8BHDl6>H{YipnAT!i zWVuChMm=xLDMllo5`%T>RUyg?_j2CwFIly}Y1OP38=qtco?pHFN`8^b_w}!O1Rl$N zJ-_MS?pJc9S#b-lzS=ABWP5>7`o;KH?TW{ezP@iURDN|)sKWEA-z)uwnGb&#C73)` zp3Psw{fDQ9YtMXxXX+1B9)Di5$ol=N+R}OUnXf#preB)$tG+lP(9J#TV)y~a2X8AL zXFC{PGFvb?XZMCMUuHW-DdEObMzz8l(wGt%@)%+dG#A=_OkcUJz5KjOX2@U1*zBd{ z(QA^IRh2O*9P8oQ&i$%ygP)R5&24{nKEd3tN+vvi{I=}XXR2qo-pREi+)L*c(@U?f zb&h>8LEEQUCtjPS!BanL(L4=?XLJ6~zjRYk>&XS7%crkqy$Zd*no}utdhX_JTp#0& z!&)mBN?ome72vnv-Jt}b1+%W|l^Q7f?BD3LFJP+W)s^?oFno#qA$*j1s^daE<6Y%T zcW$jdl%VCXb;awem)*)Y>|ndv-_7K;_qLkO1(%Z6cMM^IvDxz&Z#Uj9jaQwznsI5v k)GJ&*idD(|qKsdJs;rZh?yf5`1m+e7Pgg&ebxsLQ0M*H#!Tlzw_7#dm` zSy-7`Xd4(<85n47_z;VtAvZrIGp!Q0hUm8*4}lsq;5L+G=B5^xB-ZB^plLD&nr{rT zWs2LHDL_qkJY5_^A`ZWueo*MJ0*A}hlmGu4*&dx4am97owX!?OZYPpe*@CUCei^5x zOzij~oT9?*rD;v#N-OZ3t<Ieo~nuTCsXUtoc4kVzp!FVLq9p00i_>zopr E07fR4?f?J) diff --git a/src-tauri/icons/android/mipmap-mdpi/ic_notification.png b/src-tauri/icons/android/mipmap-mdpi/ic_notification.png index 25508402516f1adef1982df41b9c89fdedb10753..aa597d6aea9ecd79156a0590ebb61ca74605de0d 100644 GIT binary patch delta 680 zcmdnR+{!i~vz~*MQ=o*-Y7+6{v znOYf`Ya19?85n$gw2KKvLvDUbW?Cg~4GsI5_5n3$z-=hW%uOvWNvzK;z^&=}D&<55 z2F9nJE{-7{$G1-P@9+(jId1>{qr_#C$O&rNlLKZYX)j$fWzsAmZm}u7b9p0AcCq?~ zow^ouQzP}l8jZ5%-oQ`lksl0ZF8gjE-(8+JxBULz?{mHPm5M$8Q}_M%-@kSB&&%t? z{~1fI?8`EATs&)0V7pF&vH{l~W*y*aWtlN%%0(M{g zx4g=Iu8$a}-|Z{?%O3BuG7M4ZO7f|VsCRZKRWo7JS{ugQkk)za+l98dT`BjO!yAq# z)(croliYpxU4mI4oAIlfh}0c|HT^60AC8RPyJFq>9breGFwSoDKH!(2vPP-rVs*x4 z#pH(414;(sQM(L&1qZs+H?Mx>alh65$>Udd>?f?Q3;mw@n{D5{UMIQ!&3T_HAA0@R)01fzSqfxtL@D1gD-fT-8pptWAn2Z^@DJ84SrhiN zoMYl|n7U_U{tH)Ct0i^*8YkIH^S{J?s>oRN{K`3jMsCj|s!G{cKEF!h{3*ToWF+@a zAHLQ8&h1Bbh`#xHg4<=&{BxOK<5v9MRJAPcORv&I88^j7-2*BH{Ci|yOyT;&$bM+X Vp*{XvX9H6TgQu&X%Q~loCIFb9Au<2} delta 346 zcmZo=+r>N~v!0oYTaHlzw_7#dm` zSy-7`Xd4(<85n47_z;VtAvZrIGp!Q0hUm8*4}lsq;5L+G=B5^xB-ZB^plLD&nr{rT zWs2LHDL_rLJY5_^JdVGedXTTdfW!IVoB#Ea{(9VpybKNHp6n>84LB+ClY7c9X5+)t zLl&yBgq(>y!I$6>-{`|?aQ&%H$=QTiN18U>+P3eIlEYtTk%YyWZ+tKRXcI2k?YrC} z_=Lp^sg|;`nYlh&40ssI1sYy<%t&9vn(&&bAh))V$;7qV$=)&Li-z6Qih5n6G;PEW7RvbWQGI+ZBxvXMi1|DPrs5 z=-lKI;$Pd)V!&^kviFLMzUvnuji9|#k{--RO?>g=YWu8N&rbZQx}kpa`?-3{;`5f@ z=k4VG+0HC}ZddjH|JiT%e!KPh0Bg*F|I)IdeCyKu?_8XV>pJkoL%``DAdZdcsh<@18}hfF_~G~0Ed#Wmku96OjJxaP2xF+?{Wo_MzV!0Rh+ zzmy+zKC#!0_HwnY-*1(st9B*-s{2*G()x+N=2qE!{I~PSJNd8k!dw-%|H;@SdO+jC z^u#Kz3f>C-9nv$neVD|VZ4Z>$#?Hu?IF^p1?kXeT~0|KKnZ+KPLCa z+5`Rv>K=GadirgCu~w{~=ZW7}|2{jsB&3!D2FcwACx^k z1KXE3Hrgn4aaG7vOb9q{(yY(HeurTLn?=y~I>ki$JM|LX8dH-NU%9sYofqH2=U3Nz zEjuIpD)-v8FlEVY)mIfu{ldC*g&Lz9>zsTyv)y3&6M5+ObB>o5$3F7h&Ti;Ez;=jD zU$#-NbjvyG{j1o$-4dItb}r1?>v(tO;|0=T`kGsM7H!ZC@1LSFyKVEUu&>Tvr?YLl zef9O#ZlQywGM~d1*Yh)kPvJ_m+SM@CGMAq*IVFT)X0<|4mFR~6?vvt2y%KaE#!ZZO zX!+fceOu!}&;#8=tQn`eJVga6_s=e<~>YR z`e40*_Xo=l5eo_FC9%I=mw(N9pqXItGuE_@d7rw;(K3eHjkZ@pS6nXDKDXafX#>{} zi5c;RANL;k&Eo%FZSRtESJPJZA7FeC(aNMI%)Zy@*x7X@`5L!04vXfV;rz<`)oAXm zi+NHP8}7b(#>J9jvQjPD%f|VLZvCr9u}SwA>8+VkGne6tI&bXLv_hY~n~OeaDy6N~ zm%R1xY{KMQmda0pUCsnvk6a@!^|)nMmfK0@FWWlCNt^Oxst7ZKku1l zeDpiAYukkRZXW%=Ha%P%t2`%!{g$4Bveapw_Dkp6P8ss<7CQJ=^}fT2B&c#bYl9B#zyJE6S=ABar@#_~ N!PC{xWt~$(695IB9@zi@ delta 506 zcmbQqb(3X6W<4_(w;W4PzRYz71_sp<*NBpo#FA921GbWniGS;X^EnhTQy=%(P0}8lvBNJOpacfZI@#nVVW%l31TxfTqb9XudJT zmMLy)rZ6xtT6(%ThGg7(JM*T{Aq5`SgD=~^pZ~aWtLuqtI!4d-Svu`t7m7;OTp6M@ z^;df6xd+#z^ea+Zx3fN&^}R{KRer|tjD3%y8W#kzK8sb1JM(eE&s#I|{#Im4Z7So8 z5U4li?=`mW&78tsd4IzDP{+2-@=x|w_-bCr{i5RjRd_msQ|n4rJw5HuISV9xc<+?H zTFTHAa?E#e;;cn(GwT~-80!w&u$c60t(9h#jwW$f)1^4Q=-sa>G=eO1MO76as*}Y>@yXghVoo2bO z7j#B{tK~P0pKmdKI;Vst03Eo> AEC2ui diff --git a/src-tauri/icons/android/mipmap-xxhdpi/ic_notification.png b/src-tauri/icons/android/mipmap-xxhdpi/ic_notification.png index 8a3e2a860c7d90d711508f8d13b200d297530e40..facf5d62d3ba34f8717d731fc7b4c3f6ad411060 100644 GIT binary patch delta 1827 zcmZ|QSvcE?0tN8@KM`99t)-}4lv+kmTl89Mn#8o0rk0>L)KdGBAc`ibW|$P!kc^g= zs*uF@FG9TQ7i*E+Q?rL|M-^yz-zeVFrdo_^nXJh#Pn5CxG`Ntl$XM2h?m zSpWd&limEtp~2)Z^yQ?m?*&+(EUZmYwx%d6JjxDjVTDH77^6^V6zbET&5-{CvGJji z;c0&lXzh@;@4)bX3*^YyFcLYK8k_L<=v4``7UhIK zgiHq4-(ll<%g1X6A8g*{58i8{)-|Qh^;`=kuC3g$oX_~UR%+Kix!2D?Bv-j=EO}<5 z$#f&7RA?Z!XJQJUR#K|sQD33Ov{qySED#u14611`VBAA(mjUm{Zxn%Eu9O zt9>6w8{<@+Dv`;Bc(dvgl0_S7uPQZqY8Wgu`?z=Li=}9?7Ew3hI2EN{1tLI4NEui{ z8*DS$2f6f5;J<9apFnFThOA}T#Xy5a_jpREC=ttjmGm*0#12|U4zmZDx_fG+Zzcc} zVaa7Qp+_LmNmAVtP+kk^u?E-_Q7vzsM{WcawRo&?~uhQs(wJA zvluARdL|VV$rfaN6H37*?-ZP2MH=qMBil!~of2gGxW_6h~6g(w2WfSvt zU+i63o9*E&@~Xq4=<4!1hH1^MlFWW_xw}aiYJG-OD{IJwxAckd) zyKA~g&Y#`E5VRvH70zjS%^u#-w`rru+M=PN`Q&yg?ygZpUXdZ@QdYR4ltHZz%uKF> z>@6~8HJ_EOHqt%sH9RPlUOLZxCOAzzGGLr(A&v1$UO^3LdIfcD&K@D^4CwXX9(pQ# zOV#*O^jeTnZmAgW<^_(*s^=CmA1bcft`qmqm={z)$iVJNACq}5f&#vL`i@xv8Dgd_ zVyPl+8E-kmF(wl-)3P`(n0Q&eOEy6LqrBDbq!GMXb3wf3my#ThVL_pQy{NF~V${=1 zirZG!p3><1Z=7N9liz`5dL1u$a8*!y!+s)~o=wx6M_-DPcLSPuED zLjm(%78;tmQI?({5&jwey!iakD6=d7i|Y(9Q2cu9GJWScBeeA(?5uQmbpkTsVO?8O zaXi0XjP`@>hIA8rz*30b2h2hqO!t!LczNwL3R+Mk=T0z&51g%btxx-pV<+`-_vw9? zpH~{2WEx$jHaVL?oj}qb*6&~0;6;+y2IOjgL;fmjt~%PosNY`1)y;V&e(DtdatS3-0G4EnD^gY?i5~l|v9YG#LubG(D2)PJ5oz<1MlytJRP`xLMj!oRD$5;V%P_2;T9J*2G z^%KF%WjNnsCK8J=eh*3kyOBXHgAC88hf`BBdv{p z)6+Tifts1{CY_DQZOMjV1c;TyHuVVDJ-B)|(b>UPkGDF8yFQpNTh=cS`kntHtwd_? zM!@gTnJkhNPvzx_kD3u)mK=N|9A0%e_3y~eV|-&ILgSRgmIQ~mN5kUnd9u5TyB!Ay z9*`I9H>Icp65w6L*l`;M5DRjGUq3ln<%w@mcBWZ}1Rz^KJf2=qSr_Li8hDsTX+KD+ zU<|W3UGkJ1oZAcn6skw|DXskYSWZz0wgz$;HxNwGM%{h;@gpuJvX$WhR3 zNm+s%C(pTZ4UR&%U#r>~KhRE4;Ayb7SaDdwQNW1N3U!omzyC@`g&B)jfrdkbgK@Cg;3q`~> AQUCw| delta 692 zcmey)H<4{ZW<4_(w;W4PzRYz71_sp<*NBpo#FA921GbWniGS;X^EnhTQy=%(P0}8lvBNJOpacfZI@#nVVW%l31TxfTqb9Xub)= zmcWOTq!<_&KYF@2hE&{oJNsZ+ivo}9!OQ>ur|y2Sl9kQ3!9niZ-PqO4CruMe+Bh2p zoH!I)fCQs*6mQAA^mvAgIxU(rT&`=YbF+k82?#My+Olm`@#0Rap5xh?OE;J8b2Y7x zx>UQf%SC6?sU*jhOV(*7svXo{!~-J-~` z%Qxky%_N=I{V}tX*Rt+4X^@bA-nL4?|D8%@*o5k@86WZtEAFr=hWk4RwD7TVE@|43 zeU~$A!hyzp^&VA+xr8)WH_qXTaAb17@gVK&FVdQ&MBb@00;{o-T(jq diff --git a/src-tauri/icons/android/mipmap-xxxhdpi/ic_notification.png b/src-tauri/icons/android/mipmap-xxxhdpi/ic_notification.png index 334958c5d9872318b4ea49fffd69def7d0aa669b..5f39b5f1a475e27187f307545eeef3b31c91777f 100644 GIT binary patch delta 2529 zcmZ{mS5VW57Kf8iB1C!@0s;v=7(_$wAcP`d4aJavNMC{*5fDiL5hFziC4dycup(t? zQWS*0(os-C?@_$CTtX8Bq{ww&?#w>y@8!(=X1@96Je--+2dxoL3!oh1;gf-e3v0)N zKp-U921mY5B>Nir-1Pl5K&R2CF(|Y?3Vrqx+Q9JiSwpm*CK_#sMsIw61^EXM5_&!0 zM&!Q()OJYQFF@`8268}%@9$(HC4}_v(0I8r5d`8B##&okikMm{xKk;28Qx>IGt?8Z z5^wpu!P_G^9n;8D(rS}{bFlOWCtS#kQ)*LkJyZ53M;a-@XF5D~Oh?WAVaaoQWwnpi zV22Z>HsZ>6U1ITp%Uq#%?o3awQpU|<>KT*7ox%63`H?dP&UG(mS2(!_?Q4-g2iNiw z=>JG~iSjbkUjq9nm(v@H+1$UbIHGfKhAmD|`6y%zHa5x}l1p;2LtOS+K-|5=%AgDO zm)T8eFBxL5jRrZC>3A})+MUQiRArwj+v70EcX3f66btx5xLuw`KpRsRfy&&9!us47 zd%H8KhHX;MpQR5527w{na>@ZTrV-Kv8Sse7K(1uGaANUdi?YvD7anWdVMHR0`OS9n z%D2T737rP?80jI>Q5v~|>2@oyQykm=$UhqUUk2HAnok%#^_-6BLAz&F(X;#WDg)i$ zAt;B=EJe3{FIw85p<8`cgIgfU5VPqUu2LhYU*E_435%B56+|Cda0Df^U=II# z(2dCIad5`#=v6LlP+{D`afg;`NRDod-nv_!o@tIq=$qujvurZ}LJ%j3|HXsn-D_=6 zj2!~V>;YgBa08YiAYXX=x&T#Rno9ACIv1P;W~;D!0O#0E9WbxX(;c6NQmF}EV}W3B zBbROKLE9xCYI0Cq5ZI793fPJ|?#%=HRCxjlt@33r9@qqKu$zE2>Q`#s;K?9G(Vk_k zXAV(+&{Fl1QFKY{-mUj*@T`Hft5`#i3r$Ln2mCZfag*jA&P2NcaZQu5M9P>yVlda< zo%743eO%H%Gyo!O1H5?TV4Q$&`xmJ}v0mUJu*#()WhW6&7m4WVX3eYK#0j|cb z5v{JCH2J%q4BH#7*`QRA!S7-fz|St5Ia+a#L*&8>IA;!?wzjo!d z-5@i`Kl1ZOAmb2DSG11JqSeGPK0Ey18XkES_HA`(6F{maMlsA223kCbGELZT{(@j{ zMx?eQf?~zM5TRyxL~lXJg@xCEufVs7Gv}jg%CAvi6G^D#14vPO>5~H)+{2Vr(J*35 zaGYVR5JZ6sL%eGtFWsrMhyhc&#$Y9Npk2AfscdJd#t&6S4lF^pi9RLl8hzwz?^$@3 zpNZ7=ajX~ue#(PAFRq*d#um{>a!5p`HWn{I`e$u0;ObQWBXPR|U z>?)jD3Lb(#R>yp@9eNaxpxl6|+96#MT6ysnB6f zNve(Yy&p_Lf~!PWZi>NbTWXggm@<_3oW{p)`GjD9=4GIurhGH0KWHp(IkaA&JAXVUgZ*d@HJ5}OFjt9e!Gat)E-E^tGNgp9rARTOI&D}nnIknnr#ehoUm zhLl?@tBQq^)H_af-iBO_7%%PfW+%12%G?3zfyQ6t{8X%Tsp?piOwXp+i{SHoyh!1{vA)skYhofv}NVk7>M&7yz^#^bypX3MhjV!vhq5II+2c@qVk zU~3;iU1!BnFt+BQm`>tlSMLLQaLk>GqX)|h_TLl--x#vPzc{wWN!?b;&IHX)s43H= z3zTlElU%<$<@eznD3IOX>VzY1k6r0aQwKB%NK83I?gJNucB&_A%N(o^-qpq&zvkH4 zhNh|bYp)kp{$3>3?Tx2yKG5$Awx^med0Dh276#PAru9W>SAqc9+F1=`w<~*k!rlYn z4HH&7)T}iDA-i7#@KHV2MeeE*YQl?EGa0P$y%pY-_`fJ(bvVeb{gMCss%XoxmxFw= z)McHc3tCDrVgD%YH^zA@gP=y(7FR^EhVTct$PfD>&?dF$liHC0w81J z+h+xxr|p6D#0$2vBTh)dL6VN@@Kz-%6D@%^u=*^7tFIHA9uI#qC*_&1Dl!Ju>YAxk z?%O>Cd~ngMbCvfL0?4(?R>t?m2xmxVB~R&!N>e(gHbwzuCayoxr(?a$+?D0p*uy^h0yucLwLxXUz(AqwH-U8%Pla{VTIf(2 z!Dz0!+wY*#K1#V{H%`8LrqZS)PT+B9XQLhXhx+&QjRcP(t)(^f#LT9*@H#kpvWJsM z5gwJ@)8jZ6D3N=G2*fz6fg6PmKWiY|^3kYpcVgk>ebmE)dJFl7v}%nHnOoLlD-K+| z*NraUoagM)S`aT`Mk-p{{m%TAJ$g845#;=%K)sTxw1S92DLkDVm2MxC)qD1&OUddR zj8W(07Y_Ya&c%=~3l%)G^xw9p=Cmd$sOe+)W|olCz0%#lw<2sz@Ye zT|y{mdsa%_=E3kE&a59cs6*_-kLuF_ZAQLeOuya&O3BH#nJLIrIqr1;a>E6}R(9k9mut>MVD~oL_<3A%hTbzq|?1D4!Px$ny2?3N-9g<|v zWV-zK)#14TXA?+6u`Nr2ENvx@EKvuRS@M%JO@`g(Hld zjpx482h`hNywGueC-r`85~Qfbj*>%74V->kL#w?)|- z>FB*a8$ruFx;E#axNpME%w(ea({~0$Uny|fRFqq-FXxCWMcfsdae`R%>%{_LZO&W& IX-SCtADj@DE&u=k delta 877 zcmdlWa*};QW<4_(w;W4PzRYz71_sp<*NBpo#FA921GbWniGS;X^EnhTQy=%(P0}8lvBNJOpacfZI@#nVVW%l31TxfTqb9Xub)= zmcWOTq!<{OR(iTPhE&{oJI8xcvjLBbYnGX1*t>d-O;TMAxql|6c)kla?Oxe1ahEQm z;tUR;CCH#-(^;zz``$l2uq|`p%0<(jPJYne$Y$zdvzqJSdTEj5uKKi=2s6ot)u$9B zlSPzWHYJGcm&j%jzG3XqVXyTk`OLiDgx(m(KRI{ed@DHn?rQ%l`=#Cc*ZALy&}%w3 zcy@3YDAm3Ee>-u#;hy{XdA%-)E2EEHo80|8(`LJ_=OWg#FIe-UFMTjc%(7it5p}#I zl-GG8XWZ96$B$k+wPw}@*{P4}Rn@cWuJyd=I@b9k)bgC!lAkZm9mzizetW{J#hkVK zjVG_Vvy^wGlVu-H*)smS@H$u&*?W z@BRx}`I3;M8;>^~vJag6`@`j3y??szt2(*=)_8j%*X0z0{-Mc7=H@jUuH>D4`|{O# zhV75MW7qRb1ci#m@dgOmyDn9H-rMC?VUjTGho)Bj_bH|i^RvFZogwsJ%K2DN(u8|F z9%^~5T*i47Mh{M$Tl8alg7(=DDGkwH!fv0+9oJZ1QF$z=&(?CZnK3cl-qKLPB#)=V z;`hnPjDd}elYwYsp2L}A^^dX~ezdIpxadHAxP;t>drdYr^Cb@LVtnW+*-*EHLo30k zozX(@ykaH}%A`bmo!nlITc1@VW z3-*uco7fg`m1L}B&=sCG^Y53G16)jJmOXdPJ^B8{^jUweR0>TCO5;6RJy|Sn$>BTQ z;!z>t4QUHBPIvj+rk<~`GuS_45}ORS*~T^Odl&sU@}=#}wFIV?{m<_2PCopJZB2Ky zOLO&2FRi`e)iNT7l8}|A1uu^#P6FSwXf5Xca Date: Wed, 5 Aug 2026 11:40:31 +0200 Subject: [PATCH 070/135] fix(timeline): prevent redacted rows from overlapping --- src/app/features/room/RoomTimeline.test.tsx | 17 ++++++++++++- src/app/features/room/RoomTimeline.tsx | 7 +++++- src/app/features/room/ThreadDrawer.tsx | 1 + .../timeline/useProcessedTimeline.test.tsx | 24 +++++++++++++++++-- .../hooks/timeline/useProcessedTimeline.ts | 16 +++++++++---- 5 files changed, 56 insertions(+), 9 deletions(-) diff --git a/src/app/features/room/RoomTimeline.test.tsx b/src/app/features/room/RoomTimeline.test.tsx index e341644b9..aa6820f70 100644 --- a/src/app/features/room/RoomTimeline.test.tsx +++ b/src/app/features/room/RoomTimeline.test.tsx @@ -20,6 +20,7 @@ const { windowFocused, rowItemIndex, rowRenders, + eventRedacted, } = vi.hoisted(() => ({ vListHandle: { scrollSize: 1000, @@ -55,6 +56,7 @@ const { windowFocused: { current: false }, rowItemIndex: { current: 0 }, rowRenders: { count: 0 }, + eventRedacted: { current: false }, })); let lastOnScroll: ((offset: number) => void) | undefined; @@ -152,10 +154,11 @@ vi.mock('$hooks/timeline/useProcessedTimeline', async (importOriginal) => { getTs: () => Date.now(), getSender: () => '@me:example.org', getId: () => '$evt1', - isRedacted: () => false, + isRedacted: () => eventRedacted.current, }, timelineSet: undefined, eventSender: '@me:example.org', + isRedacted: eventRedacted.current, editId: undefined, reactionsKey: '', content: undefined, @@ -166,6 +169,7 @@ vi.mock('$hooks/timeline/useProcessedTimeline', async (importOriginal) => { processedTimelineOptions.current = options; // Same object every call so the row memo can compare eventData by identity. fakeEvent.itemIndex = rowItemIndex.current; + fakeEvent.isRedacted = eventRedacted.current; return (options.items as number[]).length === 0 ? [] : [fakeEvent]; }, }; @@ -292,6 +296,7 @@ beforeEach(() => { windowFocused.current = false; rowItemIndex.current = 0; rowRenders.count = 0; + eventRedacted.current = false; timelineSync.eventsLength = 1; timelineSync.focusItem = undefined; timelineSync.canPaginateBack = false; @@ -504,6 +509,16 @@ describe('MemoizedTimelineItem', () => { expect(rowRenders.count).toBe(before); }); + + it('re-renders a row when its event is redacted in place', () => { + const { rerender } = renderTimeline(); + const before = rowRenders.count; + + eventRedacted.current = true; + rerender(); + + expect(rowRenders.count).toBeGreaterThan(before); + }); }); describe('unread read marker (normal sync)', () => { diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index 378d2fb73..2d59d75a2 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -291,6 +291,7 @@ const MemoizedTimelineItem = memo( prev.eventData.id === next.eventData.id && // A filtered mid-timeline insert shifts this without changing `index`. prev.eventData.itemIndex === next.eventData.itemIndex && + prev.eventData.isRedacted === next.eventData.isRedacted && prev.eventData.collapsed === next.eventData.collapsed && prev.eventData.willRenderNewDivider === next.eventData.willRenderNewDivider && prev.eventData.willRenderDayDivider === next.eventData.willRenderDayDivider && @@ -1281,7 +1282,11 @@ export function RoomTimeline({ > {(eventData, index) => ( describe('useProcessedTimeline decryption', () => { // Stable so the append-only fast path is reachable. const ignoredUsersSet = new Set(); - const renderTimeline = (getEvents: () => MatrixEvent[]) => + const renderTimeline = ( + getEvents: () => MatrixEvent[], + timelineHiddenEvents: ResolvedHiddenEventSettings = hiddenEvents + ) => renderHook(() => useProcessedTimeline({ items: getEvents().map((_, i) => i), linkedTimelines: [createTimeline(getEvents())], ignoredUsersSet, - hiddenEvents, + hiddenEvents: timelineHiddenEvents, mxUserId: MY_USER, readUptoEventId: undefined, hideMembershipEvents: true, @@ -913,6 +916,23 @@ describe('useProcessedTimeline decryption', () => { expect(bodyOf(result.current, '$enc')).toBe('the secret'); }); + it('refreshes a row whose event was redacted since it was cached', () => { + let redacted = false; + const event = createEvent({ id: '$redacted' }); + event.isRedacted = () => redacted; + const { result, rerender } = renderTimeline(() => [event], { + ...hiddenEvents, + showTombstoneEvents: true, + }); + + expect(result.current[0]?.isRedacted).toBe(false); + + redacted = true; + rerender(); + + expect(result.current[0]?.isRedacted).toBe(true); + }); + it('keeps the append-only fast path for unencrypted events', () => { let events: MatrixEvent[] = [createEvent({ id: '$a', ts: 999_000 })]; const { result, rerender } = renderTimeline(() => events); diff --git a/src/app/hooks/timeline/useProcessedTimeline.ts b/src/app/hooks/timeline/useProcessedTimeline.ts index ef3ab9a5c..137655db6 100644 --- a/src/app/hooks/timeline/useProcessedTimeline.ts +++ b/src/app/hooks/timeline/useProcessedTimeline.ts @@ -41,6 +41,7 @@ export interface ProcessedEvent { id: string; itemIndex: number; mEvent: MatrixEvent; + isRedacted: boolean; timelineSet: EventTimelineSet; eventSender: string | null; collapsed: boolean; @@ -110,6 +111,7 @@ type ProcessedEventDraft = Omit< type TimelineEventEntry = { mEvent: MatrixEvent; timelineSet: EventTimelineSet; + isRedacted: boolean; // Decryption rewrites a MatrixEvent in place, so identity alone does not prove a cached // row still matches it. Undefined for unencrypted events. clearType: string | undefined; @@ -125,6 +127,7 @@ const flattenTimelineEvents = (linkedTimelines: EventTimeline[]): TimelineEventE entries.push({ mEvent, timelineSet, + isRedacted: mEvent.isRedacted(), clearType: encrypted ? mEvent.getType() : undefined, clearContent: encrypted ? mEvent.getContent() : undefined, }); @@ -138,6 +141,7 @@ const isCachedEntryCurrent = ( current: TimelineEventEntry | undefined ): boolean => cached.mEvent === current?.mEvent && + cached.isRedacted === current.isRedacted && cached.clearType === current.clearType && cached.clearContent === current.clearContent; @@ -233,6 +237,7 @@ const mergeDraftsAndExtras = ( id: mEvent.getId()!, itemIndex, mEvent, + isRedacted: mEvent.isRedacted(), timelineSet, eventSender: mEvent.getSender() ?? null, }, @@ -433,7 +438,7 @@ const processTimelineItems = ( for (const item of items) { const entry = timelineEvents[item]; if (!entry) continue; - const { mEvent, timelineSet } = entry; + const { mEvent, timelineSet, isRedacted } = entry; const { threadRootId } = mEvent; const mEventId = mEvent.getId(); if (!mEventId) continue; @@ -461,7 +466,7 @@ const processTimelineItems = ( } } - if (mEvent.isRedacted()) { + if (isRedacted) { const showMessageTombstone = showTombstoneEvents && isRedactableMessageType(type); const showReactionTombstone = hiddenEventReactionTombstone && isReaction; if (!showMessageTombstone && !showReactionTombstone) continue; @@ -476,8 +481,8 @@ const processTimelineItems = ( const allowSpecificHiddenEvent = (isEdit && hiddenEventEdits) || - (isReaction && !mEvent.isRedacted() && hiddenEventReactions) || - (isReaction && mEvent.isRedacted() && hiddenEventReactionTombstone) || + (isReaction && !isRedacted && hiddenEventReactions) || + (isReaction && isRedacted && hiddenEventReactionTombstone) || (isRedactionEvt && shouldShowRedactionTimelineEvent( mEvent, @@ -504,7 +509,7 @@ const processTimelineItems = ( if (isEdit && !hiddenEventEdits) continue; if (isReaction) { - if (mEvent.isRedacted()) { + if (isRedacted) { if (!hiddenEventReactionTombstone) continue; } else if (!hiddenEventReactions) { continue; @@ -555,6 +560,7 @@ const processTimelineItems = ( id: mEventId, itemIndex: item, mEvent, + isRedacted, timelineSet, eventSender, collapsed, From 44231a7363af7890bf51a5388d4867705610c646 Mon Sep 17 00:00:00 2001 From: "sable-actions[bot]" <268226691+sable-actions[bot]@users.noreply.github.com> Date: Wed, 5 Aug 2026 09:47:33 +0000 Subject: [PATCH 071/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index 79ca30963..b27924875 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -20,12 +20,12 @@ "screenshots": [], "versions": [ { - "version": "1.20.1785920392", - "buildVersion": "1.20.1785920392", - "date": "2026-08-05T09:11:46Z", - "size": 18915504, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260805085952-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260805085952" + "version": "1.20.1785922302", + "buildVersion": "1.20.1785922302", + "date": "2026-08-05T09:47:30Z", + "size": 18915326, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260805093142-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260805093142" } ], "appPermissions": { From 613af5fd4810e36fe0cd8417c6488120473a2264 Mon Sep 17 00:00:00 2001 From: Josie Date: Wed, 5 Aug 2026 11:54:35 +0100 Subject: [PATCH 072/135] Fix spoilers not being formed when a newline is introduced --- src/app/plugins/markdown/extensions/matrix-spoiler.ts | 2 +- src/app/styles/CustomHtml.css.ts | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/app/plugins/markdown/extensions/matrix-spoiler.ts b/src/app/plugins/markdown/extensions/matrix-spoiler.ts index 30bc2cba4..f69b171eb 100644 --- a/src/app/plugins/markdown/extensions/matrix-spoiler.ts +++ b/src/app/plugins/markdown/extensions/matrix-spoiler.ts @@ -13,7 +13,7 @@ export const matrixSpoilerExtension = { ) { // Only match if || at the very start of the remaining text if (!src.startsWith('||')) return undefined; - const rule = /^\|\|(.+?)\|\|/; + const rule = /^\|\|(.+?)\|\|/s; const match = rule.exec(src); if (match) { const token = { diff --git a/src/app/styles/CustomHtml.css.ts b/src/app/styles/CustomHtml.css.ts index dfae8c942..2b7772949 100644 --- a/src/app/styles/CustomHtml.css.ts +++ b/src/app/styles/CustomHtml.css.ts @@ -63,7 +63,6 @@ export const Code = style([ const SpoilerBase = style([ DefaultReset, { - padding: `0 ${config.space.S100}`, backgroundColor: color.SurfaceVariant.ContainerLine, borderRadius: config.radii.R300, selectors: { From 7ee34b503e0ea3bbaeb067fce5cf37b0f760bb1f Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Wed, 5 Aug 2026 14:02:59 +0200 Subject: [PATCH 073/135] fix(tauri): register single-instance plugin first --- src-tauri/src/lib.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 0d51c14d8..3dc6250fd 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -278,6 +278,12 @@ pub fn run() { let builder = tauri::Builder::::new(); + // this should always be the first + #[cfg(desktop)] + let builder = builder.plugin(tauri_plugin_single_instance::init(|app, _argv, _cwd| { + let _ = show_or_create_main_window(app); + })); + // macOS needs a standard menu (with the Edit submenu) for keyboard // copy/paste/select-all to work in the webview. It lives in the system menu // bar, so it is macOS-only to avoid an in-window menu bar elsewhere. @@ -306,11 +312,6 @@ pub fn run() { desktop::windows::window_tracking::TrackingState::new(), )); - #[cfg(desktop)] - let builder = builder.plugin(tauri_plugin_single_instance::init(|app, _argv, _cwd| { - let _ = show_or_create_main_window(app); - })); - let builder = builder.plugin(tauri_plugin_notifications::init()); #[cfg(all(desktop, feature = "updater"))] From fd61fa5663722bbc9d3a59f2d786c3a99951abe2 Mon Sep 17 00:00:00 2001 From: "sable-actions[bot]" <268226691+sable-actions[bot]@users.noreply.github.com> Date: Wed, 5 Aug 2026 12:11:57 +0000 Subject: [PATCH 074/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index b27924875..3404b5ac0 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -20,12 +20,12 @@ "screenshots": [], "versions": [ { - "version": "1.20.1785922302", - "buildVersion": "1.20.1785922302", - "date": "2026-08-05T09:47:30Z", - "size": 18915326, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260805093142-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260805093142" + "version": "1.20.1785931086", + "buildVersion": "1.20.1785931086", + "date": "2026-08-05T12:11:55Z", + "size": 18915592, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260805115806-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260805115806" } ], "appPermissions": { From 73654957406da2dce8f339020068188b1064a34b Mon Sep 17 00:00:00 2001 From: "sable-actions[bot]" <268226691+sable-actions[bot]@users.noreply.github.com> Date: Wed, 5 Aug 2026 12:28:25 +0000 Subject: [PATCH 075/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index 3404b5ac0..aa3ab5549 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -20,12 +20,12 @@ "screenshots": [], "versions": [ { - "version": "1.20.1785931086", - "buildVersion": "1.20.1785931086", - "date": "2026-08-05T12:11:55Z", - "size": 18915592, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260805115806-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260805115806" + "version": "1.20.1785932171", + "buildVersion": "1.20.1785932171", + "date": "2026-08-05T12:28:23Z", + "size": 18915387, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260805121611-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260805121611" } ], "appPermissions": { From f2424c764d9ef7374ddd9a9c28fb46ac38dbb802 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Wed, 5 Aug 2026 11:19:03 +0200 Subject: [PATCH 076/135] fix: fix cross-signing crypto refresh race --- .../components/ManualVerification.test.tsx | 66 +++++++++++++++ src/app/components/ManualVerification.tsx | 4 +- .../hooks/useCrossSigningResetDetect.test.tsx | 80 +++++++++++++++++++ src/app/hooks/useCrossSigningResetDetect.ts | 37 ++++++++- 4 files changed, 182 insertions(+), 5 deletions(-) create mode 100644 src/app/components/ManualVerification.test.tsx create mode 100644 src/app/hooks/useCrossSigningResetDetect.test.tsx diff --git a/src/app/components/ManualVerification.test.tsx b/src/app/components/ManualVerification.test.tsx new file mode 100644 index 000000000..b57717260 --- /dev/null +++ b/src/app/components/ManualVerification.test.tsx @@ -0,0 +1,66 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import type { CryptoApi } from '$types/matrix-sdk'; +import type { SecretStorageKeyContent } from '$types/matrix/accountData'; +import { ManualVerificationTile } from './ManualVerification'; + +const decodeRecoveryKey = vi.hoisted(() => vi.fn<(key: string) => Uint8Array>()); +const checkKey = vi.hoisted(() => vi.fn<() => Promise>()); +const storePrivateKey = vi.hoisted(() => vi.fn<() => void>()); +const processDeviceLists = vi.hoisted(() => vi.fn<() => Promise>()); +const bootstrapCrossSigning = vi.hoisted(() => vi.fn<() => Promise>()); +const bootstrapSecretStorage = vi.hoisted(() => vi.fn<() => Promise>()); +const loadSessionBackupPrivateKeyFromSecretStorage = vi.hoisted(() => vi.fn<() => Promise>()); + +vi.mock('$types/matrix-sdk', () => ({ decodeRecoveryKey })); +vi.mock('$client/secretStorageKeys', () => ({ storePrivateKey })); +vi.mock('$hooks/useMatrixClient', () => ({ + useMatrixClient: () => ({ + getSafeUserId: () => '@me:example.org', + secretStorage: { checkKey }, + getCrypto: () => + ({ + processDeviceLists, + bootstrapCrossSigning, + bootstrapSecretStorage, + loadSessionBackupPrivateKeyFromSecretStorage, + }) as unknown as CryptoApi, + }), +})); + +const KEY_ID = 'key-id'; +const KEY_CONTENT = { algorithm: 'm.secret_storage.v1.aes-hmac-sha2' } as SecretStorageKeyContent; +const recoveryKey = new Uint8Array([1, 2, 3]); + +const submitRecoveryKey = (value: string) => { + const input = document.querySelector('form input') as HTMLInputElement; + fireEvent.change(input, { target: { value } }); + const form = input.closest('form') as HTMLFormElement; + Object.defineProperty(form, input.name, { value: input, configurable: true }); + fireEvent.submit(form); +}; + +describe('ManualVerificationTile', () => { + beforeEach(() => { + vi.clearAllMocks(); + decodeRecoveryKey.mockReturnValue(recoveryKey); + checkKey.mockResolvedValue(true); + processDeviceLists.mockResolvedValue(undefined); + bootstrapCrossSigning.mockResolvedValue(undefined); + bootstrapSecretStorage.mockResolvedValue(undefined); + loadSessionBackupPrivateKeyFromSecretStorage.mockResolvedValue(undefined); + }); + + it('refreshes cross-signing public keys before importing the recovery key', async () => { + render( + + ); + + submitRecoveryKey('valid-key'); + + await waitFor(() => expect(screen.getByText('Device verified!')).toBeInTheDocument()); + expect(storePrivateKey).toHaveBeenCalledWith(KEY_ID, recoveryKey); + expect(processDeviceLists).toHaveBeenCalledWith({ changed: ['@me:example.org'] }); + expect(bootstrapCrossSigning).toHaveBeenCalledAfter(processDeviceLists); + }); +}); diff --git a/src/app/components/ManualVerification.tsx b/src/app/components/ManualVerification.tsx index 980623c01..9ced6cf2a 100644 --- a/src/app/components/ManualVerification.tsx +++ b/src/app/components/ManualVerification.tsx @@ -5,6 +5,7 @@ import { Box, Text, Chip, PopOut, Menu, config, MenuItem, color } from 'folds'; import { CaretDown, sizedIcon } from '$components/icons/phosphor'; import FocusTrap from 'focus-trap-react'; import type { SecretStorageKeyContent } from '$types/matrix/accountData'; +import type { CryptoBackend } from '$types/matrix-sdk'; import { storePrivateKey } from '$client/secretStorageKeys'; import { stopPropagation } from '$utils/keyboard'; import { useMatrixClient } from '$hooks/useMatrixClient'; @@ -117,13 +118,14 @@ export function ManualVerificationTile({ const verifyAndRestoreBackup = useCallback( async (recoveryKey: Uint8Array) => { - const crypto = mx.getCrypto(); + const crypto = mx.getCrypto() as CryptoBackend | undefined; if (!crypto) { throw new Error('Unexpected Error! Crypto object not found.'); } storePrivateKey(secretStorageKeyId, recoveryKey); + await crypto.processDeviceLists({ changed: [mx.getSafeUserId()] }); await crypto.bootstrapCrossSigning({}); await crypto.bootstrapSecretStorage({}); diff --git a/src/app/hooks/useCrossSigningResetDetect.test.tsx b/src/app/hooks/useCrossSigningResetDetect.test.tsx new file mode 100644 index 000000000..27115494e --- /dev/null +++ b/src/app/hooks/useCrossSigningResetDetect.test.tsx @@ -0,0 +1,80 @@ +import { act, renderHook } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { MatrixClient, MatrixEvent } from '$types/matrix-sdk'; +import { useCrossSigningResetDetect } from './useCrossSigningResetDetect'; + +const { useAccountDataCallback } = vi.hoisted(() => ({ + useAccountDataCallback: + vi.fn<(mx: MatrixClient | undefined, callback: (event: MatrixEvent) => void) => void>(), +})); + +vi.mock('./useAccountDataCallback', () => ({ useAccountDataCallback })); + +const ownUserId = '@me:example.org'; +const crossSigningEvent = { getType: () => 'm.cross_signing.master' } as MatrixEvent; + +const getAccountDataCallback = () => { + const callback = useAccountDataCallback.mock.calls[0]?.[1]; + if (!callback) throw new Error('Expected an account data callback'); + return callback; +}; + +describe('useCrossSigningResetDetect', () => { + beforeEach(() => { + vi.useFakeTimers(); + useAccountDataCallback.mockClear(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it('defers and coalesces cross-signing device list refreshes', async () => { + const processDeviceLists = vi + .fn<(...args: unknown[]) => Promise>() + .mockResolvedValue(undefined); + const mx = { + getCrypto: () => ({ processDeviceLists }), + getSafeUserId: () => ownUserId, + } as unknown as MatrixClient; + + renderHook(() => useCrossSigningResetDetect(mx)); + const onAccountData = getAccountDataCallback(); + + onAccountData(crossSigningEvent); + onAccountData(crossSigningEvent); + expect(processDeviceLists).not.toHaveBeenCalled(); + + await act(async () => { + await vi.advanceTimersByTimeAsync(0); + }); + + expect(processDeviceLists).toHaveBeenCalledOnce(); + expect(processDeviceLists).toHaveBeenCalledWith({ changed: [ownUserId] }); + }); + + it('cancels a queued refresh when the client is replaced', () => { + const processDeviceLists = vi + .fn<(...args: unknown[]) => Promise>() + .mockResolvedValue(undefined); + const mx = { + getCrypto: () => ({ processDeviceLists }), + getSafeUserId: () => ownUserId, + } as unknown as MatrixClient; + const props: { client: MatrixClient | undefined } = { client: mx }; + + const { rerender } = renderHook( + ({ client }: { client: MatrixClient | undefined }) => useCrossSigningResetDetect(client), + { + initialProps: props, + } + ); + const onAccountData = getAccountDataCallback(); + onAccountData(crossSigningEvent); + + rerender({ client: undefined }); + act(() => vi.runAllTimers()); + + expect(processDeviceLists).not.toHaveBeenCalled(); + }); +}); diff --git a/src/app/hooks/useCrossSigningResetDetect.ts b/src/app/hooks/useCrossSigningResetDetect.ts index 21fdc65cf..f9365fb45 100644 --- a/src/app/hooks/useCrossSigningResetDetect.ts +++ b/src/app/hooks/useCrossSigningResetDetect.ts @@ -1,14 +1,43 @@ -import { useCallback } from 'react'; +import { useCallback, useEffect, useRef } from 'react'; import type { CryptoBackend, MatrixClient, MatrixEvent } from '$types/matrix-sdk'; import { useAccountDataCallback } from './useAccountDataCallback'; export const useCrossSigningResetDetect = (mx: MatrixClient | undefined) => { + const refreshScheduled = useRef(false); + const refreshTimer = useRef>(); + + useEffect( + () => () => { + if (refreshTimer.current === undefined) return; + globalThis.clearTimeout(refreshTimer.current); + refreshTimer.current = undefined; + refreshScheduled.current = false; + }, + [mx] + ); + const onAccountData = useCallback( (evt: MatrixEvent) => { if (!mx || !evt.getType().startsWith('m.cross_signing.')) return; - const crypto = mx.getCrypto() as CryptoBackend | undefined; - if (!crypto) return; - void crypto.processDeviceLists({ changed: [mx.getSafeUserId()] }); + if (refreshScheduled.current) return; + refreshScheduled.current = true; + + // Wait for sync to update crypto before refreshing device lists. + refreshTimer.current = globalThis.setTimeout(() => { + refreshTimer.current = undefined; + const crypto = mx.getCrypto() as CryptoBackend | undefined; + if (!crypto) { + refreshScheduled.current = false; + return; + } + + void crypto + .processDeviceLists({ changed: [mx.getSafeUserId()] }) + .catch(() => undefined) + .finally(() => { + refreshScheduled.current = false; + }); + }, 0); }, [mx] ); From 8cfbe0d136f8473e38c188a2a7f146ecdac94d1c Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Wed, 5 Aug 2026 12:04:22 +0200 Subject: [PATCH 077/135] fix(dm): resolve bridged DM metadata --- src/app/hooks/useRoomMeta.test.tsx | 149 ++++++++++++++++++--- src/app/hooks/useRoomMeta.ts | 25 ++-- src/app/utils/room/directMember.test.ts | 52 +++++++ src/app/utils/room/directMember.ts | 41 ++++++ src/app/utils/room/display.test.ts | 122 +++++++++++++++++ src/app/utils/room/display.ts | 29 +++- src/client/slidingSync.test.ts | 15 ++- src/client/slidingSync.ts | 4 + src/client/slidingSyncSidebarCache.test.ts | 18 ++- src/client/slidingSyncSidebarCache.ts | 9 +- 10 files changed, 426 insertions(+), 38 deletions(-) create mode 100644 src/app/utils/room/directMember.test.ts create mode 100644 src/app/utils/room/directMember.ts diff --git a/src/app/hooks/useRoomMeta.test.tsx b/src/app/hooks/useRoomMeta.test.tsx index 6e13a4300..fc0db2ef7 100644 --- a/src/app/hooks/useRoomMeta.test.tsx +++ b/src/app/hooks/useRoomMeta.test.tsx @@ -1,11 +1,13 @@ import { describe, it, expect } from 'vitest'; import { renderHook, act } from '@testing-library/react'; import { EventEmitter } from 'events'; +import { Provider as JotaiProvider, createStore } from 'jotai'; import type { PropsWithChildren } from 'react'; import type { MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk'; -import { RoomStateEvent } from '$types/matrix-sdk'; +import { EventType, RoomStateEvent } from '$types/matrix-sdk'; +import { mDirectAtom } from '$state/mDirectList'; import { MatrixClientProvider } from './useMatrixClient'; -import { useRoomAvatar } from './useRoomMeta'; +import { useRoomAvatar, useRoomName } from './useRoomMeta'; const AVATAR_MXC = 'mxc://server/abc'; @@ -74,30 +76,19 @@ describe('useRoomAvatar', () => { }); it('updates a DM avatar when its member state arrives after the sidebar rendered', () => { - const member = { - getMxcAvatarUrl: () => AVATAR_MXC, - membership: 'join', - userId: '@alice:server', - }; - const { room, client, wrapper } = makeRoom('!dm:server'); + const { room, wrapper } = makeRoom('!dm:server'); const roomEvents = new EventEmitter(); - let members = [{ membership: 'join', userId: '@me:server' }]; + let fallbackMember: { getMxcAvatarUrl: () => string } | undefined; Object.assign(room, { - getMember: (userId: string) => members.find((roomMember) => roomMember.userId === userId), - getMembers: () => members, - getAvatarFallbackMember: () => undefined, + getAvatarFallbackMember: () => fallbackMember, on: roomEvents.on.bind(roomEvents), removeListener: roomEvents.removeListener.bind(roomEvents), }); - Object.assign(client, { - getAccountData: () => ({ getContent: () => ({ '@alice:server': [room.roomId] }) }), - getUserId: () => '@me:server', - }); const { result } = renderHook(() => useRoomAvatar(room, true), { wrapper }); expect(result.current).toBeUndefined(); - members = [{ membership: 'join', userId: '@me:server' }, member]; + fallbackMember = { getMxcAvatarUrl: () => AVATAR_MXC }; act(() => { roomEvents.emit(RoomStateEvent.Members); }); @@ -105,3 +96,127 @@ describe('useRoomAvatar', () => { expect(result.current).toBe(AVATAR_MXC); }); }); + +const makeNameRoom = ( + roomId: string, + { + mDirects = {}, + members = {}, + fallbackMember, + functionalMemberIds = [], + name = 'Room', + nameEventId, + }: { + mDirects?: Record; + members?: Record; + fallbackMember?: { userId: string; rawDisplayName?: string; membership?: string }; + functionalMemberIds?: string[]; + name?: string; + nameEventId?: string; + } +) => { + const client = new EventEmitter(); + const stateEvents: Record = { + [EventType.RoomName]: nameEventId + ? ({ + getId: () => nameEventId, + getContent: () => ({ name }), + } as unknown as MatrixEvent) + : undefined, + 'io.element.functional_members': functionalMemberIds.length + ? ({ getContent: () => ({ service_members: functionalMemberIds }) } as unknown as MatrixEvent) + : undefined, + }; + const room = { + roomId, + client, + name, + guessDMUserId: () => '', + recalculate: () => {}, + getLiveTimeline: () => ({ + getState: () => ({ getStateEvents: (type: string) => stateEvents[type] }), + }), + getMember: (userId: string) => members[userId], + getMembers: () => [{ userId: '@me:server', membership: 'join' }, ...Object.values(members)], + getAvatarFallbackMember: () => fallbackMember, + on: client.on.bind(client), + removeListener: client.removeListener.bind(client), + } as unknown as Room; + Object.assign(client, { + getAccountData: () => ({ getContent: () => mDirects }), + getUserId: () => '@me:server', + }); + + const store = createStore(); + store.set(mDirectAtom, { type: 'INITIALIZE', rooms: new Set(Object.values(mDirects).flat()) }); + + const wrapper = ({ children }: PropsWithChildren) => ( + + + {children} + + + ); + return { room, client, wrapper }; +}; + +describe('useRoomName', () => { + const fakeNameEventId = '$fake-sliding-sync-name-event-!dm:server'; + + it('prefers the counterpart over the sliding-sync server name for a bridged DM', () => { + const { room, wrapper } = makeNameRoom('!dm:server', { + mDirects: { '@alice:server': ['!dm:server'] }, + members: { + '@alice:server': { rawDisplayName: 'Alexia', membership: 'join' }, + '@signal-service:server': { membership: 'join' }, + }, + functionalMemberIds: ['@signal-service:server'], + name: 'Alexia, Signal Bridge bot', + nameEventId: fakeNameEventId, + }); + + const { result } = renderHook(() => useRoomName(room), { wrapper }); + + expect(result.current).toBe('Alexia'); + }); + + it('falls back to the hero member name when sliding sync has no member state', () => { + const { room, wrapper } = makeNameRoom('!dm:server', { + mDirects: { '@alice:server': ['!dm:server'] }, + functionalMemberIds: ['@signal-service:server'], + fallbackMember: { userId: '@alice:server', rawDisplayName: 'Alexia', membership: 'join' }, + name: 'Alexia, Signal Bridge bot', + nameEventId: fakeNameEventId, + }); + + const { result } = renderHook(() => useRoomName(room), { wrapper }); + + expect(result.current).toBe('Alexia'); + }); + + it('keeps a genuine m.room.name on a DM', () => { + const { room, wrapper } = makeNameRoom('!dm:server', { + mDirects: { '@alice:server': ['!dm:server'] }, + members: { + '@alice:server': { rawDisplayName: 'Alexia', membership: 'join' }, + }, + name: 'Movie Club', + nameEventId: '$real-name-event:server', + }); + + const { result } = renderHook(() => useRoomName(room), { wrapper }); + + expect(result.current).toBe('Movie Club'); + }); + + it('keeps the sliding-sync server name for non-DM rooms', () => { + const { room, wrapper } = makeNameRoom('!room:server', { + name: 'Bridge Lobby', + nameEventId: '$fake-sliding-sync-name-event-!room:server', + }); + + const { result } = renderHook(() => useRoomName(room), { wrapper }); + + expect(result.current).toBe('Bridge Lobby'); + }); +}); diff --git a/src/app/hooks/useRoomMeta.ts b/src/app/hooks/useRoomMeta.ts index c7fc53eba..6b62a82c6 100644 --- a/src/app/hooks/useRoomMeta.ts +++ b/src/app/hooks/useRoomMeta.ts @@ -1,6 +1,6 @@ import { useAtomValue } from 'jotai'; import { useEffect, useState } from 'react'; -import type { RoomJoinRulesEventContent, Room } from '$types/matrix-sdk'; +import type { MatrixEvent, RoomJoinRulesEventContent, Room } from '$types/matrix-sdk'; import { RoomEvent, RoomStateEvent, EventType } from '$types/matrix-sdk'; import { mDirectAtom } from '$state/mDirectList'; @@ -9,21 +9,26 @@ import { useMatrixClient } from './useMatrixClient'; import { useStateEvent } from './useStateEvent'; import { useNickname } from './useNickname'; +// Sliding sync's ensureNameEvent injects the server-computed room name with this +// fake event id; it counts bridge bots, so DMs rank it below the member name. +const isServerGeneratedRoomName = (event?: MatrixEvent): boolean => + event?.getId()?.startsWith('$fake-sliding-sync-name-event-') === true; + const getRoomDisplayName = ( roomName: string, stateName: unknown, + stateNameIsServerGenerated: boolean, isDmTagged: boolean, dmNickname?: string, dmOtherMemberName?: string ): string => { if (isDmTagged && dmNickname) return dmNickname; - if (typeof stateName === 'string' && stateName) return stateName; + if (typeof stateName === 'string' && stateName && !stateNameIsServerGenerated) return stateName; if (isDmTagged && dmOtherMemberName) return dmOtherMemberName; return roomName; }; export const useRoomAvatar = (room: Room, dm?: boolean): string | undefined => { - const mx = useMatrixClient(); const avatarEvent = useStateEvent(room, EventType.RoomAvatar); const [, refreshDmAvatar] = useState(0); @@ -39,7 +44,7 @@ export const useRoomAvatar = (room: Room, dm?: boolean): string | undefined => { }, [room, dm]); if (dm) { - return getDmOtherMember(mx, room)?.getMxcAvatarUrl(); + return room.getAvatarFallbackMember()?.getMxcAvatarUrl(); } const content = avatarEvent?.getContent(); const avatarMxc = content && typeof content.url === 'string' ? content.url : undefined; @@ -49,28 +54,30 @@ export const useRoomAvatar = (room: Room, dm?: boolean): string | undefined => { export const useRoomName = (room: Room): string => { const mx = useMatrixClient(); - const dmUserId = room.guessDMUserId(); - const dmNickname = useNickname(dmUserId || ''); const mDirects = useAtomValue(mDirectAtom); const isDmTagged = mDirects.has(room.roomId); + const dmUserId = room.guessDMUserId(); + const dmNickname = useNickname(dmUserId || ''); const nameEvent = useStateEvent(room, EventType.RoomName); const stateName = nameEvent?.getContent().name; + const stateNameIsServerGenerated = isServerGeneratedRoomName(nameEvent); const [name, setName] = useState(room.name); useEffect(() => { const updateName = () => { - if (room.name === 'Empty room') { + if (isDmTagged || room.name === 'Empty room') { room.recalculate(); } const otherMember = isDmTagged ? getDmOtherMember(mx, room) : undefined; const dmOtherMemberName = otherMember - ? (getMemberDisplayName(room, otherMember.userId) ?? otherMember.userId) + ? (getMemberDisplayName(room, otherMember.userId) ?? otherMember.rawDisplayName) : undefined; const nextName = getRoomDisplayName( room.name, stateName, + stateNameIsServerGenerated, isDmTagged, dmNickname, dmOtherMemberName @@ -87,7 +94,7 @@ export const useRoomName = (room: Room): string => { room.removeListener(RoomEvent.Name, updateName); room.removeListener(RoomStateEvent.Members, updateName); }; - }, [room, mx, stateName, dmNickname, isDmTagged]); + }, [room, mx, stateName, stateNameIsServerGenerated, dmNickname, isDmTagged]); return name; }; diff --git a/src/app/utils/room/directMember.test.ts b/src/app/utils/room/directMember.test.ts new file mode 100644 index 000000000..f71ac00af --- /dev/null +++ b/src/app/utils/room/directMember.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it } from 'vitest'; +import { isFunctionalMember, resolveDmOtherMember } from './directMember'; + +const me = { membership: 'join', userId: '@me:example.org' }; +const alice = { membership: 'join', userId: '@alice:example.org' }; +const bridge = { membership: 'join', userId: '@signal-service:example.org' }; + +describe('resolveDmOtherMember', () => { + it('prefers the sole active m.direct member', () => { + expect( + resolveDmOtherMember({ + currentUserId: me.userId, + directMembers: [alice], + members: [me, alice, bridge], + functionalMemberIds: [], + fallbackMember: bridge, + }) + ).toBe(alice); + }); + + it('excludes functional members from m.direct and membership fallbacks', () => { + expect( + resolveDmOtherMember({ + currentUserId: me.userId, + directMembers: [bridge], + members: [me, alice, bridge], + functionalMemberIds: [bridge.userId], + fallbackMember: bridge, + }) + ).toBe(alice); + }); + + it('does not infer service membership from an MXID', () => { + const alicebot = { membership: 'join', userId: '@alicebot:example.org' }; + + expect( + resolveDmOtherMember({ + currentUserId: me.userId, + directMembers: [alicebot], + members: [me, alicebot], + functionalMemberIds: [], + }) + ).toBe(alicebot); + }); +}); + +describe('isFunctionalMember', () => { + it('can be reused by other member surfaces', () => { + expect(isFunctionalMember(bridge, [bridge.userId])).toBe(true); + expect(isFunctionalMember(alice, [bridge.userId])).toBe(false); + }); +}); diff --git a/src/app/utils/room/directMember.ts b/src/app/utils/room/directMember.ts new file mode 100644 index 000000000..53863c3da --- /dev/null +++ b/src/app/utils/room/directMember.ts @@ -0,0 +1,41 @@ +export type DirectRoomMember = { + userId: string; + membership?: string; +}; + +type ResolveDmOtherMemberInput = { + currentUserId: string | null; + directMembers: Member[]; + members: Member[]; + functionalMemberIds: string[]; + fallbackMember?: Member; +}; + +export const isFunctionalMember = ( + member: DirectRoomMember, + functionalMemberIds: readonly string[] +): boolean => functionalMemberIds.includes(member.userId); + +const isActiveMember = (member: DirectRoomMember): boolean => + member.membership === 'join' || member.membership === 'invite'; + +export const resolveDmOtherMember = ({ + currentUserId, + directMembers, + members, + functionalMemberIds, + fallbackMember, +}: ResolveDmOtherMemberInput): Member | undefined => { + const isFunctional = (member: DirectRoomMember) => + isFunctionalMember(member, functionalMemberIds); + + const directMember = directMembers.filter((member) => !isFunctional(member)); + if (directMember.length === 1 && isActiveMember(directMember[0]!)) return directMember[0]; + + const otherMembers = members.filter( + (member) => member.userId !== currentUserId && !isFunctional(member) && isActiveMember(member) + ); + if (otherMembers.length === 1) return otherMembers[0]; + + return fallbackMember && !isFunctional(fallbackMember) ? fallbackMember : undefined; +}; diff --git a/src/app/utils/room/display.test.ts b/src/app/utils/room/display.test.ts index 5830acc08..4d5e7c999 100644 --- a/src/app/utils/room/display.test.ts +++ b/src/app/utils/room/display.test.ts @@ -10,6 +10,7 @@ describe('getDmOtherMember', () => { const invitedMember = makeMember('@alice:example.org', 'invite'); const room = { getMember: (userId: string) => (userId === invitedMember.userId ? invitedMember : undefined), + getMembers: () => [invitedMember], getAvatarFallbackMember: () => undefined, roomId: '!dm:example.org', } as unknown as Room; @@ -21,10 +22,36 @@ describe('getDmOtherMember', () => { expect(getDmOtherMember(mx, room)).toBe(invitedMember); }); + it('ignores missing m.direct members', () => { + const counterpart = makeMember('@alice:example.org', 'join'); + const room = { + getMember: (userId: string) => { + if (userId === counterpart.userId) return counterpart; + if (userId === '@missing:example.org') return null; + return undefined; + }, + getMembers: () => [counterpart], + getAvatarFallbackMember: () => undefined, + roomId: '!dm:example.org', + } as unknown as Room; + const mx = { + getAccountData: () => ({ + getContent: () => ({ + [counterpart.userId]: [room.roomId], + '@missing:example.org': [room.roomId], + }), + }), + getUserId: () => '@me:example.org', + } as unknown as MatrixClient; + + expect(getDmOtherMember(mx, room)).toBe(counterpart); + }); + it('uses the m.direct counterpart even when a bridge bot is also in the room', () => { const counterpart = makeMember('@alice:example.org', 'join'); const room = { getMember: (userId: string) => (userId === counterpart.userId ? counterpart : undefined), + getMembers: () => [counterpart], getAvatarFallbackMember: () => makeMember('@bridgebot:example.org', 'join'), roomId: '!dm:example.org', } as unknown as Room; @@ -35,4 +62,99 @@ describe('getDmOtherMember', () => { expect(getDmOtherMember(mx, room)).toBe(counterpart); }); + + it('does not select a functional member when it is listed in m.direct', () => { + const counterpart = makeMember('@alice:example.org', 'join'); + const bridgeMember = makeMember('@signal-service:example.org', 'join'); + const room = { + getAvatarFallbackMember: () => bridgeMember, + getLiveTimeline: () => ({ + getState: () => ({ + getStateEvents: () => ({ + getContent: () => ({ service_members: [bridgeMember.userId] }), + }), + }), + }), + getMember: (userId: string) => + [counterpart, bridgeMember].find((member) => member.userId === userId), + getMembers: () => [makeMember('@me:example.org', 'join'), counterpart, bridgeMember], + roomId: '!dm:example.org', + } as unknown as Room; + const mx = { + getAccountData: () => ({ getContent: () => ({ [bridgeMember.userId]: [room.roomId] }) }), + getUserId: () => '@me:example.org', + } as unknown as MatrixClient; + + expect(getDmOtherMember(mx, room)).toBe(counterpart); + }); + + it('selects a direct-chat participant whose MXID ends in bot', () => { + const counterpart = makeMember('@alicebot:example.org', 'join'); + const room = { + getAvatarFallbackMember: () => counterpart, + getMember: (userId: string) => (userId === counterpart.userId ? counterpart : undefined), + getMembers: () => [counterpart], + roomId: '!dm:example.org', + } as unknown as Room; + const mx = { + getAccountData: () => ({ + getContent: () => ({ + [counterpart.userId]: [room.roomId], + }), + }), + getUserId: () => '@me:example.org', + } as unknown as MatrixClient; + + expect(getDmOtherMember(mx, room)).toBe(counterpart); + }); + + it('does not select a functional bridge member from m.direct', () => { + const counterpart = makeMember('@alice:example.org', 'join'); + const bridgeMember = makeMember('@service:example.org', 'join'); + const room = { + getAvatarFallbackMember: () => bridgeMember, + getLiveTimeline: () => ({ + getState: () => ({ + getStateEvents: () => ({ + getContent: () => ({ service_members: [bridgeMember.userId] }), + }), + }), + }), + getMember: (userId: string) => + [counterpart, bridgeMember].find((member) => member.userId === userId), + getMembers: () => [makeMember('@me:example.org', 'join'), counterpart, bridgeMember], + roomId: '!dm:example.org', + } as unknown as Room; + const mx = { + getAccountData: () => ({ getContent: () => ({ '@service:example.org': [room.roomId] }) }), + getUserId: () => '@me:example.org', + } as unknown as MatrixClient; + + expect(getDmOtherMember(mx, room)).toBe(counterpart); + }); + + it('ignores a functional members event whose service_members is not an array', () => { + const counterpart = makeMember('@alice:example.org', 'join'); + const bridgeMember = makeMember('@signal-service:example.org', 'join'); + const room = { + getAvatarFallbackMember: () => bridgeMember, + getLiveTimeline: () => ({ + getState: () => ({ + getStateEvents: () => ({ + getContent: () => ({ service_members: counterpart.userId }), + }), + }), + }), + getMember: (userId: string) => + [counterpart, bridgeMember].find((member) => member.userId === userId), + getMembers: () => [makeMember('@me:example.org', 'join'), counterpart, bridgeMember], + roomId: '!dm:example.org', + } as unknown as Room; + const mx = { + getAccountData: () => ({ getContent: () => ({ [counterpart.userId]: [room.roomId] }) }), + getUserId: () => '@me:example.org', + } as unknown as MatrixClient; + + expect(getDmOtherMember(mx, room)).toBe(counterpart); + }); }); diff --git a/src/app/utils/room/display.ts b/src/app/utils/room/display.ts index f4a7ac5cd..9394cdb13 100644 --- a/src/app/utils/room/display.ts +++ b/src/app/utils/room/display.ts @@ -1,8 +1,9 @@ -import { EventType } from '$types/matrix-sdk'; -import type { MatrixClient, Room, RoomMember } from '$types/matrix-sdk'; +import { EventTimeline, EventType, UNSTABLE_ELEMENT_FUNCTIONAL_USERS } from '$types/matrix-sdk'; +import type { MatrixClient, Room, RoomMember, StateEvents } from '$types/matrix-sdk'; import { getMxIdLocalPart } from '$utils/matrix'; import { mxcUrlToHttp } from '../mediaUrl'; +import { resolveDmOtherMember } from './directMember'; /** * The square-cropped avatar conversion every avatar call site repeats. Goes @@ -26,6 +27,15 @@ export const getRoomAvatarUrl = ( ): string | undefined => getAvatarUrl(mx, room.getMxcAvatarUrl(), size, useAuthentication); export const getDmOtherMember = (mx: MatrixClient, room: Room): RoomMember | undefined => { + // A non-array service_members would otherwise make .includes a substring match. + const serviceMembers = room + .getLiveTimeline?.() + ?.getState(EventTimeline.FORWARDS) + ?.getStateEvents(UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name as keyof StateEvents, '') + ?.getContent<{ service_members?: unknown }>().service_members; + const functionalMembers = Array.isArray(serviceMembers) + ? serviceMembers.filter((userId): userId is string => typeof userId === 'string') + : []; const currentUserId = mx.getUserId(); const mDirect = mx.getAccountData(EventType.Direct)?.getContent>(); const directUserIds = Object.entries(mDirect ?? {}) @@ -35,12 +45,17 @@ export const getDmOtherMember = (mx: MatrixClient, room: Room): RoomMember | und ) .map(([userId]) => userId); - if (directUserIds.length === 1) { - const member = room.getMember(directUserIds[0]!); - if (member?.membership === 'join' || member?.membership === 'invite') return member; - } + const directMembers = directUserIds + .map((userId) => room.getMember(userId)) + .filter((member): member is RoomMember => member != null); - return room.getAvatarFallbackMember(); + return resolveDmOtherMember({ + currentUserId, + directMembers, + members: room.getMembers(), + functionalMemberIds: functionalMembers, + fallbackMember: room.getAvatarFallbackMember(), + }); }; export const getDirectRoomAvatarUrl = ( diff --git a/src/client/slidingSync.test.ts b/src/client/slidingSync.test.ts index 3324f4b00..242b35ec8 100644 --- a/src/client/slidingSync.test.ts +++ b/src/client/slidingSync.test.ts @@ -4,7 +4,13 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import type { MatrixClient, MatrixEvent, MSC3575List } from '$types/matrix-sdk'; -import { EventType, KnownMembership, SlidingSyncEvent, SlidingSyncState } from '$types/matrix-sdk'; +import { + EventType, + KnownMembership, + SlidingSyncEvent, + SlidingSyncState, + UNSTABLE_ELEMENT_FUNCTIONAL_USERS, +} from '$types/matrix-sdk'; import { scopeEphemeralExtensions, SlidingSyncManager } from './slidingSync'; import type { SlidingSyncSidebarCache } from './slidingSyncSidebarCache'; @@ -170,8 +176,9 @@ describe('SlidingSyncManager initial request', () => { expect(joined?.ranges).toEqual([[0, 29]]); expect(joined?.timeline_limit).toBe(1); - expect(joined?.required_state).toHaveLength(10); + expect(joined?.required_state).toHaveLength(11); expect(joined?.required_state).toContainEqual([EventType.RoomJoinRules, '']); + expect(joined?.required_state).toContainEqual([UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name, '']); expect(joined?.required_state).not.toContainEqual(['m.space.child', '*']); expect(updates).toMatchObject({ ranges: [[0, 29]], @@ -706,6 +713,10 @@ describe('SlidingSyncManager room subscription coordination', () => { expect(activeRoom).toBeDefined(); expect(activeRoom![1].timeline_limit).toBe(50); expect(activeRoom![1].required_state).toContainEqual([EventType.RoomMember, '$LAZY']); + expect(activeRoom![1].required_state).toContainEqual([ + UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name, + '', + ]); expect(sidebarRoom).toBeDefined(); expect(sidebarRoom![1].timeline_limit).toBe(1); diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index 3eec08431..96e9eb821 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -22,6 +22,7 @@ import { EventTimeline, EventEmitterEvents, ClientEvent, + UNSTABLE_ELEMENT_FUNCTIONAL_USERS, } from '$types/matrix-sdk'; import { createLogger } from '$utils/debug'; import { createDebugLogger } from '$utils/debugLogger'; @@ -159,6 +160,8 @@ const buildListRequiredState = (): MSC3575RoomSubscription['required_state'] => [EventType.RoomMember, MSC3575_STATE_KEY_ME], [EventType.GroupCallPrefix, ''], [EventType.GroupCallMemberPrefix, MSC3575_WILDCARD], + // Feeds functional-member filtering for bridged DM names/avatars. + [UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name, ''], ]; const SPACE_REQUIRED_STATE: MSC3575RoomSubscription['required_state'] = [ @@ -196,6 +199,7 @@ const ACTIVE_ROOM_REQUIRED_STATE: MSC3575RoomSubscription['required_state'] = [ [EventType.SpaceParent, MSC3575_WILDCARD], [EventType.GroupCallPrefix, ''], [EventType.GroupCallMemberPrefix, MSC3575_WILDCARD], + [UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name, ''], ...Object.values(CustomStateEvent).map((type) => [type, MSC3575_WILDCARD] as [string, string]), ]; diff --git a/src/client/slidingSyncSidebarCache.test.ts b/src/client/slidingSyncSidebarCache.test.ts index adff12ec0..510f36b59 100644 --- a/src/client/slidingSyncSidebarCache.test.ts +++ b/src/client/slidingSyncSidebarCache.test.ts @@ -1,6 +1,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import type { MatrixClient, MSC3575RoomData, SlidingSync } from '$types/matrix-sdk'; -import { EventType, MatrixEvent, SlidingSyncEvent } from '$types/matrix-sdk'; +import { + EventType, + MatrixEvent, + SlidingSyncEvent, + UNSTABLE_ELEMENT_FUNCTIONAL_USERS, +} from '$types/matrix-sdk'; import { CustomAccountDataEvent } from '$types/matrix/accountData'; import { SlidingSyncSidebarCache } from './slidingSyncSidebarCache'; @@ -46,6 +51,9 @@ describe('SlidingSyncSidebarCache', () => { stateEvent(EventType.SpaceChild, '!child:example.com', { via: ['example.com'] }), stateEvent(EventType.RoomMember, userId, { membership: 'join' }), stateEvent(EventType.RoomMember, '@other:example.com', { membership: 'join' }), + stateEvent(UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name, '', { + service_members: ['@bridgebot:example.com'], + }), ], timeline: [ { @@ -90,7 +98,13 @@ describe('SlidingSyncSidebarCache', () => { }) ); const hydratedRoom = emitPromised.mock.calls[0]?.[2] as MSC3575RoomData; - expect(hydratedRoom.required_state).toHaveLength(3); + expect(hydratedRoom.required_state).toHaveLength(4); + expect(hydratedRoom.required_state).toContainEqual( + expect.objectContaining({ + type: UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name, + state_key: '', + }) + ); expect(hydratedRoom.required_state).toContainEqual( expect.objectContaining({ type: EventType.SpaceChild, diff --git a/src/client/slidingSyncSidebarCache.ts b/src/client/slidingSyncSidebarCache.ts index 9ee118a35..8bdcff1d8 100644 --- a/src/client/slidingSyncSidebarCache.ts +++ b/src/client/slidingSyncSidebarCache.ts @@ -1,5 +1,11 @@ import type { MatrixClient, MSC3575RoomData, SlidingSync } from '$types/matrix-sdk'; -import { EventType, KnownMembership, MatrixEvent, SlidingSyncEvent } from '$types/matrix-sdk'; +import { + EventType, + KnownMembership, + MatrixEvent, + SlidingSyncEvent, + UNSTABLE_ELEMENT_FUNCTIONAL_USERS, +} from '$types/matrix-sdk'; import { CustomAccountDataEvent } from '$types/matrix/accountData'; import { CustomStateEvent } from '$types/matrix/room'; @@ -44,6 +50,7 @@ const CACHED_STATE_TYPES = new Set([ EventType.RoomServerAcl, EventType.SpaceChild, EventType.SpaceParent, + UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name, CustomStateEvent.PowerLevelTags, CustomStateEvent.RoomWidget, CustomStateEvent.RoomAbbreviations, From 75c8794ff71256c5707b5156dbb4ebdea747059d Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sat, 1 Aug 2026 17:06:30 +0200 Subject: [PATCH 078/135] fix(emoji-board): cancel in-flight gif searches and debounce timers --- src/app/components/emoji-board/EmojiBoard.tsx | 17 ++- .../emoji-board/useGifSearch.test.tsx | 134 ++++++++++++++++++ .../components/emoji-board/useGifSearch.ts | 58 ++++++-- src/app/hooks/useDebounce.test.tsx | 29 ++++ src/app/hooks/useDebounce.ts | 25 +++- 5 files changed, 243 insertions(+), 20 deletions(-) create mode 100644 src/app/components/emoji-board/useGifSearch.test.tsx diff --git a/src/app/components/emoji-board/EmojiBoard.tsx b/src/app/components/emoji-board/EmojiBoard.tsx index a9f6864fa..80abb06d4 100644 --- a/src/app/components/emoji-board/EmojiBoard.tsx +++ b/src/app/components/emoji-board/EmojiBoard.tsx @@ -1,5 +1,5 @@ import type { - ChangeEventHandler, + ChangeEvent, FocusEventHandler, MouseEventHandler, ReactNode, @@ -527,6 +527,7 @@ export function EmojiBoard({ loading: gifsLoading, error: gifsError, searchGifs, + cancelSearch: cancelGifSearch, } = useGifSearch(favoriteGifs, showGifPicker, gifSearch); const [emojiGroupItems, stickerGroupItems, gifGroupItems] = useGroups(tab, imagePacks, gifs); const [showFavoritesOnly, setShowFavoritesOnly] = useState(true); @@ -555,9 +556,9 @@ export function EmojiBoard({ const groups = groupsByTab[tab]; const renderItem = useItemRenderer(tab, saveStickerEmojiBandwidth); - const handleOnChange: ChangeEventHandler = useDebounce( + const handleOnChange = useDebounce( useCallback( - (evt) => { + (evt: ChangeEvent) => { const term = evt.target.value; if (tab === EmojiBoardTab.Gif) { if (term) { @@ -565,6 +566,7 @@ export function EmojiBoard({ searchGifs(term); } else { setShowFavoritesOnly(true); + cancelGifSearch(); resetGifSearch(); } } else if (term) { @@ -573,7 +575,7 @@ export function EmojiBoard({ resetEmojiSearch(); } }, - [emojiSearch, resetEmojiSearch, searchGifs, resetGifSearch, tab] + [cancelGifSearch, emojiSearch, resetEmojiSearch, searchGifs, resetGifSearch, tab] ), { wait: 200 } ); @@ -585,6 +587,13 @@ export function EmojiBoard({ else resetGifSearch(); }, [gifTab, initialGifSearch, searchGifs, resetGifSearch]); + useEffect(() => { + if (!showGifPicker) { + handleOnChange.cancel(); + cancelGifSearch(); + } + }, [cancelGifSearch, handleOnChange, showGifPicker]); + const contentScrollRef = useRef(null); const virtualBaseRef = useRef(null); const virtualizer = useVirtualizer({ diff --git a/src/app/components/emoji-board/useGifSearch.test.tsx b/src/app/components/emoji-board/useGifSearch.test.tsx new file mode 100644 index 000000000..26d37a29c --- /dev/null +++ b/src/app/components/emoji-board/useGifSearch.test.tsx @@ -0,0 +1,134 @@ +import { act, renderHook } from '@testing-library/react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { useGifSearch } from './useGifSearch'; + +const { fetchMock } = vi.hoisted(() => ({ + fetchMock: vi.fn<(input: string, init?: RequestInit) => Promise>(), +})); + +vi.mock('$utils/fetch', () => ({ fetch: fetchMock })); +vi.mock('$hooks/useClientConfig', () => ({ + useClientConfig: () => ({ gifs: { klipyApiKey: 'test-key' } }), +})); + +type Deferred = { + promise: Promise; + resolve: (value: T) => void; + reject: (reason?: unknown) => void; +}; + +const deferred = (): Deferred => { + let resolve!: (value: T) => void; + let reject!: (reason?: unknown) => void; + const promise = new Promise((promiseResolve, promiseReject) => { + resolve = promiseResolve; + reject = promiseReject; + }); + return { promise, resolve, reject }; +}; + +const responseFor = (id: string): Response => + new Response( + JSON.stringify({ + data: { + data: [ + { + id, + title: id, + file: { xs: { gif: { url: `https://${id}.preview` } } }, + }, + ], + }, + }), + { status: 200 } + ); + +const flushPromises = async () => { + await Promise.resolve(); + await Promise.resolve(); +}; + +afterEach(() => { + fetchMock.mockReset(); +}); + +describe('useGifSearch', () => { + it('keeps stale success, error, and finally handlers from changing the latest request', async () => { + const first = deferred(); + const second = deferred(); + fetchMock.mockImplementation((url: string) => + url.includes('q=first') ? first.promise : second.promise + ); + + const { result } = renderHook(() => useGifSearch([], true, vi.fn<() => void>())); + + act(() => { + void result.current.searchGifs('first'); + void result.current.searchGifs('second'); + }); + + const firstSignal = fetchMock.mock.calls[0]?.[1]?.signal as AbortSignal; + expect(firstSignal.aborted).toBe(true); + + first.reject(new Error('stale failure')); + await act(async () => { + await flushPromises(); + }); + expect(result.current.loading).toBe(true); + expect(result.current.error).toBeNull(); + + second.resolve(responseFor('second')); + await act(async () => { + await flushPromises(); + }); + expect(result.current.gifs.gifs[0]?.id).toBe('second'); + expect(result.current.loading).toBe(false); + + first.resolve(responseFor('first')); + await act(async () => { + await flushPromises(); + }); + expect(result.current.gifs.gifs[0]?.id).toBe('second'); + }); + + it('aborts and invalidates a request when cancelled or closed', async () => { + const request = deferred(); + fetchMock.mockReturnValue(request.promise); + + const { result, rerender } = renderHook( + ({ open }) => useGifSearch([], open, vi.fn<() => void>()), + { initialProps: { open: true } } + ); + + act(() => { + void result.current.searchGifs('query'); + }); + const signal = fetchMock.mock.calls[0]?.[1]?.signal as AbortSignal; + + rerender({ open: false }); + + expect(signal.aborted).toBe(true); + expect(result.current.loading).toBe(false); + + request.resolve(responseFor('stale')); + await act(async () => { + await flushPromises(); + }); + expect(result.current.gifs.gifs).toEqual([]); + }); + + it('aborts the active request on unmount', () => { + const request = deferred(); + fetchMock.mockReturnValue(request.promise); + const { result, unmount } = renderHook(() => useGifSearch([], true, vi.fn<() => void>())); + + act(() => { + void result.current.searchGifs('query'); + }); + const signal = fetchMock.mock.calls[0]?.[1]?.signal as AbortSignal; + + unmount(); + + expect(signal.aborted).toBe(true); + }); +}); diff --git a/src/app/components/emoji-board/useGifSearch.ts b/src/app/components/emoji-board/useGifSearch.ts index dc7402a66..0e2cf1421 100644 --- a/src/app/components/emoji-board/useGifSearch.ts +++ b/src/app/components/emoji-board/useGifSearch.ts @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import type { AsyncSearchHandler } from '$utils/AsyncSearch'; import { fetch } from '$utils/fetch'; import { useClientConfig } from '$hooks/useClientConfig'; @@ -57,14 +57,34 @@ export function useGifSearch( const [error, setError] = useState(null); const clientConfig = useClientConfig(); const klipyApiKey = clientConfig.gifs?.klipyApiKey ?? ''; + const requestGenerationRef = useRef(0); + const abortControllerRef = useRef(); + const mountedRef = useRef(true); + const showGifPickerRef = useRef(showGifPicker); + showGifPickerRef.current = showGifPicker; + + const cancelRequest = useCallback(() => { + requestGenerationRef.current += 1; + abortControllerRef.current?.abort(); + abortControllerRef.current = undefined; + }, []); + + const cancelSearch = useCallback(() => { + cancelRequest(); + if (mountedRef.current) setLoading(false); + }, [cancelRequest]); const searchGifs = useCallback( async (query: string) => { - if (!showGifPicker) { + if (!mountedRef.current || !showGifPickerRef.current) { return; } const trimmedQuery = query.trim(); + cancelRequest(); + const generation = requestGenerationRef.current; + const controller = new AbortController(); + abortControllerRef.current = controller; setLoading(true); setError(null); @@ -77,30 +97,50 @@ export function useGifSearch( url.searchParams.set('q', trimmedQuery); url.searchParams.set('per_page', '50'); // TODO: infinite scroll? - const response = await fetch(url.toString()); + const response = await fetch(url.toString(), { signal: controller.signal }); if (response.status === 200) { const data = (await response.json()) as KlipySearchResponse; const results = data.data?.data; - setSearchResults(results ? results.map(parseKlipyResult) : []); + if (generation === requestGenerationRef.current && mountedRef.current) { + setSearchResults(results ? results.map(parseKlipyResult) : []); + } } else { throw new Error(`HTTP ${response.status}`); } } catch { - setError('Failed to search GIFs'); - setSearchResults([]); + if (generation === requestGenerationRef.current && mountedRef.current) { + setError('Failed to search GIFs'); + setSearchResults([]); + } } finally { - setLoading(false); + if (generation === requestGenerationRef.current && mountedRef.current) { + abortControllerRef.current = undefined; + setLoading(false); + } } }, - [klipyApiKey, showGifPicker, gifSearch] + [cancelRequest, klipyApiKey, gifSearch] ); + useEffect(() => { + mountedRef.current = true; + + return () => { + mountedRef.current = false; + cancelRequest(); + }; + }, [cancelRequest]); + + useEffect(() => { + if (!showGifPicker) cancelSearch(); + }, [cancelSearch, showGifPicker]); + const gifs = useMemo( () => ({ gifs: searchResults, favorites: favoriteGifs }), [searchResults, favoriteGifs] ); - return { gifs, loading, error, searchGifs }; + return { gifs, loading, error, searchGifs, cancelSearch }; } diff --git a/src/app/hooks/useDebounce.test.tsx b/src/app/hooks/useDebounce.test.tsx index 0c28edea5..1de88db55 100644 --- a/src/app/hooks/useDebounce.test.tsx +++ b/src/app/hooks/useDebounce.test.tsx @@ -97,4 +97,33 @@ describe('useDebounce', () => { expect(fn).toHaveBeenCalledOnce(); expect(fn).toHaveBeenCalledWith('go'); }); + + it('cancels a pending callback explicitly', () => { + const fn = vi.fn<(arg: string) => void>(); + const { result } = renderHook(() => useDebounce(fn, { wait: 200 })); + + act(() => { + result.current('cancelled'); + result.current.cancel(); + vi.advanceTimersByTime(200); + }); + + expect(fn).not.toHaveBeenCalled(); + }); + + it('cancels a pending callback when unmounted', () => { + const fn = vi.fn<(arg: string) => void>(); + const { result, unmount } = renderHook(() => useDebounce(fn, { wait: 200 })); + + act(() => { + result.current('cancelled'); + }); + unmount(); + + act(() => { + vi.advanceTimersByTime(200); + }); + + expect(fn).not.toHaveBeenCalled(); + }); }); diff --git a/src/app/hooks/useDebounce.ts b/src/app/hooks/useDebounce.ts index 5f33976a3..018defe79 100644 --- a/src/app/hooks/useDebounce.ts +++ b/src/app/hooks/useDebounce.ts @@ -1,23 +1,32 @@ -import { useCallback, useRef } from 'react'; +import { useCallback, useEffect, useMemo, useRef } from 'react'; export interface DebounceOptions { wait?: number; immediate?: boolean; } export type DebounceCallback = (...args: T) => void; +export type DebouncedCallback = DebounceCallback & { + cancel: () => void; +}; export function useDebounce( callback: DebounceCallback, options?: DebounceOptions -): DebounceCallback { +): DebouncedCallback { const timeoutIdRef = useRef(); const { wait, immediate } = options ?? {}; + const cancel = useCallback(() => { + if (timeoutIdRef.current !== undefined) { + clearTimeout(timeoutIdRef.current); + timeoutIdRef.current = undefined; + } + }, []); + const debounceCallback = useCallback( (...cbArgs: T) => { - if (timeoutIdRef.current) { - clearTimeout(timeoutIdRef.current); - timeoutIdRef.current = undefined; + if (timeoutIdRef.current !== undefined) { + cancel(); } else if (immediate) { callback(...cbArgs); } @@ -27,8 +36,10 @@ export function useDebounce( timeoutIdRef.current = undefined; }, wait); }, - [callback, wait, immediate] + [callback, cancel, wait, immediate] ); - return debounceCallback; + useEffect(() => cancel, [cancel]); + + return useMemo(() => Object.assign(debounceCallback, { cancel }), [debounceCallback, cancel]); } From a233d8d0c3b147e14ce5edfd03fbb24450e66914 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 6 Aug 2026 01:29:16 +0000 Subject: [PATCH 079/135] chore: bump the github-actions group across 1 directory with 4 updates Bumps the github-actions group with 4 updates in the / directory: [github/codeql-action/init](https://github.com/github/codeql-action), [github/codeql-action/analyze](https://github.com/github/codeql-action), [docker/login-action](https://github.com/docker/login-action) and [DeterminateSystems/determinate-nix-action](https://github.com/determinatesystems/determinate-nix-action). Updates `github/codeql-action/init` from 4.37.3 to 4.37.4 - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/e4fba868fa4b1b91e1fdab776edc8cfbe6e9fb81...f205ea1c3313d32999d8d6a48b4f6530d4437b38) Updates `github/codeql-action/analyze` from 4.37.3 to 4.37.4 - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/e4fba868fa4b1b91e1fdab776edc8cfbe6e9fb81...f205ea1c3313d32999d8d6a48b4f6530d4437b38) Updates `docker/login-action` from 4.5.1 to 4.6.0 - [Release notes](https://github.com/docker/login-action/releases) - [Commits](https://github.com/docker/login-action/compare/abd2ef45e78c5afb21d64d4ca52ee8550d9572c7...dbcb813823bdd20940b903addbd779551569679f) Updates `DeterminateSystems/determinate-nix-action` from 3.21.8 to 3.21.9 - [Release notes](https://github.com/determinatesystems/determinate-nix-action/releases) - [Commits](https://github.com/determinatesystems/determinate-nix-action/compare/d96678350ffd6a456235832eb11e1c491589b7bb...61cbfe2efc2d4e7a8a6d56967c3c1058e846c858) --- updated-dependencies: - dependency-name: github/codeql-action/init dependency-version: 4.37.4 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: github-actions - dependency-name: github/codeql-action/analyze dependency-version: 4.37.4 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: github-actions - dependency-name: docker/login-action dependency-version: 4.6.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: github-actions - dependency-name: DeterminateSystems/determinate-nix-action dependency-version: 3.21.9 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: github-actions ... Signed-off-by: dependabot[bot] --- .github/workflows/codeql.yml | 4 ++-- .github/workflows/docker-publish.yml | 2 +- .github/workflows/flake-lock-fix.yml | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 04b03bc42..5d7f1f994 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -69,7 +69,7 @@ jobs: # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@e4fba868fa4b1b91e1fdab776edc8cfbe6e9fb81 # v4.37.3 + uses: github/codeql-action/init@f205ea1c3313d32999d8d6a48b4f6530d4437b38 # v4.37.4 with: languages: ${{ matrix.language }} build-mode: ${{ matrix.build-mode }} @@ -98,6 +98,6 @@ jobs: exit 1 - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@e4fba868fa4b1b91e1fdab776edc8cfbe6e9fb81 # v4.37.3 + uses: github/codeql-action/analyze@f205ea1c3313d32999d8d6a48b4f6530d4437b38 # v4.37.4 with: category: '/language:${{matrix.language}}' diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml index 29f11223b..4422748d9 100644 --- a/.github/workflows/docker-publish.yml +++ b/.github/workflows/docker-publish.yml @@ -38,7 +38,7 @@ jobs: - name: Log in to GitHub Container Registry if: github.event_name != 'pull_request' - uses: docker/login-action@abd2ef45e78c5afb21d64d4ca52ee8550d9572c7 # v4.5.1 + uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} diff --git a/.github/workflows/flake-lock-fix.yml b/.github/workflows/flake-lock-fix.yml index 3ce91131a..328590126 100644 --- a/.github/workflows/flake-lock-fix.yml +++ b/.github/workflows/flake-lock-fix.yml @@ -30,7 +30,7 @@ jobs: token: ${{ steps.app-token.outputs.token }} - name: Install Determinate Nix - uses: DeterminateSystems/determinate-nix-action@d96678350ffd6a456235832eb11e1c491589b7bb # v3.21.8 + uses: DeterminateSystems/determinate-nix-action@61cbfe2efc2d4e7a8a6d56967c3c1058e846c858 # v3.21.9 - id: check run: nix flake check -L From 53226ab1d96685677c3f6f815b7acde5456ac5b2 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Wed, 5 Aug 2026 21:10:03 -0500 Subject: [PATCH 080/135] fix(perf): search only when gif tab open --- src/app/components/emoji-board/EmojiBoard.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/app/components/emoji-board/EmojiBoard.tsx b/src/app/components/emoji-board/EmojiBoard.tsx index 80abb06d4..b273bd1a2 100644 --- a/src/app/components/emoji-board/EmojiBoard.tsx +++ b/src/app/components/emoji-board/EmojiBoard.tsx @@ -528,7 +528,7 @@ export function EmojiBoard({ error: gifsError, searchGifs, cancelSearch: cancelGifSearch, - } = useGifSearch(favoriteGifs, showGifPicker, gifSearch); + } = useGifSearch(favoriteGifs, showGifPicker && gifTab, gifSearch); const [emojiGroupItems, stickerGroupItems, gifGroupItems] = useGroups(tab, imagePacks, gifs); const [showFavoritesOnly, setShowFavoritesOnly] = useState(true); const groupsByTab = { @@ -588,11 +588,11 @@ export function EmojiBoard({ }, [gifTab, initialGifSearch, searchGifs, resetGifSearch]); useEffect(() => { - if (!showGifPicker) { + if (!showGifPicker || !gifTab) { handleOnChange.cancel(); cancelGifSearch(); } - }, [cancelGifSearch, handleOnChange, showGifPicker]); + }, [cancelGifSearch, gifTab, handleOnChange, showGifPicker]); const contentScrollRef = useRef(null); const virtualBaseRef = useRef(null); From a466ba15a0a67db77c8d906859ee24ec14810700 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sat, 1 Aug 2026 17:07:38 +0200 Subject: [PATCH 081/135] fix(persona): serialize per-message-profile account data writes --- .../hooks/usePerMessageProfile.proxy.test.ts | 62 ++++++++++++++- src/app/hooks/usePerMessageProfile.ts | 78 ++++++++++--------- src/app/utils/keyedQueue.ts | 20 +++++ 3 files changed, 124 insertions(+), 36 deletions(-) create mode 100644 src/app/utils/keyedQueue.ts diff --git a/src/app/hooks/usePerMessageProfile.proxy.test.ts b/src/app/hooks/usePerMessageProfile.proxy.test.ts index 2f5fca6e2..ac910a9ea 100644 --- a/src/app/hooks/usePerMessageProfile.proxy.test.ts +++ b/src/app/hooks/usePerMessageProfile.proxy.test.ts @@ -1,4 +1,5 @@ -import { describe, expect, it } from 'vitest'; +import type { MatrixClient } from '$types/matrix-sdk'; +import { describe, expect, it, vi } from 'vitest'; import { extractCircumfixProxyTagsFromKey, @@ -8,6 +9,8 @@ import { type PerMessageProfileProxyAssociationV1, proxyNeedsMigration, createProxyKey, + setCurrentlyUsedPerMessageProfileIdForAccount, + setCurrentlyUsedPerMessageProfileIdForRoom, } from './usePerMessageProfile'; describe('migratePerMessageProfileProxyAssociation', () => { @@ -132,3 +135,60 @@ describe('parsePerMessageProfileProxyAssociation', () => { expect(parsed.regex.test('[no] trailing')).toBe(false); }); }); + +describe('per-message profile persistence', () => { + it('serializes room writes and reads the latest account data snapshot', async () => { + const associations: Record = {}; + const writes: unknown[] = []; + let releaseFirstWrite!: () => void; + const firstWrite = new Promise((resolve) => { + releaseFirstWrite = resolve; + }); + + const mx = { + getAccountData: vi.fn<() => { getContent: () => { associations: typeof associations } }>( + () => ({ getContent: () => ({ associations }) }) + ), + setAccountData: vi.fn< + (_event: unknown, content: { associations: typeof associations }) => Promise + >(async (_event, content) => { + writes.push(content); + if (writes.length === 1) await firstWrite; + Object.assign(associations, content.associations); + }), + } as unknown as MatrixClient; + + const first = setCurrentlyUsedPerMessageProfileIdForRoom(mx, '!room:example.org', 'first'); + const second = setCurrentlyUsedPerMessageProfileIdForRoom(mx, '!room:example.org', 'second'); + + await vi.waitFor(() => expect(writes).toHaveLength(1)); + + releaseFirstWrite(); + await Promise.all([first, second]); + + expect(writes).toHaveLength(2); + expect((writes[1] as { associations: typeof associations }).associations).toEqual({ + '!room:example.org': { profileId: 'second' }, + }); + }); + + it('continues queued account writes after a rejected write', async () => { + const writes: string[] = []; + const mx = { + setAccountData: vi.fn< + (_event: unknown, content: { association: { profileId: string } }) => Promise + >(async (_event, content) => { + writes.push(content.association.profileId); + if (writes.length === 1) throw new Error('write failed'); + }), + deleteAccountData: vi.fn<(...args: unknown[]) => void>(), + } as unknown as MatrixClient; + + const first = setCurrentlyUsedPerMessageProfileIdForAccount(mx, 'first'); + const second = setCurrentlyUsedPerMessageProfileIdForAccount(mx, 'second'); + + await expect(first).rejects.toThrow('write failed'); + await expect(second).resolves.toBeUndefined(); + expect(writes).toEqual(['first', 'second']); + }); +}); diff --git a/src/app/hooks/usePerMessageProfile.ts b/src/app/hooks/usePerMessageProfile.ts index 4914aa7ef..6e61fc37b 100644 --- a/src/app/hooks/usePerMessageProfile.ts +++ b/src/app/hooks/usePerMessageProfile.ts @@ -4,16 +4,20 @@ import type { PronounSet } from '$utils/pronouns'; import type { MatrixClient } from '$types/matrix-sdk'; import { CustomAccountDataEvent } from '$types/matrix/accountData'; import type { ColorSet } from './useUserProfile'; -import { MATRIX_UNSTABLE_COLORS } from '$unstable/prefixes'; import { + MATRIX_UNSTABLE_COLORS, MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_CIRCUMFIX_PROPERTY_NAME, MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_SUFFIX_PROPERTY_NAME, MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME, MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME, } from '$unstable/prefixes'; +import { createKeyedQueue } from '$utils/keyedQueue'; const ACCOUNT_DATA_PREFIX = CustomAccountDataEvent.SablePerProfileMessageProfiles; +/** Account data is read-modify-written, so writes to the same key must not interleave. */ +const enqueueProfilePersistence = createKeyedQueue(); + /** * @deprecated in favour if {@link PerMessageProfileMsc4461} * a per message profile @@ -622,32 +626,34 @@ export async function setCurrentlyUsedPerMessageProfileIdForRoom( validUntil?: number, reset?: boolean ) { - const accountData = mx.getAccountData( - `${ACCOUNT_DATA_PREFIX}.roomassociation` as Parameters[0] - ); - const content: PerMessageProfileRoomAssociationWrapper | undefined = accountData?.getContent(); - const associations = getAssociationsMap(content); + return enqueueProfilePersistence('roomassociation', async () => { + const accountData = mx.getAccountData( + `${ACCOUNT_DATA_PREFIX}.roomassociation` as Parameters[0] + ); + const content: PerMessageProfileRoomAssociationWrapper | undefined = accountData?.getContent(); + const associations = getAssociationsMap(content); - if (reset) { - associations.delete(roomId); + if (reset) { + associations.delete(roomId); + await mx.setAccountData( + `${ACCOUNT_DATA_PREFIX}.roomassociation` as Parameters[0], + { associations: associationsMapToObject(associations) } as Parameters< + typeof mx.setAccountData + >[1] + ); + return; + } + if (!profileId) { + throw new Error("profile Id is empty, yet it isn't a reset"); + } + associations.set(roomId, { profileId, validUntil }); await mx.setAccountData( `${ACCOUNT_DATA_PREFIX}.roomassociation` as Parameters[0], { associations: associationsMapToObject(associations) } as Parameters< typeof mx.setAccountData >[1] ); - return; - } - if (!profileId) { - throw new Error("profile Id is empty, yet it isn't a reset"); - } - associations.set(roomId, { profileId, validUntil }); - await mx.setAccountData( - `${ACCOUNT_DATA_PREFIX}.roomassociation` as Parameters[0], - { associations: associationsMapToObject(associations) } as Parameters< - typeof mx.setAccountData - >[1] - ); + }); } /** @@ -659,22 +665,24 @@ export async function setCurrentlyUsedPerMessageProfileIdForAccount( validUntil?: number, reset?: boolean ) { - if (reset) { - await mx.deleteAccountData( - `${ACCOUNT_DATA_PREFIX}.globalassociation` as Parameters[0] + return enqueueProfilePersistence('globalassociation', async () => { + if (reset) { + await mx.deleteAccountData( + `${ACCOUNT_DATA_PREFIX}.globalassociation` as Parameters[0] + ); + return; + } + if (!profileId) { + throw new Error("profile Id is empty, yet it isn't a reset"); + } + + const association: PerMessageProfileRoomAssociation = { profileId, validUntil }; + + await mx.setAccountData( + `${ACCOUNT_DATA_PREFIX}.globalassociation` as Parameters[0], + { association: association } as Parameters[1] ); - return; - } - if (!profileId) { - throw new Error("profile Id is empty, yet it isn't a reset"); - } - - const association: PerMessageProfileRoomAssociation = { profileId, validUntil }; - - await mx.setAccountData( - `${ACCOUNT_DATA_PREFIX}.globalassociation` as Parameters[0], - { association: association } as Parameters[1] - ); + }); } /* diff --git a/src/app/utils/keyedQueue.ts b/src/app/utils/keyedQueue.ts new file mode 100644 index 000000000..1ce68997a --- /dev/null +++ b/src/app/utils/keyedQueue.ts @@ -0,0 +1,20 @@ +/** Serializes operations per key so read-modify-write sequences cannot interleave. */ +export function createKeyedQueue() { + const tails = new Map>(); + + return function run(key: string, operation: () => T | PromiseLike): Promise { + const previous = tails.get(key) ?? Promise.resolve(); + const current = previous.catch(() => undefined).then(operation); + const tail = current.then( + () => undefined, + () => undefined + ); + + tails.set(key, tail); + void tail.then(() => { + if (tails.get(key) === tail) tails.delete(key); + }); + + return current; + }; +} From 04973d67db603fbdfda0eeed836f46144262f854 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sat, 1 Aug 2026 17:08:45 +0200 Subject: [PATCH 082/135] fix(schedule-send): serialize scheduled message cancellation per room --- .../ScheduledMessagesList.test.tsx | 197 ++++++++++++++++++ .../schedule-send/ScheduledMessagesList.tsx | 63 +++++- .../room/roomScheduleCoordinator.test.ts | 62 ++++++ src/app/state/room/roomScheduleCoordinator.ts | 4 + 4 files changed, 319 insertions(+), 7 deletions(-) create mode 100644 src/app/features/room/schedule-send/ScheduledMessagesList.test.tsx create mode 100644 src/app/state/room/roomScheduleCoordinator.test.ts create mode 100644 src/app/state/room/roomScheduleCoordinator.ts diff --git a/src/app/features/room/schedule-send/ScheduledMessagesList.test.tsx b/src/app/features/room/schedule-send/ScheduledMessagesList.test.tsx new file mode 100644 index 000000000..2137f9248 --- /dev/null +++ b/src/app/features/room/schedule-send/ScheduledMessagesList.test.tsx @@ -0,0 +1,197 @@ +/* oxlint-disable typescript/no-explicit-any, typescript/no-extraneous-class, unicorn/consistent-function-scoping, vitest/require-mock-type-parameters */ + +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { ScheduledMessagesList } from './ScheduledMessagesList'; +import type * as MatrixSdkModule from '$types/matrix-sdk'; + +const testState = vi.hoisted(() => ({ + cancelDelayedEvent: vi.fn(), + coordinatorRun: vi.fn(), + invalidateQueries: vi.fn(), + matrix: { + getSafeUserId: vi.fn(() => '@me:example.org'), + }, +})); + +vi.mock('$hooks/useMatrixClient', () => ({ + useMatrixClient: () => testState.matrix, +})); + +vi.mock('$utils/delayedEvents', () => ({ + cancelDelayedEvent: testState.cancelDelayedEvent, + getDelayedEvents: vi.fn(), +})); + +vi.mock('$state/room/roomScheduleCoordinator', () => ({ + roomScheduleCoordinator: { + run: testState.coordinatorRun, + }, +})); + +vi.mock('@tanstack/react-query', () => ({ + useQuery: () => ({ + data: { + delayed_events: [ + { + delay_id: 'delay-1', + room_id: '!room:example.org', + type: 'm.room.message', + content: { body: 'Scheduled message' }, + running_since: 1_000, + delay: 60_000, + }, + ], + }, + }), + useQueryClient: () => ({ invalidateQueries: testState.invalidateQueries }), +})); + +vi.mock('$state/scheduledMessages', async () => { + const { atom } = await import('jotai'); + const scheduledTimeAtom = atom(null); + const editingScheduledDelayIdAtom = atom(null); + + return { + delayedEventsSupportedAtom: atom(true), + roomIdToScheduledTimeAtomFamily: () => scheduledTimeAtom, + roomIdToEditingScheduledDelayIdAtomFamily: () => editingScheduledDelayIdAtom, + }; +}); + +vi.mock('$state/hooks/settings', () => ({ + useSetting: (_atom: unknown, key: string) => [ + key === 'hour24Clock' ? false : 'YYYY-MM-DD', + vi.fn(), + ], +})); + +vi.mock('$state/settings', () => ({ settingsAtom: {} })); + +vi.mock('$types/matrix-sdk', async (importOriginal) => ({ + ...(await importOriginal()), + MatrixEvent: class MatrixEvent {}, +})); + +vi.mock('$utils/time', () => ({ + timeDayMonthYear: () => '2026-07-28', + timeHourMinute: () => '00:01', +})); + +vi.mock('$components/message-preview', () => ({ + MessagePreview: ({ actions, event }: any) => ( +
+ {event.getContent?.().body ?? 'Scheduled message'} + {actions} +
+ ), + useRoomMessagePreviewRenderer: () => vi.fn(), +})); + +vi.mock('$components/icons/phosphor', () => ({ + CaretDown: 'CaretDown', + CaretUp: 'CaretUp', + Clock: 'Clock', + Lock: 'Lock', + PencilSimple: 'PencilSimple', + X: 'X', + chipIcon: () => null, +})); + +vi.mock('folds', () => { + const Box = ({ children, ...props }: any) =>
{children}
; + const Text = ({ children, ...props }: any) => {children}; + const Button = ({ children, ...props }: any) => ; + + return { + Box, + Chip: Button, + IconButton: Button, + Spinner: () => Cancelling, + Text, + config: { + borderWidth: { B300: '1px' }, + space: { S100: '1px', S200: '2px', S400: '4px' }, + }, + toRem: (value: number) => `${value / 16}rem`, + }; +}); + +vi.mock('./SchedulePickerDialog', () => ({ + SchedulePickerDialog: () => null, +})); + +const room = { roomId: '!room:example.org' } as any; + +function deferred() { + let resolve!: (value: T) => void; + let reject!: (reason?: unknown) => void; + const promise = new Promise((promiseResolve, promiseReject) => { + resolve = promiseResolve; + reject = promiseReject; + }); + return { promise, resolve, reject }; +} + +function renderExpandedList() { + render(); + fireEvent.click(screen.getByRole('button', { name: /1 scheduled message/i })); + return screen.getByRole('button', { name: 'Cancel scheduled message' }); +} + +describe('ScheduledMessagesList cancellation', () => { + beforeEach(() => { + testState.cancelDelayedEvent.mockReset(); + testState.coordinatorRun.mockReset(); + testState.invalidateQueries.mockReset(); + testState.coordinatorRun.mockImplementation((_roomId: string, operation: () => unknown) => + operation() + ); + }); + + it('blocks duplicate cancellation clicks and shows pending state', () => { + const pending = deferred(); + testState.cancelDelayedEvent.mockReturnValue(pending.promise); + + const cancel = renderExpandedList(); + fireEvent.click(cancel); + fireEvent.click(cancel); + + expect(testState.coordinatorRun).toHaveBeenCalledWith(room.roomId, expect.any(Function)); + expect(testState.cancelDelayedEvent).toHaveBeenCalledOnce(); + expect(cancel).toBeDisabled(); + expect(cancel).toHaveAttribute('aria-busy', 'true'); + expect(screen.getByRole('progressbar')).toBeInTheDocument(); + }); + + it('shows a retryable alert when cancellation fails', async () => { + testState.cancelDelayedEvent.mockRejectedValueOnce(new Error('Cancel failed')); + const cancel = renderExpandedList(); + + fireEvent.click(cancel); + + await waitFor(() => + expect(screen.getByRole('alert')).toHaveTextContent( + 'Failed to cancel scheduled message. Try again.' + ) + ); + expect(cancel).not.toBeDisabled(); + expect(cancel).not.toHaveAttribute('aria-busy', 'true'); + }); + + it('successfully retries cancellation after a failure', async () => { + testState.cancelDelayedEvent + .mockRejectedValueOnce(new Error('Cancel failed')) + .mockResolvedValueOnce(undefined); + const cancel = renderExpandedList(); + + fireEvent.click(cancel); + await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument()); + + fireEvent.click(cancel); + + await waitFor(() => expect(testState.cancelDelayedEvent).toHaveBeenCalledTimes(2)); + await waitFor(() => expect(testState.invalidateQueries).toHaveBeenCalledOnce()); + expect(screen.queryByRole('alert')).not.toBeInTheDocument(); + }); +}); diff --git a/src/app/features/room/schedule-send/ScheduledMessagesList.tsx b/src/app/features/room/schedule-send/ScheduledMessagesList.tsx index 16583b392..c9aafa05a 100644 --- a/src/app/features/room/schedule-send/ScheduledMessagesList.tsx +++ b/src/app/features/room/schedule-send/ScheduledMessagesList.tsx @@ -1,6 +1,6 @@ -import { useCallback, useMemo, useState } from 'react'; +import { useCallback, useMemo, useRef, useState } from 'react'; import { useQuery, useQueryClient } from '@tanstack/react-query'; -import { Box, Text, Chip, IconButton } from 'folds'; +import { Box, Text, Chip, IconButton, Spinner } from 'folds'; import { CaretDown, CaretUp, @@ -27,6 +27,7 @@ import { import { timeHourMinute, timeDayMonthYear } from '$utils/time'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom } from '$state/settings'; +import { roomScheduleCoordinator } from '$state/room/roomScheduleCoordinator'; import { MessagePreview, useRoomMessagePreviewRenderer } from '$components/message-preview'; import { SchedulePickerDialog } from './SchedulePickerDialog'; import * as css from './ScheduledMessagesList.css'; @@ -44,6 +45,12 @@ type ScheduledMessageRowProps = { hour24Clock: boolean; onEdit: (delayId: string, body: string, formattedBody?: string, scheduledTs?: number) => void; onCancel: (delayId: string) => void; + cancellationState: CancellationState; +}; + +type CancellationState = { + status: 'idle' | 'pending' | 'error'; + error?: string; }; function ScheduledMessageRow({ @@ -52,6 +59,7 @@ function ScheduledMessageRow({ hour24Clock, onEdit, onCancel, + cancellationState, }: ScheduledMessageRowProps) { const mx = useMatrixClient(); const [dateFormatString] = useSetting(settingsAtom, 'dateFormatString'); @@ -63,6 +71,8 @@ function ScheduledMessageRow({ !isEncrypted && typeof event.content.formatted_body === 'string' ? event.content.formatted_body : undefined; + const isCancelling = cancellationState.status === 'pending'; + const cancelIcon = isCancelling ? : chipIcon(X); const matrixEvent = useMemo( () => new MatrixEvent({ @@ -106,9 +116,11 @@ function ScheduledMessageRow({ variant="Critical" radii="300" onClick={() => onCancel(event.delay_id)} + disabled={isCancelling} + aria-busy={isCancelling} aria-label="Cancel scheduled message" > - {chipIcon(X)} + {cancelIcon} } @@ -126,12 +138,19 @@ function ScheduledMessageRow({ variant="Critical" radii="300" onClick={() => onCancel(event.delay_id)} + disabled={isCancelling} + aria-busy={isCancelling} aria-label="Cancel scheduled message" > - {chipIcon(X)} + {cancelIcon} )} + {cancellationState.status === 'error' && ( + + {cancellationState.error} + + )} ); } @@ -146,6 +165,10 @@ export function ScheduledMessagesList({ room, onEditMessage }: ScheduledMessages const [editingDelayId, setEditingDelayId] = useAtom( roomIdToEditingScheduledDelayIdAtomFamily(room.roomId) ); + const [cancellationStates, setCancellationStates] = useState>( + {} + ); + const pendingCancellations = useRef(new Set()); const { data } = useQuery({ queryKey: ['delayedEvents', room.roomId], @@ -167,10 +190,35 @@ export function ScheduledMessagesList({ room, onEditMessage }: ScheduledMessages const handleCancel = useCallback( async (delayId: string) => { - await cancelDelayedEvent(mx, delayId); - invalidateEvents(); + if (pendingCancellations.current.has(delayId)) return; + + pendingCancellations.current.add(delayId); + setCancellationStates((states) => ({ + ...states, + [delayId]: { status: 'pending' }, + })); + + try { + await roomScheduleCoordinator.run(room.roomId, () => cancelDelayedEvent(mx, delayId)); + invalidateEvents(); + setCancellationStates((states) => { + const next = { ...states }; + delete next[delayId]; + return next; + }); + } catch { + setCancellationStates((states) => ({ + ...states, + [delayId]: { + status: 'error', + error: 'Failed to cancel scheduled message. Try again.', + }, + })); + } finally { + pendingCancellations.current.delete(delayId); + } }, - [mx, invalidateEvents] + [mx, room.roomId, invalidateEvents] ); const handleEdit = useCallback( @@ -218,6 +266,7 @@ export function ScheduledMessagesList({ room, onEditMessage }: ScheduledMessages hour24Clock={hour24Clock} onEdit={handleEdit} onCancel={handleCancel} + cancellationState={cancellationStates[event.delay_id] ?? { status: 'idle' }} /> ))} diff --git a/src/app/state/room/roomScheduleCoordinator.test.ts b/src/app/state/room/roomScheduleCoordinator.test.ts new file mode 100644 index 000000000..98f67e548 --- /dev/null +++ b/src/app/state/room/roomScheduleCoordinator.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it, vi } from 'vitest'; +import { roomScheduleCoordinator } from './roomScheduleCoordinator'; + +function deferred() { + let resolve!: () => void; + const promise = new Promise((resolvePromise) => { + resolve = resolvePromise; + }); + return { promise, resolve }; +} + +describe('roomScheduleCoordinator', () => { + it('runs operations in FIFO order for a room', async () => { + const first = deferred(); + const order: string[] = []; + + const firstOperation = roomScheduleCoordinator.run('!room:example.org', async () => { + order.push('first-start'); + await first.promise; + order.push('first-end'); + }); + const secondOperation = roomScheduleCoordinator.run('!room:example.org', async () => { + order.push('second'); + }); + + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(order).toEqual(['first-start']); + + first.resolve(); + await Promise.all([firstOperation, secondOperation]); + expect(order).toEqual(['first-start', 'first-end', 'second']); + }); + + it('continues the room queue after an operation fails', async () => { + const second = vi.fn<() => Promise>(async () => 'completed'); + + await expect( + roomScheduleCoordinator.run('!room:example.org', async () => { + throw new Error('cancel failed'); + }) + ).rejects.toThrow('cancel failed'); + await expect(roomScheduleCoordinator.run('!room:example.org', second)).resolves.toBe( + 'completed' + ); + + expect(second).toHaveBeenCalledOnce(); + }); + + it('does not serialize operations for different rooms', async () => { + const first = deferred(); + const second = vi.fn<() => Promise>(async () => 'completed'); + + const firstOperation = roomScheduleCoordinator.run('!first:example.org', () => first.promise); + const secondOperation = roomScheduleCoordinator.run('!second:example.org', second); + + await expect(secondOperation).resolves.toBe('completed'); + expect(second).toHaveBeenCalledOnce(); + + first.resolve(); + await firstOperation; + }); +}); diff --git a/src/app/state/room/roomScheduleCoordinator.ts b/src/app/state/room/roomScheduleCoordinator.ts new file mode 100644 index 000000000..ddfa595ed --- /dev/null +++ b/src/app/state/room/roomScheduleCoordinator.ts @@ -0,0 +1,4 @@ +import { createKeyedQueue } from '$utils/keyedQueue'; + +/** Serializes delayed-event mutations for each room without blocking other rooms. */ +export const roomScheduleCoordinator = { run: createKeyedQueue() }; From 7f9d042bbe03ff193133f0d698a5b0bc38caa5ad Mon Sep 17 00:00:00 2001 From: 7w1 Date: Wed, 5 Aug 2026 21:21:13 -0500 Subject: [PATCH 083/135] fix: scope by account --- .../ScheduledMessagesList.test.tsx | 10 +++-- .../schedule-send/ScheduledMessagesList.tsx | 2 +- .../room/roomScheduleCoordinator.test.ts | 41 ++++++++++++++++--- src/app/state/room/roomScheduleCoordinator.ts | 15 ++++++- 4 files changed, 56 insertions(+), 12 deletions(-) diff --git a/src/app/features/room/schedule-send/ScheduledMessagesList.test.tsx b/src/app/features/room/schedule-send/ScheduledMessagesList.test.tsx index 2137f9248..d5d20be54 100644 --- a/src/app/features/room/schedule-send/ScheduledMessagesList.test.tsx +++ b/src/app/features/room/schedule-send/ScheduledMessagesList.test.tsx @@ -144,8 +144,8 @@ describe('ScheduledMessagesList cancellation', () => { testState.cancelDelayedEvent.mockReset(); testState.coordinatorRun.mockReset(); testState.invalidateQueries.mockReset(); - testState.coordinatorRun.mockImplementation((_roomId: string, operation: () => unknown) => - operation() + testState.coordinatorRun.mockImplementation( + (_mx: unknown, _roomId: string, operation: () => unknown) => operation() ); }); @@ -157,7 +157,11 @@ describe('ScheduledMessagesList cancellation', () => { fireEvent.click(cancel); fireEvent.click(cancel); - expect(testState.coordinatorRun).toHaveBeenCalledWith(room.roomId, expect.any(Function)); + expect(testState.coordinatorRun).toHaveBeenCalledWith( + testState.matrix, + room.roomId, + expect.any(Function) + ); expect(testState.cancelDelayedEvent).toHaveBeenCalledOnce(); expect(cancel).toBeDisabled(); expect(cancel).toHaveAttribute('aria-busy', 'true'); diff --git a/src/app/features/room/schedule-send/ScheduledMessagesList.tsx b/src/app/features/room/schedule-send/ScheduledMessagesList.tsx index c9aafa05a..98f19beee 100644 --- a/src/app/features/room/schedule-send/ScheduledMessagesList.tsx +++ b/src/app/features/room/schedule-send/ScheduledMessagesList.tsx @@ -199,7 +199,7 @@ export function ScheduledMessagesList({ room, onEditMessage }: ScheduledMessages })); try { - await roomScheduleCoordinator.run(room.roomId, () => cancelDelayedEvent(mx, delayId)); + await roomScheduleCoordinator.run(mx, room.roomId, () => cancelDelayedEvent(mx, delayId)); invalidateEvents(); setCancellationStates((states) => { const next = { ...states }; diff --git a/src/app/state/room/roomScheduleCoordinator.test.ts b/src/app/state/room/roomScheduleCoordinator.test.ts index 98f67e548..758f0ae1f 100644 --- a/src/app/state/room/roomScheduleCoordinator.test.ts +++ b/src/app/state/room/roomScheduleCoordinator.test.ts @@ -1,6 +1,9 @@ import { describe, expect, it, vi } from 'vitest'; import { roomScheduleCoordinator } from './roomScheduleCoordinator'; +const account = (userId: string) => ({ getSafeUserId: () => userId }); +const alice = account('@alice:example.org'); + function deferred() { let resolve!: () => void; const promise = new Promise((resolvePromise) => { @@ -14,12 +17,12 @@ describe('roomScheduleCoordinator', () => { const first = deferred(); const order: string[] = []; - const firstOperation = roomScheduleCoordinator.run('!room:example.org', async () => { + const firstOperation = roomScheduleCoordinator.run(alice, '!room:example.org', async () => { order.push('first-start'); await first.promise; order.push('first-end'); }); - const secondOperation = roomScheduleCoordinator.run('!room:example.org', async () => { + const secondOperation = roomScheduleCoordinator.run(alice, '!room:example.org', async () => { order.push('second'); }); @@ -35,11 +38,11 @@ describe('roomScheduleCoordinator', () => { const second = vi.fn<() => Promise>(async () => 'completed'); await expect( - roomScheduleCoordinator.run('!room:example.org', async () => { + roomScheduleCoordinator.run(alice, '!room:example.org', async () => { throw new Error('cancel failed'); }) ).rejects.toThrow('cancel failed'); - await expect(roomScheduleCoordinator.run('!room:example.org', second)).resolves.toBe( + await expect(roomScheduleCoordinator.run(alice, '!room:example.org', second)).resolves.toBe( 'completed' ); @@ -50,8 +53,34 @@ describe('roomScheduleCoordinator', () => { const first = deferred(); const second = vi.fn<() => Promise>(async () => 'completed'); - const firstOperation = roomScheduleCoordinator.run('!first:example.org', () => first.promise); - const secondOperation = roomScheduleCoordinator.run('!second:example.org', second); + const firstOperation = roomScheduleCoordinator.run( + alice, + '!first:example.org', + () => first.promise + ); + const secondOperation = roomScheduleCoordinator.run(alice, '!second:example.org', second); + + await expect(secondOperation).resolves.toBe('completed'); + expect(second).toHaveBeenCalledOnce(); + + first.resolve(); + await firstOperation; + }); + + it('does not serialize the same room ID across accounts', async () => { + const first = deferred(); + const second = vi.fn<() => Promise>(async () => 'completed'); + + const firstOperation = roomScheduleCoordinator.run( + alice, + '!room:example.org', + () => first.promise + ); + const secondOperation = roomScheduleCoordinator.run( + account('@bob:example.org'), + '!room:example.org', + second + ); await expect(secondOperation).resolves.toBe('completed'); expect(second).toHaveBeenCalledOnce(); diff --git a/src/app/state/room/roomScheduleCoordinator.ts b/src/app/state/room/roomScheduleCoordinator.ts index ddfa595ed..80182b760 100644 --- a/src/app/state/room/roomScheduleCoordinator.ts +++ b/src/app/state/room/roomScheduleCoordinator.ts @@ -1,4 +1,15 @@ import { createKeyedQueue } from '$utils/keyedQueue'; +import type { MatrixClient } from '$types/matrix-sdk'; -/** Serializes delayed-event mutations for each room without blocking other rooms. */ -export const roomScheduleCoordinator = { run: createKeyedQueue() }; +const runQueued = createKeyedQueue(); + +/** Serializes delayed-event mutations per account and room. */ +export const roomScheduleCoordinator = { + run( + mx: Pick, + roomId: string, + operation: () => T | PromiseLike + ): Promise { + return runQueued(`${mx.getSafeUserId()}\0${roomId}`, operation); + }, +}; From c8e8f30466373e289cf54c6a1cf40416efc8b9e4 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sat, 1 Aug 2026 17:10:14 +0200 Subject: [PATCH 084/135] fix(composer): scope scheduled send state to the room composer --- src/app/features/room/RoomInput.tsx | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index ed8b3ae4c..172c93f60 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -515,10 +515,26 @@ export const RoomInput = forwardRef( const queryClient = useQueryClient(); const delayedEventsSupported = useAtomValue(delayedEventsSupportedAtom); - const [scheduledTime, setScheduledTime] = useAtom(roomIdToScheduledTimeAtomFamily(roomId)); - const [editingScheduledDelayId, setEditingScheduledDelayId] = useAtom( + const [roomScheduledTime, setRoomScheduledTime] = useAtom( + roomIdToScheduledTimeAtomFamily(roomId) + ); + const [roomEditingScheduledDelayId, setRoomEditingScheduledDelayId] = useAtom( roomIdToEditingScheduledDelayIdAtomFamily(roomId) ); + const scheduledTime = threadRootId ? null : roomScheduledTime; + const editingScheduledDelayId = threadRootId ? null : roomEditingScheduledDelayId; + const setScheduledTime = useCallback( + (value: Date | null) => { + if (!threadRootId) setRoomScheduledTime(value); + }, + [setRoomScheduledTime, threadRootId] + ); + const setEditingScheduledDelayId = useCallback( + (value: string | null) => { + if (!threadRootId) setRoomEditingScheduledDelayId(value); + }, + [setRoomEditingScheduledDelayId, threadRootId] + ); const [AddMenuAnchor, setAddMenuAnchor] = useState(); const [showAttachmentSheet, setShowAttachmentSheet] = useState(false); const attachmentSkipReturnFocusRef = useRef(false); From 83d3e66103ec158a63d419665685e97966982255 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Wed, 5 Aug 2026 21:36:14 -0500 Subject: [PATCH 085/135] fix: scope scheduled messages by account --- src/app/features/room/RoomInput.tsx | 6 ++++-- .../ScheduledMessagesList.test.tsx | 1 + .../schedule-send/ScheduledMessagesList.tsx | 6 ++++-- src/app/state/scheduledMessages.test.ts | 21 +++++++++++++++++++ src/app/state/scheduledMessages.ts | 3 +++ 5 files changed, 33 insertions(+), 4 deletions(-) create mode 100644 src/app/state/scheduledMessages.test.ts diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 172c93f60..d3f7e7311 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -129,6 +129,7 @@ import { useQueryClient } from '@tanstack/react-query'; import * as Sentry from '@sentry/react'; import { delayedEventsSupportedAtom, + getScheduledMessageStateKey, roomIdToScheduledTimeAtomFamily, roomIdToEditingScheduledDelayIdAtomFamily, serverMaxDelayMsAtom, @@ -515,11 +516,12 @@ export const RoomInput = forwardRef( const queryClient = useQueryClient(); const delayedEventsSupported = useAtomValue(delayedEventsSupportedAtom); + const scheduledStateKey = getScheduledMessageStateKey(mx.getSafeUserId(), roomId); const [roomScheduledTime, setRoomScheduledTime] = useAtom( - roomIdToScheduledTimeAtomFamily(roomId) + roomIdToScheduledTimeAtomFamily(scheduledStateKey) ); const [roomEditingScheduledDelayId, setRoomEditingScheduledDelayId] = useAtom( - roomIdToEditingScheduledDelayIdAtomFamily(roomId) + roomIdToEditingScheduledDelayIdAtomFamily(scheduledStateKey) ); const scheduledTime = threadRootId ? null : roomScheduledTime; const editingScheduledDelayId = threadRootId ? null : roomEditingScheduledDelayId; diff --git a/src/app/features/room/schedule-send/ScheduledMessagesList.test.tsx b/src/app/features/room/schedule-send/ScheduledMessagesList.test.tsx index d5d20be54..873c51c4b 100644 --- a/src/app/features/room/schedule-send/ScheduledMessagesList.test.tsx +++ b/src/app/features/room/schedule-send/ScheduledMessagesList.test.tsx @@ -54,6 +54,7 @@ vi.mock('$state/scheduledMessages', async () => { return { delayedEventsSupportedAtom: atom(true), + getScheduledMessageStateKey: (userId: string, roomId: string) => `${userId}\0${roomId}`, roomIdToScheduledTimeAtomFamily: () => scheduledTimeAtom, roomIdToEditingScheduledDelayIdAtomFamily: () => editingScheduledDelayIdAtom, }; diff --git a/src/app/features/room/schedule-send/ScheduledMessagesList.tsx b/src/app/features/room/schedule-send/ScheduledMessagesList.tsx index 98f19beee..683e1f9d9 100644 --- a/src/app/features/room/schedule-send/ScheduledMessagesList.tsx +++ b/src/app/features/room/schedule-send/ScheduledMessagesList.tsx @@ -21,6 +21,7 @@ import { } from '$utils/delayedEvents'; import { delayedEventsSupportedAtom, + getScheduledMessageStateKey, roomIdToScheduledTimeAtomFamily, roomIdToEditingScheduledDelayIdAtomFamily, } from '$state/scheduledMessages'; @@ -159,11 +160,12 @@ export function ScheduledMessagesList({ room, onEditMessage }: ScheduledMessages const mx = useMatrixClient(); const queryClient = useQueryClient(); const supported = useAtomValue(delayedEventsSupportedAtom); - const setScheduledTime = useSetAtom(roomIdToScheduledTimeAtomFamily(room.roomId)); + const scheduledStateKey = getScheduledMessageStateKey(mx.getSafeUserId(), room.roomId); + const setScheduledTime = useSetAtom(roomIdToScheduledTimeAtomFamily(scheduledStateKey)); const [hour24Clock] = useSetting(settingsAtom, 'hour24Clock'); const [expanded, setExpanded] = useState(false); const [editingDelayId, setEditingDelayId] = useAtom( - roomIdToEditingScheduledDelayIdAtomFamily(room.roomId) + roomIdToEditingScheduledDelayIdAtomFamily(scheduledStateKey) ); const [cancellationStates, setCancellationStates] = useState>( {} diff --git a/src/app/state/scheduledMessages.test.ts b/src/app/state/scheduledMessages.test.ts new file mode 100644 index 000000000..bd2b029ba --- /dev/null +++ b/src/app/state/scheduledMessages.test.ts @@ -0,0 +1,21 @@ +import { createStore } from 'jotai'; +import { describe, expect, it } from 'vitest'; +import { + getScheduledMessageStateKey, + roomIdToEditingScheduledDelayIdAtomFamily, + roomIdToScheduledTimeAtomFamily, +} from './scheduledMessages'; + +describe('scheduled message state', () => { + it('isolates the same room across accounts', () => { + const store = createStore(); + const aliceKey = getScheduledMessageStateKey('@alice:example.org', '!room:example.org'); + const bobKey = getScheduledMessageStateKey('@bob:example.org', '!room:example.org'); + + store.set(roomIdToScheduledTimeAtomFamily(aliceKey), new Date(1_000)); + store.set(roomIdToEditingScheduledDelayIdAtomFamily(aliceKey), 'alice-delay'); + + expect(store.get(roomIdToScheduledTimeAtomFamily(bobKey))).toBeNull(); + expect(store.get(roomIdToEditingScheduledDelayIdAtomFamily(bobKey))).toBeNull(); + }); +}); diff --git a/src/app/state/scheduledMessages.ts b/src/app/state/scheduledMessages.ts index d9144b2ad..5836300dc 100644 --- a/src/app/state/scheduledMessages.ts +++ b/src/app/state/scheduledMessages.ts @@ -3,6 +3,9 @@ import { atomFamily } from 'jotai/utils'; export const delayedEventsSupportedAtom = atom(false); +export const getScheduledMessageStateKey = (userId: string, roomId: string): string => + `${userId}\0${roomId}`; + export const roomIdToScheduledTimeAtomFamily = atomFamily< string, ReturnType> From d7a84369cafe672edba8dbfa1ff3b5b308572096 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sat, 1 Aug 2026 17:14:57 +0200 Subject: [PATCH 086/135] refactor(composer): extract message building out of RoomInput --- src/app/features/room/RoomInput.tsx | 367 +++--------------- src/app/features/room/composerMessage.test.ts | 207 ++++++++++ src/app/features/room/composerMessage.ts | 333 ++++++++++++++++ 3 files changed, 588 insertions(+), 319 deletions(-) create mode 100644 src/app/features/room/composerMessage.test.ts create mode 100644 src/app/features/room/composerMessage.ts diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index d3f7e7311..7075276db 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -22,7 +22,7 @@ import type { StickerEventContent, } from '$types/matrix-sdk'; import { MatrixError } from '$types/matrix-sdk'; -import { EventType, MsgType, RelationType } from '$types/matrix-sdk'; +import { EventType, RelationType } from '$types/matrix-sdk'; import { ReactEditor } from 'slate-react'; import { Editor, Point, Range, Transforms } from 'slate'; import type { RectCords } from 'folds'; @@ -63,17 +63,12 @@ import { moveCursor, resetEditorHistory, isEmptyEditor, - getBeginCommand, - trimCommand, - getMentions, ANYWHERE_AUTOCOMPLETE_PREFIXES, BEGINNING_AUTOCOMPLETE_PREFIXES, - getLinks, MarkdownFormattingToolbarBottom, MarkdownFormattingToolbarToggle, focusEditor, replaceWithElement, - BlockType, } from '$components/editor'; import { stripMarkdownEscapesForHiddenPreviews } from './message/hiddenLinkPreviews'; import { plainToEditorInput } from '$components/editor/input'; @@ -111,10 +106,9 @@ import { useSetting } from '$state/hooks/settings'; import type { EditorButtonId } from '$state/settings'; import { settingsAtom } from '$state/settings'; import { matchesShortcut } from '../../keyboard/shortcuts'; -import { getEditedEvent, getMentionContent, getThreadReplyEvents } from '$utils/room/relations'; -import { buildReplacementContent } from './buildReplacementContent'; +import { getEditedEvent, getThreadReplyEvents } from '$utils/room/relations'; import { htmlToMarkdown } from '$plugins/markdown'; -import { Command, SHRUG, TABLEFLIP, UNFLIP, useCommands } from '$hooks/useCommands'; +import { Command, useCommands } from '$hooks/useCommands'; import { isMobileOrTablet } from '$utils/platform'; import { Reply, ThreadIndicator } from '$components/message'; import { roomToParentsAtom } from '$state/room/roomToParents'; @@ -181,7 +175,6 @@ import { } from '$components/icons/phosphor'; import { getSupportedAudioExtension } from '$plugins/voice-recorder-kit/supportedCodec'; import { ErrorCode } from '../../cs-errorcode'; -import { sanitizeText } from '$utils/sanitize'; import { PKitCommandMessageHandler } from '$plugins/pluralkit-handler/PKitCommandMessageHandler'; import { PKitProxyMessageHandler } from '$plugins/pluralkit-handler/PKitProxyMessageHandler'; import type { IGenericMSC4459, MSC4459ImagePackReference } from '$types/matrix/common'; @@ -207,7 +200,7 @@ import { buildGalleryContent, getGalleryItemContent, } from './msgContent'; -import { outgoingMessageTransforms } from './outgoingMessageTransforms'; +import { buildEditReplacement, buildOutgoingMessage } from './composerMessage'; import { getSendableKlipyMxcUrl } from '$utils/klipy'; import { CommandAutocomplete } from './CommandAutocomplete'; import type { @@ -1084,57 +1077,19 @@ export const RoomInput = forwardRef( const submit = useCallback(async () => { if (editingEvent && isMobileOrTablet()) { - let plainText = toPlainText(editor.children).trim(); - if (!plainText) { + const content = buildEditReplacement(editor.children, { + mx, + room, + roomId, + editingEvent, + currentContent: getEditingContent(editingEvent), + pmpNoFallback, + }); + if (!content) { onCancelEdit?.(); return; } - let customHtml = trimCustomHtml( - toMatrixCustomHTML(editor.children, { - forEmote: editingEvent.getContent().msgtype === MsgType.Emote, - room, - }) - ); - const oldContent = editingEvent.getContent(); - const currentContent = getEditingContent(editingEvent); - const eventId = editingEvent.getId(); - if (!eventId) return; - - const rawPmp = - currentContent['com.beeper.per_message_profile'] ?? - oldContent['com.beeper.per_message_profile']; - - const mentionData = getMentions(mx, roomId, editor); - const previousMentions = currentContent['m.mentions']; - if ( - previousMentions && - typeof previousMentions === 'object' && - 'user_ids' in previousMentions && - Array.isArray(previousMentions.user_ids) - ) { - previousMentions.user_ids.forEach((userId) => { - if (typeof userId === 'string') mentionData.users.add(userId); - }); - } - const mMentions = getMentionContent(Array.from(mentionData.users), mentionData.room); - - const linkPreviews = - getLinks(editor.children)?.map((matchedUrl) => ({ - matched_url: matchedUrl, - })) ?? []; - - const content = buildReplacementContent( - oldContent, - plainText, - customHtml, - eventId, - mMentions, - linkPreviews, - rawPmp, - pmpNoFallback - ); - await mx.sendMessage(roomId, content as RoomMessageEventContent); onCancelEdit?.(); sendTypingStatus(false); @@ -1153,287 +1108,61 @@ export const RoomInput = forwardRef( return; } - const commandName = getBeginCommand(editor); - /** - * a map of regex patterns to replace nicknames with, - * used when stripNickname is true in toMatrixCustomHTML - * during HTML generation for the message content. - * This is necessary because the HTML generation needs to know - * which nicknames to strip in order to generate the correct formatted_body, - * and the plain text generation needs to replace those same nicknames with - * the original user IDs so that the message content remains consistent and - * mentions are correctly processed by the server and clients. - */ - const nicknameReplacement = new Map(); - if (replyEvent) { - /** - * the id of the user being replied to, - * whose nickname (if any) should be stripped - * from the message content and replaced with their - * user ID for correct mention processing - */ - const senderId = replyEvent.getSender(); - if (senderId) { - const nick = nicknames[senderId]; - if (typeof nick === 'string' && nick.length > 0) { - nicknameReplacement.set( - new RegExp(`@?${nick}`, 'g'), - room.getMember(senderId)?.rawDisplayName ?? senderId - ); - } - } - } - /** - * any other users mentioned in the message being replied to, - * whose nicknames should also be stripped and replaced with user IDs - */ - const mentions = getMentions(mx, roomId, editor); - if (mentions?.users) { - mentions.users.forEach((id) => { - const nick = nicknames[id]; - if (typeof nick === 'string' && nick.length > 0) { - nicknameReplacement.set( - new RegExp(`@?${nick}`, 'g'), - room.getMember(id)?.rawDisplayName ?? id - ); - } - }); - } - /** - * the plain text we will send - */ - let serializedChildren = editor.children; - if (commandName) { - // Strip the empty text node and command node from the beginning of the first paragraph - const firstPara = serializedChildren[0]; - if ( - firstPara && - 'type' in firstPara && - firstPara.type === BlockType.Paragraph && - firstPara.children.length >= 2 - ) { - serializedChildren = [ - { - ...firstPara, - children: firstPara.children.slice(2), - }, - ...serializedChildren.slice(1), - ]; - } - } - const outgoingTransformContext = { - isMarkdown: true, + const outgoing = await buildOutgoingMessage(editor.children, { + mx, + room, + roomId, + nicknames, + replyEvent, + replyDraft, + silentReply, settingsLinkBaseUrl, - }; - - outgoingMessageTransforms.forEach((transform) => { - if (!transform.shouldApply(serializedChildren, outgoingTransformContext)) return; - serializedChildren = transform.apply(serializedChildren, outgoingTransformContext); + canSendReaction, + pkCompatEnable, + pmpProxyingEnable, + pmpLatchingEnable, + pmpNoFallback, + latchedPersona, + isPKCommand: (text) => PKitCommandMessageHandler.isPKCommand(text), + pluralkitProxyMessageHandler, + imagePacksUsed: imagePacksUsedRef.current, }); - let plainText = toPlainText(serializedChildren, true, true, nicknameReplacement).trim(); - - /** - * the html we will send - */ - let customHtml = trimCustomHtml( - toMatrixCustomHTML(serializedChildren, { - stripNickname: true, - nickNameReplacement: nicknameReplacement, - forEmote: commandName === Command.Me || commandName === Command.RainbowMe, - room, - }) - ); - const rawGifCommand = - commandName === undefined ? plainText.match(/^\/gif(?:\s+(.*))?$/i) : undefined; - - let msgType = MsgType.Text; - - // quick text react - if (canSendReaction && plainText.startsWith('+#')) { - handleQuickReact(plainText.substring(2)); + if (outgoing.kind === 'empty') return; + if (outgoing.kind === 'quickReact') { + handleQuickReact(outgoing.key); return; } - - // check if its a pk command - if (pkCompatEnable && PKitCommandMessageHandler.isPKCommand(plainText)) { - await pluralkitCmdMessageHandler.handleMessage(plainText); - resetEditor(editor); // clear the editor - return; // don't do anything besides handling the command + if (outgoing.kind === 'pkCommand') { + await pluralkitCmdMessageHandler.handleMessage(outgoing.plainText); + resetEditor(editor); + return; } - - if (rawGifCommand) { - setInitialGifSearch(rawGifCommand[1] ?? ''); + if (outgoing.kind === 'gifSearch') { + setInitialGifSearch(outgoing.query); setEmojiBoardTab(EmojiBoardTab.Gif); resetEditor(editor); resetEditorHistory(editor); sendTypingStatus(false); return; } - - if (commandName) { - plainText = trimCommand(commandName, plainText); - customHtml = trimCommand(commandName, customHtml); - } - if (commandName === Command.Me) { - msgType = MsgType.Emote; - } else if (commandName === Command.Notice) { - msgType = MsgType.Notice; - } else if (commandName === Command.Shrug) { - plainText = `${SHRUG} ${plainText}`; - customHtml = `${SHRUG} ${customHtml}`; - } else if (commandName === Command.TableFlip) { - plainText = `${TABLEFLIP} ${plainText}`; - customHtml = `${TABLEFLIP} ${customHtml}`; - } else if (commandName === Command.UnFlip) { - plainText = `${UNFLIP} ${plainText}`; - customHtml = `${UNFLIP} ${customHtml}`; - } else if (commandName) { - if ((commandName as Command) === Command.Poll) setShowPollPicker(true); - else if ((commandName as Command) === Command.Location && plainText.trim().length === 0) + if (outgoing.kind === 'command') { + const { command, plainText, customHtml } = outgoing; + if (command === Command.Poll) setShowPollPicker(true); + else if (command === Command.Location && plainText.trim().length === 0) setShowLocationPicker(true); - else if (commandName === 'gif') { - setInitialGifSearch(plainText); - setEmojiBoardTab(EmojiBoardTab.Gif); - } else { - const commandContent = commands[commandName as Command]; - if (commandContent) { - commandContent.exe(plainText, customHtml); - } - } + else commands[command as Command]?.exe(plainText, customHtml); resetEditor(editor); resetEditorHistory(editor); sendTypingStatus(false); - return; } - if (plainText === '') return; - - // PluralKit-style proxy wrappers (per-message profile proxies) must be stripped - // *before* building `content`, otherwise we end up sending the wrapper verbatim. - let proxiedPerMessageProfile: - | Awaited> - | undefined; - if (pmpProxyingEnable) { - proxiedPerMessageProfile = - await pluralkitProxyMessageHandler.getPmpBasedOnMessage(plainText); - if (proxiedPerMessageProfile) { - // normal plainText has spoilers stripped, but this breaks spoilers with a proxy tag. - // here we get a new 'unsanitized' plainText without spoiler stripping - let unsanitizedPlainText = toPlainText( - serializedChildren, - true, - false, - nicknameReplacement - ).trim(); - - const stripped = pluralkitProxyMessageHandler.stripProxyFromMessage(unsanitizedPlainText); - if (stripped !== undefined) { - // Re-run the normal outgoing pipeline on the stripped content so the message - // goes through the same transforms/parsers as any other message. - serializedChildren = plainToEditorInput(stripped); - - outgoingMessageTransforms.forEach((transform) => { - if (!transform.shouldApply(serializedChildren, outgoingTransformContext)) return; - serializedChildren = transform.apply(serializedChildren, outgoingTransformContext); - }); - - plainText = toPlainText(serializedChildren, true, true, nicknameReplacement).trim(); - customHtml = trimCustomHtml( - toMatrixCustomHTML(serializedChildren, { - stripNickname: true, - nickNameReplacement: nicknameReplacement, - forEmote: commandName === Command.Me || commandName === Command.RainbowMe, - room, - }) - ); - - if (pmpLatchingEnable) { - await setCurrentlyUsedPerMessageProfileIdForRoom( - mx, - roomId, - proxiedPerMessageProfile.id - ); - setLatchedPersona(proxiedPerMessageProfile); - } - } - } + const { content } = outgoing; + if (outgoing.latchPersona) { + await setCurrentlyUsedPerMessageProfileIdForRoom(mx, roomId, outgoing.latchPersona.id); + setLatchedPersona(outgoing.latchPersona); } - - const body = plainText; - const formattedBody = customHtml; - const mentionData = getMentions(mx, roomId, editor); - - const content: IContent & Pick = { - msgtype: msgType, - body, - }; - - if (replyDraft && !silentReply) { - mentionData.users.add(replyDraft.userId); - } - - content['m.mentions'] = getMentionContent(Array.from(mentionData.users), mentionData.room); - content[prefix.MATRIX_UNSTABLE_IMAGE_SOURCE_PACK_PROPERTY_NAME] = - imagePacksUsedRef.current.toJSON(); - - const links = getLinks(serializedChildren); - content[prefix.MATRIX_UNSTABLE_EMBEDDED_LINK_PREVIEW_PROPERTY_NAME] = []; - links?.forEach((link) => - content[prefix.MATRIX_UNSTABLE_EMBEDDED_LINK_PREVIEW_PROPERTY_NAME].push({ - matched_url: link, - }) - ); - - if (replyDraft || !customHtmlEqualsPlainText(formattedBody, body)) { - content.format = 'org.matrix.custom.html'; - content.formatted_body = formattedBody; - } - - /** - * the currently with the room associated per-message profile, if any, so that it can be included in the message content when sending. - * This allows the server to apply the correct profile-based transformations (e.g. font size adjustments) when processing the message, - * and also allows clients to display an accurate preview of how the message will look with the profile applied while it's being composed. - */ - const globalPerMessageProfile = await getCurrentlyUsedPerMessageProfileForAccount(mx); - const roomPerMessageProfile = await getCurrentlyUsedPerMessageProfileForRoom(mx, roomId); - let perMessageProfile = latchedPersona ?? roomPerMessageProfile ?? globalPerMessageProfile; - - if (pmpProxyingEnable) { - if (proxiedPerMessageProfile) perMessageProfile = proxiedPerMessageProfile; - } - if (perMessageProfile) { - content[prefix.MATRIX_UNSTABLE_PER_MESSAGE_PROFILE_PROPERTY_NAME] = - convertPerMessageProfileToBeeperFormat(perMessageProfile, !pmpNoFallback); - - if (!pmpNoFallback && perMessageProfile.displayname.trim() !== '') { - // if a per-message profile is used, it must per spec include a fallback - const pmpPrefix = `${perMessageProfile.displayname}: `; - - if (!content.body.startsWith(pmpPrefix)) { - // to prevent double-prefixing when the fallback is already present - content.body = pmpPrefix + content.body; - } - - /** - * html escaped version of the display name - */ - const escapedName = sanitizeText(perMessageProfile.displayname); - - const htmlPrefix = `${escapedName}: `; - - if (content.formatted_body && !content.formatted_body.startsWith(htmlPrefix)) { - content.formatted_body = htmlPrefix + content.formatted_body; - } else { - // we don't have a formatted body, but we need one - content.format = 'org.matrix.custom.html'; - const escapedBody = sanitizeText(plainText).replaceAll('\n', '
'); - content.formatted_body = `${htmlPrefix}${escapedBody}`; - } - } - } - if (replyDraft) { content['m.relates_to'] = getReplyContent(replyDraft, room); } diff --git a/src/app/features/room/composerMessage.test.ts b/src/app/features/room/composerMessage.test.ts new file mode 100644 index 000000000..b2f0544c7 --- /dev/null +++ b/src/app/features/room/composerMessage.test.ts @@ -0,0 +1,207 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { BlockType, plainToEditorInput } from '$components/editor'; +import { Command, SHRUG } from '$hooks/useCommands'; +import type { MatrixClient, Room } from '$types/matrix-sdk'; +import { SerializableMap } from '$types/wrapper/SerializableMap'; +import type { MSC4459ImagePackReference } from '$types/matrix/common'; +import type { PKitProxyMessageHandler } from '$plugins/pluralkit-handler/PKitProxyMessageHandler'; +import type * as PerMessageProfileModule from '$hooks/usePerMessageProfile'; +import type { PerMessageProfileMsc4461 } from '$hooks/usePerMessageProfile'; + +const { profiles } = vi.hoisted(() => ({ + profiles: { + account: undefined as PerMessageProfileMsc4461 | undefined, + room: undefined as PerMessageProfileMsc4461 | undefined, + }, +})); + +vi.mock('$hooks/usePerMessageProfile', async (importOriginal) => ({ + ...(await importOriginal()), + getCurrentlyUsedPerMessageProfileForAccount: () => Promise.resolve(profiles.account), + getCurrentlyUsedPerMessageProfileForRoom: () => Promise.resolve(profiles.room), +})); + +const { buildOutgoingMessage } = await import('./composerMessage'); + +const ROOM_ID = '!room:example.org'; + +const room = { + roomId: ROOM_ID, + getMember: (userId: string) => ({ rawDisplayName: `Display ${userId}` }), +} as unknown as Room; + +const mx = { + getUserId: () => '@me:example.org', + getSafeUserId: () => '@me:example.org', + getRoom: () => room, +} as unknown as MatrixClient; + +const noProxyHandler = { + getPmpBasedOnMessage: () => Promise.resolve(undefined), + stripProxyFromMessage: () => undefined, +} as unknown as PKitProxyMessageHandler; + +const profile = (id: string, displayname: string): PerMessageProfileMsc4461 => ({ + id, + displayname, + trigger: { prefix: [] }, +}); + +/** Mirrors how the editor represents a typed command: empty text node, then a command node. */ +const commandInput = (command: Command, rest = '') => [ + { + type: BlockType.Paragraph as const, + children: [ + { text: '' }, + { type: BlockType.Command as const, command, children: [{ text: '' }] }, + { text: rest }, + ], + }, +]; + +const build = ( + input: string | ReturnType, + overrides: Partial[1]> = {} +) => + buildOutgoingMessage(typeof input === 'string' ? plainToEditorInput(input) : input, { + mx, + room, + roomId: ROOM_ID, + nicknames: {}, + replyEvent: undefined, + replyDraft: undefined, + silentReply: false, + settingsLinkBaseUrl: 'https://app.example', + canSendReaction: true, + pkCompatEnable: false, + pmpProxyingEnable: false, + pmpLatchingEnable: false, + pmpNoFallback: false, + latchedPersona: undefined, + isPKCommand: () => false, + pluralkitProxyMessageHandler: noProxyHandler, + imagePacksUsed: new SerializableMap(), + ...overrides, + }); + +beforeEach(() => { + profiles.account = undefined; + profiles.room = undefined; +}); + +describe('buildOutgoingMessage', () => { + it('builds a plain text message', async () => { + const result = await build('hello world'); + expect(result).toMatchObject({ kind: 'message' }); + if (result.kind !== 'message') throw new Error('expected a message'); + expect(result.content.body).toBe('hello world'); + expect(result.content.msgtype).toBe('m.text'); + }); + + it('reports empty input instead of sending a blank message', async () => { + await expect(build(' ')).resolves.toEqual({ kind: 'empty' }); + }); + + it('returns a quick-react descriptor rather than reacting itself', async () => { + await expect(build('+#tada')).resolves.toEqual({ kind: 'quickReact', key: 'tada' }); + }); + + it('ignores quick-react syntax without permission to react', async () => { + const result = await build('+#tada', { canSendReaction: false }); + expect(result.kind).toBe('message'); + }); + + it('returns a pk-command descriptor only when pk compat is on', async () => { + await expect( + build('pk;switch', { pkCompatEnable: false, isPKCommand: () => true }) + ).resolves.toMatchObject({ kind: 'message' }); + await expect( + build('pk;switch', { pkCompatEnable: true, isPKCommand: () => true }) + ).resolves.toEqual({ kind: 'pkCommand', plainText: 'pk;switch' }); + }); + + it('prefixes shrug and emits an emote for /me', async () => { + const shrug = await build(commandInput(Command.Shrug, ' take it')); + if (shrug.kind !== 'message') throw new Error('expected a message'); + expect(shrug.content.body.startsWith(SHRUG)).toBe(true); + + const emote = await build(commandInput(Command.Me, ' waves')); + if (emote.kind !== 'message') throw new Error('expected a message'); + expect(emote.content.msgtype).toBe('m.emote'); + expect(emote.content.body).toBe('waves'); + }); + + it('hands unhandled commands back to the caller to execute', async () => { + const result = await build(commandInput(Command.Poll)); + expect(result).toMatchObject({ kind: 'command', command: Command.Poll }); + }); + + it('mentions the replied-to user unless the reply is silent', async () => { + const replyDraft = { userId: '@other:example.org', eventId: '$reply', body: 'hi' }; + + const loud = await build('answer', { replyDraft }); + if (loud.kind !== 'message') throw new Error('expected a message'); + expect(loud.content['m.mentions']?.user_ids).toContain('@other:example.org'); + + const silent = await build('answer', { replyDraft, silentReply: true }); + if (silent.kind !== 'message') throw new Error('expected a message'); + expect(silent.content['m.mentions']?.user_ids ?? []).not.toContain('@other:example.org'); + }); + + it('adds the spec-required fallback prefix for a named per-message profile', async () => { + profiles.room = profile('p1', 'Alter'); + const result = await build('hello'); + if (result.kind !== 'message') throw new Error('expected a message'); + expect(result.content.body).toBe('Alter: hello'); + expect(result.content.formatted_body).toContain('data-mx-profile-fallback'); + expect(result.content.formatted_body).toContain('Alter: '); + }); + + it('does not double-prefix a body that already carries the fallback', async () => { + profiles.room = profile('p1', 'Alter'); + const result = await build('Alter: hello'); + if (result.kind !== 'message') throw new Error('expected a message'); + expect(result.content.body).toBe('Alter: hello'); + }); + + it('prefers the room profile over the account profile', async () => { + profiles.account = profile('global', 'Global'); + profiles.room = profile('scoped', 'Scoped'); + const result = await build('hello'); + if (result.kind !== 'message') throw new Error('expected a message'); + expect(result.content.body).toBe('Scoped: hello'); + }); + + it('omits an unnamed profile fallback but still tags the profile', async () => { + profiles.account = profile('p1', ''); + const result = await build('hello'); + if (result.kind !== 'message') throw new Error('expected a message'); + expect(result.content.body).toBe('hello'); + }); + + it('strips a pluralkit proxy wrapper and lets its profile win', async () => { + const proxied = profile('proxy', 'Proxied'); + const handler = { + getPmpBasedOnMessage: () => Promise.resolve(proxied), + stripProxyFromMessage: (text: string) => text.replace(/^A:\s*/, ''), + } as unknown as PKitProxyMessageHandler; + profiles.account = profile('global', 'Global'); + + const result = await build('A: hello there', { + pmpProxyingEnable: true, + pluralkitProxyMessageHandler: handler, + }); + if (result.kind !== 'message') throw new Error('expected a message'); + // The wrapper must never reach the wire, and the proxy's profile wins. + expect(result.content.body).toBe('Proxied: hello there'); + }); + + it('records embedded link previews for urls in the body', async () => { + const result = await build('see https://example.com/page'); + if (result.kind !== 'message') throw new Error('expected a message'); + const previews = result.content['com.beeper.linkpreviews'] as + | { matched_url: string }[] + | undefined; + expect(previews?.map((preview) => preview.matched_url)).toContain('https://example.com/page'); + }); +}); diff --git a/src/app/features/room/composerMessage.ts b/src/app/features/room/composerMessage.ts new file mode 100644 index 000000000..49f642494 --- /dev/null +++ b/src/app/features/room/composerMessage.ts @@ -0,0 +1,333 @@ +import type { Editor } from 'slate'; +import type { IContent, MatrixEvent, Room } from '$types/matrix-sdk'; +import { MsgType } from '$types/matrix-sdk'; +import type { MatrixClient, RoomMessageEventContent } from '$types/matrix-sdk'; +import { + BlockType, + customHtmlEqualsPlainText, + getBeginCommand, + getLinks, + getMentions, + plainToEditorInput, + toMatrixCustomHTML, + toPlainText, + trimCommand, + trimCustomHtml, +} from '$components/editor'; +import { sanitizeText } from '$utils/sanitize'; +import { getMentionContent } from '$utils/room/relations'; +import type { IReplyDraft } from '$state/room/roomInputDrafts'; +import { + convertPerMessageProfileToBeeperFormat, + getCurrentlyUsedPerMessageProfileForAccount, + getCurrentlyUsedPerMessageProfileForRoom, + type PerMessageProfileMsc4461, +} from '$hooks/usePerMessageProfile'; +import * as prefix from '$unstable/prefixes'; +import { outgoingMessageTransforms } from './outgoingMessageTransforms'; +import { buildReplacementContent } from './buildReplacementContent'; +import { Command, SHRUG, TABLEFLIP, UNFLIP } from '$hooks/useCommands'; +import type { PKitProxyMessageHandler } from '$plugins/pluralkit-handler/PKitProxyMessageHandler'; +import type { MSC4459ImagePackReference } from '$types/matrix/common'; +import type { SerializableMap } from '$types/wrapper/SerializableMap'; + +export type MessageContent = IContent & Pick; + +/** + * Branches needing React state (opening a picker, running a command, reacting) are + * returned as descriptors rather than executed, keeping this module pure. + */ +export type OutgoingMessage = + | { kind: 'message'; content: MessageContent; latchPersona?: PerMessageProfileMsc4461 } + | { kind: 'quickReact'; key: string } + | { kind: 'pkCommand'; plainText: string } + | { kind: 'command'; command: Command; plainText: string; customHtml: string } + | { kind: 'gifSearch'; query: string } + | { kind: 'empty' }; + +export interface BuildOutgoingMessageDeps { + mx: MatrixClient; + room: Room; + roomId: string; + /** userId -> nickname, stripped from the body and replaced with the real display name. */ + nicknames: Record; + replyEvent: MatrixEvent | undefined; + replyDraft: IReplyDraft | undefined; + silentReply: boolean; + settingsLinkBaseUrl: string; + canSendReaction: boolean; + pkCompatEnable: boolean; + pmpProxyingEnable: boolean; + pmpLatchingEnable: boolean; + pmpNoFallback: boolean; + /** Persona latched by an earlier proxied message in this room. */ + latchedPersona: PerMessageProfileMsc4461 | undefined; + isPKCommand: (plainText: string) => boolean; + pluralkitProxyMessageHandler: PKitProxyMessageHandler; + imagePacksUsed: SerializableMap; +} + +const resolveNickname = ( + room: Room, + nicknames: Record, + userId: string +): string | undefined => { + const nick = nicknames[userId]; + if (typeof nick !== 'string' || nick.length === 0) return undefined; + return room.getMember(userId)?.rawDisplayName ?? userId; +}; + +// Nicknames are local-only, so they are swapped back to real display names before the +// body goes out, keeping server-side mention processing correct. +const buildNicknameReplacement = ( + children: Editor['children'], + { mx, room, roomId, nicknames, replyEvent }: BuildOutgoingMessageDeps +): Map => { + const replacement = new Map(); + const add = (userId: string) => { + const displayName = resolveNickname(room, nicknames, userId); + if (displayName) + replacement.set(new RegExp(`@?${nicknames[userId] as string}`, 'g'), displayName); + }; + + const senderId = replyEvent?.getSender(); + if (senderId) add(senderId); + getMentions(mx, roomId, { children } as Editor)?.users?.forEach(add); + + return replacement; +}; + +const stripCommandNode = (children: Editor['children']): Editor['children'] => { + const firstPara = children[0]; + if ( + firstPara && + 'type' in firstPara && + firstPara.type === BlockType.Paragraph && + firstPara.children.length >= 2 + ) { + return [{ ...firstPara, children: firstPara.children.slice(2) }, ...children.slice(1)]; + } + return children; +}; + +const applyPerMessageProfileFallback = ( + content: MessageContent, + profile: PerMessageProfileMsc4461, + noFallback: boolean +) => { + content[prefix.MATRIX_UNSTABLE_PER_MESSAGE_PROFILE_PROPERTY_NAME] = + convertPerMessageProfileToBeeperFormat(profile, !noFallback); + if (noFallback || profile.displayname.trim() === '') return; + + // Per spec a per-message profile must ship a fallback prefix for clients that ignore it. + const pmpPrefix = `${profile.displayname}: `; + // guard against double-prefixing when the fallback is already present + if (!content.body.startsWith(pmpPrefix)) content.body = pmpPrefix + content.body; + + const htmlPrefix = `${sanitizeText(profile.displayname)}: `; + if (content.formatted_body && !content.formatted_body.startsWith(htmlPrefix)) { + content.formatted_body = htmlPrefix + content.formatted_body; + } else { + // we don't have a formatted body, but the fallback needs one + content.format = 'org.matrix.custom.html'; + const escapedBody = sanitizeText(content.body).replaceAll('\n', '
'); + content.formatted_body = `${htmlPrefix}${escapedBody}`; + } +}; + +export async function buildOutgoingMessage( + children: Editor['children'], + deps: BuildOutgoingMessageDeps +): Promise { + const { + mx, + room, + roomId, + replyDraft, + silentReply, + settingsLinkBaseUrl, + canSendReaction, + pkCompatEnable, + pmpProxyingEnable, + pmpLatchingEnable, + pmpNoFallback, + latchedPersona, + isPKCommand, + pluralkitProxyMessageHandler, + imagePacksUsed, + } = deps; + + const commandName = getBeginCommand({ children } as Editor); + const nicknameReplacement = buildNicknameReplacement(children, deps); + const transformContext = { isMarkdown: true, settingsLinkBaseUrl }; + + const runTransforms = (input: Editor['children']): Editor['children'] => { + let output = input; + outgoingMessageTransforms.forEach((transform) => { + if (!transform.shouldApply(output, transformContext)) return; + output = transform.apply(output, transformContext); + }); + return output; + }; + const forEmote = commandName === Command.Me || commandName === Command.RainbowMe; + const serializeHtml = (input: Editor['children']) => + trimCustomHtml( + toMatrixCustomHTML(input, { + stripNickname: true, + nickNameReplacement: nicknameReplacement, + forEmote, + room, + }) + ); + + let serializedChildren = runTransforms(commandName ? stripCommandNode(children) : children); + let plainText = toPlainText(serializedChildren, true, true, nicknameReplacement).trim(); + let customHtml = serializeHtml(serializedChildren); + let msgType = MsgType.Text; + + if (canSendReaction && plainText.startsWith('+#')) { + return { kind: 'quickReact', key: plainText.substring(2) }; + } + if (pkCompatEnable && isPKCommand(plainText)) { + return { kind: 'pkCommand', plainText }; + } + const rawGifCommand = + commandName === undefined ? plainText.match(/^\/gif(?:\s+(.*))?$/i) : undefined; + if (rawGifCommand) return { kind: 'gifSearch', query: rawGifCommand[1] ?? '' }; + + if (commandName) { + plainText = trimCommand(commandName, plainText); + customHtml = trimCommand(commandName, customHtml); + } + if (commandName === Command.Me) { + msgType = MsgType.Emote; + } else if (commandName === Command.Notice) { + msgType = MsgType.Notice; + } else if (commandName === Command.Shrug) { + plainText = `${SHRUG} ${plainText}`; + customHtml = `${SHRUG} ${customHtml}`; + } else if (commandName === Command.TableFlip) { + plainText = `${TABLEFLIP} ${plainText}`; + customHtml = `${TABLEFLIP} ${customHtml}`; + } else if (commandName === Command.UnFlip) { + plainText = `${UNFLIP} ${plainText}`; + customHtml = `${UNFLIP} ${customHtml}`; + } else if (commandName) { + if (commandName === 'gif') return { kind: 'gifSearch', query: plainText }; + return { kind: 'command', command: commandName as Command, plainText, customHtml }; + } + + if (plainText === '') return { kind: 'empty' }; + + // PluralKit-style proxy wrappers must be stripped before building `content`, otherwise + // the wrapper itself gets sent verbatim. + let proxiedPerMessageProfile: PerMessageProfileMsc4461 | undefined; + let proxyStripped = false; + if (pmpProxyingEnable) { + proxiedPerMessageProfile = await pluralkitProxyMessageHandler.getPmpBasedOnMessage(plainText); + if (proxiedPerMessageProfile) { + // plainText has spoilers stripped, which breaks spoilers carrying a proxy tag, so + // match the proxy against an unsanitized copy instead. + const unsanitizedPlainText = toPlainText( + serializedChildren, + true, + false, + nicknameReplacement + ).trim(); + const stripped = pluralkitProxyMessageHandler.stripProxyFromMessage(unsanitizedPlainText); + if (stripped !== undefined) { + proxyStripped = true; + // Re-run the normal pipeline so a proxied message is parsed like any other. + serializedChildren = runTransforms(plainToEditorInput(stripped)); + plainText = toPlainText(serializedChildren, true, true, nicknameReplacement).trim(); + customHtml = serializeHtml(serializedChildren); + } + } + } + + const mentionData = getMentions(mx, roomId, { children } as Editor); + if (replyDraft && !silentReply) mentionData.users.add(replyDraft.userId); + + const content: MessageContent = { msgtype: msgType, body: plainText }; + content['m.mentions'] = getMentionContent(Array.from(mentionData.users), mentionData.room); + content[prefix.MATRIX_UNSTABLE_IMAGE_SOURCE_PACK_PROPERTY_NAME] = imagePacksUsed.toJSON(); + content[prefix.MATRIX_UNSTABLE_EMBEDDED_LINK_PREVIEW_PROPERTY_NAME] = ( + getLinks(serializedChildren) ?? [] + ).map((matched_url) => ({ matched_url })); + + if (replyDraft || !customHtmlEqualsPlainText(customHtml, plainText)) { + content.format = 'org.matrix.custom.html'; + content.formatted_body = customHtml; + } + + const [globalProfile, roomProfile] = await Promise.all([ + getCurrentlyUsedPerMessageProfileForAccount(mx), + getCurrentlyUsedPerMessageProfileForRoom(mx, roomId), + ]); + const perMessageProfile = + proxiedPerMessageProfile ?? latchedPersona ?? roomProfile ?? globalProfile; + if (perMessageProfile) applyPerMessageProfileFallback(content, perMessageProfile, pmpNoFallback); + + return { + kind: 'message', + content, + // Only a proxy we actually stripped counts as used, so a wrapper we failed to + // strip does not latch the persona for the rest of the room. + latchPersona: pmpLatchingEnable && proxyStripped ? proxiedPerMessageProfile : undefined, + }; +} + +export interface BuildEditReplacementDeps { + mx: MatrixClient; + room: Room; + roomId: string; + editingEvent: MatrixEvent; + /** Content of the latest edit, so a re-edit builds on the current body. */ + currentContent: IContent; + pmpNoFallback: boolean; +} + +/** Returns undefined when there is nothing to send, which cancels the edit. */ +export function buildEditReplacement( + children: Editor['children'], + { mx, room, roomId, editingEvent, currentContent, pmpNoFallback }: BuildEditReplacementDeps +): IContent | undefined { + const plainText = toPlainText(children).trim(); + if (!plainText) return undefined; + + const eventId = editingEvent.getId(); + if (!eventId) return undefined; + + const oldContent = editingEvent.getContent(); + const customHtml = trimCustomHtml( + toMatrixCustomHTML(children, { + forEmote: oldContent.msgtype === MsgType.Emote, + room, + }) + ); + + const mentionData = getMentions(mx, roomId, { children } as Editor); + const previousMentions = currentContent['m.mentions']; + if ( + previousMentions && + typeof previousMentions === 'object' && + 'user_ids' in previousMentions && + Array.isArray(previousMentions.user_ids) + ) { + previousMentions.user_ids.forEach((userId) => { + if (typeof userId === 'string') mentionData.users.add(userId); + }); + } + + return buildReplacementContent( + oldContent, + plainText, + customHtml, + eventId, + getMentionContent(Array.from(mentionData.users), mentionData.room), + (getLinks(children) ?? []).map((matched_url) => ({ matched_url })), + currentContent['com.beeper.per_message_profile'] ?? + oldContent['com.beeper.per_message_profile'], + pmpNoFallback + ); +} From 9bb65886f662a2976286dc0b48f813242ba304c3 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Wed, 5 Aug 2026 21:45:44 -0500 Subject: [PATCH 087/135] fix: duplicated pmp fallback --- src/app/features/room/composerMessage.test.ts | 8 ++++++-- src/app/features/room/composerMessage.ts | 5 ++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/app/features/room/composerMessage.test.ts b/src/app/features/room/composerMessage.test.ts index b2f0544c7..e41edc067 100644 --- a/src/app/features/room/composerMessage.test.ts +++ b/src/app/features/room/composerMessage.test.ts @@ -153,8 +153,9 @@ describe('buildOutgoingMessage', () => { const result = await build('hello'); if (result.kind !== 'message') throw new Error('expected a message'); expect(result.content.body).toBe('Alter: hello'); - expect(result.content.formatted_body).toContain('data-mx-profile-fallback'); - expect(result.content.formatted_body).toContain('Alter: '); + expect(result.content.formatted_body).toBe( + 'Alter: hello' + ); }); it('does not double-prefix a body that already carries the fallback', async () => { @@ -162,6 +163,9 @@ describe('buildOutgoingMessage', () => { const result = await build('Alter: hello'); if (result.kind !== 'message') throw new Error('expected a message'); expect(result.content.body).toBe('Alter: hello'); + expect(result.content.formatted_body).toBe( + 'Alter: hello' + ); }); it('prefers the room profile over the account profile', async () => { diff --git a/src/app/features/room/composerMessage.ts b/src/app/features/room/composerMessage.ts index 49f642494..dc66bed01 100644 --- a/src/app/features/room/composerMessage.ts +++ b/src/app/features/room/composerMessage.ts @@ -121,6 +121,9 @@ const applyPerMessageProfileFallback = ( // Per spec a per-message profile must ship a fallback prefix for clients that ignore it. const pmpPrefix = `${profile.displayname}: `; + const bodyWithoutFallback = content.body.startsWith(pmpPrefix) + ? content.body.slice(pmpPrefix.length) + : content.body; // guard against double-prefixing when the fallback is already present if (!content.body.startsWith(pmpPrefix)) content.body = pmpPrefix + content.body; @@ -130,7 +133,7 @@ const applyPerMessageProfileFallback = ( } else { // we don't have a formatted body, but the fallback needs one content.format = 'org.matrix.custom.html'; - const escapedBody = sanitizeText(content.body).replaceAll('\n', '
'); + const escapedBody = sanitizeText(bodyWithoutFallback).replaceAll('\n', '
'); content.formatted_body = `${htmlPrefix}${escapedBody}`; } }; From e2ac75846b64b38f46592aa1c658f59f23a84cfb Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sat, 1 Aug 2026 17:17:20 +0200 Subject: [PATCH 088/135] fix(composer): serialize sends and snapshot drafts across the composer --- .../components/upload-board/UploadBoard.tsx | 29 +- .../room/AudioMessageRecorder.test.tsx | 107 ++ .../features/room/AudioMessageRecorder.tsx | 34 +- src/app/features/room/RoomInput.test.tsx | 1114 +++++++++++++++ src/app/features/room/RoomInput.tsx | 1207 +++++++++++------ .../features/room/composerController.test.ts | 72 + src/app/features/room/composerController.ts | 40 + .../location-modal/LocationDialog.test.tsx | 101 ++ .../room/location-modal/LocationDialog.tsx | 49 +- .../persona-picker/PersonaPicker.test.tsx | 262 ++++ .../room/persona-picker/PersonaPicker.tsx | 477 +++---- .../room/poll-modals/PollDialog.test.tsx | 116 ++ .../features/room/poll-modals/PollDialog.tsx | 47 +- src/app/utils/common.ts | 6 - src/app/utils/delayedEvents.ts | 10 +- 15 files changed, 2940 insertions(+), 731 deletions(-) create mode 100644 src/app/features/room/AudioMessageRecorder.test.tsx create mode 100644 src/app/features/room/RoomInput.test.tsx create mode 100644 src/app/features/room/composerController.test.ts create mode 100644 src/app/features/room/composerController.ts create mode 100644 src/app/features/room/location-modal/LocationDialog.test.tsx create mode 100644 src/app/features/room/persona-picker/PersonaPicker.test.tsx create mode 100644 src/app/features/room/poll-modals/PollDialog.test.tsx diff --git a/src/app/components/upload-board/UploadBoard.tsx b/src/app/components/upload-board/UploadBoard.tsx index f0a26d386..6d0d86e44 100644 --- a/src/app/components/upload-board/UploadBoard.tsx +++ b/src/app/components/upload-board/UploadBoard.tsx @@ -1,5 +1,5 @@ import type { MutableRefObject, ReactNode } from 'react'; -import { useEffect, useImperativeHandle, useRef } from 'react'; +import { useEffect, useImperativeHandle } from 'react'; import { Badge, Box, Chip, Header, Spinner, Text, as, percent } from 'folds'; import { CaretRight, CaretUp, X, sizedIcon } from '$components/icons/phosphor'; import classNames from 'classnames'; @@ -27,14 +27,15 @@ export const UploadBoard = as<'div', UploadBoardProps>(({ header, children, ...p )); -export type UploadBoardImperativeHandlers = { handleSend: () => Promise }; +// Progress ticks re-render this header, so the caller reads uploads on demand here +// instead of subscribing to them itself. +export type UploadBoardImperativeHandlers = { getSendableUploads: () => Upload[] }; type UploadBoardHeaderProps = { open: boolean; onToggle: () => void; uploadFamilyObserverAtom: TUploadFamilyObserverAtom; onCancel: (uploads: Upload[]) => void; - onSend: (uploads: Upload[]) => Promise; onBusyChange?: (busy: boolean) => void; imperativeHandlerRef: MutableRefObject; }; @@ -44,11 +45,9 @@ export function UploadBoardHeader({ onToggle, uploadFamilyObserverAtom, onCancel, - onSend, onBusyChange, imperativeHandlerRef, }: UploadBoardHeaderProps) { - const sendingRef = useRef(false); const uploads = useAtomValue(uploadFamilyObserverAtom); const isSuccess = uploads.every((upload) => upload.status === UploadStatus.Success); @@ -72,23 +71,11 @@ export function UploadBoardHeader({ { loaded: 0, total: 0 } ); - const handleSend = async () => { - if (sendingRef.current) return; - sendingRef.current = true; - try { - await onSend( - uploads.filter( - (upload) => - upload.status === UploadStatus.Success || upload.status === UploadStatus.Loading - ) - ); - } finally { - sendingRef.current = false; - } - }; - useImperativeHandle(imperativeHandlerRef, () => ({ - handleSend, + getSendableUploads: () => + uploads.filter( + (upload) => upload.status === UploadStatus.Success || upload.status === UploadStatus.Loading + ), })); const handleCancel = () => onCancel(uploads); diff --git a/src/app/features/room/AudioMessageRecorder.test.tsx b/src/app/features/room/AudioMessageRecorder.test.tsx new file mode 100644 index 000000000..279649f4c --- /dev/null +++ b/src/app/features/room/AudioMessageRecorder.test.tsx @@ -0,0 +1,107 @@ +/* oxlint-disable typescript/no-explicit-any, vitest/require-mock-type-parameters */ + +import { act, render } from '@testing-library/react'; +import { createRef } from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { AudioMessageRecorder, type AudioMessageRecorderHandle } from './AudioMessageRecorder'; + +const recorderState = vi.hoisted(() => ({ + handleStop: vi.fn(), + handleDelete: vi.fn(), + onStop: undefined as ((payload: any) => void) | undefined, + onDelete: undefined as (() => void) | undefined, +})); + +vi.mock('$plugins/voice-recorder-kit', () => ({ + useVoiceRecorder: ({ onStop, onDelete }: any) => { + recorderState.onStop = onStop; + recorderState.onDelete = onDelete; + return { + levels: [], + seconds: 0, + error: undefined, + handleStop: recorderState.handleStop, + handleDelete: recorderState.handleDelete, + }; + }, +})); +vi.mock('$hooks/useElementSizeObserver', () => ({ useElementSizeObserver: () => {} })); +vi.mock('folds', () => ({ + Box: ({ children }: any) =>
{children}
, + Text: ({ children }: any) => {children}, +})); + +const payload = { + audioFile: new Blob(['audio'], { type: 'audio/ogg' }), + waveform: [0.5], + audioLength: 1, + audioCodec: 'audio/ogg', +}; + +function renderRecorder() { + const ref = createRef(); + const onRecordingComplete = vi.fn(); + const result = render( + + ); + return { ref, onRecordingComplete, result }; +} + +beforeEach(() => { + vi.useFakeTimers(); + recorderState.handleStop.mockReset(); + recorderState.handleDelete.mockReset(); + recorderState.onStop = undefined; + recorderState.onDelete = undefined; +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe('AudioMessageRecorder lifecycle', () => { + it('makes stop idempotent and surfaces one completion', () => { + const { ref, onRecordingComplete } = renderRecorder(); + + act(() => { + ref.current?.stop(); + ref.current?.stop(); + recorderState.onStop?.(payload); + recorderState.onStop?.(payload); + }); + + expect(recorderState.handleStop).toHaveBeenCalledOnce(); + expect(onRecordingComplete).toHaveBeenCalledOnce(); + }); + + it('makes delayed cancel idempotent and cancels its timer on unmount', () => { + const { ref, result } = renderRecorder(); + + act(() => { + ref.current?.cancel(); + ref.current?.cancel(); + vi.advanceTimersByTime(180); + }); + expect(recorderState.handleDelete).toHaveBeenCalledOnce(); + + result.unmount(); + act(() => vi.runOnlyPendingTimers()); + expect(recorderState.handleDelete).toHaveBeenCalledOnce(); + }); + + it('does not delete after cancel is followed by unmount before the delay', () => { + const { ref, result } = renderRecorder(); + + act(() => ref.current?.cancel()); + result.unmount(); + act(() => vi.advanceTimersByTime(180)); + + expect(recorderState.handleDelete).not.toHaveBeenCalled(); + }); +}); diff --git a/src/app/features/room/AudioMessageRecorder.tsx b/src/app/features/room/AudioMessageRecorder.tsx index f0db57b3d..d73fe8056 100644 --- a/src/app/features/room/AudioMessageRecorder.tsx +++ b/src/app/features/room/AudioMessageRecorder.tsx @@ -48,8 +48,9 @@ export const AudioMessageRecorder = forwardRef< AudioMessageRecorderHandle, AudioMessageRecorderProps >(({ onRecordingComplete, onRequestClose, onWaveformUpdate, onAudioLengthUpdate }, ref) => { - const isDismissedRef = useRef(false); const userRequestedStopRef = useRef(false); + const actionRef = useRef<'active' | 'stopping' | 'canceling' | 'dismissed'>('active'); + const cancelTimerRef = useRef | null>(null); const containerRef = useRef(null); const [isCanceling, setIsCanceling] = useState(false); const [announcedTime, setAnnouncedTime] = useState(0); @@ -67,8 +68,8 @@ export const AudioMessageRecorder = forwardRef< const stableOnStop = useCallback((payload: VoiceRecorderStopPayload) => { // useVoiceRecorder also stops during cancel/teardown paths, so only surface a completed // recording after an explicit user stop. - if (!userRequestedStopRef.current) return; - if (isDismissedRef.current) return; + if (!userRequestedStopRef.current || actionRef.current !== 'stopping') return; + actionRef.current = 'dismissed'; onRecordingCompleteRef.current({ audioBlob: payload.audioFile, waveform: payload.waveform, @@ -80,7 +81,11 @@ export const AudioMessageRecorder = forwardRef< }, []); const stableOnDelete = useCallback(() => { - isDismissedRef.current = true; + if (cancelTimerRef.current !== null) { + clearTimeout(cancelTimerRef.current); + cancelTimerRef.current = null; + } + actionRef.current = 'dismissed'; onRequestCloseRef.current(); }, []); @@ -91,22 +96,35 @@ export const AudioMessageRecorder = forwardRef< }); const doStop = useCallback(() => { - if (isDismissedRef.current) return; + if (actionRef.current !== 'active') return; + actionRef.current = 'stopping'; userRequestedStopRef.current = true; handleStop(); }, [handleStop]); const doCancel = useCallback(() => { - if (isDismissedRef.current) return; + if (actionRef.current !== 'active') return; + actionRef.current = 'canceling'; setIsCanceling(true); - setTimeout(() => { - isDismissedRef.current = true; + cancelTimerRef.current = setTimeout(() => { + cancelTimerRef.current = null; + if (actionRef.current !== 'canceling') return; + actionRef.current = 'dismissed'; handleDelete(); }, 180); }, [handleDelete]); useImperativeHandle(ref, () => ({ stop: doStop, cancel: doCancel }), [doStop, doCancel]); + useEffect( + () => () => { + if (cancelTimerRef.current !== null) clearTimeout(cancelTimerRef.current); + cancelTimerRef.current = null; + actionRef.current = 'dismissed'; + }, + [] + ); + useEffect(() => { if (seconds > 0 && seconds % 30 === 0 && seconds !== announcedTime) { setAnnouncedTime(seconds); diff --git a/src/app/features/room/RoomInput.test.tsx b/src/app/features/room/RoomInput.test.tsx new file mode 100644 index 000000000..cb950bc57 --- /dev/null +++ b/src/app/features/room/RoomInput.test.tsx @@ -0,0 +1,1114 @@ +/* oxlint-disable typescript/no-explicit-any, typescript/no-extraneous-class, unicorn/consistent-function-scoping, vitest/require-mock-type-parameters */ + +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { + forwardRef, + useEffect, + useImperativeHandle, + useMemo, + useState, + type ReactNode, +} from 'react'; +import { useAtom, useAtomValue } from 'jotai'; +import { createEditor, Transforms } from 'slate'; +import { M_POLL_START } from 'matrix-js-sdk'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { RoomInput } from './RoomInput'; +import { + roomIdToMsgDraftAtomFamily, + roomIdToReplyDraftAtomFamily, + roomIdToUploadItemsAtomFamily, +} from '$state/room/roomInputDrafts'; +import { + roomIdToEditingScheduledDelayIdAtomFamily, + roomIdToScheduledTimeAtomFamily, +} from '$state/scheduledMessages'; +import { roomScheduleCoordinator } from '$state/room/roomScheduleCoordinator'; + +const testState = vi.hoisted(() => ({ + isMobile: false, + matrix: { + sendMessage: vi.fn(), + sendEvent: vi.fn(), + getUserId: vi.fn(() => '@me:example.org'), + getSafeUserId: vi.fn(() => '@me:example.org'), + }, + cancelDelayedEvent: vi.fn(), + sendDelayedMessage: vi.fn(), + pendingUploads: [] as unknown[], + sendIndividualAttachmentAsCaption: false, + encrypted: false, + handleFiles: undefined as ((files: File[]) => Promise) | undefined, + safeUploadFile: vi.fn(), + encryptFile: vi.fn(), + editingEvent: undefined as + | { getId: () => string; getContent: () => Record } + | undefined, +})); + +vi.mock('$hooks/useMatrixClient', () => ({ + useMatrixClient: () => testState.matrix, +})); + +vi.mock(import('$utils/platform'), async (importOriginal) => ({ + ...(await importOriginal()), + isMobileOrTablet: () => testState.isMobile, + isMobileTauri: () => false, +})); + +vi.mock('$state/hooks/settings', () => ({ + useSetting: (_atom: unknown, key: string) => { + const values: Record = { + enterForNewline: false, + editorGifButton: false, + editorEmojiButton: false, + editorStickerButton: false, + editorMicButton: false, + editorButtonOrder: [], + shortcutOverrides: {}, + hideActivity: true, + mentionInReplies: true, + pkCompat: false, + pmpProxying: false, + pmpPicker: false, + hour24Clock: false, + enableMediaGalleries: false, + sendIndividualAttachmentAsCaption: testState.sendIndividualAttachmentAsCaption, + }; + return [values[key], vi.fn()]; + }, +})); + +vi.mock('$state/settings', () => ({ settingsAtom: {} })); + +vi.mock('$state/room/roomInputDrafts', async () => { + const { atom } = await import('jotai'); + const msgDraftAtom = atom([]); + const replyDraftAtom = atom(undefined); + const uploadItemsAtom = atom([], (get, set, action) => { + const update = action as any; + if (Array.isArray(update)) { + set(uploadItemsAtom, update); + return; + } + if (update?.type === 'PUT') set(uploadItemsAtom, [...get(uploadItemsAtom), ...update.item]); + if (update?.type === 'DELETE') { + const deleted = new Set(Array.isArray(update.item) ? update.item : [update.item]); + set( + uploadItemsAtom, + get(uploadItemsAtom).filter((item: any) => !deleted.has(item)) + ); + } + if (update?.type === 'REPLACE') { + set( + uploadItemsAtom, + get(uploadItemsAtom).map((item: any) => (item === update.item ? update.replacement : item)) + ); + } + }); + const scheduledTimeAtom = atom(null); + const editingScheduledDelayIdAtom = atom(null); + return { + roomIdToMsgDraftAtomFamily: () => msgDraftAtom, + roomIdToReplyDraftAtomFamily: () => replyDraftAtom, + roomIdToUploadItemsAtomFamily: () => uploadItemsAtom, + roomUploadAtomFamily: Object.assign(() => atom(undefined), { remove: vi.fn() }), + roomIdToScheduledTimeAtomFamily: () => scheduledTimeAtom, + roomIdToEditingScheduledDelayIdAtomFamily: () => editingScheduledDelayIdAtom, + }; +}); + +vi.mock('$state/upload', async () => { + const { atom } = await import('jotai'); + const observerAtom = atom([]); + return { + UploadStatus: { Loading: 'loading', Success: 'success' }, + createUploadFamilyObserverAtom: () => observerAtom, + }; +}); + +vi.mock('$components/editor', () => { + const textOf = (nodes: any[]) => + nodes + .map((node) => (node.children ?? []).map((child: any) => child.text ?? '').join('')) + .join('\n'); + const passthrough = ({ children }: { children?: unknown }) => children ?? null; + const CustomEditor = ({ + editableName, + editor, + onChange, + onKeyDown, + before, + top, + after, + bottom, + }: any) => ( +
+ {top} + {before} +
+ {after} + {bottom} +
+ ); + return { + AutocompletePrefix: { + RoomMention: 'room-mention', + UserMention: 'user-mention', + Emoticon: 'emoticon', + Reaction: 'reaction', + Command: 'command', + }, + ANYWHERE_AUTOCOMPLETE_PREFIXES: [], + BEGINNING_AUTOCOMPLETE_PREFIXES: [], + BlockType: { Paragraph: 'paragraph' }, + Command: {}, + CustomEditor, + EmoticonAutocomplete: passthrough, + MarkdownFormattingToolbarBottom: passthrough, + MarkdownFormattingToolbarToggle: passthrough, + RoomMentionAutocomplete: passthrough, + UserMentionAutocomplete: passthrough, + createEmoticonElement: () => ({ text: '' }), + customHtmlEqualsPlainText: (html: string, text: string) => html === text, + focusEditor: vi.fn(), + getAutocompleteQuery: vi.fn(), + getBeginCommand: () => undefined, + getLinks: () => [], + getMentions: () => ({ users: new Set(), room: undefined }), + getPrevWorldRange: () => undefined, + isEmptyEditor: (editor: any) => textOf(editor.children).trim() === '', + moveCursor: vi.fn(), + plainToEditorInput: (text: string) => [{ type: 'paragraph', children: [{ text }] }], + replaceWithElement: vi.fn(), + resetEditor: (editor: any) => { + editor.children = [{ type: 'paragraph', children: [{ text: '' }] }]; + editor.selection = null; + }, + resetEditorHistory: vi.fn(), + toMatrixCustomHTML: (nodes: any[]) => textOf(nodes), + toPlainText: textOf, + trimCommand: (_command: unknown, text: string) => text, + trimCustomHtml: (html: string) => html, + }; +}); + +vi.mock('$components/upload-board', async () => { + const UploadBoardHeader = ({ imperativeHandlerRef }: any) => { + useImperativeHandle(imperativeHandlerRef, () => ({ + getSendableUploads: () => testState.pendingUploads, + })); + return null; + }; + const UploadBoard = ({ header, children }: any) => ( + <> + {header} + {children} + + ); + return { + UploadBoard, + UploadBoardContent: ({ children }: any) => <>{children}, + UploadBoardHeader, + }; +}); + +vi.mock('$components/upload-card', () => ({ + UploadCardRenderer: ({ fileItem, setMetadata, setDesc }: any) => ( + <> + + + + ), +})); +vi.mock('$components/attachment-sheet/AttachmentSheet', () => ({ AttachmentSheet: () => null })); +vi.mock('$components/emoji-board', () => ({ + EmojiBoard: ({ onStickerSelect }: any) => ( + + ), + EmojiBoardTab: {}, +})); +vi.mock('$components/UseStateProvider', () => ({ + UseStateProvider: ({ children }: any) => (typeof children === 'function' ? children() : children), +})); +vi.mock('$components/message', () => ({ Reply: () => null, ThreadIndicator: () => null })); +vi.mock('./CommandAutocomplete', () => ({ CommandAutocomplete: () => null })); +vi.mock('./AudioMessageRecorder', () => ({ AudioMessageRecorder: () => null })); +vi.mock('./persona-picker/PersonaPicker', () => ({ PersonaPicker: () => null })); +vi.mock('./schedule-send', () => ({ SchedulePickerDialog: () => null })); +vi.mock('./poll-modals', () => ({ + PollDialog: ({ onSubmit }: any) => ( + + ), +})); +vi.mock('./location-modal', () => ({ + LocationDialog: ({ onSubmit, onCancel }: any) => { + const [failed, setFailed] = useState(false); + return ( + <> + {failed &&
location submit failed
} + + + ); + }, +})); +vi.mock('$components/icons/phosphor', () => { + const Icon = forwardRef(({ children }, ref) => ( + + )); + return { + Bell: Icon, + BellSlash: Icon, + CaretDown: Icon, + Clock: Icon, + File: Icon, + Gif: Icon, + Image: Icon, + ListBullets: Icon, + MapPinPlusIcon: Icon, + Microphone: Icon, + PaperPlaneTilt: Icon, + PencilSimple: Icon, + PlusCircle: Icon, + Smiley: Icon, + Sticker: Icon, + Stop: Icon, + X: Icon, + chipIcon: () => null, + composerIcon: () => null, + dropzoneIcon: () => null, + getPhosphorIconSize: () => 16, + menuIcon: () => null, + }; +}); + +vi.mock('folds', () => { + const Box = ({ children }: any) =>
{children}
; + const Button = forwardRef(({ children, ...props }, ref) => ( + + )); + const passthrough = ({ children }: any) => <>{children}; + return { + Box, + Dialog: passthrough, + IconButton: Button, + Menu: passthrough, + MenuItem: Button, + Overlay: passthrough, + OverlayBackdrop: () => null, + OverlayCenter: passthrough, + PopOut: ({ children, content }: any) => ( + <> + {children} + {content} + + ), + Scroll: passthrough, + Spinner: () => Sending, + Text: ({ children }: any) => {children}, + color: { Critical: { Main: 'red' } }, + config: { space: { S100: '1px', S200: '2px', S300: '3px' } }, + toRem: (value: number) => `${value / 16}rem`, + }; +}); + +vi.mock('$hooks/useTypingStatusUpdater', () => ({ useTypingStatusUpdater: () => vi.fn() })); +vi.mock('$hooks/useFilePicker', () => ({ + useFilePicker: (handleFiles: (files: File[]) => Promise) => { + testState.handleFiles = handleFiles; + return vi.fn(); + }, +})); +vi.mock('$hooks/useFilePasteHandler', () => ({ useFilePasteHandler: () => vi.fn() })); +vi.mock('$hooks/useFileDrop', () => ({ useFileDropZone: () => false })); +vi.mock('$hooks/useCommands', () => ({ + Command: {}, + SHRUG: '¯\\_(ツ)_/¯', + TABLEFLIP: '(╯°□°)╯︵ ┻━┻', + UNFLIP: '┬─┬ノ( º _ ºノ)', + useCommands: () => ({}), +})); +vi.mock('$hooks/useClientConfig', () => ({ useClientConfig: () => ({}) })); +vi.mock('$hooks/useMediaAuthentication', () => ({ useMediaAuthentication: () => false })); +vi.mock('$hooks/useImagePackRooms', () => ({ useImagePackRooms: () => [] })); +vi.mock('$hooks/useComposingCheck', () => ({ useComposingCheck: () => () => false })); +vi.mock('$hooks/usePerMessageProfile', () => ({ + convertPerMessageProfileToBeeperFormat: () => ({}), + getCurrentlyUsedPerMessageProfileForAccount: async () => undefined, + getCurrentlyUsedPerMessageProfileForRoom: async () => undefined, +})); +vi.mock('@tanstack/react-query', () => ({ + useQueryClient: () => ({ invalidateQueries: vi.fn() }), +})); +vi.mock('$hooks/usePowerLevels', () => ({ + usePowerLevelsContext: () => ({}), + useRoomPermissions: () => ({ event: () => true }), +})); +vi.mock('$hooks/useRoomPermissions', () => ({ useRoomPermissions: () => ({ event: () => true }) })); +vi.mock('$hooks/useRoomCreators', () => ({ useRoomCreators: () => [] })); +vi.mock('$features/settings/useSettingsLinkBaseUrl', () => ({ useSettingsLinkBaseUrl: () => '' })); +vi.mock('$state/room/roomToParents', async () => { + const { atom } = await import('jotai'); + return { roomToParentsAtom: atom({}) }; +}); +vi.mock('$state/nicknames', async () => { + const { atom } = await import('jotai'); + return { nicknamesAtom: atom({}) }; +}); +vi.mock('$state/scheduledMessages', async () => { + const { atom } = await import('jotai'); + const scheduledTimeAtom = atom(null); + const editingScheduledDelayIdAtom = atom(null); + return { + delayedEventsSupportedAtom: atom(false), + roomIdToScheduledTimeAtomFamily: () => scheduledTimeAtom, + roomIdToEditingScheduledDelayIdAtomFamily: () => editingScheduledDelayIdAtom, + serverMaxDelayMsAtom: atom(null), + }; +}); +vi.mock('$utils/matrix', () => ({ + cancelUploadContent: vi.fn(), + encryptFile: testState.encryptFile, + getImageInfo: vi.fn(), + mxcUrlToHttp: vi.fn(), + toggleReaction: vi.fn(), +})); +vi.mock('$utils/mimeTypes', () => ({ + FALLBACK_MIMETYPE: 'application/octet-stream', + TGS_MIMETYPE: 'application/x-tgsticker', + isImageMimeType: () => false, + safeUploadFile: testState.safeUploadFile, +})); +vi.mock('$utils/dom', () => ({ loadImageElementFromMediaUrl: vi.fn() })); +vi.mock('$plugins/custom-emoji/utils', () => ({ getPackImageInfo: () => undefined })); +vi.mock('$utils/msc4459helper', () => ({ + getImagePackReferencesForMxc: () => undefined, + getImagePackReferencesForMxcWrappedInMap: () => ({}), +})); +vi.mock('$utils/room/relations', () => ({ + getEditedEvent: vi.fn(), + getMentionContent: () => ({ user_ids: [] }), + getThreadReplyEvents: () => [], +})); +vi.mock('$plugins/markdown', () => ({ htmlToMarkdown: (html: string) => html })); +vi.mock('$utils/delayedEvents', () => ({ + cancelDelayedEvent: testState.cancelDelayedEvent, + computeDelayMs: vi.fn(), + sendDelayedMessage: testState.sendDelayedMessage, + sendDelayedMessageE2EE: vi.fn(), +})); +vi.mock('$utils/time', () => ({ + daysToMs: () => 1, + timeDayMonthYear: () => '', + timeHourMinute: () => '', +})); +vi.mock('$utils/keyboard', () => ({ stopPropagation: vi.fn() })); +vi.mock('$utils/debug', () => ({ createLogger: () => ({ error: vi.fn(), warn: vi.fn() }) })); +vi.mock('$utils/debugLogger', () => ({ + createDebugLogger: () => ({ info: vi.fn(), error: vi.fn() }), +})); +vi.mock('$plugins/pluralkit-handler/PKitCommandMessageHandler', () => ({ + PKitCommandMessageHandler: class { + static isPKCommand() { + return false; + } + }, +})); +vi.mock('$plugins/pluralkit-handler/PKitProxyMessageHandler', () => ({ + PKitProxyMessageHandler: class { + init() {} + async getPmpBasedOnMessage() { + return undefined; + } + }, +})); +vi.mock('$sentry/react', () => ({ + metrics: { count: vi.fn(), distribution: vi.fn() }, + startSpan: (_options: unknown, callback: () => unknown) => callback(), +})); + +const room = { + roomId: '!room:example.org', + name: 'Test room', + hasEncryptionStateEvent: () => testState.encrypted, + findEventById: (eventId: string) => + eventId === testState.editingEvent?.getId() ? testState.editingEvent : undefined, + getTimelineForEvent: () => undefined, + getMember: () => undefined, + getLiveTimeline: () => ({ getEvents: () => [] }), +} as any; + +function RoomInputHarness({ + editId, + onCancelEdit, + scheduled = false, + scheduledText = false, + initialDraft, + initialReply = false, + threadRootId, +}: { + editId?: string; + onCancelEdit?: () => void; + scheduled?: boolean; + /** Schedules a text-only send, with no attachments involved. */ + scheduledText?: boolean; + initialDraft?: string; + initialReply?: boolean; + threadRootId?: string; +}) { + const editor = useMemo(() => { + const nextEditor = createEditor(); + nextEditor.children = [{ type: 'paragraph' as any, children: [{ text: '' }] }]; + return nextEditor; + }, []); + const fileDropContainerRef = useMemo(() => ({ current: null }), []); + const [, setMsgDraft] = useAtom(roomIdToMsgDraftAtomFamily(room.roomId)); + const [, setSelectedFiles] = useAtom(roomIdToUploadItemsAtomFamily(room.roomId)); + const [, setReplyDraft] = useAtom(roomIdToReplyDraftAtomFamily(room.roomId)); + const [, setScheduledTime] = useAtom(roomIdToScheduledTimeAtomFamily(room.roomId)); + const [, setEditingScheduledDelayId] = useAtom( + roomIdToEditingScheduledDelayIdAtomFamily(room.roomId) + ); + useEffect(() => { + (setMsgDraft as any)( + initialDraft ? [{ type: 'paragraph', children: [{ text: initialDraft }] }] : [] + ); + (setSelectedFiles as any)([]); + setReplyDraft( + initialReply ? { userId: '@other:example.org', eventId: '$reply', body: 'reply' } : undefined + ); + setScheduledTime(scheduledText ? new Date('2026-07-28T12:00:00.000Z') : null); + setEditingScheduledDelayId(null); + }, [ + scheduledText, + initialDraft, + initialReply, + setEditingScheduledDelayId, + setMsgDraft, + setReplyDraft, + setScheduledTime, + setSelectedFiles, + ]); + const setText = (text = 'retry me') => { + editor.children = [{ type: 'paragraph' as any, children: [{ text: '' }] }]; + Transforms.select(editor, { path: [0, 0], offset: 0 }); + Transforms.insertText(editor, text); + fireEvent.input(screen.getByTestId('room-input-editor')); + }; + return ( + <> + + + + + + + + ); +} + +function DraftObserver() { + const draft = useAtomValue(roomIdToMsgDraftAtomFamily(room.roomId)); + return ( +
{((draft[0] as any)?.children?.[0] as any)?.text ?? ''}
+ ); +} + +function DraftSetter({ text }: { text: string }) { + const [, setDraft] = useAtom(roomIdToMsgDraftAtomFamily(room.roomId)); + useEffect(() => { + setDraft([{ type: 'paragraph' as any, children: [{ text }] }]); + }, [setDraft, text]); + return null; +} + +function ReplyObserver() { + const reply = useAtomValue(roomIdToReplyDraftAtomFamily(room.roomId)); + return
{reply?.eventId ?? ''}
; +} + +function UploadObserver() { + const uploads = useAtomValue(roomIdToUploadItemsAtomFamily(room.roomId)); + return ( +
+ {JSON.stringify( + uploads.map((upload) => ({ + encrypting: upload.encrypting, + metadata: upload.metadata, + body: upload.body, + })) + )} +
+ ); +} + +const sendButton = () => screen.getByRole('button', { name: 'Send your composed Message' }); + +function deferred() { + let resolve!: (value: T) => void; + let reject!: (reason?: unknown) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + +beforeEach(() => { + testState.isMobile = false; + testState.pendingUploads = []; + testState.sendIndividualAttachmentAsCaption = false; + testState.encrypted = false; + testState.handleFiles = undefined; + testState.safeUploadFile.mockReset().mockImplementation(async (file: File) => file); + testState.encryptFile.mockReset(); + testState.editingEvent = undefined; + testState.matrix.sendMessage.mockReset().mockResolvedValue({ event_id: '$event' }); + testState.matrix.sendEvent.mockReset().mockResolvedValue({}); + testState.cancelDelayedEvent.mockReset(); + testState.sendDelayedMessage.mockReset(); +}); + +describe('RoomInput submit regressions', () => { + it('sends only once when submitted twice before the first send resolves', async () => { + const send = deferred<{ event_id: string }>(); + testState.matrix.sendMessage.mockReturnValue(send.promise); + render(); + fireEvent.click(screen.getByRole('button', { name: 'Prepare attachment' })); + fireEvent.click(screen.getByRole('button', { name: 'Compose text' })); + + const submit = screen.getByRole('button', { name: 'Send your composed Message' }); + fireEvent.click(submit); + fireEvent.click(submit); + + await waitFor(() => expect(testState.matrix.sendMessage).toHaveBeenCalledOnce()); + send.resolve({ event_id: '$event' }); + await waitFor(() => + expect(screen.getByRole('button', { name: 'Send your composed Message' })).toBeEnabled() + ); + }); + + it('waits for an attachment transaction instead of sending text independently', async () => { + const upload = deferred<{ content_uri: string }>(); + const file = new File(['attachment'], 'attachment.txt', { type: 'text/plain' }); + testState.pendingUploads = [{ status: 'loading', file, promise: upload.promise }]; + + render(); + fireEvent.click(screen.getByRole('button', { name: 'Prepare attachment' })); + fireEvent.click(screen.getByRole('button', { name: 'Compose text' })); + + fireEvent.click(screen.getByRole('button', { name: 'Send your composed Message' })); + expect(testState.matrix.sendMessage).not.toHaveBeenCalled(); + upload.resolve({ content_uri: 'mxc://example/attachment' }); + await waitFor(() => expect(testState.matrix.sendMessage).toHaveBeenCalledTimes(2)); + expect(testState.matrix.sendMessage.mock.calls[0]?.[2]?.body).toBe('attachment.txt'); + expect(testState.matrix.sendMessage.mock.calls[1]?.[2]?.body).toBe('retry me'); + }); + + it('keeps attachment retry locked until every sibling send settles', async () => { + const delayedSecondSend = deferred<{ event_id: string }>(); + let sendNumber = 0; + testState.matrix.sendMessage.mockImplementation(() => { + sendNumber += 1; + return sendNumber === 1 + ? Promise.reject(new Error('first attachment failed')) + : delayedSecondSend.promise; + }); + + render(); + fireEvent.click(screen.getByRole('button', { name: 'Prepare two attachments' })); + fireEvent.keyDown(screen.getByTestId('room-input-editor'), { key: 'Enter', code: 'Enter' }); + + // Clearing the composer remounts the editor subtree, so re-query the button. + await waitFor(() => expect(testState.matrix.sendMessage).toHaveBeenCalledTimes(2)); + expect(sendButton()).toBeDisabled(); + fireEvent.click(sendButton()); + expect(testState.matrix.sendMessage).toHaveBeenCalledTimes(2); + + delayedSecondSend.resolve({ event_id: '$second' }); + await waitFor(() => expect(sendButton()).toBeEnabled()); + expect(testState.matrix.sendMessage).toHaveBeenCalledTimes(2); + }); + + it('waits for all scheduled siblings before unlocking and does not re-cancel on retry', async () => { + const delayedSecondSend = deferred(); + let sendNumber = 0; + testState.sendDelayedMessage.mockImplementation(() => { + sendNumber += 1; + if (sendNumber === 1) return Promise.reject(new Error('first scheduled send failed')); + if (sendNumber === 2) return delayedSecondSend.promise; + return Promise.resolve(); + }); + + render(); + fireEvent.click(screen.getByRole('button', { name: 'Prepare two attachments' })); + fireEvent.keyDown(screen.getByTestId('room-input-editor'), { key: 'Enter', code: 'Enter' }); + + await waitFor(() => expect(testState.sendDelayedMessage).toHaveBeenCalledTimes(2)); + expect(sendButton()).toBeDisabled(); + fireEvent.click(sendButton()); + expect(testState.sendDelayedMessage).toHaveBeenCalledTimes(2); + + delayedSecondSend.resolve(undefined); + await waitFor(() => expect(sendButton()).toBeEnabled()); + expect(testState.cancelDelayedEvent).toHaveBeenCalledOnce(); + + testState.pendingUploads = [testState.pendingUploads[0]]; + fireEvent.click(sendButton()); + await waitFor(() => expect(testState.sendDelayedMessage).toHaveBeenCalledTimes(3)); + expect(testState.cancelDelayedEvent).toHaveBeenCalledOnce(); + }); + + it('routes delayed replacement sends through the room schedule coordinator', async () => { + const runSpy = vi.spyOn(roomScheduleCoordinator, 'run'); + try { + render(); + fireEvent.click(screen.getByRole('button', { name: 'Prepare two attachments' })); + fireEvent.keyDown(screen.getByTestId('room-input-editor'), { key: 'Enter', code: 'Enter' }); + + await waitFor(() => expect(testState.sendDelayedMessage).toHaveBeenCalledTimes(2)); + expect(runSpy).toHaveBeenCalledWith(room.roomId, expect.any(Function)); + } finally { + runSpy.mockRestore(); + } + }); + + it('does not consume main-room scheduling state from a thread composer', async () => { + render(); + fireEvent.click(screen.getByRole('button', { name: 'Prepare two attachments' })); + fireEvent.keyDown(screen.getByTestId('room-input-editor'), { key: 'Enter', code: 'Enter' }); + + await waitFor(() => expect(testState.matrix.sendMessage).toHaveBeenCalledTimes(2)); + expect(testState.sendDelayedMessage).not.toHaveBeenCalled(); + expect(testState.cancelDelayedEvent).not.toHaveBeenCalled(); + }); + + it('queues poll content behind a picker and applies reply semantics', async () => { + const stickerSend = deferred(); + testState.matrix.sendEvent.mockReturnValue(stickerSend.promise); + render(); + + fireEvent.click(screen.getByRole('button', { name: 'Select sticker' })); + await waitFor(() => expect(testState.matrix.sendEvent).toHaveBeenCalledOnce()); + fireEvent.click(screen.getByRole('button', { name: 'Select newer reply' })); + fireEvent.click(screen.getByRole('button', { name: 'Create Poll' })); + fireEvent.click(screen.getByRole('button', { name: 'Submit poll' })); + + expect(testState.matrix.sendEvent).toHaveBeenCalledOnce(); + stickerSend.resolve({}); + await waitFor(() => expect(testState.matrix.sendEvent).toHaveBeenCalledTimes(2)); + + // A poll must go out as its own event type, not as an m.room.message. + const pollCall = testState.matrix.sendEvent.mock.calls[1]; + expect(pollCall?.[2]).toBe(M_POLL_START.name); + expect(pollCall?.[3]?.['m.relates_to']).toBeDefined(); + expect(testState.matrix.sendMessage).not.toHaveBeenCalled(); + }); + + it('keeps the location dialog open when the queued send rejects', async () => { + testState.matrix.sendMessage.mockRejectedValueOnce(new Error('send failed')); + render(); + + fireEvent.click(screen.getByRole('button', { name: 'Add Location' })); + await waitFor(() => + expect(screen.getByRole('button', { name: 'Submit location' })).toBeInTheDocument() + ); + fireEvent.click(screen.getByRole('button', { name: 'Submit location' })); + + await waitFor(() => expect(testState.matrix.sendMessage).toHaveBeenCalledOnce()); + expect(screen.getByTestId('location-submit-failed')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Submit location' })).toBeInTheDocument(); + }); + + it('clears the composer on a failed immediate send, leaving retry to the local echo', async () => { + // A rejected mx.sendMessage leaves a NOT_SENT local echo in the timeline with resend + // and delete affordances, so putting the text back would duplicate the message. + testState.matrix.sendMessage.mockRejectedValueOnce(new Error('send failed')); + render(); + fireEvent.click(screen.getByRole('button', { name: 'Compose text' })); + + fireEvent.click(sendButton()); + await waitFor(() => expect(testState.matrix.sendMessage).toHaveBeenCalledOnce()); + await waitFor(() => + expect(screen.getByTestId('room-input-editor')).toHaveAttribute('data-editor-text', '') + ); + }); + + it('restores composed text when a scheduled send fails', async () => { + // Delayed events produce no local echo, so the composer is the only way back. + testState.sendDelayedMessage.mockRejectedValueOnce(new Error('schedule failed')); + render(); + fireEvent.click(screen.getByRole('button', { name: 'Compose text' })); + + fireEvent.click(sendButton()); + await waitFor(() => expect(testState.sendDelayedMessage).toHaveBeenCalledOnce()); + await waitFor(() => + expect(screen.getByTestId('room-input-editor')).toHaveAttribute( + 'data-editor-text', + 'retry me' + ) + ); + }); + + it('keeps text typed while a send is in flight', async () => { + const send = deferred<{ event_id: string }>(); + testState.matrix.sendMessage.mockReturnValue(send.promise); + render(); + fireEvent.click(screen.getByRole('button', { name: 'Compose text' })); + const submit = screen.getByRole('button', { name: 'Send your composed Message' }); + + fireEvent.click(submit); + fireEvent.click(screen.getByRole('button', { name: 'Compose updated text' })); + send.resolve({ event_id: '$event' }); + + await waitFor(() => + expect(screen.getByTestId('room-input-editor')).toHaveAttribute( + 'data-editor-text', + 'updated while sending' + ) + ); + }); + + it('blocks submission while file preprocessing is pending', async () => { + const preprocessing = deferred(); + const file = new File(['attachment'], 'attachment.txt', { type: 'text/plain' }); + testState.safeUploadFile.mockReturnValue(preprocessing.promise); + render(); + + void testState.handleFiles?.([file]); + await waitFor(() => expect(testState.safeUploadFile).toHaveBeenCalledOnce()); + fireEvent.click(screen.getByRole('button', { name: 'Compose text' })); + const submit = screen.getByRole('button', { name: 'Send your composed Message' }); + + expect(submit).toBeDisabled(); + fireEvent.click(submit); + expect(testState.matrix.sendMessage).not.toHaveBeenCalled(); + + preprocessing.resolve(file); + }); + + it('uses the queued Enter snapshot after a slow sticker send', async () => { + const stickerSend = deferred(); + testState.matrix.sendEvent.mockReturnValue(stickerSend.promise); + render(); + + fireEvent.click(screen.getByRole('button', { name: 'Select sticker' })); + await waitFor(() => expect(testState.matrix.sendEvent).toHaveBeenCalledOnce()); + fireEvent.click(screen.getByRole('button', { name: 'Compose text' })); + fireEvent.keyDown(screen.getByTestId('room-input-editor'), { key: 'Enter', code: 'Enter' }); + fireEvent.click(screen.getByRole('button', { name: 'Compose updated text' })); + + stickerSend.resolve({}); + await waitFor(() => expect(testState.matrix.sendMessage).toHaveBeenCalledOnce()); + expect(testState.matrix.sendMessage.mock.calls[0]?.[2]?.body).toBe('retry me'); + }); + + it('gives a claimed reply only to the slow sticker, not queued Enter', async () => { + const stickerSend = deferred(); + testState.matrix.sendEvent.mockReturnValue(stickerSend.promise); + render(); + + fireEvent.click(screen.getByRole('button', { name: 'Select sticker' })); + await waitFor(() => expect(testState.matrix.sendEvent).toHaveBeenCalledOnce()); + fireEvent.click(screen.getByRole('button', { name: 'Compose text' })); + fireEvent.keyDown(screen.getByTestId('room-input-editor'), { key: 'Enter', code: 'Enter' }); + + stickerSend.resolve({}); + await waitFor(() => expect(testState.matrix.sendMessage).toHaveBeenCalledOnce()); + expect(testState.matrix.sendEvent.mock.calls[0]?.[2]?.['m.relates_to']).toBeDefined(); + expect(testState.matrix.sendMessage.mock.calls[0]?.[2]?.['m.relates_to']).toBeUndefined(); + }); + + it('preserves a newer reply selected during a slow sticker send', async () => { + const stickerSend = deferred(); + testState.matrix.sendEvent.mockReturnValue(stickerSend.promise); + render(); + render(); + + fireEvent.click(screen.getByRole('button', { name: 'Select sticker' })); + await waitFor(() => expect(testState.matrix.sendEvent).toHaveBeenCalledOnce()); + fireEvent.click(screen.getByRole('button', { name: 'Select newer reply' })); + await waitFor(() => + expect(screen.getByTestId('reply-observer')).toHaveTextContent('$new-reply') + ); + + stickerSend.resolve({}); + await waitFor(() => expect(testState.matrix.sendEvent).toHaveBeenCalledOnce()); + expect(testState.matrix.sendEvent.mock.calls[0]?.[2]?.['m.relates_to']).toBeDefined(); + expect(screen.getByTestId('reply-observer')).toHaveTextContent('$new-reply'); + }); + + it('resets after a selection-only editor change', async () => { + const send = deferred<{ event_id: string }>(); + testState.matrix.sendMessage.mockReturnValue(send.promise); + render(); + fireEvent.click(screen.getByRole('button', { name: 'Compose text' })); + const submit = screen.getByRole('button', { name: 'Send your composed Message' }); + + fireEvent.click(submit); + fireEvent.input(screen.getByTestId('room-input-editor')); + send.resolve({ event_id: '$event' }); + + await waitFor(() => + expect(screen.getByTestId('room-input-editor')).toHaveAttribute('data-editor-text', '') + ); + }); + + it('keeps an updated attachment caption after the upload completes', async () => { + const upload = deferred<{ content_uri: string }>(); + const file = new File(['attachment'], 'attachment.txt', { type: 'text/plain' }); + testState.sendIndividualAttachmentAsCaption = true; + testState.pendingUploads = [{ status: 'loading', file, promise: upload.promise }]; + testState.matrix.sendMessage.mockResolvedValue({ event_id: '$event' }); + + render(); + fireEvent.click(screen.getByRole('button', { name: 'Prepare attachment' })); + fireEvent.click(screen.getByRole('button', { name: 'Compose text' })); + fireEvent.click(screen.getByRole('button', { name: 'Send your composed Message' })); + fireEvent.click(screen.getByRole('button', { name: 'Compose updated text' })); + + upload.resolve({ content_uri: 'mxc://example/attachment' }); + await waitFor(() => expect(testState.matrix.sendMessage).toHaveBeenCalledOnce()); + expect(testState.matrix.sendMessage.mock.calls[0]?.[2]?.body).toBe('retry me'); + expect(screen.getByTestId('room-input-editor')).toHaveAttribute( + 'data-editor-text', + 'updated while sending' + ); + }); + + it('finishes encryption after metadata replacement using the stable original file', async () => { + const encryption = deferred<{ file: File; originalFile: File; encInfo: object }>(); + const file = new File(['attachment'], 'attachment.txt', { type: 'text/plain' }); + testState.encrypted = true; + testState.encryptFile.mockReturnValue(encryption.promise); + + render(); + render(); + await act(async () => { + void testState.handleFiles?.([file]); + await Promise.resolve(); + }); + + await waitFor(() => expect(screen.getByTestId('upload-observer')).toHaveTextContent('true')); + fireEvent.click(screen.getByRole('button', { name: 'Update attachment metadata' })); + await act(async () => { + encryption.resolve({ + file: new File(['encrypted'], 'attachment.txt', { type: 'text/plain' }), + originalFile: file, + encInfo: {}, + }); + await encryption.promise; + }); + + await waitFor(() => expect(screen.getByTestId('upload-observer')).toHaveTextContent('false')); + expect(screen.getByTestId('upload-observer')).toHaveTextContent('"markedAsSpoiler":true'); + }); + + it('removes the current replaced item when encryption fails', async () => { + const encryption = deferred(); + const file = new File(['attachment'], 'attachment.txt', { type: 'text/plain' }); + testState.encrypted = true; + testState.encryptFile.mockReturnValue(encryption.promise); + + render(); + render(); + await act(async () => { + void testState.handleFiles?.([file]); + await Promise.resolve(); + }); + + await waitFor(() => expect(screen.getByTestId('upload-observer')).toHaveTextContent('true')); + fireEvent.click(screen.getByRole('button', { name: 'Update attachment metadata' })); + fireEvent.click(screen.getByRole('button', { name: 'Update attachment description' })); + await waitFor(() => + expect(screen.getByTestId('upload-observer')).toHaveTextContent('updated description') + ); + await act(async () => { + encryption.reject(new Error('encryption failed')); + await encryption.promise.catch(() => undefined); + }); + + await waitFor(() => expect(screen.getByTestId('upload-observer')).toHaveTextContent('[]')); + expect(screen.getByTestId('upload-observer')).not.toHaveTextContent('encrypting'); + }); + + it('uses the submitted editor snapshot for an attachment reply relation', async () => { + const upload = deferred<{ content_uri: string }>(); + const file = new File(['attachment'], 'attachment.txt', { type: 'text/plain' }); + testState.pendingUploads = [{ status: 'loading', file, promise: upload.promise }]; + + const seed = render(); + seed.unmount(); + render(); + fireEvent.click(screen.getByRole('button', { name: 'Prepare attachment' })); + fireEvent.click(screen.getByRole('button', { name: 'Send your composed Message' })); + fireEvent.click(screen.getByRole('button', { name: 'Compose updated text' })); + upload.resolve({ content_uri: 'mxc://example/attachment' }); + + await waitFor(() => expect(testState.matrix.sendMessage).toHaveBeenCalledOnce()); + expect(testState.matrix.sendMessage.mock.calls[0]?.[2]?.['m.relates_to']).toEqual( + expect.objectContaining({ 'm.in_reply_to': expect.anything() }) + ); + }); + + it('preserves the normal draft when an edited message input unmounts', async () => { + testState.isMobile = true; + testState.editingEvent = { + getId: () => '$original', + getContent: () => ({ body: 'original', msgtype: 'm.text' }), + }; + const seed = render(); + seed.unmount(); + const input = render(); + render(); + + await waitFor(() => expect(screen.getByTestId('room-input-editor')).toBeInTheDocument()); + input.unmount(); + + expect(screen.getByTestId('draft-observer')).toHaveTextContent('keep this draft'); + }); + + it('does not submit mobile edits before initialization, then sends the replacement', async () => { + testState.isMobile = true; + testState.editingEvent = { + getId: () => '$original', + getContent: () => ({ body: 'original', msgtype: 'm.text' }), + }; + const onCancelEdit = vi.fn(); + render(); + + expect(testState.matrix.sendMessage).not.toHaveBeenCalled(); + await waitFor(() => expect(screen.getByTestId('room-input-editor')).toBeInTheDocument()); + fireEvent.input(screen.getByTestId('room-input-editor')); + fireEvent.click(screen.getByRole('button', { name: 'Send your composed Message' })); + + await waitFor(() => expect(testState.matrix.sendMessage).toHaveBeenCalledOnce()); + expect(testState.matrix.sendMessage).toHaveBeenCalledWith( + room.roomId, + expect.objectContaining({ + body: '* original', + 'm.new_content': expect.objectContaining({ body: 'original' }), + 'm.relates_to': expect.anything(), + }) + ); + expect(onCancelEdit).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 7075276db..41fa5595c 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -20,9 +20,11 @@ import type { IEventRelation, RoomMessageEventContent, StickerEventContent, + TimelineEvents, } from '$types/matrix-sdk'; import { MatrixError } from '$types/matrix-sdk'; import { EventType, RelationType } from '$types/matrix-sdk'; +import { M_POLL_START } from 'matrix-js-sdk'; import { ReactEditor } from 'slate-react'; import { Editor, Point, Range, Transforms } from 'slate'; import type { RectCords } from 'folds'; @@ -101,7 +103,6 @@ import type { Upload, UploadSuccess } from '$state/upload'; import { UploadStatus, createUploadFamilyObserverAtom } from '$state/upload'; import { loadImageElementFromMediaUrl } from '$utils/dom'; import { isImageMimeType, safeUploadFile } from '$utils/mimeTypes'; -import { fulfilledPromiseSettledResult } from '$utils/common'; import { useSetting } from '$state/hooks/settings'; import type { EditorButtonId } from '$state/settings'; import { settingsAtom } from '$state/settings'; @@ -134,6 +135,7 @@ import { computeDelayMs, cancelDelayedEvent, } from '$utils/delayedEvents'; +import { roomScheduleCoordinator } from '$state/room/roomScheduleCoordinator'; import { timeHourMinute, timeDayMonthYear, daysToMs } from '$utils/time'; import { stopPropagation } from '$utils/keyboard'; @@ -147,7 +149,6 @@ import { getCurrentlyUsedPerMessageProfileForRoom, type PerMessageProfileMsc4461, setCurrentlyUsedPerMessageProfileIdForRoom, - stripPerMessageProfileFormattedBody, } from '$hooks/usePerMessageProfile'; import { Bell, @@ -200,7 +201,6 @@ import { buildGalleryContent, getGalleryItemContent, } from './msgContent'; -import { buildEditReplacement, buildOutgoingMessage } from './composerMessage'; import { getSendableKlipyMxcUrl } from '$utils/klipy'; import { CommandAutocomplete } from './CommandAutocomplete'; import type { @@ -212,6 +212,8 @@ import * as prefix from '$unstable/prefixes'; import { PollDialog } from './poll-modals'; import { useClientConfig } from '$hooks/useClientConfig'; import { PersistentPersonaPicker, type PersonaPickerTab } from './persona-picker/PersonaPicker.tsx'; +import { createComposerController, type ComposerController } from './composerController'; +import { buildEditReplacement, buildOutgoingMessage } from './composerMessage'; const LocationDialog = lazy(() => import('./location-modal').then((module) => ({ default: module.LocationDialog })) @@ -276,6 +278,28 @@ interface ReplyEventContent { const createUploadItemKey = () => globalThis.crypto.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(16).slice(2)}`; +interface ReplyClaim { + epoch: number; + snapshot: IReplyDraft; + silentReply: boolean; +} + +interface Submission { + children: Editor['children']; + epoch: number; + replyClaim: ReplyClaim | undefined; +} + +interface SendContentsOptions { + contents: IContent[]; + submission: Submission; + isLive: () => boolean; + includeReplyWithText?: boolean; + /** Defaults to `m.room.message`. Polls and other non-message events set this. */ + eventType?: keyof TimelineEvents; + onContentSent?: (index: number) => void | Promise; +} + interface RoomInputProps { editor: Editor; fileDropContainerRef: RefObject; @@ -362,13 +386,28 @@ export const RoomInput = forwardRef( const [msgDraft, setMsgDraft] = useAtom(roomIdToMsgDraftAtomFamily(draftKey)); const [replyDraft, setReplyDraft] = useAtom(roomIdToReplyDraftAtomFamily(draftKey)); + const replyDraftRef = useRef(replyDraft); + replyDraftRef.current = replyDraft; const [uploadBoard, setUploadBoard] = useState(true); const [uploadSending, setUploadSending] = useState(false); const [uploadBusy, setUploadBusy] = useState(false); + const [isSending, setIsSending] = useState(false); + const [ingestingFiles, setIngestingFiles] = useState(false); + const fileIngestionCountRef = useRef(0); + const composerControllerRef = useRef(); + composerControllerRef.current ??= createComposerController(); + // Bumped when this composer goes away, so async work started for a previous + // room/thread stops writing to the current one. + const draftEpochRef = useRef(0); + const mountedRef = useRef(false); const [selectedFiles, setSelectedFiles] = useAtom(roomIdToUploadItemsAtomFamily(draftKey)); + const selectedFilesRef = useRef(selectedFiles); + selectedFilesRef.current = selectedFiles; + const uploadItemOverridesRef = useRef(new Map>()); + const removedUploadFilesRef = useRef(new WeakSet()); const isEncrypting = selectedFiles.some((f) => f.encrypting); - const sendBusy = uploadSending || isEncrypting || uploadBusy; + const sendBusy = isSending || uploadSending || isEncrypting || uploadBusy || ingestingFiles; const uploadFamilyObserverAtom = createUploadFamilyObserverAtom( roomUploadAtomFamily, selectedFiles.map((f) => f.file) @@ -377,12 +416,27 @@ export const RoomInput = forwardRef( const longPressTimer = useRef | null>(null); const isLongPress = useRef(false); const suppressBlurRefocusRef = useRef(false); + const editorRafIdsRef = useRef(new Set()); + const scheduleEditorRaf = useCallback((callback: () => void) => { + const rafId = requestAnimationFrame(() => { + editorRafIdsRef.current.delete(rafId); + callback(); + }); + editorRafIdsRef.current.add(rafId); + }, []); + useEffect( + () => () => { + editorRafIdsRef.current.forEach((rafId) => cancelAnimationFrame(rafId)); + editorRafIdsRef.current.clear(); + }, + [] + ); const suppressEditorRefocus = useCallback(() => { suppressBlurRefocusRef.current = true; - requestAnimationFrame(() => { + scheduleEditorRaf(() => { suppressBlurRefocusRef.current = false; }); - }, []); + }, [scheduleEditorRaf]); const imagePackRooms: Room[] = useImagePackRooms(roomId, roomToParents); @@ -390,11 +444,26 @@ export const RoomInput = forwardRef( const audioRecorderRef = useRef(null); const micHoldStartRef = useRef(0); const micHoldReleaseRef = useRef<(() => void) | null>(null); + const recorderActionRef = useRef<'stop' | 'cancel'>(); + const recorderTimerRef = useRef>(); + const scheduleRecorderTimer = useCallback((callback: () => void) => { + recorderTimerRef.current = setTimeout(() => { + recorderTimerRef.current = undefined; + callback(); + }, 50); + }, []); + const requestRecorderStop = useCallback(() => { + if (recorderActionRef.current) return; + recorderActionRef.current = 'stop'; + audioRecorderRef.current?.stop(); + }, []); const HOLD_THRESHOLD_MS = 400; useEffect( () => () => { micHoldReleaseRef.current?.(); + clearTimeout(recorderTimerRef.current); + recorderActionRef.current = undefined; }, [] ); @@ -417,6 +486,17 @@ export const RoomInput = forwardRef( const sendTypingStatus = useTypingStatusUpdater(mx, roomId, { disabled: !!threadRootId }); + useEffect(() => { + mountedRef.current = true; + const controller = (composerControllerRef.current ??= createComposerController()); + return () => { + mountedRef.current = false; + draftEpochRef.current += 1; + controller.dispose(); + composerControllerRef.current = undefined; + }; + }, [draftKey]); + const [inputKey, setInputKey] = useState(0); const getUploadItemKey = useCallback((fileItem: TUploadItem): string => { const existingKey = uploadItemKeysRef.current.get(fileItem.originalFile); @@ -429,64 +509,98 @@ export const RoomInput = forwardRef( const handleFiles = useCallback( async (files: File[], audioMeta?: { waveform: number[]; audioDuration: number }) => { - setUploadBoard(true); - const safeFiles = await Promise.all(files.map(safeUploadFile)); - // Eager-read to avoid Android content URI expiry after SAF picker - const blobbedFiles = isMobileOrTablet() - ? await Promise.all( - safeFiles.map(async (f) => { - try { - const buf = await f.arrayBuffer(); - return new File([buf], f.name, { type: f.type, lastModified: f.lastModified }); - } catch { - return f; - } - }) - ) - : safeFiles; - const makeMetadata = () => ({ - markedAsSpoiler: false, - waveform: audioMeta?.waveform, - audioDuration: audioMeta?.audioDuration, - }); + const epoch = draftEpochRef.current; + fileIngestionCountRef.current += 1; + setIngestingFiles(true); + try { + setUploadBoard(true); + const safeFiles = await Promise.all(files.map(safeUploadFile)); + if (epoch !== draftEpochRef.current || !mountedRef.current) return; - if (room.hasEncryptionStateEvent()) { - const placeholders: TUploadItem[] = blobbedFiles.map((f) => ({ - file: f, - originalFile: f, - encInfo: undefined, - encrypting: true, - metadata: makeMetadata(), - })); - setSelectedFiles({ type: 'PUT', item: placeholders }); - placeholders.forEach((placeholder) => { - encryptFile(placeholder.originalFile) - .then((ef) => - setSelectedFiles({ - type: 'REPLACE', - item: placeholder, - replacement: { ...ef, encrypting: false, metadata: placeholder.metadata }, + // Eager-read to avoid Android content URI expiry after SAF picker + const blobbedFiles = isMobileOrTablet() + ? await Promise.all( + safeFiles.map(async (f) => { + try { + const buf = await f.arrayBuffer(); + return new File([buf], f.name, { type: f.type, lastModified: f.lastModified }); + } catch { + return f; + } }) ) - .catch((encryptError: unknown) => { - log.warn('Failed to encrypt file for upload:', encryptError); - setSelectedFiles({ type: 'DELETE', item: placeholder }); - }); - }); - return; - } + : safeFiles; + if (epoch !== draftEpochRef.current || !mountedRef.current) return; + blobbedFiles.forEach((file) => removedUploadFilesRef.current.delete(file)); - setSelectedFiles({ - type: 'PUT', - item: blobbedFiles.map((f) => ({ - file: f, - originalFile: f, - encInfo: undefined, - metadata: makeMetadata(), - })), - }); + const makeMetadata = () => ({ + markedAsSpoiler: false, + waveform: audioMeta?.waveform, + audioDuration: audioMeta?.audioDuration, + }); + + if (room.hasEncryptionStateEvent()) { + const placeholders: TUploadItem[] = blobbedFiles.map((f) => ({ + file: f, + originalFile: f, + encInfo: undefined, + encrypting: true, + metadata: makeMetadata(), + })); + setSelectedFiles({ type: 'PUT', item: placeholders }); + await Promise.all( + placeholders.map(async (placeholder) => { + try { + const encryptedFile = await encryptFile(placeholder.originalFile); + if (epoch !== draftEpochRef.current || !mountedRef.current) return; + if (removedUploadFilesRef.current.has(placeholder.originalFile)) return; + const currentItem = selectedFilesRef.current.find( + (item) => item.originalFile === placeholder.originalFile + ); + if (!currentItem) return; + const overrides = uploadItemOverridesRef.current.get(placeholder.originalFile); + setSelectedFiles({ + type: 'REPLACE', + item: currentItem, + replacement: { + ...currentItem, + ...encryptedFile, + ...overrides, + encrypting: false, + metadata: overrides?.metadata ?? currentItem.metadata, + }, + }); + } catch (encryptError: unknown) { + log.warn('Failed to encrypt file for upload:', encryptError); + if (epoch === draftEpochRef.current && mountedRef.current) { + const currentItem = selectedFilesRef.current.find( + (item) => item.originalFile === placeholder.originalFile + ); + if (currentItem) setSelectedFiles({ type: 'DELETE', item: currentItem }); + } + } + }) + ); + return; + } + + setSelectedFiles({ + type: 'PUT', + item: blobbedFiles.map((f) => ({ + file: f, + originalFile: f, + encInfo: undefined, + metadata: makeMetadata(), + })), + }); + } catch (error: unknown) { + log.warn('Failed to prepare files for upload:', error); + } finally { + fileIngestionCountRef.current -= 1; + if (fileIngestionCountRef.current === 0 && mountedRef.current) setIngestingFiles(false); + } }, - [setSelectedFiles, room] + [room, setSelectedFiles] ); const pickFile = useFilePicker(handleFiles, true); const handlePaste = useFilePasteHandler(handleFiles); @@ -538,6 +652,26 @@ export const RoomInput = forwardRef( const [scheduleMenuAnchor, setScheduleMenuAnchor] = useState(); const [showSchedulePicker, setShowSchedulePicker] = useState(false); const [silentReply, setSilentReply] = useState(!mentionInReplies); + // Clears the reply draft up front so it cannot be re-sent, keeping a snapshot to + // restore if the send never lands. + const claimReply = useCallback((): ReplyClaim | undefined => { + const currentReply = replyDraftRef.current; + if (!currentReply) return undefined; + + const epoch = draftEpochRef.current; + replyDraftRef.current = replyDraftBase; + setReplyDraft(replyDraftBase); + return { epoch, snapshot: structuredClone(currentReply), silentReply }; + }, [replyDraftBase, setReplyDraft, silentReply]); + const restoreReplyClaim = useCallback( + (claim: ReplyClaim | undefined) => { + if (!claim || claim.epoch !== draftEpochRef.current) return; + if (replyDraftRef.current !== replyDraftBase) return; + replyDraftRef.current = claim.snapshot; + setReplyDraft(claim.snapshot); + }, + [replyDraftBase, setReplyDraft] + ); const [hour24Clock] = useSetting(settingsAtom, 'hour24Clock'); const setServerMaxDelayMs = useSetAtom(serverMaxDelayMsAtom); const [sendError, setSendError] = useState(); @@ -599,9 +733,13 @@ export const RoomInput = forwardRef( Transforms.insertFragment(editor, msgDraft); }, [editor, msgDraft]); + const editingStateRef = useRef(false); + const preEditDraftRef = useRef(); useEffect( () => () => { - if (isEmptyEditor(editor)) { + if (editingStateRef.current) { + setMsgDraft(structuredClone(preEditDraftRef.current ?? [])); + } else if (isEmptyEditor(editor)) { setMsgDraft([]); } else { const parsedDraft = structuredClone(editor.children); @@ -614,6 +752,9 @@ export const RoomInput = forwardRef( ); const editingEvent = editId ? room.findEventById(editId) : undefined; + const isMobile = isMobileOrTablet(); + const [initializedEditId, setInitializedEditId] = useState(); + const isEditInitializing = isMobile && editId !== undefined && initializedEditId !== editId; const getEditingContent = useCallback( (event: MatrixEvent): IContent => { const eventId = event.getId(); @@ -628,15 +769,23 @@ export const RoomInput = forwardRef( ); const prevEditingEventId = useRef(); - const preEditDraftRef = useRef(); useEffect(() => { - if (!isMobileOrTablet()) { + if (!isMobile) { + editingStateRef.current = false; prevEditingEventId.current = undefined; preEditDraftRef.current = undefined; + setInitializedEditId(undefined); + return; + } + + if (editId !== undefined && !editingEvent) { + setInitializedEditId(undefined); + onCancelEdit?.(); return; } if (editingEvent) { + editingStateRef.current = true; if (editingEvent.getId() !== prevEditingEventId.current) { if (!prevEditingEventId.current) { preEditDraftRef.current = structuredClone(editor.children); @@ -664,7 +813,7 @@ export const RoomInput = forwardRef( } } const editableHtml = pmpDisplayname - ? stripPerMessageProfileFormattedBody(customHtml ?? '') + ? customHtml?.replace(/^]*>.*?<\/strong>/, '') : customHtml; const mentionOptions = { @@ -686,7 +835,7 @@ export const RoomInput = forwardRef( resetEditorHistory(editor); Transforms.insertFragment(editor, initialValue); - requestAnimationFrame(() => { + scheduleEditorRaf(() => { try { ReactEditor.focus(editor); moveCursor(editor); @@ -695,7 +844,9 @@ export const RoomInput = forwardRef( } }); } + setInitializedEditId(editId); } else { + editingStateRef.current = false; const previousDraft = preEditDraftRef.current; if (prevEditingEventId.current && previousDraft) { resetEditor(editor); @@ -707,7 +858,7 @@ export const RoomInput = forwardRef( prevEditingEventId.current && (!replyDraft?.eventId || replyDraft.eventId === threadRootId) ) { - requestAnimationFrame(() => { + scheduleEditorRaf(() => { try { const domNode = ReactEditor.toDOMNode(editor, editor); domNode.blur(); @@ -718,8 +869,10 @@ export const RoomInput = forwardRef( }); } prevEditingEventId.current = undefined; + setInitializedEditId(undefined); } }, [ + editId, editingEvent, editor, getEditingContent, @@ -728,6 +881,10 @@ export const RoomInput = forwardRef( room, replyDraft?.eventId, threadRootId, + isMobile, + setInitializedEditId, + onCancelEdit, + scheduleEditorRaf, ]); useEffect(() => { @@ -760,7 +917,7 @@ export const RoomInput = forwardRef( prevReplyEventId.current = newId; if (newId && newId !== threadRootId) { - requestAnimationFrame(() => { + scheduleEditorRaf(() => { try { ReactEditor.focus(editor); moveCursor(editor); @@ -769,7 +926,7 @@ export const RoomInput = forwardRef( } }); } else if (!newId && prevId && prevId !== threadRootId && !editId) { - requestAnimationFrame(() => { + scheduleEditorRaf(() => { try { const domNode = ReactEditor.toDOMNode(editor, editor); domNode.blur(); @@ -780,10 +937,14 @@ export const RoomInput = forwardRef( }); } } - }, [replyDraft?.eventId, threadRootId, editId, editor]); + }, [replyDraft?.eventId, threadRootId, editId, editor, scheduleEditorRaf]); const handleFileMetadata = useCallback( (fileItem: TUploadItem, metadata: TUploadMetadata) => { + uploadItemOverridesRef.current.set(fileItem.originalFile, { + ...uploadItemOverridesRef.current.get(fileItem.originalFile), + metadata, + }); setSelectedFiles({ type: 'REPLACE', item: fileItem, @@ -794,6 +955,11 @@ export const RoomInput = forwardRef( ); const setDesc = useCallback( (fileItem: TUploadItem, body: string, formatted_body: string) => { + uploadItemOverridesRef.current.set(fileItem.originalFile, { + ...uploadItemOverridesRef.current.get(fileItem.originalFile), + body, + formatted_body, + }); setSelectedFiles({ type: 'REPLACE', item: fileItem, @@ -809,13 +975,18 @@ export const RoomInput = forwardRef( type: 'DELETE', item: selectedFiles.filter((f) => uploads.find((u) => u === f.file)), }); - uploads.forEach((u) => roomUploadAtomFamily.remove(u)); + uploads.forEach((u) => { + removedUploadFilesRef.current.add(u); + roomUploadAtomFamily.remove(u); + uploadItemOverridesRef.current.delete(u); + }); }, [setSelectedFiles, selectedFiles] ); const handleAudioRecordingComplete = useCallback( (payload: AudioRecordingCompletePayload) => { + recorderActionRef.current = undefined; const extension = getSupportedAudioExtension(payload.audioCodec); const file = new File( [payload.audioBlob], @@ -836,7 +1007,10 @@ export const RoomInput = forwardRef( const audioRecorder = showAudioRecorder ? ( setShowAudioRecorder(false)} + onRequestClose={() => { + recorderActionRef.current = undefined; + setShowAudioRecorder(false); + }} onRecordingComplete={handleAudioRecordingComplete} onAudioLengthUpdate={() => {}} onWaveformUpdate={() => {}} @@ -852,8 +1026,53 @@ export const RoomInput = forwardRef( handleRemoveUpload(uploads.map((upload) => upload.file)); }; - const handleSendContents = async (contents: IContent[]) => { - const plainText = toPlainText(editor.children).trim(); + // Clears the composer immediately so a slow send cannot be edited or submitted + // twice; anything that fails without a local echo is restored afterwards. + const takeSubmission = useCallback( + ({ clearEditor = true, claimReplyDraft = true } = {}): Submission => { + const children = structuredClone(editor.children); + const submission: Submission = { + children, + epoch: draftEpochRef.current, + replyClaim: claimReplyDraft ? claimReply() : undefined, + }; + if (clearEditor) { + resetEditor(editor); + resetEditorHistory(editor); + setInputKey((prev) => prev + 1); + imagePacksUsedRef.current.clear(); + sendTypingStatus(false); + } + return submission; + }, + [claimReply, editor, sendTypingStatus] + ); + const restoreSubmission = useCallback( + (submission: Submission) => { + restoreReplyClaim(submission.replyClaim); + if ( + !mountedRef.current || + submission.epoch !== draftEpochRef.current || + !isEmptyEditor(editor) + ) { + return; + } + Transforms.insertFragment(editor, submission.children); + }, + [editor, restoreReplyClaim] + ); + + const handleSendContents = async ({ + contents, + submission, + isLive, + includeReplyWithText = false, + eventType, + onContentSent, + }: SendContentsOptions) => { + const plainText = toPlainText(submission.children).trim(); + const submittedReplyDraft = submission.replyClaim?.snapshot; + const submittedSilentReply = submission.replyClaim?.silentReply ?? silentReply; /** * the currently with the room associated per-message profile, if any, so that it can be included in the message content when sending. @@ -874,39 +1093,61 @@ export const RoomInput = forwardRef( }); } - if (contents.length > 0) { - const replyContent = - plainText?.length === 0 ? getReplyContent(replyDraft, room) : undefined; - if (replyContent) { - contents[0]!['m.relates_to'] = replyContent; - if (!silentReply && replyDraft) - contents[0]!['m.mentions'] = { ['user_ids']: [replyDraft.userId] }; - setReplyDraft(replyDraftBase); - } + const replyContent = + submittedReplyDraft && (includeReplyWithText || plainText.length === 0) + ? getReplyContent(submittedReplyDraft, room) + : undefined; + if (replyContent && contents.length > 0) { + contents[0]!['m.relates_to'] = replyContent; + if (!submittedSilentReply && submittedReplyDraft) + contents[0]!['m.mentions'] = { ['user_ids']: [submittedReplyDraft.userId] }; } - const invalidate = () => - queryClient.invalidateQueries({ queryKey: ['delayedEvents', roomId] }); + const invalidate = () => { + if (isLive()) queryClient.invalidateQueries({ queryKey: ['delayedEvents', roomId] }); + }; + const handleContentSent = async (index: number) => { + if (onContentSent && isLive()) await onContentSent(index); + }; if (scheduledTime) { try { const delayMs = computeDelayMs(scheduledTime); - if (editingScheduledDelayId) { - await cancelDelayedEvent(mx, editingScheduledDelayId); - } + await roomScheduleCoordinator.run(roomId, async () => { + if (editingScheduledDelayId) { + await cancelDelayedEvent(mx, editingScheduledDelayId); + if (isLive()) setEditingScheduledDelayId(null); + } - await Promise.all( - contents.map((content) => { - if (isEncrypted) { - return sendDelayedMessageE2EE(mx, roomId, room, content, delayMs); - } - return sendDelayedMessage(mx, roomId, content, delayMs); - }) - ); + const sendResults = await Promise.allSettled( + contents.map(async (content, index) => { + const response = isEncrypted + ? await sendDelayedMessageE2EE( + mx, + roomId, + room, + content, + delayMs, + null, + eventType + ) + : await sendDelayedMessage(mx, roomId, content, delayMs, null, eventType); + await handleContentSent(index); + return response; + }) + ); + const failedSend = sendResults.find( + (result): result is PromiseRejectedResult => result.status === 'rejected' + ); + if (failedSend) throw failedSend.reason; + }); invalidate(); - setEditingScheduledDelayId(null); - setScheduledTime(null); + if (isLive()) { + setEditingScheduledDelayId(null); + setScheduledTime(null); + } + return contents.length > 0; } catch (error) { debugLog.error('message', 'Failed to schedule message', { roomId, @@ -916,40 +1157,65 @@ export const RoomInput = forwardRef( throw error; } } else { - if (editingScheduledDelayId) { - try { - await cancelDelayedEvent(mx, editingScheduledDelayId); - invalidate(); - setEditingScheduledDelayId(null); - } catch { - debugLog.error('message', 'Failed to cancel scheduled event before immediate send', { - roomId, - }); - } - } - - await Promise.all( - contents.map((content) => - mx - .sendMessage(roomId, threadRootId ?? null, content as RoomMessageEventContent) - .then((res: { event_id: string }) => { + const sendImmediateContents = async () => + Promise.allSettled( + contents.map(async (content, index) => { + try { + const res = eventType + ? await mx.sendEvent( + roomId, + threadRootId ?? null, + eventType, + content as TimelineEvents[keyof TimelineEvents] + ) + : await mx.sendMessage( + roomId, + threadRootId ?? null, + content as RoomMessageEventContent + ); + await handleContentSent(index); debugLog.info('message', 'Message sent', { roomId, eventId: res.event_id, msgtype: content.msgtype, }); return res; - }) - .catch((error: unknown) => { + } catch (error: unknown) { debugLog.error('message', 'Failed to send message', { roomId, error: error instanceof Error ? error.message : String(error), }); log.error('failed to send message', { roomId }, error); throw error; - }) - ) + } + }) + ); + let sendResults: PromiseSettledResult[] = []; + if (editingScheduledDelayId) { + let cancellationFailed = false; + await roomScheduleCoordinator.run(roomId, async () => { + try { + await cancelDelayedEvent(mx, editingScheduledDelayId); + invalidate(); + if (isLive()) setEditingScheduledDelayId(null); + } catch { + cancellationFailed = true; + debugLog.error('message', 'Failed to cancel scheduled event before immediate send', { + roomId, + }); + return; + } + sendResults = await sendImmediateContents(); + }); + if (cancellationFailed) sendResults = await sendImmediateContents(); + } else { + sendResults = await sendImmediateContents(); + } + const failedSend = sendResults.find( + (result): result is PromiseRejectedResult => result.status === 'rejected' ); + if (failedSend) throw failedSend.reason; + return contents.length > 0; } }; @@ -969,11 +1235,17 @@ export const RoomInput = forwardRef( return getFileMsgContent(fileItem, upload.mxc); }; - const handleSendUpload = async (uploads: Upload[]) => { - const plainText = toPlainText(editor.children).trim(); + // Resolves true when the composer text went out as an attachment caption, meaning + // the caller must not send it again. + const handleSendUpload = async ( + uploads: Upload[], + submission: Submission, + isLive: () => boolean + ): Promise => { + const plainText = toPlainText(submission.children).trim(); const caption = plainText.length > 0 ? plainText : undefined; let customHtml = trimCustomHtml( - toMatrixCustomHTML(editor.children, { + toMatrixCustomHTML(submission.children, { stripNickname: true, room, }) @@ -981,26 +1253,24 @@ export const RoomInput = forwardRef( const formattedCaption = caption && !customHtmlEqualsPlainText(customHtml, plainText) ? customHtml : undefined; - const resolved = fulfilledPromiseSettledResult( - await Promise.allSettled( - uploads.map(async (upload): Promise => { - if (upload.status === UploadStatus.Success) return upload; - if (upload.status === UploadStatus.Loading) { - const response = await upload.promise; - if (!response.content_uri) throw new Error('Upload failed'); - return { status: UploadStatus.Success, file: upload.file, mxc: response.content_uri }; - } - throw new Error('Upload not ready'); - }) - ) + if (uploads.length !== selectedFiles.length) throw new Error('Upload not ready'); + const resolved = await Promise.all( + uploads.map(async (upload): Promise => { + if (upload.status === UploadStatus.Success) return upload; + if (upload.status === UploadStatus.Loading) { + const response = await upload.promise; + if (!response.content_uri) throw new Error('Upload failed'); + return { status: UploadStatus.Success, file: upload.file, mxc: response.content_uri }; + } + throw new Error('Upload not ready'); + }) ); - if (resolved.length === 0) return; + if (resolved.length === 0) throw new Error('Upload not ready'); - if (resolved.length == 1 && sendIndividualAttachmentAsCaption) { + if (selectedFiles.length == 1 && sendIndividualAttachmentAsCaption) { const upload = resolved[0]; if (!upload) throw new Error('Broken upload'); let content = await uploadToContent(upload); - handleCancelUpload(resolved); content.body = caption ?? ''; content.formatted_body = undefined; @@ -1010,30 +1280,70 @@ export const RoomInput = forwardRef( content.formatted_body = formattedCaption; } - await handleSendContents([content]); - return; + await handleSendContents({ + contents: [content], + submission, + isLive, + includeReplyWithText: true, + }); + if (isLive()) handleCancelUpload(resolved); + return true; } - if (resolved.length >= 2 && enableMediaGalleries) { + if (selectedFiles.length >= 2 && enableMediaGalleries) { const itemsPromises = resolved.map(async (upload) => { const fileItem = selectedFiles.find((f) => f.file === upload.file); if (!fileItem) throw new Error('Broken upload'); return getGalleryItemContent(mx, fileItem, upload.mxc); }); - handleCancelUpload(resolved); - const items = fulfilledPromiseSettledResult(await Promise.allSettled(itemsPromises)); - - if (items.length === 0) return; + const items = await Promise.all(itemsPromises); const galleryContent = buildGalleryContent(items, caption, formattedCaption); - await handleSendContents([galleryContent]); - return; + await handleSendContents({ + contents: [galleryContent], + submission, + isLive, + includeReplyWithText: true, + }); + if (isLive()) handleCancelUpload(resolved); + return true; } - const contentsPromises = resolved.map(uploadToContent); - handleCancelUpload(resolved); - const contents = fulfilledPromiseSettledResult(await Promise.allSettled(contentsPromises)); + const contents = await Promise.all(resolved.map(uploadToContent)); - await handleSendContents(contents); + await handleSendContents({ + contents, + submission, + isLive, + onContentSent: (index) => { + const upload = resolved[index]; + if (upload) handleCancelUpload([upload]); + }, + }); + return false; + }; + // `submit` is memoized but this closure is not. + const handleSendUploadRef = useRef(handleSendUpload); + handleSendUploadRef.current = handleSendUpload; + + const handleDialogSendContent = async ( + content: IContent, + eventType?: keyof TimelineEvents + ): Promise => { + const submission = takeSubmission({ clearEditor: false }); + await composerControllerRef.current?.enqueue(async (isLive) => { + try { + await handleSendContents({ + contents: [content], + submission, + isLive, + includeReplyWithText: true, + eventType, + }); + } catch (error) { + restoreReplyClaim(submission.replyClaim); + throw error; + } + }); }; const handleCloseAutocomplete = useCallback(() => { @@ -1075,243 +1385,284 @@ export const RoomInput = forwardRef( [editor, handleCloseAutocomplete, mx, room, sendTypingStatus] ); - const submit = useCallback(async () => { - if (editingEvent && isMobileOrTablet()) { - const content = buildEditReplacement(editor.children, { - mx, - room, - roomId, - editingEvent, - currentContent: getEditingContent(editingEvent), - pmpNoFallback, - }); - if (!content) { - onCancelEdit?.(); + const executeSubmit = useCallback( + async (submission: Submission, isLive: () => boolean) => { + if ( + fileIngestionCountRef.current > 0 || + isEditInitializing || + (isMobile && editId !== undefined && !editingEvent) + ) { + restoreSubmission(submission); return; } - await mx.sendMessage(roomId, content as RoomMessageEventContent); - onCancelEdit?.(); - sendTypingStatus(false); - return; - } + setIsSending(true); + const submittedReplyDraft = submission.replyClaim?.snapshot; + const submittedSilentReply = submission.replyClaim?.silentReply ?? silentReply; + try { + if (editingEvent && isMobile) { + const content = buildEditReplacement(submission.children, { + mx, + room, + roomId, + editingEvent, + currentContent: getEditingContent(editingEvent), + pmpNoFallback, + }); + if (!content) { + if (isLive()) onCancelEdit?.(); + return; + } + await mx.sendMessage(roomId, content as RoomMessageEventContent); + if (isLive()) { + onCancelEdit?.(); + sendTypingStatus(false); + } + return; + } - if (selectedFiles.some((f) => f.encrypting)) return; - uploadBoardHandlers.current?.handleSend(); - if ( - (selectedFiles.length >= 2 && enableMediaGalleries) || - (selectedFiles.length == 1 && sendIndividualAttachmentAsCaption) - ) { - resetEditor(editor); - resetEditorHistory(editor); - sendTypingStatus(false); - return; - } + if (selectedFiles.some((f) => f.encrypting)) { + restoreSubmission(submission); + return; + } + if (selectedFiles.length > 0) { + const uploads = uploadBoardHandlers.current?.getSendableUploads() ?? []; + const sendUpload = handleSendUploadRef.current; + setUploadSending(true); + try { + if (await sendUpload(uploads, submission, isLive)) return; + } catch (error: unknown) { + log.error('failed to send attachments', { roomId }, error); + if (isLive()) { + setSendError('Failed to send attachments. Please try again.'); + } + restoreSubmission(submission); + return; + } finally { + if (isLive()) setUploadSending(false); + } + } - const outgoing = await buildOutgoingMessage(editor.children, { - mx, - room, - roomId, - nicknames, + const outgoing = await buildOutgoingMessage(submission.children, { + mx, + room, + roomId, + nicknames, + replyEvent, + replyDraft: submittedReplyDraft, + silentReply: submittedSilentReply, + settingsLinkBaseUrl, + canSendReaction, + pkCompatEnable, + pmpProxyingEnable, + pmpLatchingEnable, + pmpNoFallback, + latchedPersona, + isPKCommand: (text) => PKitCommandMessageHandler.isPKCommand(text), + pluralkitProxyMessageHandler, + imagePacksUsed: imagePacksUsedRef.current, + }); + + if (outgoing.kind === 'empty') return; + if (outgoing.kind === 'quickReact') { + handleQuickReact(outgoing.key); + return; + } + if (outgoing.kind === 'pkCommand') { + await pluralkitCmdMessageHandler.handleMessage(outgoing.plainText); + return; + } + if (outgoing.kind === 'gifSearch') { + setInitialGifSearch(outgoing.query); + setEmojiBoardTab(EmojiBoardTab.Gif); + return; + } + if (outgoing.kind === 'command') { + const { command, plainText, customHtml } = outgoing; + if (command === Command.Poll) setShowPollPicker(true); + else if (command === Command.Location && plainText.trim().length === 0) + setShowLocationPicker(true); + else commands[command as Command]?.exe(plainText, customHtml); + return; + } + + const { content } = outgoing; + if (outgoing.latchPersona) { + await setCurrentlyUsedPerMessageProfileIdForRoom(mx, roomId, outgoing.latchPersona.id); + if (isLive()) setLatchedPersona(outgoing.latchPersona); + } + if (submittedReplyDraft) { + content['m.relates_to'] = getReplyContent(submittedReplyDraft, room); + } + const invalidate = () => { + if (isLive()) { + queryClient.invalidateQueries({ queryKey: ['delayedEvents', roomId] }); + } + }; + + if (scheduledTime) { + try { + const delayMs = computeDelayMs(scheduledTime); + await roomScheduleCoordinator.run(roomId, async () => { + if (editingScheduledDelayId) { + await cancelDelayedEvent(mx, editingScheduledDelayId); + if (isLive()) setEditingScheduledDelayId(null); + } + if (isEncrypted) { + await sendDelayedMessageE2EE(mx, roomId, room, content, delayMs); + } else { + await sendDelayedMessage(mx, roomId, content as RoomMessageEventContent, delayMs); + } + }); + invalidate(); + if (isLive()) { + setSendError(undefined); + setEditingScheduledDelayId(null); + setScheduledTime(null); + } + } catch (e: unknown) { + // A scheduled send leaves no local echo, so hand the message back. + restoreSubmission(submission); + if (!isLive()) return; + if ( + e instanceof MatrixError && + (e.errcode === ErrorCode.M_MAX_DELAY_EXCEEDED || + e.data?.['org.matrix.msc4140.errcode'] === 'M_MAX_DELAY_EXCEEDED') + ) { + const maxDelay = + (e.data as { max_delay?: number })?.max_delay ?? + e.data?.['org.matrix.msc4140.max_delay']; + if (typeof maxDelay === 'number') setServerMaxDelayMs(maxDelay); + const maxDelayDays = maxDelay / daysToMs(1); + setSendError( + `Scheduled time exceeds the maximum delay allowed by this server. Please choose an earlier time. The Maximum Delay is of ${maxDelayDays} day${maxDelayDays > 1 ? 's' : ''}.` + ); + } else { + setSendError('Failed to schedule message. Please try again.'); + } + } + } else if (editingScheduledDelayId) { + const scheduledDelayId = editingScheduledDelayId; + try { + await roomScheduleCoordinator.run(roomId, async () => { + await cancelDelayedEvent(mx, scheduledDelayId); + if (isLive()) setEditingScheduledDelayId(null); + debugLog.info('message', 'Sending message after cancelling scheduled event', { + roomId, + scheduledDelayId, + }); + const res = await mx.sendMessage( + roomId, + threadRootId ?? null, + content as RoomMessageEventContent + ); + debugLog.info('message', 'Message sent successfully', { + roomId, + eventId: res.event_id, + }); + }); + invalidate(); + } catch (error) { + debugLog.error('message', 'Failed to send message after cancelling scheduled event', { + roomId, + error: error instanceof Error ? error.message : String(error), + }); + // The scheduled copy may still exist, so don't drop the user's text. + restoreSubmission(submission); + if (isLive()) setSendError('Failed to reschedule message. Please try again.'); + } + } else { + const msgSendStart = performance.now(); + debugLog.info('message', 'Sending message', { + roomId, + msgtype: content.msgtype, + }); + try { + const res = await Sentry.startSpan( + { + name: 'message.send', + op: 'matrix.message', + attributes: { encrypted: String(isEncrypted) }, + }, + () => + mx.sendMessage(roomId, threadRootId ?? null, content as RoomMessageEventContent) + ); + 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); + // The failed send stays in the timeline as a local echo the user can retry, + // so the composer is intentionally left empty here. + } + } + } finally { + if (isLive()) setIsSending(false); + } + }, + [ replyEvent, - replyDraft, - silentReply, - settingsLinkBaseUrl, + mx, + roomId, canSendReaction, pkCompatEnable, + silentReply, pmpProxyingEnable, + pluralkitProxyMessageHandler, + scheduledTime, + editingScheduledDelayId, + nicknames, + room, + handleQuickReact, + pluralkitCmdMessageHandler, + commands, + sendTypingStatus, + queryClient, + threadRootId, + settingsLinkBaseUrl, + isEncrypted, + setEditingScheduledDelayId, + setScheduledTime, + setServerMaxDelayMs, + selectedFiles, + editingEvent, + getEditingContent, + onCancelEdit, + restoreSubmission, + isMobile, + editId, + isEditInitializing, pmpLatchingEnable, pmpNoFallback, latchedPersona, - isPKCommand: (text) => PKitCommandMessageHandler.isPKCommand(text), - pluralkitProxyMessageHandler, - imagePacksUsed: imagePacksUsedRef.current, + ] + ); + + const submit = useCallback(() => { + // A mobile edit replaces an existing event, so it owns neither the draft nor the reply. + const isMobileEdit = Boolean(editingEvent && isMobile); + const submission = takeSubmission({ + clearEditor: !isMobileEdit, + claimReplyDraft: !isMobileEdit, }); - - if (outgoing.kind === 'empty') return; - if (outgoing.kind === 'quickReact') { - handleQuickReact(outgoing.key); - return; - } - if (outgoing.kind === 'pkCommand') { - await pluralkitCmdMessageHandler.handleMessage(outgoing.plainText); - resetEditor(editor); - return; - } - if (outgoing.kind === 'gifSearch') { - setInitialGifSearch(outgoing.query); - setEmojiBoardTab(EmojiBoardTab.Gif); - resetEditor(editor); - resetEditorHistory(editor); - sendTypingStatus(false); - return; - } - if (outgoing.kind === 'command') { - const { command, plainText, customHtml } = outgoing; - if (command === Command.Poll) setShowPollPicker(true); - else if (command === Command.Location && plainText.trim().length === 0) - setShowLocationPicker(true); - else commands[command as Command]?.exe(plainText, customHtml); - resetEditor(editor); - resetEditorHistory(editor); - sendTypingStatus(false); - return; - } - - const { content } = outgoing; - if (outgoing.latchPersona) { - await setCurrentlyUsedPerMessageProfileIdForRoom(mx, roomId, outgoing.latchPersona.id); - setLatchedPersona(outgoing.latchPersona); - } - if (replyDraft) { - content['m.relates_to'] = getReplyContent(replyDraft, room); - } - const invalidate = () => - queryClient.invalidateQueries({ queryKey: ['delayedEvents', roomId] }); - - const resetInput = () => { - resetEditor(editor); - resetEditorHistory(editor); - setInputKey((prev) => prev + 1); - imagePacksUsedRef.current.clear(); - setReplyDraft(replyDraftBase); - sendTypingStatus(false); - }; - if (scheduledTime) { - try { - const delayMs = computeDelayMs(scheduledTime); - if (editingScheduledDelayId) { - await cancelDelayedEvent(mx, editingScheduledDelayId); - } - if (isEncrypted) { - await sendDelayedMessageE2EE(mx, roomId, room, content, delayMs); - } else { - await sendDelayedMessage(mx, roomId, content as RoomMessageEventContent, delayMs); - } - setSendError(undefined); - invalidate(); - setEditingScheduledDelayId(null); - setScheduledTime(null); - resetInput(); - } catch (e: unknown) { - if ( - e instanceof MatrixError && - (e.errcode === ErrorCode.M_MAX_DELAY_EXCEEDED || - e.data?.['org.matrix.msc4140.errcode'] === 'M_MAX_DELAY_EXCEEDED') - ) { - const maxDelay = - (e.data as { max_delay?: number })?.max_delay ?? - e.data?.['org.matrix.msc4140.max_delay']; - if (typeof maxDelay === 'number') setServerMaxDelayMs(maxDelay); - const maxDelayDays = maxDelay / daysToMs(1); - setSendError( - `Scheduled time exceeds the maximum delay allowed by this server. Please choose an earlier time. The Maximum Delay is of ${maxDelayDays} day${maxDelayDays > 1 ? 's' : ''}.` - ); - } else { - setSendError('Failed to schedule message. Please try again.'); - } - } - } else if (editingScheduledDelayId) { - try { - await cancelDelayedEvent(mx, editingScheduledDelayId); - debugLog.info('message', 'Sending message after cancelling scheduled event', { - roomId, - scheduledDelayId: editingScheduledDelayId, - }); - const res = await mx.sendMessage( - roomId, - threadRootId ?? null, - content as RoomMessageEventContent - ); - debugLog.info('message', 'Message sent successfully', { - roomId, - eventId: res.event_id, - }); - invalidate(); - setEditingScheduledDelayId(null); - resetInput(); - } catch (error) { - debugLog.error('message', 'Failed to send message after cancelling scheduled event', { - roomId, - error: error instanceof Error ? error.message : String(error), - }); - // Cancel failed — leave state intact for retry - } - } else { - const msgSendStart = performance.now(); - resetInput(); - debugLog.info('message', 'Sending message', { - roomId, - msgtype: content.msgtype, - }); - Sentry.startSpan( - { - name: 'message.send', - op: 'matrix.message', - attributes: { encrypted: String(isEncrypted) }, - }, - () => mx.sendMessage(roomId, threadRootId ?? null, content as RoomMessageEventContent) - ) - .then((res: { event_id: string }) => { - 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); - }); - } - }, [ - editor, - replyEvent, - mx, - roomId, - canSendReaction, - pkCompatEnable, - replyDraft, - silentReply, - pmpProxyingEnable, - pmpLatchingEnable, - pmpNoFallback, - pluralkitProxyMessageHandler, - scheduledTime, - editingScheduledDelayId, - nicknames, - room, - handleQuickReact, - pluralkitCmdMessageHandler, - commands, - sendTypingStatus, - queryClient, - threadRootId, - setReplyDraft, - settingsLinkBaseUrl, - isEncrypted, - setEditingScheduledDelayId, - setScheduledTime, - setServerMaxDelayMs, - replyDraftBase, - selectedFiles, - enableMediaGalleries, - sendIndividualAttachmentAsCaption, - editingEvent, - getEditingContent, - onCancelEdit, - latchedPersona, - ]); + return ( + composerControllerRef.current?.enqueue((isLive) => executeSubmit(submission, isLive)) ?? + Promise.resolve(undefined) + ); + }, [editingEvent, executeSubmit, isMobile, takeSubmission]); const handleKeyDown: KeyboardEventHandler = useCallback( (evt) => { @@ -1467,7 +1818,9 @@ export const RoomInput = forwardRef( handleCloseAutocomplete(); }; - const handleStickerSelect = async (mxc: string, shortcode: string, label: string) => { + const executeStickerSelect = async (mxc: string, label: string, submission: Submission) => { + const replySnapshot = submission.replyClaim?.snapshot; + const silentReplySnapshot = submission.replyClaim?.silentReply ?? silentReply; // Packs declare their own info, so sending does not need the file. Measuring it instead made // the send fail outright whenever the media fetch did. let info = getPackImageInfo(mx, room, ImageUsage.Sticker, mxc); @@ -1510,29 +1863,46 @@ export const RoomInput = forwardRef( content[prefix.MATRIX_UNSTABLE_IMAGE_SOURCE_PACK_PROPERTY_NAME] = getImagePackReferencesForMxcWrappedInMap(mxc, mx, ImageUsage.Sticker, room); - if (replyDraft) { - content['m.relates_to'] = getReplyContent(replyDraft, room); - if (!silentReply && replyDraft) - content['m.mentions'] = { ['user_ids']: [replyDraft.userId] }; - setReplyDraft(replyDraftBase); - } - try { - await mx.sendEvent(roomId, EventType.Sticker, content); - } catch (error) { - log.error('failed to send sticker', { roomId }, error); + if (replySnapshot) { + content['m.relates_to'] = getReplyContent(replySnapshot, room); + if (!silentReplySnapshot) content['m.mentions'] = { ['user_ids']: [replySnapshot.userId] }; } + await mx.sendEvent(roomId, EventType.Sticker, content); }; - const handleGifSelect = async (gif: GifData, spoiler?: boolean) => { - const url = getSendableKlipyMxcUrl(gif.url, clientConfig.gifs?.proxyUrl); - if (!url) return; - - const content = await getGifMsgContent(mx, gif, url, spoiler); - if (!content) return; - - await handleSendContents([content]); + const handleStickerSelect = (mxc: string, _shortcode: string, label: string) => { + const submission = takeSubmission({ clearEditor: false }); + return composerControllerRef.current?.enqueue(async () => { + try { + await executeStickerSelect(mxc, label, submission); + } catch (error) { + log.error('failed to send sticker', { roomId }, error); + restoreReplyClaim(submission.replyClaim); + } + }); }; + const handleGifSelect = (gif: GifData, spoiler?: boolean) => { + const submission = takeSubmission({ clearEditor: false }); + return composerControllerRef.current?.enqueue(async (isLive) => { + try { + const url = getSendableKlipyMxcUrl(gif.url, clientConfig.gifs?.proxyUrl); + if (!url) throw new Error('Unsendable GIF url'); + + const content = await getGifMsgContent(mx, gif, url, spoiler); + if (!content) throw new Error('Unsendable GIF content'); + + return await handleSendContents({ contents: [content], submission, isLive }); + } catch (error) { + log.error('failed to send gif', { roomId }, error); + restoreReplyClaim(submission.replyClaim); + return false; + } + }); + }; + + if (isEditInitializing) return
; + return (
( open={uploadBoard} onToggle={() => setUploadBoard(!uploadBoard)} uploadFamilyObserverAtom={uploadFamilyObserverAtom} - onSend={async (uploads) => { - setUploadSending(true); - try { - await handleSendUpload(uploads); - } finally { - setUploadSending(false); - } - }} onBusyChange={setUploadBusy} imperativeHandlerRef={uploadBoardHandlers} onCancel={handleCancelUpload} @@ -2141,7 +2503,7 @@ export const RoomInput = forwardRef( aria-pressed={!hasContent && editorMicButton ? showAudioRecorder : undefined} onClick={() => { if (showAudioRecorder) { - audioRecorderRef.current?.stop(); + requestRecorderStop(); return; } if (hasContent) { @@ -2154,6 +2516,7 @@ export const RoomInput = forwardRef( } if (!editorMicButton) return; if (isMobileOrTablet()) return; + recorderActionRef.current = undefined; setShowAudioRecorder(true); }} onMouseDown={(e: MouseEvent) => { @@ -2163,7 +2526,7 @@ export const RoomInput = forwardRef( if (showAudioRecorder) return; if (hasContent) { isLongPress.current = false; - if (isMobileOrTablet() && delayedEventsSupported) { + if (isMobileOrTablet() && delayedEventsSupported && !threadRootId) { longPressTimer.current = setTimeout(() => { isLongPress.current = true; setShowSchedulePicker(true); @@ -2173,22 +2536,27 @@ export const RoomInput = forwardRef( } if (!editorMicButton) return; if (!isMobileOrTablet()) return; + recorderActionRef.current = undefined; micHoldStartRef.current = Date.now(); setShowAudioRecorder(true); function discardRecording() { + if (recorderActionRef.current) return; + recorderActionRef.current = 'cancel'; releaseListeners(); - setTimeout(() => { + scheduleRecorderTimer(() => { audioRecorderRef.current?.cancel(); - }, 50); + }); } function onUp() { + if (recorderActionRef.current) return; const held = Date.now() - micHoldStartRef.current; if (held >= HOLD_THRESHOLD_MS) { + recorderActionRef.current = 'stop'; releaseListeners(); - setTimeout(() => { + scheduleRecorderTimer(() => { audioRecorderRef.current?.stop(); - }, 50); + }); } else { discardRecording(); } @@ -2214,8 +2582,12 @@ export const RoomInput = forwardRef( longPressTimer.current = null; } }} - disabled={hasContent && sendBusy && !showAudioRecorder} - className={hasContent && delayedEventsSupported ? css.SplitSendButton : undefined} + disabled={sendBusy && !showAudioRecorder} + className={ + hasContent && delayedEventsSupported && !threadRootId + ? css.SplitSendButton + : undefined + } > {showAudioRecorder ? ( ( weight="fill" style={{ color: color.Critical.Main }} /> + ) : sendBusy ? ( + ) : hasContent || !editorMicButton ? ( - sendBusy ? ( - - ) : scheduledTime ? ( + scheduledTime ? ( composerIcon(Clock) ) : ( composerIcon(PaperPlaneTilt) @@ -2278,7 +2650,7 @@ export const RoomInput = forwardRef( } /> - {delayedEventsSupported && !isMobileOrTablet() && ( + {delayedEventsSupported && !isMobileOrTablet() && !threadRootId && ( ) => { setScheduleMenuAnchor(evt.currentTarget.getBoundingClientRect()); @@ -2298,7 +2670,7 @@ export const RoomInput = forwardRef( } bottom={} /> - {showSchedulePicker && ( + {showSchedulePicker && !threadRootId && ( ( {showPollPicker && ( setShowPollPicker(false)} - mx={mx} - room={room} - replyDraft={replyDraft} - clearReplyDraft={() => setReplyDraft(replyDraftBase)} + onSubmit={(content) => + handleDialogSendContent(content, M_POLL_START.name as keyof TimelineEvents) + } /> )} {showLocationPicker && ( setShowLocationPicker(false)} - mx={mx} room={room} - replyDraft={replyDraft} - clearReplyDraft={() => setReplyDraft(replyDraftBase)} + onSubmit={handleDialogSendContent} /> )} diff --git a/src/app/features/room/composerController.test.ts b/src/app/features/room/composerController.test.ts new file mode 100644 index 000000000..3ef5f1f49 --- /dev/null +++ b/src/app/features/room/composerController.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it } from 'vitest'; +import { createComposerController } from './composerController'; + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((res) => { + resolve = res; + }); + return { promise, resolve }; +} + +describe('composer controller', () => { + it('runs a later send only after a slow one finishes', async () => { + const controller = createComposerController(); + const slow = deferred(); + const order: string[] = []; + + const slowSend = controller.enqueue(async () => { + order.push('slow:start'); + await slow.promise; + order.push('slow:end'); + }); + const nextSend = controller.enqueue(() => { + order.push('next'); + }); + + await Promise.resolve(); + expect(order).toEqual(['slow:start']); + slow.resolve(); + await Promise.all([slowSend, nextSend]); + expect(order).toEqual(['slow:start', 'slow:end', 'next']); + }); + + it('reports the composer as gone after disposal', async () => { + const controller = createComposerController(); + const completion = deferred(); + let cleanupCount = 0; + + const send = controller.enqueue(async (isLive) => { + await completion.promise; + if (isLive()) cleanupCount += 1; + }); + + await Promise.resolve(); + controller.dispose(); + completion.resolve(); + await send; + + expect(cleanupCount).toBe(0); + }); + + it('skips operations enqueued after disposal', async () => { + const controller = createComposerController(); + let ran = false; + + controller.dispose(); + + await expect(controller.enqueue(() => (ran = true))).resolves.toBeUndefined(); + expect(ran).toBe(false); + }); + + it('advances the tail after a rejected operation', async () => { + const controller = createComposerController(); + + await expect( + controller.enqueue(() => { + throw new Error('send failed'); + }) + ).rejects.toThrow('send failed'); + await expect(controller.enqueue(() => 'completed')).resolves.toBe('completed'); + }); +}); diff --git a/src/app/features/room/composerController.ts b/src/app/features/room/composerController.ts new file mode 100644 index 000000000..8fb7b986d --- /dev/null +++ b/src/app/features/room/composerController.ts @@ -0,0 +1,40 @@ +export type ComposerOperation = (isLive: () => boolean) => T | Promise; + +export interface ComposerController { + enqueue(operation: ComposerOperation): Promise; + dispose(): void; +} + +/** Serializes composer sends so a slow send cannot interleave with the next one. */ +export const createComposerController = (): ComposerController => { + let queueTail: Promise = Promise.resolve(); + let disposed = false; + const isLive = () => !disposed; + + const enqueue = (operation: ComposerOperation): Promise => + new Promise((resolve, reject) => { + const run = async () => { + if (disposed) { + resolve(undefined); + return; + } + try { + resolve(await operation(isLive)); + } catch (error) { + reject(error); + } + }; + + queueTail = queueTail.then(run, run).then( + () => undefined, + () => undefined + ); + }); + + return { + enqueue, + dispose: () => { + disposed = true; + }, + }; +}; diff --git a/src/app/features/room/location-modal/LocationDialog.test.tsx b/src/app/features/room/location-modal/LocationDialog.test.tsx new file mode 100644 index 000000000..4ca1edbb4 --- /dev/null +++ b/src/app/features/room/location-modal/LocationDialog.test.tsx @@ -0,0 +1,101 @@ +/* oxlint-disable typescript/no-explicit-any, react/void-dom-elements-no-children, vitest/require-mock-type-parameters, unicorn/consistent-function-scoping, typescript/no-extraneous-class */ + +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; +import { LocationDialog } from './LocationDialog'; + +vi.mock('folds', () => { + const div = ({ children, ...props }: any) =>
{children}
; + const button = ({ children, ...props }: any) => ; + return { + Dialog: div, + Header: div, + Box: div, + Text: div, + IconButton: button, + Button: button, + Input: (props: any) => , + Chip: button, + color: { Critical: { OnContainer: 'red' } }, + }; +}); + +vi.mock('@phosphor-icons/react', () => ({ + ClipboardIcon: () => null, + MapPinAreaIcon: () => null, + MapPinLineIcon: () => null, +})); + +vi.mock('$components/icons/phosphor', () => ({ + chipIcon: () => null, + composerIcon: () => null, + Warning: 'Warning', + X: 'X', +})); + +vi.mock('$components/modal-overlay/ModalOverlay', () => ({ + ModalOverlay: ({ children }: any) =>
{children}
, +})); + +vi.mock('$state/settings', () => ({ settingsAtom: {} })); +vi.mock('$state/hooks/settings', () => ({ + useSetting: (_atom: unknown, key: string) => [key === 'showInteractiveMap', vi.fn()], +})); +vi.mock('$utils/dom', () => ({ readClipboardText: vi.fn() })); +vi.mock('react-leaflet', () => ({ + MapContainer: ({ children }: any) =>
{children}
, + Marker: () => null, + TileLayer: () => null, + useMapEvents: () => null, +})); + +vi.mock('leaflet', () => { + class Icon {} + return { + default: { Icon, Marker: class Marker {}, marker: () => ({ addTo: () => ({}) }) }, + Icon, + }; +}); + +describe('LocationDialog', () => { + it('awaits the content callback and only closes after success', async () => { + let resolveSubmit!: () => void; + const onSubmit = vi.fn( + () => + new Promise((resolve) => { + resolveSubmit = resolve; + }) + ); + const onCancel = vi.fn(); + const room = { hasEncryptionStateEvent: () => false } as any; + + render(); + const submit = screen.getByRole('button', { name: 'Share Location' }); + fireEvent.click(submit); + fireEvent.click(submit); + + expect(onSubmit).toHaveBeenCalledTimes(1); + expect(onCancel).not.toHaveBeenCalled(); + expect(submit).toBeDisabled(); + expect((onSubmit as any).mock.calls[0]?.[0]).toMatchObject({ + msgtype: 'm.location', + geo_uri: expect.stringMatching(/^geo:/), + }); + + resolveSubmit(); + await waitFor(() => expect(onCancel).toHaveBeenCalledTimes(1)); + }); + + it('shows a retryable error when submission fails', async () => { + const onSubmit = vi.fn().mockRejectedValueOnce(new Error('Send failed')); + const onCancel = vi.fn(); + const room = { hasEncryptionStateEvent: () => false } as any; + + render(); + fireEvent.click(screen.getByRole('button', { name: 'Share Location' })); + + await waitFor(() => expect(screen.getByText('Send failed')).toBeInTheDocument()); + expect(onCancel).not.toHaveBeenCalled(); + expect(screen.getByRole('button', { name: 'Share Location' })).not.toBeDisabled(); + }); +}); diff --git a/src/app/features/room/location-modal/LocationDialog.tsx b/src/app/features/room/location-modal/LocationDialog.tsx index d35c07281..338489d1f 100644 --- a/src/app/features/room/location-modal/LocationDialog.tsx +++ b/src/app/features/room/location-modal/LocationDialog.tsx @@ -1,17 +1,14 @@ -import { Dialog, Header, Box, Text, IconButton, Button, Input, Chip } from 'folds'; +import { Dialog, Header, Box, Text, IconButton, Button, Input, Chip, color } from 'folds'; import { ClipboardIcon, MapPinAreaIcon, MapPinLineIcon } from '@phosphor-icons/react'; import { chipIcon, composerIcon, Warning, X } from '$components/icons/phosphor'; import { readClipboardText } from '$utils/dom'; -import type { IContent, MatrixClient, Room } from 'matrix-js-sdk'; +import type { IContent, Room } from 'matrix-js-sdk'; import * as css from './LocationDialog.css'; -import type { IReplyDraft } from '$state/room/roomInputDrafts'; import { MapContainer, Marker, TileLayer, useMapEvents } from 'react-leaflet'; import 'leaflet/dist/leaflet.css'; import { useCallback, useEffect, useRef, useState, type ChangeEventHandler } from 'react'; import type { LatLngLiteral } from 'leaflet'; import L from 'leaflet'; -import { getReplyContent } from '../RoomInput'; -import type { RoomMessageEventContent } from '$types/matrix-sdk'; import { MsgType } from '$types/matrix-sdk'; import { settingsAtom } from '$state/settings'; import { useSetting } from '$state/hooks/settings'; @@ -85,10 +82,8 @@ export function filterLocationString(result: string) { type LocationDialogProps = { onCancel: () => void; - mx: MatrixClient; + onSubmit: (content: IContent) => Promise; room: Room; - replyDraft?: IReplyDraft; - clearReplyDraft?: () => void; }; export enum LocationErrors { @@ -106,13 +101,7 @@ export type LocationPoint = { lon?: number; }; -export function LocationDialog({ - onCancel, - mx, - room, - replyDraft, - clearReplyDraft, -}: LocationDialogProps) { +export function LocationDialog({ onCancel, onSubmit, room }: LocationDialogProps) { const [showInteractiveMap] = useSetting(settingsAtom, 'showInteractiveMap'); const [showEncInteractiveMap] = useSetting(settingsAtom, 'showEncInteractiveMap'); const showMaps = room.hasEncryptionStateEvent() ? showEncInteractiveMap : showInteractiveMap; @@ -125,6 +114,8 @@ export function LocationDialog({ const [pinPosition, setPinPosition] = useState(initCoords); const zoom = useRef(2); const [locationError, setLocationError] = useState(LocationErrors.none); + const [submitError, setSubmitError] = useState(undefined); + const [isSubmitting, setIsSubmitting] = useState(false); const [map, setMap] = useState(null); @@ -235,7 +226,8 @@ export function LocationDialog({ } }; - const handleSubmit = () => { + const handleSubmit = async () => { + if (isSubmitting) return; const mlat = pinPosition.lat.toFixed(6); const mlon = pinPosition.lng.toFixed(6); const content: IContent = { @@ -243,13 +235,18 @@ export function LocationDialog({ geo_uri: `geo:${mlat},${mlon};u=0`, body: `https://www.openstreetmap.org/?mlat=${mlat}&mlon=${mlon}#map=16/${mlat}/${mlon}"`, }; - if (replyDraft && clearReplyDraft) { - content['m.relates_to'] = getReplyContent(replyDraft, room); - clearReplyDraft(); - } - mx.sendMessage(room.roomId, content as RoomMessageEventContent).then(() => { + setSubmitError(undefined); + setIsSubmitting(true); + try { + await onSubmit(content); onCancel(); - }); + } catch (err) { + setSubmitError( + err instanceof Error ? err.message : 'Failed to share location. Please try again.' + ); + } finally { + setIsSubmitting(false); + } }; return ( @@ -258,7 +255,7 @@ export function LocationDialog({
- {`Share Location ${replyDraft ? '(reply / thread)' : ''}`} + Share Location Share Location + {!!submitError && ( + + {submitError} + + )} diff --git a/src/app/features/room/persona-picker/PersonaPicker.test.tsx b/src/app/features/room/persona-picker/PersonaPicker.test.tsx new file mode 100644 index 000000000..c5f6b4c5e --- /dev/null +++ b/src/app/features/room/persona-picker/PersonaPicker.test.tsx @@ -0,0 +1,262 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import type { ReactNode } from 'react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import type { MatrixClient } from 'matrix-js-sdk'; +import type { PerMessageProfileMsc4461 } from '$hooks/usePerMessageProfile'; +import { PersonaPicker, PersonaPickerTab } from './PersonaPicker'; + +const mocked = vi.hoisted(() => ({ + getAll: vi.fn<(mx: MatrixClient) => Promise>(), + getRoom: + vi.fn<(mx: MatrixClient, roomId: string) => Promise>(), + getAccount: vi.fn<(mx: MatrixClient) => Promise>(), + setRoom: vi.fn<(...args: unknown[]) => Promise>(), + setAccount: vi.fn<(...args: unknown[]) => Promise>(), +})); + +vi.mock('$hooks/usePerMessageProfile', () => ({ + getAllPerMessageProfiles: mocked.getAll, + getCurrentlyUsedPerMessageProfileForRoom: mocked.getRoom, + getCurrentlyUsedPerMessageProfileForAccount: mocked.getAccount, + setCurrentlyUsedPerMessageProfileIdForRoom: mocked.setRoom, + setCurrentlyUsedPerMessageProfileIdForAccount: mocked.setAccount, +})); +vi.mock('$hooks/useMediaAuthentication.ts', () => ({ useMediaAuthentication: () => false })); +// useActiveTheme reaches for window.matchMedia, which jsdom does not provide. +vi.mock('$hooks/useTheme.ts', () => ({ + ThemeKind: { Light: 'light', Dark: 'dark' }, + useActiveTheme: () => ({ kind: 'light' }), +})); +vi.mock('$components/icons/phosphor', () => ({ + MagnifyingGlass: {}, + User: {}, + composerIcon: () => null, + menuIcon: () => null, +})); +vi.mock('$components/ResponsiveMenu', () => ({ + ResponsiveMenu: ({ children, menu }: { children: ReactNode; menu: ReactNode }) => ( +
+ {children} + {menu} +
+ ), +})); +vi.mock('$components/user-avatar/UserAvatar.tsx', () => ({ + UserAvatar: ({ renderFallback }: { renderFallback: () => ReactNode }) => <>{renderFallback()}, +})); +vi.mock('$components/info-card/InfoCard.tsx', () => ({ + InfoCard: ({ description }: { description: ReactNode }) =>
{description}
, +})); +vi.mock('@phosphor-icons/react', () => ({ InfoIcon: {} })); +vi.mock('$utils/matrix.ts', () => ({ mxcUrlToHttp: () => undefined })); +vi.mock('$utils/platform', () => ({ isMobileOrTablet: () => false })); +vi.mock('$utils/common', () => ({ nameInitials: (name: string) => name.slice(0, 1) })); +vi.mock('./PersonaPicker.css.ts', () => ({ + PersonaPickerMenuItem: '', + PersonaPickerButtonAvatar: '', + SelectedPersonaPickerButtonAvatar: '', + PersonaPickerButtonAvatarImage: '', +})); + +vi.mock('folds', async () => { + const React = await import('react'); + const Input = React.forwardRef>((props, ref) => ( + + )); + const TestButton = ({ children, ...props }: React.ComponentProps<'button'>) => + React.createElement('button', props, children); + const TestContainer = ({ children }: { children?: ReactNode }) => + React.createElement('div', null, children); + + return { + Avatar: TestContainer, + Badge: TestButton, + Box: TestContainer, + IconButton: TestButton, + Input, + Menu: TestContainer, + MenuItem: TestButton, + Scroll: TestContainer, + Text: TestContainer, + config: { space: { S200: 0 } }, + toRem: (value: number) => `${value}rem`, + }; +}); + +function deferred() { + let resolve!: (value: T) => void; + let reject!: (reason?: unknown) => void; + const promise = new Promise((resolvePromise, rejectPromise) => { + resolve = resolvePromise; + reject = rejectPromise; + }); + return { promise, resolve, reject }; +} + +const profiles: PerMessageProfileMsc4461[] = [ + { id: 'first', displayname: 'First', trigger: { prefix: [] } }, + { id: 'second', displayname: 'Second', trigger: { prefix: [] } }, +]; + +function renderPicker(mx = {} as MatrixClient, tab = PersonaPickerTab.Global) { + return render( + void>()} + onTabChange={vi.fn<(tab: PersonaPickerTab) => void>()} + latchedPersona={undefined} + /> + ); +} + +describe('PersonaPicker async flows', () => { + beforeEach(() => { + vi.clearAllMocks(); + mocked.getAll.mockResolvedValue(profiles); + mocked.getRoom.mockResolvedValue(undefined); + mocked.getAccount.mockResolvedValue(undefined); + mocked.setRoom.mockResolvedValue(undefined); + mocked.setAccount.mockResolvedValue(undefined); + }); + + it('ignores a stale profile fetch after the client changes', async () => { + const firstClient = {} as MatrixClient; + const secondClient = {} as MatrixClient; + const firstFetch = deferred(); + const secondFetch = deferred(); + mocked.getAll.mockImplementation((client: MatrixClient) => + client === firstClient ? firstFetch.promise : secondFetch.promise + ); + + const view = renderPicker(firstClient); + view.rerender( + void>()} + onTabChange={vi.fn<(tab: PersonaPickerTab) => void>()} + latchedPersona={undefined} + /> + ); + + secondFetch.resolve([{ id: 'new', displayname: 'New', trigger: { prefix: [] } }]); + expect(await screen.findByText('New')).toBeInTheDocument(); + firstFetch.resolve([{ id: 'old', displayname: 'Old', trigger: { prefix: [] } }]); + + await waitFor(() => expect(screen.queryByText('Old')).not.toBeInTheDocument()); + }); + + it('does not update state when an in-flight profile fetch resolves after unmount', async () => { + const fetch = deferred(); + mocked.getAll.mockReturnValue(fetch.promise); + const view = renderPicker(); + view.unmount(); + + fetch.resolve(profiles); + await Promise.resolve(); + expect(screen.queryByText('First')).not.toBeInTheDocument(); + }); + + it('commits an independent global sync when the room sync is still pending', async () => { + const roomSync = deferred(); + mocked.getRoom.mockReturnValue(roomSync.promise); + mocked.getAccount.mockResolvedValue(profiles[0]); + renderPicker(); + + await waitFor(() => { + expect(screen.getByRole('button', { name: 'First' })).toHaveAttribute( + 'aria-selected', + 'true' + ); + }); + + roomSync.reject(new Error('room sync failed')); + }); + + it('keeps the latest optimistic selection when an earlier write fails', async () => { + const firstWrite = deferred(); + const secondWrite = deferred(); + mocked.setAccount.mockImplementationOnce(() => firstWrite.promise); + mocked.setAccount.mockImplementationOnce(() => secondWrite.promise); + renderPicker(); + await screen.findByText('First'); + + fireEvent.click(screen.getByRole('button', { name: 'First' })); + fireEvent.click(screen.getByRole('button', { name: 'Second' })); + + firstWrite.reject(new Error('first write failed')); + secondWrite.resolve(); + + await waitFor(() => { + expect(screen.getByRole('button', { name: 'Second' })).toHaveAttribute( + 'aria-selected', + 'true' + ); + }); + }); + + it('rolls back a failed global selection without suppressing a room selection', async () => { + const mx = {} as MatrixClient; + const globalWrite = deferred(); + const roomWrite = deferred(); + mocked.setAccount.mockImplementationOnce(() => globalWrite.promise); + mocked.setRoom.mockImplementationOnce(() => roomWrite.promise); + const view = renderPicker(mx); + await screen.findByText('First'); + + fireEvent.click(screen.getByRole('button', { name: 'First' })); + view.rerender( + void>()} + onTabChange={vi.fn<(tab: PersonaPickerTab) => void>()} + latchedPersona={undefined} + /> + ); + fireEvent.click(screen.getByRole('button', { name: 'Second' })); + + globalWrite.reject(new Error('global write failed')); + roomWrite.resolve(); + + await waitFor(() => { + expect(screen.getByRole('button', { name: 'Second' })).toHaveAttribute( + 'aria-selected', + 'true' + ); + }); + + view.rerender( + void>()} + onTabChange={vi.fn<(tab: PersonaPickerTab) => void>()} + latchedPersona={undefined} + /> + ); + expect(screen.getByRole('button', { name: 'First' })).not.toHaveAttribute( + 'aria-selected', + 'true' + ); + }); + + it('reconciles an optimistic selection when its write is rejected', async () => { + mocked.setAccount.mockRejectedValueOnce(new Error('write failed')); + renderPicker(); + await screen.findByText('First'); + + fireEvent.click(screen.getByRole('button', { name: 'First' })); + + await waitFor(() => { + expect(screen.getByRole('button', { name: 'First' })).not.toHaveAttribute( + 'aria-selected', + 'true' + ); + }); + }); +}); diff --git a/src/app/features/room/persona-picker/PersonaPicker.tsx b/src/app/features/room/persona-picker/PersonaPicker.tsx index 6a747f2cb..3d5cd8614 100644 --- a/src/app/features/room/persona-picker/PersonaPicker.tsx +++ b/src/app/features/room/persona-picker/PersonaPicker.tsx @@ -33,7 +33,14 @@ import { Badge, } from 'folds'; import type { MatrixClient } from 'matrix-js-sdk'; -import { useCallback, useEffect, useRef, useState, type FormEvent } from 'react'; +import { + useCallback, + useEffect, + useRef, + useState, + type FormEvent, + type MutableRefObject, +} from 'react'; import * as css from './PersonaPicker.css.ts'; import { InfoCard } from '$components/info-card/InfoCard.tsx'; import { InfoIcon, XIcon } from '@phosphor-icons/react'; @@ -43,15 +50,16 @@ const pillStyles = { cursor: 'pointer', } as const; -export enum PersonaPickerPresentation { - TemporarySelectorMenu = 'TemporarySelectorMenu', - PersistentPicker = 'PersistentPicker', -} export enum PersonaPickerTab { Global = 'Global', PerRoom = 'PerRoom', } +export enum PersonaPickerPresentation { + TemporarySelectorMenu = 'TemporarySelectorMenu', + PersistentPicker = 'PersistentPicker', +} + type PersonaPickerProps = { tab?: PersonaPickerTab; mx: MatrixClient; @@ -59,83 +67,60 @@ type PersonaPickerProps = { suppressEditorRefocus?: () => void; onTabChange?: (tab: PersonaPickerTab) => void; latchedPersona?: PerMessageProfileMsc4461; - hideTabs?: boolean; onPersonaSelect?: (persona: PerMessageProfileMsc4461 | undefined) => void; requestClose?: () => void; showNoneOption?: boolean; hideButton?: boolean; + hideTabs?: boolean; anchor?: RectCords; }; -function PersonaSelectMenuTabs({ - tab, - setTab, -}: { - tab: PersonaPickerTab; - setTab: (tab: PersonaPickerTab) => void; -}) { - return ( - - setTab(PersonaPickerTab.Global)} - > - - Global - - - setTab(PersonaPickerTab.PerRoom)} - > - - Per-room - - - - ); -} - export function TemporaryPersonaPicker(props: PersonaPickerProps) { return ( - + ); } + +export const PersonaPicker = TemporaryPersonaPicker; + export function PersistentPersonaPicker(props: PersonaPickerProps) { - return ; + return ; } -function PersonaPicker({ +function PersonaPickerMenu({ tab: tabProp = PersonaPickerTab.Global, mx, roomId, suppressEditorRefocus, + onTabChange, latchedPersona, onPersonaSelect, anchor, requestClose, presentation, - onTabChange, }: PersonaPickerProps & { presentation: PersonaPickerPresentation }) { const useAuthentication = useMediaAuthentication(); const persistent = presentation === PersonaPickerPresentation.PersistentPicker; const [tab, setTab] = useState(tabProp); - const [AddPersonaMenuAnchor, setAddPersonaMenuAnchor] = useState(anchor); const activeTheme = useActiveTheme(); + const [AddPersonaMenuAnchor, setAddPersonaMenuAnchor] = useState(anchor); const [profiles, setProfiles] = useState(undefined); const [selectedGlobalPersona, setSelectedGlobalPersona] = useState(null); const [selectedRoomPersona, setSelectedRoomPersona] = useState( latchedPersona ?? null ); + const mountedRef = useRef(false); + const profileFetchGenerationRef = useRef(0); + // Bumped on each click so an in-flight sync cannot undo a fresher choice. Global and + // per-room selections are independent, so one must not invalidate the other's rollback. + const globalSelectionRef = useRef(0); + const roomSelectionRef = useRef(0); + const isPickerMenuItemSelected = (persona: PerMessageProfileMsc4461) => { + const selectedPersona = + tab === PersonaPickerTab.Global ? selectedGlobalPersona : selectedRoomPersona; + return persona.id === selectedPersona?.id ? true : undefined; + }; const nameColor = useCallback( (persona: PerMessageProfileMsc4461) => @@ -147,27 +132,85 @@ function PersonaPicker({ const defactoPersona = () => selectedRoomPersona ?? selectedGlobalPersona; - useEffect(() => { - const syncProfile = async () => { - if (roomId) { - const syncedRoomProfile = await getCurrentlyUsedPerMessageProfileForRoom(mx, roomId); - if (!selectedRoomPersona) setSelectedRoomPersona(syncedRoomProfile ?? null); - - const syncedGlobalProfile = await getCurrentlyUsedPerMessageProfileForAccount(mx); - setSelectedGlobalPersona(syncedGlobalProfile ?? null); - } - }; - syncProfile(); - }, [mx, roomId, profiles, latchedPersona, selectedRoomPersona]); - - const fetchProfiles = async (mx_: MatrixClient) => { - const fetchedProfiles = await getAllPerMessageProfiles(mx_); - setProfiles(fetchedProfiles); - setFilteredProfiles(fetchedProfiles); - }; + const searchInputRef = useRef(null); const scrollRef = useRef(null); - const searchInputRef = useRef(null); + const [filteredProfiles, setFilteredProfiles] = useState( + undefined + ); + + useEffect(() => { + mountedRef.current = true; + return () => { + mountedRef.current = false; + profileFetchGenerationRef.current += 1; + }; + }, []); + + const clearFilterInput = () => { + if (searchInputRef.current) { + searchInputRef.current.value = ''; + } + setFilteredProfiles(profiles); + }; + + useEffect(() => { + let cancelled = false; + + const syncProfile = async ( + generationRef: MutableRefObject, + load: () => Promise, + apply: (profile: PerMessageProfileMsc4461 | null) => void + ) => { + const generation = generationRef.current; + try { + const synced = await load(); + if (!cancelled && generation === generationRef.current) apply(synced ?? null); + } catch { + // Profile synchronization is best effort; retain the current selection on failure. + } + }; + + void syncProfile( + roomSelectionRef, + () => + roomId ? getCurrentlyUsedPerMessageProfileForRoom(mx, roomId) : Promise.resolve(undefined), + // A latched persona already reflects the user's intent, so don't overwrite it. + (profile) => { + if (!selectedRoomPersona) setSelectedRoomPersona(profile); + } + ); + void syncProfile( + globalSelectionRef, + () => getCurrentlyUsedPerMessageProfileForAccount(mx), + setSelectedGlobalPersona + ); + + return () => { + cancelled = true; + }; + }, [mx, roomId, latchedPersona, selectedRoomPersona]); + + const fetchProfiles = useCallback(async (mx_: MatrixClient) => { + const fetchGeneration = ++profileFetchGenerationRef.current; + try { + const fetchedProfiles = await getAllPerMessageProfiles(mx_); + if (!mountedRef.current || fetchGeneration !== profileFetchGenerationRef.current) { + return; + } + setProfiles(fetchedProfiles); + setFilteredProfiles(fetchedProfiles); + } catch { + // Profile loading is best effort; keep the existing list when it fails. + } + }, []); + + useEffect(() => { + void fetchProfiles(mx); + return () => { + profileFetchGenerationRef.current += 1; + }; + }, [fetchProfiles, mx]); const filter = useCallback( (e: FormEvent) => { @@ -187,18 +230,6 @@ function PersonaPicker({ [profiles] ); - const isSelected = (persona: PerMessageProfileMsc4461 | undefined) => { - if (!persona) return undefined; - const selected = tab === PersonaPickerTab.Global ? selectedGlobalPersona : selectedRoomPersona; - return persona.id === selected?.id ? true : undefined; - }; - - const [filteredProfiles, setFilteredProfiles] = useState(profiles); - - useEffect(() => { - fetchProfiles(mx); - }, [mx]); - const avatarUrl = useCallback( (profile: PerMessageProfileMsc4461) => { if (profile.avatar_url !== undefined) { @@ -210,58 +241,16 @@ function PersonaPicker({ [mx, useAuthentication] ); - const handleSelect = useCallback( - async (profile: PerMessageProfileMsc4461 | undefined) => { - if (onPersonaSelect) { - onPersonaSelect(profile); - return; - } - if (!roomId) return; - - const isGlobal = tab === PersonaPickerTab.Global; - const selectedPersona = isGlobal ? selectedGlobalPersona : selectedRoomPersona; - const disabling = !profile || profile.id === selectedPersona?.id; - - if (!disabling) { - if (isGlobal) { - setSelectedGlobalPersona(profile); - await setCurrentlyUsedPerMessageProfileIdForAccount(mx, profile.id); - } else { - setSelectedRoomPersona(profile); - await setCurrentlyUsedPerMessageProfileIdForRoom(mx, roomId, profile.id); - } - } else { - if (isGlobal) { - setSelectedGlobalPersona(null); - await setCurrentlyUsedPerMessageProfileIdForAccount(mx, undefined, undefined, true); - } else { - setSelectedRoomPersona(null); - await setCurrentlyUsedPerMessageProfileIdForRoom(mx, roomId, undefined, undefined, true); - } - } - }, - [ - mx, - roomId, - tab, - selectedRoomPersona, - selectedGlobalPersona, - setSelectedGlobalPersona, - setSelectedRoomPersona, - onPersonaSelect, - ] - ); - return ( { setAddPersonaMenuAnchor(undefined); - requestClose?.(); + clearFilterInput(); }} menu={ @@ -270,15 +259,39 @@ function PersonaPicker({ gap="100" style={{ padding: config.space.S200, minWidth: '18rem' }} > - {persistent && ( - { - onTabChange?.(newTab); - setTab(newTab); + + { + setTab(PersonaPickerTab.Global); + onTabChange?.(PersonaPickerTab.Global); }} - /> - )} + > + + Global + + + { + setTab(PersonaPickerTab.PerRoom); + onTabChange?.(PersonaPickerTab.PerRoom); + }} + > + + Per-room + + + + <> - + {filteredProfiles?.map((profile) => ( handleSelect(profile)} + aria-selected={isPickerMenuItemSelected(profile)} + onClick={async () => { + if (onPersonaSelect) { + await onPersonaSelect(profile); + requestClose?.(); + return; + } + const isGlobal = tab === PersonaPickerTab.Global; + const previousPersona = isGlobal + ? selectedGlobalPersona + : selectedRoomPersona; + const disabling = profile.id === previousPersona?.id; + const setPersona = isGlobal + ? setSelectedGlobalPersona + : setSelectedRoomPersona; + const generationRef = isGlobal ? globalSelectionRef : roomSelectionRef; + const selectionGeneration = ++generationRef.current; + + setPersona(disabling ? null : profile); + + try { + if (isGlobal) { + await setCurrentlyUsedPerMessageProfileIdForAccount( + mx, + disabling ? undefined : profile.id, + undefined, + disabling + ); + } else { + await setCurrentlyUsedPerMessageProfileIdForRoom( + mx, + roomId!, + disabling ? undefined : profile.id, + undefined, + disabling + ); + } + } catch { + if (mountedRef.current && selectionGeneration === generationRef.current) { + setPersona(previousPersona); + } + } + }} before={ ))} - {presentation !== PersonaPickerPresentation.PersistentPicker && ( - handleSelect(undefined)} - before={ -
- {menuIcon(XIcon, { weight: 'regular', size: 28 })}{' '} -
- } - > - - No persona - -
- )}
- {presentation === PersonaPickerPresentation.PersistentPicker && ( - - Message will use your per-room persona. - - ) : selectedGlobalPersona ? ( - <> - Message will use your global persona. - - ) : ( - <>No persona chosen. - ) - } - /> - )} + + Message will use your per-room persona. + + ) : selectedGlobalPersona ? ( + <> + Message will use your global persona. + + ) : ( + <>No persona chosen. + ) + } + />
} > - {persistent && ( - { - // getAllPerMessageProfiles can return an empty list during initial startup. - if (profiles?.length === 0) { - fetchProfiles(mx); + { + // getAllPerMessageProfiles can return an empty list during initial startup. + if (profiles?.length === 0) { + void fetchProfiles(mx); + } + setAddPersonaMenuAnchor(evt.currentTarget.getBoundingClientRect()); + }} + onPointerDown={suppressEditorRefocus} + variant="SurfaceVariant" + size="300" + style={{ backgroundColor: 'transparent' }} + title="Switch persona" + aria-label="Switch persona" + > + {(selectedRoomPersona ?? selectedGlobalPersona) ? ( + - {(selectedRoomPersona ?? selectedGlobalPersona) ? ( - - ( - - {nameInitials(defactoPersona()!.displayname)} - - )} - alt={`Avatar for profile ${defactoPersona()!.id}`} - /> - - ) : ( - composerIcon(UserIcon, { weight: AddPersonaMenuAnchor ? 'fill' : 'regular' }) - )} - - )} + aria-label="Profile avatar" + > + ( + + {nameInitials(defactoPersona()!.displayname)} + + )} + alt={`Avatar for profile ${defactoPersona()!.id}`} + /> + + ) : ( + composerIcon(UserIcon, { weight: AddPersonaMenuAnchor ? 'fill' : 'regular' }) + )} +
); } diff --git a/src/app/features/room/poll-modals/PollDialog.test.tsx b/src/app/features/room/poll-modals/PollDialog.test.tsx new file mode 100644 index 000000000..62e7e74fb --- /dev/null +++ b/src/app/features/room/poll-modals/PollDialog.test.tsx @@ -0,0 +1,116 @@ +/* oxlint-disable typescript/no-explicit-any, react/void-dom-elements-no-children, vitest/require-mock-type-parameters, unicorn/consistent-function-scoping */ + +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { PollDialog } from './PollDialog'; + +vi.mock('folds', () => { + const div = ({ children, ...props }: any) =>
{children}
; + const button = ({ children, ...props }: any) => ; + const input = (props: any) => ; + return { + Dialog: div, + Header: div, + Box: div, + Text: div, + IconButton: button, + Button: button, + Input: input, + Chip: button, + Switch: ({ value, onChange }: any) => ( + onChange(event.target.checked)} /> + ), + Scroll: div, + color: { Critical: { OnContainer: 'red' } }, + }; +}); + +vi.mock('$components/icons/phosphor', () => ({ + chipIcon: () => null, + composerIcon: () => null, + ListBullets: 'ListBullets', + Minus: 'Minus', + X: 'X', +})); + +vi.mock('$components/setting-tile', () => ({ + SettingTile: ({ children, after }: any) => ( +
+ {children} + {after} +
+ ), +})); + +vi.mock('$components/sequence-card', () => ({ + SequenceCard: ({ children }: any) =>
{children}
, + SequenceCardStyle: '', +})); + +vi.mock('$components/modal-overlay/ModalOverlay', () => ({ + ModalOverlay: ({ children }: any) =>
{children}
, +})); + +describe('PollDialog', () => { + beforeEach(() => vi.clearAllMocks()); + + it('awaits submission, prevents duplicates, and closes after success', async () => { + let resolveSubmit!: () => void; + const onSubmit = vi.fn( + () => + new Promise((resolve) => { + resolveSubmit = resolve; + }) + ); + const onCancel = vi.fn(); + + render(); + fireEvent.change(screen.getByLabelText('Insert Title'), { + target: { value: 'Dinner' }, + }); + fireEvent.change(screen.getByLabelText('Type Option 1'), { + target: { value: 'Pizza' }, + }); + fireEvent.change(screen.getByLabelText('Type Option 2'), { + target: { value: 'Pasta' }, + }); + + const submit = screen.getByRole('button', { name: 'Create Poll' }); + fireEvent.click(submit); + fireEvent.click(submit); + + expect(onSubmit).toHaveBeenCalledTimes(1); + expect(onCancel).not.toHaveBeenCalled(); + expect(submit).toBeDisabled(); + expect((onSubmit as any).mock.calls[0]?.[0]).toMatchObject({ + 'org.matrix.msc3381.poll.start': expect.objectContaining({ + question: expect.objectContaining({ body: 'Dinner' }), + }), + }); + + resolveSubmit(); + await waitFor(() => expect(onCancel).toHaveBeenCalledTimes(1)); + }); + + it('keeps the dialog open and shows a retryable error when submission fails', async () => { + const onSubmit = vi.fn().mockRejectedValueOnce(new Error('Send failed')); + const onCancel = vi.fn(); + + render(); + fireEvent.change(screen.getByLabelText('Insert Title'), { + target: { value: 'Dinner' }, + }); + fireEvent.change(screen.getByLabelText('Type Option 1'), { + target: { value: 'Pizza' }, + }); + fireEvent.change(screen.getByLabelText('Type Option 2'), { + target: { value: 'Pasta' }, + }); + + fireEvent.click(screen.getByRole('button', { name: 'Create Poll' })); + + await waitFor(() => expect(screen.getByText('Send failed')).toBeInTheDocument()); + expect(onCancel).not.toHaveBeenCalled(); + expect(screen.getByRole('button', { name: 'Create Poll' })).not.toBeDisabled(); + }); +}); diff --git a/src/app/features/room/poll-modals/PollDialog.tsx b/src/app/features/room/poll-modals/PollDialog.tsx index a0e15b8f6..b65389b67 100644 --- a/src/app/features/room/poll-modals/PollDialog.tsx +++ b/src/app/features/room/poll-modals/PollDialog.tsx @@ -18,7 +18,7 @@ import type { PollAnswerItem } from '$components/message/PollEvent'; import { randomStr } from '$utils/common'; import { SettingTile } from '$components/setting-tile'; import { SequenceCard, SequenceCardStyle } from '$components/sequence-card'; -import type { IContent, MatrixClient, Room, TimelineEvents } from 'matrix-js-sdk'; +import type { IContent } from 'matrix-js-sdk'; import { M_POLL_KIND_DISCLOSED, M_POLL_KIND_UNDISCLOSED, @@ -28,16 +28,11 @@ import { import { MsgType } from '$types/matrix-sdk'; import { isKeyHotkey } from 'is-hotkey'; import * as css from './PollDialog.css'; -import type { IReplyDraft } from '$state/room/roomInputDrafts'; -import { getReplyContent } from '../RoomInput'; import { ModalOverlay } from '$components/modal-overlay/ModalOverlay'; type PollDialogProps = { onCancel: () => void; - mx: MatrixClient; - room: Room; - replyDraft?: IReplyDraft; - clearReplyDraft?: () => void; + onSubmit: (content: IContent) => Promise; }; type ErrorProps = { @@ -45,13 +40,14 @@ type ErrorProps = { errorString: string; }; -export function PollDialog({ onCancel, mx, room, replyDraft, clearReplyDraft }: PollDialogProps) { - const roomId = room.roomId; +export function PollDialog({ onCancel, onSubmit }: PollDialogProps) { const [isDisclosed, setIsDisclosed] = useState(true); const [maxSelections, setMaxSelections] = useState(1); const [inputValue, setInputValue] = useState(1); const title = useRef(''); const [error, setError] = useState(undefined); + const [submitError, setSubmitError] = useState(undefined); + const [isSubmitting, setIsSubmitting] = useState(false); const [answers, setAnswers] = useState([ { id: randomStr(), @@ -88,7 +84,8 @@ export function PollDialog({ onCancel, mx, room, replyDraft, clearReplyDraft }: [answers, setAnswers, maxSelections, setMaxSelections] ); - const handleSubmit = () => { + const handleSubmit = async () => { + if (isSubmitting) return; if (title.current.length === 0) { setError({ errorcode: 'title', errorString: 'Missing Title' }); return; @@ -122,18 +119,18 @@ export function PollDialog({ onCancel, mx, room, replyDraft, clearReplyDraft }: }, [M_TEXT.name]: `New poll\n Question: ${title.current}\nAnswers:\n ${answers.map((item) => item[M_TEXT.name]).join('\n')}`, }; - if (replyDraft && clearReplyDraft) { - pollContent['m.relates_to'] = getReplyContent(replyDraft, room); - clearReplyDraft(); + setSubmitError(undefined); + setIsSubmitting(true); + try { + await onSubmit(pollContent); + onCancel(); + } catch (err) { + setSubmitError( + err instanceof Error ? err.message : 'Failed to create poll. Please try again.' + ); + } finally { + setIsSubmitting(false); } - - mx.sendEvent( - roomId, - M_POLL_START.name as keyof TimelineEvents, - pollContent as TimelineEvents[keyof TimelineEvents] - ); - - onCancel(); }; const handleMaxOptions: ChangeEventHandler = (evt) => { @@ -155,7 +152,7 @@ export function PollDialog({ onCancel, mx, room, replyDraft, clearReplyDraft }:
{composerIcon(ListBullets)} - {`New Poll ${replyDraft ? '(reply / thread)' : ''}`} + New Poll )} + {!!submitError && ( + + {submitError} + + )} diff --git a/src/app/utils/common.ts b/src/app/utils/common.ts index 3f590320a..887a368fe 100644 --- a/src/app/utils/common.ts +++ b/src/app/utils/common.ts @@ -45,12 +45,6 @@ export const getFileTypeIconComponent = (fileType: string): PhosphorIcon => { return File; }; -export const fulfilledPromiseSettledResult = (prs: PromiseSettledResult[]): T[] => - prs.reduce((values, pr) => { - if (pr.status === 'fulfilled') values.push(pr.value); - return values; - }, []); - export const promiseFulfilledResult = ( settledResult: PromiseSettledResult ): T | undefined => { diff --git a/src/app/utils/delayedEvents.ts b/src/app/utils/delayedEvents.ts index e63deaf77..2ce5c089d 100644 --- a/src/app/utils/delayedEvents.ts +++ b/src/app/utils/delayedEvents.ts @@ -36,13 +36,14 @@ export async function sendDelayedMessage( roomId: string, content: IContent, delayMs: number, - threadId?: string | null + threadId?: string | null, + eventType: keyof TimelineEvents = EventType.RoomMessage ): Promise { return mx._unstable_sendDelayedEvent( roomId, { delay: delayMs }, threadId ?? null, - EventType.RoomMessage as Parameters[3], + eventType as Parameters[3], content as RoomMessageEventContent ); } @@ -59,7 +60,8 @@ export async function sendDelayedMessageE2EE( room: Room, content: IContent, delayMs: number, - threadId?: string | null + threadId?: string | null, + eventType: keyof TimelineEvents = EventType.RoomMessage ): Promise { const crypto = mx.getCrypto(); if (!crypto || !('encryptEvent' in crypto)) { @@ -68,7 +70,7 @@ export async function sendDelayedMessageE2EE( // Create a temporary MatrixEvent to encrypt in-place. const event = new MatrixEvent({ - type: EventType.RoomMessage, + type: eventType, content, room_id: roomId, sender: mx.getUserId() ?? '', From 4f1f2ef6dee58bd1a9ddd966c518d0851e9ea762 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Tue, 4 Aug 2026 11:26:02 +0200 Subject: [PATCH 089/135] fix(persona): align picker with MSC4461 profiles --- src/app/features/room/persona-picker/PersonaPicker.tsx | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/app/features/room/persona-picker/PersonaPicker.tsx b/src/app/features/room/persona-picker/PersonaPicker.tsx index 3d5cd8614..2e098937a 100644 --- a/src/app/features/room/persona-picker/PersonaPicker.tsx +++ b/src/app/features/room/persona-picker/PersonaPicker.tsx @@ -43,7 +43,7 @@ import { } from 'react'; import * as css from './PersonaPicker.css.ts'; import { InfoCard } from '$components/info-card/InfoCard.tsx'; -import { InfoIcon, XIcon } from '@phosphor-icons/react'; +import { InfoIcon } from '@phosphor-icons/react'; import { ThemeKind, useActiveTheme } from '$hooks/useTheme.ts'; const pillStyles = { @@ -67,7 +67,7 @@ type PersonaPickerProps = { suppressEditorRefocus?: () => void; onTabChange?: (tab: PersonaPickerTab) => void; latchedPersona?: PerMessageProfileMsc4461; - onPersonaSelect?: (persona: PerMessageProfileMsc4461 | undefined) => void; + onPersonaSelect?: (persona: PerMessageProfileMsc4461 | undefined) => void | Promise; requestClose?: () => void; showNoneOption?: boolean; hideButton?: boolean; @@ -97,10 +97,8 @@ function PersonaPickerMenu({ onPersonaSelect, anchor, requestClose, - presentation, }: PersonaPickerProps & { presentation: PersonaPickerPresentation }) { const useAuthentication = useMediaAuthentication(); - const persistent = presentation === PersonaPickerPresentation.PersistentPicker; const [tab, setTab] = useState(tabProp); const activeTheme = useActiveTheme(); const [AddPersonaMenuAnchor, setAddPersonaMenuAnchor] = useState(anchor); From 31e30c7cc56a7c55246ecf677a19f2f1a1ea1945 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Wed, 5 Aug 2026 22:11:35 -0500 Subject: [PATCH 090/135] fix deferred composer replies --- src/app/features/room/RoomInput.test.tsx | 161 +++++++++++++++--- src/app/features/room/RoomInput.tsx | 19 ++- .../persona-picker/PersonaPicker.test.tsx | 10 +- .../room/persona-picker/PersonaPicker.tsx | 2 - 4 files changed, 159 insertions(+), 33 deletions(-) diff --git a/src/app/features/room/RoomInput.test.tsx b/src/app/features/room/RoomInput.test.tsx index cb950bc57..d4807fb6c 100644 --- a/src/app/features/room/RoomInput.test.tsx +++ b/src/app/features/room/RoomInput.test.tsx @@ -14,6 +14,7 @@ import { createEditor, Transforms } from 'slate'; import { M_POLL_START } from 'matrix-js-sdk'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { RoomInput } from './RoomInput'; +import type * as MsgContentModule from './msgContent'; import { roomIdToMsgDraftAtomFamily, roomIdToReplyDraftAtomFamily, @@ -128,9 +129,9 @@ vi.mock('$state/upload', async () => { }); vi.mock('$components/editor', () => { - const textOf = (nodes: any[]) => + const textOf = (nodes: any[]): string => nodes - .map((node) => (node.children ?? []).map((child: any) => child.text ?? '').join('')) + .map((node) => (typeof node.text === 'string' ? node.text : textOf(node.children ?? []))) .join('\n'); const passthrough = ({ children }: { children?: unknown }) => children ?? null; const CustomEditor = ({ @@ -172,7 +173,7 @@ vi.mock('$components/editor', () => { ANYWHERE_AUTOCOMPLETE_PREFIXES: [], BEGINNING_AUTOCOMPLETE_PREFIXES: [], BlockType: { Paragraph: 'paragraph' }, - Command: {}, + Command: { Poll: 'poll', Location: 'location' }, CustomEditor, EmoticonAutocomplete: passthrough, MarkdownFormattingToolbarBottom: passthrough, @@ -183,7 +184,7 @@ vi.mock('$components/editor', () => { customHtmlEqualsPlainText: (html: string, text: string) => html === text, focusEditor: vi.fn(), getAutocompleteQuery: vi.fn(), - getBeginCommand: () => undefined, + getBeginCommand: (editor: any) => editor.children[0]?.children?.[1]?.command, getLinks: () => [], getMentions: () => ({ users: new Set(), room: undefined }), getPrevWorldRange: () => undefined, @@ -241,14 +242,41 @@ vi.mock('$components/upload-card', () => ({ ), })); +vi.mock('./msgContent', async (importOriginal) => ({ + ...(await importOriginal()), + getGifMsgContent: async (_mx: unknown, gif: { title: string }, url: string) => ({ + msgtype: 'm.image', + body: gif.title, + url, + }), +})); vi.mock('$components/attachment-sheet/AttachmentSheet', () => ({ AttachmentSheet: () => null })); vi.mock('$components/emoji-board', () => ({ - EmojiBoard: ({ onStickerSelect }: any) => ( - + EmojiBoard: ({ onStickerSelect, onGifSelect, requestClose }: any) => ( + <> + + + + ), - EmojiBoardTab: {}, + EmojiBoardTab: { Emoji: 'emoji', Gif: 'gif', Sticker: 'sticker' }, })); vi.mock('$components/UseStateProvider', () => ({ UseStateProvider: ({ children }: any) => (typeof children === 'function' ? children() : children), @@ -256,16 +284,24 @@ vi.mock('$components/UseStateProvider', () => ({ vi.mock('$components/message', () => ({ Reply: () => null, ThreadIndicator: () => null })); vi.mock('./CommandAutocomplete', () => ({ CommandAutocomplete: () => null })); vi.mock('./AudioMessageRecorder', () => ({ AudioMessageRecorder: () => null })); -vi.mock('./persona-picker/PersonaPicker', () => ({ PersonaPicker: () => null })); +vi.mock('./persona-picker/PersonaPicker', () => ({ + PersistentPersonaPicker: () => null, + PersonaPickerTab: { Global: 'Global', PerRoom: 'PerRoom' }, +})); vi.mock('./schedule-send', () => ({ SchedulePickerDialog: () => null })); vi.mock('./poll-modals', () => ({ - PollDialog: ({ onSubmit }: any) => ( - + PollDialog: ({ onSubmit, onCancel }: any) => ( + <> + + + ), })); vi.mock('./location-modal', () => ({ @@ -284,6 +320,9 @@ vi.mock('./location-modal', () => ({ > Submit location + ); }, @@ -360,7 +399,7 @@ vi.mock('$hooks/useFilePicker', () => ({ vi.mock('$hooks/useFilePasteHandler', () => ({ useFilePasteHandler: () => vi.fn() })); vi.mock('$hooks/useFileDrop', () => ({ useFileDropZone: () => false })); vi.mock('$hooks/useCommands', () => ({ - Command: {}, + Command: { Poll: 'poll', Location: 'location' }, SHRUG: '¯\\_(ツ)_/¯', TABLEFLIP: '(╯°□°)╯︵ ┻━┻', UNFLIP: '┬─┬ノ( º _ ºノ)', @@ -399,6 +438,7 @@ vi.mock('$state/scheduledMessages', async () => { const editingScheduledDelayIdAtom = atom(null); return { delayedEventsSupportedAtom: atom(false), + getScheduledMessageStateKey: (userId: string, roomId: string) => `${userId}\0${roomId}`, roomIdToScheduledTimeAtomFamily: () => scheduledTimeAtom, roomIdToEditingScheduledDelayIdAtomFamily: () => editingScheduledDelayIdAtom, serverMaxDelayMsAtom: atom(null), @@ -533,6 +573,19 @@ function RoomInputHarness({ Transforms.insertText(editor, text); fireEvent.input(screen.getByTestId('room-input-editor')); }; + const setCommand = (command: 'poll' | 'location') => { + editor.children = [ + { + type: 'paragraph' as any, + children: [ + { text: '' }, + { type: 'command' as any, command, children: [{ text: `/${command}` }] }, + { text: '' }, + ], + }, + ]; + fireEvent.input(screen.getByTestId('room-input-editor')); + }; return ( <> + + + + + )} + {!newNameColorDark && newNameColorLight && ( + + + + )} void; onSave?: (color: string | null) => void; disabled?: boolean; @@ -27,18 +28,27 @@ export function NameColorEditor({ description, focusId, current, + newNameColor, onChange, onSave, disabled, }: Readonly) { - const [tempColor, setTempColor] = useState(stripQuotes(current) || undefined); + const [tempColor, setTempColor] = useState( + stripQuotes(newNameColor) || stripQuotes(current) || undefined + ); const [hasChanged, setHasChanged] = useState(false); useEffect(() => { - const sanitized = stripQuotes(current); + // this condition stops infinite loops on input clear when onChange is changing newColor in outer scope + if (!newNameColor && onChange) return; + const sanitized = stripQuotes(newNameColor || current); if (sanitized) setTempColor(sanitized); else setTempColor(undefined); - }, [current]); + }, [current, newNameColor, onChange]); + + useEffect(() => { + setHasChanged(newNameColor !== current); + }, [newNameColor, current]); // Valid in the sense that it should look like an error during input. // It's disruptive to the user to immediately present their input as an error. diff --git a/src/app/features/settings/account/Profile.tsx b/src/app/features/settings/account/Profile.tsx index 652691c69..3b89d2e62 100644 --- a/src/app/features/settings/account/Profile.tsx +++ b/src/app/features/settings/account/Profile.tsx @@ -13,7 +13,7 @@ import { useUserProfile } from '$hooks/useUserProfile'; import { getMxIdLocalPart, mxcUrlToHttp } from '$utils/matrix'; import { UserAvatar } from '$components/user-avatar'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; -import { nameInitials } from '$utils/common'; +import { nameInitials, xor } from '$utils/common'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import { useFilePicker } from '$hooks/useFilePicker'; import { useObjectURL } from '$hooks/useObjectURL'; @@ -40,6 +40,8 @@ import { AnimalCosmetics } from './AnimalCosmetics'; import * as prefix from '$unstable/prefixes'; import { confirm } from '$components/confirm/confirm'; import { AvatarUploadTile } from '$components/avatar-upload-tile/AvatarUploadTile'; +import { accessibleColor } from '$plugins/color'; +import { ThemeKind } from '$hooks/useTheme'; type PronounSet = { summary: string; @@ -426,21 +428,25 @@ function ProfileExtended({ profile, userId }: Readonly) { [mx, presence] ); - const color_on_dark = + const colorOnDark = profile.nameColors?.on_dark ?? - (profile.extended?.[prefix.MATRIX_UNSTABLE_COLORS] as ColorSet | undefined)?.on_dark; - const color_on_light = + (profile.extended?.[prefix.MATRIX_UNSTABLE_COLORS] as ColorSet | undefined)?.on_dark ?? + null; + const colorOnLight = profile.nameColors?.on_light ?? - (profile.extended?.[prefix.MATRIX_UNSTABLE_COLORS] as ColorSet | undefined)?.on_light; + (profile.extended?.[prefix.MATRIX_UNSTABLE_COLORS] as ColorSet | undefined)?.on_light ?? + null; + const [newColorOnDark, setNewColorOnDark] = useState(null); + const [newColorOnLight, setNewColorOnLight] = useState(null); // Deletes the depricated key, the color specific ones should be depricated too at a later date if (profile.nameColor || (profile.extended?.[prefix.MATRIX_UNSTABLE_COLORS] as string)) { const fallback = profile.nameColor ?? (profile.extended?.[prefix.MATRIX_UNSTABLE_COLORS] as string); - if (!color_on_light || !color_on_dark) + if (!newColorOnLight || !newColorOnDark) handleSaveField(prefix.MATRIX_UNSTABLE_COLORS, { - on_dark: color_on_dark ?? fallback, - on_light: color_on_light ?? fallback, + on_dark: newColorOnDark ?? fallback, + on_light: newColorOnLight ?? fallback, }); handleSaveField(prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_PROPERTY_NAME, null); } @@ -466,11 +472,13 @@ function ProfileExtended({ profile, userId }: Readonly) { title="Dark theme Global Name Color" description="Your name's color for a dark theme user." focusId="name-color-dark-theme" - current={color_on_dark} + current={colorOnDark ?? undefined} + newNameColor={newColorOnDark ?? undefined} + onChange={setNewColorOnDark} onSave={(color) => handleSaveField(prefix.MATRIX_UNSTABLE_COLORS, { on_dark: color, - on_light: color_on_light, + on_light: newColorOnLight, }) } /> @@ -478,14 +486,42 @@ function ProfileExtended({ profile, userId }: Readonly) { title="Light theme Global Name Color" description="Your name's color for a light theme user." focusId="name-color-light-theme" - current={color_on_light} + current={colorOnLight ?? undefined} + newNameColor={newColorOnLight ?? undefined} + onChange={setNewColorOnLight} onSave={(color) => handleSaveField(prefix.MATRIX_UNSTABLE_COLORS, { - on_dark: color_on_dark, + on_dark: newColorOnDark, on_light: color, }) } /> + {xor(newColorOnDark, newColorOnLight) && ( + + {!newColorOnDark && newColorOnLight && ( + + )} + {newColorOnDark && !newColorOnLight && ( + + )} + + )} { if (trimmedContent === '') return []; return trimmedContent.split(' '); }; + +export const xor = (left: unknown, right: unknown): boolean => { + return !left !== !right; +}; From 4690ab763d8c89ac55ae348ddd461827f228f542 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Fri, 7 Aug 2026 09:29:21 +0200 Subject: [PATCH 118/135] fix(tauri): defer single-instance callback to avoid SendMessageW deadlock --- src-tauri/src/lib.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 3dc6250fd..5203450e3 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -281,7 +281,13 @@ pub fn run() { // this should always be the first #[cfg(desktop)] let builder = builder.plugin(tauri_plugin_single_instance::init(|app, _argv, _cwd| { - let _ = show_or_create_main_window(app); + let handle = app.clone(); + std::thread::spawn(move || { + let app_handle = handle.clone(); + let _ = handle.run_on_main_thread(move || { + let _ = show_or_create_main_window(&app_handle); + }); + }); })); // macOS needs a standard menu (with the Edit submenu) for keyboard From 1224b0209219245db107cd906845d4156f1384e1 Mon Sep 17 00:00:00 2001 From: "sable-actions[bot]" <268226691+sable-actions[bot]@users.noreply.github.com> Date: Fri, 7 Aug 2026 09:14:44 +0000 Subject: [PATCH 119/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index ac87bf3d0..b5e8757a9 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -20,12 +20,12 @@ "screenshots": [], "versions": [ { - "version": "1.20.1786089755", - "buildVersion": "1.20.1786089755", - "date": "2026-08-07T08:14:10Z", - "size": 18927922, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260807080235-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260807080235" + "version": "1.20.1786093217", + "buildVersion": "1.20.1786093217", + "date": "2026-08-07T09:14:41Z", + "size": 18927758, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260807090017-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260807090017" } ], "appPermissions": { From d1ac1beb9104d512e4210ddbf68b9b9b2f848c24 Mon Sep 17 00:00:00 2001 From: Josie Date: Fri, 7 Aug 2026 07:45:02 +0100 Subject: [PATCH 120/135] Accessible color stuff --- src/app/features/room/message/Message.tsx | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/app/features/room/message/Message.tsx b/src/app/features/room/message/Message.tsx index d4698fd58..9ce8dca54 100644 --- a/src/app/features/room/message/Message.tsx +++ b/src/app/features/room/message/Message.tsx @@ -134,6 +134,7 @@ export type MessageProps = { import { useMenuAnchor } from '$hooks/useMenuAnchor'; import { ThemeKind, useActiveTheme } from '$hooks/useTheme'; import { shouldIgnoreMessageLongPress } from './messageTouch'; +import { accessibleColor } from '$plugins/color'; const clamp = (str: string, len: number) => (str.length > len ? `${str.slice(0, len)}...` : str); @@ -477,6 +478,11 @@ function MessageInternal( false, isVisible ); + + const accessibleNameColor = useCallback((color: any) => + (color) ? accessibleColor(activeTheme.kind, color) : color + , []) + const senderFallbackName = getMxIdLocalPart(senderId) ?? senderId; const resolvedSenderDisplayName = senderDisplayName === senderFallbackName || senderDisplayName === senderId @@ -588,7 +594,7 @@ function MessageInternal( )} {showPmPInfo && ( From 260a00e9ecfdcdba5630445111c28a97b5bbe235 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Fri, 7 Aug 2026 11:51:15 +0200 Subject: [PATCH 121/135] fix: resolve clippy errors from cargo dependency bumps --- src-tauri/src/desktop/tray.rs | 2 +- src-tauri/src/network/native_upload.rs | 6 +++--- src-tauri/src/sentry.rs | 28 +++++++++++++------------- 3 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src-tauri/src/desktop/tray.rs b/src-tauri/src/desktop/tray.rs index 465ec0627..83bc82f0e 100644 --- a/src-tauri/src/desktop/tray.rs +++ b/src-tauri/src/desktop/tray.rs @@ -280,7 +280,7 @@ fn appindicator_available() -> bool { ]; CANDIDATES .iter() - .any(|name| unsafe { libloading::Library::new(name) }.is_ok()) + .any(|name| unsafe { libloading::Library::new(*name) }.is_ok()) } pub fn create_system_tray(app: &AppHandle) -> tauri::Result<()> { diff --git a/src-tauri/src/network/native_upload.rs b/src-tauri/src/network/native_upload.rs index fb1afaa0a..58127b349 100644 --- a/src-tauri/src/network/native_upload.rs +++ b/src-tauri/src/network/native_upload.rs @@ -7,12 +7,12 @@ use std::{ use base64::Engine; use futures_util::StreamExt; -use serde::Serialize; -use tauri::{ipc::Channel, AppHandle, Manager, Runtime}; -use tauri_plugin_http::reqwest::{ +use reqwest::{ header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE}, Body, Client, ClientBuilder, Method, Url, }; +use serde::Serialize; +use tauri::{ipc::Channel, AppHandle, Manager, Runtime}; use tokio::{ fs::{File, OpenOptions}, io::AsyncWriteExt, diff --git a/src-tauri/src/sentry.rs b/src-tauri/src/sentry.rs index dfba7681f..74c117467 100644 --- a/src-tauri/src/sentry.rs +++ b/src-tauri/src/sentry.rs @@ -11,20 +11,20 @@ pub fn init() -> Option { let environment = option_env!("SENTRY_ENVIRONMENT"); let release = option_env!("SENTRY_APP_VERSION").map(|v| format!("sable@{v}")); - let guard = sentry::init(sentry::ClientOptions { - dsn: dsn.parse().ok(), - release: release.map(Into::into), - environment: environment.map(Into::into), - send_default_pii: false, - before_send: Some(std::sync::Arc::new(|event: Event<'static>| { - if CONSENT.load(Ordering::Relaxed) { - Some(event) - } else { - None - } - })), - ..Default::default() - }); + // ClientOptions is #[non_exhaustive]; mutate a default instance instead. + let mut options = sentry::ClientOptions::default(); + options.dsn = dsn.parse().ok(); + options.release = release.map(Into::into); + options.environment = environment.map(Into::into); + options.send_default_pii = false; + options.before_send = Some(std::sync::Arc::new(|event: Event<'static>| { + if CONSENT.load(Ordering::Relaxed) { + Some(event) + } else { + None + } + })); + let guard = sentry::init(options); Some(guard) } From 85526654568c64ae8be9507afe5689f8e08bae5f Mon Sep 17 00:00:00 2001 From: Josie Date: Fri, 7 Aug 2026 10:04:32 +0100 Subject: [PATCH 122/135] Add accessibility tab --- ...ity_tab_and_accessible_color_correction.md | 5 + src/app/components/message/Reply.tsx | 30 ++- src/app/features/room/message/Message.tsx | 23 ++- src/app/features/settings/Settings.tsx | 8 +- .../settings/accessibility/Accessibility.tsx | 181 ++++++++++++++++++ .../features/settings/cosmetics/Cosmetics.tsx | 38 ---- .../features/settings/cosmetics/Themes.tsx | 41 ---- src/app/features/settings/routes.ts | 2 + src/app/features/settings/settingsLink.ts | 15 +- src/app/hooks/useSableCosmetics.ts | 21 +- src/app/plugins/color.ts | 31 ++- src/app/state/settings.ts | 15 +- 12 files changed, 301 insertions(+), 109 deletions(-) create mode 100644 .changeset/add_accessibility_tab_and_accessible_color_correction.md create mode 100644 src/app/features/settings/accessibility/Accessibility.tsx diff --git a/.changeset/add_accessibility_tab_and_accessible_color_correction.md b/.changeset/add_accessibility_tab_and_accessible_color_correction.md new file mode 100644 index 000000000..1ca120853 --- /dev/null +++ b/.changeset/add_accessibility_tab_and_accessible_color_correction.md @@ -0,0 +1,5 @@ +--- +default: minor +--- + +# Add accessibility tab and accessible color correction diff --git a/src/app/components/message/Reply.tsx b/src/app/components/message/Reply.tsx index 96898cdd4..6e7c7fc7f 100644 --- a/src/app/components/message/Reply.tsx +++ b/src/app/components/message/Reply.tsx @@ -68,6 +68,7 @@ import { convertBeeperFormatToOurPerMessageProfile, stripPerMessageProfileFormattedBody, } from '$hooks/usePerMessageProfile'; +import { accessibleColor, accessibleColorWeakCorrection } from '$plugins/color'; const ROOM_REPLY_TIMELINE_EVENT_TYPES = new Set([ EventType.RoomMessage as string, @@ -296,10 +297,29 @@ export const Reply = as<'div', ReplyProps>( const { color: usernameColor, font: usernameFont } = useSableCosmetics(sender ?? '', room); const activeTheme = useActiveTheme(); - const pmpNameColor = - activeTheme.kind === ThemeKind.Dark - ? pmp?.['eu.she-a.color']?.on_dark - : pmp?.['eu.she-a.color']?.on_light; + + const [nameColorLightnessCorrection] = useSetting(settingsAtom, 'nameColorLightnessCorrection'); + const accessibleNameColor = useCallback( + (nameColor: string | undefined) => { + const colorCorrection = + nameColorLightnessCorrection === 'strong' + ? accessibleColor + : nameColorLightnessCorrection === 'weak' + ? accessibleColorWeakCorrection + : () => nameColor; + + return nameColor ? colorCorrection(activeTheme.kind, nameColor) : nameColor; + }, + [nameColorLightnessCorrection, activeTheme] + ); + const pmpNameColor = useMemo(() => { + return accessibleNameColor( + activeTheme.kind === ThemeKind.Dark + ? pmp?.['eu.she-a.color']?.on_dark + : pmp?.['eu.she-a.color']?.on_light + ); + }, [activeTheme, pmp, accessibleNameColor]); + const nicknames = useAtomValue(nicknamesAtom); const cachedProfiles = useAtomValue(profilesCacheAtom); useRoomMemberHydration(room, sender ?? ''); @@ -512,7 +532,7 @@ export const Reply = as<'div', ReplyProps>( )} (str.length > len ? `${str.slice(0, len)}...` : str); @@ -374,6 +374,7 @@ function MessageInternal( const [isVisible, setIsVisible] = useState(() => typeof IntersectionObserver === 'undefined'); const activeTheme = useActiveTheme(); const [renderPersonaColors] = useSetting(settingsAtom, 'renderPersonaColors'); + const [nameColorLightnessCorrection] = useSetting(settingsAtom, 'nameColorLightnessCorrection'); useEffect(() => { const element = messageRef.current; @@ -479,9 +480,19 @@ function MessageInternal( isVisible ); - const accessibleNameColor = useCallback((color: any) => - (color) ? accessibleColor(activeTheme.kind, color) : color - , []) + const accessibleNameColor = useCallback( + (color: string | undefined) => { + if (!color || nameColorLightnessCorrection === 'off') { + return color; + } else if (nameColorLightnessCorrection === 'strong') { + return accessibleColor(activeTheme.kind, color); + } else { + /* weak color correction */ + return accessibleColorWeakCorrection(activeTheme.kind, color); + } + }, + [nameColorLightnessCorrection, activeTheme] + ); const senderFallbackName = getMxIdLocalPart(senderId) ?? senderId; const resolvedSenderDisplayName = @@ -594,7 +605,7 @@ function MessageInternal( )} {showPmPInfo && ( diff --git a/src/app/features/settings/Settings.tsx b/src/app/features/settings/Settings.tsx index 3d9b30689..cc7af5e3d 100644 --- a/src/app/features/settings/Settings.tsx +++ b/src/app/features/settings/Settings.tsx @@ -1,6 +1,6 @@ import { useMemo, useState } from 'react'; import type { ComponentType, ReactNode } from 'react'; -import { DesktopIcon, type IconProps } from '@phosphor-icons/react'; +import { DesktopIcon, PersonSimpleCircleIcon, type IconProps } from '@phosphor-icons/react'; import { Avatar, Box, Button, config, Text } from 'folds'; import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize'; import { useUserProfile } from '$hooks/useUserProfile'; @@ -46,10 +46,12 @@ import { SettingsLinkProvider } from './SettingsLinkContext'; import { useSettingsLinkBaseUrl } from './useSettingsLinkBaseUrl'; import { Desktop } from './desktop'; import { isDesktopTauri } from '$utils/platform'; +import { Accessibility } from './accessibility/Accessibility'; enum SettingsPages { GeneralPage, AccountPage, + AccessibilityPage, PerMessageProfilesPage, NotificationPage, DevicesPage, @@ -79,6 +81,7 @@ const settingsMenuIcons: Record< account: { icon: User }, persona: { icon: UsersThree }, appearance: { icon: Palette }, + accessibility: { icon: PersonSimpleCircleIcon }, notifications: { icon: Bell }, devices: { icon: DevicesIcon }, desktop: { icon: DesktopIcon }, @@ -92,6 +95,7 @@ const settingsMenuIcons: Record< const settingsPageToSectionId: Record = { [SettingsPages.GeneralPage]: 'general', [SettingsPages.AccountPage]: 'account', + [SettingsPages.AccessibilityPage]: 'accessibility', [SettingsPages.PerMessageProfilesPage]: 'persona', [SettingsPages.NotificationPage]: 'notifications', [SettingsPages.DevicesPage]: 'devices', @@ -109,6 +113,7 @@ const settingsSectionIdToPage: Record = { account: SettingsPages.AccountPage, persona: SettingsPages.PerMessageProfilesPage, appearance: SettingsPages.CosmeticsPage, + accessibility: SettingsPages.AccessibilityPage, notifications: SettingsPages.NotificationPage, devices: SettingsPages.DevicesPage, desktop: SettingsPages.DesktopPage, @@ -124,6 +129,7 @@ const settingsSectionComponents = { account: Account, persona: PerMessageProfilePage, appearance: Cosmetics, + accessibility: Accessibility, notifications: Notifications, devices: Devices, desktop: Desktop, diff --git a/src/app/features/settings/accessibility/Accessibility.tsx b/src/app/features/settings/accessibility/Accessibility.tsx new file mode 100644 index 000000000..9b6ae564c --- /dev/null +++ b/src/app/features/settings/accessibility/Accessibility.tsx @@ -0,0 +1,181 @@ +import { useRef } from 'react'; +import { Box, config, Scroll, Text, toRem } from 'folds'; +import { PageContent, SettingsSectionPage } from '$components/page'; +import { SequenceCard, SequenceCardStyle } from '$components/sequence-card'; +import { useSetting } from '$state/hooks/settings'; +import { settingsAtom } from '$state/settings'; +import { SettingTile, SettingToggle } from '$components/setting-tile'; +import { SettingMenuSelector } from '$components/setting-menu-selector'; + +function MotionPreferences() { + const [reducedMotion, setReducedMotion] = useSetting(settingsAtom, 'reducedMotion'); + const [autoplayGifs, setAutoplayGifs] = useSetting(settingsAtom, 'autoplayGifs'); + const [autoplayStickers, setAutoplayStickers] = useSetting(settingsAtom, 'autoplayStickers'); + const [autoplayEmojis, setAutoplayEmojis] = useSetting(settingsAtom, 'autoplayEmojis'); + + return ( + + Motion + + + + + + ); +} + +function TextColorPreferences() { + const [saturation, setSaturation] = useSetting(settingsAtom, 'saturationLevel'); + const [underlineLinks, setUnderlineLinks] = useSetting(settingsAtom, 'underlineLinks'); + + const [renderGlobalColors, setRenderGlobalColors] = useSetting( + settingsAtom, + 'renderGlobalNameColors' + ); + const [renderRoomColors, setRenderRoomColors] = useSetting(settingsAtom, 'renderRoomColors'); + const [renderPersonaColors, setRenderPersonaColors] = useSetting( + settingsAtom, + 'renderPersonaColors' + ); + const [nameColorLightnessCorrection, setNameColorLightnessCorrection] = useSetting( + settingsAtom, + 'nameColorLightnessCorrection' + ); + const [renderRoomFonts, setRenderRoomFonts] = useSetting(settingsAtom, 'renderRoomFonts'); + + return ( + + Text and Color + + + setSaturation(Number.parseInt(e.target.value, 10))} + style={{ + width: toRem(160), + cursor: 'pointer', + appearance: 'none', + height: toRem(6), + borderRadius: config.radii.Pill, + backgroundColor: 'var(--sable-surface-container-line)', + accentColor: 'var(--sable-primary-main)', + }} + /> + } + /> + + + + + + + + + + + } + /> + + + ); +} + +type AccessibilityProps = { + requestBack?: () => void; + requestClose: () => void; +}; + +export function Accessibility({ requestBack, requestClose }: AccessibilityProps) { + const appearanceScrollRef = useRef(null); + + return ( + + + + + + + + + + + + + ); +} diff --git a/src/app/features/settings/cosmetics/Cosmetics.tsx b/src/app/features/settings/cosmetics/Cosmetics.tsx index ea3ef5bb7..9e6a69b90 100644 --- a/src/app/features/settings/cosmetics/Cosmetics.tsx +++ b/src/app/features/settings/cosmetics/Cosmetics.tsx @@ -407,16 +407,6 @@ function IdentityCosmetics() { ); const [showPronouns, setShowPronouns] = useSetting(settingsAtom, 'showPronouns'); const [parsePronouns, setParsePronouns] = useSetting(settingsAtom, 'parsePronouns'); - const [renderGlobalColors, setRenderGlobalColors] = useSetting( - settingsAtom, - 'renderGlobalNameColors' - ); - const [renderRoomColors, setRenderRoomColors] = useSetting(settingsAtom, 'renderRoomColors'); - const [renderPersonaColors, setRenderPersonaColors] = useSetting( - settingsAtom, - 'renderPersonaColors' - ); - const [renderRoomFonts, setRenderRoomFonts] = useSetting(settingsAtom, 'renderRoomFonts'); const [uniformIcons, setUniformIcons] = useSetting(settingsAtom, 'uniformIcons'); return ( @@ -477,34 +467,6 @@ function IdentityCosmetics() { after={} /> - - - - - - - - - - { if (!room || !userId) return { color: undefined, font: undefined }; - let finalColor = isUserHero ? profile.heroNameColor : profile.resolvedColor; + const accessibleNameColor = (color: string | undefined) => { + if (!color || nameColorLightnessCorrection === 'off') { + return color; + } else if (nameColorLightnessCorrection === 'strong') { + return accessibleColor(theme.kind, color); + } else { + /* weak color correction */ + return accessibleColorWeakCorrection(theme.kind, color); + } + }; + + let finalColor = accessibleNameColor( + isUserHero ? profile.heroNameColor : profile.resolvedColor + ); if (!finalColor) { const memberPowerTag = getPowerTag(userId); finalColor = memberPowerTag?.color @@ -51,5 +68,7 @@ export function useSableCosmetics( profile.resolvedFont, getPowerTag, accessibleTagColors, + nameColorLightnessCorrection, + theme.kind, ]); } diff --git a/src/app/plugins/color.ts b/src/app/plugins/color.ts index 97b756e3a..869683681 100644 --- a/src/app/plugins/color.ts +++ b/src/app/plugins/color.ts @@ -1,16 +1,35 @@ import chroma from 'chroma-js'; import { ThemeKind } from '$hooks/useTheme'; +const clampColor = ( + lightness: number, + lightCap: number, + darkCap: number, + themeKind: ThemeKind +): number => { + if (themeKind === ThemeKind.Dark && lightness < darkCap) { + lightness = darkCap; + } + if (themeKind === ThemeKind.Light && lightness > lightCap) { + lightness = lightCap; + } + return lightness; +}; + export const accessibleColor = (themeKind: ThemeKind, color: string): string => { if (!chroma.valid(color)) return color; let lightness = chroma(color).lab()[0]; - if (themeKind === ThemeKind.Dark && lightness < 60) { - lightness = 60; - } - if (themeKind === ThemeKind.Light && lightness > 50) { - lightness = 50; - } + lightness = clampColor(lightness, 50, 60, themeKind); + + return chroma(color).set('lab.l', lightness).hex(); +}; + +export const accessibleColorWeakCorrection = (themeKind: ThemeKind, color: string): string => { + if (!chroma.valid(color)) return color; + + let lightness = chroma(color).lab()[0]; + lightness = clampColor(lightness, 70, 40, themeKind); return chroma(color).set('lab.l', lightness).hex(); }; diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index 1833db37e..b4d106c3f 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -216,11 +216,6 @@ export interface Settings { showEasterEggs: boolean; hideReads: boolean; emojiSuggestThreshold: number; - underlineLinks: boolean; - reducedMotion: boolean; - autoplayGifs: boolean; - autoplayStickers: boolean; - autoplayEmojis: boolean; oldSidebar: boolean; pixelatedImageRendering: PixelatedImageRenderingMode; incomingInlineImagesDefaultHeight: number; @@ -262,6 +257,14 @@ export interface Settings { isShowingAllRoomsInHome: boolean; sendIndividualAttachmentAsCaption: boolean; + // accessibility stuff + underlineLinks: boolean; + reducedMotion: boolean; + autoplayGifs: boolean; + autoplayStickers: boolean; + autoplayEmojis: boolean; + nameColorLightnessCorrection: 'off' | 'weak' | 'strong'; + // furry stuff renderAnimals: boolean; animalKind: string | undefined; @@ -443,6 +446,8 @@ export const defaultSettings: Settings = { widgetSidebarWidth: 420, isShowingAllRoomsInHome: false, sendIndividualAttachmentAsCaption: true, + nameColorLightnessCorrection: 'off', + // furry stuff renderAnimals: true, animalKind: undefined, From 8236bcf4959a1ee51f16097ac93f328f0d947c4d Mon Sep 17 00:00:00 2001 From: "sable-actions[bot]" <268226691+sable-actions[bot]@users.noreply.github.com> Date: Fri, 7 Aug 2026 11:02:50 +0000 Subject: [PATCH 123/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index b5e8757a9..f19824fd2 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -20,12 +20,12 @@ "screenshots": [], "versions": [ { - "version": "1.20.1786093217", - "buildVersion": "1.20.1786093217", - "date": "2026-08-07T09:14:41Z", - "size": 18927758, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260807090017-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260807090017" + "version": "1.20.1786099774", + "buildVersion": "1.20.1786099774", + "date": "2026-08-07T11:02:48Z", + "size": 19105890, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260807104934-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260807104934" } ], "appPermissions": { From 39e0ef2cb4a4881c5f951b4cbbd08844b0b4bb50 Mon Sep 17 00:00:00 2001 From: "sable-actions[bot]" <268226691+sable-actions[bot]@users.noreply.github.com> Date: Fri, 7 Aug 2026 11:28:57 +0000 Subject: [PATCH 124/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index f19824fd2..a4553cb98 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -20,12 +20,12 @@ "screenshots": [], "versions": [ { - "version": "1.20.1786099774", - "buildVersion": "1.20.1786099774", - "date": "2026-08-07T11:02:48Z", - "size": 19105890, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260807104934-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260807104934" + "version": "1.20.1786101241", + "buildVersion": "1.20.1786101241", + "date": "2026-08-07T11:28:55Z", + "size": 19107453, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260807111401-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260807111401" } ], "appPermissions": { From 5a7945e2da3d37a50fc5b938e8dbc81bd1459c13 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Fri, 7 Aug 2026 15:35:34 +0200 Subject: [PATCH 125/135] fix(composer): detect autocomplete from onChange for mobile keyboards --- src/app/features/room/RoomInput.tsx | 69 ++++++++++--------- .../features/room/message/MessageEditor.tsx | 16 +++-- 2 files changed, 47 insertions(+), 38 deletions(-) diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 8bb444479..c22e505b6 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -607,8 +607,42 @@ export const RoomInput = forwardRef( const dropZoneVisible = useFileDropZone(fileDropContainerRef, handleFiles); const [hasText, setHasText] = useState(false); const lastEncryptionPreparationAt = useRef(0); + const detectAutocomplete = useCallback(() => { + const firstPosition = Editor.start(editor, []); + const secondChar = Editor.after(editor, firstPosition, { + distance: 2, + unit: 'character', + }); + const quickReactPrefix = Editor.string( + editor, + Editor.range(editor, firstPosition, secondChar) + ); + if (quickReactPrefix === '+#') { + setQuickTextReact(true); + setAutocompleteQuery(undefined); + return; + } + setQuickTextReact(false); + + const prevWordRange = getPrevWorldRange(editor); + if (!prevWordRange) { + setAutocompleteQuery(undefined); + return; + } + + const isRangeAtBeginning = !Point.isAfter(Range.start(prevWordRange), firstPosition); + const query = + (isRangeAtBeginning + ? getAutocompleteQuery(editor, prevWordRange, BEGINNING_AUTOCOMPLETE_PREFIXES) + : undefined) ?? + getAutocompleteQuery(editor, prevWordRange, ANYWHERE_AUTOCOMPLETE_PREFIXES); + + setAutocompleteQuery(query); + }, [editor]); + const handleEditorChange = useCallback(() => { setHasText(!isEmptyEditor(editor)); + detectAutocomplete(); if (!room.hasEncryptionStateEvent()) return; const now = Date.now(); @@ -616,7 +650,7 @@ export const RoomInput = forwardRef( lastEncryptionPreparationAt.current = now; mx.getCrypto()?.prepareToEncrypt(room); - }, [editor, mx, room]); + }, [editor, detectAutocomplete, mx, room]); const hasContent = hasText || selectedFiles.length > 0; const isComposing = useComposingCheck(); @@ -1774,38 +1808,9 @@ export const RoomInput = forwardRef( sendTypingStatus(!isEmptyEditor(editor)); } - const firstPosition = Editor.start(editor, []); - const secondChar = Editor.after(editor, firstPosition, { - distance: 2, - unit: 'character', - }); - const quickReactPrefix = Editor.string( - editor, - Editor.range(editor, firstPosition, secondChar) - ); - if (quickReactPrefix === '+#') { - setQuickTextReact(true); - setAutocompleteQuery(undefined); - return; - } - setQuickTextReact(false); - - const prevWordRange = getPrevWorldRange(editor); - if (!prevWordRange) { - setAutocompleteQuery(undefined); - return; - } - - const isRangeAtBeginning = !Point.isAfter(Range.start(prevWordRange), firstPosition); - const query = - (isRangeAtBeginning - ? getAutocompleteQuery(editor, prevWordRange, BEGINNING_AUTOCOMPLETE_PREFIXES) - : undefined) ?? - getAutocompleteQuery(editor, prevWordRange, ANYWHERE_AUTOCOMPLETE_PREFIXES); - - setAutocompleteQuery(query); + detectAutocomplete(); }, - [editor, sendTypingStatus, hideActivity] + [editor, sendTypingStatus, hideActivity, detectAutocomplete] ); const handleEmoticonSelect = (key: string, shortcode: string) => { diff --git a/src/app/features/room/message/MessageEditor.tsx b/src/app/features/room/message/MessageEditor.tsx index fe150cff5..f72c66e36 100644 --- a/src/app/features/room/message/MessageEditor.tsx +++ b/src/app/features/room/message/MessageEditor.tsx @@ -337,6 +337,14 @@ export const MessageEditor = as<'div', MessageEditorProps>( [enterForNewline, isComposing, editor, handleSave, onCancel] ); + const detectAutocomplete = useCallback(() => { + const prevWordRange = getPrevWorldRange(editor); + const query = prevWordRange + ? getAutocompleteQuery(editor, prevWordRange, ANYWHERE_AUTOCOMPLETE_PREFIXES) + : undefined; + setAutocompleteQuery(query); + }, [editor]); + const handleKeyUp: KeyboardEventHandler = useCallback( (evt) => { if (isKeyHotkey('escape', evt)) { @@ -344,13 +352,9 @@ export const MessageEditor = as<'div', MessageEditorProps>( return; } - const prevWordRange = getPrevWorldRange(editor); - const query = prevWordRange - ? getAutocompleteQuery(editor, prevWordRange, ANYWHERE_AUTOCOMPLETE_PREFIXES) - : undefined; - setAutocompleteQuery(query); + detectAutocomplete(); }, - [editor] + [detectAutocomplete] ); const handleCloseAutocomplete = useCallback(() => { From f7d1a45bbfa70cd4d520cc585be42ecaa061c3b5 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Fri, 7 Aug 2026 13:36:04 +0200 Subject: [PATCH 126/135] fix: migrate Android JNI bridge to jni 0.22 API --- src-tauri/src/mobile.rs | 87 ++++++++++++++++++++++------------------- 1 file changed, 46 insertions(+), 41 deletions(-) diff --git a/src-tauri/src/mobile.rs b/src-tauri/src/mobile.rs index fa2b42dad..04b87c1bd 100644 --- a/src-tauri/src/mobile.rs +++ b/src-tauri/src/mobile.rs @@ -7,19 +7,22 @@ use std::sync::OnceLock; use jni::objects::{JObject, JValue}; -use jni::{JNIEnv, JavaVM}; +use jni::strings::JNIString; +use jni::{jni_sig, jni_str, EnvUnowned, JavaVM}; static JAVA_VM: OnceLock = OnceLock::new(); // Called by MainActivity.onCreate to cache the JavaVM for later callbacks. #[no_mangle] pub extern "system" fn Java_moe_sable_client_MainActivity_nativeInitStatusBar( - env: JNIEnv, + mut env: EnvUnowned, _this: JObject, ) { - if let Ok(vm) = env.get_java_vm() { + let _ = env.with_env(|env| { + let vm = env.get_java_vm()?; let _ = JAVA_VM.set(vm); - } + Ok::<_, jni::errors::Error>(()) + }); } /// `color` is a packed ARGB int (as produced by Android's `Color`). @@ -52,49 +55,51 @@ pub(crate) fn play_notification_sound(kind: String) -> Result<(), String> { _ => 0, }; let vm = JAVA_VM.get().ok_or("java vm not initialized")?; - let mut env = vm.attach_current_thread().map_err(|e| e.to_string())?; - - let result = env.call_static_method( - "moe/sable/client/MainActivity", - "playNotificationSoundNative", - "(I)V", - &[JValue::Int(code)], - ); - if result.is_err() { - let _ = env.exception_clear(); - } - result.map_err(|e| e.to_string())?; - - Ok(()) + vm.attach_current_thread(|env| { + let result = env.call_static_method( + jni_str!("moe/sable/client/MainActivity"), + jni_str!("playNotificationSoundNative"), + jni_sig!("(I)V"), + &[JValue::Int(code)], + ); + if result.is_err() { + let _ = env.exception_clear(); + } + result.map(|_| ()) + }) + .map_err(|e| e.to_string()) } fn call_bar_color(method: &str, color: u32) -> Result<(), String> { let vm = JAVA_VM.get().ok_or("java vm not initialized")?; - let mut env = vm.attach_current_thread().map_err(|e| e.to_string())?; - - let result = env.call_static_method( - "moe/sable/client/MainActivity", - method, - "(I)V", - &[JValue::Int(color as i32)], - ); - if result.is_err() { - let _ = env.exception_clear(); - } - result.map_err(|e| e.to_string())?; - - Ok(()) + vm.attach_current_thread(|env| { + let result = env.call_static_method( + jni_str!("moe/sable/client/MainActivity"), + JNIString::new(method), + jni_sig!("(I)V"), + &[JValue::Int(color as i32)], + ); + if result.is_err() { + let _ = env.exception_clear(); + } + result.map(|_| ()) + }) + .map_err(|e| e.to_string()) } fn call_static_method(method: &str) -> Result<(), String> { let vm = JAVA_VM.get().ok_or("java vm not initialized")?; - let mut env = vm.attach_current_thread().map_err(|e| e.to_string())?; - - let result = env.call_static_method("moe/sable/client/MainActivity", method, "()V", &[]); - if result.is_err() { - let _ = env.exception_clear(); - } - result.map_err(|e| e.to_string())?; - - Ok(()) + vm.attach_current_thread(|env| { + let result = env.call_static_method( + jni_str!("moe/sable/client/MainActivity"), + JNIString::new(method), + jni_sig!("()V"), + &[], + ); + if result.is_err() { + let _ = env.exception_clear(); + } + result.map(|_| ()) + }) + .map_err(|e| e.to_string()) } From 6297a4e16e7eeb3bd5f9529ac4f439b5838f2116 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Fri, 7 Aug 2026 16:02:00 +0200 Subject: [PATCH 127/135] fix(tauri): pin reqwest to 0.12 so native uploads keep rustls TLS --- src-tauri/Cargo.lock | 20 ++++++++++++++++++-- src-tauri/Cargo.toml | 2 +- src-tauri/src/network/native_upload.rs | 6 +++--- 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 1b56c7686..0034a495d 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -5188,6 +5188,7 @@ dependencies = [ "cookie_store", "encoding_rs", "futures-core", + "futures-util", "h2 0.4.15", "http 1.4.2", "http-body 1.1.0", @@ -5209,12 +5210,14 @@ dependencies = [ "sync_wrapper 1.0.2", "tokio", "tokio-rustls", + "tokio-util", "tower 0.5.3", "tower-http 0.6.11", "tower-service", "url", "wasm-bindgen", "wasm-bindgen-futures", + "wasm-streams 0.4.2", "web-sys", "webpki-roots", ] @@ -5254,7 +5257,7 @@ dependencies = [ "url", "wasm-bindgen", "wasm-bindgen-futures", - "wasm-streams", + "wasm-streams 0.5.0", "web-sys", ] @@ -5462,7 +5465,7 @@ dependencies = [ "objc2-photos", "percent-encoding", "regex", - "reqwest 0.13.4", + "reqwest 0.12.28", "sentry", "serde", "serde_json", @@ -8190,6 +8193,19 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "wasm-streams" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "wasm-streams" version = "0.5.0" diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index cd5ed5d9a..7ab48a7ae 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -41,7 +41,7 @@ percent-encoding = "2" # Enables `stream` (for native_upload's `Body::wrap_stream`) on the reqwest that # tauri-plugin-http pulls in without it. default-features = false keeps # openssl-sys out of the Android cross-compile. -reqwest = { version = "0.13", default-features = false, features = ["stream"] } +reqwest = { version = "0.12", default-features = false, features = ["stream"] } async-stream = "0.3" base64 = "0.23" tokio-util = { version = "0.7", features = ["codec"] } diff --git a/src-tauri/src/network/native_upload.rs b/src-tauri/src/network/native_upload.rs index 58127b349..fb1afaa0a 100644 --- a/src-tauri/src/network/native_upload.rs +++ b/src-tauri/src/network/native_upload.rs @@ -7,12 +7,12 @@ use std::{ use base64::Engine; use futures_util::StreamExt; -use reqwest::{ +use serde::Serialize; +use tauri::{ipc::Channel, AppHandle, Manager, Runtime}; +use tauri_plugin_http::reqwest::{ header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE}, Body, Client, ClientBuilder, Method, Url, }; -use serde::Serialize; -use tauri::{ipc::Channel, AppHandle, Manager, Runtime}; use tokio::{ fs::{File, OpenOptions}, io::AsyncWriteExt, From 20ade55752c9af328a883ef71f297bd1bc62eb43 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Fri, 7 Aug 2026 16:33:11 +0200 Subject: [PATCH 128/135] fix(push): resolve the account for pushes that omit user_id --- src/sw-media-auth-recovery.test.ts | 44 ++++++++++++++++++++++++++++++ src/sw.ts | 17 +++++++++--- 2 files changed, 57 insertions(+), 4 deletions(-) diff --git a/src/sw-media-auth-recovery.test.ts b/src/sw-media-auth-recovery.test.ts index 7d5720958..1b27b2a9b 100644 --- a/src/sw-media-auth-recovery.test.ts +++ b/src/sw-media-auth-recovery.test.ts @@ -82,6 +82,50 @@ describe('service worker media auth recovery', () => { expect(fetch).not.toHaveBeenCalled(); }); + it('resolves a push without user_id against the only known account', async () => { + await swTestHooks.setSession( + 'alice-window', + 'alice-token', + 'https://matrix.example.org', + '@alice:example.org' + ); + + await expect(swTestHooks.getSessionForPush(undefined)).resolves.toMatchObject({ + accessToken: 'alice-token', + }); + }); + + it('resolves a push without user_id from cache after an sw restart', async () => { + persistedSessions = JSON.stringify({ + '@alice:example.org': { + accessToken: 'alice-token', + baseUrl: 'https://matrix.example.org', + userId: '@alice:example.org', + }, + }); + + await expect(swTestHooks.getSessionForPush(undefined)).resolves.toMatchObject({ + accessToken: 'alice-token', + }); + }); + + it('refuses to guess an account for a push without user_id when several are signed in', async () => { + await swTestHooks.setSession( + 'alice-window', + 'alice-token', + 'https://matrix.example.org', + '@alice:example.org' + ); + await swTestHooks.setSession( + 'bob-window', + 'bob-token', + 'https://matrix.example.org', + '@bob:example.org' + ); + + await expect(swTestHooks.getSessionForPush(undefined)).resolves.toBeUndefined(); + }); + it('removes a stale persisted account when a client switches users', async () => { await swTestHooks.setSession( 'client-a', diff --git a/src/sw.ts b/src/sw.ts index c11abfc17..2f23eeb47 100644 --- a/src/sw.ts +++ b/src/sw.ts @@ -382,9 +382,17 @@ function mxcToNotificationUrl(mxcUrl: string, baseUrl: string): string | undefin return `${baseUrl}/_matrix/media/v3/thumbnail/${encodeURIComponent(server)}/${encodeURIComponent(mediaId)}?width=96&height=96&method=crop`; } -async function getSessionForPush(userId: string): Promise { - const liveSession = [...sessions.values()].find((session) => session.userId === userId); - return liveSession ?? loadPersistedSession(userId); +async function getSessionForPush(userId?: string): Promise { + if (userId) { + const liveSession = [...sessions.values()].find((session) => session.userId === userId); + return liveSession ?? loadPersistedSession(userId); + } + + const liveAccounts = new Set([...sessions.values()].map((session) => session.userId)); + if (liveAccounts.size === 1) return sessions.values().next().value; + + const persisted = Object.values(await loadPersistedSessions()); + return persisted.length === 1 ? persisted[0] : undefined; } /** @@ -450,7 +458,7 @@ async function handleMinimalPushPayload( userId: string | undefined, windowClients: readonly Client[] ): Promise { - const session = userId ? await getSessionForPush(userId) : undefined; + const session = await getSessionForPush(userId); if (!session) { // No session anywhere — app was never opened since install, or the user logged out. @@ -859,6 +867,7 @@ function unavailableAuthenticatedMediaResponse(): Response { } export const swTestHooks = { + getSessionForPush, requestSessionWithTimeout, respondWithMediaAuthRecovery, setSession, From 1f9a9c8cee628762758265d40ffe00d29fcdb0be Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Fri, 7 Aug 2026 16:28:54 +0200 Subject: [PATCH 129/135] fix(sync): only pause background sync on mobile --- src/app/hooks/useBackgroundSyncPause.test.tsx | 43 ++++++++++++++----- src/app/hooks/useBackgroundSyncPause.ts | 3 +- src/client/slidingSync.test.ts | 17 ++++++++ src/client/slidingSync.ts | 2 +- 4 files changed, 53 insertions(+), 12 deletions(-) diff --git a/src/app/hooks/useBackgroundSyncPause.test.tsx b/src/app/hooks/useBackgroundSyncPause.test.tsx index 79362eca8..97410a6c1 100644 --- a/src/app/hooks/useBackgroundSyncPause.test.tsx +++ b/src/app/hooks/useBackgroundSyncPause.test.tsx @@ -1,16 +1,25 @@ import { describe, expect, it, vi, beforeEach } from 'vitest'; import { renderHook } from '@testing-library/react'; -const { pause, resume, getSlidingSyncManager, listen, listenOff, mockIsTauri, mockCallEmbed } = - vi.hoisted(() => ({ - pause: vi.fn<() => void>(), - resume: vi.fn<() => void>(), - getSlidingSyncManager: vi.fn<() => unknown>(), - listen: vi.fn<(_event: string, _cb: () => void) => Promise<() => void>>(), - listenOff: vi.fn<() => void>(), - mockIsTauri: { value: false }, - mockCallEmbed: { value: undefined as unknown }, - })); +const { + pause, + resume, + getSlidingSyncManager, + listen, + listenOff, + mockIsTauri, + mockIsMobileTauri, + mockCallEmbed, +} = vi.hoisted(() => ({ + pause: vi.fn<() => void>(), + resume: vi.fn<() => void>(), + getSlidingSyncManager: vi.fn<() => unknown>(), + listen: vi.fn<(_event: string, _cb: () => void) => Promise<() => void>>(), + listenOff: vi.fn<() => void>(), + mockIsTauri: { value: false }, + mockIsMobileTauri: { value: true }, + mockCallEmbed: { value: undefined as unknown }, +})); vi.mock('$client/initMatrix', () => ({ getSlidingSyncManager })); @@ -28,6 +37,8 @@ vi.mock('@tauri-apps/api/event', () => ({ vi.mock('@tauri-apps/api/core', () => ({ isTauri: () => mockIsTauri.value })); +vi.mock('$utils/platform', () => ({ isMobileTauri: () => mockIsMobileTauri.value })); + import { useBackgroundSyncPause } from './useBackgroundSyncPause'; const setVisibility = (state: 'visible' | 'hidden') => @@ -42,6 +53,7 @@ describe('useBackgroundSyncPause', () => { listen.mockReset().mockResolvedValue(listenOff); getSlidingSyncManager.mockReset().mockReturnValue({ pause, resume }); mockIsTauri.value = false; + mockIsMobileTauri.value = true; mockCallEmbed.value = undefined; }); @@ -88,6 +100,17 @@ describe('useBackgroundSyncPause', () => { expect(resume).toHaveBeenCalled(); }); + it('keeps polling when a browser tab is hidden', () => { + mockIsMobileTauri.value = false; + setVisibility('visible'); + renderHook(() => useBackgroundSyncPause({ clientRunning: true } as never)); + + setVisibility('hidden'); + document.dispatchEvent(new Event('visibilitychange')); + + expect(pause).not.toHaveBeenCalled(); + }); + it('does nothing without a client', () => { renderHook(() => useBackgroundSyncPause(undefined)); diff --git a/src/app/hooks/useBackgroundSyncPause.ts b/src/app/hooks/useBackgroundSyncPause.ts index 21486c929..5c904a443 100644 --- a/src/app/hooks/useBackgroundSyncPause.ts +++ b/src/app/hooks/useBackgroundSyncPause.ts @@ -4,6 +4,7 @@ import { TauriEvent, listen } from '@tauri-apps/api/event'; import { isTauri } from '@tauri-apps/api/core'; import type { MatrixClient } from '$types/matrix-sdk'; import { getSlidingSyncManager } from '$client/initMatrix'; +import { isMobileTauri } from '$utils/platform'; import { callEmbedAtom } from '../state/callEmbed'; /** @@ -17,7 +18,7 @@ export const useBackgroundSyncPause = (mx: MatrixClient | undefined): void => { const callActive = callEmbed !== undefined; useEffect(() => { - if (!mx) return undefined; + if (!mx || !isMobileTauri()) return undefined; const resume = () => getSlidingSyncManager(mx)?.resume(); const applyVisibility = () => { diff --git a/src/client/slidingSync.test.ts b/src/client/slidingSync.test.ts index fe67f79ea..f89533023 100644 --- a/src/client/slidingSync.test.ts +++ b/src/client/slidingSync.test.ts @@ -1445,6 +1445,23 @@ describe('SlidingSyncManager pause/resume', () => { } }); + it('keeps the watchdog silent when the aborted poll emits a lifecycle event', () => { + vi.useFakeTimers(); + try { + const manager = makeManager(makeMockMx()); + manager.attach(); + manager.pause(); + mocks.slidingSyncInstance.resend.mockClear(); + + fireLifecycle(SlidingSyncState.RequestFinished, {}); + vi.advanceTimersByTime(DEFAULT_DEADLINE_MS * 3); + + expect(mocks.slidingSyncInstance.resend).not.toHaveBeenCalled(); + } finally { + vi.useRealTimers(); + } + }); + it('re-arms the poll watchdog on resume', () => { vi.useFakeTimers(); try { diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index 87dcb23ce..b7e88c1b3 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -706,7 +706,7 @@ export class SlidingSyncManager { * `continue`s without emitting a lifecycle event. */ private armPollWatchdog(): void { - if (this.disposed) return; + if (this.disposed || this.paused) return; globalThis.clearTimeout(this.pollWatchdogTimer); this.pollWatchdogTimer = globalThis.setTimeout(() => { this.pollWatchdogTimer = undefined; From ba82664dacb41a06b3a8ffe2f2b8b5198134c68d Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Fri, 7 Aug 2026 16:32:49 +0200 Subject: [PATCH 130/135] fix(settings): correct accessibility settings links and dedupe name color correction --- src/app/components/message/Reply.tsx | 27 ++++------------- src/app/components/user-profile/UserHero.tsx | 6 +++- src/app/features/room/message/Message.tsx | 17 ++--------- .../settings/accessibility/Accessibility.tsx | 10 +++++-- .../features/settings/cosmetics/Themes.tsx | 29 +------------------ .../settings/settingTileFocusCoverage.test.ts | 1 + .../features/settings/settingsLink.test.ts | 28 ++++++++++++++++++ src/app/features/settings/settingsLink.ts | 21 ++++++++++---- src/app/hooks/useAccessibleNameColor.ts | 21 ++++++++++++++ src/app/hooks/useMemberPowerTag.ts | 10 ++++--- src/app/hooks/useSableCosmetics.ts | 20 ++----------- 11 files changed, 96 insertions(+), 94 deletions(-) create mode 100644 src/app/hooks/useAccessibleNameColor.ts diff --git a/src/app/components/message/Reply.tsx b/src/app/components/message/Reply.tsx index 6e7c7fc7f..821eb1c0d 100644 --- a/src/app/components/message/Reply.tsx +++ b/src/app/components/message/Reply.tsx @@ -68,7 +68,7 @@ import { convertBeeperFormatToOurPerMessageProfile, stripPerMessageProfileFormattedBody, } from '$hooks/usePerMessageProfile'; -import { accessibleColor, accessibleColorWeakCorrection } from '$plugins/color'; +import { useAccessibleNameColor } from '$hooks/useAccessibleNameColor'; const ROOM_REPLY_TIMELINE_EVENT_TYPES = new Set([ EventType.RoomMessage as string, @@ -298,27 +298,12 @@ export const Reply = as<'div', ReplyProps>( const { color: usernameColor, font: usernameFont } = useSableCosmetics(sender ?? '', room); const activeTheme = useActiveTheme(); - const [nameColorLightnessCorrection] = useSetting(settingsAtom, 'nameColorLightnessCorrection'); - const accessibleNameColor = useCallback( - (nameColor: string | undefined) => { - const colorCorrection = - nameColorLightnessCorrection === 'strong' - ? accessibleColor - : nameColorLightnessCorrection === 'weak' - ? accessibleColorWeakCorrection - : () => nameColor; - - return nameColor ? colorCorrection(activeTheme.kind, nameColor) : nameColor; - }, - [nameColorLightnessCorrection, activeTheme] - ); + const accessibleNameColor = useAccessibleNameColor(activeTheme.kind); const pmpNameColor = useMemo(() => { - return accessibleNameColor( - activeTheme.kind === ThemeKind.Dark - ? pmp?.['eu.she-a.color']?.on_dark - : pmp?.['eu.she-a.color']?.on_light - ); - }, [activeTheme, pmp, accessibleNameColor]); + return activeTheme.kind === ThemeKind.Dark + ? pmp?.['eu.she-a.color']?.on_dark + : pmp?.['eu.she-a.color']?.on_light; + }, [activeTheme, pmp]); const nicknames = useAtomValue(nicknamesAtom); const cachedProfiles = useAtomValue(profilesCacheAtom); diff --git a/src/app/components/user-profile/UserHero.tsx b/src/app/components/user-profile/UserHero.tsx index c0781101e..0a1251161 100644 --- a/src/app/components/user-profile/UserHero.tsx +++ b/src/app/components/user-profile/UserHero.tsx @@ -19,6 +19,8 @@ import { BreakWord, LineClamp3 } from '$styles/Text.css'; import type { UserPresence } from '$hooks/useUserPresence'; import { useRoom } from '$hooks/useRoom'; import { useSableCosmetics } from '$hooks/useSableCosmetics'; +import { useActiveTheme } from '$hooks/useTheme'; +import { useAccessibleNameColor } from '$hooks/useAccessibleNameColor'; import { useNickname } from '$hooks/useNickname'; import { useRenderableMediaUrl } from '$hooks/useRenderableMediaUrl'; import { ImageViewer } from '$components/image-viewer'; @@ -358,6 +360,8 @@ export function GlobalUserHeroName({ displayName, userId, server }: UserHeroName const username = getMxIdLocalPart(userId); const nick = useNickname(userId); const profile = useUserProfile(userId); + const activeTheme = useActiveTheme(); + const accessibleNameColor = useAccessibleNameColor(activeTheme.kind); const shownName = nick ?? displayName ?? username ?? userId; @@ -367,7 +371,7 @@ export function GlobalUserHeroName({ displayName, userId, server }: UserHeroName server={server} shownName={shownName} font={profile.resolvedFont} - color={profile.resolvedColor} + color={accessibleNameColor(profile.resolvedColor)} /> ); } diff --git a/src/app/features/room/message/Message.tsx b/src/app/features/room/message/Message.tsx index dc1880bce..29575fe3d 100644 --- a/src/app/features/room/message/Message.tsx +++ b/src/app/features/room/message/Message.tsx @@ -133,8 +133,8 @@ export type MessageProps = { import { useMenuAnchor } from '$hooks/useMenuAnchor'; import { ThemeKind, useActiveTheme } from '$hooks/useTheme'; +import { useAccessibleNameColor } from '$hooks/useAccessibleNameColor'; import { shouldIgnoreMessageLongPress } from './messageTouch'; -import { accessibleColor, accessibleColorWeakCorrection } from '$plugins/color'; const clamp = (str: string, len: number) => (str.length > len ? `${str.slice(0, len)}...` : str); @@ -374,7 +374,6 @@ function MessageInternal( const [isVisible, setIsVisible] = useState(() => typeof IntersectionObserver === 'undefined'); const activeTheme = useActiveTheme(); const [renderPersonaColors] = useSetting(settingsAtom, 'renderPersonaColors'); - const [nameColorLightnessCorrection] = useSetting(settingsAtom, 'nameColorLightnessCorrection'); useEffect(() => { const element = messageRef.current; @@ -480,19 +479,7 @@ function MessageInternal( isVisible ); - const accessibleNameColor = useCallback( - (color: string | undefined) => { - if (!color || nameColorLightnessCorrection === 'off') { - return color; - } else if (nameColorLightnessCorrection === 'strong') { - return accessibleColor(activeTheme.kind, color); - } else { - /* weak color correction */ - return accessibleColorWeakCorrection(activeTheme.kind, color); - } - }, - [nameColorLightnessCorrection, activeTheme] - ); + const accessibleNameColor = useAccessibleNameColor(activeTheme.kind); const senderFallbackName = getMxIdLocalPart(senderId) ?? senderId; const resolvedSenderDisplayName = diff --git a/src/app/features/settings/accessibility/Accessibility.tsx b/src/app/features/settings/accessibility/Accessibility.tsx index 9b6ae564c..4edceb7f4 100644 --- a/src/app/features/settings/accessibility/Accessibility.tsx +++ b/src/app/features/settings/accessibility/Accessibility.tsx @@ -162,12 +162,16 @@ type AccessibilityProps = { }; export function Accessibility({ requestBack, requestClose }: AccessibilityProps) { - const appearanceScrollRef = useRef(null); + const accessibilityScrollRef = useRef(null); return ( - + - + diff --git a/src/app/features/settings/cosmetics/Themes.tsx b/src/app/features/settings/cosmetics/Themes.tsx index 068640b83..cb5c4aca7 100644 --- a/src/app/features/settings/cosmetics/Themes.tsx +++ b/src/app/features/settings/cosmetics/Themes.tsx @@ -1,6 +1,6 @@ import type { ChangeEventHandler, KeyboardEventHandler } from 'react'; import { type MouseEventHandler, useEffect, useMemo, useState } from 'react'; -import { Box, Chip, config, Input, Switch, Text, toRem } from 'folds'; +import { Box, Chip, Input, Switch, Text, toRem } from 'folds'; import { CaretDown, menuIcon } from '$components/icons/phosphor'; import { isKeyHotkey } from 'is-hotkey'; @@ -211,7 +211,6 @@ const onNumberInputKeyDown = }; function ThemeVisualPreferences() { - const [saturation, setSaturation] = useSetting(settingsAtom, 'saturationLevel'); const [oldSidebar, setOldSidebar] = useSetting(settingsAtom, 'oldSidebar'); const [pixelatedImageRendering, setPixelatedImageRendering] = useSetting( settingsAtom, @@ -270,32 +269,6 @@ function ThemeVisualPreferences() { Display - - setSaturation(Number.parseInt(e.target.value, 10))} - style={{ - width: toRem(160), - cursor: 'pointer', - appearance: 'none', - height: toRem(6), - borderRadius: config.radii.Pill, - backgroundColor: 'var(--sable-surface-container-line)', - accentColor: 'var(--sable-primary-main)', - }} - /> - } - /> - = { account: 'account', + accessibility: 'accessibility', Persona: 'persona', cosmetics: 'appearance', notifications: 'notifications', diff --git a/src/app/features/settings/settingsLink.test.ts b/src/app/features/settings/settingsLink.test.ts index 529ee1401..ecbd0be3a 100644 --- a/src/app/features/settings/settingsLink.test.ts +++ b/src/app/features/settings/settingsLink.test.ts @@ -166,6 +166,34 @@ describe('settingsLink', () => { ).toBeUndefined(); }); + it('redirects settings links whose focus id moved to a different section', () => { + for (const focus of [ + 'autoplay-gifs', + 'autoplay-stickers', + 'autoplay-emojis', + 'saturation', + 'reduced-motion', + 'underline-links', + 'render-global-username-colors', + 'render-space-room-username-colors', + 'render-persona-username-colors', + 'render-space-room-fonts', + ]) { + expect( + parseSettingsLink( + 'https://app.example', + `https://app.example/settings/appearance?focus=${focus}` + ) + ).toEqual({ section: 'accessibility', focus }); + expect( + parseSettingsLink( + 'https://app.example', + `https://app.example/settings/accessibility?focus=${focus}` + ) + ).toEqual({ section: 'accessibility', focus }); + } + }); + it('rejects settings links with malformed query params', () => { expect( parseSettingsLink( diff --git a/src/app/features/settings/settingsLink.ts b/src/app/features/settings/settingsLink.ts index ceb20969e..651ecd352 100644 --- a/src/app/features/settings/settingsLink.ts +++ b/src/app/features/settings/settingsLink.ts @@ -113,10 +113,7 @@ export const settingsLinkFocusIdsBySection: Record const isShareableSettingsFocusId = (section: SettingsSectionId, focus: string): boolean => settingsLinkFocusIdsBySectionSet[section].has(focus); +// Focus ids may live under a different section than the link claims when +// settings get reorganized; redirect to the owning section. +const settingsSectionByFocusId = settingsSections.reduce((acc, section) => { + for (const focusId of settingsLinkFocusIdsBySection[section.id]) { + acc.set(focusId, section.id); + } + return acc; +}, new Map()); + const parseSettingsLinkQuery = ( search: string ): { focus?: string; hasActionMarker: boolean } | undefined => { @@ -343,7 +352,9 @@ const parseSettingsAppPath = (appPath: string): SettingsLink | undefined => { if (!query) return undefined; if (query.focus && !isShareableSettingsFocusId(section, query.focus)) { - return undefined; + const owningSection = settingsSectionByFocusId.get(query.focus); + if (!owningSection) return undefined; + return { section: owningSection, focus: query.focus }; } return { section, focus: query.focus }; diff --git a/src/app/hooks/useAccessibleNameColor.ts b/src/app/hooks/useAccessibleNameColor.ts new file mode 100644 index 000000000..abe1036ef --- /dev/null +++ b/src/app/hooks/useAccessibleNameColor.ts @@ -0,0 +1,21 @@ +import { useCallback } from 'react'; +import { useSetting } from '$state/hooks/settings'; +import { settingsAtom } from '$state/settings'; +import { accessibleColor, accessibleColorWeakCorrection } from '$plugins/color'; +import type { ThemeKind } from './useTheme'; + +export const useAccessibleNameColor = (themeKind: ThemeKind) => { + const [nameColorLightnessCorrection] = useSetting(settingsAtom, 'nameColorLightnessCorrection'); + + return useCallback( + (color: string | undefined) => { + if (!color || nameColorLightnessCorrection === 'off') { + return color; + } + return nameColorLightnessCorrection === 'strong' + ? accessibleColor(themeKind, color) + : accessibleColorWeakCorrection(themeKind, color); + }, + [nameColorLightnessCorrection, themeKind] + ); +}; diff --git a/src/app/hooks/useMemberPowerTag.ts b/src/app/hooks/useMemberPowerTag.ts index f7c83cffa..b6d0b1f52 100644 --- a/src/app/hooks/useMemberPowerTag.ts +++ b/src/app/hooks/useMemberPowerTag.ts @@ -1,7 +1,7 @@ import { useCallback, useMemo } from 'react'; import type { MatrixClient, Room, RoomMember } from '$types/matrix-sdk'; import type { MemberPowerTag, MemberPowerTagIcon } from '$types/matrix/room'; -import { accessibleColor } from '$plugins/color'; +import { useAccessibleNameColor } from './useAccessibleNameColor'; import { mxcUrlToHttp } from '$utils/matrix'; import type { PowerLevelTags } from './usePowerLevelTags'; import { getPowerLevelTag, usePowerLevelTags } from './usePowerLevelTags'; @@ -49,21 +49,23 @@ export const useAccessiblePowerTagColors = ( creatorsTag: MemberPowerTag, powerLevelTags: PowerLevelTags ): Map => { + const accessibleNameColor = useAccessibleNameColor(themeKind); + const accessibleColors: Map = useMemo(() => { const colors: Map = new Map(); if (creatorsTag.color) { - colors.set(creatorsTag.color, accessibleColor(themeKind, creatorsTag.color)); + colors.set(creatorsTag.color, accessibleNameColor(creatorsTag.color) ?? creatorsTag.color); } Object.values(powerLevelTags).forEach((tag) => { const { color } = tag; if (!color) return; - colors.set(color, accessibleColor(themeKind, color)); + colors.set(color, accessibleNameColor(color) ?? color); }); return colors; - }, [powerLevelTags, creatorsTag, themeKind]); + }, [powerLevelTags, creatorsTag, accessibleNameColor]); return accessibleColors; }; diff --git a/src/app/hooks/useSableCosmetics.ts b/src/app/hooks/useSableCosmetics.ts index 970bbdfef..06ea1f49e 100644 --- a/src/app/hooks/useSableCosmetics.ts +++ b/src/app/hooks/useSableCosmetics.ts @@ -8,9 +8,7 @@ import { useRoomCreatorsTag } from './useRoomCreatorsTag'; import { usePowerLevelTags } from './usePowerLevelTags'; import { useTheme } from './useTheme'; import { useUserProfile } from './useUserProfile'; -import { useSetting } from '$state/hooks/settings'; -import { settingsAtom } from '$state/settings'; -import { accessibleColor, accessibleColorWeakCorrection } from '$plugins/color'; +import { useAccessibleNameColor } from './useAccessibleNameColor'; export function useSableCosmetics( userId: string, @@ -28,22 +26,11 @@ export function useSableCosmetics( const getPowerTag = useGetMemberPowerTag(room, creators, powerLevels); const accessibleTagColors = useAccessiblePowerTagColors(theme.kind, creatorsTag, powerLevelTags); - const [nameColorLightnessCorrection] = useSetting(settingsAtom, 'nameColorLightnessCorrection'); + const accessibleNameColor = useAccessibleNameColor(theme.kind); return useMemo(() => { if (!room || !userId) return { color: undefined, font: undefined }; - const accessibleNameColor = (color: string | undefined) => { - if (!color || nameColorLightnessCorrection === 'off') { - return color; - } else if (nameColorLightnessCorrection === 'strong') { - return accessibleColor(theme.kind, color); - } else { - /* weak color correction */ - return accessibleColorWeakCorrection(theme.kind, color); - } - }; - let finalColor = accessibleNameColor( isUserHero ? profile.heroNameColor : profile.resolvedColor ); @@ -68,7 +55,6 @@ export function useSableCosmetics( profile.resolvedFont, getPowerTag, accessibleTagColors, - nameColorLightnessCorrection, - theme.kind, + accessibleNameColor, ]); } From 666eff10838eb90da9d2a9ec4c570afb033a6829 Mon Sep 17 00:00:00 2001 From: "sable-actions[bot]" <268226691+sable-actions[bot]@users.noreply.github.com> Date: Fri, 7 Aug 2026 17:38:36 +0000 Subject: [PATCH 131/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index a4553cb98..b62228efb 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -20,12 +20,12 @@ "screenshots": [], "versions": [ { - "version": "1.20.1786101241", - "buildVersion": "1.20.1786101241", - "date": "2026-08-07T11:28:55Z", - "size": 19107453, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260807111401-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260807111401" + "version": "1.20.1786123510", + "buildVersion": "1.20.1786123510", + "date": "2026-08-07T17:38:34Z", + "size": 18940434, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260807172510-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260807172510" } ], "appPermissions": { From f968b9f4f9058407d79cc5d357e09cff0dd90141 Mon Sep 17 00:00:00 2001 From: "sable-actions[bot]" <268226691+sable-actions[bot]@users.noreply.github.com> Date: Fri, 7 Aug 2026 18:03:49 +0000 Subject: [PATCH 132/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index b62228efb..aadc6f4b8 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -20,12 +20,12 @@ "screenshots": [], "versions": [ { - "version": "1.20.1786123510", - "buildVersion": "1.20.1786123510", - "date": "2026-08-07T17:38:34Z", - "size": 18940434, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260807172510-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260807172510" + "version": "1.20.1786125045", + "buildVersion": "1.20.1786125045", + "date": "2026-08-07T18:03:47Z", + "size": 18940492, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260807175045-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260807175045" } ], "appPermissions": { From de0f5c88122a29f2042993428f17341ba13d8aea Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Mon, 3 Aug 2026 21:16:31 +0200 Subject: [PATCH 133/135] fix: show desktop update errors --- src/app/pages/client/DesktopUpdater.test.tsx | 15 +++++-- src/app/pages/client/DesktopUpdater.tsx | 45 +++++++++++++++++--- 2 files changed, 50 insertions(+), 10 deletions(-) diff --git a/src/app/pages/client/DesktopUpdater.test.tsx b/src/app/pages/client/DesktopUpdater.test.tsx index ccae75e22..05c095f68 100644 --- a/src/app/pages/client/DesktopUpdater.test.tsx +++ b/src/app/pages/client/DesktopUpdater.test.tsx @@ -2,7 +2,7 @@ import { render, screen, fireEvent, waitFor } from '@testing-library/react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { useAtomValue, useSetAtom, Provider } from 'jotai'; import { globalBannersAtom } from '$state/globalBanners'; -import { triggerUpdateCheckAtom } from '$state/desktopUpdate'; +import { triggerUpdateCheckAtom, updatePhaseAtom } from '$state/desktopUpdate'; import { DesktopUpdatePill } from '$components/tauri/DesktopUpdatePill'; import { getDebugLogger } from '$utils/debugLogger'; import { DesktopUpdater } from './DesktopUpdater'; @@ -33,6 +33,7 @@ function BannersProbe() { {banners.map((b) => (
{b.title} + {b.description} @@ -56,6 +57,11 @@ function CheckNowButton() { ); } +function UpdatePhaseProbe() { + const phase = useAtomValue(updatePhaseAtom); + return {phase.type}; +} + function makeUpdate(version: string) { return { version, @@ -168,6 +174,7 @@ describe('DesktopUpdater', () => { + ); @@ -178,7 +185,7 @@ describe('DesktopUpdater', () => { fireEvent.click(screen.getByRole('button', { name: 'Download & Install' })); await waitFor(() => expect(update.downloadAndInstall).toHaveBeenCalledTimes(1)); await waitFor(() => { - expect(screen.getByRole('button', { name: 'Download & Install' })).toBeInTheDocument(); + expect(screen.getByText('Update Failed')).toBeInTheDocument(); }); expect(debugLog).toHaveBeenCalledWith( 'error', @@ -186,8 +193,10 @@ describe('DesktopUpdater', () => { 'DesktopUpdater', 'Failed to install update: permission denied' ); + expect(screen.getByText('permission denied')).toBeInTheDocument(); + expect(screen.getByTestId('update-phase')).toHaveTextContent('ready'); - fireEvent.click(screen.getByRole('button', { name: 'Download & Install' })); + fireEvent.click(screen.getByRole('button', { name: 'Retry' })); await waitFor(() => expect(update.downloadAndInstall).toHaveBeenCalledTimes(2)); await screen.findByTestId('banner-desktop-update-restart'); }); diff --git a/src/app/pages/client/DesktopUpdater.tsx b/src/app/pages/client/DesktopUpdater.tsx index fe02f69c0..f3c3c38ea 100644 --- a/src/app/pages/client/DesktopUpdater.tsx +++ b/src/app/pages/client/DesktopUpdater.tsx @@ -20,15 +20,21 @@ import { const log = createLogger('DesktopUpdater'); const UPDATE_POLL_INTERVAL_MS = 300_000; // 5 minutes +const getUpdaterErrorMessage = (error: unknown): string => + error instanceof Error + ? error.message + : typeof error === 'object' && error !== null && 'message' in error + ? String(error.message) + : String(error); + const logUpdaterError = (message: string, error: unknown): void => { log.error(message, error); - const detail = - error instanceof Error - ? error.message - : typeof error === 'object' && error !== null && 'message' in error - ? String(error.message) - : String(error); - getDebugLogger().log('error', 'network', 'DesktopUpdater', `${message}: ${detail}`); + getDebugLogger().log( + 'error', + 'network', + 'DesktopUpdater', + `${message}: ${getUpdaterErrorMessage(error)}` + ); }; export function DesktopUpdater() { @@ -41,6 +47,7 @@ export function DesktopUpdater() { const [isDownloading, setIsDownloading] = useState(false); const [isInstalled, setIsInstalled] = useState(false); const [isInstalling, setIsInstalling] = useState(false); + const [installError, setInstallError] = useState(null); const [dismissed, setDismissed] = useState(false); const [useCustomTitleBar] = useDesktopSetting('useCustomTitleBar'); const hasUpdateRef = useRef(false); @@ -157,6 +164,7 @@ export function DesktopUpdater() { if (!updateInfo || installStartedRef.current) return; installStartedRef.current = true; try { + setInstallError(null); setIsDownloading(true); setPhase({ type: 'downloading', progress: 0 }); @@ -192,8 +200,10 @@ export function DesktopUpdater() { closePendingUpdate(updateInfo); } catch (err) { logUpdaterError('Failed to install update', err); + setInstallError(getUpdaterErrorMessage(err)); setIsDownloading(false); setIsInstalling(false); + setPhase({ type: 'ready', version: updateInfo.version }); installStartedRef.current = false; } }, [closePendingUpdate, updateInfo, setPhase]); @@ -235,6 +245,26 @@ export function DesktopUpdater() { }; } + if (installError) { + return { + id: 'desktop-update-ready', + priority: 200, + icon: ArrowUp, + title: 'Update Failed', + description: installError, + primaryAction: { + label: 'Retry', + variant: 'Primary', + onClick: handleInstall, + }, + secondaryAction: { + label: 'Later', + variant: 'Secondary', + onClick: handleDismiss, + }, + }; + } + return { id: 'desktop-update-ready', priority: 200, @@ -263,6 +293,7 @@ export function DesktopUpdater() { isDownloading, isInstalled, isInstalling, + installError, handleInstall, handleRestart, handleDismiss, From 1925246819bf254efe3e8a5c85d184f8164fef7e Mon Sep 17 00:00:00 2001 From: "sable-actions[bot]" <268226691+sable-actions[bot]@users.noreply.github.com> Date: Fri, 7 Aug 2026 20:05:50 +0000 Subject: [PATCH 134/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index aadc6f4b8..a02b0ba42 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -20,12 +20,12 @@ "screenshots": [], "versions": [ { - "version": "1.20.1786125045", - "buildVersion": "1.20.1786125045", - "date": "2026-08-07T18:03:47Z", - "size": 18940492, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260807175045-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260807175045" + "version": "1.20.1786132397", + "buildVersion": "1.20.1786132397", + "date": "2026-08-07T20:05:49Z", + "size": 18940531, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260807195317-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260807195317" } ], "appPermissions": { From ed4886c4b288b3bb30709dec5b24989aa3e505c6 Mon Sep 17 00:00:00 2001 From: "sable-actions[bot]" <268226691+sable-actions[bot]@users.noreply.github.com> Date: Fri, 7 Aug 2026 20:22:23 +0000 Subject: [PATCH 135/135] chore: update altstore-source-nightly.json for nightly [skip ci] --- altstore-source-nightly.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index a02b0ba42..c24c21c85 100644 --- a/altstore-source-nightly.json +++ b/altstore-source-nightly.json @@ -20,12 +20,12 @@ "screenshots": [], "versions": [ { - "version": "1.20.1786132397", - "buildVersion": "1.20.1786132397", - "date": "2026-08-07T20:05:49Z", - "size": 18940531, - "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260807195317-ios-arm64.ipa", - "localizedDescription": "Sable 1.20.1-nightly.260807195317" + "version": "1.20.1786133496", + "buildVersion": "1.20.1786133496", + "date": "2026-08-07T20:22:21Z", + "size": 18940363, + "downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260807201136-ios-arm64.ipa", + "localizedDescription": "Sable 1.20.1-nightly.260807201136" } ], "appPermissions": {