mirror of
https://github.com/vector-im/element-call.git
synced 2026-11-28 10:01:09 +08:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0eff661159 |
@@ -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
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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 }}
|
||||
|
||||
@@ -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"
|
||||
@@ -46,5 +41,3 @@ jobs:
|
||||
run: "pnpm run lint:types"
|
||||
- name: Dead code analysis
|
||||
run: "pnpm run lint:knip"
|
||||
- name: Component externals
|
||||
run: "pnpm run lint:externals"
|
||||
|
||||
@@ -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: |
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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).
|
||||
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -2,7 +2,6 @@ node_modules
|
||||
.DS_Store
|
||||
.env
|
||||
dist
|
||||
/dist-widget-rtc-sdk-example
|
||||
dist-ssr
|
||||
*.local
|
||||
*.bkp
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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),
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -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}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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}
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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:f85350f2b31a7521a800d9050e9f5c0676d04cfb60675242ccc0c6e25cad7d04
|
||||
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:f85350f2b31a7521a800d9050e9f5c0676d04cfb60675242ccc0c6e25cad7d04
|
||||
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
@@ -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` /
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
```
|
||||
|
||||
@@ -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",
|
||||
],
|
||||
|
||||
@@ -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.",
|
||||
|
||||
+13
-15
@@ -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,21 @@
|
||||
"build-storybook": "storybook build"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@codecov/vite-plugin": "^2.0.0",
|
||||
"@base-ui/react": "^1.9.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 +80,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 +92,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 +115,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
@@ -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,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -1,78 +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, type Page } from "@playwright/test";
|
||||
|
||||
import { SpaHelpers } from "./spa-helpers.ts";
|
||||
|
||||
test.use({
|
||||
launchOptions: {
|
||||
args: [
|
||||
"--use-fake-ui-for-media-stream",
|
||||
"--use-fake-device-for-media-stream=device-count=2",
|
||||
"--mute-audio",
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
test.describe("the camera menu", () => {
|
||||
test.skip(
|
||||
({ browserName }) => browserName !== "chromium",
|
||||
"Only Chromium offers a second fake camera",
|
||||
);
|
||||
|
||||
test("moves the preview to the camera picked, and the call after it", async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.goto("/");
|
||||
await SpaHelpers.createCall(page, "Camera user", "Camera switch");
|
||||
await expectCamera(page, "fake_device_0");
|
||||
|
||||
await selectCamera(page, "fake_device_1");
|
||||
await expectCamera(page, "fake_device_1");
|
||||
|
||||
await page.getByTestId("lobby_joinCall").click();
|
||||
await expect(page.getByTestId("name_tag")).toContainText("Camera user");
|
||||
await expectCamera(page, "fake_device_1");
|
||||
|
||||
await selectCamera(page, "fake_device_0");
|
||||
await expectCamera(page, "fake_device_0");
|
||||
|
||||
// Turning the camera on again opens it anew
|
||||
const camera = page.getByTestId("incall_videomute");
|
||||
await camera.click();
|
||||
await expect(camera).toHaveAttribute("aria-checked", "false");
|
||||
await camera.click();
|
||||
await expect(camera).toHaveAttribute("aria-checked", "true");
|
||||
await expectCamera(page, "fake_device_0");
|
||||
});
|
||||
});
|
||||
|
||||
async function selectCamera(page: Page, name: string): Promise<void> {
|
||||
await page.getByRole("button", { name: "Camera", exact: true }).click();
|
||||
await page.getByRole("menuitemradio", { name }).click();
|
||||
// Selecting doesn't close the menu, so dismiss it.
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(page.getByRole("menu")).not.toBeVisible();
|
||||
}
|
||||
|
||||
/** Every video on the page shows this camera, and there is one that does. */
|
||||
async function expectCamera(page: Page, label: string): Promise<void> {
|
||||
await expect
|
||||
.poll(async () =>
|
||||
page.evaluate(() => [
|
||||
...new Set(
|
||||
[...document.querySelectorAll("video")].flatMap((video) =>
|
||||
video.srcObject instanceof MediaStream
|
||||
? video.srcObject.getVideoTracks().map((track) => track.label)
|
||||
: [],
|
||||
),
|
||||
),
|
||||
]),
|
||||
)
|
||||
.toEqual([label]);
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,36 +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 "@playwright/test";
|
||||
|
||||
import { SpaHelpers } from "./spa-helpers.ts";
|
||||
|
||||
test("The full screen button can be clicked while the footer overlays the video", async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.goto("/");
|
||||
await SpaHelpers.createCall(page, "John Doe", "ShortWindow", true);
|
||||
await SpaHelpers.expectVideoTilesCount(page, 1);
|
||||
|
||||
const fullScreenButton = page.getByRole("button", { name: "maximise" });
|
||||
const footer = page.getByTestId("footer-container");
|
||||
|
||||
// Short enough for the footer to be drawn over the video
|
||||
await page.setViewportSize({ width: 1000, height: 500 });
|
||||
await expect(fullScreenButton).toBeVisible();
|
||||
await page.getByTestId("videoTile").first().hover();
|
||||
await expect(footer).toHaveCSS("opacity", "1");
|
||||
|
||||
const buttonBox = (await fullScreenButton.boundingBox())!;
|
||||
const footerBox = (await footer.boundingBox())!;
|
||||
expect(buttonBox.y + buttonBox.height).toBeLessThanOrEqual(footerBox.y);
|
||||
|
||||
await fullScreenButton.click();
|
||||
await expect
|
||||
.poll(async () => page.evaluate(() => document.fullscreenElement !== null))
|
||||
.toBe(true);
|
||||
});
|
||||
@@ -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/),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,95 +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, type Page } from "@playwright/test";
|
||||
|
||||
import { widgetTest } from "../fixtures/widget-user.ts";
|
||||
import { TestHelpers } from "./test-helpers.ts";
|
||||
|
||||
widgetTest.use({ callType: "dm" });
|
||||
|
||||
// The bug from issue #4403, in a real call between two users in Element Web.
|
||||
// 1. Brooks' browser is made slow: it lists its camera and microphone only
|
||||
// after the call is on screen.
|
||||
// 2. Brooks starts a video call in a DM. A DM call has no lobby.
|
||||
// 3. Whistler picks up.
|
||||
// 4. Brooks' camera button shows "on".
|
||||
// 5. Whistler must see two videos: their own and the one brooks sends.
|
||||
// Before the fix whistler saw only their own video.
|
||||
//
|
||||
// What it guards: the unit tests only check the mute button's own logic. This
|
||||
// test checks the whole chain: button, call, SFU, and what the other person
|
||||
// really sees. The bug depends on timing (camera listed before or after the
|
||||
// call opens), so the normal DM call tests pass by luck most of the time.
|
||||
// This test forces the bad timing every run, so a regression shows up always
|
||||
// and not only sometimes.
|
||||
widgetTest(
|
||||
"Publishes a camera the browser lists only once the call is on screen",
|
||||
async ({ asWidget, browserName }) => {
|
||||
test.skip(
|
||||
browserName === "firefox",
|
||||
"The is test is not working on firefox CI environment. No mic/audio device inputs so cam/mic are disabled",
|
||||
);
|
||||
|
||||
// Two Element Webs and a real call.
|
||||
test.slow();
|
||||
const { brooks, whistler } = asWidget;
|
||||
await listDevicesOnlyInTheCall(brooks.page);
|
||||
|
||||
await TestHelpers.startCallInCurrentRoom(brooks.page, false);
|
||||
await expect(whistler.page.getByText("Incoming video call")).toBeVisible();
|
||||
await whistler.page
|
||||
.getByRole("alert")
|
||||
.getByRole("button", { name: "Join" })
|
||||
.click();
|
||||
|
||||
const brooksFrame = brooks.page
|
||||
.locator('iframe[title="Element Call"]')
|
||||
.contentFrame();
|
||||
await expect(
|
||||
brooksFrame.getByRole("switch", { name: "Stop video", checked: true }),
|
||||
).toBeVisible();
|
||||
|
||||
// Whistler's own camera and the one brooks sends
|
||||
const whistlerFrame = whistler.page
|
||||
.locator('iframe[title="Element Call"]')
|
||||
.contentFrame();
|
||||
await TestHelpers.expectVisibleVideoCount(whistlerFrame, 2);
|
||||
await expect(whistlerFrame.getByText("Waiting for media...")).toHaveCount(
|
||||
0,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* Holds the device list back in the widget until the call view shows a tile,
|
||||
* as a browser that is slow to answer does. Call before the widget loads.
|
||||
*
|
||||
* How: it replaces the browser's `enumerateDevices` with one that waits. It
|
||||
* checks every 50ms whether a video tile is on the page, waits half a second
|
||||
* more, and only then gives the real list. Element Web itself (the outer
|
||||
* page) is left alone; only the call inside the iframe is slowed down.
|
||||
*/
|
||||
async function listDevicesOnlyInTheCall(page: Page): Promise<void> {
|
||||
await page.addInitScript(() => {
|
||||
if (window.parent === window) return;
|
||||
const devices = navigator.mediaDevices;
|
||||
const enumerate = devices.enumerateDevices.bind(devices);
|
||||
const inTheCall = new Promise<void>((resolve) => {
|
||||
const poll = setInterval(() => {
|
||||
if (document.querySelector("[data-testid='videoTile']") === null)
|
||||
return;
|
||||
clearInterval(poll);
|
||||
setTimeout(resolve, 500);
|
||||
}, 50);
|
||||
});
|
||||
devices.enumerateDevices = async (): Promise<MediaDeviceInfo[]> => {
|
||||
await inTheCall;
|
||||
return enumerate();
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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" },
|
||||
);
|
||||
});
|
||||
@@ -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!",
|
||||
);
|
||||
},
|
||||
);
|
||||
Generated
+2360
-1963
File diff suppressed because it is too large
Load Diff
+14
-10
@@ -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"
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
@@ -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
@@ -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`
|
||||
```
|
||||
|
||||
|
||||
+16
-17
@@ -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
|
||||
|
||||
@@ -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`.
|
||||
@@ -781,6 +779,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
|
||||
|
||||
@@ -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
@@ -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 =
|
||||
|
||||
@@ -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,
|
||||
|
||||
+17
-195
@@ -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" },
|
||||
@@ -24,7 +24,7 @@ describe("createLocalMedia", () => {
|
||||
]);
|
||||
|
||||
expect(getUserMedia).toHaveBeenCalledExactlyOnceWith({
|
||||
audio: { deviceId: { exact: "mic" } },
|
||||
audio: { deviceId: "mic" },
|
||||
video: { width: 640, height: 480, frameRate: undefined },
|
||||
});
|
||||
expect(tracks.map((t) => t.source)).toEqual(["microphone", "camera"]);
|
||||
@@ -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: "other" },
|
||||
});
|
||||
expect(first.stop).toHaveBeenCalled();
|
||||
expect(processor.restart).toHaveBeenCalledOnce();
|
||||
@@ -157,140 +132,14 @@ 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" } }),
|
||||
);
|
||||
});
|
||||
|
||||
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 });
|
||||
|
||||
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" } }) }],
|
||||
]);
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
it("keeps the camera it has where another cannot be opened", async () => {
|
||||
const getUserMedia = vi.mocked(fakeGetUserMedia());
|
||||
const media = createLocalMedia({ getUserMedia });
|
||||
const [camera] = await media.capture([
|
||||
{ source: "camera", deviceId: "cam" },
|
||||
]);
|
||||
const first = trackBehind(camera);
|
||||
getUserMedia.mockRejectedValueOnce(overconstrained());
|
||||
|
||||
await expect(camera.setDevice("unplugged")).rejects.toThrow();
|
||||
|
||||
expect(first.stop).not.toHaveBeenCalled();
|
||||
expect(media.takeTracks().get("camera")).toMatchObject({
|
||||
track: first,
|
||||
constraints: { deviceId: { exact: "cam" } },
|
||||
});
|
||||
});
|
||||
|
||||
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 [camera] = (await media.capture([
|
||||
{ source: "camera", deviceId: "front" },
|
||||
])) as [LocalVideoMediaTrack];
|
||||
|
||||
await camera.switchFacingMode();
|
||||
|
||||
expect(getUserMedia).toHaveBeenLastCalledWith({
|
||||
video: at720p({ facingMode: "environment" }),
|
||||
expect(media.takeTracks().get("camera")?.constraints).toEqual({
|
||||
deviceId: "other",
|
||||
});
|
||||
});
|
||||
|
||||
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 +148,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 +162,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 +179,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,33 +227,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" });
|
||||
}
|
||||
|
||||
function fakeProcessor(): VideoProcessor & { output: MediaStreamTrack } {
|
||||
const output = fakeTrack("video");
|
||||
return {
|
||||
|
||||
+24
-138
@@ -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<
|
||||
@@ -96,14 +78,11 @@ export function createLocalMedia({
|
||||
);
|
||||
bySource.set(request.source, request);
|
||||
}
|
||||
const { stream, constraints } = await open(getUserMedia, {
|
||||
microphone: bySource.has("microphone")
|
||||
? trackConstraints(bySource.get("microphone")!, cameraResolution)
|
||||
: undefined,
|
||||
camera: bySource.has("camera")
|
||||
? trackConstraints(bySource.get("camera")!, cameraResolution)
|
||||
: undefined,
|
||||
});
|
||||
const constraints: MediaStreamConstraints = {};
|
||||
for (const request of bySource.values())
|
||||
constraints[request.source === "microphone" ? "audio" : "video"] =
|
||||
trackConstraints(request);
|
||||
const stream = await getUserMedia(constraints);
|
||||
const captured: CapturedTrack[] = [];
|
||||
for (const track of stream.getTracks()) {
|
||||
const source: Source = track.kind === "audio" ? "microphone" : "camera";
|
||||
@@ -112,7 +91,7 @@ export function createLocalMedia({
|
||||
const captured_ = new CapturedTrack(
|
||||
source,
|
||||
track,
|
||||
constraints[source]!,
|
||||
trackConstraints(request),
|
||||
getUserMedia,
|
||||
);
|
||||
capturedTracks.set(source, captured_);
|
||||
@@ -160,86 +139,18 @@ export function createLocalMedia({
|
||||
};
|
||||
}
|
||||
|
||||
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.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
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 {
|
||||
// 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
|
||||
// opens its default device.
|
||||
const device = request.deviceId && {
|
||||
deviceId: { exact: request.deviceId },
|
||||
};
|
||||
function trackConstraints(request: Request): MediaTrackConstraints {
|
||||
const device = request.deviceId && { deviceId: 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,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -273,12 +184,7 @@ class CapturedTrack {
|
||||
// The device actually in use, so that a backend asked for it again
|
||||
// recognises it rather than restarting the track
|
||||
const { deviceId } = track.getSettings();
|
||||
// `exact` here too: the call reopens the camera with these constraints
|
||||
// after a mute, and must get the same device again, not the default one
|
||||
const constraints = {
|
||||
...this.constraints,
|
||||
...(deviceId && { deviceId: { exact: deviceId } }),
|
||||
};
|
||||
const constraints = { ...this.constraints, ...(deviceId && { deviceId }) };
|
||||
this.finish();
|
||||
return { track, constraints, muted: this.muted$.value, processor };
|
||||
}
|
||||
@@ -339,28 +245,12 @@ class CapturedTrack {
|
||||
for (const element of this.elements) play(element, this.shown());
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the current with the one from the selector. On fail, keep current.
|
||||
*
|
||||
* The old `deviceId` and `facingMode` are removed before the new selector
|
||||
* is applied. This is needed because we use `exact` device ids: if the old
|
||||
* exact id stayed, asking for a new facing mode could not leave the deviceId.
|
||||
* "flip camera" would do nothing.
|
||||
*/
|
||||
private async reacquire(
|
||||
selector: Pick<MediaTrackConstraints, "deviceId" | "facingMode">,
|
||||
): Promise<void> {
|
||||
private async reacquire(constraints: MediaTrackConstraints): Promise<void> {
|
||||
this.live();
|
||||
const constraints = {
|
||||
...this.constraints,
|
||||
// One selects the device at a time: a facing mode cannot move a track
|
||||
// off a device it is pinned to
|
||||
deviceId: undefined,
|
||||
facingMode: undefined,
|
||||
...selector,
|
||||
};
|
||||
const stream = await this.getUserMedia({ [this.track.kind]: constraints });
|
||||
this.constraints = constraints;
|
||||
this.constraints = { ...this.constraints, ...constraints };
|
||||
const stream = await this.getUserMedia({
|
||||
[this.track.kind]: this.constraints,
|
||||
});
|
||||
this.track.stop();
|
||||
this.track = stream.getTracks()[0];
|
||||
this.track.enabled = !this.muted$.value;
|
||||
@@ -398,11 +288,7 @@ class CapturedTrack {
|
||||
},
|
||||
setDevice: async (deviceId: string): Promise<void> => {
|
||||
if (this.track.getSettings().deviceId === deviceId) return;
|
||||
// THE FIX for "cannot switch cameras in Chrome" (#4479), switching in
|
||||
// the lobby. With a plain `{ deviceId }` Chromium reopened the same
|
||||
// camera, so the preview only flashed. `exact` opens the one picked,
|
||||
// or rejects and leaves the current camera running.
|
||||
await this.reacquire({ deviceId: { exact: deviceId } });
|
||||
await this.reacquire({ deviceId });
|
||||
},
|
||||
};
|
||||
if (this.source === "microphone")
|
||||
|
||||
@@ -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
@@ -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
@@ -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
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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
@@ -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`. */
|
||||
|
||||
@@ -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 },
|
||||
];
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -143,10 +143,7 @@ export interface LocalMediaTrack {
|
||||
* from the request where the device could not be used.
|
||||
*/
|
||||
setEnabled(enabled: boolean): Promise<boolean>;
|
||||
/**
|
||||
* Captures from another device. Rejects where that device cannot be opened,
|
||||
* leaving the track on the one it had, and for a screen share, which has none.
|
||||
*/
|
||||
/** Captures from another device. Rejects for a screen share, which has none. */
|
||||
setDevice(deviceId: string): Promise<void>;
|
||||
}
|
||||
|
||||
|
||||
@@ -344,7 +344,6 @@ describe("createLivekitBackend", () => {
|
||||
userId: "@bob:example.org",
|
||||
deviceId: "DEV000",
|
||||
memberId: legacyId,
|
||||
matrixEventId$: constant("$bob"),
|
||||
transport$: constant({
|
||||
type: "livekit",
|
||||
id: JSON.stringify(transport),
|
||||
|
||||
@@ -213,7 +213,7 @@ describe("createLivekitMediaTrack", () => {
|
||||
expect(switchActiveDevice).toHaveBeenCalledWith(
|
||||
"audioinput",
|
||||
"mic-2",
|
||||
true,
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -225,23 +225,19 @@ describe("createLivekitMediaTrack", () => {
|
||||
])(
|
||||
"leaves a processed camera alone unless its device changes: $deviceId",
|
||||
async ({ deviceId, switches }) => {
|
||||
let openDevice = "cam-1";
|
||||
const camera = Object.assign(Object.create(LocalVideoTrack.prototype), {
|
||||
source: Track.Source.Camera,
|
||||
_mediaStreamTrack: {
|
||||
readyState: "live",
|
||||
label: "",
|
||||
getSettings: () => ({ deviceId: openDevice }),
|
||||
getSettings: () => ({ deviceId: "cam-1" }),
|
||||
},
|
||||
// What LiveKit shows as the track, with no device of its own
|
||||
processor: {
|
||||
processedTrack: { label: "", getSettings: () => ({}) },
|
||||
},
|
||||
}) as LocalVideoTrack;
|
||||
const switchActiveDevice = vi.fn(async (_kind: string, id: string) => {
|
||||
openDevice = id;
|
||||
return Promise.resolve(true);
|
||||
});
|
||||
const switchActiveDevice = vi.fn().mockResolvedValue(true);
|
||||
const { participant, publication, room } = fakes({
|
||||
track: camera as unknown as FakeTrack,
|
||||
});
|
||||
@@ -257,63 +253,11 @@ describe("createLivekitMediaTrack", () => {
|
||||
|
||||
await track.setDevice(deviceId);
|
||||
expect(switchActiveDevice.mock.calls).toEqual(
|
||||
switches ? [["videoinput", deviceId, true]] : [],
|
||||
switches ? [["videoinput", deviceId, false]] : [],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
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);
|
||||
|
||||
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 () => {
|
||||
const source = {
|
||||
readyState: "live",
|
||||
@@ -412,36 +356,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,16 @@ 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)
|
||||
: 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 (
|
||||
current instanceof LocalTrack &&
|
||||
(await current.getDeviceId(false)) === deviceId
|
||||
)
|
||||
return;
|
||||
await room.switchActiveDevice(
|
||||
base.kind === "audio" ? "audioinput" : "videoinput",
|
||||
deviceId,
|
||||
false,
|
||||
);
|
||||
},
|
||||
};
|
||||
if (base.kind === "audio") return { ...base, ...local };
|
||||
@@ -273,19 +254,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,
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
@@ -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;
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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
@@ -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]);
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
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.
|
||||
*/
|
||||
|
||||
.popover {
|
||||
position: relative;
|
||||
border-radius: var(--cpd-space-3x);
|
||||
background: var(--cpd-color-bg-canvas-default);
|
||||
box-shadow: var(--big-drop-shadow);
|
||||
padding: var(--cpd-space-5x);
|
||||
box-sizing: border-box;
|
||||
inline-size: 310px;
|
||||
max-inline-size: 90vw;
|
||||
|
||||
/* Draw an internal border */
|
||||
&::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border: var(--cpd-border-width-1) solid
|
||||
var(--cpd-color-border-interactive-secondary);
|
||||
border-radius: inherit;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
transition:
|
||||
opacity 180ms,
|
||||
transform 180ms;
|
||||
|
||||
&[data-starting-style] {
|
||||
opacity: 0;
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
transform: translate(0, var(--cpd-space-3x));
|
||||
}
|
||||
}
|
||||
|
||||
&[data-ending-style] {
|
||||
transition-duration: 110ms;
|
||||
opacity: 0;
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
transform: translate(0, var(--cpd-space-2x));
|
||||
}
|
||||
}
|
||||
|
||||
p {
|
||||
font: var(--cpd-font-body-sm-regular);
|
||||
color: var(--cpd-color-text-secondary);
|
||||
margin-block-end: var(--cpd-space-4x);
|
||||
}
|
||||
}
|
||||
|
||||
.title {
|
||||
margin-block-end: var(--cpd-space-2x);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
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 { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { Popover } from "./Popover";
|
||||
import { Button } from "@vector-im/compound-web";
|
||||
import { VideoCallOffSolidIcon } from "@vector-im/compound-design-tokens/assets/web/icons";
|
||||
import { useState } from "react";
|
||||
|
||||
const meta = {
|
||||
component: Popover,
|
||||
} satisfies Meta<typeof Popover>;
|
||||
|
||||
export default meta;
|
||||
|
||||
export const Default: StoryObj = {
|
||||
render: () => {
|
||||
const [open, setOpen] = useState(true);
|
||||
return (
|
||||
<Popover
|
||||
title="Poor network connection"
|
||||
trigger={<Button>Open popover</Button>}
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
>
|
||||
<p>Turn off all videos to improve call performance.</p>
|
||||
<Button
|
||||
size="md"
|
||||
Icon={VideoCallOffSolidIcon}
|
||||
style={{ width: "100%", marginBlockStart: 24 }}
|
||||
>
|
||||
Turn off all videos
|
||||
</Button>
|
||||
</Popover>
|
||||
);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
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 { axe } from "vitest-axe";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
|
||||
import { Popover } from "./Popover";
|
||||
|
||||
test("Popover renders", async () => {
|
||||
render(
|
||||
<Popover
|
||||
title="Example"
|
||||
trigger={<button>Open popover</button>}
|
||||
open
|
||||
onOpenChange={() => {}}
|
||||
>
|
||||
<p>This is an example of a popover.</p>
|
||||
</Popover>,
|
||||
);
|
||||
const button = screen.getByRole("button", { name: "Open popover" });
|
||||
const popover = screen.getByRole("dialog", { name: "Example" });
|
||||
expect(button).toMatchSnapshot("button");
|
||||
expect(popover).toMatchSnapshot("popover");
|
||||
expect(await axe(document.body)).toHaveNoViolations();
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
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 FC, type ReactElement, type ReactNode } from "react";
|
||||
import { Popover as BUIPopover } from "@base-ui/react/popover";
|
||||
|
||||
import styles from "./Popover.module.css";
|
||||
import { Heading } from "@vector-im/compound-web";
|
||||
import classNames from "classnames";
|
||||
|
||||
export interface PopoverProps {
|
||||
/**
|
||||
* The popover title.
|
||||
*/
|
||||
title: string;
|
||||
/**
|
||||
* The button that opens the popover. This must be a component that accepts a
|
||||
* ref and spreads props.
|
||||
*
|
||||
* https://base-ui.com/react/handbook/composition
|
||||
*/
|
||||
trigger: ReactElement;
|
||||
/**
|
||||
* Whether the popover is open.
|
||||
*/
|
||||
open: boolean;
|
||||
/**
|
||||
* Event handler called when the user tries to open or close the popover.
|
||||
*/
|
||||
onOpenChange: (open: boolean) => void;
|
||||
/**
|
||||
* The popover contents.
|
||||
*/
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
/**
|
||||
* The side of the trigger on which to place the popover. Note that the menu
|
||||
* may still end up on a different side than the one you request if there
|
||||
* isn't enough space.
|
||||
* @default bottom
|
||||
*/
|
||||
side?: "top" | "bottom" | "left" | "right" | "inline-end" | "inline-start";
|
||||
/**
|
||||
* The edge along which the popover and trigger will be aligned.
|
||||
* @default center
|
||||
*/
|
||||
align?: "start" | "center" | "end";
|
||||
}
|
||||
|
||||
/**
|
||||
* A popover opened by pressing a button.
|
||||
*/
|
||||
export const Popover: FC<PopoverProps> = ({
|
||||
title,
|
||||
trigger,
|
||||
open,
|
||||
onOpenChange,
|
||||
children,
|
||||
className,
|
||||
side,
|
||||
align,
|
||||
}) => {
|
||||
return (
|
||||
<BUIPopover.Root open={open} onOpenChange={onOpenChange}>
|
||||
<BUIPopover.Trigger render={trigger} />
|
||||
<BUIPopover.Portal>
|
||||
<BUIPopover.Positioner sideOffset={8} side={side} align={align}>
|
||||
<BUIPopover.Popup className={classNames(styles.popover, className)}>
|
||||
<BUIPopover.Title
|
||||
className={styles.title}
|
||||
render={
|
||||
<Heading as="h3" type="body" weight="semibold" size="lg">
|
||||
{title}
|
||||
</Heading>
|
||||
}
|
||||
/>
|
||||
{children}
|
||||
</BUIPopover.Popup>
|
||||
</BUIPopover.Positioner>
|
||||
</BUIPopover.Portal>
|
||||
</BUIPopover.Root>
|
||||
);
|
||||
};
|
||||
@@ -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";
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`Popover renders > button 1`] = `
|
||||
<button
|
||||
aria-controls="_r_0_"
|
||||
aria-expanded="true"
|
||||
aria-haspopup="dialog"
|
||||
data-base-ui-click-trigger=""
|
||||
data-popup-open=""
|
||||
id="base-ui-_r_1_"
|
||||
tabindex="0"
|
||||
type="button"
|
||||
>
|
||||
Open popover
|
||||
</button>
|
||||
`;
|
||||
|
||||
exports[`Popover renders > popover 1`] = `
|
||||
<div
|
||||
aria-labelledby="base-ui-_r_4_"
|
||||
class="_popover_8e8188"
|
||||
data-align="center"
|
||||
data-base-ui-focusable=""
|
||||
data-open=""
|
||||
data-side="bottom"
|
||||
id="_r_0_"
|
||||
role="dialog"
|
||||
tabindex="-1"
|
||||
>
|
||||
<h3
|
||||
class="_typography_6v6n8_153 _font-body-lg-semibold_6v6n8_74 _title_8e8188"
|
||||
id="base-ui-_r_4_"
|
||||
>
|
||||
Example
|
||||
</h3>
|
||||
<p>
|
||||
This is an example of a popover.
|
||||
</p>
|
||||
</div>
|
||||
`;
|
||||
@@ -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({
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 (
|
||||
<>
|
||||
|
||||
@@ -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"));
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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
@@ -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.
|
||||
|
||||
+101
-184
@@ -13,24 +13,21 @@ import {
|
||||
useMemo,
|
||||
useState,
|
||||
} from "react";
|
||||
import { type MatrixClient, JoinRule, type Room } from "matrix-js-sdk";
|
||||
import {
|
||||
type MatrixClient,
|
||||
JoinRule,
|
||||
type Room,
|
||||
UnsupportedStickyEventsEndpointError,
|
||||
} from "matrix-js-sdk";
|
||||
import {
|
||||
Room as LivekitRoom,
|
||||
isE2EESupported as isE2EESupportedBrowser,
|
||||
} from "livekit-client";
|
||||
import { logger } from "matrix-js-sdk/lib/logger";
|
||||
import {
|
||||
MatrixRTCSessionEvent,
|
||||
type MatrixRTCSession,
|
||||
type Statistics,
|
||||
} from "matrix-js-sdk/lib/matrixrtc";
|
||||
import { type Observable } from "rxjs";
|
||||
import {
|
||||
createRTCSlot,
|
||||
type EncryptionSystem,
|
||||
MembershipManagerError as RTCMembershipManagerError,
|
||||
type RTCSlot,
|
||||
withEmitter,
|
||||
} from "@element-hq/matrixrtc-sdk";
|
||||
|
||||
import { type JoinCallData } from "../widget";
|
||||
import { LobbyView } from "./LobbyView";
|
||||
@@ -42,6 +39,7 @@ import { findDeviceByName } from "../utils/media";
|
||||
import { ActiveCall } from "./InCallView";
|
||||
import { type MuteStates } from "../state/MuteStates";
|
||||
import { useMediaDevices } from "../MediaDevicesContext";
|
||||
import { useMatrixRTCSessionMemberships } from "../useMatrixRTCSessionMemberships";
|
||||
import {
|
||||
saveKeyForRoom,
|
||||
useRoomEncryptionSystem,
|
||||
@@ -59,11 +57,14 @@ import {
|
||||
} from "./CallEventAudioRenderer";
|
||||
import { useLatest } from "../useLatest";
|
||||
import {
|
||||
ConnectionLostError,
|
||||
E2EENotSupportedError,
|
||||
ElementCallError,
|
||||
StickyEventsRequiredError,
|
||||
UnknownCallError,
|
||||
} from "../utils/errors.ts";
|
||||
import { GroupCallErrorBoundary } from "./GroupCallErrorBoundary.tsx";
|
||||
import { useTypedEventEmitter } from "../useEvents";
|
||||
import { muteAllAudio$ } from "../state/MuteAllAudioModel.ts";
|
||||
import { useAppBarTitle } from "../AppBar.tsx";
|
||||
import { useBehavior } from "../useBehavior.ts";
|
||||
@@ -72,9 +73,6 @@ import { useHostBridge } from "../HostBridge.ts";
|
||||
import { useMuteStates } from "../state/useMuteStates.ts";
|
||||
import { useLeaveToHome } from "../LeaveToHomeContext.ts";
|
||||
import { useLocalMedia } from "../useLocalMedia.ts";
|
||||
import { ObservableScope } from "../state/ObservableScope.ts";
|
||||
import { type CallNotificationWrapper } from "../state/CallViewModel/CallNotificationLifecycle.ts";
|
||||
import { type CallMatrixBackend } from "../CallMatrixBackend.ts";
|
||||
|
||||
/**
|
||||
* If there already are this many participants in the call, we automatically mute
|
||||
@@ -82,19 +80,17 @@ import { type CallMatrixBackend } from "../CallMatrixBackend.ts";
|
||||
*/
|
||||
export const MUTE_PARTICIPANT_COUNT = 8;
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
rtcSession?: MatrixRTCSession;
|
||||
}
|
||||
}
|
||||
|
||||
interface Props {
|
||||
/** The client and room to place the call with and in. */
|
||||
backend: CallMatrixBackend;
|
||||
/**
|
||||
* The call to join, which the RTC slot is built on.
|
||||
* Passing undefined -> the SDK will create a inner RTCSession (or in the future a rust equivalent)
|
||||
* @deprecated: It should not get its rtcSession from here.
|
||||
* The goal is that the RTC session is fully encapsulated inside the SDK (`createRTCSlot`)
|
||||
* We keep this as a fallback for the SPA. In that mode we currently expect to manage Our
|
||||
* own rtcSession with `useLoadGroupCall`. This is an open TODO. Until then we have this
|
||||
* alternative.
|
||||
*/
|
||||
rtcSession?: MatrixRTCSession;
|
||||
/** The client to place the call with. */
|
||||
client: MatrixClient;
|
||||
/** The call to join. */
|
||||
rtcSession: MatrixRTCSession;
|
||||
/**
|
||||
* Whether the user is signed in as a guest, and so should be offered the
|
||||
* chance to create an account when the call ends.
|
||||
@@ -125,58 +121,18 @@ interface Props {
|
||||
* whatever is hosting it — the standalone app's own shell, or an application
|
||||
* embedding Element Call as a component. Both render this.
|
||||
*/
|
||||
export const CallView: FC<Props> = ({
|
||||
backend,
|
||||
rtcSession: externalRtcSession,
|
||||
...props
|
||||
}): ReactNode => {
|
||||
// STOP GAP: what is below is still written against a client and a room.
|
||||
// Both are refactored along with the backend.
|
||||
const client = useMemo(
|
||||
() => withEmitter(backend, backend.clientEmitter),
|
||||
[backend],
|
||||
);
|
||||
const room = useMemo(
|
||||
() => withEmitter(backend, backend.roomEmitter),
|
||||
[backend],
|
||||
);
|
||||
|
||||
export const CallView: FC<Props> = (props): ReactNode => {
|
||||
// Whether the user is in the call is the call's own business, not its host's.
|
||||
// Held here rather than below so that it survives the mute state being
|
||||
// rebuilt.
|
||||
const [joined, setJoined] = useState(false);
|
||||
const muteStates = useMuteStates();
|
||||
const e2eeSystem = useRoomEncryptionSystem(backend.roomId);
|
||||
|
||||
// One slot for every join of this call: leaving and joining again, to
|
||||
// reconnect or from the lobby, happens on the same one
|
||||
const [slot, setSlot] = useState<ReturnType<typeof createRTCSlot> | null>(
|
||||
null,
|
||||
);
|
||||
useEffect(() => {
|
||||
const scope = new ObservableScope();
|
||||
setSlot(
|
||||
createRTCSlot(
|
||||
scope,
|
||||
backend,
|
||||
{ encryptionSystem: e2eeSystem },
|
||||
externalRtcSession,
|
||||
),
|
||||
);
|
||||
return (): void => scope.end();
|
||||
}, [backend, e2eeSystem, externalRtcSession]);
|
||||
|
||||
if (muteStates === null || slot === null) return null;
|
||||
if (muteStates === null) return null;
|
||||
|
||||
return (
|
||||
<LoadedCallView
|
||||
{...props}
|
||||
client={client}
|
||||
room={room}
|
||||
sentCallNotification$={slot.sentCallNotification$}
|
||||
statistics={slot.statistics}
|
||||
slot={slot}
|
||||
e2eeSystem={e2eeSystem}
|
||||
joined={joined}
|
||||
setJoined={setJoined}
|
||||
muteStates={muteStates}
|
||||
@@ -184,100 +140,20 @@ export const CallView: FC<Props> = ({
|
||||
);
|
||||
};
|
||||
|
||||
// Here we do not pass the rtcSession anymore. This is a huge step!!
|
||||
// We only rely on our sdk abstraction (+ client and +room but only a
|
||||
// smaller list of callbacks.)
|
||||
interface LoadedProps extends Omit<Props, "rtcSession" | "backend"> {
|
||||
// Narrower than `Props.client`: the `slot` already has what only it and its
|
||||
// session need, `getRTCTransports`, `delegateDelayedLeave`, `baseUrl`,
|
||||
// `getSyncState`, `ClientEvent.Sync`, and the session's sending
|
||||
client: Pick<
|
||||
MatrixClient,
|
||||
| "getUserId"
|
||||
| "getDeviceId"
|
||||
| "getDomain"
|
||||
| "getOpenIdToken"
|
||||
| "getLivekitToken"
|
||||
| "sendEvent"
|
||||
| "redactEvent"
|
||||
| "decryptEventIfNeeded"
|
||||
| "getUser"
|
||||
| "setDisplayName"
|
||||
| "setAvatarUrl"
|
||||
| "uploadContent"
|
||||
| "doesServerSupportUnstableFeature"
|
||||
| "getCrypto"
|
||||
// `on`/`off`, to listen for `MatrixEventEvent.Decrypted` (reactions once
|
||||
// decrypted)
|
||||
| "on"
|
||||
| "off"
|
||||
>;
|
||||
// Narrower than `Props.room`: the `slot` already follows
|
||||
// `RoomStateEvent.Events` for its status, `RoomStateEvent.Members` for its
|
||||
// own members, and the timeline its session reads the memberships from
|
||||
room: Pick<
|
||||
Room,
|
||||
| "roomId"
|
||||
| "name"
|
||||
| "getMxcAvatarUrl"
|
||||
| "getJoinRule"
|
||||
| "getMembersWithMembership"
|
||||
| "_unstable_getStickyEvents"
|
||||
| "getLiveTimeline"
|
||||
| "relations"
|
||||
// `on`/`off`, to listen for:
|
||||
// - `RoomEvent.Name` (room name)
|
||||
// - `RoomStateEvent.Update` and `RoomEvent.CurrentStateUpdated` (avatar
|
||||
// and join rule hooks)
|
||||
// - `RoomStateEvent.Members` (call view model members)
|
||||
// - `RoomStateEvent.Events` (call view model functional members)
|
||||
// - `RoomEvent.Timeline` and `RoomStickyEventsEvent.Update` (call notifications)
|
||||
// - `RoomEvent.Timeline`, `RoomEvent.Redaction` and
|
||||
// `RoomEvent.LocalEchoUpdated` (reactions and raised hands)
|
||||
| "on"
|
||||
| "off"
|
||||
>;
|
||||
/**
|
||||
* The call notifications the session sends with our join, so the call can
|
||||
* show it ringing: the slot's `sentCallNotification$`.
|
||||
*/
|
||||
sentCallNotification$: Observable<CallNotificationWrapper>;
|
||||
/** The session's media key statistics, reported when the call ends. */
|
||||
statistics: Statistics;
|
||||
slot: RTCSlot;
|
||||
e2eeSystem: EncryptionSystem;
|
||||
interface LoadedProps extends Props {
|
||||
joined: boolean;
|
||||
setJoined: (value: boolean) => void;
|
||||
muteStates: MuteStates;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether our membership is live in the slot: seen in the room, and not taken
|
||||
* down by the membership manager stopping. Leaving the call only makes sense
|
||||
* then; an error before the join, or one that ended the membership, leaves
|
||||
* nothing to leave.
|
||||
*/
|
||||
function isInCall(slot: RTCSlot): boolean {
|
||||
const participation = slot.participation$.value;
|
||||
if (participation?.localMember$.value == null) return false;
|
||||
const state = participation.state$.value;
|
||||
return !(
|
||||
state.kind === "failed" && state.error instanceof RTCMembershipManagerError
|
||||
);
|
||||
}
|
||||
|
||||
/** {@link CallView}, once it has the slot and mute state everything below needs. */
|
||||
/** {@link CallView}, once it has the mute state everything below needs. */
|
||||
const LoadedCallView: FC<LoadedProps> = ({
|
||||
client,
|
||||
room,
|
||||
isPasswordlessUser,
|
||||
confineToRoom,
|
||||
preload,
|
||||
skipLobby,
|
||||
slot,
|
||||
sentCallNotification$,
|
||||
statistics,
|
||||
e2eeSystem,
|
||||
rtcSession,
|
||||
joined,
|
||||
setJoined,
|
||||
muteStates,
|
||||
@@ -286,7 +162,7 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
const [externalError, setExternalError] = useState<ElementCallError | null>(
|
||||
null,
|
||||
);
|
||||
const members = useBehavior(slot.members$);
|
||||
const memberships = useMatrixRTCSessionMemberships(rtcSession);
|
||||
const rootElement = useRootElement();
|
||||
const hostBridge = useHostBridge();
|
||||
// A host that can close us is a host that decides when we stop existing, so
|
||||
@@ -305,7 +181,7 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
);
|
||||
// This should use `useEffectEvent` (only available in experimental versions)
|
||||
useEffect(() => {
|
||||
if (members.length >= MUTE_PARTICIPANT_COUNT)
|
||||
if (memberships.length >= MUTE_PARTICIPANT_COUNT)
|
||||
muteStates.audio.setEnabled$.value?.(false);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
@@ -327,10 +203,48 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
};
|
||||
}, [rootElement]);
|
||||
|
||||
useEffect(() => {
|
||||
window.rtcSession = rtcSession;
|
||||
return (): void => {
|
||||
delete window.rtcSession;
|
||||
};
|
||||
}, [rtcSession]);
|
||||
|
||||
// TODO move this into the callViewModel LocalMembership.ts
|
||||
// We might actually not need this at all. Since we get into fatalError on those errors already?
|
||||
useTypedEventEmitter(
|
||||
rtcSession,
|
||||
MatrixRTCSessionEvent.MembershipManagerError,
|
||||
(error) => {
|
||||
// When matrix_rtc_mode=matrix_2_0 is in effect but the homeserver does
|
||||
// not advertise MSC4354 (sticky events), the SDK throws an
|
||||
// `UnsupportedStickyEventsEndpointError`. The MembershipManager
|
||||
// scheduler wraps it and exposes the original via `.cause`.
|
||||
if (
|
||||
error instanceof Error &&
|
||||
error.cause instanceof UnsupportedStickyEventsEndpointError
|
||||
) {
|
||||
setExternalError(new StickyEventsRequiredError());
|
||||
} else {
|
||||
setExternalError(new ConnectionLostError());
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
// Sanity check the room object
|
||||
if (client.getRoom(rtcSession.room.roomId) !== rtcSession.room)
|
||||
logger.warn(
|
||||
`We've ended up with multiple rooms for the same ID (${rtcSession.room.roomId}). This indicates a bug in the group call loading code, and may lead to incomplete room state.`,
|
||||
);
|
||||
}, [client, rtcSession.room]);
|
||||
|
||||
const room = rtcSession.room as Room;
|
||||
const { displayName, avatarUrl } = useProfile(client);
|
||||
const roomName = useRoomName(room);
|
||||
const roomAvatar = useRoomAvatar(room);
|
||||
const { returnToLobby, password: passwordFromUrl, header } = useUrlParams();
|
||||
const e2eeSystem = useRoomEncryptionSystem(room.roomId);
|
||||
|
||||
// Save the password once we start the groupCallView
|
||||
useEffect(() => {
|
||||
@@ -346,6 +260,7 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
avatarUrl: avatarUrl!,
|
||||
roomId: room.roomId,
|
||||
roomName,
|
||||
roomAlias: room.getCanonicalAlias(),
|
||||
roomAvatar,
|
||||
e2eeSystem,
|
||||
};
|
||||
@@ -353,8 +268,8 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
|
||||
// Count each member only once, regardless of how many devices they use
|
||||
const participantCount = useMemo(
|
||||
() => new Set<string>(members.map((m) => m.userId)).size,
|
||||
[members],
|
||||
() => new Set<string>(memberships.map((m) => m.userId!)).size,
|
||||
[memberships],
|
||||
);
|
||||
|
||||
const mediaDevices = useMediaDevices();
|
||||
@@ -362,24 +277,27 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
// Opened by the lobby, published by the call: one capture for both
|
||||
const media = useLocalMedia();
|
||||
|
||||
const enterRTCSessionOrError = useCallback(async (): Promise<void> => {
|
||||
try {
|
||||
setJoined(true);
|
||||
// TODO-MULTI-SFU what to do with error handling now that we don't use this function?
|
||||
// @BillCarsonFr
|
||||
} catch (e) {
|
||||
if (e instanceof ElementCallError) {
|
||||
setExternalError(e);
|
||||
} else {
|
||||
logger.error(`Unknown Error while entering RTC session`, e);
|
||||
const error = new UnknownCallError(
|
||||
e instanceof Error ? e : new Error("Unknown error", { cause: e }),
|
||||
);
|
||||
setExternalError(error);
|
||||
const enterRTCSessionOrError = useCallback(
|
||||
async (rtcSession: MatrixRTCSession): Promise<void> => {
|
||||
try {
|
||||
setJoined(true);
|
||||
// TODO-MULTI-SFU what to do with error handling now that we don't use this function?
|
||||
// @BillCarsonFr
|
||||
} catch (e) {
|
||||
if (e instanceof ElementCallError) {
|
||||
setExternalError(e);
|
||||
} else {
|
||||
logger.error(`Unknown Error while entering RTC session`, e);
|
||||
const error = new UnknownCallError(
|
||||
e instanceof Error ? e : new Error("Unknown error", { cause: e }),
|
||||
);
|
||||
setExternalError(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
return Promise.resolve();
|
||||
}, [setJoined]);
|
||||
return Promise.resolve();
|
||||
},
|
||||
[setJoined],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const defaultDeviceSetup = async ({
|
||||
@@ -442,6 +360,7 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
}
|
||||
}, [
|
||||
hostBridge,
|
||||
rtcSession,
|
||||
preload,
|
||||
skipLobby,
|
||||
mediaDevices,
|
||||
@@ -488,9 +407,9 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
const sendInstantly = hostControlsLifetime;
|
||||
PosthogAnalytics.instance.eventCallEnded.track(
|
||||
room.roomId,
|
||||
slot.members$.value.length,
|
||||
rtcSession.memberships.length,
|
||||
sendInstantly,
|
||||
statistics,
|
||||
rtcSession,
|
||||
);
|
||||
// Unfortunately the PostHog library provides no way to await the
|
||||
// tracking of an event, but we don't really want it to hold up our
|
||||
@@ -536,8 +455,7 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
hostBridge,
|
||||
hostControlsLifetime,
|
||||
room.roomId,
|
||||
slot,
|
||||
statistics,
|
||||
rtcSession,
|
||||
isPasswordlessUser,
|
||||
confineToRoom,
|
||||
returnToLobby,
|
||||
@@ -551,7 +469,7 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
hostBridge.setAlwaysOnScreen(true).catch((e) => {
|
||||
logger.error("Error calling setAlwaysOnScreen(true)", e);
|
||||
});
|
||||
}, [hostBridge, joined]);
|
||||
}, [hostBridge, joined, rtcSession]);
|
||||
|
||||
const joinRule = useJoinRule(room);
|
||||
|
||||
@@ -612,8 +530,7 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
<ActiveCall
|
||||
client={client}
|
||||
matrixInfo={matrixInfo}
|
||||
slot={slot}
|
||||
sentCallNotification$={sentCallNotification$}
|
||||
rtcSession={rtcSession as MatrixRTCSession}
|
||||
matrixRoom={room}
|
||||
onLeft={onLeft}
|
||||
media={media}
|
||||
@@ -636,7 +553,7 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
if (isPasswordlessUser || PosthogAnalytics.instance.isEnabled()) {
|
||||
body = (
|
||||
<CallEndedView
|
||||
endedCallId={room.roomId}
|
||||
endedCallId={rtcSession.room.roomId}
|
||||
client={client}
|
||||
isPasswordlessUser={isPasswordlessUser}
|
||||
hideHeader={header === HeaderStyle.None}
|
||||
@@ -653,7 +570,7 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
// Left, and the host decides what happens next:
|
||||
body = returnToLobby ? lobbyView : null;
|
||||
} else if (preload || skipLobby) {
|
||||
// Not in the call yet: waiting for the host to say when, or about to join
|
||||
// The RTC session is not joined to yet (`isJoined`), but enterRTCSessionOrError should have been called.
|
||||
body = null;
|
||||
} else {
|
||||
body = lobbyView;
|
||||
@@ -665,16 +582,16 @@ const LoadedCallView: FC<LoadedProps> = ({
|
||||
setExternalError(null);
|
||||
if (action == "reconnect") {
|
||||
setLeft(false);
|
||||
await enterRTCSessionOrError().catch((e) => {
|
||||
await enterRTCSessionOrError(rtcSession).catch((e) => {
|
||||
logger.error("Error re-entering RTC session", e);
|
||||
});
|
||||
}
|
||||
}}
|
||||
onError={(_error) => {
|
||||
if (isInCall(slot)) onLeft("error");
|
||||
if (rtcSession.isJoined()) onLeft("error");
|
||||
// If there is an error we need to be dismissible again. This is done in
|
||||
// `onLeft` as well; we need it here explicitly in case we were not in
|
||||
// the call.
|
||||
// `onLeft` as well; we need it here explicitly in case
|
||||
// rtcSession.isJoined is false.
|
||||
void hostBridge.setAlwaysOnScreen(false);
|
||||
}}
|
||||
>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user