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/.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/.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/.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/.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/.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/.changeset/fix_for_the_call_room_name_positioning.md b/.changeset/fix_for_the_call_room_name_positioning.md new file mode 100644 index 000000000..1fd0f1800 --- /dev/null +++ b/.changeset/fix_for_the_call_room_name_positioning.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +# Fix for the call room name positioning 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/.github/scripts/set-tauri-version.mjs b/.github/scripts/set-tauri-version.mjs index dea0f0e56..79d7ab02e 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,30 @@ const sanitizedVersion = version.replace(/^(\d+\.\d+\.\d+-nightly)\.(.+)$/, (_, return `${prefix}.${sanitizedBuild}`; }); -config.version = sanitizedVersion; +// 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) { + 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; 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/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 diff --git a/.github/workflows/tauri-build.yml b/.github/workflows/tauri-build.yml index 3d976d462..c8a63e3c2 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 @@ -455,7 +482,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 +575,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 diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index adbdab882..820903120 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. diff --git a/README.md b/README.md index 787f27bee..9773fd3c9 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,42 @@ 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 + +Add to Obtainium +  +App config +  +Download APK + +### Setup & install + +1. Install [Obtainium](https://github.com/ImranR98/Obtainium/releases/latest). +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. + +### 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). @@ -55,7 +91,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. diff --git a/altstore-source-nightly.json b/altstore-source-nightly.json index 39579c499..c24c21c85 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.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" + "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": { diff --git a/flake.nix b/flake.nix index c476cc8cc..7c7ae9b96 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,140 +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-1siT4fB6ty2azmWXe5L40EFUdk0th59qIdARUB0cVOc="; }; - 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 - libpulseaudio - alsa-lib - 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 @@ -202,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}"; + }; }; }; - }; }; } 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/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/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/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" < [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 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, + 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}`); diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index f58607f69..0034a495d 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -35,13 +35,13 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "aes" -version = "0.8.4" +version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +checksum = "f8eb277bec05f56a0e0591f155a484cbd0f4f07ff2905051a48c72f004f7ed58" dependencies = [ - "cfg-if", "cipher", - "cpufeatures 0.2.17", + "cpubits", + "cpufeatures 0.3.0", ] [[package]] @@ -168,7 +168,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -179,7 +179,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -496,6 +496,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b25655df2c3cdd83c5e5b293b88acd880332b2ddadd7c30ac43144fdc0033da9" + [[package]] name = "bit-set" version = "0.8.0" @@ -541,6 +547,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "block2" version = "0.6.2" @@ -903,11 +918,12 @@ dependencies = [ [[package]] name = "cipher" -version = "0.4.4" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" dependencies = [ - "crypto-common", + "block-buffer 0.12.1", + "crypto-common 0.2.2", "inout", ] @@ -1058,6 +1074,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + [[package]] name = "const-random" version = "0.1.18" @@ -1177,6 +1199,12 @@ dependencies = [ "libc", ] +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -1254,6 +1282,15 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + [[package]] name = "cssparser" version = "0.29.6" @@ -1312,9 +1349,9 @@ checksum = "52560adf09603e58c9a7ee1fe1dcb95a16927b17c127f0ac02d6e768a0e25bc1" [[package]] name = "ctr" -version = "0.9.2" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +checksum = "baaca1c4b237092596f64d571e9db6ce4109c4ef9742e27590f1709594461f21" dependencies = [ "cipher", ] @@ -1525,8 +1562,19 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "crypto-common", + "block-buffer 0.10.4", + "crypto-common 0.1.7", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", ] [[package]] @@ -1553,7 +1601,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -1781,9 +1829,9 @@ checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" [[package]] name = "enigo" -version = "0.5.0" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71744ff36f35a4276e8827add8102d0e792378c574fd93cb4e1c8e0505f96b7c" +checksum = "71c6c56e50f7acae2906a0dcbb34529ca647e40421119ad5d12e7f8ba6e50010" dependencies = [ "core-foundation 0.10.1", "core-graphics 0.25.0", @@ -1794,7 +1842,7 @@ dependencies = [ "objc2", "objc2-app-kit", "objc2-foundation", - "windows", + "windows 0.61.3", "x11rb", "xkbcommon", "xkeysym", @@ -1855,7 +1903,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2733,6 +2781,15 @@ dependencies = [ "libm", ] +[[package]] +name = "hybrid-array" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707114b52a152fa7bdb290cd7cd5912d9467273b6d74e21b8d81aca1f8533f6b" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "0.14.32" @@ -3070,11 +3127,11 @@ checksum = "f4200d433cbd5178df7797c9c2e75b348b728e39631cf14520d1e2fc424201f4" [[package]] name = "inout" -version = "0.1.4" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7" dependencies = [ - "generic-array", + "hybrid-array", ] [[package]] @@ -3653,7 +3710,7 @@ dependencies = [ "png 0.18.1", "serde", "thiserror 2.0.19", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -3777,7 +3834,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -4217,7 +4274,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.48.0", ] [[package]] @@ -4875,7 +4932,7 @@ dependencies = [ "once_cell", "socket2 0.6.5", "tracing", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5294,7 +5351,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5352,7 +5409,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5390,7 +5447,7 @@ version = "1.20.0" dependencies = [ "aes", "async-stream", - "base64 0.22.1", + "base64 0.23.0", "block2", "cef", "ctr", @@ -5398,8 +5455,8 @@ dependencies = [ "futures-util", "gtk", "infer 0.22.0", - "jni 0.21.1", - "libloading 0.8.9", + "jni 0.22.4", + "libloading 0.9.0", "log", "objc2", "objc2-avf-audio", @@ -5412,7 +5469,7 @@ dependencies = [ "sentry", "serde", "serde_json", - "sha2", + "sha2 0.11.0", "tauri", "tauri-build", "tauri-plugin-android-fs", @@ -5440,8 +5497,8 @@ dependencies = [ "tokio-util", "ts-rs", "webkit2gtk", - "windows", - "zip", + "windows 0.62.2", + "zip 8.6.0", ] [[package]] @@ -5610,9 +5667,9 @@ dependencies = [ [[package]] name = "sentry" -version = "0.48.5" +version = "0.49.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d631477761f57c76148456e55e80e9a479ff3fa4c65b2b4a0c3acf1167fd4638" +checksum = "d91e4790d8c2f43a6645ee2cb12aac2db79221fddd035b94c8166b88ea094408" dependencies = [ "cfg_aliases", "httpdate", @@ -5627,9 +5684,9 @@ dependencies = [ [[package]] name = "sentry-backtrace" -version = "0.48.5" +version = "0.49.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "448b0981fbde6cdc9eb087ba3dc01035a253fef9a0d9e79aaf198fc26acb2e64" +checksum = "e3bcc2497c2327998146207b7600599ef7592233920f4d4e1d41ddeeba0e4210" dependencies = [ "backtrace", "regex", @@ -5638,9 +5695,9 @@ dependencies = [ [[package]] name = "sentry-contexts" -version = "0.48.5" +version = "0.49.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e5e909d02170ba6d1dc5ebd05bef7999280f5d960e3eaee5d1a18d88d41b334" +checksum = "1cb04cba225b38f59d08f9e3c29ab7259d9cc94fbb2c46d613a51cb0a4a7ee05" dependencies = [ "hostname", "libc", @@ -5652,9 +5709,9 @@ dependencies = [ [[package]] name = "sentry-core" -version = "0.48.5" +version = "0.49.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecf0b1a4a4e9ec88395b52e6fa4868b95564c1fa96b26a0606f5f6288a0f7149" +checksum = "48759bc392fb5e3b36b4efcb485f51074c0ba8479711cd5c8cf79e86f9f75d41" dependencies = [ "rand 0.9.5", "sentry-types", @@ -5665,9 +5722,9 @@ dependencies = [ [[package]] name = "sentry-debug-images" -version = "0.48.5" +version = "0.49.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f81d7749c57fc78ed52134889e8121da874065bc40da788d5798cce0f8c19f15" +checksum = "0a5bd325059b70b21ca6e42b0f2409821272dddc1cf37923de37269af55389b5" dependencies = [ "findshlibs", "sentry-core", @@ -5675,9 +5732,9 @@ dependencies = [ [[package]] name = "sentry-panic" -version = "0.48.5" +version = "0.49.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7d93d6ecb55d2251c5fc084c55c03a2bc68904918d76117e602c999e92f00f" +checksum = "a685d22f672b1562ebeff3f2affceb5960595648cc936dae73da3e1d6a55fbd1" dependencies = [ "sentry-backtrace", "sentry-core", @@ -5685,9 +5742,9 @@ dependencies = [ [[package]] name = "sentry-tracing" -version = "0.48.5" +version = "0.49.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58d26379236c4ef97eaf081bca3c7bf0ef6f06b3aa881eca2ee8e8dbc923e5b8" +checksum = "8aa7d8e0db4cccddbac01ddabd5344ad03b7c2f954b3ff850cecb1d9cf5d4758" dependencies = [ "bitflags 2.13.1", "sentry-backtrace", @@ -5698,9 +5755,9 @@ dependencies = [ [[package]] name = "sentry-types" -version = "0.48.5" +version = "0.49.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2239099d47e76857b0825a182ecdb90159add7aa1097b60247c6e7ca6bf49c6a" +checksum = "fab146d15a30ab4897a95fd15d6a038b8d7fbf2661c5f8b13738ce8df7a095b7" dependencies = [ "debugid", "hex", @@ -5913,7 +5970,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "digest 0.11.3", ] [[package]] @@ -6051,7 +6119,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -6391,7 +6459,7 @@ dependencies = [ "tao-macros", "unicode-segmentation", "url", - "windows", + "windows 0.61.3", "windows-core 0.61.2", "windows-version", "x11-dl", @@ -6475,7 +6543,7 @@ dependencies = [ "webkit2gtk", "webview2-com", "window-vibrancy", - "windows", + "windows 0.61.3", ] [[package]] @@ -6516,7 +6584,7 @@ dependencies = [ "semver", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "syn 2.0.119", "tauri-utils", "thiserror 2.0.19", @@ -6558,9 +6626,9 @@ dependencies = [ [[package]] name = "tauri-plugin-android-fs" -version = "28.4.0" +version = "29.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "999e39313646a1f48f65270e75df20664a692bf28fa21f44a16bf8706c154f31" +checksum = "8ca3a802951458c58c32e4605d43143ca92c205ba3eb7c989b03183cd88e9e6e" dependencies = [ "base64 0.22.1", "glob", @@ -6613,9 +6681,9 @@ dependencies = [ [[package]] name = "tauri-plugin-devtools" -version = "2.0.0" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e5cd17faa36a826e5686bd0fda5bc3f4c903682263f00cd50f2f778fc4bb866" +checksum = "6a8fa7b8275c5f3efed02591d5c080540bec4c3e5b3180586fcd824953328e8e" dependencies = [ "async-stream", "bytes", @@ -6754,7 +6822,7 @@ dependencies = [ [[package]] name = "tauri-plugin-notifications" version = "0.5.0-rc.11" -source = "git+https://github.com/SableClient/tauri-plugin-notifications.git?rev=0175b5ec58a31ab15397e981a67f47fa32254620#0175b5ec58a31ab15397e981a67f47fa32254620" +source = "git+https://github.com/SableClient/tauri-plugin-notifications.git?rev=057d323862d815a0c7459a1f1acd5a3c08750a51#057d323862d815a0c7459a1f1acd5a3c08750a51" dependencies = [ "log", "notify-rust", @@ -6772,7 +6840,7 @@ dependencies = [ "tokio", "url", "uuid", - "windows", + "windows 0.61.3", "windows-core 0.61.2", "zbus", ] @@ -6795,7 +6863,7 @@ dependencies = [ "tauri-plugin", "thiserror 2.0.19", "url", - "windows", + "windows 0.61.3", "zbus", ] @@ -6844,8 +6912,8 @@ dependencies = [ "tauri-plugin", "thiserror 2.0.19", "tokio", - "windows", - "windows-collections", + "windows 0.61.3", + "windows-collections 0.2.0", ] [[package]] @@ -6911,7 +6979,7 @@ dependencies = [ "tokio", "url", "windows-sys 0.60.2", - "zip", + "zip 4.6.1", ] [[package]] @@ -6951,13 +7019,13 @@ dependencies = [ "url", "webkit2gtk", "webview2-com", - "windows", + "windows 0.61.3", ] [[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#6aee1cdbe137b53cb28201417ec302b75a93330a" dependencies = [ "base64 0.22.1", "cef", @@ -6980,12 +7048,12 @@ dependencies = [ "raw-window-handle", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "softbuffer", "tauri-runtime", "tauri-utils", "url", - "windows", + "windows 0.61.3", "winit", "x11-dl", ] @@ -7013,7 +7081,7 @@ dependencies = [ "url", "webkit2gtk", "webview2-com", - "windows", + "windows 0.61.3", "wry", ] @@ -7095,7 +7163,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed071c670382e85fc2f48ae706492d8c338f4f89bf72520d32f8abfe880aade" dependencies = [ "thiserror 2.0.19", - "windows", + "windows 0.61.3", "windows-version", ] @@ -7109,7 +7177,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -7734,7 +7802,7 @@ dependencies = [ "png 0.18.1", "serde", "thiserror 2.0.19", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -7782,6 +7850,12 @@ version = "0.25.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" +[[package]] +name = "typed-path" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" + [[package]] name = "typeid" version = "1.0.3" @@ -7808,7 +7882,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" dependencies = [ "memoffset", "tempfile", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -8382,7 +8456,7 @@ checksum = "7130243a7a5b33c54a444e54842e6a9e133de08b5ad7b5861cd8ed9a6a5bc96a" dependencies = [ "webview2-com-macros", "webview2-com-sys", - "windows", + "windows 0.61.3", "windows-core 0.61.2", "windows-implement", "windows-interface", @@ -8406,7 +8480,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "381336cfffd772377d291702245447a5251a2ffa5bad679c99e61bc48bacbf9c" dependencies = [ "thiserror 2.0.19", - "windows", + "windows 0.61.3", "windows-core 0.61.2", ] @@ -8438,7 +8512,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.48.0", ] [[package]] @@ -8468,11 +8542,23 @@ version = "0.61.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" dependencies = [ - "windows-collections", + "windows-collections 0.2.0", "windows-core 0.61.2", - "windows-future", + "windows-future 0.2.1", "windows-link 0.1.3", - "windows-numerics", + "windows-numerics 0.2.0", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections 0.3.2", + "windows-core 0.62.2", + "windows-future 0.3.2", + "windows-numerics 0.3.1", ] [[package]] @@ -8484,6 +8570,15 @@ dependencies = [ "windows-core 0.61.2", ] +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core 0.62.2", +] + [[package]] name = "windows-core" version = "0.61.2" @@ -8518,7 +8613,18 @@ checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" dependencies = [ "windows-core 0.61.2", "windows-link 0.1.3", - "windows-threading", + "windows-threading 0.1.0", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core 0.62.2", + "windows-link 0.2.1", + "windows-threading 0.2.1", ] [[package]] @@ -8565,6 +8671,16 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core 0.62.2", + "windows-link 0.2.1", +] + [[package]] name = "windows-registry" version = "0.5.3" @@ -8738,6 +8854,15 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link 0.2.1", +] + [[package]] name = "windows-version" version = "0.1.7" @@ -9246,7 +9371,7 @@ dependencies = [ "once_cell", "percent-encoding", "raw-window-handle", - "sha2", + "sha2 0.10.9", "soup3", "tao-macros", "thiserror 2.0.19", @@ -9255,7 +9380,7 @@ dependencies = [ "webkit2gtk", "webkit2gtk-sys", "webview2-com", - "windows", + "windows 0.61.3", "windows-core 0.61.2", "windows-version", "x11-dl", @@ -9322,9 +9447,9 @@ checksum = "bec9e4a500ca8864c5b47b8b482a73d62e4237670e5b5f1d6b9e3cae50f28f2b" [[package]] name = "xkbcommon" -version = "0.8.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d66ca9352cbd4eecbbc40871d8a11b4ac8107cfc528a6e14d7c19c69d0e1ac9" +checksum = "a7a974f48060a14e95705c01f24ad9c3345022f4d97441b8a36beb7ed5c4a02d" dependencies = [ "libc", "memmap2", @@ -9522,10 +9647,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1" dependencies = [ "arbitrary", + "crc32fast", + "indexmap 2.14.0", + "memchr", +] + +[[package]] +name = "zip" +version = "8.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b" +dependencies = [ "crc32fast", "flate2", "indexmap 2.14.0", "memchr", + "typed-path", ] [[package]] diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index c8c27dac8..7ab48a7ae 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -24,7 +24,7 @@ serde = { version = "1.0", features = ["derive"] } log = "0.4" # default-features = false drops reqwest + native-tls (openssl); ureq is a sync # rustls transport with no async-runtime dependency. -sentry = { version = "0.48.5", default-features = false, features = [ +sentry = { version = "0.49.0", default-features = false, features = [ "backtrace", "contexts", "panic", @@ -33,9 +33,9 @@ sentry = { version = "0.48.5", default-features = false, features = [ ] } tokio = { version = "1", features = ["time", "sync", "fs", "io-util"] } ts-rs = "12.0.0" -sha2 = "0.10" -aes = "0.8" -ctr = "0.9" +sha2 = "0.11" +aes = "0.9" +ctr = "0.10" infer = { version = "0.22", default-features = false } percent-encoding = "2" # Enables `stream` (for native_upload's `Body::wrap_stream`) on the reqwest that @@ -43,11 +43,11 @@ percent-encoding = "2" # openssl-sys out of the Android cross-compile. reqwest = { version = "0.12", default-features = false, features = ["stream"] } async-stream = "0.3" -base64 = "0.22" +base64 = "0.23" tokio-util = { version = "0.7", features = ["codec"] } futures-util = "0.3" regex = "1" -zip = { version = "=4.6.1", default-features = false, features = ["deflate-flate2-zlib-rs"] } +zip = { version = "=8.6.0", default-features = false, features = ["deflate-flate2-zlib-rs"] } tauri = { version = "2.11.5", default-features = false, features = [ "tray-icon", @@ -76,11 +76,11 @@ tauri-plugin-dialog = "2" # wry/tauri-runtime-wry/webkit2gtk. # Pinned to =2.0.0 because 2.1.0+ introduced an unconditional call to # tauri::webview_version() which is gated behind tauri's `wry` feature. -tauri-plugin-devtools = { version = "=2.0.0", default-features = false, optional = true } +tauri-plugin-devtools = { version = "=2.1.0", default-features = false, optional = true } [target.'cfg(target_os = "windows")'.dependencies] -enigo = "0.5.0" -windows = { version = "0.61", features = [ +enigo = "0.6.1" +windows = { version = "0.62", features = [ "Win32_Foundation", "Win32_UI_WindowsAndMessaging", "Win32_System_Threading", @@ -91,12 +91,12 @@ windows = { version = "0.61", features = [ tauri-plugin-single-instance = { version = "2.4.3", features = ["deep-link"] } [target.'cfg(any(windows, target_os = "linux"))'.dependencies] -tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "0175b5ec58a31ab15397e981a67f47fa32254620" } +tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "057d323862d815a0c7459a1f1acd5a3c08750a51" } # default-features = false drops notify-rust so macOS uses the native # UNUserNotificationCenter backend (needs a signed .app to deliver). [target.'cfg(target_os = "macos")'.dependencies] -tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "0175b5ec58a31ab15397e981a67f47fa32254620", default-features = false } +tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "057d323862d815a0c7459a1f1acd5a3c08750a51", default-features = false } [target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies] tauri-plugin-updater = { version = "2", optional = true } @@ -116,10 +116,10 @@ webkit2gtk = { version = "2.0", optional = true } [target.'cfg(target_os = "linux")'.dependencies] tauri-runtime-cef = { git = "https://github.com/SableClient/tauri-runtime-cef", branch = "main", optional = true } cef = { version = "=150.2.1", optional = true } -libloading = "0.8" +libloading = "0.9" [target.'cfg(any(target_os = "android", target_os = "ios"))'.dependencies] -tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "0175b5ec58a31ab15397e981a67f47fa32254620", features = [ +tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "057d323862d815a0c7459a1f1acd5a3c08750a51", features = [ "push-notifications", ] } tauri-plugin-edge-to-edge = { git = "https://github.com/SableClient/tauri-plugin-edge-to-edge.git", rev = "33c6116c27be28c06df5a9d02231ecc5fdeb93c5" } @@ -171,8 +171,8 @@ objc2-call-kit = { version = "0.3", default-features = false, features = [ ] } [target.'cfg(target_os = "android")'.dependencies] -tauri-plugin-android-fs = { version = "=28.4.0", features = ["legacy-storage-permission"] } -jni = "0.21" +tauri-plugin-android-fs = { version = "=29.0.0", features = ["legacy-storage-permission"] } +jni = "0.22" [features] default = ["wry", "updater"] 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 9e7178aa7..1663c86a4 100644 Binary files a/src-tauri/gen/android/app/src/main/res/mipmap-hdpi/ic_notification.png and b/src-tauri/gen/android/app/src/main/res/mipmap-hdpi/ic_notification.png differ 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 805fe1c8e..aa597d6ae 100644 Binary files a/src-tauri/gen/android/app/src/main/res/mipmap-mdpi/ic_notification.png and b/src-tauri/gen/android/app/src/main/res/mipmap-mdpi/ic_notification.png differ 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 f3d89b5bf..047324fff 100644 Binary files a/src-tauri/gen/android/app/src/main/res/mipmap-xhdpi/ic_notification.png and b/src-tauri/gen/android/app/src/main/res/mipmap-xhdpi/ic_notification.png differ 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 854e9e43a..facf5d62d 100644 Binary files a/src-tauri/gen/android/app/src/main/res/mipmap-xxhdpi/ic_notification.png and b/src-tauri/gen/android/app/src/main/res/mipmap-xxhdpi/ic_notification.png differ 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 e6d61da79..5f39b5f1a 100644 Binary files a/src-tauri/gen/android/app/src/main/res/mipmap-xxxhdpi/ic_notification.png and b/src-tauri/gen/android/app/src/main/res/mipmap-xxxhdpi/ic_notification.png differ diff --git a/src-tauri/icons/android/drawable/ic_notification.xml b/src-tauri/icons/android/drawable/ic_notification.xml index 696a13d0c..6aebe88af 100644 --- a/src-tauri/icons/android/drawable/ic_notification.xml +++ b/src-tauri/icons/android/drawable/ic_notification.xml @@ -1,7 +1,6 @@ - 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 e2d71f7d2..1663c86a4 100644 Binary files a/src-tauri/icons/android/mipmap-hdpi/ic_notification.png and b/src-tauri/icons/android/mipmap-hdpi/ic_notification.png differ diff --git a/src-tauri/icons/android/mipmap-mdpi/ic_notification.png b/src-tauri/icons/android/mipmap-mdpi/ic_notification.png index 255084025..aa597d6ae 100644 Binary files a/src-tauri/icons/android/mipmap-mdpi/ic_notification.png and b/src-tauri/icons/android/mipmap-mdpi/ic_notification.png differ diff --git a/src-tauri/icons/android/mipmap-xhdpi/ic_notification.png b/src-tauri/icons/android/mipmap-xhdpi/ic_notification.png index bea0f2d25..047324fff 100644 Binary files a/src-tauri/icons/android/mipmap-xhdpi/ic_notification.png and b/src-tauri/icons/android/mipmap-xhdpi/ic_notification.png differ diff --git a/src-tauri/icons/android/mipmap-xxhdpi/ic_notification.png b/src-tauri/icons/android/mipmap-xxhdpi/ic_notification.png index 8a3e2a860..facf5d62d 100644 Binary files a/src-tauri/icons/android/mipmap-xxhdpi/ic_notification.png and b/src-tauri/icons/android/mipmap-xxhdpi/ic_notification.png differ diff --git a/src-tauri/icons/android/mipmap-xxxhdpi/ic_notification.png b/src-tauri/icons/android/mipmap-xxxhdpi/ic_notification.png index 334958c5d..5f39b5f1a 100644 Binary files a/src-tauri/icons/android/mipmap-xxxhdpi/ic_notification.png and b/src-tauri/icons/android/mipmap-xxxhdpi/ic_notification.png differ diff --git a/src-tauri/src/desktop/diagnostics.rs b/src-tauri/src/desktop/diagnostics.rs index c741e2a4e..6d93b3555 100644 --- a/src-tauri/src/desktop/diagnostics.rs +++ b/src-tauri/src/desktop/diagnostics.rs @@ -7,16 +7,22 @@ use tauri_plugin_dialog::DialogExt; const DEFAULT_ARCHIVE_NAME: &str = "sable-diagnostics.zip"; #[tauri::command] -pub fn export_diagnostics( +pub async fn export_diagnostics( app: AppHandle, frontend_logs: Option, ) -> Result, String> { - let Some(path) = app - .dialog() + let (sender, receiver) = tokio::sync::oneshot::channel(); + app.dialog() .file() .set_file_name(DEFAULT_ARCHIVE_NAME) .add_filter("ZIP archive", &["zip"]) - .blocking_save_file() + .save_file(move |path| { + let _ = sender.send(path); + }); + + let Some(path) = receiver + .await + .map_err(|error| format!("Save dialog did not return a result: {error}"))? else { return Ok(None); }; diff --git a/src-tauri/src/desktop/download.rs b/src-tauri/src/desktop/download.rs index 30078f801..cba83d6b3 100644 --- a/src-tauri/src/desktop/download.rs +++ b/src-tauri/src/desktop/download.rs @@ -2,16 +2,22 @@ use tauri::AppHandle; use tauri_plugin_dialog::DialogExt; #[tauri::command] -pub fn save_download( +pub async fn save_download( app: AppHandle, filename: String, bytes: Vec, ) -> Result { - let Some(path) = app - .dialog() + let (sender, receiver) = tokio::sync::oneshot::channel(); + app.dialog() .file() .set_file_name(&filename) - .blocking_save_file() + .save_file(move |path| { + let _ = sender.send(path); + }); + + let Some(path) = receiver + .await + .map_err(|error| format!("Save dialog did not return a result: {error}"))? else { return Ok(false); }; 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/lib.rs b/src-tauri/src/lib.rs index 7fcfe176c..5203450e3 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); @@ -304,6 +278,18 @@ 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 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 // 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. @@ -332,11 +318,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"))] diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 8fdd89c9e..34d6e6d07 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| { @@ -130,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); } 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()) } diff --git a/src-tauri/src/network/media_protocol.rs b/src-tauri/src/network/media_protocol.rs index 2d9f399fd..2fcf96f92 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,9 @@ 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); const MAX_NEGATIVE_CACHE_ENTRIES: usize = 512; @@ -475,9 +478,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 +492,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 +534,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 +1096,105 @@ 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 (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 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 (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), + }; + partial_response( + body[start as usize..=end as usize].to_vec(), + content_type, + start, + end, + total, + ) +} + +enum RangeSelection { + Partial { start: u64, end: u64 }, + Ignore, + Unsatisfiable, +} + +fn select_range(range_header: &str, total: u64) -> RangeSelection { + if total == 0 { + return RangeSelection::Unsatisfiable; + } + 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 Ok(suffix) = end.parse::() else { + return RangeSelection::Unsatisfiable; + }; + if suffix == 0 { + return RangeSelection::Unsatisfiable; + } + let length = suffix.min(total).min(MAX_RANGE_CHUNK); + (total - length, total - 1) + } else { + let Ok(start) = start.parse::() else { + return RangeSelection::Unsatisfiable; + }; + let requested_end = if end.is_empty() { + total - 1 + } else { + 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) + }; + if start <= end && start < total { + RangeSelection::Partial { start, end } + } else { + RangeSelection::Unsatisfiable + } +} + // 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 +1231,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 +1241,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 +1258,43 @@ 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> { + 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> { Response::builder() .status(StatusCode::SERVICE_UNAVAILABLE) @@ -1209,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(), @@ -1725,6 +1878,168 @@ 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 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] + fn malformed_or_unsatisfiable_range_is_rejected() { + for range in [ + "bytes=1000-1001", + "bytes=500-400", + "bytes=abc-def", + "items=0-1", + ] { + assert!( + matches!( + super::select_range(range, 1000), + super::RangeSelection::Unsatisfiable + ), + "{range}" + ); + } + 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] + 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()) + ); + + 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] + 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] 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) } 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/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/components/RenderMessageContent.tsx b/src/app/components/RenderMessageContent.tsx index d29f6333e..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; @@ -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 ( 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, @@ -525,7 +527,8 @@ export function EmojiBoard({ loading: gifsLoading, error: gifsError, searchGifs, - } = useGifSearch(favoriteGifs, showGifPicker, gifSearch); + cancelSearch: cancelGifSearch, + } = useGifSearch(favoriteGifs, showGifPicker && gifTab, gifSearch); const [emojiGroupItems, stickerGroupItems, gifGroupItems] = useGroups(tab, imagePacks, gifs); const [showFavoritesOnly, setShowFavoritesOnly] = useState(true); const groupsByTab = { @@ -553,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) { @@ -563,6 +566,7 @@ export function EmojiBoard({ searchGifs(term); } else { setShowFavoritesOnly(true); + cancelGifSearch(); resetGifSearch(); } } else if (term) { @@ -571,11 +575,25 @@ export function EmojiBoard({ resetEmojiSearch(); } }, - [emojiSearch, resetEmojiSearch, searchGifs, resetGifSearch, tab] + [cancelGifSearch, emojiSearch, resetEmojiSearch, searchGifs, resetGifSearch, tab] ), { wait: 200 } ); + useEffect(() => { + if (!gifTab || initialGifSearch === undefined) return; + setShowFavoritesOnly(initialGifSearch.length === 0); + if (initialGifSearch) searchGifs(initialGifSearch); + else resetGifSearch(); + }, [gifTab, initialGifSearch, searchGifs, resetGifSearch]); + + useEffect(() => { + if (!showGifPicker || !gifTab) { + handleOnChange.cancel(); + cancelGifSearch(); + } + }, [cancelGifSearch, gifTab, handleOnChange, showGifPicker]); + const contentScrollRef = useRef(null); const virtualBaseRef = useRef(null); const virtualizer = useVirtualizer({ @@ -677,10 +695,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 ? ( ({ + 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/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/MsgTypeRenderers.tsx b/src/app/components/message/MsgTypeRenderers.tsx index 976a88aa8..2340979b5 100644 --- a/src/app/components/message/MsgTypeRenderers.tsx +++ b/src/app/components/message/MsgTypeRenderers.tsx @@ -21,7 +21,11 @@ import { FALLBACK_MIMETYPE, getBlobSafeMimeType } from '$utils/mimeTypes'; import { parseGeoUri, scaleYDimension } from '$utils/common'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom } from '$state/settings'; -import type { PerMessageProfileBeeperFormat } from '$hooks/usePerMessageProfile'; +import { + stripPerMessageProfileFormattedBody, + stripPerMessageProfilePlainBody, + type PerMessageProfileBeeperFormat, +} from '$hooks/usePerMessageProfile'; import { Attachment, AttachmentBox, AttachmentContent, AttachmentHeader } from './attachment'; import { FileHeader, FileDownloadButton } from './FileHeader'; import { @@ -217,29 +221,51 @@ 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( - () => - cleanedMessage?.replace(/]*data-mx-profile-fallback[^>]*>(.*?):\s*<\/strong>/i, ''), + const hadPerMessageProfileFallback = useMemo( + () => cleanedMessage?.match(/]*data-mx-profile-fallback[^>]*>(.*?):\s*<\/strong>/i), [cleanedMessage] ); + // the html body, with PMP fallback removed + const unwrappedPmpCustomBody = useMemo( + () => (cleanedMessage ? stripPerMessageProfileFormattedBody(cleanedMessage) : undefined), + [cleanedMessage] + ); + // the plain body, with PMP fallback removed + const unwrappedPmpBody = useMemo( + () => + hadPerMessageProfileFallback + ? stripPerMessageProfilePlainBody(trimmedBody ?? '') + : 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 +286,7 @@ export function MText({ > {renderBody({ body: trimmedBody, - customBody: unwrappedPerMessageProfileMessage, + customBody: unwrappedPmpCustomBody, })} {edited && } 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, })); diff --git a/src/app/components/message/Reply.tsx b/src/app/components/message/Reply.tsx index 66cf450c2..821eb1c0d 100644 --- a/src/app/components/message/Reply.tsx +++ b/src/app/components/message/Reply.tsx @@ -63,7 +63,12 @@ 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 { ThemeKind, useActiveTheme } from '$hooks/useTheme'; +import { + convertBeeperFormatToOurPerMessageProfile, + stripPerMessageProfileFormattedBody, +} from '$hooks/usePerMessageProfile'; +import { useAccessibleNameColor } from '$hooks/useAccessibleNameColor'; const ROOM_REPLY_TIMELINE_EVENT_TYPES = new Set([ EventType.RoomMessage as string, @@ -272,7 +277,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 @@ -291,6 +296,15 @@ export const Reply = as<'div', ReplyProps>( const parseMemberEvent = useMemberEventParser(); const { color: usernameColor, font: usernameFont } = useSableCosmetics(sender ?? '', room); + const activeTheme = useActiveTheme(); + + const accessibleNameColor = useAccessibleNameColor(activeTheme.kind); + const pmpNameColor = useMemo(() => { + 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); useRoomMemberHydration(room, sender ?? ''); @@ -503,7 +517,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..25def1c85 100644 --- a/src/app/components/message/modals/Options.tsx +++ b/src/app/components/message/modals/Options.tsx @@ -62,12 +62,15 @@ 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'; 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'; @@ -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(); @@ -414,7 +418,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/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, 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 ( 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/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/call-status/CallRoomName.tsx b/src/app/features/call-status/CallRoomName.tsx index 6f620f77e..7a0f15d11 100644 --- a/src/app/features/call-status/CallRoomName.tsx +++ b/src/app/features/call-status/CallRoomName.tsx @@ -37,7 +37,13 @@ export function CallRoomName({ room }: CallRoomNameProps) { variant="Background" radii="Pill" before={ - + } onClick={() => navigateRoom(room.roomId)} > 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/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/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/CommandAutocomplete.tsx b/src/app/features/room/CommandAutocomplete.tsx index 0dc0d2e9c..99b49043c 100644 --- a/src/app/features/room/CommandAutocomplete.tsx +++ b/src/app/features/room/CommandAutocomplete.tsx @@ -19,6 +19,7 @@ import { useKeyDown } from '$hooks/useKeyDown'; import { onTabPress } from '$utils/keyboard'; type CommandAutoCompleteHandler = (commandName: string) => void; +const GIF_COMMAND = 'gif'; type CommandAutocompleteProps = { room: Room; @@ -41,7 +42,10 @@ export function CommandAutocomplete({ }: 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, @@ -106,7 +110,9 @@ export function CommandAutocomplete({ {`/${commandName}`} - {commands[commandName].description} + {commandName === GIF_COMMAND + ? 'Search and send a GIF: /gif ' + : commands[commandName as Command].description} diff --git a/src/app/features/room/RoomInput.test.tsx b/src/app/features/room/RoomInput.test.tsx new file mode 100644 index 000000000..517db52c6 --- /dev/null +++ b/src/app/features/room/RoomInput.test.tsx @@ -0,0 +1,1257 @@ +/* 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 type * as MsgContentModule from './msgContent'; +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[]): string => + nodes + .map((node) => (typeof node.text === 'string' ? node.text : textOf(node.children ?? []))) + .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: { Poll: 'poll', Location: 'location' }, + 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: (editor: any) => editor.children[0]?.children?.[1]?.command, + 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('./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, onGifSelect, requestClose }: any) => ( + <> + + + + + ), + EmojiBoardTab: { Emoji: 'emoji', Gif: 'gif', Sticker: 'sticker' }, +})); +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', () => ({ + PersistentPersonaPicker: () => null, + PersonaPickerTab: { Global: 'Global', PerRoom: 'PerRoom' }, +})); +vi.mock('./schedule-send', () => ({ SchedulePickerDialog: () => null })); +vi.mock('./poll-modals', () => ({ + PollDialog: ({ onSubmit, onCancel }: 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: { Poll: 'poll', Location: 'location' }, + 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), + getScheduledMessageStateKey: (userId: string, roomId: string) => `${userId}\0${roomId}`, + 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')); + }; + 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 ( + <> + + + + + + + + + + + ); +} + +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(testState.matrix, 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 a reply through GIF command dispatch and claims it exactly once on selection', async () => { + render(); + render(); + + fireEvent.click(screen.getByRole('button', { name: 'Compose GIF command' })); + fireEvent.click(sendButton()); + + await waitFor(() => expect(screen.getByTestId('reply-observer')).toHaveTextContent('$reply')); + expect(testState.matrix.sendMessage).not.toHaveBeenCalled(); + + fireEvent.click(screen.getByRole('button', { name: 'Select GIF' })); + await waitFor(() => expect(testState.matrix.sendMessage).toHaveBeenCalledOnce()); + expect(testState.matrix.sendMessage.mock.calls[0]?.[2]?.['m.relates_to']).toBeDefined(); + expect(screen.getByTestId('reply-observer')).toHaveTextContent(''); + }); + + it('restores a reply while a poll command is pending, including cancellation and retry', async () => { + render(); + render(); + + fireEvent.click(screen.getByRole('button', { name: 'Compose poll command' })); + fireEvent.click(sendButton()); + await waitFor(() => + expect(screen.getByRole('button', { name: 'Cancel poll' })).toBeInTheDocument() + ); + expect(screen.getByTestId('reply-observer')).toHaveTextContent('$reply'); + + fireEvent.click(screen.getByRole('button', { name: 'Cancel poll' })); + expect(testState.matrix.sendEvent).not.toHaveBeenCalled(); + expect(screen.getByTestId('reply-observer')).toHaveTextContent('$reply'); + + fireEvent.click(screen.getByRole('button', { name: 'Compose poll command' })); + fireEvent.click(sendButton()); + await waitFor(() => + expect(screen.getByRole('button', { name: 'Submit poll' })).toBeInTheDocument() + ); + fireEvent.click(screen.getByRole('button', { name: 'Submit poll' })); + + await waitFor(() => expect(testState.matrix.sendEvent).toHaveBeenCalledOnce()); + expect(testState.matrix.sendEvent.mock.calls[0]?.[3]?.['m.relates_to']).toBeDefined(); + expect(screen.getByTestId('reply-observer')).toHaveTextContent(''); + }); + + it('keeps a thread reply through an empty location command until submission', async () => { + render(); + + fireEvent.click(screen.getByRole('button', { name: 'Compose location command' })); + fireEvent.click(sendButton()); + 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(testState.matrix.sendMessage).toHaveBeenCalledWith( + room.roomId, + '$thread', + expect.objectContaining({ 'm.relates_to': expect.anything() }) + ); + }); + + 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(); + }); + + it('sends a mobile edit as a replacement, not a reply, when a reply draft exists', async () => { + testState.isMobile = true; + testState.editingEvent = { + getId: () => '$original', + getContent: () => ({ body: 'original', msgtype: 'm.text' }), + }; + const onCancelEdit = vi.fn(); + render(); + + 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()); + const sentContent = testState.matrix.sendMessage.mock.calls[0]![1]; + expect(sentContent['m.relates_to']).toEqual(expect.objectContaining({ rel_type: 'm.replace' })); + expect(sentContent['m.relates_to']).not.toHaveProperty('m.in_reply_to'); + expect(onCancelEdit).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 34e511469..c22e505b6 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, MsgType, RelationType } 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'; @@ -63,17 +65,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'; @@ -106,15 +103,13 @@ 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'; 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'; @@ -129,6 +124,7 @@ import { useQueryClient } from '@tanstack/react-query'; import * as Sentry from '@sentry/react'; import { delayedEventsSupportedAtom, + getScheduledMessageStateKey, roomIdToScheduledTimeAtomFamily, roomIdToEditingScheduledDelayIdAtomFamily, serverMaxDelayMsAtom, @@ -139,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'; @@ -150,7 +147,7 @@ import { convertPerMessageProfileToBeeperFormat, getCurrentlyUsedPerMessageProfileForAccount, getCurrentlyUsedPerMessageProfileForRoom, - type PerMessageProfile, + type PerMessageProfileMsc4461, setCurrentlyUsedPerMessageProfileIdForRoom, } from '$hooks/usePerMessageProfile'; import { @@ -179,7 +176,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'; @@ -205,7 +201,6 @@ import { buildGalleryContent, getGalleryItemContent, } from './msgContent'; -import { outgoingMessageTransforms } from './outgoingMessageTransforms'; import { getSendableKlipyMxcUrl } from '$utils/klipy'; import { CommandAutocomplete } from './CommandAutocomplete'; import type { @@ -217,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 })) @@ -273,6 +270,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; } @@ -280,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; @@ -341,8 +361,9 @@ 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(); + const [latchedPersona, setLatchedPersona] = useState(); const emojiBtnRef = useRef(null); const gifBtnRef = useRef(null); @@ -365,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) @@ -380,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); @@ -393,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; }, [] ); @@ -420,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); @@ -432,81 +509,174 @@ 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); 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)); - }, [editor]); + detectAutocomplete(); + 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, detectAutocomplete, mx, room]); const hasContent = hasText || selectedFiles.length > 0; const isComposing = useComposingCheck(); const queryClient = useQueryClient(); const delayedEventsSupported = useAtomValue(delayedEventsSupportedAtom); - const [scheduledTime, setScheduledTime] = useAtom(roomIdToScheduledTimeAtomFamily(roomId)); - const [editingScheduledDelayId, setEditingScheduledDelayId] = useAtom( - roomIdToEditingScheduledDelayIdAtomFamily(roomId) + const scheduledStateKey = getScheduledMessageStateKey(mx.getSafeUserId(), roomId); + const [roomScheduledTime, setRoomScheduledTime] = useAtom( + roomIdToScheduledTimeAtomFamily(scheduledStateKey) + ); + const [roomEditingScheduledDelayId, setRoomEditingScheduledDelayId] = useAtom( + roomIdToEditingScheduledDelayIdAtomFamily(scheduledStateKey) + ); + 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); @@ -516,16 +686,38 @@ 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(); 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) => { @@ -575,9 +767,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); @@ -590,6 +786,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(); @@ -604,15 +803,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); @@ -662,7 +869,7 @@ export const RoomInput = forwardRef( resetEditorHistory(editor); Transforms.insertFragment(editor, initialValue); - requestAnimationFrame(() => { + scheduleEditorRaf(() => { try { ReactEditor.focus(editor); moveCursor(editor); @@ -671,7 +878,9 @@ export const RoomInput = forwardRef( } }); } + setInitializedEditId(editId); } else { + editingStateRef.current = false; const previousDraft = preEditDraftRef.current; if (prevEditingEventId.current && previousDraft) { resetEditor(editor); @@ -683,7 +892,7 @@ export const RoomInput = forwardRef( prevEditingEventId.current && (!replyDraft?.eventId || replyDraft.eventId === threadRootId) ) { - requestAnimationFrame(() => { + scheduleEditorRaf(() => { try { const domNode = ReactEditor.toDOMNode(editor, editor); domNode.blur(); @@ -694,8 +903,10 @@ export const RoomInput = forwardRef( }); } prevEditingEventId.current = undefined; + setInitializedEditId(undefined); } }, [ + editId, editingEvent, editor, getEditingContent, @@ -704,6 +915,10 @@ export const RoomInput = forwardRef( room, replyDraft?.eventId, threadRootId, + isMobile, + setInitializedEditId, + onCancelEdit, + scheduleEditorRaf, ]); useEffect(() => { @@ -736,7 +951,7 @@ export const RoomInput = forwardRef( prevReplyEventId.current = newId; if (newId && newId !== threadRootId) { - requestAnimationFrame(() => { + scheduleEditorRaf(() => { try { ReactEditor.focus(editor); moveCursor(editor); @@ -745,7 +960,7 @@ export const RoomInput = forwardRef( } }); } else if (!newId && prevId && prevId !== threadRootId && !editId) { - requestAnimationFrame(() => { + scheduleEditorRaf(() => { try { const domNode = ReactEditor.toDOMNode(editor, editor); domNode.blur(); @@ -756,10 +971,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, @@ -770,6 +989,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, @@ -785,13 +1009,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], @@ -812,7 +1041,10 @@ export const RoomInput = forwardRef( const audioRecorder = showAudioRecorder ? ( setShowAudioRecorder(false)} + onRequestClose={() => { + recorderActionRef.current = undefined; + setShowAudioRecorder(false); + }} onRecordingComplete={handleAudioRecordingComplete} onAudioLengthUpdate={() => {}} onWaveformUpdate={() => {}} @@ -828,8 +1060,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. @@ -850,39 +1127,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(mx, 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, @@ -892,40 +1191,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(mx, 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; } }; @@ -945,11 +1269,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, }) @@ -957,26 +1287,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; @@ -986,30 +1314,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(() => { @@ -1051,494 +1419,289 @@ export const RoomInput = forwardRef( [editor, handleCloseAutocomplete, mx, room, sendTypingStatus] ); - const submit = useCallback(async () => { - if (editingEvent && isMobileOrTablet()) { - let plainText = toPlainText(editor.children).trim(); - if (!plainText) { - onCancelEdit?.(); + const executeSubmit = useCallback( + async (submission: Submission, isLive: () => boolean) => { + if ( + fileIngestionCountRef.current > 0 || + isEditInitializing || + (isMobile && editId !== undefined && !editingEvent) + ) { + restoreSubmission(submission); 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 - ); - - await mx.sendMessage(roomId, content as RoomMessageEventContent); - 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; - } - - 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, - settingsLinkBaseUrl, - }; - - outgoingMessageTransforms.forEach((transform) => { - if (!transform.shouldApply(serializedChildren, outgoingTransformContext)) return; - serializedChildren = transform.apply(serializedChildren, outgoingTransformContext); - }); - - 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, - }) - ); - - let msgType = MsgType.Text; - - // quick text react - if (canSendReaction && plainText.startsWith('+#')) { - handleQuickReact(plainText.substring(2)); - 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 (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) - setShowLocationPicker(true); - else { - const commandContent = commands[commandName as Command]; - if (commandContent) { - commandContent.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); + 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; + } - 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); + 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(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') { + restoreReplyClaim(submission.replyClaim); + setInitialGifSearch(outgoing.query); + setEmojiBoardTab(EmojiBoardTab.Gif); + return; + } + if (outgoing.kind === 'command') { + const { command, plainText, customHtml } = outgoing; + if (command === Command.Poll) { + restoreReplyClaim(submission.replyClaim); + setShowPollPicker(true); + } else if (command === Command.Location && plainText.trim().length === 0) { + restoreReplyClaim(submission.replyClaim); + 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(mx, 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(mx, 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, + 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, + restoreReplyClaim, + restoreSubmission, + isMobile, + editId, + isEditInitializing, + pmpLatchingEnable, + pmpNoFallback, + latchedPersona, + ] + ); - 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, - }) + 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, + }); + return ( + composerControllerRef.current?.enqueue((isLive) => executeSubmit(submission, isLive)) ?? + Promise.resolve(undefined) ); - - 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, - perMessageProfile.name.trim() !== '' - ); - - if (perMessageProfile.name.trim() !== '') { - // if a per-message profile is used, it must per spec include a fallback - const pmpPrefix = `${perMessageProfile.name}: `; - - 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.name); - - 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); - } - 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, - 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, - ]); + }, [editingEvent, executeSubmit, isMobile, takeSubmission]); const handleKeyDown: KeyboardEventHandler = useCallback( (evt) => { @@ -1645,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) => { @@ -1694,7 +1828,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); @@ -1737,27 +1873,47 @@ 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 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 content = await getGifMsgContent(mx, gif, url, spoiler); - if (!content) return; + 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'); - await handleSendContents([content]); + const content = await getGifMsgContent(mx, gif, url, spoiler); + if (!content) throw new Error('Unsendable GIF content'); + + const sent = await handleSendContents({ contents: [content], submission, isLive }); + // When the editor has text, the reply is not attached to the GIF, so hand the + // claim back for the follow-up message to carry it. + if (sent && submission.replyClaim && toPlainText(submission.children).trim().length > 0) + restoreReplyClaim(submission.replyClaim); + return sent; + } catch (error) { + log.error('failed to send gif', { roomId }, error); + restoreReplyClaim(submission.replyClaim); + return false; + } + }); }; return ( @@ -1863,14 +2019,6 @@ export const RoomInput = forwardRef( 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} @@ -2221,6 +2369,7 @@ export const RoomInput = forwardRef( onCustomEmojiSelect={handleEmoticonSelect} onStickerSelect={handleStickerSelect} onGifSelect={handleGifSelect} + initialGifSearch={initialGifSearch} requestClose={closeEmojiBoard} /> ); @@ -2367,7 +2516,7 @@ export const RoomInput = forwardRef( aria-pressed={!hasContent && editorMicButton ? showAudioRecorder : undefined} onClick={() => { if (showAudioRecorder) { - audioRecorderRef.current?.stop(); + requestRecorderStop(); return; } if (hasContent) { @@ -2380,6 +2529,7 @@ export const RoomInput = forwardRef( } if (!editorMicButton) return; if (isMobileOrTablet()) return; + recorderActionRef.current = undefined; setShowAudioRecorder(true); }} onMouseDown={(e: MouseEvent) => { @@ -2389,7 +2539,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); @@ -2399,22 +2549,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(); } @@ -2440,8 +2595,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) @@ -2504,7 +2663,7 @@ export const RoomInput = forwardRef( } /> - {delayedEventsSupported && !isMobileOrTablet() && ( + {delayedEventsSupported && !isMobileOrTablet() && !threadRootId && ( ) => { setScheduleMenuAnchor(evt.currentTarget.getBoundingClientRect()); @@ -2524,7 +2683,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/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) => ( handleEdit(undefined), [handleEdit]); + const onEditLastMessage = useCallback(() => editLastMessageRef.current?.(), []); useDelayedEventsSupport(); const delayedEventsSupported = useAtomValue(delayedEventsSupportedAtom); @@ -194,9 +196,9 @@ export function RoomView({ eventId }: { eventId?: string }) { roomId={roomId} fileDropContainerRef={roomViewRef} ref={roomInputRef} - onEditLastMessage={() => editLastMessageRef.current?.()} + onEditLastMessage={onEditLastMessage} editId={editId} - onCancelEdit={() => handleEdit(undefined)} + onCancelEdit={onCancelEdit} /> )} {!canMessage && ( diff --git a/src/app/features/room/ThreadDrawer.tsx b/src/app/features/room/ThreadDrawer.tsx index 3cf0f5136..5531fee23 100644 --- a/src/app/features/room/ThreadDrawer.tsx +++ b/src/app/features/room/ThreadDrawer.tsx @@ -231,6 +231,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra id: ev.getId() ?? `thread-reply-${idx}`, itemIndex: idx, mEvent: ev, + isRedacted: ev.isRedacted(), timelineSet, eventSender: ev.getSender() ?? null, collapsed: false, diff --git a/src/app/features/room/buildReplacementContent.ts b/src/app/features/room/buildReplacementContent.ts index 2b3e24fa8..4c680135d 100644 --- a/src/app/features/room/buildReplacementContent.ts +++ b/src/app/features/room/buildReplacementContent.ts @@ -2,8 +2,11 @@ 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 { convertPerMessageProfileToBeeperFormat } from '$hooks/usePerMessageProfile'; +import type { PerMessageProfileMsc4461 } from '$hooks/usePerMessageProfile'; +import { + convertPerMessageProfileToBeeperFormat, + stripPerMessageProfileFormattedBody, +} from '$hooks/usePerMessageProfile'; import { MATRIX_UNSTABLE_PER_MESSAGE_PROFILE_PROPERTY_NAME } from '$unstable/prefixes'; /** @@ -17,7 +20,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 +35,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; @@ -100,7 +104,7 @@ export function buildReplacementContent( export function buildReplacementPmpContent( oldContent: IContent, eventId: string, - newProfile: PerMessageProfile | undefined + newProfile: PerMessageProfileMsc4461 | undefined ) { const profileBeeperFormat = newProfile && convertPerMessageProfileToBeeperFormat(newProfile, true); @@ -111,17 +115,16 @@ 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; } if (newProfile) { - const escapedName = sanitizeText(newProfile.name); + const escapedName = sanitizeText(newProfile.displayname); const htmlPrefix = `${escapedName}: `; if (oldContent.formatted_body) { @@ -133,7 +136,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/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/composerMessage.test.ts b/src/app/features/room/composerMessage.test.ts new file mode 100644 index 000000000..e41edc067 --- /dev/null +++ b/src/app/features/room/composerMessage.test.ts @@ -0,0 +1,211 @@ +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).toBe( + 'Alter: hello' + ); + }); + + 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'); + expect(result.content.formatted_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..dc66bed01 --- /dev/null +++ b/src/app/features/room/composerMessage.ts @@ -0,0 +1,336 @@ +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}: `; + 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; + + 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(bodyWithoutFallback).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 + ); +} 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/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' }, }); diff --git a/src/app/features/room/message/Message.tsx b/src/app/features/room/message/Message.tsx index c3e13c960..29575fe3d 100644 --- a/src/app/features/room/message/Message.tsx +++ b/src/app/features/room/message/Message.tsx @@ -133,6 +133,7 @@ export type MessageProps = { import { useMenuAnchor } from '$hooks/useMenuAnchor'; import { ThemeKind, useActiveTheme } from '$hooks/useTheme'; +import { useAccessibleNameColor } from '$hooks/useAccessibleNameColor'; import { shouldIgnoreMessageLongPress } from './messageTouch'; const clamp = (str: string, len: number) => (str.length > len ? `${str.slice(0, len)}...` : str); @@ -458,8 +459,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 +469,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( @@ -477,6 +478,9 @@ function MessageInternal( false, isVisible ); + + const accessibleNameColor = useAccessibleNameColor(activeTheme.kind); + const senderFallbackName = getMxIdLocalPart(senderId) ?? senderId; const resolvedSenderDisplayName = senderDisplayName === senderFallbackName || senderDisplayName === senderId @@ -488,7 +492,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'); @@ -588,7 +592,7 @@ function MessageInternal( )} {showPmPInfo && ( diff --git a/src/app/features/room/message/MessageEditor.tsx b/src/app/features/room/message/MessageEditor.tsx index 7829440f4..f72c66e36 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 @@ -126,6 +127,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] = @@ -164,10 +166,7 @@ export const MessageEditor = as<'div', MessageEditorProps>( } if (pmpDisplayname && typeof customHtml === 'string') { - customHtml = customHtml.replace( - /^]*>.*?<\/strong>/, - '' - ); + customHtml = stripPerMessageProfileFormattedBody(customHtml); } const bundleContent = @@ -292,11 +291,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(() => { @@ -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(() => { 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/features/room/persona-picker/PersonaPicker.test.tsx b/src/app/features/room/persona-picker/PersonaPicker.test.tsx new file mode 100644 index 000000000..6051f0bb7 --- /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 { TemporaryPersonaPicker, 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 a5173d294..db23973b6 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, @@ -33,137 +33,180 @@ 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'; +import { InfoIcon } from '@phosphor-icons/react'; import { ThemeKind, useActiveTheme } from '$hooks/useTheme.ts'; 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; roomId?: string; suppressEditorRefocus?: () => void; onTabChange?: (tab: PersonaPickerTab) => void; - latchedPersona?: PerMessageProfile; - hideTabs?: boolean; - onPersonaSelect?: (persona: PerMessageProfile | undefined) => void; + latchedPersona?: PerMessageProfileMsc4461; + onPersonaSelect?: (persona: PerMessageProfileMsc4461 | undefined) => void | Promise; 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 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 activeTheme = useActiveTheme(); const [AddPersonaMenuAnchor, setAddPersonaMenuAnchor] = useState(anchor); - const [profiles, setProfiles] = useState(undefined); - const [selectedGlobalPersona, setSelectedGlobalPersona] = useState( - null - ); - const [selectedRoomPersona, setSelectedRoomPersona] = useState( + 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) => + activeTheme.kind === ThemeKind.Dark + ? persona['eu.she-a.color']?.on_dark + : persona['eu.she-a.color']?.on_light, + [activeTheme] + ); const defactoPersona = () => selectedRoomPersona ?? selectedGlobalPersona; - const activeTheme = useActiveTheme(); - - 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) => { @@ -172,7 +215,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,28 +225,11 @@ 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) => { - 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: 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; } @@ -211,58 +237,16 @@ function PersonaPicker({ [mx, useAuthentication] ); - const handleSelect = useCallback( - async (profile: PerMessageProfile | 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={ @@ -271,15 +255,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={ ( - {nameInitials(profile.name)} + {nameInitials(profile.displayname)} )} alt={`Avatar for profile ${profile.id}`} @@ -335,104 +379,76 @@ function PersonaPicker({ truncate style={{ color: nameColor(profile) ?? undefined, maxWidth: toRem(150) }} > - {profile.name} + {profile.displayname} ))} - {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()!.name)} - - )} - 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/features/room/schedule-send/ScheduledMessagesList.test.tsx b/src/app/features/room/schedule-send/ScheduledMessagesList.test.tsx new file mode 100644 index 000000000..873c51c4b --- /dev/null +++ b/src/app/features/room/schedule-send/ScheduledMessagesList.test.tsx @@ -0,0 +1,202 @@ +/* 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), + getScheduledMessageStateKey: (userId: string, roomId: string) => `${userId}\0${roomId}`, + 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( + (_mx: unknown, _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( + testState.matrix, + 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..683e1f9d9 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, @@ -21,12 +21,14 @@ import { } from '$utils/delayedEvents'; import { delayedEventsSupportedAtom, + getScheduledMessageStateKey, roomIdToScheduledTimeAtomFamily, roomIdToEditingScheduledDelayIdAtomFamily, } from '$state/scheduledMessages'; 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 +46,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 +60,7 @@ function ScheduledMessageRow({ hour24Clock, onEdit, onCancel, + cancellationState, }: ScheduledMessageRowProps) { const mx = useMatrixClient(); const [dateFormatString] = useSetting(settingsAtom, 'dateFormatString'); @@ -63,6 +72,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 +117,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 +139,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} + + )} ); } @@ -140,12 +160,17 @@ 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>( + {} + ); + const pendingCancellations = useRef(new Set()); const { data } = useQuery({ queryKey: ['delayedEvents', room.roomId], @@ -167,10 +192,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(mx, 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 +268,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/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/Persona/PerMessageProfileEditor.tsx b/src/app/features/settings/Persona/PerMessageProfileEditor.tsx index 5463cdcb3..0e2fb8ba3 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,62 @@ 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'; +import { accessibleColor } from '$plugins/color'; +import { ThemeKind } from '$hooks/useTheme'; -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 +75,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 +136,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 +188,7 @@ type PerMessageProfileEditorProps = { pronouns?: PronounSet[]; nameColorLightTheme?: string; nameColorDarkTheme?: string; - shorthands?: Shorthand[]; + shorthands?: ProfileTrigger; onDelete?: (profileId: string) => void; }; @@ -334,6 +200,7 @@ export function PerMessageProfileEditor({ pronouns = Array(), nameColorLightTheme, nameColorDarkTheme, + shorthands, onDelete, }: Readonly) { const useAuthentication = useMediaAuthentication(); @@ -364,6 +231,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 +314,7 @@ export function PerMessageProfileEditor({ newPronounsString !== currentPronounsString || newNameColorLight !== currentNameColorLight || newNameColorDark !== currentNameColorDark || + newShorthands !== currentShorthands || hasIdChange || imageHasChanges, [ @@ -420,6 +326,8 @@ export function PerMessageProfileEditor({ currentNameColorLight, newNameColorDark, currentNameColorDark, + newShorthands, + currentShorthands, hasIdChange, imageHasChanges, ] @@ -447,10 +355,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 +369,7 @@ export function PerMessageProfileEditor({ setCurrentPronouns(newPronouns); setCurrentNameColorLight(newNameColorLight); setCurrentNameColorDark(newNameColorDark); + setCurrentShorthands(newShorthands); setImageHasChanges(false); setChangingDisplayName(false); setDisableSetDisplayname(false); @@ -476,6 +386,7 @@ export function PerMessageProfileEditor({ newPronouns, newNameColorLight, newNameColorDark, + newShorthands, hasIdChange, newId, ]) @@ -694,8 +605,22 @@ export function PerMessageProfileEditor({ description="This persona's name color for a dark theme user." focusId={`nameColorDarkTheme-${profileId}`} current={currentNameColorDark ?? undefined} + newNameColor={newNameColorDark ?? undefined} onChange={setNewNameColorDark} /> + {!newNameColorLight && newNameColorDark && ( + + + + )} + {!newNameColorDark && newNameColorLight && ( + + + + )} 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/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..4edceb7f4 --- /dev/null +++ b/src/app/features/settings/accessibility/Accessibility.tsx @@ -0,0 +1,185 @@ +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 accessibilityScrollRef = useRef(null); + + return ( + + + + + + + + + + + + + ); +} diff --git a/src/app/features/settings/account/NameColorEditor.tsx b/src/app/features/settings/account/NameColorEditor.tsx index d948c9809..bfd6557f2 100644 --- a/src/app/features/settings/account/NameColorEditor.tsx +++ b/src/app/features/settings/account/NameColorEditor.tsx @@ -11,6 +11,7 @@ type NameColorEditorProps = { description?: string; focusId?: string; current?: string; + newNameColor?: string; onChange?: (color: string | null) => 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 && ( + + )} + + )} } /> - - - - 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)', - }} - /> - } - /> - - - - - - - { 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/features/settings/notifications/SystemNotification.tsx b/src/app/features/settings/notifications/SystemNotification.tsx index 3d7827889..1ececb70d 100644 --- a/src/app/features/settings/notifications/SystemNotification.tsx +++ b/src/app/features/settings/notifications/SystemNotification.tsx @@ -37,7 +37,6 @@ import { } from './PushNotifications'; import { DeregisterAllPushersSetting } from './DeregisterPushNotifications'; import { - deriveLegacyPushFlags, disableNativePush, enableNativePush, getSupportedNotificationTransportModes, @@ -76,13 +75,6 @@ function getBackgroundPushPlatform(isTauriRuntime: boolean): BackgroundPushPlatf return 'desktop'; } -function deriveLegacyPushSync(input: { enabled: boolean; provider: BackgroundPushKind | null }): { - usePushNotifications: boolean; - useUnifiedPush: boolean; -} { - return deriveLegacyPushFlags(input.enabled, input.provider); -} - export async function switchBackgroundPushTransport(params: { previousKind: BackgroundPushKind | null; activate: () => Promise; @@ -352,11 +344,6 @@ function BackgroundPushNotificationSetting() { ); const [useRichPushPayloads] = useSetting(settingsAtom, 'useRichPushPayloads'); const [pushNotifyUrlOverride] = useSetting(settingsAtom, 'pushNotifyUrlOverride'); - const [legacyPushNotifications, setLegacyPushNotifications] = useSetting( - settingsAtom, - 'usePushNotifications' - ); - const [legacyUnifiedPush, setLegacyUnifiedPush] = useSetting(settingsAtom, 'useUnifiedPush'); const pushSubAtom = useAtom(pushSubscriptionAtom); const [upEndpoint, setUpEndpoint] = useAtom(unifiedPushEndpointAtom); const unifiedPushStateRef = useRef(upEndpoint); @@ -407,28 +394,6 @@ function BackgroundPushNotificationSetting() { unifiedPushStateRef.current = upEndpoint; }, [upEndpoint]); - useEffect(() => { - const sync = deriveLegacyPushSync({ - enabled: backgroundPushEnabled, - provider: backgroundPushEnabled ? (backgroundPushProvider ?? preferredKind) : null, - }); - - if (legacyPushNotifications !== sync.usePushNotifications) { - setLegacyPushNotifications(sync.usePushNotifications); - } - if (legacyUnifiedPush !== sync.useUnifiedPush) { - setLegacyUnifiedPush(sync.useUnifiedPush); - } - }, [ - backgroundPushEnabled, - backgroundPushProvider, - preferredKind, - legacyPushNotifications, - legacyUnifiedPush, - setLegacyPushNotifications, - setLegacyUnifiedPush, - ]); - useEffect(() => { if (runtimePlatform !== 'android') { setAvailableDistributors([]); diff --git a/src/app/features/settings/notifications/TauriNotificationsApiClient.ts b/src/app/features/settings/notifications/TauriNotificationsApiClient.ts index 71716c82d..d5d7face9 100644 --- a/src/app/features/settings/notifications/TauriNotificationsApiClient.ts +++ b/src/app/features/settings/notifications/TauriNotificationsApiClient.ts @@ -20,6 +20,7 @@ export type TauriNotificationsApi = { importance?: number; vibration?: boolean; }) => Promise; + removeChannel: (id: string) => Promise; isPermissionGranted: () => Promise; requestPermission: () => Promise; sendNotification: (payload: Record) => Promise; diff --git a/src/app/features/settings/notifications/UnifiedPushNotifications.test.ts b/src/app/features/settings/notifications/UnifiedPushNotifications.test.ts index 1a624b27e..272242c06 100644 --- a/src/app/features/settings/notifications/UnifiedPushNotifications.test.ts +++ b/src/app/features/settings/notifications/UnifiedPushNotifications.test.ts @@ -14,8 +14,10 @@ const notificationsApi = vi.hoisted(() => ({ sendNotification: vi.fn<(notification: Record) => Promise>(), removeActive: vi.fn<(notifications: Array<{ id: number }>) => Promise>(), createChannel: vi.fn<() => void>(), + removeChannel: vi.fn<() => Promise>(), Importance: { Default: 3, + High: 4, }, })); @@ -88,6 +90,7 @@ function makeRoom() { const encryptedPush = (eventId: string) => ({ type: 'm.room.encrypted', + user_id: '@user:example.com', room_id: '!room:example.com', room_name: 'Room', event_id: eventId, @@ -101,6 +104,7 @@ describe('UnifiedPushNotifications', () => { notificationsApi.sendNotification.mockResolvedValue(undefined); notificationsApi.removeActive.mockResolvedValue(undefined); notificationsApi.createChannel.mockResolvedValue(undefined); + notificationsApi.removeChannel.mockResolvedValue(undefined); getTauriNotificationsApi.mockResolvedValue(notificationsApi); unifiedPushTransport.registerUnifiedPushTransport.mockResolvedValue({ status: 'registered', @@ -145,9 +149,34 @@ describe('UnifiedPushNotifications', () => { async function listenAndPush(payload: Record, settings = makeSettings()) { await listenForUnifiedPushMessages(() => settings as never); - pushHandler({ message: JSON.stringify(payload) }); + pushHandler({ + message: JSON.stringify({ user_id: '@user:example.com', ...payload }), + }); } + it('ignores pushes without an exact active-account identity', async () => { + await listenForUnifiedPushMessages(() => makeSettings() as never); + + pushHandler({ + message: JSON.stringify({ + type: 'm.room.message', + room_id: '!room:example.com', + content: { body: 'unscoped' }, + }), + }); + pushHandler({ + message: JSON.stringify({ + type: 'm.room.message', + user_id: '@other:example.com', + room_id: '!room:example.com', + content: { body: 'wrong account' }, + }), + }); + + await vi.waitFor(() => expect(notificationsApi.sendNotification).not.toHaveBeenCalled()); + expect(matrixClient.getRoom).not.toHaveBeenCalled(); + }); + it('posts an encrypted baseline before a hanging local decryption completes', async () => { matrixClient.getRoom.mockReturnValue(makeRoom()); let resolveDecryption!: (content: Record) => void; @@ -180,6 +209,55 @@ describe('UnifiedPushNotifications', () => { await vi.waitFor(() => expect(notificationsApi.sendNotification).toHaveBeenCalledTimes(2)); }); + it('posts message notifications as a conversation on the high-importance channel', async () => { + matrixClient.getRoom.mockReturnValue(makeRoom()); + + await listenAndPush({ + type: 'm.room.message', + room_id: '!room:example.com', + room_name: 'Room', + event_id: '$plain:example.com', + sender: '@alice:example.com', + sender_display_name: 'Alice', + content: { body: 'hello' }, + }); + + await vi.waitFor(() => expect(notificationsApi.sendNotification).toHaveBeenCalledOnce()); + expect(notificationsApi.sendNotification.mock.calls[0]?.[0]).toMatchObject({ + channelId: 'messages.v2', + groupConversation: false, + messages: [{ body: 'hello', senderName: 'Alice', senderKey: '@alice:example.com' }], + }); + }); + + it('posts invitations on their own channel', async () => { + await listenAndPush({ + type: 'm.room.member', + room_id: '!room:example.com', + room_name: 'Room', + sender_display_name: 'Alice', + content: { membership: 'invite' }, + }); + + await vi.waitFor(() => expect(notificationsApi.sendNotification).toHaveBeenCalledOnce()); + expect(notificationsApi.sendNotification.mock.calls[0]?.[0]).toMatchObject({ + channelId: 'invites', + title: 'New Invitation', + }); + }); + + it('creates the messages channel at high importance and drops the legacy one', async () => { + await tryEnableUnifiedPush(matrixClient as never); + + expect(notificationsApi.createChannel).toHaveBeenCalledWith( + expect.objectContaining({ id: 'messages.v2', importance: 4 }) + ); + expect(notificationsApi.createChannel).toHaveBeenCalledWith( + expect.objectContaining({ id: 'invites' }) + ); + expect(notificationsApi.removeChannel).toHaveBeenCalledWith('messages'); + }); + it('silently updates the same notification after encrypted decryption succeeds', async () => { matrixClient.getRoom.mockReturnValue(makeRoom()); matrixClient.getCrypto.mockReturnValue({ @@ -232,7 +310,7 @@ describe('UnifiedPushNotifications', () => { expect(decryptEvent).not.toHaveBeenCalled(); }); - it('discards encrypted enrichment that resolves after the observation deadline', async () => { + it('applies encrypted enrichment that only decrypts long after the baseline post', async () => { vi.useFakeTimers(); try { matrixClient.getRoom.mockReturnValue(makeRoom()); @@ -244,18 +322,50 @@ describe('UnifiedPushNotifications', () => { decryptEvent: vi.fn<() => Promise>>().mockReturnValue(decryption), }); - await listenAndPush(encryptedPush('$deadline:example.com')); + await listenAndPush(encryptedPush('$late:example.com')); await vi.waitFor(() => expect(notificationsApi.sendNotification).toHaveBeenCalledOnce()); - vi.advanceTimersByTime(2_500); + vi.advanceTimersByTime(30_000); resolveDecryption({ clearEvent: { type: 'm.room.message', content: { body: 'late plaintext' }, }, }); - await Promise.resolve(); - await Promise.resolve(); + + await vi.waitFor(() => expect(notificationsApi.sendNotification).toHaveBeenCalledTimes(2)); + expect(notificationsApi.sendNotification.mock.calls[1]?.[0]).toMatchObject({ + body: 'You: late plaintext', + silent: true, + }); + } finally { + vi.useRealTimers(); + } + }); + + it('stops waiting for the room key once the retry window elapses', async () => { + vi.useFakeTimers(); + try { + matrixClient.getRoom.mockReturnValue(makeRoom()); + let resolveDecryption!: (content: Record) => void; + const decryption = new Promise>((resolve) => { + resolveDecryption = resolve; + }); + matrixClient.getCrypto.mockReturnValue({ + decryptEvent: vi.fn<() => Promise>>().mockReturnValue(decryption), + }); + + await listenAndPush(encryptedPush('$expired:example.com')); + await vi.waitFor(() => expect(notificationsApi.sendNotification).toHaveBeenCalledOnce()); + + await vi.advanceTimersByTimeAsync(5 * 60_000); + resolveDecryption({ + clearEvent: { + type: 'm.room.message', + content: { body: 'far too late' }, + }, + }); + await vi.advanceTimersByTimeAsync(0); expect(notificationsApi.sendNotification).toHaveBeenCalledOnce(); } finally { @@ -386,20 +496,8 @@ describe('UnifiedPushNotifications', () => { ); }); - it('serializes cross-room summary writes and refreshes from current caches', async () => { + it('posts one notification per room and no account-level summary', async () => { matrixClient.getRoom.mockReturnValue(makeRoom()); - const summaryPosts: Record[] = []; - let releaseFirstSummary!: () => void; - const firstSummary = new Promise((resolve) => { - releaseFirstSummary = resolve; - }); - notificationsApi.sendNotification.mockImplementation(async (notification) => { - if (notification.groupSummary) { - summaryPosts.push(notification); - if (summaryPosts.length === 1) await firstSummary; - } - }); - await listenForUnifiedPushMessages(() => makeSettings() as never); const roomPayload = (roomId: string, eventId: string, roomName: string) => ({ ...encryptedPush(eventId), @@ -407,108 +505,38 @@ describe('UnifiedPushNotifications', () => { room_name: roomName, }); pushHandler({ message: JSON.stringify(roomPayload('!room-a:example.com', '$a', 'Room A')) }); - await vi.waitFor(() => expect(notificationsApi.sendNotification).toHaveBeenCalledOnce()); pushHandler({ message: JSON.stringify(roomPayload('!room-b:example.com', '$b', 'Room B')) }); - await vi.waitFor(() => expect(summaryPosts).toHaveLength(1)); - pushHandler({ message: JSON.stringify(roomPayload('!room-c:example.com', '$c', 'Room C')) }); - releaseFirstSummary(); - await vi.waitFor(() => expect(summaryPosts).toHaveLength(2)); - - expect(summaryPosts[0]).toMatchObject({ title: '2 messages in 2 chats' }); - expect(summaryPosts[1]).toMatchObject({ title: '3 messages in 3 chats' }); + await vi.waitFor(() => expect(notificationsApi.sendNotification).toHaveBeenCalledTimes(2)); + const posted = notificationsApi.sendNotification.mock.calls.map( + ([notification]) => notification + ); + expect(posted.some((notification) => notification.groupSummary)).toBe(false); + expect(new Set(posted.map((notification) => notification.title))).toEqual( + new Set(['Room A', 'Room B']) + ); + expect(new Set(posted.map((notification) => notification.id)).size).toBe(2); }); - it('compensates a summary that observed a baseline pending for another room', async () => { + it('dismisses a group summary left behind by an older version', async () => { + await listenForUnifiedPushMessages(() => makeSettings() as never); + + await vi.waitFor(() => expect(notificationsApi.removeActive).toHaveBeenCalledOnce()); + expect(notificationsApi.removeActive.mock.calls[0]?.[0]).toEqual([{ id: expect.any(Number) }]); + }); + + it('clears a room even when dismissing its notification fails', async () => { matrixClient.getRoom.mockReturnValue(makeRoom()); - let rejectFailedPost!: (error: Error) => void; - let failedPostStarted!: () => void; - const failedPost = new Promise((_, reject) => { - rejectFailedPost = reject; - }); - const failedPostStartedPromise = new Promise((resolve) => { - failedPostStarted = resolve; - }); - const summaryPosts: Record[] = []; - notificationsApi.sendNotification.mockImplementation(async (notification) => { - const eventId = (notification.extra as Record | undefined)?.event_id; - if (eventId === '$a-failed') { - failedPostStarted(); - await failedPost; - return; - } - if (notification.groupSummary) summaryPosts.push(notification); - }); - await listenForUnifiedPushMessages(() => makeSettings() as never); - const roomPayload = ( - roomId: string, - eventId: string, - roomName: string, - sender_display_name: string - ) => ({ - ...encryptedPush(eventId), - room_id: roomId, - room_name: roomName, - sender_display_name, - }); pushHandler({ - message: JSON.stringify( - roomPayload('!room-a:example.com', '$a-old', 'Room A', 'Old message') - ), + message: JSON.stringify({ ...encryptedPush('$a'), room_id: '!room-a:example.com' }), }); await vi.waitFor(() => expect(notificationsApi.sendNotification).toHaveBeenCalledOnce()); - pushHandler({ - message: JSON.stringify( - roomPayload('!room-a:example.com', '$a-failed', 'Room A', 'Failed message') - ), - }); - await failedPostStartedPromise; - pushHandler({ - message: JSON.stringify(roomPayload('!room-b:example.com', '$b', 'Room B', 'B message')), - }); - await vi.waitFor(() => expect(summaryPosts).toHaveLength(1)); - - rejectFailedPost(new Error('pending baseline failed')); - await vi.waitFor(() => expect(summaryPosts).toHaveLength(2)); - - expect(summaryPosts[0]?.inboxLines).toEqual( - expect.arrayContaining(['Room A: Failed message: Encrypted message']) - ); - expect(summaryPosts[1]?.inboxLines).toEqual( - expect.arrayContaining(['Room A: Old message: Encrypted message']) - ); - expect(summaryPosts[1]?.inboxLines).not.toEqual( - expect.arrayContaining(['Room A: Failed message: Encrypted message']) - ); - }); - - it('still cleans up the account summary when child removal fails', async () => { - matrixClient.getRoom.mockReturnValue(makeRoom()); - await listenForUnifiedPushMessages(() => makeSettings() as never); - const roomPayload = (roomId: string, eventId: string) => ({ - ...encryptedPush(eventId), - room_id: roomId, - }); - pushHandler({ message: JSON.stringify(roomPayload('!room-a:example.com', '$a')) }); - pushHandler({ message: JSON.stringify(roomPayload('!room-b:example.com', '$b')) }); - await vi.waitFor(() => - expect( - notificationsApi.sendNotification.mock.calls.some( - ([notification]) => notification.groupSummary - ) - ).toBe(true) - ); - - let removeAttempts = 0; - notificationsApi.removeActive.mockImplementation(async () => { - removeAttempts += 1; - if (removeAttempts === 1) throw new Error('child removal failed'); - }); - await clearRoomNotification('@user:example.com', '!room-a:example.com'); - - expect(removeAttempts).toBe(2); + notificationsApi.removeActive.mockRejectedValueOnce(new Error('child removal failed')); + await expect( + clearRoomNotification('@user:example.com', '!room-a:example.com') + ).resolves.toBeUndefined(); }); it('checks preview policy again after a minimal event resolves', async () => { diff --git a/src/app/features/settings/notifications/UnifiedPushNotifications.ts b/src/app/features/settings/notifications/UnifiedPushNotifications.ts index 31ed4dda7..8c1846f94 100644 --- a/src/app/features/settings/notifications/UnifiedPushNotifications.ts +++ b/src/app/features/settings/notifications/UnifiedPushNotifications.ts @@ -3,6 +3,7 @@ import { type IPusherRequest, type MatrixClient, MatrixEvent, + MatrixEventEvent, } from '$types/matrix-sdk'; import { EventType } from 'matrix-js-sdk/lib/@types/event'; import { @@ -11,7 +12,6 @@ import { } from '$utils/notificationStyle'; import { getMxIdLocalPart } from '$utils/matrix'; import { getStateEvent } from '$utils/room/hierarchy'; -import { getMemberAvatarMxc } from '$utils/room/display'; import { createDebugLogger } from '$utils/debugLogger'; import { registerUnifiedPushTransport, @@ -56,6 +56,34 @@ type UnifiedPushPayload = { const UP_REGISTER_TIMEOUT_MS = 30_000; +// Android freezes a channel's importance at creation, so raising `messages` from +// Default to High needs a new id. Mirrored in the plugin's UnifiedPushNotifier. +const MESSAGES_CHANNEL_ID = 'messages.v2'; +const INVITES_CHANNEL_ID = 'invites'; +const LEGACY_MESSAGES_CHANNEL_ID = 'messages'; + +async function ensureNotificationChannels( + notificationsApi: Awaited> +): Promise { + await notificationsApi.createChannel({ + id: MESSAGES_CHANNEL_ID, + name: 'Messages', + description: 'Matrix message notifications', + importance: notificationsApi.Importance.High, + vibration: true, + }); + await notificationsApi.createChannel({ + id: INVITES_CHANNEL_ID, + name: 'Invitations', + description: 'Room and space invitations', + importance: notificationsApi.Importance.Default, + vibration: true, + }); + await notificationsApi.removeChannel(LEGACY_MESSAGES_CHANNEL_ID).catch(() => { + // Never created on this device, or already gone. + }); +} + export type UnifiedPushTransportConfigInput = Pick< PushTransportConfig, 'unifiedPushGatewayUrl' | 'unifiedPushAppID' @@ -117,14 +145,7 @@ export async function tryEnableUnifiedPush( config?: UnifiedPushTransportConfigInput ): Promise { const notificationsApi = await getTauriNotificationsApi(); - - await notificationsApi.createChannel({ - id: 'messages', - name: 'Messages', - description: 'Matrix message and invite notifications', - importance: notificationsApi.Importance.Default, - vibration: true, - }); + await ensureNotificationChannels(notificationsApi); const registration = await registerUnifiedPushWithTimeout(config?.vapidPublicKey); @@ -305,12 +326,11 @@ type NotificationSettings = { const NOTIF_GROUP_KEY = 'matrix_messages'; const MAX_MESSAGES = 10; const MAX_SEEN_EVENT_IDS = 200; -const ENCRYPTED_PREVIEW_OBSERVATION_DEADLINE_MS = 2_500; +const ENCRYPTED_PREVIEW_RETRY_WINDOW_MS = 5 * 60_000; type NotifPerson = { name: string; key?: string; - iconUrl?: string; }; type NotifMessage = { @@ -351,29 +371,55 @@ async function resolvePreviewEvent( } /** - * Decrypts the ciphertext from a rich push payload locally — no homeserver - * fetch needed. The Megolm session keys are in the crypto store. This is - * what makes encrypted notifications as fast as Element. + * Rebuilds the encrypted event from a rich push payload so it can be decrypted + * locally — no homeserver fetch needed, the Megolm keys are in the crypto store. */ -async function decryptPreviewFromPayload( - mx: MatrixClient, +function buildEncryptedPreviewEvent( roomId: string, eventId: string, pushData: UnifiedPushPayload -): Promise { - const crypto = mx.getCrypto(); - if (!crypto || !pushData.content) return undefined; - const mEvent = new MatrixEvent({ - type: EventType.RoomMessageEncrypted, +): MatrixEvent | undefined { + if (!pushData.content) return undefined; + return new MatrixEvent({ + type: 'm.room.encrypted', content: pushData.content, room_id: roomId, event_id: eventId, sender: pushData.sender, origin_server_ts: Date.now(), }); - await mEvent.attemptDecryption(crypto as CryptoBackend); - if (mEvent.isDecryptionFailure()) throw new Error('Encrypted preview decryption failed'); - return mEvent; +} + +function holdsPlaintext(event: MatrixEvent): boolean { + return ( + !event.isDecryptionFailure() && event.getType() !== EventType.RoomMessageEncrypted.toString() + ); +} + +/** + * Runs `apply` as soon as `event` holds plaintext: right away when it is already + * decrypted, or later once the Megolm key arrives — a backgrounded app routinely + * receives the push before the to-device key, and the SDK retries decryption on + * its own when the key lands. + */ +function whenDecrypted(event: MatrixEvent, apply: () => Promise): void { + if (holdsPlaintext(event)) { + void apply(); + return; + } + + const onDecrypted = () => { + if (!holdsPlaintext(event)) return; + event.off(MatrixEventEvent.Decrypted, onDecrypted); + clearTimeout(retryWindowTimer); + void apply(); + }; + + event.on(MatrixEventEvent.Decrypted, onDecrypted); + const retryWindowTimer = setTimeout(() => { + event.off(MatrixEventEvent.Decrypted, onDecrypted); + unifiedPushLog.warn('notification', 'Encrypted preview never decrypted within retry window'); + }, ENCRYPTED_PREVIEW_RETRY_WINDOW_MS); } const roomNotifId = (userId: string, roomId: string) => hashCode(`${userId}\u0000${roomId}`); @@ -392,7 +438,6 @@ type RoomNotifCache = { const roomNotifCaches = new Map(); const roomNotifGenerations = new Map(); const roomNotifQueues = new Map>(); -const accountSummaryQueues = new Map>(); function enqueueRoomOperation(key: string, operation: () => Promise): Promise { const previous = roomNotifQueues.get(key) ?? Promise.resolve(); @@ -408,31 +453,6 @@ function enqueueRoomOperation(key: string, operation: () => Promise): Prom return task; } -function enqueueAccountSummaryOperation( - userId: string, - operation: () => Promise -): Promise { - const previous = accountSummaryQueues.get(userId) ?? Promise.resolve(); - const task = previous.then(operation, operation); - const completion = task.then( - () => undefined, - () => undefined - ); - accountSummaryQueues.set(userId, completion); - void completion.then(() => { - if (accountSummaryQueues.get(userId) === completion) accountSummaryQueues.delete(userId); - }); - return task; -} - -function resolveAvatarUrl(mx: MatrixClient, roomId: string, userId: string): string | undefined { - const room = mx.getRoom(roomId); - if (!room) return undefined; - const mxcUrl = getMemberAvatarMxc(room, userId); - if (!mxcUrl) return undefined; - return mx.mxcUrlToHttp(mxcUrl, 96, 96, 'crop', false, true, true) ?? undefined; -} - function getOrCreateRoomCache(userId: string, roomId: string, roomName: string): RoomNotifCache { const key = `${userId}\u0000${roomId}`; let cache = roomNotifCaches.get(key); @@ -463,71 +483,18 @@ export function resetUnifiedPushNotificationStateForTests(): void { roomNotifCaches.clear(); roomNotifGenerations.clear(); roomNotifQueues.clear(); - accountSummaryQueues.clear(); } -async function refreshAccountSummary( - userId: string, - removeWhenEmpty: boolean, - isCurrent?: () => boolean -): Promise { - await enqueueAccountSummaryOperation(userId, async () => { - let notificationsApi: Awaited>; - try { - notificationsApi = await getTauriNotificationsApi(); - } catch { - return; - } - if (isCurrent && !isCurrent()) return; - - const accountCaches = Array.from(roomNotifCaches.entries()).filter(([key]) => - key.startsWith(`${userId}\u0000`) - ); - const roomCount = accountCaches.length; - if (roomCount <= 1) { - if (removeWhenEmpty) { - try { - await notificationsApi.removeActive([{ id: summaryNotifId(userId) }]); - } catch { - // already dismissed - } - } - return; - } - - const totalMessages = accountCaches - .map(([, accountCache]) => accountCache) - .reduce((sum, accountCache) => sum + accountCache.messages.length, 0); - const summaryText = `${totalMessages} messages in ${roomCount} chats`; - const summaryLines: string[] = []; - accountCaches.forEach(([, accountCache]) => { - const latest = accountCache.messages[accountCache.messages.length - 1]; - if (latest) { - summaryLines.push( - `${accountCache.roomName}: ${latest.sender?.name ?? 'You'}: ${latest.text}` - ); - } - }); - - if (isCurrent && !isCurrent()) return; - try { - await notificationsApi.sendNotification({ - id: summaryNotifId(userId), - title: summaryText, - body: '', - summary: summaryText, - inboxLines: summaryLines.slice(-5), - channelId: 'messages', - group: NOTIF_GROUP_KEY, - groupSummary: true, - icon: 'notification_icon', - silent: true, - autoCancel: true, - }); - } catch { - // The room notification was already posted; a summary is best effort. - } - }); +// Older versions posted an account-level summary that collapsed every room into +// one entry; Android bundles the per-room notifications on its own. +async function dismissLegacyGroupSummary(userId: string): Promise { + if (!userId) return; + try { + const notificationsApi = await getTauriNotificationsApi(); + await notificationsApi.removeActive([{ id: summaryNotifId(userId) }]); + } catch { + // Nothing to dismiss, or the plugin is unavailable. + } } /** Clears accumulated messages for a room and dismisses its notification. */ @@ -542,7 +509,6 @@ export async function clearRoomNotification(userId: string, roomId: string) { } catch { // already dismissed } - await refreshAccountSummary(userId, true); }); } @@ -566,17 +532,24 @@ async function postRoomNotification( id: roomNotifId(userId, roomId), title: roomName, body: latestBody, - channelId: 'messages', + channelId: MESSAGES_CHANNEL_ID, group: NOTIF_GROUP_KEY, icon: 'notification_icon', silent: isSilent, autoCancel: true, extra, ...(isMobileTauri() ? { actionTypeId: 'sable-message' } : {}), + // Android renders these as a conversation; inbox/big-text covers the rest. + messages: messages.map((m) => ({ + body: m.text, + timestamp: m.timestamp, + senderName: m.sender?.name, + senderKey: m.sender?.key, + })), + groupConversation: cache.isGroupConversation, inboxLines: inboxLines.length > 1 ? inboxLines : undefined, largeBody: inboxLines.length > 1 ? undefined : latestBody, }); - await refreshAccountSummary(userId, false, isCurrent); return true; } @@ -615,7 +588,7 @@ async function handleRichPushPayload( await notificationsApi.sendNotification({ title: roomName, body: senderName ? `${senderName}: ${previewText}` : previewText, - channelId: 'messages', + channelId: MESSAGES_CHANNEL_ID, icon: 'notification_icon', silent: isSilent, autoCancel: true, @@ -655,11 +628,7 @@ async function handleRichPushPayload( } const sender: NotifPerson | undefined = senderName - ? { - name: senderName, - key: senderId, - iconUrl: senderId ? resolveAvatarUrl(settings.mx, roomId, senderId) : undefined, - } + ? { name: senderName, key: senderId } : undefined; const message: NotifMessage = { @@ -698,7 +667,6 @@ async function handleRichPushPayload( cache.messages = previousMessages; if (eventId) cache.pendingEventIds.delete(eventId); if (cache.messages.length === 0) roomNotifCaches.delete(cache.key); - await refreshAccountSummary(userId, true); unifiedPushLog.warn('notification', 'UnifiedPush baseline notification failed'); return false; } @@ -749,7 +717,7 @@ async function handleRichPushPayload( title: 'New Invitation', body, largeBody: body, - channelId: 'messages', + channelId: INVITES_CHANNEL_ID, group: NOTIF_GROUP_KEY, icon: 'notification_icon', autoCancel: true, @@ -779,102 +747,80 @@ function scheduleEncryptedPreviewEnrichment( const initialSettings = getSettings(); if (!initialSettings.showMessageContent || !initialSettings.showEncryptedMessageContent) return; - let settled = false; - let deadlineExpired = false; - const deadlineTimer = setTimeout(() => { - if (!settled) { - deadlineExpired = true; - unifiedPushLog.warn( - 'notification', - 'Encrypted preview decryption exceeded observation deadline' - ); - } - }, ENCRYPTED_PREVIEW_OBSERVATION_DEADLINE_MS); + const crypto = initialSettings.mx.getCrypto(); + const decrypted = buildEncryptedPreviewEvent(roomId, eventId, pushData); + if (!crypto || !decrypted) return; - const enrichment = decryptPreviewFromPayload(initialSettings.mx, roomId, eventId, pushData); - void enrichment - .then(async (decrypted) => { - if (deadlineExpired || !decrypted) return; + const applyDecryptedPreview = async (): Promise => { + await enqueueRoomOperation(cache.key, async () => { + const liveSettings = getSettings(); + const isAllowed = + liveSettings.showMessageContent && + liveSettings.showEncryptedMessageContent && + !(document.visibilityState === 'visible' && liveSettings.useInAppNotifications); + if (!isAllowed || !isCurrentRoomCache(cache) || !cache.messages.includes(message)) { + return; + } - await enqueueRoomOperation(cache.key, async () => { - const liveSettings = getSettings(); - const isAllowed = - liveSettings.showMessageContent && - liveSettings.showEncryptedMessageContent && - !(document.visibilityState === 'visible' && liveSettings.useInAppNotifications); - if (!isAllowed || !isCurrentRoomCache(cache) || !cache.messages.includes(message)) { - return; - } + const enrichedPreview = resolveNotificationPreviewText({ + content: decrypted.getContent(), + eventType: decrypted.getType(), + isEncryptedRoom: true, + showMessageContent: liveSettings.showMessageContent, + showEncryptedMessageContent: liveSettings.showEncryptedMessageContent, + }); + if (!enrichedPreview || enrichedPreview === ENCRYPTED_MESSAGE_PREVIEW) return; - const enrichedPreview = resolveNotificationPreviewText({ - content: decrypted.getContent(), - eventType: decrypted.getType(), - isEncryptedRoom: true, - showMessageContent: liveSettings.showMessageContent, - showEncryptedMessageContent: liveSettings.showEncryptedMessageContent, - }); - if (!enrichedPreview || enrichedPreview === ENCRYPTED_MESSAGE_PREVIEW) return; + const liveRoom = liveSettings.mx.getRoom(roomId); + const decryptedSender = decrypted.getSender(); + const senderName = decryptedSender + ? (liveRoom?.getMember(decryptedSender)?.name ?? + getMxIdLocalPart(decryptedSender) ?? + decryptedSender) + : undefined; + const previousText = message.text; + const previousSender = message.sender; + message.text = enrichedPreview; + message.sender = senderName ? { name: senderName, key: decryptedSender } : message.sender; - const liveRoom = liveSettings.mx.getRoom(roomId); - const decryptedSender = decrypted.getSender(); - const senderName = decryptedSender - ? (liveRoom?.getMember(decryptedSender)?.name ?? - getMxIdLocalPart(decryptedSender) ?? - decryptedSender) - : undefined; - const previousText = message.text; - const previousSender = message.sender; - message.text = enrichedPreview; - message.sender = senderName - ? { - name: senderName, - key: decryptedSender, - iconUrl: decryptedSender - ? resolveAvatarUrl(liveSettings.mx, roomId, decryptedSender) - : undefined, - } - : message.sender; - - const current = () => { - const currentSettings = getSettings(); - return ( - isCurrentRoomCache(cache) && - cache.messages.includes(message) && - currentSettings.showMessageContent && - currentSettings.showEncryptedMessageContent && - !(document.visibilityState === 'visible' && currentSettings.useInAppNotifications) - ); - }; - try { - const posted = await postRoomNotification( - userId, - roomId, - cache, - true, - { - room_id: roomId, - event_id: eventId, - user_id: pushData?.user_id, - }, - current - ); - if (!posted) { - message.text = previousText; - message.sender = previousSender; - } - } catch { + const current = () => { + const currentSettings = getSettings(); + return ( + isCurrentRoomCache(cache) && + cache.messages.includes(message) && + currentSettings.showMessageContent && + currentSettings.showEncryptedMessageContent && + !(document.visibilityState === 'visible' && currentSettings.useInAppNotifications) + ); + }; + try { + const posted = await postRoomNotification( + userId, + roomId, + cache, + true, + { + room_id: roomId, + event_id: eventId, + user_id: pushData?.user_id, + }, + current + ); + if (!posted) { message.text = previousText; message.sender = previousSender; } - }); - }) - .catch(() => { - unifiedPushLog.warn('notification', 'Encrypted preview decryption failed'); - }) - .finally(() => { - settled = true; - clearTimeout(deadlineTimer); + } catch { + message.text = previousText; + message.sender = previousSender; + } }); + }; + + whenDecrypted(decrypted, applyDecryptedPreview); + void decrypted.attemptDecryption(crypto as CryptoBackend).catch(() => { + unifiedPushLog.warn('notification', 'Encrypted preview decryption failed'); + }); } /** @@ -934,11 +880,7 @@ async function handleMinimalPushPayload( } const sender: NotifPerson | undefined = senderName - ? { - name: senderName, - key: senderId, - iconUrl: senderId && roomId ? resolveAvatarUrl(settings.mx, roomId, senderId) : undefined, - } + ? { name: senderName, key: senderId } : undefined; const message: NotifMessage = { @@ -974,7 +916,6 @@ async function handleMinimalPushPayload( cache.messages = previousMessages; if (eventId) cache.pendingEventIds.delete(eventId); if (cache.messages.length === 0) roomNotifCaches.delete(cache.key); - await refreshAccountSummary(userId, true); throw error; } @@ -999,81 +940,76 @@ async function handleMinimalPushPayload( (!isEncryptedRoom || settings.showEncryptedMessageContent) ) { resolvePreviewEvent(settings.mx, roomId, eventId) - .then(async (fetched) => { + .then((fetched) => { if (!fetched) return; - await enqueueRoomOperation(cache.key, async () => { - const liveSettings = getSettings(); - const eventEncrypted = isEncryptedRoom || fetched.isEncrypted(); - const isAllowed = - liveSettings.showMessageContent && - (!eventEncrypted || liveSettings.showEncryptedMessageContent) && - !(document.visibilityState === 'visible' && liveSettings.useInAppNotifications); - if (!isAllowed || !isCurrentRoomCache(cache) || !cache.messages.includes(message)) { - return; - } + const applyFetchedPreview = () => + enqueueRoomOperation(cache.key, async () => { + const liveSettings = getSettings(); + const eventEncrypted = isEncryptedRoom || fetched.isEncrypted(); + const isAllowed = + liveSettings.showMessageContent && + (!eventEncrypted || liveSettings.showEncryptedMessageContent) && + !(document.visibilityState === 'visible' && liveSettings.useInAppNotifications); + if (!isAllowed || !isCurrentRoomCache(cache) || !cache.messages.includes(message)) { + return; + } - const enrichedPreview = resolveNotificationPreviewText({ - content: fetched.getContent(), - eventType: fetched.getType(), - isEncryptedRoom: eventEncrypted, - showMessageContent: liveSettings.showMessageContent, - showEncryptedMessageContent: liveSettings.showEncryptedMessageContent, - }); - if (!enrichedPreview) return; + const enrichedPreview = resolveNotificationPreviewText({ + content: fetched.getContent(), + eventType: fetched.getType(), + isEncryptedRoom: eventEncrypted, + showMessageContent: liveSettings.showMessageContent, + showEncryptedMessageContent: liveSettings.showEncryptedMessageContent, + }); + if (!enrichedPreview) return; - const fetchedSender = fetched.getSender(); - const liveRoom = liveSettings.mx.getRoom(roomId); - const nextSenderName = fetchedSender - ? (liveRoom?.getMember(fetchedSender)?.name ?? - getMxIdLocalPart(fetchedSender) ?? - fetchedSender) - : undefined; - const previousText = message.text; - const previousSender = message.sender; - message.text = enrichedPreview; - message.sender = nextSenderName - ? { - name: nextSenderName, - key: fetchedSender, - iconUrl: fetchedSender - ? resolveAvatarUrl(liveSettings.mx, roomId, fetchedSender) - : undefined, + const fetchedSender = fetched.getSender(); + const liveRoom = liveSettings.mx.getRoom(roomId); + const nextSenderName = fetchedSender + ? (liveRoom?.getMember(fetchedSender)?.name ?? + getMxIdLocalPart(fetchedSender) ?? + fetchedSender) + : undefined; + const previousText = message.text; + const previousSender = message.sender; + message.text = enrichedPreview; + message.sender = nextSenderName ? { name: nextSenderName, key: fetchedSender } : sender; + + const current = () => { + const currentSettings = getSettings(); + return ( + isCurrentRoomCache(cache) && + cache.messages.includes(message) && + currentSettings.showMessageContent && + (!eventEncrypted || currentSettings.showEncryptedMessageContent) && + !(document.visibilityState === 'visible' && currentSettings.useInAppNotifications) + ); + }; + try { + const sent = await postRoomNotification( + userId, + roomId, + cache, + true, + { + room_id: roomId, + event_id: eventId, + user_id: pushData?.user_id, + }, + current + ); + if (!sent) { + message.text = previousText; + message.sender = previousSender; } - : sender; - - const current = () => { - const currentSettings = getSettings(); - return ( - isCurrentRoomCache(cache) && - cache.messages.includes(message) && - currentSettings.showMessageContent && - (!eventEncrypted || currentSettings.showEncryptedMessageContent) && - !(document.visibilityState === 'visible' && currentSettings.useInAppNotifications) - ); - }; - try { - const sent = await postRoomNotification( - userId, - roomId, - cache, - true, - { - room_id: roomId, - event_id: eventId, - user_id: pushData?.user_id, - }, - current - ); - if (!sent) { + } catch { message.text = previousText; message.sender = previousSender; } - } catch { - message.text = previousText; - message.sender = previousSender; - } - }); + }); + + whenDecrypted(fetched, applyFetchedPreview); }) .catch((error) => { unifiedPushLog.warn( @@ -1098,7 +1034,11 @@ async function handleUnifiedPushPayload( const pushData = (raw.extra ?? raw) as UnifiedPushPayload; const eventType = pushData?.type as EventType | undefined; - const userId = pushData?.user_id ?? settings.mx.getUserId() ?? ''; + const userId = isNonEmptyString(pushData?.user_id) ? pushData.user_id.trim() : undefined; + if (!userId || userId !== settings.mx.getUserId()) { + unifiedPushLog.warn('notification', 'Ignoring push without an exact active-account match'); + return; + } if (eventType) { await handleRichPushPayload(pushData, settings, userId, getSettings); @@ -1133,6 +1073,8 @@ export async function listenForUnifiedPushMessages(getSettings: () => Notificati throw error; } + void dismissLegacyGroupSummary(getSettings().mx.getUserId() ?? ''); + return { unregister: async () => { try { diff --git a/src/app/features/settings/routes.ts b/src/app/features/settings/routes.ts index 685005dc2..17872d2f3 100644 --- a/src/app/features/settings/routes.ts +++ b/src/app/features/settings/routes.ts @@ -3,6 +3,7 @@ export type SettingsSectionId = | 'account' | 'persona' | 'appearance' + | 'accessibility' | 'notifications' | 'devices' | 'desktop' @@ -22,6 +23,7 @@ export const settingsSections = [ { id: 'account', label: 'Account' }, { id: 'persona', label: 'Persona' }, { id: 'appearance', label: 'Appearance' }, + { id: 'accessibility', label: 'Accessibility' }, { id: 'notifications', label: 'Notifications' }, { id: 'devices', label: 'Devices' }, { id: 'desktop', label: 'Desktop' }, diff --git a/src/app/features/settings/settingTileFocusCoverage.test.ts b/src/app/features/settings/settingTileFocusCoverage.test.ts index 7862aceb3..3c644c3ad 100644 --- a/src/app/features/settings/settingTileFocusCoverage.test.ts +++ b/src/app/features/settings/settingTileFocusCoverage.test.ts @@ -10,6 +10,7 @@ const SETTINGS_DIR = 'src/app/features/settings'; // --- directory → section id mapping --- const dirToSection: Record = { 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 4d85fd0d8..651ecd352 100644 --- a/src/app/features/settings/settingsLink.ts +++ b/src/app/features/settings/settingsLink.ts @@ -108,14 +108,12 @@ 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 => { @@ -339,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/generated/tauri/commands.ts b/src/app/generated/tauri/commands.ts index 1dd132bbb..a712d062e 100644 --- a/src/app/generated/tauri/commands.ts +++ b/src/app/generated/tauri/commands.ts @@ -1,7 +1,7 @@ /** * Auto-generated TypeScript bindings for Tauri commands * Generated by tauri-typegen v0.5.0 - * Generated at: 2026-07-31T11:14:58.599659+00:00 + * Generated at: 2026-08-05T12:41:11.731056+00:00 * Generator: none * * Do not edit manually - regenerate using: cargo tauri-typegen generate diff --git a/src/app/generated/tauri/events.ts b/src/app/generated/tauri/events.ts index 0260d39ed..ff0d63855 100644 --- a/src/app/generated/tauri/events.ts +++ b/src/app/generated/tauri/events.ts @@ -1,7 +1,7 @@ /** * Auto-generated TypeScript bindings for Tauri commands * Generated by tauri-typegen v0.5.0 - * Generated at: 2026-07-31T11:14:58.602356+00:00 + * Generated at: 2026-08-05T12:41:11.732167+00:00 * Generator: none * * Do not edit manually - regenerate using: cargo tauri-typegen generate diff --git a/src/app/generated/tauri/index.ts b/src/app/generated/tauri/index.ts index 727bb5d08..0b97ef4c5 100644 --- a/src/app/generated/tauri/index.ts +++ b/src/app/generated/tauri/index.ts @@ -1,7 +1,7 @@ /** * Auto-generated TypeScript bindings for Tauri commands * Generated by tauri-typegen v0.5.0 - * Generated at: 2026-07-31T11:14:58.603222+00:00 + * Generated at: 2026-08-05T12:41:11.732351+00:00 * Generator: none * * Do not edit manually - regenerate using: cargo tauri-typegen generate diff --git a/src/app/generated/tauri/types.ts b/src/app/generated/tauri/types.ts index 5c41032af..8bd687fe8 100644 --- a/src/app/generated/tauri/types.ts +++ b/src/app/generated/tauri/types.ts @@ -1,7 +1,7 @@ /** * Auto-generated TypeScript bindings for Tauri commands * Generated by tauri-typegen v0.5.0 - * Generated at: 2026-07-31T11:14:58.596290+00:00 + * Generated at: 2026-08-05T12:41:11.729365+00:00 * Generator: none * * Do not edit manually - regenerate using: cargo tauri-typegen generate 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/timeline/useProcessedTimeline.test.tsx b/src/app/hooks/timeline/useProcessedTimeline.test.tsx index aa636988a..7be970e0c 100644 --- a/src/app/hooks/timeline/useProcessedTimeline.test.tsx +++ b/src/app/hooks/timeline/useProcessedTimeline.test.tsx @@ -834,3 +834,114 @@ 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[], + timelineHiddenEvents: ResolvedHiddenEventSettings = hiddenEvents + ) => + renderHook(() => + useProcessedTimeline({ + items: getEvents().map((_, i) => i), + linkedTimelines: [createTimeline(getEvents())], + ignoredUsersSet, + hiddenEvents: timelineHiddenEvents, + 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('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); + 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..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,17 +111,40 @@ 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; + 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, + isRedacted: mEvent.isRedacted(), + 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.isRedacted === current.isRedacted && + cached.clearType === current.clearType && + cached.clearContent === current.clearContent; + const computeCollapseAndDividers = ( drafts: ProcessedEventDraft[], mxUserId: string | null, @@ -213,6 +237,7 @@ const mergeDraftsAndExtras = ( id: mEvent.getId()!, itemIndex, mEvent, + isRedacted: mEvent.isRedacted(), timelineSet, eventSender: mEvent.getSender() ?? null, }, @@ -413,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; @@ -441,7 +466,7 @@ const processTimelineItems = ( } } - if (mEvent.isRedacted()) { + if (isRedacted) { const showMessageTombstone = showTombstoneEvents && isRedactableMessageType(type); const showReactionTombstone = hiddenEventReactionTombstone && isReaction; if (!showMessageTombstone && !showReactionTombstone) continue; @@ -456,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, @@ -484,7 +509,7 @@ const processTimelineItems = ( if (isEdit && !hiddenEventEdits) continue; if (isReaction) { - if (mEvent.isRedacted()) { + if (isRedacted) { if (!hiddenEventReactionTombstone) continue; } else if (!hiddenEventReactions) { continue; @@ -535,6 +560,7 @@ const processTimelineItems = ( id: mEventId, itemIndex: item, mEvent, + isRedacted, timelineSet, eventSender, collapsed, @@ -648,8 +674,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); 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/useAppVisibility.ts b/src/app/hooks/useAppVisibility.ts index 97053c106..1b7fe399d 100644 --- a/src/app/hooks/useAppVisibility.ts +++ b/src/app/hooks/useAppVisibility.ts @@ -14,7 +14,7 @@ const debugLog = createDebugLogger('AppVisibility'); export function useAppVisibility(mx: MatrixClient | undefined) { const clientConfig = useClientConfig(); - const [usePushNotifications] = useSetting(settingsAtom, 'usePushNotifications'); + const [backgroundPushEnabled] = useSetting(settingsAtom, 'backgroundPushEnabled'); const pushSubAtom = useAtom(pushSubscriptionAtom); const isMobile = isMobileOrTablet(); @@ -43,12 +43,12 @@ export function useAppVisibility(mx: MatrixClient | undefined) { if (!mx) return undefined; const handleVisibilityForNotifications = (isVisible: boolean) => { - togglePusher(mx, clientConfig, isVisible, usePushNotifications, pushSubAtom, isMobile); + togglePusher(mx, clientConfig, isVisible, backgroundPushEnabled, pushSubAtom, isMobile); }; appEvents.onVisibilityChange = handleVisibilityForNotifications; return () => { appEvents.onVisibilityChange = null; }; - }, [mx, clientConfig, usePushNotifications, pushSubAtom, isMobile]); + }, [mx, clientConfig, backgroundPushEnabled, pushSubAtom, isMobile]); } diff --git a/src/app/hooks/useBackgroundSyncPause.test.tsx b/src/app/hooks/useBackgroundSyncPause.test.tsx new file mode 100644 index 000000000..97410a6c1 --- /dev/null +++ b/src/app/hooks/useBackgroundSyncPause.test.tsx @@ -0,0 +1,130 @@ +import { describe, expect, it, vi, beforeEach } from 'vitest'; +import { renderHook } from '@testing-library/react'; + +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 })); + +vi.mock('jotai', () => ({ + useAtomValue: () => mockCallEmbed.value, + atom: vi.fn<() => unknown>(), +})); + +vi.mock('../state/callEmbed', () => ({ callEmbedAtom: {} })); + +vi.mock('@tauri-apps/api/event', () => ({ + listen, + TauriEvent: { WINDOW_RESUMED: 'tauri://resumed' }, +})); + +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') => + vi.spyOn(document, 'visibilityState', 'get').mockReturnValue(state); + +describe('useBackgroundSyncPause', () => { + beforeEach(() => { + vi.restoreAllMocks(); + pause.mockReset(); + resume.mockReset(); + listenOff.mockReset(); + listen.mockReset().mockResolvedValue(listenOff); + getSlidingSyncManager.mockReset().mockReturnValue({ pause, resume }); + mockIsTauri.value = false; + mockIsMobileTauri.value = true; + mockCallEmbed.value = undefined; + }); + + it('pauses sync when the app is backgrounded', () => { + setVisibility('visible'); + renderHook(() => useBackgroundSyncPause({ clientRunning: true } as never)); + + setVisibility('hidden'); + document.dispatchEvent(new Event('visibilitychange')); + + expect(pause).toHaveBeenCalled(); + }); + + it('resumes sync when the app returns to the foreground', () => { + setVisibility('hidden'); + renderHook(() => useBackgroundSyncPause({ clientRunning: true } as never)); + pause.mockClear(); + + setVisibility('visible'); + document.dispatchEvent(new Event('visibilitychange')); + + expect(resume).toHaveBeenCalled(); + }); + + it('keeps polling in the background during a call', () => { + mockCallEmbed.value = { dispose: vi.fn<() => void>() }; + setVisibility('hidden'); + + renderHook(() => useBackgroundSyncPause({ clientRunning: true } as never)); + + expect(pause).not.toHaveBeenCalled(); + expect(resume).toHaveBeenCalled(); + }); + + it('resumes on tauri://resumed without waiting for visibilitychange', () => { + mockIsTauri.value = true; + setVisibility('hidden'); + renderHook(() => useBackgroundSyncPause({ clientRunning: true } as never)); + resume.mockClear(); + + const [, cb] = listen.mock.calls[0] as [string, () => void]; + cb(); + + 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)); + + expect(pause).not.toHaveBeenCalled(); + expect(resume).not.toHaveBeenCalled(); + }); + + it('resumes on unmount so a paused transport is never left parked', () => { + setVisibility('hidden'); + const { unmount } = renderHook(() => useBackgroundSyncPause({ clientRunning: true } as never)); + resume.mockClear(); + + unmount(); + + expect(resume).toHaveBeenCalled(); + }); +}); diff --git a/src/app/hooks/useBackgroundSyncPause.ts b/src/app/hooks/useBackgroundSyncPause.ts new file mode 100644 index 000000000..5c904a443 --- /dev/null +++ b/src/app/hooks/useBackgroundSyncPause.ts @@ -0,0 +1,42 @@ +import { useEffect } from 'react'; +import { useAtomValue } from 'jotai'; +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'; + +/** + * Stop polling while the app is backgrounded. wry only calls Android `WebView.onPause()`, + * which does not pause JavaScript, so the long-poll otherwise runs until the OS freezes + * the process. Driven by `visibilitychange` rather than `tauri://suspended`, which on iOS + * maps to applicationWillResignActive. + */ +export const useBackgroundSyncPause = (mx: MatrixClient | undefined): void => { + const callEmbed = useAtomValue(callEmbedAtom); + const callActive = callEmbed !== undefined; + + useEffect(() => { + if (!mx || !isMobileTauri()) return undefined; + + const resume = () => getSlidingSyncManager(mx)?.resume(); + const applyVisibility = () => { + const manager = getSlidingSyncManager(mx); + if (!manager) return; + if (document.visibilityState === 'hidden' && !callActive) manager.pause(); + else manager.resume(); + }; + + document.addEventListener('visibilitychange', applyVisibility); + const unlisten = isTauri() ? listen(TauriEvent.WINDOW_RESUMED, resume) : undefined; + + applyVisibility(); + + return () => { + document.removeEventListener('visibilitychange', applyVisibility); + unlisten?.then((off) => off()); + resume(); + }; + }, [mx, callActive]); +}; 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] ); 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]); } diff --git a/src/app/hooks/useGroupDMMembers.ts b/src/app/hooks/useGroupDMMembers.ts index da5532e7d..c0ad51694 100644 --- a/src/app/hooks/useGroupDMMembers.ts +++ b/src/app/hooks/useGroupDMMembers.ts @@ -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. @@ -32,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/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/useNetworkRecovery.test.tsx b/src/app/hooks/useNetworkRecovery.test.tsx index 2e26506c2..40dac044d 100644 --- a/src/app/hooks/useNetworkRecovery.test.tsx +++ b/src/app/hooks/useNetworkRecovery.test.tsx @@ -2,7 +2,7 @@ import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'; import { renderHook } from '@testing-library/react'; const { nudgeReconnect, setOnline, listenOff, listen, mockIsTauri } = vi.hoisted(() => ({ - nudgeReconnect: vi.fn<(mx: unknown, reason: string) => boolean>(), + nudgeReconnect: vi.fn<(mx: unknown, reason: string, opts?: { force?: boolean }) => boolean>(), setOnline: vi.fn<() => void>(), listenOff: vi.fn<() => void>(), listen: vi.fn<(_event: string, _cb: () => void) => Promise<() => void>>(), @@ -59,7 +59,7 @@ describe('useNetworkRecovery', () => { dispatchEvent(new Event('online')); - expect(nudgeReconnect).toHaveBeenCalledWith(expect.anything(), 'online'); + expect(nudgeReconnect).toHaveBeenCalledWith(expect.anything(), 'online', undefined); expect(setOnline).toHaveBeenCalled(); }); @@ -71,7 +71,7 @@ describe('useNetworkRecovery', () => { vi.advanceTimersByTime(30_001); document.dispatchEvent(new Event('visibilitychange')); - expect(nudgeReconnect).toHaveBeenCalledWith(expect.anything(), 'visible'); + expect(nudgeReconnect).toHaveBeenCalledWith(expect.anything(), 'visible', undefined); visState.mockRestore(); }); @@ -112,7 +112,7 @@ describe('useNetworkRecovery', () => { vi.advanceTimersByTime(80_000); - expect(nudgeReconnect).toHaveBeenCalledWith(expect.anything(), 'stalled'); + expect(nudgeReconnect).toHaveBeenCalledWith(expect.anything(), 'stalled', undefined); }); it('does not trigger stalled nudge when Sync events keep arriving', () => { @@ -178,7 +178,7 @@ describe('useNetworkRecovery', () => { dispatchEvent(new Event('online')); expect(nudgeReconnect).toHaveBeenCalledTimes(1); - expect(nudgeReconnect).toHaveBeenLastCalledWith(expect.anything(), 'online'); + expect(nudgeReconnect).toHaveBeenLastCalledWith(expect.anything(), 'online', undefined); vi.advanceTimersByTime(3_000); @@ -213,7 +213,7 @@ describe('useNetworkRecovery', () => { mockIsTauri.value = true; }); - it('nudges on tauri://resumed event', () => { + it('force-nudges on tauri://resumed event', () => { listen.mockResolvedValue(listenOff); renderHook(() => useNetworkRecovery({ clientRunning: true } as never)); @@ -222,7 +222,16 @@ describe('useNetworkRecovery', () => { const [, cb] = listen.mock.calls[0] as [string, () => void]; cb(); - expect(nudgeReconnect).toHaveBeenCalledWith(expect.anything(), 'resumed'); + expect(nudgeReconnect).toHaveBeenCalledWith(expect.anything(), 'resumed', { force: true }); + }); + + it('does not subscribe to tauri://suspended', () => { + listen.mockResolvedValue(listenOff); + + renderHook(() => useNetworkRecovery({ clientRunning: true } as never)); + + expect(listen).toHaveBeenCalledOnce(); + expect(listen).not.toHaveBeenCalledWith('tauri://suspended', expect.any(Function)); }); it('calls the listen cleanup on unmount', async () => { diff --git a/src/app/hooks/useNetworkRecovery.ts b/src/app/hooks/useNetworkRecovery.ts index 6bb74c566..71d5ca7c5 100644 --- a/src/app/hooks/useNetworkRecovery.ts +++ b/src/app/hooks/useNetworkRecovery.ts @@ -26,10 +26,10 @@ export const useNetworkRecovery = (mx: MatrixClient | undefined): void => { }, []); const nudge = useCallback( - (reason: NudgeReason): boolean => { + (reason: NudgeReason, opts?: { force?: boolean }): boolean => { if (!mx) return false; onlineManager.setOnline(true); - return nudgeReconnect(mx, reason); + return nudgeReconnect(mx, reason, opts); }, [mx] ); @@ -45,11 +45,11 @@ export const useNetworkRecovery = (mx: MatrixClient | undefined): void => { // Foreground nudges (resume / visible-stale / online) get one sync verification: // if no Sync arrives within VERIFY_AFTER_NUDGE_MS, retry once past the throttle. const nudgeForeground = useCallback( - (reason: NudgeReason): void => { + (reason: NudgeReason, opts?: { force?: boolean }): void => { cancelVerify(); if (!mx) return; const syncAtNudge = lastSyncAtRef.current; - if (!nudge(reason)) return; + if (!nudge(reason, opts)) return; verifyTimerRef.current = window.setTimeout(() => { verifyTimerRef.current = undefined; if (lastSyncAtRef.current === syncAtNudge) { @@ -83,7 +83,7 @@ export const useNetworkRecovery = (mx: MatrixClient | undefined): void => { }, STALL_CHECK_INTERVAL_MS); const unlisten = isTauri() - ? listen(TauriEvent.WINDOW_RESUMED, () => nudgeForeground('resumed')) + ? listen(TauriEvent.WINDOW_RESUMED, () => nudgeForeground('resumed', { force: true })) : undefined; return () => { 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.test.ts b/src/app/hooks/usePerMessageProfile.test.ts new file mode 100644 index 000000000..7b31cace8 --- /dev/null +++ b/src/app/hooks/usePerMessageProfile.test.ts @@ -0,0 +1,135 @@ +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 PerMessageProfileMsc4461, +} from './usePerMessageProfile'; + +function createMatrixClient(profiles: PerMessageProfileMsc4461[] = []) { + const accountData = new Map(); + accountData.set(MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME, { + profiles, + }); + + 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('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')]); + + 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 3b18de237..6e61fc37b 100644 --- a/src/app/hooks/usePerMessageProfile.ts +++ b/src/app/hooks/usePerMessageProfile.ts @@ -3,16 +3,26 @@ 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, + 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 */ -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 +46,146 @@ 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 = { + 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; +}; + +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 { + const content = mx + .getAccountData( + MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME as Parameters< + typeof mx.getAccountData + >[0] + ) + ?.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[]) { + await mx.setAccountData( + MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME as Parameters< + typeof mx.setAccountData + >[0], + { profiles } as Parameters[1] + ); +} + +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 +221,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 +257,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 +492,23 @@ 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 { + return getPerMessageProfileIndex(mx)?.profiles.find((profile) => profile.id === id); +} + +/** + * @deprecated + * * getting a profile from the account data where the profile matches a given id * * @export @@ -342,7 +516,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 { @@ -352,6 +526,39 @@ export async function getPerMessageProfileById( 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 * @@ -359,13 +566,13 @@ 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] - ); - 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); +export async function getAllPerMessageProfiles( + mx: MatrixClient +): Promise { + const profiles = getPerMessageProfileIndex(mx)?.profiles; + if (profiles) return profiles; + + return (await migrateLegacyPerMessageProfiles(mx)) ?? []; } /** @@ -374,54 +581,20 @@ export async function getAllPerMessageProfiles(mx: MatrixClient): Promise[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 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] - ), - ]); -} +export async function addOrUpdatePerMessageProfile( + mx: MatrixClient, + profile: PerMessageProfileMsc4461 +) { + const profiles = getPerMessageProfileIndex(mx)?.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 + ); -/** - * 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 { @@ -453,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); - mx.setAccountData( + 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 }); - mx.setAccountData( - `${ACCOUNT_DATA_PREFIX}.roomassociation` as Parameters[0], - { associations: associationsMapToObject(associations) } as Parameters< - typeof mx.setAccountData - >[1] - ); + }); } /** @@ -490,111 +665,29 @@ export async function setCurrentlyUsedPerMessageProfileIdForAccount( validUntil?: number, reset?: boolean ) { - if (reset) { - 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 }; - - mx.setAccountData( - `${ACCOUNT_DATA_PREFIX}.globalassociation` as Parameters[0], - { association: association } as Parameters[1] - ); -} - -/** - * - * @param mx the matrix client - * @param profileId the profile id which the prefix should be attached to - * @param proxy the prefix to use as index - * @param proxyRegExp the regex we can use to match the prefix - * @param reset wheather to delete the prefix - */ -export async function associateProxyWithProfile( - mx: MatrixClient, - profileId: string | undefined, - 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 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"); } - return parr.push(v as PerMessageProfileProxyAssociationV2); - }); - if (needsMigration) { - const newPmap = new Map( - pmap.entries().map(([k, v]) => [k, migratePmpProxyAssociation(k, v) ?? v]) - ); + const association: PerMessageProfileRoomAssociation = { profileId, validUntil }; await mx.setAccountData( - `${ACCOUNT_DATA_PREFIX}.proxyassociation` as Parameters[0], - { associations: proxyAssociationsMapToObject(newPmap) } as Parameters< - typeof mx.setAccountData - >[1] + `${ACCOUNT_DATA_PREFIX}.globalassociation` as Parameters[0], + { association: association } as Parameters[1] ); - } - - return parr; + }); } +/* + * @deprecated in favor of Msc4461 format triggers + */ export async function getAllProxiesForPMP( mx: MatrixClient, profileId: string @@ -616,24 +709,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. @@ -668,11 +743,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)?.profiles; + if (!profiles) return; + + await savePerMessageProfileIndex( + mx, + profiles.filter((profile) => profile.id !== id) ); - await dropIdFromIndex(mx, id); } /** @@ -683,13 +760,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)?.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)) + ); } /** @@ -701,7 +780,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 +796,7 @@ export async function getCurrentlyUsedPerMessageProfileForRoom( */ export async function getCurrentlyUsedPerMessageProfileForAccount( mx: MatrixClient -): Promise { +): Promise { const accountData = mx.getAccountData( `${ACCOUNT_DATA_PREFIX}.globalassociation` as Parameters[0] ); @@ -726,3 +805,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>/, ''); +} 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 31e04867f..f953e3ea2 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,15 @@ 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(); - }); + }; + room.loadMembersIfNeeded().then(() => { + stopLoading(); + void hydrateAllRoomMembers(mx, roomId).then(() => updateMemberList()); + }, stopLoading); } const handleStateEvent = (event: MatrixEvent) => { diff --git a/src/app/hooks/useRoomMeta.test.tsx b/src/app/hooks/useRoomMeta.test.tsx index 7721813f2..fc0db2ef7 100644 --- a/src/app/hooks/useRoomMeta.test.tsx +++ b/src/app/hooks/useRoomMeta.test.tsx @@ -1,9 +1,13 @@ 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 { RoomStateEvent } from '$types/matrix-sdk'; -import { useRoomAvatar } from './useRoomMeta'; +import { Provider as JotaiProvider, createStore } from 'jotai'; +import type { PropsWithChildren } from 'react'; +import type { MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk'; +import { EventType, RoomStateEvent } from '$types/matrix-sdk'; +import { mDirectAtom } from '$state/mDirectList'; +import { MatrixClientProvider } from './useMatrixClient'; +import { useRoomAvatar, useRoomName } from './useRoomMeta'; const AVATAR_MXC = 'mxc://server/abc'; @@ -28,6 +32,11 @@ const makeRoom = (roomId: string) => { return { room, client, + wrapper: ({ children }: PropsWithChildren) => ( + + {children} + + ), setAvatarEvent: (event: MatrixEvent) => { avatarEvent = event; }, @@ -36,14 +45,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 +65,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)); @@ -65,4 +74,149 @@ describe('useRoomAvatar', () => { expect(result.current).toBeUndefined(); }); + + it('updates a DM avatar when its member state arrives after the sidebar rendered', () => { + const { room, wrapper } = makeRoom('!dm:server'); + const roomEvents = new EventEmitter(); + let fallbackMember: { getMxcAvatarUrl: () => string } | undefined; + Object.assign(room, { + getAvatarFallbackMember: () => fallbackMember, + on: roomEvents.on.bind(roomEvents), + removeListener: roomEvents.removeListener.bind(roomEvents), + }); + + const { result } = renderHook(() => useRoomAvatar(room, true), { wrapper }); + expect(result.current).toBeUndefined(); + + fallbackMember = { getMxcAvatarUrl: () => AVATAR_MXC }; + act(() => { + roomEvents.emit(RoomStateEvent.Members); + }); + + 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 1c7387a54..6b62a82c6 100644 --- a/src/app/hooks/useRoomMeta.ts +++ b/src/app/hooks/useRoomMeta.ts @@ -1,25 +1,47 @@ 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'; +import { getDmOtherMember, getMemberDisplayName } from '$utils/room/display'; +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 + 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 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 room.getAvatarFallbackMember()?.getMxcAvatarUrl(); @@ -31,21 +53,35 @@ export const useRoomAvatar = (room: Room, dm?: boolean): string | undefined => { }; export const useRoomName = (room: Room): string => { - const dmUserId = room.guessDMUserId(); - const dmNickname = useNickname(dmUserId || ''); + const mx = useMatrixClient(); 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 nextName = getRoomDisplayName(room.name, stateName, isDmTagged, dmNickname); + const otherMember = isDmTagged ? getDmOtherMember(mx, room) : undefined; + const dmOtherMemberName = otherMember + ? (getMemberDisplayName(room, otherMember.userId) ?? otherMember.rawDisplayName) + : undefined; + + const nextName = getRoomDisplayName( + room.name, + stateName, + stateNameIsServerGenerated, + isDmTagged, + dmNickname, + dmOtherMemberName + ); setName((prev) => (prev !== nextName ? nextName : prev)); }; @@ -58,7 +94,7 @@ export const useRoomName = (room: Room): string => { room.removeListener(RoomEvent.Name, updateName); room.removeListener(RoomStateEvent.Members, updateName); }; - }, [room, stateName, dmNickname, isDmTagged]); + }, [room, mx, stateName, stateNameIsServerGenerated, dmNickname, isDmTagged]); return name; }; diff --git a/src/app/hooks/useSableCosmetics.ts b/src/app/hooks/useSableCosmetics.ts index 0b87a1ff2..06ea1f49e 100644 --- a/src/app/hooks/useSableCosmetics.ts +++ b/src/app/hooks/useSableCosmetics.ts @@ -8,6 +8,7 @@ import { useRoomCreatorsTag } from './useRoomCreatorsTag'; import { usePowerLevelTags } from './usePowerLevelTags'; import { useTheme } from './useTheme'; import { useUserProfile } from './useUserProfile'; +import { useAccessibleNameColor } from './useAccessibleNameColor'; export function useSableCosmetics( userId: string, @@ -25,11 +26,14 @@ export function useSableCosmetics( const getPowerTag = useGetMemberPowerTag(room, creators, powerLevels); const accessibleTagColors = useAccessiblePowerTagColors(theme.kind, creatorsTag, powerLevelTags); + const accessibleNameColor = useAccessibleNameColor(theme.kind); return useMemo(() => { if (!room || !userId) return { color: undefined, font: undefined }; - let finalColor = isUserHero ? profile.heroNameColor : profile.resolvedColor; + let finalColor = accessibleNameColor( + isUserHero ? profile.heroNameColor : profile.resolvedColor + ); if (!finalColor) { const memberPowerTag = getPowerTag(userId); finalColor = memberPowerTag?.color @@ -51,5 +55,6 @@ export function useSableCosmetics( profile.resolvedFont, getPowerTag, accessibleTagColors, + accessibleNameColor, ]); } 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/BackgroundNotifications.tsx b/src/app/pages/client/BackgroundNotifications.tsx index 3a9ba270b..f362a1730 100644 --- a/src/app/pages/client/BackgroundNotifications.tsx +++ b/src/app/pages/client/BackgroundNotifications.tsx @@ -100,8 +100,13 @@ const startBackgroundClient = async (session: Session): Promise => timelineLimit: 1, }; - await startClient(mx, startOpts); - return mx; + try { + await startClient(mx, startOpts); + return mx; + } catch (error) { + stopClient(mx); + throw error; + } }; /** @@ -136,14 +141,14 @@ export function BackgroundNotifications() { const sessions = useAtomValue(sessionsAtom); const [activeSessionId, setActiveSessionId] = useAtom(activeSessionIdAtom); const [showNotifications] = useSetting(settingsAtom, 'useInAppNotifications'); - const [usePushNotifications] = useSetting(settingsAtom, 'usePushNotifications'); + const [backgroundPushEnabled] = useSetting(settingsAtom, 'backgroundPushEnabled'); const [notificationSound] = useSetting(settingsAtom, 'isNotificationSounds'); const [showMessageContent] = useSetting(settingsAtom, 'showMessageContentInNotifications'); const [showEncryptedMessageContent] = useSetting( settingsAtom, 'showMessageContentInEncryptedNotifications' ); - const shouldRunBackgroundNotifications = showNotifications || usePushNotifications; + const shouldRunBackgroundNotifications = showNotifications || backgroundPushEnabled; const nicknames = useAtomValue(nicknamesAtom); const nicknamesRef = useRef(nicknames); nicknamesRef.current = nicknames; @@ -207,7 +212,9 @@ export function BackgroundNotifications() { } const { current } = clientsRef; + let disposed = false; const activeIds = new Set(inactiveSessions.map((s) => s.userId)); + const retryTimers: ReturnType[] = []; async function sendNotification(opts: NotifyOptions): Promise { if (isDesktopTauri()) { @@ -285,15 +292,27 @@ export function BackgroundNotifications() { // Using a named function (vs. inline .then) lets the .catch() schedule a // fresh retry referencing the latest session from inactiveSessionsRef. const startSession = (session: Session, attempt = 0): void => { + if (disposed || current.has(session.userId)) return; + let sessionMx: MatrixClient | undefined; startBackgroundClient(session) .then(async (mx) => { sessionMx = mx; + if (disposed) { + stopClient(mx); + return; + } current.set(session.userId, mx); Sentry.metrics.gauge('sable.background.client_count', current.size); await waitForSync(mx); + if (disposed) return; + if (current.get(session.userId) !== mx) { + stopClient(mx); + return; + } + // Wait for m.direct account data to load. This is critical for DM detection. // Without it, rooms in /direct/ won't be recognized as DMs, causing notifications to fail. let mDirectsSet: Set | undefined; @@ -317,6 +336,12 @@ export function BackgroundNotifications() { }); } + if (disposed) return; + if (current.get(session.userId) !== mx) { + stopClient(mx); + return; + } + const pushProcessor = mx.pushProcessor; const handleAccountData = (event: MatrixEvent) => { @@ -564,6 +589,7 @@ export function BackgroundNotifications() { }); }) .catch((err) => { + if (disposed) return; log.error('failed to start background client for', session.userId, err); debugLog.error('notification', 'Failed to start background client', { userId: session.userId, @@ -585,14 +611,17 @@ export function BackgroundNotifications() { // Retry with exponential backoff, up to 5 attempts (5s, 10s, 20s, 40s, 60s cap). if (attempt < 5) { const retryDelay = Math.min(5_000 * 2 ** attempt, 60_000); - setTimeout(() => { - const latestSession = inactiveSessionsRef.current.find( - (s) => s.userId === session.userId - ); - if (latestSession && !current.has(session.userId)) { - startSession(latestSession, attempt + 1); - } - }, retryDelay); + retryTimers.push( + setTimeout(() => { + if (disposed) return; + const latestSession = inactiveSessionsRef.current.find( + (s) => s.userId === session.userId + ); + if (latestSession && !current.has(session.userId)) { + startSession(latestSession, attempt + 1); + } + }, retryDelay) + ); } }); }; @@ -610,16 +639,15 @@ export function BackgroundNotifications() { }); const cleanupMap = clientCleanupRef.current; - const activeUserIds = new Set(inactiveSessions.map((s) => s.userId)); return () => { + disposed = true; staggerTimers.forEach(clearTimeout); + retryTimers.forEach(clearTimeout); current.forEach((mx, userId) => { - if (!activeUserIds.has(userId)) { - cleanupMap.get(userId)?.(); - cleanupMap.delete(userId); - stopClient(mx); - current.delete(userId); - } + cleanupMap.get(userId)?.(); + cleanupMap.delete(userId); + stopClient(mx); + current.delete(userId); }); }; }, [ diff --git a/src/app/pages/client/ClientRoot.tsx b/src/app/pages/client/ClientRoot.tsx index 19389f1fc..b1128e17e 100644 --- a/src/app/pages/client/ClientRoot.tsx +++ b/src/app/pages/client/ClientRoot.tsx @@ -51,6 +51,7 @@ import { createLogger } from '$utils/debug'; import { useSyncNicknames } from '$hooks/useNickname'; import { useAppVisibility } from '$hooks/useAppVisibility'; import { useNetworkRecovery } from '$hooks/useNetworkRecovery'; +import { useBackgroundSyncPause } from '$hooks/useBackgroundSyncPause'; import { composerIcon, DotsThreeOutlineVerticalIcon } from '$components/icons/phosphor'; import { getHomePath } from '$pages/pathUtils'; import { DIRECT_ROOM_PATH, HOME_ROOM_PATH, SPACE_ROOM_PATH } from '$pages/paths'; @@ -353,6 +354,7 @@ export function ClientRoot({ children }: ClientRootProps) { useLogoutListener(mx); useAppVisibility(mx); useNetworkRecovery(mx); + useBackgroundSyncPause(mx); useCrossSigningResetDetect(mx); useDeviceDisplayName(mx); diff --git a/src/app/pages/client/DesktopUpdater.test.tsx b/src/app/pages/client/DesktopUpdater.test.tsx index dcf3f8a6d..05c095f68 100644 --- a/src/app/pages/client/DesktopUpdater.test.tsx +++ b/src/app/pages/client/DesktopUpdater.test.tsx @@ -2,8 +2,9 @@ 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'; const { checkFn } = vi.hoisted(() => ({ checkFn: vi.fn<() => Promise>() })); @@ -32,6 +33,7 @@ function BannersProbe() { {banners.map((b) => (
{b.title} + {b.description} @@ -55,6 +57,11 @@ function CheckNowButton() { ); } +function UpdatePhaseProbe() { + const phase = useAtomValue(updatePhaseAtom); + return {phase.type}; +} + function makeUpdate(version: string) { return { version, @@ -156,8 +163,9 @@ describe('DesktopUpdater', () => { it('retries when downloadAndInstall fails', async () => { const update = makeUpdate('4.0.0'); + const debugLog = vi.spyOn(getDebugLogger(), 'log'); update.downloadAndInstall - .mockRejectedValueOnce(new Error('eacces')) + .mockRejectedValueOnce({ message: 'permission denied' }) .mockResolvedValueOnce(undefined); checkFn.mockResolvedValue(update); @@ -166,6 +174,7 @@ describe('DesktopUpdater', () => { + ); @@ -176,10 +185,18 @@ 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', + 'network', + '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 80a279d9c..f3c3c38ea 100644 --- a/src/app/pages/client/DesktopUpdater.tsx +++ b/src/app/pages/client/DesktopUpdater.tsx @@ -4,6 +4,7 @@ import type { Update } from '@tauri-apps/plugin-updater'; import { isDesktopTauri } from '$utils/platform'; import { autoUpdateCheckAtom } from '$state/autoUpdateCheck'; import { createLogger } from '$utils/debug'; +import { getDebugLogger } from '$utils/debugLogger'; import { hasCustomDesktopTitlebar } from '$utils/tauriTitlebar'; import { useDesktopSetting } from '$state/hooks/desktopSettings'; import { ArrowUp } from '$components/icons/phosphor'; @@ -19,6 +20,23 @@ 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); + getDebugLogger().log( + 'error', + 'network', + 'DesktopUpdater', + `${message}: ${getUpdaterErrorMessage(error)}` + ); +}; + export function DesktopUpdater() { const autoUpdateCheck = useAtomValue(autoUpdateCheckAtom); const triggerCount = useAtomValue(triggerUpdateCheckAtom); @@ -29,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); @@ -92,7 +111,7 @@ export function DesktopUpdater() { setLastChecked(new Date().toISOString()); if (!hasCustomDesktopTitlebar(useCustomTitleBar)) setBannerVisible(true); } catch (err) { - log.error('Desktop update check failed', err); + logUpdaterError('Desktop update check failed', err); if (mounted) { if (!hasUpdateRef.current) { setPhase({ type: 'idle' }); @@ -145,6 +164,7 @@ export function DesktopUpdater() { if (!updateInfo || installStartedRef.current) return; installStartedRef.current = true; try { + setInstallError(null); setIsDownloading(true); setPhase({ type: 'downloading', progress: 0 }); @@ -179,9 +199,11 @@ export function DesktopUpdater() { pendingUpdateRef.current = null; closePendingUpdate(updateInfo); } catch (err) { - log.error('Failed to install update', 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]); @@ -223,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, @@ -251,6 +293,7 @@ export function DesktopUpdater() { isDownloading, isInstalled, isInstalling, + installError, handleInstall, handleRestart, handleDismiss, diff --git a/src/app/pages/client/client-non-ui/badging.tsx b/src/app/pages/client/client-non-ui/badging.tsx index 6bad98518..d8c1ae0d1 100644 --- a/src/app/pages/client/client-non-ui/badging.tsx +++ b/src/app/pages/client/client-non-ui/badging.tsx @@ -51,7 +51,7 @@ export function PageTitleUpdater() { export function FaviconUpdater() { const roomToUnread = useAtomValue(roomToUnreadAtom); - const [usePushNotifications] = useSetting(settingsAtom, 'usePushNotifications'); + const [backgroundPushEnabled] = useSetting(settingsAtom, 'backgroundPushEnabled'); const [faviconForMentionsOnly] = useSetting(settingsAtom, 'faviconForMentionsOnly'); const registration = useAtomValue(registrationAtom); @@ -83,7 +83,7 @@ export function FaviconUpdater() { } else { navigator.clearAppBadge(); } - if (usePushNotifications && registration) { + if (backgroundPushEnabled && registration) { if (total === 0) { // All rooms read — clear every notification. registration.getNotifications().then((notifs) => notifs.forEach((n) => n.close())); @@ -104,7 +104,7 @@ export function FaviconUpdater() { } catch { // Likely Firefox/Gecko-based and doesn't support badging API } - }, [roomToUnread, usePushNotifications, registration, faviconForMentionsOnly]); + }, [roomToUnread, backgroundPushEnabled, registration, faviconForMentionsOnly]); return null; } diff --git a/src/app/pages/client/client-non-ui/notifications.test.tsx b/src/app/pages/client/client-non-ui/notifications.test.tsx index d5ec92346..7eb648e3a 100644 --- a/src/app/pages/client/client-non-ui/notifications.test.tsx +++ b/src/app/pages/client/client-non-ui/notifications.test.tsx @@ -2,7 +2,9 @@ import { render, waitFor } from '@testing-library/react'; import { Provider, createStore } from 'jotai'; import { MemoryRouter } from 'react-router-dom'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { NativeNotificationClickRouting } from './notifications'; +import { NativeNotificationActionRouting, NativeNotificationClickRouting } from './notifications'; +import { activeSessionIdAtom, pendingNotificationAtom } from '$state/sessions'; +import { nativeNotificationRepliesAtom } from '$state/nativeNotificationReplies'; // Controllable platform gates + a capturable notifications API. The click-routing // effect only calls onNotificationClicked, so the rest of the plugin surface is stubbed @@ -15,10 +17,29 @@ const platform = vi.hoisted(() => ({ const notificationsApi = vi.hoisted(() => ({ onNotificationClicked: vi - .fn<() => Promise<{ unregister: () => void }>>() + .fn< + ( + handler: (event: { data?: Record }) => void + ) => Promise<{ unregister: () => void }> + >() .mockResolvedValue({ unregister: () => {} }), })); +const matrixClient = vi.hoisted(() => ({ + getUserId: vi.fn<() => string>(() => '@user:example.com'), + getRoom: vi.fn<() => { getMyMembership: () => string }>(() => ({ + getMyMembership: () => 'join', + })), + getSyncState: vi.fn<() => string>(() => 'SYNCING'), + sendMessage: vi.fn<() => Promise>().mockResolvedValue(undefined), +})); + +const notificationUtils = vi.hoisted(() => ({ + markAsRead: vi.fn<() => Promise>().mockResolvedValue(undefined), +})); + +const toast = vi.hoisted(() => ({ showToast: vi.fn<(message: string) => void>() })); + const getTauriNotificationsApi = vi.hoisted(() => vi.fn<() => Promise>().mockResolvedValue(notificationsApi) ); @@ -34,15 +55,22 @@ vi.mock('$features/settings/notifications/TauriNotificationsApiClient', () => ({ IOS_NOTIFICATION_SOUND: 'notification.caf', })); +vi.mock('$hooks/useMatrixClient', () => ({ useMatrixClient: () => matrixClient })); +vi.mock('$state/hooks/settings', () => ({ + useSetting: () => [false, vi.fn<(value: unknown) => void>()], +})); +vi.mock('$utils/notifications', () => notificationUtils); +vi.mock('$state/toast', () => toast); + function setPlatform(kind: 'android' | 'ios' | 'desktop' | 'web') { platform.isAndroidTauri.mockReturnValue(kind === 'android'); platform.isIosTauri.mockReturnValue(kind === 'ios'); platform.isDesktopTauri.mockReturnValue(kind === 'desktop'); } -function renderRouting() { +function renderRouting(store = createStore()) { return render( - + @@ -54,6 +82,8 @@ beforeEach(() => { vi.clearAllMocks(); getTauriNotificationsApi.mockResolvedValue(notificationsApi); notificationsApi.onNotificationClicked.mockResolvedValue({ unregister: () => {} }); + matrixClient.sendMessage.mockResolvedValue(undefined); + notificationUtils.markAsRead.mockResolvedValue(undefined); }); afterEach(() => { @@ -99,4 +129,60 @@ describe('NativeNotificationClickRouting', () => { expect(getTauriNotificationsApi).not.toHaveBeenCalled(); expect(notificationsApi.onNotificationClicked).not.toHaveBeenCalled(); }); + + it('ignores unscoped clicks and switches account before routing scoped invites', async () => { + setPlatform('android'); + const store = createStore(); + let clickHandler!: (event: { data?: Record }) => void; + notificationsApi.onNotificationClicked.mockImplementation(async (handler) => { + clickHandler = handler; + return { unregister: () => {} }; + }); + renderRouting(store); + await waitFor(() => expect(clickHandler).toBeTypeOf('function')); + + clickHandler({ data: { type: 'invite', room_id: '!room:example.com' } }); + expect(store.get(activeSessionIdAtom)).not.toBe('@other:example.com'); + expect(store.get(pendingNotificationAtom)).toBeNull(); + + clickHandler({ + data: { + type: 'invite', + user_id: '@other:example.com', + room_id: '!room:example.com', + }, + }); + expect(store.get(activeSessionIdAtom)).toBe('@other:example.com'); + }); +}); + +describe('NativeNotificationActionRouting', () => { + it('does not report a successful reply as failed when marking it read fails', async () => { + setPlatform('web'); + const store = createStore(); + store.set(nativeNotificationRepliesAtom, [ + { + key: 'reply', + userId: '@user:example.com', + roomId: '!room:example.com', + eventId: '$event', + text: 'hello', + createdAt: Date.now(), + }, + ]); + notificationUtils.markAsRead.mockRejectedValueOnce(new Error('receipt failed')); + + render( + + + + + + ); + + await waitFor(() => expect(matrixClient.sendMessage).toHaveBeenCalledOnce()); + await waitFor(() => expect(store.get(nativeNotificationRepliesAtom)).toEqual([])); + expect(notificationUtils.markAsRead).toHaveBeenCalledOnce(); + expect(toast.showToast).not.toHaveBeenCalled(); + }); }); diff --git a/src/app/pages/client/client-non-ui/notifications.tsx b/src/app/pages/client/client-non-ui/notifications.tsx index 80b43bc51..e3b0b0bb3 100644 --- a/src/app/pages/client/client-non-ui/notifications.tsx +++ b/src/app/pages/client/client-non-ui/notifications.tsx @@ -34,6 +34,7 @@ import { settingsAtom } from '$state/settings'; import { nicknamesAtom } from '$state/nicknames'; import { mDirectAtom } from '$state/mDirectList'; import { allInvitesAtom } from '$state/room-list/inviteList'; +import { markAsRead } from '$utils/notifications'; import { usePreviousValue } from '$hooks/usePreviousValue'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { getStateEvent } from '$utils/room/hierarchy'; @@ -79,7 +80,7 @@ export function InviteNotifications() { const navigate = useNavigate(); const [showSystemNotifications] = useSetting(settingsAtom, 'useSystemNotifications'); - const [usePushNotifications] = useSetting(settingsAtom, 'usePushNotifications'); + const [backgroundPushEnabled] = useSetting(settingsAtom, 'backgroundPushEnabled'); const [notificationSound] = useSetting(settingsAtom, 'isNotificationSounds'); const [backgroundNotificationSounds] = useSetting(settingsAtom, 'backgroundNotificationSounds'); @@ -127,7 +128,7 @@ export function InviteNotifications() { if (invites.length <= perviousInviteLen || mx.getSyncState() !== SyncState.Syncing) return; // SW push (via Sygnal) handles invite notifications when the app is backgrounded. - if (!isPageVisible() && usePushNotifications) return; + if (!isPageVisible() && backgroundPushEnabled) return; const withSound = notificationSound && (isWindowFocused() || backgroundNotificationSounds); let soundOnNotification = false; @@ -153,7 +154,7 @@ export function InviteNotifications() { invites, perviousInviteLen, showSystemNotifications, - usePushNotifications, + backgroundPushEnabled, notificationSound, backgroundNotificationSounds, notify, @@ -704,6 +705,7 @@ function registerNativeNotificationListener( // payload attached in sendNativeTauriNotification. export function NativeNotificationClickRouting() { const setPending = useSetAtom(pendingNotificationAtom); + const setActiveSessionId = useSetAtom(activeSessionIdAtom); const navigate = useNavigate(); useEffect( @@ -716,6 +718,8 @@ export function NativeNotificationClickRouting() { .catch(() => {}); } if (!data) return; + if (!data.user_id) return; + setActiveSessionId(data.user_id); if (data.type === 'invite') { navigate(getInboxInvitesPath()); return; @@ -729,7 +733,7 @@ export function NativeNotificationClickRouting() { } }) ), - [setPending, navigate] + [setPending, setActiveSessionId, navigate] ); return null; @@ -740,6 +744,7 @@ const SABLE_REPLY_ACTION = 'sable-reply'; export function NativeNotificationActionRouting() { const mx = useMatrixClient(); + const [hideReads] = useSetting(settingsAtom, 'hideReads'); const queue = useAtomValue(nativeNotificationRepliesAtom); const sessions = useAtomValue(sessionsAtom); const sessionsRef = useRef(sessions); @@ -811,6 +816,9 @@ export function NativeNotificationActionRouting() { setInFlight((previous: Set) => new Set(previous).add(item.key)); void mx .sendMessage(item.roomId, null, { msgtype: MsgType.Text, body: item.text }) + // Replying is reading; otherwise the room stays unread and its + // notification lingers while later pushes stack onto it. + .then(() => markAsRead(mx, item.roomId, hideReads).catch(() => undefined)) .catch(() => { showToast('Reply was not sent. Open the room to retry.'); }) @@ -823,7 +831,7 @@ export function NativeNotificationActionRouting() { remove(item.key); }); return clearExpiryTimer; - }, [mx, queue, remove, setActiveSessionId, inFlight, setInFlight, replyWakeup]); + }, [mx, queue, remove, setActiveSessionId, inFlight, setInFlight, replyWakeup, hideReads]); return null; } diff --git a/src/app/pages/client/sidebar/DirectDMsList.tsx b/src/app/pages/client/sidebar/DirectDMsList.tsx index ac836775e..9b35447e2 100644 --- a/src/app/pages/client/sidebar/DirectDMsList.tsx +++ b/src/app/pages/client/sidebar/DirectDMsList.tsx @@ -15,12 +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 { useRoomAvatar, useRoomName } from '$hooks/useRoomMeta'; import { useSidebarDirectRoomIds } from './useSidebarDirectRoomIds'; import * as css from './DirectDMsList.css'; @@ -41,24 +42,18 @@ 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); + 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 = !getDmOtherMember(mx, room) && 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) { @@ -67,33 +62,11 @@ function DMItem({ room, selected }: DMItemProps) { ( - {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 +105,7 @@ function DMItem({ room, selected }: DMItemProps) { return ( - + {(triggerRef) => ( {renderAvatar()} 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] ); 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 []; 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/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/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 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/app/state/room/roomScheduleCoordinator.test.ts b/src/app/state/room/roomScheduleCoordinator.test.ts new file mode 100644 index 000000000..758f0ae1f --- /dev/null +++ b/src/app/state/room/roomScheduleCoordinator.test.ts @@ -0,0 +1,91 @@ +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) => { + 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(alice, '!room:example.org', async () => { + order.push('first-start'); + await first.promise; + order.push('first-end'); + }); + const secondOperation = roomScheduleCoordinator.run(alice, '!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(alice, '!room:example.org', async () => { + throw new Error('cancel failed'); + }) + ).rejects.toThrow('cancel failed'); + await expect(roomScheduleCoordinator.run(alice, '!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( + 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(); + + 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..80182b760 --- /dev/null +++ b/src/app/state/room/roomScheduleCoordinator.ts @@ -0,0 +1,15 @@ +import { createKeyedQueue } from '$utils/keyedQueue'; +import type { MatrixClient } from '$types/matrix-sdk'; + +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); + }, +}; 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> diff --git a/src/app/state/settings.defaults.test.ts b/src/app/state/settings.defaults.test.ts index 2b798084d..6703649d9 100644 --- a/src/app/state/settings.defaults.test.ts +++ b/src/app/state/settings.defaults.test.ts @@ -79,6 +79,28 @@ describe('mergePersistedSettings', () => { expect(merged).not.toHaveProperty('callCustomRingtoneName'); expect(merged).not.toHaveProperty('callCustomRingbackName'); }); + + it.each([ + [{ usePushNotifications: true }, true, null], + [{ usePushNotifications: true, useUnifiedPush: true }, true, 'unifiedpush'], + [{ usePushNotifications: false, useUnifiedPush: false }, false, null], + [ + { + usePushNotifications: true, + backgroundPushEnabled: false, + backgroundPushProvider: null, + }, + false, + null, + ], + ] as const)( + 'migrates legacy push settings without overwriting new transport state', + (persisted, enabled, provider) => { + const merged = mergePersistedSettings(JSON.stringify(persisted), {}); + expect(merged.backgroundPushEnabled).toBe(enabled); + expect(merged.backgroundPushProvider).toBe(provider); + } + ); }); describe('sanitizeSettingsDefaults', () => { diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index a296dbfe4..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; @@ -243,6 +238,7 @@ export interface Settings { pmpProxying: boolean; pmpLatching: boolean; pmpPicker: boolean; + pmpNoFallback: boolean; mentionInReplies: boolean; profileChangePropagation: ProfileChangePropagation; showPersonaSetting: boolean; @@ -261,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; @@ -424,6 +428,7 @@ export const defaultSettings: Settings = { pmpProxying: false, pmpLatching: false, pmpPicker: false, + pmpNoFallback: false, mentionInReplies: true, profileChangePropagation: 'unchanged', showPersonaSetting: false, @@ -441,6 +446,8 @@ export const defaultSettings: Settings = { widgetSidebarWidth: 420, isShowingAllRoomsInHome: false, sendIndividualAttachmentAsCaption: true, + nameColorLightnessCorrection: 'off', + // furry stuff renderAnimals: true, animalKind: undefined, @@ -483,6 +490,19 @@ const isCallToneId = (value: unknown): value is CallRingtoneId => CALL_TONE_ID_S const clampPercent = (value: number): number => Math.max(0, Math.min(100, Math.round(value))); function migrateParsedLocalStorage(parsed: Record): void { + if (typeof parsed.backgroundPushEnabled !== 'boolean') { + const legacyProvider = parsed.useUnifiedPush === true ? 'unifiedpush' : null; + if ( + legacyProvider !== null || + typeof parsed.usePushNotifications === 'boolean' || + typeof parsed.useUnifiedPush === 'boolean' + ) { + parsed.backgroundPushEnabled = + legacyProvider !== null || parsed.usePushNotifications === true; + parsed.backgroundPushProvider = legacyProvider; + } + } + const shortcutOverrides = sanitizeShortcutOverrides(parsed.shortcutOverrides); if (shortcutOverrides) parsed.shortcutOverrides = shortcutOverrides; else delete parsed.shortcutOverrides; 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: { 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'); diff --git a/src/app/utils/common.ts b/src/app/utils/common.ts index 3f590320a..c4c02430c 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 => { @@ -157,3 +151,7 @@ export const splitWithSpace = (content: string): string[] => { if (trimmedContent === '') return []; return trimmedContent.split(' '); }; + +export const xor = (left: unknown, right: unknown): boolean => { + return !left !== !right; +}; 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() ?? '', 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; + }; +} 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 new file mode 100644 index 000000000..4d5e7c999 --- /dev/null +++ b/src/app/utils/room/display.test.ts @@ -0,0 +1,160 @@ +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), + getMembers: () => [invitedMember], + 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('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; + const mx = { + getAccountData: () => ({ getContent: () => ({ '@alice:example.org': [room.roomId] }) }), + getUserId: () => '@me:example.org', + } as unknown as MatrixClient; + + 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 5bbaffa64..9394cdb13 100644 --- a/src/app/utils/room/display.ts +++ b/src/app/utils/room/display.ts @@ -1,7 +1,9 @@ -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 @@ -24,13 +26,45 @@ export const getRoomAvatarUrl = ( useAuthentication = false ): 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 ?? {}) + .filter( + ([userId, roomIds]) => + userId !== currentUserId && Array.isArray(roomIds) && roomIds.includes(room.roomId) + ) + .map(([userId]) => userId); + + const directMembers = directUserIds + .map((userId) => room.getMember(userId)) + .filter((member): member is RoomMember => member != null); + + return resolveDmOtherMember({ + currentUserId, + directMembers, + members: room.getMembers(), + functionalMemberIds: functionalMembers, + fallbackMember: room.getAvatarFallbackMember(), + }); +}; + 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); 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' ); }; diff --git a/src/client/initMatrix.test.ts b/src/client/initMatrix.test.ts index 4c0aca6d3..1482bbb96 100644 --- a/src/client/initMatrix.test.ts +++ b/src/client/initMatrix.test.ts @@ -1,8 +1,24 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import type { MatrixClient } from '$types/matrix-sdk'; import type { Session } from '$state/sessions'; +import type * as PlatformModule from '$utils/platform'; import { ACTIVE_SESSION_KEY, MATRIX_SESSIONS_KEY } from '$state/sessions'; -import { newSlidingSyncConnId, ownsActiveMediaSession, supportsSlidingSync } from './initMatrix'; + +const { isMobileTauri } = vi.hoisted(() => ({ + isMobileTauri: vi.fn<() => boolean>(), +})); + +vi.mock('$utils/platform', async (importOriginal) => ({ + ...(await importOriginal()), + isMobileTauri, +})); + +import { + newSlidingSyncConnId, + ownsActiveMediaSession, + resolvePollTimeoutMs, + supportsSlidingSync, +} from './initMatrix'; const alice = { userId: '@alice:example.org' } as Session; const bob = { userId: '@bob:example.org' } as Session; @@ -112,3 +128,27 @@ describe('supportsSlidingSync', () => { ).resolves.toEqual({ supported: false, reason: 'unknown' }); }); }); + +describe('resolvePollTimeoutMs', () => { + beforeEach(() => { + isMobileTauri.mockReset(); + }); + + it('uses the shorter poll on mobile tauri', () => { + isMobileTauri.mockReturnValue(true); + + expect(resolvePollTimeoutMs(undefined)).toBe(30000); + }); + + it('uses the default poll elsewhere', () => { + isMobileTauri.mockReturnValue(false); + + expect(resolvePollTimeoutMs(undefined)).toBe(45000); + }); + + it('prefers an explicitly configured timeout on mobile', () => { + isMobileTauri.mockReturnValue(true); + + expect(resolvePollTimeoutMs(5000)).toBe(5000); + }); +}); diff --git a/src/client/initMatrix.ts b/src/client/initMatrix.ts index 470812056..7e910c403 100644 --- a/src/client/initMatrix.ts +++ b/src/client/initMatrix.ts @@ -26,6 +26,7 @@ import { import { getLocalStorageItem } from '$state/utils/atomWithLocalStorage'; import { createLogger } from '$utils/debug'; import { createDebugLogger } from '$utils/debugLogger'; +import { isMobileTauri } from '$utils/platform'; import * as Sentry from '@sentry/react'; import { pushSessionToSW } from '../sw-session'; import { assertAuthMetadataIssuer, createSessionTokenRefresher } from './oidcTokenRefresher'; @@ -63,6 +64,12 @@ export const ownsActiveMediaSession = (session?: Session): boolean => { }; const presenceStartCleanupByClient = new WeakMap void>(); const SLIDING_SYNC_POLL_TIMEOUT_MS = 45000; +const SLIDING_SYNC_POLL_TIMEOUT_MOBILE_MS = 30000; + +/** Shorter poll on mobile: a wedged long-poll costs more when the OS freezes the webview. */ +export const resolvePollTimeoutMs = (configured?: number): number => + configured ?? + (isMobileTauri() ? SLIDING_SYNC_POLL_TIMEOUT_MOBILE_MS : SLIDING_SYNC_POLL_TIMEOUT_MS); const isInitialSyncReady = (state: string | null): boolean => state === SyncState.Prepared || state === SyncState.Syncing || state === SyncState.Catchup; @@ -156,6 +163,14 @@ function installSlidingSyncRequestPatch(mx: MatrixClient, manager: SlidingSyncMa const mxWritable = mx as MatrixClientWithWritableSlidingSync; const original = mx.slidingSync.bind(mx) as SlidingSyncMethod; mxWritable.slidingSync = async (reqBody, baseUrl, abortSignal) => { + // AbortError makes the SDK loop `continue` and reissue at the same `pos`, no sleep. + if (manager.isPaused()) { + await manager.waitForResume(); + const aborted = new Error('Sliding sync paused while backgrounded'); + aborted.name = 'AbortError'; + throw aborted; + } + const req = reqBody as SlidingSyncRequestWithConnId; if (req.conn_id === undefined) { req.conn_id = connId; @@ -516,7 +531,7 @@ export const startClient = async (mx: MatrixClient, config?: StartClientConfig): startPresenceAfterInitialSync(mx, presenceManager); manager = new SlidingSyncManager(mx, baseUrl, { - pollTimeoutMs: config?.pollTimeoutMs ?? SLIDING_SYNC_POLL_TIMEOUT_MS, + pollTimeoutMs: resolvePollTimeoutMs(config?.pollTimeoutMs), timelineLimit: config?.timelineLimit, initialRoomIds: config?.initialRoomIds, }); 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, diff --git a/src/client/slidingSync.test.ts b/src/client/slidingSync.test.ts index 7571a2581..dbca806e2 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 { markExpandedTimelinesLimited, @@ -22,6 +28,7 @@ const mocks = vi.hoisted(() => ({ off: vi.fn<() => void>(), removeListener: vi.fn<() => void>(), stop: vi.fn<() => void>(), + resend: vi.fn<() => void>(), modifyRoomSubscriptions: vi.fn<() => void>(), modifyRoomSubscriptionInfo: vi.fn<() => void>(), addCustomSubscription: vi.fn<() => void>(), @@ -173,8 +180,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([...lists.keys()]).toEqual(['joined', 'invites']); expect(defaultSubscription.timeline_limit).toBe(50); @@ -720,6 +728,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); @@ -1347,6 +1359,190 @@ describe('SlidingSyncManager.dispose()', () => { }); }); +describe('SlidingSyncManager poll watchdog', () => { + // DEFAULT_POLL_TIMEOUT_MS + SDK_CLIENT_TIMEOUT_BUFFER_MS + POLL_DEADLINE_MARGIN_MS + const DEFAULT_DEADLINE_MS = 45_000 + 10_000 + 20_000; + + it('cycles the transport when no lifecycle event arrives within the deadline', () => { + vi.useFakeTimers(); + try { + const manager = makeManager(makeMockMx()); + manager.attach(); + + expect(mocks.slidingSyncInstance.resend).not.toHaveBeenCalled(); + + vi.advanceTimersByTime(DEFAULT_DEADLINE_MS); + + expect(mocks.slidingSyncInstance.resend).toHaveBeenCalledOnce(); + } finally { + vi.useRealTimers(); + } + }); + + it('stays quiet while lifecycle events keep arriving', () => { + vi.useFakeTimers(); + try { + const manager = makeManager(makeMockMx()); + manager.attach(); + + for (let i = 0; i < 5; i += 1) { + vi.advanceTimersByTime(DEFAULT_DEADLINE_MS - 1_000); + fireLifecycle(SlidingSyncState.Complete, {}); + } + + expect(mocks.slidingSyncInstance.resend).not.toHaveBeenCalled(); + } finally { + vi.useRealTimers(); + } + }); + + it('keeps cycling when the replacement poll also wedges', () => { + vi.useFakeTimers(); + try { + const manager = makeManager(makeMockMx()); + manager.attach(); + + vi.advanceTimersByTime(DEFAULT_DEADLINE_MS); + expect(mocks.slidingSyncInstance.resend).toHaveBeenCalledOnce(); + + // No lifecycle event arrives, so the watchdog must re-arm itself. + vi.advanceTimersByTime(DEFAULT_DEADLINE_MS); + expect(mocks.slidingSyncInstance.resend).toHaveBeenCalledTimes(2); + + vi.advanceTimersByTime(DEFAULT_DEADLINE_MS); + expect(mocks.slidingSyncInstance.resend).toHaveBeenCalledTimes(3); + } finally { + vi.useRealTimers(); + } + }); + + it('does not fire after dispose', () => { + vi.useFakeTimers(); + try { + const manager = makeManager(makeMockMx()); + manager.attach(); + manager.dispose(); + + vi.advanceTimersByTime(DEFAULT_DEADLINE_MS * 2); + + expect(mocks.slidingSyncInstance.resend).not.toHaveBeenCalled(); + } finally { + vi.useRealTimers(); + } + }); +}); + +describe('SlidingSyncManager pause/resume', () => { + const DEFAULT_DEADLINE_MS = 45_000 + 10_000 + 20_000; + + it('aborts the in-flight poll on pause so the radio goes idle', () => { + const manager = makeManager(makeMockMx()); + manager.attach(); + + manager.pause(); + + expect(manager.isPaused()).toBe(true); + expect(mocks.slidingSyncInstance.resend).toHaveBeenCalledOnce(); + }); + + it('does not tear the transport down', () => { + const manager = makeManager(makeMockMx()); + manager.attach(); + + manager.pause(); + + expect(mocks.slidingSyncInstance.stop).not.toHaveBeenCalled(); + }); + + it('holds waitForResume() until resume', async () => { + const manager = makeManager(makeMockMx()); + manager.attach(); + manager.pause(); + + let resolved = false; + const parked = manager.waitForResume().then(() => { + resolved = true; + }); + + await Promise.resolve(); + expect(resolved).toBe(false); + + manager.resume(); + await parked; + + expect(resolved).toBe(true); + expect(manager.isPaused()).toBe(false); + }); + + it('resolves waitForResume() immediately when not paused', async () => { + const manager = makeManager(makeMockMx()); + manager.attach(); + + await expect(manager.waitForResume()).resolves.toBeUndefined(); + }); + + it('silences the poll watchdog while paused', () => { + vi.useFakeTimers(); + try { + const manager = makeManager(makeMockMx()); + manager.attach(); + manager.pause(); + mocks.slidingSyncInstance.resend.mockClear(); + + vi.advanceTimersByTime(DEFAULT_DEADLINE_MS * 3); + + expect(mocks.slidingSyncInstance.resend).not.toHaveBeenCalled(); + } finally { + vi.useRealTimers(); + } + }); + + 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 { + const manager = makeManager(makeMockMx()); + manager.attach(); + manager.pause(); + manager.resume(); + mocks.slidingSyncInstance.resend.mockClear(); + + vi.advanceTimersByTime(DEFAULT_DEADLINE_MS); + + expect(mocks.slidingSyncInstance.resend).toHaveBeenCalledOnce(); + } finally { + vi.useRealTimers(); + } + }); + + it('releases parked requests on dispose so the sync loop can unwind', async () => { + const manager = makeManager(makeMockMx()); + manager.attach(); + manager.pause(); + + const parked = manager.waitForResume(); + manager.dispose(); + + await expect(parked).resolves.toBeUndefined(); + }); +}); + // ── onMembershipLeave: auto-unsubscribe on leave/ban ───────────────────────── /** Fire the RoomMemberEvent.Membership listener registered on mx.on */ diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index 9e927424b..2a85c8d80 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'; @@ -37,6 +38,9 @@ const LIST_INVITES = 'invites'; const LIST_TIMELINE_LIMIT = 1; const LIST_PAGE_SIZE = 30; const DEFAULT_POLL_TIMEOUT_MS = 45000; +// Mirrors the js-sdk's own BUFFER_PERIOD_MS so our watchdog sits after its `clientTimeout`. +const SDK_CLIENT_TIMEOUT_BUFFER_MS = 10_000; +const POLL_DEADLINE_MARGIN_MS = 20_000; const ACTIVE_ROOM_SUBSCRIPTION_KEY = 'active_room'; const SIDEBAR_ROOM_SUBSCRIPTION_KEY = 'sidebar_room'; @@ -153,6 +157,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'] = [ @@ -190,6 +196,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]), ]; @@ -417,6 +424,14 @@ export class SlidingSyncManager { /** Wall-clock time recorded in attach() — used to compute true initial-sync latency. */ private attachTime: number | null = null; + private readonly pollDeadlineMs: number; + + private pollWatchdogTimer: ReturnType | undefined; + + private paused = false; + + private readonly resumeWaiters = new Set<() => void>(); + /** Span covering the period from attach() to the first successful complete cycle. */ private initialSyncSpan: ReturnType | null = null; @@ -428,6 +443,7 @@ export class SlidingSyncManager { options: SlidingSyncOptions = {} ) { const pollTimeoutMs = clampPositive(options.pollTimeoutMs, DEFAULT_POLL_TIMEOUT_MS); + this.pollDeadlineMs = pollTimeoutMs + SDK_CLIENT_TIMEOUT_BUFFER_MS + POLL_DEADLINE_MARGIN_MS; const roomTimelineLimit = clampPositive(options.timelineLimit, ACTIVE_ROOM_TIMELINE_LIMIT); this.roomTimelineLimit = roomTimelineLimit; @@ -485,6 +501,8 @@ export class SlidingSyncManager { return; } + this.armPollWatchdog(); + if (state === SlidingSyncState.RequestFinished) { if (!err && resp) { this.responseProcessing = true; @@ -671,9 +689,72 @@ export class SlidingSyncManager { this.mx.on(RoomMemberEvent.Membership, this.onMembershipLeave); this.mx.on(ClientEvent.AccountData, this.onCacheAccountData); + this.armPollWatchdog(); + debugLog.info('sync', 'Sliding sync listeners attached successfully'); } + /** + * Backstop for the SDK's own `clientTimeout`, which is a JS timer and so cannot fire + * while a mobile webview is frozen. Re-arms itself because the SDK's abort path + * `continue`s without emitting a lifecycle event. + */ + private armPollWatchdog(): void { + if (this.disposed || this.paused) return; + globalThis.clearTimeout(this.pollWatchdogTimer); + this.pollWatchdogTimer = globalThis.setTimeout(() => { + this.pollWatchdogTimer = undefined; + if (this.disposed) return; + debugLog.warn('sync', 'Sliding sync poll exceeded client-side deadline; cycling transport', { + pollDeadlineMs: this.pollDeadlineMs, + syncNumber: this.syncCount, + }); + this.slidingSync.resend(); + this.armPollWatchdog(); + }, this.pollDeadlineMs); + } + + /** + * Stop issuing requests without tearing the transport down. `SlidingSync.stop()` is + * terminal and drops the `pos` token held in `start()`, so stop/start would force a + * full initial sync on every resume; the request patch parks on `waitForResume()` + * instead. + */ + public pause(): void { + if (this.paused || this.disposed) return; + this.paused = true; + globalThis.clearTimeout(this.pollWatchdogTimer); + this.pollWatchdogTimer = undefined; + this.slidingSync.resend(); + debugLog.info('sync', 'Sliding sync paused'); + } + + public resume(): void { + if (!this.paused) return; + this.paused = false; + this.releaseResumeWaiters(); + this.armPollWatchdog(); + debugLog.info('sync', 'Sliding sync resumed'); + } + + public isPaused(): boolean { + return this.paused; + } + + /** Resolves on the next resume(), or immediately when not paused. */ + public waitForResume(): Promise { + if (!this.paused) return Promise.resolve(); + return new Promise((resolve) => { + this.resumeWaiters.add(resolve); + }); + } + + private releaseResumeWaiters(): void { + const waiters = Array.from(this.resumeWaiters); + this.resumeWaiters.clear(); + waiters.forEach((resolve) => resolve()); + } + public dispose(): void { if (this.disposed) return; @@ -697,6 +778,10 @@ export class SlidingSyncManager { this.hydrationStatusListeners.clear(); this.disposed = true; + this.paused = false; + this.releaseResumeWaiters(); + globalThis.clearTimeout(this.pollWatchdogTimer); + this.pollWatchdogTimer = undefined; this.slidingSync.stop(); this.slidingSync.removeListener(SlidingSyncEvent.Lifecycle, this.onLifecycle); this.slidingSync.removeListener(SlidingSyncEvent.RoomData, this.onCacheRoomData); 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, diff --git a/src/sw-media-auth-recovery.test.ts b/src/sw-media-auth-recovery.test.ts index 02b7067e1..1b27b2a9b 100644 --- a/src/sw-media-auth-recovery.test.ts +++ b/src/sw-media-auth-recovery.test.ts @@ -13,19 +13,25 @@ describe('service worker media auth recovery', () => { let swTestHooks: SwTestHooks; let clients: Map; let addEventListener: ReturnType; + let persistedSessions: string | undefined; beforeEach(async () => { vi.resetModules(); clients = new Map(); addEventListener = vi.fn(); + persistedSessions = undefined; vi.stubGlobal('self', { __WB_MANIFEST: [], addEventListener, caches: { open: vi.fn(async () => ({ delete: vi.fn(async () => true), - match: vi.fn(async () => undefined), - put: vi.fn(async () => undefined), + match: vi.fn(async () => + persistedSessions ? new Response(persistedSessions) : undefined + ), + put: vi.fn(async (_key: string, response: Response) => { + persistedSessions = await response.text(); + }), })), }, clients: { @@ -55,6 +61,117 @@ describe('service worker media auth recovery', () => { expect(respondWith).not.toHaveBeenCalled(); }); + it('does not borrow another account session for an unscoped media request', async () => { + const fetchHandler = addEventListener.mock.calls.find(([type]) => type === 'fetch')?.[1] as + | ((event: FetchEvent) => void) + | undefined; + const respondWith = vi.fn<(response: Promise) => void>(); + const request = new Request( + 'https://matrix.example.org/_matrix/client/v1/media/download/example.org/media-id' + ); + + await swTestHooks.setSession( + 'alice-window', + 'alice-token', + 'https://matrix.example.org', + '@alice:example.org' + ); + fetchHandler?.({ request, respondWith, clientId: 'widget-client' } as unknown as FetchEvent); + + await expect(respondWith.mock.calls[0]?.[0]).resolves.toMatchObject({ status: 503 }); + 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', + 'alice-token', + 'https://matrix.example.org', + '@alice:example.org' + ); + await swTestHooks.setSession( + 'client-a', + 'bob-token', + 'https://matrix.example.org', + '@bob:example.org' + ); + + expect(Object.keys(JSON.parse(persistedSessions ?? '{}'))).toEqual(['@bob:example.org']); + }); + + it('keeps a persisted account until its final client logs out', async () => { + await swTestHooks.setSession( + 'alice-a', + 'alice-token', + 'https://matrix.example.org', + '@alice:example.org' + ); + await swTestHooks.setSession( + 'alice-b', + 'alice-token', + 'https://matrix.example.org', + '@alice:example.org' + ); + await swTestHooks.setSession( + 'alice-a', + 'bob-token', + 'https://matrix.example.org', + '@bob:example.org' + ); + + expect(Object.keys(JSON.parse(persistedSessions ?? '{}')).toSorted()).toEqual([ + '@alice:example.org', + '@bob:example.org', + ]); + + await swTestHooks.setSession('alice-b', undefined, undefined); + expect(Object.keys(JSON.parse(persistedSessions ?? '{}'))).toEqual(['@bob:example.org']); + }); + it('shares recovery and preserves each Range header on retry', async () => { const client = { id: 'client-a', diff --git a/src/sw-session-persistence.test.ts b/src/sw-session-persistence.test.ts index 97f6c7528..69530243a 100644 --- a/src/sw-session-persistence.test.ts +++ b/src/sw-session-persistence.test.ts @@ -1,6 +1,12 @@ -import { describe, expect, it } from 'vitest'; +/* oxlint-disable vitest/require-mock-type-parameters */ +import { beforeEach, describe, expect, it, vi } from 'vitest'; import { readPersistedSession } from './sw-session-persistence'; +vi.mock('workbox-precaching', () => ({ + cleanupOutdatedCaches: vi.fn(), + precacheAndRoute: vi.fn(), +})); + describe('readPersistedSession', () => { it('keeps older persisted sessions instead of expiring them after one minute', () => { const persistedAt = Date.now() - 1000 * 60 * 60 * 6; @@ -20,3 +26,95 @@ describe('readPersistedSession', () => { }); }); }); + +describe('service worker session persistence', () => { + let addEventListener: ReturnType; + let cachePut: ReturnType; + let resolveCachePut: (() => void) | undefined; + + beforeEach(async () => { + vi.resetModules(); + addEventListener = vi.fn(); + cachePut = vi.fn( + () => + new Promise((resolve) => { + resolveCachePut = resolve; + }) + ); + + vi.stubGlobal('self', { + __WB_MANIFEST: [], + addEventListener, + caches: { + open: vi.fn(async () => ({ + delete: vi.fn(async () => true), + match: vi.fn(async () => undefined), + put: cachePut, + })), + }, + clients: { + claim: vi.fn(), + get: vi.fn(), + matchAll: vi.fn(async () => []), + }, + registration: {}, + }); + vi.stubGlobal('fetch', vi.fn()); + await import('./sw'); + }); + + it('keeps setSession persistence alive through waitUntil', async () => { + const messageHandler = addEventListener.mock.calls.find(([type]) => type === 'message')?.[1] as + | ((event: ExtendableMessageEvent) => void) + | undefined; + const waitUntil = vi.fn<(promise: Promise) => void>(); + + messageHandler?.({ + source: { id: 'client-a' }, + data: { + type: 'setSession', + accessToken: 'token', + baseUrl: 'https://matrix.example.org', + userId: '@alice:example.org', + }, + waitUntil, + } as unknown as ExtendableMessageEvent); + + expect(messageHandler).toBeTypeOf('function'); + expect(waitUntil).toHaveBeenCalledOnce(); + + let settled = false; + const lifetime = waitUntil.mock.calls[0]?.[0]; + void lifetime?.then(() => { + settled = true; + }); + await vi.waitFor(() => expect(resolveCachePut).toBeTypeOf('function')); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(settled).toBe(false); + + resolveCachePut?.(); + await expect(lifetime).resolves.toBeUndefined(); + }); + + it('settles the worker lifetime when session persistence fails', async () => { + cachePut.mockRejectedValueOnce(new Error('cache unavailable')); + const messageHandler = addEventListener.mock.calls.find(([type]) => type === 'message')?.[1] as + | ((event: ExtendableMessageEvent) => void) + | undefined; + const waitUntil = vi.fn<(promise: Promise) => void>(); + + messageHandler?.({ + source: { id: 'client-a' }, + data: { + type: 'setSession', + accessToken: 'token', + baseUrl: 'https://matrix.example.org', + userId: '@alice:example.org', + }, + waitUntil, + } as unknown as ExtendableMessageEvent); + + expect(waitUntil).toHaveBeenCalledOnce(); + await expect(waitUntil.mock.calls[0]?.[0]).resolves.toBeUndefined(); + }); +}); diff --git a/src/sw.ts b/src/sw.ts index 8b20daea5..2f23eeb47 100644 --- a/src/sw.ts +++ b/src/sw.ts @@ -6,6 +6,7 @@ import { EventType } from 'matrix-js-sdk/lib/@types/event'; import { createPushNotifications } from './sw/pushNotification'; import { withMediaFetchSlot } from './app/utils/mediaConcurrency'; +import { readPersistedSession } from './sw-session-persistence'; declare const self: ServiceWorkerGlobalScope; @@ -26,7 +27,7 @@ const { handlePushNotificationPushData } = createPushNotifications(self, () => ( const SW_SETTINGS_CACHE = 'sable-sw-settings-v1'; const SW_SETTINGS_URL = '/sw-settings-meta'; -/** Cache key used to persist the active session so push-event fetches work after SW restart. */ +/** Cache key used to persist sessions so push-event fetches work after SW restart. */ const SW_SESSION_CACHE = 'sable-sw-session-v1'; const SW_SESSION_URL = '/sw-session-meta'; @@ -77,43 +78,54 @@ async function loadPersistedSettings() { } } -async function persistSession(session: SessionInfo): Promise { - try { - const cache = await self.caches.open(SW_SESSION_CACHE); - await cache.put( - SW_SESSION_URL, - new Response(JSON.stringify(session), { - headers: { 'Content-Type': 'application/json' }, - }) - ); - } catch { - // Ignore — caches may be unavailable in some environments. - } -} - -async function clearPersistedSession(): Promise { - try { - const cache = await self.caches.open(SW_SESSION_CACHE); - await cache.delete(SW_SESSION_URL); - } catch { - // Ignore. - } -} - -async function loadPersistedSession(): Promise { +async function loadPersistedSessions(): Promise> { try { const cache = await self.caches.open(SW_SESSION_CACHE); const response = await cache.match(SW_SESSION_URL); - if (!response) return undefined; - const s = await response.json(); - if (typeof s.accessToken === 'string' && typeof s.baseUrl === 'string') { - return { - accessToken: s.accessToken, - baseUrl: s.baseUrl, - userId: typeof s.userId === 'string' ? s.userId : undefined, - }; + if (!response) return {}; + const value = await response.json(); + const sessions: Record = {}; + + if (typeof value !== 'object' || value === null) return sessions; + const legacySession = readPersistedSession(value); + if (legacySession?.userId) return { [legacySession.userId]: legacySession }; + for (const [userId, candidate] of Object.entries(value)) { + const session = readPersistedSession(candidate); + if (session?.userId === userId) sessions[userId] = session; } - return undefined; + return sessions; + } catch { + return {}; + } +} + +let persistedSessionWrites = Promise.resolve(); + +function updatePersistedSession(userId: string, session?: SessionInfo): Promise { + const update = async () => { + try { + const cache = await self.caches.open(SW_SESSION_CACHE); + const sessions = await loadPersistedSessions(); + if (session) sessions[userId] = session; + else delete sessions[userId]; + await cache.put( + SW_SESSION_URL, + new Response(JSON.stringify(sessions), { + headers: { 'Content-Type': 'application/json' }, + }) + ); + } catch { + // Ignore, caches may be unavailable in some environments. + } + }; + + persistedSessionWrites = persistedSessionWrites.then(update, update); + return persistedSessionWrites; +} + +async function loadPersistedSession(userId: string): Promise { + try { + return (await loadPersistedSessions())[userId]; } catch { return undefined; } @@ -131,14 +143,6 @@ type SessionInfo = { */ const sessions = new Map(); -/** - * Session pre-loaded from cache on SW activation. Acts as an immediate - * fallback so media fetches don't 401 during the window between SW restart - * and the first live setSession message from the page. - * Cleared as soon as any real setSession call comes in. - */ -let preloadedSession: SessionInfo | undefined; - type PendingSessionRequest = { promise: Promise; resolve: (value: SessionInfo | undefined) => void; @@ -157,7 +161,14 @@ async function cleanupDeadClients() { }); } -function setSession(clientId: string, accessToken: unknown, baseUrl: unknown, userId?: unknown) { +function setSession( + clientId: string, + accessToken: unknown, + baseUrl: unknown, + userId?: unknown +): Promise { + const previous = sessions.get(clientId); + const persistence: Promise[] = []; if (typeof accessToken === 'string' && typeof baseUrl === 'string') { const info: SessionInfo = { accessToken, @@ -165,17 +176,20 @@ function setSession(clientId: string, accessToken: unknown, baseUrl: unknown, us userId: typeof userId === 'string' ? userId : undefined, }; sessions.set(clientId, info); - // A real session has arrived — discard the preloaded fallback. - preloadedSession = undefined; console.debug('[SW] setSession: stored', clientId, baseUrl); - // Persist so push-event fetches work after iOS restarts the SW. - persistSession(info).catch(() => undefined); + if (info.userId) persistence.push(updatePersistedSession(info.userId, info)); } else { // Logout or invalid session sessions.delete(clientId); - preloadedSession = undefined; console.debug('[SW] setSession: removed', clientId); - clearPersistedSession().catch(() => undefined); + } + + if ( + previous?.userId && + previous.userId !== sessions.get(clientId)?.userId && + ![...sessions.values()].some((session) => session.userId === previous.userId) + ) { + persistence.push(updatePersistedSession(previous.userId)); } const pending = pendingSessionRequests.get(clientId); @@ -183,6 +197,8 @@ function setSession(clientId: string, accessToken: unknown, baseUrl: unknown, us pending.resolve(sessions.get(clientId)); pendingSessionRequests.delete(clientId); } + + return Promise.all(persistence).then(() => undefined); } function requestSession(client: Client): Promise { @@ -366,12 +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`; } -/** - * Return the first any-session we have stored (used for push fetches where we - * don't have a client ID, e.g. when the app is backgrounded but still loaded). - */ -function getAnyStoredSession(): SessionInfo | undefined { - return sessions.values().next().value; +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; } /** @@ -434,12 +455,10 @@ async function requestDecryptionFromClient( async function handleMinimalPushPayload( roomId: string, eventId: string, + userId: string | undefined, windowClients: readonly Client[] ): Promise { - // On iOS the SW is killed and restarted for every push, clearing the in-memory sessions - // Map. Fall back to the Cache Storage copy that was written when the user last opened - // the app (same pattern as settings persistence). - const session = getAnyStoredSession() ?? (await loadPersistedSession()); + const session = await getSessionForPush(userId); if (!session) { // No session anywhere — app was never opened since install, or the user logged out. @@ -555,10 +574,6 @@ self.addEventListener('activate', (event: ExtendableEvent) => { (async () => { await self.clients.claim(); await cleanupDeadClients(); - // Pre-load the persisted session into memory so that media fetches arriving - // before the first setSession message from the page are immediately - // authenticated rather than falling through to a 3-second timeout. - preloadedSession = await loadPersistedSession(); // Proactively request sessions from all window clients so the sessions Map // is pre-populated after a SW restart, rather than waiting for the first // media fetch to trigger requestSessionWithTimeout. @@ -580,8 +595,11 @@ self.addEventListener('message', (event: ExtendableMessageEvent) => { const { type, accessToken, baseUrl, userId } = data as Record; if (type === 'setSession') { - setSession(client.id, accessToken, baseUrl, userId); - event.waitUntil(cleanupDeadClients()); + event.waitUntil( + Promise.all([setSession(client.id, accessToken, baseUrl, userId), cleanupDeadClients()]).then( + () => undefined + ) + ); } if (type === 'swMediaAuthProbe') { // Capability handshake: prove this SW intercepts authenticated media so the @@ -849,6 +867,7 @@ function unavailableAuthenticatedMediaResponse(): Response { } export const swTestHooks = { + getSessionForPush, requestSessionWithTimeout, respondWithMediaAuthRecovery, setSession, @@ -911,34 +930,9 @@ self.addEventListener('fetch', (event: FetchEvent) => { return; } - // Since widgets like element call have their own client ids, - // we need this logic. We just go through the sessions list and get a session - // with the right base url. Media requests to a homeserver simply are fine with any account - // on the homeserver authenticating it, so this is fine. But it can be technically wrong. - // If you have two tabs for different users on the same homeserver, it might authenticate - // as the wrong one. - // Thus any logic in the future which cares about which user is authenticating the request - // might break this. Also, again, it is technically wrong. - // Also checks preloadedSession — populated from cache at SW activate — for the window - // between SW restart and the first live setSession arriving from the page. - const byBaseUrl = - [...sessions.values()].find((s) => validMediaRequest(url, s.baseUrl)) ?? - (preloadedSession && validMediaRequest(url, preloadedSession.baseUrl) - ? preloadedSession - : undefined); - if (byBaseUrl) { - event.respondWith(respondWithMediaAuthRecovery(event.request, byBaseUrl, redirect, clientId)); - return; - } - - // No clientId: the fetch came from a context not associated with a specific - // window (e.g. a prerender). Fall back to the persisted session directly. if (!clientId) { event.respondWith( - loadPersistedSession().then((persisted) => { - if (persisted && validMediaRequest(url, persisted.baseUrl)) { - return respondWithMediaAuthRecovery(event.request, persisted, redirect); - } + Promise.resolve().then(() => { if (authenticatedMediaPath(url)) return unavailableAuthenticatedMediaResponse(); return fetch(event.request); }) @@ -952,12 +946,6 @@ self.addEventListener('fetch', (event: FetchEvent) => { if (s && validMediaRequest(url, s.baseUrl)) { return respondWithMediaAuthRecovery(event.request, s, redirect, clientId); } - // Fallback: try the persisted session (helps when SW restarts on iOS and - // the client window hasn't responded to requestSession yet). - const persisted = await loadPersistedSession(); - if (persisted && validMediaRequest(url, persisted.baseUrl)) { - return respondWithMediaAuthRecovery(event.request, persisted, redirect, clientId); - } if (authenticatedMediaPath(url)) return unavailableAuthenticatedMediaResponse(); return fetch(event.request); }) @@ -966,7 +954,9 @@ self.addEventListener('fetch', (event: FetchEvent) => { // Detect a minimal (event_id_only) payload: has room_id + event_id but no // event type field — meaning the homeserver stripped the event content. -function isMinimalPushPayload(data: unknown): data is { room_id: string; event_id: string } { +function isMinimalPushPayload( + data: unknown +): data is { room_id: string; event_id: string; user_id?: string } { if (!data || typeof data !== 'object') return false; const d = data as Record; return typeof d.room_id === 'string' && typeof d.event_id === 'string' && !d.type; @@ -978,9 +968,8 @@ const onPushNotification = async (event: PushEvent) => { // The SW may have been restarted by the OS (iOS is aggressive about this), // so in-memory settings would be at their defaults. Reload from cache and // match active clients in parallel — they are independent operations. - const [, , clients] = await Promise.all([ + const [, clients] = await Promise.all([ loadPersistedSettings(), - loadPersistedSession(), self.clients.matchAll({ type: 'window', includeUncontrolled: true }), ]); @@ -1037,7 +1026,7 @@ const onPushNotification = async (event: PushEvent) => { // to relay decryption to an open app tab. if (isMinimalPushPayload(pushData)) { console.debug('[SW push] minimal payload detected — fetching event', pushData.event_id); - await handleMinimalPushPayload(pushData.room_id, pushData.event_id, clients); + await handleMinimalPushPayload(pushData.room_id, pushData.event_id, pushData.user_id, clients); return; } diff --git a/src/types/tauri-plugin-notifications-api.d.ts b/src/types/tauri-plugin-notifications-api.d.ts index dbcb7c3a5..8e4549b95 100644 --- a/src/types/tauri-plugin-notifications-api.d.ts +++ b/src/types/tauri-plugin-notifications-api.d.ts @@ -9,6 +9,13 @@ declare module '@choochmeque/tauri-plugin-notifications-api' { readonly High: 4; }; + export type NotificationMessage = { + body: string; + timestamp: number; + senderName?: string; + senderKey?: string; + }; + export type NotificationOptions = { id?: number; channelId?: string; @@ -22,6 +29,8 @@ declare module '@choochmeque/tauri-plugin-notifications-api' { groupSummary?: boolean; sound?: string; inboxLines?: string[]; + messages?: NotificationMessage[]; + groupConversation?: boolean; icon?: string; largeIcon?: string; iconColor?: string; 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';