Compare commits

..
150 changed files with 4747 additions and 7227 deletions
@@ -1,53 +0,0 @@
<!-- Maintainer template. External contributors use the default template. -->
## Motivation and context
<!-- Link the issue this closes, or explain the context for a bug fix -->
## Plan (optional)
_Reviewer: read and challenge this plan carefully as part of the review._
<!--
Only if this change was made with AI; delete this section otherwise.
Plan := the final version of the human-edited plan/prompt this change used.
It is not the implementation plan from Claude's plan mode. That goes under Content.
-->
## Content
<!--
Mandatory. Describe what has been changed.
This is also where an LLM implementation plan or other plan artifacts are linked:
paste them in a collapsed <details> block, or attach them as files.
-->
## Screenshots / GIFs / Storybook links
<!--
You can use a table like this to show a before/after comparison.
Uncomment the markdown table below and fill in the last line:
|Before|After|
|-|-|
|||
-->
## Tests
<!-- Explain how you tested your changes -->
- Step 1
- Step ...
## Checklist
- [ ] Exactly one `PR-*` label is set.
- [ ] New behaviour has unit tests, a story if it renders, and an e2e spec if it is user-facing.
- [ ] Visible changes link their Storybook stories (add the `storybook build` label for a preview deploy).
- [ ] Visible changes without a story include screenshots or a video.
- [ ] Checked standalone, as a widget and as a component.
- [ ] Linter and other CI checks pass.
- [ ] Claude review has been run at least once (assign the Claude-Review label)
@@ -9,11 +9,6 @@ on:
required: false
type: string
default: ${{ github.run_id }}
secrets:
TS_OAUTH_CLIENT_ID:
required: true
TS_AUDIENCE:
required: true
env:
REGISTRY: ghcr.io
+2 -2
View File
@@ -7,7 +7,7 @@ on:
type: string
package:
type: string # This would ideally be a `choice` type, but that isn't supported yet
description: The package type to be built. Must be one of 'full', 'embedded', or 'widget-rtc-sdk'
description: The package type to be built. Must be one of 'full', 'embedded', or 'sdk'
required: true
build_mode:
type: string # This would ideally be a `choice` type, but that isn't supported yet
@@ -38,7 +38,7 @@ jobs:
- name: Enable Corepack
run: corepack enable
- name: pnpm cache
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
cache: "pnpm"
node-version-file: ".node-version"
+12 -24
View File
@@ -7,15 +7,10 @@ on:
- labeled
push:
branches: [main]
permissions: {}
jobs:
build_full_element_call:
# Use the full package vite build
permissions:
contents: read
uses: $/.github/workflows/build-element-call.yaml
uses: ./.github/workflows/build-element-call.yaml
with:
package: full
vite_app_version: ${{ github.event.release.tag_name || github.sha }}
@@ -31,7 +26,6 @@ jobs:
if: github.ref == 'refs/heads/main'
needs: build_full_element_call
runs-on: ubuntu-24.04
permissions: {}
steps:
- name: Deploy to call.element.dev
uses: actions/github-script@d7906e4ad0b1822421a7e6a35d5ca353c962f410 # v6
@@ -56,10 +50,8 @@ jobs:
contents: write
packages: write
id-token: write
uses: $/.github/workflows/build-and-publish-docker.yaml
secrets:
TS_OAUTH_CLIENT_ID: ${{ secrets.TS_OAUTH_CLIENT_ID }}
TS_AUDIENCE: ${{ secrets.TS_AUDIENCE }}
uses: ./.github/workflows/build-and-publish-docker.yaml
secrets: inherit
with:
artifact_run_id: ${{ github.run_id }}
docker_tags: |
@@ -68,9 +60,7 @@ jobs:
type=raw,value=latest-ci_{{date 'X' }}
build_embedded_element_call:
# Use the embedded package vite build
permissions:
contents: read
uses: $/.github/workflows/build-element-call.yaml
uses: ./.github/workflows/build-element-call.yaml
with:
package: embedded
vite_app_version: ${{ github.event.release.tag_name || github.sha }}
@@ -82,14 +72,14 @@ jobs:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
build_widget_rtc_sdk:
# The widget wrapper around the sdk/ package (widget-rtc-sdk/), not the
# package itself. Deployed by pr-deploy.yaml as the pr<N>-widget-rtc-sdk preview.
permissions:
contents: read
uses: $/.github/workflows/build-element-call.yaml
build_sdk_element_call:
# The 'sdk' package is the CallViewModel bundle that predates the sdk/
# package (build:sdk:production, sdk-target-based-on-call-view-model/), not
# the package itself. The name is shared with pr-deploy.yaml, which always
# runs from main, so it stays until the bundle's consumers have moved over.
uses: ./.github/workflows/build-element-call.yaml
with:
package: widget-rtc-sdk
package: sdk
vite_app_version: ${{ github.event.release.tag_name || github.sha }}
build_mode: ${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'development build') && 'development' || 'production' }}
secrets:
@@ -103,8 +93,6 @@ jobs:
name: Build Storybook
if: contains(github.event.pull_request.labels.*.name, 'storybook build')
runs-on: ubuntu-24.04
permissions:
contents: read
steps:
- name: Checkout code
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
@@ -113,7 +101,7 @@ jobs:
- name: Enable Corepack
run: corepack enable
- name: pnpm cache
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
cache: "pnpm"
node-version-file: ".node-version"
+4 -18
View File
@@ -44,13 +44,12 @@ jobs:
that still deliver value?
2. Commits:
- Is the work split into self-contained commits of reasonable size?
- Are the commits arranged in a sensible order?
- Have required refactorings been split out into separate commits?
- Is the history free of "wip", checkpoint and fixup-style commits
which only correct an earlier commit in the same PR?
- Are SDK and Element Call changes split into separate commits?
3. Code:
@@ -61,19 +60,6 @@ jobs:
- Don't check anything that is already validated via other GitHub
workflows like linting, formatting or tests passing.
4. Code style:
- Does the change follow docs/agents/code-style.md and
docs/agents/architecture.md?
5. Repo architecture:
- Does the change follow "Element Call on the SDK" in
docs/agents/architecture.md and, where it touches `sdk/`,
sdk/SdkArchitecture.md?
- If an `api.ts` changed and the PR description does not document
it, summarize the change in the final review comment.
Read the commits themselves with `git log` and `git diff` against
the base branch of the PR.
@@ -82,9 +68,9 @@ jobs:
"🟠 medium" or "🔴 high". Devise at least one possible resolution for each
finding.
Report the graded findings and resolutions from the "Code" and "Code style"
angles as inline comments. Add a footer "_-- Finding from automated review_"
to each inline comment.
Report the graded findings and resolutions from the "Code" angle as inline
comments. Add a footer "_-- Finding from automated review_" to each inline
comment.
Finally, report your overall result as PR comment. Start your message with
"# Automated review". Then add one section per review angle with:
+11 -13
View File
@@ -17,7 +17,7 @@ on:
package:
required: true
type: string
description: Which package to deploy - 'full', 'embedded', 'widget-rtc-sdk', or 'storybook'
description: Which package to deploy - 'full', 'embedded', 'sdk', or 'storybook'
artifact_run_id:
required: false
type: string
@@ -64,27 +64,25 @@ jobs:
run: curl -s https://raw.githubusercontent.com/element-hq/element-call/main/config/netlify_redirects > webapp/_redirects
- name: Add config file
# Only the app reads a config.json beside it. A widget gets everything
# about the homeserver from its host.
if: inputs.package == 'full'
run: curl -s "https://raw.githubusercontent.com/${INPUTS_PR_HEAD_FULL_NAME}/${INPUTS_PR_HEAD_REF}/config/config_netlify_preview.json" > webapp/config.json
# Not needed for storybook deployments
if: inputs.package != 'storybook'
run: |
if [ "${INPUTS_PACKAGE}" = "full" ]; then
curl -s "https://raw.githubusercontent.com/${INPUTS_PR_HEAD_FULL_NAME}/${INPUTS_PR_HEAD_REF}/config/config_netlify_preview.json" > webapp/config.json
else
curl -s "https://raw.githubusercontent.com/${INPUTS_PR_HEAD_FULL_NAME}/${INPUTS_PR_HEAD_REF}/config/config_netlify_preview_sdk.json" > webapp/config.json
fi
env:
INPUTS_PACKAGE: ${{ inputs.package }}
INPUTS_PR_HEAD_FULL_NAME: ${{ inputs.pr_head_full_name }}
INPUTS_PR_HEAD_REF: ${{ inputs.pr_head_ref }}
- name: Add headers file
# A widget page on another origin imports the widget RTC SDK bundle as a
# module, which the browser only allows with CORS
if: inputs.package == 'widget-rtc-sdk'
run: |
printf '/*\n Access-Control-Allow-Origin: *\n' > webapp/_headers
- name: ☁️ Deploy to Netlify
id: netlify
uses: nwtgck/actions-netlify@4cbaf4c08f1a7bfa537d6113472ef4424e4eb654 # v3.0
with:
publish-dir: webapp
deploy-message: "Deploy from GitHub Actions"
alias: ${{ inputs.package == 'widget-rtc-sdk' && format('pr{0}-widget-rtc-sdk', inputs.pr_number) || inputs.package == 'storybook' && format('pr{0}-storybook', inputs.pr_number) || format('pr{0}', inputs.pr_number) }}
alias: ${{ inputs.package == 'sdk' && format('pr{0}-sdk', inputs.pr_number) || inputs.package == 'storybook' && format('pr{0}-storybook', inputs.pr_number) || format('pr{0}', inputs.pr_number) }}
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
+1 -6
View File
@@ -7,15 +7,10 @@ on:
type: string
required: false
description: The matrix-js-sdk commit to build against instead of the locked one
permissions: {}
jobs:
lint:
name: Lint, format & type check
runs-on: ubuntu-24.04
permissions:
contents: read
steps:
- name: Checkout code
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
@@ -26,7 +21,7 @@ jobs:
- name: Enable Corepack
run: corepack enable
- name: pnpm cache
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
cache: "pnpm"
node-version-file: ".node-version"
+7 -13
View File
@@ -7,8 +7,6 @@ on:
types:
- completed
permissions: {}
jobs:
prdetails:
# Logic:
@@ -20,8 +18,6 @@ jobs:
github.event.workflow_run.event == 'pull_request' &&
github.event.workflow_run.head_repository.full_name == github.repository
runs-on: ubuntu-24.04
permissions:
pull-requests: read
outputs:
pr_number: ${{ steps.prdetails.outputs.pr_id }}
pr_data_json: ${{ steps.prdetails.outputs.data }}
@@ -37,7 +33,7 @@ jobs:
needs: prdetails
permissions:
deployments: write
uses: $/.github/workflows/deploy-to-netlify.yaml
uses: ./.github/workflows/deploy-to-netlify.yaml
with:
artifact_run_id: ${{ github.event.workflow_run.id || github.run_id }}
pr_number: ${{ needs.prdetails.outputs.pr_number }}
@@ -50,18 +46,18 @@ jobs:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
netlify-widget-rtc-sdk:
netlify-sdk:
needs: prdetails
permissions:
deployments: write
uses: $/.github/workflows/deploy-to-netlify.yaml
uses: ./.github/workflows/deploy-to-netlify.yaml
with:
artifact_run_id: ${{ github.event.workflow_run.id || github.run_id }}
pr_number: ${{ needs.prdetails.outputs.pr_number }}
pr_head_full_name: ${{ github.event.workflow_run.head_repository.full_name }}
pr_head_ref: ${{ needs.prdetails.outputs.pr_data_json && fromJSON(needs.prdetails.outputs.pr_data_json).head.ref }}
deployment_ref: ${{ needs.prdetails.outputs.pr_data_json && fromJSON(needs.prdetails.outputs.pr_data_json).head.sha || github.ref || github.head_ref }}
package: widget-rtc-sdk
package: sdk
secrets:
ELEMENT_BOT_TOKEN: ${{ secrets.ELEMENT_BOT_TOKEN }}
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
@@ -72,7 +68,7 @@ jobs:
if: ${{ needs.prdetails.outputs.pr_data_json && contains(fromJSON(needs.prdetails.outputs.pr_data_json).labels.*.name, 'storybook build') }}
permissions:
deployments: write
uses: $/.github/workflows/deploy-to-netlify.yaml
uses: ./.github/workflows/deploy-to-netlify.yaml
with:
artifact_run_id: ${{ github.event.workflow_run.id || github.run_id }}
pr_number: ${{ needs.prdetails.outputs.pr_number }}
@@ -92,10 +88,8 @@ jobs:
contents: write
packages: write
id-token: write
uses: $/.github/workflows/build-and-publish-docker.yaml
secrets:
TS_OAUTH_CLIENT_ID: ${{ secrets.TS_OAUTH_CLIENT_ID }}
TS_AUDIENCE: ${{ secrets.TS_AUDIENCE }}
uses: ./.github/workflows/build-and-publish-docker.yaml
secrets: inherit
with:
artifact_run_id: ${{ github.event.workflow_run.id || github.run_id }}
docker_tags: |
+7 -20
View File
@@ -73,10 +73,9 @@ jobs:
- name: Enable Corepack
run: corepack enable
- name: Setup node
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
# No dependency cache: a release build must not restore one another workflow could have poisoned
with:
package-manager-cache: false
node-version-file: .node-version
registry-url: "https://registry.npmjs.org"
# Layered like build-element-call.yaml, so a PR paired with a matrix-js-sdk branch
@@ -113,10 +112,8 @@ jobs:
if: ${{ needs.versioning.outputs.DRY_RUN == 'false' }}
name: Update release notes
runs-on: ubuntu-24.04
# Shared with publish.yaml and publish-embedded-packages.yaml, which append to the same
# release. GitHub lets only one job wait per group, so if all three arrive at once the
# waiting one is cancelled: re-run it. To mitigate this, the append exits early when its
# heading already exists.
# Shared with publish-embedded-packages.yaml, which appends to the same release: two
# appends at once would each write back the body without the other's section
concurrency:
group: release-notes-${{ github.event.release.tag_name || github.run_id }}
cancel-in-progress: false
@@ -124,20 +121,10 @@ jobs:
contents: write # to update release notes
steps:
- name: Add release notes
run: |
gh release view "$RELEASE_TAG" --json body --jq .body > release-body.md
if grep -qF "$HEADING" release-body.md; then
echo "Section already present, nothing to add"
exit 0
fi
printf '%s\n' "$NOTES" >> release-body.md
gh release edit "$RELEASE_TAG" --notes-file release-body.md
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
RELEASE_TAG: ${{ github.event.release.tag_name }}
HEADING: "## React component (experimental)"
NOTES: |
uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
with:
append_body: true
body: |
## React component (experimental)
@@ -11,8 +11,6 @@ on:
push:
branches: [main]
permissions: {}
jobs:
versioning:
name: Versioning
@@ -64,9 +62,7 @@ jobs:
build_element_call:
needs: versioning
permissions:
contents: read
uses: $/.github/workflows/build-element-call.yaml
uses: ./.github/workflows/build-element-call.yaml
with:
vite_app_version: embedded-${{ needs.versioning.outputs.PREFIXED_VERSION }}
package: embedded
@@ -101,11 +97,11 @@ jobs:
run: find ${FILENAME_PREFIX} -type f -print0 | sort -z | xargs -0 sha256sum | tee ${FILENAME_PREFIX}.sha256
- name: Upload
if: ${{ needs.versioning.outputs.DRY_RUN == 'false' }}
run: gh release upload "$RELEASE_TAG" "${FILENAME_PREFIX}.tar.gz" "${FILENAME_PREFIX}.sha256" --clobber
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
RELEASE_TAG: ${{ github.event.release.tag_name }}
uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
with:
files: |
${{ env.FILENAME_PREFIX }}.tar.gz
${{ env.FILENAME_PREFIX }}.sha256
publish_npm:
needs: [build_element_call, versioning]
@@ -133,10 +129,8 @@ jobs:
# n.b. We don't enable corepack here because we are using plain npm
- name: Setup node
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
# No dependency cache: a release build must not restore one another workflow could have poisoned
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
package-manager-cache: false
node-version-file: .node-version
registry-url: "https://registry.npmjs.org"
@@ -289,10 +283,8 @@ jobs:
if: always()
name: Update release notes
runs-on: ubuntu-24.04
# Shared with publish.yaml and publish-component.yaml, which append to the same
# release. GitHub lets only one job wait per group, so if all three arrive at once the
# waiting one is cancelled: re-run it. To mitigate this, the append exits early when its
# heading already exists.
# Shared with publish-component.yaml, which appends to the same release: two appends
# at once would each write back the body without the other's section
concurrency:
group: release-notes-${{ github.event.release.tag_name || github.run_id }}
cancel-in-progress: false
@@ -310,20 +302,10 @@ jobs:
NEEDS_PUBLISH_IOS_OUTPUTS_ARTIFACT_VERSION: ${{ needs.publish_ios.outputs.ARTIFACT_VERSION }}
- name: Add release notes
if: ${{ needs.versioning.outputs.DRY_RUN == 'false' }}
run: |
gh release view "$RELEASE_TAG" --json body --jq .body > release-body.md
if grep -qF "$HEADING" release-body.md; then
echo "Section already present, nothing to add"
exit 0
fi
printf '%s\n' "$NOTES" >> release-body.md
gh release edit "$RELEASE_TAG" --notes-file release-body.md
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
RELEASE_TAG: ${{ github.event.release.tag_name }}
HEADING: "## Embedded packages"
NOTES: |
uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
with:
append_body: true
body: |
## Embedded packages
+12 -35
View File
@@ -7,13 +7,9 @@ on:
env:
VERSION: ${{ github.event.release.tag_name }}
permissions: {}
jobs:
build_element_call:
permissions:
contents: read
uses: $/.github/workflows/build-element-call.yaml
uses: ./.github/workflows/build-element-call.yaml
with:
package: full
vite_app_version: ${{ github.event.release.tag_name }} # Using ${{ env.VERSION }} here doesn't work
@@ -46,10 +42,11 @@ jobs:
- name: Create Checksum
run: find ${FILENAME_PREFIX} -type f -print0 | sort -z | xargs -0 sha256sum | tee ${FILENAME_PREFIX}.sha256
- name: Upload
run: gh release upload "$VERSION" "${FILENAME_PREFIX}.tar.gz" "${FILENAME_PREFIX}.sha256" --clobber
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
with:
files: |
${{ env.FILENAME_PREFIX }}.tar.gz
${{ env.FILENAME_PREFIX }}.sha256
publish_docker:
needs: build_element_call
@@ -59,10 +56,8 @@ jobs:
contents: write
packages: write
id-token: write
uses: $/.github/workflows/build-and-publish-docker.yaml
secrets:
TS_OAUTH_CLIENT_ID: ${{ secrets.TS_OAUTH_CLIENT_ID }}
TS_AUDIENCE: ${{ secrets.TS_AUDIENCE }}
uses: ./.github/workflows/build-and-publish-docker.yaml
secrets: inherit
with:
artifact_run_id: ${{ github.event.workflow_run.id || github.run_id }}
docker_tags: |
@@ -74,30 +69,12 @@ jobs:
needs: publish_docker
name: Add docker release note
runs-on: ubuntu-24.04
# Shared with publish-component.yaml and publish-embedded-packages.yaml, which append
# to the same release. GitHub lets only one job wait per group, so if all three arrive at once the
# waiting one is cancelled: re-run it. To mitigate this, the append exits early when its
# heading already exists.
concurrency:
group: release-notes-${{ github.event.release.tag_name || github.run_id }}
cancel-in-progress: false
permissions:
contents: write # to update release notes
steps:
- name: Add release note
run: |
gh release view "$VERSION" --json body --jq .body > release-body.md
if grep -qF "$HEADING" release-body.md; then
echo "Section already present, nothing to add"
exit 0
fi
printf '\n%s\n' "$NOTES" >> release-body.md
gh release edit "$VERSION" --notes-file release-body.md
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
HEADING: "## Docker full package"
NOTES: |
uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
with:
append_body: true
body: |
## Docker full package
Element Call is available as a Docker image from the [GitHub Container Registry](https://github.com/element-hq/element-call/pkgs/container/element-call).
+3 -13
View File
@@ -22,16 +22,10 @@ on:
secrets:
CODECOV_TOKEN:
required: false
# Each job asks for what it needs
permissions: {}
jobs:
vitest:
name: Run unit tests
runs-on: ubuntu-24.04
permissions:
contents: read
steps:
- name: Checkout code
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
@@ -42,7 +36,7 @@ jobs:
- name: Enable Corepack
run: corepack enable
- name: pnpm cache
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
cache: "pnpm"
node-version-file: ".node-version"
@@ -81,8 +75,6 @@ jobs:
if: ${{ !inputs.disable_e2e_tests }}
timeout-minutes: 60
runs-on: ubuntu-24.04
permissions:
contents: read
# We manually shard the tests across runners. Playwright's own shards cut
# the list of tests into equal counts in file order, which would leave the
# widget suite, the slowest tests by far, together at the end.
@@ -108,7 +100,7 @@ jobs:
persist-credentials: false
- name: Enable Corepack
run: corepack enable
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
cache: "pnpm"
node-version-file: ".node-version"
@@ -159,8 +151,6 @@ jobs:
needs: playwright
if: ${{ always() && !inputs.disable_e2e_tests }}
runs-on: ubuntu-24.04
permissions:
contents: read
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
with:
@@ -169,7 +159,7 @@ jobs:
persist-credentials: false
- name: Enable Corepack
run: corepack enable
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
cache: "pnpm"
node-version-file: ".node-version"
+1 -1
View File
@@ -20,7 +20,7 @@ jobs:
- name: Enable Corepack
run: corepack enable
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
cache: "pnpm"
node-version-file: ".node-version"
+1 -1
View File
@@ -20,4 +20,4 @@ jobs:
persist-credentials: false
- name: Run zizmor 🌈
uses: zizmorcore/zizmor-action@1b4550e929643b8b26a62303c6bd64814271a4f1 # v0.9.2
uses: zizmorcore/zizmor-action@192e21d79ab29983730a13d1382995c2307fbcaa # v0.5.7
-1
View File
@@ -2,7 +2,6 @@ node_modules
.DS_Store
.env
dist
/dist-widget-rtc-sdk-example
dist-ssr
*.local
*.bkp
+2 -4
View File
@@ -43,10 +43,8 @@ Git-ignored. One kebab-case subfolder per task, matching the branch topic:
promoted into the PR body or a doc before the task ends.
- Never write scratch files to the repo root. Stray `load_test_summary.md` and
`config.json_` files are what this folder prevents.
- Start `pr-body.md` from `.github/PULL_REQUEST_TEMPLATE/maintainer.md` when
working for a maintainer, otherwise from `.github/PULL_REQUEST_TEMPLATE.md`.
In the maintainer template, Plan is the human-edited prompt (`NN-prompt.md`);
`plan.md` is the implementation plan and goes under Content.
- Start `pr-body.md` from `.github/PULL_REQUEST_TEMPLATE.md` and fill every
section.
## Gates
-5
View File
@@ -46,11 +46,6 @@ The issue is where we resolve all of that **before** anyone writes code.
5. **Open a PR.** Link to the issue in your PR description and satisfy the checklist
in the PR template.
Maintainers use the simpler
[maintainer template](.github/PULL_REQUEST_TEMPLATE/maintainer.md) instead:
`gh pr create --template maintainer.md`, or add `&template=maintainer.md` to the
compare URL.
## Code Quality
Element Call moves fast and the codebase must stay clean and maintainable.
+4 -11
View File
@@ -245,15 +245,12 @@ the build (`allowBuilds` in its `pnpm-workspace.yaml`).
##### Use
1. Provide the externals yourself: `react`, `react-dom`,
1. Provide the externals yourself: `react`, `react-dom`, `matrix-js-sdk`,
`@vector-im/compound-web`, `@vector-im/compound-design-tokens`, and
Compound's stylesheet. The component bundles its own `matrix-js-sdk`; the
host's client and room can be on any version that has what the `client`
and `room` props pick from them, which the host's type check enforces.
Compound's stylesheet.
2. Import `@element-hq/element-call-component/style.css`.
3. Await `initializeElementCall(config)` once before rendering.
4. Render the component with `client`, `room` (from that client) and an
`intent`; optionally
4. Render the component with `client`, `roomId` and an `intent`; optionally
pass `config`, `hostBridge`, `language` and `theme` (both can change
mid-call). Control it through the `ref` handle (`join`, `hangUp`,
`setDeviceMute`).
@@ -278,11 +275,7 @@ API is in `component/index.tsx`, `component/api.ts` and `component/host.ts`.
##### Develop
- `pnpm build:component` builds the library into `component/dist`. It ends
with `scripts/check-component-bundle.mjs`, which fails the build on what a
host must not be handed: an asset inlined as a data URL, a file referenced
by an absolute path, the standalone app's client store worker, or a module
over its size budget.
- `pnpm build:component` builds the library into `component/dist`.
- `pnpm dev:component` serves a test host on `https://localhost:3001`: two
calls side by side in resizable boxes, with host messages logged at the
bottom. It uses the development backend, `public/config.json` if present,
-87
View File
@@ -1,87 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { afterEach, beforeEach, expect, test, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import { type MatrixClient, type Room } from "matrix-js-sdk";
import { mockEmitter, mockMatrixRoom } from "../src/utils/test";
import { ElementCall } from "./index";
// The call itself is out of scope: what matters is what it is handed
const callView = vi.hoisted(() => vi.fn());
vi.mock("../src/room/CallView", () => ({
CallView: (props: object): string => {
callView(props);
return "call";
},
}));
// Media devices need a browser jsdom does not have
vi.mock("../src/state/AppViewModel", () => ({
AppViewModel: class {
public mediaDevices = {};
public backgroundEffects = {};
},
}));
const roomId = "!room:example.org";
let room: Room;
beforeEach(() => {
// What the call's backend takes from the room
room = mockMatrixRoom({
roomId,
getMembersWithMembership: vi.fn(),
getLiveTimeline: vi.fn(),
getVersion: vi.fn(),
hasMembershipState: vi.fn(),
_unstable_getStickyEvents: vi.fn(),
getMxcAvatarUrl: vi.fn(),
getJoinRule: vi.fn(),
});
});
afterEach(() => {
callView.mockClear();
});
test("calls in the room, leaving the session to the call", async () => {
render(<ElementCall client={mockClient()} room={room} />);
await screen.findByText("call");
const props = callView.mock.lastCall?.[0];
expect(props).toMatchObject({ backend: { roomId } });
expect(props).not.toHaveProperty("rtcSession");
});
// No `matrixRTC`: the host's session manager is not ours to use
function mockClient(): MatrixClient {
return {
...mockEmitter(),
// What the call view's client is made from
baseUrl: "https://matrix.example.org",
getUserId: () => "@alice:example.org",
getDeviceId: () => "DEVICE",
getAccessToken: () => "token",
getSyncState: () => null,
getUser: () => null,
getCrypto: () => undefined,
sendEvent: vi.fn(),
sendStateEvent: vi.fn(),
_unstable_sendStickyEvent: vi.fn(),
_unstable_sendStickyDelayedEvent: vi.fn(),
cancelPendingEvent: vi.fn(),
encryptAndSendToDevice: vi.fn(),
redactEvent: vi.fn(),
decryptEventIfNeeded: vi.fn(),
setDisplayName: vi.fn(),
setAvatarUrl: vi.fn(),
uploadContent: vi.fn(),
doesServerSupportUnstableFeature: vi.fn(),
} as unknown as MatrixClient;
}
+4 -36
View File
@@ -25,12 +25,10 @@ Please see LICENSE in the repository root for full details.
*/
import type { Ref } from "react";
import type { Room } from "matrix-js-sdk";
import type { MatrixClient } from "matrix-js-sdk";
import type { UrlProperties } from "../src/UrlParams";
import type { ElementCallHandle, ElementCallHostBridge } from "./host";
import type { HostClientPart } from "./componentLocalJsClient";
import type { SuppliedClient } from "../src/ClientContext";
import {
BackgroundStyle,
configurationForIntent,
@@ -71,44 +69,14 @@ export {
export type ElementCallConfiguration = Partial<UrlConfiguration> &
Partial<Pick<UrlProperties, "background">>;
/**
* Everything Element Call reads of the host's room. Listed here rather than
* taken from the call's backend, whose types a host cannot resolve.
*
* STOP GAP until the host passes an interface of our own instead of its `Room`.
*/
type HostRoomPart = Pick<
Room,
| "roomId"
| "on"
| "off"
| "getMembersWithMembership"
| "getLiveTimeline"
| "getVersion"
| "hasMembershipState"
| "_unstable_getStickyEvents"
| "name"
| "getMxcAvatarUrl"
| "getJoinRule"
| "relations"
>;
export interface ElementCallProps {
/**
* The client to place the call with. Element Call does not authenticate
* anyone or manage a session of its own; this one is the host's.
*
* Typed with the host's own js-sdk, as only what Element Call calls on it: by
* the call's backend, and by the rest of the call through its context. A
* js-sdk too old for Element Call fails to type-check rather than failing
* once a call is shown.
*/
client: HostClientPart & SuppliedClient;
/**
* The room to call in, from the host's client. Typed like `client`: only what
* Element Call reads of it.
*/
room: HostRoomPart;
client: MatrixClient;
/** The room to call in. The host's client must already know about it. */
roomId: string;
/**
* What the user asked for — whether they started the call or joined one that
* was already running, and whether it is a call in a group or a DM. Element
-148
View File
@@ -1,148 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { afterEach, expect, test, vi } from "vitest";
import {
ClientEvent,
ConnectionError,
EventType,
type MatrixClient,
SyncState,
} from "matrix-js-sdk";
import { createComponentLocalJsClient } from "./componentLocalJsClient";
afterEach(() => {
vi.unstubAllGlobals();
});
test("reads the host's live state from the host's client", () => {
const host = mockHost();
const client = createComponentLocalJsClient(host);
const listener = (): void => {};
expect(client.getSyncState()).toBe(SyncState.Syncing);
client.on(ClientEvent.Sync, listener);
client.off(ClientEvent.Sync, listener);
client.getUser("@bob:example.org");
client.getCrypto();
expect(host.getSyncState).toHaveBeenCalledOnce();
expect(host.on).toHaveBeenCalledWith(ClientEvent.Sync, listener);
expect(host.off).toHaveBeenCalledWith(ClientEvent.Sync, listener);
expect(host.getUser).toHaveBeenCalledWith("@bob:example.org");
expect(host.getCrypto).toHaveBeenCalledOnce();
});
test("sends the RTC session's encrypted events with the host's crypto", async () => {
const host = mockHost();
const client = createComponentLocalJsClient(host);
await client._unstable_sendStickyEvent(
"!room:example.org",
1000,
null,
EventType.RTCMembership,
{ slot_id: "m.call#ROOM", msc4354_sticky_key: "key" },
);
await client.encryptAndSendToDevice("m.room.encrypted", [], {});
expect(host._unstable_sendStickyEvent).toHaveBeenCalledOnce();
expect(host.encryptAndSendToDevice).toHaveBeenCalledOnce();
});
test.each([
"sendEvent",
"redactEvent",
"decryptEventIfNeeded",
"_unstable_sendStickyEvent",
"_unstable_sendStickyDelayedEvent",
"encryptAndSendToDevice",
"sendStateEvent",
"setDisplayName",
"setAvatarUrl",
"uploadContent",
"doesServerSupportUnstableFeature",
] as const)(
"the host's %s fails with errors our js-sdk recognises",
async (method) => {
const host = mockHost();
// A ConnectionError of the host's own js-sdk: not ours, but shaped like it
const hostError = Object.assign(new Error("fetch failed"), {
name: "ConnectionError",
});
vi.mocked(host[method]).mockRejectedValue(hostError);
const client = createComponentLocalJsClient(host);
await expect(
(client[method] as () => Promise<unknown>)(),
).rejects.toBeInstanceOf(ConnectionError);
},
);
test("takes its credentials from the host", () => {
const client = createComponentLocalJsClient(mockHost());
expect(client.getUserId()).toBe("@alice:example.org");
expect(client.getDeviceId()).toBe("DEVICE");
expect(client.getDomain()).toBe("example.org");
expect(client.baseUrl).toBe("https://matrix.example.org");
});
test("makes requests with whichever token the host holds now", async () => {
const fetch = vi.fn(
async () =>
await Promise.resolve(
new Response(JSON.stringify({ access_token: "openid" }), {
headers: { "Content-Type": "application/json" },
}),
),
);
vi.stubGlobal("fetch", fetch);
const host = mockHost();
const client = createComponentLocalJsClient(host);
// As if the host had refreshed its token after we were created
host.token = "refreshed";
await client.getOpenIdToken();
expect(fetch).toHaveBeenCalledOnce();
const [url, init] = fetch.mock.calls[0] as unknown as [URL, RequestInit];
expect(url.toString()).toBe(
"https://matrix.example.org/_matrix/client/v3/user/%40alice%3Aexample.org/openid/request_token",
);
expect(new Headers(init.headers).get("Authorization")).toBe(
"Bearer refreshed",
);
});
function mockHost(): MatrixClient & { token: string } {
const host = {
token: "first",
baseUrl: "https://matrix.example.org",
getUserId: (): string => "@alice:example.org",
getDeviceId: (): string => "DEVICE",
getAccessToken: (): string => host.token,
getSyncState: vi.fn(() => SyncState.Syncing),
on: vi.fn(),
off: vi.fn(),
getUser: vi.fn(() => null),
getCrypto: vi.fn(() => undefined),
sendEvent: vi.fn(),
sendStateEvent: vi.fn(),
_unstable_sendStickyEvent: vi.fn(),
_unstable_sendStickyDelayedEvent: vi.fn(),
encryptAndSendToDevice: vi.fn(),
redactEvent: vi.fn(),
decryptEventIfNeeded: vi.fn(),
setDisplayName: vi.fn(),
setAvatarUrl: vi.fn(),
uploadContent: vi.fn(),
doesServerSupportUnstableFeature: vi.fn(),
};
return host as unknown as MatrixClient & { token: string };
}
-152
View File
@@ -1,152 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { createClient, type MatrixClient } from "matrix-js-sdk";
import type { createCallMatrixBackend } from "../src/CallMatrixBackend";
import { adoptingHostErrors } from "./hostErrors";
/**
* Everything the component calls on the host's client. Part of the public
* `client` prop (see api.ts), so that a host whose js-sdk lacks one of these
* fails to type-check.
*
* STOP GAP until the host passes an interface of our own instead of its
* `MatrixClient`.
*/
export type HostClientPart = Pick<
MatrixClient,
| "baseUrl"
| "getUserId"
| "getDeviceId"
| "getAccessToken"
| "getSyncState"
| "on"
| "off"
| "getUser"
| "getCrypto"
| "sendEvent"
| "redactEvent"
| "decryptEventIfNeeded"
| "_unstable_sendStickyEvent"
| "_unstable_sendStickyDelayedEvent"
| "encryptAndSendToDevice"
| "sendStateEvent"
| "setDisplayName"
| "setAvatarUrl"
| "uploadContent"
| "doesServerSupportUnstableFeature"
>;
/**
* The client for Element Call in Component mode.
* We do get the full host client but we dont want to use it as it
* might use older versions of methods were we expect changes. (f.ex. getLivekitToken)
* We really want the expected implementation to not get runtime errors.
*
* This creates a new client that does use the hosts token and "stable"
* methods but uses the ElementCall Components js-sdk's client impl for anything else.
*/
export function createComponentLocalJsClient(
host: HostClientPart,
): Parameters<typeof createCallMatrixBackend>[0] {
const own = createClient({
baseUrl: host.baseUrl,
userId: host.getUserId() ?? undefined,
deviceId: host.getDeviceId() ?? undefined,
accessToken: host.getAccessToken() ?? undefined,
// The host refreshes its token without telling us, so each request takes
// whichever token the host holds now
fetchFn: async (input, init) => {
const headers = new Headers(init?.headers);
const token = host.getAccessToken();
if (token !== null) headers.set("Authorization", `Bearer ${token}`);
return globalThis.fetch(input, { ...init, headers });
},
});
return {
// Own has no sync loop: `syncApi?.getSyncState() ?? null` is always null
getSyncState: host.getSyncState.bind(host),
// Only the syncing host emits `Sync`, `ToDeviceEvent` and `Decrypted`
on: host.on.bind(host),
// The same emitter as `on`
off: host.off.bind(host),
// `this.store.getUser`: own's store is empty, only the host's sync fills it
getUser: host.getUser.bind(host),
// Own never inits crypto, and a second one on the device would corrupt it
getCrypto: host.getCrypto.bind(host),
// Every one of the host's methods that can fail rejects with our error
// classes, which ours can recognise (see hostErrors.ts)
// Own has no rooms: `encryptEventIfNeeded`'s `if (!room) return` skips E2EE
sendEvent: adoptingHostErrors(host.sendEvent.bind(host)),
// Not encrypted, but the local echo goes to `getRoom()`: only the host's
redactEvent: adoptingHostErrors(host.redactEvent.bind(host)),
// `attemptDecryption` only runs `if (this.getCrypto())`: a no-op on own
decryptEventIfNeeded: adoptingHostErrors(
host.decryptEventIfNeeded.bind(host),
),
// Like `sendEvent`: on own, `if (!room) return` sends it in plaintext
_unstable_sendStickyEvent: adoptingHostErrors(
host._unstable_sendStickyEvent.bind(host),
),
// Like `sendEvent`: delayed, but still `encryptEventIfNeeded(event, room)`
_unstable_sendStickyDelayedEvent: adoptingHostErrors(
host._unstable_sendStickyDelayedEvent.bind(host),
),
// `if (!this.cryptoBackend) throw`: own has no crypto
encryptAndSendToDevice: adoptingHostErrors(
host.encryptAndSendToDevice.bind(host),
),
// Static: own was created with the host's user id
getUserId: own.getUserId.bind(own),
// Static: own was created with the host's device id
getDeviceId: own.getDeviceId.bind(own),
// Static: derived from the user id
getDomain: own.getDomain.bind(own),
// Static: own was created with the host's base URL
baseUrl: own.baseUrl,
// MSC4143 stable or unstable prefix, picked by /versions: ours knows both
getRTCTransports: own.getRTCTransports.bind(own),
// Plain HTTP with the copied credentials, like the other LiveKit auth
getOpenIdToken: own.getOpenIdToken.bind(own),
// MSC4195 stable or `io.element.msc4195` prefix: an older host may lack it
getLivekitToken: own.getLivekitToken.bind(own),
// MSC4195, like `getLivekitToken`: an older host may lack it
delegateDelayedLeave: own.delegateDelayedLeave.bind(own),
// Plain HTTP into own's cache, which `getCachedCapabilities` reads
fetchCapabilities: own.fetchCapabilities.bind(own),
// Has to be the client whose cache `fetchCapabilities` filled
getCachedCapabilities: own.getCachedCapabilities.bind(own),
// Straight to `scheduleDelayedEvent`: no room, no crypto, plain HTTP
_unstable_sendDelayedStateEvent:
own._unstable_sendDelayedStateEvent.bind(own),
// Plain POST `/delayed_events/{id}/cancel`; newer API an old host may lack
_unstable_cancelScheduledDelayedEvent:
own._unstable_cancelScheduledDelayedEvent.bind(own),
// Plain POST by the server's delay id: restarts the host's sticky leave too
_unstable_restartScheduledDelayedEvent:
own._unstable_restartScheduledDelayedEvent.bind(own),
// Plain POST `/delayed_events/{id}/send`; newer API an old host may lack
_unstable_sendScheduledDelayedEvent:
own._unstable_sendScheduledDelayedEvent.bind(own),
// Plain HTTP, either client works; a stable API, so the host's
sendStateEvent: adoptingHostErrors(host.sendStateEvent.bind(host)),
// Updates the `User` in the host's store, which `useProfile` listens to
setDisplayName: adoptingHostErrors(host.setDisplayName.bind(host)),
// Like `setDisplayName`: updates the `User` in the host's store
setAvatarUrl: adoptingHostErrors(host.setAvatarUrl.bind(host)),
// Plain HTTP, either client works; a stable API, so the host's
uploadContent: adoptingHostErrors(host.uploadContent.bind(host)),
// Reads the host's /versions, which it has already fetched
doesServerSupportUnstableFeature: adoptingHostErrors(
host.doesServerSupportUnstableFeature.bind(host),
),
};
}
+2 -4
View File
@@ -99,7 +99,6 @@ const Pane: FC<{
log: (pane: string, message: string) => void;
}> = ({ session, roomId, theme, language, log }): ReactNode => {
const [mounted, setMounted] = useState(true);
const room = session.client.getRoom(roomId);
const bridge = useMemo(
() =>
@@ -160,12 +159,11 @@ const Pane: FC<{
{/* Resizable, because how Element Call copes with the size it is given is
one of the things we cannot find out from the standalone app */}
<div className={styles.paneCall} data-testid="call-container">
{mounted && room === null && <p>This client does not know {roomId}</p>}
{mounted && room !== null && (
{mounted && (
<ElementCall
ref={handle}
client={session.client}
room={room}
roomId={roomId}
hostBridge={bridge}
theme={theme}
language={language}
-158
View File
@@ -1,158 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { expect, test } from "vitest";
import {
ConnectionError,
HTTPError,
MatrixError,
UnsupportedDelayedEventsEndpointError,
UnsupportedStickyEventsEndpointError,
} from "matrix-js-sdk";
import { adoptHostError, adoptingHostErrors } from "./hostErrors";
test("a rate limit from the host is one of ours, retry delay included", () => {
const error = adoptHostError(
new HostMatrixError(
{ errcode: "M_LIMIT_EXCEEDED", error: "Too many requests" },
429,
"https://matrix.example.org/_matrix/client/v3/rooms/x/send",
new Headers({ "Retry-After": "3" }),
),
);
expect(error).toBeInstanceOf(MatrixError);
const matrixError = error as MatrixError;
expect(matrixError.errcode).toBe("M_LIMIT_EXCEEDED");
expect(matrixError.data).toEqual({
errcode: "M_LIMIT_EXCEEDED",
error: "Too many requests",
});
expect(matrixError.httpStatus).toBe(429);
expect(matrixError.url).toBe(
"https://matrix.example.org/_matrix/client/v3/rooms/x/send",
);
expect(matrixError.isRateLimitError()).toBe(true);
expect(matrixError.getRetryAfterMs()).toBe(3000);
});
test("an HTTP error without a Matrix body from the host is one of ours", () => {
const error = adoptHostError(new HostHTTPError("Conflict", 409));
expect(error).toBeInstanceOf(HTTPError);
expect(error).not.toBeInstanceOf(MatrixError);
expect((error as HTTPError).httpStatus).toBe(409);
expect((error as HTTPError).message).toBe("Conflict");
});
test("a connection failure from the host is one of ours", () => {
const error = adoptHostError(new HostConnectionError("fetch failed"));
expect(error).toBeInstanceOf(ConnectionError);
expect((error as ConnectionError).message).toBe("fetch failed");
});
test("missing sticky and delayed event endpoints on the host's server are ours", () => {
const sticky = adoptHostError(
new HostUnsupportedEndpointError(
"UnsupportedStickyEventsEndpointError",
"sendStickyEvent",
),
);
const delayed = adoptHostError(
new HostUnsupportedEndpointError(
"UnsupportedDelayedEventsEndpointError",
"sendDelayedStateEvent",
),
);
expect(sticky).toBeInstanceOf(UnsupportedStickyEventsEndpointError);
expect((sticky as UnsupportedStickyEventsEndpointError).clientEndpoint).toBe(
"sendStickyEvent",
);
expect(delayed).toBeInstanceOf(UnsupportedDelayedEventsEndpointError);
expect(
(delayed as UnsupportedDelayedEventsEndpointError).clientEndpoint,
).toBe("sendDelayedStateEvent");
});
test("keeps where the host's error was thrown", () => {
const original = new HostConnectionError("fetch failed");
expect((adoptHostError(original) as Error).stack).toBe(original.stack);
});
test("leaves our own errors and everything else as they are", () => {
const own = new MatrixError({ errcode: "M_FORBIDDEN" }, 403);
const refusedByWidgetHost = new Error("Action not allowed");
const aborted = new DOMException("Aborted", "AbortError");
expect(adoptHostError(own)).toBe(own);
expect(adoptHostError(refusedByWidgetHost)).toBe(refusedByWidgetHost);
expect(adoptHostError(aborted)).toBe(aborted);
expect(adoptHostError("not an error")).toBe("not an error");
});
test("a wrapped host method rejects with ours and resolves as it did", async () => {
const failing = adoptingHostErrors(async (): Promise<string> =>
Promise.reject(new HostConnectionError("fetch failed")),
);
const succeeding = adoptingHostErrors(
async (a: number, b: number): Promise<number> => Promise.resolve(a + b),
);
await expect(failing()).rejects.toBeInstanceOf(ConnectionError);
await expect(succeeding(1, 2)).resolves.toBe(3);
});
// Lookalikes of the host js-sdk's classes: the same shape, but not ours
class HostHTTPError extends Error {
public constructor(
message: string,
public readonly httpStatus?: number,
public readonly httpHeaders?: Headers,
) {
super(message);
}
public isRateLimitError(): boolean {
return this.httpStatus === 429;
}
}
class HostMatrixError extends HostHTTPError {
public readonly errcode?: string;
public constructor(
public data: { errcode?: string; error?: string },
httpStatus?: number,
public url?: string,
httpHeaders?: Headers,
) {
super(`MatrixError: ${data.error}`, httpStatus, httpHeaders);
this.errcode = data.errcode;
this.name = data.errcode ?? "Unknown error code";
}
}
class HostConnectionError extends Error {
public get name(): string {
return "ConnectionError";
}
}
class HostUnsupportedEndpointError extends Error {
public constructor(
name: string,
public clientEndpoint: string,
) {
super(`Server does not support ${clientEndpoint}`);
this.name = name;
}
}
-92
View File
@@ -1,92 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import {
ConnectionError,
HTTPError,
MatrixError,
UnsupportedDelayedEventsEndpointError,
UnsupportedStickyEventsEndpointError,
} from "matrix-js-sdk";
/**
* Wraps a method of the host's client so that what it rejects with is
* {@link adoptHostError adopted}.
*/
export function adoptingHostErrors<
F extends (...args: never[]) => Promise<unknown>,
>(call: F): F {
const adopting = async (
...args: Parameters<F>
): Promise<Awaited<ReturnType<F>>> => {
try {
return (await call(...args)) as Awaited<ReturnType<F>>;
} catch (e) {
throw adoptHostError(e);
}
};
return adopting as F;
}
/**
* The same error as one of our own js-sdk's classes, where it is one of the
* host's.
*
* The host's client is a different copy of the js-sdk, and ours (the MatrixRTC
* session above all) tells rate limits, network failures and missing endpoints
* apart with `instanceof`, which never matches the host's classes.
*/
export function adoptHostError(error: unknown): unknown {
if (!(error instanceof Error) || isOwn(error)) return error;
const adopted = adopt(error);
if (adopted === undefined) return error;
adopted.stack = error.stack;
return adopted;
}
function isOwn(error: Error): boolean {
return (
error instanceof HTTPError ||
error instanceof ConnectionError ||
error instanceof UnsupportedStickyEventsEndpointError ||
error instanceof UnsupportedDelayedEventsEndpointError
);
}
/** Recognised by shape, since the host's classes cannot be named. */
function adopt(error: Error & Partial<HostErrorFields>): Error | undefined {
switch (error.name) {
case "ConnectionError":
return new ConnectionError(error.message);
case "UnsupportedStickyEventsEndpointError":
return new UnsupportedStickyEventsEndpointError(
error.message,
error.clientEndpoint as UnsupportedStickyEventsEndpointError["clientEndpoint"],
{ cause: error.cause },
);
case "UnsupportedDelayedEventsEndpointError":
return new UnsupportedDelayedEventsEndpointError(
error.message,
error.clientEndpoint as UnsupportedDelayedEventsEndpointError["clientEndpoint"],
);
}
if (typeof error.isRateLimitError !== "function") return undefined;
if (error.data !== undefined)
return new MatrixError(
error.data,
error.httpStatus,
error.url,
error.event,
error.httpHeaders,
);
return new HTTPError(error.message, error.httpStatus, error.httpHeaders);
}
type HostErrorFields = Pick<
MatrixError,
"data" | "httpStatus" | "httpHeaders" | "url" | "event" | "isRateLimitError"
> & { clientEndpoint: string };
+13 -13
View File
@@ -11,7 +11,7 @@ Please see LICENSE in the repository root for full details.
* Element Call as a React component, for an application that wants to show a
* call inside itself rather than in an iframe.
*
* The host supplies the client and the room to call in; Element Call
* The host supplies the client and says which room to call in; Element Call
* supplies the call. Everything it would otherwise take from the page it is on
* — the URL, the document body, a Matrix session of its own — comes from the
* host instead, or is confined to the container it is mounted in.
@@ -84,9 +84,7 @@ import styles from "./ElementCall.module.css";
import { useComponentHostBridge } from "./host";
import { CallPortalRoot } from "./CallPortalRoot";
import { type ElementCallProps } from "./api";
import { createComponentLocalJsClient } from "./componentLocalJsClient";
import { supportedLanguages, translationsBackend } from "./localization";
import { createCallMatrixBackend } from "../src/CallMatrixBackend";
// The languages Element Call can be shown in
export { supportedLanguages } from "./localization";
@@ -150,7 +148,7 @@ const Decoration: FC<{ children: JSX.Element }> = ({ children }) => {
export const ElementCall: FC<ElementCallProps> = ({
client,
room,
roomId,
intent = UserIntent.JoinExistingCall,
config,
hostBridge: suppliedHostBridge,
@@ -181,7 +179,6 @@ export const ElementCall: FC<ElementCallProps> = ({
// to be stable for as long as its contents are. A host writing `config`
// inline would otherwise tear the call down on every render.
const stableConfig = useStableValue(config);
const { roomId } = room;
const params = useMemo(
(): UrlParams => ({
...componentProperties,
@@ -207,17 +204,23 @@ export const ElementCall: FC<ElementCallProps> = ({
};
}, [controlledAudioDevices, callIntent]);
const backend = useMemo(
() => createCallMatrixBackend(createComponentLocalJsClient(client), room),
const room = client.getRoom(roomId);
const rtcSession = useMemo(
() => (room === null ? null : client.matrixRTC.getRoomSession(room)),
[client, room],
);
if (rtcSession === null)
logger.error(
`Element Call was asked to call in ${roomId}, which its host's client does not know about`,
);
// Everything the call needs is in hand once these exist, and the first
// render with them is where the call itself appears: the moment the host
// is told that Element Call has loaded, as the widget tells its client once
// its own initialisation is over. Once per mount, however often the pieces
// are later swapped out.
const ready = container !== null && vm !== null;
const ready = container !== null && rtcSession !== null && vm !== null;
const announcedLoaded = useRef(false);
useEffect(() => {
if (!ready || announcedLoaded.current) return;
@@ -247,17 +250,14 @@ export const ElementCall: FC<ElementCallProps> = ({
>
<Decoration>
<TooltipProvider>
{/* The host's own client: what reads it through
the context (avatars, the encryption system,
rageshakes, the disconnected banner) uses only its
stable methods. */}
<ClientProvider client={client}>
<MediaDevicesContext value={vm.mediaDevices}>
<BackgroundEffectsProvider
effects={vm.backgroundEffects}
>
<CallView
backend={backend}
client={client}
rtcSession={rtcSession}
isPasswordlessUser={false}
confineToRoom={params.confineToRoom}
preload={params.preload}
+1
View File
@@ -42,6 +42,7 @@
"peerDependencies": {
"@vector-im/compound-design-tokens": "^11.0.0",
"@vector-im/compound-web": "^10.3.1",
"matrix-js-sdk": "*",
"react": "^19",
"react-dom": "^19"
}
+13
View File
@@ -0,0 +1,13 @@
{
"default_server_config": {
"m.homeserver": {
"base_url": "https://call-unstable.ems.host",
"server_name": "call-unstable.ems.host"
}
},
"ssla": "https://static.element.io/legal/element-software-and-services-license-agreement-uk-1.pdf",
"matrix_rtc_session": {
"membership_event_expiry_ms": 180000000,
"network_error_retry_ms": 100
}
}
+2 -2
View File
@@ -63,7 +63,7 @@ services:
- ecbackend
livekit:
image: livekit/livekit-server:v1.13.11
image: livekit/livekit-server:v1.13.4
pull_policy: always
hostname: livekit-sfu
command: --dev --config /etc/livekit.yaml
@@ -86,7 +86,7 @@ services:
- ecbackend
livekit-1:
image: livekit/livekit-server:v1.13.11
image: livekit/livekit-server:v1.13.4
pull_policy: always
hostname: livekit-sfu-1
command: --dev --config /etc/livekit.yaml
+2 -2
View File
@@ -19,10 +19,10 @@ services:
- ./backend/playwright_homeserver-othersite.yaml:/data/cfg/homeserver.yaml:Z
element-web:
# Pin to a SHA so that upstream cannot break our tests. Renovate handles regular updates.
image: ghcr.io/element-hq/element-web:develop@sha256:58b673f867f78fe83c08f2b688b254e34625ebfcebdc5eff84bfdf407445e88e
image: ghcr.io/element-hq/element-web:develop@sha256:b355371adc13161afc7e3c436b533f99e26bd6482e9b53e9572501821f8ddb21
element-web-1:
# Pin to a SHA so that upstream cannot break our tests. Renovate handles regular updates.
image: ghcr.io/element-hq/element-web:develop@sha256:58b673f867f78fe83c08f2b688b254e34625ebfcebdc5eff84bfdf407445e88e
image: ghcr.io/element-hq/element-web:develop@sha256:b355371adc13161afc7e3c436b533f99e26bd6482e9b53e9572501821f8ddb21
volumes:
# The other site opens the embedded package under test in place of the
# copy its image bundles (the first site opens the dev server's app.
+12 -39
View File
@@ -4,17 +4,12 @@
- Call logic lives in `src/state/`. A component that derives call state is
misplaced logic.
- New state is a `create<Thing>$(scope, …)` factory returning an interface of
named behaviors plus callbacks — `createCallViewModel$`,
`createCallNotificationLifecycle$`, the SDK's `createLocalMembership$`. Prefer
it to a class for anything new, including something that owns a resource.
- Inside the factory, mutable state is a local `BehaviorSubject` exposed through
`scope.behavior(…)`, a resource is released in `scope.onEnd`, and the returned
object comes before the helpers it calls, which are `function` declarations
beneath it.
- Older resource owners are classes taking the scope in their constructor —
`MediaDevices`, `MuteStates`, `TileStore`, `Publisher`, `Connection`. Convert
one only when that is the task, never in passing.
- Composing behaviors: a factory taking `(scope, ...deps$)`, returning named
behaviors plus callbacks. Copy `src/state/LayoutSwitchViewModel.ts`. Prefer this
for anything new.
- Owning a resource: a class taking the scope in its constructor — `MediaDevices`,
`MuteStates`, `TileStore`, `Publisher`, `Connection`. Both styles are current;
don't convert one to the other in passing.
- A factory's required parameters are what the thing is made of: no sensible
default. Several of them go in a props interface, so each can carry a doc
comment. Its trailing `options` bag is how the host wants it to behave: every
@@ -78,27 +73,6 @@ and widget behaviour.
`AudioOutput`. Intent presets set it on non-desktop; standalone leaves it off.
- URL params are a published contract: change one, update `docs/url_params.md`.
## Element Call on the SDK
`sdk/` is `@element-hq/matrixrtc-sdk`; its design is
[`sdk/SdkArchitecture.md`](../../sdk/SdkArchitecture.md). Read it before touching
`sdk/`.
- MatrixRTC and media logic lives in `sdk/`; UI, configuration, settings and host
concerns stay in `src/`. The dependency points Element Call → SDK, never back:
`element-call/sdk-import-boundary` rejects `src/`, React, i18n or Compound
under `sdk/`.
- The SDK assumes no host — no widget, URL params or config file. It is designed for any
matrix rtc application/type. What only makes sense for a call stays in `CallViewModel`;
the SDK doc lists it under [Call-specific things kept out of the client](../../sdk/SdkArchitecture.md#call-specific-things-kept-out-of-the-client).
- Element Call imports the SDK from `@element-hq/matrixrtc-sdk` only — never a
path into `sdk/src/`, never a copy of what the SDK already does. Missing
something? Extend the SDK's API.
- Every `api.ts` is a contract: `sdk/src/api.ts`, `sdk/src/media-api.ts`, the
internal `sdk/src/media-backend/api.ts` and `component/api.ts`. A PR that
changes one lists the change in its body.
- SDK and Element Call changes go in separate commits.
## Build targets
Code that builds in only one is a bug.
@@ -108,13 +82,12 @@ Code that builds in only one is a bug.
- `build:sdk` — `@element-hq/matrixrtc-sdk`, sources in `sdk/`, entry `sdk/index.ts`.
Packaged exactly like the component (own pnpm project, run pnpm from the repo
root, types from `sdk/tsconfig.build.json`, externals checked by
`pnpm lint:externals`). Minified by default (`build:sdk:production`),
unminified with `build:sdk:development`; source maps in both.
- `build:widget-rtc-sdk` — a single bundle for widget pages that wraps the
`sdk/` package and the widget API, nothing of `src/`; entry
`widget-rtc-sdk/main.ts`. CI builds it as the `widget-rtc-sdk` package
(`build:widget-rtc-sdk:production` / `:development`) and deploys it as the
`pr<N>-widget-rtc-sdk` Netlify preview.
`pnpm lint:externals`). Interface only so far; the design is `sdk-plan.md`.
- `build:sdk-target-based-on-call-view-model` — the SDK demo that predates the
package, one bundle of the `CallViewModel`; entry
`sdk-target-based-on-call-view-model/main.ts`. CI's `sdk` package
(`build:sdk:production` / `build:sdk:development`, the Netlify `-sdk` preview)
is still this bundle, not `build:sdk`.
- `build:component` — `@element-hq/element-call-component`, sources in `component/`
(its own pnpm project; run pnpm from the repo root). Host API is in the README;
`pnpm lint:externals` rejects an import of a `react` / `react-dom` /
-12
View File
@@ -21,18 +21,6 @@ rejected and why — never add one silently. Extend or parameterise before forki
and extract shared logic into a hook both callers use before copying it; if you
copy, the PR says so.
The same holds for tools and patterns: solve a problem the way the codebase
already solves it. A new library or pattern is a decision the PR body names, not a
side effect.
## Pick the primitive the job needs
- Call state lives in a view model; `useState` holds only what the view alone
cares about — an open menu, a hover.
- A prop by default. Context is for what a whole mounted instance shares — the
host bridge, the root element, URL params — not for skipping a level of props.
- A `Behavior` for anything with a current value, a plain observable for events.
## Ordering
- **Newspaper order.** Headline first, detail down. A file opens with what it
-1
View File
@@ -60,5 +60,4 @@ pnpm backend # Synapse + LiveKit, required for e2e
pnpm test:playwright # or :open
pnpm dev:component # component harness, port 3001
pnpm dev:sdk # SDK harness, port 3002
pnpm dev:widget-rtc-sdk # widget RTC SDK example widget, port 3003
```
+1 -2
View File
@@ -14,8 +14,7 @@ export default {
"vite-embedded.config.ts",
"vite-sdk.config.ts",
"vite-sdk-dev.config.ts",
"vite-widget-rtc-sdk.config.ts",
"vite-widget-rtc-sdk-dev.config.ts",
"vite-sdk-target-based-on-call-view-model.config.ts",
"vite-component.config.ts",
"vite-component-dev.config.ts",
],
+2
View File
@@ -118,6 +118,8 @@
"livekit_connection_error": "Failed to connect to Livekit server",
"livekit_connection_error_description": "An error occurred while connecting to the Livekit server (<1>Reason:</1> <2>{{ reason }}</2>).",
"matrix_rtc_transport_missing": "The server is not configured to work with {{brand}} and no other call participant provides a usable transport. Please contact your server admin (Domain: {{domain}}, Error Code: {{ errorCode }}).",
"membership_manager": "Membership Manager Error",
"membership_manager_description": "The Membership Manager had to shut down. This is caused by many consecutive failed network requests.",
"no_matrix_2_authorization_service": "The authorization service for your media server (SFU) is out of date.",
"open_elsewhere": "Opened in another tab",
"open_elsewhere_description": "{{brand}} has been opened in another tab. If that doesn't sound right, try reloading the page.",
+12 -15
View File
@@ -8,7 +8,6 @@
"dev:embedded": "vite --config vite-embedded.config.js",
"dev:component": "vite --config vite-component-dev.config.ts",
"dev:sdk": "vite --config vite-sdk-dev.config.ts",
"dev:widget-rtc-sdk": "vite --config vite-widget-rtc-sdk-dev.config.ts",
"build": "pnpm build:full",
"build:full": "node --max-old-space-size=16384 node_modules/vite/bin/vite.js build",
"build:full:production": "pnpm build:full",
@@ -19,17 +18,14 @@
"build:sdk": "pnpm build:sdk:js && pnpm build:sdk:types",
"build:sdk:js": "pnpm build:full --config vite-sdk.config.js",
"build:sdk:types": "tsc -p sdk/tsconfig.build.json",
"build:sdk:production": "pnpm build:sdk",
"build:sdk:development": "pnpm build:sdk:js --mode development && pnpm build:sdk:types",
"build:widget-rtc-sdk": "pnpm build:full --config vite-widget-rtc-sdk.config.js",
"build:widget-rtc-sdk:production": "pnpm build:widget-rtc-sdk",
"build:widget-rtc-sdk:development": "pnpm build:widget-rtc-sdk --mode development",
"build:component": "pnpm build:component:js && pnpm build:component:check && pnpm build:component:types",
"build:sdk-target-based-on-call-view-model": "pnpm build:full --config vite-sdk-target-based-on-call-view-model.config.js",
"build:sdk:production": "pnpm build:sdk-target-based-on-call-view-model",
"build:sdk:development": "pnpm build:sdk-target-based-on-call-view-model --mode development",
"build:component": "pnpm build:component:js && pnpm build:component:types",
"build:component:js": "pnpm build:full --config vite-component.config.js",
"build:component:check": "node scripts/check-component-bundle.mjs",
"build:component:types": "tsc -p component/tsconfig.build.json",
"build:component:production": "pnpm build:component",
"build:component:development": "pnpm build:component:js --mode development && pnpm build:component:check && pnpm build:component:types",
"build:component:development": "pnpm build:component:js --mode development && pnpm build:component:types",
"serve": "vite preview",
"format": "oxfmt",
"format:check": "oxfmt --check; rc=$?; [[ $rc -ne 0 ]] && printf '\\033[46;30m INFO \\033[0m To fix, run: pnpm format\\n' >&2; exit $rc",
@@ -55,20 +51,20 @@
"build-storybook": "storybook build"
},
"devDependencies": {
"@codecov/vite-plugin": "^2.0.0",
"@codecov/vite-plugin": "^1.3.0",
"@fontsource/inconsolata": "^5.1.0",
"@fontsource/inter": "^5.1.0",
"@formatjs/intl-durationformat": "^0.13.0",
"@formatjs/intl-durationformat": "^0.10.0",
"@formatjs/intl-segmenter": "^11.7.3",
"@livekit/components-core": "^0.12.0",
"@livekit/track-processors": "^0.8.0",
"@livekit/track-processors": "^0.7.1",
"@mediapipe/tasks-vision": "^0.10.18",
"@playwright/test": "^1.60.0",
"@radix-ui/react-dialog": "^1.0.4",
"@radix-ui/react-slider": "^1.1.2",
"@radix-ui/react-visually-hidden": "^1.0.3",
"@react-spring/web": "^10.0.0",
"@rolldown/plugin-babel": "^0.3.0",
"@rolldown/plugin-babel": "^0.2.3",
"@sentry/react": "^8.0.0",
"@sentry/vite-plugin": "^3.0.0",
"@storybook/addon-docs": "^10.3.6",
@@ -83,6 +79,7 @@
"@types/jsdom": "^21.1.7",
"@types/lodash-es": "^4.17.12",
"@types/node": "^24.0.0",
"@types/pako": "^2.0.3",
"@types/qrcode": "^1.5.5",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
@@ -94,7 +91,7 @@
"@vitejs/plugin-react": "^6.0.2",
"@vitest/browser-playwright": "^4.1.5",
"@vitest/coverage-v8": "^4.0.18",
"@vitest/ui": "4.1.12",
"@vitest/ui": "4.1.11",
"babel-plugin-react-compiler": "^1.0.0",
"classnames": "^2.3.1",
"copy-to-clipboard": "^3.3.3",
@@ -117,7 +114,7 @@
"oxfmt": "^0.79.0",
"oxlint": "^1.70.0",
"oxlint-tsgolint": "^0.25.0",
"pako": "^3.0.3",
"pako": "^2.0.4",
"postcss": "^8.4.41",
"postcss-preset-env": "^10.0.0",
"postcss-selector-parser": "^7.1.1",
+1 -34
View File
@@ -13,7 +13,6 @@ import { fileURLToPath } from "node:url";
import { COMPONENT_HARNESS_URL } from "./playwright/component/harness.ts";
import { SDK_HARNESS_URL } from "./playwright/sdk/harness.ts";
import { WIDGET_RTC_SDK_URL } from "./playwright/widget/test-helpers.ts";
const baseURL = process.env.USE_DOCKER
? "http://localhost:8080"
@@ -83,11 +82,6 @@ export default defineConfig({
name: "build-embedded",
testMatch: "**/widget/embedded/build.setup.ts",
},
{
// Builds the widget RTC SDK's example widget for its preview server
name: "build-widget-rtc-sdk",
testMatch: "**/widget/widget-rtc-sdk.setup.ts",
},
{
name: "chromium",
testIgnore: ["**/mobile/**", "**/widget/**"],
@@ -99,21 +93,12 @@ export default defineConfig({
name: "widget",
dependencies: ["build-embedded"],
testMatch: "**/widget/**/*.@(spec|test).ts",
testIgnore: "**/widget/widget-rtc-sdk.spec.ts",
use: desktopChrome,
},
{
// The widget RTC SDK's example widget in Element Web. CI does not run
// this project; see widget-rtc-sdk/README.md for running it by hand.
name: "widget-rtc-sdk",
dependencies: ["build-widget-rtc-sdk"],
testMatch: "**/widget/widget-rtc-sdk.spec.ts",
use: desktopChrome,
},
{
name: "firefox",
dependencies: ["build-embedded"],
testIgnore: ["**/mobile/**", "**/widget/widget-rtc-sdk.spec.ts"],
testIgnore: "**/mobile/**",
use: {
...devices["Desktop Firefox"],
ignoreHTTPSErrors: true,
@@ -198,23 +183,5 @@ export default defineConfig({
timeout: 500,
},
},
{
// The widget RTC SDK's example widget, which Element Web opens as a
// widget. Bundled rather than from the dev server: Firefox now and then
// stalls on the dev server's hundreds of module requests. Servers start
// before any project, so the build-widget-rtc-sdk project fills the
// directory later and only the projects that open the widget wait for
// it. Until then there is no page, hence the port rather than the url.
command:
"mkdir -p dist-widget-rtc-sdk-example && " +
"pnpm exec vite preview --config vite-widget-rtc-sdk-dev.config.ts",
port: Number(new URL(WIDGET_RTC_SDK_URL).port),
reuseExistingServer: !process.env.CI,
ignoreHTTPSErrors: true,
gracefulShutdown: {
signal: "SIGTERM",
timeout: 500,
},
},
],
});
+3 -5
View File
@@ -32,11 +32,9 @@ export interface MyFixtures {
export const widgetTest = test.extend<MyFixtures>({
// allow per-test override: `widgetTest.use({ callType: "dm" })`
callType: ["room", { option: true }],
asWidget: async ({ browser, callType }, pUse, testInfo) => {
// Tests in parallel workers can reach this in the same millisecond.
const uniqueSuffix = `${Date.now()}_${testInfo.parallelIndex}`;
const brooksDisplayName = `brooks_${uniqueSuffix}`;
const whistlerDisplayName = `whistler_${uniqueSuffix}`;
asWidget: async ({ browser, callType }, pUse) => {
const brooksDisplayName = `brooks_${Date.now()}`;
const whistlerDisplayName = `whistler_${Date.now()}`;
// Register users
const {
+62 -16
View File
@@ -58,20 +58,20 @@ const cases: {
guestFlows: ["cs-api"],
},
{
// Publishers keep the legacy participant identity that clients predating
// MSC4195 expect, which only the JWT service assigns.
// The client-server API is preferred wherever a transport names a url.
// Clients since 0.28.1 match such a publisher by either identity.
hostShape: "url+legacy",
guestShape: "url+legacy",
hostFlows: ["service-legacy"],
guestFlows: ["service-legacy"],
hostFlows: ["cs-api"],
guestFlows: ["cs-api"],
},
{
// The MatrixRTC mode has no bearing on the choice.
hostShape: "url+legacy",
guestShape: "url+legacy",
mode: "2_0",
hostFlows: ["service-legacy"],
guestFlows: ["service-legacy"],
hostFlows: ["cs-api"],
guestFlows: ["cs-api"],
},
{
hostShape: "url",
@@ -80,10 +80,12 @@ const cases: {
guestFlows: ["service-legacy", "cs-api"],
},
{
// Both reach the SFU through the client-server API, under one identity
// each, so one connection serves the own and the other's transport.
hostShape: "url",
guestShape: "url+legacy",
hostFlows: ["cs-api", "service-default"],
guestFlows: ["service-legacy", "cs-api"],
hostFlows: ["cs-api"],
guestFlows: ["cs-api"],
},
];
@@ -160,6 +162,50 @@ test("Publisher shows an error when the homeserver lacks MSC4195", async ({
).toBeVisible();
});
test("Falls back to the JWT service for a url+legacy transport when the homeserver lacks MSC4195", async ({
browser,
page,
browserName,
}) => {
skipOnFirefox(browserName);
// The host starts the call; its C-S requests fail.
await advertiseTransport(page, shapes["url+legacy"]);
await rejectCsApiTokens(page);
const hostRequests = recordAuthRequests(page);
await page.goto("/");
await SpaHelpers.createCall(page, "Androl", "HelloCall", true);
const inviteLink = await SpaHelpers.getCallInviteLink(page);
// The guest joins, and its C-S requests fail as well.
const guestContext = await browser.newContext({ reducedMotion: "reduce" });
const guestPage = await guestContext.newPage();
await advertiseTransport(guestPage, shapes["url+legacy"]);
await rejectCsApiTokens(guestPage);
const guestRequests = recordAuthRequests(guestPage);
await SpaHelpers.joinCallFromInviteLink(guestPage, inviteLink, "Pevara");
// The call connects all the same.
await SpaHelpers.expectVideoTilesCount(page, 2);
await SpaHelpers.expectVideoTilesCount(guestPage, 2);
for (const requests of [hostRequests, guestRequests]) {
// Each published through the JWT service, under the legacy identity, and
// subscribes to the other over that same connection.
expect(flowsOf(requests)).toEqual(
new Set<Flow>(["cs-api", "service-legacy"]),
);
for (const request of requests) {
if (request.flow === "cs-api") {
expect(request.status).toBe(404);
} else {
expect(request.status).toBe(200);
expect(request.identity).toMatch(legacyIdentity);
}
}
}
});
test("Group call with all possible transport shapes at once", async ({
browser,
page,
@@ -193,13 +239,12 @@ test("Group call with all possible transport shapes at once", async ({
});
/**
* Delegation follows the flow that authenticated the publisher: the homeserver
* for a `url`-only transport, the JWT service wherever there is one.
* Delegation follows the flow that authenticated the publisher.
*/
const delegationCases: { shape: Shape; via: Delegation["via"] }[] = [
{ shape: "url", via: "homeserver" },
{ shape: "legacy", via: "service" },
{ shape: "url+legacy", via: "service" },
{ shape: "url+legacy", via: "homeserver" },
];
for (const { shape, via } of delegationCases) {
@@ -228,10 +273,9 @@ for (const { shape, via } of delegationCases) {
await SpaHelpers.expectVideoTilesCount(page, 2);
await SpaHelpers.expectVideoTilesCount(guestPage, 2);
// The guest handed its delayed leave over, after probing for delegation
// support with bodiless requests, which count as supported unless they
// 404. The homeserver is always probed; the JWT service only when there
// is one.
// The guest handed its delayed leave over. A JWT service is first probed
// for delegation support with a bodiless request, which counts as
// supported unless it 404s. A homeserver that issued the token is not.
await expect
.poll(() => delegations.at(-1))
.toEqual({
@@ -241,7 +285,9 @@ for (const { shape, via } of delegationCases) {
...(via === "homeserver" && { sfuUrl }),
});
const probes = delegations.slice(0, -1);
expect(probes.some((probe) => probe.via === via)).toBe(true);
expect(probes.map((probe) => probe.via)).toEqual(
via === "service" ? ["service"] : [],
);
for (const probe of probes) {
expect(probe.status).toBeGreaterThanOrEqual(400);
expect(probe.status).not.toBe(404);
+2 -7
View File
@@ -5,10 +5,9 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { expect, test as setup } from "@playwright/test";
import { test as setup } from "@playwright/test";
import { execFileSync } from "node:child_process";
import { mkdirSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { mkdirSync } from "node:fs";
const EMBEDDED_DIST = "embedded/web/dist";
@@ -18,8 +17,4 @@ setup("build the embedded package", () => {
execFileSync("pnpm", ["build:embedded", "--outDir", EMBEDDED_DIST], {
stdio: "inherit",
});
// The host does the crypto, and nothing runs the standalone client
expect(readdirSync(join(EMBEDDED_DIST, "assets"))).not.toContainEqual(
expect.stringMatching(/rust-crypto|matrix_sdk_crypto|IndexedDBWorker/),
);
});
+2 -11
View File
@@ -22,12 +22,6 @@ const PASSWORD = "foobarbaz1!";
export const HOST1 = "https://app.m.localhost/#/welcome";
export const HOST2 = "https://app.othersite.m.localhost/#/welcome";
/**
* Where the widget RTC SDK's example widget is served (`pnpm dev:widget-rtc-sdk`):
* `widget-rtc-sdk/index.html`, running the bundle from source.
*/
export const WIDGET_RTC_SDK_URL = "https://localhost:3003";
export type RtcMode = "compat" | "2_0";
export class TestHelpers {
@@ -212,11 +206,8 @@ export class TestHelpers {
await expect(dialog).toBeHidden({ timeout: 5000 });
}
// The same element shows the next toast a moment after the click, so
// reading it straight away acts on the dismissed one a second time.
// Counted rather than read, as the last toast leaves no title behind.
await expect(toastTitle.filter({ hasText: title })).toHaveCount(0, {
timeout: 5000,
});
// reading it straight away acts on the dismissed one a second time
await expect(toastTitle).not.toHaveText(title, { timeout: 5000 });
} else {
// Unknown toast. We don't want to act on unknown toasts
break;
-20
View File
@@ -1,20 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { test as setup } from "@playwright/test";
import { execFileSync } from "node:child_process";
// Into the directory the widget RTC SDK's preview server already serves (see
// playwright.config.ts)
setup("build the widget RTC SDK example", () => {
setup.setTimeout(10 * 60 * 1000);
execFileSync(
"pnpm",
["exec", "vite", "build", "--config", "vite-widget-rtc-sdk-dev.config.ts"],
{ stdio: "inherit" },
);
});
-129
View File
@@ -1,129 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { expect, type FrameLocator, type Page } from "@playwright/test";
import { widgetTest } from "../fixtures/widget-user.ts";
import { WIDGET_RTC_SDK_URL } from "./test-helpers.ts";
/**
* The widget RTC SDK's example widget, `widget-rtc-sdk/index.html`, added to a
* room as a custom widget and opened in two Element Webs: the bundle's whole
* public API, from the widget API to the data channel.
*/
widgetTest.describe.configure({ timeout: 300_000 });
const WIDGET_ID = "widget-rtc-sdk-example";
const WIDGET_NAME = "Widget RTC SDK";
/** Accepts the prompts Element Web shows before it runs a widget, and finds it. */
async function openWidget(page: Page): Promise<FrameLocator> {
// Only for a widget someone else added
const loadPrompt = page.getByRole("button", { name: "Continue" });
const capabilitiesPrompt = page.getByRole("button", { name: "Approve" });
await expect(loadPrompt.or(capabilitiesPrompt)).toBeVisible({
timeout: 30_000,
});
if (await loadPrompt.isVisible()) await loadPrompt.click();
await capabilitiesPrompt.click({ timeout: 30_000 });
// The SDK authenticates with the media transport by an OpenID token, and
// asks for more than one, so the answer has to be remembered
const openIdPrompt = page.getByRole("dialog", {
name: "Allow this widget to verify your identity",
});
await openIdPrompt.getByText("Remember this").click({ timeout: 30_000 });
await openIdPrompt.getByRole("button", { name: "Continue" }).click();
return page.frameLocator(`iframe[title="${WIDGET_NAME}"]`);
}
widgetTest(
"data sent from one widget arrives in the other",
async ({ asWidget }) => {
const { brooks, whistler } = asWidget;
// Brooks adds the example widget to the room and pins it to the top, so
// that both Element Webs open it without anyone looking for it
await brooks.clientHandle.evaluate(
async (client, { widgetId, name, url }) => {
const roomId = client
.getRooms()
.find((room) => room.name === "Welcome Room")!.roomId;
await client.sendStateEvent(
roomId,
// @ts-expect-error not in the js-sdk's state event map
"im.vector.modular.widgets",
{
id: widgetId,
type: "m.custom",
name,
url,
data: {},
creatorUserId: client.getUserId(),
},
widgetId,
);
await client.sendStateEvent(
roomId,
// @ts-expect-error not in the js-sdk's state event map
"io.element.widgets.layout",
{
widgets: {
[widgetId]: {
container: "top",
index: 0,
width: 100,
height: 50,
},
},
},
"",
);
},
{
widgetId: WIDGET_ID,
name: WIDGET_NAME,
// Element Web fills the $ variables in and adds widgetId and parentUrl
url:
`${WIDGET_RTC_SDK_URL}/?widgetId=$matrix_widget_id&roomId=$matrix_room_id` +
"&userId=$matrix_user_id&deviceId=$org.matrix.msc3819.matrix_device_id" +
"&baseUrl=$org.matrix.msc4039.matrix_base_url",
},
);
const brooksWidget = await openWidget(brooks.page);
const whistlerWidget = await openWidget(whistler.page);
// The example joins on load; each sees the other as a member
for (const [widget, other] of [
[brooksWidget, whistler],
[whistlerWidget, brooks],
] as const) {
await expect(widget.locator("#connect_status")).toHaveText("Connected", {
timeout: 60_000,
});
await expect(widget.locator("#members")).toContainText(other.mxId, {
timeout: 60_000,
});
}
// Data is not queued: the receiver drops what arrives before it has matched
// the sender on the media transport, which the example does not show. So
// send until it arrives.
await expect(async () => {
await brooksWidget.getByRole("button", { name: "Send Text" }).click();
await expect(whistlerWidget.locator("#data")).toContainText(
"Hello, world!",
{ timeout: 2_000 },
);
}).toPass({ timeout: 60_000 });
// Our own data is not echoed back
await expect(brooksWidget.locator("#data")).not.toContainText(
"Hello, world!",
);
},
);
+2300 -1961
View File
File diff suppressed because it is too large Load Diff
+14 -10
View File
@@ -30,14 +30,22 @@ overrides:
"minimatch": "^11.0.0"
# Security fix: https://github.com/element-hq/element-call/security/dependabot/109
"glob": "^10.5.0"
# Security fix: https://github.com/advisories/GHSA-6pq8-jhm2-2vcw
"qs": ">=6.16.1"
# Security fix: https://github.com/advisories/GHSA-2883-xcg3-v3hh
"js-yaml": "^4.3.2"
# Security fixes:
# - https://github.com/element-hq/element-call/security/dependabot/110
# - https://github.com/element-hq/element-call/security/dependabot/122
# - https://github.com/element-hq/element-call/security/dependabot/179
"qs": "^6.15.2"
# Security fixes:
# - https://github.com/element-hq/element-call/security/dependabot/106
# - https://github.com/element-hq/element-call/security/dependabot/203
"js-yaml": "^4.2.0"
# Storybook declares support for 0.27.0 only but empirically works fine with 0.28.0.
"esbuild": "^0.28.0"
# Security fix: https://github.com/advisories/GHSA-w293-vg96-wgc3
"undici": "^6.29.1"
# Security fixes:
# - https://github.com/nodejs/undici/releases/tag/v6.24.0
# - https://github.com/element-hq/element-call/security/dependabot/201
# - https://github.com/element-hq/element-call/security/dependabot/199
"undici": "^6.27.0"
# Security fix: https://github.com/advisories/GHSA-rf6f-7fwh-wjgh
"flatted": "^3.4.2"
# Security fix: https://github.com/element-hq/element-call/security/dependabot/184
@@ -55,7 +63,3 @@ overrides:
# - https://github.com/advisories/GHSA-mrv2-3pqr-j5jr
# - https://github.com/advisories/GHSA-c6gr-qvv4-5v3f
"dompurify": "^3.4.17"
# Security fix: https://github.com/advisories/GHSA-73wf-gq98-2v4g
"browserslist": ">=4.28.7"
# Security fix: https://github.com/advisories/GHSA-7w5x-hrqm-74c2
"smol-toml": ">=1.9.0"
-117
View File
@@ -1,117 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
/**
* Checks the component build's output for what a host must not be handed.
*
* A library build inlines every asset it meets as a data URL unless the import
* says otherwise, and does so silently: one import without `no-inline` and the
* module grows by the asset, encoded a third larger, that every host then
* downloads and parses before the first call. MediaPipe's runtime alone is
* 11 MB. A reference to a file by an absolute path is just as silent and
* breaks at runtime instead, since a host serves the module from wherever it
* likes. And the standalone app's client store worker, which carries a copy of
* the Matrix SDK and its crypto, has no business in a package whose host
* supplies the client: the bundler emits it on loading its import, used or
* not (see src/utils/initClient.ts). This fails the build on each of those.
*/
import { existsSync } from "node:fs";
import { readdir, readFile, stat } from "node:fs/promises";
import { basename, join } from "node:path";
const dist = "component/dist";
/** The client store worker, whose chunk is named after this file. */
const workerSource = "src/IndexedDBWorker.ts";
/** The longest data URL a chunk may carry: enough for an icon, not a sound. */
const inlineLimit = 16 * 1024;
/**
* The module itself, in bytes. Well above where it sits with its assets as
* files, so that only an asset finding its way back in trips it.
*/
const moduleBudget = 4 * 1024 * 1024;
const problems = [];
// A rename would otherwise turn the worker check off without a word.
if (!existsSync(workerSource))
problems.push(
`${workerSource} is gone, so the check for the client store worker ` +
`cannot recognise its chunk. Point \`workerSource\` in ` +
`scripts/check-component-bundle.mjs at the worker's new name.`,
);
const workerName = basename(workerSource, ".ts");
for (const name of await assets())
if (name.includes(workerName))
problems.push(
`${dist}/assets/${name}: the standalone app's client store worker is ` +
`in the package. Something the component reaches imports the worker; ` +
`keep it on the standalone app's side (see src/utils/initClient.ts ` +
`and the \`loadClient\` prop of ClientProvider).`,
);
for (const file of await modules()) {
const code = await readFile(file, "utf8");
// Up to the closing quote rather than the end of the base64 alphabet, since
// SVGs are inlined URL-encoded rather than as base64.
for (const [, , type, payload] of code.matchAll(
/(["'`])data:([a-z0-9/.+-]*)(?:;base64)?,(.*?)\1/g,
))
if (payload.length > inlineLimit)
problems.push(
`${file}: a ${type} asset of ${Math.round(payload.length / 1024)} kB ` +
`is inlined as a data URL. Import it with \`?url&no-inline\` so ` +
`that it is emitted as a file.`,
);
for (const [reference] of code.matchAll(/["'`]\/assets\/[^"'`]+["'`]/g))
problems.push(
`${file}: ${reference} is an absolute path, which only resolves ` +
`against an origin that serves the package at its root. The build ` +
`is meant to render relative references; check \`base\` in ` +
`vite-component.config.ts.`,
);
}
const moduleSize = (await stat(join(dist, "element-call.js"))).size;
if (moduleSize > moduleBudget)
problems.push(
`${dist}/element-call.js is ${(moduleSize / 1024 / 1024).toFixed(1)} MB, ` +
`over its ${moduleBudget / 1024 / 1024} MB budget. Something large ` +
`has been bundled into the module that a host would rather fetch when ` +
`it is needed.`,
);
if (problems.length > 0) {
console.error(`The component build is not fit to publish:\n`);
for (const problem of problems) console.error(` ${problem}\n`);
process.exit(1);
}
/** The files under `assets/`, none if the build emitted no such directory. */
async function assets() {
try {
return await readdir(join(dist, "assets"));
} catch (e) {
if (e.code === "ENOENT") return [];
throw e;
}
}
/**
* The modules a host bundles: the entry points and their chunks, at the top of
* the package. What sits under `assets/` is fetched as it is, by URL.
*/
async function modules() {
const names = await readdir(dist);
return names.filter((name) => name.endsWith(".js")).map((n) => join(dist, n));
}
+6 -6
View File
@@ -9,11 +9,11 @@ Please see LICENSE in the repository root for full details.
* Checks that the library builds leave the packages a host must supply to the
* host.
*
* A host application already has React and Compound (and, for the SDK build,
* the Matrix SDK), and a second copy of any of them is worse than dead weight:
* React would hold two sets of hooks, and a second Compound would style the
* tooltips it floats into the host's body with class names the host's
* stylesheet does not know. So each library build lists them
* A host application already has React, the Matrix SDK and Compound,
* and a second copy of any of them is worse than dead weight: React would hold
* two sets of hooks, the Matrix client would run two sync loops, and a second
* Compound would style the tooltips it floats into the host's body with class
* names the host's stylesheet does not know. So each library build lists them
* as external — but that list has to name every subpath, since the bundler
* silently ignores the pattern and callback forms of the option, and an import
* it does not cover is bundled with no warning at all. That is the failure
@@ -47,10 +47,10 @@ const TARGETS = [
// `sdk` too: the build resolves `@element-hq/matrixrtc-sdk` to its source
sources: ["src", "component", "sdk"],
excluded: ["component/dev", "sdk/dev"],
// Not the Matrix SDK: the component bundles its own (see the build config)
mustBeExternal: [
"react",
"react-dom",
"matrix-js-sdk",
"@vector-im/compound-web",
"@vector-im/compound-design-tokens",
],
@@ -0,0 +1,68 @@
# SDK mode (LEGACY)
> Superseded by the `sdk/` package (`@element-hq/matrixrtc-sdk`) and its harness in
> `sdk/dev`; see `sdk/SdkArchitecture.md`. This bundle is in production use, so it
> keeps building as a thin layer over that package until its consumers have moved
> to the package directly. It will then be removed. Its members are the package's
> `RTCMember`s now, in place of its own wrapper around the raw membership.
EC can be build in sdk mode. This will result in a compiled js file that can be imported in very simple webapps.
It allows to use matrixRTC in combination with livekit without relying on element call.
This is done by instantiating the call view model and exposing some useful behaviors (observables) and methods.
This folder contains an example index.html file that showcases the sdk in use (hosted on localhost:8123 with a webserver allowing cors (for example `npx serve -l 81234 --cors`)) as a godot engine HTML export template.
## Getting started
To get started run
```
pnpm install
pnpm build:sdk-target-based-on-call-view-model
```
in the repository root. (`pnpm build:sdk` builds the `sdk/` package instead.)
CI's `sdk` package (`build:sdk:production`, `build:sdk:development`, the
`build-output-sdk` artifact and the `pr<N>-sdk` Netlify preview) is still this
bundle, not the `sdk/` package, until its consumers have moved over.
It will create `dist` containing the compiled js file, `matrixrtc-sdk.js`.
This file needs to be hosted. Locally (via `npx serve -l 81234 --cors`) or on a remote server.
Now you just need to add the widget to element web via:
```
/addwidget http://localhost:3000?widgetId=$matrix_widget_id&userId=$matrix_user_id&deviceId=$org.matrix.msc3819.matrix_device_id&baseUrl=$org.matrix.msc4039.matrix_base_url&roomId=$matrix_room_id
```
## Widgets
The sdk mode is particularly interesting to be used in widgets. In widgets you do not need to pay attention to matrix login/cs api ...
To create a widget see the example `index.html` file in this folder. And add it to EW via:
`/addwidget <widgetUrl>` (see **url parameters** for more details on `<widgetUrl>`)
### url parameters
The url parameters are needed to pass initial data to the widget. They will automatically be used
by the matrixRTCSdk to start the postmessage widget api (communication between the client (e.g. Element Web) and the widget)
```
widgetId = $matrix_widget_id
userId = $matrix_user_id
deviceId = $org.matrix.msc3819.matrix_device_id
baseUrl = $org.matrix.msc4039.matrix_base_url
```
`parentUrl = // will be inserted automatically`
Full template use as `<widgetUrl>`:
```
http://localhost:3000?widgetId=$matrix_widget_id&userId=$matrix_user_id&deviceId=$org.matrix.msc3819.matrix_device_id&baseUrl=$org.matrix.msc4039.matrix_base_url&roomId=$matrix_room_id
```
the `$` prefixed variables will be replaced by EW on widget instantiation. (e.g. `$matrix_user_id` -> `@user:example.com` (url encoding will also be applied automatically by EW) -> `%40user%3Aexample.com`)
@@ -1,13 +1,11 @@
<!doctype html>
<html>
<head>
<title>Widget RTC SDK example</title>
<title>MatrixRTC Widget</title>
<meta charset="utf-8" />
<script type="module">
// The bundle a pull request's CI deploys: replace 1234 with the PR number.
// For a local build use the url `dist/` is served from, for example
// "http://localhost:8123/widget-rtc-sdk.js".
import { createMatrixRTCSdk } from "https://pr1234-widget-rtc-sdk--element-call.netlify.app/widget-rtc-sdk.js";
// TODO use the url where the matrixrtc-sdk.js file from dist is hosted
import { createMatrixRTCSdk } from "http://localhost:8123/matrixrtc-sdk.js";
try {
window.matrixRTCSdk = await createMatrixRTCSdk(
@@ -28,7 +26,7 @@
sdk.data$.subscribe((data) => {
const child = document.createElement("p");
child.textContent = JSON.stringify(data);
child.innerHTML = JSON.stringify(data);
div.appendChild(child);
});
@@ -42,7 +40,7 @@
for (const m of members) {
console.info("member", m);
const child = document.createElement("p");
child.textContent = m;
child.innerHTML = m;
div.appendChild(child);
}
});
+193
View File
@@ -0,0 +1,193 @@
/*
Copyright 2025-2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
/**
* LEGACY, in production use
*
* The entrypoint of `pnpm build:sdk-target-based-on-call-view-model`, a
* bundle for widgets that exposes `createMatrixRTCSdk`: join a slot and
* exchange realtime data, with the `@element-hq/matrixrtc-sdk` package and
* Element Call's call view model doing the work underneath. New consumers use
* the package directly; this bundle goes away once the existing ones have.
*/
import { logger as rootLogger } from "matrix-js-sdk/lib/logger";
import { EMPTY, filter, map, type Observable, of, switchMap, take } from "rxjs";
import {
type Behavior,
createRTCSlot,
E2eeType,
type LocalRTCMember,
ObservableScope,
type RemoteRTCMember,
type RTCParticipation,
} from "@element-hq/matrixrtc-sdk";
import {
callViewModelOptionsFromParams,
type CallViewModel,
createCallViewModel$,
initialPublishRequests,
} from "../src/state/CallViewModel/CallViewModel";
import {
captureSettings,
rtcParticipationOptions,
rtcSlotOptions,
} from "../src/room/InCallView";
import { createWidgetHostBridge } from "../src/HostBridge";
import { MediaDevices } from "../src/state/MediaDevices";
import { MuteStates } from "../src/state/MuteStates";
import { getUrlParams } from "../src/UrlParams";
import { observeElementSize$ } from "../src/utils/elementSize";
import { initializeWidget } from "../src/widget";
/** The data channel topic this bundle has always used, so that old and new builds talk. */
const TOPIC = "matrixRTC";
export interface MatrixRTCSdk {
/** Joins the slot; `connected$` tracks the progress. A second call does nothing. */
join: () => void;
leave: () => void;
/** Ends everything. The sdk cannot be restarted; create a new one. */
stop: () => void;
connected$: Behavior<boolean>;
/** Our own member, null until our membership has been seen in the room. */
localMember$: Behavior<LocalRTCMember | null>;
/** The other members of the slot, with the media the participation carries for them. */
remoteMembers$: Behavior<RemoteRTCMember[]>;
/** What other members sent with `sendData`. */
data$: Observable<{ rtcBackendIdentity: string; data: string }>;
/** Sends to every member on our transport. Rejects while not joined. */
sendData: (data: unknown) => Promise<void>;
sendRoomMessage: (message: string) => Promise<void>;
}
export async function createMatrixRTCSdk(
application = "m.call",
id = "",
sticky = false,
): Promise<MatrixRTCSdk> {
const logger = rootLogger.getChild("[MatrixRTCSdk]");
const scope = new ObservableScope();
const widget = initializeWidget(application, true);
if (!widget) throw new Error("No widget: this bundle only runs as a widget");
const client = await widget.client;
const hostBridge = createWidgetHostBridge(widget);
const urlParams = getUrlParams();
const { roomId, controlledAudioDevices, callIntent } = urlParams;
const room = roomId === null ? null : client.getRoom(roomId);
if (room === null) throw new Error("No room: the url needs a joined roomId");
const mediaDevices = new MediaDevices(scope, {
controlledAudioDevices,
callIntent,
});
const muteStates = new MuteStates(
scope,
mediaDevices,
{ audioEnabled: false, videoEnabled: false },
hostBridge,
);
const encryptionSystem = { kind: E2eeType.PER_PARTICIPANT } as const;
const capture = captureSettings();
const slot = createRTCSlot(scope, client, room, {
...rtcSlotOptions(encryptionSystem),
application,
id,
});
let vm: CallViewModel | undefined;
const failed =
(what: string) =>
(e: unknown): void =>
logger.error(what, e);
const over = <T>(
pick: (participation: RTCParticipation) => Observable<T>,
fallback: T,
): Behavior<T> =>
scope.behavior(
slot.participation$.pipe(
switchMap((p) => (p === null ? of(fallback) : pick(p))),
),
);
return {
join: (): void => {
if (slot.participation$.value !== null) return;
if (sticky)
widget.api
.setAlwaysOnScreen(true)
.catch(failed("Failed to make the widget sticky"));
const participation = slot.join({
...rtcParticipationOptions(urlParams),
publish: initialPublishRequests(muteStates, mediaDevices, capture),
});
vm = createCallViewModel$(
scope,
{
rtcParticipation: participation,
matrixRoom: room,
mediaDevices,
muteStates,
encryptionSystem,
// The bundle owns its page, so the body is the space it has
viewSize$: scope.behavior(observeElementSize$(document.body)),
handsRaisedSubject$: of({}),
reactionsSubject$: of({}),
},
{
...callViewModelOptionsFromParams(urlParams),
capture,
hostBridge,
},
);
// Once the hang-up has gone through, unstick and ask the host to close us
vm.leave$
.pipe(
switchMap(() =>
participation.state$.pipe(
filter((state) => state.kind === "left"),
take(1),
),
),
scope.bind(),
)
.subscribe(() => {
hostBridge
.setAlwaysOnScreen(false)
.catch(failed("Failed to unstick the widget"))
.then(() => hostBridge.close?.())
.catch(failed("Failed to ask the host to close"));
});
},
leave: (): void => vm?.leave(),
stop: (): void => scope.end(),
connected$: over(
(p) => p.state$.pipe(map((state) => state.kind === "connected")),
false,
),
localMember$: over((p) => p.localMember$, null),
remoteMembers$: over((p) => p.remoteMembers$, []),
// Attested members only: the SDK has matched the sender
data$: slot.participation$.pipe(
switchMap((p) => p?.data$ ?? EMPTY),
filter(({ topic }) => topic === TOPIC),
map(({ member, text }) => ({
rtcBackendIdentity: member.rtcBackendIdentity,
data: text,
})),
),
sendData: async (data): Promise<void> => {
const participation = slot.participation$.value;
if (participation === null) throw new Error("Not joined");
await participation.sendData(TOPIC, JSON.stringify(data));
},
sendRoomMessage: async (message): Promise<void> => {
await client.sendTextMessage(room.roomId, message);
},
};
}
+8 -9
View File
@@ -5,7 +5,8 @@ it joins a MatrixRTC slot in a Matrix room, writes and watches the memberships,
connects to the media transport (LiveKit today), publishes the local media and
exposes every member and their tracks as observables. It has no UI. Element
Call's own `CallViewModel` is one consumer of it; any host can build a different
view on top. The design is in [`SdkArchitecture.md`](./SdkArchitecture.md).
view on top. The design is in [`SdkArchitecture.md`](./SdkArchitecture.md), what
moved out of Element Call's `src/` in [`SdkMigration.md`](./SdkMigration.md).
**Status:** first implementation. `createRTCSlot` and `slot.join()` join the
session, connect to the transport, publish the local media and expose every
@@ -18,7 +19,6 @@ nothing in Element Call's `src/`.
```ts
import {
createRTCSlot,
createSdkMatrixBackend,
E2eeType,
MatrixRTCMode,
ObservableScope,
@@ -28,15 +28,15 @@ import {
const scope = new ObservableScope();
const slot = createRTCSlot(
scope,
createSdkMatrixBackend(
client, // a matrix-js-sdk MatrixClient, logged in and syncing
room, // the matrix-js-sdk Room, from client.getRoom() once the join has synced
),
{ encryptionSystem: { kind: E2eeType.PER_PARTICIPANT } }, // the room's call, m.call#ROOM
client, // a matrix-js-sdk MatrixClient, logged in and syncing
room, // the matrix-js-sdk Room, from client.getRoom() once the join has synced
{
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
matrixRTCMode: MatrixRTCMode.Compatibility,
},
);
const participation = slot.join({
publish: [{ source: "microphone" }, { source: "camera" }],
matrixRTCMode: MatrixRTCMode.Compatibility,
});
// A <video> for each remote member's camera and an <audio> for its microphone.
@@ -99,7 +99,6 @@ own only so that a host can install it as a git dependency (see
```sh
pnpm dev:sdk # the harness, https://localhost:3002
pnpm build:sdk # dist/matrixrtc-sdk.js and dist/types
pnpm build:sdk:development # the same, unminified
pnpm test:playwright playwright/sdk # needs `pnpm backend`
```
+64 -41
View File
@@ -10,7 +10,8 @@ interface.
Element Call becomes one consumer of it: `CallViewModel` keeps what makes a session
a _call_ (ringing, auto-leave, layout, sounds, reactions, settings, the host
bridge) and takes everything else from the client. The dependency direction is
therefore `Element Call → sdk`, never the reverse.
therefore `Element Call → sdk`, never the reverse. What moved out of Element
Call's `src/` to get there is listed in [`SdkMigration.md`](./SdkMigration.md).
## The architecture
@@ -120,10 +121,10 @@ LiveKit participants.
The session discovers the transport from the homeserver and the backend prepares
it, both before `join()`, so that the membership can name it and the first frames
go out as soon as the state event is sent. Preparing is the backend's own
business: for LiveKit the token exchange for the publisher connection, and the
probe that decides whether the service that issued the token can take over the
delayed leave, which picks the delayed leave timings the join uses. The join
waits for the publisher to hold its token, so that the LiveKit room exists
business: for LiveKit the token exchange for the publisher connection, and
with it whether that service can take over the delayed leave (assumed for a homeserver
probed for a JWT service), which picks the delayed leave timings the join uses. The
join waits for the publisher to hold its token, so that the LiveKit room exists
before a subscriber, who lacks the permission to create it, asks for a token
of its own. The tracks are created once the membership is `joined`, with their
upstream paused until then. A lobby that wants them earlier captures them with
@@ -131,10 +132,7 @@ upstream paused until then. A lobby that wants them earlier captures them with
hands the media to `join()` as `publish`: the tracks are moved, not shared — they
leave the lobby's `tracks$`, their objects are finished, and the backend
publishes the very same device tracks and the processor already running on them,
so nothing is captured or initialised again at the join. Given the media quality
the join is given, it opens the camera at the resolution the backend captures
at, so that a join through a lobby publishes what a join without one does. The
upstream flows
so nothing is captured or initialised again at the join. The upstream flows
exactly while the membership is `joined`: a sync outage pauses it, and `leave()`
pauses it for good and sends the leave.
@@ -145,18 +143,18 @@ participation split in
[`client-into-slot-session-split-plan.md`](./client-into-slot-session-split-plan.md);
the sections below still describe `MatrixRTCClient` until that lands.
| Word | Meaning here | Elsewhere |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------- |
| slot | an `RTCSlot`: the namespace in a room that memberships join into, `application` plus `id`. It exists while the room does, with nobody in it too. Holds `members$`, its open or closed `status$`, and `join()` | the js-sdk `MatrixRTCSession` is one per slot; the MSC4143 slot event |
| participation | an `RTCParticipation`: the span between our `join()` of a slot and our `leave()`. Holds the connection and its `state$`, `localMember$`, `remoteMembers$`, the connected transports and the data channel. Made by `slot.join()`, never reused | "session" is not used here, because in the js-sdk it means the slot |
| member | an `RTCMember`: one membership in a slot with what the SDK derives from it, `rtcBackendIdentity`, `userId`, `deviceId`, `memberId`, `matrixEventId$`, `displayName$`, `avatarUrl$`, `transport$` and `applicationData$`. No media. What the slot hands out in `members$` | the js-sdk `CallMembership` behind it, which never leaves the SDK; Element Call's old "matrixLivekitMember" |
| local member, remote member | `LocalRTCMember` and `RemoteRTCMember`: an `RTCMember` plus its `MemberMedia`, which only a participation can carry. The local one's tracks carry the controls. What the participation hands out in `localMember$` and `remoteMembers$` | LiveKit `LocalParticipant` and `RemoteParticipant`, which never leave the SDK |
| media | a `MemberMedia`: what a member sends once it has arrived on its transport, `tracks$`, null while waiting, and `encryptionError$` beside it. The media backend supplies exactly these two fields per member | Element Call's `MediaViewModel` is a view of it |
| track | a `MediaTrack`: one publication of a member, audio or video, with `source`, `kind`, `id` and the behaviors on it. `LocalAudioMediaTrack` and `LocalVideoMediaTrack` add the controls over our own | LiveKit `TrackPublication` and `Track`, which never leave the SDK |
| publish request | a `PublishRequest`: a source, where to capture it from and how to encode it. Given at the join in `publish`, or later to `publish` on the participation | |
| attach, detach | handing a `<video>` or `<audio>` element to a track and taking it back. The SDK owns the stream and the observers on the element | LiveKit `Track.attach` |
| transport | an `RTCTransport`: where media is exchanged, a LiveKit service url today. Carries the raw js-sdk `Transport` from the membership and, in `resolved$`, what the backend fetched to connect to it | MSC4143 "focus" |
| media backend | a `MediaBackend`: what carries the media, behind `sdk/src/media-backend/api.ts`. One per participation, chosen with `backend` in the join options; LiveKit under `sdk/src/media-backend/livekit/` is the one that exists | "SFU", a LiveKit room, a peer connection |
| Word | Meaning here | Elsewhere |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------- |
| slot | an `RTCSlot`: the namespace in a room that memberships join into, `application` plus `id`. It exists while the room does, with nobody in it too. Holds `members$`, its open or closed `status$`, and `join()` | the js-sdk `MatrixRTCSession` is one per slot; the MSC4143 slot event |
| participation | an `RTCParticipation`: the span between our `join()` of a slot and our `leave()`. Holds the connection and its `state$`, `localMember$`, `remoteMembers$`, the connected transports and the data channel. Made by `slot.join()`, never reused | "session" is not used here, because in the js-sdk it means the slot |
| member | an `RTCMember`: one membership in a slot with what the SDK derives from it, `rtcBackendIdentity`, `userId`, `deviceId`, `memberId`, `displayName$`, `avatarUrl$`, `transport$` and `applicationData$`. No media. What the slot hands out in `members$` | the js-sdk `CallMembership` behind it, which never leaves the SDK; Element Call's old "matrixLivekitMember" |
| local member, remote member | `LocalRTCMember` and `RemoteRTCMember`: an `RTCMember` plus its `MemberMedia`, which only a participation can carry. The local one's tracks carry the controls. What the participation hands out in `localMember$` and `remoteMembers$` | LiveKit `LocalParticipant` and `RemoteParticipant`, which never leave the SDK |
| media | a `MemberMedia`: what a member sends once it has arrived on its transport, `tracks$`, null while waiting, and `encryptionError$` beside it. The media backend supplies exactly these two fields per member | Element Call's `MediaViewModel` is a view of it |
| track | a `MediaTrack`: one publication of a member, audio or video, with `source`, `kind`, `id` and the behaviors on it. `LocalAudioMediaTrack` and `LocalVideoMediaTrack` add the controls over our own | LiveKit `TrackPublication` and `Track`, which never leave the SDK |
| publish request | a `PublishRequest`: a source, where to capture it from and how to encode it. Given at the join in `publish`, or later to `publish` on the participation | |
| attach, detach | handing a `<video>` or `<audio>` element to a track and taking it back. The SDK owns the stream and the observers on the element | LiveKit `Track.attach` |
| transport | an `RTCTransport`: where media is exchanged, a LiveKit service url today. Carries the raw js-sdk `Transport` from the membership and, in `resolved$`, what the backend fetched to connect to it | MSC4143 "focus" |
| media backend | a `MediaBackend`: what carries the media, behind `sdk/src/media-backend/api.ts`. One per participation, chosen with `backend` in the join options; LiveKit under `sdk/src/media-backend/livekit/` is the one that exists | "SFU", a LiveKit room, a peer connection |
Names use `RTC` in capitals, as the js-sdk does: `RTCSlot`, `RTCParticipation`,
`RTCMember`, `matrixRTCMode`.
@@ -588,32 +586,56 @@ without one, LiveKit is built from the LiveKit-flavoured client options.
A LiveKit transport comes in three shapes while MSC4195 settles: an SFU `url`,
a JWT service `livekit_service_url`, or both. `media-backend/livekit/auth/`
fronts the two flows and chooses between them per connection, from the shape
and from the role we take on the transport:
fronts the two flows and chooses between them from the shape, preferring the
client-server API wherever the transport names a `url`:
| Transport | Publisher | Subscriber |
| -------------------------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------- |
| `url` only | client-server API `get_token`, no fallback | client-server API `get_token`, no fallback |
| `livekit_service_url` only | JWT service `/sfu/get` (legacy identity) | JWT service `/get_token` (hashed identity) |
| both | JWT service `/sfu/get` (legacy identity) | client-server API, falling back to the JWT service `/get_token` where the homeserver, or a widget host, has no MSC4195 |
| Transport | Publisher | Subscriber |
| -------------------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------ |
| `url` only | client-server API `get_token`, no fallback | client-server API `get_token`, no fallback |
| `livekit_service_url` only | JWT service `/sfu/get` (legacy identity) | JWT service `/get_token` (hashed identity) |
| both | client-server API, else JWT service `/sfu/get` (legacy identity) | client-server API, else JWT service `/get_token` (hashed identity) |
A publisher on a transport with a service URL keeps the legacy
`<user_id>:<device_id>` identity, because clients predating MSC4195 match a
membership against that and nothing else; a subscriber is matched by nobody and
takes the more private hashed identity. A publisher never falls back: a
homeserver that advertises a `url` without implementing MSC4195 is misconfigured
and fails with `NoMatrix2AuthorizationService`, so the admin hears about it.
The MatrixRTC mode plays no part in the choice. The delayed leave is delegated
through the same flow that issued the publisher's token, so that the identity
the service watches for on the SFU is the one we publish under, and the
delegation probe before the join asks only that service.
A member whose transport names both is matched against either identity (since
Element Call 0.28.1), so a publisher may take either flow. On the JWT service
a publisher uses `/sfu/get`, the only endpoint that assigns the legacy
`<user_id>:<device_id>` identity. A subscriber is matched by nobody and takes
the hashed one.
The JWT service stands in only where our homeserver has no MSC4195 endpoints.
A homeserver that has them advertises a `url`, so whether the API is usable is
read off our own transport: `prepareLocalTransport` stores it with the local
transport, and it is the one input, next to a transport's shape, to
`chooseAuthFlow`. Where ours names only a JWT service, transports naming both
go through that service from the start.
A homeserver may advertise a `url` and still lack the endpoints, as may a
widget host. A token request is then answered with a 404, `M_NOT_FOUND` or
`M_UNRECOGNIZED` (`isCsApiUnavailable`) and fails with
`NoMatrix2AuthorizationService`, which the connection reports to the backend
before the error surfaces. Where our transport names a JWT service too, the
backend stores the local transport again with the API ruled out; the failed
connection is stopped with its map and never shows as an error. A transport
with a `url` alone has no fallback and fails the join. The MatrixRTC mode
plays no part in the choice.
A connection is created with its flow and keeps it for life. The delayed leave
is delegated through the publisher connection's flow, the one that issued its
token, so that the service watches for the identity we publish under. A
homeserver that issued the token is assumed to delegate. Only a JWT service is
probed, before the join.
The client-server API needs the name of the homeserver the transport belongs to:
our own homeserver asks that server for the token, over federation where it is
not ours. The backend derives it from the member's user id, and from our own for
the local transport, and keys its connections on the transport plus the server
name where the transport has a `url`. A JWT service is reached directly, so
members of several homeservers advertising the same one share a connection.
the local transport. A JWT service is reached directly, so members of several
homeservers advertising the same one share a connection.
Connections are keyed on the flow and what it authenticates against: the `url`
plus the server name for the client-server API, the service URL for the JWT
service. Transports with the same key would get us the same identity on the
same SFU, so they share a connection. A connection map is built per local
transport, so whether the API is usable is fixed for the life of a map and of
every key in it; ruling the API out replaces the map.
## Media: `tracks$` and `MediaTrack`
@@ -781,6 +803,7 @@ sdk/
src/utils/ mapScoped, network retry, display names, test helpers
dev/ the harness (below)
SdkArchitecture.md this document
SdkMigration.md what moved from Element Call's src/ into the SDK
```
The lint rule `element-call/sdk-import-boundary` keeps it that way: nothing under
+53
View File
@@ -0,0 +1,53 @@
# What moved from `src/` into the SDK
Element Call's `CallViewModel` used to do everything; now it consumes the SDK and
keeps only what makes a session a call. This is the inventory of what moved out
of `src/` on the way, so that a reader of either side knows where to look. It
names source files, so it ages with the code; the shape they make is in
[`SdkArchitecture.md`](./SdkArchitecture.md).
Everything in the table is gone from `src/`. Each module came with its tests;
`sdk/src/utils/test.ts` and `test-fixtures.ts` are the subset of Element Call's
test helpers they need. `Behavior`, `ObservableScope`, the observable operators,
`E2eeType`, `EncryptionSystem` and `MatrixRTCMode` are re-exported from the SDK
by their old `src/` paths, so the rest of Element Call did not have to change.
| Was in `src/` | Is in `sdk/src/` | What changed on the way |
| ----------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `state/Behavior.ts`, `state/ObservableScope.ts`, `utils/observable.ts` | `reactive/` | as is |
| `state/SessionBehaviors.ts` | `matrixrtc/JsRtcSessionBehaviors.ts` | the memberships and key rotation behaviors only |
| `state/CallViewModel/localMember/HomeserverConnected.ts` | `matrixrtc/HomeserverConnected.ts` | the grace period defaults to `defaultSessionTimings` instead of `Config.get()` |
| `state/CallViewModel/localMember/LocalMember.ts` | `matrixrtc/LocalMembership.ts`, `media-backend/livekit/LocalMedia.ts`, `participationState.ts` | split into the Matrix side, the media side and the state machine that combines them |
| `state/CallViewModel/localMember/LocalTransport.ts`, `RtcTransportAutoDiscovery.ts` | `matrixrtc/LocalTransport.ts`, `TransportAutoDiscovery.ts` | the override and the fallback are transports from the options, not a setting and a resolved config |
| `state/CallViewModel/remoteMembers/MatrixLivekitMembers.ts` | `media-backend/livekit/LivekitBackend.ts` (`mediaFor`) | matches participants to members inside the backend; the SDK hands out `RTCMember`s |
| `state/CallViewModel/remoteMembers/MatrixMemberMetadata.ts`, `utils/displayname.ts` | `matrixrtc/MatrixMemberMetadata.ts`, `utils/displayname.ts` | as is |
| `state/CallViewModel/remoteMembers/Connection.ts` | `media-backend/livekit/Connection.ts` | throws `MatrixRTCError`s; `ConnectionState` is a discriminated union; fetches its own token for its role |
| `state/CallViewModel/remoteMembers/ConnectionFactory.ts` | `media-backend/livekit/ConnectionFactory.ts` | `LivekitConnectionFactory` builds the room options from the publish requests and `mediaQuality`, not from settings |
| `state/CallViewModel/remoteMembers/ConnectionManager.ts` | `media-backend/livekit/ConnectionMap.ts` | keyed by `TransportLocator`; the publisher role is the local transport's |
| `state/CallViewModel/localMember/Publisher.ts` | `media-backend/livekit/Publisher.ts` | rewritten on publish requests instead of `MuteStates` |
| `livekit/openIDSFU.ts`, later `livekit/auth/` | `media-backend/livekit/auth/` | the flow is chosen by the transport's shape and our role; the delegated leave timeout is a parameter |
| `livekit/options.ts` | `media-backend/livekit/livekitOptions.ts` | `buildLiveKitOptions(mediaQuality?)` only; the `Config` singleton is gone |
| `e2ee/matrixKeyProvider.ts`, the key provider selection | `media-backend/livekit/MatrixKeyProvider.ts`, `KeyProvider.ts` | as is; selection keyed off `encryptionSystem` |
| `e2ee/e2eeType.ts`, `EncryptionSystem` from `e2ee/sharedKeyManagement.ts` | `encryption.ts` | the React hooks stayed behind |
| `MatrixRTCMode`, the timings and media quality types from `config/ConfigOptions.ts` | `config.ts` | `defaultSessionTimings` and `defaultMediaQuality` replace `DEFAULT_CONFIG` |
| `utils/errors.ts` | `errors.ts` | `MatrixRTCError` with `code` and `category` replaces `ElementCallError`; messages are plain English, the host translates by code |
| `doNetworkOperationWithRetry` from `utils/matrix.ts` | `utils/network.ts` | takes a `shouldRetry` predicate |
| the join in `CallViewModel.ts` (`enterRTCSession`) | `matrixrtc/joinJsSdkSession.ts` | the timings and the delayed leave variant are parameters |
| `livekit/MatrixAudioRenderer.tsx`, the participant reads in `state/media/` | `media-backend/livekit/LivekitMediaTrack.ts`, `LivekitMemberMedia.ts` | the view models get `MediaTrack`s with `attach`; nothing in `src/` imports a LiveKit participant any more |
## What still binds Element Call to LiveKit
Each is a gap in the SDK's API rather than something to rename; the import goes
away when the SDK grows the piece. The names Element Call owes to the outside
stay as they are: the `livekit.livekit_service_url` key in `config.json`, the
persisted setting keys `extended-livekit-logs` and `custom-transport`, the
Posthog fields `callBackend` and `callReconnectingCountLivekit`, the rageshake
field `call_backend`, and the translated error strings.
| Gap | Where it shows |
| ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
| Preview before `join()`: local tracks for the lobby, handed out as `MediaTrack`s | `LobbyView` (`usePreviewTracks`), `VideoPreview` (`LocalVideoTrack`, `facingModeFromLocalTrack`) |
| Device enumeration without LiveKit's helpers | `MediaDevices` (`createMediaDeviceObserver`), `CallView` (`Room.getLocalDevices`) |
| A `logging` option: log level and a sink for the transport's logs | `initializer.tsx`, the `extended-livekit-logs` setting |
| A `capabilities` field: output selection and background processors, asked of the SDK rather than of LiveKit | `CallFooterViewModel` (`supportsAudioOutputSelection`, `supportsBackgroundProcessors`) |
| Element Call's error and analytics types on the SDK's | `PosthogEvents` (`DisconnectReason`), `errors.ts` (`ConnectionError`, `LivekitConnectionError`) |
+2 -3
View File
@@ -16,7 +16,6 @@ import { combineLatest, type Observable, of, switchMap } from "rxjs";
import {
type AudioMediaTrack,
createRTCSlot,
createSdkMatrixBackend,
E2eeType,
type LocalRTCMember,
MatrixRTCMode,
@@ -71,12 +70,12 @@ async function start(
const room = await joinRoom(client, roomIdOrAlias);
const scope = new ObservableScope();
const slot = createRTCSlot(scope, createSdkMatrixBackend(client, room), {
const slot = createRTCSlot(scope, client, room, {
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
matrixRTCMode: MatrixRTCMode.Compatibility,
});
const rtcParticipation = slot.join({
publish: [{ source: "microphone" }, { source: "camera" }],
matrixRTCMode: MatrixRTCMode.Compatibility,
});
rtcParticipation.state$.pipe(scope.bind()).subscribe((state) => {
status.textContent =
+2 -7
View File
@@ -57,11 +57,6 @@ export * from "./src/media-api";
export * from "./src/media-backend/api";
export { trackBySource$, type TrackOfSource } from "./src/utils/tracks";
export { createRTCSlot } from "./src/RTCSlot";
export {
createSdkMatrixBackend,
type SdkMatrixBackend,
withEmitter,
} from "./src/SdkMatrixBackend";
export {
createLivekitBackend,
type LivekitBackendOptions,
@@ -75,6 +70,6 @@ export {
} from "./src/media-backend/livekit/videoProcessor";
// For a developer panel to check a transport before using it
export {
getSFUConfig as authenticateWithTransport,
type GetSFUConfigParams as AuthenticateWithTransportParams,
authenticateWithTransport,
type AuthenticateWithTransportParams,
} from "./src/media-backend/livekit/auth";
+29 -157
View File
@@ -13,7 +13,7 @@ import { type LocalVideoMediaTrack, type VideoProcessor } from "./media-api";
describe("createLocalMedia", () => {
it("opens the microphone and the camera in one request", async () => {
const getUserMedia = fakeGetUserMedia();
const media = createLocalMedia({ getUserMedia });
const media = createLocalMedia(getUserMedia);
const tracks = await media.capture([
{ source: "microphone", deviceId: "mic" },
@@ -35,34 +35,9 @@ describe("createLocalMedia", () => {
]);
});
it("opens a camera asked for without a resolution at the one a backend captures at", async () => {
const getUserMedia = fakeGetUserMedia();
const media = createLocalMedia({ getUserMedia });
await media.capture([{ source: "camera" }]);
expect(getUserMedia).toHaveBeenCalledExactlyOnceWith({
video: { width: 1280, height: 720, frameRate: 30 },
});
});
it("opens the camera at the resolution of the media quality it is given", async () => {
const getUserMedia = fakeGetUserMedia();
const media = createLocalMedia({
mediaQuality: { video: { max_resolution: 360 } },
getUserMedia,
});
await media.capture([{ source: "camera" }]);
expect(getUserMedia).toHaveBeenCalledExactlyOnceWith({
video: { width: 640, height: 360, frameRate: 20 },
});
});
it("joins an identical capture still in flight rather than opening the devices again", async () => {
const getUserMedia = fakeGetUserMedia();
const media = createLocalMedia({ getUserMedia });
const media = createLocalMedia(getUserMedia);
const requests = [{ source: "camera" as const }];
const [first, second] = await Promise.all([
@@ -77,7 +52,7 @@ describe("createLocalMedia", () => {
it("shows the processor's output, initialised once", async () => {
const processor = fakeProcessor();
const media = createLocalMedia({ getUserMedia: fakeGetUserMedia() });
const media = createLocalMedia(fakeGetUserMedia());
const [camera] = await media.capture([{ source: "camera", processor }]);
const element = document.createElement("video");
@@ -90,7 +65,7 @@ describe("createLocalMedia", () => {
it("hands the tracks over as they are: no second capture, no second init", async () => {
const getUserMedia = fakeGetUserMedia();
const processor = fakeProcessor();
const media = createLocalMedia({ getUserMedia });
const media = createLocalMedia(getUserMedia);
const [microphone, camera] = await media.capture([
{ source: "microphone" },
{ source: "camera", processor },
@@ -101,7 +76,7 @@ describe("createLocalMedia", () => {
expect(taken.get("microphone")?.track).toBe(trackBehind(microphone));
expect(taken.get("camera")).toEqual({
track: trackBehind(camera),
constraints: at720p(),
constraints: {},
muted: false,
processor: { processor, processedTrack: processor.output },
});
@@ -114,7 +89,7 @@ describe("createLocalMedia", () => {
});
it("finishes a handed-over track", async () => {
const media = createLocalMedia({ getUserMedia: fakeGetUserMedia() });
const media = createLocalMedia(fakeGetUserMedia());
const [camera] = await media.capture([{ source: "camera" }]);
const element = document.createElement("video");
camera.attach(element);
@@ -127,7 +102,7 @@ describe("createLocalMedia", () => {
});
it("mutes by disabling the track and hands the mute over", async () => {
const media = createLocalMedia({ getUserMedia: fakeGetUserMedia() });
const media = createLocalMedia(fakeGetUserMedia());
const [microphone] = await media.capture([{ source: "microphone" }]);
await expect(microphone.setEnabled(false)).resolves.toBe(false);
@@ -140,7 +115,7 @@ describe("createLocalMedia", () => {
it("switches the device by opening it anew", async () => {
const getUserMedia = fakeGetUserMedia();
const processor = fakeProcessor();
const media = createLocalMedia({ getUserMedia });
const media = createLocalMedia(getUserMedia);
const [camera] = await media.capture([{ source: "camera", processor }]);
const first = trackBehind(camera);
const element = document.createElement("video");
@@ -149,7 +124,7 @@ describe("createLocalMedia", () => {
await camera.setDevice("other");
expect(getUserMedia).toHaveBeenLastCalledWith({
video: at720p({ deviceId: { exact: "other" } }),
video: { deviceId: { exact: "other" } },
});
expect(first.stop).toHaveBeenCalled();
expect(processor.restart).toHaveBeenCalledOnce();
@@ -157,108 +132,28 @@ describe("createLocalMedia", () => {
expect(restartedOn).not.toBe(first);
expect(input).toBe(vi.mocked(processor.init).mock.calls[0][1]);
expect(tracksOn(element)).toEqual([processor.output]);
expect(media.takeTracks().get("camera")?.constraints).toEqual(
at720p({ deviceId: { exact: "other" } }),
);
expect(media.takeTracks().get("camera")?.constraints).toEqual({
deviceId: { exact: "other" },
});
});
it.each([
{
gone: ["mic"],
audio: { deviceId: { ideal: "mic" } },
video: at720p({ deviceId: { exact: "cam" } }),
},
{
gone: ["cam"],
audio: { deviceId: { exact: "mic" } },
video: at720p({ deviceId: { ideal: "cam" } }),
},
{
gone: ["mic", "cam"],
audio: { deviceId: { ideal: "mic" } },
video: at720p({ deviceId: { ideal: "cam" } }),
},
])(
"lets only a device that is gone off the one asked for: $gone",
async ({ gone, audio, video }) => {
const getUserMedia = without(gone, fakeGetUserMedia());
const media = createLocalMedia({ getUserMedia });
it("opens the browser's choice where the device asked for is gone", async () => {
const getUserMedia = vi.mocked(fakeGetUserMedia());
getUserMedia.mockRejectedValueOnce(overconstrained());
const media = createLocalMedia(getUserMedia);
const tracks = await media.capture([
{ source: "microphone", deviceId: "mic" },
{ source: "camera", deviceId: "cam" },
]);
expect(getUserMedia).toHaveBeenLastCalledWith({ audio, video });
expect(tracks.map((t) => t.source)).toEqual(["microphone", "camera"]);
},
);
it("asks twice for a single device that is gone", async () => {
const getUserMedia = without(["cam"], fakeGetUserMedia());
const media = createLocalMedia({ getUserMedia });
await media.capture([{ source: "camera", deviceId: "cam" }]);
expect(vi.mocked(getUserMedia).mock.calls).toEqual([
[{ video: at720p({ deviceId: { exact: "cam" } }) }],
[{ video: at720p({ deviceId: { ideal: "cam" } }) }],
const tracks = await media.capture([
{ source: "microphone", deviceId: "unplugged" },
{ source: "camera", deviceId: "cam" },
]);
});
it("hands over the device that opened in place of the one that is gone", async () => {
const getUserMedia = without(
["cam"],
fakeGetUserMedia({ deviceId: "built-in" }),
);
const media = createLocalMedia({ getUserMedia });
await media.capture([{ source: "camera", deviceId: "cam" }]);
expect(media.takeTracks().get("camera")?.constraints).toEqual(
at720p({ deviceId: { exact: "built-in" } }),
);
});
it("takes a refusal that is not an Error for a device that is gone", async () => {
const getUserMedia = vi.mocked(fakeGetUserMedia());
getUserMedia.mockRejectedValueOnce({ name: "OverconstrainedError" });
const media = createLocalMedia({ getUserMedia });
await media.capture([{ source: "camera", deviceId: "cam" }]);
expect(getUserMedia).toHaveBeenLastCalledWith({
video: at720p({ deviceId: { ideal: "cam" } }),
});
});
it("does not ask again where the device is there and refused", async () => {
const getUserMedia = vi.mocked(fakeGetUserMedia());
const denied = Object.assign(new Error(), { name: "NotAllowedError" });
getUserMedia.mockRejectedValueOnce(denied);
const media = createLocalMedia({ getUserMedia });
await expect(
media.capture([{ source: "camera", deviceId: "cam" }]),
).rejects.toBe(denied);
expect(getUserMedia).toHaveBeenCalledOnce();
});
it("rejects where no device opens at all", async () => {
const refusal = overconstrained();
const media = createLocalMedia({
getUserMedia: vi.fn().mockRejectedValue(refusal),
});
await expect(
media.capture([{ source: "camera", deviceId: "cam" }]),
).rejects.toBe(refusal);
expect(getUserMedia).toHaveBeenLastCalledWith({ audio: {}, video: {} });
expect(tracks.map((t) => t.source)).toEqual(["microphone", "camera"]);
});
it("keeps the camera it has where another cannot be opened", async () => {
const getUserMedia = vi.mocked(fakeGetUserMedia());
const media = createLocalMedia({ getUserMedia });
const media = createLocalMedia(getUserMedia);
const [camera] = await media.capture([
{ source: "camera", deviceId: "cam" },
]);
@@ -276,7 +171,7 @@ describe("createLocalMedia", () => {
it("lets go of the device it was opened on to face the other way", async () => {
const getUserMedia = fakeGetUserMedia({ facingMode: "user" });
const media = createLocalMedia({ getUserMedia });
const media = createLocalMedia(getUserMedia);
const [camera] = (await media.capture([
{ source: "camera", deviceId: "front" },
])) as [LocalVideoMediaTrack];
@@ -284,13 +179,13 @@ describe("createLocalMedia", () => {
await camera.switchFacingMode();
expect(getUserMedia).toHaveBeenLastCalledWith({
video: at720p({ facingMode: "environment" }),
video: { facingMode: "environment" },
});
});
it("reports the facing mode and switches it", async () => {
const getUserMedia = fakeGetUserMedia({ facingMode: "user" });
const media = createLocalMedia({ getUserMedia });
const media = createLocalMedia(getUserMedia);
const [camera] = (await media.capture([{ source: "camera" }])) as [
LocalVideoMediaTrack,
];
@@ -299,13 +194,13 @@ describe("createLocalMedia", () => {
await camera.switchFacingMode();
expect(getUserMedia).toHaveBeenLastCalledWith({
video: at720p({ facingMode: "environment" }),
video: { facingMode: "environment" },
});
});
// As the built-in camera of a Mac
it("takes a camera that doesn't say which way it faces to face the user", async () => {
const media = createLocalMedia({ getUserMedia: fakeGetUserMedia() });
const media = createLocalMedia(fakeGetUserMedia());
const [camera] = (await media.capture([{ source: "camera" }])) as [
LocalVideoMediaTrack,
];
@@ -313,7 +208,7 @@ describe("createLocalMedia", () => {
});
it("releases one device and stops the rest", async () => {
const media = createLocalMedia({ getUserMedia: fakeGetUserMedia() });
const media = createLocalMedia(fakeGetUserMedia());
const [microphone, camera] = await media.capture([
{ source: "microphone" },
{ source: "camera" },
@@ -330,7 +225,7 @@ describe("createLocalMedia", () => {
});
it("refuses a screen share", async () => {
const media = createLocalMedia({ getUserMedia: fakeGetUserMedia() });
const media = createLocalMedia(fakeGetUserMedia());
await expect(media.capture([{ source: "screenShare" }])).rejects.toThrow(
"screen share",
);
@@ -378,29 +273,6 @@ function fakeGetUserMedia(videoSettings?: MediaTrackSettings): GetUserMedia {
});
}
/** Camera constraints with the resolution a request without one is opened at. */
function at720p(
constraints: MediaTrackConstraints = {},
): MediaTrackConstraints {
return { ...constraints, width: 1280, height: 720, frameRate: 30 };
}
/** A browser these devices are unplugged from: asked for one of them exactly, it refuses. */
function without(gone: string[], getUserMedia: GetUserMedia): GetUserMedia {
return vi.fn(async (constraints: MediaStreamConstraints) => {
for (const wanted of [constraints.audio, constraints.video]) {
const deviceId = typeof wanted === "object" ? wanted.deviceId : undefined;
const exact =
typeof deviceId === "object" && !Array.isArray(deviceId)
? deviceId.exact
: undefined;
if (typeof exact === "string" && gone.includes(exact))
throw overconstrained();
}
return getUserMedia(constraints);
});
}
function overconstrained(): Error {
return Object.assign(new Error("deviceId"), { name: "OverconstrainedError" });
}
+35 -80
View File
@@ -7,11 +7,6 @@ Please see LICENSE in the repository root for full details.
import { BehaviorSubject, type Observable, of } from "rxjs";
import {
cameraCaptureResolution,
type CaptureResolution,
type MediaQuality,
} from "./config";
import { MatrixRTCError } from "./errors";
import {
type HandedOverTrack,
@@ -33,28 +28,15 @@ export type GetUserMedia = (
constraints: MediaStreamConstraints,
) => Promise<MediaStream>;
export interface LocalMediaOptions {
/**
* The media quality the join is given. A camera asked for without a
* resolution is opened at the one this means, as the backend opens it at
* the join; left to the browser it would be published at a lower one.
*/
mediaQuality?: MediaQuality;
/** In place of the browser's, for a test. */
getUserMedia?: GetUserMedia;
}
/**
* Local media on the browser's devices alone, for a lobby ahead of a join:
* no backend is involved, so whichever backend joins can take the tracks
* over. Activity and level are not measured; stats are none.
*/
export function createLocalMedia({
mediaQuality,
getUserMedia = async (constraints) =>
export function createLocalMedia(
getUserMedia: GetUserMedia = async (constraints) =>
navigator.mediaDevices.getUserMedia(constraints),
}: LocalMediaOptions = {}): LocalMedia {
const cameraResolution = cameraCaptureResolution(mediaQuality);
): LocalMedia {
const capturedTracks = new Map<Source, CapturedTrack>();
const requests = new Map<Source, Request>();
const tracks$ = new BehaviorSubject<
@@ -98,10 +80,10 @@ export function createLocalMedia({
}
const { stream, constraints } = await open(getUserMedia, {
microphone: bySource.has("microphone")
? trackConstraints(bySource.get("microphone")!, cameraResolution)
? trackConstraints(bySource.get("microphone")!)
: undefined,
camera: bySource.has("camera")
? trackConstraints(bySource.get("camera")!, cameraResolution)
? trackConstraints(bySource.get("camera")!)
: undefined,
});
const captured: CapturedTrack[] = [];
@@ -164,68 +146,39 @@ type SourceConstraints = Partial<Record<Source, MediaTrackConstraints>>;
/**
* Opens the devices asked for. Where one of them is gone, as a remembered
* choice that was unplugged, that source opens on another device and the
* other source keeps the device picked: an exact request for a device that no
* longer exists would otherwise open nothing.
* choice that was unplugged, the browser picks instead.
*
* This is needed because we use `exact` device ids: an exact request for a
* device that no longer exists fails, where a preferred one would have opened
* another device. Without the retry here a stale choice would open nothing.
*/
async function open(
getUserMedia: GetUserMedia,
constraints: SourceConstraints,
): Promise<{ stream: MediaStream; constraints: SourceConstraints }> {
let refusal: unknown;
for (const attempt of attempts(constraints)) {
try {
const stream = await getUserMedia({
...(attempt.microphone && { audio: attempt.microphone }),
...(attempt.camera && { video: attempt.camera }),
});
return { stream, constraints: attempt };
} catch (e) {
if (!isOverconstrained(e)) throw e;
refusal ??= e;
}
const streamOf = async (wanted: SourceConstraints): Promise<MediaStream> =>
getUserMedia({
...(wanted.microphone && { audio: wanted.microphone }),
...(wanted.camera && { video: wanted.camera }),
});
try {
return { stream: await streamOf(constraints), constraints };
} catch (e) {
if (!(e instanceof Error) || e.name !== "OverconstrainedError") throw e;
const anyDevice: SourceConstraints = {
...(constraints.microphone && {
microphone: { ...constraints.microphone, deviceId: undefined },
}),
...(constraints.camera && {
camera: { ...constraints.camera, deviceId: undefined },
}),
};
return { stream: await streamOf(anyDevice), constraints: anyDevice };
}
throw refusal;
}
/**
* As asked, then with one source let off its device, then both: the refusal
* does not say which of the two devices is gone.
*/
function attempts(wanted: SourceConstraints): SourceConstraints[] {
const { microphone, camera } = wanted;
const camera_ = camera && relaxed(camera);
const microphone_ = microphone && relaxed(microphone);
return [
wanted,
...(camera_ ? [{ ...wanted, camera: camera_ }] : []),
...(microphone_ ? [{ ...wanted, microphone: microphone_ }] : []),
...(camera_ && microphone_
? [{ microphone: microphone_, camera: camera_ }]
: []),
];
}
/** The same request with its device preferred, not required; nothing where it requires none. */
function relaxed(
constraints: MediaTrackConstraints,
): MediaTrackConstraints | undefined {
const { deviceId } = constraints;
if (typeof deviceId !== "object" || Array.isArray(deviceId)) return undefined;
if (deviceId.exact === undefined) return undefined;
return { ...constraints, deviceId: { ideal: deviceId.exact } };
}
/** By name: the refusal is not an `Error` in every browser. */
function isOverconstrained(e: unknown): boolean {
return (e as { name?: unknown } | null)?.name === "OverconstrainedError";
}
/** The constraints a request means to the browser. */
function trackConstraints(
request: Request,
cameraResolution: CaptureResolution,
): MediaTrackConstraints {
function trackConstraints(request: Request): MediaTrackConstraints {
// THE FIX for "cannot switch cameras in Chrome" (#4479), first capture.
// `exact` makes the browser open this device or fail. A plain
// `deviceId: "abc"` is only a wish, and Chromium ignores the wish and
@@ -234,12 +187,14 @@ function trackConstraints(
deviceId: { exact: request.deviceId },
};
if (request.source === "microphone") return { ...device, ...request.capture };
const resolution = request.capture?.resolution ?? cameraResolution;
const resolution = request.capture?.resolution;
return {
...device,
width: resolution.width,
height: resolution.height,
frameRate: resolution.frameRate,
...(resolution && {
width: resolution.width,
height: resolution.height,
frameRate: resolution.frameRate,
}),
};
}
+13 -16
View File
@@ -22,6 +22,7 @@ import {
type ParticipationState,
type RTCMember,
type RTCParticipationOptions,
type RTCSlot,
type TransportMetadata,
} from "./api";
import { defaultSessionTimings, MatrixRTCMode } from "./config";
@@ -85,7 +86,6 @@ function member(
rtcBackendIdentity: overrides.memberId,
backendIdentities: [overrides.memberId],
deviceId: "DEV",
matrixEventId$: constant(`$${overrides.memberId}`),
transport$: constant(metadata(transport)),
applicationData$: constant({}),
displayName$: constant(overrides.userId),
@@ -111,6 +111,7 @@ interface FakeBackend {
function setup(
options: Partial<RTCParticipationOptions> = {},
slotOptions: { matrixRTCMode?: MatrixRTCMode } = {},
{
homeserverTransports = [transport],
memberships = [],
@@ -190,24 +191,19 @@ function setup(
scope,
{
client,
slot: {
roomId: room.roomId,
application: "m.call",
id: "ROOM",
status$: constant(undefined),
members$: scope.behavior(members$),
},
room,
slot: {} as RTCSlot,
jsSdkSession: mockedSession,
members$: scope.behavior(members$),
transports: { get: metadata, connected$: constant([]) },
slotOptions: { encryptionSystem: { kind: E2eeType.PER_PARTICIPANT } },
slotOptions: {
matrixRTCMode: MatrixRTCMode.Compatibility,
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
...slotOptions,
},
logger,
},
{
publish: [],
matrixRTCMode: MatrixRTCMode.Compatibility,
backend: backendFactory,
...options,
},
{ publish: [], backend: backendFactory, ...options },
);
const states: ParticipationState[] = [];
participation.state$.subscribe((state) => states.push(state));
@@ -258,6 +254,7 @@ describe("createRTCParticipation", () => {
fociPreferred: [{ type: "livekit", url: "wss://sfu.example.org" }],
});
const { join, fake } = setup(
{},
{},
{ homeserverTransports: [], memberships: [bobOnSfu] },
);
@@ -352,7 +349,7 @@ describe("createRTCParticipation", () => {
});
compatibility.scope.end();
const matrix2 = setup({ matrixRTCMode: MatrixRTCMode.Matrix_2_0 });
const matrix2 = setup({}, { matrixRTCMode: MatrixRTCMode.Matrix_2_0 });
const { memberId } = matrix2.fake.context.ownMembershipIdentity;
expect(memberId).not.toBe(legacyMemberId);
expect(memberId).toMatch(/^[0-9a-f-]{36}$/);
+33 -53
View File
@@ -5,7 +5,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { type MatrixClient } from "matrix-js-sdk";
import { type MatrixClient, type Room } from "matrix-js-sdk";
import { type Logger } from "matrix-js-sdk/lib/logger";
import {
type MatrixRTCSession as JsSdkRTCSession,
@@ -30,17 +30,19 @@ import {
import { defaultSessionTimings, MatrixRTCMode } from "./config";
import { E2eeType } from "./encryption";
import { type Behavior } from "./reactive/Behavior";
import { type ObservableScope } from "./reactive/ObservableScope";
import { generateItems } from "./reactive/observable";
import { mapScoped } from "./utils/mapScoped";
import {
type ParticipationSlot,
type DataMessage,
type LocalRTCMember,
type ParticipationState,
type RemoteRTCMember,
type RTCMember,
type RTCParticipation,
type RTCParticipationOptions,
type RTCSlot,
type RTCSlotOptions,
} from "./api";
import {
@@ -65,34 +67,15 @@ import { createKeyRotationSuppressed$ } from "./matrixrtc/JsRtcSessionBehaviors"
import { type TransportRegistry } from "./matrixrtc/Transports";
import { participationState } from "./participationState";
/** What is needed for our own participation. */
/** What the slot lends a participation. */
export interface ParticipationDeps {
client: Pick<
MatrixClient,
// Our own membership identity
| "getUserId"
| "getDeviceId"
// Local transport discovery
| "getDomain"
| "getRTCTransports"
// LiveKit auth: `getOpenIdToken` for the JWT service flow, `getLivekitToken`
// for the client-server API flow (MSC4195), `delegateDelayedLeave` and
// `baseUrl` for the delayed leave delegation and its probe
| "getOpenIdToken"
| "getLivekitToken"
| "delegateDelayedLeave"
| "baseUrl"
// Homeserver connection: whether the client is syncing
| "getSyncState"
// `on`/`off`, to listen for:
// - `ClientEvent.Sync` (homeserver connection)
| "on"
| "off"
>;
slot: ParticipationSlot;
client: MatrixClient;
room: Room;
slot: RTCSlot;
jsSdkSession: JsSdkRTCSession;
members$: Behavior<RTCMember[]>;
transports: TransportRegistry;
slotOptions: RTCSlotOptions;
slotOptions: Pick<RTCSlotOptions, "matrixRTCMode" | "encryptionSystem">;
logger: Logger;
}
@@ -111,19 +94,16 @@ export function createRTCParticipation(
scope: ObservableScope,
{
client,
room,
slot,
jsSdkSession,
members$,
transports,
slotOptions: { encryptionSystem },
slotOptions: { matrixRTCMode, encryptionSystem },
logger: parentLogger,
}: ParticipationDeps,
options: RTCParticipationOptions,
): ParticipationInternals {
const { matrixRTCMode } = options;
const { roomId, members$ } = slot;
// The full `{application}#{id}`, which the auth service and the other
// members key the media room on
const slotId = jsSdkSession.slotId;
const logger = parentLogger.getChild("[RTCParticipation]");
const userId = client.getUserId()!;
const deviceId = client.getDeviceId()!;
@@ -142,8 +122,8 @@ export function createRTCParticipation(
};
const backend = createBackend(scope, client, options, {
roomId,
slotId,
roomId: room.roomId,
slotId: jsSdkSession.slotId,
ownMembershipIdentity,
publish: options.publish,
encryptionSystem,
@@ -164,8 +144,8 @@ export function createRTCParticipation(
// to come back later rather than wait in a half-working lobby
memberships: jsSdkSession.memberships,
ownMembershipIdentity,
roomId,
slotId,
roomId: room.roomId,
slotId: jsSdkSession.slotId,
logger,
})
: null;
@@ -195,15 +175,21 @@ export function createRTCParticipation(
timings.syncDisconnectGracePeriodMs,
),
joinMatrixRTC: (transport, delayedLeave) =>
joinJsSdkSession(roomId, jsSdkSession, ownMembershipIdentity, transport, {
encryptMedia: encryptionSystem.kind !== E2eeType.NONE,
matrixRTCMode,
sendNotificationType: options.sendNotificationType,
callIntent: options.callIntent,
applicationData: options.applicationData,
timings,
delayedLeave,
}),
joinJsSdkSession(
room.roomId,
jsSdkSession,
ownMembershipIdentity,
transport,
{
encryptMedia: encryptionSystem.kind !== E2eeType.NONE,
matrixRTCMode,
sendNotificationType: options.sendNotificationType,
callIntent: options.callIntent,
applicationData: options.applicationData,
timings,
delayedLeave,
},
),
membershipManagerError$: fromEvent(
jsSdkSession,
MatrixRTCSessionEvent.MembershipManagerError,
@@ -329,13 +315,7 @@ export function createRTCParticipation(
/** The host's backend, or LiveKit configured from the participation options. */
function createBackend(
scope: ObservableScope,
client: Pick<
MatrixClient,
// LiveKit auth: `getOpenIdToken` for the JWT service flow, `getLivekitToken`
// for the client-server API flow (MSC4195), `delegateDelayedLeave` and
// `baseUrl` for the delayed leave delegation and its probe
"getOpenIdToken" | "getLivekitToken" | "delegateDelayedLeave" | "baseUrl"
>,
client: MatrixClient,
{ backend, mediaQuality }: RTCParticipationOptions,
context: MediaBackendContext,
): MediaBackend {
+9 -202
View File
@@ -5,39 +5,23 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { EMPTY } from "rxjs";
import { describe, expect, it, vi } from "vitest";
import { type MatrixClient, type Room, SyncState } from "matrix-js-sdk";
import { describe, expect, it } from "vitest";
import { type MatrixClient, type Room } from "matrix-js-sdk";
import { EventType } from "matrix-js-sdk/lib/@types/event";
import { type MatrixEvent } from "matrix-js-sdk/lib/models/event";
import {
type RoomState,
RoomStateEvent,
} from "matrix-js-sdk/lib/models/room-state";
import { RoomStickyEventsEvent } from "matrix-js-sdk/lib/models/room-sticky-events";
import {
MatrixRTCSessionEvent,
type MatrixRTCSessionEventHandlerMap,
} from "matrix-js-sdk/lib/matrixrtc";
import { createRTCSlot } from "./RTCSlot";
import { type SdkMatrixBackend } from "./SdkMatrixBackend";
import { ObservableScope } from "./reactive/ObservableScope";
import { type RTCParticipationOptions, type RTCSlotOptions } from "./api";
import { type RTCSlotOptions } from "./api";
import { MatrixRTCMode } from "./config";
import { E2eeType } from "./encryption";
import { MatrixRTCError } from "./errors";
import { type MediaBackend, MediaConnectionState } from "./media-backend/api";
import { constant } from "./reactive/Behavior";
import {
mockEmitter,
mockRtcMembership,
MockRTCSession,
testScope,
} from "./utils/test";
import { mockEmitter, MockRTCSession, testScope } from "./utils/test";
const options: RTCSlotOptions = {
matrixRTCMode: MatrixRTCMode.Compatibility,
encryptionSystem: { kind: E2eeType.NONE },
};
@@ -50,140 +34,28 @@ function setup(): {
...mockEmitter(),
roomId: "!room:example.org",
getMembersWithMembership: (): [] => [],
// An empty room, for a session of the slot's own
getLiveTimeline: () => ({ getState: (): undefined => undefined }),
hasMembershipState: (): boolean => false,
getVersion: (): string => "11",
_unstable_getStickyEvents: (): [] => [],
} as unknown as Room;
const session = new MockRTCSession(room);
const client = {
...mockEmitter(),
getUserId: (): string => "@alice:example.org",
getDeviceId: (): string => "AAAA",
matrixRTC: { getRoomSession: (): MockRTCSession => session },
} as unknown as MatrixClient;
return { client, room, session };
}
function backendOf(client: MatrixClient, room: Room): SdkMatrixBackend {
return {
...client,
...room,
clientEmitter: client,
roomEmitter: room,
} as unknown as SdkMatrixBackend;
}
/** A media backend whose transport never gets ready: a participation on it stays waiting. */
function idleBackend(): MediaBackend {
return {
transportTypes: ["livekit"],
prepareLocalTransport: async () => new Promise(() => {}),
delegateDelayedLeave: vi.fn(),
local: {
connectionState$: constant(MediaConnectionState.Initialized),
setPublishing: vi.fn(),
publishError$: constant(null),
publish: vi.fn(),
unpublish: vi.fn(),
tracks$: constant(null),
encryptionError$: EMPTY,
},
mediaFor: vi.fn(),
connections$: constant([]),
setAudioOutputDeviceId: vi.fn(),
sendData: vi.fn(),
data$: EMPTY,
};
}
describe("createRTCSlot", () => {
describe("session", () => {
it("joins the room's call slot by default", () => {
const { client, room } = setup();
const slot = createRTCSlot(testScope(), backendOf(client, room), options);
expect(slot).toMatchObject({ application: "m.call", id: "ROOM" });
});
it("joins the slot the options name", () => {
const { client, room } = setup();
const slot = createRTCSlot(testScope(), backendOf(client, room), {
...options,
slotDescription: { application: "io.element.example", id: "" },
});
expect(slot).toMatchObject({ application: "io.element.example", id: "" });
});
it("stops its own session when the scope ends", async () => {
const { client, room } = setup();
const off = vi.spyOn(room, "off");
const scope = new ObservableScope();
createRTCSlot(scope, backendOf(client, room), options);
scope.end();
await vi.waitFor(() =>
expect(off).toHaveBeenCalledWith(
RoomStickyEventsEvent.Update,
expect.any(Function),
),
);
});
it("leaves a session it is given to its caller", () => {
const { client, room, session } = setup();
const given = session.asMockedSession();
given.stop = vi.fn();
const scope = new ObservableScope();
createRTCSlot(scope, backendOf(client, room), options, given);
scope.end();
expect(given.stop).not.toHaveBeenCalled();
});
it("has the session's statistics and sent call notifications", () => {
const { client, room, session } = setup();
const slot = createRTCSlot(
testScope(),
backendOf(client, room),
options,
session.asMockedSession(),
);
expect(slot.statistics).toBe(session.statistics);
const sent: unknown[] = [];
slot.sentCallNotification$.subscribe((n) => sent.push(n));
const notification = { event_id: "$notification" };
session.emit(
MatrixRTCSessionEvent.DidSendCallNotification,
notification as Parameters<
MatrixRTCSessionEventHandlerMap[MatrixRTCSessionEvent.DidSendCallNotification]
>[0],
);
expect(sent).toEqual([notification]);
});
});
describe("status$", () => {
it("is undefined while the room has no slot event", () => {
const { client, room, session } = setup();
const slot = createRTCSlot(
testScope(),
backendOf(client, room),
options,
session.asMockedSession(),
);
const { client, room } = setup();
const slot = createRTCSlot(testScope(), client, room, options);
expect(slot.status$.value).toBeUndefined();
});
it("follows the slot event", () => {
const { client, room, session } = setup();
session.rtcSlot = { status: "open" };
const slot = createRTCSlot(
testScope(),
backendOf(client, room),
options,
session.asMockedSession(),
);
const slot = createRTCSlot(testScope(), client, room, options);
expect(slot.status$.value).toBe("open");
session.rtcSlot = { status: "closed" };
@@ -196,69 +68,4 @@ describe("createRTCSlot", () => {
expect(slot.status$.value).toBe("closed");
});
});
describe("join", () => {
it("holds one participation at a time, and is free again once it has left", () => {
const { client, room, session } = setup();
const slot = createRTCSlot(
testScope(),
backendOf(
{
...client,
getDomain: (): string => "example.org",
getSyncState: (): SyncState => SyncState.Syncing,
getRTCTransports: vi.fn().mockResolvedValue([]),
} as unknown as MatrixClient,
room,
),
options,
session.asMockedSession(),
);
const joinOptions: RTCParticipationOptions = {
publish: [],
matrixRTCMode: MatrixRTCMode.Compatibility,
backend: idleBackend,
};
expect(slot.participation$.value).toBeNull();
const participation = slot.join(joinOptions);
expect(slot.participation$.value).toBe(participation);
expect(participation.slot).toMatchObject({
roomId: room.roomId,
application: "m.call",
id: "ROOM",
});
expect(() => slot.join(joinOptions)).toThrow(MatrixRTCError);
participation.leave();
expect(slot.participation$.value).toBeNull();
const again = slot.join(joinOptions);
expect(slot.participation$.value).toBe(again);
again.leave();
});
});
describe("members$", () => {
it("keeps the member when its membership is sent again, with the new event id", () => {
const { client, room, session } = setup();
const first = mockRtcMembership("@bob:example.org", "BOB");
session.memberships = [first];
const slot = createRTCSlot(
testScope(),
backendOf(client, room),
options,
session.asMockedSession(),
);
const [bob] = slot.members$.value;
expect(bob.matrixEventId$.value).toBe(first.eventId);
const resent = mockRtcMembership("@bob:example.org", "BOB");
session.memberships = [resent];
session.emit(MatrixRTCSessionEvent.MembershipsChanged, [first], [resent]);
expect(slot.members$.value).toHaveLength(1);
expect(slot.members$.value[0]).toBe(bob);
expect(bob.matrixEventId$.value).toBe(resent.eventId);
expect(resent.eventId).not.toBe(first.eventId);
});
});
});
+74 -124
View File
@@ -5,14 +5,12 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { type MatrixClient } from "matrix-js-sdk";
import { type MatrixClient, type Room } from "matrix-js-sdk";
import { EventType } from "matrix-js-sdk/lib/@types/event";
import { logger as rootLogger } from "matrix-js-sdk/lib/logger";
import { type Logger, logger as rootLogger } from "matrix-js-sdk/lib/logger";
import {
type Statistics,
MatrixRTCSession as JsMatrixRTCSession,
MatrixRTCSessionEvent,
type IRTCNotificationContent,
type MatrixRTCSession as JsSdkRTCSession,
MatrixRTCSessionManager,
type SlotDescription,
} from "matrix-js-sdk/lib/matrixrtc";
import { type MatrixEvent } from "matrix-js-sdk/lib/models/event";
@@ -22,7 +20,6 @@ import {
filter,
fromEvent,
map,
type Observable,
of,
startWith,
switchMap,
@@ -31,7 +28,6 @@ import {
import { ObservableScope } from "./reactive/ObservableScope";
import { generateItems } from "./reactive/observable";
import {
type ParticipationSlot,
type RTCMember,
type RTCParticipation,
type RTCParticipationOptions,
@@ -54,64 +50,33 @@ import {
membershipKeys,
} from "./matrixrtc/Members";
import { createTransportRegistry } from "./matrixrtc/Transports";
import {
type createSdkMatrixBackend,
type SdkMatrixBackend,
withEmitter,
} from "./SdkMatrixBackend";
const ROOM_CALL_SLOT: SlotDescription = { application: "m.call", id: "ROOM" };
/**
* The slot runs on a matrix-js-sdk session of its own, from the SDK's copy of
* matrix-js-sdk rather than the client's, and stops it when the scope ends.
* Takes the whole `MatrixClient` rather than a slice of it, and finds the
* MatrixRTC session itself. The js-sdk is the MatrixRTC implementation today;
* when the rust-rtc crate replaces it, the SDK has to bridge the crate to the
* js-sdk client, and only the SDK knows what that bridge needs. Holding the
* client keeps that change inside the SDK.
*/
export function createRTCSlot(
scope: ObservableScope,
backend: SdkMatrixBackend,
client: MatrixClient,
room: Room,
options: RTCSlotOptions,
/**
* @deprecated A session the caller owns and stops, in place of the slot's
* own; `options.slotDescription` is then the session's. Only for the
* standalone app, which still takes its session from its client's session
* manager.
*/
externalJsSdkSession?: JsMatrixRTCSession,
): RTCSlot & {
// STOP GAP: This should be its own external machine. It is call
// specific and should not live inside the sdk/rtc-slot.
// We only put it here today, to make sure the rtcSession is fully
// hidden inside the sdk.
// Next step. disable sending call notificaitons in the sdk, write a new
// notification sender in EC directly on client + room.
sentCallNotification$: Observable<
{
event_id: string;
} & IRTCNotificationContent
>;
// STOP GAP: the same as above. Has to live here. but should become a native
// SDK propery independent of the rtcSession
statistics: Statistics;
} {
// STOP GAP: the slot is still written against a client and a room. Both
// are refactored along with the backend.
const client = withEmitter(backend, backend.clientEmitter);
const room = withEmitter(backend, backend.roomEmitter);
): RTCSlot {
const logger = rootLogger.getChild("[RTCSlot]");
const userId = client.getUserId();
const deviceId = client.getDeviceId();
const roomId = room.roomId;
if (!(userId && deviceId))
throw new MatrixRTCError("The client has to be logged in");
const { application = "m.call", id = "ROOM" } = options;
const jsSdkSession =
externalJsSdkSession ??
createJsSdkSession(
scope,
client,
room,
options.slotDescription ?? ROOM_CALL_SLOT,
);
const jsSdkSession = sessionManager(
scope,
client,
{ application, id },
logger,
).getRoomSession(room);
const memberships$ = createMemberships$(scope, jsSdkSession);
const active$ = new BehaviorSubject<ParticipationInternals | null>(null);
@@ -161,85 +126,70 @@ export function createRTCSlot(
),
);
const participationSlot: ParticipationSlot = {
roomId,
const slot: RTCSlot = {
roomId: room.roomId,
application,
id,
status$,
members$,
...jsSdkSession.slotDescription,
};
const join = (
participationOptions: RTCParticipationOptions,
): RTCParticipation => {
if (active$.value !== null)
throw new MatrixRTCError(
"Already in this slot: leave the participation before joining again",
);
const participationScope = new ObservableScope();
participationScopes.add(participationScope);
const internals = createRTCParticipation(
participationScope,
{
client,
slot: participationSlot,
jsSdkSession,
transports,
slotOptions: options,
logger,
},
participationOptions,
);
participationScope.onEnd(() => {
participationScopes.delete(participationScope);
if (active$.value === internals) active$.next(null);
});
active$.next(internals);
return internals.participation;
};
const slot = {
join,
participation$: scope.behavior(
active$.pipe(map((active) => active?.participation ?? null)),
),
...participationSlot,
join: (participationOptions: RTCParticipationOptions): RTCParticipation => {
if (active$.value !== null)
throw new MatrixRTCError(
"Already in this slot: leave the participation before joining again",
);
const participationScope = new ObservableScope();
participationScopes.add(participationScope);
const internals = createRTCParticipation(
participationScope,
{
client,
room,
slot,
jsSdkSession,
members$,
transports,
slotOptions: options,
logger,
},
participationOptions,
);
participationScope.onEnd(() => {
participationScopes.delete(participationScope);
if (active$.value === internals) active$.next(null);
});
active$.next(internals);
return internals.participation;
},
};
return {
...slot,
sentCallNotification$: fromEvent(
jsSdkSession,
MatrixRTCSessionEvent.DidSendCallNotification,
(notification: { event_id: string } & IRTCNotificationContent) =>
notification,
),
statistics: jsSdkSession.statistics,
};
}
function createJsSdkSession(
scope: ObservableScope,
client: Pick<
MatrixClient,
keyof Parameters<typeof createSdkMatrixBackend>[0]
>,
room: ConstructorParameters<typeof JsMatrixRTCSession>[1],
slotDescription: SlotDescription,
): JsMatrixRTCSession {
const session = new JsMatrixRTCSession(
// The session's type also asks for `cancelPendingEvent`,
// `_unstable_updateDelayedEvent` and `decryptEventIfNeeded`, which it
// never calls
client as ConstructorParameters<typeof JsMatrixRTCSession>[0],
room,
slotDescription,
);
scope.onEnd(() => void session.stop());
return session;
return slot;
}
function slotStatus(
session: Pick<JsMatrixRTCSession, "getRtcSlot">,
session: Pick<JsSdkRTCSession, "getRtcSlot">,
): "open" | "closed" | undefined {
return session.getRtcSlot()?.status;
}
/**
* The js-sdk keeps one session manager per slot. The client comes with the
* manager for the default slot; any other slot gets a manager of its own,
* which lives as long as the scope.
*/
function sessionManager(
scope: ObservableScope,
client: MatrixClient,
{ application, id }: SlotDescription,
logger: Logger,
): MatrixRTCSessionManager {
if (application === "m.call" && id === "ROOM") return client.matrixRTC;
const manager = new MatrixRTCSessionManager(logger, client, {
application,
id,
});
manager.start();
scope.onEnd(() => manager.stop());
return manager;
}
-85
View File
@@ -1,85 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { describe, expect, it, vi } from "vitest";
import {
ClientEvent,
createClient,
type MatrixClient,
Room,
RoomEvent,
SyncState,
} from "matrix-js-sdk";
import { createSdkMatrixBackend, withEmitter } from "./SdkMatrixBackend";
describe("createSdkMatrixBackend", () => {
it("calls each member on the client or the room it came from", () => {
const { client, room } = setup();
const backend = createSdkMatrixBackend(client, room);
expect(backend.getUserId()).toBe("@alice:example.org");
expect(backend.roomId).toBe("!room:example.org");
expect(backend.getVersion()).toBe(room.getVersion());
});
it("keeps the client's and the room's events apart", () => {
const { client, room } = setup();
const backend = createSdkMatrixBackend(client, room);
const onClient = vi.fn();
const onRoom = vi.fn();
backend.clientEmitter.on(ClientEvent.Sync, onClient);
backend.roomEmitter.on(RoomEvent.Name, onRoom);
client.emit(ClientEvent.Sync, SyncState.Syncing, null);
expect(onClient).toHaveBeenCalledOnce();
expect(onRoom).not.toHaveBeenCalled();
room.emit(RoomEvent.Name, room);
expect(onRoom).toHaveBeenCalledOnce();
});
});
describe("withEmitter", () => {
it("is the backend with one side's events", () => {
const { client, room } = setup();
const backend = createSdkMatrixBackend(client, room);
const asRoom = withEmitter(backend, backend.roomEmitter);
const listener = vi.fn();
asRoom.on(RoomEvent.Name, listener);
room.emit(RoomEvent.Name, room);
expect(listener).toHaveBeenCalledOnce();
expect(asRoom.getUserId()).toBe("@alice:example.org");
});
it("reads the backend's getters through", () => {
const { room } = setup();
const asRoom = withEmitter(
{
get name() {
return room.name;
},
},
room,
);
room.name = "Renamed";
expect(asRoom.name).toBe("Renamed");
});
});
function setup(): { client: MatrixClient; room: Room } {
const client = createClient({
baseUrl: "https://matrix.example.org",
userId: "@alice:example.org",
deviceId: "DEVICE",
});
const room = new Room("!room:example.org", client, "@alice:example.org");
return { client, room };
}
-129
View File
@@ -1,129 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { type MatrixClient, type Room } from "matrix-js-sdk";
/** What the SDK needs of the client. */
type SdkClientPart = Pick<
MatrixClient,
// Our own membership identity
| "getUserId"
| "getDeviceId"
// The session: memberships, delayed leave events, sticky events, call
// notifications, and the media keys sent to device
| "fetchCapabilities"
| "getCachedCapabilities"
| "sendEvent"
| "sendStateEvent"
| "_unstable_sendDelayedStateEvent"
| "_unstable_cancelScheduledDelayedEvent"
| "_unstable_restartScheduledDelayedEvent"
| "_unstable_sendScheduledDelayedEvent"
| "_unstable_sendStickyEvent"
| "_unstable_sendStickyDelayedEvent"
| "encryptAndSendToDevice"
// Local transport discovery
| "getDomain"
| "getRTCTransports"
// LiveKit auth: `getOpenIdToken` for the JWT service flow, `getLivekitToken`
// for the client-server API flow (MSC4195), `delegateDelayedLeave` and
// `baseUrl` for the delayed leave delegation and its probe
| "getOpenIdToken"
| "getLivekitToken"
| "delegateDelayedLeave"
| "baseUrl"
// Homeserver connection: whether the client is syncing
| "getSyncState"
>;
/** What the SDK needs of the room. */
type SdkRoomPart = Pick<
Room,
| "roomId"
// The members' display names and avatars
| "getMembersWithMembership"
// The session: memberships from the room's state, timeline and sticky events
| "getLiveTimeline"
| "getVersion"
| "hasMembershipState"
| "_unstable_getStickyEvents"
>;
/**
* STOP GAP: what the SDK needs of a Matrix client and room, on one object.
* Only their emitters stay apart, since both have an `on` and an `off`. It is
* to converge, along with the SDK that takes it, on whichever API fits every
* layer best.
*/
export interface SdkMatrixBackend extends SdkClientPart, SdkRoomPart {
/**
* `ClientEvent.Sync` (homeserver connection) and `ClientEvent.ToDeviceEvent`
* (the session's media keys)
*/
clientEmitter: Pick<MatrixClient, "on" | "off">;
/** The room's state, member and sticky events */
roomEmitter: Pick<Room, "on" | "off">;
}
/** The SDK's backend from a client and a room. */
export function createSdkMatrixBackend(
client: SdkClientPart & Pick<MatrixClient, "on" | "off">,
room: SdkRoomPart & Pick<Room, "on" | "off">,
): SdkMatrixBackend {
return {
getUserId: client.getUserId.bind(client),
getDeviceId: client.getDeviceId.bind(client),
fetchCapabilities: client.fetchCapabilities.bind(client),
getCachedCapabilities: client.getCachedCapabilities.bind(client),
sendEvent: client.sendEvent.bind(client),
sendStateEvent: client.sendStateEvent.bind(client),
_unstable_sendDelayedStateEvent:
client._unstable_sendDelayedStateEvent.bind(client),
_unstable_cancelScheduledDelayedEvent:
client._unstable_cancelScheduledDelayedEvent.bind(client),
_unstable_restartScheduledDelayedEvent:
client._unstable_restartScheduledDelayedEvent.bind(client),
_unstable_sendScheduledDelayedEvent:
client._unstable_sendScheduledDelayedEvent.bind(client),
_unstable_sendStickyEvent: client._unstable_sendStickyEvent.bind(client),
_unstable_sendStickyDelayedEvent:
client._unstable_sendStickyDelayedEvent.bind(client),
encryptAndSendToDevice: client.encryptAndSendToDevice.bind(client),
getDomain: client.getDomain.bind(client),
getRTCTransports: client.getRTCTransports.bind(client),
getOpenIdToken: client.getOpenIdToken.bind(client),
getLivekitToken: client.getLivekitToken.bind(client),
delegateDelayedLeave: client.delegateDelayedLeave.bind(client),
baseUrl: client.baseUrl,
getSyncState: client.getSyncState.bind(client),
roomId: room.roomId,
getMembersWithMembership: room.getMembersWithMembership.bind(room),
getLiveTimeline: room.getLiveTimeline.bind(room),
getVersion: room.getVersion.bind(room),
hasMembershipState: room.hasMembershipState.bind(room),
_unstable_getStickyEvents: room._unstable_getStickyEvents.bind(room),
clientEmitter: client,
roomEmitter: room,
};
}
/**
* STOP GAP: the backend as the client (or the room) code written against one
* still expects, with that side's `on` and `off`.
*/
export function withEmitter<
Backend extends object,
Emitter extends {
on: (...args: never[]) => unknown;
off: (...args: never[]) => unknown;
},
>(backend: Backend, emitter: Emitter): Backend & Pick<Emitter, "on" | "off"> {
return Object.defineProperties<object>(
{ on: emitter.on.bind(emitter), off: emitter.off.bind(emitter) },
Object.getOwnPropertyDescriptors(backend),
) as Backend & Pick<Emitter, "on" | "off">;
}
+7 -23
View File
@@ -14,7 +14,6 @@ Please see LICENSE in the repository root for full details.
import {
type RTCCallIntent,
type RTCNotificationType,
type SlotDescription,
type Transport,
} from "matrix-js-sdk/lib/matrixrtc";
import { type Observable } from "rxjs";
@@ -44,9 +43,13 @@ export { MatrixRTCError } from "./errors";
// Slot
export interface RTCSlotOptions {
/** The application the slot belongs to, as named in the membership. Default `m.call`. */
application?: string;
/** The application's slot in the room. Default `ROOM`. */
id?: string;
/** How memberships and keys in this slot are written. Resolved by the host. */
matrixRTCMode: MatrixRTCMode;
encryptionSystem: EncryptionSystem;
/** Which slot of the room to join. Defaults to the room's call, `m.call#ROOM`. */
slotDescription?: SlotDescription;
}
/**
@@ -78,12 +81,6 @@ export interface RTCSlot {
join(options: RTCParticipationOptions): RTCParticipation; // Maybe MediaSession,
}
/**
* The slot as its participation sees it: members, status and identity, without
* `join` and `participation$`, which belong to whoever joins.
*/
export type ParticipationSlot = Omit<RTCSlot, "join" | "participation$">;
// ---------------------------------------------------------------------------
// Participation
@@ -98,12 +95,6 @@ export interface RTCParticipationOptions {
* before the first connection exists.
*/
publish: PublishRequest[] | LocalMedia;
/**
* How our membership and keys are written: the member id and whether the
* membership is a sticky event. Resolved by the host. Others' memberships
* are read whatever their mode.
*/
matrixRTCMode: MatrixRTCMode;
/**
* LEGACY
*
@@ -175,8 +166,7 @@ export type ParticipationState =
/** The span between our `join()` of a slot and our `leave()`. */
export interface RTCParticipation {
/** Required slot information (no `join` fn and `participation`) */
readonly slot: ParticipationSlot;
readonly slot: RTCSlot;
/** Sends the leave, tears the connections down and ends the participation. */
leave(): void;
state$: Behavior<ParticipationState>;
@@ -299,12 +289,6 @@ export interface RTCMember {
deviceId: string;
/** The membership's own id; what the Matrix 2.0 identity is derived from. */
memberId: string;
/**
* The Matrix event currently carrying the membership, which events about
* it (reactions, raised hands) relate to. Changes when the membership is
* sent again while the member stays the same.
*/
matrixEventId$: Behavior<string>;
/** Which transport this member is on; undefined when the membership has none. */
transport$: Behavior<TransportMetadata | undefined>;
/** What the member's application says about itself, e.g. `intent`. */
-34
View File
@@ -99,37 +99,3 @@ export const defaultMediaQuality = {
max_framerate: 30,
},
} as const satisfies MediaQuality;
export interface CaptureResolution {
width: number;
height: number;
frameRate: number;
}
/**
* What a camera is captured at for a media quality. A lobby that opens the
* camera ahead of the join asks for this, so that the track it hands over is
* the one the backend would have captured.
*/
export function cameraCaptureResolution(
mediaQuality?: MediaQuality,
): CaptureResolution {
const height =
mediaQuality?.video?.max_resolution ??
defaultMediaQuality.video.max_resolution;
return (
captureResolutions.find((resolution) => height <= resolution.height) ??
captureResolutions.at(-1)!
);
}
/** Lowest first; a height between two takes the higher. */
const captureResolutions: CaptureResolution[] = [
{ width: 320, height: 180, frameRate: 20 },
{ width: 640, height: 360, frameRate: 20 },
{ width: 960, height: 540, frameRate: 25 },
{ width: 1280, height: 720, frameRate: 30 },
{ width: 1920, height: 1080, frameRate: 30 },
{ width: 2560, height: 1440, frameRate: 30 },
{ width: 3840, height: 2160, frameRate: 30 },
];
+21 -69
View File
@@ -8,7 +8,7 @@ Please see LICENSE in the repository root for full details.
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { EventEmitter } from "events";
import { ClientEvent, type MatrixClient, SyncState } from "matrix-js-sdk";
import { ClientEvent, SyncState } from "matrix-js-sdk";
import { MembershipManagerEvent, Status } from "matrix-js-sdk/lib/matrixrtc";
import { ObservableScope } from "../reactive/ObservableScope";
@@ -20,7 +20,7 @@ import { testScope, withTestScheduler } from "../utils/test";
```
createHomeserverConnected$(
scope: ObservableScope,
client: Pick<MatrixClient, "getSyncState" | "on" | "off">,
client: NodeStyleEventEmitter & Pick<MatrixClient, "getSyncState">,
matrixRTCSession: NodeStyleEventEmitter &
Pick<MatrixRTCSession, "membershipStatus" | "probablyLeft">,
)
@@ -34,15 +34,12 @@ class MockMatrixClient extends EventEmitter {
}
public setSyncState(state: SyncState): void {
this.syncState = state;
this.emit(ClientEvent.Sync, state);
// Matrix's Sync event in createHomeserverConnected$ expects [SyncState]
this.emit(ClientEvent.Sync, [state]);
}
public getSyncState(): SyncState {
return this.syncState;
}
/** `MatrixClient`'s `on`/`off` return the client itself, which no mock is. */
public get asClient(): Pick<MatrixClient, "getSyncState" | "on" | "off"> {
return this as unknown as Pick<MatrixClient, "getSyncState" | "on" | "off">;
}
}
/**
@@ -50,7 +47,7 @@ class MockMatrixClient extends EventEmitter {
```
createHomeserverConnected$(
scope: ObservableScope,
client: Pick<MatrixClient, "getSyncState" | "on" | "off">,
client: NodeStyleEventEmitter & Pick<MatrixClient, "getSyncState">,
matrixRTCSession: NodeStyleEventEmitter &
Pick<MatrixRTCSession, "membershipStatus" | "probablyLeft">,
)
@@ -102,33 +99,18 @@ describe("createHomeserverConnected$", () => {
// easy enough to read them so I think they can stay.
// Note: gracePeriodMs is set to 0 to avoid debouncing delays in tests
it("reports syncing reason when sync state is not Syncing", () => {
const hsConnected = createHomeserverConnected$(
scope,
client.asClient,
session,
0,
);
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
expect(hsConnected.disconnectReason$.value).toEqual("sync");
});
it("reports membership reason when sync is Syncing but membership is not Connected", () => {
const hsConnected = createHomeserverConnected$(
scope,
client.asClient,
session,
0,
);
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
client.setSyncState(SyncState.Syncing);
expect(hsConnected.disconnectReason$.value).toEqual("membership");
});
it("reports probablyLeft reason when membership transitions to Connected but ProbablyLeft is true", () => {
const hsConnected = createHomeserverConnected$(
scope,
client.asClient,
session,
0,
);
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
// Make sync loop OK
client.setSyncState(SyncState.Syncing);
// Indicate probable leave before connection
@@ -138,12 +120,7 @@ describe("createHomeserverConnected$", () => {
});
it("becomes null (connected) only when all three conditions are satisfied", () => {
const hsConnected = createHomeserverConnected$(
scope,
client.asClient,
session,
0,
);
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
// 1. Sync loop connected
client.setSyncState(SyncState.Syncing);
expect(hsConnected.disconnectReason$.value).toEqual("membership"); // not yet membership connected
@@ -153,12 +130,7 @@ describe("createHomeserverConnected$", () => {
});
it("returns syncing reason when sync loop leaves Syncing", () => {
const hsConnected = createHomeserverConnected$(
scope,
client.asClient,
session,
0,
);
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
// Reach connected state
client.setSyncState(SyncState.Syncing);
session.setMembershipStatus(Status.Connected);
@@ -170,12 +142,7 @@ describe("createHomeserverConnected$", () => {
});
it("returns membershipConnected reason when membership status becomes disconnected", () => {
const hsConnected = createHomeserverConnected$(
scope,
client.asClient,
session,
0,
);
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
client.setSyncState(SyncState.Syncing);
session.setMembershipStatus(Status.Connected);
expect(hsConnected.disconnectReason$.value).toEqual(null);
@@ -185,12 +152,7 @@ describe("createHomeserverConnected$", () => {
});
it("returns certainlyConnected reason when ProbablyLeft is emitted", () => {
const hsConnected = createHomeserverConnected$(
scope,
client.asClient,
session,
0,
);
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
client.setSyncState(SyncState.Syncing);
session.setMembershipStatus(Status.Connected);
expect(hsConnected.disconnectReason$.value).toEqual(null);
@@ -200,12 +162,7 @@ describe("createHomeserverConnected$", () => {
});
it("recovers to null (connected) if ProbablyLeft becomes false again while other conditions remain true", () => {
const hsConnected = createHomeserverConnected$(
scope,
client.asClient,
session,
0,
);
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
client.setSyncState(SyncState.Syncing);
session.setMembershipStatus(Status.Connected);
expect(hsConnected.disconnectReason$.value).toEqual(null);
@@ -219,12 +176,7 @@ describe("createHomeserverConnected$", () => {
});
it("composite sequence reflects each individual failure reason", () => {
const hsConnected = createHomeserverConnected$(
scope,
client.asClient,
session,
0,
);
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
// Initially: sync error + membership disconnected → syncing wins (highest priority)
expect(hsConnected.disconnectReason$.value).toEqual("sync");
@@ -273,7 +225,7 @@ describe("createHomeserverConnected$ - disconnectReason$ reason values", () => {
it("is null when all three conditions are satisfied", () => {
const { disconnectReason$ } = createHomeserverConnected$(
scope,
client.asClient,
client,
session,
0,
);
@@ -285,7 +237,7 @@ describe("createHomeserverConnected$ - disconnectReason$ reason values", () => {
it("reports syncing when sync loop is not Syncing", () => {
const { disconnectReason$ } = createHomeserverConnected$(
scope,
client.asClient,
client,
session,
0,
);
@@ -296,7 +248,7 @@ describe("createHomeserverConnected$ - disconnectReason$ reason values", () => {
it("reports membershipConnected when sync is fine but membership is not Connected", () => {
const { disconnectReason$ } = createHomeserverConnected$(
scope,
client.asClient,
client,
session,
0,
);
@@ -308,7 +260,7 @@ describe("createHomeserverConnected$ - disconnectReason$ reason values", () => {
it("reports certainlyConnected when probablyLeft is true", () => {
const { disconnectReason$ } = createHomeserverConnected$(
scope,
client.asClient,
client,
session,
0,
);
@@ -321,7 +273,7 @@ describe("createHomeserverConnected$ - disconnectReason$ reason values", () => {
it("prioritises syncing over membershipConnected when both fail", () => {
const { disconnectReason$ } = createHomeserverConnected$(
scope,
client.asClient,
client,
session,
0,
);
@@ -332,7 +284,7 @@ describe("createHomeserverConnected$ - disconnectReason$ reason values", () => {
it("updates reason as conditions change", () => {
const { disconnectReason$ } = createHomeserverConnected$(
scope,
client.asClient,
client,
session,
0,
);
@@ -377,7 +329,7 @@ describe("createHomeserverConnected$ - Grace Period", () => {
});
const hsConnected = createHomeserverConnected$(
testScope(),
client.asClient,
client,
session,
GRACE_PERIOD,
);
+6 -15
View File
@@ -17,6 +17,7 @@ import {
startWith,
map,
tap,
type Observable,
distinctUntilChanged,
switchMap,
of,
@@ -60,15 +61,7 @@ export interface HomeserverConnected {
*/
export function createHomeserverConnected$(
scope: ObservableScope,
client: Pick<
MatrixClient,
// Whether the client is syncing
| "getSyncState"
// `on`/`off`, to listen for:
// - `ClientEvent.Sync`
| "on"
| "off"
>,
client: NodeStyleEventEmitter & Pick<MatrixClient, "getSyncState">,
matrixRTCSession: NodeStyleEventEmitter &
Pick<MatrixRTCSession, "membershipStatus" | "probablyLeft">,
gracePeriodMs?: number,
@@ -78,13 +71,11 @@ export function createHomeserverConnected$(
const graceMs =
gracePeriodMs ?? defaultSessionTimings.syncDisconnectGracePeriodMs;
const syncing$ = fromEvent(
client,
ClientEvent.Sync,
(state: SyncState) => state,
const syncing$ = (
fromEvent(client, ClientEvent.Sync) as Observable<[SyncState]>
).pipe(
startWith(client.getSyncState()),
map((state) => state === SyncState.Syncing),
startWith([client.getSyncState()]),
map(([state]) => state === SyncState.Syncing),
distinctUntilChanged(),
switchMap((isSyncing) => {
if (isSyncing || graceMs <= 0) {
+2 -5
View File
@@ -23,9 +23,7 @@ export type RoomMemberMap = Map<
string,
Pick<RoomMember, "userId" | "getMxcAvatarUrl" | "rawDisplayName">
>;
export function roomToMembersMap(
matrixRoom: Pick<MatrixRoom, "getMembersWithMembership">,
): RoomMemberMap {
export function roomToMembersMap(matrixRoom: MatrixRoom): RoomMemberMap {
const members = matrixRoom
.getMembersWithMembership(KnownMembership.Join)
.concat(matrixRoom.getMembersWithMembership(KnownMembership.Invite));
@@ -39,10 +37,9 @@ export function roomToMembersMap(
}, new Map());
}
/** Listens for `RoomStateEvent.Members` on the room. */
export function createRoomMembers$(
scope: ObservableScope,
matrixRoom: Pick<MatrixRoom, "getMembersWithMembership" | "on" | "off">,
matrixRoom: MatrixRoom,
): Behavior<RoomMemberMap> {
return scope.behavior(
fromEvent(matrixRoom, RoomStateEvent.Members).pipe(
-6
View File
@@ -57,12 +57,6 @@ export function createRTCMember(
userId,
deviceId,
memberId,
matrixEventId$: scope.behavior(
membership$.pipe(
map((membership) => membership.eventId),
distinctUntilChanged(),
),
),
displayName$: scope.behavior(
metadata
.createDisplayNameBehavior$(scope, userId)
@@ -42,7 +42,11 @@ import {
} from "./Connection.ts";
import { ObservableScope } from "../../reactive/ObservableScope";
import { type ClientGetTokenParts, type ClientOpenIDParts } from "./auth";
import { LivekitConnectionError, MatrixRTCError } from "../../errors";
import {
LivekitConnectionError,
MatrixRTCError,
NoMatrix2AuthorizationService,
} from "../../errors";
import { testJWTToken } from "../../utils/test-fixtures";
import { ownMemberMock } from "../../utils/test";
import { mockRemoteParticipant } from "./test";
@@ -63,15 +67,15 @@ const FIREFOX_USER_AGENT =
const CHROME_USER_AGENT =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36";
const transport: UnstableLivekitTransport = {
type: "livekit",
url: "wss://matrix-rtc.m.localhost/livekit/sfu",
};
const url = "wss://matrix-rtc.m.localhost/livekit/sfu";
const transport: UnstableLivekitTransport = { type: "livekit", url };
/** The options of a subscriber connection to `transport`. */
function connectionOpts(): ConnectionOpts {
return {
client,
flow: { kind: "csApi", url },
onCsApiMissing: vi.fn(),
roomId: ROOM_ID,
slotId: SLOT_ID,
role: "subscriber",
@@ -372,6 +376,7 @@ describe("Start connection states", () => {
...connectionOpts(),
role: "publisher",
transport: { type: "livekit", livekit_service_url: serviceUrl },
flow: { kind: "openID", serviceUrl },
},
logger,
);
@@ -387,6 +392,49 @@ describe("Start connection states", () => {
expect(connection.livekitAlias).toBe("!example_room_id");
});
it("reports the CS API missing where the homeserver lacks the endpoint", async () => {
setupTest();
const opts = connectionOpts();
client.getLivekitToken.mockRejectedValue(
new MatrixError({ errcode: "M_UNRECOGNIZED" }, 404),
);
const connection = new Connection(opts, logger);
await expect(connection.start()).rejects.toThrow(
expect.any(NoMatrix2AuthorizationService),
);
expect(opts.onCsApiMissing).toHaveBeenCalledOnce();
});
it("does not show as failed when reporting the CS API missing gets it stopped", async () => {
setupTest();
fakeLivekitRoom.disconnect.mockResolvedValue(undefined);
client.getLivekitToken.mockRejectedValue(
new MatrixError({ errcode: "M_UNRECOGNIZED" }, 404),
);
const connection: Connection = new Connection(
{ ...connectionOpts(), onCsApiMissing: () => void connection.stop() },
logger,
);
await connection.start();
await vi.waitFor(() =>
expect(connection.state$.value).toEqual({ state: "stopped" }),
);
});
it("does not report the CS API missing where the homeserver refuses the request", async () => {
setupTest();
const opts = connectionOpts();
client.getLivekitToken.mockRejectedValue(
new MatrixError({ errcode: "M_FORBIDDEN" }, 403),
);
const connection = new Connection(opts, logger);
await expect(connection.start()).rejects.toThrow();
expect(opts.onCsApiMissing).not.toHaveBeenCalled();
});
it("retries a join that failed on the WebSocket in Firefox", async () => {
setupTest();
mockUserAgent(FIREFOX_USER_AGENT);
+29 -10
View File
@@ -32,6 +32,7 @@ import { type CallMembershipIdentityParts } from "matrix-js-sdk/lib/matrixrtc/En
import {
type ClientGetTokenParts,
type ClientOpenIDParts,
type AuthFlow,
type ConnectionRole,
getSFUConfig,
type SFUConfig,
@@ -42,6 +43,7 @@ import {
MatrixRTCError,
InsufficientCapacityError,
LivekitConnectionError,
NoMatrix2AuthorizationService,
PeerConnectionTimeoutError,
SFURoomCreationRestrictedError,
UnknownRTCError,
@@ -58,6 +60,10 @@ export interface ConnectionOpts {
serverName: string;
/** The Matrix client, for the token exchange. */
client: ClientGetTokenParts & ClientOpenIDParts;
/** The flow to authenticate with, for as long as the connection lives. */
flow: AuthFlow;
/** Called when the client-server API flow finds the API missing. */
onCsApiMissing: () => void;
/** The Matrix room the session is in. */
roomId: string;
/** The MatrixRTC slot the session is in. */
@@ -106,6 +112,9 @@ export class Connection {
/** The homeserver the transport belongs to. */
public readonly serverName: string;
/** The flow that issues this connection's tokens. */
public readonly flow: AuthFlow;
public readonly livekitRoom: LivekitRoom;
private scope: ObservableScope;
@@ -134,6 +143,7 @@ export class Connection {
protected stopped = false;
private readonly client: ClientGetTokenParts & ClientOpenIDParts;
private readonly onCsApiMissing: () => void;
private readonly roomId: string;
private readonly slotId: string;
private readonly logger: Logger;
@@ -161,6 +171,8 @@ export class Connection {
this.transport = transport;
this.serverName = serverName;
this.client = client;
this.flow = opts.flow;
this.onCsApiMissing = opts.onCsApiMissing;
this.remoteParticipants$ = scope.behavior(
// Only tracks remote participants
@@ -401,16 +413,23 @@ export class Connection {
}
protected async getSFUConfig(): Promise<SFUConfig> {
return await getSFUConfig({
client: this.client,
membership: this.ownMembershipIdentity,
role: this.role,
transport: this.transport,
serverName: this.serverName,
roomId: this.roomId,
slotId: this.slotId,
logger: this.logger,
});
try {
return await getSFUConfig({
client: this.client,
membership: this.ownMembershipIdentity,
role: this.role,
flow: this.flow,
serverName: this.serverName,
roomId: this.roomId,
slotId: this.slotId,
logger: this.logger,
});
} catch (e) {
// Reported before the error surfaces: where there is a fallback, this
// connection is stopped and replaced, so it never shows as failed
if (e instanceof NoMatrix2AuthorizationService) this.onCsApiMissing();
throw e;
}
}
/**
@@ -18,7 +18,11 @@ import { type PublishRequest } from "../../media-api";
import { constant } from "../../reactive/Behavior";
import { ownMemberMock, testScope } from "../../utils/test";
import { testJWTToken } from "../../utils/test-fixtures";
import { type ClientGetTokenParts, type ClientOpenIDParts } from "./auth";
import {
type ClientGetTokenParts,
type ClientOpenIDParts,
chooseAuthFlow,
} from "./auth";
import {
LivekitConnectionFactory,
type ResolvedConnection,
@@ -50,6 +54,7 @@ function create(
): { connection: ResolvedConnection; options: RoomOptions } {
const factory = new LivekitConnectionFactory(
client(),
() => {},
"!room:example.org",
"m.call#ROOM",
publish,
@@ -62,6 +67,7 @@ function create(
"subscriber",
transport,
"example.org",
chooseAuthFlow(transport, true),
ownMemberMock,
logger,
) as ResolvedConnection;
@@ -24,6 +24,7 @@ import { type PublishRequest } from "../../media-api";
import { type Behavior } from "../../reactive/Behavior";
import { type ObservableScope } from "../../reactive/ObservableScope";
import {
type AuthFlow,
type ClientGetTokenParts,
type ClientOpenIDParts,
type ConnectionRole,
@@ -44,6 +45,7 @@ export interface ConnectionFactory {
role: ConnectionRole,
transport: UnstableLivekitTransport,
serverName: string,
flow: AuthFlow,
ownMembershipIdentity: CallMembershipIdentityParts,
logger: Logger,
): Connection;
@@ -102,6 +104,7 @@ function resolvedTransport(config: SFUConfig): ResolvedTransport {
export class LivekitConnectionFactory implements ConnectionFactory {
public constructor(
private readonly client: ClientGetTokenParts & ClientOpenIDParts,
private readonly onCsApiMissing: () => void,
private readonly roomId: string,
private readonly slotId: string,
private readonly publish: PublishRequest[],
@@ -115,6 +118,7 @@ export class LivekitConnectionFactory implements ConnectionFactory {
role: ConnectionRole,
transport: UnstableLivekitTransport,
serverName: string,
flow: AuthFlow,
ownMembershipIdentity: CallMembershipIdentityParts,
logger: Logger,
): Connection {
@@ -125,7 +129,9 @@ export class LivekitConnectionFactory implements ConnectionFactory {
role,
transport,
serverName,
flow,
client: this.client,
onCsApiMissing: this.onCsApiMissing,
scope,
livekitRoomFactory: () =>
new LivekitRoom(
@@ -16,11 +16,7 @@ import {
mapEpoch,
ObservableScope,
} from "../../reactive/ObservableScope";
import {
createConnectionMap$,
ConnectionMap,
keyFor,
} from "./ConnectionMap.ts";
import { createConnectionMap$, ConnectionMap } from "./ConnectionMap.ts";
import { type ConnectionFactory } from "./ConnectionFactory.ts";
import { type Connection } from "./Connection.ts";
import { ownMemberMock, withTestScheduler } from "../../utils/test";
@@ -43,6 +39,33 @@ const TRANSPORT_2: TransportLocator = {
serverName: "sample.com",
};
const SERVICE_URL_TRANSPORT: TransportLocator = {
transport: {
type: "livekit",
livekit_service_url: "https://jwt.example.org",
},
serverName: "example.org",
};
const URL_TRANSPORT: TransportLocator = {
transport: { type: "livekit", url: "wss://sfu.example.org" },
serverName: "example.org",
};
/** Names the same SFU as URL_TRANSPORT and the same service as SERVICE_URL_TRANSPORT. */
const URL_AND_SERVICE_URL_TRANSPORT: TransportLocator = {
transport: {
type: "livekit",
url: "wss://sfu.example.org",
livekit_service_url: "https://jwt.example.org",
},
serverName: "example.org",
};
/** Tells the locators used here apart; not the key the map folds them by. */
const keyFor = ({ transport, serverName }: TransportLocator): string =>
JSON.stringify([transport, serverName]);
function findConnection(
transport: TransportLocator,
connections: Connection[],
@@ -102,6 +125,7 @@ describe("connections$ stream", () => {
a: new Epoch([TRANSPORT_1, TRANSPORT_2], 0),
}),
logger: logger,
csApiUsable: true,
ownMembershipIdentity: ownMemberMock,
});
@@ -139,6 +163,7 @@ describe("connections$ stream", () => {
a: new Epoch([TRANSPORT_2], 0),
}),
logger: logger,
csApiUsable: true,
ownMembershipIdentity: ownMemberMock,
});
@@ -150,6 +175,7 @@ describe("connections$ stream", () => {
"publisher",
TRANSPORT_1.transport,
TRANSPORT_1.serverName,
{ kind: "openID", serviceUrl: "https://lk.example.org" },
ownMemberMock,
expect.anything(),
);
@@ -158,6 +184,7 @@ describe("connections$ stream", () => {
"subscriber",
TRANSPORT_2.transport,
TRANSPORT_2.serverName,
{ kind: "openID", serviceUrl: "https://lk.sample.com" },
ownMemberMock,
expect.anything(),
);
@@ -181,6 +208,7 @@ describe("connections$ stream", () => {
a: new Epoch([sameServiceElsewhere], 0),
}),
logger: logger,
csApiUsable: true,
ownMembershipIdentity: ownMemberMock,
});
@@ -198,6 +226,7 @@ describe("connections$ stream", () => {
"publisher",
TRANSPORT_1.transport,
"example.org",
{ kind: "openID", serviceUrl: "https://lk.example.org" },
expect.anything(),
expect.anything(),
);
@@ -225,6 +254,7 @@ describe("connections$ stream", () => {
a: new Epoch([sameUrlElsewhere], 0),
}),
logger: logger,
csApiUsable: true,
ownMembershipIdentity: ownMemberMock,
});
@@ -243,42 +273,43 @@ describe("connections$ stream", () => {
});
});
test("Shares connection between local livekit_service_url transport and remote url + livekit_service_url transport", () => {
withTestScheduler(({ behavior, expectObservable, scope }) => {
const serviceUrlTransport: TransportLocator = {
transport: {
type: "livekit",
livekit_service_url: "https://jwt.example.org",
},
serverName: "example.org",
};
const urlAndServiceUrlTransport: TransportLocator = {
transport: {
type: "livekit",
livekit_service_url: "https://jwt.example.org",
url: "wss://sfu.elsewhere.org",
},
// Should pass even if local server != remote server
serverName: "elsewhere.org",
};
test("Shares connection between url transport and url + livekit_service_url transport", () => {
withTestScheduler(({ expectObservable, scope }) => {
const connectionMap$ = createConnectionMap$({
scope,
connectionFactory: fakeConnectionFactory,
localTransport: serviceUrlTransport,
remoteTransports$: constant(new Epoch([urlAndServiceUrlTransport])),
localTransport: URL_AND_SERVICE_URL_TRANSPORT,
remoteTransports$: constant(
new Epoch([URL_TRANSPORT, SERVICE_URL_TRANSPORT]),
),
csApiUsable: true,
logger,
ownMembershipIdentity: ownMemberMock,
});
expectObservable(
connectionMap$.pipe(mapEpoch((d) => d.getConnections())),
).toBe("a", {
a: expect.toSatisfy(({ value: cs }: Epoch<Connection[]>) => {
// One connection total, since local and remote connections are shared
expect(cs.length).toBe(1);
expect(findConnection(serviceUrlTransport, cs)).toBeDefined();
expect(findConnection(serviceUrlTransport, cs)).toBe(
findConnection(urlAndServiceUrlTransport, cs),
expectObservable(connectionMap$).toBe("a", {
a: expect.toSatisfy(({ value: map }: Epoch<ConnectionMap>) => {
// Both get the CS API flow, and with it the same identity on the
// same SFU. The JWT service assigns another, so it may stay apart.
expect(map.getConnections().length).toBe(2);
const shared = map.getConnectionForTransport(
URL_AND_SERVICE_URL_TRANSPORT,
);
expect(shared).not.toBeNull();
expect(map.getConnectionForTransport(URL_TRANSPORT)).toBe(shared);
expect(map.getConnectionForTransport(SERVICE_URL_TRANSPORT)).not.toBe(
shared,
);
expect(
vi.mocked(fakeConnectionFactory).createConnection,
).toHaveBeenCalledWith(
expect.anything(),
"publisher",
URL_AND_SERVICE_URL_TRANSPORT.transport,
"example.org",
{ kind: "csApi", url: "wss://sfu.example.org" },
ownMemberMock,
expect.anything(),
);
return true;
}),
@@ -286,44 +317,35 @@ describe("connections$ stream", () => {
});
});
test("Shares connection between remote livekit_service_url transport and remote url + livekit_service_url transport", () => {
withTestScheduler(({ behavior, expectObservable, scope }) => {
const serviceUrlTransport: TransportLocator = {
transport: {
type: "livekit",
livekit_service_url: "https://jwt.example.org",
},
serverName: "example.org",
};
const urlAndServiceUrlTransport: TransportLocator = {
transport: {
type: "livekit",
livekit_service_url: "https://jwt.example.org",
url: "wss://sfu.elsewhere.org",
},
// Should pass even if local server != remote server
serverName: "elsewhere.org",
};
test("Shares connection between livekit_service_url transport and url + livekit_service_url transport without the CS API", () => {
withTestScheduler(({ expectObservable, scope }) => {
const connectionMap$ = createConnectionMap$({
scope,
connectionFactory: fakeConnectionFactory,
localTransport: TRANSPORT_2,
localTransport: SERVICE_URL_TRANSPORT,
remoteTransports$: constant(
new Epoch([serviceUrlTransport, urlAndServiceUrlTransport]),
new Epoch([
{
...URL_AND_SERVICE_URL_TRANSPORT,
// Should pass even if local server != remote server
serverName: "elsewhere.org",
},
]),
),
csApiUsable: false,
logger,
ownMembershipIdentity: ownMemberMock,
});
expectObservable(
connectionMap$.pipe(mapEpoch((d) => d.getConnections())),
).toBe("a", {
a: expect.toSatisfy(({ value: cs }: Epoch<Connection[]>) => {
// Two connections total: a local connection and a shared remote connection
expect(cs.length).toBe(2);
expect(findConnection(serviceUrlTransport, cs)).toBeDefined();
expect(findConnection(serviceUrlTransport, cs)).toBe(
findConnection(urlAndServiceUrlTransport, cs),
expectObservable(connectionMap$).toBe("a", {
a: expect.toSatisfy(({ value: map }: Epoch<ConnectionMap>) => {
// One connection total, since both go through the same JWT service
expect(map.getConnections().length).toBe(1);
expect(
map.getConnectionForTransport(SERVICE_URL_TRANSPORT),
).not.toBeNull();
expect(map.getConnectionForTransport(SERVICE_URL_TRANSPORT)).toBe(
map.getConnectionForTransport(URL_AND_SERVICE_URL_TRANSPORT),
);
return true;
}),
@@ -331,6 +353,30 @@ describe("connections$ stream", () => {
});
});
test("Publishes on a url + livekit_service_url transport through the JWT service without the CS API", () => {
createConnectionMap$({
scope: testScope,
connectionFactory: fakeConnectionFactory,
localTransport: URL_AND_SERVICE_URL_TRANSPORT,
remoteTransports$: constant(new Epoch([])),
csApiUsable: false,
logger,
ownMembershipIdentity: ownMemberMock,
});
expect(
vi.mocked(fakeConnectionFactory).createConnection,
).toHaveBeenCalledExactlyOnceWith(
expect.anything(),
"publisher",
URL_AND_SERVICE_URL_TRANSPORT.transport,
"example.org",
{ kind: "openID", serviceUrl: "https://jwt.example.org" },
ownMemberMock,
expect.anything(),
);
});
test("Should start connection only once", () => {
withTestScheduler(({ behavior, expectObservable }) => {
const connectionMap$ = createConnectionMap$({
@@ -346,6 +392,7 @@ describe("connections$ stream", () => {
f: new Epoch([TRANSPORT_1, TRANSPORT_2], 5),
}),
logger: logger,
csApiUsable: true,
ownMembershipIdentity: ownMemberMock,
});
@@ -386,6 +433,7 @@ describe("connections$ stream", () => {
c: new Epoch([TRANSPORT_1], 2),
}),
logger: logger,
csApiUsable: true,
ownMembershipIdentity: ownMemberMock,
});
@@ -424,7 +472,7 @@ describe("connections$ stream", () => {
describe("ConnectionMap", () => {
test("warns when a second connection to the same URL is merged", () => {
const warn = vi.spyOn(logger, "warn").mockImplementation(() => {});
const data = new ConnectionMap(logger);
const data = new ConnectionMap(true, logger);
const connection = TRANSPORT_1 as unknown as Connection;
const p = (identity: string): RemoteParticipant =>
({ identity }) as unknown as RemoteParticipant;
@@ -525,6 +573,7 @@ describe("connectionMap$", () => {
a: new Epoch([TRANSPORT_1, TRANSPORT_2], 0),
}),
logger,
csApiUsable: true,
ownMembershipIdentity: ownMemberMock,
});
+53 -56
View File
@@ -18,32 +18,29 @@ import {
type ObservableScope,
} from "../../reactive/ObservableScope";
import { generateItemsWithEpoch } from "../../reactive/observable";
import {
chooseAuthFlow,
type ConnectionRole,
type TransportLocator,
} from "./auth";
import { chooseAuthFlow, type TransportLocator } from "./auth";
import { type Connection } from "./Connection";
import { type ConnectionFactory } from "./ConnectionFactory";
// Branded, so that only values returned by `keyFor` can be used as keys
export type TransportKey = string & { __transportKey: true };
type TransportKey = string & { __transportKey: true };
/**
* Converts a {@link TransportLocator} to a key suitable for identifying it in a
* map of connections.
*
* @param csApiUsable - Whether the map it is for uses the client-server API
* where a transport leaves the choice.
*/
export function keyFor({
transport,
serverName,
}: TransportLocator): TransportKey {
function keyFor(
{ transport, serverName }: TransportLocator,
csApiUsable: boolean,
): TransportKey {
// Base the key on the auth flow we would use, so that we never create two
// connections that share the same auth details. (That would be bad, as we
// might then try to connect to the same SFU twice with the same participant
// ID, resulting in only one working connection.)
// TODO: This strategy will not work once `chooseAuthFlow` begins allowing for
// falling back from the CS API flow to the OpenID flow.
const flow = chooseAuthFlow(transport);
const flow = chooseAuthFlow(transport, csApiUsable);
// Serialize the fields in a consistent order
return JSON.stringify([
flow.kind,
@@ -52,18 +49,6 @@ export function keyFor({
]) as TransportKey;
}
function removeDuplicateTransports(
transports: TransportLocator[],
): TransportLocator[] {
// The first locator wins, so the local one stays first in the list
const map = new Map<TransportKey, TransportLocator>();
for (const transport of transports) {
const key = keyFor(transport);
if (!map.has(key)) map.set(key, transport);
}
return [...map.values()];
}
/** The connections at one moment, with the remote participants seen on each. */
export class ConnectionMap {
private readonly map = new Map<
@@ -71,10 +56,16 @@ export class ConnectionMap {
{ connection: Connection; participants: RemoteParticipant[] }
>();
public constructor(private readonly logger?: Logger) {}
/**
* @param csApiUsable - What the connections were keyed with.
*/
public constructor(
private readonly csApiUsable = true,
private readonly logger?: Logger,
) {}
public add(connection: Connection, participants: RemoteParticipant[]): void {
const key = keyFor(connection);
const key = keyFor(connection, this.csApiUsable);
const existing = this.map.get(key);
if (!existing) {
this.map.set(key, { connection, participants });
@@ -95,13 +86,15 @@ export class ConnectionMap {
public getConnectionForTransport(
transport: TransportLocator,
): Connection | null {
return this.map.get(keyFor(transport))?.connection ?? null;
const key = keyFor(transport, this.csApiUsable);
return this.map.get(key)?.connection ?? null;
}
public getParticipantsForTransport(
transport: TransportLocator,
): RemoteParticipant[] {
return this.map.get(keyFor(transport))?.participants ?? [];
const key = keyFor(transport, this.csApiUsable);
return this.map.get(key)?.participants ?? [];
}
}
@@ -112,6 +105,11 @@ interface Props {
localTransport: TransportLocator;
/** Every transport some member is on, deduplicated against the local one. */
remoteTransports$: Behavior<Epoch<TransportLocator[]>>;
/**
* Whether a transport naming both a `url` and a `livekit_service_url` is
* reached through the client-server API. Fixed for the life of the map.
*/
csApiUsable: boolean;
logger: Logger;
ownMembershipIdentity: CallMembershipIdentityParts;
}
@@ -126,46 +124,45 @@ export function createConnectionMap$({
connectionFactory,
localTransport,
remoteTransports$,
csApiUsable,
logger: parentLogger,
ownMembershipIdentity,
}: Props): Behavior<Epoch<ConnectionMap>> {
const logger = parentLogger.getChild("[ConnectionMap]");
const localAndRemoteTransports$: Behavior<Epoch<TransportLocator[]>> =
scope.behavior(
remoteTransports$.pipe(
mapEpoch((remoteTransports) =>
removeDuplicateTransports([localTransport, ...remoteTransports]),
),
tap((transports) =>
logger.debug("localAndRemoteTransports$ = ", transports),
),
const transportsByKey$ = scope.behavior(
remoteTransports$.pipe(
mapEpoch(
(remote) =>
// The last locator wins a key, so the local one goes last
new Map(
[...remote, localTransport].map((transport) => [
keyFor(transport, csApiUsable),
transport,
]),
),
),
);
const localTransportKey = keyFor(localTransport);
tap(({ value }) =>
logger.debug("transportsByKey$ = ", [...value.values()]),
),
),
);
const localTransportKey = keyFor(localTransport, csApiUsable);
const connections$ = scope.behavior(
localAndRemoteTransports$.pipe(
transportsByKey$.pipe(
generateItemsWithEpoch(
"ConnectionMap connections$",
function* (transports) {
for (const transport of transports) {
const role: ConnectionRole =
keyFor(transport) === localTransportKey
? "publisher"
: "subscriber";
// The locator is an object, so a stable key stands in for it
yield { keys: [role, keyFor(transport)], data: transport };
}
},
(scope, locator$, role, _key) => {
// The locator is an object, so a stable key stands in for it
(byKey) => Array.from(byKey, ([key, data]) => ({ keys: [key], data })),
(scope, locator$, key) => {
const { transport, serverName } = locator$.value;
const connection = connectionFactory.createConnection(
scope,
role,
key === localTransportKey ? "publisher" : "subscriber",
transport,
serverName,
chooseAuthFlow(transport, csApiUsable),
ownMembershipIdentity,
logger,
);
@@ -181,7 +178,7 @@ export function createConnectionMap$({
connections$.pipe(
switchMap(({ value: connections, epoch }) => {
if (connections.length === 0)
return of(new Epoch(new ConnectionMap(), epoch));
return of(new Epoch(new ConnectionMap(csApiUsable), epoch));
return combineLatest(
connections.map((connection) =>
connection.remoteParticipants$.pipe(
@@ -189,7 +186,7 @@ export function createConnectionMap$({
),
),
(...list) => {
const map = new ConnectionMap(logger);
const map = new ConnectionMap(csApiUsable, logger);
for (const item of list)
map.add(item.connection, item.participants);
return new Epoch(map, epoch);
@@ -148,7 +148,6 @@ describe("toMediaConnectionState", () => {
describe("createLivekitBackend", () => {
const homeserver = "https://matrix.example.org";
const homeserverEndpoint = `${homeserver}/_matrix/client/unstable/io.element.msc4195/rtc/livekit/delegate_delayed_leave`;
const urlTransport: UnstableLivekitTransport = {
type: "livekit",
url: "wss://sfu.example.org",
@@ -169,6 +168,7 @@ describe("createLivekitBackend", () => {
participants$: BehaviorSubject<RemoteParticipant[]>;
state$: BehaviorSubject<ConnectionState>;
}[];
let onCsApiMissing: () => void;
const connected: ConnectionState = {
state: "authenticated",
livekitState: LivekitConnectionState.Connected,
@@ -177,13 +177,15 @@ describe("createLivekitBackend", () => {
/** Stands in for the factory: connections whose state and participants the test drives. */
function stubFactory(initialState: ConnectionState): void {
vi.spyOn(connectionFactory, "LivekitConnectionFactory").mockImplementation(
function (this: unknown) {
function (this: unknown, _client, onMissing) {
onCsApiMissing = onMissing;
return {
createConnection: (
scope: ObservableScope,
role: auth.ConnectionRole,
transport: UnstableLivekitTransport,
serverName: string,
flow: auth.AuthFlow,
): Connection => {
const participants$ = new BehaviorSubject<RemoteParticipant[]>([]);
const state$ = new BehaviorSubject<ConnectionState>(initialState);
@@ -191,6 +193,7 @@ describe("createLivekitBackend", () => {
role,
transport,
serverName,
flow,
state$,
remoteParticipants$: scope.behavior(participants$),
livekitRoom: fakeLivekitRoom(),
@@ -232,17 +235,15 @@ describe("createLivekitBackend", () => {
}
// Delegation goes through whichever service authenticates us as a
// publisher: the JWT service wherever the transport names one, the
// homeserver for a `url` alone
// publisher.
it.each([
["the JWT service", exampleTransport, 404, 401, true],
["the JWT service, and only it", bothTransport, 401, 404, false],
["the homeserver", urlTransport, 401, 404, true],
["neither", exampleTransport, 404, 404, false],
["a JWT service that delegates", exampleTransport, 401, true],
["a JWT service that does not", exampleTransport, 404, false],
["the homeserver over the JWT service", bothTransport, 404, true],
["the homeserver", urlTransport, 404, true],
])(
"prepares the local transport and asks %s about delegation",
async (_name, transport, homeserverStatus, serviceStatus, expected) => {
fetchMock.post(homeserverEndpoint, homeserverStatus);
"prepares the local transport for delegation through %s",
async (_name, transport, serviceStatus, expected) => {
fetchMock.post(
`${exampleServiceUrl}/delegate_delayed_leave`,
serviceStatus,
@@ -251,6 +252,10 @@ describe("createLivekitBackend", () => {
const capabilities = await backend().prepareLocalTransport(transport);
expect(capabilities).toEqual({ canDelegateDelayedLeave: expected });
// Only the service that issued the publisher's token is asked.
expect(
fetchMock.called(`${exampleServiceUrl}/delegate_delayed_leave`),
).toBe(transport === exampleTransport);
expect(connections).toHaveLength(1);
expect(connections[0].connection.role).toBe("publisher");
expect(connections[0].connection.transport).toEqual(transport);
@@ -259,9 +264,8 @@ describe("createLivekitBackend", () => {
);
it("prepares a remote SFU's transport on its homeserver, where delegation is not possible", async () => {
// Our own homeserver would delegate, so only the SFU being remote can
// explain delegation being skipped
fetchMock.post(homeserverEndpoint, 401);
// A token through the homeserver means delegation, unless the SFU is
// another homeserver's.
const remoteTransport: UnstableLivekitTransport = {
type: "livekit",
url: "wss://sfu.sample.com",
@@ -276,7 +280,6 @@ describe("createLivekitBackend", () => {
});
it("waits for the publisher connection to hold its token before the join", async () => {
fetchMock.post(homeserverEndpoint, 404);
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 404);
stubFactory({ state: "authenticating" });
@@ -293,7 +296,6 @@ describe("createLivekitBackend", () => {
});
it("fails the preparation with the publisher connection's error", async () => {
fetchMock.post(homeserverEndpoint, 404);
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 404);
stubFactory({ state: "authenticating" });
const preparing = backend().prepareLocalTransport(exampleTransport);
@@ -303,8 +305,60 @@ describe("createLivekitBackend", () => {
await expect(preparing).rejects.toBe(error);
});
it.each([
["names no JWT service", urlTransport],
["names no url", exampleTransport],
])(
"keeps its connections where the CS API is found missing and our transport %s",
async (_what, transport) => {
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 404);
await backend().prepareLocalTransport(transport);
onCsApiMissing();
expect(connections).toHaveLength(1);
},
);
it("moves the publisher to the JWT service where the CS API is found missing", async () => {
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 401);
const delegate = vi.spyOn(auth, "delegateDelayedLeave").mockResolvedValue();
stubFactory({ state: "authenticating" });
const b = backend();
let prepared = false;
const preparing = b.prepareLocalTransport(bothTransport).then((c) => {
prepared = true;
return c;
});
await flushPromises();
expect(connections).toHaveLength(1);
expect(connections[0].connection.flow.kind).toBe("csApi");
// The publisher's token request finds no API.
onCsApiMissing();
expect(connections).toHaveLength(2);
expect(connections[1].connection.role).toBe("publisher");
expect(connections[1].connection.transport).toEqual(bothTransport);
expect(connections[1].connection.flow.kind).toBe("openID");
// The replaced connection winding down is not the preparation failing.
connections[0].state$.next({ state: "stopped" });
await flushPromises();
expect(prepared).toBe(false);
connections[1].state$.next(connected);
expect(await preparing).toEqual({ canDelegateDelayedLeave: true });
expect(
fetchMock.called(`${exampleServiceUrl}/delegate_delayed_leave`),
).toBe(true);
await b.delegateDelayedLeave("delay-1");
expect(delegate.mock.calls[0][0].flow).toEqual({
kind: "openID",
serviceUrl: exampleServiceUrl,
});
});
it("delegates the leave through the flow that authenticated the publisher", async () => {
fetchMock.post(homeserverEndpoint, 401);
const delegate = vi.spyOn(auth, "delegateDelayedLeave").mockResolvedValue();
const b = backend();
await expect(b.delegateDelayedLeave("delay-1")).rejects.toThrow(
@@ -318,7 +372,7 @@ describe("createLivekitBackend", () => {
expect.objectContaining({
client,
membership: ownMemberMock,
transport: urlTransport,
flow: { kind: "csApi", url: "wss://sfu.example.org" },
roomId: "!room:example.org",
slotId: "m.call#ROOM",
delayId: "delay-1",
@@ -344,7 +398,6 @@ describe("createLivekitBackend", () => {
userId: "@bob:example.org",
deviceId: "DEV000",
memberId: legacyId,
matrixEventId$: constant("$bob"),
transport$: constant({
type: "livekit",
id: JSON.stringify(transport),
@@ -360,7 +413,6 @@ describe("createLivekitBackend", () => {
async function prepared(): Promise<
ReturnType<typeof createLivekitBackend>
> {
fetchMock.post(homeserverEndpoint, 404);
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 404);
const b = backend();
await b.prepareLocalTransport(bothTransport);
@@ -392,6 +444,30 @@ describe("createLivekitBackend", () => {
},
);
it("reaches a url + livekit_service_url member through the JWT service where our transport names no url", async () => {
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 404);
const b = backend();
await b.prepareLocalTransport(exampleTransport);
const media = b.mediaFor(
testScope(),
bob(bothTransport, [hashedId, legacyId]),
);
await flushPromises();
// Bob names our JWT service, so no connection of his own, and none
// through a client-server API our homeserver does not have
expect(connections).toHaveLength(1);
expect(connections[0].connection.flow.kind).toBe("openID");
connections[0].participants$.next([
mockRemoteParticipant({
identity: hashedId,
trackPublications: new Map(),
}),
]);
await flushPromises();
expect(media.tracks$.value).toEqual([]);
});
it("does not match a member with two candidate identities to anyone else", async () => {
const b = await prepared();
const media = b.mediaFor(
@@ -463,10 +539,11 @@ describe("createLivekitBackend", () => {
(c) => c.connection.role === "subscriber",
);
expect(remote?.connection.transport).toEqual(otherTransport);
expect(b.connections$.value.map(({ transport }) => transport)).toEqual([
bothTransport,
otherTransport,
]);
const transports = b.connections$.value.map(({ transport }) => transport);
expect(transports).toHaveLength(2);
expect(transports).toEqual(
expect.arrayContaining([bothTransport, otherTransport]),
);
transport$.next(bob(bothTransport, [legacyId]).transport$.value);
await flushPromises();
+85 -61
View File
@@ -18,6 +18,7 @@ import {
filter,
firstValueFrom,
map,
NEVER,
type Observable,
of,
switchMap,
@@ -41,18 +42,9 @@ import {
type MediaBackendContext,
type TransportCapabilities,
} from "../api";
import {
chooseAuthFlow,
delegateDelayedLeave,
type TransportLocator,
} from "./auth";
import { delegateDelayedLeave, type TransportLocator } from "./auth";
import { type Connection } from "./Connection";
import {
ConnectionMap,
createConnectionMap$,
keyFor,
type TransportKey,
} from "./ConnectionMap";
import { ConnectionMap, createConnectionMap$ } from "./ConnectionMap";
import {
LivekitConnectionFactory,
ResolvedConnection,
@@ -66,10 +58,20 @@ import {
} from "./LivekitMemberMedia";
import { createLivekitLocalMedia } from "./LocalMedia";
/** The transport we publish on, with what is fixed for its connection map. */
interface LocalTransport extends TransportLocator {
/**
* Whether a transport naming both a `url` and a `livekit_service_url` is
* reached through the client-server API: where ours names a `url`, until
* a connection finds the API missing.
*/
csApiUsable: boolean;
}
export interface LivekitBackendOptions {
/**
* `getOpenIdToken` for the JWT service flow, the MSC4195 methods for the
* client-server API flow, `baseUrl` for the delegation probe and handover.
* client-server API flow, `baseUrl` for the delegation handover.
*/
client: Pick<
MatrixClient,
@@ -103,12 +105,20 @@ export function createLivekitBackend(
: [requestsOrMedia.requests, requestsOrMedia];
const keyProvider = createKeyProvider(encryptionSystem, mediaKeys$, logger);
const transports = createTransportRegistry(scope);
const localTransport$ = new BehaviorSubject<TransportLocator | null>(null);
const localTransport$ = new BehaviorSubject<LocalTransport | null>(null);
const audioOutputDeviceId$ = new BehaviorSubject<string | undefined>(
undefined,
);
const connectionFactory = new LivekitConnectionFactory(
client,
// The MSC defines no unstable feature flag, so a homeserver that
// advertises a `url` without the API shows in a token request. Where our
// transport names a JWT service too, start over without the API.
() => {
const local = localTransport$.value;
if (local?.csApiUsable && "livekit_service_url" in local.transport)
localTransport$.next({ ...local, csApiUsable: false });
},
roomId,
slotId,
publish,
@@ -118,7 +128,8 @@ export function createLivekitBackend(
);
// A new map, in a scope of its own, whenever the local transport changes:
// the publisher role sits on one connection, and which one is fixed per map
// the publisher role sits on one connection, and which one is fixed per map,
// as is whether the client-server API is usable
const connectionMap$ = scope.behavior<Epoch<ConnectionMap>>(
mapScoped(scope, localTransport$, (mapScope, localTransport) =>
createConnectionMap$({
@@ -126,6 +137,7 @@ export function createLivekitBackend(
connectionFactory,
localTransport,
remoteTransports$: transports.transports$,
csApiUsable: localTransport.csApiUsable,
logger,
ownMembershipIdentity,
}),
@@ -143,13 +155,6 @@ export function createLivekitBackend(
logger,
});
// Probed once: the answer cannot change within a session
const homeserverSupportsDelegation = supportsDelegation(
`${client.baseUrl}/_matrix/client/unstable/io.element.msc4195/rtc/livekit/delegate_delayed_leave`,
"homeserver",
logger,
);
const ownServerName = serverNameOf(ownMembershipIdentity.userId);
const prepareLocalTransport = async (
@@ -162,45 +167,45 @@ export function createLivekitBackend(
ownMembershipIdentity.userId,
);
const locator: TransportLocator = { transport, serverName };
let canDelegate: Promise<boolean>;
// A homeserver with the client-server API advertises a `url`
localTransport$.next({ ...locator, csApiUsable: "url" in transport });
// The membership is only sent once the publisher connection holds its
// token, so that the LiveKit room exists before anyone subscribes to it:
// a subscriber lacks the permission to create it and would fail without
// retrying
const { flow } = await authenticated(localMedia_.connection$);
if (serverName !== ownServerName) {
// Our homeserver only takes over leaves for its own SFUs
logger.info(
`Publishing on a remote SFU of ${serverName}, delegation is not possible`,
);
canDelegate = Promise.resolve(false);
} else {
// Check for support using the same auth flow that we intend to use later
const flow = chooseAuthFlow(transport);
canDelegate =
flow.kind === "openID"
? supportsDelegation(
`${flow.serviceUrl}/delegate_delayed_leave`,
`transport ${flow.serviceUrl}`,
logger,
)
: homeserverSupportsDelegation;
return { canDelegateDelayedLeave: false };
}
localTransport$.next(locator);
// The membership is only sent once the publisher connection holds its
// token, so that the LiveKit room exists before anyone subscribes to it:
// a subscriber lacks the permission to create it and would fail without
// retrying
const [, canDelegateDelayedLeave] = await Promise.all([
authenticated(localMedia_.connection$),
canDelegate,
]);
return { canDelegateDelayedLeave };
// Delegation goes through the flow that authenticated us
if (flow.kind === "csApi") {
// If the client-server authentication endpoint is available, the delegation
// endpoint is available, too. Both have been released together in lk-jwt-service.
return { canDelegateDelayedLeave: true };
}
// The OpenID flow was used but the lk-jwt-instance may still predate delegation. Check
// if the delegation endpoint is supported.
return {
canDelegateDelayedLeave: await supportsDelegation(
`${flow.serviceUrl}/delegate_delayed_leave`,
`transport ${flow.serviceUrl}`,
logger,
),
};
};
const delegateLeave = async (delayId: string): Promise<void> => {
const local = localTransport$.value;
if (local === null)
const connection = localMedia_.connection$.value;
if (connection === null)
throw new MatrixRTCError("No local transport to delegate the leave to");
await delegateDelayedLeave({
client,
membership: ownMembershipIdentity,
transport: local.transport,
flow: connection.flow,
roomId,
slotId,
delayId,
@@ -225,7 +230,9 @@ export function createLivekitBackend(
}
: undefined;
}),
distinctUntilChanged((a, b) => (a && keyFor(a)) === (b && keyFor(b))),
distinctUntilChanged(
(a, b) => (a && registryKeyFor(a)) === (b && registryKeyFor(b)),
),
),
);
transports.follow(memberScope, locator$);
@@ -292,27 +299,31 @@ export function createLivekitBackend(
};
}
/** Resolves once the connection holds its token; rejects with its error otherwise. */
/** Resolves with the connection once it holds its token; rejects with its error otherwise. */
async function authenticated(
connection$: Behavior<Connection | null>,
): Promise<void> {
const state = await firstValueFrom(
): Promise<Connection> {
const { connection, state } = await firstValueFrom(
connection$.pipe(
switchMap((connection) => connection?.state$ ?? of(null)),
switchMap(
(connection) =>
connection?.state$.pipe(map((state) => ({ connection, state }))) ??
NEVER,
),
filter(
(state) =>
state !== null &&
(state.state === "authenticated" ||
state.state === "error" ||
state.state === "stopped"),
({ state }) =>
state.state === "authenticated" ||
state.state === "error" ||
state.state === "stopped",
),
),
);
if (state?.state === "error") throw state.error;
if (state?.state === "stopped")
if (state.state === "error") throw state.error;
if (state.state === "stopped")
throw new MatrixRTCError(
"The local connection stopped before it was authenticated",
);
return connection;
}
function backendConnection$(
@@ -331,6 +342,19 @@ function backendConnection$(
);
}
/**
* The key used for a transport locator in the transport registry.
*
* Note that this is *not* the key used for folding locators into connections.
*/
function registryKeyFor({ transport, serverName }: TransportLocator): string {
return JSON.stringify([
"url" in transport ? transport.url : null,
"livekit_service_url" in transport ? transport.livekit_service_url : null,
serverName,
]);
}
export interface TransportRegistry {
/** Keeps a member's transport registered for as long as its scope lives. */
follow(
@@ -350,7 +374,7 @@ export function createTransportRegistry(
scope: ObservableScope,
): TransportRegistry {
const counts = new Map<
TransportKey,
string,
{ locator: TransportLocator; count: number }
>();
const transports = new BehaviorSubject<TransportLocator[]>([]);
@@ -358,7 +382,7 @@ export function createTransportRegistry(
transports.next([...counts.values()].map(({ locator }) => locator));
const register = (locator: TransportLocator): (() => void) => {
const key = keyFor(locator);
const key = registryKeyFor(locator);
const entry = counts.get(key) ?? { locator, count: 0 };
entry.count++;
if (entry.count === 1) {
@@ -210,11 +210,7 @@ describe("createLivekitMediaTrack", () => {
await expect(track.setEnabled(false)).resolves.toBe(false);
expect(setEnabled).toHaveBeenCalledWith("microphone", false);
await track.setDevice("mic-2");
expect(switchActiveDevice).toHaveBeenCalledWith(
"audioinput",
"mic-2",
true,
);
expect(switchActiveDevice).toHaveBeenCalledWith("audioinput", "mic-2");
});
// LiveKit's media stream track is the processed one while a processor runs,
@@ -257,61 +253,36 @@ describe("createLivekitMediaTrack", () => {
await track.setDevice(deviceId);
expect(switchActiveDevice.mock.calls).toEqual(
switches ? [["videoinput", deviceId, true]] : [],
switches ? [["videoinput", deviceId]] : [],
);
},
);
it("rejects where the camera did not move to the device asked for, and returns to the one it had", async () => {
const switchActiveDevice = vi.fn().mockResolvedValue(true);
const track = localCameraOn(scope, "cam-1", switchActiveDevice);
it("rejects where the camera did not move to the device asked for", async () => {
const camera = Object.assign(Object.create(LocalVideoTrack.prototype), {
source: Track.Source.Camera,
_mediaStreamTrack: {
readyState: "live",
label: "",
getSettings: () => ({ deviceId: "cam-1" }),
},
}) as LocalVideoTrack;
const { participant, publication, room } = fakes({
track: camera as unknown as FakeTrack,
});
const track = createLocalLivekitMediaTrack(
scope,
Object.assign(participant, {
isLocal: true,
}) as unknown as LocalParticipant,
publication as unknown as TrackPublication,
Object.assign(room, {
switchActiveDevice: vi.fn().mockResolvedValue(true),
}),
vi.fn(),
);
await expect(track.setDevice("cam-2")).rejects.toThrow("another device");
expect(switchActiveDevice.mock.calls).toEqual([
["videoinput", "cam-2", true],
["videoinput", "cam-1", true],
]);
});
it("returns to the device it had where the one asked for does not open", async () => {
const gone = new Error("gone");
const switchActiveDevice = vi
.fn()
.mockRejectedValueOnce(gone)
.mockResolvedValue(true);
const track = localCameraOn(scope, "cam-1", switchActiveDevice);
await expect(track.setDevice("cam-2")).rejects.toBe(gone);
expect(switchActiveDevice).toHaveBeenLastCalledWith(
"videoinput",
"cam-1",
true,
);
});
it("reports the switch that failed where the return fails too", async () => {
const gone = new Error("gone");
const switchActiveDevice = vi
.fn()
.mockRejectedValueOnce(gone)
.mockRejectedValue(new Error("busy"));
const track = localCameraOn(scope, "cam-1", switchActiveDevice);
await expect(track.setDevice("cam-2")).rejects.toBe(gone);
});
// It is stopped, and opens the device LiveKit remembers on turning on
it("does not return a camera that is off to its device", async () => {
const switchActiveDevice = vi.fn().mockRejectedValue(new Error("gone"));
const track = localCameraOn(scope, "cam-1", switchActiveDevice, {
isMuted: true,
});
await expect(track.setDevice("cam-2")).rejects.toThrow("gone");
expect(switchActiveDevice).toHaveBeenCalledOnce();
});
it("takes the facing mode of a processed camera from the camera", async () => {
@@ -412,36 +383,6 @@ function fakeTrack(): FakeTrack {
}) as FakeTrack;
}
/** Our own camera, open on a device, in a room whose device switch the test decides. */
function localCameraOn(
scope: ObservableScope,
deviceId: string,
switchActiveDevice: LivekitRoom["switchActiveDevice"],
state: { isMuted?: boolean } = {},
): LocalVideoMediaTrack {
const camera = Object.assign(Object.create(LocalVideoTrack.prototype), {
source: Track.Source.Camera,
_mediaStreamTrack: {
readyState: "live",
label: "",
getSettings: () => ({ deviceId }),
},
...state,
}) as LocalVideoTrack;
const { participant, publication, room } = fakes({
track: camera as unknown as FakeTrack,
});
return createLocalLivekitMediaTrack(
scope,
Object.assign(participant, {
isLocal: true,
}) as unknown as LocalParticipant,
publication as unknown as TrackPublication,
Object.assign(room, { switchActiveDevice }),
vi.fn(),
) as LocalVideoMediaTrack;
}
function fakes({
track = fakeTrack(),
kind = Track.Kind.Video,
@@ -203,35 +203,32 @@ export function createLocalLivekitMediaTrack(
// of the camera track itself: with a processor on, LiveKit's media
// stream track is the processed one, which names no device
const current = publication.track;
const previous =
current instanceof LocalTrack
? await current.getDeviceId(false)
if (
current instanceof LocalTrack &&
(await current.getDeviceId(false)) === deviceId
)
return;
// THE FIX for "cannot switch cameras in Chrome" (#4479), switching in
// the call. No third argument: LiveKit then asks for the device with
// `exact`. Passing `false` there made it a wish, which Chromium ignores
// by reopening its default device.
await room.switchActiveDevice(
base.kind === "audio" ? "audioinput" : "videoinput",
deviceId,
);
// A check that the switch really happened, so that a failure is an
// error and not silence. Asked of the track again rather than taken
// from LiveKit's answer, which compares against the processed track
// too. A muted track is stopped and takes the device on turning on again
const now = publication.track;
const deviceNow =
now instanceof LocalTrack && !now.isMuted
? await now.getDeviceId(false)
: undefined;
if (previous === deviceId) return;
const kind = base.kind === "audio" ? "audioinput" : "videoinput";
try {
// Exact: asked for as a preference, the browser may open another
// device that fits the rest of the constraints better
await room.switchActiveDevice(kind, deviceId, true);
// A check that the switch really happened, so that a failure is an
// error and not silence. Asked of the track again rather than taken
// from LiveKit's answer, which compares against the processed track
// too. A muted track is stopped and takes the device on turning on again
const deviceNow = await openDevice(publication.track);
if (deviceNow !== undefined && deviceNow !== deviceId)
throw new MatrixRTCError(
`The ${base.source} is on another device than the one asked for`,
);
} catch (e) {
// LiveKit stops the track before it opens the device asked for, so a
// switch that fails leaves nothing running
if (previous !== undefined && !isMuted(publication.track))
// The failed switch is the error to report, not this one
await room
.switchActiveDevice(kind, previous, true)
.catch(() => undefined);
throw e;
}
if (deviceNow !== undefined && deviceNow !== deviceId)
throw new MatrixRTCError(
`The ${base.source} is on another device than the one asked for`,
);
},
};
if (base.kind === "audio") return { ...base, ...local };
@@ -273,19 +270,6 @@ export function createLocalLivekitMediaTrack(
};
}
/** The device a local track captures from; none while it is muted. */
async function openDevice(
track: Track | undefined,
): Promise<string | undefined> {
return track instanceof LocalTrack && !isMuted(track)
? track.getDeviceId(false)
: undefined;
}
function isMuted(track: Track | undefined): boolean {
return track instanceof LocalTrack && track.isMuted;
}
/** The track behind a publication; a remote one arrives on subscription. */
function publicationTrack$(
scope: ObservableScope,
+140 -97
View File
@@ -20,7 +20,13 @@ import {
} from "../../../utils/test-fixtures";
import type * as csApi from "./csApi";
import type * as openID from "./openID";
import { chooseAuthFlow, delegateDelayedLeave, getSFUConfig } from ".";
import {
type AuthFlow,
authenticateWithTransport,
chooseAuthFlow,
delegateDelayedLeave,
getSFUConfig,
} from ".";
const aliceId = `${aliceUserId}:${aliceDeviceId}`;
const csApiJWTToken = createJWTToken(aliceId, "via CS API");
@@ -67,6 +73,9 @@ const urlAndServiceUrlTransport: UnstableLivekitTransport = {
...serviceUrlTransport,
};
const viaCsApi: AuthFlow = { kind: "csApi", url: "wss://livekit.example.org" };
const viaOpenID: AuthFlow = { kind: "openID", serviceUrl };
/** The JWT service, answering each endpoint with a token that names it. */
function mockJWTService(): void {
fetchMock.post(`${serviceUrl}/sfu/get`, {
@@ -100,11 +109,9 @@ describe("getSFUConfig", () => {
logger,
};
it("uses CS API with url transport", async () => {
it("uses the CS API for the CS API flow", async () => {
mockJWTService();
expect(
await getSFUConfig({ ...defaultParams, transport: urlTransport }),
).toEqual(
expect(await getSFUConfig({ ...defaultParams, flow: viaCsApi })).toEqual(
expect.objectContaining({
jwt: csApiJWTToken,
livekitAlias: "via CS API",
@@ -120,21 +127,19 @@ describe("getSFUConfig", () => {
expect(jwtServiceCalls()).toEqual([]);
});
it("does not fall back to OpenID with url transport", async () => {
it("reports the CS API missing where the homeserver lacks the endpoint, without falling back", async () => {
mockJWTService();
client.getLivekitToken.mockRejectedValueOnce(unsupportedError);
await expect(
getSFUConfig({ ...defaultParams, transport: urlTransport }),
getSFUConfig({ ...defaultParams, flow: viaCsApi }),
).rejects.toThrow(expect.any(NoMatrix2AuthorizationService));
expect(client.getLivekitToken).toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual([]);
});
it("uses OpenID with livekit_service_url transport", async () => {
it("uses the JWT service for the OpenID flow", async () => {
mockJWTService();
expect(
await getSFUConfig({ ...defaultParams, transport: serviceUrlTransport }),
).toEqual(
expect(await getSFUConfig({ ...defaultParams, flow: viaOpenID })).toEqual(
expect.objectContaining({
jwt: defaultJWTToken,
livekitAlias: "via default endpoint",
@@ -144,80 +149,141 @@ describe("getSFUConfig", () => {
expect(jwtServiceCalls()).toEqual(["/get_token"]);
});
it("uses OpenID when subscribing with url + livekit_service_url transport", async () => {
it("does not report the CS API missing where the homeserver refuses the request", async () => {
mockJWTService();
expect(
await getSFUConfig({
...defaultParams,
transport: urlAndServiceUrlTransport,
}),
).toEqual(
expect.objectContaining({
jwt: defaultJWTToken,
livekitAlias: "via default endpoint",
}),
);
expect(client.getLivekitToken).not.toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual(["/get_token"]);
});
it("surfaces the widget host's refusal with url transport", async () => {
mockJWTService();
const error = new Error(
"The rtc_livekit_get_token action is not supported by the client.",
);
client.getLivekitToken.mockRejectedValueOnce(error);
const forbidden = new MatrixError({ errcode: "M_FORBIDDEN" }, 403);
client.getLivekitToken.mockRejectedValueOnce(forbidden);
await expect(
getSFUConfig({ ...defaultParams, transport: urlTransport }),
).rejects.toThrow(error);
getSFUConfig({ ...defaultParams, flow: viaCsApi }),
).rejects.toThrow(forbidden);
expect(jwtServiceCalls()).toEqual([]);
});
it("uses CS API when publishing with url transport", async () => {
it("reports the CS API missing for another homeserver's transport", async () => {
mockJWTService();
client.getLivekitToken.mockRejectedValueOnce(
new MatrixError({ errcode: "M_UNRECOGNIZED" }, 404),
);
await expect(
getSFUConfig({
...defaultParams,
serverName: "elsewhere.org",
flow: viaCsApi,
}),
).rejects.toThrow(expect.any(NoMatrix2AuthorizationService));
expect(jwtServiceCalls()).toEqual([]);
});
it("reports the CS API missing where a widget host relays the homeserver's not found", async () => {
mockJWTService();
// The widget API's WidgetApiResponseError arrives in a minified build.
const relayed = Object.assign(new Error("Unrecognized request"), {
name: "n",
data: {
matrix_api_error: {
http_status: 404,
response: { errcode: "M_UNRECOGNIZED" },
},
},
});
client.getLivekitToken.mockRejectedValueOnce(relayed);
await expect(
getSFUConfig({ ...defaultParams, flow: viaCsApi }),
).rejects.toThrow(expect.any(NoMatrix2AuthorizationService));
expect(jwtServiceCalls()).toEqual([]);
});
it.each([
["a token that does not decode", { jwt: "not a token" }],
["an error of our own", new TypeError("oops")],
])("does not judge the CS API by %s", async (_what, outcome) => {
mockJWTService();
if (outcome instanceof Error)
client.getLivekitToken.mockRejectedValueOnce(outcome);
else client.getLivekitToken.mockResolvedValueOnce(outcome);
await expect(
getSFUConfig({ ...defaultParams, flow: viaCsApi }),
).rejects.not.toBeInstanceOf(NoMatrix2AuthorizationService);
expect(jwtServiceCalls()).toEqual([]);
});
it("uses the CS API when publishing through the CS API flow", async () => {
mockJWTService();
expect(
await getSFUConfig({
...defaultParams,
transport: urlTransport,
flow: viaCsApi,
role: "publisher",
}),
).toEqual(expect.objectContaining({ jwt: csApiJWTToken }));
expect(client.getLivekitToken).toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual([]);
});
});
it("does not fall back to OpenID when publishing with url transport", async () => {
describe("authenticateWithTransport", () => {
const defaultParams = {
client,
membership,
serverName: "example.org",
role: "subscriber" as const,
roomId,
slotId,
logger,
};
it("uses CS API with url + livekit_service_url transport", async () => {
mockJWTService();
client.getLivekitToken.mockRejectedValueOnce(unsupportedError);
await expect(
getSFUConfig({
expect(
await authenticateWithTransport({
...defaultParams,
transport: urlTransport,
role: "publisher",
transport: urlAndServiceUrlTransport,
}),
).rejects.toThrow(expect.any(NoMatrix2AuthorizationService));
expect(client.getLivekitToken).toHaveBeenCalled();
).toEqual(expect.objectContaining({ jwt: csApiJWTToken }));
expect(jwtServiceCalls()).toEqual([]);
});
it("uses the legacy OpenID endpoint when publishing with url + livekit_service_url transport", async () => {
it.each([
["subscriber", "/get_token", defaultJWTToken],
["publisher", "/sfu/get", legacyJWTToken],
] as const)(
"falls back to OpenID as %s where the homeserver lacks the endpoint",
async (role, endpoint, jwt) => {
mockJWTService();
client.getLivekitToken.mockRejectedValueOnce(unsupportedError);
expect(
await authenticateWithTransport({
...defaultParams,
transport: urlAndServiceUrlTransport,
role,
}),
).toEqual(expect.objectContaining({ jwt }));
expect(client.getLivekitToken).toHaveBeenCalledTimes(1);
expect(jwtServiceCalls()).toEqual([endpoint]);
},
);
it("does not fall back with url transport", async () => {
mockJWTService();
// Subscribers predating MSC4195 expect a legacy participant identity from
// anyone advertising a membership, which only the JWT service assigns
expect(
await getSFUConfig({
client.getLivekitToken.mockRejectedValueOnce(unsupportedError);
await expect(
authenticateWithTransport({ ...defaultParams, transport: urlTransport }),
).rejects.toThrow(expect.any(NoMatrix2AuthorizationService));
expect(client.getLivekitToken).toHaveBeenCalledTimes(1);
expect(jwtServiceCalls()).toEqual([]);
});
it("does not fall back where the homeserver refuses the request", async () => {
mockJWTService();
const forbidden = new MatrixError({ errcode: "M_FORBIDDEN" }, 403);
client.getLivekitToken.mockRejectedValueOnce(forbidden);
await expect(
authenticateWithTransport({
...defaultParams,
transport: urlAndServiceUrlTransport,
role: "publisher",
}),
).toEqual(
expect.objectContaining({
jwt: legacyJWTToken,
livekitAlias: "via legacy endpoint",
}),
);
expect(client.getLivekitToken).not.toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual(["/sfu/get"]);
).rejects.toThrow(forbidden);
expect(jwtServiceCalls()).toEqual([]);
});
});
@@ -242,9 +308,9 @@ describe("delegateDelayedLeave", () => {
return { delay_id, delay_timeout, delay_cs_api_url };
}
it("uses CS API with url transport", async () => {
it("uses the CS API for the CS API flow", async () => {
mockJWTService();
await delegateDelayedLeave({ ...defaultParams, transport: urlTransport });
await delegateDelayedLeave({ ...defaultParams, flow: viaCsApi });
expect(client.delegateDelayedLeave).toHaveBeenCalledWith({
url: urlTransport.url,
room_id: roomId,
@@ -255,37 +321,19 @@ describe("delegateDelayedLeave", () => {
expect(jwtServiceCalls()).toEqual([]);
});
it("does not fall back to OpenID with url transport", async () => {
it("does not fall back to the JWT service from the CS API flow", async () => {
mockJWTService();
client.delegateDelayedLeave.mockRejectedValueOnce(unsupportedError);
await expect(
delegateDelayedLeave({ ...defaultParams, transport: urlTransport }),
delegateDelayedLeave({ ...defaultParams, flow: viaCsApi }),
).rejects.toThrow();
expect(client.delegateDelayedLeave).toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual([]);
});
it("uses OpenID with livekit_service_url transport", async () => {
it("uses the JWT service for the OpenID flow", async () => {
mockJWTService();
await delegateDelayedLeave({
...defaultParams,
transport: serviceUrlTransport,
});
expect(client.delegateDelayedLeave).not.toHaveBeenCalled();
expect(delegationViaJWTService()).toEqual({
delay_id: "delay123",
delay_timeout: 3_600_000,
delay_cs_api_url: client.baseUrl,
});
});
it("uses OpenID with url + livekit_service_url transport", async () => {
mockJWTService();
// Must match the flow that got the token, so the identities line up
await delegateDelayedLeave({
...defaultParams,
transport: urlAndServiceUrlTransport,
});
await delegateDelayedLeave({ ...defaultParams, flow: viaOpenID });
expect(client.delegateDelayedLeave).not.toHaveBeenCalled();
expect(delegationViaJWTService()).toEqual({
delay_id: "delay123",
@@ -297,21 +345,16 @@ describe("delegateDelayedLeave", () => {
describe("chooseAuthFlow", () => {
it.each([
["url", urlTransport, { kind: "csApi", url: urlTransport.url }],
[
"livekit_service_url",
serviceUrlTransport,
{ kind: "openID", serviceUrl },
],
[
"url + livekit_service_url",
urlAndServiceUrlTransport,
{ kind: "openID", serviceUrl },
],
["url", urlTransport, true, viaCsApi],
["url", urlTransport, false, viaCsApi],
["livekit_service_url", serviceUrlTransport, true, viaOpenID],
["livekit_service_url", serviceUrlTransport, false, viaOpenID],
["url + livekit_service_url", urlAndServiceUrlTransport, true, viaCsApi],
["url + livekit_service_url", urlAndServiceUrlTransport, false, viaOpenID],
] as const)(
"chooses the flow for a %s transport as %s",
(_shape, transport, flow) => {
expect(chooseAuthFlow(transport)).toEqual(flow);
"chooses the flow for a %s transport with the CS API usable: %s",
(_shape, transport, csApiUsable, flow) => {
expect(chooseAuthFlow(transport, csApiUsable)).toEqual(flow);
},
);
});
+109 -43
View File
@@ -6,13 +6,10 @@ Please see LICENSE in the repository root for full details.
*/
/**
* Authentication with a LiveKit transport: the MSC4195 client-server API
* through our homeserver for a transport with an SFU `url`, the OpenID flow
* against the JWT service for one with a `livekit_service_url`, and the
* choice between them where a transport carries both.
* Authentication with a LiveKit transport.
*/
import { ConnectionError, MatrixError } from "matrix-js-sdk";
import { MatrixError } from "matrix-js-sdk";
import { type Logger } from "matrix-js-sdk/lib/logger";
import { type UnstableLivekitTransport } from "matrix-js-sdk/lib/matrixrtc";
import { type CallMembershipIdentityParts } from "matrix-js-sdk/lib/matrixrtc/EncryptionManager";
@@ -28,35 +25,66 @@ export type * from "./types";
/**
* Whether an error means the homeserver does not implement the MSC4195
* endpoints. The MSC says `M_NOT_FOUND`; a homeserver without support answers
* with whatever it uses for unknown routes (Synapse: 404 with
* `M_UNRECOGNIZED`), so any 404 counts.
* endpoints. Such a homeserver answers with whatever it uses for unknown
* routes (Synapse: 404 with `M_UNRECOGNIZED`), so any 404 counts.
*/
function isEndpointUnsupported(e: unknown): boolean {
export function isCsApiUnavailable(e: unknown): boolean {
const answer = unwrapErrorDetails(e);
return (
e instanceof MatrixError &&
(e.httpStatus === 404 ||
e.errcode === "M_NOT_FOUND" ||
e.errcode === "M_UNRECOGNIZED")
answer !== undefined &&
(answer.status === 404 ||
answer.errcode === "M_NOT_FOUND" ||
answer.errcode === "M_UNRECOGNIZED")
);
}
/**
* Whether an error means the MSC4195 client-server API cannot be used from
* here: the homeserver does not implement it, or the request never reached
* the homeserver because a widget host does not expose the endpoint
* (MSC4533), which the widget API reports as a plain error. A connection
* error is neither: the endpoint may well exist.
* Tries to unwrap the details from an unknown error object, regardless of whether
* it came from the Widget API or not.
*/
export function isCsApiUnavailable(e: unknown): boolean {
if (isEndpointUnsupported(e)) return true;
return !(e instanceof MatrixError) && !(e instanceof ConnectionError);
function unwrapErrorDetails(
e: unknown,
): { status?: number; errcode?: string } | undefined {
// If the error is an instance of `MatrixError`, take its details directly.
if (e instanceof MatrixError) {
return { status: e.httpStatus, errcode: e.errcode };
}
// If the error originated from the widget API, try to extract the bundled
// Matrix API error. We identify the widget's `WidgetApiResponseError` by
// the shape of its payload to avoid making the SDK dependent on the widget
// API. This isn't great, but we'll drop this branch anyway once we eliminate
// usage.
if (e instanceof Error && "data" in e) {
const relayed = (
e as {
data?: {
matrix_api_error?: {
http_status?: unknown;
response?: { errcode?: unknown };
};
};
}
).data?.matrix_api_error;
if (typeof relayed === "object" && relayed !== null) {
const { http_status: status, response } = relayed;
const errcode = response?.errcode;
return {
status: typeof status === "number" ? status : undefined,
errcode: typeof errcode === "string" ? errcode : undefined,
};
}
}
// We're not able to extract any details from this error.
return undefined;
}
export interface GetSFUConfigParams {
client: csApi.ClientGetTokenParts & openID.ClientOpenIDParts;
membership: CallMembershipIdentityParts;
transport: UnstableLivekitTransport;
/** The flow to authenticate with, as chosen by {@link chooseAuthFlow}. */
flow: AuthFlow;
/** The homeserver the transport belongs to. */
serverName: string;
roomId: string;
@@ -66,20 +94,23 @@ export interface GetSFUConfigParams {
}
/**
* Gets an {@link SFUConfig} appropriate for connecting to a given transport,
* using whichever auth flow is appropriate.
* Gets an {@link SFUConfig} for connecting to a transport through the given
* auth flow.
*
* @throws {@link NoMatrix2AuthorizationService} if the client-server API flow
* finds the API missing. The MSC defines no unstable feature flag, so this is
* how a caller learns to choose its flows without the API from then on.
*/
export async function getSFUConfig({
client,
membership,
transport,
flow,
serverName,
roomId,
slotId,
role,
logger,
}: GetSFUConfigParams): Promise<SFUConfig> {
const flow = chooseAuthFlow(transport);
if (flow.kind === "openID") {
return await openID.getSFUConfig({
client,
@@ -101,10 +132,14 @@ export async function getSFUConfig({
slotId,
});
} catch (e) {
if (isEndpointUnsupported(e)) {
logger.error(
if (isCsApiUnavailable(e)) {
logger.warn(
`Homeserver does not support the MSC4195 get_token endpoint, cannot get token for transport ${flow.url}`,
);
// This is our own homeserver's answer: as per MSC4195, only 403 /
// M_FORBIDDEN and 400 / M_INVALID_PARAM are forwarded from the remote
// server. Any other remote error becomes 502 / M_UNKNOWN on the
// client-server API.
throw new NoMatrix2AuthorizationService(e as Error);
}
throw e;
@@ -112,11 +147,40 @@ export async function getSFUConfig({
}
}
export type AuthenticateWithTransportParams = Omit<
GetSFUConfigParams,
"flow"
> & { transport: UnstableLivekitTransport };
/**
* Authenticates with a transport once, outside any session. This automatically
* falls back from the client-server API flow to the OpenID flow if needed and
* possible.
*
* @throws {@link NoMatrix2AuthorizationService} if the client-server API is missing
* but the transport does not allow falling back to the OpenID flow.
*/
export async function authenticateWithTransport({
transport,
...params
}: AuthenticateWithTransportParams): Promise<SFUConfig> {
try {
const flow = chooseAuthFlow(transport, true);
return await getSFUConfig({ ...params, flow });
} catch (e) {
const flow = chooseAuthFlow(transport, false);
// Nothing else to try unless the API is missing and there is a JWT service
if (!(e instanceof NoMatrix2AuthorizationService) || flow.kind !== "openID")
throw e;
return await getSFUConfig({ ...params, flow });
}
}
export interface DelegateDelayedLeaveParams {
client: csApi.ClientDelegationParts & openID.ClientOpenIDParts;
membership: CallMembershipIdentityParts;
/** The transport we publish on. */
transport: UnstableLivekitTransport;
/** The flow that issued the token we publish with. */
flow: AuthFlow;
roomId: string;
slotId: string;
delayId: string;
@@ -133,14 +197,13 @@ export interface DelegateDelayedLeaveParams {
export async function delegateDelayedLeave({
client,
membership,
transport,
flow,
roomId,
slotId,
delayId,
delayTimeoutMs,
logger,
}: DelegateDelayedLeaveParams): Promise<void> {
const flow = chooseAuthFlow(transport);
if (flow.kind === "csApi") {
try {
await csApi.delegateDelayedLeave({
@@ -152,7 +215,7 @@ export async function delegateDelayedLeave({
delayId,
});
} catch (e) {
if (isEndpointUnsupported(e))
if (isCsApiUnavailable(e))
logger.error(
"Server misconfigured: transport contains a 'url' field but server does not support the MSC4195 delegate_delayed_leave endpoint",
);
@@ -181,18 +244,21 @@ export type AuthFlow =
| { kind: "openID"; serviceUrl: string };
/**
* Chooses which auth flow to use for a given transport. For now this returns a
* single auth flow, with no provision for a fallback behavior.
* Chooses which auth flow to use for a given transport.
*/
export function chooseAuthFlow(transport: UnstableLivekitTransport): AuthFlow {
export function chooseAuthFlow(
transport: UnstableLivekitTransport,
csApiUsable: boolean,
): AuthFlow {
// If we only have url, we have no choice but to use the CS API.
if ("url" in transport && !("livekit_service_url" in transport))
return { kind: "csApi", url: transport.url };
// All other transports use the OpenID flow, even if they contain a `url`.
// This is necessary since the auth flow determines the participant identity
// format, and we still have older clients out in the wild which would not yet
// know to look for a hashed participant identity in case `url` is present in
// someone else's transport.
// TODO: Once users have updated their clients, choose the CS API flow if
// available, keeping OpenID as a fallback.
// If we have both url and livekit_service_url, prefer the CS API if it is usable.
if ("url" in transport && csApiUsable)
return { kind: "csApi", url: transport.url };
// If the CS API is not usable or we only have livekit_service_url, fall back
// to using the OpenID flow.
return { kind: "openID", serviceUrl: transport.livekit_service_url };
}
@@ -8,7 +8,6 @@ Please see LICENSE in the repository root for full details.
import { describe, expect, it } from "vitest";
import { VideoPresets, type VideoPreset } from "livekit-client";
import { cameraCaptureResolution } from "../../config";
import { buildLiveKitOptions } from "./livekitOptions";
describe("buildLiveKitOptions", () => {
@@ -109,33 +108,6 @@ describe("buildLiveKitOptions", () => {
}
});
it.each([
undefined,
90,
180,
240,
360,
480,
540,
720,
1080,
1440,
2160,
4320,
])(
"captures at what a lobby opens the camera at ahead of the join: %s",
(height) => {
const mediaQuality =
height === undefined
? undefined
: { video: { max_resolution: height } };
expect(
buildLiveKitOptions(mediaQuality).videoCaptureDefaults?.resolution,
).toMatchObject(cameraCaptureResolution(mediaQuality));
},
);
it("screen share layers fall back to max_framerate, then 30", () => {
const fromMax = buildLiveKitOptions({
screen_share: {
-1
View File
@@ -276,7 +276,6 @@ export class MockRTCSession extends TypedEventEmitter<
return this.joined;
}
public slotDescription = { application: "m.call", id: "ROOM" };
public slotId = "m.call#ROOM";
/** The id of the delayed leave event; undefined until the manager has sent one. */
public delayId: string | undefined = undefined;
-37
View File
@@ -1,37 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { afterEach, expect, test, vi } from "vitest";
const initSPA = vi.hoisted(() => vi.fn());
vi.mock("./utils/spa", () => ({ initSPA }));
afterEach(() => {
vi.unstubAllEnvs();
vi.resetModules();
initSPA.mockReset();
});
test("the app restores its own session", async () => {
vi.stubEnv("VITE_PACKAGE", "full");
const { loadStandaloneClient } = await import("./App");
const loadSession = vi.fn();
const clearSession = vi.fn();
initSPA.mockResolvedValue(null);
await expect(loadStandaloneClient!(loadSession, clearSession)).resolves.toBe(
null,
);
expect(initSPA).toHaveBeenCalledWith(loadSession, clearSession);
});
test("the embedded package has no session of its own", async () => {
vi.stubEnv("VITE_PACKAGE", "embedded");
const { loadStandaloneClient } = await import("./App");
expect(loadStandaloneClient).toBeUndefined();
});
+2 -6
View File
@@ -64,12 +64,8 @@ const SentryRoute = Sentry.withSentryReactRouterV7Routing(Route);
// - Imported on demand, as it was before, so that a widget, which gets its
// client from the host, never downloads it.
// - Module-level, so that the provider's effect sees one stable loader.
// - None in the embedded package, which only runs as a widget: the constant
// condition lets its build drop the client setup and the store worker.
export const loadStandaloneClient: ClientLoader | undefined =
import.meta.env.VITE_PACKAGE === "embedded"
? undefined
: async (...args) => (await import("./utils/spa")).initSPA(...args);
const loadStandaloneClient: ClientLoader = async (...args) =>
(await import("./utils/spa")).initSPA(...args);
interface SimpleProviderProps {
children: JSX.Element;
-42
View File
@@ -1,42 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { expect, test } from "vitest";
import { createClient, Room } from "matrix-js-sdk";
import { withEmitter } from "@element-hq/matrixrtc-sdk";
import { createCallMatrixBackend } from "./CallMatrixBackend";
test("has the SDK's part and the call's own", () => {
const { backend, room } = setup();
expect(backend.getUserId()).toBe("@alice:example.org");
expect(backend.getJoinRule()).toBe(room.getJoinRule());
expect(backend.relations).toBe(room.relations);
});
test("reads the room's name as it is now, also as a room", () => {
const { backend, room } = setup();
const asRoom = withEmitter(backend, backend.roomEmitter);
room.name = "Renamed";
expect(backend.name).toBe("Renamed");
expect(asRoom.name).toBe("Renamed");
});
function setup(): {
backend: ReturnType<typeof createCallMatrixBackend>;
room: Room;
} {
const client = createClient({
baseUrl: "https://matrix.example.org",
userId: "@alice:example.org",
deviceId: "DEVICE",
});
const room = new Room("!room:example.org", client, "@alice:example.org");
return { backend: createCallMatrixBackend(client, room), room };
}
-77
View File
@@ -1,77 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { type MatrixClient, type Room } from "matrix-js-sdk";
import {
createSdkMatrixBackend,
type SdkMatrixBackend,
} from "@element-hq/matrixrtc-sdk";
/** What a call needs of the client beyond the SDK's part. */
type CallClientPart = Pick<
MatrixClient,
// Reactions and raised hands: decrypting, and lowering a hand
| "decryptEventIfNeeded"
| "redactEvent"
// Our own display name and avatar
| "getUser"
// Changing them, where the host lets us (`supportsProfileChanges`)
| "setDisplayName"
| "setAvatarUrl"
| "uploadContent"
// Developer settings
| "doesServerSupportUnstableFeature"
| "getCrypto"
>;
/** What a call needs of the room beyond the SDK's part. */
type CallRoomPart = Pick<
Room,
// The header and the invite link
| "name"
| "getMxcAvatarUrl"
// Whether to offer the invite link
| "getJoinRule"
// Raised hands already in the room
| "relations"
>;
/**
* STOP GAP: everything a call needs from Matrix on one object. Its
* `clientEmitter` also carries `MatrixEventEvent.Decrypted` (reactions); its
* `roomEmitter` every room event.
*/
export interface CallMatrixBackend
extends SdkMatrixBackend, CallClientPart, CallRoomPart {}
/** A call's backend from a client and a room. */
export function createCallMatrixBackend(
client: Parameters<typeof createSdkMatrixBackend>[0] & CallClientPart,
room: Parameters<typeof createSdkMatrixBackend>[1] & CallRoomPart,
): CallMatrixBackend {
return {
...createSdkMatrixBackend(client, room),
decryptEventIfNeeded: client.decryptEventIfNeeded.bind(client),
redactEvent: client.redactEvent.bind(client),
getUser: client.getUser.bind(client),
setDisplayName: client.setDisplayName.bind(client),
setAvatarUrl: client.setAvatarUrl.bind(client),
uploadContent: client.uploadContent.bind(client),
doesServerSupportUnstableFeature:
client.doesServerSupportUnstableFeature.bind(client),
getCrypto: client.getCrypto.bind(client),
// Read through: the room is renamed while we show it
get name() {
return room.name;
},
getMxcAvatarUrl: room.getMxcAvatarUrl.bind(room),
getJoinRule: room.getJoinRule.bind(room),
get relations() {
return room.relations;
},
};
}
+1 -1
View File
@@ -20,7 +20,7 @@ import {
const mockClient = (userId = "@alice:example.org"): MatrixClient =>
({
on: vi.fn(),
off: vi.fn(),
removeListener: vi.fn(),
getUserId: () => userId,
getDeviceId: () => "AAAA",
stopClient: vi.fn(),
+3 -41
View File
@@ -142,7 +142,7 @@ interface Props {
* itself — from the widget API, or by restoring or creating a session of its
* own.
*/
client?: SuppliedClient;
client?: MatrixClient;
/**
* How Element Call finds a client when none is supplied: the standalone app
* restores or creates a session of its own. Stable, as a hook dependency.
@@ -161,37 +161,6 @@ interface Props {
loadClient?: ClientLoader;
}
/**
* What is read of a supplied client under a call, and by this provider and
* analytics. Stable methods only, so a host's client, from the host's own copy
* of matrix-js-sdk, will do.
*/
export type SuppliedClient = Pick<
MatrixClient,
// The disconnected banner, and stopping a client opened elsewhere
| "on"
| "off"
| "stopClient"
// Analytics, through `window.matrixclient`
| "getCrypto"
| "isGuest"
| "getAccountDataFromServer"
| "setAccountData"
// The room's encryption system
| "getRoom"
// Avatars
| "mxcUrlToHttp"
| "getAccessToken"
// Rageshakes: who sends them, their crypto state, and asking others for theirs
| "getUserId"
| "getUser"
| "credentials"
| "deviceId"
| "secretStorage"
| "isKeyBackupKeyStored"
| "sendEvent"
>;
/**
* Restores or creates a session of Element Call's own, kept where the given
* functions keep it. Resolves to null when no one is signed in.
@@ -201,14 +170,7 @@ export type ClientLoader = (
clearSession: () => void,
) => Promise<InitResult | null>;
export const ClientProvider: FC<Props> = ({
children,
client: suppliedClient,
loadClient,
}) => {
// STOP GAP: held as a whole client, as the standalone and widget pages need
// one. A component host's client is only read through `SuppliedClient`.
const client = suppliedClient as MatrixClient | undefined;
export const ClientProvider: FC<Props> = ({ children, client, loadClient }) => {
const leaveToHome = useLeaveToHome();
const hostBridge = useHostBridge();
@@ -410,7 +372,7 @@ export const ClientProvider: FC<Props> = ({
return (): void => {
if (initClientState.client) {
initClientState.client.off(ClientEvent.Sync, onSync);
initClientState.client.removeListener(ClientEvent.Sync, onSync);
}
};
}, [initClientState, onSync, hostBridge]);
+2 -8
View File
@@ -18,17 +18,11 @@ Please see LICENSE in the repository root for full details.
*/
import {
RTC_CALL_INTENT_AUDIO,
RTC_CALL_INTENT_VIDEO,
type RTCCallIntent,
type RTCNotificationType,
} from "matrix-js-sdk/lib/matrixrtc";
// Not from the `matrixrtc` index above. Those are not type imports,
// So those two imports would add a whole copy of "matrix-js-sdk/lib/matrixrtc"
// The "api.ts" file is meant to be the only thing loaded by EW on pageload.
// Everything beyond it should be lazy loaded on first call start.
import {
RTC_CALL_INTENT_AUDIO,
RTC_CALL_INTENT_VIDEO,
} from "matrix-js-sdk/lib/matrixrtc/CallIntent";
import { platform } from "./Platform";
+22 -20
View File
@@ -15,7 +15,7 @@ import {
afterAll,
} from "vitest";
import { logger } from "matrix-js-sdk/lib/logger";
import { type Statistics } from "matrix-js-sdk/lib/matrixrtc";
import { type MatrixRTCSession } from "matrix-js-sdk/lib/matrixrtc";
import { PosthogAnalytics } from "./PosthogAnalytics";
import {
@@ -34,14 +34,16 @@ const defaultTotals = {
roomEventEncryptionKeysReceivedTotalAge: 500,
};
function createMockStatistics(overrides?: {
function createMockRtcSession(overrides?: {
counters?: Partial<typeof defaultCounters>;
totals?: Partial<typeof defaultTotals>;
}): Statistics {
}): MatrixRTCSession {
return {
counters: { ...defaultCounters, ...overrides?.counters },
totals: { ...defaultTotals, ...overrides?.totals },
} as Statistics;
statistics: {
counters: { ...defaultCounters, ...overrides?.counters },
totals: { ...defaultTotals, ...overrides?.totals },
},
} as unknown as MatrixRTCSession;
}
describe("CallEnded", () => {
@@ -63,9 +65,9 @@ describe("CallEnded", () => {
it("warns if startTime is missing when track is called", () => {
const warnSpy = vi.spyOn(logger, "warn");
const tracker = new CallEndedTracker();
const statistics = createMockStatistics();
const mockSession = createMockRtcSession();
tracker.track("test-call-id", 2, false, statistics);
tracker.track("test-call-id", 2, false, mockSession);
expect(warnSpy).toHaveBeenCalledWith(
"[PosthogEvents] Failed to send posthog callEnded event due to missing startTime",
@@ -75,11 +77,11 @@ describe("CallEnded", () => {
it("tracks event with correct properties when startTime is set", () => {
const tracker = new CallEndedTracker();
const statistics = createMockStatistics();
const mockSession = createMockRtcSession();
tracker.cacheStartCall(new Date(Date.now() - 60000));
tracker.cacheParticipantCountChanged(5);
tracker.track("test-call-id", 3, true, statistics);
tracker.track("test-call-id", 3, true, mockSession);
expect(PosthogAnalytics.instance.trackEvent).toHaveBeenCalledWith(
{
@@ -103,13 +105,13 @@ describe("CallEnded", () => {
it("tracks maxParticipantsCount correctly across multiple changes", () => {
const tracker = new CallEndedTracker();
const statistics = createMockStatistics();
const mockSession = createMockRtcSession();
tracker.cacheStartCall(new Date());
tracker.cacheParticipantCountChanged(3);
tracker.cacheParticipantCountChanged(7);
tracker.cacheParticipantCountChanged(2);
tracker.track("test-call-id", 1, false, statistics);
tracker.track("test-call-id", 1, false, mockSession);
expect(PosthogAnalytics.instance.trackEvent).toHaveBeenCalledWith(
expect.objectContaining({
@@ -121,12 +123,12 @@ describe("CallEnded", () => {
it("computes roomEventEncryptionKeysReceivedAverageAge as 0 when no keys received", () => {
const tracker = new CallEndedTracker();
const statistics = createMockStatistics({
const mockSession = createMockRtcSession({
counters: { roomEventEncryptionKeysReceived: 0 },
});
tracker.cacheStartCall(new Date());
tracker.track("test-call-id", 1, false, statistics);
tracker.track("test-call-id", 1, false, mockSession);
expect(PosthogAnalytics.instance.trackEvent).toHaveBeenCalledWith(
expect.objectContaining({
@@ -138,13 +140,13 @@ describe("CallEnded", () => {
it("computes roomEventEncryptionKeysReceivedAverageAge correctly when keys are received", () => {
const tracker = new CallEndedTracker();
const statistics = createMockStatistics({
const mockSession = createMockRtcSession({
counters: { roomEventEncryptionKeysReceived: 4 },
totals: { roomEventEncryptionKeysReceivedTotalAge: 200 },
});
tracker.cacheStartCall(new Date());
tracker.track("test-call-id", 1, false, statistics);
tracker.track("test-call-id", 1, false, mockSession);
expect(PosthogAnalytics.instance.trackEvent).toHaveBeenCalledWith(
expect.objectContaining({
@@ -156,10 +158,10 @@ describe("CallEnded", () => {
it("passes send_instantly option correctly", () => {
const tracker = new CallEndedTracker();
const statistics = createMockStatistics();
const mockSession = createMockRtcSession();
tracker.cacheStartCall(new Date());
tracker.track("test-call-id", 1, false, statistics);
tracker.track("test-call-id", 1, false, mockSession);
expect(PosthogAnalytics.instance.trackEvent).toHaveBeenCalledWith(
expect.anything(),
@@ -169,14 +171,14 @@ describe("CallEnded", () => {
it("includes per-reason reconnecting counts in CallEnded", () => {
const tracker = new CallEndedTracker();
const statistics = createMockStatistics();
const mockSession = createMockRtcSession();
tracker.cacheStartCall(new Date());
tracker.cacheReconnecting("sync");
tracker.cacheReconnecting("sync");
tracker.cacheReconnecting("livekit");
tracker.cacheReconnecting("membership");
tracker.track("test-call-id", 1, false, statistics);
tracker.track("test-call-id", 1, false, mockSession);
expect(PosthogAnalytics.instance.trackEvent).toHaveBeenCalledWith(
expect.objectContaining({
+8 -7
View File
@@ -7,7 +7,7 @@ Please see LICENSE in the repository root for full details.
import { type DisconnectReason } from "livekit-client";
import { logger } from "matrix-js-sdk/lib/logger";
import { type Statistics } from "matrix-js-sdk/lib/matrixrtc";
import { type MatrixRTCSession } from "matrix-js-sdk/lib/matrixrtc";
import {
type IPosthogEvent,
@@ -80,7 +80,7 @@ export class CallEndedTracker {
callId: string,
callParticipantsNow: number,
sendInstantly: boolean,
statistics: Statistics,
rtcSession: MatrixRTCSession,
): void {
if (this.cache.startTime) {
PosthogAnalytics.instance.trackEvent<CallEnded>(
@@ -91,13 +91,14 @@ export class CallEndedTracker {
callParticipantsOnLeave: callParticipantsNow,
callDuration: (Date.now() - this.cache.startTime.getTime()) / 1000,
roomEventEncryptionKeysSent:
statistics.counters.roomEventEncryptionKeysSent,
rtcSession.statistics.counters.roomEventEncryptionKeysSent,
roomEventEncryptionKeysReceived:
statistics.counters.roomEventEncryptionKeysReceived,
rtcSession.statistics.counters.roomEventEncryptionKeysReceived,
roomEventEncryptionKeysReceivedAverageAge:
statistics.counters.roomEventEncryptionKeysReceived > 0
? statistics.totals.roomEventEncryptionKeysReceivedTotalAge /
statistics.counters.roomEventEncryptionKeysReceived
rtcSession.statistics.counters.roomEventEncryptionKeysReceived > 0
? rtcSession.statistics.totals
.roomEventEncryptionKeysReceivedTotalAge /
rtcSession.statistics.counters.roomEventEncryptionKeysReceived
: 0,
callReconnectingCount: this.cache.reconnectingCount,
callReconnectingCountSync: this.cache.reconnectingCountByReason.sync,
+5 -7
View File
@@ -147,13 +147,11 @@ export const RegisterPage: FC = () => {
}
}, [loading, navigate, authenticated, passwordlessUser, registering]);
useEffect(() => {
if (!loading) {
PosthogAnalytics.instance.eventSignup.cacheSignupStart(new Date());
}
}, [loading]);
if (loading) return <LoadingPage />;
if (loading) {
return <LoadingPage />;
} else {
PosthogAnalytics.instance.eventSignup.cacheSignupStart(new Date());
}
return (
<>
+27 -35
View File
@@ -10,13 +10,13 @@ import { expect, test } from "vitest";
import { TooltipProvider } from "@vector-im/compound-web";
import { userEvent } from "@testing-library/user-event";
import { type ReactNode } from "react";
import { type MatrixClient, type Room } from "matrix-js-sdk";
import { ReactionToggleButton } from "./ReactionToggleButton";
import { ElementCallReactionEventType } from "../reactions";
import { type CallViewModel } from "../state/CallViewModel/CallViewModel";
import { getBasicCallViewModelEnvironment } from "../utils/test-viewmodel";
import { alice, local, localRtcMember } from "../utils/test-fixtures";
import { type MockRTCSession } from "../utils/test";
import { ReactionsSenderProvider } from "../reactions/useReactionsSender";
import { initializeWidget } from "../widget";
initializeWidget();
@@ -24,17 +24,18 @@ initializeWidget();
const localIdent = `${localRtcMember.userId}:${localRtcMember.deviceId}`;
function TestComponent({
matrixRoom,
client,
rtcSession,
vm,
}: {
matrixRoom: Room;
client: MatrixClient;
rtcSession: MockRTCSession;
vm: CallViewModel;
}): ReactNode {
return (
<TooltipProvider>
<ReactionsSenderProvider vm={vm} room={matrixRoom} client={client}>
<ReactionsSenderProvider
vm={vm}
rtcSession={rtcSession.asMockedSession()}
>
<ReactionToggleButton
reactionData={{
reactions$: vm.reactions$,
@@ -49,9 +50,9 @@ function TestComponent({
test("Can open menu", async () => {
const user = userEvent.setup();
const { vm, matrixRoom, client } = getBasicCallViewModelEnvironment([alice]);
const { vm, rtcSession } = getBasicCallViewModelEnvironment([alice]);
const { getByLabelText, container } = render(
<TestComponent vm={vm} matrixRoom={matrixRoom} client={client} />,
<TestComponent vm={vm} rtcSession={rtcSession} />,
);
await user.click(getByLabelText("Reactions"));
expect(container).toMatchSnapshot();
@@ -59,15 +60,15 @@ test("Can open menu", async () => {
test("Can raise hand", async () => {
const user = userEvent.setup();
const { vm, matrixRoom, client, handRaisedSubject$ } =
const { vm, rtcSession, handRaisedSubject$ } =
getBasicCallViewModelEnvironment([local, alice]);
const { getByLabelText, container } = render(
<TestComponent vm={vm} matrixRoom={matrixRoom} client={client} />,
<TestComponent vm={vm} rtcSession={rtcSession} />,
);
await user.click(getByLabelText("Reactions"));
await user.click(getByLabelText("Raise hand"));
expect(client.sendEvent).toHaveBeenCalledWith(
matrixRoom.roomId,
expect(rtcSession.room.client.sendEvent).toHaveBeenCalledWith(
rtcSession.room.roomId,
"m.reaction",
{
"m.relates_to": {
@@ -93,10 +94,10 @@ test("Can raise hand", async () => {
test("Can lower hand", async () => {
const reactionEventId = "$my-reaction-event:example.org";
const user = userEvent.setup();
const { vm, matrixRoom, client, handRaisedSubject$ } =
const { vm, rtcSession, handRaisedSubject$ } =
getBasicCallViewModelEnvironment([local, alice]);
const { getByLabelText, container } = render(
<TestComponent vm={vm} matrixRoom={matrixRoom} client={client} />,
<TestComponent vm={vm} rtcSession={rtcSession} />,
);
await user.click(getByLabelText("Reactions"));
await user.click(getByLabelText("Raise hand"));
@@ -111,8 +112,8 @@ test("Can lower hand", async () => {
});
await user.click(getByLabelText("Reactions"));
await user.click(getByLabelText("Lower hand"));
expect(client.redactEvent).toHaveBeenCalledWith(
matrixRoom.roomId,
expect(rtcSession.room.client.redactEvent).toHaveBeenCalledWith(
rtcSession.room.roomId,
reactionEventId,
);
act(() => {
@@ -124,17 +125,14 @@ test("Can lower hand", async () => {
test("Can react with emoji", async () => {
const user = userEvent.setup();
const { vm, matrixRoom, client } = getBasicCallViewModelEnvironment([
local,
alice,
]);
const { vm, rtcSession } = getBasicCallViewModelEnvironment([local, alice]);
const { getByLabelText, getByText } = render(
<TestComponent vm={vm} matrixRoom={matrixRoom} client={client} />,
<TestComponent vm={vm} rtcSession={rtcSession} />,
);
await user.click(getByLabelText("Reactions"));
await user.click(getByText("🐶"));
expect(client.sendEvent).toHaveBeenCalledWith(
matrixRoom.roomId,
expect(rtcSession.room.client.sendEvent).toHaveBeenCalledWith(
rtcSession.room.roomId,
ElementCallReactionEventType,
{
"m.relates_to": {
@@ -149,19 +147,16 @@ test("Can react with emoji", async () => {
test("Can fully expand emoji picker", async () => {
const user = userEvent.setup();
const { vm, matrixRoom, client } = getBasicCallViewModelEnvironment([
local,
alice,
]);
const { vm, rtcSession } = getBasicCallViewModelEnvironment([local, alice]);
const { getByLabelText, container, getByText } = render(
<TestComponent vm={vm} matrixRoom={matrixRoom} client={client} />,
<TestComponent vm={vm} rtcSession={rtcSession} />,
);
await user.click(getByLabelText("Reactions"));
await user.click(getByLabelText("Show more"));
expect(container).toMatchSnapshot();
await user.click(getByText("🦗"));
expect(client.sendEvent).toHaveBeenCalledWith(
matrixRoom.roomId,
expect(rtcSession.room.client.sendEvent).toHaveBeenCalledWith(
rtcSession.room.roomId,
ElementCallReactionEventType,
{
"m.relates_to": {
@@ -176,12 +171,9 @@ test("Can fully expand emoji picker", async () => {
test("Can close reaction dialog", async () => {
const user = userEvent.setup();
const { vm, matrixRoom, client } = getBasicCallViewModelEnvironment([
local,
alice,
]);
const { vm, rtcSession } = getBasicCallViewModelEnvironment([local, alice]);
const { getByLabelText, container } = render(
<TestComponent vm={vm} matrixRoom={matrixRoom} client={client} />,
<TestComponent vm={vm} rtcSession={rtcSession} />,
);
await user.click(getByLabelText("Reactions"));
await user.click(getByLabelText("Show more"));
+1 -6
View File
@@ -37,12 +37,7 @@ interface UseProfile extends ProfileLoadState {
saveProfile: ProfileSaveCallback;
}
export type ProfileClientParts = Pick<
MatrixClient,
"getUserId" | "getUser" | "setDisplayName" | "setAvatarUrl" | "uploadContent"
>;
export function useProfile(client: ProfileClientParts | undefined): UseProfile {
export function useProfile(client: MatrixClient | undefined): UseProfile {
const [{ success, loading, displayName, avatarUrl, error }, setState] =
useState<ProfileLoadState>(() => {
let user: User | undefined = undefined;
+56 -172
View File
@@ -23,130 +23,30 @@ import {
localRtcMember,
} from "../utils/test-fixtures";
import { getBasicRTCSession } from "../utils/test-viewmodel";
import { mockRtcMembership, testScope, withTestScheduler } from "../utils/test";
import { testScope, withTestScheduler } from "../utils/test";
import { ElementCallReactionEventType, ReactionSet } from ".";
afterEach(() => {
vitest.useRealTimers();
});
function raiseLocalHand(
matrixRoom: ReturnType<typeof getBasicRTCSession>["matrixRoom"],
reactionEventId: string,
localTimestamp: Date,
): void {
matrixRoom.emit(
MatrixRoomEvent.Timeline,
new MatrixEvent({
room_id: matrixRoom.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: EventType.Reaction,
origin_server_ts: localTimestamp.getTime(),
content: {
"m.relates_to": { event_id: localRtcMember.eventId, key: "🖐️" },
},
}),
matrixRoom,
undefined,
false,
{} as IRoomTimelineData,
);
}
test("lowers the hand of a member who leaves", () => {
const { members$, matrixRoom, client, rtcMemberships$ } = getBasicRTCSession([
local,
alice,
]);
const reactionEventId = "$my_event_id:example.org";
const localTimestamp = new Date();
withTestScheduler(({ schedule, expectObservable }) => {
renderHook(() => {
const { raisedHands$ } = new ReactionsReader(
testScope(),
members$,
matrixRoom,
client,
);
schedule("abc", {
a: () => {},
b: () => raiseLocalHand(matrixRoom, reactionEventId, localTimestamp),
c: () => rtcMemberships$.next([aliceRtcMember]),
});
expectObservable(raisedHands$).toBe("abc", {
a: {},
b: {
[`${localRtcMember.userId}:${localRtcMember.deviceId}`]: {
reactionEventId,
membershipEventId: localRtcMember.eventId,
time: localTimestamp,
},
},
c: {},
});
});
});
});
test("lowers the hand of a member whose membership is sent again", () => {
const { members$, matrixRoom, client, rtcMemberships$ } = getBasicRTCSession([
local,
alice,
]);
const reactionEventId = "$my_event_id:example.org";
const localTimestamp = new Date();
const resent = mockRtcMembership(
localRtcMember.userId,
localRtcMember.deviceId,
);
withTestScheduler(({ schedule, expectObservable }) => {
renderHook(() => {
const { raisedHands$ } = new ReactionsReader(
testScope(),
members$,
matrixRoom,
client,
);
schedule("abc", {
a: () => {},
b: () => raiseLocalHand(matrixRoom, reactionEventId, localTimestamp),
c: () => rtcMemberships$.next([resent, aliceRtcMember]),
});
expectObservable(raisedHands$).toBe("abc", {
a: {},
b: {
[`${localRtcMember.userId}:${localRtcMember.deviceId}`]: {
reactionEventId,
membershipEventId: localRtcMember.eventId,
time: localTimestamp,
},
},
c: {},
});
});
});
});
test("handles a hand raised reaction", () => {
const { members$, matrixRoom, client } = getBasicRTCSession([local, alice]);
const { rtcSession } = getBasicRTCSession([local, alice]);
const reactionEventId = "$my_event_id:example.org";
const localTimestamp = new Date();
withTestScheduler(({ schedule, expectObservable }) => {
renderHook(() => {
const { raisedHands$ } = new ReactionsReader(
testScope(),
members$,
matrixRoom,
client,
rtcSession.asMockedSession(),
);
schedule("ab", {
a: () => {},
b: () => {
matrixRoom.emit(
rtcSession.room.emit(
MatrixRoomEvent.Timeline,
new MatrixEvent({
room_id: matrixRoom.roomId,
room_id: rtcSession.room.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: EventType.Reaction,
@@ -158,7 +58,7 @@ test("handles a hand raised reaction", () => {
},
},
}),
matrixRoom,
rtcSession.room,
undefined,
false,
{} as IRoomTimelineData,
@@ -180,24 +80,22 @@ test("handles a hand raised reaction", () => {
});
test("handles a redaction", () => {
const { members$, matrixRoom, client } = getBasicRTCSession([local, alice]);
const { rtcSession } = getBasicRTCSession([local, alice]);
const reactionEventId = "$my_event_id:example.org";
const localTimestamp = new Date();
withTestScheduler(({ schedule, expectObservable }) => {
renderHook(() => {
const { raisedHands$ } = new ReactionsReader(
testScope(),
members$,
matrixRoom,
client,
rtcSession.asMockedSession(),
);
schedule("abc", {
a: () => {},
b: () => {
matrixRoom.emit(
rtcSession.room.emit(
MatrixRoomEvent.Timeline,
new MatrixEvent({
room_id: matrixRoom.roomId,
room_id: rtcSession.room.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: EventType.Reaction,
@@ -209,23 +107,23 @@ test("handles a redaction", () => {
},
},
}),
matrixRoom,
rtcSession.room,
undefined,
false,
{} as IRoomTimelineData,
);
},
c: () => {
matrixRoom.emit(
rtcSession.room.emit(
MatrixRoomEvent.Redaction,
new MatrixEvent({
room_id: matrixRoom.roomId,
room_id: rtcSession.room.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: EventType.RoomRedaction,
redacts: reactionEventId,
}),
matrixRoom,
rtcSession.room,
undefined,
);
},
@@ -246,22 +144,20 @@ test("handles a redaction", () => {
});
test("handles waiting for event decryption", () => {
const { members$, matrixRoom, client } = getBasicRTCSession([local, alice]);
const { rtcSession } = getBasicRTCSession([local, alice]);
const reactionEventId = "$my_event_id:example.org";
const localTimestamp = new Date();
withTestScheduler(({ schedule, expectObservable }) => {
renderHook(() => {
const { raisedHands$ } = new ReactionsReader(
testScope(),
members$,
matrixRoom,
client,
rtcSession.asMockedSession(),
);
schedule("abc", {
a: () => {},
b: () => {
const encryptedEvent = new MatrixEvent({
room_id: matrixRoom.roomId,
room_id: rtcSession.room.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: EventType.Reaction,
@@ -275,20 +171,20 @@ test("handles waiting for event decryption", () => {
});
// Should ignore encrypted events that are still encrypting
encryptedEvent["decryptionPromise"] = Promise.resolve();
matrixRoom.emit(
rtcSession.room.emit(
MatrixRoomEvent.Timeline,
encryptedEvent,
matrixRoom,
rtcSession.room,
undefined,
false,
{} as IRoomTimelineData,
);
},
c: () => {
client.emit(
rtcSession.room.client.emit(
MatrixEventEvent.Decrypted,
new MatrixEvent({
room_id: matrixRoom.roomId,
room_id: rtcSession.room.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: EventType.Reaction,
@@ -318,24 +214,22 @@ test("handles waiting for event decryption", () => {
});
test("hands rejecting events without a proper membership", () => {
const { members$, matrixRoom, client } = getBasicRTCSession([local, alice]);
const { rtcSession } = getBasicRTCSession([local, alice]);
const reactionEventId = "$my_event_id:example.org";
const localTimestamp = new Date();
withTestScheduler(({ schedule, expectObservable }) => {
renderHook(() => {
const { raisedHands$ } = new ReactionsReader(
testScope(),
members$,
matrixRoom,
client,
rtcSession.asMockedSession(),
);
schedule("ab", {
a: () => {},
b: () => {
matrixRoom.emit(
rtcSession.room.emit(
MatrixRoomEvent.Timeline,
new MatrixEvent({
room_id: matrixRoom.roomId,
room_id: rtcSession.room.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: EventType.Reaction,
@@ -347,7 +241,7 @@ test("hands rejecting events without a proper membership", () => {
},
},
}),
matrixRoom,
rtcSession.room,
undefined,
false,
{} as IRoomTimelineData,
@@ -362,7 +256,7 @@ test("hands rejecting events without a proper membership", () => {
});
test("handles a reaction", () => {
const { members$, matrixRoom, client } = getBasicRTCSession([local, alice]);
const { rtcSession } = getBasicRTCSession([local, alice]);
const reactionEventId = "$my_event_id:example.org";
const reaction = ReactionSet[1];
@@ -373,17 +267,15 @@ test("handles a reaction", () => {
renderHook(() => {
const { reactions$ } = new ReactionsReader(
testScope(),
members$,
matrixRoom,
client,
rtcSession.asMockedSession(),
);
schedule(`abc`, {
a: () => {},
b: () => {
matrixRoom.emit(
rtcSession.room.emit(
MatrixRoomEvent.Timeline,
new MatrixEvent({
room_id: matrixRoom.roomId,
room_id: rtcSession.room.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: ElementCallReactionEventType,
@@ -395,7 +287,7 @@ test("handles a reaction", () => {
},
},
}),
matrixRoom,
rtcSession.room,
undefined,
false,
{} as IRoomTimelineData,
@@ -424,11 +316,7 @@ test("handles a reaction", () => {
});
test("ignores bad reaction events", () => {
const {
members$,
matrixRoom: room,
client,
} = getBasicRTCSession([local, alice]);
const { rtcSession } = getBasicRTCSession([local, alice]);
const reactionEventId = "$my_event_id:example.org";
const reaction = ReactionSet[1];
@@ -438,33 +326,31 @@ test("ignores bad reaction events", () => {
renderHook(() => {
const { reactions$ } = new ReactionsReader(
testScope(),
members$,
room,
client,
rtcSession.asMockedSession(),
);
schedule("ab", {
a: () => {},
b: () => {
// Missing content
room.emit(
rtcSession.room.emit(
MatrixRoomEvent.Timeline,
new MatrixEvent({
room_id: room.roomId,
room_id: rtcSession.room.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: ElementCallReactionEventType,
content: {},
}),
room,
rtcSession.room,
undefined,
false,
{} as IRoomTimelineData,
);
// Wrong relates event
room.emit(
rtcSession.room.emit(
MatrixRoomEvent.Timeline,
new MatrixEvent({
room_id: room.roomId,
room_id: rtcSession.room.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: ElementCallReactionEventType,
@@ -476,16 +362,16 @@ test("ignores bad reaction events", () => {
},
},
}),
room,
rtcSession.room,
undefined,
false,
{} as IRoomTimelineData,
);
// Wrong rtc member event
room.emit(
rtcSession.room.emit(
MatrixRoomEvent.Timeline,
new MatrixEvent({
room_id: room.roomId,
room_id: rtcSession.room.roomId,
event_id: reactionEventId,
sender: aliceRtcMember.userId,
type: ElementCallReactionEventType,
@@ -497,16 +383,16 @@ test("ignores bad reaction events", () => {
},
},
}),
room,
rtcSession.room,
undefined,
false,
{} as IRoomTimelineData,
);
// No emoji
room.emit(
rtcSession.room.emit(
MatrixRoomEvent.Timeline,
new MatrixEvent({
room_id: room.roomId,
room_id: rtcSession.room.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: ElementCallReactionEventType,
@@ -517,16 +403,16 @@ test("ignores bad reaction events", () => {
},
},
}),
room,
rtcSession.room,
undefined,
false,
{} as IRoomTimelineData,
);
// Invalid emoji
room.emit(
rtcSession.room.emit(
MatrixRoomEvent.Timeline,
new MatrixEvent({
room_id: room.roomId,
room_id: rtcSession.room.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: ElementCallReactionEventType,
@@ -538,7 +424,7 @@ test("ignores bad reaction events", () => {
},
},
}),
room,
rtcSession.room,
undefined,
false,
{} as IRoomTimelineData,
@@ -553,7 +439,7 @@ test("ignores bad reaction events", () => {
});
test("that reactions cannot be spammed", () => {
const { members$, matrixRoom, client } = getBasicRTCSession([local, alice]);
const { rtcSession } = getBasicRTCSession([local, alice]);
const reactionEventId = "$my_event_id:example.org";
const reactionA = ReactionSet[1];
const reactionB = ReactionSet[2];
@@ -565,17 +451,15 @@ test("that reactions cannot be spammed", () => {
renderHook(() => {
const { reactions$ } = new ReactionsReader(
testScope(),
members$,
matrixRoom,
client,
rtcSession.asMockedSession(),
);
schedule("abcd", {
a: () => {},
b: () => {
matrixRoom.emit(
rtcSession.room.emit(
MatrixRoomEvent.Timeline,
new MatrixEvent({
room_id: matrixRoom.roomId,
room_id: rtcSession.room.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: ElementCallReactionEventType,
@@ -587,17 +471,17 @@ test("that reactions cannot be spammed", () => {
},
},
}),
matrixRoom,
rtcSession.room,
undefined,
false,
{} as IRoomTimelineData,
);
},
c: () => {
matrixRoom.emit(
rtcSession.room.emit(
MatrixRoomEvent.Timeline,
new MatrixEvent({
room_id: matrixRoom.roomId,
room_id: rtcSession.room.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: ElementCallReactionEventType,
@@ -609,7 +493,7 @@ test("that reactions cannot be spammed", () => {
},
},
}),
matrixRoom,
rtcSession.room,
undefined,
false,
{} as IRoomTimelineData,
+66 -87
View File
@@ -5,28 +5,20 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { logger } from "matrix-js-sdk/lib/logger";
import {
type MatrixClient,
type MatrixEvent,
MatrixEventEvent,
type Room,
} from "matrix-js-sdk";
type CallMembership,
MatrixRTCSessionEvent,
type MatrixRTCSession,
} from "matrix-js-sdk/lib/matrixrtc";
import { logger } from "matrix-js-sdk/lib/logger";
import { type MatrixEvent, MatrixEventEvent } from "matrix-js-sdk";
import { type ReactionEventContent } from "matrix-js-sdk/lib/types";
import {
RelationType,
EventType,
RoomEvent as MatrixRoomEvent,
} from "matrix-js-sdk";
import {
BehaviorSubject,
combineLatest,
delay,
map,
of,
switchMap,
} from "rxjs";
import { type RTCMember } from "@element-hq/matrixrtc-sdk";
import { BehaviorSubject, delay } from "rxjs";
import {
ElementCallReactionEventType,
@@ -37,20 +29,13 @@ import {
type ReactionInfo,
} from ".";
import { type ObservableScope } from "../state/ObservableScope";
import { type Behavior } from "../state/Behavior";
export const REACTION_ACTIVE_TIME_MS = 3000;
/** A member's membership event, which its reactions relate to. */
interface MembershipEvent {
userId: string;
deviceId: string;
eventId: string;
}
/**
* Listens for reactions to the slot members' memberships and populates
* subjects for consumption by the CallViewModel.
* Listens for reactions from a RTCSession and populates subjects
* for consumption by the CallViewModel.
* @param rtcSession
*/
export class ReactionsReader {
private readonly raisedHandsSubject$ = new BehaviorSubject<
@@ -70,33 +55,9 @@ export class ReactionsReader {
*/
public readonly reactions$ = this.reactionsSubject$.asObservable();
private memberships: MembershipEvent[] = [];
public constructor(
private readonly scope: ObservableScope,
members$: Behavior<RTCMember[]>,
private readonly room: Pick<
Room,
// To ignore events from other rooms
| "roomId"
// The raised hands already in the room, as reactions to memberships
| "relations"
// `on`/`off`, to listen for:
// - `RoomEvent.Timeline` (new reactions)
// - `RoomEvent.Redaction` (lowered hands)
// - `RoomEvent.LocalEchoUpdated` (the real id of our own reactions)
| "on"
| "off"
>,
private readonly client: Pick<
MatrixClient,
// Reactions that arrived encrypted
| "decryptEventIfNeeded"
// `on`/`off`, to listen for:
// - `MatrixEventEvent.Decrypted` (reactions once decrypted)
| "on"
| "off"
>,
private readonly rtcSession: MatrixRTCSession,
) {
// Hide reactions after a given time.
this.reactionsSubject$
@@ -115,44 +76,62 @@ export class ReactionsReader {
// TODO: Convert this class to the functional reactive style and get rid of
// all this manual setup and teardown for event listeners
this.room.on(MatrixRoomEvent.Timeline, this.handleReactionEvent);
this.rtcSession.room.on(MatrixRoomEvent.Timeline, this.handleReactionEvent);
this.scope.onEnd(() =>
this.room.off(MatrixRoomEvent.Timeline, this.handleReactionEvent),
this.rtcSession.room.off(
MatrixRoomEvent.Timeline,
this.handleReactionEvent,
),
);
this.room.on(MatrixRoomEvent.Redaction, this.handleReactionEvent);
this.rtcSession.room.on(
MatrixRoomEvent.Redaction,
this.handleReactionEvent,
);
this.scope.onEnd(() =>
this.room.off(MatrixRoomEvent.Redaction, this.handleReactionEvent),
this.rtcSession.room.off(
MatrixRoomEvent.Redaction,
this.handleReactionEvent,
),
);
this.client.on(MatrixEventEvent.Decrypted, this.handleReactionEvent);
this.rtcSession.room.client.on(
MatrixEventEvent.Decrypted,
this.handleReactionEvent,
);
this.scope.onEnd(() =>
this.client.off(MatrixEventEvent.Decrypted, this.handleReactionEvent),
this.rtcSession.room.client.off(
MatrixEventEvent.Decrypted,
this.handleReactionEvent,
),
);
// We listen for a local echo to get the real event ID, as timeline events
// may still be sending.
this.room.on(MatrixRoomEvent.LocalEchoUpdated, this.handleReactionEvent);
this.rtcSession.room.on(
MatrixRoomEvent.LocalEchoUpdated,
this.handleReactionEvent,
);
this.scope.onEnd(() =>
this.room.off(MatrixRoomEvent.LocalEchoUpdated, this.handleReactionEvent),
this.rtcSession.room.off(
MatrixRoomEvent.LocalEchoUpdated,
this.handleReactionEvent,
),
);
members$
.pipe(
switchMap((members) =>
members.length === 0
? of([])
: combineLatest(
members.map(({ userId, deviceId, matrixEventId$ }) =>
matrixEventId$.pipe(
map((eventId) => ({ userId, deviceId, eventId })),
),
),
),
),
this.scope.bind(),
)
.subscribe(this.onMembershipsChanged);
this.rtcSession.on(
MatrixRTCSessionEvent.MembershipsChanged,
this.onMembershipsChanged,
);
this.scope.onEnd(() =>
this.rtcSession.off(
MatrixRTCSessionEvent.MembershipsChanged,
this.onMembershipsChanged,
),
);
// Run this once to ensure we have fetched the state from the call.
this.onMembershipsChanged([]);
}
/**
@@ -166,7 +145,7 @@ export class ReactionsReader {
membershipEventId: string,
expectedSender: string,
): MatrixEvent | undefined {
const relations = this.room.relations.getChildEventsForEvent(
const relations = this.rtcSession.room.relations.getChildEventsForEvent(
membershipEventId,
RelationType.Annotation,
EventType.Reaction,
@@ -183,23 +162,22 @@ export class ReactionsReader {
/**
* Will remove any hand raises by old members, and look for any
* existing hand raises by new members.
* @param memberships The membership events of everyone in the call now.
* @param oldMemberships Any members who have left the call.
*/
private onMembershipsChanged = (memberships: MembershipEvent[]): void => {
this.memberships = memberships;
private onMembershipsChanged = (oldMemberships: CallMembership[]): void => {
// Remove any raised hands for users no longer joined to the call.
const present = new Set(
memberships.map((m) => `${m.userId}:${m.deviceId}`),
);
for (const identifier of Object.keys(this.raisedHandsSubject$.value).filter(
(rhId) => !present.has(rhId),
(rhId) => oldMemberships.find((u) => u.userId == rhId),
)) {
this.removeRaisedHand(identifier);
}
// For each member in the call, check to see if a reaction has
// been raised and adjust.
for (const m of memberships) {
for (const m of this.rtcSession.memberships) {
if (!m.userId || !m.eventId) {
continue;
}
const identifier = `${m.userId}:${m.deviceId}`;
if (
this.raisedHandsSubject$.value[identifier] &&
@@ -257,8 +235,9 @@ export class ReactionsReader {
* @param event The incoming matrix event, which may or may not be decrypted.
*/
private handleReactionEvent = (event: MatrixEvent): void => {
const room = this.rtcSession.room;
// Decrypted events might come from a different room
if (event.getRoomId() !== this.room.roomId) return;
if (event.getRoomId() !== room.roomId) return;
// Skip any events that are still sending.
if (event.isSending()) return;
@@ -267,7 +246,7 @@ export class ReactionsReader {
// Skip any event without a sender or event ID.
if (!sender || !reactionEventId) return;
this.client
room.client
.decryptEventIfNeeded(event)
.catch((e) => logger.warn(`Failed to decrypt ${event.getId()}`, e));
if (event.isBeingDecrypted() || event.isDecryptionFailure()) return;
@@ -276,7 +255,7 @@ export class ReactionsReader {
const content: ECallReactionEventContent = event.getContent();
const membershipEventId = content?.["m.relates_to"]?.event_id;
const membershipEvent = this.memberships.find(
const membershipEvent = this.rtcSession.memberships.find(
(e) => e.eventId === membershipEventId && e.userId === sender,
);
// Check to see if this reaction was made to a membership event (and the
@@ -336,7 +315,7 @@ export class ReactionsReader {
// Check to see if this reaction was made to a membership event (and the
// sender of the reaction matches the membership)
const membershipEvent = this.memberships.find(
const membershipEvent = this.rtcSession.memberships.find(
(e) => e.eventId === membershipEventId && e.userId === sender,
);
if (!membershipEvent) {
+38 -40
View File
@@ -5,12 +5,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import {
EventType,
type MatrixClient,
RelationType,
type Room,
} from "matrix-js-sdk";
import { EventType, RelationType } from "matrix-js-sdk";
import {
createContext,
use,
@@ -19,15 +14,14 @@ import {
useMemo,
type JSX,
} from "react";
import { type MatrixRTCSession } from "matrix-js-sdk/lib/matrixrtc";
import { logger } from "matrix-js-sdk/lib/logger";
import { useMatrixRTCSessionMemberships } from "../useMatrixRTCSessionMemberships";
import { useClientState } from "../ClientContext";
import { ElementCallReactionEventType, type ReactionOption } from ".";
import { type CallViewModel } from "../state/CallViewModel/CallViewModel";
import { useBehavior } from "../useBehavior";
import { constant } from "../state/Behavior";
const noMembershipEvent$ = constant(undefined);
interface ReactionsSenderContextType {
supportsReactions: boolean;
@@ -52,34 +46,28 @@ export const useReactionsSender = (): ReactionsSenderContextType => {
*/
export const ReactionsSenderProvider = ({
children,
room,
client,
rtcSession,
vm,
}: {
children: ReactNode;
/** The room the reactions are sent in. */
room: Pick<Room, "roomId">;
client: Pick<
MatrixClient,
// Our own identity, which reactions and raised hands are keyed by
| "getUserId"
| "getDeviceId"
// Sending reactions and raising a hand
| "sendEvent"
// Lowering a hand
| "redactEvent"
>;
/** Our own membership, which the reactions relate to, and the current reactions. */
rtcSession: MatrixRTCSession;
vm: CallViewModel;
}): JSX.Element => {
const memberships = useMatrixRTCSessionMemberships(rtcSession);
const clientState = useClientState();
const supportsReactions =
clientState?.state === "valid" && clientState.supportedFeatures.reactions;
const myMembershipIdentifier = `${client.getUserId()}:${client.getDeviceId()}`;
const room = rtcSession.room;
const myUserId = room.client.getUserId();
const myDeviceId = room.client.getDeviceId();
const myMembershipIdentifier = `${myUserId}:${myDeviceId}`;
const localMember = useBehavior(vm.localMember$);
const myMembershipEvent = useBehavior(
localMember?.matrixEventId$ ?? noMembershipEvent$,
const myMembershipEvent = useMemo(
() =>
memberships.find(
(m) => m.userId === myUserId && m.deviceId === myDeviceId,
)?.eventId,
[memberships, myUserId, myDeviceId],
);
const reactions = useBehavior(vm.reactions$);
@@ -111,8 +99,8 @@ export const ReactionsSenderProvider = ({
if (!myMembershipEvent) {
throw new Error("Cannot find own membership event");
}
const reaction = await client.sendEvent(
room.roomId,
const reaction = await room.client.sendEvent(
rtcSession.room.roomId,
EventType.Reaction,
{
"m.relates_to": {
@@ -128,14 +116,20 @@ export const ReactionsSenderProvider = ({
}
} else {
try {
await client.redactEvent(room.roomId, myReactionId);
await room.client.redactEvent(rtcSession.room.roomId, myReactionId);
logger.debug("Redacted raise hand event");
} catch (ex) {
logger.error("Failed to redact reaction event", myReactionId, ex);
throw ex;
}
}
}, [myMembershipEvent, myMembershipIdentifier, myRaisedHand, client, room]);
}, [
myMembershipEvent,
myMembershipIdentifier,
myRaisedHand,
rtcSession,
room,
]);
const sendReaction = useCallback(
async (reaction: ReactionOption) => {
@@ -146,16 +140,20 @@ export const ReactionsSenderProvider = ({
if (!myMembershipEvent) {
throw new Error("Cannot find own membership event");
}
await client.sendEvent(room.roomId, ElementCallReactionEventType, {
"m.relates_to": {
rel_type: RelationType.Reference,
event_id: myMembershipEvent,
await room.client.sendEvent(
rtcSession.room.roomId,
ElementCallReactionEventType,
{
"m.relates_to": {
rel_type: RelationType.Reference,
event_id: myMembershipEvent,
},
emoji: reaction.emoji,
name: reaction.name,
},
emoji: reaction.emoji,
name: reaction.name,
});
);
},
[myMembershipEvent, myReaction, client, room, myMembershipIdentifier],
[myMembershipEvent, myReaction, room, myMembershipIdentifier, rtcSession],
);
return (
+3 -2
View File
@@ -6,12 +6,13 @@ Please see LICENSE in the repository root for full details.
*/
import { type FC, type FormEventHandler, useCallback, useState } from "react";
import { type MatrixClient } from "matrix-js-sdk";
import { Trans, useTranslation } from "react-i18next";
import { Button, Heading, Text } from "@vector-im/compound-web";
import styles from "./CallEndedView.module.css";
import feedbackStyle from "../input/FeedbackInput.module.css";
import { type ProfileClientParts, useProfile } from "../profile/useProfile";
import { useProfile } from "../profile/useProfile";
import { Header, HeaderLogo, LeftNav, RightNav } from "../Header";
import { PosthogAnalytics } from "../analytics/PosthogAnalytics";
import { FieldRow, InputField } from "../input/Input";
@@ -21,7 +22,7 @@ import { LeaveToHomeLink } from "../button/LeaveToHomeLink";
import { useLeaveToHome } from "../LeaveToHomeContext";
interface Props {
client: ProfileClientParts;
client: MatrixClient;
isPasswordlessUser: boolean;
hideHeader: boolean;
confineToRoom: boolean;
+80 -46
View File
@@ -19,8 +19,16 @@ import {
vitest,
} from "vitest";
import { render, waitFor, screen, act } from "@testing-library/react";
import { type MatrixClient, JoinRule } from "matrix-js-sdk";
import { type MatrixRTCSession } from "matrix-js-sdk/lib/matrixrtc";
import {
type MatrixClient,
JoinRule,
type RoomState,
UnsupportedStickyEventsEndpointError,
} from "matrix-js-sdk";
import {
MatrixRTCSessionEvent,
type MatrixRTCSession,
} from "matrix-js-sdk/lib/matrixrtc";
import { BrowserRouter } from "react-router-dom";
import userEvent, {
PointerEventsCheckLevel,
@@ -45,7 +53,7 @@ import {
testScope,
} from "../utils/test";
import { CallView } from "./CallView";
import { type CallMatrixBackend } from "../CallMatrixBackend";
import { GroupCallErrorBoundary } from "./GroupCallErrorBoundary";
import {
type HostBridge,
HostBridgeProvider,
@@ -53,10 +61,7 @@ import {
nullHostBridge,
} from "../HostBridge";
import { type JoinCallData } from "../widget";
import {
ConnectionLostError,
MatrixRTCTransportMissingError,
} from "../utils/errors";
import { MatrixRTCTransportMissingError } from "../utils/errors";
import {
BackgroundEffectsProvider,
createAppBackgroundEffects,
@@ -141,6 +146,7 @@ function createCallView(
hostBridge: HostBridge,
joined = true,
options: {
withErrorBoundary?: boolean;
/** Wait for the host to say when to join, rather than joining at once. */
preload?: boolean;
} = {},
@@ -149,7 +155,6 @@ function createCallView(
getByText: ReturnType<typeof render>["getByText"];
} {
const client = {
...mockEmitter(),
getUser: () => null,
getUserId: () => localRtcMember.userId,
getDeviceId: () => localRtcMember.deviceId,
@@ -165,14 +170,28 @@ function createCallView(
client,
roomId,
getMember: (userId) => roomMembers.get(userId) ?? null,
getMembersWithMembership: () => [carol],
getMxcAvatarUrl: () => null,
getJoinRule: () => JoinRule.Invite,
getCanonicalAlias: () => null,
currentState: {
...mockEmitter(),
getJoinRule: () => JoinRule.Invite,
} as Partial<RoomState> as RoomState,
});
const rtcSession = new MockRTCSession(room, []).withMemberships(
constant([localRtcMember]),
);
rtcSession.joined = joined;
const callView = (
<CallView
client={client}
isPasswordlessUser={false}
confineToRoom={false}
preload={options.preload ?? false}
// Straight into the (mocked) call, past the lobby
skipLobby
rtcSession={rtcSession.asMockedSession()}
/>
);
const { getByText } = render(
<BrowserRouter>
<HostBridgeProvider value={hostBridge}>
@@ -181,22 +200,13 @@ function createCallView(
<BackgroundEffectsProvider
effects={createAppBackgroundEffects(testScope())}
>
<CallView
backend={
{
...client,
...room,
clientEmitter: client,
roomEmitter: room,
} as unknown as CallMatrixBackend
}
isPasswordlessUser={false}
confineToRoom={false}
preload={options.preload ?? false}
// Straight into the (mocked) call, past the lobby
skipLobby
rtcSession={rtcSession.asMockedSession()}
/>
{options.withErrorBoundary ? (
<GroupCallErrorBoundary recoveryActionHandler={vi.fn()}>
{callView}
</GroupCallErrorBoundary>
) : (
callView
)}
</BackgroundEffectsProvider>
</MediaDevicesContext>
</TooltipProvider>
@@ -361,28 +371,52 @@ test.skip("CallView shows errors that occur during joining", async () => {
screen.getByText("Call is not supported");
});
test("user can reconnect after losing the connection", async () => {
// What the call throws once the view model reports the connection lost
(ActiveCall as MockedFunction<typeof ActiveCall>).mockImplementation(
({ onLeft }) => {
const [error, setError] = useState<Error | null>(null);
if (error !== null) throw error;
return (
<div>
<button onClick={() => onLeft("user")}>Leave</button>
<button onClick={() => setError(new ConnectionLostError())}>
LoseConnection
</button>
</div>
);
},
test("translates wrapped UnsupportedStickyEventsEndpointError to the StickyEventsRequiredError screen", async () => {
// Mirror the shape the SDK emits: the MembershipManager scheduler wraps
// the original UnsupportedStickyEventsEndpointError in a generic Error
// but preserves the original on `.cause`.
const stickyError = new UnsupportedStickyEventsEndpointError(
"Server does not support the sticky events",
"sendStickyEvent",
);
const user = userEvent.setup();
createCallView(nullHostBridge, true);
await user.click(screen.getByRole("button", { name: "LoseConnection" }));
const wrappedError = new Error(
"The MembershipManager shut down because of the end condition: " +
String(stickyError),
{ cause: stickyError },
);
const { rtcSession } = createCallView(nullHostBridge, true, {
withErrorBoundary: true,
});
await act(() =>
rtcSession.emit(MatrixRTCSessionEvent.MembershipManagerError, wrappedError),
);
await screen.findByText("Homeserver does not support Matrix 2.0 calls");
});
test("falls back to ConnectionLostError for unrecognised membership manager errors", async () => {
const { rtcSession } = createCallView(nullHostBridge, true, {
withErrorBoundary: true,
});
await act(() =>
rtcSession.emit(
MatrixRTCSessionEvent.MembershipManagerError,
new Error("something else broke"),
),
);
await screen.findByText("Connection lost");
// Never joined, so there was no call to leave
expect(playSound).not.toHaveBeenCalled();
});
test("user can reconnect after a membership manager error", async () => {
const user = userEvent.setup();
const { rtcSession } = createCallView(nullHostBridge, true);
await act(() =>
rtcSession.emit(MatrixRTCSessionEvent.MembershipManagerError, undefined),
);
// XXX: Wrapping the following click in act() shouldn't be necessary (the
// async state update should be processed automatically by the waitFor call),
// and yet here we are.

Some files were not shown because too many files have changed in this diff Show More