mirror of
https://github.com/vector-im/element-call.git
synced 2026-11-28 10:01:09 +08:00
Compare commits
82
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f6a919aa6 | ||
|
|
13ce1c2648 | ||
|
|
e71203f913 | ||
|
|
2bf7b1385b | ||
|
|
eb69706111 | ||
|
|
9cb668eabb | ||
|
|
d53e1a25c0 | ||
|
|
58f41e1f59 | ||
|
|
e18322462b | ||
|
|
b40ccc4091 | ||
|
|
4daf10d043 | ||
|
|
d440cd49b2 | ||
|
|
cd44d0ff5b | ||
|
|
b6b2af595f | ||
|
|
e881803922 | ||
|
|
1c93370462 | ||
|
|
9bd510c1bf | ||
|
|
88eb3aaf9d | ||
|
|
d85c1d86f0 | ||
|
|
ca5fc7adc0 | ||
|
|
dbfe494852 | ||
|
|
78ddd9839c | ||
|
|
64ad1d7314 | ||
|
|
1c4d2c5d29 | ||
|
|
b4408dcecf | ||
|
|
98afaa71ce | ||
|
|
aef28af48a | ||
|
|
35280e3847 | ||
|
|
2c85cdb308 | ||
|
|
6ca17f4e2d | ||
|
|
6751c753ea | ||
|
|
707b218e38 | ||
|
|
95d24486ef | ||
|
|
8d04612f9c | ||
|
|
dc2e64c666 | ||
|
|
20b989b3e5 | ||
|
|
ecd542f526 | ||
|
|
be85e0b49d | ||
|
|
b5571dd837 | ||
|
|
e3b414434c | ||
|
|
69ad5ff68c | ||
|
|
cc93991fbe | ||
|
|
7b803e1dc8 | ||
|
|
96e6a811f4 | ||
|
|
2b5ad74ede | ||
|
|
208ef89d7c | ||
|
|
a3edc058a0 | ||
|
|
1b94460ddf | ||
|
|
17e3c02aa5 | ||
|
|
d3b653d25d | ||
|
|
f1e82b9e85 | ||
|
|
6be739f168 | ||
|
|
382c688a2f | ||
|
|
ff11990046 | ||
|
|
b480f7ebb4 | ||
|
|
b2f7fccc6e | ||
|
|
eb5c4b8633 | ||
|
|
f9dafcd5ea | ||
|
|
ded4471525 | ||
|
|
e74e83ab08 | ||
|
|
3917bbb8f2 | ||
|
|
4c66fe6f7d | ||
|
|
ffd6360277 | ||
|
|
eabc6c0823 | ||
|
|
7d6fbd336d | ||
|
|
f9fb566f41 | ||
|
|
ef1f69e085 | ||
|
|
95a646b3bc | ||
|
|
86ad9bcb28 | ||
|
|
7cd9ed8022 | ||
|
|
6cdcd5e83e | ||
|
|
29b80b62c9 | ||
|
|
1cdcb62791 | ||
|
|
87bd273fa5 | ||
|
|
a5dd993dd4 | ||
|
|
b3fe19f192 | ||
|
|
e631979256 | ||
|
|
a27a76d6f1 | ||
|
|
8b9dde62d1 | ||
|
|
25c4f14d8f | ||
|
|
5f776519b1 | ||
|
|
904062b917 |
@@ -0,0 +1,53 @@
|
||||
<!-- 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,6 +9,11 @@ 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 'sdk'
|
||||
description: The package type to be built. Must be one of 'full', 'embedded', or 'widget-rtc-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@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with:
|
||||
cache: "pnpm"
|
||||
node-version-file: ".node-version"
|
||||
|
||||
@@ -7,10 +7,15 @@ on:
|
||||
- labeled
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
build_full_element_call:
|
||||
# Use the full package vite build
|
||||
uses: ./.github/workflows/build-element-call.yaml
|
||||
permissions:
|
||||
contents: read
|
||||
uses: $/.github/workflows/build-element-call.yaml
|
||||
with:
|
||||
package: full
|
||||
vite_app_version: ${{ github.event.release.tag_name || github.sha }}
|
||||
@@ -26,6 +31,7 @@ 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
|
||||
@@ -50,8 +56,10 @@ jobs:
|
||||
contents: write
|
||||
packages: write
|
||||
id-token: write
|
||||
uses: ./.github/workflows/build-and-publish-docker.yaml
|
||||
secrets: inherit
|
||||
uses: $/.github/workflows/build-and-publish-docker.yaml
|
||||
secrets:
|
||||
TS_OAUTH_CLIENT_ID: ${{ secrets.TS_OAUTH_CLIENT_ID }}
|
||||
TS_AUDIENCE: ${{ secrets.TS_AUDIENCE }}
|
||||
with:
|
||||
artifact_run_id: ${{ github.run_id }}
|
||||
docker_tags: |
|
||||
@@ -60,7 +68,9 @@ jobs:
|
||||
type=raw,value=latest-ci_{{date 'X' }}
|
||||
build_embedded_element_call:
|
||||
# Use the embedded package vite build
|
||||
uses: ./.github/workflows/build-element-call.yaml
|
||||
permissions:
|
||||
contents: read
|
||||
uses: $/.github/workflows/build-element-call.yaml
|
||||
with:
|
||||
package: embedded
|
||||
vite_app_version: ${{ github.event.release.tag_name || github.sha }}
|
||||
@@ -72,14 +82,14 @@ jobs:
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
|
||||
|
||||
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
|
||||
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
|
||||
with:
|
||||
package: sdk
|
||||
package: widget-rtc-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:
|
||||
@@ -93,6 +103,8 @@ 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
|
||||
@@ -101,7 +113,7 @@ jobs:
|
||||
- name: Enable Corepack
|
||||
run: corepack enable
|
||||
- name: pnpm cache
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with:
|
||||
cache: "pnpm"
|
||||
node-version-file: ".node-version"
|
||||
|
||||
@@ -44,12 +44,13 @@ 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:
|
||||
|
||||
@@ -60,6 +61,19 @@ 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.
|
||||
|
||||
@@ -68,9 +82,9 @@ jobs:
|
||||
"🟠 medium" or "🔴 high". Devise at least one possible resolution for each
|
||||
finding.
|
||||
|
||||
Report the graded findings and resolutions from the "Code" angle as inline
|
||||
comments. Add a footer "_-- Finding from automated review_" to each inline
|
||||
comment.
|
||||
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.
|
||||
|
||||
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', 'sdk', or 'storybook'
|
||||
description: Which package to deploy - 'full', 'embedded', 'widget-rtc-sdk', or 'storybook'
|
||||
artifact_run_id:
|
||||
required: false
|
||||
type: string
|
||||
@@ -64,25 +64,27 @@ jobs:
|
||||
run: curl -s https://raw.githubusercontent.com/element-hq/element-call/main/config/netlify_redirects > webapp/_redirects
|
||||
|
||||
- name: Add config file
|
||||
# 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
|
||||
# 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
|
||||
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 == 'sdk' && format('pr{0}-sdk', inputs.pr_number) || inputs.package == 'storybook' && format('pr{0}-storybook', inputs.pr_number) || format('pr{0}', inputs.pr_number) }}
|
||||
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) }}
|
||||
env:
|
||||
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
|
||||
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
|
||||
|
||||
@@ -7,10 +7,15 @@ 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
|
||||
@@ -21,7 +26,7 @@ jobs:
|
||||
- name: Enable Corepack
|
||||
run: corepack enable
|
||||
- name: pnpm cache
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with:
|
||||
cache: "pnpm"
|
||||
node-version-file: ".node-version"
|
||||
@@ -41,3 +46,5 @@ jobs:
|
||||
run: "pnpm run lint:types"
|
||||
- name: Dead code analysis
|
||||
run: "pnpm run lint:knip"
|
||||
- name: Component externals
|
||||
run: "pnpm run lint:externals"
|
||||
|
||||
@@ -7,6 +7,8 @@ on:
|
||||
types:
|
||||
- completed
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
prdetails:
|
||||
# Logic:
|
||||
@@ -18,6 +20,8 @@ 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 }}
|
||||
@@ -33,7 +37,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 }}
|
||||
@@ -46,18 +50,18 @@ jobs:
|
||||
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
|
||||
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
|
||||
|
||||
netlify-sdk:
|
||||
netlify-widget-rtc-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: sdk
|
||||
package: widget-rtc-sdk
|
||||
secrets:
|
||||
ELEMENT_BOT_TOKEN: ${{ secrets.ELEMENT_BOT_TOKEN }}
|
||||
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
|
||||
@@ -68,7 +72,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 }}
|
||||
@@ -88,8 +92,10 @@ jobs:
|
||||
contents: write
|
||||
packages: write
|
||||
id-token: write
|
||||
uses: ./.github/workflows/build-and-publish-docker.yaml
|
||||
secrets: inherit
|
||||
uses: $/.github/workflows/build-and-publish-docker.yaml
|
||||
secrets:
|
||||
TS_OAUTH_CLIENT_ID: ${{ secrets.TS_OAUTH_CLIENT_ID }}
|
||||
TS_AUDIENCE: ${{ secrets.TS_AUDIENCE }}
|
||||
with:
|
||||
artifact_run_id: ${{ github.event.workflow_run.id || github.run_id }}
|
||||
docker_tags: |
|
||||
|
||||
@@ -73,9 +73,10 @@ jobs:
|
||||
- name: Enable Corepack
|
||||
run: corepack enable
|
||||
- name: Setup node
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
# 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
|
||||
@@ -112,8 +113,10 @@ jobs:
|
||||
if: ${{ needs.versioning.outputs.DRY_RUN == 'false' }}
|
||||
name: Update release notes
|
||||
runs-on: ubuntu-24.04
|
||||
# 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
|
||||
# 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.
|
||||
concurrency:
|
||||
group: release-notes-${{ github.event.release.tag_name || github.run_id }}
|
||||
cancel-in-progress: false
|
||||
@@ -121,10 +124,20 @@ jobs:
|
||||
contents: write # to update release notes
|
||||
steps:
|
||||
- name: Add release notes
|
||||
uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
|
||||
with:
|
||||
append_body: true
|
||||
body: |
|
||||
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: |
|
||||
|
||||
## React component (experimental)
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@ on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
versioning:
|
||||
name: Versioning
|
||||
@@ -62,7 +64,9 @@ jobs:
|
||||
|
||||
build_element_call:
|
||||
needs: versioning
|
||||
uses: ./.github/workflows/build-element-call.yaml
|
||||
permissions:
|
||||
contents: read
|
||||
uses: $/.github/workflows/build-element-call.yaml
|
||||
with:
|
||||
vite_app_version: embedded-${{ needs.versioning.outputs.PREFIXED_VERSION }}
|
||||
package: embedded
|
||||
@@ -97,11 +101,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' }}
|
||||
uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
|
||||
with:
|
||||
files: |
|
||||
${{ env.FILENAME_PREFIX }}.tar.gz
|
||||
${{ env.FILENAME_PREFIX }}.sha256
|
||||
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 }}
|
||||
|
||||
publish_npm:
|
||||
needs: [build_element_call, versioning]
|
||||
@@ -129,8 +133,10 @@ jobs:
|
||||
|
||||
# n.b. We don't enable corepack here because we are using plain npm
|
||||
- name: Setup node
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
# 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"
|
||||
|
||||
@@ -283,8 +289,10 @@ jobs:
|
||||
if: always()
|
||||
name: Update release notes
|
||||
runs-on: ubuntu-24.04
|
||||
# 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
|
||||
# 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.
|
||||
concurrency:
|
||||
group: release-notes-${{ github.event.release.tag_name || github.run_id }}
|
||||
cancel-in-progress: false
|
||||
@@ -302,10 +310,20 @@ jobs:
|
||||
NEEDS_PUBLISH_IOS_OUTPUTS_ARTIFACT_VERSION: ${{ needs.publish_ios.outputs.ARTIFACT_VERSION }}
|
||||
- name: Add release notes
|
||||
if: ${{ needs.versioning.outputs.DRY_RUN == 'false' }}
|
||||
uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
|
||||
with:
|
||||
append_body: true
|
||||
body: |
|
||||
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: |
|
||||
|
||||
## Embedded packages
|
||||
|
||||
|
||||
@@ -7,9 +7,13 @@ on:
|
||||
env:
|
||||
VERSION: ${{ github.event.release.tag_name }}
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
build_element_call:
|
||||
uses: ./.github/workflows/build-element-call.yaml
|
||||
permissions:
|
||||
contents: read
|
||||
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
|
||||
@@ -42,11 +46,10 @@ jobs:
|
||||
- name: Create Checksum
|
||||
run: find ${FILENAME_PREFIX} -type f -print0 | sort -z | xargs -0 sha256sum | tee ${FILENAME_PREFIX}.sha256
|
||||
- name: Upload
|
||||
uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
|
||||
with:
|
||||
files: |
|
||||
${{ env.FILENAME_PREFIX }}.tar.gz
|
||||
${{ env.FILENAME_PREFIX }}.sha256
|
||||
run: gh release upload "$VERSION" "${FILENAME_PREFIX}.tar.gz" "${FILENAME_PREFIX}.sha256" --clobber
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
|
||||
publish_docker:
|
||||
needs: build_element_call
|
||||
@@ -56,8 +59,10 @@ jobs:
|
||||
contents: write
|
||||
packages: write
|
||||
id-token: write
|
||||
uses: ./.github/workflows/build-and-publish-docker.yaml
|
||||
secrets: inherit
|
||||
uses: $/.github/workflows/build-and-publish-docker.yaml
|
||||
secrets:
|
||||
TS_OAUTH_CLIENT_ID: ${{ secrets.TS_OAUTH_CLIENT_ID }}
|
||||
TS_AUDIENCE: ${{ secrets.TS_AUDIENCE }}
|
||||
with:
|
||||
artifact_run_id: ${{ github.event.workflow_run.id || github.run_id }}
|
||||
docker_tags: |
|
||||
@@ -69,12 +74,30 @@ 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
|
||||
uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
|
||||
with:
|
||||
append_body: true
|
||||
body: |
|
||||
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: |
|
||||
## 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,10 +22,16 @@ 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
|
||||
@@ -36,7 +42,7 @@ jobs:
|
||||
- name: Enable Corepack
|
||||
run: corepack enable
|
||||
- name: pnpm cache
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with:
|
||||
cache: "pnpm"
|
||||
node-version-file: ".node-version"
|
||||
@@ -75,6 +81,8 @@ 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.
|
||||
@@ -100,7 +108,7 @@ jobs:
|
||||
persist-credentials: false
|
||||
- name: Enable Corepack
|
||||
run: corepack enable
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with:
|
||||
cache: "pnpm"
|
||||
node-version-file: ".node-version"
|
||||
@@ -151,6 +159,8 @@ 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:
|
||||
@@ -159,7 +169,7 @@ jobs:
|
||||
persist-credentials: false
|
||||
- name: Enable Corepack
|
||||
run: corepack enable
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with:
|
||||
cache: "pnpm"
|
||||
node-version-file: ".node-version"
|
||||
|
||||
@@ -20,7 +20,7 @@ jobs:
|
||||
- name: Enable Corepack
|
||||
run: corepack enable
|
||||
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with:
|
||||
cache: "pnpm"
|
||||
node-version-file: ".node-version"
|
||||
|
||||
@@ -20,4 +20,4 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Run zizmor 🌈
|
||||
uses: zizmorcore/zizmor-action@192e21d79ab29983730a13d1382995c2307fbcaa # v0.5.7
|
||||
uses: zizmorcore/zizmor-action@1b4550e929643b8b26a62303c6bd64814271a4f1 # v0.9.2
|
||||
|
||||
@@ -2,6 +2,7 @@ node_modules
|
||||
.DS_Store
|
||||
.env
|
||||
dist
|
||||
/dist-widget-rtc-sdk-example
|
||||
dist-ssr
|
||||
*.local
|
||||
*.bkp
|
||||
|
||||
@@ -43,8 +43,10 @@ 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.md` and fill every
|
||||
section.
|
||||
- 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.
|
||||
|
||||
## Gates
|
||||
|
||||
|
||||
@@ -46,6 +46,11 @@ 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.
|
||||
|
||||
@@ -275,7 +275,11 @@ API is in `component/index.tsx`, `component/api.ts` and `component/host.ts`.
|
||||
|
||||
##### Develop
|
||||
|
||||
- `pnpm build:component` builds the library into `component/dist`.
|
||||
- `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 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,13 +0,0 @@
|
||||
{
|
||||
"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.4
|
||||
image: livekit/livekit-server:v1.13.11
|
||||
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.4
|
||||
image: livekit/livekit-server:v1.13.11
|
||||
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:f85350f2b31a7521a800d9050e9f5c0676d04cfb60675242ccc0c6e25cad7d04
|
||||
image: ghcr.io/element-hq/element-web:develop@sha256:c850f5058acf2eeb9ed4b392f2f3e53b02240e7a74af8e5f7cc8424d12974c49
|
||||
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:f85350f2b31a7521a800d9050e9f5c0676d04cfb60675242ccc0c6e25cad7d04
|
||||
image: ghcr.io/element-hq/element-web:develop@sha256:c850f5058acf2eeb9ed4b392f2f3e53b02240e7a74af8e5f7cc8424d12974c49
|
||||
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.
|
||||
|
||||
+39
-12
@@ -4,12 +4,17 @@
|
||||
|
||||
- Call logic lives in `src/state/`. A component that derives call state is
|
||||
misplaced logic.
|
||||
- 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.
|
||||
- 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.
|
||||
- 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
|
||||
@@ -73,6 +78,27 @@ 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.
|
||||
@@ -82,12 +108,13 @@ 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`). 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`.
|
||||
`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.
|
||||
- `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,6 +21,18 @@ 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,4 +60,5 @@ 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,7 +14,8 @@ export default {
|
||||
"vite-embedded.config.ts",
|
||||
"vite-sdk.config.ts",
|
||||
"vite-sdk-dev.config.ts",
|
||||
"vite-sdk-target-based-on-call-view-model.config.ts",
|
||||
"vite-widget-rtc-sdk.config.ts",
|
||||
"vite-widget-rtc-sdk-dev.config.ts",
|
||||
"vite-component.config.ts",
|
||||
"vite-component-dev.config.ts",
|
||||
],
|
||||
|
||||
+15
-12
@@ -8,6 +8,7 @@
|
||||
"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",
|
||||
@@ -18,14 +19,17 @@
|
||||
"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-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: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: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:types",
|
||||
"build:component:development": "pnpm build:component:js --mode development && pnpm build:component:check && 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",
|
||||
@@ -51,20 +55,20 @@
|
||||
"build-storybook": "storybook build"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@codecov/vite-plugin": "^1.3.0",
|
||||
"@codecov/vite-plugin": "^2.0.0",
|
||||
"@fontsource/inconsolata": "^5.1.0",
|
||||
"@fontsource/inter": "^5.1.0",
|
||||
"@formatjs/intl-durationformat": "^0.10.0",
|
||||
"@formatjs/intl-durationformat": "^0.13.0",
|
||||
"@formatjs/intl-segmenter": "^11.7.3",
|
||||
"@livekit/components-core": "^0.12.0",
|
||||
"@livekit/track-processors": "^0.7.1",
|
||||
"@livekit/track-processors": "^0.8.0",
|
||||
"@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.2.3",
|
||||
"@rolldown/plugin-babel": "^0.3.0",
|
||||
"@sentry/react": "^8.0.0",
|
||||
"@sentry/vite-plugin": "^3.0.0",
|
||||
"@storybook/addon-docs": "^10.3.6",
|
||||
@@ -79,7 +83,6 @@
|
||||
"@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",
|
||||
@@ -91,7 +94,7 @@
|
||||
"@vitejs/plugin-react": "^6.0.2",
|
||||
"@vitest/browser-playwright": "^4.1.5",
|
||||
"@vitest/coverage-v8": "^4.0.18",
|
||||
"@vitest/ui": "4.1.11",
|
||||
"@vitest/ui": "4.1.12",
|
||||
"babel-plugin-react-compiler": "^1.0.0",
|
||||
"classnames": "^2.3.1",
|
||||
"copy-to-clipboard": "^3.3.3",
|
||||
@@ -114,7 +117,7 @@
|
||||
"oxfmt": "^0.79.0",
|
||||
"oxlint": "^1.70.0",
|
||||
"oxlint-tsgolint": "^0.25.0",
|
||||
"pako": "^2.0.4",
|
||||
"pako": "^3.0.3",
|
||||
"postcss": "^8.4.41",
|
||||
"postcss-preset-env": "^10.0.0",
|
||||
"postcss-selector-parser": "^7.1.1",
|
||||
|
||||
+34
-1
@@ -13,6 +13,7 @@ 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"
|
||||
@@ -82,6 +83,11 @@ 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/**"],
|
||||
@@ -93,12 +99,21 @@ 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/**",
|
||||
testIgnore: ["**/mobile/**", "**/widget/widget-rtc-sdk.spec.ts"],
|
||||
use: {
|
||||
...devices["Desktop Firefox"],
|
||||
ignoreHTTPSErrors: true,
|
||||
@@ -183,5 +198,23 @@ 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,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
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,9 +32,11 @@ 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) => {
|
||||
const brooksDisplayName = `brooks_${Date.now()}`;
|
||||
const whistlerDisplayName = `whistler_${Date.now()}`;
|
||||
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}`;
|
||||
|
||||
// Register users
|
||||
const {
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
/*
|
||||
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);
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
/*
|
||||
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,6 +22,12 @@ 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 {
|
||||
@@ -206,8 +212,11 @@ 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
|
||||
await expect(toastTitle).not.toHaveText(title, { timeout: 5000 });
|
||||
// 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,
|
||||
});
|
||||
} else {
|
||||
// Unknown toast. We don't want to act on unknown toasts
|
||||
break;
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
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" },
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
/*
|
||||
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
+1960
-2299
File diff suppressed because it is too large
Load Diff
+10
-14
@@ -30,22 +30,14 @@ overrides:
|
||||
"minimatch": "^11.0.0"
|
||||
# Security fix: https://github.com/element-hq/element-call/security/dependabot/109
|
||||
"glob": "^10.5.0"
|
||||
# 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"
|
||||
# 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"
|
||||
# Storybook declares support for 0.27.0 only but empirically works fine with 0.28.0.
|
||||
"esbuild": "^0.28.0"
|
||||
# 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-w293-vg96-wgc3
|
||||
"undici": "^6.29.1"
|
||||
# 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
|
||||
@@ -63,3 +55,7 @@ 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"
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
/*
|
||||
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));
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
# 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,193 +0,0 @@
|
||||
/*
|
||||
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);
|
||||
},
|
||||
};
|
||||
}
|
||||
+2
-2
@@ -5,8 +5,7 @@ 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), what
|
||||
moved out of Element Call's `src/` in [`SdkMigration.md`](./SdkMigration.md).
|
||||
view on top. The design is in [`SdkArchitecture.md`](./SdkArchitecture.md).
|
||||
|
||||
**Status:** first implementation. `createRTCSlot` and `slot.join()` join the
|
||||
session, connect to the transport, publish the local media and expose every
|
||||
@@ -99,6 +98,7 @@ 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`
|
||||
```
|
||||
|
||||
|
||||
@@ -10,8 +10,7 @@ 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. What moved out of Element
|
||||
Call's `src/` to get there is listed in [`SdkMigration.md`](./SdkMigration.md).
|
||||
therefore `Element Call → sdk`, never the reverse.
|
||||
|
||||
## The architecture
|
||||
|
||||
@@ -132,7 +131,10 @@ 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. The upstream flows
|
||||
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
|
||||
exactly while the membership is `joined`: a sync outage pauses it, and `leave()`
|
||||
pauses it for good and sends the leave.
|
||||
|
||||
@@ -779,7 +781,6 @@ 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
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
# 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`) |
|
||||
+195
-17
@@ -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: "mic" },
|
||||
audio: { deviceId: { exact: "mic" } },
|
||||
video: { width: 640, height: 480, frameRate: undefined },
|
||||
});
|
||||
expect(tracks.map((t) => t.source)).toEqual(["microphone", "camera"]);
|
||||
@@ -35,9 +35,34 @@ 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([
|
||||
@@ -52,7 +77,7 @@ describe("createLocalMedia", () => {
|
||||
|
||||
it("shows the processor's output, initialised once", async () => {
|
||||
const processor = fakeProcessor();
|
||||
const media = createLocalMedia(fakeGetUserMedia());
|
||||
const media = createLocalMedia({ getUserMedia: fakeGetUserMedia() });
|
||||
const [camera] = await media.capture([{ source: "camera", processor }]);
|
||||
const element = document.createElement("video");
|
||||
|
||||
@@ -65,7 +90,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 },
|
||||
@@ -76,7 +101,7 @@ describe("createLocalMedia", () => {
|
||||
expect(taken.get("microphone")?.track).toBe(trackBehind(microphone));
|
||||
expect(taken.get("camera")).toEqual({
|
||||
track: trackBehind(camera),
|
||||
constraints: {},
|
||||
constraints: at720p(),
|
||||
muted: false,
|
||||
processor: { processor, processedTrack: processor.output },
|
||||
});
|
||||
@@ -89,7 +114,7 @@ describe("createLocalMedia", () => {
|
||||
});
|
||||
|
||||
it("finishes a handed-over track", async () => {
|
||||
const media = createLocalMedia(fakeGetUserMedia());
|
||||
const media = createLocalMedia({ getUserMedia: fakeGetUserMedia() });
|
||||
const [camera] = await media.capture([{ source: "camera" }]);
|
||||
const element = document.createElement("video");
|
||||
camera.attach(element);
|
||||
@@ -102,7 +127,7 @@ describe("createLocalMedia", () => {
|
||||
});
|
||||
|
||||
it("mutes by disabling the track and hands the mute over", async () => {
|
||||
const media = createLocalMedia(fakeGetUserMedia());
|
||||
const media = createLocalMedia({ getUserMedia: fakeGetUserMedia() });
|
||||
const [microphone] = await media.capture([{ source: "microphone" }]);
|
||||
|
||||
await expect(microphone.setEnabled(false)).resolves.toBe(false);
|
||||
@@ -115,7 +140,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");
|
||||
@@ -124,7 +149,7 @@ describe("createLocalMedia", () => {
|
||||
await camera.setDevice("other");
|
||||
|
||||
expect(getUserMedia).toHaveBeenLastCalledWith({
|
||||
video: { deviceId: "other" },
|
||||
video: at720p({ deviceId: { exact: "other" } }),
|
||||
});
|
||||
expect(first.stop).toHaveBeenCalled();
|
||||
expect(processor.restart).toHaveBeenCalledOnce();
|
||||
@@ -132,14 +157,140 @@ 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({
|
||||
deviceId: "other",
|
||||
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" }),
|
||||
});
|
||||
});
|
||||
|
||||
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,
|
||||
];
|
||||
@@ -148,13 +299,13 @@ describe("createLocalMedia", () => {
|
||||
await camera.switchFacingMode();
|
||||
|
||||
expect(getUserMedia).toHaveBeenLastCalledWith({
|
||||
video: { facingMode: "environment" },
|
||||
video: at720p({ 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(fakeGetUserMedia());
|
||||
const media = createLocalMedia({ getUserMedia: fakeGetUserMedia() });
|
||||
const [camera] = (await media.capture([{ source: "camera" }])) as [
|
||||
LocalVideoMediaTrack,
|
||||
];
|
||||
@@ -162,7 +313,7 @@ describe("createLocalMedia", () => {
|
||||
});
|
||||
|
||||
it("releases one device and stops the rest", async () => {
|
||||
const media = createLocalMedia(fakeGetUserMedia());
|
||||
const media = createLocalMedia({ getUserMedia: fakeGetUserMedia() });
|
||||
const [microphone, camera] = await media.capture([
|
||||
{ source: "microphone" },
|
||||
{ source: "camera" },
|
||||
@@ -179,7 +330,7 @@ describe("createLocalMedia", () => {
|
||||
});
|
||||
|
||||
it("refuses a screen share", async () => {
|
||||
const media = createLocalMedia(fakeGetUserMedia());
|
||||
const media = createLocalMedia({ getUserMedia: fakeGetUserMedia() });
|
||||
await expect(media.capture([{ source: "screenShare" }])).rejects.toThrow(
|
||||
"screen share",
|
||||
);
|
||||
@@ -227,6 +378,33 @@ 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 {
|
||||
|
||||
+138
-24
@@ -7,6 +7,11 @@ 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,
|
||||
@@ -28,15 +33,28 @@ 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(
|
||||
getUserMedia: GetUserMedia = async (constraints) =>
|
||||
export function createLocalMedia({
|
||||
mediaQuality,
|
||||
getUserMedia = async (constraints) =>
|
||||
navigator.mediaDevices.getUserMedia(constraints),
|
||||
): LocalMedia {
|
||||
}: LocalMediaOptions = {}): LocalMedia {
|
||||
const cameraResolution = cameraCaptureResolution(mediaQuality);
|
||||
const capturedTracks = new Map<Source, CapturedTrack>();
|
||||
const requests = new Map<Source, Request>();
|
||||
const tracks$ = new BehaviorSubject<
|
||||
@@ -78,11 +96,14 @@ export function createLocalMedia(
|
||||
);
|
||||
bySource.set(request.source, request);
|
||||
}
|
||||
const constraints: MediaStreamConstraints = {};
|
||||
for (const request of bySource.values())
|
||||
constraints[request.source === "microphone" ? "audio" : "video"] =
|
||||
trackConstraints(request);
|
||||
const stream = await getUserMedia(constraints);
|
||||
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 captured: CapturedTrack[] = [];
|
||||
for (const track of stream.getTracks()) {
|
||||
const source: Source = track.kind === "audio" ? "microphone" : "camera";
|
||||
@@ -91,7 +112,7 @@ export function createLocalMedia(
|
||||
const captured_ = new CapturedTrack(
|
||||
source,
|
||||
track,
|
||||
trackConstraints(request),
|
||||
constraints[source]!,
|
||||
getUserMedia,
|
||||
);
|
||||
capturedTracks.set(source, captured_);
|
||||
@@ -139,18 +160,86 @@ 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): MediaTrackConstraints {
|
||||
const device = request.deviceId && { deviceId: request.deviceId };
|
||||
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 },
|
||||
};
|
||||
if (request.source === "microphone") return { ...device, ...request.capture };
|
||||
const resolution = request.capture?.resolution;
|
||||
const resolution = request.capture?.resolution ?? cameraResolution;
|
||||
return {
|
||||
...device,
|
||||
...(resolution && {
|
||||
width: resolution.width,
|
||||
height: resolution.height,
|
||||
frameRate: resolution.frameRate,
|
||||
}),
|
||||
width: resolution.width,
|
||||
height: resolution.height,
|
||||
frameRate: resolution.frameRate,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -184,7 +273,12 @@ 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();
|
||||
const constraints = { ...this.constraints, ...(deviceId && { deviceId }) };
|
||||
// `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 } }),
|
||||
};
|
||||
this.finish();
|
||||
return { track, constraints, muted: this.muted$.value, processor };
|
||||
}
|
||||
@@ -245,12 +339,28 @@ class CapturedTrack {
|
||||
for (const element of this.elements) play(element, this.shown());
|
||||
}
|
||||
|
||||
private async reacquire(constraints: MediaTrackConstraints): Promise<void> {
|
||||
/**
|
||||
* 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> {
|
||||
this.live();
|
||||
this.constraints = { ...this.constraints, ...constraints };
|
||||
const stream = await this.getUserMedia({
|
||||
[this.track.kind]: this.constraints,
|
||||
});
|
||||
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.track.stop();
|
||||
this.track = stream.getTracks()[0];
|
||||
this.track.enabled = !this.muted$.value;
|
||||
@@ -288,7 +398,11 @@ class CapturedTrack {
|
||||
},
|
||||
setDevice: async (deviceId: string): Promise<void> => {
|
||||
if (this.track.getSettings().deviceId === deviceId) return;
|
||||
await this.reacquire({ deviceId });
|
||||
// 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 } });
|
||||
},
|
||||
};
|
||||
if (this.source === "microphone")
|
||||
|
||||
@@ -99,3 +99,37 @@ 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 },
|
||||
];
|
||||
|
||||
@@ -143,7 +143,10 @@ export interface LocalMediaTrack {
|
||||
* from the request where the device could not be used.
|
||||
*/
|
||||
setEnabled(enabled: boolean): Promise<boolean>;
|
||||
/** Captures from another device. Rejects for a screen share, which has none. */
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
setDevice(deviceId: string): Promise<void>;
|
||||
}
|
||||
|
||||
|
||||
@@ -213,7 +213,7 @@ describe("createLivekitMediaTrack", () => {
|
||||
expect(switchActiveDevice).toHaveBeenCalledWith(
|
||||
"audioinput",
|
||||
"mic-2",
|
||||
false,
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -225,19 +225,23 @@ 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: "cam-1" }),
|
||||
getSettings: () => ({ deviceId: openDevice }),
|
||||
},
|
||||
// What LiveKit shows as the track, with no device of its own
|
||||
processor: {
|
||||
processedTrack: { label: "", getSettings: () => ({}) },
|
||||
},
|
||||
}) as LocalVideoTrack;
|
||||
const switchActiveDevice = vi.fn().mockResolvedValue(true);
|
||||
const switchActiveDevice = vi.fn(async (_kind: string, id: string) => {
|
||||
openDevice = id;
|
||||
return Promise.resolve(true);
|
||||
});
|
||||
const { participant, publication, room } = fakes({
|
||||
track: camera as unknown as FakeTrack,
|
||||
});
|
||||
@@ -253,11 +257,63 @@ describe("createLivekitMediaTrack", () => {
|
||||
|
||||
await track.setDevice(deviceId);
|
||||
expect(switchActiveDevice.mock.calls).toEqual(
|
||||
switches ? [["videoinput", deviceId, false]] : [],
|
||||
switches ? [["videoinput", deviceId, true]] : [],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
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",
|
||||
@@ -356,6 +412,36 @@ 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,16 +203,35 @@ 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;
|
||||
if (
|
||||
current instanceof LocalTrack &&
|
||||
(await current.getDeviceId(false)) === deviceId
|
||||
)
|
||||
return;
|
||||
await room.switchActiveDevice(
|
||||
base.kind === "audio" ? "audioinput" : "videoinput",
|
||||
deviceId,
|
||||
false,
|
||||
);
|
||||
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 (base.kind === "audio") return { ...base, ...local };
|
||||
@@ -254,6 +273,19 @@ 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,6 +8,7 @@ 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", () => {
|
||||
@@ -108,6 +109,33 @@ 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: {
|
||||
|
||||
@@ -147,11 +147,13 @@ export const RegisterPage: FC = () => {
|
||||
}
|
||||
}, [loading, navigate, authenticated, passwordlessUser, registering]);
|
||||
|
||||
if (loading) {
|
||||
return <LoadingPage />;
|
||||
} else {
|
||||
PosthogAnalytics.instance.eventSignup.cacheSignupStart(new Date());
|
||||
}
|
||||
useEffect(() => {
|
||||
if (!loading) {
|
||||
PosthogAnalytics.instance.eventSignup.cacheSignupStart(new Date());
|
||||
}
|
||||
}, [loading]);
|
||||
|
||||
if (loading) return <LoadingPage />;
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -750,8 +750,7 @@ export const InCallView: FC<InCallViewProps> = ({
|
||||
|
||||
/**
|
||||
* How the tracks are captured and encoded, from Element Call's settings and
|
||||
* configuration. Shared with the legacy SDK bundle so that a widget built from
|
||||
* it behaves like the app.
|
||||
* configuration.
|
||||
*/
|
||||
export function captureSettings(): CaptureSettings {
|
||||
const config = Config.get();
|
||||
@@ -800,8 +799,7 @@ export function captureSettings(): CaptureSettings {
|
||||
/**
|
||||
* What the client needs from Element Call's configuration, settings and URL:
|
||||
* the SDK reads none of them itself. What to publish depends on the mute
|
||||
* switches and the devices, so the caller adds that. Shared with the legacy
|
||||
* SDK bundle so that a widget built from it behaves like the app.
|
||||
* switches and the devices, so the caller adds that.
|
||||
*/
|
||||
export function rtcSlotOptions(
|
||||
encryptionSystem: EncryptionSystem,
|
||||
|
||||
@@ -432,7 +432,7 @@ exports[`InCallView > rendering > renders 1`] = `
|
||||
</div>
|
||||
<fieldset
|
||||
aria-label="Layout"
|
||||
class="_toggle_1t5ha_9 _layout_20b7b4"
|
||||
class="_toggle_1kvhc_9 _layout_20b7b4"
|
||||
data-size="lg"
|
||||
>
|
||||
<input
|
||||
|
||||
@@ -16,12 +16,16 @@ The following sound effects have been licensed from Pixabay, under https://pixab
|
||||
|
||||
The following sound effects have been originally created by Element.
|
||||
|
||||
- `blocked`
|
||||
- `end_talk`
|
||||
- `start_talk_local`
|
||||
- `start_talk_remote`
|
||||
- `join_call`
|
||||
- `end_call`
|
||||
- `left_call`
|
||||
- `screen_share_started`
|
||||
- `ringtone`
|
||||
- `call_declined`
|
||||
- `call_timeout`
|
||||
- `reactions/rock`
|
||||
- `reactions/wave`
|
||||
- `reactions/baduntss`
|
||||
- `reactions/deer`
|
||||
|
||||
@@ -53,7 +53,7 @@ function mockRingEvent(
|
||||
|
||||
const defaultProps = {
|
||||
memberUserIds$: constant<string[]>([]),
|
||||
roomMemberUserIds$: constant([alice.userId]),
|
||||
humanRoomMemberUserIds$: constant([alice.userId]),
|
||||
receivedDecline$: NEVER,
|
||||
options: {
|
||||
waitForCallPickup: true,
|
||||
|
||||
@@ -110,8 +110,12 @@ export interface Props {
|
||||
scope: ObservableScope;
|
||||
/** The user ids of the session's members, ours included. */
|
||||
memberUserIds$: Behavior<string[]>;
|
||||
/** The user ids of the room's members, ours included. */
|
||||
roomMemberUserIds$: Behavior<string[]>;
|
||||
/**
|
||||
* The user ids of the room's human members, ours included. Functional
|
||||
* members (bots) must be excluded: the ring recipient is the first one that
|
||||
* is not us.
|
||||
*/
|
||||
humanRoomMemberUserIds$: Behavior<string[]>;
|
||||
sentCallNotification$: Observable<CallNotificationWrapper | null>;
|
||||
receivedDecline$: Observable<MatrixEvent>;
|
||||
options: { waitForCallPickup?: boolean; autoLeaveWhenOthersLeft?: boolean };
|
||||
@@ -121,7 +125,7 @@ export interface Props {
|
||||
export function createCallNotificationLifecycle$({
|
||||
scope,
|
||||
memberUserIds$,
|
||||
roomMemberUserIds$,
|
||||
humanRoomMemberUserIds$,
|
||||
sentCallNotification$,
|
||||
receivedDecline$,
|
||||
options,
|
||||
@@ -153,8 +157,7 @@ export function createCallNotificationLifecycle$({
|
||||
),
|
||||
switchMap((notificationEvent) => {
|
||||
// We assume that there is only one other user in the room when ringing
|
||||
// TODO: Respect io.element.functional_members
|
||||
const recipient = roomMemberUserIds$.value.find(
|
||||
const recipient = humanRoomMemberUserIds$.value.find(
|
||||
(userId) => userId !== localUser.userId,
|
||||
);
|
||||
if (recipient === undefined) {
|
||||
|
||||
@@ -567,6 +567,58 @@ describe.each(modes)("CallViewModel (%s mode)", (mode) => {
|
||||
});
|
||||
});
|
||||
|
||||
test("one-on-one mobile layout hides name tags in room with 2 members and a bot", () => {
|
||||
withTestScheduler(({ expectObservable }) => {
|
||||
withCallViewModel(
|
||||
{
|
||||
remoteParticipants$: constant([aliceParticipant]),
|
||||
roomMembers: [local, alice, bob],
|
||||
functionalMembers: [bob.userId],
|
||||
rtcMembers$: constant([localRtcMember, aliceRtcMember]),
|
||||
viewSize$: constant({ width: 380, height: 700 }), // Mobile phone
|
||||
},
|
||||
(vm) => {
|
||||
expectObservable(summarizeLayout$(vm.layout$)).toBe("a", {
|
||||
a: {
|
||||
type: "one-on-one-mobile",
|
||||
spotlight: [`${aliceId}:0`],
|
||||
pip: undefined,
|
||||
pipSize: undefined,
|
||||
},
|
||||
});
|
||||
// Bob is a bot, so the room is still a DM with Alice
|
||||
expectObservable(vm.showNameTags$).toBe("n", yesNo);
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test("one-on-one mobile layout shows name tags when a bot is in the call", () => {
|
||||
withTestScheduler(({ expectObservable }) => {
|
||||
withCallViewModel(
|
||||
{
|
||||
remoteParticipants$: constant([bobParticipant]),
|
||||
roomMembers: [local, alice, bob],
|
||||
functionalMembers: [bob.userId],
|
||||
rtcMembers$: constant([localRtcMember, bobRtcMember]),
|
||||
viewSize$: constant({ width: 380, height: 700 }), // Mobile phone
|
||||
},
|
||||
(vm) => {
|
||||
expectObservable(summarizeLayout$(vm.layout$)).toBe("a", {
|
||||
a: {
|
||||
type: "one-on-one-mobile",
|
||||
spotlight: [`${bobId}:0`],
|
||||
pip: undefined,
|
||||
pipSize: undefined,
|
||||
},
|
||||
});
|
||||
// The remote tile is the bot's media, which must never go unlabelled
|
||||
expectObservable(vm.showNameTags$).toBe("y", yesNo);
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test("landscape mobile layouts show screen shares and group call participants", () => {
|
||||
withTestScheduler(({ behavior, expectObservable }) => {
|
||||
// Starts as a one-on-one call, then Alice shares her screen, then Bob
|
||||
@@ -1624,6 +1676,47 @@ describe.each(modes)("CallViewModel (%s mode)", (mode) => {
|
||||
});
|
||||
});
|
||||
|
||||
test("ringing picks the human recipient over a functional member listed first", () => {
|
||||
withTestScheduler(({ behavior, schedule, expectObservable }) => {
|
||||
withCallViewModel(
|
||||
{
|
||||
// Alice answers after 20ms
|
||||
rtcMembers$: behavior("a 20ms b", {
|
||||
a: [localRtcMember],
|
||||
b: [localRtcMember, aliceRtcMember],
|
||||
}),
|
||||
// A DM with a bot, where the bot happens to come first
|
||||
roomMembers: [bob, alice, local],
|
||||
functionalMembers: [bob.userId],
|
||||
},
|
||||
(vm, rtcSession) => {
|
||||
// Fire a ringing notification with a 30ms lifetime
|
||||
schedule("n", {
|
||||
n: () => {
|
||||
rtcSession.emit(
|
||||
MatrixRTCSessionEvent.DidSendCallNotification,
|
||||
mockRingEvent("$notif1", 30),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
// Alice, not the bot, is the recipient, and her pickup stops the ring
|
||||
expectObservable(vm.ringingVm$).toBe("(ab) 17ms a", {
|
||||
a: null,
|
||||
b: expect.objectContaining({
|
||||
type: "ringing",
|
||||
userId: alice.userId,
|
||||
intent: RTC_CALL_INTENT_AUDIO,
|
||||
}),
|
||||
});
|
||||
// The ring was answered, so the lifetime running out must not leave
|
||||
expectObservable(vm.autoLeave$).toBe("-");
|
||||
},
|
||||
{ waitForCallPickup: true },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it.skip("audio output changes when toggling earpiece mode", () => {
|
||||
withTestScheduler(({ schedule, expectObservable }) => {
|
||||
const devices = new MediaDevices(testScope(), {
|
||||
|
||||
@@ -114,6 +114,7 @@ import {
|
||||
createCallNotificationLifecycle$,
|
||||
createReceivedDecline$,
|
||||
} from "./CallNotificationLifecycle.ts";
|
||||
import { createFunctionalMembers$ } from "./FunctionalMembers.ts";
|
||||
import {
|
||||
type LayoutSwitchViewModel,
|
||||
createLayoutSwitchViewModel,
|
||||
@@ -655,6 +656,14 @@ export function createCallViewModel$(
|
||||
),
|
||||
roomMembers(matrixRoom),
|
||||
);
|
||||
const functionalMembers$ = createFunctionalMembers$(scope, matrixRoom);
|
||||
const humanRoomMembers$ = scope.behavior(
|
||||
combineLatest([matrixRoomMembers$, functionalMembers$]).pipe(
|
||||
map(([members, functional]) =>
|
||||
members.filter((m) => !functional.has(m.userId)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// TODO if we are in "unknown" state we need a loading rendering (or empty screen)
|
||||
// Otherwise it looks like we already connected and only than the ringing starts which is weird.
|
||||
@@ -663,8 +672,8 @@ export function createCallViewModel$(
|
||||
memberUserIds$: scope.behavior(
|
||||
members$.pipe(map((members) => members.map((m) => m.userId))),
|
||||
),
|
||||
roomMemberUserIds$: scope.behavior(
|
||||
matrixRoomMembers$.pipe(map((members) => members.map((m) => m.userId))),
|
||||
humanRoomMemberUserIds$: scope.behavior(
|
||||
humanRoomMembers$.pipe(map((members) => members.map((m) => m.userId))),
|
||||
),
|
||||
sentCallNotification$,
|
||||
receivedDecline$: createReceivedDecline$(matrixRoom),
|
||||
@@ -1120,18 +1129,21 @@ export function createCallViewModel$(
|
||||
layoutMedia$.pipe(
|
||||
switchMap((l) =>
|
||||
l.type === "pip" || l.type === "one-on-one-mobile"
|
||||
? matrixRoomMembers$.pipe(
|
||||
? combineLatest([
|
||||
humanRoomMembers$,
|
||||
members$,
|
||||
functionalMembers$,
|
||||
]).pipe(
|
||||
map(
|
||||
(members) =>
|
||||
([humanMembers, callMembers, functional]) =>
|
||||
// Hide name tags by default in these layouts. For safety we
|
||||
// still need to show them in case it wouldn't be clear who
|
||||
// the spotlight media belongs to.
|
||||
// TODO: Respect io.element.functional_members (while still
|
||||
// being careful to never show a functional member's media
|
||||
// without a name tag!)
|
||||
// the spotlight media belongs to: a third person in the room,
|
||||
// or a functional member in the call.
|
||||
// TODO: Only hide name tags in DMs, not group chats that just
|
||||
// happen to have only 2 users
|
||||
members.length > 2,
|
||||
humanMembers.length > 2 ||
|
||||
callMembers.some((m) => functional.has(m.userId)),
|
||||
),
|
||||
)
|
||||
: of(true),
|
||||
|
||||
@@ -19,7 +19,14 @@ import {
|
||||
} from "@element-hq/matrixrtc-sdk";
|
||||
import { SyncState } from "matrix-js-sdk/lib/sync";
|
||||
import { BehaviorSubject, map, of, switchMap } from "rxjs";
|
||||
import { ClientEvent, type RoomMember, type MatrixClient } from "matrix-js-sdk";
|
||||
import {
|
||||
ClientEvent,
|
||||
KnownMembership,
|
||||
type MatrixEvent,
|
||||
type RoomMember,
|
||||
type MatrixClient,
|
||||
UNSTABLE_ELEMENT_FUNCTIONAL_USERS,
|
||||
} from "matrix-js-sdk";
|
||||
import EventEmitter from "events";
|
||||
|
||||
import type { CallMembership } from "matrix-js-sdk/lib/matrixrtc";
|
||||
@@ -32,6 +39,7 @@ import {
|
||||
import { createSentCallNotification$ } from "./CallNotificationLifecycle";
|
||||
import {
|
||||
mockConfig,
|
||||
mockLiveTimeline,
|
||||
mockMatrixRoom,
|
||||
mockMatrixRoomMember,
|
||||
mockRTCParticipation,
|
||||
@@ -74,6 +82,8 @@ export interface CallViewModelInputs {
|
||||
remoteParticipants$: Behavior<Participant[]>;
|
||||
rtcMembers$: Behavior<Partial<CallMembership>[]>;
|
||||
roomMembers: RoomMember[];
|
||||
/** The user IDs the room marks as functional members (bots). */
|
||||
functionalMembers: string[];
|
||||
/** Whether the local transport is connected. */
|
||||
connected$: Behavior<boolean>;
|
||||
speaking: Map<Participant, Behavior<boolean>>;
|
||||
@@ -100,6 +110,7 @@ export function withCallViewModel(mode: MatrixRTCMode) {
|
||||
dave,
|
||||
daveRTL,
|
||||
],
|
||||
functionalMembers = [],
|
||||
connected$ = constant(true),
|
||||
speaking = new Map(),
|
||||
videoEnabled = new Map(),
|
||||
@@ -145,7 +156,15 @@ export function withCallViewModel(mode: MatrixRTCMode) {
|
||||
}
|
||||
})() as Partial<MatrixClient> as MatrixClient,
|
||||
getMembers: () => roomMembers,
|
||||
getMembersWithMembership: () => roomMembers,
|
||||
getMembersWithMembership: (membership: string) =>
|
||||
membership === KnownMembership.Join ? roomMembers : [],
|
||||
getLiveTimeline: mockLiveTimeline((type, stateKey) =>
|
||||
UNSTABLE_ELEMENT_FUNCTIONAL_USERS.matches(type) && stateKey === ""
|
||||
? ({
|
||||
getContent: () => ({ service_members: functionalMembers }),
|
||||
} as Partial<MatrixEvent> as MatrixEvent)
|
||||
: null,
|
||||
),
|
||||
_unstable_getStickyEvents: () => [],
|
||||
});
|
||||
const rtcSession = new MockRTCSession(room, []).withMemberships(
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
/*
|
||||
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 { beforeEach, describe, it } from "vitest";
|
||||
import {
|
||||
type MatrixEvent,
|
||||
type Room as MatrixRoom,
|
||||
type RoomState,
|
||||
RoomStateEvent,
|
||||
UNSTABLE_ELEMENT_FUNCTIONAL_USERS,
|
||||
} from "matrix-js-sdk";
|
||||
|
||||
import {
|
||||
mockLiveTimeline,
|
||||
mockMatrixRoom,
|
||||
testScope,
|
||||
withTestScheduler,
|
||||
} from "../../utils/test";
|
||||
import { createFunctionalMembers$ } from "./FunctionalMembers";
|
||||
|
||||
describe("createFunctionalMembers$", () => {
|
||||
let room: MatrixRoom;
|
||||
let serviceMembers: string[] | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
serviceMembers = undefined;
|
||||
room = mockMatrixRoom({
|
||||
getLiveTimeline: mockLiveTimeline((type, stateKey) =>
|
||||
serviceMembers !== undefined &&
|
||||
UNSTABLE_ELEMENT_FUNCTIONAL_USERS.matches(type) &&
|
||||
stateKey === ""
|
||||
? ({
|
||||
getContent: () => ({ service_members: serviceMembers }),
|
||||
} as Partial<MatrixEvent> as MatrixEvent)
|
||||
: null,
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
function emitStateEvent(type: string): void {
|
||||
room.emit(
|
||||
RoomStateEvent.Events,
|
||||
{ getType: () => type } as unknown as MatrixEvent,
|
||||
{} as RoomState,
|
||||
null,
|
||||
);
|
||||
}
|
||||
|
||||
it("is empty without a functional members event", () => {
|
||||
withTestScheduler(({ expectObservable }) => {
|
||||
expectObservable(createFunctionalMembers$(testScope(), room)).toBe("a", {
|
||||
a: new Set(),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("tracks the functional members event", () => {
|
||||
withTestScheduler(({ expectObservable, schedule }) => {
|
||||
serviceMembers = ["@bot:example.com"];
|
||||
const functional$ = createFunctionalMembers$(testScope(), room);
|
||||
schedule("-a", {
|
||||
a: () => {
|
||||
serviceMembers = ["@bot:example.com", "@bot2:example.com"];
|
||||
emitStateEvent(UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name);
|
||||
},
|
||||
});
|
||||
expectObservable(functional$).toBe("ab", {
|
||||
a: new Set(["@bot:example.com"]),
|
||||
b: new Set(["@bot:example.com", "@bot2:example.com"]),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores unrelated state events", () => {
|
||||
withTestScheduler(({ expectObservable, schedule }) => {
|
||||
const functional$ = createFunctionalMembers$(testScope(), room);
|
||||
schedule("-a", { a: () => emitStateEvent("m.room.topic") });
|
||||
expectObservable(functional$).toBe("a", { a: new Set() });
|
||||
});
|
||||
});
|
||||
|
||||
it("drops entries that are not user IDs", () => {
|
||||
withTestScheduler(({ expectObservable }) => {
|
||||
serviceMembers = ["@bot:example.com", 42 as unknown as string];
|
||||
expectObservable(createFunctionalMembers$(testScope(), room)).toBe("a", {
|
||||
a: new Set(["@bot:example.com"]),
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
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 {
|
||||
EventTimeline,
|
||||
type MatrixEvent,
|
||||
type Room as MatrixRoom,
|
||||
RoomStateEvent,
|
||||
UNSTABLE_ELEMENT_FUNCTIONAL_USERS,
|
||||
} from "matrix-js-sdk";
|
||||
import { filter, fromEvent, map, type Observable } from "rxjs";
|
||||
import { type Behavior, type ObservableScope } from "@element-hq/matrixrtc-sdk";
|
||||
|
||||
/**
|
||||
* The user IDs that the room marks as functional members (bots and other
|
||||
* service accounts). They should not be treated as participants when deciding who
|
||||
* to ring or whether the room is a DM.
|
||||
*/
|
||||
export function createFunctionalMembers$(
|
||||
scope: ObservableScope,
|
||||
matrixRoom: MatrixRoom,
|
||||
): Behavior<Set<string>> {
|
||||
return scope.behavior(
|
||||
(
|
||||
fromEvent(matrixRoom, RoomStateEvent.Events) as Observable<[MatrixEvent]>
|
||||
).pipe(
|
||||
filter(([event]) =>
|
||||
UNSTABLE_ELEMENT_FUNCTIONAL_USERS.matches(event.getType()),
|
||||
),
|
||||
map(() => functionalMembers(matrixRoom)),
|
||||
),
|
||||
functionalMembers(matrixRoom),
|
||||
);
|
||||
}
|
||||
|
||||
function functionalMembers(matrixRoom: MatrixRoom): Set<string> {
|
||||
const serviceMembers: unknown = matrixRoom
|
||||
.getLiveTimeline()
|
||||
.getState(EventTimeline.FORWARDS)
|
||||
?.getStateEvents(UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name, "")
|
||||
?.getContent().service_members;
|
||||
return new Set(
|
||||
Array.isArray(serviceMembers)
|
||||
? serviceMembers.filter((id): id is string => typeof id === "string")
|
||||
: [],
|
||||
);
|
||||
}
|
||||
@@ -169,6 +169,111 @@ describe("MuteState", () => {
|
||||
expect(syncingValues).toContain(true);
|
||||
expect(syncingValues.at(-1)).toBe(false);
|
||||
});
|
||||
|
||||
// The bug from issue #4403: we join a call without a lobby, and the browser
|
||||
// tells us about the camera only after the call has started.
|
||||
// 1. Start with no camera, with the camera set to be on by default.
|
||||
// 2. Set a handler, like the call does when it starts.
|
||||
// 3. The camera shows up.
|
||||
// The handler must be called with "on", so the call publishes the camera,
|
||||
// and the button must show "on" only after the handler is done.
|
||||
//
|
||||
// What it guards: the button and the real camera must never disagree. In
|
||||
// the bug the button jumped to "on" by itself and nobody told the call, so
|
||||
// the other side saw "Waiting for media". If someone changes how the
|
||||
// default is applied and forgets the handler again, this test fails.
|
||||
test("asks the handler for the default of a device listed after it was set", async () => {
|
||||
const available$ = new BehaviorSubject(new Map<string, DeviceLabel>());
|
||||
const muteState = new MuteState(
|
||||
testScope,
|
||||
aDevice(available$),
|
||||
true,
|
||||
constant(false),
|
||||
);
|
||||
const handler = vi.fn(async (desired: boolean) => Promise.resolve(desired));
|
||||
muteState.setHandler(handler);
|
||||
expect(muteState.enabled$.value).toBe(false);
|
||||
|
||||
available$.next(aCamera);
|
||||
// On only once the handler has acted on it
|
||||
expect(muteState.enabled$.value).toBe(false);
|
||||
await flushPromises();
|
||||
|
||||
expect(handler).toHaveBeenLastCalledWith(true);
|
||||
expect(muteState.enabled$.value).toBe(true);
|
||||
expect(muteState.syncing$.value).toBe(false);
|
||||
});
|
||||
|
||||
// A camera that is unplugged and plugged back in during a call.
|
||||
// 1. Start with a camera, on by default, and set a handler.
|
||||
// 2. The camera goes away, then comes back.
|
||||
// The handler is told "off" when the camera goes away and is not called
|
||||
// again. The camera stays off: we must not turn on a camera that the user
|
||||
// may have turned off before.
|
||||
//
|
||||
// What it guards: a privacy problem the fix for #4403 could cause. The fix
|
||||
// sends the default "on" to the handler. If it did that every time a
|
||||
// camera shows up, replugging a camera (or leaving earpiece mode) would
|
||||
// start sending video without the user asking. This test fails if the
|
||||
// default is ever applied a second time during a call.
|
||||
test("leaves a device that comes back under a handler off", async () => {
|
||||
const available$ = new BehaviorSubject(aCamera);
|
||||
const muteState = new MuteState(
|
||||
testScope,
|
||||
aDevice(available$),
|
||||
true,
|
||||
constant(false),
|
||||
);
|
||||
expect(muteState.enabled$.value).toBe(true);
|
||||
const handler = vi.fn(async (desired: boolean) => Promise.resolve(desired));
|
||||
muteState.setHandler(handler);
|
||||
|
||||
available$.next(new Map());
|
||||
available$.next(aCamera);
|
||||
await flushPromises();
|
||||
|
||||
expect(handler.mock.calls).toEqual([[false]]);
|
||||
expect(muteState.enabled$.value).toBe(false);
|
||||
});
|
||||
|
||||
// The lobby case, which must keep working as before: no handler is set.
|
||||
// 1. Start with no camera, with the camera set to be on by default.
|
||||
// 2. The camera shows up.
|
||||
// The button shows "on" right away, with no waiting.
|
||||
//
|
||||
// What it guards: the lobby and the join read the button's value at once
|
||||
// to decide which devices to open. If the fix for #4403 made the default
|
||||
// wait for a handler here too, the value would be "off" for a moment and
|
||||
// the lobby would open no camera. This test fails if that happens.
|
||||
test("assumes the default at once where no handler is set", () => {
|
||||
const available$ = new BehaviorSubject(new Map<string, DeviceLabel>());
|
||||
const muteState = new MuteState(
|
||||
testScope,
|
||||
aDevice(available$),
|
||||
true,
|
||||
constant(false),
|
||||
);
|
||||
|
||||
available$.next(aCamera);
|
||||
|
||||
expect(muteState.enabled$.value).toBe(true);
|
||||
});
|
||||
|
||||
// A device list with one camera in it.
|
||||
const aCamera = new Map<string, DeviceLabel>([
|
||||
["fbac11", { type: "name", name: "HD Camera" }],
|
||||
]);
|
||||
|
||||
// A fake camera whose device list the test can change while it runs.
|
||||
function aDevice(
|
||||
available$: BehaviorSubject<Map<string, DeviceLabel>>,
|
||||
): MediaDevice<DeviceLabel, SelectedDevice> {
|
||||
return {
|
||||
available$,
|
||||
selected$: constant({ id: "fbac11" }),
|
||||
select(): void {},
|
||||
} as unknown as MediaDevice<DeviceLabel, SelectedDevice>;
|
||||
}
|
||||
});
|
||||
|
||||
describe("MuteStates", () => {
|
||||
|
||||
+26
-10
@@ -53,6 +53,8 @@ export class MuteState<Label, Selected> {
|
||||
this.handler$.next(defaultHandler);
|
||||
}
|
||||
|
||||
private devicesConnectedBefore = false;
|
||||
|
||||
private readonly canControlDevices$ = combineLatest([
|
||||
this.device.available$,
|
||||
this.forceMute$,
|
||||
@@ -86,15 +88,26 @@ export class MuteState<Label, Selected> {
|
||||
};
|
||||
}
|
||||
|
||||
// Assume the default value only once devices are actually connected
|
||||
let enabled = this.enabledByDefault;
|
||||
// defaultHander = no-op hanlder = "no actual device handler available"
|
||||
const handlerAttached = this.handler$.value !== defaultHandler;
|
||||
const deviceCameBackInCall =
|
||||
handlerAttached && this.devicesConnectedBefore;
|
||||
// Set the flag. A marker, that we reached this code before.
|
||||
this.devicesConnectedBefore = true;
|
||||
const initialWanted = deviceCameBackInCall
|
||||
? false
|
||||
: this.enabledByDefault;
|
||||
// With a handler attached we start off and let the sync below actually call
|
||||
// the handler, so the switch shows "on" only once the track is really there.
|
||||
// Without one (lobby) enabled = initialWanted -> no call to handler.
|
||||
let enabled = handlerAttached ? false : initialWanted;
|
||||
const set$ = new Subject<boolean>();
|
||||
const toggle$ = new Subject<void>();
|
||||
const syncing$ = new BehaviorSubject(false);
|
||||
const desired$ = merge(set$, toggle$.pipe(map(() => !enabled)));
|
||||
const enabled$ = new Observable<boolean>((subscriber) => {
|
||||
subscriber.next(enabled);
|
||||
let latestDesired = this.enabledByDefault;
|
||||
let latestDesired = initialWanted;
|
||||
|
||||
const sync = async (): Promise<void> => {
|
||||
if (enabled === latestDesired) {
|
||||
@@ -120,16 +133,19 @@ export class MuteState<Label, Selected> {
|
||||
}
|
||||
};
|
||||
|
||||
const startSync = (): void => {
|
||||
syncing$.next(true);
|
||||
sync().catch((err) => {
|
||||
// TODO: better error handling
|
||||
logger.error("MuteState: handler error", err);
|
||||
});
|
||||
};
|
||||
|
||||
const s = desired$.subscribe((desired) => {
|
||||
latestDesired = desired;
|
||||
if (syncing$.value === false) {
|
||||
syncing$.next(true);
|
||||
sync().catch((err) => {
|
||||
// TODO: better error handling
|
||||
logger.error("MuteState: handler error", err);
|
||||
});
|
||||
}
|
||||
if (syncing$.value === false) startSync();
|
||||
});
|
||||
if (enabled !== latestDesired) startSync();
|
||||
return (): void => {
|
||||
s.unsubscribe();
|
||||
syncing$.complete();
|
||||
|
||||
@@ -111,7 +111,10 @@ Please see LICENSE in the repository root for full details.
|
||||
display: flex;
|
||||
gap: var(--cpd-space-2x);
|
||||
position: absolute;
|
||||
inset-block-end: var(--cpd-space-1x);
|
||||
/* Ensure that the buttons lie within the safe area */
|
||||
inset-block-end: calc(
|
||||
var(--call-view-safe-area-inset-bottom, 0px) + var(--cpd-space-1x)
|
||||
);
|
||||
inset-inline-end: var(--cpd-space-1x);
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ Please see LICENSE in the repository root for full details.
|
||||
import { useEffect } from "react";
|
||||
import { createLocalMedia, type LocalMedia } from "@element-hq/matrixrtc-sdk";
|
||||
|
||||
import { Config } from "./config/Config";
|
||||
import { useInitial } from "./useInitial";
|
||||
|
||||
/**
|
||||
@@ -15,7 +16,11 @@ import { useInitial } from "./useInitial";
|
||||
* the component where the join never comes.
|
||||
*/
|
||||
export function useLocalMedia(): LocalMedia {
|
||||
const media = useInitial(() => createLocalMedia());
|
||||
const media = useInitial(() =>
|
||||
// The quality the join is given, so that a camera opened in the lobby has
|
||||
// the same resolution as one opened by a join without a lobby.
|
||||
createLocalMedia({ mediaQuality: Config.get().media_quality }),
|
||||
);
|
||||
useEffect(() => (): void => media.stop(), [media]);
|
||||
return media;
|
||||
}
|
||||
|
||||
+21
-1
@@ -24,11 +24,13 @@ import {
|
||||
vitest,
|
||||
} from "vitest";
|
||||
import {
|
||||
type EventTimeline,
|
||||
EventType,
|
||||
MatrixEvent,
|
||||
type Room as MatrixRoom,
|
||||
type Room,
|
||||
type RoomMember,
|
||||
type RoomState,
|
||||
TypedEventEmitter,
|
||||
} from "matrix-js-sdk";
|
||||
import {
|
||||
@@ -291,8 +293,26 @@ export function mockMatrixRoomMember(
|
||||
} as RoomMember;
|
||||
}
|
||||
|
||||
/**
|
||||
* A room's `getLiveTimeline`, whose forwards state looks up single state
|
||||
* events with the given function.
|
||||
*/
|
||||
export function mockLiveTimeline(
|
||||
getStateEvent: (type: string, stateKey: string) => MatrixEvent | null,
|
||||
): () => EventTimeline {
|
||||
const state = {
|
||||
getStateEvents: getStateEvent,
|
||||
} as Partial<RoomState> as RoomState;
|
||||
return () =>
|
||||
({ getState: () => state }) as Partial<EventTimeline> as EventTimeline;
|
||||
}
|
||||
|
||||
export function mockMatrixRoom(room: Partial<MatrixRoom>): MatrixRoom {
|
||||
return { ...mockEmitter(), ...room } as Partial<MatrixRoom> as MatrixRoom;
|
||||
return {
|
||||
...mockEmitter(),
|
||||
getLiveTimeline: mockLiveTimeline(() => null),
|
||||
...room,
|
||||
} as Partial<MatrixRoom> as MatrixRoom;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+8
-1
@@ -6,7 +6,11 @@ Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { describe, expect, vi, it, beforeEach } from "vitest";
|
||||
import { createRoomWidgetClient, EventType } from "matrix-js-sdk";
|
||||
import {
|
||||
createRoomWidgetClient,
|
||||
EventType,
|
||||
UNSTABLE_ELEMENT_FUNCTIONAL_USERS,
|
||||
} from "matrix-js-sdk";
|
||||
|
||||
import { getUrlParams } from "./UrlParams";
|
||||
import { initializeWidget } from "./widget";
|
||||
@@ -67,6 +71,7 @@ describe("widget", () => {
|
||||
ElementCallReactionEventType,
|
||||
EventType.RTCDecline,
|
||||
EventType.RTCMembership,
|
||||
"m.rtc.member",
|
||||
];
|
||||
|
||||
const sendState = [
|
||||
@@ -85,6 +90,7 @@ describe("widget", () => {
|
||||
{ eventType: EventType.RoomName },
|
||||
{ eventType: EventType.RoomMember },
|
||||
{ eventType: EventType.RoomEncryption },
|
||||
{ eventType: UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name },
|
||||
{ eventType: EventType.GroupCallMemberPrefix },
|
||||
];
|
||||
|
||||
@@ -100,6 +106,7 @@ describe("widget", () => {
|
||||
EventType.CallSDPStreamMetadataChangedPrefix,
|
||||
EventType.CallReplaces,
|
||||
EventType.CallEncryptionKeysPrefix,
|
||||
"m.rtc.encryption_key",
|
||||
];
|
||||
|
||||
expect(createRoomWidgetClientSpy.mock.calls[0][1]).toStrictEqual({
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
EventType,
|
||||
createRoomWidgetClient,
|
||||
type MatrixClient,
|
||||
UNSTABLE_ELEMENT_FUNCTIONAL_USERS,
|
||||
} from "matrix-js-sdk";
|
||||
import {
|
||||
WidgetApi,
|
||||
@@ -132,6 +133,7 @@ export const initializeWidget = (
|
||||
ElementCallReactionEventType,
|
||||
EventType.RTCDecline,
|
||||
EventType.RTCMembership,
|
||||
"m.rtc.member",
|
||||
];
|
||||
|
||||
const sendState = [
|
||||
@@ -147,6 +149,7 @@ export const initializeWidget = (
|
||||
{ eventType: EventType.RoomName },
|
||||
{ eventType: EventType.RoomMember },
|
||||
{ eventType: EventType.RoomEncryption },
|
||||
{ eventType: UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name },
|
||||
{ eventType: EventType.GroupCallMemberPrefix },
|
||||
];
|
||||
|
||||
@@ -162,6 +165,7 @@ export const initializeWidget = (
|
||||
EventType.CallSDPStreamMetadataChangedPrefix,
|
||||
EventType.CallReplaces,
|
||||
EventType.CallEncryptionKeysPrefix,
|
||||
"m.rtc.encryption_key",
|
||||
];
|
||||
|
||||
const client = createRoomWidgetClient(
|
||||
|
||||
+1
-1
@@ -58,7 +58,7 @@
|
||||
"./src/**/*.tsx",
|
||||
"./playwright/**/*.ts",
|
||||
"./sdk/**/*.ts",
|
||||
"./sdk-target-based-on-call-view-model/**/*.ts",
|
||||
"./widget-rtc-sdk/**/*.ts",
|
||||
"./component/**/*.ts",
|
||||
"./component/**/*.tsx"
|
||||
],
|
||||
|
||||
@@ -133,6 +133,7 @@ export default defineConfig(({ mode }) => {
|
||||
"matrix-js-sdk/lib/models/relations-container",
|
||||
"matrix-js-sdk/lib/models/room",
|
||||
"matrix-js-sdk/lib/models/room-state",
|
||||
"matrix-js-sdk/lib/models/room-sticky-events",
|
||||
"matrix-js-sdk/lib/models/typed-event-emitter",
|
||||
"matrix-js-sdk/lib/randomstring",
|
||||
"matrix-js-sdk/lib/sync",
|
||||
|
||||
@@ -22,6 +22,9 @@ export default defineConfig(({ mode }) => {
|
||||
// Into the package directory, so that `sdk/package.json` describes what
|
||||
// sits next to it and the directory can be installed as a package
|
||||
outDir: "sdk/dist",
|
||||
// Minified for production (`build:sdk`, `build:sdk:production`), readable
|
||||
// in development (`build:sdk:development`). Source maps in both, as for
|
||||
// the component: they ship with the package for the host to debug with.
|
||||
minify: mode === "production",
|
||||
sourcemap: true,
|
||||
lib: {
|
||||
@@ -54,6 +57,7 @@ export default defineConfig(({ mode }) => {
|
||||
"matrix-js-sdk/lib/models/relations-container",
|
||||
"matrix-js-sdk/lib/models/room",
|
||||
"matrix-js-sdk/lib/models/room-state",
|
||||
"matrix-js-sdk/lib/models/room-sticky-events",
|
||||
"matrix-js-sdk/lib/models/typed-event-emitter",
|
||||
"matrix-js-sdk/lib/randomstring",
|
||||
"matrix-js-sdk/lib/sync",
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
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 { defineConfig, searchForWorkspaceRoot } from "vite";
|
||||
import { realpathSync } from "node:fs";
|
||||
import * as fs from "node:fs";
|
||||
|
||||
import { vitePluginsConfig, withoutMatrixCrypto } from "./vite.config.ts";
|
||||
|
||||
// Serves the widget RTC SDK's example widget, `widget-rtc-sdk/index.html`, with
|
||||
// its import of a deployed bundle pointed at the source instead, so that a host
|
||||
// can open the example as a widget against the code in the tree. The shape of
|
||||
// the SDK's development config.
|
||||
//
|
||||
// `vite build` and `vite preview` with this config serve the example bundled,
|
||||
// which the e2e tests use: unbundled, the page is hundreds of module requests,
|
||||
// on which Firefox now and then stalls.
|
||||
export default defineConfig(({ mode }) => {
|
||||
const allow = [searchForWorkspaceRoot(process.cwd())];
|
||||
for (const path of [
|
||||
"node_modules/matrix-js-sdk/node_modules/@matrix-org/matrix-sdk-crypto-wasm",
|
||||
"node_modules/@matrix-org/matrix-sdk-crypto-wasm",
|
||||
]) {
|
||||
try {
|
||||
allow.push(realpathSync(path));
|
||||
} catch {}
|
||||
}
|
||||
|
||||
const base = vitePluginsConfig({ mode, html: false });
|
||||
return {
|
||||
...base,
|
||||
root: "widget-rtc-sdk",
|
||||
publicDir: false,
|
||||
plugins: [
|
||||
...(base.plugins ?? []),
|
||||
// As in the bundle itself (vite-widget-rtc-sdk.config.ts)
|
||||
withoutMatrixCrypto(),
|
||||
{
|
||||
name: "widget-rtc-sdk-from-source",
|
||||
transformIndexHtml: {
|
||||
order: "pre" as const,
|
||||
handler: (html: string): string =>
|
||||
html.replace(
|
||||
/https:\/\/pr\d+-widget-rtc-sdk--element-call\.netlify\.app\/widget-rtc-sdk\.js/,
|
||||
"/main.ts",
|
||||
),
|
||||
},
|
||||
},
|
||||
],
|
||||
server: {
|
||||
host: true,
|
||||
// After the app (3000), the component harness (3001) and the SDK harness
|
||||
// (3002), so that all of them can run at once
|
||||
port: 3003,
|
||||
strictPort: true,
|
||||
fs: { allow },
|
||||
// The same certificate the app uses, which Element Web's pages trust
|
||||
https: {
|
||||
key: fs.readFileSync("./backend/dev_tls_m.localhost.key"),
|
||||
cert: fs.readFileSync("./backend/dev_tls_m.localhost.crt"),
|
||||
},
|
||||
},
|
||||
// The e2e tests' copy, out of the way of `pnpm build:widget-rtc-sdk`'s
|
||||
build: { outDir: "../dist-widget-rtc-sdk-example", emptyOutDir: true },
|
||||
preview: { port: 3003, strictPort: true },
|
||||
worker: {
|
||||
format: "es" as const,
|
||||
},
|
||||
};
|
||||
});
|
||||
+14
-10
@@ -10,11 +10,11 @@ import { fileURLToPath } from "node:url";
|
||||
import { defineConfig } from "vite";
|
||||
import nodePolyfills from "vite-plugin-node-stdlib-browser";
|
||||
|
||||
// Config for the legacy SDK bundle that predates the sdk/ package: a single
|
||||
// bundle of Element Call's CallViewModel for a plain web page or widget. It is
|
||||
// in production use, so it keeps building on top of the sdk/ package until its
|
||||
// consumers have moved to that package directly.
|
||||
export default defineConfig(() => ({
|
||||
import { withoutMatrixCrypto } from "./vite.config.ts";
|
||||
|
||||
// Config for the widget RTC SDK: a single bundle that wraps the sdk/ package for
|
||||
// a widget page. CI deploys it as the `pr<N>-widget-rtc-sdk` Netlify preview.
|
||||
export default defineConfig(({ mode }) => ({
|
||||
worker: { format: "es" as const },
|
||||
resolve: {
|
||||
alias: {
|
||||
@@ -29,14 +29,18 @@ export default defineConfig(() => ({
|
||||
// Otherwise the developer's own config.json in `public` is copied into the output
|
||||
publicDir: false,
|
||||
build: {
|
||||
sourcemap: true,
|
||||
// Optimised for production (`build:widget-rtc-sdk:production`): minified and
|
||||
// without source maps, which nothing uploads for this bundle. Readable in
|
||||
// development.
|
||||
minify: mode === "production",
|
||||
sourcemap: mode !== "production",
|
||||
manifest: true,
|
||||
lib: {
|
||||
formats: ["es" as const],
|
||||
entry: "./sdk-target-based-on-call-view-model/main.ts",
|
||||
name: "MatrixrtcSdk",
|
||||
fileName: "matrixrtc-sdk",
|
||||
entry: "./widget-rtc-sdk/main.ts",
|
||||
name: "WidgetRtcSdk",
|
||||
fileName: "widget-rtc-sdk",
|
||||
},
|
||||
},
|
||||
plugins: [nodePolyfills()],
|
||||
plugins: [nodePolyfills(), withoutMatrixCrypto()],
|
||||
}));
|
||||
@@ -195,6 +195,39 @@ export default ({
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Leaves the Matrix SDK's own end-to-end encryption out of a build that only
|
||||
* runs as a widget: the host's client encrypts and decrypts for it, so the Rust
|
||||
* crypto chunk and its WASM (about 10 MB) would only be shipped, never loaded.
|
||||
* The SDK imports it dynamically, from `initRustCrypto` and `preloadRustCrypto`;
|
||||
* here those reject instead.
|
||||
*/
|
||||
export function withoutMatrixCrypto(): Plugin {
|
||||
const crypto = "\0without-matrix-crypto";
|
||||
const unavailable =
|
||||
"new Error('This build runs as a widget only: the host does the crypto')";
|
||||
return {
|
||||
name: "without-matrix-crypto",
|
||||
enforce: "pre",
|
||||
resolveId(source, importer): string | null {
|
||||
if (
|
||||
importer?.includes("matrix-js-sdk") &&
|
||||
/(^|\/)rust-crypto\/index(\.js)?$/.test(source)
|
||||
)
|
||||
return crypto;
|
||||
return null;
|
||||
},
|
||||
load(id): string | null {
|
||||
if (id === crypto)
|
||||
return [
|
||||
`export async function initRustCrypto() { throw ${unavailable}; }`,
|
||||
`export async function preloadRustCrypto() { throw ${unavailable}; }`,
|
||||
].join("\n");
|
||||
return null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps a plugin's transform off MediaPipe's WASM loader. The loader is a
|
||||
* classic script that sets `self.ModuleFactory`; transformed into a module it
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
> [!CAUTION]
|
||||
> This widget specific sdk should be treated as deprecated.
|
||||
> The VoIP team will keep it here while it is low maintainance.
|
||||
> But we might remove it at any time (Or preferrably move this folder
|
||||
> into its own repository.)
|
||||
> Our recommendation for any web rtc solution (inlcuding widgets)
|
||||
> is to build it directly on the `/sdk` folder of EC.
|
||||
|
||||
# Widget RTC SDK
|
||||
|
||||
A single JavaScript bundle for widget pages: it connects to the host (for
|
||||
example Element Web) over the widget API and wraps the `sdk/` package
|
||||
(`@element-hq/matrixrtc-sdk`) to join a MatrixRTC slot and exchange realtime
|
||||
data. A widget needs no Matrix login of its own: the host's client does the
|
||||
talking. It uses nothing of Element Call's app; a page that is not a widget
|
||||
uses the `sdk/` package directly (see `sdk/README.md`).
|
||||
|
||||
```ts
|
||||
import { createMatrixRTCSdk } from "<bundle url>/widget-rtc-sdk.js";
|
||||
|
||||
const sdk = await createMatrixRTCSdk("com.example.my-app"); // the rtc application
|
||||
sdk.join();
|
||||
sdk.connected$.subscribe((connected) => console.info({ connected }));
|
||||
sdk.remoteMembers$.subscribe((members) => console.info(members));
|
||||
sdk.data$.subscribe(({ rtcBackendIdentity, data }) =>
|
||||
console.info(rtcBackendIdentity, JSON.parse(data)),
|
||||
);
|
||||
await sdk.sendData({ hello: "world" });
|
||||
sdk.leave();
|
||||
```
|
||||
|
||||
`createMatrixRTCSdk(application = "m.call", id = "", sticky = false)` takes the
|
||||
slot's application and id, and whether to ask the host to keep the widget on
|
||||
screen while joined. The participation publishes no media; `sendData` and
|
||||
`data$` carry JSON over the `matrixRTC` data channel topic. When the
|
||||
participation has left, the widget asks the host to close it.
|
||||
|
||||
If the widget page has a `config.json` beside it, the bundle reads Element
|
||||
Call's `matrix_rtc_mode`, `livekit.livekit_service_url`,
|
||||
`sync_disconnect_grace_period_ms` and `matrix_rtc_session` from it.
|
||||
|
||||
## Using a pull request's build
|
||||
|
||||
CI builds the bundle for every pull request and deploys it to Netlify as
|
||||
`pr<N>-widget-rtc-sdk`, so a widget can import it without building anything:
|
||||
|
||||
```
|
||||
https://pr<N>-widget-rtc-sdk--element-call.netlify.app/widget-rtc-sdk.js
|
||||
```
|
||||
|
||||
1. Host a page that imports it. `index.html` in this folder is one: set the
|
||||
PR number in its import and serve the folder, for example with
|
||||
`npx serve -l 8080`.
|
||||
2. Add the page as a widget in a room in Element Web (see
|
||||
[Widget url](#widget-url)):
|
||||
|
||||
```
|
||||
/addwidget http://localhost:8080?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
|
||||
```
|
||||
|
||||
3. Open the widget, approve the capabilities it asks for and allow it to
|
||||
verify your identity, ticking "Remember this": it asks for an OpenID token
|
||||
more than once. The example joins on load. Open it from a second account to see members and
|
||||
data arrive.
|
||||
|
||||
## Building it yourself
|
||||
|
||||
```
|
||||
pnpm install
|
||||
pnpm build:widget-rtc-sdk
|
||||
```
|
||||
|
||||
in the repository root writes the bundle to `dist/`, entry `widget-rtc-sdk.js`.
|
||||
Serve it with CORS, so a page on another origin can import it (for example
|
||||
`npx serve -l 8123 --cors dist`), and point the page's import at
|
||||
`http://localhost:8123/widget-rtc-sdk.js`.
|
||||
|
||||
`build:widget-rtc-sdk:production` (what CI deploys) minifies and leaves out
|
||||
source maps; `build:widget-rtc-sdk:development` does neither.
|
||||
|
||||
## End-to-end test
|
||||
|
||||
`playwright/widget/widget-rtc-sdk.spec.ts` opens `index.html` as a widget in
|
||||
two Element Webs and sends data from one to the other. CI does not run it for
|
||||
now, so run it by hand when you change the bundle or the `sdk/` package. With
|
||||
the Playwright backend running (`pnpm backend-playwright`), in the repository
|
||||
root:
|
||||
|
||||
```
|
||||
pnpm exec playwright test --project=widget-rtc-sdk
|
||||
```
|
||||
|
||||
The `widget-rtc-sdk` project builds the example into
|
||||
`dist-widget-rtc-sdk-example/` and Playwright serves it on
|
||||
https://localhost:3003. Add `--ui` to watch it run.
|
||||
|
||||
## Widget url
|
||||
|
||||
The host fills the widget url's parameters in when it opens the widget; the
|
||||
bundle reads them, from the query or from a query in the fragment, to start the
|
||||
widget API:
|
||||
|
||||
```
|
||||
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
|
||||
```
|
||||
|
||||
`parentUrl` is added by the host. `sendNotificationType` (`ring` or
|
||||
`notification`) optionally notifies the room on join.
|
||||
|
||||
The `$` prefixed variables are replaced by Element Web when it opens the widget
|
||||
(for example `$matrix_user_id` becomes `@user:example.com`, url encoded as
|
||||
`%40user%3Aexample.com`).
|
||||
@@ -1,11 +1,13 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<title>MatrixRTC Widget</title>
|
||||
<title>Widget RTC SDK example</title>
|
||||
<meta charset="utf-8" />
|
||||
<script type="module">
|
||||
// TODO use the url where the matrixrtc-sdk.js file from dist is hosted
|
||||
import { createMatrixRTCSdk } from "http://localhost:8123/matrixrtc-sdk.js";
|
||||
// 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";
|
||||
|
||||
try {
|
||||
window.matrixRTCSdk = await createMatrixRTCSdk(
|
||||
@@ -26,7 +28,7 @@
|
||||
|
||||
sdk.data$.subscribe((data) => {
|
||||
const child = document.createElement("p");
|
||||
child.innerHTML = JSON.stringify(data);
|
||||
child.textContent = JSON.stringify(data);
|
||||
div.appendChild(child);
|
||||
});
|
||||
|
||||
@@ -40,7 +42,7 @@
|
||||
for (const m of members) {
|
||||
console.info("member", m);
|
||||
const child = document.createElement("p");
|
||||
child.innerHTML = m;
|
||||
child.textContent = m;
|
||||
div.appendChild(child);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,312 @@
|
||||
/*
|
||||
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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* The entrypoint of `pnpm build:widget-rtc-sdk`: a bundle for widget pages that
|
||||
* exposes `createMatrixRTCSdk`, to join a slot and exchange realtime data. It is
|
||||
* a thin widget wrapper around the `@element-hq/matrixrtc-sdk` package and uses
|
||||
* nothing of Element Call's app.
|
||||
*/
|
||||
|
||||
import { logger as rootLogger } from "matrix-js-sdk/lib/logger";
|
||||
import {
|
||||
createRoomWidgetClient,
|
||||
EventType,
|
||||
type MatrixClient,
|
||||
} from "matrix-js-sdk/lib/matrix";
|
||||
import { MatrixCapabilities, WidgetApi } from "matrix-widget-api";
|
||||
import {
|
||||
EMPTY,
|
||||
filter,
|
||||
fromEvent,
|
||||
map,
|
||||
type Observable,
|
||||
of,
|
||||
switchMap,
|
||||
take,
|
||||
} from "rxjs";
|
||||
import {
|
||||
type Behavior,
|
||||
createRTCSlot,
|
||||
type DelayedLeaveTimings,
|
||||
E2eeType,
|
||||
type LocalRTCMember,
|
||||
MatrixRTCMode,
|
||||
ObservableScope,
|
||||
type RemoteRTCMember,
|
||||
type RTCParticipation,
|
||||
type RTCParticipationOptions,
|
||||
} from "@element-hq/matrixrtc-sdk";
|
||||
|
||||
/** The data channel topic this bundle has always used, so that old and new builds talk. */
|
||||
const TOPIC = "matrixRTC";
|
||||
|
||||
/** The widget actions of Element Web's that this bundle takes part in. */
|
||||
const HANGUP_ACTION = "im.vector.hangup";
|
||||
const CLOSE_ACTION = "io.element.close";
|
||||
|
||||
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>;
|
||||
}
|
||||
|
||||
/** The subset of Element Call's `config.json` this bundle reads. */
|
||||
interface WidgetConfig {
|
||||
matrix_rtc_mode?: MatrixRTCMode;
|
||||
livekit?: { livekit_service_url: string };
|
||||
sync_disconnect_grace_period_ms?: number;
|
||||
matrix_rtc_session?: {
|
||||
network_error_retry_ms?: number;
|
||||
membership_event_expiry_ms?: number;
|
||||
key_rotation_participant_limit?: number;
|
||||
delayed_leave?: DelayedLeaveTimings;
|
||||
delegated_delayed_leave?: DelayedLeaveTimings;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The parameters the host fills into the widget URL, from the query or from a
|
||||
* query in the fragment, as Element Call reads them.
|
||||
*/
|
||||
function widgetParams(): URLSearchParams {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const hash = window.location.hash;
|
||||
const fragmentQuery = hash.indexOf("?");
|
||||
if (fragmentQuery !== -1)
|
||||
for (const [key, value] of new URLSearchParams(
|
||||
hash.substring(fragmentQuery),
|
||||
))
|
||||
params.set(key, value);
|
||||
return params;
|
||||
}
|
||||
|
||||
/** `config.json` beside the widget page, if there is one. */
|
||||
async function loadConfig(): Promise<WidgetConfig> {
|
||||
try {
|
||||
const response = await fetch("config.json");
|
||||
if (response.ok) return (await response.json()) as WidgetConfig;
|
||||
} catch {}
|
||||
return {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects to the host over the widget API and builds the Matrix client that
|
||||
* routes every request through it, asking for what the SDK needs.
|
||||
*/
|
||||
function connectWidget(
|
||||
params: URLSearchParams,
|
||||
application: string,
|
||||
): { api: WidgetApi; client: MatrixClient; roomId: string } {
|
||||
const required = (name: string): string => {
|
||||
const value = params.get(name);
|
||||
if (!value) throw new Error(`The widget url needs ${name}`);
|
||||
return value;
|
||||
};
|
||||
const widgetId = required("widgetId");
|
||||
const parentUrl = required("parentUrl");
|
||||
const roomId = required("roomId");
|
||||
const userId = required("userId");
|
||||
const deviceId = required("deviceId");
|
||||
const baseUrl = required("baseUrl");
|
||||
|
||||
const api = new WidgetApi(widgetId, new URL(parentUrl).origin);
|
||||
api.requestCapability(MatrixCapabilities.AlwaysOnScreen);
|
||||
|
||||
const sendRecvEvent = [
|
||||
EventType.CallEncryptionKeysPrefix,
|
||||
EventType.RTCDecline,
|
||||
EventType.RTCMembership,
|
||||
"m.rtc.member",
|
||||
];
|
||||
const sendRecvToDevice = [
|
||||
EventType.CallEncryptionKeysPrefix,
|
||||
"m.rtc.encryption_key",
|
||||
];
|
||||
const client = createRoomWidgetClient(
|
||||
api,
|
||||
{
|
||||
sendEvent: [
|
||||
...sendRecvEvent,
|
||||
EventType.CallNotify, // Sent as a deprecated fallback
|
||||
EventType.RTCNotification,
|
||||
EventType.RoomMessage, // For sendRoomMessage
|
||||
],
|
||||
receiveEvent: sendRecvEvent,
|
||||
sendState: [
|
||||
userId, // Legacy call membership events
|
||||
`_${userId}_${deviceId}_${application}`, // Session membership events
|
||||
`${userId}_${deviceId}_${application}`, // The above with no leading underscore, for room versions whose auth rules allow it
|
||||
].map((stateKey) => ({
|
||||
eventType: EventType.GroupCallMemberPrefix,
|
||||
stateKey,
|
||||
})),
|
||||
receiveState: [
|
||||
{ eventType: EventType.RoomCreate },
|
||||
{ eventType: EventType.RoomName },
|
||||
{ eventType: EventType.RoomMember },
|
||||
{ eventType: EventType.RoomEncryption },
|
||||
{ eventType: EventType.GroupCallMemberPrefix },
|
||||
{ eventType: EventType.RTCSlot },
|
||||
],
|
||||
sendToDevice: sendRecvToDevice,
|
||||
receiveToDevice: sendRecvToDevice,
|
||||
turnServers: false,
|
||||
rtcTransports: true,
|
||||
rtcLivekitGetToken: true,
|
||||
rtcLivekitDelegateDelayedLeave: true,
|
||||
sendDelayedEvents: true,
|
||||
updateDelayedEvents: true,
|
||||
sendSticky: true,
|
||||
receiveSticky: true,
|
||||
},
|
||||
roomId,
|
||||
{ baseUrl, userId, deviceId, timelineSupport: true },
|
||||
false,
|
||||
);
|
||||
return { api, client, roomId };
|
||||
}
|
||||
|
||||
export async function createMatrixRTCSdk(
|
||||
application = "m.call",
|
||||
id = "",
|
||||
sticky = false,
|
||||
): Promise<MatrixRTCSdk> {
|
||||
const logger = rootLogger.getChild("[MatrixRTCSdk]");
|
||||
const params = widgetParams();
|
||||
const { api, client, roomId } = connectWidget(params, application);
|
||||
const config = await loadConfig();
|
||||
await client.startClient();
|
||||
const room = client.getRoom(roomId);
|
||||
if (room === null) throw new Error("No room: the url needs a joined roomId");
|
||||
|
||||
const scope = new ObservableScope();
|
||||
const slot = createRTCSlot(scope, client, room, {
|
||||
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
|
||||
matrixRTCMode: config.matrix_rtc_mode ?? MatrixRTCMode.Compatibility,
|
||||
application,
|
||||
id,
|
||||
});
|
||||
const session = config.matrix_rtc_session;
|
||||
const sendNotificationType = params.get("sendNotificationType");
|
||||
const participationOptions: RTCParticipationOptions = {
|
||||
// A data-only participation: nothing is published
|
||||
publish: [],
|
||||
sendNotificationType:
|
||||
sendNotificationType === "ring" || sendNotificationType === "notification"
|
||||
? sendNotificationType
|
||||
: undefined,
|
||||
// Only what the config sets: the SDK spreads these over its defaults
|
||||
timings: Object.fromEntries(
|
||||
Object.entries({
|
||||
syncDisconnectGracePeriodMs: config.sync_disconnect_grace_period_ms,
|
||||
networkErrorRetryMs: session?.network_error_retry_ms,
|
||||
membershipEventExpiryMs: session?.membership_event_expiry_ms,
|
||||
keyRotationParticipantLimit: session?.key_rotation_participant_limit,
|
||||
delayedLeave: session?.delayed_leave,
|
||||
delegatedDelayedLeave: session?.delegated_delayed_leave,
|
||||
}).filter(([, value]) => value !== undefined),
|
||||
),
|
||||
fallbackTransport: config.livekit && {
|
||||
type: "livekit",
|
||||
livekit_service_url: config.livekit.livekit_service_url,
|
||||
},
|
||||
};
|
||||
|
||||
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))),
|
||||
),
|
||||
);
|
||||
|
||||
const leave = (): void => slot.participation$.value?.leave();
|
||||
|
||||
// The host's hang-up button
|
||||
fromEvent<CustomEvent>(api, `action:${HANGUP_ACTION}`)
|
||||
.pipe(scope.bind())
|
||||
.subscribe((ev) => {
|
||||
ev.preventDefault();
|
||||
api.transport.reply(ev.detail, {});
|
||||
leave();
|
||||
});
|
||||
|
||||
return {
|
||||
join: (): void => {
|
||||
if (slot.participation$.value !== null) return;
|
||||
if (sticky)
|
||||
api
|
||||
.setAlwaysOnScreen(true)
|
||||
.catch(failed("Failed to make the widget sticky"));
|
||||
const participation = slot.join(participationOptions);
|
||||
// Once the hang-up has gone through, unstick and ask the host to close us
|
||||
participation.state$
|
||||
.pipe(
|
||||
filter((state) => state.kind === "left"),
|
||||
take(1),
|
||||
scope.bind(),
|
||||
)
|
||||
.subscribe(() => {
|
||||
api
|
||||
.setAlwaysOnScreen(false)
|
||||
.catch(failed("Failed to unstick the widget"))
|
||||
.then(async () => api.transport.send(CLOSE_ACTION, {}))
|
||||
.catch(failed("Failed to ask the host to close"))
|
||||
.finally(() => api.transport.stop());
|
||||
});
|
||||
},
|
||||
leave,
|
||||
stop: (): void => {
|
||||
scope.end();
|
||||
client.stopClient();
|
||||
api.transport.stop();
|
||||
},
|
||||
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);
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user