mirror of
https://github.com/vector-im/element-call.git
synced 2026-11-28 10:01:09 +08:00
Compare commits
216
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a135a7404e | ||
|
|
0118be7ee7 | ||
|
|
788f43f578 | ||
|
|
1816cb3887 | ||
|
|
bddd96e509 | ||
|
|
c0370c254c | ||
|
|
cd1685091f | ||
|
|
48ada17b19 | ||
|
|
4f6a919aa6 | ||
|
|
13ce1c2648 | ||
|
|
9a7ce81396 | ||
|
|
a50a7d19f2 | ||
|
|
a96091411c | ||
|
|
532803d5f5 | ||
|
|
56d5d87954 | ||
|
|
f0ce686a27 | ||
|
|
35310b2771 | ||
|
|
b2b768b4d0 | ||
|
|
2362694216 | ||
|
|
608198be9a | ||
|
|
08be167644 | ||
|
|
df34bb06ff | ||
|
|
c573afee08 | ||
|
|
ddfd48138a | ||
|
|
60c2c353c6 | ||
|
|
fab67321e3 | ||
|
|
00851b0f4f | ||
|
|
92e0965347 | ||
|
|
ada8d6b464 | ||
|
|
caf5e28b23 | ||
|
|
e71203f913 | ||
|
|
2bf7b1385b | ||
|
|
e15b3f9914 | ||
|
|
eb69706111 | ||
|
|
9cb668eabb | ||
|
|
d53e1a25c0 | ||
|
|
58f41e1f59 | ||
|
|
e18322462b | ||
|
|
b40ccc4091 | ||
|
|
4daf10d043 | ||
|
|
d440cd49b2 | ||
|
|
4bb407afc0 | ||
|
|
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 | ||
|
|
df1156b385 | ||
|
|
7cf6cb4fee | ||
|
|
23c8cb05c8 | ||
|
|
89e3ff4c5a | ||
|
|
586154772e | ||
|
|
20a174c0b4 | ||
|
|
02eb134e40 | ||
|
|
3acf5d9a28 | ||
|
|
ac461840a3 | ||
|
|
1cdcb62791 | ||
|
|
2e3f40e08c | ||
|
|
438d14d1a1 | ||
|
|
d04bfdc624 | ||
|
|
b1f8fcd604 | ||
|
|
001a015a3f | ||
|
|
cee9e02617 | ||
|
|
b3bbdc79f5 | ||
|
|
e91d1387b7 | ||
|
|
34465d7230 | ||
|
|
512e885bf2 | ||
|
|
629031038f | ||
|
|
3879cd65b5 | ||
|
|
74500f37ea | ||
|
|
c9616efc5b | ||
|
|
b9546b80f5 | ||
|
|
ad316bbe9a | ||
|
|
63f31e711c | ||
|
|
3e864c537a | ||
|
|
3ce3d0e266 | ||
|
|
6f328d7304 | ||
|
|
e5d74102e1 | ||
|
|
87bd273fa5 | ||
|
|
413b795459 | ||
|
|
a5dd993dd4 | ||
|
|
e9c1e25542 | ||
|
|
60985885d3 | ||
|
|
b3fe19f192 | ||
|
|
f88d8d5830 | ||
|
|
6c66f9a3e7 | ||
|
|
e631979256 | ||
|
|
a27a76d6f1 | ||
|
|
99f48ff987 | ||
|
|
6846c8dd3e | ||
|
|
28ee707ace | ||
|
|
3100c1c410 | ||
|
|
fc1e91f54c | ||
|
|
1ea5f0821d | ||
|
|
d5f72f464d | ||
|
|
1227b0aa18 | ||
|
|
96949a57da | ||
|
|
2e05ef77a0 | ||
|
|
73826ec4f9 | ||
|
|
1135c02e6f | ||
|
|
9dc425b5f8 | ||
|
|
c1b94b62dd | ||
|
|
fa6efd9dad | ||
|
|
6906404a64 | ||
|
|
98e8343d0b | ||
|
|
88659d6498 | ||
|
|
704cbd65a6 | ||
|
|
5f59283b4a | ||
|
|
07dc08cd1c | ||
|
|
60d6029184 | ||
|
|
f41bc2589a | ||
|
|
ceeb26b271 | ||
|
|
e822f967c1 | ||
|
|
ec46b04b71 | ||
|
|
4f3dc9af75 | ||
|
|
cfd8312e46 | ||
|
|
38edc47f64 | ||
|
|
ab4f0f0f77 | ||
|
|
9411a56afc | ||
|
|
889828763c | ||
|
|
a5374791e4 | ||
|
|
a0601876d8 | ||
|
|
eef86fc06e | ||
|
|
cd5c367ce9 | ||
|
|
190902eec0 | ||
|
|
88f748ec21 | ||
|
|
9639effd28 | ||
|
|
f2f67019b4 | ||
|
|
51fac690f4 | ||
|
|
797a86815b | ||
|
|
1ae57e9647 | ||
|
|
4b05ab503e | ||
|
|
ea977cecd9 | ||
|
|
aadbda39b1 | ||
|
|
53c1e4c30f | ||
|
|
6b56c7e683 | ||
|
|
fb4cbc72e2 | ||
|
|
bac9811829 | ||
|
|
a2cfc2af93 | ||
|
|
dcb2b9e8f6 | ||
|
|
373b1e0fc0 | ||
|
|
1bc372b587 | ||
|
|
82ba51ea6a | ||
|
|
07aaa326d2 | ||
|
|
e9cffb60dd | ||
|
|
741dab6dbb | ||
|
|
4f184f504d | ||
|
|
ecf2cbc71e | ||
|
|
fb38a1e6e0 | ||
|
|
06f07fb808 | ||
|
|
eee101ffba | ||
|
|
4e779ac4f5 | ||
|
|
7fb222ce60 | ||
|
|
5fdb920ea8 | ||
|
|
11e143c8ab | ||
|
|
783bd946e8 | ||
|
|
9c64316b42 | ||
|
|
8b9dde62d1 | ||
|
|
25c4f14d8f | ||
|
|
5f776519b1 | ||
|
|
904062b917 |
@@ -0,0 +1,35 @@
|
||||
---
|
||||
name: handoff
|
||||
description: Implement the first cut of a task and stop for a direction check before the quality pass.
|
||||
argument-hint: <the task>
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
Task: $ARGUMENTS
|
||||
|
||||
Stop after the first implementation and hand it back before the quality pass.
|
||||
|
||||
## Before the hand-off
|
||||
|
||||
- Run the narrowest check that rules out an obviously broken hand-off: the test
|
||||
file for the touched code, `tsc` on its own, a single story. Not the full
|
||||
`pnpm lint`, not the whole suite.
|
||||
- If a wider check is needed before feedback can be useful, keep it to the touched
|
||||
code and say why it was needed.
|
||||
- Leave wider refactors, extra tests and documentation polish out. They are
|
||||
follow-up work, not part of the first hand-off.
|
||||
|
||||
## The hand-off
|
||||
|
||||
Stop and ask whether the direction is right. The message says:
|
||||
|
||||
- what was built and where, in a few lines,
|
||||
- which check ran and what it returned, verbatim if it failed,
|
||||
- what was left out on purpose,
|
||||
- the decisions that could have gone another way.
|
||||
|
||||
Do not continue past this point on your own.
|
||||
|
||||
## After the user confirms
|
||||
|
||||
The skill ends here. Continue with the quality pass as usual.
|
||||
@@ -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)
|
||||
@@ -105,6 +105,9 @@
|
||||
- name: "Claude-Review"
|
||||
description: "Request code review from Claude"
|
||||
color: "e57157"
|
||||
- name: "Claude-Analyse-Failures"
|
||||
description: "Request an analysis of failing tests from Claude"
|
||||
color: "4ADEC0"
|
||||
- name: "customer-retainer"
|
||||
color: "F44A5F"
|
||||
- name: "dependencies"
|
||||
|
||||
@@ -14,7 +14,7 @@ permissions:
|
||||
jobs:
|
||||
prevent-blocked:
|
||||
name: Prevent blocked
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
pull-requests: read
|
||||
steps:
|
||||
|
||||
@@ -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
|
||||
@@ -17,7 +22,7 @@ env:
|
||||
jobs:
|
||||
build_and_deploy:
|
||||
name: Build & publish docker
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: write # required to upload release asset
|
||||
packages: write # needed for publishing packages to GHCR
|
||||
|
||||
@@ -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
|
||||
@@ -29,7 +29,7 @@ on:
|
||||
jobs:
|
||||
build:
|
||||
name: Build Element Call
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
@@ -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 }}
|
||||
@@ -25,7 +30,8 @@ jobs:
|
||||
# Deploy main branch to call.element.dev after build completes
|
||||
if: github.ref == 'refs/heads/main'
|
||||
needs: build_full_element_call
|
||||
runs-on: ubuntu-latest
|
||||
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:
|
||||
@@ -92,7 +102,9 @@ jobs:
|
||||
build_storybook:
|
||||
name: Build Storybook
|
||||
if: contains(github.event.pull_request.labels.*.name, 'storybook build')
|
||||
runs-on: ubuntu-latest
|
||||
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"
|
||||
|
||||
@@ -13,7 +13,7 @@ permissions:
|
||||
|
||||
jobs:
|
||||
pr-changelog-label:
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: yogevbd/enforce-label-action@a3c219da6b8fa73f6ba62b68ff09c469b3a1c024 # 2.2.2
|
||||
with:
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
name: Claude failure analysis
|
||||
on:
|
||||
pull_request:
|
||||
types: [labeled]
|
||||
|
||||
permissions:
|
||||
# The action exchanges the GitHub OIDC token for a short-lived Anthropic
|
||||
# access token. GitHub API access goes through CLAUDE_GH_TOKEN instead.
|
||||
id-token: write
|
||||
actions: read
|
||||
|
||||
jobs:
|
||||
analysis:
|
||||
name: Analyse failures
|
||||
# Only run on labelling and skip forks.
|
||||
if: github.event.label.name == 'Claude-Analyse-Failures' && github.event.pull_request.head.repo.full_name == github.repository
|
||||
runs-on: ubuntu-24.04
|
||||
# The turn limit below is generous, so bound the job by time instead.
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
with:
|
||||
# We may need commit history.
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
# Pre-download job logs and artifacts of failed runs so that Claude doesn't spend cycles on it.
|
||||
- name: Download logs and artifacts of failed workflow runs
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
run: |
|
||||
set -eu
|
||||
dir=agent-workspace/ci-artifacts
|
||||
mkdir -p "$dir"
|
||||
|
||||
for run in $(gh run list --commit "$HEAD_SHA" --status failure --json databaseId --jq '.[].databaseId'); do
|
||||
mkdir -p "$dir/$run"
|
||||
|
||||
# Fetch run summary, logs of failed jobs and artifacts.
|
||||
gh run view "$run" > "$dir/$run/run.txt"
|
||||
gh run view "$run" --log-failed > "$dir/$run/failed-jobs.log"
|
||||
gh run download "$run" --dir "$dir/$run" || echo "No artifacts for run $run"
|
||||
done
|
||||
|
||||
# Unpack any (nested) zip archives.
|
||||
while zips=$(find "$dir" -name '*.zip') && [ -n "$zips" ]; do
|
||||
echo "$zips" | while IFS= read -r zip; do
|
||||
unzip -oq "$zip" -d "${zip%.zip}" && rm "$zip"
|
||||
done
|
||||
done
|
||||
|
||||
find "$dir" -maxdepth 3 -type d
|
||||
- name: Analyse
|
||||
uses: anthropics/claude-code-action@6fed3ca145920b639991cb756090506e1bcaf515 # v1.0.245
|
||||
with:
|
||||
anthropic_federation_rule_id: fdrl_01XQmWo4nka1ZTqZdsdeScyr
|
||||
anthropic_organization_id: dfbc9a23-d636-4653-8970-035204ef60fa
|
||||
anthropic_service_account_id: svac_018Ay5qaA7ZW8X7XsbdekqUM
|
||||
anthropic_workspace_id: wrkspc_01Aw8LHjBS6fZysu9yqzYifW
|
||||
# The token used here must grant read access to code, issues, and metadata as well as
|
||||
# read and write access to pull requests.
|
||||
github_token: ${{ secrets.CLAUDE_GH_TOKEN }}
|
||||
use_sticky_comment: true
|
||||
track_progress: true
|
||||
additional_permissions: |
|
||||
actions: read
|
||||
prompt: |
|
||||
One or more test jobs failed on this pull request. Find out why and
|
||||
what would need to change to make them pass.
|
||||
|
||||
The details, logs and artifacts of every failed workflow run have
|
||||
already been downloaded into `agent-workspace/ci-artifacts/<run id>/`:
|
||||
|
||||
- `run.txt`: Textual run summary with jobs, steps and failure annotations
|
||||
- `failed-jobs.log`: Logs of the failed jobs
|
||||
- Any other file: Unpacked run artifacts.
|
||||
|
||||
If `agent-workspace/ci-artifacts` is empty, no workflow failed. Say so
|
||||
and stop in this case.
|
||||
|
||||
Read the commits on this branch with `git log` and `git diff` against
|
||||
the base branch of the PR.
|
||||
|
||||
For each failed workflow run , find out what failed and search the
|
||||
root cause(s). Stop investigating once direct evidence confirms a root
|
||||
cause. Devise at least one possible resolution for each root cause.
|
||||
|
||||
Report your findings as PR comment. Start your message with "# Automated
|
||||
CI failure analysis". Then add one section per root cause with:
|
||||
|
||||
- The affected workflows
|
||||
- Evidence from the logs
|
||||
- The fix proposal(s)
|
||||
|
||||
Be brief and concise in all your communication. Do not mention things
|
||||
workflows that did not fail.
|
||||
|
||||
Use Markdown links for anything that can be navigated to on GitHub
|
||||
such as files, commits, issues, pull requests, workflow runs and
|
||||
jobs.
|
||||
# Set a generous turn limit. It's bounded by timeout-minutes above.
|
||||
claude_args: |
|
||||
--model claude-fable-5-1
|
||||
--allowedTools "mcp__github_ci__get_ci_status,mcp__github_ci__get_workflow_run_details,mcp__github_ci__download_job_log,mcp__github__list_commits,mcp__github__get_commit,mcp__github__get_file_contents,mcp__github__search_code,mcp__github__list_workflow_runs,mcp__github__get_workflow_run,mcp__github__list_pull_requests,mcp__github__get_pull_request,mcp__github__get_pull_request_files,mcp__github__list_tags,Bash(git log:*),Bash(git diff:*),Bash(git show:*),Bash(gh run list:*),Bash(gh run view:*),Bash(gh run download:*),Bash(gh pr view:*),Bash(gh pr diff:*),Bash(gh api:*),Bash(docker:*)"
|
||||
--max-turns 150
|
||||
@@ -1,4 +1,4 @@
|
||||
name: Claude
|
||||
name: Claude review
|
||||
on:
|
||||
pull_request:
|
||||
types: [labeled]
|
||||
@@ -13,7 +13,7 @@ jobs:
|
||||
name: Review
|
||||
# Only run on labelling and skip forks.
|
||||
if: github.event.label.name == 'Claude-Review' && github.event.pull_request.head.repo.full_name == github.repository
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
@@ -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
|
||||
@@ -32,7 +32,7 @@ on:
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
deployments: write
|
||||
environment: Netlify
|
||||
@@ -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-latest
|
||||
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:
|
||||
@@ -17,7 +19,9 @@ jobs:
|
||||
github.event.workflow_run.conclusion == 'success' &&
|
||||
github.event.workflow_run.event == 'pull_request' &&
|
||||
github.event.workflow_run.head_repository.full_name == github.repository
|
||||
runs-on: ubuntu-latest
|
||||
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: |
|
||||
|
||||
@@ -17,7 +17,7 @@ permissions: {}
|
||||
jobs:
|
||||
versioning:
|
||||
name: Versioning
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
DRY_RUN: ${{ steps.dry_run.outputs.DRY_RUN }}
|
||||
PREFIXED_VERSION: ${{ steps.prefixed_version.outputs.PREFIXED_VERSION }}
|
||||
@@ -59,7 +59,7 @@ jobs:
|
||||
publish_npm:
|
||||
needs: versioning
|
||||
name: Publish NPM
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
ARTIFACT_VERSION: ${{ steps.artifact_version.outputs.ARTIFACT_VERSION }}
|
||||
permissions:
|
||||
@@ -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
|
||||
@@ -111,9 +112,11 @@ jobs:
|
||||
needs: [versioning, publish_npm]
|
||||
if: ${{ needs.versioning.outputs.DRY_RUN == 'false' }}
|
||||
name: Update release notes
|
||||
runs-on: ubuntu-latest
|
||||
# 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
|
||||
runs-on: ubuntu-24.04
|
||||
# Shared with publish.yaml and publish-embedded-packages.yaml, which append to the same
|
||||
# release. GitHub lets only one job wait per group, so if all three arrive at once the
|
||||
# waiting one is cancelled: re-run it. To mitigate this, the append exits early when its
|
||||
# heading already exists.
|
||||
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,10 +11,12 @@ on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
versioning:
|
||||
name: Versioning
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
DRY_RUN: ${{ steps.dry_run.outputs.DRY_RUN }}
|
||||
PREFIXED_VERSION: ${{ steps.prefixed_version.outputs.PREFIXED_VERSION }}
|
||||
@@ -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
|
||||
@@ -76,7 +80,7 @@ jobs:
|
||||
needs: [build_element_call, versioning]
|
||||
if: always()
|
||||
name: Publish tarball
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: write # required to upload release asset
|
||||
steps:
|
||||
@@ -97,17 +101,17 @@ 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]
|
||||
if: always()
|
||||
name: Publish NPM
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
ARTIFACT_VERSION: ${{ steps.artifact_version.outputs.ARTIFACT_VERSION }}
|
||||
permissions:
|
||||
@@ -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"
|
||||
|
||||
@@ -152,7 +158,7 @@ jobs:
|
||||
needs: [build_element_call, versioning]
|
||||
if: always()
|
||||
name: Publish Android AAR
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
ARTIFACT_VERSION: ${{ steps.artifact_version.outputs.ARTIFACT_VERSION }}
|
||||
permissions:
|
||||
@@ -212,7 +218,7 @@ jobs:
|
||||
needs: [build_element_call, versioning]
|
||||
if: always()
|
||||
name: Publish SwiftPM Library
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
ARTIFACT_VERSION: ${{ steps.artifact_version.outputs.ARTIFACT_VERSION }}
|
||||
permissions:
|
||||
@@ -282,9 +288,11 @@ jobs:
|
||||
needs: [versioning, publish_npm, publish_android, publish_ios]
|
||||
if: always()
|
||||
name: Update release notes
|
||||
runs-on: ubuntu-latest
|
||||
# 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
|
||||
runs-on: ubuntu-24.04
|
||||
# Shared with publish.yaml and publish-component.yaml, which append to the same
|
||||
# release. GitHub lets only one job wait per group, so if all three arrive at once the
|
||||
# waiting one is cancelled: re-run it. To mitigate this, the append exits early when its
|
||||
# heading already exists.
|
||||
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
|
||||
@@ -23,7 +27,7 @@ jobs:
|
||||
needs: build_element_call
|
||||
if: always()
|
||||
name: Publish tarball
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: write # required to upload release asset
|
||||
packages: write
|
||||
@@ -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: |
|
||||
@@ -68,13 +73,31 @@ jobs:
|
||||
add_docker_release_note:
|
||||
needs: publish_docker
|
||||
name: Add docker release note
|
||||
runs-on: ubuntu-latest
|
||||
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-latest
|
||||
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"
|
||||
@@ -71,10 +77,29 @@ jobs:
|
||||
flags: unittests
|
||||
fail_ci_if_error: true
|
||||
playwright:
|
||||
name: Run end-to-end tests
|
||||
name: Run end-to-end tests (${{ matrix.part }})
|
||||
if: ${{ !inputs.disable_e2e_tests }}
|
||||
timeout-minutes: 60
|
||||
runs-on: ubuntu-latest
|
||||
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.
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- part: chromium-1
|
||||
args: --project=chromium --shard=1/2
|
||||
- part: chromium-2
|
||||
args: --project=chromium --shard=2/2
|
||||
- part: widget-1
|
||||
args: --project=widget --shard=1/2
|
||||
- part: widget-2
|
||||
args: --project=widget --shard=2/2
|
||||
- part: firefox-mobile
|
||||
args: --project=firefox --project=mobile
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with:
|
||||
@@ -83,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"
|
||||
@@ -107,17 +132,66 @@ jobs:
|
||||
run: pnpm playwright install --with-deps
|
||||
- name: Run backend components
|
||||
run: |
|
||||
# Make sure the directory for the embedded build exists as Docker might
|
||||
# create it with wrong access rights otherwise.
|
||||
mkdir -p embedded/web/dist
|
||||
docker compose -f docker-compose-dev.yml -f docker-compose-playwright.yml pull
|
||||
docker compose -f docker-compose-dev.yml -f docker-compose-playwright.yml up -d
|
||||
docker ps
|
||||
- name: Run Playwright tests
|
||||
env:
|
||||
USE_DOCKER: 1
|
||||
run: pnpm exec playwright test
|
||||
ARGS: ${{ matrix.args }}
|
||||
# Unquoted on purpose: the part's arguments are several words
|
||||
run: pnpm exec playwright test $ARGS
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
if: ${{ !cancelled() }}
|
||||
with:
|
||||
name: blob-report-${{ matrix.part }}
|
||||
path: blob-report
|
||||
if-no-files-found: error
|
||||
# Only read by the merge below.
|
||||
retention-days: 1
|
||||
|
||||
e2e_report:
|
||||
# Combines the blobs into a single HTML report and blocks PRs on failure.
|
||||
name: Run end-to-end tests
|
||||
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:
|
||||
# Inside a called workflow, github.repository is the caller so we need to make sure to still check out the EC repo here.
|
||||
repository: ${{ inputs.matrix-js-sdk-sha && 'element-hq/element-call' || github.repository }}
|
||||
persist-credentials: false
|
||||
- name: Enable Corepack
|
||||
run: corepack enable
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with:
|
||||
cache: "pnpm"
|
||||
node-version-file: ".node-version"
|
||||
- name: Install dependencies
|
||||
run: scripts/layered.sh --ignore-pnpmfile
|
||||
env:
|
||||
PR_HEAD_REPO_OWNER: ${{ github.event.pull_request.head.repo.owner.login }}
|
||||
JS_SDK_GITHUB_BASE_REF: ${{ inputs.matrix-js-sdk-sha }}
|
||||
- name: Download the parts' reports
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
|
||||
with:
|
||||
pattern: blob-report-*
|
||||
path: all-blob-reports
|
||||
merge-multiple: true
|
||||
- name: Merge into one HTML report
|
||||
run: pnpm exec playwright merge-reports --reporter html ./all-blob-reports
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: html-report
|
||||
path: playwright-report
|
||||
if-no-files-found: error
|
||||
retention-days: 4
|
||||
- name: Fail on a failed part
|
||||
if: ${{ needs.playwright.result != 'success' }}
|
||||
run: exit 1
|
||||
|
||||
@@ -7,7 +7,7 @@ on:
|
||||
|
||||
jobs:
|
||||
download:
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -8,7 +8,7 @@ on:
|
||||
|
||||
jobs:
|
||||
upload:
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ permissions: {}
|
||||
jobs:
|
||||
zizmor:
|
||||
name: Run zizmor 🌈
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
security-events: write # Required for upload-sarif (used by zizmor-action) to upload SARIF files.
|
||||
steps:
|
||||
@@ -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
|
||||
@@ -44,3 +45,7 @@ storybook-static
|
||||
|
||||
# Nested checkout made by scripts/layered.sh
|
||||
/matrix-js-sdk/
|
||||
|
||||
# Claude
|
||||
/.claude/*
|
||||
!/.claude/skills/
|
||||
|
||||
@@ -16,19 +16,37 @@ host's page. It is the MatrixRTC reference implementation.
|
||||
`@media`, global `i18next` or the `widget` global — take it from a provider.
|
||||
- The change works standalone, as a widget and as a component. Say what you checked.
|
||||
- Every gate below is green before you push.
|
||||
- Hand off after the first implementation, before the quality pass. Then commit on
|
||||
the user's word where the setup allows it, or hand them the message.
|
||||
|
||||
## Read before you
|
||||
|
||||
| … | … |
|
||||
| -------------------------------- | ---------------------------------------------------------- |
|
||||
| start a task of any size | [docs/agents/workflow.md](docs/agents/workflow.md) |
|
||||
| touch call logic or a view model | [docs/agents/architecture.md](docs/agents/architecture.md) |
|
||||
| write any code | [docs/agents/code-style.md](docs/agents/code-style.md) |
|
||||
| write a test, story or e2e spec | [docs/agents/testing.md](docs/agents/testing.md) |
|
||||
| open a PR | [CONTRIBUTING.md](CONTRIBUTING.md) |
|
||||
| implement from a feature spec | [FEATURES_SPEC/AGENTS.md](FEATURES_SPEC/AGENTS.md) |
|
||||
|
||||
## Scratch files live in `agent-workspace/`
|
||||
|
||||
Git-ignored. One kebab-case subfolder per task, matching the branch topic:
|
||||
`agent-workspace/<slug>/`.
|
||||
|
||||
| File | Purpose |
|
||||
| --------------------------- | -------------------------------------------------------------------------------- |
|
||||
| `plan.md` | The concrete approach — files, symbols, edit order — once direction is confirmed |
|
||||
| `commit-msg.txt` | `git commit -F agent-workspace/<slug>/commit-msg.txt` |
|
||||
| `pr-body.md` | `gh pr create --body-file agent-workspace/<slug>/pr-body.md` |
|
||||
| `implementation-summary.md` | What was built, decisions, trade-offs |
|
||||
| `NN-prompt.md` | Raw prompt text, numbered, when worth keeping |
|
||||
|
||||
- Nothing here is durable. The folder is ignored, so anything worth keeping is
|
||||
promoted into the PR body or a doc before the task ends.
|
||||
- Never write scratch files to the repo root. Stray `load_test_summary.md` and
|
||||
`config.json_` files are what this folder prevents.
|
||||
- Start `pr-body.md` from `.github/PULL_REQUEST_TEMPLATE/maintainer.md` when
|
||||
working for a maintainer, otherwise from `.github/PULL_REQUEST_TEMPLATE.md`.
|
||||
In the maintainer template, Plan is the human-edited prompt (`NN-prompt.md`);
|
||||
`plan.md` is the implementation plan and goes under Content.
|
||||
|
||||
## Gates
|
||||
|
||||
@@ -42,6 +60,11 @@ pnpm i18n:check
|
||||
`knip` fails on dead code; a file deliberately inert ahead of its consumer goes in
|
||||
`knip.ts` `ignoreFiles` with a reason.
|
||||
|
||||
Ready means every gate is green and the change is covered at the layers
|
||||
[testing.md](docs/agents/testing.md) asks for. Read the diff against
|
||||
[code-style.md](docs/agents/code-style.md) first. Re-run the whole checklist after
|
||||
any fix.
|
||||
|
||||
## A good PR
|
||||
|
||||
- One slice, under ~400 changed lines, green on its own, linked to its issue.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -221,119 +221,75 @@ See also:
|
||||
|
||||
- [Developing with linked packages](./docs/linking.md)
|
||||
|
||||
#### Element Call as a component (experimental)
|
||||
#### Element Call as a component
|
||||
|
||||
Element Call can also be embedded directly into another React application
|
||||
rather than being loaded in an iframe as a widget. `pnpm build:component`
|
||||
builds it as a library into `component/dist` (the bundle, its stylesheet and
|
||||
type declarations), and
|
||||
Element Call can be rendered inside another React app instead of an iframe.
|
||||
The host supplies its own Matrix client, and the call stays inside the element
|
||||
it is mounted in.
|
||||
|
||||
```sh
|
||||
pnpm dev:component
|
||||
```
|
||||
|
||||
serves a harness on port 3001 that stands in for such an application: it signs
|
||||
in twice against the development backend and shows two calls side by side, in
|
||||
resizable boxes, with page furniture of its own around them. Use it to see how
|
||||
Element Call behaves when it does not own the page — the size it is given,
|
||||
whether it stays inside its container, and what it says to its host, which is
|
||||
logged along the bottom. The harness is served with the same development
|
||||
certificate as the app, so unless the development CA is trusted, the browser
|
||||
needs a certificate exception for `https://localhost:3001` as well (see the
|
||||
note under [Backend](#backend)). It reads the same `public/config.json` as
|
||||
`pnpm dev` if one exists, and runs with Element Call's defaults otherwise.
|
||||
|
||||
The call lays itself out for the size of the element it is mounted in, not the
|
||||
window: a host that shrinks the container to a corner of its page gets the
|
||||
picture-in-picture layout, just as a host that shrank the whole iframe used to.
|
||||
The breakpoints in the stylesheets the component uses are
|
||||
`@container element-call` queries against its root element for the same reason;
|
||||
for the standalone app the root is the page, so they mean what the media queries
|
||||
they replaced did. (The standalone-only views, such as the home and login pages,
|
||||
still use plain media queries, since the component never shows them.)
|
||||
|
||||
The component's stylesheet is confined to the element it is mounted in: the
|
||||
build rewrites every selector so that it matches only Element Call's root or
|
||||
what is inside it, with `html`, `body` and `:root` standing for that root (see
|
||||
`component/build/scopeStylesToRoot.ts`). A host's own page keeps its styles,
|
||||
and Element Call brings its own fonts and design tokens along.
|
||||
|
||||
The component speaks every language the app does. English is bundled in; the
|
||||
other locales are split into chunks the host's bundler loads the first time
|
||||
they are needed. It starts in the browser's language, and follows the host's
|
||||
own language setting through the `language` prop (`supportedLanguages` lists
|
||||
the tags it accepts, and anything else falls back to its base language or to
|
||||
English). The `theme` prop works the same way and takes the same values as the
|
||||
widget's `theme` URL parameter: `light`, `dark`, `light-high-contrast` or
|
||||
`dark-high-contrast`. Both can change while a call is running without
|
||||
disturbing it.
|
||||
|
||||
A host must call and await `initializeElementCall(config)` once before
|
||||
rendering the component: it loads the `Intl` polyfills, applies the
|
||||
deployment-wide `config.json`-style configuration and sets up translations.
|
||||
The component itself takes the host's `client` and the `roomId` to call in, an
|
||||
`intent` saying what the user asked for (which decides whether to show the
|
||||
lobby, ring, and so on), an optional `config` overriding what the intent
|
||||
implies, and an optional `hostBridge` through which Element Call tells the host
|
||||
that the user has joined or hung up, that it wants to stay on screen, and so
|
||||
on. The host makes its own requests (`join`, `hangUp`, `setDeviceMute`) through
|
||||
the handle exposed on `ref`. The full API is documented in the type declarations
|
||||
(`component/index.tsx` and `component/host.ts`).
|
||||
|
||||
A few things differ from the widget on purpose: the component draws a solid
|
||||
background rather than a gradient unless told otherwise, never offers to edit
|
||||
the user's profile (the account is the host's), scopes its keyboard shortcuts to
|
||||
its own root element so that several instances can share a page, and only shows
|
||||
its own post-call and error screens when the host has not supplied a `close()`
|
||||
callback; with one, it asks the host to unmount it instead. The
|
||||
[global JS controls](./docs/controls.md) on `window` are unchanged and remain
|
||||
page-wide, so with several instances on one page they apply to all of them.
|
||||
|
||||
Each release publishes the package to npm, with the same version as the release:
|
||||
##### Install
|
||||
|
||||
```sh
|
||||
npm install @element-hq/element-call-component
|
||||
```
|
||||
|
||||
To use an unreleased commit, a host can instead install it as a git dependency
|
||||
on the `component` directory of this repository,
|
||||
Releases publish the package with the same version as Element Call. For an
|
||||
unreleased commit, depend on this repository directly:
|
||||
|
||||
```json
|
||||
"@element-hq/element-call-component": "github:element-hq/element-call#main&path:/component"
|
||||
```
|
||||
|
||||
whose `prepare` script runs the build on install. That build needs pnpm (via
|
||||
Corepack) on the host's machine, runs a full `pnpm install` of this repository,
|
||||
since it inherits the `--max-old-space-size` setting of
|
||||
the app build; the host's pnpm also has to allow it to run at all
|
||||
(`allowBuilds` in its `pnpm-workspace.yaml`). Note that `component/` is a pnpm
|
||||
project of its own for this reason, so pnpm commands run from inside that
|
||||
directory target it rather than the repository; run them from the repository
|
||||
root. The host imports the component from
|
||||
`@element-hq/element-call-component` and the stylesheet from
|
||||
`@element-hq/element-call-component/style.css`, and has to provide `react`,
|
||||
`react-dom`, `matrix-js-sdk`, `@vector-im/compound-web` and
|
||||
`@vector-im/compound-design-tokens` itself, since the bundle leaves them
|
||||
external.
|
||||
Compound's stylesheet are the host's to load too: the component shares
|
||||
the host's copy of Compound, (required for example for tooltips)
|
||||
This builds on install, so the host needs pnpm (via Corepack) and must allow
|
||||
the build (`allowBuilds` in its `pnpm-workspace.yaml`).
|
||||
|
||||
The component is large, and a host will usually load it lazily, only once a
|
||||
call is shown. Everything a host needs in order to talk about a call before
|
||||
then is also exported
|
||||
from `@element-hq/element-call-component/api` (a small entry point that does not
|
||||
load the component).
|
||||
##### Use
|
||||
|
||||
- props and the types they are made of
|
||||
- the handle
|
||||
- the host bridge
|
||||
- `UserIntent`
|
||||
- `HeaderStyle`
|
||||
- `BackgroundStyle` enums
|
||||
- `configurationForIntent`, the defaults each intent implies
|
||||
Import from it wherever a value such as
|
||||
`BackgroundStyle.Solid` is needed on a path that must stay light; the main
|
||||
entry point re-exports all of it too.
|
||||
1. Provide the externals yourself: `react`, `react-dom`,
|
||||
`@vector-im/compound-web`, `@vector-im/compound-design-tokens`, and
|
||||
Compound's stylesheet. The component bundles its own `matrix-js-sdk`; the
|
||||
host's client and room can be on any version that has what the `client`
|
||||
and `room` props pick from them, which the host's type check enforces.
|
||||
2. Import `@element-hq/element-call-component/style.css`.
|
||||
3. Await `initializeElementCall(config)` once before rendering.
|
||||
4. Render the component with `client`, `room` (from that client) and an
|
||||
`intent`; optionally
|
||||
pass `config`, `hostBridge`, `language` and `theme` (both can change
|
||||
mid-call). Control it through the `ref` handle (`join`, `hangUp`,
|
||||
`setDeviceMute`).
|
||||
|
||||
Load the component lazily. Types, enums and `configurationForIntent` are
|
||||
available without it from `@element-hq/element-call-component/api`. The full
|
||||
API is in `component/index.tsx`, `component/api.ts` and `component/host.ts`.
|
||||
|
||||
##### How it differs from the widget
|
||||
|
||||
- It lays out for its container, not the window: a small container gets the
|
||||
picture-in-picture layout.
|
||||
- Its styles and keyboard shortcuts are scoped to its root, so the host page is
|
||||
untouched and several instances can share a page. The
|
||||
[global JS controls](./docs/controls.md) stay page-wide.
|
||||
- It draws a solid background by default and never offers profile editing.
|
||||
- If the host bridge implements `close()`, it asks to be unmounted instead of
|
||||
showing its own post-call and error screens.
|
||||
- Sounds, images and the MediaPipe runtime are separate files the host's
|
||||
bundler copies (webpack 5, Vite, Rollup); MediaPipe is fetched only when a
|
||||
background effect is first used.
|
||||
|
||||
##### Develop
|
||||
|
||||
- `pnpm build:component` builds the library into `component/dist`. It ends
|
||||
with `scripts/check-component-bundle.mjs`, which fails the build on what a
|
||||
host must not be handed: an asset inlined as a data URL, a file referenced
|
||||
by an absolute path, the standalone app's client store worker, or a module
|
||||
over its size budget.
|
||||
- `pnpm 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,
|
||||
and needs the same certificate exception as `pnpm dev` (see
|
||||
[Backend](#backend)).
|
||||
- Run pnpm commands from the repository root; `component/` is its own pnpm
|
||||
project.
|
||||
|
||||
### Backend
|
||||
|
||||
|
||||
@@ -26,8 +26,7 @@
|
||||
"features": {
|
||||
"feature_element_call_video_rooms": true,
|
||||
"feature_video_rooms": true,
|
||||
"feature_group_calls": true,
|
||||
"feature_release_announcement": false
|
||||
"feature_group_calls": true
|
||||
},
|
||||
"default_federate": true,
|
||||
"default_theme": "light",
|
||||
@@ -40,7 +39,10 @@
|
||||
},
|
||||
"setting_defaults": {
|
||||
"breadcrumbs": true,
|
||||
"feature_group_calls": true
|
||||
"feature_group_calls": true,
|
||||
"releaseAnnouncementData": {
|
||||
"room_list_section": true
|
||||
}
|
||||
},
|
||||
"jitsi": {
|
||||
"preferred_domain": "meet.element.io"
|
||||
|
||||
@@ -26,8 +26,7 @@
|
||||
"features": {
|
||||
"feature_element_call_video_rooms": true,
|
||||
"feature_video_rooms": true,
|
||||
"feature_group_calls": true,
|
||||
"feature_release_announcement": false
|
||||
"feature_group_calls": true
|
||||
},
|
||||
"default_federate": true,
|
||||
"default_theme": "light",
|
||||
@@ -40,7 +39,10 @@
|
||||
},
|
||||
"setting_defaults": {
|
||||
"breadcrumbs": true,
|
||||
"feature_group_calls": true
|
||||
"feature_group_calls": true,
|
||||
"releaseAnnouncementData": {
|
||||
"room_list_section": true
|
||||
}
|
||||
},
|
||||
"jitsi": {
|
||||
"preferred_domain": "meet.element.io"
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { afterEach, beforeEach, expect, test, vi } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { type MatrixClient, type Room } from "matrix-js-sdk";
|
||||
|
||||
import { mockEmitter, mockMatrixRoom } from "../src/utils/test";
|
||||
import { ElementCall } from "./index";
|
||||
|
||||
// The call itself is out of scope: what matters is what it is handed
|
||||
const callView = vi.hoisted(() => vi.fn());
|
||||
vi.mock("../src/room/CallView", () => ({
|
||||
CallView: (props: object): string => {
|
||||
callView(props);
|
||||
return "call";
|
||||
},
|
||||
}));
|
||||
|
||||
// Media devices need a browser jsdom does not have
|
||||
vi.mock("../src/state/AppViewModel", () => ({
|
||||
AppViewModel: class {
|
||||
public mediaDevices = {};
|
||||
public backgroundEffects = {};
|
||||
},
|
||||
}));
|
||||
|
||||
const roomId = "!room:example.org";
|
||||
let room: Room;
|
||||
|
||||
beforeEach(() => {
|
||||
// What the call's backend takes from the room
|
||||
room = mockMatrixRoom({
|
||||
roomId,
|
||||
getMembersWithMembership: vi.fn(),
|
||||
getLiveTimeline: vi.fn(),
|
||||
getVersion: vi.fn(),
|
||||
hasMembershipState: vi.fn(),
|
||||
_unstable_getStickyEvents: vi.fn(),
|
||||
getMxcAvatarUrl: vi.fn(),
|
||||
getJoinRule: vi.fn(),
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
callView.mockClear();
|
||||
});
|
||||
|
||||
test("calls in the room, leaving the session to the call", async () => {
|
||||
render(<ElementCall client={mockClient()} room={room} />);
|
||||
|
||||
await screen.findByText("call");
|
||||
const props = callView.mock.lastCall?.[0];
|
||||
expect(props).toMatchObject({ backend: { roomId } });
|
||||
expect(props).not.toHaveProperty("rtcSession");
|
||||
});
|
||||
|
||||
// No `matrixRTC`: the host's session manager is not ours to use
|
||||
function mockClient(): MatrixClient {
|
||||
return {
|
||||
...mockEmitter(),
|
||||
// What the call view's client is made from
|
||||
baseUrl: "https://matrix.example.org",
|
||||
getUserId: () => "@alice:example.org",
|
||||
getDeviceId: () => "DEVICE",
|
||||
getAccessToken: () => "token",
|
||||
getSyncState: () => null,
|
||||
getUser: () => null,
|
||||
getCrypto: () => undefined,
|
||||
sendEvent: vi.fn(),
|
||||
sendStateEvent: vi.fn(),
|
||||
_unstable_sendStickyEvent: vi.fn(),
|
||||
_unstable_sendStickyDelayedEvent: vi.fn(),
|
||||
cancelPendingEvent: vi.fn(),
|
||||
encryptAndSendToDevice: vi.fn(),
|
||||
redactEvent: vi.fn(),
|
||||
decryptEventIfNeeded: vi.fn(),
|
||||
setDisplayName: vi.fn(),
|
||||
setAvatarUrl: vi.fn(),
|
||||
uploadContent: vi.fn(),
|
||||
doesServerSupportUnstableFeature: vi.fn(),
|
||||
} as unknown as MatrixClient;
|
||||
}
|
||||
+36
-4
@@ -25,10 +25,12 @@ Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import type { Ref } from "react";
|
||||
import type { MatrixClient } from "matrix-js-sdk";
|
||||
import type { Room } from "matrix-js-sdk";
|
||||
|
||||
import type { UrlProperties } from "../src/UrlParams";
|
||||
import type { ElementCallHandle, ElementCallHostBridge } from "./host";
|
||||
import type { HostClientPart } from "./componentLocalJsClient";
|
||||
import type { SuppliedClient } from "../src/ClientContext";
|
||||
import {
|
||||
BackgroundStyle,
|
||||
configurationForIntent,
|
||||
@@ -69,14 +71,44 @@ export {
|
||||
export type ElementCallConfiguration = Partial<UrlConfiguration> &
|
||||
Partial<Pick<UrlProperties, "background">>;
|
||||
|
||||
/**
|
||||
* Everything Element Call reads of the host's room. Listed here rather than
|
||||
* taken from the call's backend, whose types a host cannot resolve.
|
||||
*
|
||||
* STOP GAP until the host passes an interface of our own instead of its `Room`.
|
||||
*/
|
||||
type HostRoomPart = Pick<
|
||||
Room,
|
||||
| "roomId"
|
||||
| "on"
|
||||
| "off"
|
||||
| "getMembersWithMembership"
|
||||
| "getLiveTimeline"
|
||||
| "getVersion"
|
||||
| "hasMembershipState"
|
||||
| "_unstable_getStickyEvents"
|
||||
| "name"
|
||||
| "getMxcAvatarUrl"
|
||||
| "getJoinRule"
|
||||
| "relations"
|
||||
>;
|
||||
|
||||
export interface ElementCallProps {
|
||||
/**
|
||||
* The client to place the call with. Element Call does not authenticate
|
||||
* anyone or manage a session of its own; this one is the host's.
|
||||
*
|
||||
* Typed with the host's own js-sdk, as only what Element Call calls on it: by
|
||||
* the call's backend, and by the rest of the call through its context. A
|
||||
* js-sdk too old for Element Call fails to type-check rather than failing
|
||||
* once a call is shown.
|
||||
*/
|
||||
client: MatrixClient;
|
||||
/** The room to call in. The host's client must already know about it. */
|
||||
roomId: string;
|
||||
client: HostClientPart & SuppliedClient;
|
||||
/**
|
||||
* The room to call in, from the host's client. Typed like `client`: only what
|
||||
* Element Call reads of it.
|
||||
*/
|
||||
room: HostRoomPart;
|
||||
/**
|
||||
* What the user asked for — whether they started the call or joined one that
|
||||
* was already running, and whether it is a call in a group or a DM. Element
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
import {
|
||||
ClientEvent,
|
||||
ConnectionError,
|
||||
EventType,
|
||||
type MatrixClient,
|
||||
SyncState,
|
||||
} from "matrix-js-sdk";
|
||||
|
||||
import { createComponentLocalJsClient } from "./componentLocalJsClient";
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
test("reads the host's live state from the host's client", () => {
|
||||
const host = mockHost();
|
||||
const client = createComponentLocalJsClient(host);
|
||||
const listener = (): void => {};
|
||||
|
||||
expect(client.getSyncState()).toBe(SyncState.Syncing);
|
||||
client.on(ClientEvent.Sync, listener);
|
||||
client.off(ClientEvent.Sync, listener);
|
||||
client.getUser("@bob:example.org");
|
||||
client.getCrypto();
|
||||
|
||||
expect(host.getSyncState).toHaveBeenCalledOnce();
|
||||
expect(host.on).toHaveBeenCalledWith(ClientEvent.Sync, listener);
|
||||
expect(host.off).toHaveBeenCalledWith(ClientEvent.Sync, listener);
|
||||
expect(host.getUser).toHaveBeenCalledWith("@bob:example.org");
|
||||
expect(host.getCrypto).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
test("sends the RTC session's encrypted events with the host's crypto", async () => {
|
||||
const host = mockHost();
|
||||
const client = createComponentLocalJsClient(host);
|
||||
|
||||
await client._unstable_sendStickyEvent(
|
||||
"!room:example.org",
|
||||
1000,
|
||||
null,
|
||||
EventType.RTCMembership,
|
||||
{ slot_id: "m.call#ROOM", msc4354_sticky_key: "key" },
|
||||
);
|
||||
await client.encryptAndSendToDevice("m.room.encrypted", [], {});
|
||||
|
||||
expect(host._unstable_sendStickyEvent).toHaveBeenCalledOnce();
|
||||
expect(host.encryptAndSendToDevice).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
test.each([
|
||||
"sendEvent",
|
||||
"redactEvent",
|
||||
"decryptEventIfNeeded",
|
||||
"_unstable_sendStickyEvent",
|
||||
"_unstable_sendStickyDelayedEvent",
|
||||
"encryptAndSendToDevice",
|
||||
"sendStateEvent",
|
||||
"setDisplayName",
|
||||
"setAvatarUrl",
|
||||
"uploadContent",
|
||||
"doesServerSupportUnstableFeature",
|
||||
] as const)(
|
||||
"the host's %s fails with errors our js-sdk recognises",
|
||||
async (method) => {
|
||||
const host = mockHost();
|
||||
// A ConnectionError of the host's own js-sdk: not ours, but shaped like it
|
||||
const hostError = Object.assign(new Error("fetch failed"), {
|
||||
name: "ConnectionError",
|
||||
});
|
||||
vi.mocked(host[method]).mockRejectedValue(hostError);
|
||||
const client = createComponentLocalJsClient(host);
|
||||
|
||||
await expect(
|
||||
(client[method] as () => Promise<unknown>)(),
|
||||
).rejects.toBeInstanceOf(ConnectionError);
|
||||
},
|
||||
);
|
||||
|
||||
test("takes its credentials from the host", () => {
|
||||
const client = createComponentLocalJsClient(mockHost());
|
||||
|
||||
expect(client.getUserId()).toBe("@alice:example.org");
|
||||
expect(client.getDeviceId()).toBe("DEVICE");
|
||||
expect(client.getDomain()).toBe("example.org");
|
||||
expect(client.baseUrl).toBe("https://matrix.example.org");
|
||||
});
|
||||
|
||||
test("makes requests with whichever token the host holds now", async () => {
|
||||
const fetch = vi.fn(
|
||||
async () =>
|
||||
await Promise.resolve(
|
||||
new Response(JSON.stringify({ access_token: "openid" }), {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}),
|
||||
),
|
||||
);
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
const host = mockHost();
|
||||
const client = createComponentLocalJsClient(host);
|
||||
// As if the host had refreshed its token after we were created
|
||||
host.token = "refreshed";
|
||||
|
||||
await client.getOpenIdToken();
|
||||
|
||||
expect(fetch).toHaveBeenCalledOnce();
|
||||
const [url, init] = fetch.mock.calls[0] as unknown as [URL, RequestInit];
|
||||
expect(url.toString()).toBe(
|
||||
"https://matrix.example.org/_matrix/client/v3/user/%40alice%3Aexample.org/openid/request_token",
|
||||
);
|
||||
expect(new Headers(init.headers).get("Authorization")).toBe(
|
||||
"Bearer refreshed",
|
||||
);
|
||||
});
|
||||
|
||||
function mockHost(): MatrixClient & { token: string } {
|
||||
const host = {
|
||||
token: "first",
|
||||
baseUrl: "https://matrix.example.org",
|
||||
getUserId: (): string => "@alice:example.org",
|
||||
getDeviceId: (): string => "DEVICE",
|
||||
getAccessToken: (): string => host.token,
|
||||
getSyncState: vi.fn(() => SyncState.Syncing),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
getUser: vi.fn(() => null),
|
||||
getCrypto: vi.fn(() => undefined),
|
||||
sendEvent: vi.fn(),
|
||||
sendStateEvent: vi.fn(),
|
||||
_unstable_sendStickyEvent: vi.fn(),
|
||||
_unstable_sendStickyDelayedEvent: vi.fn(),
|
||||
encryptAndSendToDevice: vi.fn(),
|
||||
redactEvent: vi.fn(),
|
||||
decryptEventIfNeeded: vi.fn(),
|
||||
setDisplayName: vi.fn(),
|
||||
setAvatarUrl: vi.fn(),
|
||||
uploadContent: vi.fn(),
|
||||
doesServerSupportUnstableFeature: vi.fn(),
|
||||
};
|
||||
return host as unknown as MatrixClient & { token: string };
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { createClient, type MatrixClient } from "matrix-js-sdk";
|
||||
import type { createCallMatrixBackend } from "../src/CallMatrixBackend";
|
||||
import { adoptingHostErrors } from "./hostErrors";
|
||||
|
||||
/**
|
||||
* Everything the component calls on the host's client. Part of the public
|
||||
* `client` prop (see api.ts), so that a host whose js-sdk lacks one of these
|
||||
* fails to type-check.
|
||||
*
|
||||
* STOP GAP until the host passes an interface of our own instead of its
|
||||
* `MatrixClient`.
|
||||
*/
|
||||
export type HostClientPart = Pick<
|
||||
MatrixClient,
|
||||
| "baseUrl"
|
||||
| "getUserId"
|
||||
| "getDeviceId"
|
||||
| "getAccessToken"
|
||||
| "getSyncState"
|
||||
| "on"
|
||||
| "off"
|
||||
| "getUser"
|
||||
| "getCrypto"
|
||||
| "sendEvent"
|
||||
| "redactEvent"
|
||||
| "decryptEventIfNeeded"
|
||||
| "_unstable_sendStickyEvent"
|
||||
| "_unstable_sendStickyDelayedEvent"
|
||||
| "encryptAndSendToDevice"
|
||||
| "sendStateEvent"
|
||||
| "setDisplayName"
|
||||
| "setAvatarUrl"
|
||||
| "uploadContent"
|
||||
| "doesServerSupportUnstableFeature"
|
||||
>;
|
||||
|
||||
/**
|
||||
* The client for Element Call in Component mode.
|
||||
* We do get the full host client but we dont want to use it as it
|
||||
* might use older versions of methods were we expect changes. (f.ex. getLivekitToken)
|
||||
* We really want the expected implementation to not get runtime errors.
|
||||
*
|
||||
* This creates a new client that does use the hosts token and "stable"
|
||||
* methods but uses the ElementCall Components js-sdk's client impl for anything else.
|
||||
*/
|
||||
export function createComponentLocalJsClient(
|
||||
host: HostClientPart,
|
||||
): Parameters<typeof createCallMatrixBackend>[0] {
|
||||
const own = createClient({
|
||||
baseUrl: host.baseUrl,
|
||||
userId: host.getUserId() ?? undefined,
|
||||
deviceId: host.getDeviceId() ?? undefined,
|
||||
accessToken: host.getAccessToken() ?? undefined,
|
||||
// The host refreshes its token without telling us, so each request takes
|
||||
// whichever token the host holds now
|
||||
fetchFn: async (input, init) => {
|
||||
const headers = new Headers(init?.headers);
|
||||
const token = host.getAccessToken();
|
||||
if (token !== null) headers.set("Authorization", `Bearer ${token}`);
|
||||
return globalThis.fetch(input, { ...init, headers });
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
// Own has no sync loop: `syncApi?.getSyncState() ?? null` is always null
|
||||
getSyncState: host.getSyncState.bind(host),
|
||||
// Only the syncing host emits `Sync`, `ToDeviceEvent` and `Decrypted`
|
||||
on: host.on.bind(host),
|
||||
// The same emitter as `on`
|
||||
off: host.off.bind(host),
|
||||
// `this.store.getUser`: own's store is empty, only the host's sync fills it
|
||||
getUser: host.getUser.bind(host),
|
||||
// Own never inits crypto, and a second one on the device would corrupt it
|
||||
getCrypto: host.getCrypto.bind(host),
|
||||
// Every one of the host's methods that can fail rejects with our error
|
||||
// classes, which ours can recognise (see hostErrors.ts)
|
||||
|
||||
// Own has no rooms: `encryptEventIfNeeded`'s `if (!room) return` skips E2EE
|
||||
sendEvent: adoptingHostErrors(host.sendEvent.bind(host)),
|
||||
// Not encrypted, but the local echo goes to `getRoom()`: only the host's
|
||||
redactEvent: adoptingHostErrors(host.redactEvent.bind(host)),
|
||||
// `attemptDecryption` only runs `if (this.getCrypto())`: a no-op on own
|
||||
decryptEventIfNeeded: adoptingHostErrors(
|
||||
host.decryptEventIfNeeded.bind(host),
|
||||
),
|
||||
// Like `sendEvent`: on own, `if (!room) return` sends it in plaintext
|
||||
_unstable_sendStickyEvent: adoptingHostErrors(
|
||||
host._unstable_sendStickyEvent.bind(host),
|
||||
),
|
||||
// Like `sendEvent`: delayed, but still `encryptEventIfNeeded(event, room)`
|
||||
_unstable_sendStickyDelayedEvent: adoptingHostErrors(
|
||||
host._unstable_sendStickyDelayedEvent.bind(host),
|
||||
),
|
||||
// `if (!this.cryptoBackend) throw`: own has no crypto
|
||||
encryptAndSendToDevice: adoptingHostErrors(
|
||||
host.encryptAndSendToDevice.bind(host),
|
||||
),
|
||||
|
||||
// Static: own was created with the host's user id
|
||||
getUserId: own.getUserId.bind(own),
|
||||
// Static: own was created with the host's device id
|
||||
getDeviceId: own.getDeviceId.bind(own),
|
||||
// Static: derived from the user id
|
||||
getDomain: own.getDomain.bind(own),
|
||||
// Static: own was created with the host's base URL
|
||||
baseUrl: own.baseUrl,
|
||||
// MSC4143 stable or unstable prefix, picked by /versions: ours knows both
|
||||
getRTCTransports: own.getRTCTransports.bind(own),
|
||||
// Plain HTTP with the copied credentials, like the other LiveKit auth
|
||||
getOpenIdToken: own.getOpenIdToken.bind(own),
|
||||
// MSC4195 stable or `io.element.msc4195` prefix: an older host may lack it
|
||||
getLivekitToken: own.getLivekitToken.bind(own),
|
||||
// MSC4195, like `getLivekitToken`: an older host may lack it
|
||||
delegateDelayedLeave: own.delegateDelayedLeave.bind(own),
|
||||
// Plain HTTP into own's cache, which `getCachedCapabilities` reads
|
||||
fetchCapabilities: own.fetchCapabilities.bind(own),
|
||||
// Has to be the client whose cache `fetchCapabilities` filled
|
||||
getCachedCapabilities: own.getCachedCapabilities.bind(own),
|
||||
// Straight to `scheduleDelayedEvent`: no room, no crypto, plain HTTP
|
||||
_unstable_sendDelayedStateEvent:
|
||||
own._unstable_sendDelayedStateEvent.bind(own),
|
||||
// Plain POST `/delayed_events/{id}/cancel`; newer API an old host may lack
|
||||
_unstable_cancelScheduledDelayedEvent:
|
||||
own._unstable_cancelScheduledDelayedEvent.bind(own),
|
||||
// Plain POST by the server's delay id: restarts the host's sticky leave too
|
||||
_unstable_restartScheduledDelayedEvent:
|
||||
own._unstable_restartScheduledDelayedEvent.bind(own),
|
||||
// Plain POST `/delayed_events/{id}/send`; newer API an old host may lack
|
||||
_unstable_sendScheduledDelayedEvent:
|
||||
own._unstable_sendScheduledDelayedEvent.bind(own),
|
||||
|
||||
// Plain HTTP, either client works; a stable API, so the host's
|
||||
sendStateEvent: adoptingHostErrors(host.sendStateEvent.bind(host)),
|
||||
// Updates the `User` in the host's store, which `useProfile` listens to
|
||||
setDisplayName: adoptingHostErrors(host.setDisplayName.bind(host)),
|
||||
// Like `setDisplayName`: updates the `User` in the host's store
|
||||
setAvatarUrl: adoptingHostErrors(host.setAvatarUrl.bind(host)),
|
||||
// Plain HTTP, either client works; a stable API, so the host's
|
||||
uploadContent: adoptingHostErrors(host.uploadContent.bind(host)),
|
||||
// Reads the host's /versions, which it has already fetched
|
||||
doesServerSupportUnstableFeature: adoptingHostErrors(
|
||||
host.doesServerSupportUnstableFeature.bind(host),
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -99,6 +99,7 @@ const Pane: FC<{
|
||||
log: (pane: string, message: string) => void;
|
||||
}> = ({ session, roomId, theme, language, log }): ReactNode => {
|
||||
const [mounted, setMounted] = useState(true);
|
||||
const room = session.client.getRoom(roomId);
|
||||
|
||||
const bridge = useMemo(
|
||||
() =>
|
||||
@@ -159,11 +160,12 @@ const Pane: FC<{
|
||||
{/* Resizable, because how Element Call copes with the size it is given is
|
||||
one of the things we cannot find out from the standalone app */}
|
||||
<div className={styles.paneCall} data-testid="call-container">
|
||||
{mounted && (
|
||||
{mounted && room === null && <p>This client does not know {roomId}</p>}
|
||||
{mounted && room !== null && (
|
||||
<ElementCall
|
||||
ref={handle}
|
||||
client={session.client}
|
||||
roomId={roomId}
|
||||
room={room}
|
||||
hostBridge={bridge}
|
||||
theme={theme}
|
||||
language={language}
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { expect, test } from "vitest";
|
||||
import {
|
||||
ConnectionError,
|
||||
HTTPError,
|
||||
MatrixError,
|
||||
UnsupportedDelayedEventsEndpointError,
|
||||
UnsupportedStickyEventsEndpointError,
|
||||
} from "matrix-js-sdk";
|
||||
|
||||
import { adoptHostError, adoptingHostErrors } from "./hostErrors";
|
||||
|
||||
test("a rate limit from the host is one of ours, retry delay included", () => {
|
||||
const error = adoptHostError(
|
||||
new HostMatrixError(
|
||||
{ errcode: "M_LIMIT_EXCEEDED", error: "Too many requests" },
|
||||
429,
|
||||
"https://matrix.example.org/_matrix/client/v3/rooms/x/send",
|
||||
new Headers({ "Retry-After": "3" }),
|
||||
),
|
||||
);
|
||||
|
||||
expect(error).toBeInstanceOf(MatrixError);
|
||||
const matrixError = error as MatrixError;
|
||||
expect(matrixError.errcode).toBe("M_LIMIT_EXCEEDED");
|
||||
expect(matrixError.data).toEqual({
|
||||
errcode: "M_LIMIT_EXCEEDED",
|
||||
error: "Too many requests",
|
||||
});
|
||||
expect(matrixError.httpStatus).toBe(429);
|
||||
expect(matrixError.url).toBe(
|
||||
"https://matrix.example.org/_matrix/client/v3/rooms/x/send",
|
||||
);
|
||||
expect(matrixError.isRateLimitError()).toBe(true);
|
||||
expect(matrixError.getRetryAfterMs()).toBe(3000);
|
||||
});
|
||||
|
||||
test("an HTTP error without a Matrix body from the host is one of ours", () => {
|
||||
const error = adoptHostError(new HostHTTPError("Conflict", 409));
|
||||
|
||||
expect(error).toBeInstanceOf(HTTPError);
|
||||
expect(error).not.toBeInstanceOf(MatrixError);
|
||||
expect((error as HTTPError).httpStatus).toBe(409);
|
||||
expect((error as HTTPError).message).toBe("Conflict");
|
||||
});
|
||||
|
||||
test("a connection failure from the host is one of ours", () => {
|
||||
const error = adoptHostError(new HostConnectionError("fetch failed"));
|
||||
|
||||
expect(error).toBeInstanceOf(ConnectionError);
|
||||
expect((error as ConnectionError).message).toBe("fetch failed");
|
||||
});
|
||||
|
||||
test("missing sticky and delayed event endpoints on the host's server are ours", () => {
|
||||
const sticky = adoptHostError(
|
||||
new HostUnsupportedEndpointError(
|
||||
"UnsupportedStickyEventsEndpointError",
|
||||
"sendStickyEvent",
|
||||
),
|
||||
);
|
||||
const delayed = adoptHostError(
|
||||
new HostUnsupportedEndpointError(
|
||||
"UnsupportedDelayedEventsEndpointError",
|
||||
"sendDelayedStateEvent",
|
||||
),
|
||||
);
|
||||
|
||||
expect(sticky).toBeInstanceOf(UnsupportedStickyEventsEndpointError);
|
||||
expect((sticky as UnsupportedStickyEventsEndpointError).clientEndpoint).toBe(
|
||||
"sendStickyEvent",
|
||||
);
|
||||
expect(delayed).toBeInstanceOf(UnsupportedDelayedEventsEndpointError);
|
||||
expect(
|
||||
(delayed as UnsupportedDelayedEventsEndpointError).clientEndpoint,
|
||||
).toBe("sendDelayedStateEvent");
|
||||
});
|
||||
|
||||
test("keeps where the host's error was thrown", () => {
|
||||
const original = new HostConnectionError("fetch failed");
|
||||
|
||||
expect((adoptHostError(original) as Error).stack).toBe(original.stack);
|
||||
});
|
||||
|
||||
test("leaves our own errors and everything else as they are", () => {
|
||||
const own = new MatrixError({ errcode: "M_FORBIDDEN" }, 403);
|
||||
const refusedByWidgetHost = new Error("Action not allowed");
|
||||
const aborted = new DOMException("Aborted", "AbortError");
|
||||
|
||||
expect(adoptHostError(own)).toBe(own);
|
||||
expect(adoptHostError(refusedByWidgetHost)).toBe(refusedByWidgetHost);
|
||||
expect(adoptHostError(aborted)).toBe(aborted);
|
||||
expect(adoptHostError("not an error")).toBe("not an error");
|
||||
});
|
||||
|
||||
test("a wrapped host method rejects with ours and resolves as it did", async () => {
|
||||
const failing = adoptingHostErrors(async (): Promise<string> =>
|
||||
Promise.reject(new HostConnectionError("fetch failed")),
|
||||
);
|
||||
const succeeding = adoptingHostErrors(
|
||||
async (a: number, b: number): Promise<number> => Promise.resolve(a + b),
|
||||
);
|
||||
|
||||
await expect(failing()).rejects.toBeInstanceOf(ConnectionError);
|
||||
await expect(succeeding(1, 2)).resolves.toBe(3);
|
||||
});
|
||||
|
||||
// Lookalikes of the host js-sdk's classes: the same shape, but not ours
|
||||
|
||||
class HostHTTPError extends Error {
|
||||
public constructor(
|
||||
message: string,
|
||||
public readonly httpStatus?: number,
|
||||
public readonly httpHeaders?: Headers,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public isRateLimitError(): boolean {
|
||||
return this.httpStatus === 429;
|
||||
}
|
||||
}
|
||||
|
||||
class HostMatrixError extends HostHTTPError {
|
||||
public readonly errcode?: string;
|
||||
|
||||
public constructor(
|
||||
public data: { errcode?: string; error?: string },
|
||||
httpStatus?: number,
|
||||
public url?: string,
|
||||
httpHeaders?: Headers,
|
||||
) {
|
||||
super(`MatrixError: ${data.error}`, httpStatus, httpHeaders);
|
||||
this.errcode = data.errcode;
|
||||
this.name = data.errcode ?? "Unknown error code";
|
||||
}
|
||||
}
|
||||
|
||||
class HostConnectionError extends Error {
|
||||
public get name(): string {
|
||||
return "ConnectionError";
|
||||
}
|
||||
}
|
||||
|
||||
class HostUnsupportedEndpointError extends Error {
|
||||
public constructor(
|
||||
name: string,
|
||||
public clientEndpoint: string,
|
||||
) {
|
||||
super(`Server does not support ${clientEndpoint}`);
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import {
|
||||
ConnectionError,
|
||||
HTTPError,
|
||||
MatrixError,
|
||||
UnsupportedDelayedEventsEndpointError,
|
||||
UnsupportedStickyEventsEndpointError,
|
||||
} from "matrix-js-sdk";
|
||||
|
||||
/**
|
||||
* Wraps a method of the host's client so that what it rejects with is
|
||||
* {@link adoptHostError adopted}.
|
||||
*/
|
||||
export function adoptingHostErrors<
|
||||
F extends (...args: never[]) => Promise<unknown>,
|
||||
>(call: F): F {
|
||||
const adopting = async (
|
||||
...args: Parameters<F>
|
||||
): Promise<Awaited<ReturnType<F>>> => {
|
||||
try {
|
||||
return (await call(...args)) as Awaited<ReturnType<F>>;
|
||||
} catch (e) {
|
||||
throw adoptHostError(e);
|
||||
}
|
||||
};
|
||||
return adopting as F;
|
||||
}
|
||||
|
||||
/**
|
||||
* The same error as one of our own js-sdk's classes, where it is one of the
|
||||
* host's.
|
||||
*
|
||||
* The host's client is a different copy of the js-sdk, and ours (the MatrixRTC
|
||||
* session above all) tells rate limits, network failures and missing endpoints
|
||||
* apart with `instanceof`, which never matches the host's classes.
|
||||
*/
|
||||
export function adoptHostError(error: unknown): unknown {
|
||||
if (!(error instanceof Error) || isOwn(error)) return error;
|
||||
const adopted = adopt(error);
|
||||
if (adopted === undefined) return error;
|
||||
adopted.stack = error.stack;
|
||||
return adopted;
|
||||
}
|
||||
|
||||
function isOwn(error: Error): boolean {
|
||||
return (
|
||||
error instanceof HTTPError ||
|
||||
error instanceof ConnectionError ||
|
||||
error instanceof UnsupportedStickyEventsEndpointError ||
|
||||
error instanceof UnsupportedDelayedEventsEndpointError
|
||||
);
|
||||
}
|
||||
|
||||
/** Recognised by shape, since the host's classes cannot be named. */
|
||||
function adopt(error: Error & Partial<HostErrorFields>): Error | undefined {
|
||||
switch (error.name) {
|
||||
case "ConnectionError":
|
||||
return new ConnectionError(error.message);
|
||||
case "UnsupportedStickyEventsEndpointError":
|
||||
return new UnsupportedStickyEventsEndpointError(
|
||||
error.message,
|
||||
error.clientEndpoint as UnsupportedStickyEventsEndpointError["clientEndpoint"],
|
||||
{ cause: error.cause },
|
||||
);
|
||||
case "UnsupportedDelayedEventsEndpointError":
|
||||
return new UnsupportedDelayedEventsEndpointError(
|
||||
error.message,
|
||||
error.clientEndpoint as UnsupportedDelayedEventsEndpointError["clientEndpoint"],
|
||||
);
|
||||
}
|
||||
if (typeof error.isRateLimitError !== "function") return undefined;
|
||||
if (error.data !== undefined)
|
||||
return new MatrixError(
|
||||
error.data,
|
||||
error.httpStatus,
|
||||
error.url,
|
||||
error.event,
|
||||
error.httpHeaders,
|
||||
);
|
||||
return new HTTPError(error.message, error.httpStatus, error.httpHeaders);
|
||||
}
|
||||
|
||||
type HostErrorFields = Pick<
|
||||
MatrixError,
|
||||
"data" | "httpStatus" | "httpHeaders" | "url" | "event" | "isRateLimitError"
|
||||
> & { clientEndpoint: string };
|
||||
+13
-13
@@ -11,7 +11,7 @@ Please see LICENSE in the repository root for full details.
|
||||
* Element Call as a React component, for an application that wants to show a
|
||||
* call inside itself rather than in an iframe.
|
||||
*
|
||||
* The host supplies the client and says which room to call in; Element Call
|
||||
* The host supplies the client and the room to call in; Element Call
|
||||
* supplies the call. Everything it would otherwise take from the page it is on
|
||||
* — the URL, the document body, a Matrix session of its own — comes from the
|
||||
* host instead, or is confined to the container it is mounted in.
|
||||
@@ -84,7 +84,9 @@ import styles from "./ElementCall.module.css";
|
||||
import { useComponentHostBridge } from "./host";
|
||||
import { CallPortalRoot } from "./CallPortalRoot";
|
||||
import { type ElementCallProps } from "./api";
|
||||
import { createComponentLocalJsClient } from "./componentLocalJsClient";
|
||||
import { supportedLanguages, translationsBackend } from "./localization";
|
||||
import { createCallMatrixBackend } from "../src/CallMatrixBackend";
|
||||
|
||||
// The languages Element Call can be shown in
|
||||
export { supportedLanguages } from "./localization";
|
||||
@@ -148,7 +150,7 @@ const Decoration: FC<{ children: JSX.Element }> = ({ children }) => {
|
||||
|
||||
export const ElementCall: FC<ElementCallProps> = ({
|
||||
client,
|
||||
roomId,
|
||||
room,
|
||||
intent = UserIntent.JoinExistingCall,
|
||||
config,
|
||||
hostBridge: suppliedHostBridge,
|
||||
@@ -179,6 +181,7 @@ export const ElementCall: FC<ElementCallProps> = ({
|
||||
// to be stable for as long as its contents are. A host writing `config`
|
||||
// inline would otherwise tear the call down on every render.
|
||||
const stableConfig = useStableValue(config);
|
||||
const { roomId } = room;
|
||||
const params = useMemo(
|
||||
(): UrlParams => ({
|
||||
...componentProperties,
|
||||
@@ -204,23 +207,17 @@ export const ElementCall: FC<ElementCallProps> = ({
|
||||
};
|
||||
}, [controlledAudioDevices, callIntent]);
|
||||
|
||||
const room = client.getRoom(roomId);
|
||||
const rtcSession = useMemo(
|
||||
() => (room === null ? null : client.matrixRTC.getRoomSession(room)),
|
||||
const backend = useMemo(
|
||||
() => createCallMatrixBackend(createComponentLocalJsClient(client), room),
|
||||
[client, room],
|
||||
);
|
||||
|
||||
if (rtcSession === null)
|
||||
logger.error(
|
||||
`Element Call was asked to call in ${roomId}, which its host's client does not know about`,
|
||||
);
|
||||
|
||||
// Everything the call needs is in hand once these exist, and the first
|
||||
// render with them is where the call itself appears: the moment the host
|
||||
// is told that Element Call has loaded, as the widget tells its client once
|
||||
// its own initialisation is over. Once per mount, however often the pieces
|
||||
// are later swapped out.
|
||||
const ready = container !== null && rtcSession !== null && vm !== null;
|
||||
const ready = container !== null && vm !== null;
|
||||
const announcedLoaded = useRef(false);
|
||||
useEffect(() => {
|
||||
if (!ready || announcedLoaded.current) return;
|
||||
@@ -250,14 +247,17 @@ export const ElementCall: FC<ElementCallProps> = ({
|
||||
>
|
||||
<Decoration>
|
||||
<TooltipProvider>
|
||||
{/* The host's own client: what reads it through
|
||||
the context (avatars, the encryption system,
|
||||
rageshakes, the disconnected banner) uses only its
|
||||
stable methods. */}
|
||||
<ClientProvider client={client}>
|
||||
<MediaDevicesContext value={vm.mediaDevices}>
|
||||
<BackgroundEffectsProvider
|
||||
effects={vm.backgroundEffects}
|
||||
>
|
||||
<CallView
|
||||
client={client}
|
||||
rtcSession={rtcSession}
|
||||
backend={backend}
|
||||
isPasswordlessUser={false}
|
||||
confineToRoom={params.confineToRoom}
|
||||
preload={params.preload}
|
||||
|
||||
@@ -42,7 +42,6 @@
|
||||
"peerDependencies": {
|
||||
"@vector-im/compound-design-tokens": "^11.0.0",
|
||||
"@vector-im/compound-web": "^10.3.1",
|
||||
"matrix-js-sdk": "*",
|
||||
"react": "^19",
|
||||
"react-dom": "^19"
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ networks:
|
||||
|
||||
services:
|
||||
auth-service:
|
||||
image: ghcr.io/element-hq/lk-jwt-service:0.8.0
|
||||
image: ghcr.io/element-hq/lk-jwt-service:0.10.0
|
||||
pull_policy: always
|
||||
hostname: auth-server
|
||||
environment:
|
||||
@@ -33,7 +33,7 @@ services:
|
||||
- ecbackend
|
||||
|
||||
auth-service-1:
|
||||
image: ghcr.io/element-hq/lk-jwt-service:0.8.0
|
||||
image: ghcr.io/element-hq/lk-jwt-service:0.10.0
|
||||
pull_policy: always
|
||||
hostname: auth-server-1
|
||||
environment:
|
||||
@@ -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,7 +19,12 @@ 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:a79801206c628a912d57fa6f355d5c5ab9c6c40c2d1b6208d4192678fb6e80c7
|
||||
image: ghcr.io/element-hq/element-web:develop@sha256:58b673f867f78fe83c08f2b688b254e34625ebfcebdc5eff84bfdf407445e88e
|
||||
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:a79801206c628a912d57fa6f355d5c5ab9c6c40c2d1b6208d4192678fb6e80c7
|
||||
image: ghcr.io/element-hq/element-web:develop@sha256:58b673f867f78fe83c08f2b688b254e34625ebfcebdc5eff84bfdf407445e88e
|
||||
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.
|
||||
# Built by the Playwright run (see build.setup.ts).
|
||||
- ./embedded/web/dist:/app/widgets/element-call:ro,Z
|
||||
|
||||
+5
-1
@@ -14,7 +14,11 @@ This folder contains documentation for setup, usage, and development of Element
|
||||
|
||||
Entry point: [AGENTS.md](../AGENTS.md).
|
||||
|
||||
- [Agent workflow](./agents/workflow.md)
|
||||
- [Architecture](./agents/architecture.md)
|
||||
- [Code style](./agents/code-style.md)
|
||||
- [Testing](./agents/testing.md)
|
||||
|
||||
Opt-in skills in [`.claude/skills/`](../.claude/skills/):
|
||||
|
||||
- `/handoff <task>` — get the first implementation back for a direction check
|
||||
before lint, the full suite and polish.
|
||||
|
||||
+55
-21
@@ -4,12 +4,24 @@
|
||||
|
||||
- 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
|
||||
field optional, each defaulting to standalone behaviour, so `{}` works. A
|
||||
value with no default is never an option; a test seam is never an option
|
||||
either — mock the dependency it comes from. See `createCallViewModel$`, with
|
||||
`CallViewModelProps` and `CallViewModelOptions`.
|
||||
- `foo$` is an observable. `Behavior<T>`, an observable with a current value, is
|
||||
the default for anything a view reads.
|
||||
|
||||
@@ -36,15 +48,15 @@ Element Call can be mounted several times inside a host's React tree, so it owns
|
||||
neither window, URL, document nor router. Each seam defaults to the old standalone
|
||||
and widget behaviour.
|
||||
|
||||
| Never | Use |
|
||||
| --------------------------------------------- | ------------------------------------------------------------- |
|
||||
| the `widget` global | `useHostBridge()` — `src/HostBridge.ts` |
|
||||
| `getUrlParams()`, `window.location` | `useUrlParams()` |
|
||||
| `useNavigate("/")`, `<Link to="/">` | `useLeaveToHome()`, `LeaveToHomeLink` |
|
||||
| `document.body` | `useRootElement()` |
|
||||
| `window.innerWidth/Height`, `useMediaQuery` | `useRootSizeMatches()` in views, `windowSize$` in view models |
|
||||
| global `i18next` | the instance in `src/utils/i18n.ts` |
|
||||
| config or analytics reading their environment | `Config.initWith()`, `PosthogAnalytics.configure()` |
|
||||
| Never | Use |
|
||||
| --------------------------------------------- | ----------------------------------------------------------- |
|
||||
| the `widget` global | `useHostBridge()` — `src/HostBridge.ts` |
|
||||
| `getUrlParams()`, `window.location` | `useUrlParams()` |
|
||||
| `useNavigate("/")`, `<Link to="/">` | `useLeaveToHome()`, `LeaveToHomeLink` |
|
||||
| `document.body` | `useRootElement()` |
|
||||
| `window.innerWidth/Height`, `useMediaQuery` | `useRootSizeMatches()` in views, `viewSize$` in view models |
|
||||
| global `i18next` | the instance in `src/utils/i18n.ts` |
|
||||
| config or analytics reading their environment | `Config.initWith()`, `PosthogAnalytics.configure()` |
|
||||
|
||||
- View models take values as options, never `getUrlParams()`
|
||||
(`callViewModelOptionsFromParams`, `CallViewModelOptions.hostBridge`).
|
||||
@@ -66,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.
|
||||
@@ -75,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
|
||||
|
||||
@@ -34,6 +34,10 @@ translations. The browser is Playwright's, so a fresh clone needs
|
||||
|
||||
## End-to-end
|
||||
|
||||
The Element Web instance `HOST1` opens the app the dev server serves. The instance
|
||||
`HOST2` (the other site) opens the embedded package as a host ships it. This package
|
||||
is built by the `build-embedded` setup project and mounted in `docker-compose-playwright.yml`.
|
||||
|
||||
- `playwright/*.spec.ts` — standalone, on Chromium and Firefox.
|
||||
- `playwright/widget/` — widget mode, where cross-context bugs surface.
|
||||
- `playwright/component/` — the component in a host page, via the harness on port
|
||||
@@ -48,10 +52,13 @@ Test what a user observes: the peer sees the change, it survives a reconnect, it
|
||||
right after a reload. Reuse `playwright/spa-helpers.ts`,
|
||||
`playwright/widget/test-helpers.ts`, `playwright/fixtures/`.
|
||||
|
||||
To mark new release announcements as viewed, add them in `backend/ew.test*.config.json`.
|
||||
|
||||
```sh
|
||||
pnpm test # unit + storybook
|
||||
pnpm backend # Synapse + LiveKit, required for e2e
|
||||
pnpm test:playwright # or :open
|
||||
pnpm dev:component # component harness, port 3001
|
||||
pnpm dev:sdk # SDK harness, port 3002
|
||||
pnpm dev:widget-rtc-sdk # widget RTC SDK example widget, port 3003
|
||||
```
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
# Agent workflow
|
||||
|
||||
## Scratch files live in `agent-workspace/`
|
||||
|
||||
Git-ignored. One kebab-case subfolder per task, matching the branch topic:
|
||||
`agent-workspace/<slug>/`.
|
||||
|
||||
| File | Purpose |
|
||||
| --------------------------- | -------------------------------------------------------------------------------- |
|
||||
| `plan.md` | The concrete approach — files, symbols, edit order — once direction is confirmed |
|
||||
| `commit-msg.txt` | `git commit -F agent-workspace/<slug>/commit-msg.txt` |
|
||||
| `pr-body.md` | `gh pr create --body-file agent-workspace/<slug>/pr-body.md` |
|
||||
| `implementation-summary.md` | What was built, decisions, trade-offs |
|
||||
| `NN-prompt.md` | Raw prompt text, numbered, when worth keeping |
|
||||
|
||||
- Nothing here is durable. The folder is ignored, so anything worth keeping is
|
||||
promoted into the PR body, a doc, or a feature spec 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.
|
||||
- Commit subjects are plain imperative English. No conventional-commits prefixes.
|
||||
- A `plan.md` and a feature spec sit at different altitudes; neither replaces the
|
||||
other. A spec in `FEATURES_SPEC/` is durable and deliberately abstract —
|
||||
behaviour, decisions, acceptance criteria — so the feature can be rebuilt against
|
||||
a `main` nobody has seen yet. A plan is one slice of it landing on today's
|
||||
`main`: the paths, symbols and edit order the spec's decisions and criteria must
|
||||
not name. `FEATURES_SPEC/AGENTS.md` wins wherever the two genuinely overlap.
|
||||
|
||||
## Hand off before the quality pass
|
||||
|
||||
- Implement the change, run the narrowest check that rules out an obviously broken
|
||||
handoff, then stop and ask whether the direction is right.
|
||||
- Full `pnpm lint`, the whole suite, coverage and benchmarks come after the
|
||||
direction is confirmed.
|
||||
- Wider refactors, extra tests and documentation polish are follow-up work, not
|
||||
part of the first handoff.
|
||||
- If a check is needed before feedback, keep it to the touched code and say why.
|
||||
|
||||
## Commit and PR readiness
|
||||
|
||||
- Commit once the user confirms direction, or asks for one. Not before. Where the
|
||||
setup has no git identity, a sandbox included, write the message to
|
||||
`commit-msg.txt` and hand it over instead.
|
||||
- Ready means every gate in [AGENTS.md](../../AGENTS.md#gates) is green and the
|
||||
change is covered at the layers [testing.md](./testing.md) asks for. Read the diff
|
||||
against [code-style.md](./code-style.md) first.
|
||||
- Re-run the whole checklist after any fix. Only on green, either way.
|
||||
- Once a human has started reviewing, fix forward — never force-push a
|
||||
regeneration over a review in progress.
|
||||
@@ -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",
|
||||
],
|
||||
|
||||
+6
-2
@@ -3,6 +3,7 @@
|
||||
"user_menu": "User menu"
|
||||
},
|
||||
"action": {
|
||||
"add_background_image": "Add image",
|
||||
"close": "Close",
|
||||
"copy_link": "Copy link",
|
||||
"edit": "Edit",
|
||||
@@ -26,6 +27,7 @@
|
||||
"blur": "Blur",
|
||||
"none": "None",
|
||||
"numbered": "Background {{n}}",
|
||||
"slow": "Background effects run slowly on this platform, which may cause your video to stutter.",
|
||||
"unavailable": "Background effects are not supported on this platform."
|
||||
},
|
||||
"call_ended_view": {
|
||||
@@ -97,6 +99,10 @@
|
||||
},
|
||||
"disconnected_banner": "Connectivity to the server has been lost.",
|
||||
"error": {
|
||||
"background_animated": "Animated images cannot be used as a background",
|
||||
"background_not_an_image": "That file is not a supported image",
|
||||
"background_not_kept": "That background could not be saved",
|
||||
"background_undecodable": "That image could not be opened",
|
||||
"call_is_not_supported": "Call is not supported",
|
||||
"call_not_found": "Call not found",
|
||||
"call_not_found_description": "<0>That link doesn't appear to belong to any existing call. Check that you have the right link, or <2>create a new one</2>.</0>",
|
||||
@@ -112,8 +118,6 @@
|
||||
"livekit_connection_error": "Failed to connect to Livekit server",
|
||||
"livekit_connection_error_description": "An error occurred while connecting to the Livekit server (<1>Reason:</1> <2>{{ reason }}</2>).",
|
||||
"matrix_rtc_transport_missing": "The server is not configured to work with {{brand}} and no other call participant provides a usable transport. Please contact your server admin (Domain: {{domain}}, Error Code: {{ errorCode }}).",
|
||||
"membership_manager": "Membership Manager Error",
|
||||
"membership_manager_description": "The Membership Manager had to shut down. This is caused by many consecutive failed network requests.",
|
||||
"no_matrix_2_authorization_service": "The authorization service for your media server (SFU) is out of date.",
|
||||
"open_elsewhere": "Opened in another tab",
|
||||
"open_elsewhere_description": "{{brand}} has been opened in another tab. If that doesn't sound right, try reloading the page.",
|
||||
|
||||
+18
-14
@@ -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,12 +94,13 @@
|
||||
"@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",
|
||||
"eslint-plugin-element-call": "link:eslint",
|
||||
"eslint-plugin-storybook": "^10.3.6",
|
||||
"fake-indexeddb": "^6.2.5",
|
||||
"fetch-mock": "11.1.5",
|
||||
"i18next": "^26.0.0",
|
||||
"i18next-browser-languagedetector": "^8.0.0",
|
||||
@@ -106,14 +110,14 @@
|
||||
"livekit-client": "^2.18.1",
|
||||
"lodash-es": "^4.17.21",
|
||||
"loglevel": "^1.9.1",
|
||||
"matrix-js-sdk": "github:matrix-org/matrix-js-sdk#a9ef09fbf2f1644c8663d0aeaf6a921cd16e7b01",
|
||||
"matrix-js-sdk": "github:matrix-org/matrix-js-sdk#6c8b1b418189919bc69fd9df5e57354e7b3c39cb",
|
||||
"matrix-widget-api": "^1.18.0",
|
||||
"node-stdlib-browser": "^1.3.1",
|
||||
"normalize.css": "^8.0.1",
|
||||
"oxfmt": "^0.66.0",
|
||||
"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",
|
||||
|
||||
+67
-22
@@ -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"
|
||||
@@ -26,6 +27,19 @@ process.env.NODE_EXTRA_CA_CERTS = join(
|
||||
"backend/dev_tls_local-ca.crt",
|
||||
);
|
||||
|
||||
const desktopChrome = {
|
||||
...devices["Desktop Chrome"],
|
||||
permissions: ["clipboard-write", "clipboard-read", "microphone", "camera"],
|
||||
ignoreHTTPSErrors: true,
|
||||
launchOptions: {
|
||||
args: [
|
||||
"--use-fake-ui-for-media-stream",
|
||||
"--use-fake-device-for-media-stream",
|
||||
"--mute-audio",
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* See https://playwright.dev/docs/test-configuration.
|
||||
*/
|
||||
@@ -43,11 +57,11 @@ export default defineConfig({
|
||||
* Reporter to use. See https://playwright.dev/docs/test-reporters
|
||||
*
|
||||
* On CI, `list` prints a line per test as it finishes, which keeps the job
|
||||
* log moving; `github` annotates failures on the PR; `html` is uploaded as
|
||||
* an artifact and must never try to open a browser there.
|
||||
* log moving; `github` annotates failures on the PR; the `blob` format is
|
||||
* uploaded by sharded CI runs and combined into a HTML report by the workflow.
|
||||
*/
|
||||
reporter: process.env.CI
|
||||
? [["list"], ["github"], ["html", { open: "never" }]]
|
||||
? [["list"], ["github"], ["blob"]]
|
||||
: [["list"], ["html"]],
|
||||
/* Stop a broken run early on CI instead of waiting out every retry. */
|
||||
maxFailures: process.env.CI ? 5 : undefined,
|
||||
@@ -63,30 +77,43 @@ export default defineConfig({
|
||||
},
|
||||
/* Configure projects for major browsers */
|
||||
projects: [
|
||||
{
|
||||
// Builds the embedded package into the directory the other site's
|
||||
// Element Web container serves it from (see docker-compose-playwright.yml).
|
||||
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/**",
|
||||
use: {
|
||||
...devices["Desktop Chrome"],
|
||||
permissions: [
|
||||
"clipboard-write",
|
||||
"clipboard-read",
|
||||
"microphone",
|
||||
"camera",
|
||||
],
|
||||
ignoreHTTPSErrors: true,
|
||||
launchOptions: {
|
||||
args: [
|
||||
"--use-fake-ui-for-media-stream",
|
||||
"--use-fake-device-for-media-stream",
|
||||
"--mute-audio",
|
||||
],
|
||||
},
|
||||
},
|
||||
testIgnore: ["**/mobile/**", "**/widget/**"],
|
||||
use: desktopChrome,
|
||||
},
|
||||
{
|
||||
// Element Call as a widget in Element Web, on Chromium. This uses its
|
||||
// own project so that it can be sharded on CI.
|
||||
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",
|
||||
testIgnore: "**/mobile/**",
|
||||
dependencies: ["build-embedded"],
|
||||
testIgnore: ["**/mobile/**", "**/widget/widget-rtc-sdk.spec.ts"],
|
||||
use: {
|
||||
...devices["Desktop Firefox"],
|
||||
ignoreHTTPSErrors: true,
|
||||
@@ -171,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,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -5,9 +5,15 @@ 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 Locator, type Page } from "@playwright/test";
|
||||
import { expect, test, type Browser, type Page } from "@playwright/test";
|
||||
|
||||
import { SpaHelpers } from "./spa-helpers.ts";
|
||||
import {
|
||||
averageColour,
|
||||
cameraColour,
|
||||
type Colour,
|
||||
distance,
|
||||
} from "./utils/colour.ts";
|
||||
|
||||
// Background effects need WebGL2, and headless Firefox on a CI runner has none,
|
||||
// so it rightly offers none of them.
|
||||
@@ -16,15 +22,13 @@ test.skip(
|
||||
"Background effects need WebGL2, which headless Firefox on CI does not have",
|
||||
);
|
||||
|
||||
type Colour = [number, number, number];
|
||||
|
||||
test.describe("background effects", () => {
|
||||
test("pre-join preview shows the chosen effect", async ({ page }) => {
|
||||
test.slow();
|
||||
await page.goto("/");
|
||||
await SpaHelpers.createCall(page, "Effect user", "Background effects");
|
||||
const preview = page.locator("video").first();
|
||||
const camera = await averageColour(preview);
|
||||
const camera = await cameraColour(preview);
|
||||
|
||||
await page.getByRole("button", { name: "Camera", exact: true }).click();
|
||||
const tile = page
|
||||
@@ -102,25 +106,847 @@ async function drawsPerSecond(page: Page): Promise<number> {
|
||||
});
|
||||
}
|
||||
|
||||
/** The mean colour of a video's current frame or an image, drawn small. */
|
||||
async function averageColour(element: Locator): Promise<Colour> {
|
||||
return element.evaluate(
|
||||
async (source: HTMLVideoElement | HTMLImageElement) => {
|
||||
if (source instanceof HTMLImageElement) await source.decode();
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = canvas.height = 32;
|
||||
const context = canvas.getContext("2d")!;
|
||||
context.drawImage(source, 0, 0, 32, 32);
|
||||
const { data } = context.getImageData(0, 0, 32, 32);
|
||||
const sum = [0, 0, 0];
|
||||
for (let i = 0; i < data.length; i += 4)
|
||||
for (let c = 0; c < 3; c++) sum[c] += data[i + c];
|
||||
const pixels = data.length / 4;
|
||||
return sum.map((s) => s / pixels) as Colour;
|
||||
},
|
||||
);
|
||||
test.describe("the camera menu's preview", () => {
|
||||
test("shows the camera with the effect in force", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
await page.goto("/");
|
||||
await SpaHelpers.createCall(page, "Preview user", "Preview in the menu");
|
||||
const camera = await cameraColour(page.locator("video").first());
|
||||
|
||||
await page.getByRole("button", { name: "Camera", exact: true }).click();
|
||||
const preview = page.getByRole("menu").locator("video");
|
||||
await expect(preview).toBeVisible();
|
||||
await expect
|
||||
.poll(async () => distance(await averageColour(preview), camera), {
|
||||
timeout: 20_000,
|
||||
})
|
||||
.toBeLessThan(30);
|
||||
|
||||
const tile = page.getByRole("menuitemradio", { name: "Background 1" });
|
||||
await tile.click();
|
||||
const picture = await averageColour(tile.locator("img"));
|
||||
await expect
|
||||
.poll(async () => distance(await averageColour(preview), picture), {
|
||||
timeout: 60_000,
|
||||
})
|
||||
.toBeLessThan(distance(camera, picture) / 2);
|
||||
});
|
||||
|
||||
test("shows the call's own camera once joined", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
await page.goto("/");
|
||||
await SpaHelpers.createCall(
|
||||
page,
|
||||
"Call preview user",
|
||||
"Preview in the call's menu",
|
||||
true,
|
||||
);
|
||||
await expect(page.getByTestId("incall_videomute")).toBeEnabled({
|
||||
timeout: 10_000,
|
||||
});
|
||||
const camera = await cameraColour(page.locator("video").first());
|
||||
|
||||
await page.getByRole("button", { name: "Camera", exact: true }).click();
|
||||
const preview = page.getByRole("menu").locator("video");
|
||||
await expect(preview).toBeVisible();
|
||||
await expect
|
||||
.poll(async () => distance(await averageColour(preview), camera), {
|
||||
timeout: 20_000,
|
||||
})
|
||||
.toBeLessThan(30);
|
||||
|
||||
const tile = page.getByRole("menuitemradio", { name: "Background 1" });
|
||||
await tile.click();
|
||||
const picture = await averageColour(tile.locator("img"));
|
||||
await expect
|
||||
.poll(async () => distance(await averageColour(preview), picture), {
|
||||
timeout: 60_000,
|
||||
})
|
||||
.toBeLessThan(distance(camera, picture) / 2);
|
||||
});
|
||||
});
|
||||
|
||||
test.describe("background effects section", () => {
|
||||
test("section stays within the call area at every size", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
await page.goto("/");
|
||||
await SpaHelpers.createCall(page, "Sizes user", "Background effect sizes");
|
||||
|
||||
for (const size of [
|
||||
{ width: 1280, height: 800 },
|
||||
{ width: 800, height: 600 },
|
||||
{ width: 600, height: 420 },
|
||||
{ width: 480, height: 360 },
|
||||
{ width: 360, height: 640 },
|
||||
]) {
|
||||
await page.setViewportSize(size);
|
||||
await page.getByRole("button", { name: "Camera", exact: true }).click();
|
||||
const menu = page.getByRole("menu");
|
||||
await expect(menu).toBeVisible();
|
||||
|
||||
const box = (await menu.boundingBox())!;
|
||||
const where = `at ${size.width}x${size.height}`;
|
||||
expect(box.x, where).toBeGreaterThanOrEqual(0);
|
||||
expect(box.y, where).toBeGreaterThanOrEqual(0);
|
||||
expect(box.x + box.width, where).toBeLessThanOrEqual(size.width);
|
||||
expect(box.y + box.height, where).toBeLessThanOrEqual(size.height);
|
||||
|
||||
const last = page
|
||||
.getByRole("group", { name: "Background effects" })
|
||||
.getByRole("menuitemradio")
|
||||
.last();
|
||||
await last.scrollIntoViewIfNeeded();
|
||||
await expect(last, where).toBeInViewport({ ratio: 1 });
|
||||
await last.click();
|
||||
await expect(last, where).toHaveAttribute("aria-checked", "true");
|
||||
|
||||
// Back to no effect for the next size, and close.
|
||||
await page
|
||||
.getByRole("group", { name: "Background effects" })
|
||||
.getByRole("menuitemradio", { name: "None" })
|
||||
.click();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(menu).toBeHidden();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test.describe("a pipeline that fails to build", () => {
|
||||
test("offers no effects for the session, and keeps the choice", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
await page.goto("/");
|
||||
await SpaHelpers.createCall(page, "Failing user", "Pipeline fails");
|
||||
const preview = page.locator("video").first();
|
||||
const camera = await cameraColour(preview);
|
||||
await page.route("**/*.tflite*", async (route) => route.abort());
|
||||
|
||||
await page.getByRole("button", { name: "Camera", exact: true }).click();
|
||||
const tile = page.getByRole("menuitemradio", { name: "Background 1" });
|
||||
await tile.click();
|
||||
await expect(
|
||||
page.getByText("Background effects are not supported on this platform."),
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
await expect(tile).toBeDisabled();
|
||||
await page.keyboard.press("Escape");
|
||||
// The camera and microphone carry on without it.
|
||||
expect(distance(await cameraColour(preview), camera)).toBeLessThan(30);
|
||||
await expect(page.getByTestId("incall_mute")).toHaveAttribute(
|
||||
"aria-checked",
|
||||
"true",
|
||||
);
|
||||
|
||||
await page.unroute("**/*.tflite*");
|
||||
await page.reload();
|
||||
await expect(page.getByTestId("lobby_joinCall")).toBeVisible();
|
||||
await page.getByRole("button", { name: "Camera", exact: true }).click();
|
||||
await expect(tile).toHaveAttribute("aria-checked", "true");
|
||||
const picture = await averageColour(tile.locator("img"));
|
||||
await expect
|
||||
.poll(async () => distance(await averageColour(preview), picture), {
|
||||
timeout: 60_000,
|
||||
})
|
||||
.toBeLessThan(distance(camera, picture) / 2);
|
||||
});
|
||||
});
|
||||
|
||||
test.describe("the chosen effect", () => {
|
||||
test("chosen effect survives leaving and rejoining", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
await page.goto("/");
|
||||
await SpaHelpers.createCall(page, "Returning user", "Effect remembered");
|
||||
const { camera, picture } = await chooseAndWear(page, "Background 1");
|
||||
await page.getByTestId("lobby_joinCall").click();
|
||||
await page.getByTestId("incall_leave").click();
|
||||
await expect(page.getByRole("heading")).toContainText(
|
||||
"your call has ended",
|
||||
);
|
||||
|
||||
await page.goto("/");
|
||||
await page.getByTestId("home_callName").fill("Effect remembered again");
|
||||
await page.getByTestId("home_go").click();
|
||||
await expect(page.getByTestId("lobby_joinCall")).toBeVisible();
|
||||
await page.getByRole("button", { name: "Camera", exact: true }).click();
|
||||
const tile = page
|
||||
.getByRole("group", { name: "Background effects" })
|
||||
.getByRole("menuitemradio", { name: "Background 1" });
|
||||
await expect(tile).toHaveAttribute("aria-checked", "true");
|
||||
const preview = page.locator("video").first();
|
||||
await expect
|
||||
.poll(async () => distance(await averageColour(preview), picture), {
|
||||
timeout: 60_000,
|
||||
})
|
||||
.toBeLessThan(distance(camera, picture) / 2);
|
||||
});
|
||||
|
||||
test("second session still shows the existing error", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
await page.goto("/");
|
||||
await SpaHelpers.createCall(page, "Two tabs", "Effect in two tabs");
|
||||
await chooseAndWear(page, "Background 1");
|
||||
|
||||
const second = await page.context().newPage();
|
||||
await second.goto("/");
|
||||
await expect(
|
||||
page.getByRole("heading", { name: "Opened in another tab" }),
|
||||
).toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
/** Chooses an effect in the lobby, and waits until the preview wears it. */
|
||||
async function chooseAndWear(
|
||||
page: Page,
|
||||
name: string,
|
||||
): Promise<{ camera: Colour; picture: Colour }> {
|
||||
const preview = page.locator("video").first();
|
||||
const camera = await cameraColour(preview);
|
||||
await page.getByRole("button", { name: "Camera", exact: true }).click();
|
||||
const tile = page.getByRole("menuitemradio", { name });
|
||||
await tile.click();
|
||||
const picture = await averageColour(tile.locator("img"));
|
||||
await expect
|
||||
.poll(async () => distance(await averageColour(preview), picture), {
|
||||
timeout: 60_000,
|
||||
})
|
||||
.toBeLessThan(distance(camera, picture) / 2);
|
||||
await page.keyboard.press("Escape");
|
||||
return { camera, picture };
|
||||
}
|
||||
|
||||
function distance(a: Colour, b: Colour): number {
|
||||
return Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
|
||||
test.describe("a background of one's own", () => {
|
||||
test("adds an image from the device", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
await page.goto("/");
|
||||
await SpaHelpers.createCall(page, "Adding user", "Own background");
|
||||
const preview = page.locator("video").first();
|
||||
const camera = await cameraColour(preview);
|
||||
const red = await redImage(page);
|
||||
|
||||
await addImage(page, red);
|
||||
const mine = page
|
||||
.getByRole("group", { name: "Background effects" })
|
||||
.getByRole("menuitemradio", { name: "Background 3" });
|
||||
await expect(mine).toBeVisible();
|
||||
await expect(mine).toHaveAttribute("aria-checked", "false");
|
||||
|
||||
await mine.click();
|
||||
await expect
|
||||
.poll(async () => distance(await averageColour(preview), RED), {
|
||||
timeout: 60_000,
|
||||
})
|
||||
.toBeLessThan(distance(camera, RED) / 2);
|
||||
});
|
||||
|
||||
test("adding an image makes no upload", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
await page.goto("/");
|
||||
await SpaHelpers.createCall(page, "Private user", "Own background kept");
|
||||
const preview = page.locator("video").first();
|
||||
const camera = await cameraColour(preview);
|
||||
const red = await redImage(page);
|
||||
const sent: { request: string; body: Buffer | null }[] = [];
|
||||
page.on("request", (request) =>
|
||||
sent.push({
|
||||
request: `${request.method()} ${request.url()}`,
|
||||
body: request.postDataBuffer(),
|
||||
}),
|
||||
);
|
||||
|
||||
await addImage(page, red);
|
||||
await page
|
||||
.getByRole("group", { name: "Background effects" })
|
||||
.getByRole("menuitemradio", { name: "Background 3" })
|
||||
.click();
|
||||
// Kept, chosen and in force: anything that would send it has had its turn.
|
||||
await expect
|
||||
.poll(async () => distance(await averageColour(preview), RED), {
|
||||
timeout: 60_000,
|
||||
})
|
||||
.toBeLessThan(distance(camera, RED) / 2);
|
||||
// The file as given, and the copy kept, which is encoded anew.
|
||||
const samples = [red, await keptBytes(page)].map((bytes) =>
|
||||
bytes.subarray(bytes.length - 64),
|
||||
);
|
||||
const carriesIt = sent.filter(
|
||||
({ request, body }) =>
|
||||
request.includes("/_matrix/media/") ||
|
||||
samples.some((sample) => body?.includes(sample)),
|
||||
);
|
||||
expect(carriesIt.map(({ request }) => request)).toEqual([]);
|
||||
});
|
||||
|
||||
test("added image survives rejoining and is gone after storage is cleared", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
await page.goto("/");
|
||||
await SpaHelpers.createCall(page, "Keeping user", "Own background again");
|
||||
const preview = page.locator("video").first();
|
||||
const camera = await cameraColour(preview);
|
||||
const red = await redImage(page);
|
||||
await addImage(page, red);
|
||||
const mine = page
|
||||
.getByRole("group", { name: "Background effects" })
|
||||
.getByRole("menuitemradio", { name: "Background 3" });
|
||||
await mine.click();
|
||||
await page.keyboard.press("Escape");
|
||||
|
||||
await page.reload();
|
||||
await expect(page.getByTestId("lobby_joinCall")).toBeVisible();
|
||||
await page.getByRole("button", { name: "Camera", exact: true }).click();
|
||||
await expect(mine).toHaveAttribute("aria-checked", "true");
|
||||
await page.keyboard.press("Escape");
|
||||
await expect
|
||||
.poll(async () => distance(await averageColour(preview), RED), {
|
||||
timeout: 60_000,
|
||||
})
|
||||
.toBeLessThan(distance(camera, RED) / 2);
|
||||
|
||||
await page.evaluate(
|
||||
async () =>
|
||||
new Promise<void>((resolve, reject) => {
|
||||
const request = indexedDB.deleteDatabase(
|
||||
"element-call-background-images",
|
||||
);
|
||||
request.onsuccess = (): void => resolve();
|
||||
request.onerror = (): void => reject(request.error);
|
||||
request.onblocked = (): void => resolve();
|
||||
}),
|
||||
);
|
||||
await page.reload();
|
||||
await expect(page.getByTestId("lobby_joinCall")).toBeVisible();
|
||||
await page.getByRole("button", { name: "Camera", exact: true }).click();
|
||||
await expect(
|
||||
page.getByRole("group", { name: "Background effects" }),
|
||||
).toBeVisible();
|
||||
await expect(mine).toHaveCount(0);
|
||||
await page.keyboard.press("Escape");
|
||||
|
||||
await addImage(page, red);
|
||||
await expect(mine).toBeVisible();
|
||||
});
|
||||
|
||||
test("a removed image stays removed", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
await page.goto("/");
|
||||
await SpaHelpers.createCall(
|
||||
page,
|
||||
"Removing user",
|
||||
"Own background removed",
|
||||
);
|
||||
await addImage(page, await redImage(page));
|
||||
const mine = page
|
||||
.getByRole("group", { name: "Background effects" })
|
||||
.getByRole("menuitemradio", { name: "Background 3" });
|
||||
await expect(mine).toHaveAttribute("aria-keyshortcuts", "Delete");
|
||||
await mine.focus();
|
||||
await page.keyboard.press("Delete");
|
||||
await expect(mine).toHaveCount(0);
|
||||
|
||||
await page.reload();
|
||||
await expect(page.getByTestId("lobby_joinCall")).toBeVisible();
|
||||
await page.getByRole("button", { name: "Camera", exact: true }).click();
|
||||
await expect(
|
||||
page.getByRole("group", { name: "Background effects" }),
|
||||
).toBeVisible();
|
||||
await expect(mine).toHaveCount(0);
|
||||
expect(await keptImages(page)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
test.describe("what can be added", () => {
|
||||
test("refuses an animated image", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
await page.goto("/");
|
||||
await SpaHelpers.createCall(page, "Refused user", "Animated refused");
|
||||
await addImage(page, ANIMATED_GIF, {
|
||||
name: "moving.gif",
|
||||
type: "image/gif",
|
||||
});
|
||||
|
||||
await expect(
|
||||
page.getByText("Animated images cannot be used as a background"),
|
||||
).toBeVisible();
|
||||
const section = page.getByRole("group", { name: "Background effects" });
|
||||
await expect(
|
||||
section.getByRole("menuitemradio", { name: "Background 3" }),
|
||||
).toHaveCount(0);
|
||||
await expect(
|
||||
section.getByRole("menuitemradio", { name: "None" }),
|
||||
).toHaveAttribute("aria-checked", "true");
|
||||
expect(await keptImages(page)).toEqual([]);
|
||||
});
|
||||
|
||||
test("reduces an oversized image", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
await page.goto("/");
|
||||
await SpaHelpers.createCall(page, "Large user", "Oversized reduced");
|
||||
await addImage(page, await pngImage(page, { width: 4000, height: 3000 }));
|
||||
|
||||
await expect(
|
||||
page
|
||||
.getByRole("group", { name: "Background effects" })
|
||||
.getByRole("menuitemradio", { name: "Background 3" }),
|
||||
).toBeVisible();
|
||||
await expect(page.getByRole("alert")).toHaveCount(0);
|
||||
const [kept] = await keptImages(page);
|
||||
expect(kept).toMatchObject({ width: 1920, height: 1440 });
|
||||
});
|
||||
|
||||
test("lays every image on an opaque ground", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
await page.goto("/");
|
||||
await SpaHelpers.createCall(page, "Logo user", "Transparent made opaque");
|
||||
await addImage(
|
||||
page,
|
||||
await pngImage(page, { width: 320, height: 180, transparent: true }),
|
||||
);
|
||||
|
||||
await expect(
|
||||
page
|
||||
.getByRole("group", { name: "Background effects" })
|
||||
.getByRole("menuitemradio", { name: "Background 3" }),
|
||||
).toBeVisible();
|
||||
const [kept] = await keptImages(page);
|
||||
expect(kept.minAlpha).toBe(255);
|
||||
});
|
||||
});
|
||||
|
||||
/** Two frames of one pixel, red then blue. */
|
||||
const ANIMATED_GIF = Buffer.from(
|
||||
"R0lGODlhAQABAPEAAP8AAAAA/wAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQACgAAACwAAAAAAQABAAACAkQBACH5BAAKAAAALAAAAAABAAEAAAICTAEAOw==",
|
||||
"base64",
|
||||
);
|
||||
|
||||
/** A red PNG of the given size; transparent leaves its right half empty. */
|
||||
async function pngImage(
|
||||
page: Page,
|
||||
size: { width: number; height: number; transparent?: boolean },
|
||||
): Promise<Buffer> {
|
||||
const dataUrl = await page.evaluate(({ width, height, transparent }) => {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
const context = canvas.getContext("2d")!;
|
||||
context.fillStyle = "rgb(255, 0, 0)";
|
||||
context.fillRect(0, 0, transparent ? width / 2 : width, height);
|
||||
return canvas.toDataURL("image/png");
|
||||
}, size);
|
||||
return Buffer.from(dataUrl.split(",")[1], "base64");
|
||||
}
|
||||
|
||||
/** The images the device keeps, as it keeps them. */
|
||||
async function keptImages(
|
||||
page: Page,
|
||||
): Promise<{ width: number; height: number; minAlpha: number }[]> {
|
||||
return page.evaluate(async () => {
|
||||
const db = await new Promise<IDBDatabase>((resolve, reject) => {
|
||||
const request = indexedDB.open("element-call-background-images");
|
||||
request.onsuccess = (): void => resolve(request.result);
|
||||
request.onerror = (): void => reject(request.error);
|
||||
});
|
||||
if (!db.objectStoreNames.contains("backgrounds")) return [];
|
||||
const kept = await new Promise<{ image: Blob }[]>((resolve, reject) => {
|
||||
const request = db
|
||||
.transaction("backgrounds")
|
||||
.objectStore("backgrounds")
|
||||
.getAll();
|
||||
request.onsuccess = (): void => resolve(request.result);
|
||||
request.onerror = (): void => reject(request.error);
|
||||
});
|
||||
db.close();
|
||||
return Promise.all(
|
||||
kept.map(async ({ image }) => {
|
||||
const bitmap = await createImageBitmap(image);
|
||||
const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
|
||||
const context = canvas.getContext("2d")!;
|
||||
context.drawImage(bitmap, 0, 0);
|
||||
const { data } = context.getImageData(
|
||||
0,
|
||||
0,
|
||||
bitmap.width,
|
||||
bitmap.height,
|
||||
);
|
||||
let minAlpha = 255;
|
||||
for (let i = 3; i < data.length; i += 4)
|
||||
minAlpha = Math.min(minAlpha, data[i]);
|
||||
return { width: bitmap.width, height: bitmap.height, minAlpha };
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/** The bytes of the one image the device keeps. */
|
||||
async function keptBytes(page: Page): Promise<Buffer> {
|
||||
const base64 = await page.evaluate(
|
||||
async () =>
|
||||
new Promise<string>((resolve, reject) => {
|
||||
const open = indexedDB.open("element-call-background-images");
|
||||
open.onerror = (): void => reject(open.error);
|
||||
open.onsuccess = (): void => {
|
||||
const all = open.result
|
||||
.transaction("backgrounds")
|
||||
.objectStore("backgrounds")
|
||||
.getAll();
|
||||
all.onerror = (): void => reject(all.error);
|
||||
all.onsuccess = (): void => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (): void =>
|
||||
resolve((reader.result as string).split(",")[1]);
|
||||
reader.readAsDataURL((all.result[0] as { image: Blob }).image);
|
||||
};
|
||||
};
|
||||
}),
|
||||
);
|
||||
return Buffer.from(base64, "base64");
|
||||
}
|
||||
|
||||
const RED: Colour = [255, 0, 0];
|
||||
|
||||
/** A solid red PNG, unlike the camera and the shipped pictures. */
|
||||
async function redImage(page: Page): Promise<Buffer> {
|
||||
const dataUrl = await page.evaluate(() => {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = 320;
|
||||
canvas.height = 180;
|
||||
const context = canvas.getContext("2d")!;
|
||||
context.fillStyle = "rgb(255, 0, 0)";
|
||||
context.fillRect(0, 0, canvas.width, canvas.height);
|
||||
return canvas.toDataURL("image/png");
|
||||
});
|
||||
return Buffer.from(dataUrl.split(",")[1], "base64");
|
||||
}
|
||||
|
||||
/** Adds an image from the camera menu's add tile, leaving the menu open. */
|
||||
async function addImage(
|
||||
page: Page,
|
||||
image: Buffer,
|
||||
{ name, type } = { name: "mine.png", type: "image/png" },
|
||||
): Promise<void> {
|
||||
if (!(await page.getByRole("menu").isVisible()))
|
||||
await page.getByRole("button", { name: "Camera", exact: true }).click();
|
||||
const chooser = page.waitForEvent("filechooser");
|
||||
await page.getByRole("menuitem", { name: "Add image" }).click();
|
||||
await (await chooser).setFiles({ name, mimeType: type, buffer: image });
|
||||
}
|
||||
|
||||
test.describe("joining with a background chosen", () => {
|
||||
test("publishes no frame of the room", async ({ browser }) => {
|
||||
// Two first builds of the pipeline, one of them held back.
|
||||
test.setTimeout(180_000);
|
||||
const hostContext = await browser.newContext();
|
||||
const host = await hostContext.newPage();
|
||||
await recordIncomingFrames(host);
|
||||
await host.goto("/");
|
||||
await SpaHelpers.createCall(host, "Host", "Join with a background", true);
|
||||
await expect(host.getByTestId("incall_videomute")).toBeEnabled({
|
||||
timeout: 10_000,
|
||||
});
|
||||
const inviteLink = await SpaHelpers.getCallInviteLink(host);
|
||||
await host.keyboard.press("Escape");
|
||||
|
||||
const guestContext = await browser.newContext();
|
||||
const guest = await guestContext.newPage();
|
||||
await guest.goto(inviteLink);
|
||||
await guest.getByTestId("joincall_displayName").fill("Guest");
|
||||
await guest.getByTestId("joincall_joincall").click();
|
||||
const preview = guest.locator("video").first();
|
||||
await expect(preview).toBeVisible();
|
||||
const camera = await cameraColour(preview);
|
||||
await guest.getByRole("button", { name: "Camera", exact: true }).click();
|
||||
const tile = guest.getByRole("menuitemradio", { name: "Background 1" });
|
||||
await tile.click();
|
||||
const picture = await averageColour(tile.locator("img"));
|
||||
await expect
|
||||
.poll(async () => distance(await averageColour(preview), picture), {
|
||||
timeout: 60_000,
|
||||
})
|
||||
.toBeLessThan(distance(camera, picture) / 2);
|
||||
// Were the pipeline built again for the call's track, it would take as
|
||||
// long as on the slower route. Routing bypasses the cache, so it waits.
|
||||
let heldBack = 0;
|
||||
await guest.route("**/*.tflite*", async (route) => {
|
||||
heldBack += 1;
|
||||
await new Promise((resolve) => setTimeout(resolve, 15_000));
|
||||
await route.continue();
|
||||
});
|
||||
await guest.keyboard.press("Escape");
|
||||
await guest.getByTestId("lobby_joinCall").click();
|
||||
|
||||
const guestTile = host
|
||||
.getByTestId("videoTile")
|
||||
.filter({ has: host.getByTestId("name_tag").getByText("Guest") });
|
||||
await expect(guestTile.locator("video")).toBeVisible({ timeout: 60_000 });
|
||||
// Visible can come before the stream is attached.
|
||||
let trackId: string | undefined;
|
||||
await expect
|
||||
.poll(async () => {
|
||||
trackId = await guestTile
|
||||
.locator("video")
|
||||
.evaluate(
|
||||
(video: HTMLVideoElement) =>
|
||||
(video.srcObject as MediaStream | null)?.getVideoTracks()[0]?.id,
|
||||
);
|
||||
return trackId;
|
||||
})
|
||||
.toBeDefined();
|
||||
await expectNoFrameOfTheRoom(host, trackId!, 0, camera, picture);
|
||||
// The join adopts the lobby's pipeline, so the model is never fetched again.
|
||||
expect(heldBack).toBe(0);
|
||||
|
||||
await hostContext.close();
|
||||
await guestContext.close();
|
||||
});
|
||||
});
|
||||
|
||||
test.describe("the first build", () => {
|
||||
test("survives the camera turned off and on while it runs", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
const failures: string[] = [];
|
||||
page.on("console", (m) => {
|
||||
if (m.text().includes("Failed to attach video processor"))
|
||||
failures.push(m.text());
|
||||
});
|
||||
await page.goto("/");
|
||||
await SpaHelpers.createCall(page, "Toggling user", "Toggle while building");
|
||||
const preview = page.locator("video").first();
|
||||
const camera = await cameraColour(preview);
|
||||
|
||||
const held = await holdBackTheModel(page);
|
||||
await page.getByRole("button", { name: "Camera", exact: true }).click();
|
||||
const tile = page.getByRole("menuitemradio", { name: "Background 1" });
|
||||
await tile.click();
|
||||
const picture = await averageColour(tile.locator("img"));
|
||||
await page.keyboard.press("Escape");
|
||||
// New preview tracks, each attached while the first is still building.
|
||||
for (let i = 0; i < 2; i++) {
|
||||
await page.getByTestId("incall_videomute").click();
|
||||
await page.getByTestId("incall_videomute").click();
|
||||
}
|
||||
|
||||
await expect
|
||||
.poll(async () => distance(await averageColour(preview), picture), {
|
||||
timeout: 60_000,
|
||||
})
|
||||
.toBeLessThan(distance(camera, picture) / 2);
|
||||
expect(failures).toEqual([]);
|
||||
expect(held()).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
test.describe("turning the camera on with a background chosen", () => {
|
||||
test("publishes no frame of the room when the camera started off", async ({
|
||||
browser,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
const { host, guest, close } = await hostAndGuest(browser);
|
||||
const camera = await cameraColour(guest.locator("video").first());
|
||||
await guest.getByTestId("incall_videomute").click();
|
||||
await guest.getByTestId("lobby_joinCall").click();
|
||||
|
||||
const picture = await chooseBackground(guest);
|
||||
const held = await holdBackTheModel(guest);
|
||||
await guest.getByTestId("incall_videomute").click();
|
||||
|
||||
const trackId = await incomingTrackId(host);
|
||||
await expectNoFrameOfTheRoom(host, trackId, 0, camera, picture);
|
||||
expect(held()).toBeGreaterThan(0);
|
||||
await close();
|
||||
});
|
||||
|
||||
test("publishes no frame of the room when the camera was turned off", async ({
|
||||
browser,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
const { host, guest, close } = await hostAndGuest(browser);
|
||||
const camera = await cameraColour(guest.locator("video").first());
|
||||
await guest.getByTestId("lobby_joinCall").click();
|
||||
const trackId = await incomingTrackId(host);
|
||||
await expect
|
||||
.poll(async () => (await framesOf(host, trackId)).length, {
|
||||
timeout: 20_000,
|
||||
})
|
||||
.toBeGreaterThan(0);
|
||||
await guest.getByTestId("incall_videomute").click();
|
||||
|
||||
const picture = await chooseBackground(guest);
|
||||
const held = await holdBackTheModel(guest);
|
||||
const before = (await framesOf(host, trackId)).length;
|
||||
await guest.getByTestId("incall_videomute").click();
|
||||
|
||||
await expectNoFrameOfTheRoom(host, trackId, before, camera, picture);
|
||||
expect(held()).toBeGreaterThan(0);
|
||||
await close();
|
||||
});
|
||||
});
|
||||
|
||||
/** A host in a call, recording what it receives, and a guest in its lobby. */
|
||||
async function hostAndGuest(browser: Browser): Promise<{
|
||||
host: Page;
|
||||
guest: Page;
|
||||
close: () => Promise<void>;
|
||||
}> {
|
||||
const hostContext = await browser.newContext();
|
||||
const host = await hostContext.newPage();
|
||||
await recordIncomingFrames(host);
|
||||
await host.goto("/");
|
||||
await SpaHelpers.createCall(host, "Host", "Camera with a background", true);
|
||||
await expect(host.getByTestId("incall_videomute")).toBeEnabled({
|
||||
timeout: 10_000,
|
||||
});
|
||||
const inviteLink = await SpaHelpers.getCallInviteLink(host);
|
||||
await host.keyboard.press("Escape");
|
||||
|
||||
const guestContext = await browser.newContext();
|
||||
const guest = await guestContext.newPage();
|
||||
await guest.goto(inviteLink);
|
||||
await guest.getByTestId("joincall_displayName").fill("Guest");
|
||||
await guest.getByTestId("joincall_joincall").click();
|
||||
await expect(guest.locator("video").first()).toBeVisible();
|
||||
return {
|
||||
host,
|
||||
guest,
|
||||
close: async (): Promise<void> => {
|
||||
await hostContext.close();
|
||||
await guestContext.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Chooses the first shipped picture in the call, and answers its colour. */
|
||||
async function chooseBackground(guest: Page): Promise<Colour> {
|
||||
// The lobby has a camera button of its own, so wait for the call's.
|
||||
await expect(guest.getByTestId("incall_leave")).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expect(guest.getByTestId("incall_videomute")).toBeEnabled({
|
||||
timeout: 10_000,
|
||||
});
|
||||
await guest.getByRole("button", { name: "Camera", exact: true }).click();
|
||||
const tile = guest.getByRole("menuitemradio", { name: "Background 1" });
|
||||
await tile.click();
|
||||
await expect(tile).toHaveAttribute("aria-checked", "true");
|
||||
const picture = await averageColour(tile.locator("img"));
|
||||
await guest.keyboard.press("Escape");
|
||||
return picture;
|
||||
}
|
||||
|
||||
/** Makes the pipeline's first build as slow as on the slower route. */
|
||||
/** Answers how often it held the model back, which a check should see. */
|
||||
async function holdBackTheModel(page: Page): Promise<() => number> {
|
||||
let held = 0;
|
||||
// Routing bypasses the cache, so it waits.
|
||||
await page.route("**/*.tflite*", async (route) => {
|
||||
held += 1;
|
||||
await new Promise((resolve) => setTimeout(resolve, 5_000));
|
||||
await route.continue();
|
||||
});
|
||||
return () => held;
|
||||
}
|
||||
|
||||
/** The id of the guest's camera track, as the host receives it. */
|
||||
async function incomingTrackId(host: Page): Promise<string> {
|
||||
const guestTile = host
|
||||
.getByTestId("videoTile")
|
||||
.filter({ has: host.getByTestId("name_tag").getByText("Guest") });
|
||||
await expect(guestTile.locator("video")).toBeVisible({ timeout: 60_000 });
|
||||
// Visible can come before the stream is attached.
|
||||
let trackId: string | undefined;
|
||||
await expect
|
||||
.poll(async () => {
|
||||
trackId = await guestTile
|
||||
.locator("video")
|
||||
.evaluate(
|
||||
(video: HTMLVideoElement) =>
|
||||
(video.srcObject as MediaStream | null)?.getVideoTracks()[0]?.id,
|
||||
);
|
||||
return trackId;
|
||||
})
|
||||
.toBeDefined();
|
||||
return trackId!;
|
||||
}
|
||||
|
||||
/** Waits for the picture to arrive, then finds no frame of the room since. */
|
||||
async function expectNoFrameOfTheRoom(
|
||||
host: Page,
|
||||
trackId: string,
|
||||
since: number,
|
||||
camera: Colour,
|
||||
picture: Colour,
|
||||
): Promise<void> {
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const frames = (await framesOf(host, trackId)).slice(since);
|
||||
// A black frame, as a track starts, is nearer the picture than the
|
||||
// camera, but shows neither.
|
||||
return frames.some(
|
||||
(f) =>
|
||||
distance(f, picture) <
|
||||
Math.min(distance(f, camera), distance(f, [0, 0, 0])),
|
||||
);
|
||||
},
|
||||
{ timeout: 60_000 },
|
||||
)
|
||||
.toBe(true);
|
||||
const frames = (await framesOf(host, trackId)).slice(since);
|
||||
expect(
|
||||
frames.filter((f) => distance(f, camera) < distance(f, picture)),
|
||||
).toEqual([]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Records the mean colour of every frame of every video track the page
|
||||
* receives, from the moment it arrives: a tile may attach it later than its
|
||||
* first frame.
|
||||
*/
|
||||
async function recordIncomingFrames(page: Page): Promise<void> {
|
||||
await page.addInitScript(() => {
|
||||
const frames: Record<string, [number, number, number][]> = {};
|
||||
(window as unknown as { receivedFrames: typeof frames }).receivedFrames =
|
||||
frames;
|
||||
const record = (track: MediaStreamTrack): void => {
|
||||
if (track.kind !== "video" || frames[track.id]) return;
|
||||
const seen: [number, number, number][] = (frames[track.id] = []);
|
||||
const video = document.createElement("video");
|
||||
video.muted = true;
|
||||
video.srcObject = new MediaStream([track]);
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = canvas.height = 16;
|
||||
const context = canvas.getContext("2d", { willReadFrequently: true })!;
|
||||
const step = (): void => {
|
||||
context.drawImage(video, 0, 0, 16, 16);
|
||||
const { data } = context.getImageData(0, 0, 16, 16);
|
||||
const sum = [0, 0, 0];
|
||||
for (let i = 0; i < data.length; i += 4)
|
||||
for (let c = 0; c < 3; c++) sum[c] += data[i + c];
|
||||
seen.push(sum.map((v) => v / (data.length / 4)) as Colour);
|
||||
video.requestVideoFrameCallback(step);
|
||||
};
|
||||
video.requestVideoFrameCallback(step);
|
||||
void video.play();
|
||||
};
|
||||
const Connection = window.RTCPeerConnection;
|
||||
window.RTCPeerConnection = class extends Connection {
|
||||
public constructor(...args: ConstructorParameters<typeof Connection>) {
|
||||
super(...args);
|
||||
this.addEventListener("track", (e) => record(e.track));
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function framesOf(page: Page, trackId: string): Promise<Colour[]> {
|
||||
return page.evaluate(
|
||||
(id) =>
|
||||
(
|
||||
window as unknown as {
|
||||
receivedFrames: Record<string, [number, number, number][]>;
|
||||
}
|
||||
).receivedFrames[id] ?? [],
|
||||
trackId,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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]);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
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 Locator, type Page, test } from "@playwright/test";
|
||||
|
||||
import { createUserAndRoom, resizeContainer, startHarness } from "./harness.ts";
|
||||
import { averageColour, cameraColour, expectWearing } from "../utils/colour.ts";
|
||||
|
||||
// Background effects need WebGL2, and headless Firefox on a CI runner has none,
|
||||
// so it rightly offers none of them.
|
||||
test.skip(
|
||||
({ browserName }) => browserName === "firefox",
|
||||
"Background effects need WebGL2, which headless Firefox on CI does not have",
|
||||
);
|
||||
|
||||
/**
|
||||
* Background effects with Element Call as a component in a host page: the
|
||||
* pipeline's model and WebAssembly have to load from the component's bundle,
|
||||
* and the portalled menu has to be sized against the call, not the window.
|
||||
* Driven from the lobby, which builds the same menu and pipeline.
|
||||
*/
|
||||
|
||||
// Sign-in, crypto setup and sync happen twice before anything shows.
|
||||
test.describe.configure({ timeout: 180_000 });
|
||||
|
||||
test("puts a picture on the call's preview", async ({ page }) => {
|
||||
const { username, roomId } = await createUserAndRoom("effects");
|
||||
const panes = await startHarness(page, username, roomId);
|
||||
const pane = panes.first();
|
||||
await resizeContainer(pane.getByTestId("call-container"), {
|
||||
width: 900,
|
||||
height: 480,
|
||||
});
|
||||
await expect(pane.getByTestId("lobby_joinCall")).toBeVisible({
|
||||
timeout: 60_000,
|
||||
});
|
||||
const preview = pane.locator("video").first();
|
||||
const camera = await cameraColour(preview);
|
||||
|
||||
const tile = await openEffect(page, pane, "Background 1");
|
||||
const picture = await averageColour(tile.locator("img"));
|
||||
await tile.click();
|
||||
await expect(tile).toHaveAttribute("aria-checked", "true");
|
||||
await expectWearing(preview, picture, camera);
|
||||
});
|
||||
|
||||
test("keeps every effect reachable in a small container", async ({ page }) => {
|
||||
const { username, roomId } = await createUserAndRoom("effectsreach");
|
||||
const panes = await startHarness(page, username, roomId);
|
||||
const pane = panes.first();
|
||||
const container = pane.getByTestId("call-container");
|
||||
await resizeContainer(container, { width: 400, height: 360 });
|
||||
await expect(pane.getByTestId("lobby_joinCall")).toBeVisible({
|
||||
timeout: 60_000,
|
||||
});
|
||||
|
||||
const last = await openEffect(page, pane, "Background 2");
|
||||
const list = page.locator("[role='menu'] div[role='none']").first();
|
||||
expect((await list.boundingBox())!.height).toBeLessThanOrEqual(
|
||||
(await container.boundingBox())!.height,
|
||||
);
|
||||
await last.scrollIntoViewIfNeeded();
|
||||
await expect(last).toBeInViewport({ ratio: 1 });
|
||||
await last.click();
|
||||
await expect(last).toHaveAttribute("aria-checked", "true");
|
||||
});
|
||||
|
||||
/** Opens a component's camera menu and returns one of its effects. */
|
||||
async function openEffect(
|
||||
page: Page,
|
||||
pane: Locator,
|
||||
name: string,
|
||||
): Promise<Locator> {
|
||||
await pane
|
||||
.getByRole("button", { name: "Camera", exact: true })
|
||||
.click({ timeout: 60_000 });
|
||||
// Portalled out of the pane, so found on the page.
|
||||
return page
|
||||
.getByRole("group", { name: "Background effects" })
|
||||
.getByRole("menuitemradio", { name });
|
||||
}
|
||||
@@ -29,49 +29,14 @@ export interface MyFixtures {
|
||||
addUser: (username: string, host: string) => Promise<UserBaseFixture>;
|
||||
}
|
||||
|
||||
// Minimal config.json for the local element-web instance
|
||||
const CONFIG_JSON = {
|
||||
default_server_config: {
|
||||
"m.homeserver": {
|
||||
base_url: "https://synapse.m.localhost",
|
||||
server_name: "synapse.m.localhost",
|
||||
},
|
||||
},
|
||||
|
||||
element_call: {
|
||||
participant_limit: 8,
|
||||
brand: "Element Call",
|
||||
},
|
||||
|
||||
// The default language is set here for test consistency
|
||||
setting_defaults: {
|
||||
language: "en-GB",
|
||||
feature_group_calls: true,
|
||||
},
|
||||
|
||||
// the location tests want a map style url.
|
||||
map_style_url:
|
||||
"https://api.maptiler.com/maps/streets/style.json?key=fU3vlMsMn4Jb6dnEIFsx",
|
||||
|
||||
features: {
|
||||
// We don't want to go through the feature announcement during the e2e test
|
||||
feature_release_announcement: false,
|
||||
feature_element_call_video_rooms: true,
|
||||
feature_video_rooms: true,
|
||||
feature_group_calls: true,
|
||||
},
|
||||
};
|
||||
|
||||
export const widgetTest = test.extend<MyFixtures>({
|
||||
// allow per-test override: `widgetTest.use({ callType: "dm" })`
|
||||
callType: ["room", { option: true }],
|
||||
asWidget: async ({ browser, context, callType }, pUse) => {
|
||||
await context.route(`http://localhost:8081/config.json*`, async (route) => {
|
||||
await route.fulfill({ json: CONFIG_JSON });
|
||||
});
|
||||
|
||||
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 {
|
||||
@@ -109,15 +74,7 @@ export const widgetTest = test.extend<MyFixtures>({
|
||||
await TestHelpers.dismissInviteUnknownUserModal(ewPage1);
|
||||
|
||||
// Accept the invite
|
||||
await TestHelpers.closeReleaseAnnouncement(
|
||||
ewPage2,
|
||||
"Introducing Sections",
|
||||
);
|
||||
await TestHelpers.expandAllSections(ewPage2);
|
||||
await expect(
|
||||
TestHelpers.roomListItem(ewPage2, "Welcome Room"),
|
||||
).toBeVisible();
|
||||
await TestHelpers.roomListItem(ewPage2, "Welcome Room").click();
|
||||
await TestHelpers.openRoomInvite(ewPage2, "Welcome Room");
|
||||
await ewPage2.getByRole("button", { name: "Accept" }).click();
|
||||
await expect(
|
||||
ewPage2
|
||||
@@ -125,17 +82,7 @@ export const widgetTest = test.extend<MyFixtures>({
|
||||
.getByRole("heading", { name: "Welcome Room" }),
|
||||
).toBeVisible();
|
||||
} else if (callType === "dm") {
|
||||
await TestHelpers.closeReleaseAnnouncement(
|
||||
ewPage1,
|
||||
"Introducing Sections",
|
||||
);
|
||||
|
||||
await ewPage1
|
||||
.getByRole("navigation", { name: "Room list" })
|
||||
.getByRole("button", { name: "New", exact: true })
|
||||
.click();
|
||||
|
||||
await ewPage1.getByRole("menuitem", { name: "Start chat" }).click();
|
||||
await TestHelpers.chooseFromRoomListNewMenu(ewPage1, "Start chat");
|
||||
await ewPage1.getByRole("textbox", { name: "Search" }).click();
|
||||
await ewPage1.getByRole("textbox", { name: "Search" }).fill(whistlerMxId);
|
||||
await ewPage1.getByRole("button", { name: "Go" }).click();
|
||||
@@ -157,12 +104,7 @@ export const widgetTest = test.extend<MyFixtures>({
|
||||
).toBeVisible();
|
||||
|
||||
// Accept the DM invite from brooks
|
||||
await TestHelpers.closeReleaseAnnouncement(
|
||||
ewPage2,
|
||||
"Introducing Sections",
|
||||
);
|
||||
await TestHelpers.expandAllSections(ewPage2);
|
||||
await TestHelpers.roomListItem(ewPage2, brooksDisplayName).click();
|
||||
await TestHelpers.openRoomInvite(ewPage2, brooksDisplayName);
|
||||
await ewPage2.getByRole("button", { name: "Start chatting" }).click();
|
||||
}
|
||||
|
||||
@@ -187,13 +129,14 @@ export const widgetTest = test.extend<MyFixtures>({
|
||||
* Provide a way to add additional users within a test.
|
||||
* The returned user will be registered on the default homeserver, the name will be made unique by appending a timestamp.
|
||||
*/
|
||||
addUser: async ({ browser }, use) => {
|
||||
addUser: async ({ browser }, use, testInfo) => {
|
||||
await use(
|
||||
async (
|
||||
username: string,
|
||||
host: string = HOST1,
|
||||
): Promise<UserBaseFixture> => {
|
||||
const uniqueSuffix = Date.now();
|
||||
// Tests in parallel workers can reach this in the same millisecond.
|
||||
const uniqueSuffix = `${Date.now()}_${testInfo.parallelIndex}`;
|
||||
const { page, clientHandle, mxId } = await TestHelpers.registerUser(
|
||||
browser,
|
||||
`${username.toLowerCase()}_${uniqueSuffix}`,
|
||||
|
||||
@@ -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,55 @@
|
||||
/*
|
||||
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 Locator } from "@playwright/test";
|
||||
|
||||
export type Colour = [number, number, number];
|
||||
|
||||
/** The camera's colour, once the preview is showing it rather than nothing. */
|
||||
export async function cameraColour(preview: Locator): Promise<Colour> {
|
||||
await expect
|
||||
.poll(async () => Math.max(...(await averageColour(preview))))
|
||||
.toBeGreaterThan(40);
|
||||
return averageColour(preview);
|
||||
}
|
||||
|
||||
/** The mean colour of a video's current frame or an image, drawn small. */
|
||||
export async function averageColour(element: Locator): Promise<Colour> {
|
||||
return element.evaluate(
|
||||
async (source: HTMLVideoElement | HTMLImageElement) => {
|
||||
if (source instanceof HTMLImageElement) await source.decode();
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = canvas.height = 32;
|
||||
const context = canvas.getContext("2d")!;
|
||||
context.drawImage(source, 0, 0, 32, 32);
|
||||
const { data } = context.getImageData(0, 0, 32, 32);
|
||||
const sum = [0, 0, 0];
|
||||
for (let i = 0; i < data.length; i += 4)
|
||||
for (let c = 0; c < 3; c++) sum[c] += data[i + c];
|
||||
const pixels = data.length / 4;
|
||||
return sum.map((s) => s / pixels) as Colour;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export function distance(a: Colour, b: Colour): number {
|
||||
return Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
|
||||
}
|
||||
|
||||
/** Waits until a preview shows a picture rather than the camera. */
|
||||
export async function expectWearing(
|
||||
preview: Locator,
|
||||
picture: Colour,
|
||||
camera: Colour,
|
||||
): Promise<void> {
|
||||
// Long enough for the first effect of a session to be built.
|
||||
await expect
|
||||
.poll(async () => distance(await averageColour(preview), picture), {
|
||||
timeout: 60_000,
|
||||
})
|
||||
.toBeLessThan(distance(camera, picture) / 2);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
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 { widgetTest } from "../fixtures/widget-user.ts";
|
||||
import { TestHelpers } from "./test-helpers.ts";
|
||||
import { averageColour, cameraColour, expectWearing } from "../utils/colour.ts";
|
||||
|
||||
// Background effects need WebGL2, and headless Firefox on a CI runner has none,
|
||||
// so it rightly offers none of them.
|
||||
test.skip(
|
||||
({ browserName }) => browserName === "firefox",
|
||||
"Background effects need WebGL2, which headless Firefox on CI does not have",
|
||||
);
|
||||
|
||||
widgetTest(
|
||||
"puts a picture on the preview inside Element Web",
|
||||
async ({ asWidget }) => {
|
||||
test.slow();
|
||||
const { brooks } = asWidget;
|
||||
await TestHelpers.startCallInCurrentRoom(brooks.page, false);
|
||||
const frame = brooks.page
|
||||
.locator('iframe[title="Element Call"]')
|
||||
.contentFrame();
|
||||
await expect(frame.getByTestId("lobby_joinCall")).toBeVisible();
|
||||
const preview = frame.locator("video").first();
|
||||
const camera = await cameraColour(preview);
|
||||
|
||||
await frame.getByRole("button", { name: "Camera", exact: true }).click();
|
||||
const tile = frame
|
||||
.getByRole("group", { name: "Background effects" })
|
||||
.getByRole("menuitemradio", { name: "Background 1" });
|
||||
const picture = await averageColour(tile.locator("img"));
|
||||
await tile.click();
|
||||
await expect(tile).toHaveAttribute("aria-checked", "true");
|
||||
await expectWearing(preview, picture, camera);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
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 as setup } from "@playwright/test";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdirSync, readdirSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
const EMBEDDED_DIST = "embedded/web/dist";
|
||||
|
||||
setup("build the embedded package", () => {
|
||||
setup.setTimeout(10 * 60 * 1000);
|
||||
mkdirSync(EMBEDDED_DIST, { recursive: true });
|
||||
execFileSync("pnpm", ["build:embedded", "--outDir", EMBEDDED_DIST], {
|
||||
stdio: "inherit",
|
||||
});
|
||||
// The host does the crypto, and nothing runs the standalone client
|
||||
expect(readdirSync(join(EMBEDDED_DIST, "assets"))).not.toContainEqual(
|
||||
expect.stringMatching(/rust-crypto|matrix_sdk_crypto|IndexedDBWorker/),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
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 Route } from "@playwright/test";
|
||||
|
||||
import { widgetTest } from "../../fixtures/widget-user.ts";
|
||||
import { HOST2, TestHelpers } from "../test-helpers.ts";
|
||||
|
||||
/** Where the other site's Element Web serves the embedded package from */
|
||||
const CONFIG_JSON = "**/widgets/element-call/config.json";
|
||||
|
||||
const HOST_ANSWERS: Record<string, (route: Route) => Promise<void>> = {
|
||||
"a 404": async (route) => route.fulfill({ status: 404 }),
|
||||
"a failed fetch": async (route) => route.abort("failed"),
|
||||
"an HTML page": async (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: "text/html",
|
||||
body: "<!doctype html><title>Element</title>",
|
||||
}),
|
||||
};
|
||||
|
||||
widgetTest.skip(
|
||||
({ browserName }) => browserName === "firefox",
|
||||
"The widget suite does not run on Firefox, see the other specs here",
|
||||
);
|
||||
|
||||
for (const [answer, respond] of Object.entries(HOST_ANSWERS)) {
|
||||
widgetTest(
|
||||
`reaches the lobby when config.json gets ${answer}`,
|
||||
async ({ addUser }) => {
|
||||
const { page } = await addUser("Brooks", HOST2);
|
||||
await TestHelpers.createRoom("Config Room", page);
|
||||
|
||||
let answered = 0;
|
||||
await page.route(CONFIG_JSON, async (route) => {
|
||||
answered++;
|
||||
await respond(route);
|
||||
});
|
||||
|
||||
await TestHelpers.startCallInCurrentRoom(page);
|
||||
|
||||
await expect(
|
||||
page
|
||||
.locator('iframe[title="Element Call"]')
|
||||
.contentFrame()
|
||||
.getByTestId("lobby_joinCall"),
|
||||
).toBeVisible({ timeout: 15000 });
|
||||
expect(answered).toBeGreaterThan(0);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -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 {
|
||||
@@ -144,7 +150,11 @@ export class TestHelpers {
|
||||
|
||||
await this.dismissStartupToasts(page);
|
||||
|
||||
await TestHelpers.setDevToolElementCallDevUrl(page);
|
||||
// The other site's Element Web opens the embedded package it serves itself
|
||||
// (see docker-compose-playwright.yml), not the dev server's app.
|
||||
if (host !== HOST2) {
|
||||
await TestHelpers.setDevToolElementCallDevUrl(page);
|
||||
}
|
||||
|
||||
const clientHandle = await page.evaluateHandle(() =>
|
||||
window.mxMatrixClientPeg.get(),
|
||||
@@ -153,29 +163,40 @@ export class TestHelpers {
|
||||
return { page, clientHandle, mxId };
|
||||
}
|
||||
|
||||
// Dismisses any toasts that appear on startup, such as "Failed to load service worker" or "Back up your chats".
|
||||
// Toast can be stacked, and only the top one can be dismiss, so just look at what is on top and
|
||||
// dismiss (if part of expected toats)
|
||||
// Dismisses the toasts a fresh device gets after sign-in.
|
||||
//
|
||||
// Toasts stack and only the top one can be dismissed, so look
|
||||
// at what is on top each time.
|
||||
public static async dismissStartupToasts(page: Page): Promise<void> {
|
||||
const expectedToasts = [
|
||||
const expectedToasts: {
|
||||
title: string;
|
||||
button: string;
|
||||
confirm?: string;
|
||||
}[] = [
|
||||
{ title: "Failed to load service worker", button: "OK" },
|
||||
{ title: "Verify this device", button: "Later" },
|
||||
{ title: "Back up your chats", button: "Not now" },
|
||||
{ title: "Turn on key storage", button: "Dismiss" },
|
||||
{
|
||||
title: "Turn on key storage",
|
||||
button: "Dismiss",
|
||||
confirm: "Yes, dismiss",
|
||||
},
|
||||
{ title: "Notifications", button: "Dismiss" },
|
||||
{ title: "Element does not support this browser", button: "Dismiss" },
|
||||
];
|
||||
|
||||
const toast = page.locator(".mx_Toast_toast");
|
||||
const toastTitle = toast.locator(".mx_Toast_title h2");
|
||||
|
||||
// eslint-disable-next-line no-constant-condition
|
||||
while (true) {
|
||||
try {
|
||||
await toast.waitFor({ state: "visible", timeout: 700 });
|
||||
const title = await toast.locator(".mx_Toast_title h2").textContent();
|
||||
const title = await toastTitle.textContent();
|
||||
if (!title) break;
|
||||
|
||||
// Find the matching toast config
|
||||
const toastConfig = expectedToasts.find((t) =>
|
||||
title?.includes(t.title),
|
||||
);
|
||||
const toastConfig = expectedToasts.find((t) => title.includes(t.title));
|
||||
|
||||
if (toastConfig) {
|
||||
// Bounded so that a renamed button leaves the toast in place and the
|
||||
@@ -183,6 +204,19 @@ export class TestHelpers {
|
||||
await toast
|
||||
.getByRole("button", { name: toastConfig.button })
|
||||
.click({ timeout: 5000 });
|
||||
if (toastConfig.confirm) {
|
||||
const dialog = page.getByRole("dialog");
|
||||
await dialog
|
||||
.getByRole("button", { name: toastConfig.confirm })
|
||||
.click({ timeout: 5000 });
|
||||
await expect(dialog).toBeHidden({ timeout: 5000 });
|
||||
}
|
||||
// The same element shows the next toast a moment after the click, so
|
||||
// reading it straight away acts on the dismissed one a second time.
|
||||
// Counted rather than read, as the last toast leaves no title behind.
|
||||
await expect(toastTitle.filter({ hasText: title })).toHaveCount(0, {
|
||||
timeout: 5000,
|
||||
});
|
||||
} else {
|
||||
// Unknown toast. We don't want to act on unknown toasts
|
||||
break;
|
||||
@@ -194,20 +228,6 @@ export class TestHelpers {
|
||||
}
|
||||
}
|
||||
|
||||
public static async closeReleaseAnnouncement(
|
||||
page: Page,
|
||||
name: string,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await page
|
||||
.getByRole("dialog", { name })
|
||||
.getByRole("button", { name: "OK" })
|
||||
.click({ timeout: 2000 });
|
||||
} catch {
|
||||
// Announcement not shown; nothing to do
|
||||
}
|
||||
}
|
||||
|
||||
public static async expandAllSections(page: Page): Promise<void> {
|
||||
try {
|
||||
await page
|
||||
@@ -223,16 +243,7 @@ export class TestHelpers {
|
||||
page: Page,
|
||||
andInvite: string[] = [],
|
||||
): Promise<void> {
|
||||
await TestHelpers.closeReleaseAnnouncement(page, "Introducing Sections");
|
||||
|
||||
await page
|
||||
.getByRole("navigation", { name: "Room list" })
|
||||
.getByRole("button", { name: "New", exact: true })
|
||||
.click();
|
||||
|
||||
await page.getByRole("menuitem", { name: "New Room" }).click({
|
||||
timeout: 5000,
|
||||
});
|
||||
await TestHelpers.chooseFromRoomListNewMenu(page, "New Room");
|
||||
await page.getByRole("textbox", { name: "Name" }).fill(name);
|
||||
await page.getByRole("button", { name: "Create room" }).click();
|
||||
await expect(page.getByText("You created this room.")).toBeVisible({
|
||||
@@ -259,6 +270,24 @@ export class TestHelpers {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the room list's "New" menu and picks the given item.
|
||||
*
|
||||
* Driven by keyboard, as a toast arriving late sits over the button and
|
||||
* swallows clicks.
|
||||
*/
|
||||
public static async chooseFromRoomListNewMenu(
|
||||
page: Page,
|
||||
itemName: string,
|
||||
): Promise<void> {
|
||||
await TestHelpers.dismissStartupToasts(page);
|
||||
await page
|
||||
.getByRole("navigation", { name: "Room list" })
|
||||
.getByRole("button", { name: "New", exact: true })
|
||||
.press("Enter");
|
||||
await page.getByRole("menuitem", { name: itemName }).press("Enter");
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepts a room invite using the room name.
|
||||
* Locatest the invite in the room list.
|
||||
@@ -268,9 +297,7 @@ export class TestHelpers {
|
||||
roomName: string,
|
||||
page: Page,
|
||||
): Promise<void> {
|
||||
await TestHelpers.closeReleaseAnnouncement(page, "Introducing Sections");
|
||||
await TestHelpers.expandAllSections(page);
|
||||
await TestHelpers.roomListItem(page, roomName).click({ timeout: 10000 });
|
||||
await TestHelpers.openRoomInvite(page, roomName);
|
||||
await page.getByRole("button", { name: "Accept" }).click({
|
||||
timeout: 5000,
|
||||
});
|
||||
@@ -376,6 +403,28 @@ export class TestHelpers {
|
||||
return page.locator(`[aria-label^="Open room ${roomName}"]`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a pending invite from the room list by its room name.
|
||||
*
|
||||
* Element Web collapses the Invites section every time it appears, so it is
|
||||
* expanded here once the invite has arrived.
|
||||
*/
|
||||
public static async openRoomInvite(
|
||||
page: Page,
|
||||
roomName: string,
|
||||
): Promise<void> {
|
||||
const invitesSection = page.getByRole("button", {
|
||||
name: "Toggle Invites section",
|
||||
});
|
||||
await expect(invitesSection).toBeVisible({ timeout: 10000 });
|
||||
// Toasts sit over the top of the room list, where this header is.
|
||||
await TestHelpers.dismissStartupToasts(page);
|
||||
if ((await invitesSection.getAttribute("aria-expanded")) !== "true") {
|
||||
await invitesSection.click();
|
||||
}
|
||||
await TestHelpers.roomListItem(page, roomName).click({ timeout: 10000 });
|
||||
}
|
||||
|
||||
/**
|
||||
* Switches to a room in the room list by its name.
|
||||
* @param page - The EW page
|
||||
|
||||
@@ -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
+2086
-2414
File diff suppressed because it is too large
Load Diff
+15
-16
@@ -27,25 +27,17 @@ overrides:
|
||||
# Security fixes:
|
||||
# - https://github.com/advisories/GHSA-7r86-cg39-jmmj
|
||||
# - https://github.com/advisories/GHSA-23c5-xmqv-rm74
|
||||
"minimatch": "^10.2.3"
|
||||
"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
|
||||
@@ -59,4 +51,11 @@ overrides:
|
||||
# - https://github.com/element-hq/element-call/security/dependabot/196
|
||||
# - https://github.com/element-hq/element-call/security/dependabot/195
|
||||
# - https://github.com/element-hq/element-call/security/dependabot/193
|
||||
"dompurify": "^3.4.11"
|
||||
# - https://github.com/advisories/GHSA-cg2g-xh64-v4q7
|
||||
# - 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"
|
||||
|
||||
+5
-3
@@ -5,7 +5,7 @@
|
||||
"schedule:monthly",
|
||||
":enableVulnerabilityAlertsWithLabel(security)"
|
||||
],
|
||||
"addLabels": ["dependencies"],
|
||||
"labels": ["dependencies"],
|
||||
"minimumReleaseAge": "5 days",
|
||||
"packageRules": [
|
||||
{
|
||||
@@ -16,7 +16,8 @@
|
||||
{
|
||||
"groupName": "GitHub Actions",
|
||||
"matchDepTypes": ["action"],
|
||||
"pinDigests": true
|
||||
"pinDigests": true,
|
||||
"labels": ["PR-Task"]
|
||||
},
|
||||
{
|
||||
"description": "Disable Renovate for packages we want to monitor ourselves",
|
||||
@@ -69,7 +70,8 @@
|
||||
"matchUpdateTypes": ["digest"],
|
||||
"schedule": ["* 0-3 * * *"],
|
||||
"minimumReleaseAge": null,
|
||||
"automerge": true
|
||||
"automerge": true,
|
||||
"labels": ["PR-Task"]
|
||||
}
|
||||
],
|
||||
"semanticCommits": "disabled",
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
@@ -9,11 +9,11 @@ Please see LICENSE in the repository root for full details.
|
||||
* Checks that the library builds leave the packages a host must supply to the
|
||||
* host.
|
||||
*
|
||||
* A host application already has React, the Matrix SDK and Compound,
|
||||
* and a second copy of any of them is worse than dead weight: React would hold
|
||||
* two sets of hooks, the Matrix client would run two sync loops, and a second
|
||||
* Compound would style the tooltips it floats into the host's body with class
|
||||
* names the host's stylesheet does not know. So each library build lists them
|
||||
* A host application already has React and Compound (and, for the SDK build,
|
||||
* the Matrix SDK), and a second copy of any of them is worse than dead weight:
|
||||
* React would hold two sets of hooks, and a second Compound would style the
|
||||
* tooltips it floats into the host's body with class names the host's
|
||||
* stylesheet does not know. So each library build lists them
|
||||
* as external — but that list has to name every subpath, since the bundler
|
||||
* silently ignores the pattern and callback forms of the option, and an import
|
||||
* it does not cover is bundled with no warning at all. That is the failure
|
||||
@@ -47,10 +47,10 @@ const TARGETS = [
|
||||
// `sdk` too: the build resolves `@element-hq/matrixrtc-sdk` to its source
|
||||
sources: ["src", "component", "sdk"],
|
||||
excluded: ["component/dev", "sdk/dev"],
|
||||
// Not the Matrix SDK: the component bundles its own (see the build config)
|
||||
mustBeExternal: [
|
||||
"react",
|
||||
"react-dom",
|
||||
"matrix-js-sdk",
|
||||
"@vector-im/compound-web",
|
||||
"@vector-im/compound-design-tokens",
|
||||
],
|
||||
|
||||
@@ -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,191 +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,
|
||||
participation,
|
||||
room,
|
||||
mediaDevices,
|
||||
muteStates,
|
||||
{
|
||||
...callViewModelOptionsFromParams(urlParams),
|
||||
encryptionSystem,
|
||||
capture,
|
||||
hostBridge,
|
||||
// The bundle owns its page, so the body is the space it has
|
||||
windowSize$: scope.behavior(observeElementSize$(document.body)),
|
||||
},
|
||||
of({}),
|
||||
of({}),
|
||||
);
|
||||
// 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);
|
||||
},
|
||||
};
|
||||
}
|
||||
+9
-8
@@ -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
|
||||
@@ -19,6 +18,7 @@ nothing in Element Call's `src/`.
|
||||
```ts
|
||||
import {
|
||||
createRTCSlot,
|
||||
createSdkMatrixBackend,
|
||||
E2eeType,
|
||||
MatrixRTCMode,
|
||||
ObservableScope,
|
||||
@@ -28,15 +28,15 @@ import {
|
||||
const scope = new ObservableScope();
|
||||
const slot = createRTCSlot(
|
||||
scope,
|
||||
client, // a matrix-js-sdk MatrixClient, logged in and syncing
|
||||
room, // the matrix-js-sdk Room, from client.getRoom() once the join has synced
|
||||
{
|
||||
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
|
||||
matrixRTCMode: MatrixRTCMode.Compatibility,
|
||||
},
|
||||
createSdkMatrixBackend(
|
||||
client, // a matrix-js-sdk MatrixClient, logged in and syncing
|
||||
room, // the matrix-js-sdk Room, from client.getRoom() once the join has synced
|
||||
),
|
||||
{ encryptionSystem: { kind: E2eeType.PER_PARTICIPANT } }, // the room's call, m.call#ROOM
|
||||
);
|
||||
const participation = slot.join({
|
||||
publish: [{ source: "microphone" }, { source: "camera" }],
|
||||
matrixRTCMode: MatrixRTCMode.Compatibility,
|
||||
});
|
||||
|
||||
// A <video> for each remote member's camera and an <audio> for its microphone.
|
||||
@@ -99,6 +99,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`
|
||||
```
|
||||
|
||||
|
||||
+20
-17
@@ -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.
|
||||
|
||||
@@ -143,18 +145,18 @@ participation split in
|
||||
[`client-into-slot-session-split-plan.md`](./client-into-slot-session-split-plan.md);
|
||||
the sections below still describe `MatrixRTCClient` until that lands.
|
||||
|
||||
| Word | Meaning here | Elsewhere |
|
||||
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------- |
|
||||
| slot | an `RTCSlot`: the namespace in a room that memberships join into, `application` plus `id`. It exists while the room does, with nobody in it too. Holds `members$`, its open or closed `status$`, and `join()` | the js-sdk `MatrixRTCSession` is one per slot; the MSC4143 slot event |
|
||||
| participation | an `RTCParticipation`: the span between our `join()` of a slot and our `leave()`. Holds the connection and its `state$`, `localMember$`, `remoteMembers$`, the connected transports and the data channel. Made by `slot.join()`, never reused | "session" is not used here, because in the js-sdk it means the slot |
|
||||
| member | an `RTCMember`: one membership in a slot with what the SDK derives from it, `rtcBackendIdentity`, `userId`, `deviceId`, `memberId`, `displayName$`, `avatarUrl$`, `transport$` and `applicationData$`. No media. What the slot hands out in `members$` | the js-sdk `CallMembership` behind it, which never leaves the SDK; Element Call's old "matrixLivekitMember" |
|
||||
| local member, remote member | `LocalRTCMember` and `RemoteRTCMember`: an `RTCMember` plus its `MemberMedia`, which only a participation can carry. The local one's tracks carry the controls. What the participation hands out in `localMember$` and `remoteMembers$` | LiveKit `LocalParticipant` and `RemoteParticipant`, which never leave the SDK |
|
||||
| media | a `MemberMedia`: what a member sends once it has arrived on its transport, `tracks$`, null while waiting, and `encryptionError$` beside it. The media backend supplies exactly these two fields per member | Element Call's `MediaViewModel` is a view of it |
|
||||
| track | a `MediaTrack`: one publication of a member, audio or video, with `source`, `kind`, `id` and the behaviors on it. `LocalAudioMediaTrack` and `LocalVideoMediaTrack` add the controls over our own | LiveKit `TrackPublication` and `Track`, which never leave the SDK |
|
||||
| publish request | a `PublishRequest`: a source, where to capture it from and how to encode it. Given at the join in `publish`, or later to `publish` on the participation | |
|
||||
| attach, detach | handing a `<video>` or `<audio>` element to a track and taking it back. The SDK owns the stream and the observers on the element | LiveKit `Track.attach` |
|
||||
| transport | an `RTCTransport`: where media is exchanged, a LiveKit service url today. Carries the raw js-sdk `Transport` from the membership and, in `resolved$`, what the backend fetched to connect to it | MSC4143 "focus" |
|
||||
| media backend | a `MediaBackend`: what carries the media, behind `sdk/src/media-backend/api.ts`. One per participation, chosen with `backend` in the join options; LiveKit under `sdk/src/media-backend/livekit/` is the one that exists | "SFU", a LiveKit room, a peer connection |
|
||||
| Word | Meaning here | Elsewhere |
|
||||
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------- |
|
||||
| slot | an `RTCSlot`: the namespace in a room that memberships join into, `application` plus `id`. It exists while the room does, with nobody in it too. Holds `members$`, its open or closed `status$`, and `join()` | the js-sdk `MatrixRTCSession` is one per slot; the MSC4143 slot event |
|
||||
| participation | an `RTCParticipation`: the span between our `join()` of a slot and our `leave()`. Holds the connection and its `state$`, `localMember$`, `remoteMembers$`, the connected transports and the data channel. Made by `slot.join()`, never reused | "session" is not used here, because in the js-sdk it means the slot |
|
||||
| member | an `RTCMember`: one membership in a slot with what the SDK derives from it, `rtcBackendIdentity`, `userId`, `deviceId`, `memberId`, `matrixEventId$`, `displayName$`, `avatarUrl$`, `transport$` and `applicationData$`. No media. What the slot hands out in `members$` | the js-sdk `CallMembership` behind it, which never leaves the SDK; Element Call's old "matrixLivekitMember" |
|
||||
| local member, remote member | `LocalRTCMember` and `RemoteRTCMember`: an `RTCMember` plus its `MemberMedia`, which only a participation can carry. The local one's tracks carry the controls. What the participation hands out in `localMember$` and `remoteMembers$` | LiveKit `LocalParticipant` and `RemoteParticipant`, which never leave the SDK |
|
||||
| media | a `MemberMedia`: what a member sends once it has arrived on its transport, `tracks$`, null while waiting, and `encryptionError$` beside it. The media backend supplies exactly these two fields per member | Element Call's `MediaViewModel` is a view of it |
|
||||
| track | a `MediaTrack`: one publication of a member, audio or video, with `source`, `kind`, `id` and the behaviors on it. `LocalAudioMediaTrack` and `LocalVideoMediaTrack` add the controls over our own | LiveKit `TrackPublication` and `Track`, which never leave the SDK |
|
||||
| publish request | a `PublishRequest`: a source, where to capture it from and how to encode it. Given at the join in `publish`, or later to `publish` on the participation | |
|
||||
| attach, detach | handing a `<video>` or `<audio>` element to a track and taking it back. The SDK owns the stream and the observers on the element | LiveKit `Track.attach` |
|
||||
| transport | an `RTCTransport`: where media is exchanged, a LiveKit service url today. Carries the raw js-sdk `Transport` from the membership and, in `resolved$`, what the backend fetched to connect to it | MSC4143 "focus" |
|
||||
| media backend | a `MediaBackend`: what carries the media, behind `sdk/src/media-backend/api.ts`. One per participation, chosen with `backend` in the join options; LiveKit under `sdk/src/media-backend/livekit/` is the one that exists | "SFU", a LiveKit room, a peer connection |
|
||||
|
||||
Names use `RTC` in capitals, as the js-sdk does: `RTCSlot`, `RTCParticipation`,
|
||||
`RTCMember`, `matrixRTCMode`.
|
||||
@@ -634,7 +636,9 @@ export type MediaSource =
|
||||
| "unknown";
|
||||
|
||||
export type MediaStreamStats =
|
||||
RTCInboundRtpStreamStats | RTCOutboundRtpStreamStats | undefined;
|
||||
| RTCInboundRtpStreamStats
|
||||
| RTCOutboundRtpStreamStats
|
||||
| undefined;
|
||||
|
||||
/** One published track of a member. */
|
||||
export interface MediaTrack {
|
||||
@@ -777,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`) |
|
||||
+3
-2
@@ -16,6 +16,7 @@ import { combineLatest, type Observable, of, switchMap } from "rxjs";
|
||||
import {
|
||||
type AudioMediaTrack,
|
||||
createRTCSlot,
|
||||
createSdkMatrixBackend,
|
||||
E2eeType,
|
||||
type LocalRTCMember,
|
||||
MatrixRTCMode,
|
||||
@@ -70,12 +71,12 @@ async function start(
|
||||
const room = await joinRoom(client, roomIdOrAlias);
|
||||
|
||||
const scope = new ObservableScope();
|
||||
const slot = createRTCSlot(scope, client, room, {
|
||||
const slot = createRTCSlot(scope, createSdkMatrixBackend(client, room), {
|
||||
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
|
||||
matrixRTCMode: MatrixRTCMode.Compatibility,
|
||||
});
|
||||
const rtcParticipation = slot.join({
|
||||
publish: [{ source: "microphone" }, { source: "camera" }],
|
||||
matrixRTCMode: MatrixRTCMode.Compatibility,
|
||||
});
|
||||
rtcParticipation.state$.pipe(scope.bind()).subscribe((state) => {
|
||||
status.textContent =
|
||||
|
||||
@@ -57,6 +57,11 @@ export * from "./src/media-api";
|
||||
export * from "./src/media-backend/api";
|
||||
export { trackBySource$, type TrackOfSource } from "./src/utils/tracks";
|
||||
export { createRTCSlot } from "./src/RTCSlot";
|
||||
export {
|
||||
createSdkMatrixBackend,
|
||||
type SdkMatrixBackend,
|
||||
withEmitter,
|
||||
} from "./src/SdkMatrixBackend";
|
||||
export {
|
||||
createLivekitBackend,
|
||||
type LivekitBackendOptions,
|
||||
|
||||
+205
-16
@@ -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,12 +299,21 @@ 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({ getUserMedia: fakeGetUserMedia() });
|
||||
const [camera] = (await media.capture([{ source: "camera" }])) as [
|
||||
LocalVideoMediaTrack,
|
||||
];
|
||||
expect(camera.facingMode$.value).toBe("user");
|
||||
});
|
||||
|
||||
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" },
|
||||
@@ -162,6 +322,7 @@ describe("createLocalMedia", () => {
|
||||
media.release("camera");
|
||||
expect(trackBehind(camera).stop).toHaveBeenCalled();
|
||||
expect(media.tracks$.value).toEqual([microphone]);
|
||||
expect(media.requests.map((r) => r.source)).toEqual(["microphone"]);
|
||||
|
||||
media.stop();
|
||||
expect(trackBehind(microphone).stop).toHaveBeenCalled();
|
||||
@@ -169,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",
|
||||
);
|
||||
@@ -197,6 +358,7 @@ function fakeTrack(
|
||||
const track = {
|
||||
kind,
|
||||
id: `${kind}-${nextId++}`,
|
||||
label: "",
|
||||
enabled: true,
|
||||
stop: vi.fn(),
|
||||
getSettings: () => settings,
|
||||
@@ -216,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 {
|
||||
|
||||
+143
-39
@@ -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,
|
||||
@@ -19,6 +24,7 @@ import {
|
||||
type VideoProcessor,
|
||||
} from "./media-api";
|
||||
import { constant } from "./reactive/Behavior";
|
||||
import { facingModeOf } from "./utils/facingMode";
|
||||
import { inTurn } from "./utils/processorTurns";
|
||||
|
||||
type Source = "microphone" | "camera";
|
||||
@@ -27,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<
|
||||
@@ -77,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";
|
||||
@@ -90,7 +112,7 @@ export function createLocalMedia(
|
||||
const captured_ = new CapturedTrack(
|
||||
source,
|
||||
track,
|
||||
trackConstraints(request),
|
||||
constraints[source]!,
|
||||
getUserMedia,
|
||||
);
|
||||
capturedTracks.set(source, captured_);
|
||||
@@ -107,6 +129,7 @@ export function createLocalMedia(
|
||||
if (source !== "microphone" && source !== "camera") return;
|
||||
capturedTracks.get(source)?.stop();
|
||||
capturedTracks.delete(source);
|
||||
requests.delete(source);
|
||||
publishCapturedTracks();
|
||||
};
|
||||
|
||||
@@ -137,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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -160,9 +251,7 @@ function trackConstraints(request: Request): MediaTrackConstraints {
|
||||
class CapturedTrack {
|
||||
public readonly mediaTrack: LocalAudioMediaTrack | LocalVideoMediaTrack;
|
||||
private readonly muted$ = new BehaviorSubject(false);
|
||||
private readonly facingMode$: BehaviorSubject<
|
||||
"user" | "environment" | undefined
|
||||
>;
|
||||
private readonly facingMode$: BehaviorSubject<"user" | "environment">;
|
||||
private readonly elements = new Set<HTMLMediaElement>();
|
||||
private processor: HandedOverTrack["processor"];
|
||||
/** What the processor reads frames from; a processor needs a playing element. */
|
||||
@@ -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")
|
||||
@@ -305,10 +419,9 @@ class CapturedTrack {
|
||||
kind: "video",
|
||||
facingMode$: this.facingMode$,
|
||||
switchFacingMode: async () => {
|
||||
const facingMode = this.facingMode$.value;
|
||||
if (facingMode === undefined) return;
|
||||
await this.reacquire({
|
||||
facingMode: facingMode === "user" ? "environment" : "user",
|
||||
facingMode:
|
||||
this.facingMode$.value === "user" ? "environment" : "user",
|
||||
});
|
||||
return this.track.getSettings().deviceId;
|
||||
},
|
||||
@@ -324,12 +437,3 @@ function play(element: HTMLMediaElement, track: MediaStreamTrack): void {
|
||||
const playing = element.play() as Promise<void> | undefined;
|
||||
playing?.catch(() => undefined);
|
||||
}
|
||||
|
||||
function facingModeOf(
|
||||
track: MediaStreamTrack,
|
||||
): "user" | "environment" | undefined {
|
||||
const { facingMode } = track.getSettings();
|
||||
return facingMode === "user" || facingMode === "environment"
|
||||
? facingMode
|
||||
: undefined;
|
||||
}
|
||||
|
||||
@@ -22,7 +22,6 @@ import {
|
||||
type ParticipationState,
|
||||
type RTCMember,
|
||||
type RTCParticipationOptions,
|
||||
type RTCSlot,
|
||||
type TransportMetadata,
|
||||
} from "./api";
|
||||
import { defaultSessionTimings, MatrixRTCMode } from "./config";
|
||||
@@ -86,6 +85,7 @@ function member(
|
||||
rtcBackendIdentity: overrides.memberId,
|
||||
backendIdentities: [overrides.memberId],
|
||||
deviceId: "DEV",
|
||||
matrixEventId$: constant(`$${overrides.memberId}`),
|
||||
transport$: constant(metadata(transport)),
|
||||
applicationData$: constant({}),
|
||||
displayName$: constant(overrides.userId),
|
||||
@@ -111,7 +111,6 @@ interface FakeBackend {
|
||||
|
||||
function setup(
|
||||
options: Partial<RTCParticipationOptions> = {},
|
||||
slotOptions: { matrixRTCMode?: MatrixRTCMode } = {},
|
||||
{
|
||||
homeserverTransports = [transport],
|
||||
memberships = [],
|
||||
@@ -140,8 +139,8 @@ function setup(
|
||||
getDeviceId: () => deviceId,
|
||||
getDomain: () => "example.org",
|
||||
getSyncState: () => SyncState.Syncing,
|
||||
_unstable_getRTCTransports: vi.fn().mockResolvedValue(homeserverTransports),
|
||||
_unstable_getLivekitToken: vi.fn().mockResolvedValue({ jwt: publisherJWT }),
|
||||
getRTCTransports: vi.fn().mockResolvedValue(homeserverTransports),
|
||||
getLivekitToken: vi.fn().mockResolvedValue({ jwt: publisherJWT }),
|
||||
} as unknown as MatrixClient;
|
||||
const members$ = new BehaviorSubject<RTCMember[]>([]);
|
||||
|
||||
@@ -191,19 +190,24 @@ function setup(
|
||||
scope,
|
||||
{
|
||||
client,
|
||||
room,
|
||||
slot: {} as RTCSlot,
|
||||
jsSdkSession: mockedSession,
|
||||
members$: scope.behavior(members$),
|
||||
transports: { get: metadata, connected$: constant([]) },
|
||||
slotOptions: {
|
||||
matrixRTCMode: MatrixRTCMode.Compatibility,
|
||||
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
|
||||
...slotOptions,
|
||||
slot: {
|
||||
roomId: room.roomId,
|
||||
application: "m.call",
|
||||
id: "ROOM",
|
||||
status$: constant(undefined),
|
||||
members$: scope.behavior(members$),
|
||||
},
|
||||
jsSdkSession: mockedSession,
|
||||
transports: { get: metadata, connected$: constant([]) },
|
||||
slotOptions: { encryptionSystem: { kind: E2eeType.PER_PARTICIPANT } },
|
||||
logger,
|
||||
},
|
||||
{ publish: [], backend: backendFactory, ...options },
|
||||
{
|
||||
publish: [],
|
||||
matrixRTCMode: MatrixRTCMode.Compatibility,
|
||||
backend: backendFactory,
|
||||
...options,
|
||||
},
|
||||
);
|
||||
const states: ParticipationState[] = [];
|
||||
participation.state$.subscribe((state) => states.push(state));
|
||||
@@ -254,7 +258,6 @@ describe("createRTCParticipation", () => {
|
||||
fociPreferred: [{ type: "livekit", url: "wss://sfu.example.org" }],
|
||||
});
|
||||
const { join, fake } = setup(
|
||||
{},
|
||||
{},
|
||||
{ homeserverTransports: [], memberships: [bobOnSfu] },
|
||||
);
|
||||
@@ -349,7 +352,7 @@ describe("createRTCParticipation", () => {
|
||||
});
|
||||
compatibility.scope.end();
|
||||
|
||||
const matrix2 = setup({}, { matrixRTCMode: MatrixRTCMode.Matrix_2_0 });
|
||||
const matrix2 = setup({ matrixRTCMode: MatrixRTCMode.Matrix_2_0 });
|
||||
const { memberId } = matrix2.fake.context.ownMembershipIdentity;
|
||||
expect(memberId).not.toBe(legacyMemberId);
|
||||
expect(memberId).toMatch(/^[0-9a-f-]{36}$/);
|
||||
|
||||
+53
-32
@@ -5,7 +5,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { type MatrixClient, type Room } from "matrix-js-sdk";
|
||||
import { type MatrixClient } from "matrix-js-sdk";
|
||||
import { type Logger } from "matrix-js-sdk/lib/logger";
|
||||
import {
|
||||
type MatrixRTCSession as JsSdkRTCSession,
|
||||
@@ -30,19 +30,17 @@ import {
|
||||
|
||||
import { defaultSessionTimings, MatrixRTCMode } from "./config";
|
||||
import { E2eeType } from "./encryption";
|
||||
import { type Behavior } from "./reactive/Behavior";
|
||||
import { type ObservableScope } from "./reactive/ObservableScope";
|
||||
import { generateItems } from "./reactive/observable";
|
||||
import { mapScoped } from "./utils/mapScoped";
|
||||
import {
|
||||
type ParticipationSlot,
|
||||
type DataMessage,
|
||||
type LocalRTCMember,
|
||||
type ParticipationState,
|
||||
type RemoteRTCMember,
|
||||
type RTCMember,
|
||||
type RTCParticipation,
|
||||
type RTCParticipationOptions,
|
||||
type RTCSlot,
|
||||
type RTCSlotOptions,
|
||||
} from "./api";
|
||||
import {
|
||||
@@ -67,15 +65,34 @@ import { createKeyRotationSuppressed$ } from "./matrixrtc/JsRtcSessionBehaviors"
|
||||
import { type TransportRegistry } from "./matrixrtc/Transports";
|
||||
import { participationState } from "./participationState";
|
||||
|
||||
/** What the slot lends a participation. */
|
||||
/** What is needed for our own participation. */
|
||||
export interface ParticipationDeps {
|
||||
client: MatrixClient;
|
||||
room: Room;
|
||||
slot: RTCSlot;
|
||||
client: Pick<
|
||||
MatrixClient,
|
||||
// Our own membership identity
|
||||
| "getUserId"
|
||||
| "getDeviceId"
|
||||
// Local transport discovery
|
||||
| "getDomain"
|
||||
| "getRTCTransports"
|
||||
// LiveKit auth: `getOpenIdToken` for the JWT service flow, `getLivekitToken`
|
||||
// for the client-server API flow (MSC4195), `delegateDelayedLeave` and
|
||||
// `baseUrl` for the delayed leave delegation and its probe
|
||||
| "getOpenIdToken"
|
||||
| "getLivekitToken"
|
||||
| "delegateDelayedLeave"
|
||||
| "baseUrl"
|
||||
// Homeserver connection: whether the client is syncing
|
||||
| "getSyncState"
|
||||
// `on`/`off`, to listen for:
|
||||
// - `ClientEvent.Sync` (homeserver connection)
|
||||
| "on"
|
||||
| "off"
|
||||
>;
|
||||
slot: ParticipationSlot;
|
||||
jsSdkSession: JsSdkRTCSession;
|
||||
members$: Behavior<RTCMember[]>;
|
||||
transports: TransportRegistry;
|
||||
slotOptions: Pick<RTCSlotOptions, "matrixRTCMode" | "encryptionSystem">;
|
||||
slotOptions: RTCSlotOptions;
|
||||
logger: Logger;
|
||||
}
|
||||
|
||||
@@ -94,16 +111,19 @@ export function createRTCParticipation(
|
||||
scope: ObservableScope,
|
||||
{
|
||||
client,
|
||||
room,
|
||||
slot,
|
||||
jsSdkSession,
|
||||
members$,
|
||||
transports,
|
||||
slotOptions: { matrixRTCMode, encryptionSystem },
|
||||
slotOptions: { encryptionSystem },
|
||||
logger: parentLogger,
|
||||
}: ParticipationDeps,
|
||||
options: RTCParticipationOptions,
|
||||
): ParticipationInternals {
|
||||
const { matrixRTCMode } = options;
|
||||
const { roomId, members$ } = slot;
|
||||
// The full `{application}#{id}`, which the auth service and the other
|
||||
// members key the media room on
|
||||
const slotId = jsSdkSession.slotId;
|
||||
const logger = parentLogger.getChild("[RTCParticipation]");
|
||||
const userId = client.getUserId()!;
|
||||
const deviceId = client.getDeviceId()!;
|
||||
@@ -122,8 +142,8 @@ export function createRTCParticipation(
|
||||
};
|
||||
|
||||
const backend = createBackend(scope, client, options, {
|
||||
roomId: room.roomId,
|
||||
slotId: jsSdkSession.slotId,
|
||||
roomId,
|
||||
slotId,
|
||||
ownMembershipIdentity,
|
||||
publish: options.publish,
|
||||
encryptionSystem,
|
||||
@@ -144,8 +164,8 @@ export function createRTCParticipation(
|
||||
// to come back later rather than wait in a half-working lobby
|
||||
memberships: jsSdkSession.memberships,
|
||||
ownMembershipIdentity,
|
||||
roomId: room.roomId,
|
||||
slotId: jsSdkSession.slotId,
|
||||
roomId,
|
||||
slotId,
|
||||
logger,
|
||||
})
|
||||
: null;
|
||||
@@ -175,20 +195,15 @@ export function createRTCParticipation(
|
||||
timings.syncDisconnectGracePeriodMs,
|
||||
),
|
||||
joinMatrixRTC: (transport, delayedLeave) =>
|
||||
joinJsSdkSession(
|
||||
room.roomId,
|
||||
jsSdkSession,
|
||||
ownMembershipIdentity,
|
||||
transport,
|
||||
{
|
||||
encryptMedia: encryptionSystem.kind !== E2eeType.NONE,
|
||||
matrixRTCMode,
|
||||
sendNotificationType: options.sendNotificationType,
|
||||
applicationData: options.applicationData,
|
||||
timings,
|
||||
delayedLeave,
|
||||
},
|
||||
),
|
||||
joinJsSdkSession(roomId, jsSdkSession, ownMembershipIdentity, transport, {
|
||||
encryptMedia: encryptionSystem.kind !== E2eeType.NONE,
|
||||
matrixRTCMode,
|
||||
sendNotificationType: options.sendNotificationType,
|
||||
callIntent: options.callIntent,
|
||||
applicationData: options.applicationData,
|
||||
timings,
|
||||
delayedLeave,
|
||||
}),
|
||||
membershipManagerError$: fromEvent(
|
||||
jsSdkSession,
|
||||
MatrixRTCSessionEvent.MembershipManagerError,
|
||||
@@ -314,7 +329,13 @@ export function createRTCParticipation(
|
||||
/** The host's backend, or LiveKit configured from the participation options. */
|
||||
function createBackend(
|
||||
scope: ObservableScope,
|
||||
client: MatrixClient,
|
||||
client: Pick<
|
||||
MatrixClient,
|
||||
// LiveKit auth: `getOpenIdToken` for the JWT service flow, `getLivekitToken`
|
||||
// for the client-server API flow (MSC4195), `delegateDelayedLeave` and
|
||||
// `baseUrl` for the delayed leave delegation and its probe
|
||||
"getOpenIdToken" | "getLivekitToken" | "delegateDelayedLeave" | "baseUrl"
|
||||
>,
|
||||
{ backend, mediaQuality }: RTCParticipationOptions,
|
||||
context: MediaBackendContext,
|
||||
): MediaBackend {
|
||||
|
||||
+202
-9
@@ -5,23 +5,39 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { type MatrixClient, type Room } from "matrix-js-sdk";
|
||||
import { EMPTY } from "rxjs";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { type MatrixClient, type Room, SyncState } from "matrix-js-sdk";
|
||||
import { EventType } from "matrix-js-sdk/lib/@types/event";
|
||||
import { type MatrixEvent } from "matrix-js-sdk/lib/models/event";
|
||||
import {
|
||||
type RoomState,
|
||||
RoomStateEvent,
|
||||
} from "matrix-js-sdk/lib/models/room-state";
|
||||
import { RoomStickyEventsEvent } from "matrix-js-sdk/lib/models/room-sticky-events";
|
||||
|
||||
import {
|
||||
MatrixRTCSessionEvent,
|
||||
type MatrixRTCSessionEventHandlerMap,
|
||||
} from "matrix-js-sdk/lib/matrixrtc";
|
||||
|
||||
import { createRTCSlot } from "./RTCSlot";
|
||||
import { type RTCSlotOptions } from "./api";
|
||||
import { type SdkMatrixBackend } from "./SdkMatrixBackend";
|
||||
import { ObservableScope } from "./reactive/ObservableScope";
|
||||
import { type RTCParticipationOptions, type RTCSlotOptions } from "./api";
|
||||
import { MatrixRTCMode } from "./config";
|
||||
import { E2eeType } from "./encryption";
|
||||
import { mockEmitter, MockRTCSession, testScope } from "./utils/test";
|
||||
import { MatrixRTCError } from "./errors";
|
||||
import { type MediaBackend, MediaConnectionState } from "./media-backend/api";
|
||||
import { constant } from "./reactive/Behavior";
|
||||
import {
|
||||
mockEmitter,
|
||||
mockRtcMembership,
|
||||
MockRTCSession,
|
||||
testScope,
|
||||
} from "./utils/test";
|
||||
|
||||
const options: RTCSlotOptions = {
|
||||
matrixRTCMode: MatrixRTCMode.Compatibility,
|
||||
encryptionSystem: { kind: E2eeType.NONE },
|
||||
};
|
||||
|
||||
@@ -34,28 +50,140 @@ function setup(): {
|
||||
...mockEmitter(),
|
||||
roomId: "!room:example.org",
|
||||
getMembersWithMembership: (): [] => [],
|
||||
// An empty room, for a session of the slot's own
|
||||
getLiveTimeline: () => ({ getState: (): undefined => undefined }),
|
||||
hasMembershipState: (): boolean => false,
|
||||
getVersion: (): string => "11",
|
||||
_unstable_getStickyEvents: (): [] => [],
|
||||
} as unknown as Room;
|
||||
const session = new MockRTCSession(room);
|
||||
const client = {
|
||||
...mockEmitter(),
|
||||
getUserId: (): string => "@alice:example.org",
|
||||
getDeviceId: (): string => "AAAA",
|
||||
matrixRTC: { getRoomSession: (): MockRTCSession => session },
|
||||
} as unknown as MatrixClient;
|
||||
return { client, room, session };
|
||||
}
|
||||
|
||||
function backendOf(client: MatrixClient, room: Room): SdkMatrixBackend {
|
||||
return {
|
||||
...client,
|
||||
...room,
|
||||
clientEmitter: client,
|
||||
roomEmitter: room,
|
||||
} as unknown as SdkMatrixBackend;
|
||||
}
|
||||
|
||||
/** A media backend whose transport never gets ready: a participation on it stays waiting. */
|
||||
function idleBackend(): MediaBackend {
|
||||
return {
|
||||
transportTypes: ["livekit"],
|
||||
prepareLocalTransport: async () => new Promise(() => {}),
|
||||
delegateDelayedLeave: vi.fn(),
|
||||
local: {
|
||||
connectionState$: constant(MediaConnectionState.Initialized),
|
||||
setPublishing: vi.fn(),
|
||||
publishError$: constant(null),
|
||||
publish: vi.fn(),
|
||||
unpublish: vi.fn(),
|
||||
tracks$: constant(null),
|
||||
encryptionError$: EMPTY,
|
||||
},
|
||||
mediaFor: vi.fn(),
|
||||
connections$: constant([]),
|
||||
setAudioOutputDeviceId: vi.fn(),
|
||||
sendData: vi.fn(),
|
||||
data$: EMPTY,
|
||||
};
|
||||
}
|
||||
|
||||
describe("createRTCSlot", () => {
|
||||
describe("session", () => {
|
||||
it("joins the room's call slot by default", () => {
|
||||
const { client, room } = setup();
|
||||
const slot = createRTCSlot(testScope(), backendOf(client, room), options);
|
||||
expect(slot).toMatchObject({ application: "m.call", id: "ROOM" });
|
||||
});
|
||||
|
||||
it("joins the slot the options name", () => {
|
||||
const { client, room } = setup();
|
||||
const slot = createRTCSlot(testScope(), backendOf(client, room), {
|
||||
...options,
|
||||
slotDescription: { application: "io.element.example", id: "" },
|
||||
});
|
||||
expect(slot).toMatchObject({ application: "io.element.example", id: "" });
|
||||
});
|
||||
|
||||
it("stops its own session when the scope ends", async () => {
|
||||
const { client, room } = setup();
|
||||
const off = vi.spyOn(room, "off");
|
||||
const scope = new ObservableScope();
|
||||
createRTCSlot(scope, backendOf(client, room), options);
|
||||
|
||||
scope.end();
|
||||
await vi.waitFor(() =>
|
||||
expect(off).toHaveBeenCalledWith(
|
||||
RoomStickyEventsEvent.Update,
|
||||
expect.any(Function),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it("leaves a session it is given to its caller", () => {
|
||||
const { client, room, session } = setup();
|
||||
const given = session.asMockedSession();
|
||||
given.stop = vi.fn();
|
||||
const scope = new ObservableScope();
|
||||
createRTCSlot(scope, backendOf(client, room), options, given);
|
||||
|
||||
scope.end();
|
||||
expect(given.stop).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("has the session's statistics and sent call notifications", () => {
|
||||
const { client, room, session } = setup();
|
||||
const slot = createRTCSlot(
|
||||
testScope(),
|
||||
backendOf(client, room),
|
||||
options,
|
||||
session.asMockedSession(),
|
||||
);
|
||||
expect(slot.statistics).toBe(session.statistics);
|
||||
|
||||
const sent: unknown[] = [];
|
||||
slot.sentCallNotification$.subscribe((n) => sent.push(n));
|
||||
const notification = { event_id: "$notification" };
|
||||
session.emit(
|
||||
MatrixRTCSessionEvent.DidSendCallNotification,
|
||||
notification as Parameters<
|
||||
MatrixRTCSessionEventHandlerMap[MatrixRTCSessionEvent.DidSendCallNotification]
|
||||
>[0],
|
||||
);
|
||||
expect(sent).toEqual([notification]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("status$", () => {
|
||||
it("is undefined while the room has no slot event", () => {
|
||||
const { client, room } = setup();
|
||||
const slot = createRTCSlot(testScope(), client, room, options);
|
||||
const { client, room, session } = setup();
|
||||
const slot = createRTCSlot(
|
||||
testScope(),
|
||||
backendOf(client, room),
|
||||
options,
|
||||
session.asMockedSession(),
|
||||
);
|
||||
expect(slot.status$.value).toBeUndefined();
|
||||
});
|
||||
|
||||
it("follows the slot event", () => {
|
||||
const { client, room, session } = setup();
|
||||
session.rtcSlot = { status: "open" };
|
||||
const slot = createRTCSlot(testScope(), client, room, options);
|
||||
const slot = createRTCSlot(
|
||||
testScope(),
|
||||
backendOf(client, room),
|
||||
options,
|
||||
session.asMockedSession(),
|
||||
);
|
||||
expect(slot.status$.value).toBe("open");
|
||||
|
||||
session.rtcSlot = { status: "closed" };
|
||||
@@ -68,4 +196,69 @@ describe("createRTCSlot", () => {
|
||||
expect(slot.status$.value).toBe("closed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("join", () => {
|
||||
it("holds one participation at a time, and is free again once it has left", () => {
|
||||
const { client, room, session } = setup();
|
||||
const slot = createRTCSlot(
|
||||
testScope(),
|
||||
backendOf(
|
||||
{
|
||||
...client,
|
||||
getDomain: (): string => "example.org",
|
||||
getSyncState: (): SyncState => SyncState.Syncing,
|
||||
getRTCTransports: vi.fn().mockResolvedValue([]),
|
||||
} as unknown as MatrixClient,
|
||||
room,
|
||||
),
|
||||
options,
|
||||
session.asMockedSession(),
|
||||
);
|
||||
const joinOptions: RTCParticipationOptions = {
|
||||
publish: [],
|
||||
matrixRTCMode: MatrixRTCMode.Compatibility,
|
||||
backend: idleBackend,
|
||||
};
|
||||
expect(slot.participation$.value).toBeNull();
|
||||
|
||||
const participation = slot.join(joinOptions);
|
||||
expect(slot.participation$.value).toBe(participation);
|
||||
expect(participation.slot).toMatchObject({
|
||||
roomId: room.roomId,
|
||||
application: "m.call",
|
||||
id: "ROOM",
|
||||
});
|
||||
expect(() => slot.join(joinOptions)).toThrow(MatrixRTCError);
|
||||
|
||||
participation.leave();
|
||||
expect(slot.participation$.value).toBeNull();
|
||||
const again = slot.join(joinOptions);
|
||||
expect(slot.participation$.value).toBe(again);
|
||||
again.leave();
|
||||
});
|
||||
});
|
||||
|
||||
describe("members$", () => {
|
||||
it("keeps the member when its membership is sent again, with the new event id", () => {
|
||||
const { client, room, session } = setup();
|
||||
const first = mockRtcMembership("@bob:example.org", "BOB");
|
||||
session.memberships = [first];
|
||||
const slot = createRTCSlot(
|
||||
testScope(),
|
||||
backendOf(client, room),
|
||||
options,
|
||||
session.asMockedSession(),
|
||||
);
|
||||
const [bob] = slot.members$.value;
|
||||
expect(bob.matrixEventId$.value).toBe(first.eventId);
|
||||
|
||||
const resent = mockRtcMembership("@bob:example.org", "BOB");
|
||||
session.memberships = [resent];
|
||||
session.emit(MatrixRTCSessionEvent.MembershipsChanged, [first], [resent]);
|
||||
expect(slot.members$.value).toHaveLength(1);
|
||||
expect(slot.members$.value[0]).toBe(bob);
|
||||
expect(bob.matrixEventId$.value).toBe(resent.eventId);
|
||||
expect(resent.eventId).not.toBe(first.eventId);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
+124
-74
@@ -5,12 +5,14 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { type MatrixClient, type Room } from "matrix-js-sdk";
|
||||
import { type MatrixClient } from "matrix-js-sdk";
|
||||
import { EventType } from "matrix-js-sdk/lib/@types/event";
|
||||
import { type Logger, logger as rootLogger } from "matrix-js-sdk/lib/logger";
|
||||
import { logger as rootLogger } from "matrix-js-sdk/lib/logger";
|
||||
import {
|
||||
type MatrixRTCSession as JsSdkRTCSession,
|
||||
MatrixRTCSessionManager,
|
||||
type Statistics,
|
||||
MatrixRTCSession as JsMatrixRTCSession,
|
||||
MatrixRTCSessionEvent,
|
||||
type IRTCNotificationContent,
|
||||
type SlotDescription,
|
||||
} from "matrix-js-sdk/lib/matrixrtc";
|
||||
import { type MatrixEvent } from "matrix-js-sdk/lib/models/event";
|
||||
@@ -20,6 +22,7 @@ import {
|
||||
filter,
|
||||
fromEvent,
|
||||
map,
|
||||
type Observable,
|
||||
of,
|
||||
startWith,
|
||||
switchMap,
|
||||
@@ -28,6 +31,7 @@ import {
|
||||
import { ObservableScope } from "./reactive/ObservableScope";
|
||||
import { generateItems } from "./reactive/observable";
|
||||
import {
|
||||
type ParticipationSlot,
|
||||
type RTCMember,
|
||||
type RTCParticipation,
|
||||
type RTCParticipationOptions,
|
||||
@@ -50,33 +54,64 @@ import {
|
||||
membershipKeys,
|
||||
} from "./matrixrtc/Members";
|
||||
import { createTransportRegistry } from "./matrixrtc/Transports";
|
||||
import {
|
||||
type createSdkMatrixBackend,
|
||||
type SdkMatrixBackend,
|
||||
withEmitter,
|
||||
} from "./SdkMatrixBackend";
|
||||
|
||||
const ROOM_CALL_SLOT: SlotDescription = { application: "m.call", id: "ROOM" };
|
||||
|
||||
/**
|
||||
* Takes the whole `MatrixClient` rather than a slice of it, and finds the
|
||||
* MatrixRTC session itself. The js-sdk is the MatrixRTC implementation today;
|
||||
* when the rust-rtc crate replaces it, the SDK has to bridge the crate to the
|
||||
* js-sdk client, and only the SDK knows what that bridge needs. Holding the
|
||||
* client keeps that change inside the SDK.
|
||||
* The slot runs on a matrix-js-sdk session of its own, from the SDK's copy of
|
||||
* matrix-js-sdk rather than the client's, and stops it when the scope ends.
|
||||
*/
|
||||
export function createRTCSlot(
|
||||
scope: ObservableScope,
|
||||
client: MatrixClient,
|
||||
room: Room,
|
||||
backend: SdkMatrixBackend,
|
||||
options: RTCSlotOptions,
|
||||
): RTCSlot {
|
||||
/**
|
||||
* @deprecated A session the caller owns and stops, in place of the slot's
|
||||
* own; `options.slotDescription` is then the session's. Only for the
|
||||
* standalone app, which still takes its session from its client's session
|
||||
* manager.
|
||||
*/
|
||||
externalJsSdkSession?: JsMatrixRTCSession,
|
||||
): RTCSlot & {
|
||||
// STOP GAP: This should be its own external machine. It is call
|
||||
// specific and should not live inside the sdk/rtc-slot.
|
||||
// We only put it here today, to make sure the rtcSession is fully
|
||||
// hidden inside the sdk.
|
||||
// Next step. disable sending call notificaitons in the sdk, write a new
|
||||
// notification sender in EC directly on client + room.
|
||||
sentCallNotification$: Observable<
|
||||
{
|
||||
event_id: string;
|
||||
} & IRTCNotificationContent
|
||||
>;
|
||||
// STOP GAP: the same as above. Has to live here. but should become a native
|
||||
// SDK propery independent of the rtcSession
|
||||
statistics: Statistics;
|
||||
} {
|
||||
// STOP GAP: the slot is still written against a client and a room. Both
|
||||
// are refactored along with the backend.
|
||||
const client = withEmitter(backend, backend.clientEmitter);
|
||||
const room = withEmitter(backend, backend.roomEmitter);
|
||||
const logger = rootLogger.getChild("[RTCSlot]");
|
||||
const userId = client.getUserId();
|
||||
const deviceId = client.getDeviceId();
|
||||
const roomId = room.roomId;
|
||||
if (!(userId && deviceId))
|
||||
throw new MatrixRTCError("The client has to be logged in");
|
||||
const { application = "m.call", id = "ROOM" } = options;
|
||||
|
||||
const jsSdkSession = sessionManager(
|
||||
scope,
|
||||
client,
|
||||
{ application, id },
|
||||
logger,
|
||||
).getRoomSession(room);
|
||||
const jsSdkSession =
|
||||
externalJsSdkSession ??
|
||||
createJsSdkSession(
|
||||
scope,
|
||||
client,
|
||||
room,
|
||||
options.slotDescription ?? ROOM_CALL_SLOT,
|
||||
);
|
||||
const memberships$ = createMemberships$(scope, jsSdkSession);
|
||||
|
||||
const active$ = new BehaviorSubject<ParticipationInternals | null>(null);
|
||||
@@ -126,70 +161,85 @@ export function createRTCSlot(
|
||||
),
|
||||
);
|
||||
|
||||
const slot: RTCSlot = {
|
||||
roomId: room.roomId,
|
||||
application,
|
||||
id,
|
||||
const participationSlot: ParticipationSlot = {
|
||||
roomId,
|
||||
status$,
|
||||
members$,
|
||||
...jsSdkSession.slotDescription,
|
||||
};
|
||||
|
||||
const join = (
|
||||
participationOptions: RTCParticipationOptions,
|
||||
): RTCParticipation => {
|
||||
if (active$.value !== null)
|
||||
throw new MatrixRTCError(
|
||||
"Already in this slot: leave the participation before joining again",
|
||||
);
|
||||
const participationScope = new ObservableScope();
|
||||
participationScopes.add(participationScope);
|
||||
const internals = createRTCParticipation(
|
||||
participationScope,
|
||||
{
|
||||
client,
|
||||
slot: participationSlot,
|
||||
jsSdkSession,
|
||||
transports,
|
||||
slotOptions: options,
|
||||
logger,
|
||||
},
|
||||
participationOptions,
|
||||
);
|
||||
participationScope.onEnd(() => {
|
||||
participationScopes.delete(participationScope);
|
||||
if (active$.value === internals) active$.next(null);
|
||||
});
|
||||
active$.next(internals);
|
||||
return internals.participation;
|
||||
};
|
||||
|
||||
const slot = {
|
||||
join,
|
||||
participation$: scope.behavior(
|
||||
active$.pipe(map((active) => active?.participation ?? null)),
|
||||
),
|
||||
join: (participationOptions: RTCParticipationOptions): RTCParticipation => {
|
||||
if (active$.value !== null)
|
||||
throw new MatrixRTCError(
|
||||
"Already in this slot: leave the participation before joining again",
|
||||
);
|
||||
const participationScope = new ObservableScope();
|
||||
participationScopes.add(participationScope);
|
||||
const internals = createRTCParticipation(
|
||||
participationScope,
|
||||
{
|
||||
client,
|
||||
room,
|
||||
slot,
|
||||
jsSdkSession,
|
||||
members$,
|
||||
transports,
|
||||
slotOptions: options,
|
||||
logger,
|
||||
},
|
||||
participationOptions,
|
||||
);
|
||||
participationScope.onEnd(() => {
|
||||
participationScopes.delete(participationScope);
|
||||
if (active$.value === internals) active$.next(null);
|
||||
});
|
||||
active$.next(internals);
|
||||
return internals.participation;
|
||||
},
|
||||
...participationSlot,
|
||||
};
|
||||
return slot;
|
||||
|
||||
return {
|
||||
...slot,
|
||||
sentCallNotification$: fromEvent(
|
||||
jsSdkSession,
|
||||
MatrixRTCSessionEvent.DidSendCallNotification,
|
||||
(notification: { event_id: string } & IRTCNotificationContent) =>
|
||||
notification,
|
||||
),
|
||||
statistics: jsSdkSession.statistics,
|
||||
};
|
||||
}
|
||||
|
||||
function createJsSdkSession(
|
||||
scope: ObservableScope,
|
||||
client: Pick<
|
||||
MatrixClient,
|
||||
keyof Parameters<typeof createSdkMatrixBackend>[0]
|
||||
>,
|
||||
room: ConstructorParameters<typeof JsMatrixRTCSession>[1],
|
||||
slotDescription: SlotDescription,
|
||||
): JsMatrixRTCSession {
|
||||
const session = new JsMatrixRTCSession(
|
||||
// The session's type also asks for `cancelPendingEvent`,
|
||||
// `_unstable_updateDelayedEvent` and `decryptEventIfNeeded`, which it
|
||||
// never calls
|
||||
client as ConstructorParameters<typeof JsMatrixRTCSession>[0],
|
||||
room,
|
||||
slotDescription,
|
||||
);
|
||||
scope.onEnd(() => void session.stop());
|
||||
return session;
|
||||
}
|
||||
|
||||
function slotStatus(
|
||||
session: Pick<JsSdkRTCSession, "getRtcSlot">,
|
||||
session: Pick<JsMatrixRTCSession, "getRtcSlot">,
|
||||
): "open" | "closed" | undefined {
|
||||
return session.getRtcSlot()?.status;
|
||||
}
|
||||
|
||||
/**
|
||||
* The js-sdk keeps one session manager per slot. The client comes with the
|
||||
* manager for the default slot; any other slot gets a manager of its own,
|
||||
* which lives as long as the scope.
|
||||
*/
|
||||
function sessionManager(
|
||||
scope: ObservableScope,
|
||||
client: MatrixClient,
|
||||
{ application, id }: SlotDescription,
|
||||
logger: Logger,
|
||||
): MatrixRTCSessionManager {
|
||||
if (application === "m.call" && id === "ROOM") return client.matrixRTC;
|
||||
const manager = new MatrixRTCSessionManager(logger, client, {
|
||||
application,
|
||||
id,
|
||||
});
|
||||
manager.start();
|
||||
scope.onEnd(() => manager.stop());
|
||||
return manager;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
ClientEvent,
|
||||
createClient,
|
||||
type MatrixClient,
|
||||
Room,
|
||||
RoomEvent,
|
||||
SyncState,
|
||||
} from "matrix-js-sdk";
|
||||
|
||||
import { createSdkMatrixBackend, withEmitter } from "./SdkMatrixBackend";
|
||||
|
||||
describe("createSdkMatrixBackend", () => {
|
||||
it("calls each member on the client or the room it came from", () => {
|
||||
const { client, room } = setup();
|
||||
const backend = createSdkMatrixBackend(client, room);
|
||||
|
||||
expect(backend.getUserId()).toBe("@alice:example.org");
|
||||
expect(backend.roomId).toBe("!room:example.org");
|
||||
expect(backend.getVersion()).toBe(room.getVersion());
|
||||
});
|
||||
|
||||
it("keeps the client's and the room's events apart", () => {
|
||||
const { client, room } = setup();
|
||||
const backend = createSdkMatrixBackend(client, room);
|
||||
const onClient = vi.fn();
|
||||
const onRoom = vi.fn();
|
||||
backend.clientEmitter.on(ClientEvent.Sync, onClient);
|
||||
backend.roomEmitter.on(RoomEvent.Name, onRoom);
|
||||
|
||||
client.emit(ClientEvent.Sync, SyncState.Syncing, null);
|
||||
expect(onClient).toHaveBeenCalledOnce();
|
||||
expect(onRoom).not.toHaveBeenCalled();
|
||||
|
||||
room.emit(RoomEvent.Name, room);
|
||||
expect(onRoom).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
describe("withEmitter", () => {
|
||||
it("is the backend with one side's events", () => {
|
||||
const { client, room } = setup();
|
||||
const backend = createSdkMatrixBackend(client, room);
|
||||
const asRoom = withEmitter(backend, backend.roomEmitter);
|
||||
const listener = vi.fn();
|
||||
|
||||
asRoom.on(RoomEvent.Name, listener);
|
||||
room.emit(RoomEvent.Name, room);
|
||||
|
||||
expect(listener).toHaveBeenCalledOnce();
|
||||
expect(asRoom.getUserId()).toBe("@alice:example.org");
|
||||
});
|
||||
|
||||
it("reads the backend's getters through", () => {
|
||||
const { room } = setup();
|
||||
const asRoom = withEmitter(
|
||||
{
|
||||
get name() {
|
||||
return room.name;
|
||||
},
|
||||
},
|
||||
room,
|
||||
);
|
||||
|
||||
room.name = "Renamed";
|
||||
expect(asRoom.name).toBe("Renamed");
|
||||
});
|
||||
});
|
||||
|
||||
function setup(): { client: MatrixClient; room: Room } {
|
||||
const client = createClient({
|
||||
baseUrl: "https://matrix.example.org",
|
||||
userId: "@alice:example.org",
|
||||
deviceId: "DEVICE",
|
||||
});
|
||||
const room = new Room("!room:example.org", client, "@alice:example.org");
|
||||
return { client, room };
|
||||
}
|
||||
@@ -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 { type MatrixClient, type Room } from "matrix-js-sdk";
|
||||
|
||||
/** What the SDK needs of the client. */
|
||||
type SdkClientPart = Pick<
|
||||
MatrixClient,
|
||||
// Our own membership identity
|
||||
| "getUserId"
|
||||
| "getDeviceId"
|
||||
// The session: memberships, delayed leave events, sticky events, call
|
||||
// notifications, and the media keys sent to device
|
||||
| "fetchCapabilities"
|
||||
| "getCachedCapabilities"
|
||||
| "sendEvent"
|
||||
| "sendStateEvent"
|
||||
| "_unstable_sendDelayedStateEvent"
|
||||
| "_unstable_cancelScheduledDelayedEvent"
|
||||
| "_unstable_restartScheduledDelayedEvent"
|
||||
| "_unstable_sendScheduledDelayedEvent"
|
||||
| "_unstable_sendStickyEvent"
|
||||
| "_unstable_sendStickyDelayedEvent"
|
||||
| "encryptAndSendToDevice"
|
||||
// Local transport discovery
|
||||
| "getDomain"
|
||||
| "getRTCTransports"
|
||||
// LiveKit auth: `getOpenIdToken` for the JWT service flow, `getLivekitToken`
|
||||
// for the client-server API flow (MSC4195), `delegateDelayedLeave` and
|
||||
// `baseUrl` for the delayed leave delegation and its probe
|
||||
| "getOpenIdToken"
|
||||
| "getLivekitToken"
|
||||
| "delegateDelayedLeave"
|
||||
| "baseUrl"
|
||||
// Homeserver connection: whether the client is syncing
|
||||
| "getSyncState"
|
||||
>;
|
||||
|
||||
/** What the SDK needs of the room. */
|
||||
type SdkRoomPart = Pick<
|
||||
Room,
|
||||
| "roomId"
|
||||
// The members' display names and avatars
|
||||
| "getMembersWithMembership"
|
||||
// The session: memberships from the room's state, timeline and sticky events
|
||||
| "getLiveTimeline"
|
||||
| "getVersion"
|
||||
| "hasMembershipState"
|
||||
| "_unstable_getStickyEvents"
|
||||
>;
|
||||
|
||||
/**
|
||||
* STOP GAP: what the SDK needs of a Matrix client and room, on one object.
|
||||
* Only their emitters stay apart, since both have an `on` and an `off`. It is
|
||||
* to converge, along with the SDK that takes it, on whichever API fits every
|
||||
* layer best.
|
||||
*/
|
||||
export interface SdkMatrixBackend extends SdkClientPart, SdkRoomPart {
|
||||
/**
|
||||
* `ClientEvent.Sync` (homeserver connection) and `ClientEvent.ToDeviceEvent`
|
||||
* (the session's media keys)
|
||||
*/
|
||||
clientEmitter: Pick<MatrixClient, "on" | "off">;
|
||||
/** The room's state, member and sticky events */
|
||||
roomEmitter: Pick<Room, "on" | "off">;
|
||||
}
|
||||
|
||||
/** The SDK's backend from a client and a room. */
|
||||
export function createSdkMatrixBackend(
|
||||
client: SdkClientPart & Pick<MatrixClient, "on" | "off">,
|
||||
room: SdkRoomPart & Pick<Room, "on" | "off">,
|
||||
): SdkMatrixBackend {
|
||||
return {
|
||||
getUserId: client.getUserId.bind(client),
|
||||
getDeviceId: client.getDeviceId.bind(client),
|
||||
fetchCapabilities: client.fetchCapabilities.bind(client),
|
||||
getCachedCapabilities: client.getCachedCapabilities.bind(client),
|
||||
sendEvent: client.sendEvent.bind(client),
|
||||
sendStateEvent: client.sendStateEvent.bind(client),
|
||||
_unstable_sendDelayedStateEvent:
|
||||
client._unstable_sendDelayedStateEvent.bind(client),
|
||||
_unstable_cancelScheduledDelayedEvent:
|
||||
client._unstable_cancelScheduledDelayedEvent.bind(client),
|
||||
_unstable_restartScheduledDelayedEvent:
|
||||
client._unstable_restartScheduledDelayedEvent.bind(client),
|
||||
_unstable_sendScheduledDelayedEvent:
|
||||
client._unstable_sendScheduledDelayedEvent.bind(client),
|
||||
_unstable_sendStickyEvent: client._unstable_sendStickyEvent.bind(client),
|
||||
_unstable_sendStickyDelayedEvent:
|
||||
client._unstable_sendStickyDelayedEvent.bind(client),
|
||||
encryptAndSendToDevice: client.encryptAndSendToDevice.bind(client),
|
||||
getDomain: client.getDomain.bind(client),
|
||||
getRTCTransports: client.getRTCTransports.bind(client),
|
||||
getOpenIdToken: client.getOpenIdToken.bind(client),
|
||||
getLivekitToken: client.getLivekitToken.bind(client),
|
||||
delegateDelayedLeave: client.delegateDelayedLeave.bind(client),
|
||||
baseUrl: client.baseUrl,
|
||||
getSyncState: client.getSyncState.bind(client),
|
||||
roomId: room.roomId,
|
||||
getMembersWithMembership: room.getMembersWithMembership.bind(room),
|
||||
getLiveTimeline: room.getLiveTimeline.bind(room),
|
||||
getVersion: room.getVersion.bind(room),
|
||||
hasMembershipState: room.hasMembershipState.bind(room),
|
||||
_unstable_getStickyEvents: room._unstable_getStickyEvents.bind(room),
|
||||
clientEmitter: client,
|
||||
roomEmitter: room,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* STOP GAP: the backend as the client (or the room) code written against one
|
||||
* still expects, with that side's `on` and `off`.
|
||||
*/
|
||||
export function withEmitter<
|
||||
Backend extends object,
|
||||
Emitter extends {
|
||||
on: (...args: never[]) => unknown;
|
||||
off: (...args: never[]) => unknown;
|
||||
},
|
||||
>(backend: Backend, emitter: Emitter): Backend & Pick<Emitter, "on" | "off"> {
|
||||
return Object.defineProperties<object>(
|
||||
{ on: emitter.on.bind(emitter), off: emitter.off.bind(emitter) },
|
||||
Object.getOwnPropertyDescriptors(backend),
|
||||
) as Backend & Pick<Emitter, "on" | "off">;
|
||||
}
|
||||
+31
-11
@@ -12,7 +12,9 @@ Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import {
|
||||
type RTCCallIntent,
|
||||
type RTCNotificationType,
|
||||
type SlotDescription,
|
||||
type Transport,
|
||||
} from "matrix-js-sdk/lib/matrixrtc";
|
||||
import { type Observable } from "rxjs";
|
||||
@@ -42,13 +44,9 @@ export { MatrixRTCError } from "./errors";
|
||||
// Slot
|
||||
|
||||
export interface RTCSlotOptions {
|
||||
/** The application the slot belongs to, as named in the membership. Default `m.call`. */
|
||||
application?: string;
|
||||
/** The application's slot in the room. Default `ROOM`. */
|
||||
id?: string;
|
||||
/** How memberships and keys in this slot are written. Resolved by the host. */
|
||||
matrixRTCMode: MatrixRTCMode;
|
||||
encryptionSystem: EncryptionSystem;
|
||||
/** Which slot of the room to join. Defaults to the room's call, `m.call#ROOM`. */
|
||||
slotDescription?: SlotDescription;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -80,6 +78,12 @@ export interface RTCSlot {
|
||||
join(options: RTCParticipationOptions): RTCParticipation; // Maybe MediaSession,
|
||||
}
|
||||
|
||||
/**
|
||||
* The slot as its participation sees it: members, status and identity, without
|
||||
* `join` and `participation$`, which belong to whoever joins.
|
||||
*/
|
||||
export type ParticipationSlot = Omit<RTCSlot, "join" | "participation$">;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Participation
|
||||
|
||||
@@ -94,6 +98,12 @@ export interface RTCParticipationOptions {
|
||||
* before the first connection exists.
|
||||
*/
|
||||
publish: PublishRequest[] | LocalMedia;
|
||||
/**
|
||||
* How our membership and keys are written: the member id and whether the
|
||||
* membership is a sticky event. Resolved by the host. Others' memberships
|
||||
* are read whatever their mode.
|
||||
*/
|
||||
matrixRTCMode: MatrixRTCMode;
|
||||
/**
|
||||
* LEGACY
|
||||
*
|
||||
@@ -103,11 +113,14 @@ export interface RTCParticipationOptions {
|
||||
* to a notification (ringing, timeouts, declines) is the application's job.
|
||||
*/
|
||||
sendNotificationType?: RTCNotificationType;
|
||||
/**
|
||||
* The kind of call the local member intends to take part in: `"m.audio"`
|
||||
* or `"m.video"`. Carried by the membership as a field of its own.
|
||||
*/
|
||||
callIntent?: RTCCallIntent;
|
||||
/**
|
||||
* Whatever the application wants to say about itself in the membership,
|
||||
* under namespaced keys. Opaque to the SDK, apart from `m.call.intent`
|
||||
* (`"audio"` or `"video"`), which the membership format carries as a
|
||||
* field of its own.
|
||||
* under namespaced keys. Opaque to the SDK.
|
||||
*/
|
||||
applicationData?: Record<string, unknown>;
|
||||
/** Timings the host has configured; the defaults otherwise. */
|
||||
@@ -162,7 +175,8 @@ export type ParticipationState =
|
||||
|
||||
/** The span between our `join()` of a slot and our `leave()`. */
|
||||
export interface RTCParticipation {
|
||||
readonly slot: RTCSlot;
|
||||
/** Required slot information (no `join` fn and `participation`) */
|
||||
readonly slot: ParticipationSlot;
|
||||
/** Sends the leave, tears the connections down and ends the participation. */
|
||||
leave(): void;
|
||||
state$: Behavior<ParticipationState>;
|
||||
@@ -285,9 +299,15 @@ export interface RTCMember {
|
||||
deviceId: string;
|
||||
/** The membership's own id; what the Matrix 2.0 identity is derived from. */
|
||||
memberId: string;
|
||||
/**
|
||||
* The Matrix event currently carrying the membership, which events about
|
||||
* it (reactions, raised hands) relate to. Changes when the membership is
|
||||
* sent again while the member stays the same.
|
||||
*/
|
||||
matrixEventId$: Behavior<string>;
|
||||
/** Which transport this member is on; undefined when the membership has none. */
|
||||
transport$: Behavior<TransportMetadata | undefined>;
|
||||
/** What the member's application says about itself, e.g. `m.call.intent`. */
|
||||
/** What the member's application says about itself, e.g. `intent`. */
|
||||
applicationData$: Behavior<Record<string, unknown>>;
|
||||
|
||||
displayName$: Behavior<string>;
|
||||
|
||||
@@ -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 },
|
||||
];
|
||||
|
||||
@@ -8,7 +8,7 @@ Please see LICENSE in the repository root for full details.
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from "vitest";
|
||||
import { EventEmitter } from "events";
|
||||
import { ClientEvent, SyncState } from "matrix-js-sdk";
|
||||
import { ClientEvent, type MatrixClient, SyncState } from "matrix-js-sdk";
|
||||
import { MembershipManagerEvent, Status } from "matrix-js-sdk/lib/matrixrtc";
|
||||
|
||||
import { ObservableScope } from "../reactive/ObservableScope";
|
||||
@@ -20,7 +20,7 @@ import { testScope, withTestScheduler } from "../utils/test";
|
||||
```
|
||||
createHomeserverConnected$(
|
||||
scope: ObservableScope,
|
||||
client: NodeStyleEventEmitter & Pick<MatrixClient, "getSyncState">,
|
||||
client: Pick<MatrixClient, "getSyncState" | "on" | "off">,
|
||||
matrixRTCSession: NodeStyleEventEmitter &
|
||||
Pick<MatrixRTCSession, "membershipStatus" | "probablyLeft">,
|
||||
)
|
||||
@@ -34,12 +34,15 @@ class MockMatrixClient extends EventEmitter {
|
||||
}
|
||||
public setSyncState(state: SyncState): void {
|
||||
this.syncState = state;
|
||||
// Matrix's Sync event in createHomeserverConnected$ expects [SyncState]
|
||||
this.emit(ClientEvent.Sync, [state]);
|
||||
this.emit(ClientEvent.Sync, state);
|
||||
}
|
||||
public getSyncState(): SyncState {
|
||||
return this.syncState;
|
||||
}
|
||||
/** `MatrixClient`'s `on`/`off` return the client itself, which no mock is. */
|
||||
public get asClient(): Pick<MatrixClient, "getSyncState" | "on" | "off"> {
|
||||
return this as unknown as Pick<MatrixClient, "getSyncState" | "on" | "off">;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -47,7 +50,7 @@ class MockMatrixClient extends EventEmitter {
|
||||
```
|
||||
createHomeserverConnected$(
|
||||
scope: ObservableScope,
|
||||
client: NodeStyleEventEmitter & Pick<MatrixClient, "getSyncState">,
|
||||
client: Pick<MatrixClient, "getSyncState" | "on" | "off">,
|
||||
matrixRTCSession: NodeStyleEventEmitter &
|
||||
Pick<MatrixRTCSession, "membershipStatus" | "probablyLeft">,
|
||||
)
|
||||
@@ -99,18 +102,33 @@ describe("createHomeserverConnected$", () => {
|
||||
// easy enough to read them so I think they can stay.
|
||||
// Note: gracePeriodMs is set to 0 to avoid debouncing delays in tests
|
||||
it("reports syncing reason when sync state is not Syncing", () => {
|
||||
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
|
||||
const hsConnected = createHomeserverConnected$(
|
||||
scope,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
expect(hsConnected.disconnectReason$.value).toEqual("sync");
|
||||
});
|
||||
|
||||
it("reports membership reason when sync is Syncing but membership is not Connected", () => {
|
||||
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
|
||||
const hsConnected = createHomeserverConnected$(
|
||||
scope,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
client.setSyncState(SyncState.Syncing);
|
||||
expect(hsConnected.disconnectReason$.value).toEqual("membership");
|
||||
});
|
||||
|
||||
it("reports probablyLeft reason when membership transitions to Connected but ProbablyLeft is true", () => {
|
||||
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
|
||||
const hsConnected = createHomeserverConnected$(
|
||||
scope,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
// Make sync loop OK
|
||||
client.setSyncState(SyncState.Syncing);
|
||||
// Indicate probable leave before connection
|
||||
@@ -120,7 +138,12 @@ describe("createHomeserverConnected$", () => {
|
||||
});
|
||||
|
||||
it("becomes null (connected) only when all three conditions are satisfied", () => {
|
||||
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
|
||||
const hsConnected = createHomeserverConnected$(
|
||||
scope,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
// 1. Sync loop connected
|
||||
client.setSyncState(SyncState.Syncing);
|
||||
expect(hsConnected.disconnectReason$.value).toEqual("membership"); // not yet membership connected
|
||||
@@ -130,7 +153,12 @@ describe("createHomeserverConnected$", () => {
|
||||
});
|
||||
|
||||
it("returns syncing reason when sync loop leaves Syncing", () => {
|
||||
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
|
||||
const hsConnected = createHomeserverConnected$(
|
||||
scope,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
// Reach connected state
|
||||
client.setSyncState(SyncState.Syncing);
|
||||
session.setMembershipStatus(Status.Connected);
|
||||
@@ -142,7 +170,12 @@ describe("createHomeserverConnected$", () => {
|
||||
});
|
||||
|
||||
it("returns membershipConnected reason when membership status becomes disconnected", () => {
|
||||
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
|
||||
const hsConnected = createHomeserverConnected$(
|
||||
scope,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
client.setSyncState(SyncState.Syncing);
|
||||
session.setMembershipStatus(Status.Connected);
|
||||
expect(hsConnected.disconnectReason$.value).toEqual(null);
|
||||
@@ -152,7 +185,12 @@ describe("createHomeserverConnected$", () => {
|
||||
});
|
||||
|
||||
it("returns certainlyConnected reason when ProbablyLeft is emitted", () => {
|
||||
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
|
||||
const hsConnected = createHomeserverConnected$(
|
||||
scope,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
client.setSyncState(SyncState.Syncing);
|
||||
session.setMembershipStatus(Status.Connected);
|
||||
expect(hsConnected.disconnectReason$.value).toEqual(null);
|
||||
@@ -162,7 +200,12 @@ describe("createHomeserverConnected$", () => {
|
||||
});
|
||||
|
||||
it("recovers to null (connected) if ProbablyLeft becomes false again while other conditions remain true", () => {
|
||||
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
|
||||
const hsConnected = createHomeserverConnected$(
|
||||
scope,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
client.setSyncState(SyncState.Syncing);
|
||||
session.setMembershipStatus(Status.Connected);
|
||||
expect(hsConnected.disconnectReason$.value).toEqual(null);
|
||||
@@ -176,7 +219,12 @@ describe("createHomeserverConnected$", () => {
|
||||
});
|
||||
|
||||
it("composite sequence reflects each individual failure reason", () => {
|
||||
const hsConnected = createHomeserverConnected$(scope, client, session, 0);
|
||||
const hsConnected = createHomeserverConnected$(
|
||||
scope,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
|
||||
// Initially: sync error + membership disconnected → syncing wins (highest priority)
|
||||
expect(hsConnected.disconnectReason$.value).toEqual("sync");
|
||||
@@ -225,7 +273,7 @@ describe("createHomeserverConnected$ - disconnectReason$ reason values", () => {
|
||||
it("is null when all three conditions are satisfied", () => {
|
||||
const { disconnectReason$ } = createHomeserverConnected$(
|
||||
scope,
|
||||
client,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
@@ -237,7 +285,7 @@ describe("createHomeserverConnected$ - disconnectReason$ reason values", () => {
|
||||
it("reports syncing when sync loop is not Syncing", () => {
|
||||
const { disconnectReason$ } = createHomeserverConnected$(
|
||||
scope,
|
||||
client,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
@@ -248,7 +296,7 @@ describe("createHomeserverConnected$ - disconnectReason$ reason values", () => {
|
||||
it("reports membershipConnected when sync is fine but membership is not Connected", () => {
|
||||
const { disconnectReason$ } = createHomeserverConnected$(
|
||||
scope,
|
||||
client,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
@@ -260,7 +308,7 @@ describe("createHomeserverConnected$ - disconnectReason$ reason values", () => {
|
||||
it("reports certainlyConnected when probablyLeft is true", () => {
|
||||
const { disconnectReason$ } = createHomeserverConnected$(
|
||||
scope,
|
||||
client,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
@@ -273,7 +321,7 @@ describe("createHomeserverConnected$ - disconnectReason$ reason values", () => {
|
||||
it("prioritises syncing over membershipConnected when both fail", () => {
|
||||
const { disconnectReason$ } = createHomeserverConnected$(
|
||||
scope,
|
||||
client,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
@@ -284,7 +332,7 @@ describe("createHomeserverConnected$ - disconnectReason$ reason values", () => {
|
||||
it("updates reason as conditions change", () => {
|
||||
const { disconnectReason$ } = createHomeserverConnected$(
|
||||
scope,
|
||||
client,
|
||||
client.asClient,
|
||||
session,
|
||||
0,
|
||||
);
|
||||
@@ -329,7 +377,7 @@ describe("createHomeserverConnected$ - Grace Period", () => {
|
||||
});
|
||||
const hsConnected = createHomeserverConnected$(
|
||||
testScope(),
|
||||
client,
|
||||
client.asClient,
|
||||
session,
|
||||
GRACE_PERIOD,
|
||||
);
|
||||
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
startWith,
|
||||
map,
|
||||
tap,
|
||||
type Observable,
|
||||
distinctUntilChanged,
|
||||
switchMap,
|
||||
of,
|
||||
@@ -61,7 +60,15 @@ export interface HomeserverConnected {
|
||||
*/
|
||||
export function createHomeserverConnected$(
|
||||
scope: ObservableScope,
|
||||
client: NodeStyleEventEmitter & Pick<MatrixClient, "getSyncState">,
|
||||
client: Pick<
|
||||
MatrixClient,
|
||||
// Whether the client is syncing
|
||||
| "getSyncState"
|
||||
// `on`/`off`, to listen for:
|
||||
// - `ClientEvent.Sync`
|
||||
| "on"
|
||||
| "off"
|
||||
>,
|
||||
matrixRTCSession: NodeStyleEventEmitter &
|
||||
Pick<MatrixRTCSession, "membershipStatus" | "probablyLeft">,
|
||||
gracePeriodMs?: number,
|
||||
@@ -71,11 +78,13 @@ export function createHomeserverConnected$(
|
||||
const graceMs =
|
||||
gracePeriodMs ?? defaultSessionTimings.syncDisconnectGracePeriodMs;
|
||||
|
||||
const syncing$ = (
|
||||
fromEvent(client, ClientEvent.Sync) as Observable<[SyncState]>
|
||||
const syncing$ = fromEvent(
|
||||
client,
|
||||
ClientEvent.Sync,
|
||||
(state: SyncState) => state,
|
||||
).pipe(
|
||||
startWith([client.getSyncState()]),
|
||||
map(([state]) => state === SyncState.Syncing),
|
||||
startWith(client.getSyncState()),
|
||||
map((state) => state === SyncState.Syncing),
|
||||
distinctUntilChanged(),
|
||||
switchMap((isSyncing) => {
|
||||
if (isSyncing || graceMs <= 0) {
|
||||
|
||||
@@ -31,7 +31,7 @@ function client(
|
||||
): Parameters<typeof discoverLocalTransport>[0] {
|
||||
return {
|
||||
getDomain: () => "example.org",
|
||||
_unstable_getRTCTransports: vi.fn().mockResolvedValue(advertised),
|
||||
getRTCTransports: vi.fn().mockResolvedValue(advertised),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ describe("discoverLocalTransport", () => {
|
||||
logger,
|
||||
),
|
||||
).resolves.toBe(hostTransport);
|
||||
expect(c._unstable_getRTCTransports).not.toHaveBeenCalled();
|
||||
expect(c.getRTCTransports).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("prefers the homeserver's transport over the host's fallback", async () => {
|
||||
|
||||
@@ -22,7 +22,7 @@ import { TransportAutoDiscovery } from "./TransportAutoDiscovery";
|
||||
* @throws {MatrixRTCTransportMissingError} where none of these exists.
|
||||
*/
|
||||
export async function discoverLocalTransport(
|
||||
client: Pick<MatrixClient, "getDomain" | "_unstable_getRTCTransports">,
|
||||
client: Pick<MatrixClient, "getDomain" | "getRTCTransports">,
|
||||
transportTypes: readonly string[],
|
||||
{
|
||||
transport: override,
|
||||
|
||||
@@ -23,7 +23,9 @@ export type RoomMemberMap = Map<
|
||||
string,
|
||||
Pick<RoomMember, "userId" | "getMxcAvatarUrl" | "rawDisplayName">
|
||||
>;
|
||||
export function roomToMembersMap(matrixRoom: MatrixRoom): RoomMemberMap {
|
||||
export function roomToMembersMap(
|
||||
matrixRoom: Pick<MatrixRoom, "getMembersWithMembership">,
|
||||
): RoomMemberMap {
|
||||
const members = matrixRoom
|
||||
.getMembersWithMembership(KnownMembership.Join)
|
||||
.concat(matrixRoom.getMembersWithMembership(KnownMembership.Invite));
|
||||
@@ -37,9 +39,10 @@ export function roomToMembersMap(matrixRoom: MatrixRoom): RoomMemberMap {
|
||||
}, new Map());
|
||||
}
|
||||
|
||||
/** Listens for `RoomStateEvent.Members` on the room. */
|
||||
export function createRoomMembers$(
|
||||
scope: ObservableScope,
|
||||
matrixRoom: MatrixRoom,
|
||||
matrixRoom: Pick<MatrixRoom, "getMembersWithMembership" | "on" | "off">,
|
||||
): Behavior<RoomMemberMap> {
|
||||
return scope.behavior(
|
||||
fromEvent(matrixRoom, RoomStateEvent.Members).pipe(
|
||||
|
||||
@@ -57,6 +57,12 @@ export function createRTCMember(
|
||||
userId,
|
||||
deviceId,
|
||||
memberId,
|
||||
matrixEventId$: scope.behavior(
|
||||
membership$.pipe(
|
||||
map((membership) => membership.eventId),
|
||||
distinctUntilChanged(),
|
||||
),
|
||||
),
|
||||
displayName$: scope.behavior(
|
||||
metadata
|
||||
.createDisplayNameBehavior$(scope, userId)
|
||||
|
||||
@@ -36,11 +36,7 @@ const configTransport: Transport = {
|
||||
|
||||
function makeClient(): MockedObject<DiscoveryClient> {
|
||||
return {
|
||||
getDomain: vi.fn().mockReturnValue("example.org"),
|
||||
baseUrl: "https://matrix.example.org",
|
||||
_unstable_getRTCTransports: vi.fn().mockResolvedValue([]),
|
||||
getOpenIdToken: vi.fn(),
|
||||
getDeviceId: vi.fn(),
|
||||
getRTCTransports: vi.fn().mockResolvedValue([]),
|
||||
} as unknown as MockedObject<DiscoveryClient>;
|
||||
}
|
||||
|
||||
@@ -57,7 +53,7 @@ describe("TransportAutoDiscovery", () => {
|
||||
"prefers backend transport other app config $transports",
|
||||
async ({ transports }) => {
|
||||
const client = makeClient();
|
||||
client._unstable_getRTCTransports.mockResolvedValue(transports);
|
||||
client.getRTCTransports.mockResolvedValue(transports);
|
||||
|
||||
const discovery = new TransportAutoDiscovery({
|
||||
client,
|
||||
@@ -71,7 +67,7 @@ describe("TransportAutoDiscovery", () => {
|
||||
expect(discoveredTransport).toStrictEqual(backendTransport);
|
||||
expect(discoveredTransport).not.toStrictEqual(configTransport);
|
||||
|
||||
expect(client._unstable_getRTCTransports).toHaveBeenCalledTimes(1);
|
||||
expect(client.getRTCTransports).toHaveBeenCalledTimes(1);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -81,10 +77,7 @@ describe("TransportAutoDiscovery", () => {
|
||||
url: "wss://sfu.example.org",
|
||||
};
|
||||
const client = makeClient();
|
||||
client._unstable_getRTCTransports.mockResolvedValue([
|
||||
backendTransport,
|
||||
mLivekit,
|
||||
]);
|
||||
client.getRTCTransports.mockResolvedValue([backendTransport, mLivekit]);
|
||||
|
||||
const discovery = new TransportAutoDiscovery({
|
||||
client,
|
||||
@@ -100,7 +93,7 @@ describe("TransportAutoDiscovery", () => {
|
||||
|
||||
it("Retries limit_exceeded backend transport", async () => {
|
||||
const client = makeClient();
|
||||
client._unstable_getRTCTransports
|
||||
client.getRTCTransports
|
||||
.mockRejectedValueOnce(
|
||||
new MatrixError(
|
||||
{
|
||||
@@ -124,7 +117,7 @@ describe("TransportAutoDiscovery", () => {
|
||||
backendTransport,
|
||||
);
|
||||
|
||||
expect(client._unstable_getRTCTransports).toHaveBeenCalledTimes(2);
|
||||
expect(client.getRTCTransports).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
const INVALID_TEST_CASES: Array<{ transports: Transport[] }> = [
|
||||
@@ -135,7 +128,7 @@ describe("TransportAutoDiscovery", () => {
|
||||
"falls back to config when backend has no (valid) livekit transports $transports",
|
||||
async ({ transports }) => {
|
||||
const client = makeClient();
|
||||
client._unstable_getRTCTransports.mockResolvedValue(transports);
|
||||
client.getRTCTransports.mockResolvedValue(transports);
|
||||
|
||||
const discovery = new TransportAutoDiscovery({
|
||||
client,
|
||||
@@ -152,7 +145,7 @@ describe("TransportAutoDiscovery", () => {
|
||||
|
||||
it("returns null when backend and config are all unavailable", async () => {
|
||||
const client = makeClient();
|
||||
client._unstable_getRTCTransports.mockResolvedValue([]);
|
||||
client.getRTCTransports.mockResolvedValue([]);
|
||||
|
||||
const discovery = new TransportAutoDiscovery({
|
||||
client,
|
||||
|
||||
@@ -10,10 +10,7 @@ import { type Logger } from "matrix-js-sdk/lib/logger";
|
||||
|
||||
import { doNetworkOperationWithRetry } from "../utils/network";
|
||||
|
||||
type TransportDiscoveryClient = Pick<
|
||||
MatrixClient,
|
||||
"getDomain" | "_unstable_getRTCTransports"
|
||||
>;
|
||||
type TransportDiscoveryClient = Pick<MatrixClient, "getRTCTransports">;
|
||||
|
||||
export interface TransportAutoDiscoveryProps {
|
||||
client: TransportDiscoveryClient;
|
||||
@@ -74,7 +71,7 @@ export class TransportAutoDiscovery {
|
||||
this.logger.info("First try to use getRTCTransports end point ...");
|
||||
try {
|
||||
const transportList = await doNetworkOperationWithRetry(async () =>
|
||||
client._unstable_getRTCTransports(),
|
||||
client.getRTCTransports(),
|
||||
);
|
||||
for (const type of this.transportTypes) {
|
||||
const first = transportList.find(
|
||||
|
||||
@@ -60,7 +60,7 @@ describe("joinJsSdkSession", () => {
|
||||
expect(s.join).toHaveBeenCalledWith(ownMemberMock, [transportWithAlias], {
|
||||
notificationType: "ring",
|
||||
callIntent: undefined,
|
||||
applicationData: {},
|
||||
applicationData: undefined,
|
||||
manageMediaKeys: true,
|
||||
delayedLeaveEventRestartMs: 300_000,
|
||||
delayedLeaveEventDelayMs: 3_600_000,
|
||||
@@ -95,13 +95,14 @@ describe("joinJsSdkSession", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("lifts the call intent out of the application data and sends sticky events in Matrix 2.0 mode", () => {
|
||||
it("passes the call intent and application data through and sends sticky events in Matrix 2.0 mode", () => {
|
||||
const s = session();
|
||||
|
||||
joinJsSdkSession("!room:example.org", s, ownMemberMock, transport, {
|
||||
encryptMedia: true,
|
||||
matrixRTCMode: MatrixRTCMode.Matrix_2_0,
|
||||
applicationData: { "m.call.intent": "audio", custom: 1 },
|
||||
callIntent: "m.audio",
|
||||
applicationData: { custom: 1 },
|
||||
timings: defaultSessionTimings,
|
||||
delayedLeave: defaultSessionTimings.delayedLeave,
|
||||
});
|
||||
@@ -110,7 +111,7 @@ describe("joinJsSdkSession", () => {
|
||||
ownMemberMock,
|
||||
[transportWithAlias],
|
||||
expect.objectContaining({
|
||||
callIntent: "audio",
|
||||
callIntent: "m.audio",
|
||||
applicationData: { custom: 1 },
|
||||
unstableSendStickyEvents: true,
|
||||
}),
|
||||
@@ -124,7 +125,8 @@ describe("joinJsSdkSession", () => {
|
||||
joinJsSdkSession("!room:example.org", s, ownMemberMock, transport, {
|
||||
encryptMedia: true,
|
||||
matrixRTCMode: MatrixRTCMode.Matrix_2_0,
|
||||
applicationData: { "m.call.intent": "audio", custom: 1 },
|
||||
callIntent: "m.audio",
|
||||
applicationData: { custom: 1 },
|
||||
timings: defaultSessionTimings,
|
||||
delayedLeave: defaultSessionTimings.delayedLeave,
|
||||
});
|
||||
@@ -133,7 +135,7 @@ describe("joinJsSdkSession", () => {
|
||||
ownMemberMock,
|
||||
[transport],
|
||||
expect.objectContaining({
|
||||
callIntent: "audio",
|
||||
callIntent: "m.audio",
|
||||
applicationData: { custom: 1 },
|
||||
unstableSendStickyEvents: true,
|
||||
}),
|
||||
|
||||
@@ -23,6 +23,7 @@ interface Options {
|
||||
encryptMedia: boolean;
|
||||
matrixRTCMode: MatrixRTCMode;
|
||||
sendNotificationType?: RTCNotificationType;
|
||||
callIntent?: RTCCallIntent;
|
||||
applicationData?: Record<string, unknown>;
|
||||
timings: SessionTimings;
|
||||
/** The delayed leave timings to use: delegated to the SFU or not. */
|
||||
@@ -43,15 +44,12 @@ export function joinJsSdkSession(
|
||||
encryptMedia,
|
||||
matrixRTCMode,
|
||||
sendNotificationType,
|
||||
callIntent,
|
||||
applicationData,
|
||||
timings,
|
||||
delayedLeave,
|
||||
}: Options,
|
||||
): void {
|
||||
// The membership format carries the intent as a field of its own
|
||||
const { "m.call.intent": intent, ...rest } = applicationData ?? {};
|
||||
const callIntent =
|
||||
typeof intent === "string" ? (intent as RTCCallIntent) : undefined;
|
||||
// Give up on the network as soon as either the sync has been down for the
|
||||
// grace period or the delayed leave has probably been sent, whichever is
|
||||
// sooner
|
||||
@@ -78,7 +76,7 @@ export function joinJsSdkSession(
|
||||
{
|
||||
notificationType: sendNotificationType,
|
||||
callIntent,
|
||||
applicationData: rest,
|
||||
applicationData,
|
||||
manageMediaKeys: encryptMedia,
|
||||
delayedLeaveEventRestartMs: delayedLeave.restart_ms,
|
||||
delayedLeaveEventDelayMs: delayedLeave.delay_ms,
|
||||
|
||||
+10
-3
@@ -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>;
|
||||
}
|
||||
|
||||
@@ -151,12 +154,16 @@ export interface LocalAudioMediaTrack
|
||||
extends AudioMediaTrack, LocalMediaTrack {}
|
||||
|
||||
export interface LocalVideoMediaTrack extends VideoMediaTrack, LocalMediaTrack {
|
||||
/** For mirroring; undefined where the camera does not say which way it faces. */
|
||||
/**
|
||||
* For mirroring. A camera that does not say which way it faces is taken to
|
||||
* face the user, unless it is known to film the room, as a phone used as a
|
||||
* webcam. Undefined while there is no camera track.
|
||||
*/
|
||||
facingMode$: Behavior<"user" | "environment" | undefined>;
|
||||
/**
|
||||
* Restarts the camera facing the other way, on devices with a front and a
|
||||
* back camera, and resolves with the id of the device now in use. Does
|
||||
* nothing where the facing mode is unknown.
|
||||
* nothing while there is no camera track.
|
||||
*/
|
||||
switchFacingMode(): Promise<string | undefined>;
|
||||
/** Background blur and the like; undefined removes the processor. */
|
||||
|
||||
@@ -92,7 +92,7 @@ function setupTest(): void {
|
||||
matrix_server_name: "example.org",
|
||||
expires_in: 3600,
|
||||
}),
|
||||
_unstable_getLivekitToken: vi.fn().mockResolvedValue({ jwt: testJWTToken }),
|
||||
getLivekitToken: vi.fn().mockResolvedValue({ jwt: testJWTToken }),
|
||||
});
|
||||
|
||||
localParticipantEventEmiter = new EventEmitter();
|
||||
@@ -191,7 +191,7 @@ describe("Start connection states", () => {
|
||||
|
||||
const deferred = Promise.withResolvers<LivekitGetTokenResponse>();
|
||||
|
||||
client._unstable_getLivekitToken.mockImplementation(
|
||||
client.getLivekitToken.mockImplementation(
|
||||
async (): Promise<LivekitGetTokenResponse> => {
|
||||
return await deferred.promise;
|
||||
},
|
||||
@@ -235,7 +235,7 @@ describe("Start connection states", () => {
|
||||
onTestFinished(() => s.unsubscribe());
|
||||
|
||||
const deferredSFU = Promise.withResolvers<void>();
|
||||
client._unstable_getLivekitToken.mockImplementation(async () => {
|
||||
client.getLivekitToken.mockImplementation(async () => {
|
||||
await deferredSFU.promise;
|
||||
throw new MatrixError(
|
||||
{
|
||||
@@ -378,7 +378,7 @@ describe("Start connection states", () => {
|
||||
|
||||
await connection.start();
|
||||
|
||||
expect(client._unstable_getLivekitToken).not.toHaveBeenCalled();
|
||||
expect(client.getLivekitToken).not.toHaveBeenCalled();
|
||||
expect(fetchMock.called(`${serviceUrl}/sfu/get`)).toBe(true);
|
||||
expect(fakeLivekitRoom.connect).toHaveBeenCalledWith(
|
||||
"wss://sfu",
|
||||
|
||||
@@ -33,7 +33,7 @@ const urlTransport: UnstableLivekitTransport = {
|
||||
function client(): ClientGetTokenParts & ClientOpenIDParts {
|
||||
return {
|
||||
getOpenIdToken: vi.fn(),
|
||||
_unstable_getLivekitToken: vi.fn().mockResolvedValue({ jwt: testJWTToken }),
|
||||
getLivekitToken: vi.fn().mockResolvedValue({ jwt: testJWTToken }),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -160,8 +160,8 @@ describe("createLivekitBackend", () => {
|
||||
const client = {
|
||||
baseUrl: homeserver,
|
||||
getOpenIdToken: vi.fn(),
|
||||
_unstable_getLivekitToken: vi.fn(),
|
||||
_unstable_delegateDelayedLeave: vi.fn(),
|
||||
getLivekitToken: vi.fn(),
|
||||
delegateDelayedLeave: vi.fn(),
|
||||
};
|
||||
/** The connections the stubbed factory handed out, with their participants to drive. */
|
||||
let connections: {
|
||||
@@ -344,6 +344,7 @@ describe("createLivekitBackend", () => {
|
||||
userId: "@bob:example.org",
|
||||
deviceId: "DEV000",
|
||||
memberId: legacyId,
|
||||
matrixEventId$: constant("$bob"),
|
||||
transport$: constant({
|
||||
type: "livekit",
|
||||
id: JSON.stringify(transport),
|
||||
|
||||
@@ -73,10 +73,7 @@ export interface LivekitBackendOptions {
|
||||
*/
|
||||
client: Pick<
|
||||
MatrixClient,
|
||||
| "getOpenIdToken"
|
||||
| "_unstable_getLivekitToken"
|
||||
| "_unstable_delegateDelayedLeave"
|
||||
| "baseUrl"
|
||||
"getOpenIdToken" | "getLivekitToken" | "delegateDelayedLeave" | "baseUrl"
|
||||
>;
|
||||
mediaQuality?: MediaQuality;
|
||||
}
|
||||
|
||||
@@ -18,15 +18,7 @@ import {
|
||||
TrackEvent,
|
||||
type TrackPublication,
|
||||
} from "livekit-client";
|
||||
import {
|
||||
afterEach,
|
||||
beforeEach,
|
||||
describe,
|
||||
expect,
|
||||
it,
|
||||
onTestFinished,
|
||||
vi,
|
||||
} from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ObservableScope } from "../../reactive/ObservableScope";
|
||||
import {
|
||||
@@ -221,10 +213,142 @@ describe("createLivekitMediaTrack", () => {
|
||||
expect(switchActiveDevice).toHaveBeenCalledWith(
|
||||
"audioinput",
|
||||
"mic-2",
|
||||
false,
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
// LiveKit's media stream track is the processed one while a processor runs,
|
||||
// and that one names no device; the camera behind it does
|
||||
it.each([
|
||||
{ deviceId: "cam-1", switches: false },
|
||||
{ deviceId: "cam-2", switches: true },
|
||||
])(
|
||||
"leaves a processed camera alone unless its device changes: $deviceId",
|
||||
async ({ deviceId, switches }) => {
|
||||
let openDevice = "cam-1";
|
||||
const camera = Object.assign(Object.create(LocalVideoTrack.prototype), {
|
||||
source: Track.Source.Camera,
|
||||
_mediaStreamTrack: {
|
||||
readyState: "live",
|
||||
label: "",
|
||||
getSettings: () => ({ deviceId: openDevice }),
|
||||
},
|
||||
// What LiveKit shows as the track, with no device of its own
|
||||
processor: {
|
||||
processedTrack: { label: "", getSettings: () => ({}) },
|
||||
},
|
||||
}) as LocalVideoTrack;
|
||||
const switchActiveDevice = vi.fn(async (_kind: string, id: string) => {
|
||||
openDevice = id;
|
||||
return Promise.resolve(true);
|
||||
});
|
||||
const { participant, publication, room } = fakes({
|
||||
track: camera as unknown as FakeTrack,
|
||||
});
|
||||
const track = createLocalLivekitMediaTrack(
|
||||
scope,
|
||||
Object.assign(participant, {
|
||||
isLocal: true,
|
||||
}) as unknown as LocalParticipant,
|
||||
publication as unknown as TrackPublication,
|
||||
Object.assign(room, { switchActiveDevice }),
|
||||
vi.fn(),
|
||||
);
|
||||
|
||||
await track.setDevice(deviceId);
|
||||
expect(switchActiveDevice.mock.calls).toEqual(
|
||||
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",
|
||||
label: "Back Camera",
|
||||
getSettings: () => ({ facingMode: "environment" }),
|
||||
};
|
||||
const camera = Object.assign(Object.create(LocalVideoTrack.prototype), {
|
||||
source: Track.Source.Camera,
|
||||
_mediaStreamTrack: source,
|
||||
mediaStream: { getVideoTracks: () => [source] },
|
||||
processor: {
|
||||
processedTrack: { label: "", getSettings: () => ({}) },
|
||||
},
|
||||
restartTrack: vi.fn().mockResolvedValue(undefined),
|
||||
}) as LocalVideoTrack;
|
||||
const { participant, publication, room } = fakes({
|
||||
track: camera as unknown as FakeTrack,
|
||||
});
|
||||
const track = createLocalLivekitMediaTrack(
|
||||
scope,
|
||||
Object.assign(participant, {
|
||||
isLocal: true,
|
||||
}) as unknown as LocalParticipant,
|
||||
publication as unknown as TrackPublication,
|
||||
room,
|
||||
vi.fn(),
|
||||
) as LocalVideoMediaTrack;
|
||||
|
||||
expect(track.facingMode$.value).toBe("environment");
|
||||
await track.switchFacingMode();
|
||||
expect(camera.restartTrack).toHaveBeenCalledExactlyOnceWith({
|
||||
facingMode: "user",
|
||||
});
|
||||
});
|
||||
|
||||
// LiveKit stops a camera that is turned off; the processor is built when it
|
||||
// is turned on again
|
||||
it.each([
|
||||
@@ -234,10 +358,6 @@ describe("createLivekitMediaTrack", () => {
|
||||
"gives a processor to a camera that $state: $takes",
|
||||
async ({ isMuted, takes }) => {
|
||||
// jsdom has none; LiveKit's facing mode checks against it
|
||||
vi.stubGlobal("MediaStreamTrack", class {});
|
||||
onTestFinished(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
const camera = Object.assign(Object.create(LocalVideoTrack.prototype), {
|
||||
isMuted,
|
||||
_mediaStreamTrack: {
|
||||
@@ -292,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,
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
roomEventSelector,
|
||||
} from "@livekit/components-core";
|
||||
import {
|
||||
facingModeFromLocalTrack,
|
||||
type LocalParticipant,
|
||||
LocalTrack,
|
||||
LocalVideoTrack,
|
||||
@@ -50,6 +49,7 @@ import {
|
||||
type VideoMediaTrack,
|
||||
} from "../../media-api";
|
||||
import { MatrixRTCError } from "../../errors";
|
||||
import { facingModeOf } from "../../utils/facingMode";
|
||||
import { toLivekitProcessor, type LivekitProcessor } from "./videoProcessor";
|
||||
|
||||
export const mediaSources: Record<Track.Source, MediaSource> = {
|
||||
@@ -199,18 +199,39 @@ export function createLocalLivekitMediaTrack(
|
||||
throw new MatrixRTCError(`A ${base.source} track has no device`);
|
||||
// LiveKit decides whether to restart by the constraints it keeps, which
|
||||
// a browser that does not echo the device id back (Firefox) leaves
|
||||
// without one; a track already on the device is left alone here
|
||||
// without one; a track already on the device is left alone here. Asked
|
||||
// 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 &&
|
||||
current.mediaStreamTrack.getSettings().deviceId === 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 };
|
||||
@@ -229,10 +250,9 @@ export function createLocalLivekitMediaTrack(
|
||||
switchFacingMode: async () => {
|
||||
const track = videoTrack();
|
||||
if (!track) return;
|
||||
const { facingMode } = facingModeFromLocalTrack(track);
|
||||
if (facingMode !== "user" && facingMode !== "environment") return;
|
||||
await track.restartTrack({
|
||||
facingMode: facingMode === "user" ? "environment" : "user",
|
||||
facingMode:
|
||||
facingModeOf(sourceTrack(track)) === "user" ? "environment" : "user",
|
||||
});
|
||||
return track.mediaStreamTrack.getSettings().deviceId;
|
||||
},
|
||||
@@ -253,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,
|
||||
@@ -286,6 +319,14 @@ async function rtpStreamStats(
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The camera's own track. While a processor runs LiveKit's media stream track
|
||||
* is the processed one, which says nothing of the camera.
|
||||
*/
|
||||
function sourceTrack(track: LocalVideoTrack): MediaStreamTrack {
|
||||
return track.mediaStream?.getVideoTracks()[0] ?? track.mediaStreamTrack;
|
||||
}
|
||||
|
||||
function facingMode$(
|
||||
scope: ObservableScope,
|
||||
track$: Behavior<Track | undefined>,
|
||||
@@ -296,12 +337,7 @@ function facingMode$(
|
||||
if (!(track instanceof LocalVideoTrack)) return of(undefined);
|
||||
return fromEvent(track, TrackEvent.Restarted).pipe(
|
||||
startWith(null),
|
||||
map(() => {
|
||||
const { facingMode } = facingModeFromLocalTrack(track);
|
||||
return facingMode === "user" || facingMode === "environment"
|
||||
? facingMode
|
||||
: undefined;
|
||||
}),
|
||||
map(() => facingModeOf(sourceTrack(track))),
|
||||
);
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -84,7 +84,7 @@ describe("findRemotePublishLivekitTransport", () => {
|
||||
|
||||
beforeEach(() => {
|
||||
client = {
|
||||
_unstable_getLivekitToken: vi
|
||||
getLivekitToken: vi
|
||||
.fn()
|
||||
.mockResolvedValue({ jwt: jwtWithPublishGrant(true) }),
|
||||
};
|
||||
@@ -92,8 +92,8 @@ describe("findRemotePublishLivekitTransport", () => {
|
||||
|
||||
it("publishes on the oldest member's SFU with its server_name", async () => {
|
||||
await expect(find([carol, bob])).resolves.toEqual(bobsTransport);
|
||||
expect(client._unstable_getLivekitToken).toHaveBeenCalledTimes(1);
|
||||
expect(client._unstable_getLivekitToken).toHaveBeenCalledWith({
|
||||
expect(client.getLivekitToken).toHaveBeenCalledTimes(1);
|
||||
expect(client.getLivekitToken).toHaveBeenCalledWith({
|
||||
url: "wss://sfu.bob.com",
|
||||
server_name: "bob.com",
|
||||
room_id: "!room:example.org",
|
||||
@@ -103,70 +103,68 @@ describe("findRemotePublishLivekitTransport", () => {
|
||||
});
|
||||
|
||||
it("asks about an SFU once however many members are on it", async () => {
|
||||
client._unstable_getLivekitToken.mockResolvedValue({
|
||||
client.getLivekitToken.mockResolvedValue({
|
||||
jwt: jwtWithPublishGrant(false),
|
||||
});
|
||||
|
||||
await expect(find([dave, bobsLaptop, bob])).resolves.toBeNull();
|
||||
expect(client._unstable_getLivekitToken).toHaveBeenCalledTimes(1);
|
||||
expect(client.getLivekitToken).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("skips our own membership", async () => {
|
||||
await expect(find([ourselves, bob])).resolves.toEqual(bobsTransport);
|
||||
expect(client._unstable_getLivekitToken).toHaveBeenCalledTimes(1);
|
||||
expect(client.getLivekitToken).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("ignores members publishing through a legacy JWT service", async () => {
|
||||
await expect(find([legacyErin, bob])).resolves.toEqual(bobsTransport);
|
||||
expect(client._unstable_getLivekitToken).toHaveBeenCalledTimes(1);
|
||||
expect(client.getLivekitToken).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("moves on when a homeserver does not let us publish", async () => {
|
||||
client._unstable_getLivekitToken.mockImplementation(
|
||||
async ({ server_name }) =>
|
||||
Promise.resolve({
|
||||
jwt: jwtWithPublishGrant(server_name === "carol.com"),
|
||||
}),
|
||||
client.getLivekitToken.mockImplementation(async ({ server_name }) =>
|
||||
Promise.resolve({
|
||||
jwt: jwtWithPublishGrant(server_name === "carol.com"),
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(find([bob, carol])).resolves.toEqual(carolsTransport);
|
||||
expect(client._unstable_getLivekitToken).toHaveBeenCalledTimes(2);
|
||||
expect(client.getLivekitToken).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("moves on when a homeserver refuses to issue a token", async () => {
|
||||
client._unstable_getLivekitToken.mockImplementation(
|
||||
async ({ server_name }) =>
|
||||
server_name === "bob.com"
|
||||
? Promise.reject(
|
||||
new MatrixError(
|
||||
{ errcode: "M_FORBIDDEN", error: "Not joined" },
|
||||
403,
|
||||
),
|
||||
)
|
||||
: Promise.resolve({ jwt: jwtWithPublishGrant(true) }),
|
||||
client.getLivekitToken.mockImplementation(async ({ server_name }) =>
|
||||
server_name === "bob.com"
|
||||
? Promise.reject(
|
||||
new MatrixError(
|
||||
{ errcode: "M_FORBIDDEN", error: "Not joined" },
|
||||
403,
|
||||
),
|
||||
)
|
||||
: Promise.resolve({ jwt: jwtWithPublishGrant(true) }),
|
||||
);
|
||||
|
||||
await expect(find([bob, carol])).resolves.toEqual(carolsTransport);
|
||||
});
|
||||
|
||||
it("finds nothing once all candidates are exhausted", async () => {
|
||||
client._unstable_getLivekitToken.mockResolvedValue({
|
||||
client.getLivekitToken.mockResolvedValue({
|
||||
jwt: jwtWithPublishGrant(false),
|
||||
});
|
||||
|
||||
await expect(find([bob, carol])).resolves.toBeNull();
|
||||
expect(client._unstable_getLivekitToken).toHaveBeenCalledTimes(2);
|
||||
expect(client.getLivekitToken).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("gives up immediately if our homeserver lacks the CS API", async () => {
|
||||
client._unstable_getLivekitToken.mockRejectedValue(csApiMissing);
|
||||
client.getLivekitToken.mockRejectedValue(csApiMissing);
|
||||
|
||||
await expect(find([bob, carol])).resolves.toBeNull();
|
||||
expect(client._unstable_getLivekitToken).toHaveBeenCalledTimes(1);
|
||||
expect(client.getLivekitToken).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("finds nothing where there are no other members", async () => {
|
||||
await expect(find([ourselves])).resolves.toBeNull();
|
||||
expect(client._unstable_getLivekitToken).not.toHaveBeenCalled();
|
||||
expect(client.getLivekitToken).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user