mirror of
https://github.com/vector-im/element-call.git
synced 2026-11-25 09:51:09 +08:00
Compare commits
85
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0eff661159 | ||
|
|
ef1f69e085 | ||
|
|
86ad9bcb28 | ||
|
|
7cd9ed8022 | ||
|
|
29b80b62c9 | ||
|
|
df1156b385 | ||
|
|
7cf6cb4fee | ||
|
|
23c8cb05c8 | ||
|
|
89e3ff4c5a | ||
|
|
586154772e | ||
|
|
20a174c0b4 | ||
|
|
02eb134e40 | ||
|
|
3acf5d9a28 | ||
|
|
ac461840a3 | ||
|
|
2e3f40e08c | ||
|
|
438d14d1a1 | ||
|
|
d04bfdc624 | ||
|
|
b1f8fcd604 | ||
|
|
001a015a3f | ||
|
|
cee9e02617 | ||
|
|
b3bbdc79f5 | ||
|
|
e91d1387b7 | ||
|
|
34465d7230 | ||
|
|
512e885bf2 | ||
|
|
629031038f | ||
|
|
3879cd65b5 | ||
|
|
74500f37ea | ||
|
|
c9616efc5b | ||
|
|
b9546b80f5 | ||
|
|
ad316bbe9a | ||
|
|
63f31e711c | ||
|
|
3e864c537a | ||
|
|
3ce3d0e266 | ||
|
|
6f328d7304 | ||
|
|
e5d74102e1 | ||
|
|
413b795459 | ||
|
|
e9c1e25542 | ||
|
|
60985885d3 | ||
|
|
f88d8d5830 | ||
|
|
6c66f9a3e7 | ||
|
|
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 | ||
|
|
783bd946e8 | ||
|
|
9c64316b42 | ||
|
|
25c4f14d8f |
@@ -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.
|
||||
@@ -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:
|
||||
|
||||
@@ -17,7 +17,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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -25,7 +25,7 @@ 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
|
||||
steps:
|
||||
- name: Deploy to call.element.dev
|
||||
uses: actions/github-script@d7906e4ad0b1822421a7e6a35d5ca353c962f410 # v6
|
||||
@@ -92,7 +92,7 @@ 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
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
|
||||
@@ -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
|
||||
@@ -32,7 +32,7 @@ on:
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
deployments: write
|
||||
environment: Netlify
|
||||
|
||||
@@ -10,7 +10,7 @@ on:
|
||||
jobs:
|
||||
lint:
|
||||
name: Lint, format & type check
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
|
||||
@@ -17,7 +17,7 @@ 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
|
||||
outputs:
|
||||
pr_number: ${{ steps.prdetails.outputs.pr_id }}
|
||||
pr_data_json: ${{ steps.prdetails.outputs.data }}
|
||||
|
||||
@@ -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:
|
||||
@@ -111,7 +111,7 @@ jobs:
|
||||
needs: [versioning, publish_npm]
|
||||
if: ${{ needs.versioning.outputs.DRY_RUN == 'false' }}
|
||||
name: Update release notes
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
# Shared with publish-embedded-packages.yaml, which appends to the same release: two
|
||||
# appends at once would each write back the body without the other's section
|
||||
concurrency:
|
||||
|
||||
@@ -14,7 +14,7 @@ on:
|
||||
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 }}
|
||||
@@ -76,7 +76,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:
|
||||
@@ -107,7 +107,7 @@ jobs:
|
||||
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:
|
||||
@@ -152,7 +152,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 +212,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,7 +282,7 @@ jobs:
|
||||
needs: [versioning, publish_npm, publish_android, publish_ios]
|
||||
if: always()
|
||||
name: Update release notes
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
# Shared with publish-component.yaml, which appends to the same release: two appends
|
||||
# at once would each write back the body without the other's section
|
||||
concurrency:
|
||||
|
||||
@@ -23,7 +23,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
|
||||
@@ -68,7 +68,7 @@ jobs:
|
||||
add_docker_release_note:
|
||||
needs: publish_docker
|
||||
name: Add docker release note
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Add release note
|
||||
uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
|
||||
|
||||
@@ -25,7 +25,7 @@ on:
|
||||
jobs:
|
||||
vitest:
|
||||
name: Run unit tests
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
@@ -71,10 +71,27 @@ 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
|
||||
# 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:
|
||||
@@ -107,17 +124,64 @@ 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
|
||||
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@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
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
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -44,3 +44,7 @@ storybook-static
|
||||
|
||||
# Nested checkout made by scripts/layered.sh
|
||||
/matrix-js-sdk/
|
||||
|
||||
# Claude
|
||||
/.claude/*
|
||||
!/.claude/skills/
|
||||
|
||||
@@ -16,19 +16,35 @@ 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.md` and fill every
|
||||
section.
|
||||
|
||||
## Gates
|
||||
|
||||
@@ -42,6 +58,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.
|
||||
|
||||
@@ -221,119 +221,68 @@ 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`, `matrix-js-sdk`,
|
||||
`@vector-im/compound-web`, `@vector-im/compound-design-tokens`, and
|
||||
Compound's stylesheet.
|
||||
2. Import `@element-hq/element-call-component/style.css`.
|
||||
3. Await `initializeElementCall(config)` once before rendering.
|
||||
4. Render the component with `client`, `roomId` and an `intent`; optionally
|
||||
pass `config`, `hostBridge`, `language` and `theme` (both can change
|
||||
mid-call). Control it through the `ref` handle (`join`, `hangUp`,
|
||||
`setDeviceMute`).
|
||||
|
||||
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`.
|
||||
- `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
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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:e063472b6bdf6d0bfa1d43dfa4ef7effee1efd2c9684daee665d1bedfe746a47
|
||||
image: ghcr.io/element-hq/element-web:develop@sha256:f85350f2b31a7521a800d9050e9f5c0676d04cfb60675242ccc0c6e25cad7d04
|
||||
element-web-1:
|
||||
# Pin to a SHA so that upstream cannot break our tests. Renovate handles regular updates.
|
||||
image: ghcr.io/element-hq/element-web:develop@sha256:e063472b6bdf6d0bfa1d43dfa4ef7effee1efd2c9684daee665d1bedfe746a47
|
||||
image: ghcr.io/element-hq/element-web:develop@sha256:f85350f2b31a7521a800d9050e9f5c0676d04cfb60675242ccc0c6e25cad7d04
|
||||
volumes:
|
||||
# The other site opens the embedded package under test in place of the
|
||||
# copy its image bundles (the first site opens the dev server's app.
|
||||
# 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.
|
||||
|
||||
@@ -10,6 +10,13 @@
|
||||
- Owning a resource: a class taking the scope in its constructor — `MediaDevices`,
|
||||
`MuteStates`, `TileStore`, `Publisher`, `Connection`. Both styles are current;
|
||||
don't convert one to the other in passing.
|
||||
- A factory's required parameters are what the thing is made of: no sensible
|
||||
default. Several of them go in a props interface, so each can carry a doc
|
||||
comment. Its trailing `options` bag is how the host wants it to behave: every
|
||||
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 +43,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`).
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
@@ -78,11 +78,6 @@
|
||||
"device_id": "Device ID: {{id}}",
|
||||
"duplicate_tiles_label": "Number of additional tile copies per participant",
|
||||
"environment_variables": "Environment variables",
|
||||
"full_mesh_capabilities": "Take part in full mesh (MSC4575)",
|
||||
"full_mesh_capabilities_description": "Receive members publishing on full mesh. As a widget, this asks the host for the signalling permissions.",
|
||||
"full_mesh_peer_connections": "Full mesh peer connections",
|
||||
"full_mesh_publishing": "Publish on full mesh instead of LiveKit",
|
||||
"full_mesh_transport": "Full mesh: {{device}}",
|
||||
"hostname": "Hostname: {{hostname}}",
|
||||
"livekit_server_info": "LiveKit Server Info",
|
||||
"livekit_sfu": "LiveKit SFU: {{url}}",
|
||||
|
||||
+3
-2
@@ -51,6 +51,7 @@
|
||||
"build-storybook": "storybook build"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@base-ui/react": "^1.9.0",
|
||||
"@codecov/vite-plugin": "^1.3.0",
|
||||
"@fontsource/inconsolata": "^5.1.0",
|
||||
"@fontsource/inter": "^5.1.0",
|
||||
@@ -107,11 +108,11 @@
|
||||
"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",
|
||||
|
||||
+33
-21
@@ -26,6 +26,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 +56,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,29 +76,28 @@ 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",
|
||||
},
|
||||
{
|
||||
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",
|
||||
use: desktopChrome,
|
||||
},
|
||||
{
|
||||
name: "firefox",
|
||||
dependencies: ["build-embedded"],
|
||||
testIgnore: "**/mobile/**",
|
||||
use: {
|
||||
...devices["Desktop Firefox"],
|
||||
|
||||
@@ -106,6 +106,66 @@ async function drawsPerSecond(page: Page): Promise<number> {
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
@@ -151,6 +211,46 @@ test.describe("background effects section", () => {
|
||||
});
|
||||
});
|
||||
|
||||
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);
|
||||
|
||||
@@ -127,13 +127,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,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";
|
||||
import { mkdirSync } from "node:fs";
|
||||
|
||||
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",
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,179 +0,0 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { expect, type Page, test } from "@playwright/test";
|
||||
|
||||
import { widgetTest } from "../fixtures/widget-user";
|
||||
import { HOST1, TestHelpers } from "./test-helpers";
|
||||
|
||||
/**
|
||||
* Records the LiveKit signalling websockets a page opens: the SFU is reached
|
||||
* with an access token in the url, which full mesh never needs.
|
||||
*/
|
||||
function recordSfuSockets(page: Page): string[] {
|
||||
const urls: string[] = [];
|
||||
page.on("websocket", (ws) => {
|
||||
if (ws.url().includes("access_token")) urls.push(ws.url());
|
||||
});
|
||||
return urls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts recording the types of the to-device messages the widget on a page
|
||||
* asks its host to send, and returns a function reading them. On the wire
|
||||
* they are encrypted, so the type is only visible in the widget API.
|
||||
*/
|
||||
async function recordWidgetToDevice(
|
||||
page: Page,
|
||||
): Promise<() => Promise<string[]>> {
|
||||
await page.evaluate(() => {
|
||||
const types: string[] = [];
|
||||
Object.assign(window, { widgetToDeviceTypes: types });
|
||||
window.addEventListener("message", ({ data }) => {
|
||||
const {
|
||||
action,
|
||||
response,
|
||||
data: request,
|
||||
} = (data ?? {}) as {
|
||||
action?: string;
|
||||
response?: unknown;
|
||||
data?: { type?: string };
|
||||
};
|
||||
if (action === "send_to_device" && response === undefined)
|
||||
types.push(request?.type ?? "");
|
||||
});
|
||||
});
|
||||
return async () =>
|
||||
page.evaluate(
|
||||
() =>
|
||||
(window as unknown as { widgetToDeviceTypes: string[] })
|
||||
.widgetToDeviceTypes,
|
||||
);
|
||||
}
|
||||
|
||||
const cases: {
|
||||
name: string;
|
||||
/** Who publishes on full mesh; both have the capabilities unless said. */
|
||||
fullMesh: [boolean, boolean];
|
||||
capabilities?: [boolean, boolean];
|
||||
}[] = [
|
||||
// Both publish on full mesh: the media flows without any SFU
|
||||
{ name: "both on full mesh", fullMesh: [true, true] },
|
||||
// One on each: Florian receives Valere over LiveKit without publishing
|
||||
// there, and Valere receives Florian over full mesh without publishing there
|
||||
{ name: "full mesh and LiveKit mixed", fullMesh: [true, false] },
|
||||
// Without the capabilities a widget can't be subscribed to full mesh
|
||||
{
|
||||
name: "LiveKit side without the full mesh capabilities",
|
||||
fullMesh: [true, false],
|
||||
capabilities: [true, false],
|
||||
},
|
||||
];
|
||||
|
||||
cases.forEach(({ name, fullMesh, capabilities = [true, true] }) => {
|
||||
const [florianMesh, valereMesh] = fullMesh;
|
||||
const [florianCaps, valereCaps] = capabilities;
|
||||
widgetTest(`Full mesh call: ${name}`, async ({ addUser, 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",
|
||||
);
|
||||
test.slow();
|
||||
|
||||
// Distinct per case: the cases run in parallel and register at once
|
||||
const suffix = `${Number(florianMesh)}${Number(valereMesh)}${Number(florianCaps)}${Number(valereCaps)}`;
|
||||
const [florian, valere] = await Promise.all([
|
||||
addUser(`florian${suffix}`, HOST1),
|
||||
addUser(`valere${suffix}`, HOST1),
|
||||
]);
|
||||
// Element Web doesn't auto-approve the full mesh signalling for Element
|
||||
// Call yet, so it asks for it whenever a widget with full mesh opens
|
||||
for (const { page } of [florian, valere])
|
||||
await page.addLocatorHandler(
|
||||
page.getByRole("heading", { name: "Approve widget permissions" }),
|
||||
async () => page.getByRole("button", { name: "Approve" }).click(),
|
||||
);
|
||||
const sockets = {
|
||||
florian: recordSfuSockets(florian.page),
|
||||
valere: recordSfuSockets(valere.page),
|
||||
};
|
||||
|
||||
const roomName = "Full Mesh Room";
|
||||
await TestHelpers.createRoom(roomName, florian.page, [valere.mxId]);
|
||||
await TestHelpers.acceptRoomInvite(roomName, valere.page);
|
||||
|
||||
await TestHelpers.openWidgetSetEmbeddedElementCallRtcModeCloseWidget(
|
||||
florian.page,
|
||||
"2_0",
|
||||
{ capabilities: florianCaps, publish: florianMesh },
|
||||
);
|
||||
await TestHelpers.openWidgetSetEmbeddedElementCallRtcModeCloseWidget(
|
||||
valere.page,
|
||||
"2_0",
|
||||
{ capabilities: valereCaps, publish: valereMesh },
|
||||
);
|
||||
|
||||
await TestHelpers.startCallInCurrentRoom(florian.page, false);
|
||||
await TestHelpers.joinCallFromLobby(florian.page);
|
||||
await TestHelpers.joinCallInCurrentRoom(valere.page);
|
||||
|
||||
// The other's media arrives if it is on LiveKit, or we can signal full mesh
|
||||
const receives = {
|
||||
florian: !valereMesh || florianCaps,
|
||||
valere: !florianMesh || valereCaps,
|
||||
};
|
||||
// In parallel: assertions on a page also run its permission handler
|
||||
await Promise.all(
|
||||
(["florian", "valere"] as const).map(async (name) => {
|
||||
const frame = { florian, valere }[name].page
|
||||
.locator('iframe[title="Element Call"]')
|
||||
.contentFrame();
|
||||
await expect(frame.getByTestId("videoTile")).toHaveCount(2, {
|
||||
timeout: 15000,
|
||||
});
|
||||
const waiting = frame.getByText("Waiting for media...");
|
||||
if (receives[name]) {
|
||||
// Over whichever transport carries it
|
||||
await expect(waiting).not.toBeVisible({ timeout: 20000 });
|
||||
await TestHelpers.expectVisibleVideoCount(frame, 2);
|
||||
} else {
|
||||
await expect(waiting).toBeVisible({ timeout: 20000 });
|
||||
await TestHelpers.expectVisibleVideoCount(frame, 1);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
if (florianMesh && valereMesh) {
|
||||
// Nobody published on LiveKit, so nobody connected to an SFU
|
||||
expect(sockets.florian).toEqual([]);
|
||||
expect(sockets.valere).toEqual([]);
|
||||
} else {
|
||||
// Florian receives Valere's media from the SFU without publishing there
|
||||
expect(sockets.florian.length).toBeGreaterThan(0);
|
||||
}
|
||||
|
||||
// Florian sees Valere's camera go off: over the track metadata for full
|
||||
// mesh, without renegotiating
|
||||
const toDevice = await recordWidgetToDevice(valere.page);
|
||||
const valereFrame = valere.page
|
||||
.locator('iframe[title="Element Call"]')
|
||||
.contentFrame();
|
||||
await valereFrame.getByRole("switch", { name: "Stop video" }).click();
|
||||
const florianFrame = florian.page
|
||||
.locator('iframe[title="Element Call"]')
|
||||
.contentFrame();
|
||||
await TestHelpers.expectVisibleVideoCount(florianFrame, 1);
|
||||
// On the connection's control channel, not through the homeserver.
|
||||
// Candidates may still trickle there until the channel is up
|
||||
if (florianMesh && valereMesh)
|
||||
expect(
|
||||
(await toDevice()).filter(
|
||||
(type) => type.includes("full_mesh") && !type.endsWith(".candidates"),
|
||||
),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -24,14 +24,6 @@ export const HOST2 = "https://app.othersite.m.localhost/#/welcome";
|
||||
|
||||
export type RtcMode = "compat" | "2_0";
|
||||
|
||||
/** Full mesh (MSC4575) in the widget's developer settings. */
|
||||
export interface FullMeshOptions {
|
||||
/** Ask the host for the signalling capabilities, to receive full mesh. */
|
||||
capabilities?: boolean;
|
||||
/** Publish on full mesh instead of LiveKit; needs the capabilities. */
|
||||
publish?: boolean;
|
||||
}
|
||||
|
||||
export class TestHelpers {
|
||||
public static async startCallInCurrentRoom(
|
||||
page: Page,
|
||||
@@ -152,7 +144,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(),
|
||||
@@ -314,7 +310,6 @@ export class TestHelpers {
|
||||
public static async openWidgetSetEmbeddedElementCallRtcModeCloseWidget(
|
||||
page: Page,
|
||||
mode: RtcMode,
|
||||
fullMesh: FullMeshOptions = {},
|
||||
): Promise<void> {
|
||||
await page.getByRole("button", { name: "Video call" }).click({
|
||||
timeout: 5000,
|
||||
@@ -323,7 +318,7 @@ export class TestHelpers {
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
await TestHelpers.setEmbeddedElementCallRtcMode(page, mode, fullMesh);
|
||||
await TestHelpers.setEmbeddedElementCallRtcMode(page, mode);
|
||||
await page.getByRole("button", { name: "Close lobby" }).click();
|
||||
}
|
||||
|
||||
@@ -336,7 +331,6 @@ export class TestHelpers {
|
||||
public static async setEmbeddedElementCallRtcMode(
|
||||
page: Page,
|
||||
mode: RtcMode,
|
||||
{ capabilities = false, publish = false }: FullMeshOptions = {},
|
||||
): Promise<void> {
|
||||
const iframe = page.locator('iframe[title="Element Call"]').contentFrame();
|
||||
|
||||
@@ -354,14 +348,6 @@ export class TestHelpers {
|
||||
// compat
|
||||
await iframe.getByText("Compatibility: state events").click();
|
||||
}
|
||||
// Full mesh (MSC4575): the capabilities first, as publishing needs them
|
||||
await iframe
|
||||
.getByText("Take part in full mesh", { exact: false })
|
||||
.setChecked(capabilities);
|
||||
if (capabilities)
|
||||
await iframe
|
||||
.getByText("Publish on full mesh", { exact: false })
|
||||
.setChecked(publish);
|
||||
await iframe.getByTestId("modal_close").click();
|
||||
}
|
||||
|
||||
|
||||
Generated
+180
-126
@@ -16,12 +16,15 @@ overrides:
|
||||
undici: ^6.27.0
|
||||
flatted: ^3.4.2
|
||||
ws: ^8.21.0
|
||||
dompurify: ^3.4.11
|
||||
dompurify: ^3.4.17
|
||||
|
||||
importers:
|
||||
|
||||
.:
|
||||
devDependencies:
|
||||
'@base-ui/react':
|
||||
specifier: ^1.9.0
|
||||
version: 1.9.0(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)
|
||||
'@codecov/vite-plugin':
|
||||
specifier: ^1.3.0
|
||||
version: 1.9.1(vite@8.2.4(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.103.1)(terser@5.46.1)(yaml@2.9.0))
|
||||
@@ -39,7 +42,7 @@ importers:
|
||||
version: 11.7.12
|
||||
'@livekit/components-core':
|
||||
specifier: ^0.12.0
|
||||
version: 0.12.15(livekit-client@2.23.0(@types/dom-mediacapture-record@1.0.22))(tslib@2.8.1)
|
||||
version: 0.12.16(livekit-client@2.23.0(@types/dom-mediacapture-record@1.0.22))(tslib@2.8.1)
|
||||
'@livekit/track-processors':
|
||||
specifier: ^0.7.1
|
||||
version: 0.7.2(@types/dom-mediacapture-transform@0.1.11)(livekit-client@2.23.0(@types/dom-mediacapture-record@1.0.22))
|
||||
@@ -191,8 +194,8 @@ importers:
|
||||
specifier: ^1.9.1
|
||||
version: 1.9.2
|
||||
matrix-js-sdk:
|
||||
specifier: github:matrix-org/matrix-js-sdk#a9ef09fbf2f1644c8663d0aeaf6a921cd16e7b01
|
||||
version: https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/a9ef09fbf2f1644c8663d0aeaf6a921cd16e7b01
|
||||
specifier: github:matrix-org/matrix-js-sdk#6c8b1b418189919bc69fd9df5e57354e7b3c39cb
|
||||
version: https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/6c8b1b418189919bc69fd9df5e57354e7b3c39cb
|
||||
matrix-widget-api:
|
||||
specifier: ^1.18.0
|
||||
version: 1.20.0
|
||||
@@ -203,8 +206,8 @@ importers:
|
||||
specifier: ^8.0.1
|
||||
version: 8.0.1
|
||||
oxfmt:
|
||||
specifier: ^0.66.0
|
||||
version: 0.66.0
|
||||
specifier: ^0.79.0
|
||||
version: 0.79.0
|
||||
oxlint:
|
||||
specifier: ^1.70.0
|
||||
version: 1.81.0(oxlint-tsgolint@0.25.0)
|
||||
@@ -416,6 +419,33 @@ packages:
|
||||
resolution: {integrity: sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==}
|
||||
engines: {node: '>=6.9.0'}
|
||||
|
||||
'@base-ui/react@1.9.0':
|
||||
resolution: {integrity: sha512-S8CSYosASBKtpL8SWUfS78rFElfLijiCgA7oHOK22jCJ95FULsYyKwBNFOgudt0RA+/7yNc7F81bOvQnRgbBiQ==}
|
||||
engines: {node: '>=14.0.0'}
|
||||
peerDependencies:
|
||||
'@date-fns/tz': ^1.2.0
|
||||
'@types/react': ^17 || ^18 || ^19
|
||||
date-fns: ^4.0.0
|
||||
react: ^17 || ^18 || ^19
|
||||
react-dom: ^17 || ^18 || ^19
|
||||
peerDependenciesMeta:
|
||||
'@date-fns/tz':
|
||||
optional: true
|
||||
'@types/react':
|
||||
optional: true
|
||||
date-fns:
|
||||
optional: true
|
||||
|
||||
'@base-ui/utils@0.5.0':
|
||||
resolution: {integrity: sha512-dYGGcEttjkYiMoa5nHm8vLaJ2UcuTWxo3BFAwOYXeRg/q7UVVvA6cacEIXEs3FgBfK1CGtW1ptElqs7wsx+t9A==}
|
||||
peerDependencies:
|
||||
'@types/react': ^17 || ^18 || ^19
|
||||
react: ^17 || ^18 || ^19
|
||||
react-dom: ^17 || ^18 || ^19
|
||||
peerDependenciesMeta:
|
||||
'@types/react':
|
||||
optional: true
|
||||
|
||||
'@bcoe/v8-coverage@1.0.2':
|
||||
resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==}
|
||||
engines: {node: '>=18'}
|
||||
@@ -943,9 +973,6 @@ packages:
|
||||
'@floating-ui/core@1.8.0':
|
||||
resolution: {integrity: sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==}
|
||||
|
||||
'@floating-ui/dom@1.7.6':
|
||||
resolution: {integrity: sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ==}
|
||||
|
||||
'@floating-ui/dom@1.8.0':
|
||||
resolution: {integrity: sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==}
|
||||
|
||||
@@ -1176,8 +1203,8 @@ packages:
|
||||
'@jridgewell/trace-mapping@0.3.31':
|
||||
resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
|
||||
|
||||
'@livekit/components-core@0.12.15':
|
||||
resolution: {integrity: sha512-bDkK+jkPMgyT4a5lZmdcuc/hZ8fZUrXW+qQPNHVeSpXCBMzk5q9QWzx+HPtTsPJ8hnncWGfoT81RnXHBsy+Z8g==}
|
||||
'@livekit/components-core@0.12.16':
|
||||
resolution: {integrity: sha512-jcXuNeHKGkXgRiT4wniWRpg+TKUSoTL9da01tMxxKGmjp98zB2DVgPmk1fBZfgDVjPBF+jsZe/WkeFAbvJu4Gw==}
|
||||
engines: {node: '>=18'}
|
||||
peerDependencies:
|
||||
livekit-client: ^2.20.1
|
||||
@@ -1195,8 +1222,8 @@ packages:
|
||||
'@types/dom-mediacapture-transform': ^0.1.9
|
||||
livekit-client: ^1.12.0 || ^2.1.0
|
||||
|
||||
'@matrix-org/matrix-sdk-crypto-wasm@18.9.0':
|
||||
resolution: {integrity: sha512-NtLzNDTEfNASBjNCTGZHuk7N0jrQhS6Zx2CM857rCHZYYh/rpbKGQNrJ7azktm4S1P5Jy3WU3nwJTGohGw26qQ==}
|
||||
'@matrix-org/matrix-sdk-crypto-wasm@18.9.2':
|
||||
resolution: {integrity: sha512-GHeuSeb5Fj6Wg2+NE/WoLJJs9U3nOzttO+2sj7lOaS5gNBpGIksc48N/Q/kK/Z+Lxh7YMhopB7M8b6HyASXnGQ==}
|
||||
engines: {node: '>= 18'}
|
||||
|
||||
'@mdx-js/react@3.1.1':
|
||||
@@ -1629,124 +1656,124 @@ packages:
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
|
||||
'@oxfmt/binding-android-arm-eabi@0.66.0':
|
||||
resolution: {integrity: sha512-2Me9eoptv6ERdEuI2P8AOlYdHHraXebJaM6SC0kc2Dfb+mLrep2db+fedBPKaYn673h/vBgvP4tkOdAbaudX6w==}
|
||||
'@oxfmt/binding-android-arm-eabi@0.79.0':
|
||||
resolution: {integrity: sha512-xOCQ/rvokUXs8SxOQY5Wy2ukPaZJZ0PmdJovN0ryB1c8DVEtbcvliLdYtINUYh8QOTpmBOctIisSJk9tvh+J6w==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [arm]
|
||||
os: [android]
|
||||
|
||||
'@oxfmt/binding-android-arm64@0.66.0':
|
||||
resolution: {integrity: sha512-u7O+bSSF0HGsDKkQQxBqvLGVepu93RA+JKu+ONqvfh4sCnCEbj31wZj4iG5gk3XfRwrmYj0/8catkO2LcblQKQ==}
|
||||
'@oxfmt/binding-android-arm64@0.79.0':
|
||||
resolution: {integrity: sha512-WMLDvCjjchUYtI6zXKOdzTDGm72BaYZiz1/VhB1rrxdakUZRlJh1aMr3CT6ui51uHcWVBycULIXSZHpw6u2pTQ==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [arm64]
|
||||
os: [android]
|
||||
|
||||
'@oxfmt/binding-darwin-arm64@0.66.0':
|
||||
resolution: {integrity: sha512-/ikyMIVjX/sdo7KtjxoEsSUosfPzveVhT9RWMx9yGqFDKFJ89JAEKuEeLBmurDjrkb4w8tOnAdSO3SBaplY3bw==}
|
||||
'@oxfmt/binding-darwin-arm64@0.79.0':
|
||||
resolution: {integrity: sha512-+LzSN7w7tULz96ntS1Uqe5oI00XZ0o/m/t3+eSfiQp3aTPnj2eGUafqEWryMLk84j7x9NiF+GEP2YT4/BfClgA==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
|
||||
'@oxfmt/binding-darwin-x64@0.66.0':
|
||||
resolution: {integrity: sha512-q5xUsKeFqawa9NXa6ZGXWimFV19m8MogKPdTaSVDAAk2EQKBmBZRDeluwcl1p8ty/OFc9s9888OKEh3xfPVH0g==}
|
||||
'@oxfmt/binding-darwin-x64@0.79.0':
|
||||
resolution: {integrity: sha512-KFiMRhKeiiooaS1dKc4r8AZgOrfOhwVe1yf/aRef+8BajJwtVjMtlsQl/BNRxtkFbq13GjEo/4Q+9YhFGU4o6g==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
|
||||
'@oxfmt/binding-freebsd-x64@0.66.0':
|
||||
resolution: {integrity: sha512-CR+x4VzMY0pRXLK/xFQ/RzsSFkP5t2Z2mef0QY6OP/rTRcMUoMLCOM62/3Fp/t0K+UDoBKxvMyeb6D0zPMjleA==}
|
||||
'@oxfmt/binding-freebsd-x64@0.79.0':
|
||||
resolution: {integrity: sha512-lHVIp0g8ZOFKiqVscvttp+3HJkkRH6XkGgfAA0lVexIlE1mMFVp4V7RBdxz/P9p7T8pSNsYdapFWvdT21Mib9w==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [x64]
|
||||
os: [freebsd]
|
||||
|
||||
'@oxfmt/binding-linux-arm-gnueabihf@0.66.0':
|
||||
resolution: {integrity: sha512-ZEYmO/LbH9tTQCADILHGZE4GeOXOAj2VzedHkASNwjmwlwtutJCLpCJbIs37wRGTFgWRoEcD72jpMX+IBJUGjQ==}
|
||||
'@oxfmt/binding-linux-arm-gnueabihf@0.79.0':
|
||||
resolution: {integrity: sha512-Pt35GoxiMUfnr+23cuzk07XQVvISDFxxPcp/aFVB87+RQvJoQaBo/XN7Re9XxgElvbELdyxTLnV9XM2aTfJeUA==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
|
||||
'@oxfmt/binding-linux-arm-musleabihf@0.66.0':
|
||||
resolution: {integrity: sha512-hNtR9/oU0CeTkq7JnRkmBQwqe17v2ZaAMLC4VcN7IIOWeRyWDk0knSPWS9iiLmtbZ2RRBBtsG01jQgkZmKCJeQ==}
|
||||
'@oxfmt/binding-linux-arm-musleabihf@0.79.0':
|
||||
resolution: {integrity: sha512-zPi9Dni58VKp3r1QUcFvnbJNfBr49qyecq0vlM4SaX/MSjmguq77VngirghDua5tyhIDfqdUMTCK2KRlnZFp/g==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
|
||||
'@oxfmt/binding-linux-arm64-gnu@0.66.0':
|
||||
resolution: {integrity: sha512-uwOVQ8i6I1LT/+eDzfsgrrcZp8Fn6NPVUPn8fF5gdFGekFf0PddF+LEuwsD0/pbNUcKZhDj2rQ5UpITh9gF4iQ==}
|
||||
'@oxfmt/binding-linux-arm64-gnu@0.79.0':
|
||||
resolution: {integrity: sha512-XhRehATEWjwX7VVEgDUD+7pfHYncQIJaEU0qsHvEKtu9XX0QYzcKvXhU9+URfiGX9WRh3wy2Ow+YCc3EeHtImg==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@oxfmt/binding-linux-arm64-musl@0.66.0':
|
||||
resolution: {integrity: sha512-tTkF2Dmx4nGAjmBlZb+UtTGqR/EK4ZrW9qBfzte07a9XWqzoGGKzpFFlyNDhQe+Uwql94+ReCTeNbhOXscw1Dg==}
|
||||
'@oxfmt/binding-linux-arm64-musl@0.79.0':
|
||||
resolution: {integrity: sha512-gbVjFZYug0MEyqvuTAzXGNxFJmBqBO32o1Fud1lG8bGs6oVz48ZtNQyEcAzqrOwaaG+Sxtv4gVzcsfht9aqmkg==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@oxfmt/binding-linux-ppc64-gnu@0.66.0':
|
||||
resolution: {integrity: sha512-F3cKHUav4yXOHn6GFnwpBhSYsJOYKKf9eqO/9jlEuqPxNw9zb98E9ZFct79gcg8pibUGkbveEu9WDlmXJpDzKw==}
|
||||
'@oxfmt/binding-linux-ppc64-gnu@0.79.0':
|
||||
resolution: {integrity: sha512-0N0sD3vnllyuiNh1r6zKvNXWE/CakcPKJAespg7XE2+sfvxpz5Q1iFah8sF5aedsOmVvbZaOPZcSHVmMosT1fA==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [ppc64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@oxfmt/binding-linux-riscv64-gnu@0.66.0':
|
||||
resolution: {integrity: sha512-K5fDaNZfDyQMYA/3qL21bqyN0X9T15LLwwbFPt2aHc94+ZG7bh0vZEsy2y7NlRnjjHFSwN+Hzg6ldJtbOriH4Q==}
|
||||
'@oxfmt/binding-linux-riscv64-gnu@0.79.0':
|
||||
resolution: {integrity: sha512-YtjqUHolcX6cv0ZMZuKQCM4H0ae/okcowy0wGcPHJk4O+8zjy3TvNhzDQ1/KGCkMJO8Fwulm1JcPJsraVJ3p+w==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@oxfmt/binding-linux-riscv64-musl@0.66.0':
|
||||
resolution: {integrity: sha512-44Yc+I+qOmTElRcEhm5hUKIUJEQIOugymz4ua4tB0Wox7tGAfIbjzmXz/HDAtw1Ij6gmBwZlzh4hc9679RhWeA==}
|
||||
'@oxfmt/binding-linux-riscv64-musl@0.79.0':
|
||||
resolution: {integrity: sha512-H2gb9bEBr5tcdP5FU8JYTfgOavXDorWcAAlwci/zEKF2jzgh/oEr/SAw6aHB9n3FLEvnKvOh0A1fjku+vgYoUA==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@oxfmt/binding-linux-s390x-gnu@0.66.0':
|
||||
resolution: {integrity: sha512-1e29Eg9hEj2kRBB19M0seIehPbbXHCk35GvImjDvb79rjjYjXCRmtbUNHJcgoktZAMIzXrTbxDBKmTc1V4bg3A==}
|
||||
'@oxfmt/binding-linux-s390x-gnu@0.79.0':
|
||||
resolution: {integrity: sha512-aZUbyWW5dSOxT/u6suWc4S9GVDt7YPPNMKQon+z79M8dpXmosadcFHAb7jBhpU7Hdsd2GN6/y3nd0JFTsGddZw==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [s390x]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@oxfmt/binding-linux-x64-gnu@0.66.0':
|
||||
resolution: {integrity: sha512-vODY1UQo10gngn0+D4xHKU84F1Twm1LqrzV4SqPXvmQKSd87paehvZ6jqA5wKs6XQrlWul9clYMDVHcoW9CPMA==}
|
||||
'@oxfmt/binding-linux-x64-gnu@0.79.0':
|
||||
resolution: {integrity: sha512-5pW/ZHYfjjQ71gQR+EKzDz8ZzWIDHlTUtWtxVFNgZbKxVZnRxiSXVrllbjpJtx1q8VtSPZ+Lyg9BLny3yw+PTA==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@oxfmt/binding-linux-x64-musl@0.66.0':
|
||||
resolution: {integrity: sha512-YDzXx2JsT4+HL4MdkVrYjO55NS5lUKNm8rLC4ZPou8+seu0v0jhecSh+ufoO6+xEa8gccEezMlI2WHJi4ApUgw==}
|
||||
'@oxfmt/binding-linux-x64-musl@0.79.0':
|
||||
resolution: {integrity: sha512-3IVUerTDB7Dvd90c1EurAzlVnlE9Azl7Wn8e33qX3wL/IqnslF+P7HvwkD+VeMbHxRtuw0EEBGSArZFXpUAZrQ==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@oxfmt/binding-openharmony-arm64@0.66.0':
|
||||
resolution: {integrity: sha512-mJjUYd8lj0+j4JkYyEM+5qKBf1Rnrpgjn/SVYKJhicVDqLz566ooa7Fs8zflPqt+dnZDV7X054rVIQX6ZcQNlQ==}
|
||||
'@oxfmt/binding-openharmony-arm64@0.79.0':
|
||||
resolution: {integrity: sha512-C5QDgJBtu9+/2BQScoP7ynv54PLOqfoSqhRWwI0D0RPOwYD4tYj0TUdJbXMO1fNegL/5zJiSOxkq6II2xvttWg==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [arm64]
|
||||
os: [openharmony]
|
||||
|
||||
'@oxfmt/binding-win32-arm64-msvc@0.66.0':
|
||||
resolution: {integrity: sha512-soV+0vESv7e5ntCHWC61x4gg8OSak6IHHnWsZmHrJFlvMj2AK+kmldErCNkVkrvc1Ts2/++rJXn+IuAb2WMXhw==}
|
||||
'@oxfmt/binding-win32-arm64-msvc@0.79.0':
|
||||
resolution: {integrity: sha512-zlW1m8M49vNGgqQF/ze80KW8pZMicnW2XDZGBHuYtXTRYn4ewvgpqN9wwoqb6uLZZfb1R1zaQWKEB8cs7KYjwA==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [arm64]
|
||||
os: [win32]
|
||||
|
||||
'@oxfmt/binding-win32-ia32-msvc@0.66.0':
|
||||
resolution: {integrity: sha512-YCPi23uRIEYuIKTZohAkKbPFpujQ5QBuUM5iDv+UqbCmTPAkaFsxjsSuB8xlBpRT0G7eP/4HMF+cPDSqHtOD9A==}
|
||||
'@oxfmt/binding-win32-ia32-msvc@0.79.0':
|
||||
resolution: {integrity: sha512-wbb7hFv2wK3SCTfu8dl1ydNsXM5dmH+PJMU3sojCkfKcG29VDpITL5/AtouCzXjkOc90QRkcAZcg36gP0KqoHA==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [ia32]
|
||||
os: [win32]
|
||||
|
||||
'@oxfmt/binding-win32-x64-msvc@0.66.0':
|
||||
resolution: {integrity: sha512-bwTQcv/JVRPkOqQtMF0X7vpvpncDQiBcXHxZ9S2hR12Hlo8bvBdUR5x5XnxzDZ3kM0qoZw1rv7KaD66Ly+pFWA==}
|
||||
'@oxfmt/binding-win32-x64-msvc@0.79.0':
|
||||
resolution: {integrity: sha512-JLaeaQ+4LkQiVXY06JIV1dBFEDJzssvDieK/3Poi6CsY+c4UxghZVrrsfcKGJ5R/0F2Sw3C5Lf5Hu0sM5qJfPw==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
@@ -3898,8 +3925,8 @@ packages:
|
||||
resolution: {integrity: sha512-GrwoxYN+uWlzO8uhUXRl0P+kHE4GtVPfYzVLcUxPL7KNdHKj66vvlhiweIHqYYXWlw+T8iLMp42Lm67ghw4WMQ==}
|
||||
engines: {node: '>= 4'}
|
||||
|
||||
dompurify@3.4.12:
|
||||
resolution: {integrity: sha512-zQvGet8Z2sWbQhCmfFz/T5QWH2oBmjnqK3qvOjaqaNLrLEF912WamU+ohnTp0TCep/MFVHpdJuCZEdFOdTnEFg==}
|
||||
dompurify@3.4.18:
|
||||
resolution: {integrity: sha512-ofe3wI/uNm68HInABYFJYqQxRw1EaKAjNdrFVKqjUY+UZurvNd2L/HuQe097s/4RivWiZyP6tT7aoT8atjfhwg==}
|
||||
|
||||
domutils@2.8.0:
|
||||
resolution: {integrity: sha512-w96Cjofp72M5IIhpjgobBimYEfoPjx1Vx0BSX9P30WBdZW2WIKU0T1Bd0kz2eNZ9ikjKgHbEyKx8BB6H1L3h3A==}
|
||||
@@ -4679,10 +4706,6 @@ packages:
|
||||
resolution: {integrity: sha512-ja1E3yCr9i/0hmBVaM0bfwDjnGy8I/s6PP4DFp+yP+a+mrHO4Rm7DtmnqROTUkHIkqffC84YY7AeqX6oFk0WFg==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
loglevel@1.9.1:
|
||||
resolution: {integrity: sha512-hP3I3kCrDIMuRwAwHltphhDM1r8i55H33GgqjXbrisuJhF4kRhW1dNuxsRklp4bXl8DSdLaNLuiL4A/LWRfxvg==}
|
||||
engines: {node: '>= 0.6.0'}
|
||||
|
||||
loglevel@1.9.2:
|
||||
resolution: {integrity: sha512-HgMmCqIJSAKqo68l0rS2AanEWfkxaZ5wNiEFb5ggm08lDs9Xl2KxBlX3PTcaD2chBM1gXAYf491/M2Rv8Jwayg==}
|
||||
engines: {node: '>= 0.6.0'}
|
||||
@@ -4734,9 +4757,9 @@ packages:
|
||||
matrix-events-sdk@0.0.1:
|
||||
resolution: {integrity: sha512-1QEOsXO+bhyCroIe2/A5OwaxHvBm7EsSQ46DEDn8RBIfQwN5HWBpFvyWWR4QY0KHPPnnJdI99wgRiAl7Ad5qaA==}
|
||||
|
||||
matrix-js-sdk@https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/a9ef09fbf2f1644c8663d0aeaf6a921cd16e7b01:
|
||||
resolution: {gitHosted: true, integrity: sha512-ZAhn/zB44MgrXqUzi9ffSFcmZY3+2nx7bEgfEJR7chYDFyT/XmlmfCJx7Ar4rOTAYZJRVnMxrEwiEHGDapUi0Q==, tarball: https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/a9ef09fbf2f1644c8663d0aeaf6a921cd16e7b01}
|
||||
version: 45.0.0
|
||||
matrix-js-sdk@https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/6c8b1b418189919bc69fd9df5e57354e7b3c39cb:
|
||||
resolution: {gitHosted: true, tarball: https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/6c8b1b418189919bc69fd9df5e57354e7b3c39cb}
|
||||
version: 45.1.0
|
||||
engines: {node: '>=22.0.0'}
|
||||
|
||||
matrix-widget-api@1.20.0:
|
||||
@@ -4900,14 +4923,17 @@ packages:
|
||||
oxc-resolver@11.21.2:
|
||||
resolution: {integrity: sha512-w5tLwYN3Zo24w5EeWJjJWZOwhYqTtC8PS2B1tIt7BZUuqTIcU07sQValbDw+rq7+AuAGzOHklgK+ifsy4lpXfw==}
|
||||
|
||||
oxfmt@0.66.0:
|
||||
resolution: {integrity: sha512-FfvqR8RFtV6JJpRrpkfqyVCQ7HDvZ/VriWFx7veftCgL1B5ZO9qNr+1rvPieycMQnNfVG0PWyJQiy7p0hq1I5w==}
|
||||
oxfmt@0.79.0:
|
||||
resolution: {integrity: sha512-92iLHGxAgtYk6jLp/1ZBnEeABveNduHZgMDQj7tyqO9iafuJG3q+YHJq0R5Aa4YT+E6xswMQXdmPZYMwynS8ig==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
hasBin: true
|
||||
peerDependencies:
|
||||
'@astrojs/compiler-rs': ^0.5.0
|
||||
svelte: ^5.0.0
|
||||
vite-plus: '*'
|
||||
peerDependenciesMeta:
|
||||
'@astrojs/compiler-rs':
|
||||
optional: true
|
||||
svelte:
|
||||
optional: true
|
||||
vite-plus:
|
||||
@@ -4946,8 +4972,8 @@ packages:
|
||||
resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==}
|
||||
engines: {node: '>=10'}
|
||||
|
||||
p-retry@8.0.1:
|
||||
resolution: {integrity: sha512-NAigyu8hfvJe7MsS18mnc4is0MZtau3QMdBklaJKK23oBQb6occO3UPM3vHmTckW8KhfyjMZaUOqdTFEYliHgg==}
|
||||
p-retry@9.0.0:
|
||||
resolution: {integrity: sha512-HuEats8gYn/UUYa5uyveyQGv75mQmwdFtuMgnZlS12dj/7bdnJSO6keaTjgcZUhvkANTj5EO3lACUmV3xmgj0Q==}
|
||||
engines: {node: '>=22'}
|
||||
|
||||
p-try@2.2.0:
|
||||
@@ -5318,6 +5344,10 @@ packages:
|
||||
randomfill@1.0.4:
|
||||
resolution: {integrity: sha512-87lcbR8+MhcWcUiQ+9e+Rwx8MyR2P7qnt15ynUlbm3TU/fjbgz4GsvfSUDTemtCCtVCqb4ZcEFlyPNTh9bBTLw==}
|
||||
|
||||
re2js@2.9.1:
|
||||
resolution: {integrity: sha512-JIT3bEEUZTOR2YS1walNEIfH4cF/cQeZcBUFq7ldqO6lR6g0X5CBq/S8rsa9omzZcsNf8qc36jCkWpKKtncrZg==}
|
||||
engines: {node: '>=20.0.0'}
|
||||
|
||||
react-docgen-typescript@2.4.0:
|
||||
resolution: {integrity: sha512-ZtAp5XTO5HRzQctjPU0ybY0RRCQO19X/8fxn3w7y2VVTUbGHDKULPTL4ky3vB05euSgG5NpALhEhDPvQ56wvXg==}
|
||||
peerDependencies:
|
||||
@@ -5477,6 +5507,9 @@ packages:
|
||||
require-main-filename@2.0.0:
|
||||
resolution: {integrity: sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==}
|
||||
|
||||
reselect@5.3.0:
|
||||
resolution: {integrity: sha512-XGoLeRAVzUTcJ1qkxPQhDJyIZ5d6zzZD9nT7AEZOaaU9UbWclhycElmhO+VD5bFeLuzhPBaOV2oXC8uG35ZSpg==}
|
||||
|
||||
resolve-from@4.0.0:
|
||||
resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==}
|
||||
engines: {node: '>=4'}
|
||||
@@ -5787,8 +5820,8 @@ packages:
|
||||
resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}
|
||||
engines: {node: '>=12.0.0'}
|
||||
|
||||
tinypool@2.1.0:
|
||||
resolution: {integrity: sha512-Pugqs6M0m7Lv1I7FtxN4aoyToKg1C4tu+/381vH35y8oENM/Ai7f7C4StcoK4/+BSw9ebcS8jRiVrORFKCALLw==}
|
||||
tinypool@2.2.0:
|
||||
resolution: {integrity: sha512-jBrmx4lYmaC9k/mgPbylxs7kBUxHtD8256up+HjLaDFfXScKJQyil+SWXSvhAtT7XHo+yTVlpB81PGmHP8oLSQ==}
|
||||
engines: {node: ^20.0.0 || >=22.0.0}
|
||||
|
||||
tinyrainbow@2.0.0:
|
||||
@@ -6432,6 +6465,29 @@ snapshots:
|
||||
'@babel/helper-string-parser': 7.29.7
|
||||
'@babel/helper-validator-identifier': 7.29.7
|
||||
|
||||
'@base-ui/react@1.9.0(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)':
|
||||
dependencies:
|
||||
'@babel/runtime': 8.0.8
|
||||
'@base-ui/utils': 0.5.0(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)
|
||||
'@floating-ui/react-dom': 2.1.9(react-dom@19.2.8(react@19.2.8))(react@19.2.8)
|
||||
'@floating-ui/utils': 0.2.12
|
||||
react: 19.2.8
|
||||
react-dom: 19.2.8(react@19.2.8)
|
||||
use-sync-external-store: 1.7.0(react@19.2.8)
|
||||
optionalDependencies:
|
||||
'@types/react': 19.2.18
|
||||
|
||||
'@base-ui/utils@0.5.0(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)':
|
||||
dependencies:
|
||||
'@babel/runtime': 8.0.8
|
||||
'@floating-ui/utils': 0.2.12
|
||||
react: 19.2.8
|
||||
react-dom: 19.2.8(react@19.2.8)
|
||||
reselect: 5.3.0
|
||||
use-sync-external-store: 1.7.0(react@19.2.8)
|
||||
optionalDependencies:
|
||||
'@types/react': 19.2.18
|
||||
|
||||
'@bcoe/v8-coverage@1.0.2': {}
|
||||
|
||||
'@blazediff/core@1.9.1': {}
|
||||
@@ -6916,11 +6972,6 @@ snapshots:
|
||||
dependencies:
|
||||
'@floating-ui/utils': 0.2.12
|
||||
|
||||
'@floating-ui/dom@1.7.6':
|
||||
dependencies:
|
||||
'@floating-ui/core': 1.8.0
|
||||
'@floating-ui/utils': 0.2.12
|
||||
|
||||
'@floating-ui/dom@1.8.0':
|
||||
dependencies:
|
||||
'@floating-ui/core': 1.8.0
|
||||
@@ -7154,11 +7205,11 @@ snapshots:
|
||||
'@jridgewell/resolve-uri': 3.1.2
|
||||
'@jridgewell/sourcemap-codec': 1.6.0
|
||||
|
||||
'@livekit/components-core@0.12.15(livekit-client@2.23.0(@types/dom-mediacapture-record@1.0.22))(tslib@2.8.1)':
|
||||
'@livekit/components-core@0.12.16(livekit-client@2.23.0(@types/dom-mediacapture-record@1.0.22))(tslib@2.8.1)':
|
||||
dependencies:
|
||||
'@floating-ui/dom': 1.7.6
|
||||
'@floating-ui/dom': 1.8.0
|
||||
livekit-client: 2.23.0(@types/dom-mediacapture-record@1.0.22)
|
||||
loglevel: 1.9.1
|
||||
loglevel: 1.9.2
|
||||
rxjs: 7.8.2
|
||||
tslib: 2.8.1
|
||||
|
||||
@@ -7174,7 +7225,7 @@ snapshots:
|
||||
'@types/dom-mediacapture-transform': 0.1.11
|
||||
livekit-client: 2.23.0(@types/dom-mediacapture-record@1.0.22)
|
||||
|
||||
'@matrix-org/matrix-sdk-crypto-wasm@18.9.0': {}
|
||||
'@matrix-org/matrix-sdk-crypto-wasm@18.9.2': {}
|
||||
|
||||
'@mdx-js/react@3.1.1(@types/react@19.2.18)(react@19.3.1)':
|
||||
dependencies:
|
||||
@@ -7472,61 +7523,61 @@ snapshots:
|
||||
'@oxc-resolver/binding-win32-x64-msvc@11.21.2':
|
||||
optional: true
|
||||
|
||||
'@oxfmt/binding-android-arm-eabi@0.66.0':
|
||||
'@oxfmt/binding-android-arm-eabi@0.79.0':
|
||||
optional: true
|
||||
|
||||
'@oxfmt/binding-android-arm64@0.66.0':
|
||||
'@oxfmt/binding-android-arm64@0.79.0':
|
||||
optional: true
|
||||
|
||||
'@oxfmt/binding-darwin-arm64@0.66.0':
|
||||
'@oxfmt/binding-darwin-arm64@0.79.0':
|
||||
optional: true
|
||||
|
||||
'@oxfmt/binding-darwin-x64@0.66.0':
|
||||
'@oxfmt/binding-darwin-x64@0.79.0':
|
||||
optional: true
|
||||
|
||||
'@oxfmt/binding-freebsd-x64@0.66.0':
|
||||
'@oxfmt/binding-freebsd-x64@0.79.0':
|
||||
optional: true
|
||||
|
||||
'@oxfmt/binding-linux-arm-gnueabihf@0.66.0':
|
||||
'@oxfmt/binding-linux-arm-gnueabihf@0.79.0':
|
||||
optional: true
|
||||
|
||||
'@oxfmt/binding-linux-arm-musleabihf@0.66.0':
|
||||
'@oxfmt/binding-linux-arm-musleabihf@0.79.0':
|
||||
optional: true
|
||||
|
||||
'@oxfmt/binding-linux-arm64-gnu@0.66.0':
|
||||
'@oxfmt/binding-linux-arm64-gnu@0.79.0':
|
||||
optional: true
|
||||
|
||||
'@oxfmt/binding-linux-arm64-musl@0.66.0':
|
||||
'@oxfmt/binding-linux-arm64-musl@0.79.0':
|
||||
optional: true
|
||||
|
||||
'@oxfmt/binding-linux-ppc64-gnu@0.66.0':
|
||||
'@oxfmt/binding-linux-ppc64-gnu@0.79.0':
|
||||
optional: true
|
||||
|
||||
'@oxfmt/binding-linux-riscv64-gnu@0.66.0':
|
||||
'@oxfmt/binding-linux-riscv64-gnu@0.79.0':
|
||||
optional: true
|
||||
|
||||
'@oxfmt/binding-linux-riscv64-musl@0.66.0':
|
||||
'@oxfmt/binding-linux-riscv64-musl@0.79.0':
|
||||
optional: true
|
||||
|
||||
'@oxfmt/binding-linux-s390x-gnu@0.66.0':
|
||||
'@oxfmt/binding-linux-s390x-gnu@0.79.0':
|
||||
optional: true
|
||||
|
||||
'@oxfmt/binding-linux-x64-gnu@0.66.0':
|
||||
'@oxfmt/binding-linux-x64-gnu@0.79.0':
|
||||
optional: true
|
||||
|
||||
'@oxfmt/binding-linux-x64-musl@0.66.0':
|
||||
'@oxfmt/binding-linux-x64-musl@0.79.0':
|
||||
optional: true
|
||||
|
||||
'@oxfmt/binding-openharmony-arm64@0.66.0':
|
||||
'@oxfmt/binding-openharmony-arm64@0.79.0':
|
||||
optional: true
|
||||
|
||||
'@oxfmt/binding-win32-arm64-msvc@0.66.0':
|
||||
'@oxfmt/binding-win32-arm64-msvc@0.79.0':
|
||||
optional: true
|
||||
|
||||
'@oxfmt/binding-win32-ia32-msvc@0.66.0':
|
||||
'@oxfmt/binding-win32-ia32-msvc@0.79.0':
|
||||
optional: true
|
||||
|
||||
'@oxfmt/binding-win32-x64-msvc@0.66.0':
|
||||
'@oxfmt/binding-win32-x64-msvc@0.79.0':
|
||||
optional: true
|
||||
|
||||
'@oxlint-tsgolint/darwin-arm64@0.25.0':
|
||||
@@ -9511,7 +9562,7 @@ snapshots:
|
||||
dependencies:
|
||||
domelementtype: 2.3.0
|
||||
|
||||
dompurify@3.4.12:
|
||||
dompurify@3.4.18:
|
||||
optionalDependencies:
|
||||
'@types/trusted-types': 2.0.7
|
||||
|
||||
@@ -10025,7 +10076,7 @@ snapshots:
|
||||
|
||||
i18next-resources-for-ts@2.1.0:
|
||||
dependencies:
|
||||
'@babel/runtime': 7.29.7
|
||||
'@babel/runtime': 7.29.10
|
||||
'@swc/core': 1.16.2
|
||||
chokidar: 5.0.0
|
||||
yaml: 2.9.0
|
||||
@@ -10359,8 +10410,6 @@ snapshots:
|
||||
is-unicode-supported: 2.1.0
|
||||
yoctocolors: 2.2.0
|
||||
|
||||
loglevel@1.9.1: {}
|
||||
|
||||
loglevel@1.9.2: {}
|
||||
|
||||
loupe@3.2.1: {}
|
||||
@@ -10409,17 +10458,18 @@ snapshots:
|
||||
|
||||
matrix-events-sdk@0.0.1: {}
|
||||
|
||||
matrix-js-sdk@https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/a9ef09fbf2f1644c8663d0aeaf6a921cd16e7b01:
|
||||
matrix-js-sdk@https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/6c8b1b418189919bc69fd9df5e57354e7b3c39cb:
|
||||
dependencies:
|
||||
'@babel/runtime': 8.0.8
|
||||
'@matrix-org/matrix-sdk-crypto-wasm': 18.9.0
|
||||
'@matrix-org/matrix-sdk-crypto-wasm': 18.9.2
|
||||
another-json: 0.2.0
|
||||
bs58: 6.0.0
|
||||
content-type: 3.1.1
|
||||
loglevel: 1.9.2
|
||||
matrix-events-sdk: 0.0.1
|
||||
matrix-widget-api: 1.20.0
|
||||
p-retry: 8.0.1
|
||||
p-retry: 9.0.0
|
||||
re2js: 2.9.1
|
||||
sdp-transform: 3.0.0
|
||||
unhomoglyph: 1.0.6
|
||||
|
||||
@@ -10669,29 +10719,29 @@ snapshots:
|
||||
'@oxc-resolver/binding-win32-arm64-msvc': 11.21.2
|
||||
'@oxc-resolver/binding-win32-x64-msvc': 11.21.2
|
||||
|
||||
oxfmt@0.66.0:
|
||||
oxfmt@0.79.0:
|
||||
dependencies:
|
||||
tinypool: 2.1.0
|
||||
tinypool: 2.2.0
|
||||
optionalDependencies:
|
||||
'@oxfmt/binding-android-arm-eabi': 0.66.0
|
||||
'@oxfmt/binding-android-arm64': 0.66.0
|
||||
'@oxfmt/binding-darwin-arm64': 0.66.0
|
||||
'@oxfmt/binding-darwin-x64': 0.66.0
|
||||
'@oxfmt/binding-freebsd-x64': 0.66.0
|
||||
'@oxfmt/binding-linux-arm-gnueabihf': 0.66.0
|
||||
'@oxfmt/binding-linux-arm-musleabihf': 0.66.0
|
||||
'@oxfmt/binding-linux-arm64-gnu': 0.66.0
|
||||
'@oxfmt/binding-linux-arm64-musl': 0.66.0
|
||||
'@oxfmt/binding-linux-ppc64-gnu': 0.66.0
|
||||
'@oxfmt/binding-linux-riscv64-gnu': 0.66.0
|
||||
'@oxfmt/binding-linux-riscv64-musl': 0.66.0
|
||||
'@oxfmt/binding-linux-s390x-gnu': 0.66.0
|
||||
'@oxfmt/binding-linux-x64-gnu': 0.66.0
|
||||
'@oxfmt/binding-linux-x64-musl': 0.66.0
|
||||
'@oxfmt/binding-openharmony-arm64': 0.66.0
|
||||
'@oxfmt/binding-win32-arm64-msvc': 0.66.0
|
||||
'@oxfmt/binding-win32-ia32-msvc': 0.66.0
|
||||
'@oxfmt/binding-win32-x64-msvc': 0.66.0
|
||||
'@oxfmt/binding-android-arm-eabi': 0.79.0
|
||||
'@oxfmt/binding-android-arm64': 0.79.0
|
||||
'@oxfmt/binding-darwin-arm64': 0.79.0
|
||||
'@oxfmt/binding-darwin-x64': 0.79.0
|
||||
'@oxfmt/binding-freebsd-x64': 0.79.0
|
||||
'@oxfmt/binding-linux-arm-gnueabihf': 0.79.0
|
||||
'@oxfmt/binding-linux-arm-musleabihf': 0.79.0
|
||||
'@oxfmt/binding-linux-arm64-gnu': 0.79.0
|
||||
'@oxfmt/binding-linux-arm64-musl': 0.79.0
|
||||
'@oxfmt/binding-linux-ppc64-gnu': 0.79.0
|
||||
'@oxfmt/binding-linux-riscv64-gnu': 0.79.0
|
||||
'@oxfmt/binding-linux-riscv64-musl': 0.79.0
|
||||
'@oxfmt/binding-linux-s390x-gnu': 0.79.0
|
||||
'@oxfmt/binding-linux-x64-gnu': 0.79.0
|
||||
'@oxfmt/binding-linux-x64-musl': 0.79.0
|
||||
'@oxfmt/binding-openharmony-arm64': 0.79.0
|
||||
'@oxfmt/binding-win32-arm64-msvc': 0.79.0
|
||||
'@oxfmt/binding-win32-ia32-msvc': 0.79.0
|
||||
'@oxfmt/binding-win32-x64-msvc': 0.79.0
|
||||
|
||||
oxlint-tsgolint@0.25.0:
|
||||
optionalDependencies:
|
||||
@@ -10741,7 +10791,7 @@ snapshots:
|
||||
dependencies:
|
||||
p-limit: 3.1.0
|
||||
|
||||
p-retry@8.0.1:
|
||||
p-retry@9.0.0:
|
||||
dependencies:
|
||||
is-network-error: 1.3.2
|
||||
|
||||
@@ -11093,7 +11143,7 @@ snapshots:
|
||||
'@posthog/core': 1.46.4
|
||||
'@posthog/types': 1.400.0
|
||||
core-js: 3.49.0
|
||||
dompurify: 3.4.12
|
||||
dompurify: 3.4.18
|
||||
fflate: 0.4.8
|
||||
preact: 10.29.8
|
||||
query-selector-shadow-dom: 1.0.1
|
||||
@@ -11165,6 +11215,8 @@ snapshots:
|
||||
randombytes: 2.1.0
|
||||
safe-buffer: 5.2.1
|
||||
|
||||
re2js@2.9.1: {}
|
||||
|
||||
react-docgen-typescript@2.4.0(typescript@5.9.3):
|
||||
dependencies:
|
||||
typescript: 5.9.3
|
||||
@@ -11207,7 +11259,7 @@ snapshots:
|
||||
|
||||
react-i18next@17.0.13(i18next@26.4.1(typescript@5.9.3))(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(typescript@5.9.3):
|
||||
dependencies:
|
||||
'@babel/runtime': 7.29.7
|
||||
'@babel/runtime': 7.29.10
|
||||
html-parse-stringify: 4.0.1
|
||||
i18next: 26.4.1(typescript@5.9.3)
|
||||
react: 19.2.8
|
||||
@@ -11314,6 +11366,8 @@ snapshots:
|
||||
|
||||
require-main-filename@2.0.0: {}
|
||||
|
||||
reselect@5.3.0: {}
|
||||
|
||||
resolve-from@4.0.0: {}
|
||||
|
||||
resolve@1.22.12:
|
||||
@@ -11664,7 +11718,7 @@ snapshots:
|
||||
fdir: 6.5.0(picomatch@4.0.5)
|
||||
picomatch: 4.0.5
|
||||
|
||||
tinypool@2.1.0: {}
|
||||
tinypool@2.2.0: {}
|
||||
|
||||
tinyrainbow@2.0.0: {}
|
||||
|
||||
|
||||
+4
-1
@@ -59,4 +59,7 @@ 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"
|
||||
|
||||
+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",
|
||||
|
||||
@@ -128,20 +128,22 @@ export async function createMatrixRTCSdk(
|
||||
});
|
||||
vm = createCallViewModel$(
|
||||
scope,
|
||||
participation,
|
||||
room,
|
||||
mediaDevices,
|
||||
muteStates,
|
||||
{
|
||||
rtcParticipation: participation,
|
||||
matrixRoom: room,
|
||||
mediaDevices,
|
||||
muteStates,
|
||||
encryptionSystem,
|
||||
// The bundle owns its page, so the body is the space it has
|
||||
viewSize$: scope.behavior(observeElementSize$(document.body)),
|
||||
handsRaisedSubject$: of({}),
|
||||
reactionsSubject$: of({}),
|
||||
},
|
||||
{
|
||||
...callViewModelOptionsFromParams(urlParams),
|
||||
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$
|
||||
|
||||
+7
-10
@@ -66,14 +66,9 @@ media backend: whatever carries the media, behind the `MediaBackend` interface i
|
||||
`sdk/src/media-backend/api.ts`. The client is the join of the two: a member exists
|
||||
once its membership does, and gets its media once the backend has something
|
||||
for that membership on its transport; `state$` is the membership state combined
|
||||
with the local media connection. Two backends exist, LiveKit (`livekit/`) and
|
||||
full mesh (`full-mesh/`, MSC4575), and the client always runs both, combined
|
||||
(`combineBackends.ts`). It publishes on the backend of the type of
|
||||
`options.transport`, LiveKit without one, and hands every remote member to the
|
||||
backend of that member's transport, so members on either are received. A
|
||||
backend nobody is on connects nowhere. Another transport is another folder
|
||||
under `sdk/src/media-backend/`, added to the combination, and nothing in the
|
||||
left box changes; `options.backend` replaces the combination altogether.
|
||||
with the local media connection. LiveKit is the one backend today; a
|
||||
cascading SFU or full mesh is another folder under `sdk/src/media-backend/`, handed
|
||||
in through `options.backend`, and nothing in the left box changes.
|
||||
|
||||
### How Element Call uses it
|
||||
|
||||
@@ -159,7 +154,7 @@ the sections below still describe `MatrixRTCClient` until that lands.
|
||||
| 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: LiveKit and full mesh combined, publishing on the type of `transport` in the join options, unless `backend` replaces them | "SFU", a LiveKit room, a peer connection |
|
||||
| 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`.
|
||||
@@ -639,7 +634,9 @@ export type MediaSource =
|
||||
| "unknown";
|
||||
|
||||
export type MediaStreamStats =
|
||||
RTCInboundRtpStreamStats | RTCOutboundRtpStreamStats | undefined;
|
||||
| RTCInboundRtpStreamStats
|
||||
| RTCOutboundRtpStreamStats
|
||||
| undefined;
|
||||
|
||||
/** One published track of a member. */
|
||||
export interface MediaTrack {
|
||||
|
||||
@@ -61,14 +61,6 @@ export {
|
||||
createLivekitBackend,
|
||||
type LivekitBackendOptions,
|
||||
} from "./src/media-backend/livekit/LivekitBackend";
|
||||
// Join with `transport: { type: FULL_MESH_TRANSPORT_TYPE }` to publish on full mesh
|
||||
export {
|
||||
createFullMeshBackend,
|
||||
FULL_MESH_TRANSPORT_TYPE,
|
||||
type FullMeshBackendOptions,
|
||||
} from "./src/media-backend/full-mesh/FullMeshBackend";
|
||||
// For a widget host to allow the full mesh signalling
|
||||
export { signallingEventTypes as fullMeshSignallingEventTypes } from "./src/media-backend/full-mesh/signalling";
|
||||
// Tracks for a lobby, captured ahead of the join and handed to it
|
||||
export { createLocalMedia } from "./src/LocalMedia";
|
||||
// For a host whose processor is a livekit-client one, such as @livekit/track-processors
|
||||
|
||||
@@ -152,6 +152,15 @@ describe("createLocalMedia", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// As the built-in camera of a Mac
|
||||
it("takes a camera that doesn't say which way it faces to face the user", async () => {
|
||||
const media = createLocalMedia(fakeGetUserMedia());
|
||||
const [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 [microphone, camera] = await media.capture([
|
||||
@@ -162,6 +171,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();
|
||||
@@ -197,6 +207,7 @@ function fakeTrack(
|
||||
const track = {
|
||||
kind,
|
||||
id: `${kind}-${nextId++}`,
|
||||
label: "",
|
||||
enabled: true,
|
||||
stop: vi.fn(),
|
||||
getSettings: () => settings,
|
||||
|
||||
+5
-15
@@ -19,6 +19,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";
|
||||
@@ -107,6 +108,7 @@ export function createLocalMedia(
|
||||
if (source !== "microphone" && source !== "camera") return;
|
||||
capturedTracks.get(source)?.stop();
|
||||
capturedTracks.delete(source);
|
||||
requests.delete(source);
|
||||
publishCapturedTracks();
|
||||
};
|
||||
|
||||
@@ -160,9 +162,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. */
|
||||
@@ -305,10 +305,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 +323,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;
|
||||
}
|
||||
|
||||
@@ -140,8 +140,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[]>([]);
|
||||
|
||||
|
||||
@@ -50,11 +50,6 @@ import {
|
||||
type MediaBackendContext,
|
||||
type MediaKey,
|
||||
} from "./media-backend/api";
|
||||
import { combineBackends } from "./media-backend/combineBackends";
|
||||
import {
|
||||
completeFullMeshTransport,
|
||||
createFullMeshBackend,
|
||||
} from "./media-backend/full-mesh/FullMeshBackend";
|
||||
import { createLivekitBackend } from "./media-backend/livekit/LivekitBackend";
|
||||
import { findRemotePublishLivekitTransport } from "./media-backend/livekit/RemotePublishTransport";
|
||||
import { createHomeserverConnected$ } from "./matrixrtc/HomeserverConnected";
|
||||
@@ -126,13 +121,6 @@ export function createRTCParticipation(
|
||||
: `${userId}:${deviceId}`,
|
||||
};
|
||||
|
||||
// The host names full mesh by its type alone; the device is ours
|
||||
if (options.transport)
|
||||
options = {
|
||||
...options,
|
||||
transport: completeFullMeshTransport(options.transport, deviceId),
|
||||
};
|
||||
|
||||
const backend = createBackend(scope, client, options, {
|
||||
roomId: room.roomId,
|
||||
slotId: jsSdkSession.slotId,
|
||||
@@ -196,6 +184,7 @@ export function createRTCParticipation(
|
||||
encryptMedia: encryptionSystem.kind !== E2eeType.NONE,
|
||||
matrixRTCMode,
|
||||
sendNotificationType: options.sendNotificationType,
|
||||
callIntent: options.callIntent,
|
||||
applicationData: options.applicationData,
|
||||
timings,
|
||||
delayedLeave,
|
||||
@@ -323,26 +312,15 @@ export function createRTCParticipation(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The host's backend, or every backend the SDK has, combined: we publish on
|
||||
* the type of the transport the host named (LiveKit without one) and receive
|
||||
* from members on any of them.
|
||||
*/
|
||||
/** The host's backend, or LiveKit configured from the participation options. */
|
||||
function createBackend(
|
||||
scope: ObservableScope,
|
||||
client: MatrixClient,
|
||||
{ backend, mediaQuality, transport }: RTCParticipationOptions,
|
||||
{ backend, mediaQuality }: RTCParticipationOptions,
|
||||
context: MediaBackendContext,
|
||||
): MediaBackend {
|
||||
if (backend) return backend(scope, context);
|
||||
return combineBackends(
|
||||
scope,
|
||||
[
|
||||
createLivekitBackend(scope, context, { client, mediaQuality }),
|
||||
createFullMeshBackend(scope, context, { client }),
|
||||
],
|
||||
transport?.type ?? "m.livekit",
|
||||
);
|
||||
return createLivekitBackend(scope, context, { client, mediaQuality });
|
||||
}
|
||||
|
||||
/** The slot's per-participant keys: the ones it already holds on subscribe, then each new one. */
|
||||
|
||||
+8
-4
@@ -12,6 +12,7 @@ Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import {
|
||||
type RTCCallIntent,
|
||||
type RTCNotificationType,
|
||||
type Transport,
|
||||
} from "matrix-js-sdk/lib/matrixrtc";
|
||||
@@ -103,11 +104,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. */
|
||||
@@ -287,7 +291,7 @@ export interface RTCMember {
|
||||
memberId: 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>;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -151,12 +151,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. */
|
||||
|
||||
@@ -125,15 +125,8 @@ export interface MediaBackend {
|
||||
* session found it; the backend does whatever has to succeed before it is
|
||||
* advertised in the membership. Rejects with the error the session reports
|
||||
* as fatal. Called once per session.
|
||||
*
|
||||
* `null` tells the backend that the local member publishes on another
|
||||
* backend: it only subscribes from then on. Until either call, a backend
|
||||
* that would connect for its publisher connects nowhere, so that it doesn't
|
||||
* subscribe to a transport it is about to publish on.
|
||||
*/
|
||||
prepareLocalTransport(
|
||||
transport: Transport | null,
|
||||
): Promise<TransportCapabilities>;
|
||||
prepareLocalTransport(transport: Transport): Promise<TransportCapabilities>;
|
||||
|
||||
/**
|
||||
* Hands the delayed leave event to the backend, which restarts it from
|
||||
|
||||
@@ -1,103 +0,0 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { BehaviorSubject, NEVER } from "rxjs";
|
||||
|
||||
import { type RTCMember, type TransportMetadata } from "../api";
|
||||
import { type MemberMedia } from "../media-api";
|
||||
import { constant } from "../reactive/Behavior";
|
||||
import { ObservableScope } from "../reactive/ObservableScope";
|
||||
import { type MediaBackend } from "./api";
|
||||
import { combineBackends } from "./combineBackends";
|
||||
|
||||
function fakeBackend(
|
||||
type: string,
|
||||
...moreTypes: string[]
|
||||
): MediaBackend & { ended: string[] } {
|
||||
const ended: string[] = [];
|
||||
return {
|
||||
ended,
|
||||
transportTypes: [type, ...moreTypes],
|
||||
prepareLocalTransport: vi.fn(async () =>
|
||||
Promise.resolve({ canDelegateDelayedLeave: false }),
|
||||
),
|
||||
delegateDelayedLeave: vi.fn(),
|
||||
local: {} as MediaBackend["local"],
|
||||
mediaFor: (scope, member): MemberMedia => {
|
||||
scope.onEnd(() => ended.push(member.memberId));
|
||||
return {
|
||||
tracks$: constant([{ id: `${type}:${member.memberId}` }] as never),
|
||||
encryptionError$: NEVER,
|
||||
};
|
||||
},
|
||||
connections$: constant([
|
||||
{ transport: { type }, state: "connected" as never, resolved: undefined },
|
||||
]),
|
||||
setAudioOutputDeviceId: vi.fn(),
|
||||
sendData: vi.fn(),
|
||||
data$: NEVER,
|
||||
};
|
||||
}
|
||||
|
||||
function transport(type: string): TransportMetadata {
|
||||
return { type, id: type, raw: { type }, resolved$: constant(undefined) };
|
||||
}
|
||||
|
||||
describe("combineBackends", () => {
|
||||
it("routes each member to the backend of its transport type", () => {
|
||||
const scope = new ObservableScope();
|
||||
const livekit = fakeBackend("m.livekit", "livekit");
|
||||
const other = fakeBackend("other");
|
||||
const combined = combineBackends(scope, [livekit, other], "livekit");
|
||||
expect(combined.transportTypes).toEqual(["m.livekit", "livekit"]);
|
||||
expect(combined.connections$.value).toHaveLength(2);
|
||||
|
||||
const transport$ = new BehaviorSubject<TransportMetadata | undefined>(
|
||||
transport("other"),
|
||||
);
|
||||
const memberScope = new ObservableScope();
|
||||
const media = combined.mediaFor(memberScope, {
|
||||
memberId: "m1",
|
||||
transport$,
|
||||
} as unknown as RTCMember);
|
||||
expect(media.tracks$.value).toEqual([{ id: "other:m1" }]);
|
||||
|
||||
// Either type of the publishing backend stays with it
|
||||
transport$.next(transport("livekit"));
|
||||
expect(other.ended).toEqual(["m1"]);
|
||||
expect(media.tracks$.value).toEqual([{ id: "m.livekit:m1" }]);
|
||||
transport$.next(transport("m.livekit"));
|
||||
expect(media.tracks$.value).toEqual([{ id: "m.livekit:m1" }]);
|
||||
|
||||
transport$.next(transport("unknown"));
|
||||
expect(media.tracks$.value).toBeNull();
|
||||
// The publishing backend keeps every member for as long as it is one
|
||||
expect(livekit.ended).toEqual([]);
|
||||
memberScope.end();
|
||||
expect(livekit.ended).toEqual(["m1"]);
|
||||
scope.end();
|
||||
});
|
||||
|
||||
it("publishes on the backend of the publish type, telling the others", async () => {
|
||||
const scope = new ObservableScope();
|
||||
const livekit = fakeBackend("livekit");
|
||||
const other = fakeBackend("other");
|
||||
const combined = combineBackends(scope, [livekit, other], "other");
|
||||
expect(combined.transportTypes).toEqual(["other"]);
|
||||
const transport = { type: "other" };
|
||||
await combined.prepareLocalTransport(transport);
|
||||
expect(other.prepareLocalTransport).toHaveBeenCalledExactlyOnceWith(
|
||||
transport,
|
||||
);
|
||||
expect(livekit.prepareLocalTransport).toHaveBeenCalledExactlyOnceWith(null);
|
||||
expect(() => combineBackends(scope, [livekit, other], "unknown")).toThrow(
|
||||
"No media backend for transport unknown",
|
||||
);
|
||||
scope.end();
|
||||
});
|
||||
});
|
||||
@@ -1,90 +0,0 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { combineLatest, map, merge, NEVER, of, switchMap } from "rxjs";
|
||||
|
||||
import { type RTCMember } from "../api";
|
||||
import { MatrixRTCError } from "../errors";
|
||||
import { type MemberMedia } from "../media-api";
|
||||
import { type ObservableScope } from "../reactive/ObservableScope";
|
||||
import { mapScoped } from "../utils/mapScoped";
|
||||
import { type MediaBackend } from "./api";
|
||||
|
||||
/**
|
||||
* Several backends as one: we publish on the backend of `publishType`, and
|
||||
* receive from every member on a transport any of the backends serves. A
|
||||
* member is handed to the backend of its current transport type. A backend
|
||||
* nobody is on costs nothing: it connects only for the members handed to it.
|
||||
*/
|
||||
export function combineBackends(
|
||||
scope: ObservableScope,
|
||||
all: MediaBackend[],
|
||||
publishType: string,
|
||||
): MediaBackend {
|
||||
const byType = new Map(
|
||||
all.flatMap((b) => b.transportTypes.map((type) => [type, b] as const)),
|
||||
);
|
||||
const publish = byType.get(publishType);
|
||||
if (publish === undefined)
|
||||
throw new MatrixRTCError(`No media backend for transport ${publishType}`);
|
||||
|
||||
const mediaFor = (
|
||||
memberScope: ObservableScope,
|
||||
member: RTCMember,
|
||||
): MemberMedia => {
|
||||
// The publishing backend sees every member, whatever its transport, so
|
||||
// that it can tell members from strangers when a backend is asked for our
|
||||
// media by members on other transports. It connects nowhere for them
|
||||
const publishMedia = publish.mediaFor(memberScope, member);
|
||||
const type$ = memberScope.behavior(
|
||||
member.transport$.pipe(map((transport) => transport?.type)),
|
||||
);
|
||||
const media$ = mapScoped(memberScope, type$, (s, type) =>
|
||||
type !== undefined && publish.transportTypes.includes(type)
|
||||
? publishMedia
|
||||
: byType.get(type)?.mediaFor(s, member),
|
||||
);
|
||||
return {
|
||||
tracks$: memberScope.behavior(
|
||||
media$.pipe(switchMap((media) => media?.tracks$ ?? of(null))),
|
||||
),
|
||||
encryptionError$: media$.pipe(
|
||||
switchMap((media) => media?.encryptionError$ ?? NEVER),
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
transportTypes: publish.transportTypes,
|
||||
// The others learn that they only subscribe
|
||||
prepareLocalTransport: async (transport) => {
|
||||
const [capabilities] = await Promise.all([
|
||||
publish.prepareLocalTransport(transport),
|
||||
...all
|
||||
.filter((b) => b !== publish)
|
||||
.map(async (b) => b.prepareLocalTransport(null)),
|
||||
]);
|
||||
return capabilities;
|
||||
},
|
||||
delegateDelayedLeave: async (delayId) =>
|
||||
publish.delegateDelayedLeave(delayId),
|
||||
local: publish.local,
|
||||
mediaFor,
|
||||
connections$: scope.behavior(
|
||||
combineLatest(all.map((b) => b.connections$)).pipe(
|
||||
map((lists) => lists.flat()),
|
||||
),
|
||||
),
|
||||
setAudioOutputDeviceId: async (deviceId) => {
|
||||
await Promise.all(
|
||||
all.map(async (b) => b.setAudioOutputDeviceId(deviceId)),
|
||||
);
|
||||
},
|
||||
sendData: async (topic, text) => publish.sendData(topic, text),
|
||||
data$: merge(...all.map((b) => b.data$)),
|
||||
};
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
/**
|
||||
* The control channel of a full mesh connection (MSC4575): a negotiated data
|
||||
* channel both sides create, which carries every message of the connection
|
||||
* once it is open, apart from `close`.
|
||||
*/
|
||||
|
||||
import {
|
||||
type ConsumptionMetadata,
|
||||
parseConsumptionMetadata,
|
||||
parseTrackMetadata,
|
||||
type TrackMetadata,
|
||||
} from "./metadata";
|
||||
|
||||
export const CONTROL_CHANNEL_LABEL = "org.matrix.msc4575.rtc.full_mesh.control";
|
||||
const CONTROL_CHANNEL_ID = 0;
|
||||
|
||||
export type ControlMessage =
|
||||
| {
|
||||
type: "description";
|
||||
description: { type: "offer" | "answer"; sdp: string };
|
||||
track_metadata?: TrackMetadata;
|
||||
}
|
||||
| { type: "candidates"; candidates: RTCIceCandidateInit[] }
|
||||
| { type: "track_metadata"; track_metadata: TrackMetadata }
|
||||
| { type: "consumption_metadata"; consumption_metadata: ConsumptionMetadata };
|
||||
|
||||
export function createControlChannel(pc: RTCPeerConnection): RTCDataChannel {
|
||||
return pc.createDataChannel(CONTROL_CHANNEL_LABEL, {
|
||||
negotiated: true,
|
||||
id: CONTROL_CHANNEL_ID,
|
||||
});
|
||||
}
|
||||
|
||||
/** A received control message, or null for one to ignore: malformed, or of a type we don't know. */
|
||||
export function parseControlMessage(data: unknown): ControlMessage | null {
|
||||
if (typeof data !== "string") return null;
|
||||
let m: Record<string, unknown>;
|
||||
try {
|
||||
m = JSON.parse(data) as Record<string, unknown>;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (typeof m !== "object" || m === null) return null;
|
||||
switch (m.type) {
|
||||
case "description": {
|
||||
const d = m.description as { type?: unknown; sdp?: unknown } | undefined;
|
||||
if (
|
||||
(d?.type !== "offer" && d?.type !== "answer") ||
|
||||
typeof d.sdp !== "string"
|
||||
)
|
||||
return null;
|
||||
return {
|
||||
type: "description",
|
||||
description: { type: d.type, sdp: d.sdp },
|
||||
track_metadata: parseTrackMetadata(m.track_metadata) ?? undefined,
|
||||
};
|
||||
}
|
||||
case "candidates":
|
||||
if (!Array.isArray(m.candidates)) return null;
|
||||
return {
|
||||
type: "candidates",
|
||||
candidates: m.candidates as RTCIceCandidateInit[],
|
||||
};
|
||||
case "track_metadata": {
|
||||
const metadata = parseTrackMetadata(m.track_metadata);
|
||||
return metadata && { type: "track_metadata", track_metadata: metadata };
|
||||
}
|
||||
case "consumption_metadata": {
|
||||
const metadata = parseConsumptionMetadata(m.consumption_metadata);
|
||||
return (
|
||||
metadata && {
|
||||
type: "consumption_metadata",
|
||||
consumption_metadata: metadata,
|
||||
}
|
||||
);
|
||||
}
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,516 +0,0 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { EventEmitter } from "events";
|
||||
import {
|
||||
ClientEvent,
|
||||
EventType,
|
||||
type ITurnServer,
|
||||
MatrixEvent,
|
||||
} from "matrix-js-sdk";
|
||||
import { logger } from "matrix-js-sdk/lib/logger";
|
||||
import { type Transport } from "matrix-js-sdk/lib/matrixrtc";
|
||||
import { BehaviorSubject, NEVER } from "rxjs";
|
||||
|
||||
import { type RTCMember, type TransportMetadata } from "../../api";
|
||||
import { defaultSessionTimings } from "../../config";
|
||||
import { E2eeType } from "../../encryption";
|
||||
import { constant } from "../../reactive/Behavior";
|
||||
import { ObservableScope } from "../../reactive/ObservableScope";
|
||||
import {
|
||||
type DataPacket,
|
||||
type MediaBackend,
|
||||
MediaConnectionState,
|
||||
} from "../api";
|
||||
import {
|
||||
completeFullMeshTransport,
|
||||
createFullMeshBackend,
|
||||
type FullMeshBackendOptions,
|
||||
} from "./FullMeshBackend";
|
||||
import { DATA_CHANNEL_LABEL, DATA_PROTOCOL } from "./metadata";
|
||||
import { FULL_MESH_TRANSPORT_TYPE, SignallingEventType } from "./signalling";
|
||||
import {
|
||||
FakePeerConnection,
|
||||
installWebRtcFakes,
|
||||
lastPeerConnection,
|
||||
peer,
|
||||
settle,
|
||||
} from "./test";
|
||||
|
||||
const roomId = "!room:example.org";
|
||||
const slotId = "m.call#ROOM";
|
||||
const own = { userId: "@me:example.org", deviceId: "MYDEVICE", memberId: "me" };
|
||||
|
||||
const fullMesh = (deviceId: string): Transport => ({
|
||||
type: FULL_MESH_TRANSPORT_TYPE,
|
||||
device_id: deviceId,
|
||||
});
|
||||
const livekit: Transport = { type: "livekit", livekit_service_url: "x" };
|
||||
|
||||
function metadata(raw: Transport): TransportMetadata {
|
||||
return {
|
||||
type: raw.type,
|
||||
id: JSON.stringify(raw),
|
||||
raw,
|
||||
resolved$: constant(undefined),
|
||||
};
|
||||
}
|
||||
|
||||
describe("createFullMeshBackend", () => {
|
||||
let scope: ObservableScope;
|
||||
let client: EventEmitter & FullMeshBackendOptions["client"];
|
||||
let send: ReturnType<typeof vi.fn>;
|
||||
let turnServers: ITurnServer[];
|
||||
let backend: MediaBackend;
|
||||
const seq = new Map<string, number>();
|
||||
|
||||
/** A to-device message from `peer` (or another sender), as the sync would deliver it. */
|
||||
function deliver(
|
||||
type: string,
|
||||
connectionId: string,
|
||||
content: Record<string, unknown> = {},
|
||||
from = peer,
|
||||
): void {
|
||||
const next = seq.get(from.memberId) ?? 0;
|
||||
seq.set(from.memberId, next + 1);
|
||||
const event = new MatrixEvent({
|
||||
type,
|
||||
sender: from.userId,
|
||||
content: {
|
||||
room_id: roomId,
|
||||
slot_id: slotId,
|
||||
member_id: from.memberId,
|
||||
target_member_id: own.memberId,
|
||||
claimed_device_id: from.deviceId,
|
||||
connection_id: connectionId,
|
||||
seq: next,
|
||||
...content,
|
||||
},
|
||||
});
|
||||
vi.spyOn(event, "getWireType").mockReturnValue(
|
||||
EventType.RoomMessageEncrypted,
|
||||
);
|
||||
client.emit(ClientEvent.ToDeviceEvent, event);
|
||||
}
|
||||
|
||||
/** What we sent, as [type, recipient device, content]. */
|
||||
function sent(type?: string): [string, string, Record<string, unknown>][] {
|
||||
return send.mock.calls
|
||||
.filter(([t]) => type === undefined || t === type)
|
||||
.map(([t, [target], content]) => [t, target.deviceId, content]);
|
||||
}
|
||||
|
||||
/** A member of the slot, as the session hands it to the backend. */
|
||||
function addMember(
|
||||
transport: Transport,
|
||||
who = peer,
|
||||
): { scope: ObservableScope; tracks: () => unknown } {
|
||||
const memberScope = new ObservableScope();
|
||||
const media = backend.mediaFor(memberScope, {
|
||||
...who,
|
||||
rtcBackendIdentity: `${who.userId}:${who.deviceId}`,
|
||||
transport$: new BehaviorSubject(metadata(transport)),
|
||||
} as unknown as RTCMember);
|
||||
return { scope: memberScope, tracks: () => media.tracks$.value };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
installWebRtcFakes();
|
||||
seq.clear();
|
||||
scope = new ObservableScope();
|
||||
send = vi.fn(async () => Promise.resolve());
|
||||
turnServers = [];
|
||||
client = Object.assign(new EventEmitter(), {
|
||||
encryptAndSendToDevice: send,
|
||||
getTurnServers: (): ITurnServer[] => turnServers,
|
||||
checkTurnServers: vi.fn(async () => {
|
||||
turnServers = [{ urls: ["turn:x"], username: "u", credential: "p" }];
|
||||
return Promise.resolve(true);
|
||||
}),
|
||||
}) as unknown as EventEmitter & FullMeshBackendOptions["client"];
|
||||
backend = createFullMeshBackend(
|
||||
scope,
|
||||
{
|
||||
roomId,
|
||||
slotId,
|
||||
ownMembershipIdentity: own,
|
||||
publish: [],
|
||||
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
|
||||
mediaKeys$: NEVER,
|
||||
timings: defaultSessionTimings,
|
||||
logger,
|
||||
},
|
||||
{ client },
|
||||
);
|
||||
});
|
||||
afterEach(() => {
|
||||
scope.end();
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("only prepares a full mesh transport", async () => {
|
||||
await expect(backend.prepareLocalTransport(livekit)).rejects.toThrow(
|
||||
"Not a full mesh transport: livekit",
|
||||
);
|
||||
await expect(
|
||||
backend.prepareLocalTransport(fullMesh(own.deviceId)),
|
||||
).resolves.toEqual({ canDelegateDelayedLeave: false });
|
||||
expect(backend.local.connectionState$.value).toBe(
|
||||
MediaConnectionState.Connected,
|
||||
);
|
||||
});
|
||||
|
||||
it("subscribes all the same when told that another backend publishes", async () => {
|
||||
await expect(backend.prepareLocalTransport(null)).resolves.toEqual({
|
||||
canDelegateDelayedLeave: false,
|
||||
});
|
||||
addMember(fullMesh(peer.deviceId));
|
||||
await settle();
|
||||
expect(sent(SignallingEventType.subscribe)).toHaveLength(1);
|
||||
// Still not publishing
|
||||
deliver(SignallingEventType.subscribe, "c1");
|
||||
await settle();
|
||||
expect(sent(SignallingEventType.close)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("fetches TURN servers when the client has none yet", async () => {
|
||||
await backend.prepareLocalTransport(fullMesh(own.deviceId));
|
||||
expect(client.checkTurnServers).toHaveBeenCalledOnce();
|
||||
addMember(fullMesh(peer.deviceId));
|
||||
await settle();
|
||||
expect(lastPeerConnection().config.iceServers).toEqual([
|
||||
{ urls: ["turn:x"], username: "u", credential: "p" },
|
||||
]);
|
||||
});
|
||||
|
||||
describe("as a publisher", () => {
|
||||
it("turns subscribers away while it doesn't publish", async () => {
|
||||
addMember(livekit);
|
||||
deliver(SignallingEventType.subscribe, "c1");
|
||||
await settle();
|
||||
expect(sent()).toEqual([
|
||||
[
|
||||
SignallingEventType.close,
|
||||
peer.deviceId,
|
||||
expect.objectContaining({
|
||||
reason: "not_publishing",
|
||||
connection_id: "c1",
|
||||
}),
|
||||
],
|
||||
]);
|
||||
});
|
||||
|
||||
it("offers to a member on any transport", async () => {
|
||||
await backend.prepareLocalTransport(fullMesh(own.deviceId));
|
||||
addMember(livekit);
|
||||
deliver(SignallingEventType.subscribe, "c1");
|
||||
await settle();
|
||||
expect(sent(SignallingEventType.description)).toEqual([
|
||||
[
|
||||
SignallingEventType.description,
|
||||
peer.deviceId,
|
||||
expect.objectContaining({
|
||||
connection_id: "c1",
|
||||
target_member_id: peer.memberId,
|
||||
description: { type: "offer", sdp: "offer-1" },
|
||||
}),
|
||||
],
|
||||
]);
|
||||
});
|
||||
|
||||
it("waits for the membership of a subscriber that is ahead of it", async () => {
|
||||
await backend.prepareLocalTransport(fullMesh(own.deviceId));
|
||||
deliver(SignallingEventType.subscribe, "c1");
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
expect(sent()).toEqual([]);
|
||||
addMember(livekit);
|
||||
await settle();
|
||||
expect(sent(SignallingEventType.description)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("rejects a subscriber that never becomes a member", async () => {
|
||||
await backend.prepareLocalTransport(fullMesh(own.deviceId));
|
||||
deliver(SignallingEventType.subscribe, "c1");
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
expect(sent()).toEqual([
|
||||
[
|
||||
SignallingEventType.close,
|
||||
peer.deviceId,
|
||||
expect.objectContaining({ reason: "not_a_member" }),
|
||||
],
|
||||
]);
|
||||
expect(FakePeerConnection.instances).toEqual([]);
|
||||
});
|
||||
|
||||
it("rejects a subscriber claiming another device of the member", async () => {
|
||||
await backend.prepareLocalTransport(fullMesh(own.deviceId));
|
||||
addMember(livekit);
|
||||
deliver(
|
||||
SignallingEventType.subscribe,
|
||||
"c1",
|
||||
{},
|
||||
{
|
||||
...peer,
|
||||
deviceId: "OTHERDEVICE",
|
||||
},
|
||||
);
|
||||
await settle();
|
||||
expect(sent()).toEqual([
|
||||
[
|
||||
SignallingEventType.close,
|
||||
"OTHERDEVICE",
|
||||
expect.objectContaining({ reason: "not_a_member" }),
|
||||
],
|
||||
]);
|
||||
});
|
||||
|
||||
it("only serves the newest of several waiting subscribe requests", async () => {
|
||||
await backend.prepareLocalTransport(fullMesh(own.deviceId));
|
||||
deliver(SignallingEventType.subscribe, "c1");
|
||||
deliver(SignallingEventType.subscribe, "c2");
|
||||
addMember(livekit);
|
||||
await settle();
|
||||
expect(
|
||||
sent(SignallingEventType.description).map(([, , c]) => c.connection_id),
|
||||
).toEqual(["c2"]);
|
||||
});
|
||||
|
||||
it("replaces the connection of a member that subscribes again", async () => {
|
||||
await backend.prepareLocalTransport(fullMesh(own.deviceId));
|
||||
addMember(livekit);
|
||||
deliver(SignallingEventType.subscribe, "c1");
|
||||
await settle();
|
||||
const first = lastPeerConnection();
|
||||
deliver(SignallingEventType.subscribe, "c2");
|
||||
await settle();
|
||||
expect(first.closed).toBe(true);
|
||||
expect(lastPeerConnection()).not.toBe(first);
|
||||
});
|
||||
|
||||
it("hands the subscriber's messages to its connection", async () => {
|
||||
await backend.prepareLocalTransport(fullMesh(own.deviceId));
|
||||
addMember(livekit);
|
||||
deliver(SignallingEventType.subscribe, "c1");
|
||||
await settle();
|
||||
deliver(SignallingEventType.description, "c1", {
|
||||
description: { type: "answer", sdp: "answer" },
|
||||
});
|
||||
deliver(SignallingEventType.candidates, "c1", {
|
||||
candidates: [{ candidate: "x" }],
|
||||
});
|
||||
// A late message of an earlier connection goes nowhere
|
||||
deliver(SignallingEventType.candidates, "c0", {
|
||||
candidates: [{ candidate: "stale" }],
|
||||
});
|
||||
await settle();
|
||||
const pc = lastPeerConnection();
|
||||
expect(pc.remoteDescription).toEqual({ type: "answer", sdp: "answer" });
|
||||
expect(pc.addedCandidates).toEqual([{ candidate: "x" }]);
|
||||
});
|
||||
|
||||
it("drops a message of a connection from another device", async () => {
|
||||
await backend.prepareLocalTransport(fullMesh(own.deviceId));
|
||||
addMember(livekit);
|
||||
deliver(SignallingEventType.subscribe, "c1");
|
||||
await settle();
|
||||
deliver(
|
||||
SignallingEventType.description,
|
||||
"c1",
|
||||
{ description: { type: "answer", sdp: "answer" } },
|
||||
{ ...peer, deviceId: "OTHERDEVICE" },
|
||||
);
|
||||
await settle();
|
||||
expect(lastPeerConnection().remoteDescription).toBeNull();
|
||||
});
|
||||
|
||||
it("stops sending to a member that leaves", async () => {
|
||||
await backend.prepareLocalTransport(fullMesh(own.deviceId));
|
||||
const member = addMember(livekit);
|
||||
deliver(SignallingEventType.subscribe, "c1");
|
||||
await settle();
|
||||
member.scope.end();
|
||||
expect(lastPeerConnection().closed).toBe(true);
|
||||
expect(sent(SignallingEventType.close)).toEqual([
|
||||
[
|
||||
SignallingEventType.close,
|
||||
peer.deviceId,
|
||||
expect.objectContaining({ connection_id: "c1" }),
|
||||
],
|
||||
]);
|
||||
});
|
||||
|
||||
it("lists its subscribers for the developer tools", async () => {
|
||||
expect(backend.connections$.value).toEqual([]);
|
||||
await backend.prepareLocalTransport(fullMesh(own.deviceId));
|
||||
expect(backend.connections$.value).toEqual([
|
||||
{
|
||||
transport: fullMesh(own.deviceId),
|
||||
state: MediaConnectionState.Connected,
|
||||
resolved: {
|
||||
type: FULL_MESH_TRANSPORT_TYPE,
|
||||
role: "publisher",
|
||||
peerConnections: [],
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
addMember(livekit);
|
||||
deliver(SignallingEventType.subscribe, "c1");
|
||||
await settle();
|
||||
expect(backend.connections$.value[0].resolved).toMatchObject({
|
||||
peerConnections: [
|
||||
{
|
||||
memberId: peer.memberId,
|
||||
connectionId: "c1",
|
||||
connectionState: "new",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("as a subscriber", () => {
|
||||
it("subscribes to a member publishing on full mesh", async () => {
|
||||
const member = addMember(fullMesh(peer.deviceId));
|
||||
await settle();
|
||||
expect(sent()).toEqual([
|
||||
[
|
||||
SignallingEventType.subscribe,
|
||||
peer.deviceId,
|
||||
expect.objectContaining({
|
||||
room_id: roomId,
|
||||
slot_id: slotId,
|
||||
member_id: own.memberId,
|
||||
claimed_device_id: own.deviceId,
|
||||
target_member_id: peer.memberId,
|
||||
seq: 0,
|
||||
}),
|
||||
],
|
||||
]);
|
||||
expect(member.tracks()).toBeNull();
|
||||
expect(backend.connections$.value).toEqual([
|
||||
expect.objectContaining({
|
||||
transport: fullMesh(peer.deviceId),
|
||||
resolved: expect.objectContaining({ role: "subscriber" }),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("ignores a full mesh transport advertising another device", async () => {
|
||||
addMember(fullMesh("OTHERDEVICE"));
|
||||
await settle();
|
||||
expect(sent()).toEqual([]);
|
||||
});
|
||||
|
||||
it("leaves members on other transports alone", async () => {
|
||||
const member = addMember(livekit);
|
||||
await settle();
|
||||
expect(sent()).toEqual([]);
|
||||
expect(member.tracks()).toBeNull();
|
||||
});
|
||||
|
||||
it("hands the publisher's messages to the subscription", async () => {
|
||||
addMember(fullMesh(peer.deviceId));
|
||||
await settle();
|
||||
const [[, , subscribe]] = sent();
|
||||
lastPeerConnection().receive("video", "1");
|
||||
deliver(
|
||||
SignallingEventType.description,
|
||||
subscribe.connection_id as string,
|
||||
{
|
||||
description: { type: "offer", sdp: "offer" },
|
||||
track_metadata: { "1": { purpose: "m.usermedia" } },
|
||||
},
|
||||
);
|
||||
await settle();
|
||||
expect(sent(SignallingEventType.description)).toEqual([
|
||||
[
|
||||
SignallingEventType.description,
|
||||
peer.deviceId,
|
||||
expect.objectContaining({
|
||||
description: { type: "answer", sdp: "answer" },
|
||||
}),
|
||||
],
|
||||
]);
|
||||
});
|
||||
|
||||
it("closes the subscription when the member leaves", async () => {
|
||||
const member = addMember(fullMesh(peer.deviceId));
|
||||
await settle();
|
||||
member.scope.end();
|
||||
expect(lastPeerConnection().closed).toBe(true);
|
||||
expect(backend.connections$.value).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
it("doesn't take over the delayed leave", async () => {
|
||||
await expect(backend.delegateDelayedLeave("id")).rejects.toThrow();
|
||||
});
|
||||
|
||||
describe("data", () => {
|
||||
it("can't be sent while not publishing", async () => {
|
||||
await expect(backend.sendData("topic", "text")).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("is sent to every subscriber on its data channel", async () => {
|
||||
await backend.prepareLocalTransport(fullMesh(own.deviceId));
|
||||
addMember(livekit);
|
||||
deliver(SignallingEventType.subscribe, "c1");
|
||||
await settle();
|
||||
const data = lastPeerConnection().dataChannels.find(
|
||||
(c) => c.label === DATA_CHANNEL_LABEL,
|
||||
)!;
|
||||
data.open();
|
||||
await backend.sendData("greeting", "hello");
|
||||
expect(data.sent.map((m) => JSON.parse(m) as unknown)).toEqual([
|
||||
{ topic: "greeting", text: "hello" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("is received from a publisher, named by its member", async () => {
|
||||
const received: DataPacket[] = [];
|
||||
backend.data$.subscribe((p) => received.push(p));
|
||||
addMember(fullMesh(peer.deviceId));
|
||||
await settle();
|
||||
const [[, , subscribe]] = sent();
|
||||
deliver(
|
||||
SignallingEventType.description,
|
||||
subscribe.connection_id as string,
|
||||
{
|
||||
description: { type: "offer", sdp: "offer" },
|
||||
track_metadata: {},
|
||||
},
|
||||
);
|
||||
await settle();
|
||||
const channel = lastPeerConnection().announceDataChannel(
|
||||
DATA_CHANNEL_LABEL,
|
||||
DATA_PROTOCOL,
|
||||
);
|
||||
channel.receive({ topic: "greeting", text: "hello" });
|
||||
channel.receive({ topic: 1 });
|
||||
expect(received).toEqual([
|
||||
{
|
||||
senderId: `${peer.userId}:${peer.deviceId}`,
|
||||
topic: "greeting",
|
||||
text: "hello",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("completeFullMeshTransport", () => {
|
||||
it("adds our device to a full mesh transport only", () => {
|
||||
expect(
|
||||
completeFullMeshTransport({ type: FULL_MESH_TRANSPORT_TYPE }, "DEV"),
|
||||
).toEqual({ type: FULL_MESH_TRANSPORT_TYPE, device_id: "DEV" });
|
||||
expect(completeFullMeshTransport(livekit, "DEV")).toBe(livekit);
|
||||
});
|
||||
});
|
||||
@@ -1,442 +0,0 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
/**
|
||||
* The full mesh transport (MSC4575): one WebRTC connection per subscriber
|
||||
* and publisher, signalled over to-device messages, through the TURN server
|
||||
* of each side's homeserver. Works subscribe-only too: without
|
||||
* `prepareLocalTransport` it publishes nothing and still receives from every
|
||||
* member on full mesh.
|
||||
*/
|
||||
|
||||
import { type MatrixClient } from "matrix-js-sdk";
|
||||
import { type Transport } from "matrix-js-sdk/lib/matrixrtc";
|
||||
import {
|
||||
BehaviorSubject,
|
||||
combineLatest,
|
||||
distinctUntilChanged,
|
||||
filter,
|
||||
firstValueFrom,
|
||||
map,
|
||||
NEVER,
|
||||
type Observable,
|
||||
of,
|
||||
share,
|
||||
Subject,
|
||||
switchMap,
|
||||
timeout,
|
||||
} from "rxjs";
|
||||
|
||||
import { type RTCMember } from "../../api";
|
||||
import { MatrixRTCError } from "../../errors";
|
||||
import { type MemberMedia } from "../../media-api";
|
||||
import { type Behavior } from "../../reactive/Behavior";
|
||||
import { ObservableScope } from "../../reactive/ObservableScope";
|
||||
import { mapScoped } from "../../utils/mapScoped";
|
||||
import {
|
||||
type BackendConnection,
|
||||
type DataPacket,
|
||||
type MediaBackend,
|
||||
type MediaBackendContext,
|
||||
MediaConnectionState,
|
||||
} from "../api";
|
||||
import { createFullMeshLocalMedia } from "./LocalMedia";
|
||||
import { type PeerConnectionBase } from "./PeerConnection";
|
||||
import {
|
||||
createPublisherConnection,
|
||||
type PublisherConnection,
|
||||
} from "./PublisherConnection";
|
||||
import {
|
||||
createSignalling,
|
||||
FULL_MESH_TRANSPORT_TYPE,
|
||||
type Peer,
|
||||
type SignallingClient,
|
||||
type SignallingMessage,
|
||||
} from "./signalling";
|
||||
import {
|
||||
createSubscriberConnection,
|
||||
type SubscriberConnection,
|
||||
} from "./SubscriberConnection";
|
||||
|
||||
export { FULL_MESH_TRANSPORT_TYPE } from "./signalling";
|
||||
|
||||
/** How long a subscribe request waits for the subscriber's membership to arrive. */
|
||||
const SUBSCRIBE_GRACE_MS = 10_000;
|
||||
|
||||
export interface FullMeshBackendOptions {
|
||||
client: SignallingClient &
|
||||
Pick<MatrixClient, "getTurnServers" | "checkTurnServers">;
|
||||
}
|
||||
|
||||
/**
|
||||
* The transport object a member publishing on full mesh advertises: a host
|
||||
* passes `{ type: FULL_MESH_TRANSPORT_TYPE }`, and the device is filled in.
|
||||
* Any other transport is returned as it is.
|
||||
*/
|
||||
export function completeFullMeshTransport(
|
||||
transport: Transport,
|
||||
deviceId: string,
|
||||
): Transport {
|
||||
return transport.type === FULL_MESH_TRANSPORT_TYPE
|
||||
? { ...transport, device_id: deviceId }
|
||||
: transport;
|
||||
}
|
||||
|
||||
export function createFullMeshBackend(
|
||||
scope: ObservableScope,
|
||||
{
|
||||
roomId,
|
||||
slotId,
|
||||
ownMembershipIdentity,
|
||||
publish: requestsOrMedia,
|
||||
logger: parentLogger,
|
||||
}: MediaBackendContext,
|
||||
{ client }: FullMeshBackendOptions,
|
||||
): MediaBackend {
|
||||
const logger = parentLogger.getChild("[FullMeshBackend]");
|
||||
const [publish, media] = Array.isArray(requestsOrMedia)
|
||||
? [requestsOrMedia, undefined]
|
||||
: [requestsOrMedia.requests, requestsOrMedia];
|
||||
const signalling = createSignalling({
|
||||
scope,
|
||||
client,
|
||||
roomId,
|
||||
slotId,
|
||||
own: ownMembershipIdentity,
|
||||
logger,
|
||||
});
|
||||
|
||||
const iceServers = async (): Promise<RTCIceServer[]> => {
|
||||
if (client.getTurnServers().length === 0)
|
||||
await client
|
||||
.checkTurnServers()
|
||||
.catch((e: unknown) => logger.warn("No TURN servers", e));
|
||||
return client.getTurnServers().map(({ urls, username, credential }) => ({
|
||||
urls,
|
||||
username,
|
||||
credential,
|
||||
}));
|
||||
};
|
||||
|
||||
let localTransport: Transport | null = null;
|
||||
const prepared$ = new BehaviorSubject(false);
|
||||
const audioOutputDeviceId$ = new BehaviorSubject<string | undefined>(
|
||||
undefined,
|
||||
);
|
||||
|
||||
const data$ = new Subject<DataPacket>();
|
||||
scope.onEnd(() => data$.complete());
|
||||
|
||||
const members = new Map<string, RTCMember>();
|
||||
const memberAdded$ = new Subject<RTCMember>();
|
||||
const subscribers = new Map<
|
||||
string,
|
||||
{ transport: Transport; peer: Peer; connection: SubscriberConnection }
|
||||
>();
|
||||
const publishers = new Map<
|
||||
string,
|
||||
{ connection: PublisherConnection; peer: Peer; scope: ObservableScope }
|
||||
>();
|
||||
scope.onEnd(() => {
|
||||
for (const { scope: s } of Array.from(publishers.values())) s.end();
|
||||
});
|
||||
/** The connection id of the newest subscribe request per member. */
|
||||
const latestSubscribe = new Map<string, string>();
|
||||
|
||||
// For the developer tools: one entry per publisher we subscribe to, and one
|
||||
// for our own transport with every subscriber we send to. `resolved` lists
|
||||
// the peer connections, as an SFU's entry lists what it connected to
|
||||
const connectionsChanged$ = new BehaviorSubject<void>(undefined);
|
||||
const connections$ = scope.behavior<BackendConnection[]>(
|
||||
combineLatest([connectionsChanged$, prepared$]).pipe(
|
||||
switchMap(([, prepared]) => {
|
||||
const entries: Observable<BackendConnection>[] = [];
|
||||
for (const { transport, peer, connection } of subscribers.values()) {
|
||||
const base = connection.current$.value;
|
||||
if (base)
|
||||
entries.push(
|
||||
base.state$.pipe(
|
||||
map((state) => ({
|
||||
transport,
|
||||
state,
|
||||
resolved: {
|
||||
type: FULL_MESH_TRANSPORT_TYPE,
|
||||
role: "subscriber",
|
||||
peerConnections: [describe(peer, base)],
|
||||
},
|
||||
})),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (localTransport && prepared) {
|
||||
const transport = localTransport;
|
||||
const outgoing = [...publishers.values()];
|
||||
entries.push(
|
||||
(outgoing.length === 0
|
||||
? of([])
|
||||
: combineLatest(outgoing.map((p) => p.connection.state$))
|
||||
).pipe(
|
||||
map(() => ({
|
||||
transport,
|
||||
// Publishing needs no server, so it is up once prepared
|
||||
state: MediaConnectionState.Connected,
|
||||
resolved: {
|
||||
type: FULL_MESH_TRANSPORT_TYPE,
|
||||
role: "publisher",
|
||||
peerConnections: outgoing.map(({ peer, connection }) =>
|
||||
describe(peer, connection),
|
||||
),
|
||||
},
|
||||
})),
|
||||
),
|
||||
);
|
||||
}
|
||||
return entries.length === 0 ? of([]) : combineLatest(entries);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const local = createFullMeshLocalMedia({
|
||||
scope,
|
||||
publish,
|
||||
media,
|
||||
connectionState$: scope.behavior(
|
||||
prepared$.pipe(
|
||||
map((prepared) =>
|
||||
prepared
|
||||
? MediaConnectionState.Connected
|
||||
: MediaConnectionState.Initialized,
|
||||
),
|
||||
),
|
||||
),
|
||||
peerConnections: () =>
|
||||
[...publishers.values()].map(({ connection }) => connection.pc),
|
||||
logger,
|
||||
});
|
||||
|
||||
const acceptSubscribe = async (message: SignallingMessage): Promise<void> => {
|
||||
const peer: Peer = {
|
||||
userId: message.userId,
|
||||
deviceId: message.deviceId,
|
||||
memberId: message.memberId,
|
||||
};
|
||||
// We don't advertise full mesh, so nobody should have asked
|
||||
if (!prepared$.value) {
|
||||
signalling.send(peer, message.connectionId, {
|
||||
type: "close",
|
||||
reason: "not_publishing",
|
||||
});
|
||||
return;
|
||||
}
|
||||
latestSubscribe.set(peer.memberId, message.connectionId);
|
||||
// The request may overtake the subscriber's membership
|
||||
const member =
|
||||
members.get(peer.memberId) ??
|
||||
(await firstValueFrom(
|
||||
memberAdded$.pipe(
|
||||
filter((m) => m.memberId === peer.memberId),
|
||||
timeout(SUBSCRIBE_GRACE_MS),
|
||||
),
|
||||
).catch(() => undefined));
|
||||
if (latestSubscribe.get(peer.memberId) !== message.connectionId) return;
|
||||
if (
|
||||
member === undefined ||
|
||||
member.userId !== peer.userId ||
|
||||
member.deviceId !== peer.deviceId
|
||||
) {
|
||||
logger.warn(`Rejecting a subscribe from ${peer.memberId}`);
|
||||
signalling.send(peer, message.connectionId, {
|
||||
type: "close",
|
||||
reason: "not_a_member",
|
||||
});
|
||||
return;
|
||||
}
|
||||
// At most one connection per member pair: the new one replaces the old
|
||||
publishers.get(peer.memberId)?.scope.end();
|
||||
const pubScope = new ObservableScope();
|
||||
const connection = createPublisherConnection({
|
||||
scope: pubScope,
|
||||
peer,
|
||||
connectionId: message.connectionId,
|
||||
signalling,
|
||||
iceServers: await iceServers(),
|
||||
local,
|
||||
logger,
|
||||
});
|
||||
publishers.set(peer.memberId, { connection, peer, scope: pubScope });
|
||||
pubScope.onEnd(() => {
|
||||
if (publishers.get(peer.memberId)?.connection === connection) {
|
||||
publishers.delete(peer.memberId);
|
||||
connectionsChanged$.next();
|
||||
}
|
||||
});
|
||||
connectionsChanged$.next();
|
||||
};
|
||||
|
||||
// A message of a connection has to come from the device the connection
|
||||
// was set up with, not only carry its id
|
||||
const fromPeer = (message: SignallingMessage, peer: Peer): boolean =>
|
||||
message.userId === peer.userId && message.deviceId === peer.deviceId;
|
||||
signalling.messages$.pipe(scope.bind()).subscribe((message) => {
|
||||
if (message.type === "subscribe") return void acceptSubscribe(message);
|
||||
const subscriber = subscribers.get(message.memberId);
|
||||
if (
|
||||
subscriber?.connection.current$.value?.connectionId ===
|
||||
message.connectionId &&
|
||||
fromPeer(message, subscriber.peer)
|
||||
)
|
||||
return subscriber.connection.handle(message);
|
||||
const publisher = publishers.get(message.memberId);
|
||||
if (
|
||||
publisher?.connection.connectionId === message.connectionId &&
|
||||
fromPeer(message, publisher.peer)
|
||||
)
|
||||
return publisher.connection.handle(message);
|
||||
logger.debug(`Dropping ${message.type} of a stale connection`);
|
||||
});
|
||||
|
||||
const mediaFor = (
|
||||
memberScope: ObservableScope,
|
||||
member: RTCMember,
|
||||
): MemberMedia => {
|
||||
members.set(member.memberId, member);
|
||||
memberAdded$.next(member);
|
||||
memberScope.onEnd(() => {
|
||||
members.delete(member.memberId);
|
||||
// We stop sending to members that are no longer joined
|
||||
publishers.get(member.memberId)?.scope.end();
|
||||
});
|
||||
|
||||
// The advertised device has to be the one the membership names. The MSC
|
||||
// wants it checked against the device that sent the membership, which the
|
||||
// js-sdk doesn't expose, so this only catches an inconsistent membership
|
||||
const fullMesh$ = memberScope.behavior(
|
||||
member.transport$.pipe(
|
||||
map((transport) =>
|
||||
transport?.type === FULL_MESH_TRANSPORT_TYPE &&
|
||||
transport.raw.device_id === member.deviceId
|
||||
? transport.raw
|
||||
: undefined,
|
||||
),
|
||||
distinctUntilChanged((a, b) => a?.device_id === b?.device_id),
|
||||
),
|
||||
);
|
||||
const subscriber$ = mapScoped(memberScope, fullMesh$, (s, transport) => {
|
||||
const connection = createSubscriberConnection({
|
||||
scope: s,
|
||||
peer: {
|
||||
userId: member.userId,
|
||||
deviceId: member.deviceId,
|
||||
memberId: member.memberId,
|
||||
},
|
||||
signalling,
|
||||
iceServers,
|
||||
audioOutputDeviceId$,
|
||||
logger,
|
||||
});
|
||||
subscribers.set(member.memberId, {
|
||||
transport,
|
||||
peer: {
|
||||
userId: member.userId,
|
||||
deviceId: member.deviceId,
|
||||
memberId: member.memberId,
|
||||
},
|
||||
connection,
|
||||
});
|
||||
connection.current$
|
||||
.pipe(s.bind())
|
||||
.subscribe(() => connectionsChanged$.next());
|
||||
connection.data$.pipe(s.bind()).subscribe((message) => {
|
||||
const packet = parseDataMessage(message);
|
||||
if (packet === null)
|
||||
logger.debug(`Ignoring a data message from ${member.memberId}`);
|
||||
else data$.next({ senderId: member.rtcBackendIdentity, ...packet });
|
||||
});
|
||||
s.onEnd(() => {
|
||||
subscribers.delete(member.memberId);
|
||||
connectionsChanged$.next();
|
||||
});
|
||||
return connection;
|
||||
});
|
||||
|
||||
return {
|
||||
tracks$: memberScope.behavior(
|
||||
subscriber$.pipe(switchMap((s) => s?.tracks$ ?? of(null))),
|
||||
),
|
||||
encryptionError$: NEVER,
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
transportTypes: [FULL_MESH_TRANSPORT_TYPE],
|
||||
prepareLocalTransport: async (transport) => {
|
||||
// Another backend publishes: we subscribe as we do anyway
|
||||
if (transport === null) return { canDelegateDelayedLeave: false };
|
||||
if (transport.type !== FULL_MESH_TRANSPORT_TYPE)
|
||||
throw new MatrixRTCError(
|
||||
`Not a full mesh transport: ${transport.type}`,
|
||||
);
|
||||
localTransport = transport;
|
||||
// Fetched now, so that the first subscriber isn't kept waiting
|
||||
await iceServers();
|
||||
prepared$.next(true);
|
||||
return { canDelegateDelayedLeave: false };
|
||||
},
|
||||
delegateDelayedLeave: async () =>
|
||||
Promise.reject(
|
||||
new MatrixRTCError("Full mesh cannot take over the delayed leave"),
|
||||
),
|
||||
local,
|
||||
mediaFor,
|
||||
connections$: connections$ as Behavior<BackendConnection[]>,
|
||||
setAudioOutputDeviceId: async (deviceId) => {
|
||||
audioOutputDeviceId$.next(deviceId);
|
||||
return Promise.resolve();
|
||||
},
|
||||
sendData: async (topic, text) => {
|
||||
if (!prepared$.value)
|
||||
throw new MatrixRTCError(
|
||||
"Cannot send data: not publishing on full mesh",
|
||||
);
|
||||
const message = JSON.stringify({ topic, text });
|
||||
for (const { connection } of publishers.values())
|
||||
connection.sendData(message);
|
||||
return Promise.resolve();
|
||||
},
|
||||
data$: data$.pipe(share()),
|
||||
};
|
||||
}
|
||||
|
||||
/** A message of the `sendData` data channel, or null for a malformed one. */
|
||||
function parseDataMessage(
|
||||
message: string,
|
||||
): Pick<DataPacket, "topic" | "text"> | null {
|
||||
try {
|
||||
const { topic, text } = JSON.parse(message) as Record<string, unknown>;
|
||||
return typeof topic === "string" && typeof text === "string"
|
||||
? { topic, text }
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** One peer connection as the developer tools show it. */
|
||||
function describe(
|
||||
{ userId, deviceId, memberId }: Peer,
|
||||
{ connectionId, pc }: PeerConnectionBase,
|
||||
): Record<string, string> {
|
||||
return {
|
||||
userId,
|
||||
deviceId,
|
||||
memberId,
|
||||
connectionId,
|
||||
connectionState: pc.connectionState,
|
||||
iceConnectionState: pc.iceConnectionState,
|
||||
signalingState: pc.signalingState,
|
||||
};
|
||||
}
|
||||
@@ -1,280 +0,0 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import {
|
||||
afterEach,
|
||||
beforeEach,
|
||||
describe,
|
||||
expect,
|
||||
it,
|
||||
type Mock,
|
||||
vi,
|
||||
} from "vitest";
|
||||
import { logger } from "matrix-js-sdk/lib/logger";
|
||||
import { BehaviorSubject } from "rxjs";
|
||||
|
||||
import {
|
||||
type HandedOverTrack,
|
||||
type LocalMedia,
|
||||
type LocalVideoMediaTrack,
|
||||
type PublishRequest,
|
||||
type VideoProcessor,
|
||||
} from "../../media-api";
|
||||
import { constant } from "../../reactive/Behavior";
|
||||
import { ObservableScope } from "../../reactive/ObservableScope";
|
||||
import { MediaConnectionState } from "../api";
|
||||
import {
|
||||
createFullMeshLocalMedia,
|
||||
type FullMeshLocalMedia,
|
||||
} from "./LocalMedia";
|
||||
import { FakeMediaStream, fakeTrack, installWebRtcFakes } from "./test";
|
||||
|
||||
const microphone: PublishRequest = { source: "microphone" };
|
||||
const camera: PublishRequest = { source: "camera" };
|
||||
|
||||
describe("createFullMeshLocalMedia", () => {
|
||||
let scope: ObservableScope;
|
||||
let getUserMedia: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
installWebRtcFakes();
|
||||
getUserMedia = vi.fn(async (constraints: MediaStreamConstraints) => {
|
||||
const tracks: MediaStreamTrack[] = [];
|
||||
if (constraints.audio) tracks.push(fakeTrack("audio"));
|
||||
if (constraints.video)
|
||||
tracks.push(fakeTrack("video", { deviceId: "cam-in-use" }));
|
||||
return Promise.resolve(new FakeMediaStream(tracks));
|
||||
});
|
||||
vi.stubGlobal("navigator", { mediaDevices: { getUserMedia } });
|
||||
// jsdom has no media playback
|
||||
vi.spyOn(HTMLMediaElement.prototype, "play").mockResolvedValue();
|
||||
scope = new ObservableScope();
|
||||
});
|
||||
afterEach(() => {
|
||||
scope.end();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
function create(
|
||||
publish: PublishRequest[],
|
||||
media?: LocalMedia,
|
||||
): FullMeshLocalMedia {
|
||||
return createFullMeshLocalMedia({
|
||||
scope,
|
||||
publish,
|
||||
media,
|
||||
connectionState$: constant(MediaConnectionState.Connected),
|
||||
peerConnections: () => [],
|
||||
logger,
|
||||
});
|
||||
}
|
||||
|
||||
/** Starts publishing and waits for the capture (or the take-over) to finish. */
|
||||
async function start(
|
||||
local: FullMeshLocalMedia,
|
||||
sources: string[],
|
||||
): Promise<void> {
|
||||
local.setPublishing(true);
|
||||
await vi.waitFor(() =>
|
||||
expect(local.publications$.value.map((p) => p.source)).toEqual(sources),
|
||||
);
|
||||
}
|
||||
|
||||
function publication(
|
||||
local: FullMeshLocalMedia,
|
||||
source: string,
|
||||
): FullMeshLocalMedia["publications$"]["value"][number] {
|
||||
const found = local.publications$.value.find((p) => p.source === source);
|
||||
if (found === undefined) throw new Error(`No ${source} publication`);
|
||||
return found;
|
||||
}
|
||||
|
||||
it("captures the requests at the first start", async () => {
|
||||
const local = create([microphone, camera]);
|
||||
expect(local.tracks$.value).toBeNull();
|
||||
|
||||
await start(local, ["microphone", "camera"]);
|
||||
|
||||
expect(getUserMedia).toHaveBeenCalledTimes(2);
|
||||
expect(local.tracks$.value?.map((t) => t.source)).toEqual([
|
||||
"microphone",
|
||||
"camera",
|
||||
]);
|
||||
});
|
||||
|
||||
it("takes a lobby's tracks over instead of capturing", async () => {
|
||||
const processor = fakeProcessor();
|
||||
const handed = {
|
||||
microphone: handedTrack("audio", { muted: true }),
|
||||
camera: handedTrack("video", {
|
||||
constraints: { deviceId: "lobby-cam" },
|
||||
processor: { processor, processedTrack: processor.output },
|
||||
}),
|
||||
};
|
||||
const media = fakeMedia([microphone, camera], handed);
|
||||
const local = create(media.requests, media);
|
||||
|
||||
await start(local, ["microphone", "camera"]);
|
||||
|
||||
expect(media.takeTracks).toHaveBeenCalledOnce();
|
||||
expect(getUserMedia).not.toHaveBeenCalled();
|
||||
const mic = publication(local, "microphone");
|
||||
expect(mic.track$.value).toBe(handed.microphone.track);
|
||||
expect(handed.microphone.track.enabled).toBe(false);
|
||||
expect(mic.mediaTrack.muted$.value).toBe(true);
|
||||
// The running processor is adopted with its output
|
||||
const cam = publication(local, "camera");
|
||||
expect(cam.track$.value).toBe(processor.output);
|
||||
expect(processor.init).not.toHaveBeenCalled();
|
||||
expect(cam.mediaTrack.muted$.value).toBe(false);
|
||||
|
||||
// Turned off and on again, the camera reopens on the lobby's device and
|
||||
// restarts the processor rather than initialising it again
|
||||
await cam.mediaTrack.setEnabled(false);
|
||||
expect(handed.camera.track.stop).toHaveBeenCalled();
|
||||
expect(processor.output.stop).toHaveBeenCalled();
|
||||
await cam.mediaTrack.setEnabled(true);
|
||||
expect(getUserMedia).toHaveBeenCalledExactlyOnceWith({
|
||||
video: expect.objectContaining({ deviceId: { exact: "lobby-cam" } }),
|
||||
});
|
||||
expect(processor.restart).toHaveBeenCalledOnce();
|
||||
expect(processor.init).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("releases a camera that was muted in the lobby", async () => {
|
||||
const handed = { camera: handedTrack("video", { muted: true }) };
|
||||
const media = fakeMedia([camera], handed);
|
||||
const local = create(media.requests, media);
|
||||
|
||||
await start(local, ["camera"]);
|
||||
|
||||
const cam = publication(local, "camera");
|
||||
expect(handed.camera.track.stop).toHaveBeenCalled();
|
||||
expect(cam.track$.value).toBeNull();
|
||||
expect(cam.mediaTrack.muted$.value).toBe(true);
|
||||
});
|
||||
|
||||
it("stops handed over tracks it no longer wants", async () => {
|
||||
const handed = { camera: handedTrack("video") };
|
||||
const media = fakeMedia([microphone], handed);
|
||||
const local = create(media.requests, media);
|
||||
|
||||
await start(local, ["microphone"]);
|
||||
|
||||
expect(handed.camera.track.stop).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("builds a processor set while the camera is off once it turns on", async () => {
|
||||
const processor = fakeProcessor();
|
||||
const local = create([camera]);
|
||||
await start(local, ["camera"]);
|
||||
const cam = publication(local, "camera");
|
||||
const { setProcessor } = cam.mediaTrack as LocalVideoMediaTrack;
|
||||
const raw = cam.track$.value;
|
||||
|
||||
await cam.mediaTrack.setEnabled(false);
|
||||
await setProcessor(processor);
|
||||
expect(processor.init).not.toHaveBeenCalled();
|
||||
// Setting it again changes nothing
|
||||
await setProcessor(processor);
|
||||
|
||||
await cam.mediaTrack.setEnabled(true);
|
||||
expect(processor.init).toHaveBeenCalledOnce();
|
||||
expect(processor.init).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ kind: "video" }),
|
||||
expect.any(HTMLVideoElement),
|
||||
);
|
||||
expect(cam.track$.value).toBe(processor.output);
|
||||
expect(cam.track$.value).not.toBe(raw);
|
||||
expect(processor.destroy).not.toHaveBeenCalled();
|
||||
|
||||
// Removed, the raw track goes out again and the processor is torn down
|
||||
await setProcessor(undefined);
|
||||
expect(processor.destroy).toHaveBeenCalledOnce();
|
||||
expect(processor.output.stop).toHaveBeenCalled();
|
||||
expect(cam.track$.value?.kind).toBe("video");
|
||||
expect(cam.track$.value).not.toBe(processor.output);
|
||||
});
|
||||
|
||||
it("runs a processor's steps one after the other", async () => {
|
||||
const processor = fakeProcessor();
|
||||
let initDone: (() => void) | undefined;
|
||||
processor.init.mockImplementationOnce(
|
||||
async () =>
|
||||
new Promise((resolve) => {
|
||||
initDone = (): void => resolve(processor.output);
|
||||
}),
|
||||
);
|
||||
const local = create([camera]);
|
||||
await start(local, ["camera"]);
|
||||
const cam = publication(local, "camera");
|
||||
const { setProcessor } = cam.mediaTrack as LocalVideoMediaTrack;
|
||||
|
||||
// Set while the camera is on, then the camera is turned off and on while
|
||||
// its init still runs: the reopen waits for it and restarts it, rather
|
||||
// than initialising it a second time on the new track
|
||||
const setting = setProcessor(processor);
|
||||
await vi.waitFor(() => expect(processor.init).toHaveBeenCalledOnce());
|
||||
await cam.mediaTrack.setEnabled(false);
|
||||
const turningOn = cam.mediaTrack.setEnabled(true);
|
||||
await vi.waitFor(() => expect(getUserMedia).toHaveBeenCalledTimes(2));
|
||||
expect(processor.restart).not.toHaveBeenCalled();
|
||||
|
||||
initDone?.();
|
||||
await setting;
|
||||
await turningOn;
|
||||
expect(processor.init).toHaveBeenCalledOnce();
|
||||
expect(processor.restart).toHaveBeenCalledOnce();
|
||||
expect(cam.track$.value).toBe(processor.output);
|
||||
});
|
||||
});
|
||||
|
||||
function fakeProcessor(): VideoProcessor & {
|
||||
output: MediaStreamTrack;
|
||||
init: Mock<VideoProcessor["init"]>;
|
||||
restart: Mock<VideoProcessor["restart"]>;
|
||||
destroy: Mock<VideoProcessor["destroy"]>;
|
||||
} {
|
||||
const output = fakeTrack("video");
|
||||
return {
|
||||
name: "blur",
|
||||
output,
|
||||
init: vi.fn(async () => Promise.resolve(output)),
|
||||
restart: vi.fn(async () => Promise.resolve(output)),
|
||||
destroy: vi.fn(async () => Promise.resolve()),
|
||||
};
|
||||
}
|
||||
|
||||
function handedTrack(
|
||||
kind: "audio" | "video",
|
||||
rest: Partial<Omit<HandedOverTrack, "track">> = {},
|
||||
): HandedOverTrack {
|
||||
return { track: fakeTrack(kind), constraints: {}, muted: false, ...rest };
|
||||
}
|
||||
|
||||
/** A lobby's media, as the participation hands it over: only `takeTracks` matters here. */
|
||||
function fakeMedia(
|
||||
requests: PublishRequest[],
|
||||
handed: Partial<Record<"microphone" | "camera", HandedOverTrack>>,
|
||||
): LocalMedia & { takeTracks: ReturnType<typeof vi.fn> } {
|
||||
return {
|
||||
requests,
|
||||
tracks$: new BehaviorSubject([]),
|
||||
capture: vi.fn(),
|
||||
release: vi.fn(),
|
||||
stop: vi.fn(),
|
||||
takeTracks: vi.fn(
|
||||
() =>
|
||||
new Map(
|
||||
Object.entries(handed) as [
|
||||
"microphone" | "camera",
|
||||
HandedOverTrack,
|
||||
][],
|
||||
),
|
||||
),
|
||||
} as unknown as LocalMedia & { takeTracks: ReturnType<typeof vi.fn> };
|
||||
}
|
||||
@@ -1,504 +0,0 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { type Logger } from "matrix-js-sdk/lib/logger";
|
||||
import {
|
||||
BehaviorSubject,
|
||||
combineLatest,
|
||||
filter,
|
||||
firstValueFrom,
|
||||
map,
|
||||
NEVER,
|
||||
} from "rxjs";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import { MatrixRTCError, toMatrixRTCError } from "../../errors";
|
||||
import {
|
||||
type HandedOverTrack,
|
||||
type LocalAudioMediaTrack,
|
||||
type LocalMedia,
|
||||
type LocalVideoMediaTrack,
|
||||
type MediaSource,
|
||||
type PublishRequest,
|
||||
type VideoProcessor,
|
||||
} from "../../media-api";
|
||||
import { type Behavior } from "../../reactive/Behavior";
|
||||
import { ObservableScope } from "../../reactive/ObservableScope";
|
||||
import { inTurn } from "../../utils/processorTurns";
|
||||
import { type LocalMediaBackend, type MediaConnectionState } from "../api";
|
||||
import { createFullMeshMediaTrack, rtpStats } from "./MediaTrack";
|
||||
|
||||
type PublishedSource = Exclude<MediaSource, "unknown">;
|
||||
|
||||
/** One local track as the publisher connections send it. */
|
||||
export interface LocalPublication {
|
||||
source: PublishedSource;
|
||||
kind: "audio" | "video";
|
||||
/**
|
||||
* The `MediaStream` it is sent in: one for the user media, one for the
|
||||
* screen share, so that the subscriber plays each in sync.
|
||||
*/
|
||||
stream: MediaStream;
|
||||
/** What goes on the wire; null while the source is off. */
|
||||
track$: Behavior<MediaStreamTrack | null>;
|
||||
mediaTrack: LocalAudioMediaTrack | LocalVideoMediaTrack;
|
||||
}
|
||||
|
||||
export interface FullMeshLocalMedia extends LocalMediaBackend {
|
||||
/** Every local track, once the first `setPublishing(true)` started the capture. */
|
||||
publications$: Behavior<LocalPublication[]>;
|
||||
/** Whether the tracks reach the publisher connections. */
|
||||
publishing$: Behavior<boolean>;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
scope: ObservableScope;
|
||||
publish: PublishRequest[];
|
||||
/** Tracks a lobby captured ahead of the join; taken over at the start instead of capturing. */
|
||||
media?: LocalMedia;
|
||||
connectionState$: Behavior<MediaConnectionState | Error>;
|
||||
/** The publisher connections, for the outbound statistics of a track. */
|
||||
peerConnections: () => RTCPeerConnection[];
|
||||
logger: Logger;
|
||||
}
|
||||
|
||||
interface Capture {
|
||||
/** What was captured, before any processor. */
|
||||
raw: MediaStreamTrack;
|
||||
out: MediaStreamTrack;
|
||||
}
|
||||
|
||||
/** The local member's side: capture, the publication list and the controls. */
|
||||
export function createFullMeshLocalMedia({
|
||||
scope,
|
||||
publish: initialRequests,
|
||||
media,
|
||||
connectionState$,
|
||||
peerConnections,
|
||||
logger: parentLogger,
|
||||
}: Props): FullMeshLocalMedia {
|
||||
const logger = parentLogger.getChild("[LocalMedia]");
|
||||
// Only their ids matter: the tracks are added per connection
|
||||
const userMediaStream = new MediaStream();
|
||||
const screenShareStream = new MediaStream();
|
||||
const desired = new Map<PublishRequest["source"], PublishRequest>(
|
||||
initialRequests.map((r) => [r.source, r]),
|
||||
);
|
||||
const started$ = new BehaviorSubject(false);
|
||||
const publishing$ = new BehaviorSubject(false);
|
||||
const publishError$ = new BehaviorSubject<Error | null>(null);
|
||||
const publications$ = new BehaviorSubject<LocalPublication[]>([]);
|
||||
const teardowns = new Map<PublishedSource, () => void>();
|
||||
|
||||
const statsFor = async (track: MediaStreamTrack | null) => {
|
||||
for (const pc of peerConnections())
|
||||
if (pc.getSenders().some((s) => s.track === track && track !== null))
|
||||
return rtpStats(pc, track, "outbound-rtp");
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/** Adds a publication whose track is managed by `control`. */
|
||||
const addPublication = (
|
||||
source: PublishedSource,
|
||||
kind: "audio" | "video",
|
||||
stream: MediaStream,
|
||||
initial: MediaStreamTrack | null,
|
||||
enabled: boolean,
|
||||
control: {
|
||||
setEnabled: (
|
||||
enabled: boolean,
|
||||
track$: BehaviorSubject<MediaStreamTrack | null>,
|
||||
) => Promise<boolean>;
|
||||
setDevice?: (
|
||||
deviceId: string,
|
||||
track$: BehaviorSubject<MediaStreamTrack | null>,
|
||||
) => Promise<void>;
|
||||
switchFacingMode?: (
|
||||
track$: BehaviorSubject<MediaStreamTrack | null>,
|
||||
) => Promise<string | undefined>;
|
||||
setProcessor?: (
|
||||
p: VideoProcessor | undefined,
|
||||
track$: BehaviorSubject<MediaStreamTrack | null>,
|
||||
) => Promise<void>;
|
||||
stop: () => void;
|
||||
},
|
||||
): LocalPublication => {
|
||||
const pubScope = new ObservableScope();
|
||||
const track$ = new BehaviorSubject<MediaStreamTrack | null>(initial);
|
||||
const enabled$ = new BehaviorSubject(enabled);
|
||||
const base = createFullMeshMediaTrack(pubScope, {
|
||||
source,
|
||||
kind,
|
||||
id: uuidv4(),
|
||||
track$,
|
||||
muted$: pubScope.behavior(enabled$.pipe(map((e) => !e))),
|
||||
stats: async () => statsFor(track$.value),
|
||||
});
|
||||
const local = {
|
||||
setEnabled: async (enabled: boolean): Promise<boolean> => {
|
||||
const result = await control.setEnabled(enabled, track$);
|
||||
enabled$.next(result);
|
||||
return result;
|
||||
},
|
||||
setDevice: async (deviceId: string): Promise<void> => {
|
||||
if (!control.setDevice)
|
||||
throw new MatrixRTCError(`A ${source} track has no device`);
|
||||
await control.setDevice(deviceId, track$);
|
||||
},
|
||||
};
|
||||
const mediaTrack =
|
||||
base.kind === "audio"
|
||||
? { ...base, ...local }
|
||||
: {
|
||||
...base,
|
||||
...local,
|
||||
facingMode$: pubScope.behavior(
|
||||
track$.pipe(map((t) => facingModeOf(t))),
|
||||
),
|
||||
switchFacingMode: async () => control.switchFacingMode?.(track$),
|
||||
setProcessor: async (p: VideoProcessor | undefined) =>
|
||||
control.setProcessor?.(p, track$),
|
||||
};
|
||||
const publication: LocalPublication = {
|
||||
source,
|
||||
kind,
|
||||
stream,
|
||||
track$,
|
||||
mediaTrack: mediaTrack as LocalAudioMediaTrack | LocalVideoMediaTrack,
|
||||
};
|
||||
publications$.next([...publications$.value, publication]);
|
||||
teardowns.set(source, () => {
|
||||
control.stop();
|
||||
track$.value?.stop();
|
||||
pubScope.end();
|
||||
publications$.next(publications$.value.filter((p) => p !== publication));
|
||||
teardowns.delete(source);
|
||||
});
|
||||
return publication;
|
||||
};
|
||||
|
||||
const captureMicrophone = async (
|
||||
request: Extract<PublishRequest, { source: "microphone" }>,
|
||||
handed?: HandedOverTrack,
|
||||
): Promise<void> => {
|
||||
const track =
|
||||
handed?.track ??
|
||||
(await getTrack({
|
||||
audio: { deviceId: exact(request.deviceId), ...request.capture },
|
||||
}));
|
||||
const enabled = !handed?.muted;
|
||||
track.enabled = enabled;
|
||||
addPublication("microphone", "audio", userMediaStream, track, enabled, {
|
||||
// Muting a microphone keeps the device: unmuting is instant
|
||||
setEnabled: async (enabled, track$) => {
|
||||
if (track$.value) track$.value.enabled = enabled;
|
||||
return Promise.resolve(enabled);
|
||||
},
|
||||
setDevice: async (deviceId, track$) => {
|
||||
const next = await getTrack({
|
||||
audio: { deviceId: { exact: deviceId }, ...request.capture },
|
||||
});
|
||||
next.enabled = track$.value?.enabled ?? true;
|
||||
track$.value?.stop();
|
||||
track$.next(next);
|
||||
},
|
||||
stop: () => {},
|
||||
});
|
||||
};
|
||||
|
||||
const captureCamera = async (
|
||||
request: Extract<PublishRequest, { source: "camera" }>,
|
||||
handed?: HandedOverTrack,
|
||||
): Promise<void> => {
|
||||
// The device the lobby ended up on, so that a reopen stays on it
|
||||
const handedDevice = handed?.constraints.deviceId;
|
||||
let deviceId =
|
||||
typeof handedDevice === "string" ? handedDevice : request.deviceId;
|
||||
let facingMode: string | undefined;
|
||||
// A lobby's processor comes with its output: it is running already
|
||||
let processor = handed?.processor?.processor ?? request.processor;
|
||||
let processorStarted = handed?.processor !== undefined;
|
||||
let capture: Capture | null = null;
|
||||
// What the processor reads frames from; a processor needs a playing element
|
||||
let input: HTMLVideoElement | undefined;
|
||||
const inputFor = (raw: MediaStreamTrack): HTMLVideoElement => {
|
||||
input ??= document.createElement("video");
|
||||
input.muted = true;
|
||||
input.playsInline = true;
|
||||
input.srcObject = new MediaStream([raw]);
|
||||
// A test DOM returns nothing from play
|
||||
(input.play() as Promise<void> | undefined)?.catch(() => {});
|
||||
return input;
|
||||
};
|
||||
const constraints = (): MediaTrackConstraints => ({
|
||||
deviceId: exact(deviceId),
|
||||
facingMode,
|
||||
width: request.capture?.resolution?.width,
|
||||
height: request.capture?.resolution?.height,
|
||||
frameRate: request.capture?.resolution?.frameRate,
|
||||
});
|
||||
/** Runs the processor on `raw`, in its turn; `raw` itself without one. */
|
||||
const process = async (
|
||||
raw: MediaStreamTrack,
|
||||
): Promise<MediaStreamTrack> => {
|
||||
const p = processor;
|
||||
if (p === undefined) return raw;
|
||||
// Started is noted within the turn, so that the next turn sees it
|
||||
return inTurn(p, async () => {
|
||||
const out = processorStarted
|
||||
? await p.restart(raw, inputFor(raw))
|
||||
: await p.init(raw, inputFor(raw));
|
||||
processorStarted = true;
|
||||
return out;
|
||||
});
|
||||
};
|
||||
const open = async (): Promise<Capture> => {
|
||||
const raw = await getTrack({ video: constraints() });
|
||||
return { raw, out: await process(raw) };
|
||||
};
|
||||
const close = (): void => {
|
||||
capture?.raw.stop();
|
||||
if (capture?.out !== capture?.raw) capture?.out.stop();
|
||||
capture = null;
|
||||
if (input) input.srcObject = null;
|
||||
};
|
||||
// Reopens the camera with the current settings, if it is on
|
||||
const reopen = async (
|
||||
track$: BehaviorSubject<MediaStreamTrack | null>,
|
||||
): Promise<void> => {
|
||||
if (capture === null) return;
|
||||
close();
|
||||
capture = await open();
|
||||
track$.next(capture.out);
|
||||
};
|
||||
if (handed) {
|
||||
capture = {
|
||||
raw: handed.track,
|
||||
out: handed.processor?.processedTrack ?? handed.track,
|
||||
};
|
||||
// A camera muted in the lobby is released, as one muted in the call is
|
||||
if (handed.muted) close();
|
||||
} else capture = await open();
|
||||
addPublication(
|
||||
"camera",
|
||||
"video",
|
||||
userMediaStream,
|
||||
capture?.out ?? null,
|
||||
capture !== null,
|
||||
{
|
||||
// Muting a camera releases it, so that its light goes off
|
||||
setEnabled: async (enabled, track$) => {
|
||||
if (enabled === (capture !== null)) return enabled;
|
||||
if (!enabled) {
|
||||
close();
|
||||
track$.next(null);
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
capture = await open();
|
||||
track$.next(capture.out);
|
||||
return true;
|
||||
} catch (e) {
|
||||
logger.warn("Could not reopen the camera", e);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
setDevice: async (id, track$) => {
|
||||
deviceId = id;
|
||||
facingMode = undefined;
|
||||
await reopen(track$);
|
||||
},
|
||||
switchFacingMode: async (track$) => {
|
||||
const current = facingModeOf(track$.value);
|
||||
if (current === undefined) return undefined;
|
||||
deviceId = undefined;
|
||||
facingMode = current === "user" ? "environment" : "user";
|
||||
await reopen(track$);
|
||||
return capture?.raw.getSettings().deviceId;
|
||||
},
|
||||
// While the camera is off the processor is kept for when it turns on
|
||||
setProcessor: async (p, track$) => {
|
||||
if (p === processor) return;
|
||||
const previous = processor;
|
||||
processor = p;
|
||||
processorStarted = false;
|
||||
if (previous) await inTurn(previous, async () => previous.destroy());
|
||||
const current = capture;
|
||||
if (current === null) return;
|
||||
const out = await process(current.raw);
|
||||
// Turned off or reopened meanwhile: that capture has its own output
|
||||
if (capture !== current) return;
|
||||
if (current.out !== current.raw) current.out.stop();
|
||||
capture = { raw: current.raw, out };
|
||||
track$.next(out);
|
||||
},
|
||||
stop: () => {
|
||||
close();
|
||||
const p = processor;
|
||||
if (p) void inTurn(p, async () => p.destroy());
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const captureScreen = async (
|
||||
request: Extract<PublishRequest, { source: "screenShare" }>,
|
||||
): Promise<void> => {
|
||||
const stream = await navigator.mediaDevices.getDisplayMedia({
|
||||
video: {
|
||||
width: request.capture?.resolution?.width,
|
||||
height: request.capture?.resolution?.height,
|
||||
frameRate: request.capture?.resolution?.frameRate,
|
||||
},
|
||||
audio: request.audio ?? true,
|
||||
});
|
||||
const [video] = stream.getVideoTracks();
|
||||
const [audio] = stream.getAudioTracks();
|
||||
const toggle = async (
|
||||
enabled: boolean,
|
||||
track$: BehaviorSubject<MediaStreamTrack | null>,
|
||||
): Promise<boolean> => {
|
||||
if (track$.value) track$.value.enabled = enabled;
|
||||
return Promise.resolve(enabled);
|
||||
};
|
||||
addPublication("screenShare", "video", screenShareStream, video, true, {
|
||||
setEnabled: toggle,
|
||||
// The audio goes with its video
|
||||
stop: () => {
|
||||
audio?.stop();
|
||||
teardowns.get("screenShareAudio")?.();
|
||||
},
|
||||
});
|
||||
if (audio)
|
||||
addPublication(
|
||||
"screenShareAudio",
|
||||
"audio",
|
||||
screenShareStream,
|
||||
audio,
|
||||
true,
|
||||
{
|
||||
setEnabled: toggle,
|
||||
stop: () => {},
|
||||
},
|
||||
);
|
||||
// Stopped from the browser's own controls
|
||||
video.addEventListener("ended", () => void unpublish("screenShare"));
|
||||
};
|
||||
|
||||
const capture = async (
|
||||
request: PublishRequest,
|
||||
handed?: HandedOverTrack,
|
||||
): Promise<void> => {
|
||||
teardowns.get(request.source)?.();
|
||||
switch (request.source) {
|
||||
case "microphone":
|
||||
return captureMicrophone(request, handed);
|
||||
case "camera":
|
||||
return captureCamera(request, handed);
|
||||
case "screenShare":
|
||||
return captureScreen(request);
|
||||
}
|
||||
};
|
||||
|
||||
// A lobby's tracks are taken over here rather than captured again
|
||||
const start = async (): Promise<void> => {
|
||||
const handed = media?.takeTracks() ?? new Map<string, HandedOverTrack>();
|
||||
for (const request of desired.values()) {
|
||||
const track = handed.get(request.source);
|
||||
handed.delete(request.source);
|
||||
await capture(request, track).catch((e: unknown) => {
|
||||
logger.warn(`Could not capture ${request.source}`, e);
|
||||
if (publishError$.value === null)
|
||||
publishError$.next(toMatrixRTCError(e));
|
||||
});
|
||||
}
|
||||
// Handed over but no longer wanted
|
||||
for (const { track, processor } of handed.values()) {
|
||||
track.stop();
|
||||
processor?.processedTrack.stop();
|
||||
}
|
||||
};
|
||||
|
||||
const setPublishing = (publish: boolean): void => {
|
||||
publishing$.next(publish);
|
||||
if (publish && !started$.value) {
|
||||
started$.next(true);
|
||||
void start();
|
||||
}
|
||||
};
|
||||
|
||||
const publish = async (
|
||||
request: PublishRequest,
|
||||
): Promise<LocalAudioMediaTrack | LocalVideoMediaTrack> => {
|
||||
desired.set(request.source, request);
|
||||
try {
|
||||
// Before the start, the start captures everything desired itself
|
||||
if (started$.value) await capture(request);
|
||||
return await firstValueFrom(
|
||||
publications$.pipe(
|
||||
map((ps) => ps.find((p) => p.source === request.source)),
|
||||
filter((p) => p !== undefined),
|
||||
map((p) => p.mediaTrack),
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
desired.delete(request.source);
|
||||
throw toMatrixRTCError(e);
|
||||
}
|
||||
};
|
||||
|
||||
const unpublish = async (source: MediaSource): Promise<void> => {
|
||||
const published = source === "screenShareAudio" ? "screenShare" : source;
|
||||
if (published === "unknown") return;
|
||||
desired.delete(published);
|
||||
teardowns.get(published)?.();
|
||||
return Promise.resolve();
|
||||
};
|
||||
|
||||
scope.onEnd(() => {
|
||||
// Each teardown removes itself from the map
|
||||
for (const teardown of Array.from(teardowns.values())) teardown();
|
||||
});
|
||||
|
||||
const tracks$ = scope.behavior(
|
||||
combineLatest([started$, publications$]).pipe(
|
||||
map(([started, ps]) => (started ? ps.map((p) => p.mediaTrack) : null)),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
connectionState$,
|
||||
tracks$,
|
||||
encryptionError$: NEVER,
|
||||
setPublishing,
|
||||
publishError$,
|
||||
publish,
|
||||
unpublish,
|
||||
publications$,
|
||||
publishing$,
|
||||
};
|
||||
}
|
||||
|
||||
function exact(deviceId: string | undefined): ConstrainDOMString | undefined {
|
||||
return deviceId === undefined ? undefined : { exact: deviceId };
|
||||
}
|
||||
|
||||
async function getTrack(
|
||||
constraints: MediaStreamConstraints,
|
||||
): Promise<MediaStreamTrack> {
|
||||
const stream = await navigator.mediaDevices.getUserMedia(constraints);
|
||||
const [track] = stream.getTracks();
|
||||
if (track === undefined) throw new MatrixRTCError("No track was captured");
|
||||
return track;
|
||||
}
|
||||
|
||||
function facingModeOf(
|
||||
track: MediaStreamTrack | null,
|
||||
): "user" | "environment" | undefined {
|
||||
const mode = track?.getSettings().facingMode;
|
||||
return mode === "user" || mode === "environment" ? mode : undefined;
|
||||
}
|
||||
@@ -1,325 +0,0 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import {
|
||||
BehaviorSubject,
|
||||
combineLatest,
|
||||
distinctUntilChanged,
|
||||
map,
|
||||
Observable,
|
||||
of,
|
||||
scan,
|
||||
switchMap,
|
||||
timer,
|
||||
} from "rxjs";
|
||||
|
||||
import { type Behavior, constant } from "../../reactive/Behavior";
|
||||
import { type ObservableScope } from "../../reactive/ObservableScope";
|
||||
import {
|
||||
type AudioMediaTrack,
|
||||
type MediaSource,
|
||||
type MediaStreamStats,
|
||||
type MediaTrack,
|
||||
type VideoMediaTrack,
|
||||
} from "../../media-api";
|
||||
|
||||
export interface TrackProps {
|
||||
source: MediaSource;
|
||||
kind: "audio" | "video";
|
||||
id: string;
|
||||
/** The track behind it; may change, as on a device switch, or be null while off. */
|
||||
track$: Behavior<MediaStreamTrack | null>;
|
||||
muted$: Behavior<boolean>;
|
||||
/** Statistics of the RTP stream carrying it, if there is one. */
|
||||
stats: () => Promise<MediaStreamStats>;
|
||||
/** Where attached elements play; only for tracks that are played. */
|
||||
audioOutputDeviceId$?: Behavior<string | undefined>;
|
||||
/** Whether to follow where attached video elements are shown, for `viewport$`. */
|
||||
observeViewport?: boolean;
|
||||
}
|
||||
|
||||
/** Where a video is shown: the largest of its visible elements, in device pixels if known. */
|
||||
export interface Viewport {
|
||||
width?: number;
|
||||
height?: number;
|
||||
}
|
||||
|
||||
export type FullMeshMediaTrack = (AudioMediaTrack | VideoMediaTrack) & {
|
||||
/** Null while no attached element is visible; always null unless observed. */
|
||||
viewport$: Behavior<Viewport | null>;
|
||||
};
|
||||
|
||||
/** Above this level a track turns active; below `INACTIVE_LEVEL` for `INACTIVE_AFTER_MS` it turns inactive. */
|
||||
const ACTIVE_LEVEL = 0.04;
|
||||
const INACTIVE_LEVEL = 0.02;
|
||||
const LEVEL_INTERVAL_MS = 100;
|
||||
const INACTIVE_AFTER_MS = 500;
|
||||
|
||||
let levelContext: AudioContext | undefined;
|
||||
|
||||
/**
|
||||
* A `MediaStreamTrack` as a `MediaTrack`: the same object for the life of a
|
||||
* publication, with every attached element following the track behind it.
|
||||
*/
|
||||
export function createFullMeshMediaTrack(
|
||||
scope: ObservableScope,
|
||||
props: TrackProps,
|
||||
): FullMeshMediaTrack {
|
||||
const { source, kind, id, track$, muted$, stats, audioOutputDeviceId$ } =
|
||||
props;
|
||||
const attached = new Set<HTMLMediaElement>();
|
||||
const viewport =
|
||||
kind === "video" && props.observeViewport
|
||||
? observeViewport(scope)
|
||||
: undefined;
|
||||
let audioContext: AudioContext | undefined;
|
||||
let audioPlugins: AudioNode[] = [];
|
||||
let volume = 1;
|
||||
let webAudio: { nodes: AudioNode[]; gain: GainNode } | undefined;
|
||||
|
||||
const routeWebAudio = (track: MediaStreamTrack | null): void => {
|
||||
for (const node of webAudio?.nodes ?? []) node.disconnect();
|
||||
webAudio = undefined;
|
||||
if (audioContext === undefined || track === null) return;
|
||||
const input = audioContext.createMediaStreamSource(
|
||||
new MediaStream([track]),
|
||||
);
|
||||
const gain = audioContext.createGain();
|
||||
gain.gain.value = volume;
|
||||
const chain: AudioNode[] = [input, ...audioPlugins, gain];
|
||||
for (let i = 0; i < chain.length - 1; i++) chain[i].connect(chain[i + 1]);
|
||||
gain.connect(audioContext.destination);
|
||||
webAudio = { nodes: chain, gain };
|
||||
};
|
||||
|
||||
const apply = (element: HTMLMediaElement): void => {
|
||||
const track = track$.value;
|
||||
element.srcObject = track ? new MediaStream([track]) : null;
|
||||
if (kind === "audio") {
|
||||
// Played through Web Audio instead, where it is routed there
|
||||
element.muted = audioContext !== undefined;
|
||||
element.volume = volume;
|
||||
const sinkId = audioOutputDeviceId$?.value;
|
||||
if (sinkId !== undefined && "setSinkId" in element)
|
||||
void element.setSinkId(sinkId).catch(() => {});
|
||||
}
|
||||
if (element.paused) void element.play().catch(() => {});
|
||||
};
|
||||
|
||||
track$.pipe(scope.bind()).subscribe((track) => {
|
||||
for (const element of attached) apply(element);
|
||||
if (kind === "audio") routeWebAudio(track);
|
||||
});
|
||||
audioOutputDeviceId$?.pipe(scope.bind()).subscribe(() => {
|
||||
for (const element of attached) apply(element);
|
||||
});
|
||||
scope.onEnd(() => {
|
||||
for (const element of attached) element.srcObject = null;
|
||||
attached.clear();
|
||||
routeWebAudio(null);
|
||||
});
|
||||
|
||||
const base: MediaTrack = {
|
||||
source,
|
||||
kind,
|
||||
id,
|
||||
muted$,
|
||||
// DTLS-SRTP, its fingerprints exchanged over Olm
|
||||
encrypted: true,
|
||||
stats$: (intervalMs): Observable<MediaStreamStats> =>
|
||||
timer(0, intervalMs).pipe(
|
||||
switchMap(async () => stats()),
|
||||
scope.bind(),
|
||||
),
|
||||
attach: (element) => {
|
||||
if (attached.has(element)) return;
|
||||
attached.add(element);
|
||||
apply(element);
|
||||
viewport?.observe(element);
|
||||
},
|
||||
detach: (element) => {
|
||||
if (!attached.delete(element)) return;
|
||||
element.srcObject = null;
|
||||
viewport?.unobserve(element);
|
||||
},
|
||||
};
|
||||
|
||||
if (kind === "video")
|
||||
return {
|
||||
...base,
|
||||
kind: "video",
|
||||
viewport$: viewport?.viewport$ ?? constant(null),
|
||||
};
|
||||
|
||||
const audioLevel$ = scope.behavior(
|
||||
combineLatest([track$, muted$]).pipe(
|
||||
switchMap(([track, muted]) =>
|
||||
track === null || muted ? of(0) : level$(track),
|
||||
),
|
||||
),
|
||||
0,
|
||||
);
|
||||
const isActive$ = scope.behavior(
|
||||
audioLevel$.pipe(
|
||||
scan(
|
||||
({ active, quietMs }, level) => {
|
||||
if (level >= ACTIVE_LEVEL) return { active: true, quietMs: 0 };
|
||||
if (level >= INACTIVE_LEVEL) return { active, quietMs: 0 };
|
||||
const quiet = quietMs + LEVEL_INTERVAL_MS;
|
||||
return {
|
||||
active: active && quiet < INACTIVE_AFTER_MS,
|
||||
quietMs: quiet,
|
||||
};
|
||||
},
|
||||
{ active: false, quietMs: 0 },
|
||||
),
|
||||
map(({ active }) => active),
|
||||
distinctUntilChanged(),
|
||||
),
|
||||
false,
|
||||
);
|
||||
|
||||
return {
|
||||
...base,
|
||||
kind: "audio",
|
||||
viewport$: constant(null),
|
||||
audioLevel$,
|
||||
isActive$,
|
||||
setAudioContext: (ctx, plugins = []) => {
|
||||
audioContext = ctx;
|
||||
audioPlugins = plugins;
|
||||
routeWebAudio(track$.value);
|
||||
for (const element of attached) apply(element);
|
||||
},
|
||||
setVolume: (v) => {
|
||||
volume = v;
|
||||
if (webAudio) webAudio.gain.gain.value = v;
|
||||
for (const element of attached) element.volume = v;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Follows the size and visibility of elements. Where the platform has no
|
||||
* observers, an element counts as visible at an unknown size.
|
||||
*/
|
||||
function observeViewport(scope: ObservableScope): {
|
||||
viewport$: Behavior<Viewport | null>;
|
||||
observe: (element: Element) => void;
|
||||
unobserve: (element: Element) => void;
|
||||
} {
|
||||
const shown = new Map<
|
||||
Element,
|
||||
{ visible: boolean; width?: number; height?: number }
|
||||
>();
|
||||
const viewport$ = new BehaviorSubject<Viewport | null>(null);
|
||||
const update = (): void => {
|
||||
const visible = [...shown.values()].filter(
|
||||
({ visible, width, height }) => visible && width !== 0 && height !== 0,
|
||||
);
|
||||
// One element of unknown size leaves the size unknown
|
||||
const next: Viewport | null =
|
||||
visible.length === 0
|
||||
? null
|
||||
: visible.some((e) => e.width === undefined || e.height === undefined)
|
||||
? {}
|
||||
: {
|
||||
width: Math.max(...visible.map((e) => e.width!)),
|
||||
height: Math.max(...visible.map((e) => e.height!)),
|
||||
};
|
||||
const current = viewport$.value;
|
||||
if (
|
||||
(current === null) !== (next === null) ||
|
||||
current?.width !== next?.width ||
|
||||
current?.height !== next?.height
|
||||
)
|
||||
viewport$.next(next);
|
||||
};
|
||||
|
||||
const pixelRatio = globalThis.devicePixelRatio ?? 1;
|
||||
const resizes =
|
||||
typeof ResizeObserver === "undefined"
|
||||
? undefined
|
||||
: new ResizeObserver((entries) => {
|
||||
for (const { target, contentRect } of entries) {
|
||||
const entry = shown.get(target);
|
||||
if (entry === undefined) continue;
|
||||
entry.width = Math.ceil(contentRect.width * pixelRatio);
|
||||
entry.height = Math.ceil(contentRect.height * pixelRatio);
|
||||
}
|
||||
update();
|
||||
});
|
||||
const intersections =
|
||||
typeof IntersectionObserver === "undefined"
|
||||
? undefined
|
||||
: new IntersectionObserver((entries) => {
|
||||
for (const { target, isIntersecting } of entries) {
|
||||
const entry = shown.get(target);
|
||||
if (entry !== undefined) entry.visible = isIntersecting;
|
||||
}
|
||||
update();
|
||||
});
|
||||
scope.onEnd(() => {
|
||||
resizes?.disconnect();
|
||||
intersections?.disconnect();
|
||||
});
|
||||
|
||||
return {
|
||||
viewport$: scope.behavior(viewport$),
|
||||
observe: (element): void => {
|
||||
// Visible until the observers say otherwise, so that nothing is paused
|
||||
// before they first report
|
||||
shown.set(element, { visible: true });
|
||||
resizes?.observe(element);
|
||||
intersections?.observe(element);
|
||||
update();
|
||||
},
|
||||
unobserve: (element): void => {
|
||||
shown.delete(element);
|
||||
resizes?.unobserve(element);
|
||||
intersections?.unobserve(element);
|
||||
update();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The RMS level of an audio track, 0 to 1, sampled while subscribed. */
|
||||
function level$(track: MediaStreamTrack): Observable<number> {
|
||||
return new Observable<number>((subscriber) => {
|
||||
levelContext ??= new AudioContext();
|
||||
const ctx = levelContext;
|
||||
const input = ctx.createMediaStreamSource(new MediaStream([track]));
|
||||
const analyser = ctx.createAnalyser();
|
||||
analyser.fftSize = 512;
|
||||
input.connect(analyser);
|
||||
const samples = new Float32Array(analyser.fftSize);
|
||||
const sub = timer(0, LEVEL_INTERVAL_MS).subscribe(() => {
|
||||
analyser.getFloatTimeDomainData(samples);
|
||||
let sum = 0;
|
||||
for (const s of samples) sum += s * s;
|
||||
subscriber.next(Math.min(1, Math.sqrt(sum / samples.length) * 4));
|
||||
});
|
||||
return () => {
|
||||
sub.unsubscribe();
|
||||
input.disconnect();
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** The inbound or outbound RTP statistics of one track on a peer connection. */
|
||||
export async function rtpStats(
|
||||
pc: RTCPeerConnection | undefined,
|
||||
track: MediaStreamTrack | null,
|
||||
direction: "inbound-rtp" | "outbound-rtp",
|
||||
): Promise<MediaStreamStats> {
|
||||
if (pc === undefined || track === null) return undefined;
|
||||
const report = await pc.getStats(track);
|
||||
for (const stats of report.values())
|
||||
if ((stats as RTCStats).type === direction)
|
||||
return stats as RTCInboundRtpStreamStats & RTCOutboundRtpStreamStats;
|
||||
return undefined;
|
||||
}
|
||||
@@ -1,248 +0,0 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { logger } from "matrix-js-sdk/lib/logger";
|
||||
|
||||
import { ObservableScope } from "../../reactive/ObservableScope";
|
||||
import { MediaConnectionState } from "../api";
|
||||
import {
|
||||
CANDIDATE_BATCH_MS,
|
||||
createPeerConnectionBase,
|
||||
type PeerConnectionBase,
|
||||
} from "./PeerConnection";
|
||||
import { type ControlMessage, CONTROL_CHANNEL_LABEL } from "./ControlChannel";
|
||||
import {
|
||||
type FakeSignalling,
|
||||
fakeSignalling,
|
||||
installWebRtcFakes,
|
||||
lastPeerConnection,
|
||||
peer,
|
||||
settle,
|
||||
} from "./test";
|
||||
|
||||
describe("createPeerConnectionBase", () => {
|
||||
let scope: ObservableScope;
|
||||
let signalling: FakeSignalling;
|
||||
let base: PeerConnectionBase;
|
||||
let received: ControlMessage[];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
installWebRtcFakes();
|
||||
scope = new ObservableScope();
|
||||
signalling = fakeSignalling();
|
||||
received = [];
|
||||
base = createPeerConnectionBase({
|
||||
scope,
|
||||
peer,
|
||||
connectionId: "c1",
|
||||
signalling,
|
||||
iceServers: [{ urls: ["turn:example.org"] }],
|
||||
onControlMessage: (message) => received.push(message),
|
||||
logger,
|
||||
});
|
||||
});
|
||||
afterEach(() => {
|
||||
scope.end();
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("uses the ICE servers it was given", () => {
|
||||
expect(lastPeerConnection().config.iceServers).toEqual([
|
||||
{ urls: ["turn:example.org"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("sends the candidates gathered within a batch in one message", () => {
|
||||
const pc = lastPeerConnection();
|
||||
pc.gather({ candidate: "a", sdpMid: "0", sdpMLineIndex: 0 });
|
||||
pc.gather({ candidate: "b", sdpMid: "0", sdpMLineIndex: 0 });
|
||||
pc.gather(null);
|
||||
expect(signalling.send).not.toHaveBeenCalled();
|
||||
|
||||
vi.advanceTimersByTime(CANDIDATE_BATCH_MS);
|
||||
expect(signalling.sent()).toEqual([
|
||||
{
|
||||
type: "candidates",
|
||||
candidates: [
|
||||
{ candidate: "a", sdpMid: "0", sdpMLineIndex: 0 },
|
||||
{ candidate: "b", sdpMid: "0", sdpMLineIndex: 0 },
|
||||
// The end of the gathering
|
||||
{ candidate: "", sdpMid: null, sdpMLineIndex: null },
|
||||
],
|
||||
},
|
||||
]);
|
||||
expect(signalling.sentConnectionIds()).toEqual(["c1"]);
|
||||
});
|
||||
|
||||
it("drops pending candidates when it closes", () => {
|
||||
lastPeerConnection().gather({ candidate: "a" });
|
||||
base.close("bye", false);
|
||||
vi.advanceTimersByTime(CANDIDATE_BATCH_MS);
|
||||
expect(signalling.send).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("runs queued operations in order, past a failing one", async () => {
|
||||
const order: string[] = [];
|
||||
base.enqueue(async () => {
|
||||
order.push("first");
|
||||
return Promise.reject(new Error("failed"));
|
||||
});
|
||||
base.enqueue(async () => {
|
||||
order.push("second");
|
||||
return Promise.resolve();
|
||||
});
|
||||
await settle();
|
||||
expect(order).toEqual(["first", "second"]);
|
||||
});
|
||||
|
||||
it("applies received candidates, ignoring one that fails", async () => {
|
||||
base.addCandidates([{ candidate: "bad" }, { candidate: "good" }]);
|
||||
await settle();
|
||||
expect(lastPeerConnection().addedCandidates).toEqual([
|
||||
{ candidate: "good" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("tells the peer once when it closes", () => {
|
||||
base.close("done", true);
|
||||
base.close("again", true);
|
||||
expect(lastPeerConnection().closed).toBe(true);
|
||||
expect(signalling.sent()).toEqual([{ type: "close", reason: "done" }]);
|
||||
});
|
||||
|
||||
it("doesn't tell a peer that closed first", () => {
|
||||
base.close("theirs", false);
|
||||
expect(lastPeerConnection().closed).toBe(true);
|
||||
expect(signalling.send).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("closes when its scope ends", () => {
|
||||
scope.end();
|
||||
expect(lastPeerConnection().closed).toBe(true);
|
||||
expect(signalling.sent()).toEqual([{ type: "close", reason: "ended" }]);
|
||||
});
|
||||
|
||||
it("maps the connection state", () => {
|
||||
const pc = lastPeerConnection();
|
||||
expect(base.state$.value).toBe(MediaConnectionState.Initialized);
|
||||
pc.setConnectionState("connecting");
|
||||
expect(base.state$.value).toBe(MediaConnectionState.Connecting);
|
||||
pc.setConnectionState("connected");
|
||||
expect(base.state$.value).toBe(MediaConnectionState.Connected);
|
||||
pc.setConnectionState("disconnected");
|
||||
expect(base.state$.value).toBe(MediaConnectionState.Reconnecting);
|
||||
pc.setConnectionState("failed");
|
||||
expect(base.state$.value).toBeInstanceOf(Error);
|
||||
pc.setConnectionState("closed");
|
||||
expect(base.state$.value).toBe(MediaConnectionState.Stopped);
|
||||
});
|
||||
|
||||
describe("the control channel", () => {
|
||||
const offer: ControlMessage = {
|
||||
type: "description",
|
||||
description: { type: "offer", sdp: "o" },
|
||||
};
|
||||
const metadata = (muted: boolean): ControlMessage => ({
|
||||
type: "track_metadata",
|
||||
track_metadata: { "0": { purpose: "m.usermedia", muted } },
|
||||
});
|
||||
|
||||
it("is negotiated, with the reserved label and id", () => {
|
||||
base.openControlChannel();
|
||||
base.openControlChannel();
|
||||
const [channel] = lastPeerConnection().dataChannels;
|
||||
expect(lastPeerConnection().dataChannels).toHaveLength(1);
|
||||
expect(channel.label).toBe(CONTROL_CHANNEL_LABEL);
|
||||
expect(channel.init).toEqual({ negotiated: true, id: 0 });
|
||||
});
|
||||
|
||||
it("carries every message once it is open, apart from close", () => {
|
||||
base.openControlChannel();
|
||||
base.send(offer);
|
||||
expect(signalling.sent()).toEqual([offer]);
|
||||
|
||||
const channel = lastPeerConnection().control();
|
||||
channel.open();
|
||||
base.answerReceived();
|
||||
base.send(offer);
|
||||
lastPeerConnection().gather({ candidate: "a" });
|
||||
vi.advanceTimersByTime(CANDIDATE_BATCH_MS);
|
||||
expect(channel.sentMessages()).toEqual([
|
||||
offer,
|
||||
{ type: "candidates", candidates: [{ candidate: "a" }] },
|
||||
]);
|
||||
|
||||
base.close("done", true);
|
||||
expect(signalling.sent()).toEqual([
|
||||
offer,
|
||||
{ type: "close", reason: "done" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("is only switched to once no to-device offer awaits its answer", () => {
|
||||
base.openControlChannel();
|
||||
base.send(offer);
|
||||
base.send(metadata(true));
|
||||
const channel = lastPeerConnection().control();
|
||||
channel.open();
|
||||
// A late to-device offer could otherwise overwrite this metadata
|
||||
lastPeerConnection().gather({ candidate: "a" });
|
||||
vi.advanceTimersByTime(CANDIDATE_BATCH_MS);
|
||||
expect(channel.sentMessages()).toEqual([]);
|
||||
expect(signalling.sent()).toEqual([
|
||||
offer,
|
||||
{ type: "candidates", candidates: [{ candidate: "a" }] },
|
||||
]);
|
||||
|
||||
base.answerReceived();
|
||||
expect(channel.sentMessages()).toEqual([metadata(true)]);
|
||||
});
|
||||
|
||||
it("holds the latest metadata until it opens", () => {
|
||||
base.openControlChannel();
|
||||
base.send(metadata(true));
|
||||
base.send(metadata(false));
|
||||
expect(signalling.send).not.toHaveBeenCalled();
|
||||
|
||||
const channel = lastPeerConnection().control();
|
||||
channel.open();
|
||||
expect(channel.sentMessages()).toEqual([metadata(false)]);
|
||||
});
|
||||
|
||||
it("hands over the messages it receives, ignoring what it doesn't know", () => {
|
||||
base.openControlChannel();
|
||||
const channel = lastPeerConnection().control();
|
||||
channel.open();
|
||||
channel.receive(metadata(true));
|
||||
channel.receive({ type: "future_message" });
|
||||
channel.receive("not json");
|
||||
channel.receive({ type: "description", description: { type: "x" } });
|
||||
expect(received).toEqual([metadata(true)]);
|
||||
});
|
||||
|
||||
it("fails the connection when it closes on its own", () => {
|
||||
base.openControlChannel();
|
||||
const pc = lastPeerConnection();
|
||||
pc.setConnectionState("connected");
|
||||
pc.control().open();
|
||||
pc.control().close();
|
||||
expect(base.state$.value).toEqual(
|
||||
new Error("The control channel closed"),
|
||||
);
|
||||
});
|
||||
|
||||
it("doesn't fail a connection we close", () => {
|
||||
base.openControlChannel();
|
||||
lastPeerConnection().control().open();
|
||||
base.close("done", true);
|
||||
expect(base.state$.value).not.toBeInstanceOf(Error);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,226 +0,0 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
/** What the publisher and the subscriber side of a connection share. */
|
||||
|
||||
import { type Logger } from "matrix-js-sdk/lib/logger";
|
||||
import {
|
||||
BehaviorSubject,
|
||||
combineLatest,
|
||||
fromEvent,
|
||||
map,
|
||||
startWith,
|
||||
} from "rxjs";
|
||||
|
||||
import { type Behavior } from "../../reactive/Behavior";
|
||||
import { type ObservableScope } from "../../reactive/ObservableScope";
|
||||
import { MediaConnectionState } from "../api";
|
||||
import {
|
||||
type ControlMessage,
|
||||
createControlChannel,
|
||||
parseControlMessage,
|
||||
} from "./ControlChannel";
|
||||
import { type Peer, type Signalling } from "./signalling";
|
||||
|
||||
/** How long trickled candidates are collected before they are sent in one message. */
|
||||
export const CANDIDATE_BATCH_MS = 200;
|
||||
|
||||
type MetadataMessage = Extract<
|
||||
ControlMessage,
|
||||
{ type: "track_metadata" | "consumption_metadata" }
|
||||
>;
|
||||
|
||||
export interface PeerConnectionBase {
|
||||
readonly connectionId: string;
|
||||
readonly pc: RTCPeerConnection;
|
||||
readonly state$: Behavior<MediaConnectionState | Error>;
|
||||
/** Runs `op` after every operation queued before it, so that SDP and candidates apply in order. */
|
||||
enqueue(op: () => Promise<void>): void;
|
||||
/**
|
||||
* Creates our side of the control channel. The publisher does so before
|
||||
* its first offer, the subscriber once it applied that offer.
|
||||
*/
|
||||
openControlChannel(): void;
|
||||
/**
|
||||
* Sends a message to the peer: over the control channel once we switched
|
||||
* to it, before that as a to-device message. Metadata has no to-device
|
||||
* message of its own: the latest waits for the switch.
|
||||
*/
|
||||
send(message: ControlMessage): void;
|
||||
/**
|
||||
* Tells that the answer to our latest offer arrived. We switch to the
|
||||
* control channel only once no to-device offer is waiting for its answer,
|
||||
* so that a late offer can't overwrite newer metadata.
|
||||
*/
|
||||
answerReceived(): void;
|
||||
/** Applies a received batch of candidates. */
|
||||
addCandidates(candidates: RTCIceCandidateInit[]): void;
|
||||
/** Closes the peer connection, telling the peer unless it closed first. */
|
||||
close(reason: string | undefined, notifyPeer: boolean): void;
|
||||
}
|
||||
|
||||
export function createPeerConnectionBase({
|
||||
scope,
|
||||
peer,
|
||||
connectionId,
|
||||
signalling,
|
||||
iceServers,
|
||||
onControlMessage,
|
||||
logger,
|
||||
}: {
|
||||
scope: ObservableScope;
|
||||
peer: Peer;
|
||||
connectionId: string;
|
||||
signalling: Signalling;
|
||||
iceServers: RTCIceServer[];
|
||||
/** A message the peer sent over the control channel. */
|
||||
onControlMessage: (message: ControlMessage) => void;
|
||||
logger: Logger;
|
||||
}): PeerConnectionBase {
|
||||
const pc = new RTCPeerConnection({ iceServers });
|
||||
const closed$ = new BehaviorSubject(false);
|
||||
const controlFailed$ = new BehaviorSubject(false);
|
||||
|
||||
let queue = Promise.resolve();
|
||||
const enqueue = (op: () => Promise<void>): void => {
|
||||
queue = queue.then(op).catch((e: unknown) => {
|
||||
logger.warn("Signalling operation failed", e);
|
||||
});
|
||||
};
|
||||
|
||||
let control: RTCDataChannel | null = null;
|
||||
let switched = false;
|
||||
let awaitingAnswer = false;
|
||||
const pendingMetadata = new Map<MetadataMessage["type"], MetadataMessage>();
|
||||
const trySwitch = (): void => {
|
||||
if (switched || awaitingAnswer || control?.readyState !== "open") return;
|
||||
switched = true;
|
||||
logger.debug("Switched to the control channel");
|
||||
for (const message of pendingMetadata.values())
|
||||
control.send(JSON.stringify(message));
|
||||
pendingMetadata.clear();
|
||||
};
|
||||
const openControlChannel = (): void => {
|
||||
if (control !== null) return;
|
||||
const channel = createControlChannel(pc);
|
||||
control = channel;
|
||||
channel.addEventListener("open", trySwitch);
|
||||
channel.addEventListener("message", ({ data }: MessageEvent) => {
|
||||
const message = parseControlMessage(data);
|
||||
if (message === null) logger.debug("Ignoring a control message", data);
|
||||
else onControlMessage(message);
|
||||
});
|
||||
// Ours to close only with the connection: closing otherwise is a failure
|
||||
channel.addEventListener("close", () => {
|
||||
if (!closed$.value) controlFailed$.next(true);
|
||||
});
|
||||
};
|
||||
|
||||
const send = (message: ControlMessage): void => {
|
||||
if (closed$.value) return;
|
||||
if (switched) control!.send(JSON.stringify(message));
|
||||
else if (
|
||||
message.type === "track_metadata" ||
|
||||
message.type === "consumption_metadata"
|
||||
)
|
||||
pendingMetadata.set(message.type, message);
|
||||
else {
|
||||
if (
|
||||
message.type === "description" &&
|
||||
message.description.type === "offer"
|
||||
)
|
||||
awaitingAnswer = true;
|
||||
signalling.send(peer, connectionId, message);
|
||||
}
|
||||
};
|
||||
|
||||
const answerReceived = (): void => {
|
||||
awaitingAnswer = false;
|
||||
trySwitch();
|
||||
};
|
||||
|
||||
// Trickled, in batches
|
||||
let pending: RTCIceCandidateInit[] = [];
|
||||
let batchTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const flushCandidates = (): void => {
|
||||
batchTimer = undefined;
|
||||
if (pending.length === 0) return;
|
||||
send({ type: "candidates", candidates: pending });
|
||||
pending = [];
|
||||
};
|
||||
pc.addEventListener("icecandidate", ({ candidate }) => {
|
||||
// A null candidate ends the gathering: an empty one says so on the wire
|
||||
pending.push(
|
||||
candidate
|
||||
? candidate.toJSON()
|
||||
: { candidate: "", sdpMid: null, sdpMLineIndex: null },
|
||||
);
|
||||
batchTimer ??= setTimeout(flushCandidates, CANDIDATE_BATCH_MS);
|
||||
});
|
||||
|
||||
const addCandidates: PeerConnectionBase["addCandidates"] = (candidates) =>
|
||||
enqueue(async () => {
|
||||
for (const candidate of candidates)
|
||||
await pc
|
||||
.addIceCandidate(candidate)
|
||||
// A candidate of an outdated description, or a bad one: not fatal
|
||||
.catch((e: unknown) => logger.debug("Ignored a candidate", e));
|
||||
});
|
||||
|
||||
const close: PeerConnectionBase["close"] = (reason, notifyPeer) => {
|
||||
if (closed$.value) return;
|
||||
clearTimeout(batchTimer);
|
||||
// Always to-device: closing the peer connection would race a channel message
|
||||
if (notifyPeer)
|
||||
signalling.send(peer, connectionId, { type: "close", reason });
|
||||
closed$.next(true);
|
||||
pc.close();
|
||||
};
|
||||
scope.onEnd(() => close("ended", true));
|
||||
|
||||
const state$ = scope.behavior(
|
||||
combineLatest([
|
||||
fromEvent(pc, "connectionstatechange").pipe(startWith(null)),
|
||||
controlFailed$,
|
||||
]).pipe(
|
||||
map(([, controlFailed]) =>
|
||||
controlFailed && pc.connectionState !== "closed"
|
||||
? new Error("The control channel closed")
|
||||
: toState(pc.connectionState),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
connectionId,
|
||||
pc,
|
||||
state$,
|
||||
enqueue,
|
||||
openControlChannel,
|
||||
send,
|
||||
answerReceived,
|
||||
addCandidates,
|
||||
close,
|
||||
};
|
||||
}
|
||||
|
||||
function toState(state: RTCPeerConnectionState): MediaConnectionState | Error {
|
||||
switch (state) {
|
||||
case "new":
|
||||
return MediaConnectionState.Initialized;
|
||||
case "connecting":
|
||||
return MediaConnectionState.Connecting;
|
||||
case "connected":
|
||||
return MediaConnectionState.Connected;
|
||||
case "disconnected":
|
||||
return MediaConnectionState.Reconnecting;
|
||||
case "failed":
|
||||
return new Error("The peer connection failed");
|
||||
case "closed":
|
||||
return MediaConnectionState.Stopped;
|
||||
}
|
||||
}
|
||||
@@ -1,360 +0,0 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { logger } from "matrix-js-sdk/lib/logger";
|
||||
|
||||
import { ObservableScope } from "../../reactive/ObservableScope";
|
||||
import { CONTROL_CHANNEL_LABEL } from "./ControlChannel";
|
||||
import { type FullMeshLocalMedia } from "./LocalMedia";
|
||||
import { DATA_CHANNEL_LABEL, DATA_PROTOCOL } from "./metadata";
|
||||
import {
|
||||
createPublisherConnection,
|
||||
type PublisherConnection,
|
||||
} from "./PublisherConnection";
|
||||
import {
|
||||
type FakeSignalling,
|
||||
fakeLocalMedia,
|
||||
fakePublication,
|
||||
fakeSignalling,
|
||||
fakeTrack,
|
||||
fromPeer,
|
||||
type PeerMessage,
|
||||
installWebRtcFakes,
|
||||
lastPeerConnection,
|
||||
peer,
|
||||
settle,
|
||||
} from "./test";
|
||||
|
||||
describe("createPublisherConnection", () => {
|
||||
let scope: ObservableScope;
|
||||
let signalling: FakeSignalling;
|
||||
let local: ReturnType<typeof fakeLocalMedia>;
|
||||
|
||||
function create(): PublisherConnection {
|
||||
return createPublisherConnection({
|
||||
scope,
|
||||
peer,
|
||||
connectionId: "c1",
|
||||
signalling,
|
||||
iceServers: [],
|
||||
local: local as unknown as FullMeshLocalMedia,
|
||||
logger,
|
||||
});
|
||||
}
|
||||
|
||||
const answer = (): PeerMessage =>
|
||||
fromPeer("c1", {
|
||||
type: "description",
|
||||
description: { type: "answer", sdp: "answer" },
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
installWebRtcFakes();
|
||||
scope = new ObservableScope();
|
||||
signalling = fakeSignalling();
|
||||
local = fakeLocalMedia();
|
||||
});
|
||||
afterEach(() => {
|
||||
scope.end();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("offers right away, even without tracks", async () => {
|
||||
create();
|
||||
await settle();
|
||||
expect(signalling.sent("description")).toEqual([
|
||||
{
|
||||
type: "description",
|
||||
description: { type: "offer", sdp: "offer-1" },
|
||||
track_metadata: {},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("describes each track by the mid it gets with the offer", async () => {
|
||||
const mic = fakePublication("audio");
|
||||
const camera = fakePublication("video", { stream: mic.stream });
|
||||
const screen = fakePublication("video", { source: "screenShare" });
|
||||
camera.muted$.next(true);
|
||||
local.publications$.next([mic, camera, screen]);
|
||||
create();
|
||||
await settle();
|
||||
expect(signalling.sent("description")).toEqual([
|
||||
expect.objectContaining({
|
||||
track_metadata: {
|
||||
"0": { purpose: "m.usermedia", muted: false },
|
||||
"1": { purpose: "m.usermedia", muted: true },
|
||||
"2": { purpose: "m.screenshare", muted: false },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("creates the control channel and the data channel before its first offer", () => {
|
||||
create();
|
||||
const [control, data] = lastPeerConnection().dataChannels;
|
||||
expect(control.label).toBe(CONTROL_CHANNEL_LABEL);
|
||||
expect(data).toMatchObject({
|
||||
label: DATA_CHANNEL_LABEL,
|
||||
protocol: DATA_PROTOCOL,
|
||||
});
|
||||
expect(lastPeerConnection().offers).toBe(0);
|
||||
});
|
||||
|
||||
it("sends each publication on a sendonly transceiver in its stream", async () => {
|
||||
const mic = fakePublication("audio");
|
||||
const camera = fakePublication("video", { stream: mic.stream });
|
||||
local.publications$.next([mic, camera]);
|
||||
create();
|
||||
await settle();
|
||||
|
||||
const [a, v] = lastPeerConnection().transceivers;
|
||||
expect(a).toMatchObject({ kind: "audio", direction: "sendonly" });
|
||||
expect(a.streams).toEqual([mic.stream]);
|
||||
expect(a.sender.track).toBe(mic.track$.value);
|
||||
expect(v).toMatchObject({ kind: "video", direction: "sendonly" });
|
||||
expect(v.sender.track).toBe(camera.track$.value);
|
||||
// One offer for both
|
||||
expect(signalling.sent("description")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("follows a track change without renegotiating", async () => {
|
||||
const camera = fakePublication("video");
|
||||
local.publications$.next([camera]);
|
||||
create();
|
||||
await settle();
|
||||
const next = fakeTrack("video");
|
||||
camera.track$.next(next);
|
||||
expect(lastPeerConnection().transceivers[0].sender.track).toBe(next);
|
||||
expect(signalling.sent("description")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("sends nothing while not publishing", async () => {
|
||||
const camera = fakePublication("video");
|
||||
local.publications$.next([camera]);
|
||||
local.publishing$.next(false);
|
||||
create();
|
||||
await settle();
|
||||
const { sender } = lastPeerConnection().transceivers[0];
|
||||
expect(sender.track).toBeNull();
|
||||
|
||||
local.publishing$.next(true);
|
||||
expect(sender.track).toBe(camera.track$.value);
|
||||
});
|
||||
|
||||
it("holds changes while an offer is unanswered, then offers once for all", async () => {
|
||||
const connection = create();
|
||||
const pc = lastPeerConnection();
|
||||
await settle();
|
||||
expect(pc.offers).toBe(1);
|
||||
|
||||
local.publications$.next([fakePublication("audio")]);
|
||||
local.publications$.next([
|
||||
...local.publications$.value,
|
||||
fakePublication("video"),
|
||||
]);
|
||||
await settle();
|
||||
expect(pc.offers).toBe(1);
|
||||
|
||||
connection.handle(answer());
|
||||
await settle();
|
||||
expect(pc.offers).toBe(2);
|
||||
expect(pc.transceivers).toHaveLength(2);
|
||||
|
||||
// Nothing changed since: the next answer doesn't lead to another offer
|
||||
connection.handle(answer());
|
||||
await settle();
|
||||
expect(pc.offers).toBe(2);
|
||||
});
|
||||
|
||||
it("stops the transceiver of a removed publication and renegotiates", async () => {
|
||||
const camera = fakePublication("video");
|
||||
local.publications$.next([camera]);
|
||||
const connection = create();
|
||||
await settle();
|
||||
connection.handle(answer());
|
||||
await settle();
|
||||
|
||||
local.publications$.next([]);
|
||||
await settle();
|
||||
const pc = lastPeerConnection();
|
||||
expect(pc.transceivers[0].stopped).toBe(true);
|
||||
expect(pc.offers).toBe(2);
|
||||
});
|
||||
|
||||
it("signals mute changes over the control channel without renegotiating", async () => {
|
||||
const mic = fakePublication("audio");
|
||||
local.publications$.next([mic]);
|
||||
const connection = create();
|
||||
await settle();
|
||||
connection.handle(answer());
|
||||
await settle();
|
||||
const control = lastPeerConnection().control();
|
||||
control.open();
|
||||
mic.muted$.next(true);
|
||||
expect(control.sentMessages()).toEqual([
|
||||
{
|
||||
type: "track_metadata",
|
||||
track_metadata: { "0": { purpose: "m.usermedia", muted: true } },
|
||||
},
|
||||
]);
|
||||
expect(lastPeerConnection().offers).toBe(1);
|
||||
});
|
||||
|
||||
it("holds a mute change until its to-device offer is answered", async () => {
|
||||
const mic = fakePublication("audio");
|
||||
local.publications$.next([mic]);
|
||||
const connection = create();
|
||||
await settle();
|
||||
const control = lastPeerConnection().control();
|
||||
control.open();
|
||||
mic.muted$.next(true);
|
||||
expect(control.sentMessages()).toEqual([]);
|
||||
|
||||
connection.handle(answer());
|
||||
await settle();
|
||||
expect(control.sentMessages()).toEqual([
|
||||
{
|
||||
type: "track_metadata",
|
||||
track_metadata: { "0": { purpose: "m.usermedia", muted: true } },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("renegotiates over the control channel once it is open", async () => {
|
||||
const connection = create();
|
||||
await settle();
|
||||
connection.handle(answer());
|
||||
await settle();
|
||||
const control = lastPeerConnection().control();
|
||||
control.open();
|
||||
|
||||
local.publications$.next([fakePublication("audio")]);
|
||||
await settle();
|
||||
expect(control.sentMessages()).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "description",
|
||||
description: { type: "offer", sdp: "offer-2" },
|
||||
}),
|
||||
);
|
||||
expect(signalling.sent("description")).toHaveLength(1);
|
||||
|
||||
// The answer comes back the same way
|
||||
control.receive({
|
||||
type: "description",
|
||||
description: { type: "answer", sdp: "answer-2" },
|
||||
});
|
||||
await settle();
|
||||
expect(lastPeerConnection().remoteDescription).toEqual({
|
||||
type: "answer",
|
||||
sdp: "answer-2",
|
||||
});
|
||||
});
|
||||
|
||||
describe("consumption metadata", () => {
|
||||
/** A connection sending one camera track, with its control channel open. */
|
||||
async function sendingCamera(settings: MediaTrackSettings = {}): Promise<{
|
||||
camera: ReturnType<typeof fakePublication>;
|
||||
consume: (metadata: unknown) => Promise<void>;
|
||||
}> {
|
||||
const camera = fakePublication("video");
|
||||
camera.track$.next(fakeTrack("video", settings));
|
||||
local.publications$.next([camera]);
|
||||
const connection = create();
|
||||
await settle();
|
||||
connection.handle(answer());
|
||||
await settle();
|
||||
const control = lastPeerConnection().control();
|
||||
control.open();
|
||||
return {
|
||||
camera,
|
||||
consume: async (metadata): Promise<void> => {
|
||||
control.receive({
|
||||
type: "consumption_metadata",
|
||||
consumption_metadata: metadata,
|
||||
});
|
||||
await settle();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
it("stops sending a track that isn't in use, without renegotiating", async () => {
|
||||
const { camera, consume } = await sendingCamera();
|
||||
const { sender } = lastPeerConnection().transceivers[0];
|
||||
await consume({ "0": { in_use: false } });
|
||||
expect(sender.track).toBeNull();
|
||||
|
||||
await consume({});
|
||||
expect(sender.track).toBe(camera.track$.value);
|
||||
expect(lastPeerConnection().offers).toBe(1);
|
||||
});
|
||||
|
||||
it("scales the video down to the largest size shown", async () => {
|
||||
const { consume } = await sendingCamera({ width: 1280, height: 720 });
|
||||
const { sender } = lastPeerConnection().transceivers[0];
|
||||
await consume({ "0": { max_width: 320, max_height: 320 } });
|
||||
expect(sender.parameters.encodings).toEqual([
|
||||
{ scaleResolutionDownBy: 4 },
|
||||
]);
|
||||
|
||||
// Larger than the camera: sent as it is
|
||||
await consume({ "0": { max_width: 4000, max_height: 4000 } });
|
||||
expect(sender.parameters.encodings).toEqual([
|
||||
{ scaleResolutionDownBy: 1 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
it("sends data once the data channel is open", () => {
|
||||
const connection = create();
|
||||
expect(connection.sendData("early")).toBe(false);
|
||||
const data = lastPeerConnection().dataChannels[1];
|
||||
data.open();
|
||||
expect(connection.sendData("hello")).toBe(true);
|
||||
expect(data.sent).toEqual(["hello"]);
|
||||
});
|
||||
|
||||
it("closes, telling the subscriber, when the control channel fails", async () => {
|
||||
create();
|
||||
await settle();
|
||||
const pc = lastPeerConnection();
|
||||
pc.control().open();
|
||||
pc.control().close();
|
||||
expect(pc.closed).toBe(true);
|
||||
expect(signalling.sent("close")).toEqual([
|
||||
{ type: "close", reason: "failed" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("applies the subscriber's candidates", async () => {
|
||||
const connection = create();
|
||||
await settle();
|
||||
connection.handle(answer());
|
||||
connection.handle(
|
||||
fromPeer("c1", {
|
||||
type: "candidates",
|
||||
candidates: [{ candidate: "x" }],
|
||||
}),
|
||||
);
|
||||
await settle();
|
||||
expect(lastPeerConnection().addedCandidates).toEqual([{ candidate: "x" }]);
|
||||
});
|
||||
|
||||
it("ends without answering when the subscriber closes", async () => {
|
||||
const connection = create();
|
||||
await settle();
|
||||
connection.handle(fromPeer("c1", { type: "close", reason: "bye" }));
|
||||
const pc = lastPeerConnection();
|
||||
expect(pc.closed).toBe(true);
|
||||
expect(signalling.sent("close")).toEqual([]);
|
||||
// Its scope ended: no more offers go out
|
||||
local.publications$.next([fakePublication("audio")]);
|
||||
await settle();
|
||||
expect(pc.offers).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -1,281 +0,0 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { type Logger } from "matrix-js-sdk/lib/logger";
|
||||
import {
|
||||
BehaviorSubject,
|
||||
combineLatest,
|
||||
distinctUntilChanged,
|
||||
filter,
|
||||
map,
|
||||
merge,
|
||||
type Observable,
|
||||
skip,
|
||||
type Subscription,
|
||||
switchMap,
|
||||
} from "rxjs";
|
||||
|
||||
import { type ObservableScope } from "../../reactive/ObservableScope";
|
||||
import { type FullMeshLocalMedia, type LocalPublication } from "./LocalMedia";
|
||||
import {
|
||||
type ConsumptionMetadata,
|
||||
type ConsumptionMetadataEntry,
|
||||
DATA_CHANNEL_LABEL,
|
||||
DATA_PROTOCOL,
|
||||
type MediaPurpose,
|
||||
type TrackMetadata,
|
||||
} from "./metadata";
|
||||
import {
|
||||
createPeerConnectionBase,
|
||||
type PeerConnectionBase,
|
||||
} from "./PeerConnection";
|
||||
import {
|
||||
type ConnectionMessage,
|
||||
type Peer,
|
||||
type Signalling,
|
||||
} from "./signalling";
|
||||
|
||||
export interface PublisherConnection extends PeerConnectionBase {
|
||||
/** A to-device message of this connection from the subscriber. */
|
||||
handle(message: ConnectionMessage): void;
|
||||
/** Sends one message on the data channel; false while it isn't open. */
|
||||
sendData(message: string): boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Our side of a connection a subscriber asked for: we only send, and we are
|
||||
* the only side that makes offers, so there is no glare.
|
||||
*/
|
||||
export function createPublisherConnection({
|
||||
scope,
|
||||
peer,
|
||||
connectionId,
|
||||
signalling,
|
||||
iceServers,
|
||||
local,
|
||||
logger: parentLogger,
|
||||
}: {
|
||||
scope: ObservableScope;
|
||||
peer: Peer;
|
||||
connectionId: string;
|
||||
signalling: Signalling;
|
||||
iceServers: RTCIceServer[];
|
||||
local: FullMeshLocalMedia;
|
||||
logger: Logger;
|
||||
}): PublisherConnection {
|
||||
const logger = parentLogger.getChild(
|
||||
`[Publisher → ${peer.memberId} ${connectionId}]`,
|
||||
);
|
||||
const base = createPeerConnectionBase({
|
||||
scope,
|
||||
peer,
|
||||
connectionId,
|
||||
signalling,
|
||||
iceServers,
|
||||
onControlMessage: (message) => handle(message),
|
||||
logger,
|
||||
});
|
||||
const { pc, enqueue } = base;
|
||||
const consumption$ = new BehaviorSubject<ConsumptionMetadata>({});
|
||||
|
||||
// Both before the first offer, which so has the connection's data section
|
||||
base.openControlChannel();
|
||||
const data = pc.createDataChannel(DATA_CHANNEL_LABEL, {
|
||||
protocol: DATA_PROTOCOL,
|
||||
});
|
||||
|
||||
// One sendonly transceiver per publication, for as long as it exists
|
||||
const transceivers = new Map<
|
||||
LocalPublication,
|
||||
{ transceiver: RTCRtpTransceiver; tracks: Subscription }
|
||||
>();
|
||||
|
||||
/** The metadata of every track with a `mid`, which it gets with the offer that adds it. */
|
||||
const trackMetadata = (): TrackMetadata => {
|
||||
const metadata: TrackMetadata = {};
|
||||
for (const [publication, { transceiver }] of transceivers)
|
||||
if (transceiver.mid !== null)
|
||||
metadata[transceiver.mid] = {
|
||||
purpose: purposeOf(publication),
|
||||
muted: publication.mediaTrack.muted$.value,
|
||||
};
|
||||
return metadata;
|
||||
};
|
||||
|
||||
// A new offer has to wait while one is unanswered; changes made meanwhile
|
||||
// go out together in the next one
|
||||
let offerPending = false;
|
||||
let renegotiate = false;
|
||||
const negotiate = (): void => {
|
||||
if (offerPending) {
|
||||
renegotiate = true;
|
||||
return;
|
||||
}
|
||||
offerPending = true;
|
||||
renegotiate = false;
|
||||
enqueue(async () => {
|
||||
const offer = await pc.createOffer();
|
||||
await pc.setLocalDescription(offer);
|
||||
base.send({
|
||||
type: "description",
|
||||
description: { type: "offer", sdp: pc.localDescription!.sdp },
|
||||
track_metadata: trackMetadata(),
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
scope.onEnd(() => {
|
||||
for (const { tracks } of transceivers.values()) tracks.unsubscribe();
|
||||
});
|
||||
local.publications$.pipe(scope.bind()).subscribe((publications) => {
|
||||
let changed = false;
|
||||
for (const [publication, { transceiver, tracks }] of transceivers)
|
||||
if (!publications.includes(publication)) {
|
||||
tracks.unsubscribe();
|
||||
if (pc.signalingState !== "closed") transceiver.stop();
|
||||
transceivers.delete(publication);
|
||||
changed = true;
|
||||
}
|
||||
for (const publication of publications)
|
||||
if (!transceivers.has(publication)) {
|
||||
const transceiver = pc.addTransceiver(publication.kind, {
|
||||
direction: "sendonly",
|
||||
streams: [publication.stream],
|
||||
});
|
||||
const tracks = sendPublication(transceiver, publication);
|
||||
transceivers.set(publication, { transceiver, tracks });
|
||||
changed = true;
|
||||
}
|
||||
if (changed) negotiate();
|
||||
});
|
||||
// Even without tracks: the subscriber learns that we are there
|
||||
if (transceivers.size === 0) negotiate();
|
||||
|
||||
/**
|
||||
* Sends the track of a publication as the subscriber wants it. None while
|
||||
* we don't publish or it isn't in use: the local preview stays live, and
|
||||
* turning it back on needs no renegotiation.
|
||||
*/
|
||||
function sendPublication(
|
||||
transceiver: RTCRtpTransceiver,
|
||||
publication: LocalPublication,
|
||||
): Subscription {
|
||||
const { sender } = transceiver;
|
||||
return combineLatest([
|
||||
publication.track$,
|
||||
local.publishing$,
|
||||
consumptionOf(transceiver),
|
||||
]).subscribe(([track, publishing, consumption]) => {
|
||||
const inUse = consumption.in_use ?? true;
|
||||
void sender
|
||||
.replaceTrack(publishing && inUse ? track : null)
|
||||
.then(async () => {
|
||||
if (publication.kind === "video" && track !== null)
|
||||
await constrainVideo(sender, track, consumption);
|
||||
})
|
||||
.catch((e: unknown) => logger.warn("Could not send a track", e));
|
||||
});
|
||||
}
|
||||
|
||||
// The mid is only set with the local description
|
||||
function consumptionOf(
|
||||
transceiver: RTCRtpTransceiver,
|
||||
): Observable<ConsumptionMetadataEntry> {
|
||||
return consumption$.pipe(
|
||||
map((c) => (transceiver.mid === null ? {} : (c[transceiver.mid] ?? {}))),
|
||||
distinctUntilChanged(
|
||||
(a, b) =>
|
||||
a.in_use === b.in_use &&
|
||||
a.max_width === b.max_width &&
|
||||
a.max_height === b.max_height,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Mute changes without renegotiating; an offer carries the state at its time
|
||||
local.publications$
|
||||
.pipe(
|
||||
switchMap((ps) =>
|
||||
merge(...ps.map((p) => p.mediaTrack.muted$.pipe(skip(1)))),
|
||||
),
|
||||
scope.bind(),
|
||||
)
|
||||
.subscribe(() =>
|
||||
base.send({ type: "track_metadata", track_metadata: trackMetadata() }),
|
||||
);
|
||||
|
||||
base.state$
|
||||
.pipe(
|
||||
filter((s) => s instanceof Error),
|
||||
scope.bind(),
|
||||
)
|
||||
.subscribe((e) => {
|
||||
// The subscriber retries; a publisher doesn't
|
||||
logger.info(`Connection failed: ${e.message}`);
|
||||
base.close("failed", true);
|
||||
scope.end();
|
||||
});
|
||||
|
||||
function handle(message: ConnectionMessage): void {
|
||||
switch (message.type) {
|
||||
case "description":
|
||||
if (message.description.type !== "answer") return;
|
||||
enqueue(async () => {
|
||||
await pc.setRemoteDescription(message.description);
|
||||
base.answerReceived();
|
||||
offerPending = false;
|
||||
if (renegotiate) negotiate();
|
||||
});
|
||||
break;
|
||||
case "candidates":
|
||||
base.addCandidates(message.candidates);
|
||||
break;
|
||||
case "consumption_metadata":
|
||||
consumption$.next(message.consumption_metadata);
|
||||
break;
|
||||
case "close":
|
||||
logger.info(`Closed by the subscriber: ${message.reason}`);
|
||||
base.close(message.reason, false);
|
||||
scope.end();
|
||||
break;
|
||||
default:
|
||||
logger.debug(`Ignoring ${message.type}`);
|
||||
}
|
||||
}
|
||||
|
||||
const sendData = (message: string): boolean => {
|
||||
if (data.readyState !== "open") return false;
|
||||
data.send(message);
|
||||
return true;
|
||||
};
|
||||
|
||||
return { ...base, handle, sendData };
|
||||
}
|
||||
|
||||
function purposeOf({ source }: LocalPublication): MediaPurpose {
|
||||
return source === "microphone" || source === "camera"
|
||||
? "m.usermedia"
|
||||
: "m.screenshare";
|
||||
}
|
||||
|
||||
/** Scales the video down to the size the subscriber shows it at. */
|
||||
async function constrainVideo(
|
||||
sender: RTCRtpSender,
|
||||
track: MediaStreamTrack,
|
||||
{ max_width, max_height }: ConsumptionMetadataEntry,
|
||||
): Promise<void> {
|
||||
const parameters = sender.getParameters();
|
||||
const [encoding] = parameters.encodings ?? [];
|
||||
if (encoding === undefined) return;
|
||||
const { width, height } = track.getSettings();
|
||||
encoding.scaleResolutionDownBy = Math.max(
|
||||
1,
|
||||
width && max_width ? width / max_width : 1,
|
||||
height && max_height ? height / max_height : 1,
|
||||
);
|
||||
await sender.setParameters(parameters);
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
# Full mesh media backend
|
||||
|
||||
The MatrixRTC full mesh transport, as specified in
|
||||
[MSC4575: Full mesh transport for MatrixRTC](https://github.com/matrix-org/matrix-spec-proposals/pull/4575).
|
||||
|
||||
Every subscriber opens a WebRTC connection to every publisher it receives from. To-device messages set
|
||||
the connection up; after that, the connection's control channel carries all signalling.
|
||||
|
||||
The MSC is not merged, so all identifiers use its unstable prefix `org.matrix.msc4575`.
|
||||
|
||||
Not yet as the MSC has it: the membership's `transports.can_subscribe` is built by the js-sdk
|
||||
(`MembershipManager.makeMyMembership`), which lists the LiveKit types only, so full mesh isn't
|
||||
advertised there although every participation receives it.
|
||||
|
||||
| File | What it implements |
|
||||
| ------------------------- | --------------------------------------------------------------------------------------- |
|
||||
| `FullMeshBackend.ts` | The `MediaBackend`: subscribing to members, accepting subscribers |
|
||||
| `signalling.ts` | The to-device messages and their ordering by `seq` |
|
||||
| `ControlChannel.ts` | The control channel and its messages |
|
||||
| `PeerConnection.ts` | What both sides of a connection share, including the channel switch |
|
||||
| `PublisherConnection.ts` | Sending our tracks and the data channel to one subscriber |
|
||||
| `SubscriberConnection.ts` | Receiving one publisher's tracks, with retries |
|
||||
| `metadata.ts` | Track and consumption metadata, and their validation |
|
||||
| `LocalMedia.ts` | The local tracks every publisher connection sends: captured, or taken over from a lobby |
|
||||
| `MediaTrack.ts` | A WebRTC track as the SDK's `MediaTrack` |
|
||||
@@ -1,307 +0,0 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { logger } from "matrix-js-sdk/lib/logger";
|
||||
|
||||
import { constant } from "../../reactive/Behavior";
|
||||
import { ObservableScope } from "../../reactive/ObservableScope";
|
||||
import {
|
||||
DATA_CHANNEL_LABEL,
|
||||
DATA_PROTOCOL,
|
||||
type TrackMetadata,
|
||||
} from "./metadata";
|
||||
import {
|
||||
createSubscriberConnection,
|
||||
type SubscriberConnection,
|
||||
} from "./SubscriberConnection";
|
||||
import {
|
||||
type FakeSignalling,
|
||||
fakeSignalling,
|
||||
fromPeer,
|
||||
type PeerMessage,
|
||||
installWebRtcFakes,
|
||||
lastPeerConnection,
|
||||
peer,
|
||||
settle,
|
||||
} from "./test";
|
||||
|
||||
describe("createSubscriberConnection", () => {
|
||||
let scope: ObservableScope;
|
||||
let signalling: FakeSignalling;
|
||||
let subscriber: SubscriberConnection;
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.useFakeTimers();
|
||||
installWebRtcFakes();
|
||||
scope = new ObservableScope();
|
||||
signalling = fakeSignalling();
|
||||
subscriber = createSubscriberConnection({
|
||||
scope,
|
||||
peer,
|
||||
signalling,
|
||||
iceServers: async () => Promise.resolve([{ urls: ["turn:x"] }]),
|
||||
audioOutputDeviceId$: constant(undefined),
|
||||
logger,
|
||||
});
|
||||
await settle();
|
||||
});
|
||||
afterEach(() => {
|
||||
scope.end();
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("asks the publisher for its media on a fresh connection", () => {
|
||||
expect(signalling.sent()).toEqual([{ type: "subscribe" }]);
|
||||
expect(signalling.sentConnectionIds()).toEqual([current()]);
|
||||
expect(lastPeerConnection().config.iceServers).toEqual([
|
||||
{ urls: ["turn:x"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("answers an offer and shows the tracks it brings", async () => {
|
||||
expect(subscriber.tracks$.value).toBeNull();
|
||||
const pc = lastPeerConnection();
|
||||
pc.receive("video", "1");
|
||||
pc.receive("video", "2");
|
||||
|
||||
subscriber.handle(
|
||||
offer(current(), {
|
||||
"1": { purpose: "m.usermedia", muted: true },
|
||||
"2": { purpose: "m.screenshare" },
|
||||
}),
|
||||
);
|
||||
await settle();
|
||||
|
||||
expect(pc.remoteDescription).toEqual({ type: "offer", sdp: "offer" });
|
||||
// How it shows them goes over the control channel once it is open
|
||||
expect(signalling.sent("description")).toEqual([
|
||||
{ type: "description", description: { type: "answer", sdp: "answer" } },
|
||||
]);
|
||||
const tracks = subscriber.tracks$.value!;
|
||||
expect(tracks.map((t) => [t.source, t.kind, t.muted$.value])).toEqual([
|
||||
["camera", "video", true],
|
||||
["screenShare", "video", false],
|
||||
]);
|
||||
});
|
||||
|
||||
it("names audio by its purpose", async () => {
|
||||
const pc = lastPeerConnection();
|
||||
pc.receive("audio", "0");
|
||||
pc.receive("audio", "3");
|
||||
subscriber.handle(
|
||||
offer(current(), {
|
||||
"0": { purpose: "m.usermedia" },
|
||||
"3": { purpose: "m.screenshare" },
|
||||
}),
|
||||
);
|
||||
await settle();
|
||||
expect(subscriber.tracks$.value!.map((t) => t.source)).toEqual([
|
||||
"microphone",
|
||||
"screenShareAudio",
|
||||
]);
|
||||
});
|
||||
|
||||
it("leaves out tracks without metadata or with an unknown purpose", async () => {
|
||||
const pc = lastPeerConnection();
|
||||
pc.receive("video", "0");
|
||||
pc.receive("video", "1");
|
||||
subscriber.handle(offer(current(), { "1": { purpose: "m.whiteboard" } }));
|
||||
await settle();
|
||||
expect(subscriber.tracks$.value).toEqual([]);
|
||||
});
|
||||
|
||||
it("follows mute changes, keeping the same track", async () => {
|
||||
lastPeerConnection().receive("video", "1");
|
||||
subscriber.handle(offer(current(), { "1": { purpose: "m.usermedia" } }));
|
||||
await settle();
|
||||
const [track] = subscriber.tracks$.value!;
|
||||
expect(track.muted$.value).toBe(false);
|
||||
|
||||
lastPeerConnection()
|
||||
.control()
|
||||
.receive({
|
||||
type: "track_metadata",
|
||||
track_metadata: { "1": { purpose: "m.usermedia", muted: true } },
|
||||
});
|
||||
await settle();
|
||||
expect(subscriber.tracks$.value).toEqual([track]);
|
||||
expect(track.muted$.value).toBe(true);
|
||||
});
|
||||
|
||||
it("drops a track whose transceiver no longer receives", async () => {
|
||||
const pc = lastPeerConnection();
|
||||
const transceiver = pc.receive("video", "1");
|
||||
subscriber.handle(offer(current(), { "1": { purpose: "m.usermedia" } }));
|
||||
await settle();
|
||||
expect(subscriber.tracks$.value).toHaveLength(1);
|
||||
|
||||
transceiver.currentDirection = "inactive";
|
||||
subscriber.handle(offer(current(), { "1": { purpose: "m.usermedia" } }));
|
||||
await settle();
|
||||
expect(subscriber.tracks$.value).toEqual([]);
|
||||
});
|
||||
|
||||
it("ignores messages of another connection", async () => {
|
||||
subscriber.handle(offer("other", {}));
|
||||
await settle();
|
||||
expect(lastPeerConnection().remoteDescription).toBeNull();
|
||||
});
|
||||
|
||||
it("subscribes anew after the publisher closes, backing off", async () => {
|
||||
const first = current();
|
||||
subscriber.handle(fromPeer(first, { type: "close", reason: "nope" }));
|
||||
expect(subscriber.current$.value).toBeNull();
|
||||
expect(subscriber.tracks$.value).toBeNull();
|
||||
// It doesn't echo the publisher's close
|
||||
expect(signalling.sent("close")).toEqual([]);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
const second = current();
|
||||
expect(second).not.toBe(first);
|
||||
expect(signalling.sentConnectionIds("subscribe")).toEqual([first, second]);
|
||||
|
||||
// A failed connection is closed and retried after twice the wait
|
||||
lastPeerConnection().setConnectionState("failed");
|
||||
expect(signalling.sent("close")).toEqual([
|
||||
{ type: "close", reason: "failed" },
|
||||
]);
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
expect(signalling.sent("subscribe")).toHaveLength(2);
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
expect(signalling.sent("subscribe")).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("stops retrying once its scope ends", async () => {
|
||||
subscriber.handle(fromPeer(current(), { type: "close", reason: "nope" }));
|
||||
scope.end();
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
expect(signalling.sent("subscribe")).toHaveLength(1);
|
||||
});
|
||||
|
||||
describe("the control channel", () => {
|
||||
it("is created once the offer is applied", async () => {
|
||||
const pc = lastPeerConnection();
|
||||
expect(pc.dataChannels).toEqual([]);
|
||||
subscriber.handle(offer(current(), {}));
|
||||
await settle();
|
||||
expect(pc.control().init).toEqual({ negotiated: true, id: 0 });
|
||||
});
|
||||
|
||||
it("failing leads to a new subscription", async () => {
|
||||
const first = current();
|
||||
subscriber.handle(offer(first, {}));
|
||||
await settle();
|
||||
const control = lastPeerConnection().control();
|
||||
control.open();
|
||||
control.close();
|
||||
expect(signalling.sent("close")).toEqual([
|
||||
{ type: "close", reason: "failed" },
|
||||
]);
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
expect(current()).not.toBe(first);
|
||||
});
|
||||
|
||||
it("carries the answers to later offers", async () => {
|
||||
subscriber.handle(offer(current(), {}));
|
||||
await settle();
|
||||
const control = lastPeerConnection().control();
|
||||
control.open();
|
||||
control.receive({
|
||||
type: "description",
|
||||
description: { type: "offer", sdp: "offer-2" },
|
||||
track_metadata: {},
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
expect(control.sentMessages()).toContainEqual({
|
||||
type: "description",
|
||||
description: { type: "answer", sdp: "answer" },
|
||||
});
|
||||
expect(signalling.sent("description")).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("consumption metadata", () => {
|
||||
it("tells the publisher how each video is shown, once the channel is open", async () => {
|
||||
const pc = lastPeerConnection();
|
||||
pc.receive("audio", "0");
|
||||
pc.receive("video", "1");
|
||||
subscriber.handle(
|
||||
offer(current(), {
|
||||
"0": { purpose: "m.usermedia" },
|
||||
"1": { purpose: "m.usermedia" },
|
||||
}),
|
||||
);
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
const control = pc.control();
|
||||
control.open();
|
||||
// Nothing shows the video yet; the audio is always in use
|
||||
expect(control.sentMessages()).toEqual([
|
||||
{
|
||||
type: "consumption_metadata",
|
||||
consumption_metadata: { "1": { in_use: false } },
|
||||
},
|
||||
]);
|
||||
|
||||
const video = subscriber.tracks$.value!.find((t) => t.kind === "video")!;
|
||||
const element = { paused: false } as HTMLMediaElement;
|
||||
video.attach(element);
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
// Shown at a size the platform doesn't report: no constraint at all
|
||||
expect(control.sentMessages().at(-1)).toEqual({
|
||||
type: "consumption_metadata",
|
||||
consumption_metadata: {},
|
||||
});
|
||||
|
||||
video.detach(element);
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
expect(control.sentMessages().at(-1)).toEqual({
|
||||
type: "consumption_metadata",
|
||||
consumption_metadata: { "1": { in_use: false } },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("the data channel", () => {
|
||||
it("delivers what the publisher sends on it", async () => {
|
||||
const received: string[] = [];
|
||||
subscriber.data$.subscribe((text) => received.push(text));
|
||||
subscriber.handle(offer(current(), {}));
|
||||
await settle();
|
||||
const pc = lastPeerConnection();
|
||||
pc.announceDataChannel(DATA_CHANNEL_LABEL, DATA_PROTOCOL).receive("hi");
|
||||
expect(received).toEqual(["hi"]);
|
||||
});
|
||||
|
||||
it("ignores a channel whose protocol it doesn't know, whatever its label", async () => {
|
||||
const received: string[] = [];
|
||||
subscriber.data$.subscribe((text) => received.push(text));
|
||||
subscriber.handle(offer(current(), {}));
|
||||
await settle();
|
||||
const pc = lastPeerConnection();
|
||||
pc.announceDataChannel(DATA_CHANNEL_LABEL, "x.other").receive("no");
|
||||
pc.announceDataChannel(DATA_CHANNEL_LABEL).receive("no");
|
||||
expect(received).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
function offer(connectionId: string, metadata: TrackMetadata): PeerMessage {
|
||||
return fromPeer(connectionId, {
|
||||
type: "description",
|
||||
description: { type: "offer", sdp: "offer" },
|
||||
track_metadata: metadata,
|
||||
});
|
||||
}
|
||||
|
||||
/** The connection id of the current attempt. */
|
||||
function current(): string {
|
||||
const base = subscriber.current$.value;
|
||||
if (base === null) throw new Error("No current attempt");
|
||||
return base.connectionId;
|
||||
}
|
||||
});
|
||||
@@ -1,366 +0,0 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { type Logger } from "matrix-js-sdk/lib/logger";
|
||||
import {
|
||||
BehaviorSubject,
|
||||
combineLatest,
|
||||
debounceTime,
|
||||
distinctUntilChanged,
|
||||
filter,
|
||||
map,
|
||||
type Observable,
|
||||
of,
|
||||
Subject,
|
||||
switchMap,
|
||||
} from "rxjs";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import { type MediaSource } from "../../media-api";
|
||||
import { type Behavior } from "../../reactive/Behavior";
|
||||
import { ObservableScope } from "../../reactive/ObservableScope";
|
||||
import { MediaConnectionState } from "../api";
|
||||
import {
|
||||
createFullMeshMediaTrack,
|
||||
type FullMeshMediaTrack,
|
||||
rtpStats,
|
||||
type Viewport,
|
||||
} from "./MediaTrack";
|
||||
import {
|
||||
type ConsumptionMetadata,
|
||||
DATA_PROTOCOL,
|
||||
isMediaPurpose,
|
||||
type MediaPurpose,
|
||||
type TrackMetadata,
|
||||
} from "./metadata";
|
||||
import {
|
||||
createPeerConnectionBase,
|
||||
type PeerConnectionBase,
|
||||
} from "./PeerConnection";
|
||||
import {
|
||||
type ConnectionMessage,
|
||||
type Peer,
|
||||
type Signalling,
|
||||
} from "./signalling";
|
||||
|
||||
const RETRY_MIN_MS = 1_000;
|
||||
const RETRY_MAX_MS = 30_000;
|
||||
/** How long the shown size of the tracks settles before the publisher hears of it. */
|
||||
const CONSUMPTION_DEBOUNCE_MS = 200;
|
||||
|
||||
export interface SubscriberConnection {
|
||||
/** The current attempt; null while waiting to retry. */
|
||||
current$: Behavior<PeerConnectionBase | null>;
|
||||
/** The publisher's tracks; null until its first offer is applied. */
|
||||
tracks$: Behavior<FullMeshMediaTrack[] | null>;
|
||||
/** What the publisher sent on its data channel, on any attempt. */
|
||||
data$: Observable<string>;
|
||||
/** A to-device message from the publisher; dropped unless it is for the current attempt. */
|
||||
handle(message: ConnectionMessage & { connectionId: string }): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Our subscription to one publisher: asks it for its media and answers its
|
||||
* offers. A failed or closed attempt is retried with a fresh connection id,
|
||||
* backing off, for as long as `scope` lives.
|
||||
*/
|
||||
export function createSubscriberConnection({
|
||||
scope,
|
||||
peer,
|
||||
signalling,
|
||||
iceServers,
|
||||
audioOutputDeviceId$,
|
||||
logger: parentLogger,
|
||||
}: {
|
||||
scope: ObservableScope;
|
||||
peer: Peer;
|
||||
signalling: Signalling;
|
||||
iceServers: () => Promise<RTCIceServer[]>;
|
||||
audioOutputDeviceId$: Behavior<string | undefined>;
|
||||
logger: Logger;
|
||||
}): SubscriberConnection {
|
||||
const logger = parentLogger.getChild(`[Subscriber ← ${peer.memberId}]`);
|
||||
const attempt$ = new BehaviorSubject<Attempt | null>(null);
|
||||
const data$ = new Subject<string>();
|
||||
let retryMs = RETRY_MIN_MS;
|
||||
let retryTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
let ended = false;
|
||||
scope.onEnd(() => (ended = true));
|
||||
|
||||
const startAttempt = async (): Promise<void> => {
|
||||
const servers = await iceServers();
|
||||
if (ended) return;
|
||||
const attemptScope = new ObservableScope();
|
||||
const attempt = createAttempt({
|
||||
scope: attemptScope,
|
||||
peer,
|
||||
signalling,
|
||||
iceServers: servers,
|
||||
audioOutputDeviceId$,
|
||||
onData: (text) => data$.next(text),
|
||||
onFailed: (reason) => {
|
||||
logger.info(`Attempt ${attempt.connectionId} ended: ${reason}`);
|
||||
attemptScope.end();
|
||||
if (attempt$.value === attempt) attempt$.next(null);
|
||||
if (ended) return;
|
||||
retryTimer = setTimeout(() => void startAttempt(), retryMs);
|
||||
retryMs = Math.min(retryMs * 2, RETRY_MAX_MS);
|
||||
},
|
||||
onConnected: () => (retryMs = RETRY_MIN_MS),
|
||||
logger,
|
||||
});
|
||||
attempt$.next(attempt);
|
||||
};
|
||||
void startAttempt();
|
||||
scope.onEnd(() => {
|
||||
clearTimeout(retryTimer);
|
||||
attempt$.value?.end();
|
||||
attempt$.next(null);
|
||||
data$.complete();
|
||||
});
|
||||
|
||||
return {
|
||||
current$: scope.behavior(attempt$.pipe(map((a) => a?.base ?? null))),
|
||||
tracks$: scope.behavior(
|
||||
attempt$.pipe(switchMap((a) => a?.tracks$ ?? of(null))),
|
||||
),
|
||||
data$,
|
||||
handle: (message) => {
|
||||
if (message.connectionId === attempt$.value?.connectionId)
|
||||
attempt$.value.handle(message);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
interface Attempt {
|
||||
connectionId: string;
|
||||
base: PeerConnectionBase;
|
||||
tracks$: Behavior<FullMeshMediaTrack[] | null>;
|
||||
handle(message: ConnectionMessage): void;
|
||||
end(): void;
|
||||
}
|
||||
|
||||
interface ReceivedTrack {
|
||||
track: FullMeshMediaTrack;
|
||||
mid: string;
|
||||
scope: ObservableScope;
|
||||
source: MediaSource;
|
||||
}
|
||||
|
||||
function createAttempt({
|
||||
scope,
|
||||
peer,
|
||||
signalling,
|
||||
iceServers,
|
||||
audioOutputDeviceId$,
|
||||
onData,
|
||||
onFailed,
|
||||
onConnected,
|
||||
logger,
|
||||
}: {
|
||||
scope: ObservableScope;
|
||||
peer: Peer;
|
||||
signalling: Signalling;
|
||||
iceServers: RTCIceServer[];
|
||||
audioOutputDeviceId$: Behavior<string | undefined>;
|
||||
onData: (text: string) => void;
|
||||
onFailed: (reason: string) => void;
|
||||
onConnected: () => void;
|
||||
logger: Logger;
|
||||
}): Attempt {
|
||||
const connectionId = uuidv4();
|
||||
let failed = false;
|
||||
const fail = (reason: string): void => {
|
||||
if (failed) return;
|
||||
failed = true;
|
||||
onFailed(reason);
|
||||
};
|
||||
const base = createPeerConnectionBase({
|
||||
scope,
|
||||
peer,
|
||||
connectionId,
|
||||
signalling,
|
||||
iceServers,
|
||||
onControlMessage: (message) => handle(message),
|
||||
logger,
|
||||
});
|
||||
const { pc, enqueue } = base;
|
||||
const metadata$ = new BehaviorSubject<TrackMetadata>({});
|
||||
const received$ = new BehaviorSubject<ReceivedTrack[] | null>(null);
|
||||
const wrappers = new Map<RTCRtpTransceiver, ReceivedTrack>();
|
||||
|
||||
pc.addEventListener("datachannel", ({ channel }) => {
|
||||
if (channel.protocol !== DATA_PROTOCOL) return;
|
||||
channel.addEventListener("message", ({ data }: MessageEvent) => {
|
||||
if (typeof data === "string") onData(data);
|
||||
});
|
||||
});
|
||||
|
||||
/** The tracks of the transceivers that receive, after each negotiation. */
|
||||
const updateTracks = (): void => {
|
||||
const metadata = metadata$.value;
|
||||
const live = new Set<RTCRtpTransceiver>();
|
||||
for (const transceiver of pc.getTransceivers()) {
|
||||
const { mid, receiver } = transceiver;
|
||||
const track = receiver.track;
|
||||
const entry = mid === null ? undefined : metadata[mid];
|
||||
if (
|
||||
transceiver.currentDirection !== "recvonly" ||
|
||||
mid === null ||
|
||||
entry === undefined ||
|
||||
!isMediaPurpose(entry.purpose)
|
||||
)
|
||||
continue;
|
||||
const kind = track.kind === "audio" ? "audio" : "video";
|
||||
const source = sourceOf(entry.purpose, kind);
|
||||
live.add(transceiver);
|
||||
const existing = wrappers.get(transceiver);
|
||||
if (existing?.source === source) continue;
|
||||
existing?.scope.end();
|
||||
const trackScope = new ObservableScope();
|
||||
wrappers.set(transceiver, {
|
||||
scope: trackScope,
|
||||
source,
|
||||
mid,
|
||||
track: createFullMeshMediaTrack(trackScope, {
|
||||
source,
|
||||
kind,
|
||||
id: `${connectionId}:${mid}`,
|
||||
track$: trackScope.behavior(of(track)),
|
||||
muted$: trackScope.behavior(
|
||||
metadata$.pipe(
|
||||
map((m) => m[mid]?.muted ?? false),
|
||||
distinctUntilChanged(),
|
||||
),
|
||||
),
|
||||
stats: async () => rtpStats(pc, track, "inbound-rtp"),
|
||||
audioOutputDeviceId$,
|
||||
observeViewport: true,
|
||||
}),
|
||||
});
|
||||
}
|
||||
for (const [transceiver, { scope: s }] of wrappers)
|
||||
if (!live.has(transceiver)) {
|
||||
s.end();
|
||||
wrappers.delete(transceiver);
|
||||
}
|
||||
received$.next([...wrappers.values()]);
|
||||
};
|
||||
|
||||
// How the videos are shown; the first goes out once the control channel
|
||||
// is open, as everything is sent at full size until then anyway
|
||||
received$
|
||||
.pipe(
|
||||
switchMap((received) => {
|
||||
const video = (received ?? []).filter((r) => r.track.kind === "video");
|
||||
return video.length === 0
|
||||
? of({})
|
||||
: combineLatest(video.map((r) => r.track.viewport$)).pipe(
|
||||
map((viewports) => consumptionOf(video, viewports)),
|
||||
);
|
||||
}),
|
||||
distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b)),
|
||||
debounceTime(CONSUMPTION_DEBOUNCE_MS),
|
||||
scope.bind(),
|
||||
)
|
||||
.subscribe((metadata) =>
|
||||
base.send({
|
||||
type: "consumption_metadata",
|
||||
consumption_metadata: metadata,
|
||||
}),
|
||||
);
|
||||
|
||||
base.state$
|
||||
.pipe(
|
||||
filter((s) => s instanceof Error || s === MediaConnectionState.Connected),
|
||||
scope.bind(),
|
||||
)
|
||||
.subscribe((s) => {
|
||||
if (s instanceof Error) {
|
||||
base.close("failed", true);
|
||||
fail(s.message);
|
||||
} else onConnected();
|
||||
});
|
||||
|
||||
function handle(message: ConnectionMessage): void {
|
||||
switch (message.type) {
|
||||
case "description":
|
||||
if (message.description.type !== "offer") return;
|
||||
enqueue(async () => {
|
||||
if (message.track_metadata) metadata$.next(message.track_metadata);
|
||||
await pc.setRemoteDescription(message.description);
|
||||
base.openControlChannel();
|
||||
await pc.setLocalDescription(await pc.createAnswer());
|
||||
updateTracks();
|
||||
base.send({
|
||||
type: "description",
|
||||
description: { type: "answer", sdp: pc.localDescription!.sdp },
|
||||
});
|
||||
});
|
||||
break;
|
||||
case "candidates":
|
||||
base.addCandidates(message.candidates);
|
||||
break;
|
||||
case "track_metadata":
|
||||
metadata$.next(message.track_metadata);
|
||||
// A track may only become known with its metadata
|
||||
enqueue(async () => Promise.resolve(updateTracks()));
|
||||
break;
|
||||
case "close":
|
||||
base.close(message.reason, false);
|
||||
fail(`closed by the publisher: ${message.reason}`);
|
||||
break;
|
||||
default:
|
||||
logger.debug(`Ignoring ${message.type}`);
|
||||
}
|
||||
}
|
||||
|
||||
scope.onEnd(() => {
|
||||
for (const { scope: s } of wrappers.values()) s.end();
|
||||
wrappers.clear();
|
||||
});
|
||||
|
||||
signalling.send(peer, connectionId, { type: "subscribe" });
|
||||
|
||||
return {
|
||||
connectionId,
|
||||
base,
|
||||
tracks$: scope.behavior(
|
||||
received$.pipe(map((r) => r?.map(({ track }) => track) ?? null)),
|
||||
),
|
||||
handle,
|
||||
end: () => scope.end(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The consumption metadata for the received videos, given their viewports
|
||||
* in order: a video no element shows isn't in use, and one shown at a known
|
||||
* size needs no more than that.
|
||||
*/
|
||||
function consumptionOf(
|
||||
video: ReceivedTrack[],
|
||||
viewports: (Viewport | null)[],
|
||||
): ConsumptionMetadata {
|
||||
const metadata: ConsumptionMetadata = {};
|
||||
video.forEach(({ mid }, i) => {
|
||||
const viewport = viewports[i];
|
||||
if (viewport === null) metadata[mid] = { in_use: false };
|
||||
else if (viewport.width !== undefined && viewport.height !== undefined)
|
||||
metadata[mid] = {
|
||||
max_width: viewport.width,
|
||||
max_height: viewport.height,
|
||||
};
|
||||
});
|
||||
return metadata;
|
||||
}
|
||||
|
||||
function sourceOf(purpose: MediaPurpose, kind: "audio" | "video"): MediaSource {
|
||||
if (purpose === "m.usermedia")
|
||||
return kind === "audio" ? "microphone" : "camera";
|
||||
return kind === "audio" ? "screenShareAudio" : "screenShare";
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseConsumptionMetadata, parseTrackMetadata } from "./metadata";
|
||||
|
||||
describe("parseTrackMetadata", () => {
|
||||
it("keeps the well-formed entries", () => {
|
||||
expect(
|
||||
parseTrackMetadata({
|
||||
"0": { purpose: "m.usermedia", muted: true, extra: 1 },
|
||||
"1": { purpose: "m.screenshare", muted: "yes" },
|
||||
"2": { muted: true },
|
||||
"3": [],
|
||||
}),
|
||||
).toEqual({
|
||||
"0": { purpose: "m.usermedia", muted: true },
|
||||
"1": { purpose: "m.screenshare" },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects what isn't metadata at all", () => {
|
||||
expect(parseTrackMetadata("x")).toBeNull();
|
||||
expect(parseTrackMetadata([])).toBeNull();
|
||||
});
|
||||
|
||||
it("reads no more entries than any member publishes", () => {
|
||||
const many = Object.fromEntries(
|
||||
Array.from({ length: 100 }, (_, i) => [i, { purpose: "m.usermedia" }]),
|
||||
);
|
||||
expect(Object.keys(parseTrackMetadata(many)!)).toHaveLength(64);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseConsumptionMetadata", () => {
|
||||
it("bounds the sizes to what makes sense", () => {
|
||||
expect(
|
||||
parseConsumptionMetadata({
|
||||
"0": { in_use: false, max_width: 1e9, max_height: -1 },
|
||||
"1": { max_width: 320.4, max_height: Number.NaN },
|
||||
}),
|
||||
).toEqual({
|
||||
"0": { in_use: false, max_width: 16_384 },
|
||||
"1": { max_width: 320 },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,95 +0,0 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
/**
|
||||
* The track and consumption metadata of the full mesh transport (MSC4575),
|
||||
* and their validation: both come from the other member and are untrusted.
|
||||
* Both are keyed by the `mid` of a track's transceiver.
|
||||
*/
|
||||
|
||||
/**
|
||||
* The data channel every publisher connection has for `sendData`, and its
|
||||
* protocol: one JSON object `{ topic, text }` per message.
|
||||
*/
|
||||
export const DATA_CHANNEL_LABEL = "io.element.matrixrtc.data";
|
||||
export const DATA_PROTOCOL = "io.element.matrixrtc.topic_text";
|
||||
|
||||
export type MediaPurpose = "m.usermedia" | "m.screenshare";
|
||||
|
||||
export interface TrackMetadataEntry {
|
||||
purpose: string;
|
||||
muted?: boolean;
|
||||
}
|
||||
export type TrackMetadata = Record<string, TrackMetadataEntry>;
|
||||
|
||||
export interface ConsumptionMetadataEntry {
|
||||
in_use?: boolean;
|
||||
max_width?: number;
|
||||
max_height?: number;
|
||||
}
|
||||
export type ConsumptionMetadata = Record<string, ConsumptionMetadataEntry>;
|
||||
|
||||
/** Larger than any video we capture; a bound on what a subscriber can ask for. */
|
||||
const MAX_DIMENSION = 16_384;
|
||||
/** More tracks than any member publishes; a bound on the work a message causes. */
|
||||
const MAX_TRACKS = 64;
|
||||
|
||||
export function isMediaPurpose(purpose: string): purpose is MediaPurpose {
|
||||
return purpose === "m.usermedia" || purpose === "m.screenshare";
|
||||
}
|
||||
|
||||
/** The entries of `value` that are well formed, or null if it isn't metadata at all. */
|
||||
export function parseTrackMetadata(value: unknown): TrackMetadata | null {
|
||||
const entries = recordEntries(value);
|
||||
if (entries === null) return null;
|
||||
const metadata: TrackMetadata = {};
|
||||
for (const [mid, e] of entries) {
|
||||
if (typeof e.purpose !== "string") continue;
|
||||
const entry: TrackMetadataEntry = { purpose: e.purpose };
|
||||
if (typeof e.muted === "boolean") entry.muted = e.muted;
|
||||
metadata[mid] = entry;
|
||||
}
|
||||
return metadata;
|
||||
}
|
||||
|
||||
/** As `parseTrackMetadata`, with the sizes bounded to what makes sense. */
|
||||
export function parseConsumptionMetadata(
|
||||
value: unknown,
|
||||
): ConsumptionMetadata | null {
|
||||
const entries = recordEntries(value);
|
||||
if (entries === null) return null;
|
||||
const metadata: ConsumptionMetadata = {};
|
||||
for (const [mid, e] of entries) {
|
||||
const entry: ConsumptionMetadataEntry = {};
|
||||
if (typeof e.in_use === "boolean") entry.in_use = e.in_use;
|
||||
const width = bounded(e.max_width);
|
||||
if (width !== undefined) entry.max_width = width;
|
||||
const height = bounded(e.max_height);
|
||||
if (height !== undefined) entry.max_height = height;
|
||||
metadata[mid] = entry;
|
||||
}
|
||||
return metadata;
|
||||
}
|
||||
|
||||
function recordEntries(
|
||||
value: unknown,
|
||||
): [string, Record<string, unknown>][] | null {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value))
|
||||
return null;
|
||||
return Object.entries(value)
|
||||
.filter(
|
||||
(e): e is [string, Record<string, unknown>] =>
|
||||
typeof e[1] === "object" && e[1] !== null && !Array.isArray(e[1]),
|
||||
)
|
||||
.slice(0, MAX_TRACKS);
|
||||
}
|
||||
|
||||
function bounded(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isFinite(value) && value > 0
|
||||
? Math.round(Math.min(value, MAX_DIMENSION))
|
||||
: undefined;
|
||||
}
|
||||
@@ -1,199 +0,0 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { EventEmitter } from "events";
|
||||
import { ClientEvent, EventType, MatrixEvent } from "matrix-js-sdk";
|
||||
import { logger } from "matrix-js-sdk/lib/logger";
|
||||
|
||||
import { ObservableScope } from "../../reactive/ObservableScope";
|
||||
import {
|
||||
createSignalling,
|
||||
SEQ_GAP_TIMEOUT_MS,
|
||||
SeqOrderer,
|
||||
SignallingEventType,
|
||||
type SignallingClient,
|
||||
type SignallingMessage,
|
||||
} from "./signalling";
|
||||
|
||||
describe("SeqOrderer", () => {
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it("delivers in seq order", () => {
|
||||
const delivered: string[] = [];
|
||||
const orderer = new SeqOrderer<string>((s) => delivered.push(s));
|
||||
orderer.push(1, "b");
|
||||
orderer.push(2, "c");
|
||||
expect(delivered).toEqual([]);
|
||||
orderer.push(0, "a");
|
||||
expect(delivered).toEqual(["a", "b", "c"]);
|
||||
});
|
||||
|
||||
it("skips a gap that isn't filled in time, then drops the late message", () => {
|
||||
const delivered: string[] = [];
|
||||
const orderer = new SeqOrderer<string>((s) => delivered.push(s));
|
||||
orderer.push(0, "a");
|
||||
orderer.push(2, "c");
|
||||
vi.advanceTimersByTime(SEQ_GAP_TIMEOUT_MS);
|
||||
expect(delivered).toEqual(["a", "c"]);
|
||||
orderer.push(1, "b");
|
||||
expect(delivered).toEqual(["a", "c"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createSignalling", () => {
|
||||
const own = { userId: "@me:x", deviceId: "MINE", memberId: "me" };
|
||||
|
||||
function setup(): {
|
||||
client: SignallingClient & EventEmitter;
|
||||
received: SignallingMessage[];
|
||||
scope: ObservableScope;
|
||||
} {
|
||||
const client = Object.assign(new EventEmitter(), {
|
||||
encryptAndSendToDevice: vi.fn(async () => Promise.resolve()),
|
||||
}) as unknown as SignallingClient & EventEmitter;
|
||||
const scope = new ObservableScope();
|
||||
const signalling = createSignalling({
|
||||
scope,
|
||||
client,
|
||||
roomId: "!room:x",
|
||||
slotId: "m.call#ROOM",
|
||||
own,
|
||||
logger,
|
||||
});
|
||||
const received: SignallingMessage[] = [];
|
||||
signalling.messages$.subscribe((m) => received.push(m));
|
||||
return { client, received, scope };
|
||||
}
|
||||
|
||||
function toDevice(
|
||||
type: string,
|
||||
content: Record<string, unknown>,
|
||||
encrypted = true,
|
||||
): MatrixEvent {
|
||||
const event = new MatrixEvent({ type, sender: "@peer:x", content });
|
||||
if (encrypted)
|
||||
vi.spyOn(event, "getWireType").mockReturnValue(
|
||||
EventType.RoomMessageEncrypted,
|
||||
);
|
||||
return event;
|
||||
}
|
||||
|
||||
const common = {
|
||||
room_id: "!room:x",
|
||||
slot_id: "m.call#ROOM",
|
||||
member_id: "peer",
|
||||
target_member_id: "me",
|
||||
connection_id: "c1",
|
||||
claimed_device_id: "PEER",
|
||||
};
|
||||
|
||||
it("passes valid messages on and drops cleartext or misaddressed ones", () => {
|
||||
const { client, received, scope } = setup();
|
||||
client.emit(
|
||||
ClientEvent.ToDeviceEvent,
|
||||
toDevice(SignallingEventType.subscribe, { ...common, seq: 0 }, false),
|
||||
);
|
||||
client.emit(
|
||||
ClientEvent.ToDeviceEvent,
|
||||
toDevice(SignallingEventType.subscribe, {
|
||||
...common,
|
||||
target_member_id: "someone else",
|
||||
seq: 0,
|
||||
}),
|
||||
);
|
||||
expect(received).toEqual([]);
|
||||
client.emit(
|
||||
ClientEvent.ToDeviceEvent,
|
||||
toDevice(SignallingEventType.subscribe, { ...common, seq: 0 }),
|
||||
);
|
||||
expect(received).toEqual([
|
||||
{
|
||||
type: "subscribe",
|
||||
memberId: "peer",
|
||||
userId: "@peer:x",
|
||||
deviceId: "PEER",
|
||||
connectionId: "c1",
|
||||
},
|
||||
]);
|
||||
scope.end();
|
||||
});
|
||||
|
||||
it("orders by seq across connection ids", () => {
|
||||
const { client, received, scope } = setup();
|
||||
client.emit(
|
||||
ClientEvent.ToDeviceEvent,
|
||||
toDevice(SignallingEventType.subscribe, {
|
||||
...common,
|
||||
connection_id: "c2",
|
||||
seq: 2,
|
||||
}),
|
||||
);
|
||||
client.emit(
|
||||
ClientEvent.ToDeviceEvent,
|
||||
toDevice(SignallingEventType.close, { ...common, seq: 1 }),
|
||||
);
|
||||
client.emit(
|
||||
ClientEvent.ToDeviceEvent,
|
||||
toDevice(SignallingEventType.subscribe, { ...common, seq: 0 }),
|
||||
);
|
||||
expect(received.map((m) => [m.type, m.connectionId])).toEqual([
|
||||
["subscribe", "c1"],
|
||||
["close", "c1"],
|
||||
["subscribe", "c2"],
|
||||
]);
|
||||
scope.end();
|
||||
});
|
||||
|
||||
it("keeps the well-formed metadata of a description", () => {
|
||||
const { client, received, scope } = setup();
|
||||
client.emit(
|
||||
ClientEvent.ToDeviceEvent,
|
||||
toDevice(SignallingEventType.description, {
|
||||
...common,
|
||||
seq: 0,
|
||||
description: { type: "offer", sdp: "offer" },
|
||||
track_metadata: {
|
||||
"0": { purpose: "m.usermedia", muted: "yes" },
|
||||
"1": { muted: true },
|
||||
"2": "not an object",
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(received).toEqual([
|
||||
expect.objectContaining({
|
||||
type: "description",
|
||||
track_metadata: { "0": { purpose: "m.usermedia" } },
|
||||
}),
|
||||
]);
|
||||
scope.end();
|
||||
});
|
||||
|
||||
it("sends each payload as its event type", () => {
|
||||
const { client, scope } = setup();
|
||||
const signalling = createSignalling({
|
||||
scope,
|
||||
client,
|
||||
roomId: "!room:x",
|
||||
slotId: "m.call#ROOM",
|
||||
own,
|
||||
logger,
|
||||
});
|
||||
signalling.send(
|
||||
{ userId: "@peer:x", deviceId: "PEER", memberId: "peer" },
|
||||
"c1",
|
||||
{ type: "close", reason: "bye" },
|
||||
);
|
||||
expect(client.encryptAndSendToDevice).toHaveBeenCalledWith(
|
||||
SignallingEventType.close,
|
||||
[{ userId: "@peer:x", deviceId: "PEER" }],
|
||||
expect.objectContaining({ reason: "bye", connection_id: "c1", seq: 0 }),
|
||||
);
|
||||
scope.end();
|
||||
});
|
||||
});
|
||||
@@ -1,291 +0,0 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
/**
|
||||
* The to-device signalling of the full mesh transport (MSC4575): four event
|
||||
* types, the fields every one carries, and the ordering by `seq`. It sets a
|
||||
* connection up; the control channel carries the rest.
|
||||
*/
|
||||
|
||||
import { type Logger } from "matrix-js-sdk/lib/logger";
|
||||
import {
|
||||
ClientEvent,
|
||||
EventType,
|
||||
type MatrixClient,
|
||||
type MatrixEvent,
|
||||
} from "matrix-js-sdk";
|
||||
import { type CallMembershipIdentityParts } from "matrix-js-sdk/lib/matrixrtc/EncryptionManager";
|
||||
import { fromEvent, Observable, share } from "rxjs";
|
||||
|
||||
import { type ObservableScope } from "../../reactive/ObservableScope";
|
||||
import { type ControlMessage } from "./ControlChannel";
|
||||
import { parseTrackMetadata } from "./metadata";
|
||||
|
||||
export const FULL_MESH_TRANSPORT_TYPE = "org.matrix.msc4575.full_mesh";
|
||||
|
||||
const prefix = "org.matrix.msc4575.rtc.full_mesh";
|
||||
/** The event type of each payload type. */
|
||||
export const SignallingEventType = {
|
||||
subscribe: `${prefix}.subscribe`,
|
||||
description: `${prefix}.description`,
|
||||
candidates: `${prefix}.candidates`,
|
||||
close: `${prefix}.close`,
|
||||
} as const;
|
||||
|
||||
export const signallingEventTypes: string[] =
|
||||
Object.values(SignallingEventType);
|
||||
|
||||
/** How long a gap in `seq` is waited for before the missing messages are skipped. */
|
||||
export const SEQ_GAP_TIMEOUT_MS = 10_000;
|
||||
|
||||
interface CommonContent {
|
||||
room_id: string;
|
||||
slot_id: string;
|
||||
member_id: string;
|
||||
target_member_id: string;
|
||||
connection_id: string;
|
||||
seq: number;
|
||||
/**
|
||||
* The sender's device, which replies go to. Stated by the sender, as the
|
||||
* MSC has it, because the js-sdk and the widget API don't expose the Olm
|
||||
* sending device; a client that knows it checks the two agree.
|
||||
*/
|
||||
claimed_device_id: string;
|
||||
}
|
||||
|
||||
/** What a connection hears from its peer, over to-device messages or the control channel. */
|
||||
export type ConnectionMessage =
|
||||
| ControlMessage
|
||||
| { type: "close"; reason?: string };
|
||||
|
||||
export type SignallingPayload =
|
||||
| { type: "subscribe" }
|
||||
| Extract<
|
||||
ConnectionMessage,
|
||||
{ type: "description" | "candidates" | "close" }
|
||||
>;
|
||||
|
||||
export type SignallingMessage = SignallingPayload & {
|
||||
/** The member that sent it, as named in `member_id`. */
|
||||
memberId: string;
|
||||
userId: string;
|
||||
deviceId: string;
|
||||
connectionId: string;
|
||||
};
|
||||
|
||||
/** Another member, as far as signalling needs to know it. */
|
||||
export interface Peer {
|
||||
userId: string;
|
||||
deviceId: string;
|
||||
memberId: string;
|
||||
}
|
||||
|
||||
export interface Signalling {
|
||||
send(peer: Peer, connectionId: string, payload: SignallingPayload): void;
|
||||
/** Every valid message for us, per sender in `seq` order. */
|
||||
messages$: Observable<SignallingMessage>;
|
||||
}
|
||||
|
||||
export type SignallingClient = Pick<
|
||||
MatrixClient,
|
||||
"encryptAndSendToDevice" | "on" | "off"
|
||||
>;
|
||||
|
||||
interface Props {
|
||||
scope: ObservableScope;
|
||||
client: SignallingClient;
|
||||
roomId: string;
|
||||
slotId: string;
|
||||
own: CallMembershipIdentityParts;
|
||||
logger: Logger;
|
||||
}
|
||||
|
||||
export function createSignalling({
|
||||
scope,
|
||||
client,
|
||||
roomId,
|
||||
slotId,
|
||||
own,
|
||||
logger: parentLogger,
|
||||
}: Props): Signalling {
|
||||
const logger = parentLogger.getChild("[Signalling]");
|
||||
const nextSeqTo = new Map<string, number>();
|
||||
|
||||
const send = (
|
||||
peer: Peer,
|
||||
connectionId: string,
|
||||
{ type, ...payload }: SignallingPayload,
|
||||
): void => {
|
||||
const eventType = SignallingEventType[type];
|
||||
const seq = nextSeqTo.get(peer.memberId) ?? 0;
|
||||
nextSeqTo.set(peer.memberId, seq + 1);
|
||||
const content: CommonContent & Record<string, unknown> = {
|
||||
...payload,
|
||||
room_id: roomId,
|
||||
slot_id: slotId,
|
||||
member_id: own.memberId,
|
||||
target_member_id: peer.memberId,
|
||||
connection_id: connectionId,
|
||||
seq,
|
||||
claimed_device_id: own.deviceId,
|
||||
};
|
||||
client
|
||||
.encryptAndSendToDevice(
|
||||
eventType,
|
||||
[{ userId: peer.userId, deviceId: peer.deviceId }],
|
||||
content,
|
||||
)
|
||||
.catch((e: unknown) => logger.warn(`Failed to send ${eventType}`, e));
|
||||
};
|
||||
|
||||
const messages$ = new Observable<SignallingMessage>((subscriber) => {
|
||||
const orderers = new Map<string, SeqOrderer<SignallingMessage>>();
|
||||
const sub = fromEvent<MatrixEvent>(client, ClientEvent.ToDeviceEvent)
|
||||
.pipe(scope.bind())
|
||||
.subscribe((event) => {
|
||||
const parsed = parse(event, roomId, slotId, own.memberId, logger);
|
||||
if (parsed === null) return;
|
||||
let orderer = orderers.get(parsed.message.memberId);
|
||||
if (orderer === undefined) {
|
||||
orderer = new SeqOrderer((m) => subscriber.next(m), logger);
|
||||
orderers.set(parsed.message.memberId, orderer);
|
||||
}
|
||||
orderer.push(parsed.seq, parsed.message);
|
||||
});
|
||||
return () => {
|
||||
sub.unsubscribe();
|
||||
for (const orderer of orderers.values()) orderer.dispose();
|
||||
};
|
||||
}).pipe(share());
|
||||
|
||||
return { send, messages$ };
|
||||
}
|
||||
|
||||
function parse(
|
||||
event: MatrixEvent,
|
||||
roomId: string,
|
||||
slotId: string,
|
||||
ownMemberId: string,
|
||||
logger: Logger,
|
||||
): { seq: number; message: SignallingMessage } | null {
|
||||
const type = event.getType();
|
||||
if (!signallingEventTypes.includes(type)) return null;
|
||||
// Via the widget API, to-device events are reconstructed as encrypted
|
||||
if (event.getWireType() !== EventType.RoomMessageEncrypted) {
|
||||
logger.warn(`Dropping ${type} sent in clear from ${event.getSender()}`);
|
||||
return null;
|
||||
}
|
||||
const c = event.getContent<
|
||||
Partial<CommonContent> & Record<string, unknown>
|
||||
>();
|
||||
const userId = event.getSender();
|
||||
if (
|
||||
userId === undefined ||
|
||||
c.room_id !== roomId ||
|
||||
c.slot_id !== slotId ||
|
||||
c.target_member_id !== ownMemberId ||
|
||||
typeof c.member_id !== "string" ||
|
||||
typeof c.connection_id !== "string" ||
|
||||
typeof c.claimed_device_id !== "string" ||
|
||||
typeof c.seq !== "number"
|
||||
)
|
||||
return null;
|
||||
const common = {
|
||||
memberId: c.member_id,
|
||||
userId,
|
||||
deviceId: c.claimed_device_id,
|
||||
connectionId: c.connection_id,
|
||||
};
|
||||
let payload: SignallingPayload;
|
||||
switch (type) {
|
||||
case SignallingEventType.subscribe:
|
||||
payload = { type: "subscribe" };
|
||||
break;
|
||||
case SignallingEventType.description: {
|
||||
const d = c.description as { type?: unknown; sdp?: unknown } | undefined;
|
||||
if (
|
||||
(d?.type !== "offer" && d?.type !== "answer") ||
|
||||
typeof d.sdp !== "string"
|
||||
)
|
||||
return null;
|
||||
payload = {
|
||||
type: "description",
|
||||
description: { type: d.type, sdp: d.sdp },
|
||||
track_metadata: parseTrackMetadata(c.track_metadata) ?? undefined,
|
||||
};
|
||||
break;
|
||||
}
|
||||
case SignallingEventType.candidates:
|
||||
if (!Array.isArray(c.candidates)) return null;
|
||||
payload = {
|
||||
type: "candidates",
|
||||
candidates: c.candidates as RTCIceCandidateInit[],
|
||||
};
|
||||
break;
|
||||
case SignallingEventType.close:
|
||||
payload = {
|
||||
type: "close",
|
||||
reason: typeof c.reason === "string" ? c.reason : undefined,
|
||||
};
|
||||
break;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
return { seq: c.seq, message: { ...payload, ...common } };
|
||||
}
|
||||
|
||||
/**
|
||||
* Delivers the messages of one sender in `seq` order. A gap is waited for
|
||||
* `SEQ_GAP_TIMEOUT_MS`, then skipped. A message below the next expected `seq`
|
||||
* came after its gap was skipped, and is dropped.
|
||||
*/
|
||||
export class SeqOrderer<T> {
|
||||
private next = 0;
|
||||
private readonly buffer = new Map<number, T>();
|
||||
private gapTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
public constructor(
|
||||
private readonly deliver: (item: T) => void,
|
||||
private readonly logger?: Logger,
|
||||
private readonly gapTimeoutMs = SEQ_GAP_TIMEOUT_MS,
|
||||
) {}
|
||||
|
||||
public push(seq: number, item: T): void {
|
||||
if (seq < this.next) {
|
||||
this.logger?.warn(`Dropping seq ${seq}, already past it`);
|
||||
return;
|
||||
}
|
||||
this.buffer.set(seq, item);
|
||||
this.flush();
|
||||
}
|
||||
|
||||
public dispose(): void {
|
||||
clearTimeout(this.gapTimer);
|
||||
this.buffer.clear();
|
||||
}
|
||||
|
||||
private flush(): void {
|
||||
let item = this.buffer.get(this.next);
|
||||
while (item !== undefined) {
|
||||
this.buffer.delete(this.next);
|
||||
this.next++;
|
||||
this.deliver(item);
|
||||
item = this.buffer.get(this.next);
|
||||
}
|
||||
clearTimeout(this.gapTimer);
|
||||
this.gapTimer = undefined;
|
||||
if (this.buffer.size > 0)
|
||||
this.gapTimer = setTimeout(() => this.skipGap(), this.gapTimeoutMs);
|
||||
}
|
||||
|
||||
private skipGap(): void {
|
||||
const lowest = Math.min(...this.buffer.keys());
|
||||
this.logger?.warn(`Skipping seq ${this.next} to ${lowest - 1}`);
|
||||
this.next = lowest;
|
||||
this.flush();
|
||||
}
|
||||
}
|
||||
@@ -1,380 +0,0 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Fakes for the parts of WebRTC that jsdom lacks, and for the signalling, so
|
||||
* that the full mesh connections can run in unit tests.
|
||||
*/
|
||||
|
||||
import { vi } from "vitest";
|
||||
import { BehaviorSubject, Subject } from "rxjs";
|
||||
|
||||
import { CONTROL_CHANNEL_LABEL } from "./ControlChannel";
|
||||
import { type LocalPublication } from "./LocalMedia";
|
||||
import {
|
||||
type ConnectionMessage,
|
||||
type Peer,
|
||||
type Signalling,
|
||||
type SignallingMessage,
|
||||
type SignallingPayload,
|
||||
} from "./signalling";
|
||||
|
||||
let nextId = 0;
|
||||
|
||||
export class FakeMediaStream {
|
||||
public readonly id: string;
|
||||
public constructor(public readonly tracks: MediaStreamTrack[] = []) {
|
||||
this.id = `stream-${nextId++}`;
|
||||
}
|
||||
public getTracks(): MediaStreamTrack[] {
|
||||
return this.tracks;
|
||||
}
|
||||
}
|
||||
|
||||
export function fakeTrack(
|
||||
kind: "audio" | "video",
|
||||
settings: MediaTrackSettings = {},
|
||||
): MediaStreamTrack {
|
||||
return {
|
||||
id: `track-${nextId++}`,
|
||||
kind,
|
||||
enabled: true,
|
||||
stop: vi.fn(),
|
||||
getSettings: () => settings,
|
||||
} as unknown as MediaStreamTrack;
|
||||
}
|
||||
|
||||
/** A data channel whose opening and incoming messages the test drives. */
|
||||
export class FakeDataChannel extends EventTarget {
|
||||
public readyState: RTCDataChannelState = "connecting";
|
||||
public readonly sent: string[] = [];
|
||||
public readonly protocol: string;
|
||||
|
||||
public constructor(
|
||||
public readonly label: string,
|
||||
public readonly init: RTCDataChannelInit = {},
|
||||
) {
|
||||
super();
|
||||
this.protocol = init.protocol ?? "";
|
||||
}
|
||||
|
||||
public send(data: string): void {
|
||||
if (this.readyState !== "open") throw new Error("The channel isn't open");
|
||||
this.sent.push(data);
|
||||
}
|
||||
|
||||
/** What was sent, parsed. */
|
||||
public sentMessages(): unknown[] {
|
||||
return this.sent.map((data) => JSON.parse(data) as unknown);
|
||||
}
|
||||
|
||||
public open(): void {
|
||||
this.readyState = "open";
|
||||
this.dispatchEvent(new Event("open"));
|
||||
}
|
||||
|
||||
public close(): void {
|
||||
if (this.readyState === "closed") return;
|
||||
this.readyState = "closed";
|
||||
this.dispatchEvent(new Event("close"));
|
||||
}
|
||||
|
||||
/** A message from the peer; an object is sent as JSON. */
|
||||
public receive(data: unknown): void {
|
||||
this.dispatchEvent(
|
||||
Object.assign(new Event("message"), {
|
||||
data: typeof data === "string" ? data : JSON.stringify(data),
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
interface FakeTransceiver {
|
||||
kind: string;
|
||||
/** Null until a local description gives it one, as in a browser. */
|
||||
mid: string | null;
|
||||
direction: RTCRtpTransceiverDirection;
|
||||
currentDirection: RTCRtpTransceiverDirection | null;
|
||||
streams: MediaStream[];
|
||||
stopped: boolean;
|
||||
stop(): void;
|
||||
sender: {
|
||||
track: MediaStreamTrack | null;
|
||||
replaceTrack: ReturnType<typeof vi.fn>;
|
||||
parameters: RTCRtpSendParameters;
|
||||
getParameters(): RTCRtpSendParameters;
|
||||
setParameters: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
receiver: { track: MediaStreamTrack };
|
||||
}
|
||||
|
||||
/** Enough of `RTCPeerConnection` for one side of a connection, driven by the test. */
|
||||
export class FakePeerConnection extends EventTarget {
|
||||
public static instances: FakePeerConnection[] = [];
|
||||
|
||||
public signalingState: RTCSignalingState = "stable";
|
||||
public connectionState: RTCPeerConnectionState = "new";
|
||||
public iceConnectionState: RTCIceConnectionState = "new";
|
||||
public localDescription: RTCSessionDescriptionInit | null = null;
|
||||
public remoteDescription: RTCSessionDescriptionInit | null = null;
|
||||
public readonly transceivers: FakeTransceiver[] = [];
|
||||
public readonly addedCandidates: RTCIceCandidateInit[] = [];
|
||||
public readonly dataChannels: FakeDataChannel[] = [];
|
||||
public offers = 0;
|
||||
public closed = false;
|
||||
|
||||
public constructor(public readonly config: RTCConfiguration) {
|
||||
super();
|
||||
FakePeerConnection.instances.push(this);
|
||||
}
|
||||
|
||||
public addTransceiver(
|
||||
kind: string,
|
||||
init: RTCRtpTransceiverInit,
|
||||
): FakeTransceiver {
|
||||
const transceiver: FakeTransceiver = {
|
||||
kind,
|
||||
mid: null,
|
||||
direction: init.direction ?? "sendrecv",
|
||||
currentDirection: null,
|
||||
streams: init.streams ?? [],
|
||||
stopped: false,
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
},
|
||||
sender: {
|
||||
track: null,
|
||||
replaceTrack: vi.fn(async (track: MediaStreamTrack | null) => {
|
||||
transceiver.sender.track = track;
|
||||
return Promise.resolve();
|
||||
}),
|
||||
parameters: {
|
||||
encodings: [{}],
|
||||
} as unknown as RTCRtpSendParameters,
|
||||
getParameters: (): RTCRtpSendParameters =>
|
||||
structuredClone(transceiver.sender.parameters),
|
||||
setParameters: vi.fn(async (parameters: RTCRtpSendParameters) => {
|
||||
transceiver.sender.parameters = parameters;
|
||||
return Promise.resolve();
|
||||
}),
|
||||
},
|
||||
receiver: { track: fakeTrack(kind === "audio" ? "audio" : "video") },
|
||||
};
|
||||
this.transceivers.push(transceiver);
|
||||
return transceiver;
|
||||
}
|
||||
|
||||
public createDataChannel(
|
||||
label: string,
|
||||
init?: RTCDataChannelInit,
|
||||
): FakeDataChannel {
|
||||
const channel = new FakeDataChannel(label, init);
|
||||
this.dataChannels.push(channel);
|
||||
return channel;
|
||||
}
|
||||
|
||||
/** Our side of the control channel. */
|
||||
public control(): FakeDataChannel {
|
||||
const channel = this.dataChannels.find(
|
||||
(c) => c.label === CONTROL_CHANNEL_LABEL,
|
||||
);
|
||||
if (channel === undefined) throw new Error("No control channel");
|
||||
return channel;
|
||||
}
|
||||
|
||||
/** A data channel the remote side created, as `ondatachannel` brings it. */
|
||||
public announceDataChannel(label: string, protocol = ""): FakeDataChannel {
|
||||
const channel = new FakeDataChannel(label, { protocol });
|
||||
this.dispatchEvent(Object.assign(new Event("datachannel"), { channel }));
|
||||
return channel;
|
||||
}
|
||||
|
||||
public getTransceivers(): FakeTransceiver[] {
|
||||
return this.transceivers;
|
||||
}
|
||||
|
||||
public getSenders(): FakeTransceiver["sender"][] {
|
||||
return this.transceivers.map((t) => t.sender);
|
||||
}
|
||||
|
||||
public async createOffer(): Promise<RTCSessionDescriptionInit> {
|
||||
return Promise.resolve({ type: "offer", sdp: `offer-${++this.offers}` });
|
||||
}
|
||||
|
||||
public async createAnswer(): Promise<RTCSessionDescriptionInit> {
|
||||
return Promise.resolve({ type: "answer", sdp: "answer" });
|
||||
}
|
||||
|
||||
public async setLocalDescription(
|
||||
description: RTCSessionDescriptionInit,
|
||||
): Promise<void> {
|
||||
this.localDescription = description;
|
||||
this.transceivers.forEach((t, i) => (t.mid ??= String(i)));
|
||||
this.signalingState =
|
||||
description.type === "offer" ? "have-local-offer" : "stable";
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
public async setRemoteDescription(
|
||||
description: RTCSessionDescriptionInit,
|
||||
): Promise<void> {
|
||||
this.remoteDescription = description;
|
||||
this.signalingState =
|
||||
description.type === "offer" ? "have-remote-offer" : "stable";
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
public async addIceCandidate(candidate: RTCIceCandidateInit): Promise<void> {
|
||||
if (candidate.candidate === "bad")
|
||||
return Promise.reject(new Error("bad candidate"));
|
||||
this.addedCandidates.push(candidate);
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
public async getStats(): Promise<RTCStatsReport> {
|
||||
return Promise.resolve(new Map() as unknown as RTCStatsReport);
|
||||
}
|
||||
|
||||
public close(): void {
|
||||
this.closed = true;
|
||||
this.signalingState = "closed";
|
||||
this.connectionState = "closed";
|
||||
for (const channel of this.dataChannels) channel.close();
|
||||
}
|
||||
|
||||
/** Gathers a local candidate; null ends the gathering. */
|
||||
public gather(candidate: RTCIceCandidateInit | null): void {
|
||||
this.dispatchEvent(
|
||||
Object.assign(new Event("icecandidate"), {
|
||||
candidate: candidate && { toJSON: () => candidate },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
public setConnectionState(state: RTCPeerConnectionState): void {
|
||||
this.connectionState = state;
|
||||
this.dispatchEvent(new Event("connectionstatechange"));
|
||||
}
|
||||
|
||||
/** A track the remote side sends, as the next negotiation would bring it. */
|
||||
public receive(kind: "audio" | "video", mid: string): FakeTransceiver {
|
||||
const transceiver = this.addTransceiver(kind, { direction: "recvonly" });
|
||||
transceiver.currentDirection = "recvonly";
|
||||
transceiver.mid = mid;
|
||||
return transceiver;
|
||||
}
|
||||
}
|
||||
|
||||
class FakeAudioContext {
|
||||
public destination = {};
|
||||
public createMediaStreamSource(): object {
|
||||
return { connect: vi.fn(), disconnect: vi.fn() };
|
||||
}
|
||||
public createAnalyser(): object {
|
||||
return {
|
||||
fftSize: 512,
|
||||
connect: vi.fn(),
|
||||
disconnect: vi.fn(),
|
||||
getFloatTimeDomainData: (samples: Float32Array): void => {
|
||||
samples.fill(0);
|
||||
},
|
||||
};
|
||||
}
|
||||
public createGain(): object {
|
||||
return { gain: { value: 1 }, connect: vi.fn(), disconnect: vi.fn() };
|
||||
}
|
||||
}
|
||||
|
||||
/** Replaces the WebRTC and Web Audio globals jsdom doesn't have. Undo with `vi.unstubAllGlobals()`. */
|
||||
export function installWebRtcFakes(): void {
|
||||
FakePeerConnection.instances = [];
|
||||
vi.stubGlobal("RTCPeerConnection", FakePeerConnection);
|
||||
vi.stubGlobal("MediaStream", FakeMediaStream);
|
||||
vi.stubGlobal("AudioContext", FakeAudioContext);
|
||||
}
|
||||
|
||||
/** The last peer connection created. */
|
||||
export function lastPeerConnection(): FakePeerConnection {
|
||||
const pc = FakePeerConnection.instances.at(-1);
|
||||
if (pc === undefined) throw new Error("No peer connection was created");
|
||||
return pc;
|
||||
}
|
||||
|
||||
/** Lets every queued signalling operation run. */
|
||||
export async function settle(): Promise<void> {
|
||||
for (let i = 0; i < 20; i++) await Promise.resolve();
|
||||
}
|
||||
|
||||
export const peer: Peer = {
|
||||
userId: "@peer:example.org",
|
||||
deviceId: "PEERDEVICE",
|
||||
memberId: "peerMember",
|
||||
};
|
||||
|
||||
export interface FakeSignalling extends Signalling {
|
||||
send: ReturnType<typeof vi.fn<Signalling["send"]>>;
|
||||
messages$: Subject<SignallingMessage>;
|
||||
/** The payloads sent so far, optionally only those of one type. */
|
||||
sent(type?: string): SignallingPayload[];
|
||||
/** The connection ids sent with the payloads, in the same order. */
|
||||
sentConnectionIds(type?: string): string[];
|
||||
}
|
||||
|
||||
export function fakeSignalling(): FakeSignalling {
|
||||
const send = vi.fn<Signalling["send"]>();
|
||||
const calls = (type?: string): Parameters<Signalling["send"]>[] =>
|
||||
send.mock.calls.filter(([, , p]) => type === undefined || p.type === type);
|
||||
return {
|
||||
send,
|
||||
messages$: new Subject(),
|
||||
sent: (type) => calls(type).map(([, , p]) => p),
|
||||
sentConnectionIds: (type) => calls(type).map(([, id]) => id),
|
||||
};
|
||||
}
|
||||
|
||||
/** A to-device message of a connection, as signalling delivers it. */
|
||||
export type PeerMessage = ConnectionMessage & Omit<SignallingMessage, "type">;
|
||||
|
||||
/** A to-device message from `peer` on a connection. */
|
||||
export function fromPeer<P extends SignallingPayload>(
|
||||
connectionId: string,
|
||||
payload: P,
|
||||
): P & Omit<SignallingMessage, "type"> {
|
||||
return { ...payload, ...peer, connectionId };
|
||||
}
|
||||
|
||||
/** The local media a publisher connection reads. */
|
||||
export function fakeLocalMedia(): {
|
||||
publications$: BehaviorSubject<LocalPublication[]>;
|
||||
publishing$: BehaviorSubject<boolean>;
|
||||
} {
|
||||
return {
|
||||
publications$: new BehaviorSubject<LocalPublication[]>([]),
|
||||
publishing$: new BehaviorSubject(true),
|
||||
};
|
||||
}
|
||||
|
||||
export function fakePublication(
|
||||
kind: "audio" | "video",
|
||||
{
|
||||
source = kind === "audio" ? "microphone" : "camera",
|
||||
stream = new FakeMediaStream() as unknown as MediaStream,
|
||||
}: Partial<Pick<LocalPublication, "source" | "stream">> = {},
|
||||
): LocalPublication & {
|
||||
track$: BehaviorSubject<MediaStreamTrack | null>;
|
||||
muted$: BehaviorSubject<boolean>;
|
||||
} {
|
||||
const muted$ = new BehaviorSubject(false);
|
||||
return {
|
||||
source,
|
||||
kind,
|
||||
stream,
|
||||
track$: new BehaviorSubject<MediaStreamTrack | null>(fakeTrack(kind)),
|
||||
muted$,
|
||||
mediaTrack: { muted$ } as unknown as LocalPublication["mediaTrack"],
|
||||
};
|
||||
}
|
||||
@@ -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 }),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -108,11 +108,8 @@ export class ConnectionMap {
|
||||
interface Props {
|
||||
scope: ObservableScope;
|
||||
connectionFactory: ConnectionFactory;
|
||||
/**
|
||||
* The transport we publish on; the one connection with the publisher role.
|
||||
* Null for a backend that only subscribes, while another backend publishes.
|
||||
*/
|
||||
localTransport: TransportLocator | null;
|
||||
/** The transport we publish on; the one connection with the publisher role. */
|
||||
localTransport: TransportLocator;
|
||||
/** Every transport some member is on, deduplicated against the local one. */
|
||||
remoteTransports$: Behavior<Epoch<TransportLocator[]>>;
|
||||
logger: Logger;
|
||||
@@ -138,11 +135,7 @@ export function createConnectionMap$({
|
||||
scope.behavior(
|
||||
remoteTransports$.pipe(
|
||||
mapEpoch((remoteTransports) =>
|
||||
removeDuplicateTransports(
|
||||
localTransport
|
||||
? [localTransport, ...remoteTransports]
|
||||
: remoteTransports,
|
||||
),
|
||||
removeDuplicateTransports([localTransport, ...remoteTransports]),
|
||||
),
|
||||
tap((transports) =>
|
||||
logger.debug("localAndRemoteTransports$ = ", transports),
|
||||
@@ -150,7 +143,7 @@ export function createConnectionMap$({
|
||||
),
|
||||
);
|
||||
|
||||
const localTransportKey = localTransport && keyFor(localTransport);
|
||||
const localTransportKey = keyFor(localTransport);
|
||||
|
||||
const connections$ = scope.behavior(
|
||||
localAndRemoteTransports$.pipe(
|
||||
|
||||
@@ -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: {
|
||||
@@ -475,38 +475,6 @@ describe("createLivekitBackend", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("connects nowhere until it knows whether it publishes", async () => {
|
||||
const b = backend();
|
||||
const media = b.mediaFor(testScope(), bob(bothTransport, [legacyId]));
|
||||
await flushPromises();
|
||||
expect(media.tracks$.value).toBeNull();
|
||||
// A subscriber connection now would be replaced by the publisher one
|
||||
expect(connections).toHaveLength(0);
|
||||
|
||||
fetchMock.post(homeserverEndpoint, 404);
|
||||
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 404);
|
||||
await b.prepareLocalTransport(bothTransport);
|
||||
await flushPromises();
|
||||
expect(connections.map((c) => c.connection.role)).toEqual(["publisher"]);
|
||||
});
|
||||
|
||||
it("only subscribes once told that another backend publishes", async () => {
|
||||
const b = backend();
|
||||
b.mediaFor(testScope(), bob(bothTransport, [legacyId]));
|
||||
await flushPromises();
|
||||
expect(connections).toHaveLength(0);
|
||||
|
||||
await expect(b.prepareLocalTransport(null)).resolves.toEqual({
|
||||
canDelegateDelayedLeave: false,
|
||||
});
|
||||
await flushPromises();
|
||||
expect(connections.map((c) => c.connection.role)).toEqual(["subscriber"]);
|
||||
expect(connections[0].connection.transport).toEqual(bothTransport);
|
||||
await expect(b.delegateDelayedLeave("id")).rejects.toThrow(
|
||||
"No local transport",
|
||||
);
|
||||
});
|
||||
|
||||
it("has no media for a member without a transport, and opens no connection", async () => {
|
||||
const b = await prepared();
|
||||
const media = b.mediaFor(testScope(), {
|
||||
|
||||
@@ -73,10 +73,7 @@ export interface LivekitBackendOptions {
|
||||
*/
|
||||
client: Pick<
|
||||
MatrixClient,
|
||||
| "getOpenIdToken"
|
||||
| "_unstable_getLivekitToken"
|
||||
| "_unstable_delegateDelayedLeave"
|
||||
| "baseUrl"
|
||||
"getOpenIdToken" | "getLivekitToken" | "delegateDelayedLeave" | "baseUrl"
|
||||
>;
|
||||
mediaQuality?: MediaQuality;
|
||||
}
|
||||
@@ -106,11 +103,7 @@ export function createLivekitBackend(
|
||||
: [requestsOrMedia.requests, requestsOrMedia];
|
||||
const keyProvider = createKeyProvider(encryptionSystem, mediaKeys$, logger);
|
||||
const transports = createTransportRegistry(scope);
|
||||
// Undefined until the session says whether we publish here: null where
|
||||
// another backend publishes
|
||||
const localTransport$ = new BehaviorSubject<
|
||||
TransportLocator | null | undefined
|
||||
>(undefined);
|
||||
const localTransport$ = new BehaviorSubject<TransportLocator | null>(null);
|
||||
const audioOutputDeviceId$ = new BehaviorSubject<string | undefined>(
|
||||
undefined,
|
||||
);
|
||||
@@ -125,20 +118,9 @@ export function createLivekitBackend(
|
||||
);
|
||||
|
||||
// A new map, in a scope of its own, whenever the local transport changes:
|
||||
// the publisher role sits on one connection, and which one is fixed per map.
|
||||
// Without a local transport the map only subscribes, for when another
|
||||
// backend publishes; boxed so that `mapScoped` builds a map for null too.
|
||||
// None at all while it isn't known yet: a subscriber connection to the
|
||||
// transport we are about to publish on would only be torn down again
|
||||
const boxedLocalTransport$ = scope.behavior(
|
||||
localTransport$.pipe(
|
||||
map((localTransport) =>
|
||||
localTransport === undefined ? undefined : { localTransport },
|
||||
),
|
||||
),
|
||||
);
|
||||
// the publisher role sits on one connection, and which one is fixed per map
|
||||
const connectionMap$ = scope.behavior<Epoch<ConnectionMap>>(
|
||||
mapScoped(scope, boxedLocalTransport$, (mapScope, { localTransport }) =>
|
||||
mapScoped(scope, localTransport$, (mapScope, localTransport) =>
|
||||
createConnectionMap$({
|
||||
scope: mapScope,
|
||||
connectionFactory,
|
||||
@@ -153,9 +135,7 @@ export function createLivekitBackend(
|
||||
const localMedia_ = createLivekitLocalMedia({
|
||||
scope,
|
||||
connectionMap$,
|
||||
localTransport$: scope.behavior(
|
||||
localTransport$.pipe(map((localTransport) => localTransport ?? null)),
|
||||
),
|
||||
localTransport$,
|
||||
publish,
|
||||
media,
|
||||
audioOutputDeviceId$,
|
||||
@@ -163,25 +143,18 @@ export function createLivekitBackend(
|
||||
logger,
|
||||
});
|
||||
|
||||
// Probed once, when first needed: the answer cannot change within a
|
||||
// session, and a backend that only subscribes never needs it
|
||||
let homeserverProbe: Promise<boolean> | undefined;
|
||||
const homeserverSupportsDelegation = async (): Promise<boolean> =>
|
||||
(homeserverProbe ??= supportsDelegation(
|
||||
`${client.baseUrl}/_matrix/client/unstable/io.element.msc4195/rtc/livekit/delegate_delayed_leave`,
|
||||
"homeserver",
|
||||
logger,
|
||||
));
|
||||
// Probed once: the answer cannot change within a session
|
||||
const homeserverSupportsDelegation = supportsDelegation(
|
||||
`${client.baseUrl}/_matrix/client/unstable/io.element.msc4195/rtc/livekit/delegate_delayed_leave`,
|
||||
"homeserver",
|
||||
logger,
|
||||
);
|
||||
|
||||
const ownServerName = serverNameOf(ownMembershipIdentity.userId);
|
||||
|
||||
const prepareLocalTransport = async (
|
||||
transport: Transport | null,
|
||||
transport: Transport,
|
||||
): Promise<TransportCapabilities> => {
|
||||
if (transport === null) {
|
||||
localTransport$.next(null);
|
||||
return { canDelegateDelayedLeave: false };
|
||||
}
|
||||
if (!isUnstableLivekitTransport(transport))
|
||||
throw new MatrixRTCError(`Not a LiveKit transport: ${transport.type}`);
|
||||
const serverName = serverNameOfTransport(
|
||||
@@ -206,7 +179,7 @@ export function createLivekitBackend(
|
||||
`transport ${flow.serviceUrl}`,
|
||||
logger,
|
||||
)
|
||||
: homeserverSupportsDelegation();
|
||||
: homeserverSupportsDelegation;
|
||||
}
|
||||
localTransport$.next(locator);
|
||||
// The membership is only sent once the publisher connection holds its
|
||||
@@ -222,7 +195,7 @@ export function createLivekitBackend(
|
||||
|
||||
const delegateLeave = async (delayId: string): Promise<void> => {
|
||||
const local = localTransport$.value;
|
||||
if (!local)
|
||||
if (local === null)
|
||||
throw new MatrixRTCError("No local transport to delegate the leave to");
|
||||
await delegateDelayedLeave({
|
||||
client,
|
||||
|
||||
@@ -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 {
|
||||
@@ -233,10 +225,6 @@ describe("createLivekitMediaTrack", () => {
|
||||
])(
|
||||
"leaves a processed camera alone unless its device changes: $deviceId",
|
||||
async ({ deviceId, switches }) => {
|
||||
vi.stubGlobal("MediaStreamTrack", class {});
|
||||
onTestFinished(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
const camera = Object.assign(Object.create(LocalVideoTrack.prototype), {
|
||||
source: Track.Source.Camera,
|
||||
_mediaStreamTrack: {
|
||||
@@ -270,6 +258,41 @@ describe("createLivekitMediaTrack", () => {
|
||||
},
|
||||
);
|
||||
|
||||
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([
|
||||
@@ -279,10 +302,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: {
|
||||
|
||||
@@ -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> = {
|
||||
@@ -231,10 +231,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;
|
||||
},
|
||||
@@ -288,6 +287,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>,
|
||||
@@ -298,12 +305,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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -20,10 +20,7 @@ function isNetworkError(e: unknown): boolean {
|
||||
return e instanceof HTTPError || e instanceof ConnectionError;
|
||||
}
|
||||
|
||||
export type ClientGetTokenParts = Pick<
|
||||
MatrixClient,
|
||||
"_unstable_getLivekitToken"
|
||||
>;
|
||||
export type ClientGetTokenParts = Pick<MatrixClient, "getLivekitToken">;
|
||||
|
||||
export interface GetSFUConfigParams {
|
||||
client: ClientGetTokenParts;
|
||||
@@ -48,7 +45,7 @@ export async function getSFUConfig({
|
||||
}: GetSFUConfigParams): Promise<SFUConfig> {
|
||||
const res = await doNetworkOperationWithRetry(
|
||||
async () =>
|
||||
client._unstable_getLivekitToken({
|
||||
client.getLivekitToken({
|
||||
url,
|
||||
server_name: serverName,
|
||||
room_id: roomId,
|
||||
@@ -62,7 +59,7 @@ export async function getSFUConfig({
|
||||
|
||||
export type ClientDelegationParts = Pick<
|
||||
MatrixClient,
|
||||
"_unstable_delegateDelayedLeave" | "baseUrl"
|
||||
"delegateDelayedLeave" | "baseUrl"
|
||||
>;
|
||||
|
||||
export interface DelegateDelayedLeaveParams {
|
||||
@@ -90,7 +87,7 @@ export async function delegateDelayedLeave({
|
||||
}: DelegateDelayedLeaveParams): Promise<void> {
|
||||
await doNetworkOperationWithRetry(
|
||||
async () =>
|
||||
client._unstable_delegateDelayedLeave({
|
||||
client.delegateDelayedLeave({
|
||||
url,
|
||||
room_id: roomId,
|
||||
slot_id: slotId,
|
||||
|
||||
@@ -33,8 +33,8 @@ const client: Mocked<
|
||||
openID.ClientOpenIDParts
|
||||
> = {
|
||||
baseUrl: "https://matrix.example.org",
|
||||
_unstable_getLivekitToken: vi.fn().mockResolvedValue({ jwt: csApiJWTToken }),
|
||||
_unstable_delegateDelayedLeave: vi.fn().mockResolvedValue({}),
|
||||
getLivekitToken: vi.fn().mockResolvedValue({ jwt: csApiJWTToken }),
|
||||
delegateDelayedLeave: vi.fn().mockResolvedValue({}),
|
||||
getOpenIdToken: vi
|
||||
.fn()
|
||||
.mockResolvedValue({ access_token: "mock-openID-token" }),
|
||||
@@ -110,7 +110,7 @@ describe("getSFUConfig", () => {
|
||||
livekitAlias: "via CS API",
|
||||
}),
|
||||
);
|
||||
expect(client._unstable_getLivekitToken).toHaveBeenCalledWith({
|
||||
expect(client.getLivekitToken).toHaveBeenCalledWith({
|
||||
url: urlTransport.url,
|
||||
server_name: "example.org",
|
||||
room_id: roomId,
|
||||
@@ -122,11 +122,11 @@ describe("getSFUConfig", () => {
|
||||
|
||||
it("does not fall back to OpenID with url transport", async () => {
|
||||
mockJWTService();
|
||||
client._unstable_getLivekitToken.mockRejectedValueOnce(unsupportedError);
|
||||
client.getLivekitToken.mockRejectedValueOnce(unsupportedError);
|
||||
await expect(
|
||||
getSFUConfig({ ...defaultParams, transport: urlTransport }),
|
||||
).rejects.toThrow(expect.any(NoMatrix2AuthorizationService));
|
||||
expect(client._unstable_getLivekitToken).toHaveBeenCalled();
|
||||
expect(client.getLivekitToken).toHaveBeenCalled();
|
||||
expect(jwtServiceCalls()).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -140,7 +140,7 @@ describe("getSFUConfig", () => {
|
||||
livekitAlias: "via default endpoint",
|
||||
}),
|
||||
);
|
||||
expect(client._unstable_getLivekitToken).not.toHaveBeenCalled();
|
||||
expect(client.getLivekitToken).not.toHaveBeenCalled();
|
||||
expect(jwtServiceCalls()).toEqual(["/get_token"]);
|
||||
});
|
||||
|
||||
@@ -157,7 +157,7 @@ describe("getSFUConfig", () => {
|
||||
livekitAlias: "via default endpoint",
|
||||
}),
|
||||
);
|
||||
expect(client._unstable_getLivekitToken).not.toHaveBeenCalled();
|
||||
expect(client.getLivekitToken).not.toHaveBeenCalled();
|
||||
expect(jwtServiceCalls()).toEqual(["/get_token"]);
|
||||
});
|
||||
|
||||
@@ -166,7 +166,7 @@ describe("getSFUConfig", () => {
|
||||
const error = new Error(
|
||||
"The rtc_livekit_get_token action is not supported by the client.",
|
||||
);
|
||||
client._unstable_getLivekitToken.mockRejectedValueOnce(error);
|
||||
client.getLivekitToken.mockRejectedValueOnce(error);
|
||||
await expect(
|
||||
getSFUConfig({ ...defaultParams, transport: urlTransport }),
|
||||
).rejects.toThrow(error);
|
||||
@@ -182,13 +182,13 @@ describe("getSFUConfig", () => {
|
||||
role: "publisher",
|
||||
}),
|
||||
).toEqual(expect.objectContaining({ jwt: csApiJWTToken }));
|
||||
expect(client._unstable_getLivekitToken).toHaveBeenCalled();
|
||||
expect(client.getLivekitToken).toHaveBeenCalled();
|
||||
expect(jwtServiceCalls()).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not fall back to OpenID when publishing with url transport", async () => {
|
||||
mockJWTService();
|
||||
client._unstable_getLivekitToken.mockRejectedValueOnce(unsupportedError);
|
||||
client.getLivekitToken.mockRejectedValueOnce(unsupportedError);
|
||||
await expect(
|
||||
getSFUConfig({
|
||||
...defaultParams,
|
||||
@@ -196,7 +196,7 @@ describe("getSFUConfig", () => {
|
||||
role: "publisher",
|
||||
}),
|
||||
).rejects.toThrow(expect.any(NoMatrix2AuthorizationService));
|
||||
expect(client._unstable_getLivekitToken).toHaveBeenCalled();
|
||||
expect(client.getLivekitToken).toHaveBeenCalled();
|
||||
expect(jwtServiceCalls()).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -216,7 +216,7 @@ describe("getSFUConfig", () => {
|
||||
livekitAlias: "via legacy endpoint",
|
||||
}),
|
||||
);
|
||||
expect(client._unstable_getLivekitToken).not.toHaveBeenCalled();
|
||||
expect(client.getLivekitToken).not.toHaveBeenCalled();
|
||||
expect(jwtServiceCalls()).toEqual(["/sfu/get"]);
|
||||
});
|
||||
});
|
||||
@@ -245,7 +245,7 @@ describe("delegateDelayedLeave", () => {
|
||||
it("uses CS API with url transport", async () => {
|
||||
mockJWTService();
|
||||
await delegateDelayedLeave({ ...defaultParams, transport: urlTransport });
|
||||
expect(client._unstable_delegateDelayedLeave).toHaveBeenCalledWith({
|
||||
expect(client.delegateDelayedLeave).toHaveBeenCalledWith({
|
||||
url: urlTransport.url,
|
||||
room_id: roomId,
|
||||
slot_id: slotId,
|
||||
@@ -257,13 +257,11 @@ describe("delegateDelayedLeave", () => {
|
||||
|
||||
it("does not fall back to OpenID with url transport", async () => {
|
||||
mockJWTService();
|
||||
client._unstable_delegateDelayedLeave.mockRejectedValueOnce(
|
||||
unsupportedError,
|
||||
);
|
||||
client.delegateDelayedLeave.mockRejectedValueOnce(unsupportedError);
|
||||
await expect(
|
||||
delegateDelayedLeave({ ...defaultParams, transport: urlTransport }),
|
||||
).rejects.toThrow();
|
||||
expect(client._unstable_delegateDelayedLeave).toHaveBeenCalled();
|
||||
expect(client.delegateDelayedLeave).toHaveBeenCalled();
|
||||
expect(jwtServiceCalls()).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -273,7 +271,7 @@ describe("delegateDelayedLeave", () => {
|
||||
...defaultParams,
|
||||
transport: serviceUrlTransport,
|
||||
});
|
||||
expect(client._unstable_delegateDelayedLeave).not.toHaveBeenCalled();
|
||||
expect(client.delegateDelayedLeave).not.toHaveBeenCalled();
|
||||
expect(delegationViaJWTService()).toEqual({
|
||||
delay_id: "delay123",
|
||||
delay_timeout: 3_600_000,
|
||||
@@ -288,7 +286,7 @@ describe("delegateDelayedLeave", () => {
|
||||
...defaultParams,
|
||||
transport: urlAndServiceUrlTransport,
|
||||
});
|
||||
expect(client._unstable_delegateDelayedLeave).not.toHaveBeenCalled();
|
||||
expect(client.delegateDelayedLeave).not.toHaveBeenCalled();
|
||||
expect(delegationViaJWTService()).toEqual({
|
||||
delay_id: "delay123",
|
||||
delay_timeout: 3_600_000,
|
||||
|
||||
@@ -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 { describe, expect, it } from "vitest";
|
||||
|
||||
import { facingModeOf } from "./facingMode";
|
||||
|
||||
function camera(label: string, facingMode?: string): MediaStreamTrack {
|
||||
return {
|
||||
label,
|
||||
getSettings: () => (facingMode === undefined ? {} : { facingMode }),
|
||||
} as MediaStreamTrack;
|
||||
}
|
||||
|
||||
describe("facingModeOf", () => {
|
||||
it.each([
|
||||
{ label: "Back Camera", facingMode: "environment", faces: "environment" },
|
||||
{ label: "iPhone Camera", facingMode: "user", faces: "user" },
|
||||
{ label: "FaceTime HD Camera", facingMode: undefined, faces: "user" },
|
||||
{ label: "", facingMode: undefined, faces: "user" },
|
||||
{
|
||||
label: "Alice's iPhone Camera",
|
||||
facingMode: undefined,
|
||||
faces: "environment",
|
||||
},
|
||||
{ label: "iPad Camera", facingMode: undefined, faces: "environment" },
|
||||
{
|
||||
label: " OBS Virtual Camera ",
|
||||
facingMode: undefined,
|
||||
faces: "environment",
|
||||
},
|
||||
{ label: "Integrated Camera", facingMode: "left", faces: "user" },
|
||||
])(
|
||||
"takes $label ($facingMode) to face $faces",
|
||||
({ label, facingMode, faces }) => {
|
||||
expect(facingModeOf(camera(label, facingMode))).toBe(faces);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Which way a camera faces. Laptop and desktop cameras don't say and face the
|
||||
* user; of those, a phone used as a webcam (Continuity Camera) films with its
|
||||
* rear camera and OBS shows a scene, so neither is taken to face the user.
|
||||
* LiveKit makes the same guess.
|
||||
*/
|
||||
export function facingModeOf(track: MediaStreamTrack): "user" | "environment" {
|
||||
const { facingMode } = track.getSettings();
|
||||
if (facingMode === "user" || facingMode === "environment") return facingMode;
|
||||
const label = track.label.trim().toLowerCase();
|
||||
return label === "obs virtual camera" ||
|
||||
label.includes("iphone") ||
|
||||
label.includes("ipad")
|
||||
? "environment"
|
||||
: "user";
|
||||
}
|
||||
+12
-2
@@ -30,7 +30,7 @@ import { HomePage } from "./home/HomePage";
|
||||
import { LoginPage } from "./auth/LoginPage";
|
||||
import { RegisterPage } from "./auth/RegisterPage";
|
||||
import { RoomPage } from "./room/RoomPage";
|
||||
import { ClientProvider } from "./ClientContext";
|
||||
import { type ClientLoader, ClientProvider } from "./ClientContext";
|
||||
import { ErrorPage, LoadingPage } from "./FullScreenView";
|
||||
import { Initializer } from "./initializer";
|
||||
import { type WidgetHelpers } from "./widget";
|
||||
@@ -57,6 +57,16 @@ import { LeaveToHomeProvider } from "./LeaveToHomeContext";
|
||||
|
||||
const SentryRoute = Sentry.withSentryReactRouterV7Routing(Route);
|
||||
|
||||
// Element Call's own session, for when no host supplies a client.
|
||||
// - Passed in here, not imported by ClientProvider: this module is only in the
|
||||
// app builds, so the client setup and the store worker behind it stay out of
|
||||
// the component package (see the `loadClient` prop).
|
||||
// - Imported on demand, as it was before, so that a widget, which gets its
|
||||
// client from the host, never downloads it.
|
||||
// - Module-level, so that the provider's effect sees one stable loader.
|
||||
const loadStandaloneClient: ClientLoader = async (...args) =>
|
||||
(await import("./utils/spa")).initSPA(...args);
|
||||
|
||||
interface SimpleProviderProps {
|
||||
children: JSX.Element;
|
||||
}
|
||||
@@ -146,7 +156,7 @@ export const App: FC<Props> = ({ vm, widget }) => {
|
||||
|
||||
const content =
|
||||
loaded && clientReady ? (
|
||||
<ClientProvider client={widgetClient}>
|
||||
<ClientProvider client={widgetClient} loadClient={loadStandaloneClient}>
|
||||
<MediaDevicesContext value={vm.mediaDevices}>
|
||||
<BackgroundEffectsProvider effects={vm.backgroundEffects}>
|
||||
<Sentry.ErrorBoundary
|
||||
|
||||
@@ -11,7 +11,11 @@ import { BrowserRouter } from "react-router-dom";
|
||||
import { type MatrixClient } from "matrix-js-sdk";
|
||||
import { type FC } from "react";
|
||||
|
||||
import { ClientProvider, useClientState } from "./ClientContext";
|
||||
import {
|
||||
type ClientLoader,
|
||||
ClientProvider,
|
||||
useClientState,
|
||||
} from "./ClientContext";
|
||||
|
||||
const mockClient = (userId = "@alice:example.org"): MatrixClient =>
|
||||
({
|
||||
@@ -95,13 +99,13 @@ test("follows the client when the host swaps it", () => {
|
||||
|
||||
test("finds a client of its own when the host supplies none", async () => {
|
||||
const client = mockClient();
|
||||
vi.doMock("./utils/spa", () => ({
|
||||
initSPA: vi.fn().mockResolvedValue({ client, passwordlessUser: true }),
|
||||
}));
|
||||
const loadClient = vi
|
||||
.fn<ClientLoader>()
|
||||
.mockResolvedValue({ client, passwordlessUser: true });
|
||||
|
||||
const { container } = render(
|
||||
<BrowserRouter>
|
||||
<ClientProvider>
|
||||
<ClientProvider loadClient={loadClient}>
|
||||
<ShowClientState />
|
||||
</ClientProvider>
|
||||
</BrowserRouter>,
|
||||
@@ -110,6 +114,21 @@ test("finds a client of its own when the host supplies none", async () => {
|
||||
// Nothing to show until a session has been restored or created
|
||||
expect(container.textContent).toBe("loading");
|
||||
await waitFor(() => expect(container.textContent).toBe("@alice:example.org"));
|
||||
// Given the session store to restore from and to clear on a stale session
|
||||
expect(loadClient).toHaveBeenCalledWith(
|
||||
expect.any(Function),
|
||||
expect.any(Function),
|
||||
);
|
||||
});
|
||||
|
||||
vi.doUnmock("./utils/spa");
|
||||
test("has no one signed in when given neither a client nor a way to load one", async () => {
|
||||
const { container } = render(
|
||||
<BrowserRouter>
|
||||
<ClientProvider>
|
||||
<ShowClientState />
|
||||
</ClientProvider>
|
||||
</BrowserRouter>,
|
||||
);
|
||||
|
||||
await waitFor(() => expect(container.textContent).toBe("unauthenticated"));
|
||||
});
|
||||
|
||||
+32
-12
@@ -143,9 +143,34 @@ interface Props {
|
||||
* own.
|
||||
*/
|
||||
client?: MatrixClient;
|
||||
/**
|
||||
* How Element Call finds a client when none is supplied: the standalone app
|
||||
* restores or creates a session of its own. Stable, as a hook dependency.
|
||||
* Left out along with the client, no one is signed in.
|
||||
*
|
||||
* A prop, rather than this module importing `utils/spa` itself, because:
|
||||
* - This module is in the component build, and so is everything it imports,
|
||||
* dynamically or not: a dynamic import becomes a chunk in the package,
|
||||
* not a module left out of it.
|
||||
* - Behind `utils/spa` sits `utils/initClient` and the client store worker,
|
||||
* which the bundler emits as soon as it loads the import (see there).
|
||||
* - `App.tsx`, which the component never imports, is where the standalone
|
||||
* app passes the loader in; the component passes nothing, having the
|
||||
* host's client.
|
||||
*/
|
||||
loadClient?: ClientLoader;
|
||||
}
|
||||
|
||||
export const ClientProvider: FC<Props> = ({ children, client }) => {
|
||||
/**
|
||||
* Restores or creates a session of Element Call's own, kept where the given
|
||||
* functions keep it. Resolves to null when no one is signed in.
|
||||
*/
|
||||
export type ClientLoader = (
|
||||
loadSession: () => Session | undefined,
|
||||
clearSession: () => void,
|
||||
) => Promise<InitResult | null>;
|
||||
|
||||
export const ClientProvider: FC<Props> = ({ children, client, loadClient }) => {
|
||||
const leaveToHome = useLeaveToHome();
|
||||
const hostBridge = useHostBridge();
|
||||
|
||||
@@ -179,9 +204,13 @@ export const ClientProvider: FC<Props> = ({ children, client }) => {
|
||||
// React does in strict mode), we need to make sure not to doubly initialize
|
||||
// the client.
|
||||
if (initializing.current) return;
|
||||
if (loadClient === undefined) {
|
||||
setInitClientState(null);
|
||||
return;
|
||||
}
|
||||
initializing.current = true;
|
||||
|
||||
loadClient()
|
||||
loadClient(loadSession, clearSession)
|
||||
.then((initResult) => {
|
||||
setInitClientState(initResult);
|
||||
if (PosthogAnalytics.instance.isEnabled())
|
||||
@@ -189,7 +218,7 @@ export const ClientProvider: FC<Props> = ({ children, client }) => {
|
||||
})
|
||||
.catch((err) => logger.error(err))
|
||||
.finally(() => (initializing.current = false));
|
||||
}, [client]);
|
||||
}, [client, loadClient]);
|
||||
|
||||
const changePassword = useCallback(
|
||||
async (password: string) => {
|
||||
@@ -360,15 +389,6 @@ export type InitResult = {
|
||||
passwordlessUser: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Restores or creates a session of Element Call's own. Only reached when no
|
||||
* client was supplied for it to use.
|
||||
*/
|
||||
async function loadClient(): Promise<InitResult | null> {
|
||||
const { initSPA } = await import("./utils/spa");
|
||||
return initSPA(loadSession, clearSession);
|
||||
}
|
||||
|
||||
export interface Session {
|
||||
user_id: string;
|
||||
device_id: string;
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
.popover {
|
||||
position: relative;
|
||||
border-radius: var(--cpd-space-3x);
|
||||
background: var(--cpd-color-bg-canvas-default);
|
||||
box-shadow: var(--big-drop-shadow);
|
||||
padding: var(--cpd-space-5x);
|
||||
box-sizing: border-box;
|
||||
inline-size: 310px;
|
||||
max-inline-size: 90vw;
|
||||
|
||||
/* Draw an internal border */
|
||||
&::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border: var(--cpd-border-width-1) solid
|
||||
var(--cpd-color-border-interactive-secondary);
|
||||
border-radius: inherit;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
transition:
|
||||
opacity 180ms,
|
||||
transform 180ms;
|
||||
|
||||
&[data-starting-style] {
|
||||
opacity: 0;
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
transform: translate(0, var(--cpd-space-3x));
|
||||
}
|
||||
}
|
||||
|
||||
&[data-ending-style] {
|
||||
transition-duration: 110ms;
|
||||
opacity: 0;
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
transform: translate(0, var(--cpd-space-2x));
|
||||
}
|
||||
}
|
||||
|
||||
p {
|
||||
font: var(--cpd-font-body-sm-regular);
|
||||
color: var(--cpd-color-text-secondary);
|
||||
margin-block-end: var(--cpd-space-4x);
|
||||
}
|
||||
}
|
||||
|
||||
.title {
|
||||
margin-block-end: var(--cpd-space-2x);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { Popover } from "./Popover";
|
||||
import { Button } from "@vector-im/compound-web";
|
||||
import { VideoCallOffSolidIcon } from "@vector-im/compound-design-tokens/assets/web/icons";
|
||||
import { useState } from "react";
|
||||
|
||||
const meta = {
|
||||
component: Popover,
|
||||
} satisfies Meta<typeof Popover>;
|
||||
|
||||
export default meta;
|
||||
|
||||
export const Default: StoryObj = {
|
||||
render: () => {
|
||||
const [open, setOpen] = useState(true);
|
||||
return (
|
||||
<Popover
|
||||
title="Poor network connection"
|
||||
trigger={<Button>Open popover</Button>}
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
>
|
||||
<p>Turn off all videos to improve call performance.</p>
|
||||
<Button
|
||||
size="md"
|
||||
Icon={VideoCallOffSolidIcon}
|
||||
style={{ width: "100%", marginBlockStart: 24 }}
|
||||
>
|
||||
Turn off all videos
|
||||
</Button>
|
||||
</Popover>
|
||||
);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { expect, test } from "vitest";
|
||||
import { axe } from "vitest-axe";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
|
||||
import { Popover } from "./Popover";
|
||||
|
||||
test("Popover renders", async () => {
|
||||
render(
|
||||
<Popover
|
||||
title="Example"
|
||||
trigger={<button>Open popover</button>}
|
||||
open
|
||||
onOpenChange={() => {}}
|
||||
>
|
||||
<p>This is an example of a popover.</p>
|
||||
</Popover>,
|
||||
);
|
||||
const button = screen.getByRole("button", { name: "Open popover" });
|
||||
const popover = screen.getByRole("dialog", { name: "Example" });
|
||||
expect(button).toMatchSnapshot("button");
|
||||
expect(popover).toMatchSnapshot("popover");
|
||||
expect(await axe(document.body)).toHaveNoViolations();
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
Copyright 2026 Element Creations Ltd.
|
||||
|
||||
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import { type FC, type ReactElement, type ReactNode } from "react";
|
||||
import { Popover as BUIPopover } from "@base-ui/react/popover";
|
||||
|
||||
import styles from "./Popover.module.css";
|
||||
import { Heading } from "@vector-im/compound-web";
|
||||
import classNames from "classnames";
|
||||
|
||||
export interface PopoverProps {
|
||||
/**
|
||||
* The popover title.
|
||||
*/
|
||||
title: string;
|
||||
/**
|
||||
* The button that opens the popover. This must be a component that accepts a
|
||||
* ref and spreads props.
|
||||
*
|
||||
* https://base-ui.com/react/handbook/composition
|
||||
*/
|
||||
trigger: ReactElement;
|
||||
/**
|
||||
* Whether the popover is open.
|
||||
*/
|
||||
open: boolean;
|
||||
/**
|
||||
* Event handler called when the user tries to open or close the popover.
|
||||
*/
|
||||
onOpenChange: (open: boolean) => void;
|
||||
/**
|
||||
* The popover contents.
|
||||
*/
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
/**
|
||||
* The side of the trigger on which to place the popover. Note that the menu
|
||||
* may still end up on a different side than the one you request if there
|
||||
* isn't enough space.
|
||||
* @default bottom
|
||||
*/
|
||||
side?: "top" | "bottom" | "left" | "right" | "inline-end" | "inline-start";
|
||||
/**
|
||||
* The edge along which the popover and trigger will be aligned.
|
||||
* @default center
|
||||
*/
|
||||
align?: "start" | "center" | "end";
|
||||
}
|
||||
|
||||
/**
|
||||
* A popover opened by pressing a button.
|
||||
*/
|
||||
export const Popover: FC<PopoverProps> = ({
|
||||
title,
|
||||
trigger,
|
||||
open,
|
||||
onOpenChange,
|
||||
children,
|
||||
className,
|
||||
side,
|
||||
align,
|
||||
}) => {
|
||||
return (
|
||||
<BUIPopover.Root open={open} onOpenChange={onOpenChange}>
|
||||
<BUIPopover.Trigger render={trigger} />
|
||||
<BUIPopover.Portal>
|
||||
<BUIPopover.Positioner sideOffset={8} side={side} align={align}>
|
||||
<BUIPopover.Popup className={classNames(styles.popover, className)}>
|
||||
<BUIPopover.Title
|
||||
className={styles.title}
|
||||
render={
|
||||
<Heading as="h3" type="body" weight="semibold" size="lg">
|
||||
{title}
|
||||
</Heading>
|
||||
}
|
||||
/>
|
||||
{children}
|
||||
</BUIPopover.Popup>
|
||||
</BUIPopover.Positioner>
|
||||
</BUIPopover.Portal>
|
||||
</BUIPopover.Root>
|
||||
);
|
||||
};
|
||||
+10
-8
@@ -18,6 +18,8 @@ Please see LICENSE in the repository root for full details.
|
||||
*/
|
||||
|
||||
import {
|
||||
RTC_CALL_INTENT_AUDIO,
|
||||
RTC_CALL_INTENT_VIDEO,
|
||||
type RTCCallIntent,
|
||||
type RTCNotificationType,
|
||||
} from "matrix-js-sdk/lib/matrixrtc";
|
||||
@@ -179,40 +181,40 @@ export function configurationForIntent(intent: UserIntent): UrlConfiguration {
|
||||
switch (intent) {
|
||||
case UserIntent.StartNewCall:
|
||||
preset.skipLobby = false;
|
||||
preset.callIntent = "video";
|
||||
preset.callIntent = RTC_CALL_INTENT_VIDEO;
|
||||
break;
|
||||
case UserIntent.JoinExistingCall:
|
||||
// On desktop this will be overridden based on which button was used to join the call
|
||||
preset.skipLobby = false;
|
||||
preset.callIntent = "video";
|
||||
preset.callIntent = RTC_CALL_INTENT_VIDEO;
|
||||
break;
|
||||
case UserIntent.StartNewCallVoice:
|
||||
preset.skipLobby = false;
|
||||
preset.callIntent = "audio";
|
||||
preset.callIntent = RTC_CALL_INTENT_AUDIO;
|
||||
break;
|
||||
case UserIntent.JoinExistingCallVoice:
|
||||
// On desktop this will be overridden based on which button was used to join the call
|
||||
preset.skipLobby = false;
|
||||
preset.callIntent = "audio";
|
||||
preset.callIntent = RTC_CALL_INTENT_AUDIO;
|
||||
break;
|
||||
case UserIntent.StartNewCallDMVoice:
|
||||
preset.callIntent = "audio";
|
||||
preset.callIntent = RTC_CALL_INTENT_AUDIO;
|
||||
// Fall through
|
||||
case UserIntent.StartNewCallDM:
|
||||
preset.skipLobby = true;
|
||||
preset.sendNotificationType = "ring";
|
||||
preset.autoLeaveWhenOthersLeft = true;
|
||||
preset.waitForCallPickup = true;
|
||||
preset.callIntent = preset.callIntent ?? "video";
|
||||
preset.callIntent = preset.callIntent ?? RTC_CALL_INTENT_VIDEO;
|
||||
break;
|
||||
case UserIntent.JoinExistingCallDMVoice:
|
||||
preset.callIntent = "audio";
|
||||
preset.callIntent = RTC_CALL_INTENT_AUDIO;
|
||||
// Fall through
|
||||
case UserIntent.JoinExistingCallDM:
|
||||
// On desktop this will be overridden based on which button was used to join the call
|
||||
preset.skipLobby = true;
|
||||
preset.autoLeaveWhenOthersLeft = true;
|
||||
preset.callIntent = preset.callIntent ?? "video";
|
||||
preset.callIntent = preset.callIntent ?? RTC_CALL_INTENT_VIDEO;
|
||||
break;
|
||||
// Non widget usecase defaults
|
||||
default:
|
||||
|
||||
+10
-6
@@ -21,6 +21,10 @@ import {
|
||||
UserIntent,
|
||||
} from "../src/UrlParams";
|
||||
import { mockConfig } from "./utils/test";
|
||||
import {
|
||||
RTC_CALL_INTENT_AUDIO,
|
||||
RTC_CALL_INTENT_VIDEO,
|
||||
} from "matrix-js-sdk/lib/matrixrtc";
|
||||
|
||||
const ROOM_NAME = "roomNameHere";
|
||||
const ROOM_ID = "!d45f138fsd";
|
||||
@@ -275,7 +279,7 @@ describe("UrlParams", () => {
|
||||
).toMatchObject({
|
||||
...startNewCallDefaults("desktop"),
|
||||
skipLobby: false,
|
||||
callIntent: "video",
|
||||
callIntent: RTC_CALL_INTENT_VIDEO,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -322,7 +326,7 @@ describe("UrlParams", () => {
|
||||
).toMatchObject({
|
||||
...startNewCallDefaults("desktop"),
|
||||
skipLobby: false,
|
||||
callIntent: "audio",
|
||||
callIntent: RTC_CALL_INTENT_AUDIO,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -333,7 +337,7 @@ describe("UrlParams", () => {
|
||||
),
|
||||
).toMatchObject({
|
||||
...joinExistingCallDefaults("desktop"),
|
||||
callIntent: "audio",
|
||||
callIntent: RTC_CALL_INTENT_AUDIO,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -348,7 +352,7 @@ describe("UrlParams", () => {
|
||||
sendNotificationType: "ring",
|
||||
autoLeaveWhenOthersLeft: true,
|
||||
waitForCallPickup: true,
|
||||
callIntent: "audio",
|
||||
callIntent: RTC_CALL_INTENT_AUDIO,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -363,7 +367,7 @@ describe("UrlParams", () => {
|
||||
skipLobby: true,
|
||||
autoLeaveWhenOthersLeft: true,
|
||||
waitForCallPickup: false,
|
||||
callIntent: "video",
|
||||
callIntent: RTC_CALL_INTENT_VIDEO,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -377,7 +381,7 @@ describe("UrlParams", () => {
|
||||
skipLobby: true,
|
||||
autoLeaveWhenOthersLeft: true,
|
||||
waitForCallPickup: false,
|
||||
callIntent: "audio",
|
||||
callIntent: RTC_CALL_INTENT_AUDIO,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`Popover renders > button 1`] = `
|
||||
<button
|
||||
aria-controls="_r_0_"
|
||||
aria-expanded="true"
|
||||
aria-haspopup="dialog"
|
||||
data-base-ui-click-trigger=""
|
||||
data-popup-open=""
|
||||
id="base-ui-_r_1_"
|
||||
tabindex="0"
|
||||
type="button"
|
||||
>
|
||||
Open popover
|
||||
</button>
|
||||
`;
|
||||
|
||||
exports[`Popover renders > popover 1`] = `
|
||||
<div
|
||||
aria-labelledby="base-ui-_r_4_"
|
||||
class="_popover_8e8188"
|
||||
data-align="center"
|
||||
data-base-ui-focusable=""
|
||||
data-open=""
|
||||
data-side="bottom"
|
||||
id="_r_0_"
|
||||
role="dialog"
|
||||
tabindex="-1"
|
||||
>
|
||||
<h3
|
||||
class="_typography_6v6n8_153 _font-body-lg-semibold_6v6n8_74 _title_8e8188"
|
||||
id="base-ui-_r_4_"
|
||||
>
|
||||
Example
|
||||
</h3>
|
||||
<p>
|
||||
This is an example of a popover.
|
||||
</p>
|
||||
</div>
|
||||
`;
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
type MatrixClient,
|
||||
} from "matrix-js-sdk";
|
||||
|
||||
import { initClient } from "../utils/matrix";
|
||||
import { initClient } from "../utils/initClient";
|
||||
import { type Session } from "../ClientContext";
|
||||
/**
|
||||
* This provides the login method to login using user credentials.
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
} from "matrix-js-sdk";
|
||||
import { logger } from "matrix-js-sdk/lib/logger";
|
||||
|
||||
import { initClient } from "../utils/matrix";
|
||||
import { initClient } from "../utils/initClient";
|
||||
import { type Session } from "../ClientContext";
|
||||
import { Config } from "../config/Config";
|
||||
import { useUrlParams } from "../UrlParams";
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user