Compare commits

..
Author SHA1 Message Date
ValereandClaude Opus 5.5 78d9a9eeb3 Describe what Low bandwidth mode does since revision 2
The switch said it stops all video, but screen shares now still come
in, at their lowest layer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 14:13:57 +01:00
ValereandClaude Opus 5.5 14301207d0 Move focus to the camera button after the indicator's Cancel
Cancel removes the indicator, and with it the focused button; focus
fell back to the page. It now lands on the camera button, the control
the mode was holding. The call view hands a ref to the camera's mute
button down through the footer.

Compound's Tooltip reads children.ref, which React 19 warns about once
in development now that the button has a ref.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 14:12:27 +01:00
ValereandClaude Opus 5.5 3036ddd16d Show the Low bandwidth mode indicator in the desktop picture-in-picture window
In Element Web's floating call window the indicator takes its own row
between the tile and the footer, as designed. Mobile's picture-in-picture
window shows no controls, so it still shows no indicator.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:19:50 +01:00
ValereandClaude Opus 5.5 3675d28300 Give the Low bandwidth mode indicator the design's drop shadow
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 11:53:07 +01:00
ValereandClaude Opus 5.5 c55d4992dd Update the end-to-end tests for Low bandwidth mode
The specs now turn the mode on from Video settings and off with the
indicator's Cancel, and check:

- the lobby's settings have no switch;
- a remote screen share is drawn and received during the mode, no wider
  than its low layer, while cameras are still not received;
- in Element Web's picture-in-picture the share is shown and the
  indicator is not;
- on a phone, Cancel gives the camera back.

The blank share and its exclusion from picture-in-picture are gone, and
so are the checks for them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 11:24:29 +01:00
ValereandClaude Opus 5.5 7f06d8dc62 Point the unavailable buttons to the indicator and Video settings
The camera and screen share buttons, and the camera shortcut, now say
how to turn Low bandwidth mode off where it can be turned off: Cancel on
the indicator, or the switch in Video settings. They no longer send the
user to Developer options.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 11:24:23 +01:00
ValereandClaude Opus 5.5 57ac7e4ca5 Show that Low bandwidth mode is on, with a way to turn it off
While the mode is on, the call shows a pill centred above its footer:
Compound's Toast, with the camera-off icon, "Low bandwidth mode" and a
Cancel button styled as an inline link. Cancel turns the mode off exactly
as the switch does, so the camera comes back as the user had it.

- It stays when the footer hides, at the footer's place.
- It is not shown in the picture-in-picture window, which has no room.
- Where the host hides the call's controls, it shows without Cancel.
- Turning the mode on is announced once through the call view's live
  region; the pill itself is not a live region, so that it is not read
  again each time the footer shows.

Element Call's own Toast is a centred, dismissable dialog for transient
messages, so it does not fit a standing indicator. Cancel is a native
button rather than Compound's Link, which is an anchor, and its
accessible name, "Cancel Low bandwidth mode", keeps the visible word.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 11:24:23 +01:00
ValereandClaude Opus 5.5 94b13c67ce Move the Low bandwidth mode switch to Video settings
The switch now sits in the Video tab, below the background blur, with
the call's other camera options. The settings modal shows it only when
it is given the call's switch view model: the call view passes one, the
lobby and the user menu do not, so the switch is offered during a call
only. The developer tab's row, and the null it carried outside a call,
are removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 11:19:24 +01:00
ValereandClaude Opus 5.5 b1f18fd516 Describe the default low screen-share layer in the config
screen_share.simulcast_layers now replaces the SDK's low layer for Low
bandwidth mode, not LiveKit's half-resolution one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 11:14:30 +01:00
ValereandClaude Opus 5.5 9d40223198 Send a low screen-share layer fit for Low bandwidth mode
Every screen share is now published with one low layer of 960×540 at
15 fps and 625 kbps, alongside its full quality, whether or not anyone in
the call is in Low bandwidth mode. That is the layer a member in the mode
receives. Before, LiveKit derived the low layer from the top one: half
its size, at its frame rate, with a cap of about 1.25 Mbps for a 1080p
share.

These are the lab's first candidate for R22; the contract has no numbers
yet, so they are provisional and held in one constant. A deployment's
screen_share.simulcast_layers still replaces them. The advanced screen
share settings change the top encoding and the codec only, so VP8 and
H.264 shares keep this layer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 11:14:29 +01:00
ValereandClaude Opus 5.5 8d4e6975b2 Show screen shares as usual in Low bandwidth mode
A remote screen share is now received at its lowest layer during the
mode, so its tile draws it as it does any other time. This removes what
drew it blank:

- videoPaused$ on the remote screen share view model;
- MediaView's placeholder "none", and the spotlight's use of it;
- keeping the share out of the picture-in-picture window, which only
  made sense for a blank tile.

Camera tiles keep the camera-off look.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 11:13:18 +01:00
ValereandClaude Opus 5.5 afd90d7619 Receive screen shares at their lowest layer in Low bandwidth mode
While a participation does not receive video, every connection now keeps
remote screen shares subscribed and asks for their lowest layer, instead
of unsubscribing them. Cameras are still unsubscribed. Turning video back
on asks for the highest layer again, which behaves as LiveKit's default:
adaptive stream can still lower it for a small tile.

The quality is set after subscribing, because LiveKit ignores
setVideoQuality on a publication that is not subscribed. It is applied on
every sweep, so a share recreated by a full reconnect is capped again.

SDK API behaviour change: setReceiveVideo(false) now caps screen shares
rather than dropping them. The signatures are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 11:12:10 +01:00
ValereandClaude Opus 5.5 43710aeaa4 Add end-to-end tests for sending no video
Standalone, our camera goes off for us and for the other member while
the mode is on, and comes back when it is turned off. In Element Web, a
screen share started before the mode stops when it comes on, the share
button then looks unavailable, and leaving the room puts the call in
Element Web's picture-in-picture showing an avatar rather than the blank
share. On a phone, a tap on the camera button shows why it stays off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:17:21 +01:00
ValereandClaude Opus 5.5 6cc56d3613 Say why the camera and screen share are unavailable
In Low bandwidth mode the camera and screen-share buttons look
unavailable without being disabled. Compound's disabled drops the
click, and a tap is the only way a touch screen has to ask why. A
controlled tooltip gives the reason on hover, focus and activation. The
reason is the button's aria-describedby, and activating the button reads
it out through a polite live region. Activation never turns the camera
on, starts a share or turns the mode off. V says the same through the
call view's live region. The reason names developer options only.

The camera menu reports why it can't be turned on (unavailableReason),
and the footer whether a screen share can start
(screenShareUnavailable). Stories cover desktop and mobile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:17:14 +01:00
ValereandClaude Opus 5.5 24592744df Send no video in Low bandwidth mode
The mode now holds our camera off through MuteStates and gives the
user's choice back afterwards. Turning it on saves the camera choice
from chosen$; turning it off releases the hold and turns the camera back
on through the normal path if it was chosen on. The host turning the
camera off during the mode makes the saved choice off. bind() follows
mute states that are rebuilt.

A screen share in progress stops when the mode comes on and is not
restarted afterwards: a new share needs the user to pick a screen again.
None can start while the mode is on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:16:25 +01:00
ValereandClaude Opus 5.5 30227a6a05 Hold the camera off and keep the user's choice in MuteStates
holdVideoOff(held) joins earpiece mode as the camera's force-mute: while
held the handler gets false and every way of turning the camera on is
closed, the host's device_mute included. chosen$ keeps the user's last
request through a force-mute and a pending handler; a camera that comes
back after one comes back off, and that becomes the choice.
hostVideoOff$ reports the host turning the camera off while it is held.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:15:40 +01:00
ValereandClaude Opus 5.5 c18ced6455 Add end-to-end tests for receiving no video
Two users in a standalone call. The browser's own statistics show no
inbound video while the mode is on, a remote screen share stays on the
stage blank, video comes back when it is turned off, and the time to the
first picture is recorded. With the mode on, a reconnection brings no
video back, and the switch can be turned off over the reconnecting
backdrop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:14:10 +01:00
ValereandClaude Opus 5.5 c2cedb343f Add the Low bandwidth mode switch to the developer options
A checkbox in the call's Developer tab, offered only in a call: the
out-of-call tab used by the lobby and the user menu has none. Its
description says the mode lasts for this call, unlike the stored
settings beside it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:14:00 +01:00
ValereandClaude Opus 5.5 79746ba64d Receive no video in Low bandwidth mode
CallView holds the mode, so it survives the Reconnect after a failed
call; the lobby resets it for every new call. While it is on:

- the participation receives no remote video, through setReceiveVideo,
  and a Reconnect joins with receiveVideo off;
- remote camera tiles take the camera-off look, with no mark;
- a remote screen share keeps its place on the stage, drawn without its
  picture and without the sharer's avatar (MediaView placeholder
  "none"), and stays out of the small picture-in-picture window.

Our own camera and screen share are not touched yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:13:31 +01:00
ValereandClaude Opus 5.5 8bed69aa36 Add a per-call Low bandwidth mode
LowBandwidthMode is the state of the call in progress, never a stored
setting: on or off, and reset() for a new call. The developer switch and,
later, 054's hint turn it on and off; it is not gated on developer mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:12:43 +01:00
ValereandClaude Opus 5.5 6623576dc7 Let a participation stop receiving remote video
RTCParticipation.setReceiveVideo(receive), and receiveVideo on
RTCParticipationOptions for the value in force before the first
connection. The LiveKit backend hands the choice to every connection its
factory makes, so transports connected later and connections rebuilt
after a focus switch follow it too.

A connection made while video is not received connects with
autoSubscribe: false. Every connection then keeps each remote
publication subscribed or not as the choice asks, on TrackPublished,
ParticipantConnected, Connected, Reconnected and on every change of the
choice. Audio, including a screen share's, always stays subscribed.

Unsubscribing rather than RemoteTrackPublication.setEnabled(false):
setEnabled(true) leaves a manual override that disables adaptive stream
for that track for the rest of the call, and livekit-client offers no
way to clear it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:03:54 +01:00
148 changed files with 5193 additions and 4092 deletions
+10 -2
View File
@@ -1,14 +1,22 @@
name: Prevent blocked
on:
pull_request:
# zizmor: ignore[dangerous-triggers]
# Reason: This workflow does not checkout code or use secrets.
# It only reads labels to set a failure status on the PR.
pull_request_target:
types: [opened, labeled, unlabeled, synchronize]
permissions: {}
permissions:
pull-requests: read
# Required to fail the check on the PR
statuses: write
jobs:
prevent-blocked:
name: Prevent blocked
runs-on: ubuntu-24.04
permissions:
pull-requests: read
steps:
- name: Add notice
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
+2 -12
View File
@@ -7,7 +7,7 @@ on:
type: string
package:
type: string # This would ideally be a `choice` type, but that isn't supported yet
description: The package type to be built. Must be one of 'full', 'embedded', 'widget-rtc-sdk' or 'component'
description: The package type to be built. Must be one of 'full', 'embedded', or 'widget-rtc-sdk'
required: true
build_mode:
type: string # This would ideally be a `choice` type, but that isn't supported yet
@@ -59,21 +59,11 @@ jobs:
NODE_OPTIONS: "--max-old-space-size=4096"
PACKAGE: ${{ inputs.package }}
BUILD_MODE: ${{ inputs.build_mode }}
- name: Pack component
# A tarball a host installs like the npm release. Stripped as in
# publish-component.yaml, so the install does not run `prepare` and
# rebuild it.
if: inputs.package == 'component'
working-directory: component
run: |
jq 'del(.devEngines, .scripts)' package.json > package.json.tmp && mv package.json.tmp package.json
mkdir -p ../component-pack
npm pack --pack-destination ../component-pack
- name: Upload Artifact
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: build-output-${{ inputs.package }}
path: ${{ inputs.package == 'component' && 'component-pack' || 'dist' }}
path: dist
if-no-files-found: error
# We'll only use this in a triggered job, then we're done with it
retention-days: 1
-113
View File
@@ -1,113 +0,0 @@
# Element Web develop with this commit's component in place of the npm release
# it pins, and the component embedding forced on. Deployed to
# element-web--element-call.netlify.app by deploy_element_web_with_ec_component
# for main, and to pr<N>-element-web--element-call.netlify.app by pr-deploy.yaml.
#
# A workflow of its own rather than part of Build: pr-deploy.yaml runs once per
# finished workflow, so the Element Call previews do not wait for this slower
# build, and a broken Element Web develop does not hold them back.
name: Build Element Web
on:
pull_request:
types:
- synchronize
- opened
- labeled
push:
branches: [main]
permissions: {}
# A newer push to a PR cancels its running build. A label event that builds
# nothing gets a group of its own: concurrency applies before the jobs' `if`,
# so in the PR's group it would cancel a real build and then skip.
concurrency:
group: ${{ github.workflow }}-${{ (github.event.action == 'labeled' && github.event.label.name != 'development build') && github.run_id || github.event.pull_request.number || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
build_component_element_call:
# The React component package, as a tarball for build_element_web_with_ec_component
# Of the labels only `development build` changes the build
if: github.event.action != 'labeled' || github.event.label.name == 'development build'
permissions:
contents: read
uses: $/.github/workflows/build-element-call.yaml
with:
package: component
vite_app_version: ${{ github.sha }}
build_mode: ${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'development build') && 'development' || 'production' }}
secrets:
SENTRY_ORG: ${{ secrets.SENTRY_ORG }}
SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }}
SENTRY_URL: ${{ secrets.SENTRY_URL }}
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
build_element_web_with_ec_component:
# The steps follow the prepare job of Element Web's build-and-test.yaml.
name: Build Element Web with the Element Call component
needs: build_component_element_call
runs-on: ubuntu-24.04
permissions:
contents: read
steps:
- name: Checkout Element Web
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
with:
repository: element-hq/element-web
ref: develop
persist-credentials: false
# Also installs the Node of Element Web's .node-version
- uses: pnpm/setup@731dfb6463bbd11c11fd0ee11fe00ed0e36d48a1 # v3.2.0
with:
cache: true
save-cache: false
install: false
- name: Fetch layered build
id: layered
run: |
./scripts/layered.sh
VERSION=$(scripts/get-version-from-git.sh)
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
- name: Download the component
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
name: build-output-component
path: ec-component
- name: Install the component
# The same tarball install Element Web's layered.sh does for matrix-js-sdk
run: pnpm -C apps/web install "$PWD"/ec-component/*.tgz
- name: Write config
# The setting prefers the config's value, so this forces it on
working-directory: apps/web
run: jq '.features.feature_element_call_react = true' element.io/develop/config.json > config.json
- name: Build
env:
CI_PACKAGE: true
VERSION: ${{ steps.layered.outputs.version }}
working-directory: apps/web
run: pnpm run build
- name: Upload Artifact
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: build-output-element-web-with-ec-component
path: apps/web/webapp
if-no-files-found: error
# We'll only use this in a deploy job, then we're done with it
retention-days: 1
deploy_element_web_with_ec_component:
# PRs are deployed by pr-deploy.yaml, which keeps the secrets away from PR code
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
needs: build_element_web_with_ec_component
permissions:
deployments: write
uses: $/.github/workflows/deploy-to-netlify.yaml
with:
package: element-web-with-ec-component
deployment_ref: ${{ github.sha }}
secrets:
ELEMENT_BOT_TOKEN: ${{ secrets.ELEMENT_BOT_TOKEN }}
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
+7 -2
View File
@@ -1,10 +1,15 @@
name: PR changelog label
on:
pull_request:
# zizmor: ignore[dangerous-triggers]
# This is safe because we do not use actions/checkout or execute untrusted code.
# Using pull_request_target is necessary to allow status writes for PRs from forks.
pull_request_target:
types: [labeled, unlabeled, opened, synchronize]
permissions: {}
permissions:
pull-requests: read
statuses: write
jobs:
pr-changelog-label:
+1 -4
View File
@@ -14,8 +14,6 @@ jobs:
# 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-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
@@ -100,8 +98,7 @@ jobs:
Use Markdown links for anything that can be navigated to on GitHub such
as files, commits, issues, pull requests, workflow runs, etc.
# Set a generous turn limit. It's bounded by timeout-minutes above.
claude_args: |
--model claude-fable-5-1
--allowedTools "mcp__github_inline_comment__create_inline_comment,Bash(git log:*),Bash(git diff:*),Bash(git show:*)"
--max-turns 150
--max-turns 50
+8 -14
View File
@@ -2,17 +2,14 @@ name: Deploy to Netlify
on:
workflow_call:
inputs:
# Optional so that main can deploy element-web-with-ec-component,
# which then uses the alias `element-web`. Every other package needs
# pr_number (for its alias) and full needs pr_head_* (for its config).
pr_number:
required: false
required: true
type: string
pr_head_full_name:
required: false
required: true
type: string
pr_head_ref:
required: false
required: true
type: string
deployment_ref:
required: true
@@ -20,7 +17,7 @@ on:
package:
required: true
type: string
description: Which package to deploy - 'full', 'embedded', 'widget-rtc-sdk', 'storybook' or 'element-web-with-ec-component'
description: Which package to deploy - 'full', 'embedded', 'widget-rtc-sdk', or 'storybook'
artifact_run_id:
required: false
type: string
@@ -62,9 +59,8 @@ jobs:
- name: Add redirects file
# We fetch from github directly as we don't bother checking out the repo
# Not needed for storybook deployments, nor for Element Web, which
# routes with the URL fragment
if: inputs.package != 'storybook' && inputs.package != 'element-web-with-ec-component'
# Not needed for storybook deployments
if: inputs.package != 'storybook'
run: curl -s https://raw.githubusercontent.com/element-hq/element-call/main/config/netlify_redirects > webapp/_redirects
- name: Add config file
@@ -88,13 +84,11 @@ jobs:
with:
publish-dir: webapp
deploy-message: "Deploy from GitHub Actions"
# Element Web with the component deploys for main too, without a PR number
alias: ${{ inputs.package == 'widget-rtc-sdk' && format('pr{0}-widget-rtc-sdk', inputs.pr_number) || inputs.package == 'storybook' && format('pr{0}-storybook', inputs.pr_number) || inputs.package == 'element-web-with-ec-component' && (inputs.pr_number && format('pr{0}-element-web', inputs.pr_number) || 'element-web') || format('pr{0}', inputs.pr_number) }}
alias: ${{ inputs.package == 'widget-rtc-sdk' && format('pr{0}-widget-rtc-sdk', inputs.pr_number) || inputs.package == 'storybook' && format('pr{0}-storybook', inputs.pr_number) || format('pr{0}', inputs.pr_number) }}
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
# Element Web has many times the files of Element Call to upload
timeout-minutes: ${{ inputs.package == 'element-web-with-ec-component' && 10 || 1 }}
timeout-minutes: 1
- name: 🚦 Update deployment status
uses: bobheadxi/deployments@648679e8e4915b27893bd7dbc35cb504dc915bc8 # v1
+4 -47
View File
@@ -2,10 +2,8 @@ name: Deploy previews for PRs
on:
# zizmor: ignore[dangerous-triggers]
# Reason: This is now restricted to internal PRs only using the 'if' condition below.
# Runs once per finished workflow, and deploys only what that workflow built,
# so each preview goes up as soon as its own build is done
workflow_run:
workflows: ["Build", "Build Element Web"]
workflows: ["Build"]
types:
- completed
@@ -14,7 +12,7 @@ permissions: {}
jobs:
prdetails:
# Logic:
# 1. The build workflow must be successful
# 1. Build must be successful
# 2. Event must be a pull_request
# 3. Head repository must be the SAME as the base repository (No Forks!)
if: >
@@ -36,7 +34,6 @@ jobs:
branch: ${{ github.event.workflow_run.head_branch }}
netlify-full:
if: github.event.workflow_run.name == 'Build'
needs: prdetails
permissions:
deployments: write
@@ -54,7 +51,6 @@ jobs:
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
netlify-widget-rtc-sdk:
if: github.event.workflow_run.name == 'Build'
needs: prdetails
permissions:
deployments: write
@@ -71,48 +67,9 @@ jobs:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
element-web-built:
# A Build Element Web run started by a label it ignores skips every job
# and uploads nothing to deploy
if: github.event.workflow_run.name == 'Build Element Web'
needs: prdetails
runs-on: ubuntu-24.04
permissions:
actions: read
outputs:
built: ${{ steps.check.outputs.built }}
steps:
- id: check
env:
GH_TOKEN: ${{ github.token }}
RUN_ID: ${{ github.event.workflow_run.id }}
run: |
count=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$RUN_ID/artifacts?name=build-output-element-web-with-ec-component" --jq '.total_count')
if [ "$count" -gt 0 ]; then built=true; else built=false; fi
echo "built=$built" >> "$GITHUB_OUTPUT"
netlify-element-web-with-ec-component:
# Element Web with this PR's component
if: needs.element-web-built.outputs.built == 'true'
needs: [prdetails, element-web-built]
permissions:
deployments: write
uses: $/.github/workflows/deploy-to-netlify.yaml
with:
artifact_run_id: ${{ github.event.workflow_run.id || github.run_id }}
pr_number: ${{ needs.prdetails.outputs.pr_number }}
pr_head_full_name: ${{ github.event.workflow_run.head_repository.full_name }}
pr_head_ref: ${{ needs.prdetails.outputs.pr_data_json && fromJSON(needs.prdetails.outputs.pr_data_json).head.ref }}
deployment_ref: ${{ needs.prdetails.outputs.pr_data_json && fromJSON(needs.prdetails.outputs.pr_data_json).head.sha || github.ref || github.head_ref }}
package: element-web-with-ec-component
secrets:
ELEMENT_BOT_TOKEN: ${{ secrets.ELEMENT_BOT_TOKEN }}
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
netlify-storybook:
needs: prdetails
if: ${{ github.event.workflow_run.name == 'Build' && needs.prdetails.outputs.pr_data_json && contains(fromJSON(needs.prdetails.outputs.pr_data_json).labels.*.name, 'storybook build') }}
if: ${{ needs.prdetails.outputs.pr_data_json && contains(fromJSON(needs.prdetails.outputs.pr_data_json).labels.*.name, 'storybook build') }}
permissions:
deployments: write
uses: $/.github/workflows/deploy-to-netlify.yaml
@@ -129,7 +86,7 @@ jobs:
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
docker:
if: ${{ github.event.workflow_run.name == 'Build' && needs.prdetails.outputs.pr_data_json && contains(fromJSON(needs.prdetails.outputs.pr_data_json).labels.*.name, 'docker build') }}
if: ${{ needs.prdetails.outputs.pr_data_json && contains(fromJSON(needs.prdetails.outputs.pr_data_json).labels.*.name, 'docker build') }}
needs: prdetails
permissions:
contents: write
@@ -156,9 +156,7 @@ jobs:
publish_android:
needs: [build_element_call, versioning]
# Release candidates are not published to Maven Central: the organisation's Central account
# has a monthly release quota, and Element X Android (the only consumer) ships final releases.
if: always() && needs.versioning.outputs.TAG != 'rc'
if: always()
name: Publish Android AAR
runs-on: ubuntu-24.04
outputs:
@@ -190,6 +188,8 @@ jobs:
run: |
if [[ "${NEEDS_VERSIONING_OUTPUTS_TAG}" == "latest" ]]; then
echo "ARTIFACT_VERSION=${NEEDS_VERSIONING_OUTPUTS_UNPREFIXED_VERSION}" >> "$GITHUB_ENV"
elif [[ "${NEEDS_VERSIONING_OUTPUTS_TAG}" == "rc" ]]; then
echo "ARTIFACT_VERSION=${NEEDS_VERSIONING_OUTPUTS_UNPREFIXED_VERSION}" >> "$GITHUB_ENV"
else
echo "ARTIFACT_VERSION=${NEEDS_VERSIONING_OUTPUTS_UNPREFIXED_VERSION}-SNAPSHOT" >> "$GITHUB_ENV"
fi
@@ -338,7 +338,11 @@ jobs:
### Android AAR
${{ needs.publish_android.outputs.ARTIFACT_VERSION && format('`implementation ''io.element.android:element-call-embedded:{0}''`', needs.publish_android.outputs.ARTIFACT_VERSION) || 'Not published: release candidates do not go to Maven Central.' }}
```
dependencies {
implementation 'io.element.android:element-call-embedded:${{ needs.publish_android.outputs.ARTIFACT_VERSION }}'
}
```
### SwiftPM
+1 -1
View File
@@ -1 +1 @@
26
24
Binary file not shown.
+11 -61
View File
@@ -22,21 +22,13 @@ const LabelledButton = (): ReactNode => (
</TooltipProvider>
);
/** The container of Element Call's own that the button's tooltip floated into. */
const labelPortal = (): Element | null => {
const button = screen.getByRole("button", { name: "Microphone" });
return document
.getElementById(button.getAttribute("aria-labelledby")!)!
.closest("[data-element-call-portal]");
};
test("floats into the host document with no root", () => {
render(
<CallPortalRoot root={undefined}>
<LabelledButton />
</CallPortalRoot>,
);
expect(labelPortal()?.parentElement).toBe(document.body);
expect(screen.getByRole("button", { name: "Microphone" })).toBeTruthy();
});
test("floats into the root it is given", () => {
@@ -47,61 +39,19 @@ test("floats into the root it is given", () => {
<LabelledButton />
</CallPortalRoot>,
);
// Into a container of Element Call's own, for its stylesheets to find
expect(labelPortal()?.parentElement).toBe(root);
const button = screen.getByRole("button", { name: "Microphone" });
const label = document.getElementById(
button.getAttribute("aria-labelledby")!,
);
expect(root.contains(label)).toBe(true);
root.remove();
});
test("moves what floated along when the root changes", () => {
const first = document.createElement("div");
const second = document.createElement("div");
document.body.append(first, second);
const { rerender, unmount } = render(
<CallPortalRoot root={first}>
<LabelledButton />
</CallPortalRoot>,
);
rerender(
<CallPortalRoot root={second}>
<LabelledButton />
</CallPortalRoot>,
);
expect(first.querySelector("[data-element-call-portal]")).toBeNull();
expect(labelPortal()?.parentElement).toBe(second);
unmount();
expect(second.querySelector("[data-element-call-portal]")).toBeNull();
first.remove();
second.remove();
});
test("waits for a root that is not available yet", () => {
// Floated content mounted off the page would not show up in the document,
// so record every mount of the tooltip's content, wherever it happens
const mounted: HTMLElement[] = [];
const probe = (
<span
ref={(node) => {
if (node) mounted.push(node);
}}
/>
render(
<CallPortalRoot root={null}>
<LabelledButton />
</CallPortalRoot>,
);
const button = (
<TooltipProvider>
<Tooltip label="Microphone" caption={probe}>
<button>🎤</button>
</Tooltip>
</TooltipProvider>
);
const { rerender } = render(
<CallPortalRoot root={null}>{button}</CallPortalRoot>,
);
expect(mounted).toEqual([]);
expect(document.querySelector("[data-element-call-portal]")).toBeNull();
const root = document.createElement("div");
document.body.appendChild(root);
rerender(<CallPortalRoot root={root}>{button}</CallPortalRoot>);
expect(mounted.at(-1)?.isConnected).toBe(true);
expect(labelPortal()?.parentElement).toBe(root);
root.remove();
expect(screen.queryByRole("button", { name: "Microphone" })).toBeNull();
});
+9 -37
View File
@@ -5,50 +5,22 @@ 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 ReactNode, useLayoutEffect, useState } from "react";
import { type FC, type ReactNode } from "react";
import { PortalRoot } from "@vector-im/compound-web";
import { PortalElementProvider } from "../src/RootElementContext";
interface Props {
root: HTMLElement | null | undefined;
children: ReactNode;
}
/**
* Where Compound floats the call's menus and tooltips: a container of Element
* Call's own inside `root`, or inside the host document's body with no `root`.
* With `null`, the root is not available yet: Compound gets `null` too and
* floats nothing until it is.
*
* The container is marked `data-element-call-portal` and carries the call's
* theme and platform (see `useTheme`), so that Element Call's stylesheets reach
* what floats out of its root just as they reach what stays inside.
* Where Compound floats the call's menus and tooltips. With no `root` the call
* is not wrapped at all and they go into the host document's body; `null` is
* Compound's "not available yet", and the floating parts wait for it.
*/
export const CallPortalRoot: FC<Props> = ({ root, children }): ReactNode => {
// One container for the call's lifetime, moved to wherever the root is.
// What Compound has floated into it moves along, even into another
// document such as a Picture-in-Picture window's; Compound itself leaves
// what it floated where it was when its root changes.
const [container] = useState(() => {
const element = document.createElement("div");
element.setAttribute("data-element-call-portal", "");
return element;
});
useLayoutEffect(() => {
const parent = root === undefined ? document.body : root;
// Left out of the document until the root is available
if (parent === null) return;
parent.append(container);
return (): void => container.remove();
}, [root, container]);
return (
<PortalRoot root={root === null ? null : container}>
<PortalElementProvider value={container}>
{children}
</PortalElementProvider>
</PortalRoot>
export const CallPortalRoot: FC<Props> = ({ root, children }): ReactNode =>
root === undefined ? (
children
) : (
<PortalRoot root={root}>{children}</PortalRoot>
);
};
+2 -2
View File
@@ -40,8 +40,8 @@ and overlays stay below the modals and toasts, which are portalled into the
root and carry no layer of their own.
What Compound floats — tooltips, menus — is not in here at all: it goes into
Element Call's portal container in the host's `portalRoot` (see
CallPortalRoot), where Element Call's scoped stylesheets still reach it. */
the host's body, as it would for any other component on the host's page, and is
styled and layered by the host's copy of Compound. */
.content {
display: flex;
flex-direction: column;
+2 -6
View File
@@ -156,12 +156,8 @@ export interface ElementCallProps {
/**
* Where the parts of Element Call that float above it — its menus and
* tooltips, which Compound portals out of the call — are rendered. Left out,
* the host document's body.
*
* Element Call does not render them into this element directly: each mounted
* call adds its own `div[data-element-call-portal]` here and floats into
* that. The container carries the call's theme class, and Element Call's
* scoped stylesheets reach it just as they reach the call's root.
* they go into the host document's body, as they do for any other component
* on the host's page.
*
* A host that moves Element Call's DOM into another document, such as a
* Document Picture-in-Picture window, passes that document's body here so
+6 -24
View File
@@ -8,15 +8,10 @@ Please see LICENSE in the repository root for full details.
import { describe, expect, it } from "vitest";
import postcss from "postcss";
import {
PORTAL_SELECTOR,
ROOT_SELECTOR,
scopeStylesToRoot,
} from "./scopeStylesToRoot";
import { ROOT_SELECTOR, scopeStylesToRoot } from "./scopeStylesToRoot";
const inRoot = `:where(${ROOT_SELECTOR}, ${ROOT_SELECTOR} *, ${PORTAL_SELECTOR}, ${PORTAL_SELECTOR} *)`;
const inRoot = `:where(${ROOT_SELECTOR}, ${ROOT_SELECTOR} *)`;
const isRoot = `:where(${ROOT_SELECTOR})`;
const isRootOrPortal = `:where(${ROOT_SELECTOR}, ${PORTAL_SELECTOR})`;
async function scope(css: string, file = "base.css"): Promise<string> {
const result = await postcss([scopeStylesToRoot()]).process(css, {
@@ -31,10 +26,7 @@ describe("scopeStylesToRoot", () => {
`${isRoot} { line-height: 1.15 }`,
);
expect(await scope("body { margin: 0 }")).toBe(`${isRoot} { margin: 0 }`);
// The custom properties are needed by what floats out of the root too
expect(await scope(":root { --a: 1 }")).toBe(
`${isRootOrPortal} { --a: 1 }`,
);
expect(await scope(":root { --a: 1 }")).toBe(`${isRoot} { --a: 1 }`);
expect(await scope("body.no-scroll-body { position: fixed }")).toBe(
`${isRoot}.no-scroll-body { position: fixed }`,
);
@@ -74,11 +66,9 @@ describe("scopeStylesToRoot", () => {
);
});
it("leaves alone what already names the root or the portal", async () => {
it("leaves alone what already names the root", async () => {
const css = `${ROOT_SELECTOR}[data-platform="ios"] { --a: 1 }`;
expect(await scope(css)).toBe(css);
const portal = `${PORTAL_SELECTOR}[data-platform="ios"] { --a: 1 }`;
expect(await scope(portal)).toBe(portal);
});
it("reaches into layers and media queries", async () => {
@@ -109,8 +99,8 @@ describe("scopeStylesToRoot", () => {
expect(await scope("pre { font-size: 1px }", file)).toBe(
`pre${inRoot} { font-size: 1px }`,
);
expect(await scope("[data-x] pre { font-size: 1px }", file)).toBe(
`[data-x] pre${inRoot} { font-size: 1px }`,
expect(await scope(".modal pre { font-size: 1px }", file)).toBe(
`.modal pre${inRoot} { font-size: 1px }`,
);
expect(await scope(".box_abc12 { border: 0 }", file)).toBe(
".box_abc12 { border: 0 }",
@@ -118,14 +108,6 @@ describe("scopeStylesToRoot", () => {
expect(await scope(".a .b_abc12:hover { border: 0 }", file)).toBe(
".a .b_abc12:hover { border: 0 }",
);
// Confined by the class on an ancestor: these must still match in a menu
// that Compound portals out of the root
expect(await scope(".preview_abc12>video { inset: 0 }", file)).toBe(
".preview_abc12>video { inset: 0 }",
);
expect(
await scope(".menu_abc12 [role^=menuitem]:focus { outline: 0 }", file),
).toBe(".menu_abc12 [role^=menuitem]:focus { outline: 0 }");
});
it("leaves an excluded stylesheet as it is", async () => {
+14 -37
View File
@@ -24,27 +24,16 @@ import selectorParser, {
*/
export const ROOT_SELECTOR = "[data-element-call-root]";
/**
* How the stylesheets find the container that Element Call's menus and
* tooltips float into, outside the root. `CallPortalRoot` creates it in the
* host's document; it counts as Element Call's own, the way the root does.
*/
export const PORTAL_SELECTOR = "[data-element-call-portal]";
// Both are `:where()`, which has no specificity of its own, so the rules keep
// exactly the weight they had before being scoped and nothing in Element Call's
// cascade changes — only where it applies.
//
// The root or the portal container, or anything inside either. Appended to the
// element a rule is about, rather than prepended to the whole selector, so that
// a rule about the root itself (its theme class, say) still matches.
const IN_ROOT = `:where(${ROOT_SELECTOR}, ${ROOT_SELECTOR} *, ${PORTAL_SELECTOR}, ${PORTAL_SELECTOR} *)`;
// The root itself, standing in for the document's `html` and `body`. The page's
// own furniture (its height, margin and background) is not the portal's.
// The root, or anything inside it. Appended to the element a rule is about,
// rather than prepended to the whole selector, so that a rule about the root
// itself (its theme class, say) still matches.
const IN_ROOT = `:where(${ROOT_SELECTOR}, ${ROOT_SELECTOR} *)`;
// The root itself, standing in for the document.
const IS_ROOT = `:where(${ROOT_SELECTOR})`;
// The root and the portal container, standing in for `:root`: the custom
// properties declared there are needed by whatever floats out of the root too.
const IS_ROOT_OR_PORTAL = `:where(${ROOT_SELECTOR}, ${PORTAL_SELECTOR})`;
/**
* Confines a stylesheet to Element Call's root element, for the build of
@@ -56,22 +45,15 @@ const IS_ROOT_OR_PORTAL = `:where(${ROOT_SELECTOR}, ${PORTAL_SELECTOR})`;
* the host's document too. This rewrites every selector so that it matches only
* the root or its descendants:
*
* - `html` and `body` become the root element, which is what stands in for the
* document inside a host. `:root` becomes the root and the portal container
* (see `PORTAL_SELECTOR`), so that its custom properties reach both.
* - `html`, `body` and `:root` become the root element, which is what stands in
* for the document inside a host.
* - Everything else keeps its selector and gains `:where([data-element-call-root],
* [data-element-call-root] *, [data-element-call-portal],
* [data-element-call-portal] *)` on the element it styles, so that it applies
* to the menus and tooltips Compound floats out of the root as well.
* - Selectors that already name the root or the portal container are left
* alone, as are keyframe selectors and rules nested inside another rule,
* which are relative to it.
* [data-element-call-root] *)` on the element it styles.
* - Selectors that already name the root are left alone, as are keyframe
* selectors and rules nested inside another rule, which are relative to it.
*
* CSS modules are scoped by their class names already, so only their selectors
* without a class anywhere — `pre`, but neither `.pre` nor `.modal pre` — are
* touched. A module class on an ancestor confines a rule as well as one on the
* element it styles, and scoping such a rule would break it wherever Compound
* portals that part of Element Call out of the root, as it does menus.
* that would match by element alone — `pre` rather than `.pre` — are touched.
*
* The root's custom properties are still inherited by everything inside it,
* the way they were from `:root`. Compound's own stylesheet — the design
@@ -135,8 +117,7 @@ const scopeAll = processor(false);
const scopeBare = processor(true);
function scopeSelector(selector: Selector, isModule: boolean): void {
const text = String(selector);
if (text.includes(ROOT_SELECTOR) || text.includes(PORTAL_SELECTOR)) return;
if (String(selector).includes(ROOT_SELECTOR)) return;
const compounds = splitCompounds(selector);
if (compounds.length === 0) return;
@@ -144,16 +125,12 @@ function scopeSelector(selector: Selector, isModule: boolean): void {
// Something said of the document is said of the root instead
const document = compounds[0].find(isDocumentSelector);
if (document !== undefined) {
document.replaceWith(
pseudo(document.value === ":root" ? IS_ROOT_OR_PORTAL : IS_ROOT),
);
document.replaceWith(pseudo(IS_ROOT));
return;
}
if (isModule && compounds.some((c) => c.some((n) => n.type === "class")))
return;
const subject = compounds.at(-1)!;
if (isModule && subject.some((node) => node.type === "class")) return;
// Pseudo-elements have to come last in a compound selector
const pseudoElement = subject.find(isPseudoElement);
-41
View File
@@ -1,41 +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 js-sdk for the component: the package's own entry points
* (`lib/index.js`, `lib/browser-index.js`) throw when the host's copy has
* already loaded one, and `browser-index` also writes the host's globals.
* `lib/matrix` is the same API without either. The client this exports
* refuses the few calls that would collide with the host's js-sdk: a sync
* loop, crypto, and the IndexedDB stores both would open by the same name.
*/
import { IndexedDBStore, MatrixClient } from "matrix-js-sdk/lib/matrix";
function refuse<C extends { prototype: object }>(
cls: C,
name: string,
methods: (keyof C["prototype"] & string)[],
): void {
for (const method of methods)
Object.defineProperty(cls.prototype, method, {
value() {
throw new Error(
`${name}.${method} is not available in the Element Call component: the host's client does this`,
);
},
});
}
refuse(MatrixClient, "MatrixClient", [
"startClient",
"initRustCrypto",
"clearStores",
]);
refuse(IndexedDBStore, "IndexedDBStore", ["startup"]);
export * from "matrix-js-sdk/lib/matrix";
+4 -5
View File
@@ -25,11 +25,10 @@ Please see LICENSE in the repository root for full details.
//
// Compound is not in here. The component uses the host's copy of it (a peer
// dependency, left external by the build), and the host loads Compound's
// stylesheet, design tokens and fonts along with it. Element Call's root takes
// the tokens and fonts of the theme class it carries, as any element on the
// host's page would. What Compound floats out of the root — tooltips, menus —
// goes into Element Call's portal container (see CallPortalRoot), which carries
// the same theme class and is reached by the same scoped stylesheets.
// stylesheet, design tokens and fonts along with it: what Compound floats into
// the host's body — tooltips, menus — is then styled by the same stylesheet as
// everything else there, and Element Call's root takes the tokens and fonts of
// the theme class it carries, as any element on the host's page would.
//
// Where these land relative to the component stylesheets is the bundler's
// choice — the standalone app puts them first, this build puts them in the
+2 -3
View File
@@ -34,15 +34,14 @@
"./style.css": "./dist/element-call.css"
},
"sideEffects": [
"*.css",
"./guestJsSdk.ts"
"*.css"
],
"scripts": {
"prepare": "cd .. && pnpm install --frozen-lockfile && pnpm build:component"
},
"peerDependencies": {
"@vector-im/compound-design-tokens": "^11.0.0",
"@vector-im/compound-web": "^10.5.0",
"@vector-im/compound-web": "^10.3.1",
"react": "^19",
"react-dom": "^19"
}
+2 -2
View File
@@ -19,10 +19,10 @@ services:
- ./backend/playwright_homeserver-othersite.yaml:/data/cfg/homeserver.yaml:Z
element-web:
# Pin to a SHA so that upstream cannot break our tests. Renovate handles regular updates.
image: ghcr.io/element-hq/element-web:develop@sha256:5c9a8288deccb648e0d590776dff747ba674fe45c32cada6f804776800a38d2c
image: ghcr.io/element-hq/element-web:develop@sha256:58b673f867f78fe83c08f2b688b254e34625ebfcebdc5eff84bfdf407445e88e
element-web-1:
# Pin to a SHA so that upstream cannot break our tests. Renovate handles regular updates.
image: ghcr.io/element-hq/element-web:develop@sha256:5c9a8288deccb648e0d590776dff747ba674fe45c32cada6f804776800a38d2c
image: ghcr.io/element-hq/element-web:develop@sha256:58b673f867f78fe83c08f2b688b254e34625ebfcebdc5eff84bfdf407445e88e
volumes:
# The other site opens the embedded package under test in place of the
# copy its image bundles (the first site opens the dev server's app.
-1
View File
@@ -4,7 +4,6 @@ This folder contains documentation for setup, usage, and development of Element
- [Embedded vs standalone mode](./embedded_standalone.md)
- [Element Call as a React component (experimental)](../README.md#element-call-as-a-component-experimental)
- [Component CSS in a host page](./component_css_host_setup.md)
- [Url format and parameters](./url_params.md)
- [Global JS controls](./controls.md)
- [MatrixRTC modes](./matrix_rtc_modes.md)
-69
View File
@@ -1,69 +0,0 @@
# Component CSS in a host page
As a widget or standalone app, Element Call owns its document and loads
`src/index.css` unchanged. As a [React component](../README.md#element-call-as-a-component)
it shares the host's document and the host's copy of Compound, so its
stylesheet must not touch the host, and the host's must not break Element Call.
![Element Call component CSS in Element Web](component_css_host_setup.svg)
## How it works
- **Build.** The component ships `src/base.css` (not `index.css`) plus the CSS
modules as one `style.css`. `component/build/scopeStylesToRoot.ts` rewrites
every selector:
- `html` and `body` become `[data-element-call-root]`.
- `:root` becomes the root or `[data-element-call-portal]`.
- Everything else gets `:where(root, root *, portal, portal *)`.
`:where()` adds no specificity. In CSS modules only selectors without any
class are scoped, since a module class already confines a rule.
- **Runtime.** `useTheme` sets `data-element-call-root`, `data-platform` and the
`cpd-theme-*` class on the root element (`src/RootElementContext.ts`). The
theme and platform also go on the portal container.
- **Portal container.** `component/CallPortalRoot.tsx` creates
`div[data-element-call-portal]` in the host's `portalRoot`. Compound floats
tooltips and menus into it, so they get Element Call's styles too. Modals
portal into the root itself.
- **Containment.** `component/ElementCall.module.css` gives the root
`isolation: isolate` and `contain: layout paint`, so `position: fixed` modals
centre on the call, not the host window.
## What the host does
1. Provides Compound's design tokens, component styles and fonts, since the
component does not bundle them.
2. Declares Element Call's layers below Compound's, then imports
`@element-hq/element-call-component/style.css` **unlayered**. In Element Web:
```css
@layer normalize, compound-legacy, compound-tokens, compound-web, shared-components, app-web;
```
For example, a Compound `<Button>` inside the call, such as the lobby's join
button, meets two rules of equal specificity:
| Rule | From | Layer |
| ---------------------------------------------------------- | --------------------- | -------------- |
| `[type="button"]:where(…) { -webkit-appearance: button }` | normalize.css, scoped | `normalize` |
| `._button_… { appearance: none; font: var(--cpd-font-…) }` | Compound | `compound-web` |
Without layers they tie, so the one loaded last wins: Element Call's
stylesheet, loaded after the host's, and the button looks native (no styling). With
them, `compound-web` beats `normalize` whatever the load order, and a rule
in one of Element Call's CSS modules, being unlayered, would beat both.
3. Passes `portalRoot`: the page body, or the Picture-in-Picture window's body
while the call is shown there, or `null` while that window is not ready.
## Rules for Element Call code
- Style `[data-element-call-root]`, never `body` or `:root` directly; see
[code style](./agents/code-style.md#css).
- Use container queries (`@container element-call`) and `cqw`/`cqh`, not
`@media` or `vw`/`vh`.
- Nothing in `base.css` may depend on its order relative to the CSS modules:
the app and the component build put it in different places.
- `pnpm dev:component` applies the same scoping, so the test host shows what a
real host gets.
-172
View File
@@ -1,172 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1260" height="960" viewBox="0 0 1260 960" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif" font-size="12" fill="#1f2328">
<defs>
<style>
.mono { font-family: ui-monospace, Menlo, Consolas, monospace; }
.b { font-weight: 600; }
.tag { fill: #57606a; font-size: 11px; }
.ok { fill: #2e7d32; font-weight: 700; font-size: 14px; }
.no { fill: #c62828; font-weight: 700; font-size: 14px; }
.lead { stroke: #8250df; stroke-width: 1.5; stroke-dasharray: 5 3; fill: none; }
.dot { fill: #8250df; }
.reach { stroke: #e36209; stroke-width: 1.5; stroke-dasharray: 6 4; fill: none; }
</style>
<marker id="arrow" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="8" markerHeight="8" orient="auto">
<path d="M0 0 L8 4 L0 8 z" fill="#8250df"/>
</marker>
</defs>
<rect width="1260" height="960" fill="#ffffff"/>
<text x="30" y="34" font-size="17" class="b">Element Call as a component inside Element Web: the live DOM</text>
<!-- ================= DOM tree ================= -->
<!-- body -->
<rect x="30" y="52" width="620" height="680" rx="6" fill="#fafafa" stroke="#8c959f"/>
<text x="44" y="74" class="mono b">&lt;body&gt;</text>
<text x="100" y="74" class="tag">Element Web's document</text>
<!-- EW app UI -->
<rect x="50" y="86" width="580" height="400" rx="5" fill="#eceff1" stroke="#90a4ae"/>
<text x="64" y="106" class="b">EW app UI</text>
<!-- EW h3 -->
<rect x="70" y="118" width="260" height="30" rx="4" fill="#ffffff" stroke="#90a4ae"/>
<text x="82" y="138" class="mono">&lt;h3&gt;</text>
<text x="122" y="138">in EW's own UI</text>
<text x="310" y="139" class="no">✗</text>
<!-- call tile -->
<rect x="70" y="160" width="540" height="314" rx="5" fill="#f6f8fa" stroke="#b0bec5"/>
<text x="84" y="180">call tile → <tspan class="mono">WrappedElementCallComponent</tspan> <tspan class="tag">(EW)</tspan></text>
<!-- EC root -->
<rect x="88" y="192" width="504" height="270" rx="5" fill="#e8f5e9" stroke="#2e7d32" stroke-width="2"/>
<text x="102" y="214" class="mono b">div.root</text>
<text x="102" y="232" class="mono">[data-element-call-root] [data-platform] [data-background]</text>
<text x="102" y="248" class="mono">.cpd-theme-dark</text>
<text x="102" y="268" class="tag">class: component/ElementCall.module.css (isolation, contain: layout paint)</text>
<text x="102" y="284" class="tag">attributes, theme: src/useTheme.ts, Decoration in component/index.tsx</text>
<!-- div.content -->
<rect x="106" y="296" width="470" height="70" rx="4" fill="#ffffff" stroke="#66bb6a"/>
<text x="120" y="316"><tspan class="mono">div.content</tspan> → CallView …</text>
<rect x="124" y="326" width="200" height="28" rx="4" fill="#f1f8e9" stroke="#66bb6a"/>
<text x="136" y="345" class="mono">&lt;h3&gt;</text>
<text x="176" y="345">in the call view</text>
<text x="306" y="346" class="ok">✓</text>
<!-- Modal -->
<rect x="106" y="378" width="470" height="72" rx="4" fill="#ffffff" stroke="#66bb6a"/>
<text x="120" y="398">Modal / Drawer <tspan class="tag">src/Modal.tsx: Drawer.Portal container = root element</tspan></text>
<rect x="124" y="410" width="200" height="28" rx="4" fill="#f1f8e9" stroke="#66bb6a"/>
<text x="136" y="429" class="mono">&lt;h3&gt;</text>
<text x="176" y="429">modal title</text>
<text x="306" y="430" class="ok">✓</text>
<!-- EC portal container -->
<rect x="50" y="502" width="580" height="160" rx="5" fill="#e3f2fd" stroke="#1565c0" stroke-width="2"/>
<text x="64" y="524" class="mono b">div[data-element-call-portal][data-platform].cpd-theme-dark</text>
<text x="64" y="544" class="tag">created by component/CallPortalRoot.tsx, appended to EW's portalRoot:</text>
<text x="64" y="558" class="tag">this body, or the PiP window's body while the call is in Picture-in-Picture</text>
<text x="64" y="574" class="tag">theme + platform: src/useTheme.ts via usePortalElement (src/RootElementContext.ts)</text>
<rect x="70" y="586" width="540" height="64" rx="4" fill="#ffffff" stroke="#64b5f6"/>
<text x="84" y="606">Compound tooltip / menu <tspan class="tag">floated here by Compound's PortalRoot</tspan></text>
<rect x="88" y="614" width="220" height="28" rx="4" fill="#e8f4fd" stroke="#64b5f6"/>
<text x="100" y="633" class="mono">&lt;h3&gt;</text>
<text x="140" y="633">in a floated menu</text>
<text x="290" y="634" class="ok">✓</text>
<!-- EW's own floated UI -->
<rect x="50" y="676" width="580" height="42" rx="5" fill="#eceff1" stroke="#90a4ae"/>
<text x="64" y="702">EW's own Compound tooltips / menus <tspan class="tag">not inside EC's root or portal container</tspan></text>
<text x="604" y="703" class="no">✗</text>
<!-- reach of EC's scoped selectors -->
<rect x="82" y="186" width="516" height="282" rx="8" class="reach"/>
<rect x="44" y="496" width="592" height="172" rx="8" class="reach"/>
<!-- ================= h3 notes ================= -->
<!-- 1 -->
<rect x="750" y="52" width="490" height="174" rx="6" fill="#fbf8ff" stroke="#c297ff"/>
<circle cx="770" cy="72" r="11" fill="#8250df"/>
<text x="770" y="76" fill="#fff" text-anchor="middle" class="b">1</text>
<text x="790" y="77" class="b">Source: Element Call's own stylesheets</text>
<text x="790" y="100" class="tag"><tspan class="mono">src/base.css</tspan>, in <tspan class="mono">@layer compound-legacy</tspan></text>
<text x="790" y="120" class="mono">h3 {</text>
<text x="806" y="136" class="mono">font-weight: 600;</text>
<text x="806" y="152" class="mono">font-size: var(--font-size-subtitle);</text>
<text x="790" y="168" class="mono">}</text>
<text x="790" y="192" class="tag"><tspan class="mono">src/room/InviteModal.module.css</tspan>, the modal's copy-link button</text>
<text x="790" y="212" class="mono">.button { width: 100%; }</text>
<!-- 2 -->
<rect x="750" y="238" width="490" height="308" rx="6" fill="#fbf8ff" stroke="#c297ff"/>
<circle cx="770" cy="258" r="11" fill="#8250df"/>
<text x="770" y="262" fill="#fff" text-anchor="middle" class="b">2</text>
<text x="790" y="263" class="b">Component build: <tspan class="mono">component/build/scopeStylesToRoot.ts</tspan></text>
<text x="790" y="286" class="mono">h3:where(</text>
<text x="806" y="302" class="mono">[data-element-call-root],</text>
<text x="806" y="318" class="mono">[data-element-call-root] *,</text>
<text x="806" y="334" class="mono">[data-element-call-portal],</text>
<text x="806" y="350" class="mono">[data-element-call-portal] *</text>
<text x="790" y="366" class="mono">)</text>
<text x="790" y="388"><tspan class="mono">:where()</tspan> adds no specificity: same weight as a plain <tspan class="mono">h3</tspan>.</text>
<text x="790" y="412" class="mono">._button_1ibuh_15 { width: 100%; }</text>
<text x="790" y="432">Not rewritten: the module class already confines it.</text>
<line x1="764" y1="446" x2="1226" y2="446" stroke="#e1d4f5"/>
<text x="764" y="464" class="b">Rules that get <tspan class="mono">:where()</tspan>, all from Element Call's own files:</text>
<text x="764" y="482"><tspan class="mono">src/base.css</tspan> <tspan class="tag">root tokens, theme classes, typography</tspan></text>
<text x="764" y="499"><tspan class="mono">normalize.css</tspan> <tspan class="tag">imported by base.css into @layer normalize</tspan></text>
<text x="764" y="516"><tspan class="mono">*.module.css</tspan> <tspan class="tag">none: every selector there has a class</tspan></text>
<text x="764" y="533" class="tag">Compound's and Element Web's stylesheets never go through it.</text>
<!-- 3 -->
<rect x="750" y="558" width="490" height="126" rx="6" fill="#fbf8ff" stroke="#c297ff"/>
<circle cx="770" cy="578" r="11" fill="#8250df"/>
<text x="770" y="582" fill="#fff" text-anchor="middle" class="b">3</text>
<text x="790" y="583" class="b">What it matches</text>
<text x="764" y="610"><tspan class="no">✗</tspan> EW's own h3: it is in neither container</text>
<text x="764" y="640"><tspan class="ok">✓</tspan> the h3 in the call view and in the modal (inside the root)</text>
<text x="764" y="670"><tspan class="ok">✓</tspan> an h3 floated into the portal container</text>
<!-- 4 -->
<rect x="750" y="696" width="490" height="120" rx="6" fill="#fbf8ff" stroke="#c297ff"/>
<circle cx="770" cy="716" r="11" fill="#8250df"/>
<text x="770" y="720" fill="#fff" text-anchor="middle" class="b">4</text>
<text x="790" y="721" class="b">Cascade layer</text>
<text x="790" y="742">Stays in <tspan class="mono">compound-legacy</tspan>. EW's <tspan class="mono">res/css/_index.pcss</tspan> orders:</text>
<text x="790" y="762" class="mono">normalize, compound-legacy, compound-tokens,</text>
<text x="790" y="778" class="mono">compound-web, shared-components, app-web</text>
<text x="790" y="802">so Compound's styles win where both set the same property.</text>
<!-- leaders from the h3 nodes to note 3: one lane each, no crossings -->
<!-- EW's own h3 → ✗ row -->
<path class="lead" d="M330 133 H725 V610 H750" marker-end="url(#arrow)"/>
<!-- call view + modal h3 → first ✓ row -->
<path class="lead" d="M324 340 H700 V640 H750" marker-end="url(#arrow)"/>
<path class="lead" d="M324 424 H700"/>
<!-- floated menu h3 → second ✓ row -->
<path class="lead" d="M308 628 H675 V670 H750" marker-end="url(#arrow)"/>
<circle class="dot" cx="330" cy="133" r="3"/>
<circle class="dot" cx="324" cy="340" r="3"/>
<circle class="dot" cx="324" cy="424" r="3"/>
<circle class="dot" cx="308" cy="628" r="3"/>
<circle class="dot" cx="700" cy="424" r="2.5"/>
<!-- ================= legend ================= -->
<rect x="750" y="830" width="490" height="112" rx="6" fill="#ffffff" stroke="#d0d7de"/>
<text x="766" y="852" class="b">Legend</text>
<rect x="766" y="864" width="18" height="12" fill="#eceff1" stroke="#90a4ae"/>
<text x="792" y="875">Element Web</text>
<rect x="896" y="864" width="18" height="12" fill="#e8f5e9" stroke="#2e7d32"/>
<text x="922" y="875">EC root (the call)</text>
<rect x="1056" y="864" width="18" height="12" fill="#e3f2fd" stroke="#1565c0"/>
<text x="1082" y="875">EC portal container</text>
<rect x="766" y="890" width="30" height="12" rx="3" class="reach"/>
<text x="804" y="901">what EC's scoped selectors can reach</text>
<path class="lead" d="M766 922 L796 922" marker-end="url(#arrow)"/>
<text x="804" y="926">which h3 the rule in note 3 does or does not match</text>
</svg>

Before

Width:  |  Height:  |  Size: 10 KiB

+25 -25
View File
@@ -46,31 +46,31 @@ possible to support encryption.
These parameters are relevant to both [widget](./embedded_standalone.md) and [standalone](./embedded_standalone.md) modes:
| Name | Values | Required for widget | Required for SPA | Description |
| ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `intent` | `start_call`, `join_existing`, `start_call_voice`, `join_existing_voice`, `start_call_dm`, `join_existing_dm`, `start_call_dm_voice`, `join_existing_dm_voice`, or `video_room`. | No, defaults to `start_call` | No, defaults to `start_call` | The intent is a special url parameter that defines the defaults for all the other parameters. In most cases it should be enough to only set the intent to setup element-call. |
| `allowIceFallback` | `true` or `false` | No, defaults to `false` | No, defaults to `false` | Allows use of fallback STUN servers for ICE if the user's homeserver doesn’t provide any. |
| `posthogUserId` | Posthog analytics ID | No | No | Available only with user's consent for sharing telemetry in Element Web. |
| `confineToRoom` | `true` or `false` | No, defaults to `false` | No, defaults to `false` | Keeps the user confined to the current call/room. |
| `displayName` | | No | No | Display name used for auto-registration. |
| `enableE2EE` (deprecated) | `true` or `false` | No, defaults to `true` | No, defaults to `true` | Legacy flag to enable end-to-end encryption, not used in the `livekit` branch. |
| `fontScale` | A decimal number such as `0.9` | No, defaults to `1.0` | No, defaults to `1.0` | Factor by which to scale the interface's font size. |
| `fonts` | | No | No | Defines the font(s) used by the interface. Multiple font parameters can be specified: `?font=font-one&font=font-two...`. |
| `header` | `none`, `standard` or `app_bar` | No, defaults to `standard` | No, defaults to `standard` | The style of headers to show. `standard` is the default arrangement, `none` hides the header entirely, and `app_bar` produces a header with a back button like you might see in mobile apps. The callback for the back button is `window.controls.onBackButtonPressed`. |
| `hideScreensharing` | `true` or `false` | No, defaults to `false` | No, defaults to `false` | Hides the screen-sharing button. |
| `homeserver` | | Not applicable | No | Homeserver for registering a new (guest) user, configures non-default guest user server when creating a spa link. |
| `lang` | [BCP 47](https://www.rfc-editor.org/info/bcp47) code | No | No | The language the app should use. |
| `password` | | No | No | E2EE password when using a shared secret. (For individual sender keys in embedded mode this is not required.) |
| `controlledAudioDevices` | `true` or `false` | No, defaults to `false` | No, defaults to `false` | Whether the [global JS controls for audio devices](./controls.md#audio-devices) should be enabled, allowing the list of audio devices to be controlled by the app hosting Element Call. |
| `roomId` | [Matrix Room ID](https://spec.matrix.org/v1.12/appendices/#room-ids) | Yes | No | Anything about what room we're pointed to should be from useRoomIdentifier which parses the path and resolves alias with respect to the default server name, however roomId is an exception as we need the room ID in embedded widget mode, and not the room alias (or even the via params because we are not trying to join it). This is also not validated, where it is in `useRoomIdentifier()`. |
| `showControls` | `true` or `false` | No, defaults to `true` | No, defaults to `true` | Displays controls like mute, screen-share, invite, and hangup buttons during a call. |
| `skipLobby` (deprecated: use `intent` instead) | `true` or `false` | No. If `intent` is explicitly `start_call` then defaults to `true`. Otherwise defaults to `false` | No, defaults to `false` | Skips the lobby to join a call directly, can be combined with preload in widget. When `true` the audio and video inputs will be muted by default. (This means there currently is no way to start without muted video if one wants to skip the lobby. Also not in widget mode.) |
| `theme` | One of: `light`, `dark`, `light-high-contrast`, `dark-high-contrast` | No, defaults to `dark` | No, defaults to `dark` | UI theme to use. |
| `background` | One of: `solid`, `gradient` | No, defaults to `gradient` | No, defaults to `gradient` | Visual style of the page background. |
| `viaServers` | Comma separated list of [Matrix Server Names](https://spec.matrix.org/v1.12/appendices/#server-name) | Not applicable | No | Homeserver for joining a room, non-empty value required for rooms not on the user’s default homeserver. |
| `sendNotificationType` | `ring` or `notification` | No | No | Will send a "ring" or "notification" `m.rtc.notification` event if the user is the first one in the call. |
| `autoLeave` | `true` or `false` | No, defaults to `false` | No, defaults to `false` | Whether the app should automatically leave the call when there is no one left in the call. |
| `waitForCallPickup` | `true` or `false` | No, defaults to `false` | No, defaults to `false` | When sending a notification, show UI that the app is awaiting an answer, play a dial tone, and (in widget mode) auto-close the widget once the notification expires. |
| Name | Values | Required for widget | Required for SPA | Description |
| ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------- | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `intent` | `start_call`, `join_existing`, `start_call_voice`, `join_existing_voice`, `start_call_dm`, `join_existing_dm`, `start_call_dm_voice`, or `join_existing_dm_voice`. | No, defaults to `start_call` | No, defaults to `start_call` | The intent is a special url parameter that defines the defaults for all the other parameters. In most cases it should be enough to only set the intent to setup element-call. |
| `allowIceFallback` | `true` or `false` | No, defaults to `false` | No, defaults to `false` | Allows use of fallback STUN servers for ICE if the user's homeserver doesn’t provide any. |
| `posthogUserId` | Posthog analytics ID | No | No | Available only with user's consent for sharing telemetry in Element Web. |
| `confineToRoom` | `true` or `false` | No, defaults to `false` | No, defaults to `false` | Keeps the user confined to the current call/room. |
| `displayName` | | No | No | Display name used for auto-registration. |
| `enableE2EE` (deprecated) | `true` or `false` | No, defaults to `true` | No, defaults to `true` | Legacy flag to enable end-to-end encryption, not used in the `livekit` branch. |
| `fontScale` | A decimal number such as `0.9` | No, defaults to `1.0` | No, defaults to `1.0` | Factor by which to scale the interface's font size. |
| `fonts` | | No | No | Defines the font(s) used by the interface. Multiple font parameters can be specified: `?font=font-one&font=font-two...`. |
| `header` | `none`, `standard` or `app_bar` | No, defaults to `standard` | No, defaults to `standard` | The style of headers to show. `standard` is the default arrangement, `none` hides the header entirely, and `app_bar` produces a header with a back button like you might see in mobile apps. The callback for the back button is `window.controls.onBackButtonPressed`. |
| `hideScreensharing` | `true` or `false` | No, defaults to `false` | No, defaults to `false` | Hides the screen-sharing button. |
| `homeserver` | | Not applicable | No | Homeserver for registering a new (guest) user, configures non-default guest user server when creating a spa link. |
| `lang` | [BCP 47](https://www.rfc-editor.org/info/bcp47) code | No | No | The language the app should use. |
| `password` | | No | No | E2EE password when using a shared secret. (For individual sender keys in embedded mode this is not required.) |
| `controlledAudioDevices` | `true` or `false` | No, defaults to `false` | No, defaults to `false` | Whether the [global JS controls for audio devices](./controls.md#audio-devices) should be enabled, allowing the list of audio devices to be controlled by the app hosting Element Call. |
| `roomId` | [Matrix Room ID](https://spec.matrix.org/v1.12/appendices/#room-ids) | Yes | No | Anything about what room we're pointed to should be from useRoomIdentifier which parses the path and resolves alias with respect to the default server name, however roomId is an exception as we need the room ID in embedded widget mode, and not the room alias (or even the via params because we are not trying to join it). This is also not validated, where it is in `useRoomIdentifier()`. |
| `showControls` | `true` or `false` | No, defaults to `true` | No, defaults to `true` | Displays controls like mute, screen-share, invite, and hangup buttons during a call. |
| `skipLobby` (deprecated: use `intent` instead) | `true` or `false` | No. If `intent` is explicitly `start_call` then defaults to `true`. Otherwise defaults to `false` | No, defaults to `false` | Skips the lobby to join a call directly, can be combined with preload in widget. When `true` the audio and video inputs will be muted by default. (This means there currently is no way to start without muted video if one wants to skip the lobby. Also not in widget mode.) |
| `theme` | One of: `light`, `dark`, `light-high-contrast`, `dark-high-contrast` | No, defaults to `dark` | No, defaults to `dark` | UI theme to use. |
| `background` | One of: `solid`, `gradient` | No, defaults to `gradient` | No, defaults to `gradient` | Visual style of the page background. |
| `viaServers` | Comma separated list of [Matrix Server Names](https://spec.matrix.org/v1.12/appendices/#server-name) | Not applicable | No | Homeserver for joining a room, non-empty value required for rooms not on the user’s default homeserver. |
| `sendNotificationType` | `ring` or `notification` | No | No | Will send a "ring" or "notification" `m.rtc.notification` event if the user is the first one in the call. |
| `autoLeave` | `true` or `false` | No, defaults to `false` | No, defaults to `false` | Whether the app should automatically leave the call when there is no one left in the call. |
| `waitForCallPickup` | `true` or `false` | No, defaults to `false` | No, defaults to `false` | When sending a notification, show UI that the app is awaiting an answer, play a dial tone, and (in widget mode) auto-close the widget once the notification expires. |
### Widget-only parameters
+12 -2
View File
@@ -4,7 +4,6 @@
},
"action": {
"add_background_image": "Add image",
"adjust_view": "Adjust view",
"close": "Close",
"copy_link": "Copy link",
"edit": "Edit",
@@ -96,7 +95,6 @@
},
"mute_all_audio": "Mute all audio (participants, reactions, join sounds)",
"show_connection_stats": "Show connection statistics",
"throw_error_button": "Throw test error",
"url_params": "URL parameters"
},
"disconnected_banner": "Connectivity to the server has been lost.",
@@ -143,6 +141,7 @@
},
"handset": {
"overlay_back_button": "Back to Speaker Mode",
"overlay_description": "Only works while using app",
"overlay_title": "Handset Mode"
},
"hangup_button_label": "End call",
@@ -159,6 +158,7 @@
},
"layout_grid_label": "Grid",
"layout_spotlight_label": "Spotlight",
"layout_switch_label": "Layout",
"lobby": {
"ask_to_join": "Request to join call",
"join_as_guest": "Join as guest",
@@ -172,6 +172,16 @@
"login_auth_links_prompt": "Not registered yet?",
"login_subheading": "To continue to Element",
"login_title": "Login",
"low_bandwidth_mode": {
"camera_unavailable": "You can't turn on your camera while Low bandwidth mode is on. To turn it off, select Cancel on the Low bandwidth mode banner, or use Video settings.",
"indicator": "Low bandwidth mode",
"indicator_cancel": "Cancel",
"indicator_cancel_label": "Cancel Low bandwidth mode",
"screen_share_unavailable": "You can't share your screen while Low bandwidth mode is on. To turn it off, select Cancel on the Low bandwidth mode banner, or use Video settings.",
"switch_description": "Turn off cameras and lower screen-share quality to save data. Lasts until the call ends.",
"switch_label": "Low bandwidth mode",
"turned_on": "Low bandwidth mode on"
},
"microphone_level": {
"label": "Microphone level",
"no_device": "No microphone found. Connect one, then try again.",
+6 -7
View File
@@ -39,8 +39,8 @@
"lint:knip": "knip",
"lint:externals": "node scripts/check-component-externals.mjs",
"lint:types": "tsc",
"i18n": "i18next-cli extract",
"i18n:check": "i18next-cli extract --ci",
"i18n": "npx i18next-cli extract",
"i18n:check": "npx i18next-cli extract --ci",
"test": "vitest",
"test:storybook": "vitest --project=storybook",
"test:unit": "vitest --project=unit",
@@ -55,7 +55,6 @@
"build-storybook": "storybook build"
},
"devDependencies": {
"@base-ui/react": "^1.9.0",
"@codecov/vite-plugin": "^2.0.0",
"@fontsource/inconsolata": "^5.1.0",
"@fontsource/inter": "^5.1.0",
@@ -83,7 +82,7 @@
"@types/grecaptcha": "^3.0.9",
"@types/jsdom": "^21.1.7",
"@types/lodash-es": "^4.17.12",
"@types/node": "^26.6.11",
"@types/node": "^24.0.0",
"@types/qrcode": "^1.5.5",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
@@ -106,16 +105,16 @@
"i18next": "^26.0.0",
"i18next-browser-languagedetector": "^8.0.0",
"i18next-cli": "^1.61.0",
"jsdom": "^31.0.0",
"jsdom": "^26.0.0",
"knip": "^5.86.0",
"livekit-client": "^2.18.1",
"lodash-es": "^4.17.21",
"loglevel": "^1.9.1",
"matrix-js-sdk": "github:matrix-org/matrix-js-sdk#aa1a8db0689465a8549546aea4c6cf1e696d6e44",
"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.80.0",
"oxfmt": "^0.79.0",
"oxlint": "^1.70.0",
"oxlint-tsgolint": "^0.25.0",
"pako": "^3.0.3",
+3 -10
View File
@@ -27,17 +27,10 @@ process.env.NODE_EXTRA_CA_CERTS = join(
"backend/dev_tls_local-ca.crt",
);
const commonDeviceOptions = {
// Disabling motion-based animations helps Playwright position the cursor
// correctly when clicking on menus etc.
reducedMotion: "reduce" as const,
ignoreHTTPSErrors: true,
};
const desktopChrome = {
...devices["Desktop Chrome"],
...commonDeviceOptions,
permissions: ["clipboard-write", "clipboard-read", "microphone", "camera"],
ignoreHTTPSErrors: true,
launchOptions: {
args: [
"--use-fake-ui-for-media-stream",
@@ -123,7 +116,7 @@ export default defineConfig({
testIgnore: ["**/mobile/**", "**/widget/widget-rtc-sdk.spec.ts"],
use: {
...devices["Desktop Firefox"],
...commonDeviceOptions,
ignoreHTTPSErrors: true,
launchOptions: {
firefoxUserPrefs: {
"permissions.default.microphone": 1,
@@ -147,7 +140,7 @@ export default defineConfig({
testMatch: "**/mobile/**",
use: {
...devices["Pixel 7"],
...commonDeviceOptions,
ignoreHTTPSErrors: true,
permissions: [
"clipboard-write",
"clipboard-read",
+6 -4
View File
@@ -62,7 +62,8 @@ test("Sign up a new account, then login, then logout", async ({ browser }) => {
test("As a guest, create a call, share link and other join", async ({
browser,
}) => {
const creatorContext = await browser.newContext();
// Use reduce motion to disable animations that are making the tests a bit flaky
const creatorContext = await browser.newContext({ reducedMotion: "reduce" });
const creatorPage = await creatorContext.newPage();
await creatorPage.goto("/");
@@ -75,8 +76,7 @@ test("As a guest, create a call, share link and other join", async ({
// join
await creatorPage.getByTestId("lobby_joinCall").click();
// Spotlight mode to make checking the test visually clearer
await creatorPage.getByRole("button", { name: "Adjust view" }).click();
await creatorPage.getByRole("menuitemradio", { name: "Spotlight" }).click();
await creatorPage.getByRole("radio", { name: "Spotlight" }).check();
// Get the invite link
const inviteLink = await SpaHelpers.getCallInviteLink(creatorPage);
@@ -84,7 +84,9 @@ test("As a guest, create a call, share link and other join", async ({
// ========
// ACT: The other user use the invite link to join the call as a guest
// ========
const guestInviteeContext = await browser.newContext();
const guestInviteeContext = await browser.newContext({
reducedMotion: "reduce",
});
const guestPage = await guestInviteeContext.newPage();
await SpaHelpers.joinCallFromInviteLink(guestPage, inviteLink);
+4 -4
View File
@@ -50,13 +50,13 @@ test.describe("the quick audio menu", () => {
}) => {
// Two browsers and a real call.
test.slow();
const hostContext = await browser.newContext();
const hostContext = await browser.newContext({ reducedMotion: "reduce" });
const host = await hostContext.newPage();
await installFakeDevices(host, { microphones: 3, speakers: 3 });
await joinACall(host, "Host", "Device switch");
const inviteLink = await SpaHelpers.getCallInviteLink(host);
const guestContext = await browser.newContext();
const guestContext = await browser.newContext({ reducedMotion: "reduce" });
const guest = await guestContext.newPage();
await SpaHelpers.joinCallFromInviteLink(guest, inviteLink, "Guest");
await SpaHelpers.expectVideoTilesCount(guest, 2);
@@ -85,13 +85,13 @@ test.describe("the quick audio menu", () => {
}) => {
// Two browsers and a real call.
test.slow();
const hostContext = await browser.newContext();
const hostContext = await browser.newContext({ reducedMotion: "reduce" });
const host = await hostContext.newPage();
await installFakeDevices(host);
await joinACall(host, "Muted host", "Muted meter");
const inviteLink = await SpaHelpers.getCallInviteLink(host);
const guestContext = await browser.newContext();
const guestContext = await browser.newContext({ reducedMotion: "reduce" });
const guest = await guestContext.newPage();
await SpaHelpers.joinCallFromInviteLink(guest, inviteLink, "Listener");
await SpaHelpers.expectVideoTilesCount(guest, 2);
-3
View File
@@ -422,9 +422,6 @@ test.describe("a background of one's own", () => {
).toBeVisible();
await expect(mine).toHaveCount(0);
await page.keyboard.press("Escape");
// While it animates out the menu still counts as visible: addImage would
// then leave it closed instead of opening it again
await expect(page.getByRole("menu")).toBeHidden();
await addImage(page, red);
await expect(mine).toBeVisible();
+2 -6
View File
@@ -107,6 +107,8 @@ test("tracks the focus source of its own call, not the page", async ({
await openDeviceList(page, pane);
const menu = page.getByRole("menu");
// Asserted on the attribute: the component build's scoped stylesheet doesn't
// reach the portalled menu, so its ring can't be read here.
await expect(menu).toHaveAttribute("data-focus-source", "pointer");
// A key pressed in the other call says nothing about this menu.
@@ -119,12 +121,6 @@ test("tracks the focus source of its own call, not the page", async ({
await page.keyboard.press("ArrowDown");
await expect(menu).toHaveAttribute("data-focus-source", "keyboard");
// Asserted on the painted ring too: the rule is confined by the menu's module
// class on an ancestor, and has to reach the menu where Compound portals it,
// outside the call's root.
const focused = menu.locator('[role^="menuitem"]:focus');
await expect(focused).toHaveCSS("outline-style", "solid");
});
/** Opens a component's microphone menu and returns its device list. */
+11 -48
View File
@@ -30,6 +30,15 @@ import { SpaHelpers } from "../spa-helpers.ts";
// are sized for that, so the tests have to be too
test.describe.configure({ timeout: 180_000 });
/** The settings button, whichever of the two the footer is currently showing. */
function settingsButton(pane: Locator): Locator {
return pane
.getByTestId("settings-bottom-left")
.or(pane.getByTestId("settings-bottom-center"))
.filter({ visible: true })
.first();
}
test("holds a call between two components on one page", async ({ page }) => {
const { username, roomId } = await createUserAndRoom("twocomponents");
const panes = await startHarness(page, username, roomId);
@@ -72,7 +81,7 @@ test("keeps its modals inside the container it was given", async ({ page }) => {
// rather than the container until it was made a containing block. The
// settings dialog spilled over the host's interface; the reaction picker sat
// at 82vh, which put it below the container entirely and so out of sight.
await pane.getByTestId("settings-bottom").click();
await settingsButton(pane).click();
await expectWithin(pane.getByRole("dialog"), container);
await pane.getByTestId("modal_close").click();
@@ -103,8 +112,7 @@ test("keeps the call inside the container, wherever the host put it", async ({
// the container below a header of its own, so a grid offset measured from
// the top of the page instead of from the root would land the tile on top of
// the footer and out of the bottom of the container.
await pane.getByRole("button", { name: "Adjust view" }).click();
await page.getByRole("menuitemradio", { name: "Spotlight" }).click();
await pane.getByRole("radio", { name: "Spotlight" }).check();
const tile = pane.getByTestId("videoTile").first();
await expect(tile).toBeVisible({ timeout: 60_000 });
await expectWithin(tile, container);
@@ -141,51 +149,6 @@ test("leaves the host's own page unstyled", async ({ page }) => {
await expect(root).toHaveCSS("font-feature-settings", /"kern"/);
});
test("styles its tooltips as its own, outside the container", async ({
page,
}) => {
const { username, roomId } = await createUserAndRoom("portalstyles");
const panes = await startHarness(page, username, roomId);
const pane = panes.first();
await expect(pane.getByTestId("lobby_joinCall")).toBeVisible({
timeout: 60_000,
});
const button = pane.getByTestId("settings-bottom");
await button.hover();
const labelId = await button.getAttribute("aria-labelledby");
const label = page.locator(`[id="${labelId}"]`);
await expect(label).toHaveText("Settings");
// The harness passes no portal root, so the tooltip floats out of the call's
// root into a container of Element Call's own in the page's body. Each of the
// harness's two calls has one, so pick the one holding this tooltip.
const portal = page
.locator("body > [data-element-call-portal]")
.filter({ has: page.locator(`[id="${labelId}"]`) });
await expect(portal).toHaveCount(1);
await expect(portal.locator(`[id="${labelId}"]`)).toBeVisible();
await expect(pane.locator(`[id="${labelId}"]`)).toHaveCount(0);
// That container carries the call's theme and platform, as the root does
await expect(portal).toHaveClass(/\bcpd-theme-dark\b/);
await expect(portal).toHaveAttribute("data-platform", "desktop");
// And Element Call's stylesheets reach it: `--font-scale` is declared on
// `:root` in base.css, which the component build turns into the root and
// this container. The host's page itself still has none of it.
expect(
await label.evaluate((element) =>
getComputedStyle(element).getPropertyValue("--font-scale").trim(),
),
).toBe("1");
expect(
await page.evaluate(() =>
getComputedStyle(document.body).getPropertyValue("--font-scale"),
),
).toBe("");
});
test("tells its host what it is doing", async ({ page }) => {
const { username, roomId } = await createUserAndRoom("hostbridge");
const panes = await startHarness(page, username, roomId);
+1 -1
View File
@@ -30,7 +30,7 @@ export const mobileTest = test.extend<MobileCreateFixtures>({
async function createCallAndInvite(
browser: Browser,
): Promise<{ page: Page; inviteLink: string }> {
const creatorContext = await browser.newContext();
const creatorContext = await browser.newContext({ reducedMotion: "reduce" });
const creatorPage = await creatorContext.newPage();
await creatorPage.goto("/");
+151
View File
@@ -0,0 +1,151 @@
/*
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 Browser, expect, type Page, test } from "@playwright/test";
import { SpaHelpers } from "./spa-helpers.ts";
import {
cancelButton,
expectInboundVideo,
expectNoInboundVideo,
inboundVideoWidths,
openVideoSettings,
recordPeerConnections,
setLowBandwidthMode,
} from "./utils/low-bandwidth-mode.ts";
test.describe("Low bandwidth mode", () => {
test.skip(
({ browserName }) => browserName !== "chromium",
"Reads inbound video from Chromium's statistics, and shares a fake screen",
);
test.slow();
test("has no switch in the lobby's settings", async ({ page }) => {
await page.goto("/");
await SpaHelpers.createCall(page, "Alice", "Low bandwidth");
await openVideoSettings(page);
await expect(
page.getByRole("checkbox", { name: "Blur the background of the video" }),
).toBeVisible();
await expect(
page.getByRole("checkbox", { name: "Low bandwidth mode" }),
).toHaveCount(0);
});
test("receives no cameras and sends no video, and Cancel gives the camera back", async ({
browser,
}) => {
const { alice, bob } = await twoInACall(browser);
await expectInboundVideo(alice);
await expect(cancelButton(alice)).toHaveCount(0);
await setLowBandwidthMode(alice, true);
await expect(cancelButton(alice)).toBeVisible();
// Bob's camera looks off to Alice, and nothing of it arrives
await expect(tileOf(alice, "Bob")).toHaveAttribute(
"data-video-enabled",
"false",
);
await expectNoInboundVideo(alice);
// Alice's camera is off, for her and for Bob
await expect(
alice.getByRole("switch", { name: "Start video" }),
).toHaveAttribute("aria-disabled", "true");
await expect(tileOf(bob, "Alice")).toHaveAttribute(
"data-video-enabled",
"false",
);
// Bob's screen share is shown to Alice as usual, at its lowest layer
await bob.getByRole("switch", { name: "Share screen" }).click();
await expect(alice.getByRole("radio", { name: "Spotlight" })).toBeChecked();
await expect(
alice.locator('video[data-source="screenShare"]'),
).toBeVisible();
await expectInboundVideo(alice);
const widths = await inboundVideoWidths(alice);
test.info().annotations.push({
type: "screen share width received in the mode",
description: widths.join(", "),
});
expect(widths.length).toBeGreaterThan(0);
for (const width of widths) expect(width).toBeLessThanOrEqual(960);
await bob.getByRole("switch", { name: "Share screen" }).click();
// From the keyboard, to check where focus lands once the indicator goes
await cancelButton(alice).focus();
await alice.keyboard.press("Enter");
await expect(cancelButton(alice)).toHaveCount(0);
await expect(alice.getByTestId("incall_videomute")).toBeFocused();
const firstFrameMs = await expectInboundVideo(alice);
test.info().annotations.push({
type: "video back after turning the mode off",
description: `${firstFrameMs} ms`,
});
await expect(
alice.getByRole("switch", { name: "Stop video" }),
).toBeVisible();
await expect(tileOf(alice, "Bob")).toHaveAttribute(
"data-video-enabled",
"true",
);
});
test("stays on through a reconnection, and can be turned off during one", async ({
browser,
}) => {
const { alice } = await twoInACall(browser);
await setLowBandwidthMode(alice, true);
await expectNoInboundVideo(alice);
await alice.context().setOffline(true);
await expect(
alice.getByRole("dialog", { name: "Reconnecting…" }),
).toBeVisible({ timeout: 30000 });
await alice.context().setOffline(false);
await expect(
alice.getByRole("dialog", { name: "Reconnecting…" }),
).not.toBeVisible({ timeout: 30000 });
await expectNoInboundVideo(alice);
// The switch is reachable over the reconnecting backdrop
await alice.context().setOffline(true);
await expect(
alice.getByRole("dialog", { name: "Reconnecting…" }),
).toBeVisible({ timeout: 30000 });
await setLowBandwidthMode(alice, false);
await alice.context().setOffline(false);
await expectInboundVideo(alice);
});
});
async function twoInACall(
browser: Browser,
): Promise<{ alice: Page; bob: Page }> {
const aliceContext = await browser.newContext({ reducedMotion: "reduce" });
await recordPeerConnections(aliceContext);
const alice = await aliceContext.newPage();
await alice.goto("/");
await SpaHelpers.createCall(alice, "Alice", "Low bandwidth", true);
const inviteLink = await SpaHelpers.getCallInviteLink(alice);
const bob = await (await browser.newContext()).newPage();
await SpaHelpers.joinCallFromInviteLink(bob, inviteLink, "Bob");
await SpaHelpers.expectVideoTilesCount(alice, 2);
return { alice, bob };
}
function tileOf(page: Page, name: string): ReturnType<Page["getByTestId"]> {
return page
.getByTestId("videoTile")
.filter({ has: page.getByTestId("name_tag").filter({ hasText: name }) })
.first();
}
+3 -1
View File
@@ -58,7 +58,9 @@ mobileTest(
// ========
// ACT: The other user use the invite link to join the call as a guest
// ========
const guestInviteeContext = await browser.newContext();
const guestInviteeContext = await browser.newContext({
reducedMotion: "reduce",
});
const guestPage = await guestInviteeContext.newPage();
await guestPage.goto(inviteLink + "&controlledAudioDevices=true");
@@ -0,0 +1,36 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { expect, test } from "@playwright/test";
import { SpaHelpers } from "../spa-helpers.ts";
import {
cancelButton,
setLowBandwidthMode,
} from "../utils/low-bandwidth-mode.ts";
test("@mobile a tap on the camera button in Low bandwidth mode says why it stays off", async ({
page,
}) => {
await page.goto("/");
await SpaHelpers.createCall(page, "John Doe", "Low bandwidth", true);
await expect(page.getByTestId("name_tag")).toContainText("John Doe");
await setLowBandwidthMode(page, true);
const camera = page.getByTestId("incall_videomute");
await expect(camera).toHaveAttribute("aria-disabled", "true");
await camera.tap();
await expect(page.getByRole("tooltip")).toHaveText(
"You can't turn on your camera while Low bandwidth mode is on. To turn it off, select Cancel on the Low bandwidth mode banner, or use Video settings.",
);
await expect(camera).toHaveAttribute("aria-checked", "false");
await cancelButton(page).tap();
await expect(camera).not.toHaveAttribute("aria-disabled", "true");
});
+11 -9
View File
@@ -12,7 +12,8 @@ test("When creator left, avoid reconnect to the same SFU", async ({
browserName,
}) => {
test.skip(browserName === "firefox", "Browser independent");
const creatorContext = await browser.newContext();
// Use reduce motion to disable animations that are making the tests a bit flaky
const creatorContext = await browser.newContext({ reducedMotion: "reduce" });
const creatorPage = await creatorContext.newPage();
await creatorPage.goto("/");
@@ -30,8 +31,7 @@ test("When creator left, avoid reconnect to the same SFU", async ({
// join
await creatorPage.getByTestId("lobby_joinCall").click();
// Spotlight mode to make checking the test visually clearer
await creatorPage.getByRole("button", { name: "Adjust view" }).click();
await creatorPage.getByRole("menuitemradio", { name: "Spotlight" }).click();
await creatorPage.getByRole("radio", { name: "Spotlight" }).check();
// Get the invite link
await creatorPage.getByRole("button", { name: "Invite" }).click();
@@ -51,7 +51,9 @@ test("When creator left, avoid reconnect to the same SFU", async ({
// ========
// ACT: The other user use the invite link to join the call as a guest
// ========
const guestB = await browser.newContext();
const guestB = await browser.newContext({
reducedMotion: "reduce",
});
const guestBPage = await guestB.newPage();
await guestBPage.goto(inviteLink);
@@ -59,13 +61,14 @@ test("When creator left, avoid reconnect to the same SFU", async ({
await expect(guestBPage.getByTestId("joincall_joincall")).toBeVisible();
await guestBPage.getByTestId("joincall_joincall").click();
await guestBPage.getByTestId("lobby_joinCall").click();
await guestBPage.getByRole("button", { name: "Adjust view" }).click();
await guestBPage.getByRole("menuitemradio", { name: "Spotlight" }).click();
await guestBPage.getByRole("radio", { name: "Spotlight" }).check();
// ========
// ACT: add a third user to the call to reproduce the bug
// ========
const guestC = await browser.newContext();
const guestC = await browser.newContext({
reducedMotion: "reduce",
});
const guestCPage = await guestC.newPage();
// Track WebSocket connections
let wsConnectionCount = 0;
@@ -82,8 +85,7 @@ test("When creator left, avoid reconnect to the same SFU", async ({
await expect(guestCPage.getByTestId("joincall_joincall")).toBeVisible();
await guestCPage.getByTestId("joincall_joincall").click();
await guestCPage.getByTestId("lobby_joinCall").click();
await guestCPage.getByRole("button", { name: "Adjust view" }).click();
await guestCPage.getByRole("menuitemradio", { name: "Spotlight" }).click();
await guestCPage.getByRole("radio", { name: "Spotlight" }).check();
await guestCPage.waitForTimeout(1000);
if (wsConnectionCount === 2) {
+5 -3
View File
@@ -33,7 +33,7 @@ async function setupTwoUserSpaCall(
await interceptEventSend(
page,
// This room is not encrypted, so the event is sent in clear
"m.rtc.member",
"org.matrix.msc4143.rtc.member",
(req) => {
androlHasSentStickyEvent =
androlHasSentStickyEvent || isStickySend(req.url());
@@ -46,7 +46,9 @@ async function setupTwoUserSpaCall(
const inviteLink = await SpaHelpers.getCallInviteLink(page);
// Other
const guestInviteeContext = await browser.newContext();
const guestInviteeContext = await browser.newContext({
reducedMotion: "reduce",
});
const guestPage = await guestInviteeContext.newPage();
await guestPage.goto("/");
@@ -60,7 +62,7 @@ async function setupTwoUserSpaCall(
await interceptEventSend(
guestPage,
// This room is not encrypted, so the event is sent in clear
"m.rtc.member",
"org.matrix.msc4143.rtc.member",
(req) => {
pevaraHasSentStickyEvent =
pevaraHasSentStickyEvent || isStickySend(req.url());
+1 -2
View File
@@ -88,8 +88,7 @@ async function joinCallFromInviteLink(
}
await page.getByTestId("lobby_joinCall").click();
await page.getByRole("button", { name: "Adjust view" }).click();
await page.getByRole("menuitemradio", { name: "Spotlight" }).click();
await page.getByRole("radio", { name: "Spotlight" }).check();
}
async function setRtcModeFromSettings(
+21 -71
View File
@@ -58,20 +58,20 @@ const cases: {
guestFlows: ["cs-api"],
},
{
// The client-server API is preferred wherever a transport names a url.
// Clients since 0.28.1 match such a publisher by either identity.
// Publishers keep the legacy participant identity that clients predating
// MSC4195 expect, which only the JWT service assigns.
hostShape: "url+legacy",
guestShape: "url+legacy",
hostFlows: ["cs-api"],
guestFlows: ["cs-api"],
hostFlows: ["service-legacy"],
guestFlows: ["service-legacy"],
},
{
// The MatrixRTC mode has no bearing on the choice.
hostShape: "url+legacy",
guestShape: "url+legacy",
mode: "2_0",
hostFlows: ["cs-api"],
guestFlows: ["cs-api"],
hostFlows: ["service-legacy"],
guestFlows: ["service-legacy"],
},
{
hostShape: "url",
@@ -80,12 +80,10 @@ const cases: {
guestFlows: ["service-legacy", "cs-api"],
},
{
// Both reach the SFU through the client-server API, under one identity
// each, so one connection serves the own and the other's transport.
hostShape: "url",
guestShape: "url+legacy",
hostFlows: ["cs-api"],
guestFlows: ["cs-api"],
hostFlows: ["cs-api", "service-default"],
guestFlows: ["service-legacy", "cs-api"],
},
];
@@ -105,7 +103,7 @@ for (const { hostShape, guestShape, mode, hostFlows, guestFlows } of cases) {
const inviteLink = await SpaHelpers.getCallInviteLink(page);
// The guest joins.
const guestContext = await browser.newContext();
const guestContext = await browser.newContext({ reducedMotion: "reduce" });
const guestPage = await guestContext.newPage();
await advertiseTransport(guestPage, shapes[guestShape]);
const guestRequests = recordAuthRequests(guestPage);
@@ -162,53 +160,6 @@ test("Publisher shows an error when the homeserver lacks MSC4195", async ({
).toBeVisible();
});
test("Falls back to the JWT service for a url+legacy transport when the homeserver lacks MSC4195", async ({
browser,
page,
browserName,
}) => {
skipOnFirefox(browserName);
// The host starts the call; its C-S requests fail.
await advertiseTransport(page, shapes["url+legacy"]);
await rejectCsApiTokens(page);
const hostRequests = recordAuthRequests(page);
await page.goto("/");
await SpaHelpers.createCall(page, "Androl", "HelloCall", true);
const inviteLink = await SpaHelpers.getCallInviteLink(page);
// The guest joins, and its C-S requests fail as well.
const guestContext = await browser.newContext();
const guestPage = await guestContext.newPage();
await advertiseTransport(guestPage, shapes["url+legacy"]);
await rejectCsApiTokens(guestPage);
const guestRequests = recordAuthRequests(guestPage);
await SpaHelpers.joinCallFromInviteLink(guestPage, inviteLink, "Pevara");
// The call connects all the same.
await SpaHelpers.expectVideoTilesCount(page, 2);
await SpaHelpers.expectVideoTilesCount(guestPage, 2);
for (const requests of [hostRequests, guestRequests]) {
// Each published through the JWT service, under the legacy identity, and
// subscribes to the other over that same connection.
expect(flowsOf(requests)).toEqual(
new Set<Flow>(["cs-api", "service-legacy"]),
);
// The homeserver is asked once. Nothing asks it again once the API is
// known to be missing.
expect(requests.filter(({ flow }) => flow === "cs-api")).toHaveLength(1);
for (const request of requests) {
if (request.flow === "cs-api") {
expect(request.status).toBe(404);
} else {
expect(request.status).toBe(200);
expect(request.identity).toMatch(legacyIdentity);
}
}
}
});
test("Group call with all possible transport shapes at once", async ({
browser,
page,
@@ -224,13 +175,13 @@ test("Group call with all possible transport shapes at once", async ({
const inviteLink = await SpaHelpers.getCallInviteLink(page);
// The guest with a legacy transport joins.
const bobContext = await browser.newContext();
const bobContext = await browser.newContext({ reducedMotion: "reduce" });
const bobPage = await bobContext.newPage();
await advertiseTransport(bobPage, shapes.legacy);
await SpaHelpers.joinCallFromInviteLink(bobPage, inviteLink, "Bob");
// The guest with a url+legacy transport joins.
const carolContext = await browser.newContext();
const carolContext = await browser.newContext({ reducedMotion: "reduce" });
const carolPage = await carolContext.newPage();
await advertiseTransport(carolPage, shapes["url+legacy"]);
await SpaHelpers.joinCallFromInviteLink(carolPage, inviteLink, "Carol");
@@ -242,12 +193,13 @@ test("Group call with all possible transport shapes at once", async ({
});
/**
* Delegation follows the flow that authenticated the publisher.
* Delegation follows the flow that authenticated the publisher: the homeserver
* for a `url`-only transport, the JWT service wherever there is one.
*/
const delegationCases: { shape: Shape; via: Delegation["via"] }[] = [
{ shape: "url", via: "homeserver" },
{ shape: "legacy", via: "service" },
{ shape: "url+legacy", via: "homeserver" },
{ shape: "url+legacy", via: "service" },
];
for (const { shape, via } of delegationCases) {
@@ -265,7 +217,7 @@ for (const { shape, via } of delegationCases) {
const inviteLink = await SpaHelpers.getCallInviteLink(page);
// The guest joins.
const guestContext = await browser.newContext();
const guestContext = await browser.newContext({ reducedMotion: "reduce" });
const guestPage = await guestContext.newPage();
await advertiseTransport(guestPage, shapes[shape]);
const delayedLeave = recordDelayedLeave(guestPage);
@@ -276,10 +228,10 @@ for (const { shape, via } of delegationCases) {
await SpaHelpers.expectVideoTilesCount(page, 2);
await SpaHelpers.expectVideoTilesCount(guestPage, 2);
// The guest handed its delayed leave over. A JWT service is first probed
// for delegation support with a bodiless request, which counts as
// supported unless it 404s. A homeserver that issued the token is not
// probed.
// The guest handed its delayed leave over, after probing for delegation
// support with bodiless requests, which count as supported unless they
// 404. The homeserver is always probed; the JWT service only when there
// is one.
await expect
.poll(() => delegations.at(-1))
.toEqual({
@@ -289,9 +241,7 @@ for (const { shape, via } of delegationCases) {
...(via === "homeserver" && { sfuUrl }),
});
const probes = delegations.slice(0, -1);
expect(probes.map((probe) => probe.via)).toEqual(
via === "service" ? ["service"] : [],
);
expect(probes.some((probe) => probe.via === via)).toBe(true);
for (const probe of probes) {
expect(probe.status).toBeGreaterThanOrEqual(400);
expect(probe.status).not.toBe(404);
@@ -327,7 +277,7 @@ test("Subscribers get tokens for a remote homeserver's SFU over federation", asy
const inviteLink = await SpaHelpers.getCallInviteLink(page);
// The guest lives on the default homeserver and joins over federation.
const guestContext = await browser.newContext();
const guestContext = await browser.newContext({ reducedMotion: "reduce" });
const guestPage = await guestContext.newPage();
await advertiseTransport(guestPage, shapes.url);
const guestRequests = recordAuthRequests(guestPage);
+137
View File
@@ -0,0 +1,137 @@
/*
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 BrowserContext,
expect,
type FrameLocator,
type Page,
} from "@playwright/test";
declare global {
interface Window {
peerConnections?: RTCPeerConnection[];
}
}
/**
* Keeps every peer connection the pages of `context` open, so that what
* they receive can be read from the browser's own statistics. Install before
* the call loads.
*/
export async function recordPeerConnections(
context: BrowserContext,
): Promise<void> {
await context.addInitScript(() => {
const Original = window.RTCPeerConnection;
window.peerConnections = [];
window.RTCPeerConnection = class extends Original {
public constructor(config?: RTCConfiguration) {
super(config);
window.peerConnections!.push(this);
}
};
});
}
/** Bytes of video received so far, over every peer connection on the page. */
export async function inboundVideoBytes(
target: Page | FrameLocator,
): Promise<number> {
const read = async (): Promise<number> => {
let bytes = 0;
for (const connection of window.peerConnections ?? []) {
if (connection.connectionState === "closed") continue;
const report = await connection.getStats();
report.forEach((stat: RTCInboundRtpStreamStats) => {
if (stat.type === "inbound-rtp" && stat.kind === "video")
bytes += stat.bytesReceived ?? 0;
});
}
return bytes;
};
return "evaluate" in target
? target.evaluate(read)
: target.locator(":root").evaluate(read);
}
/** The widths of the videos arriving now, over every peer connection on the page. */
export async function inboundVideoWidths(
target: Page | FrameLocator,
): Promise<number[]> {
const read = async (): Promise<number[]> => {
const widths: number[] = [];
for (const connection of window.peerConnections ?? []) {
if (connection.connectionState === "closed") continue;
const report = await connection.getStats();
report.forEach((stat: RTCInboundRtpStreamStats) => {
if (stat.type === "inbound-rtp" && stat.kind === "video")
if (stat.frameWidth) widths.push(stat.frameWidth);
});
}
return widths;
};
return "evaluate" in target
? target.evaluate(read)
: target.locator(":root").evaluate(read);
}
/** Expects no video to arrive for `forMs`. */
export async function expectNoInboundVideo(
target: Page | FrameLocator,
forMs = 3000,
): Promise<void> {
// What was in flight when the subscription ended may still land
await new Promise((settled) => setTimeout(settled, 1000));
const before = await inboundVideoBytes(target);
await new Promise((settled) => setTimeout(settled, forMs));
expect(await inboundVideoBytes(target)).toBe(before);
}
/** Expects video to be arriving, and returns how long it took to start. */
export async function expectInboundVideo(
target: Page | FrameLocator,
): Promise<number> {
const start = Date.now();
const before = await inboundVideoBytes(target);
await expect
.poll(async () => inboundVideoBytes(target), { timeout: 20000 })
.toBeGreaterThan(before);
return Date.now() - start;
}
/** Opens the settings on their Video tab. */
export async function openVideoSettings(
target: Page | FrameLocator,
): Promise<void> {
await target
.getByRole("button", { name: "Settings" })
.filter({ visible: true })
.first()
.click();
await target.getByRole("tab", { name: "Video" }).click();
}
/** Turns Low bandwidth mode on or off from the call's Video settings. */
export async function setLowBandwidthMode(
target: Page | FrameLocator,
on: boolean,
): Promise<void> {
await openVideoSettings(target);
// By its label: the box itself can sit outside the dialog's scrolled view
const toggle = target.getByText("Low bandwidth mode", { exact: true });
if (on) await toggle.check();
else await toggle.uncheck();
await target.getByTestId("modal_close").click();
}
/** The indicator's way out of Low bandwidth mode. */
export function cancelButton(
target: Page | FrameLocator,
): ReturnType<Page["getByRole"]> {
return target.getByRole("button", { name: "Cancel Low bandwidth mode" });
}
@@ -1,64 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { expect, test } from "@playwright/test";
import { widgetTest } from "../fixtures/widget-user.ts";
import { TestHelpers } from "./test-helpers.ts";
widgetTest.skip(
({ browserName }) => browserName === "firefox",
"Widget specs only run on Chromium, see simple-create.spec.ts",
);
widgetTest(
"Switching rooms away from a crashed call dismisses it for good",
async ({ asWidget }) => {
test.slow();
const { brooks } = asWidget;
const page = brooks.page;
const call = page.locator('iframe[title="Element Call"]');
const callFrame = call.contentFrame();
// Somewhere to switch to once the call has crashed
await TestHelpers.createRoom("Other Room", page);
await TestHelpers.switchToRoomNamed(page, "Welcome Room");
await TestHelpers.startCallInCurrentRoom(page);
// A dev server compiles the widget on first load
await expect(callFrame.getByTestId("lobby_joinCall")).toBeVisible({
timeout: 30000,
});
await TestHelpers.joinCallFromLobby(page);
await expect(
callFrame.getByRole("button", { name: "End call" }),
).toBeVisible();
// Crash the call from its developer settings
await callFrame.getByRole("button", { name: "Settings" }).click();
await callFrame.getByRole("tab", { name: "Preferences" }).click();
await callFrame.getByText("Developer mode", { exact: true }).check();
await callFrame.getByRole("tab", { name: "Developer" }).click();
await callFrame.getByRole("button", { name: "Throw test error" }).click();
await expect(callFrame.getByText("Something went wrong")).toBeVisible();
// Showing the call collapses the room list
await TestHelpers.expandRoomList(page);
await TestHelpers.switchToRoomNamed(page, "Other Room");
await expect(
page.getByRole("main").getByRole("heading", { name: "Other Room" }),
).toBeVisible();
// The crashed call is gone and stays gone: no restart, no reconnect
await expect(call).toHaveCount(0);
await page.waitForTimeout(5000);
await expect(call).toHaveCount(0);
await expect(
page.getByRole("main").getByRole("heading", { name: "Other Room" }),
).toBeVisible();
},
);
@@ -0,0 +1,89 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { expect, test } from "@playwright/test";
import { widgetTest } from "../fixtures/widget-user.ts";
import { HOST1, TestHelpers } from "./test-helpers.ts";
import {
cancelButton,
expectInboundVideo,
expectNoInboundVideo,
recordPeerConnections,
setLowBandwidthMode,
} from "../utils/low-bandwidth-mode.ts";
widgetTest(
"Low bandwidth mode in Element Web",
async ({ addUser, browserName }) => {
test.skip(
browserName === "firefox",
"Reads inbound video from Chromium's statistics, and shares a fake screen",
);
test.slow();
const valere = await addUser("Valere", HOST1);
const timo = await addUser("Timo", HOST1);
await recordPeerConnections(valere.page.context());
const callRoom = "LowBandwidthRoom";
await TestHelpers.createRoom(callRoom, valere.page, [timo.mxId]);
await TestHelpers.createRoom("Elsewhere", valere.page);
await TestHelpers.acceptRoomInvite(callRoom, timo.page);
await TestHelpers.switchToRoomNamed(valere.page, callRoom);
await TestHelpers.startCallInCurrentRoom(valere.page, false);
await TestHelpers.joinCallFromLobby(valere.page);
await TestHelpers.joinCallInCurrentRoom(timo.page);
const valereCall = valere.page
.locator('iframe[title="Element Call"]')
.contentFrame();
const timoCall = timo.page
.locator('iframe[title="Element Call"]')
.contentFrame();
await expect(valereCall.locator("video")).toHaveCount(2, {
timeout: 15000,
});
// A share started before the mode stops when it comes on
await valereCall.getByRole("switch", { name: "Share screen" }).click();
await expect(
timoCall.locator('video[data-source="screenShare"]'),
).toHaveCount(1, { timeout: 10000 });
// Reached from the Video settings of the call's own footer
await setLowBandwidthMode(valereCall, true);
await expect(cancelButton(valereCall)).toBeVisible();
await expect(
valereCall.getByRole("switch", { name: "Share screen", checked: false }),
).toHaveAttribute("aria-disabled", "true");
await expect(
timoCall.locator('video[data-source="screenShare"]'),
).toHaveCount(0, { timeout: 10000 });
await expectNoInboundVideo(valereCall);
// Timo shares: Valere receives the share and sees it as usual
await timoCall.getByRole("switch", { name: "Share screen" }).click();
await expect(
valereCall.getByRole("radio", { name: "Spotlight" }),
).toBeChecked({ timeout: 10000 });
await expect(
valereCall.locator('video[data-source="screenShare"]'),
).toBeVisible();
await expectInboundVideo(valereCall);
// Element Web's PiP has no room for the indicator, and still shows the share
await TestHelpers.expandRoomList(valere.page);
await TestHelpers.switchToRoomNamed(valere.page, "Elsewhere");
await expect(valere.page.getByTestId("widget-pip-container")).toBeVisible();
await expect(
valereCall.locator('video[data-source="screenShare"]'),
).toBeVisible();
await expect(cancelButton(valereCall)).toHaveCount(0);
},
);
+2 -10
View File
@@ -86,11 +86,7 @@ widgetTest("Sharing screen in group call", async ({ addUser, browserName }) => {
const frame = alice.page
.locator('iframe[title="Element Call"]')
.contentFrame();
await frame.getByRole("button", { name: "Adjust view" }).click();
await expect(
frame.getByRole("menuitemradio", { name: "Grid" }),
).toBeChecked();
await frame.getByRole("menu").press("Escape");
await expect(frame.getByRole("radio", { name: "Grid" })).toBeChecked();
}
// Others should have switched to spotlight
@@ -99,11 +95,7 @@ widgetTest("Sharing screen in group call", async ({ addUser, browserName }) => {
.locator('iframe[title="Element Call"]')
.contentFrame();
await frame.getByRole("button", { name: "Adjust view" }).click();
await expect(
frame.getByRole("menuitemradio", { name: "Spotlight" }),
).toBeChecked();
await frame.getByRole("menu").press("Escape");
await expect(frame.getByRole("radio", { name: "Spotlight" })).toBeChecked();
}
// await alice.page.pause();
// await bob.page.pause();
+3 -1
View File
@@ -123,7 +123,9 @@ export class TestHelpers {
);
// STEP 2: Open browser and login
const userContext = await browser.newContext();
const userContext = await browser.newContext({
reducedMotion: "reduce",
});
const page = await userContext.newPage();
await page.goto(host);
+1098 -1049
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -28,8 +28,8 @@ overrides:
# - https://github.com/advisories/GHSA-7r86-cg39-jmmj
# - https://github.com/advisories/GHSA-23c5-xmqv-rm74
"minimatch": "^11.0.0"
# The v8 line is deprecated.
"eslint": "^9.0.0"
# Security fix: https://github.com/element-hq/element-call/security/dependabot/109
"glob": "^10.5.0"
# Security fix: https://github.com/advisories/GHSA-6pq8-jhm2-2vcw
"qs": ">=6.16.1"
# Security fix: https://github.com/advisories/GHSA-2883-xcg3-v3hh
+2 -4
View File
@@ -28,14 +28,12 @@
{
"groupName": "matrix-widget-api",
"matchDepNames": ["matrix-widget-api"],
"extends": ["schedule:weekly"],
"minimumReleaseAge": null
"extends": ["schedule:weekly"]
},
{
"groupName": "Compound",
"matchPackageNames": ["@vector-im/compound-{/,}**"],
"extends": ["schedule:weekly"],
"minimumReleaseAge": null
"extends": ["schedule:weekly"]
},
{
"groupName": "LiveKit client",
+11 -11
View File
@@ -6,18 +6,18 @@ Please see LICENSE in the repository root for full details.
*/
/**
* Checks the component build's output for things we do not want to end up in the
* component target.
* Checks the component build's output for what a host must not be handed.
*
* A library build inlines every asset it needs as a data URL unless the import
* says otherwise: if one adds an import without `no-inline` the
* module grows by the asset (due to encoding a third larger than the original file)
* that every host then downloads and parses before the first call.
* MediaPipe's runtime alone is 11 MB, so it should not be inlined.
* The standalone app's client store worker, which carries a copy of the Matrix SDK
* and its crypto, is also not needed in a package whose host supplies the client:
* the bundler packages if it is imported, even if not used (see src/utils/initClient.ts).
* The script makes sure, the build fails on each of those issues.
* A library build inlines every asset it meets as a data URL unless the import
* says otherwise, and does so silently: one import without `no-inline` and the
* module grows by the asset, encoded a third larger, that every host then
* downloads and parses before the first call. MediaPipe's runtime alone is
* 11 MB. A reference to a file by an absolute path is just as silent and
* breaks at runtime instead, since a host serves the module from wherever it
* likes. And the standalone app's client store worker, which carries a copy of
* the Matrix SDK and its crypto, has no business in a package whose host
* supplies the client: the bundler emits it on loading its import, used or
* not (see src/utils/initClient.ts). This fails the build on each of those.
*/
import { existsSync } from "node:fs";
+34 -50
View File
@@ -120,10 +120,10 @@ LiveKit participants.
The session discovers the transport from the homeserver and the backend prepares
it, both before `join()`, so that the membership can name it and the first frames
go out as soon as the state event is sent. Preparing is the backend's own
business: for LiveKit the token exchange for the publisher connection, and
with it whether that service can take over the delayed leave (assumed for a homeserver,
probed for a JWT service), which picks the delayed leave timings the join uses. The
join waits for the publisher to hold its token, so that the LiveKit room exists
business: for LiveKit the token exchange for the publisher connection, and the
probe that decides whether the service that issued the token can take over the
delayed leave, which picks the delayed leave timings the join uses. The join
waits for the publisher to hold its token, so that the LiveKit room exists
before a subscriber, who lacks the permission to create it, asks for a token
of its own. The tracks are created once the membership is `joined`, with their
upstream paused until then. A lobby that wants them earlier captures them with
@@ -228,6 +228,8 @@ export interface MatrixRTCClientOptions {
timings?: Partial<SessionTimings>;
/** Limits on what is published; LiveKit's defaults otherwise. */
mediaQuality?: MediaQuality;
/** Whether remote video is received from the first connection on; true when left out. */
receiveVideo?: boolean;
/** Use this transport instead of asking the homeserver. */
transport?: Transport;
/** Use this transport when the homeserver advertises none of the backend's type. */
@@ -343,6 +345,14 @@ export interface MatrixRTCClient {
*/
setAudioOutputDeviceId(deviceId: string): Promise<void>;
/**
* Whether remote video is received. While false no remote camera is
* subscribed, and screen shares are received at their lowest layer, on
* every transport, including transports connected later and after a
* reconnection; audio is unaffected. Defaults to true.
*/
setReceiveVideo(receive: boolean): void;
/**
* Sends a short text to every member on the local transport, over a
* reliable data channel beside the media. A packet holds about 15 KiB;
@@ -588,58 +598,32 @@ without one, LiveKit is built from the LiveKit-flavoured client options.
A LiveKit transport comes in three shapes while MSC4195 settles: an SFU `url`,
a JWT service `livekit_service_url`, or both. `media-backend/livekit/auth/`
fronts the two flows and chooses between them from the shape, preferring the
client-server API wherever the transport names a `url`:
fronts the two flows and chooses between them per connection, from the shape
and from the role we take on the transport:
| Transport | Publisher | Subscriber |
| -------------------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------ |
| `url` only | client-server API `get_token`, no fallback | client-server API `get_token`, no fallback |
| `livekit_service_url` only | JWT service `/sfu/get` (legacy identity) | JWT service `/get_token` (hashed identity) |
| both | client-server API, else JWT service `/sfu/get` (legacy identity) | client-server API, else JWT service `/get_token` (hashed identity) |
| Transport | Publisher | Subscriber |
| -------------------------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------- |
| `url` only | client-server API `get_token`, no fallback | client-server API `get_token`, no fallback |
| `livekit_service_url` only | JWT service `/sfu/get` (legacy identity) | JWT service `/get_token` (hashed identity) |
| both | JWT service `/sfu/get` (legacy identity) | client-server API, falling back to the JWT service `/get_token` where the homeserver, or a widget host, has no MSC4195 |
A member whose transport names both is matched against either identity (since
Element Call 0.28.1), so a publisher may take either flow. On the JWT service
a publisher uses `/sfu/get`, the only endpoint that assigns the legacy
`<user_id>:<device_id>` identity. A subscriber is matched by nobody and takes
the hashed one.
The JWT service stands in only where our homeserver has no MSC4195 endpoints.
A homeserver that has them advertises a `url`, so whether the API is usable is
read off our own transport: `prepareLocalTransport` stores it with the local
transport, and it is the one input, next to a transport's shape, to
`chooseAuthFlow`. Where ours names only a JWT service, transports naming both
go through that service from the start.
A homeserver may advertise a `url` and still lack the endpoints, as may a
widget host. A token request is then answered with a 404, `M_NOT_FOUND` or
`M_UNRECOGNIZED` (`isCsApiUnavailable`) and fails with
`NoMatrix2AuthorizationService`, which the publisher connection reports to
the backend before the error surfaces. Where our transport names a JWT service
too, the backend stores the local transport again with the API ruled out; the
failed connection is stopped with its map and never shows as an error. Only
the publisher's request rules the API out: it is the first one made, and a
subscriber's 404 once we publish through the API fails that connection alone.
A transport with a `url` alone has no fallback and fails the join. The MatrixRTC mode
plays no part in the choice.
A connection is created with its flow and keeps it for life. The delayed leave
is delegated through the publisher connection's flow, the one that issued its
token, so that the service watches for the identity we publish under. A
homeserver that issued the token is assumed to delegate. Only a JWT service is
probed, before the join.
A publisher on a transport with a service URL keeps the legacy
`<user_id>:<device_id>` identity, because clients predating MSC4195 match a
membership against that and nothing else; a subscriber is matched by nobody and
takes the more private hashed identity. A publisher never falls back: a
homeserver that advertises a `url` without implementing MSC4195 is misconfigured
and fails with `NoMatrix2AuthorizationService`, so the admin hears about it.
The MatrixRTC mode plays no part in the choice. The delayed leave is delegated
through the same flow that issued the publisher's token, so that the identity
the service watches for on the SFU is the one we publish under, and the
delegation probe before the join asks only that service.
The client-server API needs the name of the homeserver the transport belongs to:
our own homeserver asks that server for the token, over federation where it is
not ours. The backend derives it from the member's user id, and from our own for
the local transport. A JWT service is reached directly, so members of several
homeservers advertising the same one share a connection.
Connections are keyed on the flow and what it authenticates against: the `url`
plus the server name for the client-server API, the service URL for the JWT
service. Transports with the same key would get us the same identity on the
same SFU, so they share a connection. A connection map is built per local
transport, so whether the API is usable is fixed for the life of a map and of
every key in it; ruling the API out replaces the map.
the local transport, and keys its connections on the transport plus the server
name where the transport has a `url`. A JWT service is reached directly, so
members of several homeservers advertising the same one share a connection.
## Media: `tracks$` and `MediaTrack`
+2 -2
View File
@@ -75,6 +75,6 @@ export {
} from "./src/media-backend/livekit/videoProcessor";
// For a developer panel to check a transport before using it
export {
authenticateWithTransport,
type AuthenticateWithTransportParams,
getSFUConfig as authenticateWithTransport,
type GetSFUConfigParams as AuthenticateWithTransportParams,
} from "./src/media-backend/livekit/auth";
+18
View File
@@ -105,6 +105,7 @@ interface FakeBackend {
connectionState$: BehaviorSubject<MediaConnectionState | Error>;
data$: Subject<DataPacket>;
setPublishing: Mock<(publish: boolean) => void>;
setReceiveVideo: Mock<(receive: boolean) => void>;
delegateDelayedLeave: Mock<(delayId: string) => Promise<void>>;
mediaFor: Mock<(scope: ObservableScope, member: RTCMember) => MemberMedia>;
}
@@ -152,6 +153,7 @@ function setup(
),
data$: new Subject<DataPacket>(),
setPublishing: vi.fn(),
setReceiveVideo: vi.fn(),
delegateDelayedLeave: vi.fn(async () => Promise.resolve()),
mediaFor: vi.fn(() => ({
tracks$: constant(null),
@@ -178,6 +180,7 @@ function setup(
mediaFor: fake.mediaFor,
connections$: constant([]),
setAudioOutputDeviceId: vi.fn(),
setReceiveVideo: fake.setReceiveVideo,
sendData: vi.fn(),
data$: fake.data$,
};
@@ -375,6 +378,21 @@ describe("createRTCParticipation", () => {
scope.end();
});
it("hands the receive video choice to the backend, from the join options on", () => {
const { participation, fake, scope } = setup({ receiveVideo: false });
expect(fake.setReceiveVideo.mock.calls).toEqual([[false]]);
participation.setReceiveVideo(true);
expect(fake.setReceiveVideo).toHaveBeenLastCalledWith(true);
scope.end();
});
it("leaves the backend receiving video when the join options say nothing", () => {
const { fake, scope } = setup();
expect(fake.setReceiveVideo).not.toHaveBeenCalled();
scope.end();
});
it("gives the backend the keys the session holds and the ones that follow", () => {
const { fake, session, mockedSession, scope } = setup();
const keys: MediaKey[] = [];
+2
View File
@@ -151,6 +151,7 @@ export function createRTCParticipation(
timings,
logger,
});
if (options.receiveVideo === false) backend.setReceiveVideo(false);
// If the backend is LiveKit, we check it for transports as well, as a
// fallback: another member's SFU may let us publish (MSC4195). LiveKit only,
@@ -320,6 +321,7 @@ export function createRTCParticipation(
connectedTransports$: transports.connected$,
setAudioOutputDeviceId: async (deviceId) =>
backend.setAudioOutputDeviceId(deviceId),
setReceiveVideo: (receive) => backend.setReceiveVideo(receive),
sendData: async (topic, text) => backend.sendData(topic, text),
data$,
},
+1
View File
@@ -92,6 +92,7 @@ function idleBackend(): MediaBackend {
mediaFor: vi.fn(),
connections$: constant([]),
setAudioOutputDeviceId: vi.fn(),
setReceiveVideo: vi.fn(),
sendData: vi.fn(),
data$: EMPTY,
};
+13
View File
@@ -127,6 +127,11 @@ export interface RTCParticipationOptions {
timings?: Partial<SessionTimings>;
/** Limits on what is published; LiveKit's defaults otherwise. */
mediaQuality?: MediaQuality;
/**
* Whether remote video is received from the first connection on, as
* `setReceiveVideo` would set it. True when left out.
*/
receiveVideo?: boolean;
/**
* Use this transport instead of asking the homeserver. Any shape the
* backend serves: for LiveKit a `url`, a `livekit_service_url` or both.
@@ -216,6 +221,14 @@ export interface RTCParticipation {
*/
setAudioOutputDeviceId(deviceId: string): Promise<void>;
/**
* Whether remote video is received. While false no remote camera is
* subscribed, and screen shares are received at their lowest layer, on
* every transport, including transports connected later and after a
* reconnection; audio is unaffected. Defaults to true.
*/
setReceiveVideo(receive: boolean): void;
/**
* Sends a short text to every member on the local transport, over a
* reliable data channel beside the media. A packet holds about 15 KiB;
+1 -1
View File
@@ -81,7 +81,7 @@ export interface MediaQuality {
max_bitrate?: number;
/** Max framerate. Default 30. */
max_framerate?: number;
/** Simulcast layers, lowest quality first. Without them LiveKit adds one layer at half resolution. */
/** Simulcast layers, lowest quality first. Default one layer of 540p at 15 fps and 625 kbps. */
simulcast_layers?: Array<{
height: number;
bitrate: number;
+9
View File
@@ -159,6 +159,15 @@ export interface MediaBackend {
*/
setAudioOutputDeviceId(deviceId: string): Promise<void>;
/**
* Whether remote cameras are subscribed. While false, screen shares are
* still subscribed, capped at their lowest layer. Remembered across
* connections: every connection, existing or created later, follows it,
* including after a reconnection. Audio is always subscribed. True until
* first set.
*/
setReceiveVideo(receive: boolean): void;
/**
* A text channel beside the media: sent on the local transport, received on every one.
* This could well be just another track kind. Not needed for element call. just for the sdk target.
+235 -65
View File
@@ -25,9 +25,11 @@ import {
RoomEvent,
Track,
ConnectionState as LivekitConnectionState,
VideoQuality,
} from "livekit-client";
import fetchMock from "fetch-mock";
import EventEmitter from "events";
import { BehaviorSubject } from "rxjs";
import { MatrixError } from "matrix-js-sdk";
import { logger, type Logger } from "matrix-js-sdk/lib/logger";
import {
@@ -42,11 +44,7 @@ import {
} from "./Connection.ts";
import { ObservableScope } from "../../reactive/ObservableScope";
import { type ClientGetTokenParts, type ClientOpenIDParts } from "./auth";
import {
LivekitConnectionError,
MatrixRTCError,
NoMatrix2AuthorizationService,
} from "../../errors";
import { LivekitConnectionError, MatrixRTCError } from "../../errors";
import { testJWTToken } from "../../utils/test-fixtures";
import { ownMemberMock } from "../../utils/test";
import { mockRemoteParticipant } from "./test";
@@ -56,6 +54,7 @@ let testScope: ObservableScope;
let client: MockedObject<ClientGetTokenParts & ClientOpenIDParts>;
let fakeLivekitRoom: MockedObject<LivekitRoom>;
let receiveVideo$: BehaviorSubject<boolean>;
let localParticipantEventEmiter: EventEmitter;
let fakeLocalParticipant: MockedObject<LocalParticipant>;
@@ -67,15 +66,15 @@ const FIREFOX_USER_AGENT =
const CHROME_USER_AGENT =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36";
const url = "wss://matrix-rtc.m.localhost/livekit/sfu";
const transport: UnstableLivekitTransport = { type: "livekit", url };
const transport: UnstableLivekitTransport = {
type: "livekit",
url: "wss://matrix-rtc.m.localhost/livekit/sfu",
};
/** The options of a subscriber connection to `transport`. */
function connectionOpts(): ConnectionOpts {
return {
client,
flow: { kind: "csApi", url },
onCsApiMissing: vi.fn(),
roomId: ROOM_ID,
slotId: SLOT_ID,
role: "subscriber",
@@ -83,12 +82,14 @@ function connectionOpts(): ConnectionOpts {
serverName: "m.localhost",
scope: testScope,
ownMembershipIdentity: ownMemberMock,
receiveVideo$,
livekitRoomFactory: () => fakeLivekitRoom,
};
}
function setupTest(): void {
testScope = new ObservableScope();
receiveVideo$ = new BehaviorSubject(true);
client = vi.mocked<ClientGetTokenParts & ClientOpenIDParts>({
getOpenIdToken: vi.fn().mockResolvedValue({
access_token: "rYsmGUEwNjKgJYyeNUkZseJN",
@@ -376,7 +377,6 @@ describe("Start connection states", () => {
...connectionOpts(),
role: "publisher",
transport: { type: "livekit", livekit_service_url: serviceUrl },
flow: { kind: "openID", serviceUrl },
},
logger,
);
@@ -388,65 +388,11 @@ describe("Start connection states", () => {
expect(fakeLivekitRoom.connect).toHaveBeenCalledWith(
"wss://sfu",
testJWTToken,
{ autoSubscribe: true },
);
expect(connection.livekitAlias).toBe("!example_room_id");
});
it.each([
["reports", "publisher", 1],
// A 404 there, once we publish through the API, is not the API missing
["does not report", "subscriber", 0],
] as const)(
"%s the CS API missing as a %s where the homeserver lacks the endpoint",
async (_what, role, reports) => {
setupTest();
const opts = { ...connectionOpts(), role };
client.getLivekitToken.mockRejectedValue(
new MatrixError({ errcode: "M_UNRECOGNIZED" }, 404),
);
const connection = new Connection(opts, logger);
await expect(connection.start()).rejects.toThrow(
expect.any(NoMatrix2AuthorizationService),
);
expect(opts.onCsApiMissing).toHaveBeenCalledTimes(reports);
expect(connection.state$.value.state).toBe("error");
},
);
it("does not show as failed when reporting the CS API missing gets it stopped", async () => {
setupTest();
fakeLivekitRoom.disconnect.mockResolvedValue(undefined);
client.getLivekitToken.mockRejectedValue(
new MatrixError({ errcode: "M_UNRECOGNIZED" }, 404),
);
const connection: Connection = new Connection(
{
...connectionOpts(),
role: "publisher",
onCsApiMissing: () => void connection.stop(),
},
logger,
);
await connection.start();
await vi.waitFor(() =>
expect(connection.state$.value).toEqual({ state: "stopped" }),
);
});
it("does not report the CS API missing where the homeserver refuses the request", async () => {
setupTest();
const opts = { ...connectionOpts(), role: "publisher" as const };
client.getLivekitToken.mockRejectedValue(
new MatrixError({ errcode: "M_FORBIDDEN" }, 403),
);
const connection = new Connection(opts, logger);
await expect(connection.start()).rejects.toThrow();
expect(opts.onCsApiMissing).not.toHaveBeenCalled();
});
it("retries a join that failed on the WebSocket in Firefox", async () => {
setupTest();
mockUserAgent(FIREFOX_USER_AGENT);
@@ -676,6 +622,230 @@ describe("remote participants", () => {
});
});
describe("receiving video", () => {
it("connects without subscribing while video is not received", async () => {
setupTest();
receiveVideo$.next(false);
const connection = setupRemoteConnection();
await connection.start();
expect(fakeLivekitRoom.connect).toHaveBeenCalledWith(
expect.any(String),
expect.any(String),
{ autoSubscribe: false },
);
});
it("subscribes audio and not video as tracks are published", () => {
setupTest();
receiveVideo$.next(false);
new Connection(connectionOpts(), logger);
const { bob, publications } = remoteParticipantWithTracks(undefined);
for (const publication of Object.values(publications))
fakeLivekitRoom.emit(RoomEvent.TrackPublished, publication, bob);
expect(subscriptions(publications)).toEqual(VIDEO_OFF);
});
it("unsubscribes the video of a participant who connects while video is not received", () => {
setupTest();
receiveVideo$.next(false);
new Connection(connectionOpts(), logger);
// Published under autoSubscribe, as after a full reconnect
const { bob, publications } = remoteParticipantWithTracks(undefined);
fakeLivekitRoom.emit(RoomEvent.ParticipantConnected, bob);
expect(subscriptions(publications)).toEqual(VIDEO_OFF);
});
it.each([RoomEvent.Connected, RoomEvent.Reconnected])(
"sweeps every remote publication on %s",
(event) => {
setupTest();
receiveVideo$.next(false);
new Connection(connectionOpts(), logger);
const { publications } = remoteParticipantWithTracks(undefined);
fakeLivekitRoom.emit(event);
expect(subscriptions(publications)).toEqual(VIDEO_OFF);
},
);
it("follows every change of the choice, without resending what is already asked", () => {
setupTest();
new Connection(connectionOpts(), logger);
const { publications } = remoteParticipantWithTracks(undefined);
receiveVideo$.next(false);
expect(subscriptions(publications)).toEqual(VIDEO_OFF);
expect(publications.microphone.setSubscribed).not.toHaveBeenCalled();
receiveVideo$.next(true);
expect(subscriptions(publications)).toEqual(VIDEO_ON);
});
it("subscribes video again on a connection made while video was not received", () => {
setupTest();
receiveVideo$.next(false);
new Connection(connectionOpts(), logger);
// Published under autoSubscribe: false
const { publications } = remoteParticipantWithTracks(false);
fakeLivekitRoom.emit(RoomEvent.Connected);
expect(subscriptions(publications)).toEqual(VIDEO_OFF);
receiveVideo$.next(true);
expect(subscriptions(publications)).toEqual(VIDEO_ON);
});
it("receives a screen share at its lowest layer while video is not received", () => {
setupTest();
receiveVideo$.next(false);
new Connection(connectionOpts(), logger);
// Published under autoSubscribe: false
const { publications } = remoteParticipantWithTracks(false);
fakeLivekitRoom.emit(RoomEvent.Connected);
expect(publications.screenShare.isDesired).toBe(true);
expect(publications.screenShare.quality).toBe(VideoQuality.LOW);
expect(publications.camera.setVideoQuality).not.toHaveBeenCalled();
});
it("lifts the cap on screen shares when video is received again", () => {
setupTest();
new Connection(connectionOpts(), logger);
const { publications } = remoteParticipantWithTracks(undefined);
receiveVideo$.next(false);
expect(publications.screenShare.quality).toBe(VideoQuality.LOW);
receiveVideo$.next(true);
expect(publications.screenShare.quality).toBe(VideoQuality.HIGH);
expect(publications.screenShare.setSubscribed).not.toHaveBeenCalled();
});
it("caps the screen shares a full reconnect recreates", () => {
setupTest();
receiveVideo$.next(false);
new Connection(connectionOpts(), logger);
remoteParticipantWithTracks(undefined);
fakeLivekitRoom.remoteParticipants.clear();
const { publications } = remoteParticipantWithTracks(undefined);
fakeLivekitRoom.emit(RoomEvent.Reconnected);
expect(publications.screenShare.quality).toBe(VideoQuality.LOW);
});
it("stops following the choice once its scope ends", () => {
setupTest();
new Connection(connectionOpts(), logger);
const { publications } = remoteParticipantWithTracks(undefined);
testScope.end();
receiveVideo$.next(false);
fakeLivekitRoom.emit(RoomEvent.Reconnected);
expect(subscriptions(publications)).toEqual(VIDEO_ON);
});
});
const VIDEO_OFF = {
microphone: true,
camera: false,
screenShare: true,
screenShareAudio: true,
};
const VIDEO_ON = {
microphone: true,
camera: true,
screenShare: true,
screenShareAudio: true,
};
type MockPublication = RemoteTrackPublication & {
setSubscribed: ReturnType<typeof vi.fn>;
setVideoQuality: ReturnType<typeof vi.fn>;
quality: VideoQuality | undefined;
};
type Publications = Record<keyof typeof VIDEO_ON, MockPublication>;
/**
* Bob in the room with a microphone, a camera and a screen share with audio,
* each with the subscription LiveKit gave it: undefined under autoSubscribe.
*/
function remoteParticipantWithTracks(subscribed: boolean | undefined): {
bob: RemoteParticipant;
publications: Publications;
} {
const publications: Publications = {
microphone: mockPublication(
Track.Kind.Audio,
Track.Source.Microphone,
subscribed,
),
camera: mockPublication(Track.Kind.Video, Track.Source.Camera, subscribed),
screenShare: mockPublication(
Track.Kind.Video,
Track.Source.ScreenShare,
subscribed,
),
screenShareAudio: mockPublication(
Track.Kind.Audio,
Track.Source.ScreenShareAudio,
subscribed,
),
};
const bob = mockRemoteParticipant({
identity: "@bob:example.org:DEV111",
trackPublications: new Map(
Object.entries(publications) as [string, RemoteTrackPublication][],
),
});
fakeLivekitRoom.remoteParticipants.set(bob.identity, bob);
return { bob, publications };
}
function mockPublication(
kind: Track.Kind,
source: Track.Source,
subscribed: boolean | undefined,
): MockPublication {
const publication = {
kind,
source,
subscribed,
quality: undefined as VideoQuality | undefined,
get isDesired(): boolean {
return this.subscribed !== false;
},
setSubscribed: vi.fn((value: boolean) => {
publication.subscribed = value;
}),
// As LiveKit, which ignores it on a publication not subscribed
setVideoQuality: vi.fn((value: VideoQuality) => {
if (publication.isDesired) publication.quality = value;
}),
};
return publication as unknown as MockPublication;
}
function subscriptions(
publications: Publications,
): Record<keyof Publications, boolean> {
return Object.fromEntries(
Object.entries(publications).map(([name, publication]) => [
name,
publication.isDesired,
]),
) as Record<keyof Publications, boolean>;
}
describe("remote track logging", () => {
it("logs remote participant and track events on the connection logger", () => {
setupTest();
+77 -45
View File
@@ -19,20 +19,21 @@ import {
type RemoteParticipant,
type RemoteTrackPublication,
type Room as LivekitRoom,
type RoomConnectOptions,
RoomEvent,
type SubscriptionError,
type Track,
Track,
type TrackPublication,
VideoQuality,
} from "livekit-client";
import { type UnstableLivekitTransport } from "matrix-js-sdk/lib/matrixrtc";
import { BehaviorSubject } from "rxjs";
import { BehaviorSubject, distinctUntilChanged, skip } from "rxjs";
import { type Logger } from "matrix-js-sdk/lib/logger";
import { type CallMembershipIdentityParts } from "matrix-js-sdk/lib/matrixrtc/EncryptionManager";
import {
type ClientGetTokenParts,
type ClientOpenIDParts,
type AuthFlow,
type ConnectionRole,
getSFUConfig,
type SFUConfig,
@@ -43,7 +44,6 @@ import {
MatrixRTCError,
InsufficientCapacityError,
LivekitConnectionError,
NoMatrix2AuthorizationService,
PeerConnectionTimeoutError,
SFURoomCreationRestrictedError,
UnknownRTCError,
@@ -60,19 +60,18 @@ export interface ConnectionOpts {
serverName: string;
/** The Matrix client, for the token exchange. */
client: ClientGetTokenParts & ClientOpenIDParts;
/** The flow to authenticate with. */
flow: AuthFlow;
/**
* Called when the client-server API flow finds the API missing while
* authenticating us as a publisher.
*/
onCsApiMissing: () => void;
/** The Matrix room the session is in. */
roomId: string;
/** The MatrixRTC slot the session is in. */
slotId: string;
/** The observable scope to use for this connection. */
scope: ObservableScope;
/**
* Whether remote cameras are subscribed and screen shares received at full
* quality. Read at connect and followed for the connection's lifetime;
* audio and screen shares are always subscribed.
*/
receiveVideo$: Behavior<boolean>;
/** Optional factory to create the LiveKit room, mainly for testing purposes. */
livekitRoomFactory: () => LivekitRoom;
@@ -115,9 +114,6 @@ export class Connection {
/** The homeserver the transport belongs to. */
public readonly serverName: string;
/** The flow that issues this connection's tokens. */
public readonly flow: AuthFlow;
public readonly livekitRoom: LivekitRoom;
private scope: ObservableScope;
@@ -146,11 +142,11 @@ export class Connection {
protected stopped = false;
private readonly client: ClientGetTokenParts & ClientOpenIDParts;
private readonly onCsApiMissing: () => void;
private readonly roomId: string;
private readonly slotId: string;
private readonly logger: Logger;
private readonly ownMembershipIdentity: CallMembershipIdentityParts;
private readonly receiveVideo$: Behavior<boolean>;
/**
* Creates a new connection to a matrix RTC LiveKit backend.
*
@@ -174,14 +170,14 @@ export class Connection {
this.transport = transport;
this.serverName = serverName;
this.client = client;
this.flow = opts.flow;
this.onCsApiMissing = opts.onCsApiMissing;
this.receiveVideo$ = opts.receiveVideo$;
this.remoteParticipants$ = scope.behavior(
// Only tracks remote participants
connectedParticipantsObserver(this.livekitRoom),
);
this.logRemoteTrackEvents();
this.applyReceivePolicy();
scope.onEnd(() => {
this.logger.info(`Connection scope ended, stopping connection`);
@@ -189,6 +185,53 @@ export class Connection {
});
}
/**
* Keeps every remote publication subscribed or not, and every screen share
* at the quality, that `receiveVideo$` asks for. A full reconnect recreates
* the remote participants with the subscriptions the room first connected
* with, and events for participants already in the room are not emitted
* while it connects, so the whole room is swept again on `Connected` and
* `Reconnected`.
*/
private applyReceivePolicy(): void {
const room = this.livekitRoom;
const reconcile = (publication: RemoteTrackPublication): void => {
const receiveVideo = this.receiveVideo$.value;
const isScreenShare = publication.source === Track.Source.ScreenShare;
const wanted =
publication.kind !== Track.Kind.Video || isScreenShare || receiveVideo;
// Every call sends a subscription update, wanted or not
if (publication.isDesired !== wanted) publication.setSubscribed(wanted);
// Ignored by LiveKit until the publication is subscribed
if (isScreenShare)
publication.setVideoQuality(
receiveVideo ? VideoQuality.HIGH : VideoQuality.LOW,
);
};
const reconcileParticipant = (participant: RemoteParticipant): void =>
participant.trackPublications.forEach(reconcile);
const reconcileAll = (): void =>
room.remoteParticipants.forEach(reconcileParticipant);
const onTrackPublished = (publication: RemoteTrackPublication): void =>
reconcile(publication);
room
.on(RoomEvent.TrackPublished, onTrackPublished)
.on(RoomEvent.ParticipantConnected, reconcileParticipant)
.on(RoomEvent.Connected, reconcileAll)
.on(RoomEvent.Reconnected, reconcileAll);
this.receiveVideo$
.pipe(distinctUntilChanged(), skip(1), this.scope.bind())
.subscribe(reconcileAll);
this.scope.onEnd(() => {
room
.off(RoomEvent.TrackPublished, onTrackPublished)
.off(RoomEvent.ParticipantConnected, reconcileParticipant)
.off(RoomEvent.Connected, reconcileAll)
.off(RoomEvent.Reconnected, reconcileAll);
});
}
/**
* Logs the lifecycle of remote participants and their tracks as seen by
* livekit-client, so that rageshakes show what a tile should have been
@@ -400,7 +443,7 @@ export class Connection {
private async connectLivekitRoom(url: string, jwt: string): Promise<void> {
try {
await this.livekitRoom.connect(url, jwt);
await this.livekitRoom.connect(url, jwt, this.connectOptions());
} catch (e) {
// Behind a proxy, Firefox fails the first WebSocket to a host after trying
// it over HTTP/2, so a join that fails on the WebSocket gets a second try.
@@ -411,37 +454,26 @@ export class Connection {
e.reason === ConnectionErrorReason.WebSocket;
if (this.stopped || !failedOnFirefoxWebSocket) throw e;
this.logger.info(`livekitRoom.connect RETRY ${url}`, e);
await this.livekitRoom.connect(url, jwt);
await this.livekitRoom.connect(url, jwt, this.connectOptions());
}
}
/** A connection made while cameras are not received never asks the SFU for them. */
private connectOptions(): RoomConnectOptions {
return { autoSubscribe: this.receiveVideo$.value };
}
protected async getSFUConfig(): Promise<SFUConfig> {
try {
return await getSFUConfig({
client: this.client,
membership: this.ownMembershipIdentity,
role: this.role,
flow: this.flow,
serverName: this.serverName,
roomId: this.roomId,
slotId: this.slotId,
logger: this.logger,
});
} catch (e) {
// If authenticating through the CS API failed and we are the publisher
// connection, trigger the callback before the error surfaces. If falling
// back to the OpenID flow is possible, the connection is stopped and
// replaced, so it never shows as failed.
//
// Subscriber connections are explicitly excluded here because the publishing
// connection may already have authenticated and delegated its delayed leave.
if (
e instanceof NoMatrix2AuthorizationService &&
this.role === "publisher"
)
this.onCsApiMissing();
throw e;
}
return await getSFUConfig({
client: this.client,
membership: this.ownMembershipIdentity,
role: this.role,
transport: this.transport,
serverName: this.serverName,
roomId: this.roomId,
slotId: this.slotId,
logger: this.logger,
});
}
/**
@@ -7,22 +7,22 @@ Please see LICENSE in the repository root for full details.
import {
ConnectionState as LivekitConnectionState,
type RemoteParticipant,
type RemoteTrackPublication,
type RoomOptions,
Track,
} from "livekit-client";
import { BehaviorSubject } from "rxjs";
import { logger } from "matrix-js-sdk/lib/logger";
import { type UnstableLivekitTransport } from "matrix-js-sdk/lib/matrixrtc";
import { describe, expect, it, vi } from "vitest";
import { type MediaQuality } from "../../config";
import { type PublishRequest } from "../../media-api";
import { constant } from "../../reactive/Behavior";
import { type Behavior, constant } from "../../reactive/Behavior";
import { ownMemberMock, testScope } from "../../utils/test";
import { testJWTToken } from "../../utils/test-fixtures";
import {
type ClientGetTokenParts,
type ClientOpenIDParts,
chooseAuthFlow,
} from "./auth";
import { type ClientGetTokenParts, type ClientOpenIDParts } from "./auth";
import {
LivekitConnectionFactory,
type ResolvedConnection,
@@ -51,14 +51,15 @@ function create(
mediaQuality?: MediaQuality,
audioOutputDeviceId?: string,
transport = exampleTransport,
receiveVideo$: Behavior<boolean> = constant(true),
): { connection: ResolvedConnection; options: RoomOptions } {
const factory = new LivekitConnectionFactory(
client(),
() => {},
"!room:example.org",
"m.call#ROOM",
publish,
constant(audioOutputDeviceId),
receiveVideo$,
undefined,
mediaQuality,
);
@@ -67,7 +68,6 @@ function create(
"subscriber",
transport,
"example.org",
chooseAuthFlow(transport, true),
ownMemberMock,
logger,
) as ResolvedConnection;
@@ -75,6 +75,29 @@ function create(
}
describe("LivekitConnectionFactory", () => {
it("gives each connection the receive video choice to follow", () => {
const receiveVideo$ = new BehaviorSubject(true);
const { connection } = create(
[],
undefined,
undefined,
undefined,
receiveVideo$,
);
const camera = {
kind: Track.Kind.Video,
isDesired: true,
setSubscribed: vi.fn(),
} as unknown as RemoteTrackPublication;
connection.livekitRoom.remoteParticipants.set("@bob:example.org:DEV", {
trackPublications: new Map([["camera", camera]]),
} as unknown as RemoteParticipant);
receiveVideo$.next(false);
expect(camera.setSubscribed).toHaveBeenCalledWith(false);
});
it("builds the room on the defaults where nothing is requested", () => {
const { options } = create([]);
@@ -24,7 +24,6 @@ import { type PublishRequest } from "../../media-api";
import { type Behavior } from "../../reactive/Behavior";
import { type ObservableScope } from "../../reactive/ObservableScope";
import {
type AuthFlow,
type ClientGetTokenParts,
type ClientOpenIDParts,
type ConnectionRole,
@@ -45,7 +44,6 @@ export interface ConnectionFactory {
role: ConnectionRole,
transport: UnstableLivekitTransport,
serverName: string,
flow: AuthFlow,
ownMembershipIdentity: CallMembershipIdentityParts,
logger: Logger,
): Connection;
@@ -104,11 +102,11 @@ function resolvedTransport(config: SFUConfig): ResolvedTransport {
export class LivekitConnectionFactory implements ConnectionFactory {
public constructor(
private readonly client: ClientGetTokenParts & ClientOpenIDParts,
private readonly onCsApiMissing: () => void,
private readonly roomId: string,
private readonly slotId: string,
private readonly publish: PublishRequest[],
private readonly audioOutputDeviceId$: Behavior<string | undefined>,
private readonly receiveVideo$: Behavior<boolean>,
private readonly keyProvider: BaseKeyProvider | undefined,
private readonly mediaQuality: MediaQuality | undefined,
) {}
@@ -118,7 +116,6 @@ export class LivekitConnectionFactory implements ConnectionFactory {
role: ConnectionRole,
transport: UnstableLivekitTransport,
serverName: string,
flow: AuthFlow,
ownMembershipIdentity: CallMembershipIdentityParts,
logger: Logger,
): Connection {
@@ -129,10 +126,9 @@ export class LivekitConnectionFactory implements ConnectionFactory {
role,
transport,
serverName,
flow,
client: this.client,
onCsApiMissing: this.onCsApiMissing,
scope,
receiveVideo$: this.receiveVideo$,
livekitRoomFactory: () =>
new LivekitRoom(
roomOptions(
@@ -16,7 +16,11 @@ import {
mapEpoch,
ObservableScope,
} from "../../reactive/ObservableScope";
import { createConnectionMap$, ConnectionMap } from "./ConnectionMap.ts";
import {
createConnectionMap$,
ConnectionMap,
keyFor,
} from "./ConnectionMap.ts";
import { type ConnectionFactory } from "./ConnectionFactory.ts";
import { type Connection } from "./Connection.ts";
import { ownMemberMock, withTestScheduler } from "../../utils/test";
@@ -39,33 +43,6 @@ const TRANSPORT_2: TransportLocator = {
serverName: "sample.com",
};
const SERVICE_URL_TRANSPORT: TransportLocator = {
transport: {
type: "livekit",
livekit_service_url: "https://jwt.example.org",
},
serverName: "example.org",
};
const URL_TRANSPORT: TransportLocator = {
transport: { type: "livekit", url: "wss://sfu.example.org" },
serverName: "example.org",
};
/** Names the same SFU as URL_TRANSPORT and the same service as SERVICE_URL_TRANSPORT. */
const URL_AND_SERVICE_URL_TRANSPORT: TransportLocator = {
transport: {
type: "livekit",
url: "wss://sfu.example.org",
livekit_service_url: "https://jwt.example.org",
},
serverName: "example.org",
};
/** Tells the locators used here apart; not the key the map folds them by. */
const keyFor = ({ transport, serverName }: TransportLocator): string =>
JSON.stringify([transport, serverName]);
function findConnection(
transport: TransportLocator,
connections: Connection[],
@@ -120,7 +97,7 @@ describe("connections$ stream", () => {
const connectionMap$ = createConnectionMap$({
scope: testScope,
connectionFactory: fakeConnectionFactory,
localTransport: { ...TRANSPORT_1, csApiUsable: true },
localTransport: TRANSPORT_1,
remoteTransports$: behavior("a", {
a: new Epoch([TRANSPORT_1, TRANSPORT_2], 0),
}),
@@ -157,7 +134,7 @@ describe("connections$ stream", () => {
const connectionMap$ = createConnectionMap$({
scope: testScope,
connectionFactory: fakeConnectionFactory,
localTransport: { ...TRANSPORT_1, csApiUsable: true },
localTransport: TRANSPORT_1,
remoteTransports$: behavior("a", {
a: new Epoch([TRANSPORT_2], 0),
}),
@@ -173,7 +150,6 @@ describe("connections$ stream", () => {
"publisher",
TRANSPORT_1.transport,
TRANSPORT_1.serverName,
{ kind: "openID", serviceUrl: "https://lk.example.org" },
ownMemberMock,
expect.anything(),
);
@@ -182,7 +158,6 @@ describe("connections$ stream", () => {
"subscriber",
TRANSPORT_2.transport,
TRANSPORT_2.serverName,
{ kind: "openID", serviceUrl: "https://lk.sample.com" },
ownMemberMock,
expect.anything(),
);
@@ -201,7 +176,7 @@ describe("connections$ stream", () => {
const connectionMap$ = createConnectionMap$({
scope: testScope,
connectionFactory: fakeConnectionFactory,
localTransport: { ...TRANSPORT_1, csApiUsable: true },
localTransport: TRANSPORT_1,
remoteTransports$: behavior("a", {
a: new Epoch([sameServiceElsewhere], 0),
}),
@@ -223,7 +198,6 @@ describe("connections$ stream", () => {
"publisher",
TRANSPORT_1.transport,
"example.org",
{ kind: "openID", serviceUrl: "https://lk.example.org" },
expect.anything(),
expect.anything(),
);
@@ -246,7 +220,7 @@ describe("connections$ stream", () => {
const connectionMap$ = createConnectionMap$({
scope: testScope,
connectionFactory: fakeConnectionFactory,
localTransport: { ...urlTransport, csApiUsable: true },
localTransport: urlTransport,
remoteTransports$: behavior("a", {
a: new Epoch([sameUrlElsewhere], 0),
}),
@@ -269,42 +243,42 @@ describe("connections$ stream", () => {
});
});
test("Shares connection between url transport and url + livekit_service_url transport", () => {
withTestScheduler(({ expectObservable, scope }) => {
test("Shares connection between local livekit_service_url transport and remote url + livekit_service_url transport", () => {
withTestScheduler(({ behavior, expectObservable, scope }) => {
const serviceUrlTransport: TransportLocator = {
transport: {
type: "livekit",
livekit_service_url: "https://jwt.example.org",
},
serverName: "example.org",
};
const urlAndServiceUrlTransport: TransportLocator = {
transport: {
type: "livekit",
livekit_service_url: "https://jwt.example.org",
url: "wss://sfu.elsewhere.org",
},
// Should pass even if local server != remote server
serverName: "elsewhere.org",
};
const connectionMap$ = createConnectionMap$({
scope,
connectionFactory: fakeConnectionFactory,
localTransport: { ...URL_AND_SERVICE_URL_TRANSPORT, csApiUsable: true },
remoteTransports$: constant(
new Epoch([URL_TRANSPORT, SERVICE_URL_TRANSPORT]),
),
localTransport: serviceUrlTransport,
remoteTransports$: constant(new Epoch([urlAndServiceUrlTransport])),
logger,
ownMembershipIdentity: ownMemberMock,
});
expectObservable(connectionMap$).toBe("a", {
a: expect.toSatisfy(({ value: map }: Epoch<ConnectionMap>) => {
// Both get the CS API flow, and with it the same identity on the
// same SFU. The JWT service assigns another, so it may stay apart.
expect(map.getConnections().length).toBe(2);
const shared = map.getConnectionForTransport(
URL_AND_SERVICE_URL_TRANSPORT,
);
expect(shared).not.toBeNull();
expect(map.getConnectionForTransport(URL_TRANSPORT)).toBe(shared);
expect(map.getConnectionForTransport(SERVICE_URL_TRANSPORT)).not.toBe(
shared,
);
expect(
vi.mocked(fakeConnectionFactory).createConnection,
).toHaveBeenCalledWith(
expect.anything(),
"publisher",
URL_AND_SERVICE_URL_TRANSPORT.transport,
"example.org",
{ kind: "csApi", url: "wss://sfu.example.org" },
ownMemberMock,
expect.anything(),
expectObservable(
connectionMap$.pipe(mapEpoch((d) => d.getConnections())),
).toBe("a", {
a: expect.toSatisfy(({ value: cs }: Epoch<Connection[]>) => {
// One connection total, since local and remote connections are shared
expect(cs.length).toBe(1);
expect(findConnection(serviceUrlTransport, cs)).toBeDefined();
expect(findConnection(serviceUrlTransport, cs)).toBe(
findConnection(urlAndServiceUrlTransport, cs),
);
return true;
}),
@@ -312,34 +286,44 @@ describe("connections$ stream", () => {
});
});
test("Shares connection between livekit_service_url transport and url + livekit_service_url transport without the CS API", () => {
withTestScheduler(({ expectObservable, scope }) => {
test("Shares connection between remote livekit_service_url transport and remote url + livekit_service_url transport", () => {
withTestScheduler(({ behavior, expectObservable, scope }) => {
const serviceUrlTransport: TransportLocator = {
transport: {
type: "livekit",
livekit_service_url: "https://jwt.example.org",
},
serverName: "example.org",
};
const urlAndServiceUrlTransport: TransportLocator = {
transport: {
type: "livekit",
livekit_service_url: "https://jwt.example.org",
url: "wss://sfu.elsewhere.org",
},
// Should pass even if local server != remote server
serverName: "elsewhere.org",
};
const connectionMap$ = createConnectionMap$({
scope,
connectionFactory: fakeConnectionFactory,
localTransport: { ...SERVICE_URL_TRANSPORT, csApiUsable: false },
localTransport: TRANSPORT_2,
remoteTransports$: constant(
new Epoch([
{
...URL_AND_SERVICE_URL_TRANSPORT,
// Should pass even if local server != remote server
serverName: "elsewhere.org",
},
]),
new Epoch([serviceUrlTransport, urlAndServiceUrlTransport]),
),
logger,
ownMembershipIdentity: ownMemberMock,
});
expectObservable(connectionMap$).toBe("a", {
a: expect.toSatisfy(({ value: map }: Epoch<ConnectionMap>) => {
// One connection total, since both go through the same JWT service
expect(map.getConnections().length).toBe(1);
expect(
map.getConnectionForTransport(SERVICE_URL_TRANSPORT),
).not.toBeNull();
expect(map.getConnectionForTransport(SERVICE_URL_TRANSPORT)).toBe(
map.getConnectionForTransport(URL_AND_SERVICE_URL_TRANSPORT),
expectObservable(
connectionMap$.pipe(mapEpoch((d) => d.getConnections())),
).toBe("a", {
a: expect.toSatisfy(({ value: cs }: Epoch<Connection[]>) => {
// Two connections total: a local connection and a shared remote connection
expect(cs.length).toBe(2);
expect(findConnection(serviceUrlTransport, cs)).toBeDefined();
expect(findConnection(serviceUrlTransport, cs)).toBe(
findConnection(urlAndServiceUrlTransport, cs),
);
return true;
}),
@@ -347,35 +331,12 @@ describe("connections$ stream", () => {
});
});
test("Publishes on a url + livekit_service_url transport through the JWT service without the CS API", () => {
createConnectionMap$({
scope: testScope,
connectionFactory: fakeConnectionFactory,
localTransport: { ...URL_AND_SERVICE_URL_TRANSPORT, csApiUsable: false },
remoteTransports$: constant(new Epoch([])),
logger,
ownMembershipIdentity: ownMemberMock,
});
expect(
vi.mocked(fakeConnectionFactory).createConnection,
).toHaveBeenCalledExactlyOnceWith(
expect.anything(),
"publisher",
URL_AND_SERVICE_URL_TRANSPORT.transport,
"example.org",
{ kind: "openID", serviceUrl: "https://jwt.example.org" },
ownMemberMock,
expect.anything(),
);
});
test("Should start connection only once", () => {
withTestScheduler(({ behavior, expectObservable }) => {
const connectionMap$ = createConnectionMap$({
scope: testScope,
connectionFactory: fakeConnectionFactory,
localTransport: { ...TRANSPORT_1, csApiUsable: true },
localTransport: TRANSPORT_1,
remoteTransports$: behavior("abcdef", {
a: new Epoch([TRANSPORT_1], 0),
b: new Epoch([TRANSPORT_1], 1),
@@ -418,7 +379,7 @@ describe("connections$ stream", () => {
const connectionMap$ = createConnectionMap$({
scope: testScope,
connectionFactory: fakeConnectionFactory,
localTransport: { ...TRANSPORT_1, csApiUsable: true },
localTransport: TRANSPORT_1,
remoteTransports$: behavior("abc", {
a: new Epoch([TRANSPORT_1], 0),
b: new Epoch([TRANSPORT_1, TRANSPORT_2], 1),
@@ -461,21 +422,9 @@ describe("connections$ stream", () => {
});
describe("ConnectionMap", () => {
test("hands out the connection we publish on, if any", () => {
const connection = (role: string, locator: TransportLocator): Connection =>
({ role, ...locator }) as unknown as Connection;
const data = new ConnectionMap(true);
expect(data.getPublisherConnection()).toBeNull();
const publisher = connection("publisher", TRANSPORT_1);
data.add(connection("subscriber", TRANSPORT_2), []);
data.add(publisher, []);
expect(data.getPublisherConnection()).toBe(publisher);
});
test("warns when a second connection to the same URL is merged", () => {
const warn = vi.spyOn(logger, "warn").mockImplementation(() => {});
const data = new ConnectionMap(true, logger);
const data = new ConnectionMap(logger);
const connection = TRANSPORT_1 as unknown as Connection;
const p = (identity: string): RemoteParticipant =>
({ identity }) as unknown as RemoteParticipant;
@@ -571,7 +520,7 @@ describe("connectionMap$", () => {
const connectionMap$ = createConnectionMap$({
scope: testScope,
connectionFactory: fakeConnectionFactory,
localTransport: { ...TRANSPORT_1, csApiUsable: true },
localTransport: TRANSPORT_1,
remoteTransports$: behavior("a", {
a: new Epoch([TRANSPORT_1, TRANSPORT_2], 0),
}),
+58 -70
View File
@@ -18,67 +18,63 @@ import {
type ObservableScope,
} from "../../reactive/ObservableScope";
import { generateItemsWithEpoch } from "../../reactive/observable";
import { chooseAuthFlow, type TransportLocator } from "./auth";
import {
chooseAuthFlow,
type ConnectionRole,
type TransportLocator,
} from "./auth";
import { type Connection } from "./Connection";
import { type ConnectionFactory } from "./ConnectionFactory";
// Branded, so that only values returned by `connectionKey` can be used as keys
type ConnectionKey = string & { __connectionKey: true };
// Branded, so that only values returned by `keyFor` can be used as keys
export type TransportKey = string & { __transportKey: true };
/**
* Converts a {@link TransportLocator} to a key suitable for identifying it in a
* map of connections.
*
* @param csApiUsable - Whether the map the key is for uses the client-server API
* where a transport leaves the choice.
*
* Note that we deliberately don't use `TransportLocatorWithCsSupport` to infer
* `csApiUsable`. That setting would be transport-specific. Instead, `csApiUsable`
* is passed in from the connection map's own setting, fixed at creation time.
*/
function connectionKey(
{ transport, serverName }: TransportLocator,
csApiUsable: boolean,
): ConnectionKey {
export function keyFor({
transport,
serverName,
}: TransportLocator): TransportKey {
// Base the key on the auth flow we would use, so that we never create two
// connections that share the same auth details. (That would be bad, as we
// might then try to connect to the same SFU twice with the same participant
// ID, resulting in only one working connection.)
const flow = chooseAuthFlow(transport, csApiUsable);
// TODO: This strategy will not work once `chooseAuthFlow` begins allowing for
// falling back from the CS API flow to the OpenID flow.
const flow = chooseAuthFlow(transport);
// Serialize the fields in a consistent order
return JSON.stringify([
flow.kind,
// With the CS API flow, we additionally need to distinguish server names
...(flow.kind === "csApi" ? [flow.url, serverName] : [flow.serviceUrl]),
]) as ConnectionKey;
]) as TransportKey;
}
/** The transport we publish on, with what is fixed for its connection map. */
export interface TransportLocatorWithCsSupport extends TransportLocator {
/**
* Whether a transport naming both a `url` and a `livekit_service_url` is
* reached through the client-server API.
*/
csApiUsable: boolean;
function removeDuplicateTransports(
transports: TransportLocator[],
): TransportLocator[] {
// The first locator wins, so the local one stays first in the list
const map = new Map<TransportKey, TransportLocator>();
for (const transport of transports) {
const key = keyFor(transport);
if (!map.has(key)) map.set(key, transport);
}
return [...map.values()];
}
/** The connections at one moment, with the remote participants seen on each. */
export class ConnectionMap {
private readonly map = new Map<
ConnectionKey,
TransportKey,
{ connection: Connection; participants: RemoteParticipant[] }
>();
/**
* @param csApiUsable - What the connections were keyed with.
*/
public constructor(
private readonly csApiUsable: boolean,
private readonly logger?: Logger,
) {}
public constructor(private readonly logger?: Logger) {}
public add(connection: Connection, participants: RemoteParticipant[]): void {
const key = connectionKey(connection, this.csApiUsable);
const key = keyFor(connection);
const existing = this.map.get(key);
if (!existing) {
this.map.set(key, { connection, participants });
@@ -96,25 +92,16 @@ export class ConnectionMap {
return Array.from(this.map.values()).map(({ connection }) => connection);
}
/** The connection we publish on or `null` if no publishing connection exists in the map. */
public getPublisherConnection(): Connection | null {
return (
this.getConnections().find(({ role }) => role === "publisher") ?? null
);
}
public getConnectionForTransport(
transport: TransportLocator,
): Connection | null {
const key = connectionKey(transport, this.csApiUsable);
return this.map.get(key)?.connection ?? null;
return this.map.get(keyFor(transport))?.connection ?? null;
}
public getParticipantsForTransport(
transport: TransportLocator,
): RemoteParticipant[] {
const key = connectionKey(transport, this.csApiUsable);
return this.map.get(key)?.participants ?? [];
return this.map.get(keyFor(transport))?.participants ?? [];
}
}
@@ -122,7 +109,7 @@ interface Props {
scope: ObservableScope;
connectionFactory: ConnectionFactory;
/** The transport we publish on; the one connection with the publisher role. */
localTransport: TransportLocatorWithCsSupport;
localTransport: TransportLocator;
/** Every transport some member is on, deduplicated against the local one. */
remoteTransports$: Behavior<Epoch<TransportLocator[]>>;
logger: Logger;
@@ -143,41 +130,42 @@ export function createConnectionMap$({
ownMembershipIdentity,
}: Props): Behavior<Epoch<ConnectionMap>> {
const logger = parentLogger.getChild("[ConnectionMap]");
const { csApiUsable } = localTransport;
const transportsByKey$ = scope.behavior(
remoteTransports$.pipe(
mapEpoch(
(remote) =>
// The last locator wins a key, so the local one goes last
new Map(
[...remote, localTransport].map((transport) => [
connectionKey(transport, csApiUsable),
transport,
]),
),
const localAndRemoteTransports$: Behavior<Epoch<TransportLocator[]>> =
scope.behavior(
remoteTransports$.pipe(
mapEpoch((remoteTransports) =>
removeDuplicateTransports([localTransport, ...remoteTransports]),
),
tap((transports) =>
logger.debug("localAndRemoteTransports$ = ", transports),
),
),
tap(({ value }) =>
logger.debug("transportsByKey$ = ", [...value.values()]),
),
),
);
);
const localTransportKey = keyFor(localTransport);
const localTransportKey = connectionKey(localTransport, csApiUsable);
const connections$ = scope.behavior(
transportsByKey$.pipe(
localAndRemoteTransports$.pipe(
generateItemsWithEpoch(
"ConnectionMap connections$",
// The locator is an object, so a stable key stands in for it
(byKey) => Array.from(byKey, ([key, data]) => ({ keys: [key], data })),
(scope, locator$, key) => {
function* (transports) {
for (const transport of transports) {
const role: ConnectionRole =
keyFor(transport) === localTransportKey
? "publisher"
: "subscriber";
// The locator is an object, so a stable key stands in for it
yield { keys: [role, keyFor(transport)], data: transport };
}
},
(scope, locator$, role, _key) => {
const { transport, serverName } = locator$.value;
const connection = connectionFactory.createConnection(
scope,
key === localTransportKey ? "publisher" : "subscriber",
role,
transport,
serverName,
chooseAuthFlow(transport, csApiUsable),
ownMembershipIdentity,
logger,
);
@@ -193,7 +181,7 @@ export function createConnectionMap$({
connections$.pipe(
switchMap(({ value: connections, epoch }) => {
if (connections.length === 0)
return of(new Epoch(new ConnectionMap(csApiUsable), epoch));
return of(new Epoch(new ConnectionMap(), epoch));
return combineLatest(
connections.map((connection) =>
connection.remoteParticipants$.pipe(
@@ -201,7 +189,7 @@ export function createConnectionMap$({
),
),
(...list) => {
const map = new ConnectionMap(csApiUsable, logger);
const map = new ConnectionMap(logger);
for (const item of list)
map.add(item.connection, item.participants);
return new Epoch(map, epoch);
@@ -54,7 +54,7 @@ function setup(connections: Connection[]): {
connections$: BehaviorSubject<Epoch<ConnectionMap>>;
sendData: (topic: string, text: string) => Promise<void>;
} {
const data = new ConnectionMap(true);
const data = new ConnectionMap();
for (const connection of connections) data.add(connection, []);
const connections$ = new BehaviorSubject(new Epoch(data));
const { data$, sendData } = createDataChannel$({
@@ -99,7 +99,7 @@ describe("data$", () => {
const second = fakeConnection("https://sfu-2");
const { received, connections$ } = setup([first.connection]);
const data = new ConnectionMap(true);
const data = new ConnectionMap();
data.add(first.connection, []);
data.add(second.connection, []);
connections$.next(new Epoch(data, 1));
@@ -148,6 +148,7 @@ describe("toMediaConnectionState", () => {
describe("createLivekitBackend", () => {
const homeserver = "https://matrix.example.org";
const homeserverEndpoint = `${homeserver}/_matrix/client/unstable/io.element.msc4195/rtc/livekit/delegate_delayed_leave`;
const urlTransport: UnstableLivekitTransport = {
type: "livekit",
url: "wss://sfu.example.org",
@@ -168,7 +169,10 @@ describe("createLivekitBackend", () => {
participants$: BehaviorSubject<RemoteParticipant[]>;
state$: BehaviorSubject<ConnectionState>;
}[];
let onCsApiMissing: () => void;
/** What the backend built the factory with. */
let factoryArgs: ConstructorParameters<
typeof connectionFactory.LivekitConnectionFactory
>;
const connected: ConnectionState = {
state: "authenticated",
livekitState: LivekitConnectionState.Connected,
@@ -177,15 +181,19 @@ describe("createLivekitBackend", () => {
/** Stands in for the factory: connections whose state and participants the test drives. */
function stubFactory(initialState: ConnectionState): void {
vi.spyOn(connectionFactory, "LivekitConnectionFactory").mockImplementation(
function (this: unknown, _client, onMissing) {
onCsApiMissing = onMissing;
function (
this: unknown,
...args: ConstructorParameters<
typeof connectionFactory.LivekitConnectionFactory
>
) {
factoryArgs = args;
return {
createConnection: (
scope: ObservableScope,
role: auth.ConnectionRole,
transport: UnstableLivekitTransport,
serverName: string,
flow: auth.AuthFlow,
): Connection => {
const participants$ = new BehaviorSubject<RemoteParticipant[]>([]);
const state$ = new BehaviorSubject<ConnectionState>(initialState);
@@ -193,7 +201,6 @@ describe("createLivekitBackend", () => {
role,
transport,
serverName,
flow,
state$,
remoteParticipants$: scope.behavior(participants$),
livekitRoom: fakeLivekitRoom(),
@@ -235,15 +242,17 @@ describe("createLivekitBackend", () => {
}
// Delegation goes through whichever service authenticates us as a
// publisher.
// publisher: the JWT service wherever the transport names one, the
// homeserver for a `url` alone
it.each([
["a JWT service that delegates", exampleTransport, 401, true],
["a JWT service that does not delegate", exampleTransport, 404, false],
["the homeserver over the JWT service", bothTransport, 404, true],
["the homeserver", urlTransport, 404, true],
["the JWT service", exampleTransport, 404, 401, true],
["the JWT service, and only it", bothTransport, 401, 404, false],
["the homeserver", urlTransport, 401, 404, true],
["neither", exampleTransport, 404, 404, false],
])(
"prepares the local transport for delegation through %s",
async (_name, transport, serviceStatus, expected) => {
"prepares the local transport and asks %s about delegation",
async (_name, transport, homeserverStatus, serviceStatus, expected) => {
fetchMock.post(homeserverEndpoint, homeserverStatus);
fetchMock.post(
`${exampleServiceUrl}/delegate_delayed_leave`,
serviceStatus,
@@ -252,10 +261,6 @@ describe("createLivekitBackend", () => {
const capabilities = await backend().prepareLocalTransport(transport);
expect(capabilities).toEqual({ canDelegateDelayedLeave: expected });
// Only the service that issued the publisher's token is asked.
expect(
fetchMock.called(`${exampleServiceUrl}/delegate_delayed_leave`),
).toBe(transport === exampleTransport);
expect(connections).toHaveLength(1);
expect(connections[0].connection.role).toBe("publisher");
expect(connections[0].connection.transport).toEqual(transport);
@@ -263,9 +268,21 @@ describe("createLivekitBackend", () => {
},
);
it("hands every connection the factory makes the receive video choice, true until set", () => {
const b = backend();
const receiveVideo$ = factoryArgs[5];
expect(receiveVideo$.value).toBe(true);
b.setReceiveVideo(false);
expect(receiveVideo$.value).toBe(false);
b.setReceiveVideo(true);
expect(receiveVideo$.value).toBe(true);
});
it("prepares a remote SFU's transport on its homeserver, where delegation is not possible", async () => {
// A token through the homeserver means delegation, unless the SFU is
// another homeserver's.
// Our own homeserver would delegate, so only the SFU being remote can
// explain delegation being skipped
fetchMock.post(homeserverEndpoint, 401);
const remoteTransport: UnstableLivekitTransport = {
type: "livekit",
url: "wss://sfu.sample.com",
@@ -280,6 +297,7 @@ describe("createLivekitBackend", () => {
});
it("waits for the publisher connection to hold its token before the join", async () => {
fetchMock.post(homeserverEndpoint, 404);
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 404);
stubFactory({ state: "authenticating" });
@@ -296,6 +314,7 @@ describe("createLivekitBackend", () => {
});
it("fails the preparation with the publisher connection's error", async () => {
fetchMock.post(homeserverEndpoint, 404);
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 404);
stubFactory({ state: "authenticating" });
const preparing = backend().prepareLocalTransport(exampleTransport);
@@ -305,60 +324,8 @@ describe("createLivekitBackend", () => {
await expect(preparing).rejects.toBe(error);
});
it.each([
["names no JWT service", urlTransport],
["names no url", exampleTransport],
])(
"keeps its connections where the CS API is found missing and our transport %s",
async (_what, transport) => {
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 404);
await backend().prepareLocalTransport(transport);
onCsApiMissing();
expect(connections).toHaveLength(1);
},
);
it("moves the publisher to the JWT service where the CS API is found missing", async () => {
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 401);
const delegate = vi.spyOn(auth, "delegateDelayedLeave").mockResolvedValue();
stubFactory({ state: "authenticating" });
const b = backend();
let prepared = false;
const preparing = b.prepareLocalTransport(bothTransport).then((c) => {
prepared = true;
return c;
});
await flushPromises();
expect(connections).toHaveLength(1);
expect(connections[0].connection.flow.kind).toBe("csApi");
// The publisher's token request finds no API.
onCsApiMissing();
expect(connections).toHaveLength(2);
expect(connections[1].connection.role).toBe("publisher");
expect(connections[1].connection.transport).toEqual(bothTransport);
expect(connections[1].connection.flow.kind).toBe("openID");
// The replaced connection winding down is not the preparation failing.
connections[0].state$.next({ state: "stopped" });
await flushPromises();
expect(prepared).toBe(false);
connections[1].state$.next(connected);
expect(await preparing).toEqual({ canDelegateDelayedLeave: true });
expect(
fetchMock.called(`${exampleServiceUrl}/delegate_delayed_leave`),
).toBe(true);
await b.delegateDelayedLeave("delay-1");
expect(delegate.mock.calls[0][0].flow).toEqual({
kind: "openID",
serviceUrl: exampleServiceUrl,
});
});
it("delegates the leave through the flow that authenticated the publisher", async () => {
fetchMock.post(homeserverEndpoint, 401);
const delegate = vi.spyOn(auth, "delegateDelayedLeave").mockResolvedValue();
const b = backend();
await expect(b.delegateDelayedLeave("delay-1")).rejects.toThrow(
@@ -372,7 +339,7 @@ describe("createLivekitBackend", () => {
expect.objectContaining({
client,
membership: ownMemberMock,
flow: { kind: "csApi", url: "wss://sfu.example.org" },
transport: urlTransport,
roomId: "!room:example.org",
slotId: "m.call#ROOM",
delayId: "delay-1",
@@ -414,6 +381,7 @@ describe("createLivekitBackend", () => {
async function prepared(): Promise<
ReturnType<typeof createLivekitBackend>
> {
fetchMock.post(homeserverEndpoint, 404);
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 404);
const b = backend();
await b.prepareLocalTransport(bothTransport);
@@ -445,30 +413,6 @@ describe("createLivekitBackend", () => {
},
);
it("reaches a url + livekit_service_url member through the JWT service where our transport names no url", async () => {
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 404);
const b = backend();
await b.prepareLocalTransport(exampleTransport);
const media = b.mediaFor(
testScope(),
bob(bothTransport, [hashedId, legacyId]),
);
await flushPromises();
// Bob names our JWT service, so no connection of his own, and none
// through a client-server API our homeserver does not have
expect(connections).toHaveLength(1);
expect(connections[0].connection.flow.kind).toBe("openID");
connections[0].participants$.next([
mockRemoteParticipant({
identity: hashedId,
trackPublications: new Map(),
}),
]);
await flushPromises();
expect(media.tracks$.value).toEqual([]);
});
it("does not match a member with two candidate identities to anyone else", async () => {
const b = await prepared();
const media = b.mediaFor(
@@ -540,11 +484,10 @@ describe("createLivekitBackend", () => {
(c) => c.connection.role === "subscriber",
);
expect(remote?.connection.transport).toEqual(otherTransport);
const transports = b.connections$.value.map(({ transport }) => transport);
expect(transports).toHaveLength(2);
expect(transports).toEqual(
expect.arrayContaining([bothTransport, otherTransport]),
);
expect(b.connections$.value.map(({ transport }) => transport)).toEqual([
bothTransport,
otherTransport,
]);
transport$.next(bob(bothTransport, [legacyId]).transport$.value);
await flushPromises();
+62 -89
View File
@@ -18,7 +18,6 @@ import {
filter,
firstValueFrom,
map,
NEVER,
type Observable,
of,
switchMap,
@@ -42,12 +41,17 @@ import {
type MediaBackendContext,
type TransportCapabilities,
} from "../api";
import { delegateDelayedLeave, type TransportLocator } from "./auth";
import {
chooseAuthFlow,
delegateDelayedLeave,
type TransportLocator,
} from "./auth";
import { type Connection } from "./Connection";
import {
ConnectionMap,
createConnectionMap$,
type TransportLocatorWithCsSupport,
keyFor,
type TransportKey,
} from "./ConnectionMap";
import {
LivekitConnectionFactory,
@@ -65,7 +69,7 @@ import { createLivekitLocalMedia } from "./LocalMedia";
export interface LivekitBackendOptions {
/**
* `getOpenIdToken` for the JWT service flow, the MSC4195 methods for the
* client-server API flow, `baseUrl` for the delegation handover.
* client-server API flow, `baseUrl` for the delegation probe and handover.
*/
client: Pick<
MatrixClient,
@@ -99,31 +103,24 @@ export function createLivekitBackend(
: [requestsOrMedia.requests, requestsOrMedia];
const keyProvider = createKeyProvider(encryptionSystem, mediaKeys$, logger);
const transports = createTransportRegistry(scope);
const localTransport$ =
new BehaviorSubject<TransportLocatorWithCsSupport | null>(null);
const localTransport$ = new BehaviorSubject<TransportLocator | null>(null);
const audioOutputDeviceId$ = new BehaviorSubject<string | undefined>(
undefined,
);
const receiveVideo$ = new BehaviorSubject(true);
const connectionFactory = new LivekitConnectionFactory(
client,
// The MSC defines no unstable feature flag. If the transport names a
// JWT service too, start over without the CS API.
() => {
const local = localTransport$.value;
if (local?.csApiUsable && "livekit_service_url" in local.transport)
localTransport$.next({ ...local, csApiUsable: false });
},
roomId,
slotId,
publish,
audioOutputDeviceId$,
receiveVideo$,
keyProvider,
mediaQuality,
);
// 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,
// as is whether the client-server API is usable
// the publisher role sits on one connection, and which one is fixed per map
const connectionMap$ = scope.behavior<Epoch<ConnectionMap>>(
mapScoped(scope, localTransport$, (mapScope, localTransport) =>
createConnectionMap$({
@@ -134,17 +131,13 @@ export function createLivekitBackend(
logger,
ownMembershipIdentity,
}),
).pipe(
switchMap(
// Nothing is looked up in an empty map, so how it is keyed is moot.
(map$) => map$ ?? of(new Epoch(new ConnectionMap(true))),
),
),
).pipe(switchMap((map$) => map$ ?? of(new Epoch(new ConnectionMap())))),
);
const localMedia_ = createLivekitLocalMedia({
scope,
connectionMap$,
localTransport$,
publish,
media,
audioOutputDeviceId$,
@@ -152,16 +145,15 @@ export function createLivekitBackend(
logger,
});
// Probed once: the answer cannot change within a session
const homeserverSupportsDelegation = supportsDelegation(
`${client.baseUrl}/_matrix/client/unstable/io.element.msc4195/rtc/livekit/delegate_delayed_leave`,
"homeserver",
logger,
);
const ownServerName = serverNameOf(ownMembershipIdentity.userId);
/**
* Sets `localTransport$`, the transport we publish on. As a side effect,
* this creates the connection map, which lets subscribing connections start,
* too.
*
* Resolves once the publisher connection holds its token and reports
* whether the service that issued it can take over the delayed leave.
*/
const prepareLocalTransport = async (
transport: Transport,
): Promise<TransportCapabilities> => {
@@ -172,46 +164,45 @@ export function createLivekitBackend(
ownMembershipIdentity.userId,
);
const locator: TransportLocator = { transport, serverName };
// A homeserver with the client-server API advertises a `url`.
localTransport$.next({ ...locator, csApiUsable: "url" in transport });
// The membership is only sent once the publisher connection holds its
// token, so that the LiveKit room exists before anyone subscribes to it:
// a subscriber lacks the permission to create it and would fail without
// retrying
const { flow } = await authenticated(localMedia_.connection$);
let canDelegate: Promise<boolean>;
if (serverName !== ownServerName) {
// Our homeserver only takes over leaves for its own SFUs
logger.info(
`Publishing on a remote SFU of ${serverName}, delegation is not possible`,
);
return { canDelegateDelayedLeave: false };
canDelegate = Promise.resolve(false);
} else {
// Check for support using the same auth flow that we intend to use later
const flow = chooseAuthFlow(transport);
canDelegate =
flow.kind === "openID"
? supportsDelegation(
`${flow.serviceUrl}/delegate_delayed_leave`,
`transport ${flow.serviceUrl}`,
logger,
)
: homeserverSupportsDelegation;
}
// Now that we are authenticated, check which flow was used so that we can
// use the same flow for delegation.
if (flow.kind === "csApi") {
// If the client-server authentication endpoint is available, the delegation
// endpoint is available, too. Both have been released together in lk-jwt-service.
return { canDelegateDelayedLeave: true };
}
// The OpenID flow was used but the lk-jwt-instance may still predate delegation. Check
// if the delegation endpoint is supported.
return {
canDelegateDelayedLeave: await supportsDelegation(
`${flow.serviceUrl}/delegate_delayed_leave`,
`transport ${flow.serviceUrl}`,
logger,
),
};
localTransport$.next(locator);
// The membership is only sent once the publisher connection holds its
// token, so that the LiveKit room exists before anyone subscribes to it:
// a subscriber lacks the permission to create it and would fail without
// retrying
const [, canDelegateDelayedLeave] = await Promise.all([
authenticated(localMedia_.connection$),
canDelegate,
]);
return { canDelegateDelayedLeave };
};
const delegateLeave = async (delayId: string): Promise<void> => {
const connection = localMedia_.connection$.value;
if (connection === null)
const local = localTransport$.value;
if (local === null)
throw new MatrixRTCError("No local transport to delegate the leave to");
await delegateDelayedLeave({
client,
membership: ownMembershipIdentity,
flow: connection.flow,
transport: local.transport,
roomId,
slotId,
delayId,
@@ -236,9 +227,7 @@ export function createLivekitBackend(
}
: undefined;
}),
distinctUntilChanged(
(a, b) => (a && transportKey(a)) === (b && transportKey(b)),
),
distinctUntilChanged((a, b) => (a && keyFor(a)) === (b && keyFor(b))),
),
);
transports.follow(memberScope, locator$);
@@ -300,36 +289,33 @@ export function createLivekitBackend(
mediaFor,
connections$,
setAudioOutputDeviceId: localMedia_.setAudioOutputDeviceId,
setReceiveVideo: (receive) => receiveVideo$.next(receive),
sendData,
data$,
};
}
/** Resolves with the connection once it holds its token; rejects with its error otherwise. */
/** Resolves once the connection holds its token; rejects with its error otherwise. */
async function authenticated(
connection$: Behavior<Connection | null>,
): Promise<Connection> {
const { connection, state } = await firstValueFrom(
): Promise<void> {
const state = await firstValueFrom(
connection$.pipe(
switchMap(
(connection) =>
connection?.state$.pipe(map((state) => ({ connection, state }))) ??
NEVER,
),
switchMap((connection) => connection?.state$ ?? of(null)),
filter(
({ state }) =>
state.state === "authenticated" ||
state.state === "error" ||
state.state === "stopped",
(state) =>
state !== null &&
(state.state === "authenticated" ||
state.state === "error" ||
state.state === "stopped"),
),
),
);
if (state.state === "error") throw state.error;
if (state.state === "stopped")
if (state?.state === "error") throw state.error;
if (state?.state === "stopped")
throw new MatrixRTCError(
"The local connection stopped before it was authenticated",
);
return connection;
}
function backendConnection$(
@@ -348,19 +334,6 @@ function backendConnection$(
);
}
/**
* The key used for a transport locator in the transport registry.
*
* Note that this is *not* the key used for folding locators into connections.
*/
function transportKey({ transport, serverName }: TransportLocator): string {
return JSON.stringify([
"url" in transport ? transport.url : null,
"livekit_service_url" in transport ? transport.livekit_service_url : null,
serverName,
]);
}
export interface TransportRegistry {
/** Keeps a member's transport registered for as long as its scope lives. */
follow(
@@ -380,7 +353,7 @@ export function createTransportRegistry(
scope: ObservableScope,
): TransportRegistry {
const counts = new Map<
string,
TransportKey,
{ locator: TransportLocator; count: number }
>();
const transports = new BehaviorSubject<TransportLocator[]>([]);
@@ -388,7 +361,7 @@ export function createTransportRegistry(
transports.next([...counts.values()].map(({ locator }) => locator));
const register = (locator: TransportLocator): (() => void) => {
const key = transportKey(locator);
const key = keyFor(locator);
const entry = counts.get(key) ?? { locator, count: 0 };
entry.count++;
if (entry.count === 1) {
@@ -23,11 +23,16 @@ import { FailToStartLivekitConnection, MatrixRTCError } from "../../errors";
import { Epoch, type ObservableScope } from "../../reactive/ObservableScope";
import { flushPromises, mockEmitter, testScope } from "../../utils/test";
import { MediaConnectionState } from "../api";
import { type TransportLocator } from "./auth";
import { type Connection, type ConnectionState } from "./Connection";
import { ConnectionMap } from "./ConnectionMap";
import { createLivekitLocalMedia } from "./LocalMedia";
import { exampleTransport } from "./test";
const localTransport: TransportLocator = {
transport: exampleTransport,
serverName: "example.org",
};
const connected: ConnectionState = {
state: "authenticated",
livekitState: LivekitConnectionState.Connected,
@@ -64,7 +69,7 @@ function fakeConnection(state: ConnectionState = connected): FakeConnection {
}
function mapOf(...connections: Connection[]): Epoch<ConnectionMap> {
const map = new ConnectionMap(true);
const map = new ConnectionMap();
for (const connection of connections) map.add(connection, []);
return new Epoch(map);
}
@@ -75,44 +80,46 @@ function setup(
): {
media: ReturnType<typeof createLivekitLocalMedia>;
connectionMap$: BehaviorSubject<Epoch<ConnectionMap>>;
localTransport$: BehaviorSubject<TransportLocator | null>;
audioOutputDeviceId$: BehaviorSubject<string | undefined>;
} {
const connectionMap$ = new BehaviorSubject(mapOf());
const localTransport$ = new BehaviorSubject<TransportLocator | null>(null);
const audioOutputDeviceId$ = new BehaviorSubject<string | undefined>(
undefined,
);
const media = createLivekitLocalMedia({
scope,
connectionMap$: scope.behavior(connectionMap$),
localTransport$: scope.behavior(localTransport$),
publish,
audioOutputDeviceId$,
encryptionSystem: { kind: E2eeType.NONE },
logger,
});
return { media, connectionMap$, audioOutputDeviceId$ };
return { media, connectionMap$, localTransport$, audioOutputDeviceId$ };
}
describe("createLivekitLocalMedia", () => {
it("takes the publisher connection from the map once there is one", () => {
const { media, connectionMap$ } = setup();
it("finds the connection to the local transport once both are known", () => {
const { media, connectionMap$, localTransport$ } = setup();
const { connection } = fakeConnection();
const subscriber = {
...fakeConnection().connection,
role: "subscriber",
transport: { type: "livekit", livekit_service_url: "https://other" },
} as unknown as Connection;
expect(media.connection$.value).toBeNull();
expect(media.connectionState$.value).toBe(MediaConnectionState.Initialized);
connectionMap$.next(mapOf(subscriber, connection));
connectionMap$.next(mapOf(connection));
expect(media.connection$.value).toBeNull();
localTransport$.next(localTransport);
expect(media.connection$.value).toBe(connection);
expect(media.connectionState$.value).toBe(MediaConnectionState.Connected);
});
it("follows the connection's state", () => {
const { media, connectionMap$ } = setup();
const { media, connectionMap$, localTransport$ } = setup();
const { connection, state$ } = fakeConnection({ state: "authenticating" });
connectionMap$.next(mapOf(connection));
localTransport$.next(localTransport);
expect(media.connectionState$.value).toBe(MediaConnectionState.Preparing);
const error = new MatrixRTCError("no token");
@@ -121,9 +128,10 @@ describe("createLivekitLocalMedia", () => {
});
it("creates the tracks on the first publish and holds them back until then", async () => {
const { media, connectionMap$ } = setup();
const { media, connectionMap$, localTransport$ } = setup();
const { connection, participant } = fakeConnection();
connectionMap$.next(mapOf(connection));
localTransport$.next(localTransport);
await flushPromises();
expect(participant.setMicrophoneEnabled).not.toHaveBeenCalled();
expect(media.tracks$.value).toEqual([]);
@@ -140,9 +148,10 @@ describe("createLivekitLocalMedia", () => {
});
it("pauses the upstream while the member is not publishing", async () => {
const { media, connectionMap$ } = setup();
const { media, connectionMap$, localTransport$ } = setup();
const { connection, participant } = fakeConnection();
connectionMap$.next(mapOf(connection));
localTransport$.next(localTransport);
media.setPublishing(true);
await flushPromises();
@@ -160,7 +169,7 @@ describe("createLivekitLocalMedia", () => {
});
it("resolves a publish made before the connection exists once it is up", async () => {
const { media, connectionMap$ } = setup();
const { media, connectionMap$, localTransport$ } = setup();
let published: string | undefined;
const publishing = media
.publish({ source: "camera" })
@@ -170,6 +179,7 @@ describe("createLivekitLocalMedia", () => {
const { connection, participant } = fakeConnection();
connectionMap$.next(mapOf(connection));
localTransport$.next(localTransport);
media.setPublishing(true);
await publishing;
@@ -183,9 +193,10 @@ describe("createLivekitLocalMedia", () => {
});
it("publishes a request at once on a started publisher", async () => {
const { media, connectionMap$ } = setup();
const { media, connectionMap$, localTransport$ } = setup();
const { connection, participant } = fakeConnection();
connectionMap$.next(mapOf(connection));
localTransport$.next(localTransport);
media.setPublishing(true);
await flushPromises();
@@ -200,9 +211,10 @@ describe("createLivekitLocalMedia", () => {
});
it("rejects a publish the device refuses, and forgets the request", async () => {
const { media, connectionMap$ } = setup();
const { media, connectionMap$, localTransport$ } = setup();
const { connection, participant } = fakeConnection();
connectionMap$.next(mapOf(connection));
localTransport$.next(localTransport);
media.setPublishing(true);
await flushPromises();
vi.mocked(participant.setCameraEnabled).mockRejectedValueOnce(
@@ -222,9 +234,10 @@ describe("createLivekitLocalMedia", () => {
});
it("publishes again on a new connection and stops the old tracks", async () => {
const { media, connectionMap$ } = setup();
const { media, connectionMap$, localTransport$ } = setup();
const first = fakeConnection();
connectionMap$.next(mapOf(first.connection));
localTransport$.next(localTransport);
media.setPublishing(true);
await flushPromises();
await media.publish({ source: "camera" });
@@ -250,9 +263,10 @@ describe("createLivekitLocalMedia", () => {
});
it("remembers a mute across connections", async () => {
const { media, connectionMap$ } = setup();
const { media, connectionMap$, localTransport$ } = setup();
const first = fakeConnection();
connectionMap$.next(mapOf(first.connection));
localTransport$.next(localTransport);
media.setPublishing(true);
await flushPromises();
@@ -271,9 +285,10 @@ describe("createLivekitLocalMedia", () => {
});
it("unpublishes a source, the screen share audio with its video", async () => {
const { media, connectionMap$ } = setup();
const { media, connectionMap$, localTransport$ } = setup();
const { connection, participant } = fakeConnection();
connectionMap$.next(mapOf(connection));
localTransport$.next(localTransport);
media.setPublishing(true);
await flushPromises();
await media.publish({ source: "screenShare" });
@@ -287,9 +302,10 @@ describe("createLivekitLocalMedia", () => {
});
it("keeps the first failure to publish", async () => {
const { media, connectionMap$ } = setup();
const { media, connectionMap$, localTransport$ } = setup();
const { connection, participant } = fakeConnection();
connectionMap$.next(mapOf(connection));
localTransport$.next(localTransport);
media.setPublishing(true);
await flushPromises();
expect(media.publishError$.value).toBeNull();
@@ -310,12 +326,14 @@ describe("createLivekitLocalMedia", () => {
});
it("plays on the device given, on the current room and the rooms to come", async () => {
const { media, connectionMap$, audioOutputDeviceId$ } = setup();
const { media, connectionMap$, localTransport$, audioOutputDeviceId$ } =
setup();
await media.setAudioOutputDeviceId("speaker");
expect(audioOutputDeviceId$.value).toBe("speaker");
const { connection, room } = fakeConnection();
connectionMap$.next(mapOf(connection));
localTransport$.next(localTransport);
await flushPromises();
await media.setAudioOutputDeviceId("headset");
+8 -3
View File
@@ -40,6 +40,7 @@ import {
type ObservableScope,
} from "../../reactive/ObservableScope";
import { type LocalMediaBackend, MediaConnectionState } from "../api";
import { type TransportLocator } from "./auth";
import { type Connection } from "./Connection";
import { type ConnectionMap } from "./ConnectionMap";
import {
@@ -53,8 +54,9 @@ import { toMediaConnectionState } from "./connectionState";
interface Props {
scope: ObservableScope;
/** Holds the connection we publish on once the local transport is known. */
connectionMap$: Behavior<Epoch<ConnectionMap>>;
/** The transport we publish on; null until the session has found it. */
localTransport$: Behavior<TransportLocator | null>;
publish: PublishRequest[];
/** Tracks the host captured ahead of the join; the publisher takes them over. */
media?: LocalMedia;
@@ -78,6 +80,7 @@ export interface LivekitLocalMedia extends LocalMediaBackend {
export function createLivekitLocalMedia({
scope,
connectionMap$,
localTransport$,
publish: initialRequests,
media,
audioOutputDeviceId$,
@@ -87,8 +90,10 @@ export function createLivekitLocalMedia({
const logger = parentLogger.getChild("[LocalMedia]");
const connection$ = scope.behavior(
connectionMap$.pipe(
map(({ value: connections }) => connections.getPublisherConnection()),
combineLatest(
[connectionMap$, localTransport$],
({ value: connections }, transport) =>
transport && connections.getConnectionForTransport(transport),
),
);
@@ -14,6 +14,7 @@ import {
import { type CallMembershipIdentityParts } from "matrix-js-sdk/lib/matrixrtc/EncryptionManager";
import { serverNameOfTransport } from "../../utils/serverName";
import { isCsApiUnavailable } from "./auth";
import * as csApi from "./auth/csApi";
import { decodeSFUJWTPayload } from "./auth/types";
@@ -89,7 +90,7 @@ export async function findRemotePublishLivekitTransport({
continue;
}
} catch (e) {
if (csApi.isCsApiUnavailable(e)) {
if (isCsApiUnavailable(e)) {
// Without the endpoint no further candidate can work
logger.warn(
`Cannot use the MSC4195 get_token endpoint (${e}), so no remote SFU can be used`,
+1 -63
View File
@@ -5,12 +5,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import {
ConnectionError,
HTTPError,
type MatrixClient,
MatrixError,
} from "matrix-js-sdk";
import { ConnectionError, HTTPError, type MatrixClient } from "matrix-js-sdk";
import { type CallMembershipIdentityParts } from "matrix-js-sdk/lib/matrixrtc/EncryptionManager";
import { doNetworkOperationWithRetry } from "../../../utils/network";
@@ -25,63 +20,6 @@ function isNetworkError(e: unknown): boolean {
return e instanceof HTTPError || e instanceof ConnectionError;
}
/**
* Whether an error means the homeserver does not implement the MSC4195
* endpoints. Such a homeserver answers with whatever it uses for unknown
* routes (Synapse: 404 with `M_UNRECOGNIZED`), so any 404 counts.
*/
export function isCsApiUnavailable(e: unknown): boolean {
const answer = unwrapErrorDetails(e);
return (
answer !== undefined &&
(answer.status === 404 ||
answer.errcode === "M_NOT_FOUND" ||
answer.errcode === "M_UNRECOGNIZED")
);
}
/**
* Tries to unwrap the details from an unknown error object, regardless of whether
* it came from the Widget API or not.
*/
function unwrapErrorDetails(
e: unknown,
): { status?: number; errcode?: string } | undefined {
// If the error is an instance of `MatrixError`, take its details directly.
if (e instanceof MatrixError) {
return { status: e.httpStatus, errcode: e.errcode };
}
// If the error originated from the widget API, try to extract the bundled
// Matrix API error. We identify the widget's `WidgetApiResponseError` by
// the shape of its payload to avoid making the SDK dependent on the widget
// API. This isn't great, but we'll drop this branch anyway once we eliminate
// usage of the widget API.
if (e instanceof Error && "data" in e) {
const relayed = (
e as {
data?: {
matrix_api_error?: {
http_status?: unknown;
response?: { errcode?: unknown };
};
};
}
).data?.matrix_api_error;
if (typeof relayed === "object" && relayed !== null) {
const { http_status: status, response } = relayed;
const errcode = response?.errcode;
return {
status: typeof status === "number" ? status : undefined,
errcode: typeof errcode === "string" ? errcode : undefined,
};
}
}
// We're not able to extract any details from this error.
return undefined;
}
export type ClientGetTokenParts = Pick<MatrixClient, "getLivekitToken">;
export interface GetSFUConfigParams {
+101 -144
View File
@@ -20,13 +20,7 @@ import {
} from "../../../utils/test-fixtures";
import type * as csApi from "./csApi";
import type * as openID from "./openID";
import {
type AuthFlow,
authenticateWithTransport,
chooseAuthFlow,
delegateDelayedLeave,
getSFUConfig,
} from ".";
import { chooseAuthFlow, delegateDelayedLeave, getSFUConfig } from ".";
const aliceId = `${aliceUserId}:${aliceDeviceId}`;
const csApiJWTToken = createJWTToken(aliceId, "via CS API");
@@ -73,9 +67,6 @@ const urlAndServiceUrlTransport: UnstableLivekitTransport = {
...serviceUrlTransport,
};
const viaCsApi: AuthFlow = { kind: "csApi", url: "wss://livekit.example.org" };
const viaOpenID: AuthFlow = { kind: "openID", serviceUrl };
/** The JWT service, answering each endpoint with a token that names it. */
function mockJWTService(): void {
fetchMock.post(`${serviceUrl}/sfu/get`, {
@@ -109,9 +100,11 @@ describe("getSFUConfig", () => {
logger,
};
it("uses the CS API for the CS API flow", async () => {
it("uses CS API with url transport", async () => {
mockJWTService();
expect(await getSFUConfig({ ...defaultParams, flow: viaCsApi })).toEqual(
expect(
await getSFUConfig({ ...defaultParams, transport: urlTransport }),
).toEqual(
expect.objectContaining({
jwt: csApiJWTToken,
livekitAlias: "via CS API",
@@ -127,19 +120,21 @@ describe("getSFUConfig", () => {
expect(jwtServiceCalls()).toEqual([]);
});
it("reports the CS API missing where the homeserver lacks the endpoint, without falling back", async () => {
it("does not fall back to OpenID with url transport", async () => {
mockJWTService();
client.getLivekitToken.mockRejectedValueOnce(unsupportedError);
await expect(
getSFUConfig({ ...defaultParams, flow: viaCsApi }),
getSFUConfig({ ...defaultParams, transport: urlTransport }),
).rejects.toThrow(expect.any(NoMatrix2AuthorizationService));
expect(client.getLivekitToken).toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual([]);
});
it("uses the JWT service for the OpenID flow", async () => {
it("uses OpenID with livekit_service_url transport", async () => {
mockJWTService();
expect(await getSFUConfig({ ...defaultParams, flow: viaOpenID })).toEqual(
expect(
await getSFUConfig({ ...defaultParams, transport: serviceUrlTransport }),
).toEqual(
expect.objectContaining({
jwt: defaultJWTToken,
livekitAlias: "via default endpoint",
@@ -149,141 +144,80 @@ describe("getSFUConfig", () => {
expect(jwtServiceCalls()).toEqual(["/get_token"]);
});
it("does not report the CS API missing where the homeserver refuses the request", async () => {
mockJWTService();
const forbidden = new MatrixError({ errcode: "M_FORBIDDEN" }, 403);
client.getLivekitToken.mockRejectedValueOnce(forbidden);
await expect(
getSFUConfig({ ...defaultParams, flow: viaCsApi }),
).rejects.toThrow(forbidden);
expect(jwtServiceCalls()).toEqual([]);
});
it("reports the CS API missing for another homeserver's transport", async () => {
mockJWTService();
client.getLivekitToken.mockRejectedValueOnce(
new MatrixError({ errcode: "M_UNRECOGNIZED" }, 404),
);
await expect(
getSFUConfig({
...defaultParams,
serverName: "elsewhere.org",
flow: viaCsApi,
}),
).rejects.toThrow(expect.any(NoMatrix2AuthorizationService));
expect(jwtServiceCalls()).toEqual([]);
});
it("reports the CS API missing where a widget host relays the homeserver's not found", async () => {
mockJWTService();
// The widget API's WidgetApiResponseError arrives in a minified build.
const relayed = Object.assign(new Error("Unrecognized request"), {
name: "n",
data: {
matrix_api_error: {
http_status: 404,
response: { errcode: "M_UNRECOGNIZED" },
},
},
});
client.getLivekitToken.mockRejectedValueOnce(relayed);
await expect(
getSFUConfig({ ...defaultParams, flow: viaCsApi }),
).rejects.toThrow(expect.any(NoMatrix2AuthorizationService));
expect(jwtServiceCalls()).toEqual([]);
});
it.each([
["a token that does not decode", { jwt: "not a token" }],
["an error of our own", new TypeError("oops")],
])("does not judge the CS API by %s", async (_what, outcome) => {
mockJWTService();
if (outcome instanceof Error)
client.getLivekitToken.mockRejectedValueOnce(outcome);
else client.getLivekitToken.mockResolvedValueOnce(outcome);
await expect(
getSFUConfig({ ...defaultParams, flow: viaCsApi }),
).rejects.not.toBeInstanceOf(NoMatrix2AuthorizationService);
expect(jwtServiceCalls()).toEqual([]);
});
it("uses the CS API when publishing through the CS API flow", async () => {
it("uses OpenID when subscribing with url + livekit_service_url transport", async () => {
mockJWTService();
expect(
await getSFUConfig({
...defaultParams,
flow: viaCsApi,
transport: urlAndServiceUrlTransport,
}),
).toEqual(
expect.objectContaining({
jwt: defaultJWTToken,
livekitAlias: "via default endpoint",
}),
);
expect(client.getLivekitToken).not.toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual(["/get_token"]);
});
it("surfaces the widget host's refusal with url transport", async () => {
mockJWTService();
const error = new Error(
"The rtc_livekit_get_token action is not supported by the client.",
);
client.getLivekitToken.mockRejectedValueOnce(error);
await expect(
getSFUConfig({ ...defaultParams, transport: urlTransport }),
).rejects.toThrow(error);
expect(jwtServiceCalls()).toEqual([]);
});
it("uses CS API when publishing with url transport", async () => {
mockJWTService();
expect(
await getSFUConfig({
...defaultParams,
transport: urlTransport,
role: "publisher",
}),
).toEqual(expect.objectContaining({ jwt: csApiJWTToken }));
expect(client.getLivekitToken).toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual([]);
});
});
describe("authenticateWithTransport", () => {
const defaultParams = {
client,
membership,
serverName: "example.org",
role: "subscriber" as const,
roomId,
slotId,
logger,
};
it("uses CS API with url + livekit_service_url transport", async () => {
mockJWTService();
expect(
await authenticateWithTransport({
...defaultParams,
transport: urlAndServiceUrlTransport,
}),
).toEqual(expect.objectContaining({ jwt: csApiJWTToken }));
expect(jwtServiceCalls()).toEqual([]);
});
it.each([
["subscriber", "/get_token", defaultJWTToken],
["publisher", "/sfu/get", legacyJWTToken],
] as const)(
"falls back to OpenID as %s where the homeserver lacks the endpoint",
async (role, endpoint, jwt) => {
mockJWTService();
client.getLivekitToken.mockRejectedValueOnce(unsupportedError);
expect(
await authenticateWithTransport({
...defaultParams,
transport: urlAndServiceUrlTransport,
role,
}),
).toEqual(expect.objectContaining({ jwt }));
expect(client.getLivekitToken).toHaveBeenCalledTimes(1);
expect(jwtServiceCalls()).toEqual([endpoint]);
},
);
it("does not fall back with url transport", async () => {
it("does not fall back to OpenID when publishing with url transport", async () => {
mockJWTService();
client.getLivekitToken.mockRejectedValueOnce(unsupportedError);
await expect(
authenticateWithTransport({ ...defaultParams, transport: urlTransport }),
getSFUConfig({
...defaultParams,
transport: urlTransport,
role: "publisher",
}),
).rejects.toThrow(expect.any(NoMatrix2AuthorizationService));
expect(client.getLivekitToken).toHaveBeenCalledTimes(1);
expect(client.getLivekitToken).toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual([]);
});
it("does not fall back where the homeserver refuses the request", async () => {
it("uses the legacy OpenID endpoint when publishing with url + livekit_service_url transport", async () => {
mockJWTService();
const forbidden = new MatrixError({ errcode: "M_FORBIDDEN" }, 403);
client.getLivekitToken.mockRejectedValueOnce(forbidden);
await expect(
authenticateWithTransport({
// Subscribers predating MSC4195 expect a legacy participant identity from
// anyone advertising a membership, which only the JWT service assigns
expect(
await getSFUConfig({
...defaultParams,
transport: urlAndServiceUrlTransport,
role: "publisher",
}),
).rejects.toThrow(forbidden);
expect(jwtServiceCalls()).toEqual([]);
).toEqual(
expect.objectContaining({
jwt: legacyJWTToken,
livekitAlias: "via legacy endpoint",
}),
);
expect(client.getLivekitToken).not.toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual(["/sfu/get"]);
});
});
@@ -308,9 +242,9 @@ describe("delegateDelayedLeave", () => {
return { delay_id, delay_timeout, delay_cs_api_url };
}
it("uses the CS API for the CS API flow", async () => {
it("uses CS API with url transport", async () => {
mockJWTService();
await delegateDelayedLeave({ ...defaultParams, flow: viaCsApi });
await delegateDelayedLeave({ ...defaultParams, transport: urlTransport });
expect(client.delegateDelayedLeave).toHaveBeenCalledWith({
url: urlTransport.url,
room_id: roomId,
@@ -321,19 +255,37 @@ describe("delegateDelayedLeave", () => {
expect(jwtServiceCalls()).toEqual([]);
});
it("does not fall back to the JWT service from the CS API flow", async () => {
it("does not fall back to OpenID with url transport", async () => {
mockJWTService();
client.delegateDelayedLeave.mockRejectedValueOnce(unsupportedError);
await expect(
delegateDelayedLeave({ ...defaultParams, flow: viaCsApi }),
delegateDelayedLeave({ ...defaultParams, transport: urlTransport }),
).rejects.toThrow();
expect(client.delegateDelayedLeave).toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual([]);
});
it("uses the JWT service for the OpenID flow", async () => {
it("uses OpenID with livekit_service_url transport", async () => {
mockJWTService();
await delegateDelayedLeave({ ...defaultParams, flow: viaOpenID });
await delegateDelayedLeave({
...defaultParams,
transport: serviceUrlTransport,
});
expect(client.delegateDelayedLeave).not.toHaveBeenCalled();
expect(delegationViaJWTService()).toEqual({
delay_id: "delay123",
delay_timeout: 3_600_000,
delay_cs_api_url: client.baseUrl,
});
});
it("uses OpenID with url + livekit_service_url transport", async () => {
mockJWTService();
// Must match the flow that got the token, so the identities line up
await delegateDelayedLeave({
...defaultParams,
transport: urlAndServiceUrlTransport,
});
expect(client.delegateDelayedLeave).not.toHaveBeenCalled();
expect(delegationViaJWTService()).toEqual({
delay_id: "delay123",
@@ -345,16 +297,21 @@ describe("delegateDelayedLeave", () => {
describe("chooseAuthFlow", () => {
it.each([
["url", urlTransport, true, viaCsApi],
["url", urlTransport, false, viaCsApi],
["livekit_service_url", serviceUrlTransport, true, viaOpenID],
["livekit_service_url", serviceUrlTransport, false, viaOpenID],
["url + livekit_service_url", urlAndServiceUrlTransport, true, viaCsApi],
["url + livekit_service_url", urlAndServiceUrlTransport, false, viaOpenID],
["url", urlTransport, { kind: "csApi", url: urlTransport.url }],
[
"livekit_service_url",
serviceUrlTransport,
{ kind: "openID", serviceUrl },
],
[
"url + livekit_service_url",
urlAndServiceUrlTransport,
{ kind: "openID", serviceUrl },
],
] as const)(
"chooses the flow for a %s transport with the CS API usable: %s",
(_shape, transport, csApiUsable, flow) => {
expect(chooseAuthFlow(transport, csApiUsable)).toEqual(flow);
"chooses the flow for a %s transport as %s",
(_shape, transport, flow) => {
expect(chooseAuthFlow(transport)).toEqual(flow);
},
);
});
+54 -61
View File
@@ -6,9 +6,13 @@ Please see LICENSE in the repository root for full details.
*/
/**
* Authentication with a LiveKit transport.
* Authentication with a LiveKit transport: the MSC4195 client-server API
* through our homeserver for a transport with an SFU `url`, the OpenID flow
* against the JWT service for one with a `livekit_service_url`, and the
* choice between them where a transport carries both.
*/
import { ConnectionError, MatrixError } from "matrix-js-sdk";
import { type Logger } from "matrix-js-sdk/lib/logger";
import { type UnstableLivekitTransport } from "matrix-js-sdk/lib/matrixrtc";
import { type CallMembershipIdentityParts } from "matrix-js-sdk/lib/matrixrtc/EncryptionManager";
@@ -22,11 +26,37 @@ export type { ClientOpenIDParts } from "./openID";
export type { ClientGetTokenParts, ClientDelegationParts } from "./csApi";
export type * from "./types";
/**
* Whether an error means the homeserver does not implement the MSC4195
* endpoints. The MSC says `M_NOT_FOUND`; a homeserver without support answers
* with whatever it uses for unknown routes (Synapse: 404 with
* `M_UNRECOGNIZED`), so any 404 counts.
*/
function isEndpointUnsupported(e: unknown): boolean {
return (
e instanceof MatrixError &&
(e.httpStatus === 404 ||
e.errcode === "M_NOT_FOUND" ||
e.errcode === "M_UNRECOGNIZED")
);
}
/**
* Whether an error means the MSC4195 client-server API cannot be used from
* here: the homeserver does not implement it, or the request never reached
* the homeserver because a widget host does not expose the endpoint
* (MSC4533), which the widget API reports as a plain error. A connection
* error is neither: the endpoint may well exist.
*/
export function isCsApiUnavailable(e: unknown): boolean {
if (isEndpointUnsupported(e)) return true;
return !(e instanceof MatrixError) && !(e instanceof ConnectionError);
}
export interface GetSFUConfigParams {
client: csApi.ClientGetTokenParts & openID.ClientOpenIDParts;
membership: CallMembershipIdentityParts;
/** The flow to authenticate with, as chosen by {@link chooseAuthFlow}. */
flow: AuthFlow;
transport: UnstableLivekitTransport;
/** The homeserver the transport belongs to. */
serverName: string;
roomId: string;
@@ -36,22 +66,20 @@ export interface GetSFUConfigParams {
}
/**
* Gets an {@link SFUConfig} for connecting to a transport through the given
* auth flow.
*
* @throws {@link NoMatrix2AuthorizationService} if the client-server API flow
* finds the API missing.
* Gets an {@link SFUConfig} appropriate for connecting to a given transport,
* using whichever auth flow is appropriate.
*/
export async function getSFUConfig({
client,
membership,
flow,
transport,
serverName,
roomId,
slotId,
role,
logger,
}: GetSFUConfigParams): Promise<SFUConfig> {
const flow = chooseAuthFlow(transport);
if (flow.kind === "openID") {
return await openID.getSFUConfig({
client,
@@ -73,14 +101,10 @@ export async function getSFUConfig({
slotId,
});
} catch (e) {
if (csApi.isCsApiUnavailable(e)) {
logger.warn(
if (isEndpointUnsupported(e)) {
logger.error(
`Homeserver does not support the MSC4195 get_token endpoint, cannot get token for transport ${flow.url}`,
);
// This is our own homeserver's answer. as per MSC4195, only 403 /
// M_FORBIDDEN and 400 / M_INVALID_PARAM are forwarded from the remote
// server. Any other remote error becomes 502 / M_UNKNOWN on the
// client-server API.
throw new NoMatrix2AuthorizationService(e as Error);
}
throw e;
@@ -88,40 +112,11 @@ export async function getSFUConfig({
}
}
export type AuthenticateWithTransportParams = Omit<
GetSFUConfigParams,
"flow"
> & { transport: UnstableLivekitTransport };
/**
* Authenticates with a transport once, outside any session. This automatically
* falls back from the client-server API flow to the OpenID flow if needed and
* possible.
*
* @throws {@link NoMatrix2AuthorizationService} if the client-server API is missing
* but the transport does not allow falling back to the OpenID flow.
*/
export async function authenticateWithTransport({
transport,
...params
}: AuthenticateWithTransportParams): Promise<SFUConfig> {
try {
const flow = chooseAuthFlow(transport, true);
return await getSFUConfig({ ...params, flow });
} catch (e) {
const flow = chooseAuthFlow(transport, false);
// Nothing else to try unless the API is missing and there is a JWT service
if (!(e instanceof NoMatrix2AuthorizationService) || flow.kind !== "openID")
throw e;
return await getSFUConfig({ ...params, flow });
}
}
export interface DelegateDelayedLeaveParams {
client: csApi.ClientDelegationParts & openID.ClientOpenIDParts;
membership: CallMembershipIdentityParts;
/** The flow that issued the token we publish with. */
flow: AuthFlow;
/** The transport we publish on. */
transport: UnstableLivekitTransport;
roomId: string;
slotId: string;
delayId: string;
@@ -138,13 +133,14 @@ export interface DelegateDelayedLeaveParams {
export async function delegateDelayedLeave({
client,
membership,
flow,
transport,
roomId,
slotId,
delayId,
delayTimeoutMs,
logger,
}: DelegateDelayedLeaveParams): Promise<void> {
const flow = chooseAuthFlow(transport);
if (flow.kind === "csApi") {
try {
await csApi.delegateDelayedLeave({
@@ -156,7 +152,7 @@ export async function delegateDelayedLeave({
delayId,
});
} catch (e) {
if (csApi.isCsApiUnavailable(e))
if (isEndpointUnsupported(e))
logger.error(
"Server misconfigured: transport contains a 'url' field but server does not support the MSC4195 delegate_delayed_leave endpoint",
);
@@ -185,21 +181,18 @@ export type AuthFlow =
| { kind: "openID"; serviceUrl: string };
/**
* Chooses which auth flow to use for a given transport.
* Chooses which auth flow to use for a given transport. For now this returns a
* single auth flow, with no provision for a fallback behavior.
*/
export function chooseAuthFlow(
transport: UnstableLivekitTransport,
csApiUsable: boolean,
): AuthFlow {
// If we only have url, we have no choice but to use the CS API.
export function chooseAuthFlow(transport: UnstableLivekitTransport): AuthFlow {
if ("url" in transport && !("livekit_service_url" in transport))
return { kind: "csApi", url: transport.url };
// If we have both url and livekit_service_url, prefer the CS API if it is usable.
if ("url" in transport && csApiUsable)
return { kind: "csApi", url: transport.url };
// If the CS API is not usable or we only have livekit_service_url, fall back
// to using the OpenID flow.
// All other transports use the OpenID flow, even if they contain a `url`.
// This is necessary since the auth flow determines the participant identity
// format, and we still have older clients out in the wild which would not yet
// know to look for a hashed participant identity in case `url` is present in
// someone else's transport.
// TODO: Once users have updated their clients, choose the CS API flow if
// available, keeping OpenID as a fallback.
return { kind: "openID", serviceUrl: transport.livekit_service_url };
}
@@ -197,9 +197,24 @@ describe("buildLiveKitOptions", () => {
});
});
it("does not include screenShareSimulcastLayers when not configured", () => {
it("sends one low screen share layer fit for Low bandwidth mode when not configured", () => {
const opts = buildLiveKitOptions();
expect(opts.publishDefaults?.screenShareSimulcastLayers).toBeUndefined();
const layers = opts.publishDefaults?.screenShareSimulcastLayers;
expect(layers).toHaveLength(1);
expect(layers?.[0]).toMatchObject({
width: 960,
height: 540,
encoding: { maxBitrate: 625_000, maxFramerate: 15 },
});
});
it("keeps the low screen share layer when only the top encoding is configured", () => {
const opts = buildLiveKitOptions({
screen_share: { max_bitrate: 8_000_000, max_framerate: 60 },
});
expect(opts.publishDefaults?.screenShareSimulcastLayers).toEqual(
buildLiveKitOptions().publishDefaults?.screenShareSimulcastLayers,
);
});
it("backupCodec always uses stock VP8 720p encoding", () => {
@@ -17,6 +17,13 @@ import {
import { defaultMediaQuality, type MediaQuality } from "../../config";
const lowBandwidthScreenShareLayer = new VideoPresetClass(
960,
540,
625_000,
15,
);
/**
* Find the closest matching VideoPreset for a given height.
*/
@@ -71,7 +78,7 @@ function buildPublishOptions(
};
// Screen share simulcast layers
let screenShareSimulcastLayers: VideoPreset[] | undefined;
let screenShareSimulcastLayers: VideoPreset[];
if (screenConf?.simulcast_layers) {
screenShareSimulcastLayers = screenConf.simulcast_layers.map(
(layer) =>
@@ -82,6 +89,8 @@ function buildPublishOptions(
layer.framerate ?? screenConf?.max_framerate ?? 30,
),
);
} else {
screenShareSimulcastLayers = [lowBandwidthScreenShareLayer];
}
return {
@@ -94,9 +103,7 @@ function buildPublishOptions(
simulcast: true,
videoSimulcastLayers: videoSimulcastLayers as VideoPreset[],
screenShareEncoding,
...(screenShareSimulcastLayers && {
screenShareSimulcastLayers: screenShareSimulcastLayers as VideoPreset[],
}),
screenShareSimulcastLayers,
stopMicTrackOnMute: false,
videoCodec: codec,
videoEncoding,
+1
View File
@@ -32,6 +32,7 @@ export function mockRemoteParticipant(
({}) as Partial<RemoteTrackPublication> as RemoteTrackPublication,
// this will only get used for `getTrackPublications().length`
getTrackPublications: () => [0],
trackPublications: new Map(),
...mockEmitter(),
...participant,
} as RemoteParticipant;
-68
View File
@@ -1,68 +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.
*/
.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 {
width: 100%;
display: flex;
> h3 {
margin-block-end: var(--cpd-space-2x);
flex-grow: 1;
}
> button {
margin-block-start: calc(-1 * var(--cpd-space-1x));
margin-inline-end: calc(-1 * var(--cpd-space-1x));
}
}
-41
View File
@@ -1,41 +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 { 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 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>
);
},
};
-30
View File
@@ -1,30 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { expect, test } from "vitest";
import { 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();
});
-104
View File
@@ -1,104 +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 FC, type ReactElement, type ReactNode } from "react";
import { Popover as BUIPopover } from "@base-ui/react/popover";
import styles from "./Popover.module.css";
import { Heading, IconButton } from "@vector-im/compound-web";
import { CloseIcon } from "@vector-im/compound-design-tokens/assets/web/icons";
import classNames from "classnames";
import { useRootElement } from "./RootElementContext";
import { useTranslation } from "react-i18next";
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,
}) => {
const { t } = useTranslation();
const rootElement = useRootElement();
return (
<BUIPopover.Root open={open} onOpenChange={onOpenChange}>
<BUIPopover.Trigger render={trigger} />
<BUIPopover.Portal container={rootElement}>
<BUIPopover.Positioner sideOffset={8} side={side} align={align}>
<BUIPopover.Popup className={classNames(styles.popover, className)}>
<div className={styles.title}>
<BUIPopover.Title
render={
<Heading as="h3" type="body" weight="semibold" size="lg">
{title}
</Heading>
}
/>
<BUIPopover.Close
render={
<IconButton
kind="secondary"
size="28px"
aria-label={t("action.close")}
>
<CloseIcon />
</IconButton>
}
/>
</div>
{children}
</BUIPopover.Popup>
</BUIPopover.Positioner>
</BUIPopover.Portal>
</BUIPopover.Root>
);
};
-16
View File
@@ -41,19 +41,3 @@ export const RootElementProvider = RootElementContext.Provider;
*/
export const useRootElement = (): HTMLElement =>
use(RootElementContext) ?? document.body;
const PortalElementContext = createContext<HTMLElement | null>(null);
/**
* Supplies the container that Compound floats Element Call's menus and tooltips
* into when that is outside the root: the component build's `CallPortalRoot`.
*/
export const PortalElementProvider = PortalElementContext.Provider;
/**
* The container that Element Call's menus and tooltips float into, if it is
* not the root's own document body. It gets the root's theme and platform, so
* that what floats out of the root looks as it would inside.
*/
export const usePortalElement = (): HTMLElement | null =>
use(PortalElementContext);
-21
View File
@@ -41,7 +41,6 @@ export enum UserIntent {
StartNewCallDMVoice = "start_call_dm_voice",
JoinExistingCallDM = "join_existing_dm",
JoinExistingCallDMVoice = "join_existing_dm_voice",
VideoRoom = "video_room",
Unknown = "unknown",
}
@@ -144,18 +143,6 @@ export interface UrlConfiguration {
* Defaults to true.
*/
noiseSuppression?: boolean;
/**
* Whether the user may start with the microphone on, whether or not the
* lobby is shown. Set by the intent, not a URL parameter.
* Defaults to true.
*/
initialAudioEnabled?: boolean;
/**
* Whether the user may start with the camera on, whether or not the lobby is
* shown. Set by the intent, not a URL parameter.
* Defaults to true.
*/
initialVideoEnabled?: boolean;
callIntent?: RTCCallIntent;
}
@@ -235,14 +222,6 @@ export function configurationForIntent(intent: UserIntent): UrlConfiguration {
preset.autoLeaveWhenOthersLeft = true;
preset.callIntent = preset.callIntent ?? RTC_CALL_INTENT_VIDEO;
break;
case UserIntent.VideoRoom:
preset.skipLobby = false;
preset.returnToLobby = true;
preset.callIntent = RTC_CALL_INTENT_VIDEO;
// Opening the room should not turn on the user's microphone or camera.
preset.initialAudioEnabled = false;
preset.initialVideoEnabled = false;
break;
// Non widget usecase defaults
default:
preset = {
-27
View File
@@ -318,20 +318,6 @@ describe("UrlParams", () => {
).toMatchObject(joinExistingCallDefaults("desktop"));
});
it("accepts video_room", () => {
expect(
computeUrlParams(
"?intent=video_room&widgetId=1234&parentUrl=parent.org",
),
).toMatchObject({
...joinExistingCallDefaults("desktop"),
returnToLobby: true,
callIntent: RTC_CALL_INTENT_VIDEO,
initialAudioEnabled: false,
initialVideoEnabled: false,
});
});
it("accepts start_call_voice", () => {
expect(
computeUrlParams(
@@ -422,19 +408,6 @@ describe("UrlParams", () => {
});
});
describe.each(["initialAudioEnabled", "initialVideoEnabled"] as const)(
"%s",
(name) => {
it("is not read from the URL", () => {
expect(
computeUrlParams(
`?${name}=false&intent=join_existing&widgetId=1234&parentUrl=parent.org`,
)[name],
).toBeUndefined();
});
},
);
describe("noiseSuppression", () => {
it("defaults to true", () => {
expect(computeUrlParams().noiseSuppression).toBe(true);
+1 -1
View File
@@ -61,7 +61,7 @@ exports[`the modal renders as a drawer in mobile viewports 1`] = `
/>
<h2
id="radix-_r_a_"
style="position: absolute; border: 0px; width: 1px; height: 1px; padding: 0px; margin: -1px; overflow: hidden; clip: rect(0px, 0px, 0px, 0px); white-space: nowrap; overflow-wrap: normal;"
style="position: absolute; border: 0px; width: 1px; height: 1px; padding: 0px; margin: -1px; overflow: hidden; clip: rect(0px, 0px, 0px, 0px); white-space: nowrap; word-wrap: normal;"
>
My modal
</h2>
-71
View File
@@ -1,71 +0,0 @@
// 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"
>
<div
class="_title_8e8188"
>
<h3
class="_typography_6v6n8_153 _font-body-lg-semibold_6v6n8_74"
id="base-ui-_r_4_"
>
Example
</h3>
<button
aria-disabled="false"
aria-label="Close"
class="_icon-button_1215g_8"
data-kind="secondary"
role="button"
style="--cpd-icon-button-size: 28px;"
tabindex="0"
type="button"
>
<div
class="_indicator-icon_j097f_17"
style="--cpd-icon-button-size: 100%;"
>
<svg
fill="currentColor"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M6.293 6.293a1 1 0 0 1 1.414 0L12 10.586l4.293-4.293a1 1 0 1 1 1.414 1.414L13.414 12l4.293 4.293a1 1 0 0 1-1.414 1.414L12 13.414l-4.293 4.293a1 1 0 0 1-1.414-1.414L10.586 12 6.293 7.707a1 1 0 0 1 0-1.414"
/>
</svg>
</div>
</button>
</div>
<p>
This is an example of a popover.
</p>
</div>
`;
+3 -7
View File
@@ -123,16 +123,12 @@ before using one further down the tree. */
/* On Android and iOS, prefer native system fonts. The global.css file of
Compound Web is where these variables ultimately get consumed to set the page's
font-family. Also on the container that menus and tooltips float into, which
is outside the root in the component build. */
:is(
[data-element-call-root],
[data-element-call-portal]
)[data-platform="android"] {
font-family. */
[data-element-call-root][data-platform="android"] {
--cpd-font-family-sans: "Roboto", "Noto", "Inter", sans-serif;
}
:is([data-element-call-root], [data-element-call-portal])[data-platform="ios"] {
[data-element-call-root][data-platform="ios"] {
--cpd-font-family-sans:
-apple-system, BlinkMacSystemFont, "Inter", sans-serif;
}
+121 -38
View File
@@ -5,7 +5,15 @@ 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 ComponentPropsWithoutRef, type FC } from "react";
import {
cloneElement,
type ComponentProps,
type ComponentPropsWithoutRef,
type FC,
type ReactElement,
useId,
useState,
} from "react";
import classNames from "classnames";
import { useTranslation } from "react-i18next";
import {
@@ -25,16 +33,14 @@ import {
OverflowVerticalIcon,
VolumeOnSolidIcon,
VolumeOffSolidIcon,
SettingsSolidIcon,
GridIcon,
SpotlightViewIcon,
} from "@vector-im/compound-design-tokens/assets/web/icons";
import styles from "./Button.module.css";
import callFooterStyles from "../components/CallFooter.module.css";
import { platform } from "../Platform";
import { type LayoutMode } from "../state/LayoutSwitchViewModel";
import { useAnnouncement } from "../useAnnouncement";
interface MicButtonProps extends ComponentPropsWithoutRef<"button"> {
interface MicButtonProps extends ComponentProps<"button"> {
enabled: boolean;
busy?: boolean;
size?: "md" | "lg";
@@ -66,15 +72,25 @@ export const MicButton: FC<MicButtonProps> = ({ enabled, busy, ...props }) => {
);
};
interface VideoButtonProps extends ComponentPropsWithoutRef<"button"> {
/**
* What a button does is unavailable for now, and why. The button stays
* reachable and says why on hover, focus and activation, instead of doing it.
*/
export interface Unavailable {
description: string;
}
interface VideoButtonProps extends ComponentProps<"button"> {
enabled: boolean;
busy?: boolean;
size?: "md" | "lg";
unavailable?: Unavailable;
}
export const VideoButton: FC<VideoButtonProps> = ({
enabled,
busy,
unavailable,
...props
}) => {
const { t } = useTranslation();
@@ -88,7 +104,7 @@ export const VideoButton: FC<VideoButtonProps> = ({
: t("start_video_button_label");
return (
<Tooltip label={label}>
<UnavailableTooltip label={label} unavailable={unavailable}>
<CpdButton
iconOnly
Icon={Icon}
@@ -102,17 +118,19 @@ export const VideoButton: FC<VideoButtonProps> = ({
})}
disabled={props.disabled || busy}
/>
</Tooltip>
</UnavailableTooltip>
);
};
interface ShareScreenButtonProps extends ComponentPropsWithoutRef<"button"> {
enabled: boolean;
size: "md" | "lg";
unavailable?: Unavailable;
}
export const ShareScreenButton: FC<ShareScreenButtonProps> = ({
enabled,
unavailable,
...props
}) => {
const { t } = useTranslation();
@@ -121,7 +139,7 @@ export const ShareScreenButton: FC<ShareScreenButtonProps> = ({
: t("screenshare_button_label");
return (
<Tooltip label={label}>
<UnavailableTooltip label={label} unavailable={unavailable}>
<CpdButton
iconOnly
Icon={ShareScreenSolidIcon}
@@ -130,7 +148,68 @@ export const ShareScreenButton: FC<ShareScreenButtonProps> = ({
aria-checked={enabled}
{...props}
/>
</Tooltip>
</UnavailableTooltip>
);
};
interface UnavailableTooltipProps {
label: string;
unavailable: Unavailable | undefined;
children: ReactElement<ComponentPropsWithoutRef<"button">>;
}
/**
* The button's tooltip: its label, or while it is unavailable the reason.
* The button is then not disabled: a disabled button drops its clicks, and a
* tap is the only way a touch screen has to ask why.
*/
const UnavailableTooltip: FC<UnavailableTooltipProps> = ({
label,
unavailable,
children,
}) => {
const descriptionId = useId();
const [open, setOpen] = useState(false);
const [liveRegion, announce] = useAnnouncement();
if (unavailable === undefined)
return <Tooltip label={label}>{children}</Tooltip>;
const { description } = unavailable;
// The hover and focus Compound gives a tooltip are off once it is
// controlled, which it has to be to open on a tap
const button = cloneElement(children, {
"aria-label": label,
"aria-disabled": true,
"aria-describedby": descriptionId,
disabled: undefined,
onClick: () => {
setOpen(true);
announce(description);
},
onPointerEnter: (e) => {
if (e.pointerType !== "touch") setOpen(true);
},
onPointerLeave: (e) => {
if (e.pointerType !== "touch") setOpen(false);
},
onFocus: () => setOpen(true),
onBlur: () => setOpen(false),
});
return (
<>
<Tooltip
description={description}
open={open}
onOpenChange={setOpen}
maxLines={4}
>
{button}
</Tooltip>
<span id={descriptionId} hidden>
{description}
</span>
{liveRegion}
</>
);
};
@@ -152,7 +231,6 @@ interface LoudspeakerButtonProps extends ComponentPropsWithoutRef<"button"> {
size?: "md" | "lg";
loudspeakerModeEnabled: boolean;
}
export const LoudspeakerButton: FC<LoudspeakerButtonProps> = ({
loudspeakerModeEnabled,
...props
@@ -175,37 +253,36 @@ export const LoudspeakerButton: FC<LoudspeakerButtonProps> = ({
);
};
interface LayoutSwitchButtonProps extends ComponentPropsWithoutRef<"button"> {
layout: LayoutMode;
function classNamesForScreenWidth(
className?: string,
forScreenWidth?: "wide" | "narrow",
): string {
return classNames(className, {
[callFooterStyles.settingsOnlyShowWide]: forScreenWidth === "wide",
[callFooterStyles.settingsOnlyShowNarrow]: forScreenWidth === "narrow",
});
}
export const LayoutSwitchButton: FC<LayoutSwitchButtonProps> = ({
layout,
interface SettingsIconButtonProps extends ComponentPropsWithoutRef<"button"> {
/** If this buttons should be setup to be used in the app bar */
showForScreenWidth?: "wide" | "narrow";
kind?: "secondary" | "primary";
}
export const SettingsIconButton: FC<SettingsIconButtonProps> = ({
showForScreenWidth,
className,
...props
}) => {
const { t } = useTranslation();
return (
<Tooltip label={t("action.adjust_view")}>
<CpdButton
iconOnly
Icon={layout === "grid" ? GridIcon : SpotlightViewIcon}
kind="secondary"
{...props}
/>
</Tooltip>
);
};
interface SettingsIconButtonProps extends ComponentPropsWithoutRef<"button"> {
kind?: "secondary" | "primary";
}
export const SettingsIconButton: FC<SettingsIconButtonProps> = (props) => {
const { t } = useTranslation();
const Icon =
platform === "android" ? OverflowVerticalIcon : OverflowHorizontalIcon;
return (
<Tooltip label={t("common.settings")}>
<IconButton {...props}>
<SettingsSolidIcon aria-hidden />
<IconButton
className={classNamesForScreenWidth(className, showForScreenWidth)}
{...props}
>
<Icon aria-hidden />
</IconButton>
</Tooltip>
);
@@ -213,13 +290,19 @@ export const SettingsIconButton: FC<SettingsIconButtonProps> = (props) => {
interface SettingsButtonProps extends ComponentPropsWithoutRef<"button"> {
size?: "md" | "lg";
/** If this buttons should be setup to be used in the app bar */
showForScreenWidth?: "wide" | "narrow";
}
export const SettingsButton: FC<SettingsButtonProps> = (props) => {
export const SettingsButton: FC<SettingsButtonProps> = ({
showForScreenWidth,
className,
...props
}) => {
const { t } = useTranslation();
return (
<Tooltip label={t("common.settings")}>
<CpdButton
className={classNamesForScreenWidth(className, showForScreenWidth)}
iconOnly
Icon={
platform === "android" ? OverflowVerticalIcon : OverflowHorizontalIcon
+71
View File
@@ -0,0 +1,71 @@
/*
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, userEvent, waitFor, within } from "storybook/test";
/**
* Checks, in a story, that a button whose action is unavailable stays
* reachable and says why with every input it accepts, and never acts.
*
* @param touch - Tap it as a touch screen does, which has no hover or focus
* to show the reason first.
*/
export async function expectExplainsUnavailable(
button: HTMLElement,
description: string,
acted: () => unknown,
{ touch = false }: { touch?: boolean } = {},
): Promise<void> {
await expect(button).toHaveAttribute("aria-disabled", "true");
await expect(button).not.toHaveAttribute("disabled");
await expect(button).toHaveAttribute("aria-checked", "false");
await expect(button).toHaveAccessibleDescription(description);
if (!touch) {
await userEvent.hover(button);
await expectTooltip(description);
await userEvent.unhover(button);
await expectNoTooltip();
await expect(button.tabIndex).toBe(0);
button.focus();
await expectTooltip(description);
await userEvent.keyboard("{Escape}");
await expectNoTooltip();
button.blur();
}
if (touch)
await userEvent.pointer([
{ keys: "[TouchA]", target: button },
{ keys: "[/TouchA]", target: button },
]);
else await userEvent.click(button);
await expectTooltip(description);
await expect(liveRegionTexts()).toContain(description);
await expect(acted).not.toHaveBeenCalled();
}
async function expectTooltip(description: string): Promise<void> {
const tooltip = await within(document.body).findByRole("tooltip");
await expect(tooltip).toHaveTextContent(description);
// Not cut short by the tooltip's line clamp
const text = tooltip.querySelector("span")!;
await expect(text.scrollHeight).toBeLessThanOrEqual(text.clientHeight + 1);
}
async function expectNoTooltip(): Promise<void> {
await waitFor(async () =>
expect(within(document.body).queryByRole("tooltip")).toBeNull(),
);
}
function liveRegionTexts(): string[] {
return [...document.querySelectorAll('[aria-live="polite"]')].map((region) =>
region.textContent.trim(),
);
}
+1 -1
View File
@@ -24,7 +24,7 @@ import * as CallFooterStories from "./CallFooter.stories";
<Title> Call Footer </Title>
The footer component contains all main interactions needed for a call.
The footer compoentn contains all main interactions needed for a call.
<Subtitle> Mobile layouts </Subtitle>
+33 -93
View File
@@ -9,10 +9,9 @@ Please see LICENSE in the repository root for full details.
position: sticky;
inset-block-end: 0;
z-index: var(--call-view-header-footer-layer);
pointer-events: none;
display: grid;
grid-template-columns: 1fr auto 1fr;
grid-template-areas: ". buttons .";
grid-template-areas: ". buttons layout";
align-items: center;
gap: var(--cpd-space-3x);
/* Ensure that footer lies within the safe area */
@@ -20,10 +19,6 @@ Please see LICENSE in the repository root for full details.
padding-right: calc(env(safe-area-inset-right) + var(--cpd-space-6x));
padding-block: var(--cpd-space-10x)
calc(env(safe-area-inset-bottom) + var(--cpd-space-10x));
> * {
pointer-events: auto;
}
}
.footer.hidden {
@@ -31,57 +26,21 @@ Please see LICENSE in the repository root for full details.
}
.footer.overlay {
transition: opacity 0.18s;
opacity: 0;
> .buttons {
transition: transform 0.18s;
@media (prefers-reduced-motion: no-preference) {
transform: translateY(var(--slide-distance));
}
}
> * {
animation: none;
}
}
@keyframes enable-pointer-events {
0% {
pointer-events: none;
}
100% {
pointer-events: auto;
}
}
.footer.overlay:not(.hidden) {
/* Note that the footer is still position: sticky in this case so that certain
tiles can move up out of the way of the footer when visible. */
opacity: 1;
> .buttons {
transform: none;
}
> * {
/* Enable pointer events after a short timeout, so that tapping to reveal the
footer won't immediately cause any of the buttons to be pressed. */
animation: enable-pointer-events 1ms;
}
transition: opacity 0.15s;
}
.footer.overlay.hidden {
display: grid;
opacity: 0;
pointer-events: none;
/* Switch to position: absolute so the footer takes up no space in the layout
when hidden. */
position: absolute;
inset-block-end: 0;
inset-inline: 0;
> * {
pointer-events: none;
}
}
/* Keep the footer while it is in use: focus inside it, or a menu opened from
@@ -89,17 +48,10 @@ Please see LICENSE in the repository root for full details.
.footer.overlay:has(:focus-visible),
.footer.overlay:has([aria-expanded="true"]) {
opacity: 1;
> .buttons {
transform: none;
}
> * {
pointer-events: auto;
}
pointer-events: initial;
}
.logoContainer {
.settingsLogoContainer {
display: flex;
align-items: center;
gap: var(--cpd-space-4x);
@@ -118,45 +70,13 @@ Please see LICENSE in the repository root for full details.
.buttons {
grid-area: buttons;
justify-self: center;
background: var(--cpd-color-bg-canvas-default);
border-radius: var(--cpd-radius-pill-effect);
box-shadow: var(--big-drop-shadow);
display: flex;
flex-wrap: nowrap;
gap: var(--cpd-space-3x);
}
:global(.cpd-theme-light),
:global(.cpd-theme-light-hc) {
.buttons {
background: var(--cpd-color-bg-canvas-default);
}
}
/* Dark theme uses a different background color, since the drop shadow doesn't
provide enough contrast */
:global(.cpd-theme-dark),
:global(.cpd-theme-dark-hc) {
.buttons {
background: var(--cpd-color-bg-subtle-primary);
}
}
@media (prefers-color-scheme: dark) {
.buttons {
background: var(--cpd-color-bg-subtle-primary);
}
}
.footer[data-button-size="md"] > .buttons {
padding: var(--cpd-space-3x);
gap: var(--cpd-space-2x);
--slide-distance: var(--cpd-space-2x);
}
.footer[data-button-size="lg"] > .buttons {
padding: var(--cpd-space-4x);
gap: var(--cpd-space-4x);
--slide-distance: var(--cpd-space-4x);
.layout {
grid-area: layout;
justify-self: end;
}
/*First hide the logo*/
@@ -166,16 +86,30 @@ provide enough contrast */
}
}
.settingsOnlyShowNarrow {
display: none;
}
.settingsOnlyShowWide {
display: inherit;
}
/*
With the logo hidden >500px is enough space to show logo and buttons.
Once we exceed 500 we hide the logo.
With the logo hidden >500px is enough space to show overflow, buttons, layout.
Once we exceed 500 we hide everything except the buttons.
*/
@container element-call (max-width: 500px) {
.footer {
grid-template-areas: "buttons buttons buttons";
}
.logoContainer {
.settingsOnlyShowNarrow {
display: inherit;
}
.settingsOnlyShowWide {
display: none;
}
.settingsLogoContainer {
display: none;
}
@@ -222,3 +156,9 @@ Once we exceed 500 we hide the logo.
display: none;
}
}
@container element-call (min-width: 800px) {
.buttons {
gap: var(--cpd-space-4x);
}
}
+69 -15
View File
@@ -5,7 +5,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { expect, fn, userEvent, waitFor, within } from "storybook/test";
import { expect, fn, userEvent, within } from "storybook/test";
import { BehaviorSubject } from "rxjs";
import { type JSX, type ReactNode } from "react";
import { Link } from "@vector-im/compound-web";
@@ -23,6 +23,7 @@ import { globalScope } from "../state/ObservableScope";
import { constant } from "../state/Behavior";
import { type LayoutMode } from "../state/LayoutSwitchViewModel";
import { type MediaMenuSnapshot } from "./MediaMenuViewModel";
import { expectExplainsUnavailable } from "../button/expectExplainsUnavailable";
// consts for tests
const reactionIdentifier = "@user:example.com:DEVICE";
@@ -38,12 +39,15 @@ const mediaDevices = new MediaDevices(globalScope, {
function menu(
kind: "audio" | "video",
withDevices: boolean,
lowBandwidthMode = false,
): MediaMenuSnapshot {
const device = kind === "audio" ? "Microphone" : "Camera";
const heldOff = kind === "video" && lowBandwidthMode;
return {
enabled: true,
enabled: !heldOff,
busy: false,
toggle: fn(),
unavailableReason: heldOff ? "lowBandwidthMode" : undefined,
options: withDevices
? [
{ id: "1", label: { type: "name", name: `${device} 1` } },
@@ -106,7 +110,9 @@ function CallFooterStoryWrapper({
withDevices: boolean;
}): ReactNode {
const audioMenuVm = useStaticViewModel(menu("audio", withDevices));
const cameraMenuVm = useStaticViewModel(menu("video", withDevices));
const cameraMenuVm = useStaticViewModel(
menu("video", withDevices, vmSnapshot.screenShareUnavailable),
);
const vm = useStaticViewModel({
...vmSnapshot,
layoutSwitchVm: layout && { layout$: constant(layout), setLayout },
@@ -172,12 +178,13 @@ export const Default: Story = {
openSettings: fn(),
toggleScreenSharing: fn(),
hangup: fn(),
buttonSize: "md",
buttonSize: "lg",
showFooter: true,
hideControls: false,
asOverlay: false,
showModals: true,
sharingScreen: false,
screenShareUnavailable: false,
audioOutputSwitcher: undefined,
reactionIdentifier: undefined,
reactionData: undefined,
@@ -202,11 +209,8 @@ export const StaysWhileAMenuIsOpen: Story = {
const footer = canvasElement.querySelector<HTMLElement>(
'[data-testid="footer-container"]',
)!;
// Open microphone menu once footer becomes interactive
await waitFor(async () =>
userEvent.click(
within(canvasElement).getByRole("button", { name: "Microphone" }),
),
await userEvent.click(
within(canvasElement).getByRole("button", { name: "Microphone" }),
);
await expect(document.body.querySelector('[role="menu"]')).not.toBeNull();
@@ -235,9 +239,8 @@ export const SpotlightMode: Story = {
layout: "spotlight",
},
play: async ({ args, canvasElement }) => {
const canvas = within(canvasElement.parentElement!);
await userEvent.click(canvas.getByRole("button", { name: "Adjust view" }));
await userEvent.click(canvas.getByRole("menuitemradio", { name: "Grid" }));
const canvas = within(canvasElement);
await userEvent.click(canvas.getByRole("radio", { name: "Grid" }));
await expect(args.setLayout).toHaveBeenCalledWith("grid");
await userEvent.click(canvas.getByRole("switch", { name: "Share screen" }));
await expect(args.toggleScreenSharing).toHaveBeenCalled();
@@ -273,11 +276,12 @@ export const Pip: Story = {
...Default,
args: {
...Default.args,
buttonSize: "md",
layout: null,
},
play: async ({ canvasElement }) => {
await expect(
within(canvasElement).queryByRole("button", { name: "Adjust view" }),
within(canvasElement).queryByRole("radio", { name: "Spotlight" }),
).not.toBeInTheDocument();
},
};
@@ -304,7 +308,6 @@ export const MobileLayout: Story = {
args: {
...Default.args,
showLogo: false,
buttonSize: "lg",
audioOutputSwitcher: { targetOutput: "speaker", switch: fn() },
},
@@ -336,7 +339,6 @@ export const LobbyRecentButtonMobile: Story = {
...Default.args,
children: <Link>Back To Recents</Link>,
showLogo: false,
buttonSize: "lg",
layout: null,
toggleScreenSharing: undefined,
},
@@ -347,3 +349,55 @@ export const LobbyRecentButtonMobile: Story = {
...Default.parameters,
},
};
const screenShareExplanation =
"You can't share your screen while Low bandwidth mode is on. To turn it off, select Cancel on the Low bandwidth mode banner, or use Video settings.";
/** The camera and screen share both held, each saying why. */
export const LowBandwidthMode: Story = {
...Default,
args: {
...Default.args,
screenShareUnavailable: true,
},
play: async ({ args, canvasElement }) => {
const canvas = within(canvasElement);
await expect(
canvas.getByRole("switch", { name: "Start video" }),
).toHaveAttribute("aria-disabled", "true");
await expectExplainsUnavailable(
canvas.getByRole("switch", { name: "Share screen" }),
screenShareExplanation,
args.toggleScreenSharing!,
);
},
};
export const LowBandwidthModeMobile: Story = {
...LowBandwidthMode,
globals: {
viewport: { value: "mobile2", isRotated: false },
},
play: async ({ args, canvasElement }) => {
await expectExplainsUnavailable(
within(canvasElement).getByRole("switch", { name: "Share screen" }),
screenShareExplanation,
args.toggleScreenSharing!,
{ touch: true },
);
},
};
/** Where no share can be started there is no button, and nothing to explain. */
export const LowBandwidthModeWithoutScreenSharing: Story = {
...LowBandwidthMode,
args: {
...LowBandwidthMode.args,
toggleScreenSharing: undefined,
},
play: async ({ canvasElement }) => {
await expect(
within(canvasElement).queryByRole("switch", { name: "Share screen" }),
).toBeNull();
},
};
+47 -29
View File
@@ -7,6 +7,7 @@ Please see LICENSE in the repository root for full details.
import { type FC, type JSX, type Ref, useMemo } from "react";
import classNames from "classnames";
import { useTranslation } from "react-i18next";
import LogoMark from "../icons/LogoMark.svg?react";
import LogoType from "../icons/LogoType.svg?react";
@@ -16,6 +17,7 @@ import {
SettingsButton,
ReactionToggleButton,
LoudspeakerButton,
SettingsIconButton,
type ReactionData,
} from "../button";
import styles from "./CallFooter.module.css";
@@ -36,13 +38,13 @@ export interface AudioOutputSwitcher {
* The Snapshot combines all fields required to populate the view.
*
* It is a combination of Actions and State.
* All Actions and State will be wrapped in behaviors.
* This has the advantage that actions can mutate.
* (example: a device gets disconnected, the switch action is not possible anymore, the action becomes undefined)
* With it being reactive we can use the existence of the action to update the rendering without
* All Actions and State will be wrappen in behaviors.
* This has the advantage, that actions can mutate.
* (example: a device gets disconnected, the swicht action is not possible anymore, the actions becomes undefined)
* With it being reactive we can use the existance of the action to update the rendering without
* requiring additional state.
*
* Comment: It might not make sense to separate the two interfaces. Hence the separation
* Comment: It might not make sense to seperate the two interfaces. Hence the seperation
* just happens on the syntax level with the `type = ... & ...` notation.
*/
export type FooterSnapshot = FooterActions & FooterState;
@@ -74,6 +76,8 @@ export interface FooterState {
layoutSwitchVm: LayoutSwitchViewModel | null;
sharingScreen: boolean;
/** Whether starting a screen share is unavailable, and explained instead. */
screenShareUnavailable: boolean;
/** Also controls if the audio output button is visible */
audioOutputSwitcher: AudioOutputSwitcher | undefined;
@@ -89,6 +93,8 @@ export interface FooterState {
export interface FooterProps {
className?: string;
ref?: Ref<HTMLDivElement>;
/** The camera's mute button, for focus to be moved to it. */
cameraButtonRef?: Ref<HTMLButtonElement>;
children?: JSX.Element | JSX.Element[] | false;
vm: ViewModel<FooterSnapshot>;
}
@@ -96,9 +102,11 @@ export interface FooterProps {
export const CallFooter: FC<FooterProps> = ({
className,
ref,
cameraButtonRef,
children,
vm,
}) => {
const { t } = useTranslation();
const asOverlay = useBehavior(vm.asOverlay$);
const showFooter = useBehavior(vm.showFooter$);
const hideControls = useBehavior(vm.hideControls$);
@@ -109,6 +117,7 @@ export const CallFooter: FC<FooterProps> = ({
const openSettings = useBehavior(vm.openSettings$);
const sharingScreen = useBehavior(vm.sharingScreen$);
const toggleScreenSharing = useBehavior(vm.toggleScreenSharing$);
const screenShareUnavailable = useBehavior(vm.screenShareUnavailable$);
const reactionIdentifier = useBehavior(vm.reactionIdentifier$);
const reactionData = useBehavior(vm.reactionData$);
const audioOutputSwitcher = useBehavior(vm.audioOutputSwitcher$);
@@ -119,6 +128,20 @@ export const CallFooter: FC<FooterProps> = ({
const buttons: JSX.Element[] = [];
if (openSettings !== undefined) {
// Add the settings button to the center group so it's visible on small
// screens. On larger screens the SettingsIconButton with
// showForScreenWidth="wide" in the settingsLogoContainer is used instead.
buttons.push(
<SettingsButton
key="settings"
showForScreenWidth="narrow"
onClick={openSettings}
data-testid="settings-bottom-center"
/>,
);
}
buttons.push(
<MediaMenuButton
key="audio"
@@ -131,6 +154,7 @@ export const CallFooter: FC<FooterProps> = ({
kind="video"
vm={cameraMenuVm}
size={buttonSize}
buttonRef={cameraButtonRef}
/>,
);
@@ -142,6 +166,11 @@ export const CallFooter: FC<FooterProps> = ({
className={styles.shareScreen}
enabled={sharingScreen ?? false}
onClick={toggleScreenSharing}
unavailable={
screenShareUnavailable
? { description: t("low_bandwidth_mode.screen_share_unavailable") }
: undefined
}
data-testid="incall_screenshare"
/>,
);
@@ -174,28 +203,6 @@ export const CallFooter: FC<FooterProps> = ({
if (audioOutputButton) buttons.push(audioOutputButton);
if (layoutSwitchVm !== null) {
buttons.push(
<LayoutSwitch
key="layout"
vm={layoutSwitchVm}
className={styles.layout}
size={buttonSize}
/>,
);
}
if (openSettings !== undefined) {
buttons.push(
<SettingsButton
size={buttonSize}
key="settings"
onClick={openSettings}
data-testid="settings-bottom"
/>,
);
}
if (hangup)
buttons.push(
<EndCallButton
@@ -228,17 +235,28 @@ export const CallFooter: FC<FooterProps> = ({
<div
ref={ref}
data-testid="footer-container"
data-button-size={buttonSize}
className={classNames(className, styles.footer, {
[styles.overlay]: asOverlay,
[styles.hidden]: !showFooter,
})}
>
<div className={styles.logoContainer}>
<div className={styles.settingsLogoContainer}>
{openSettings !== undefined && (
<SettingsIconButton
key="settings"
kind="secondary"
showForScreenWidth="wide"
onClick={openSettings}
data-testid="settings-bottom-left"
/>
)}
{children}
{(showLogo || debugTileLayout) && logoDebugContainer}
</div>
{!hideControls && <div className={styles.buttons}>{buttons}</div>}
{!hideControls && layoutSwitchVm && (
<LayoutSwitch vm={layoutSwitchVm} className={styles.layout} />
)}
</div>
);
};
@@ -102,6 +102,7 @@ describe("createCallFooterViewModel", () => {
testScope(),
buildMinimalCallViewModel(layout),
mockMuteStates(),
constant(false),
devices,
pipeline,
/* reactionIdentifier */ undefined,
@@ -121,6 +122,7 @@ describe("createCallFooterViewModel", () => {
testScope(),
{ ...buildMinimalCallViewModel(gridLayout), camera$: constant(track) },
mockMuteStates(),
constant(false),
devices,
pipeline,
/* reactionIdentifier */ undefined,
+11 -2
View File
@@ -30,6 +30,8 @@ import {
* @param scope - ObservableScope that bounds the lifetime of derived behaviors.
* @param callModel - The root CallViewModel; provides layout, grid mode, reactions, etc.
* @param muteStates - Audio and video mute state + toggles.
* @param lowBandwidthMode$ - Whether the call's low bandwidth mode is on,
* which makes the camera and screen sharing unavailable.
* @param mediaDevices - Available and selected input devices.
* @param backgroundEffectsState$ - The background pipeline's state: whether
* effects run here, and the wait for the first.
@@ -42,6 +44,7 @@ export function createCallFooterViewModel(
scope: ObservableScope,
callModel: CallViewModel,
muteStates: MuteStates,
lowBandwidthMode$: Behavior<boolean>,
mediaDevices: MediaDevices,
backgroundEffectsState$: Observable<BackgroundEffectsState>,
reactionIdentifier: string | undefined,
@@ -73,6 +76,7 @@ export function createCallFooterViewModel(
disableDeviceSwitcher$,
backgroundEffectsState$,
callModel.camera$,
lowBandwidthMode$,
),
),
// candidat to move into the FooterViewModel
@@ -80,7 +84,9 @@ export function createCallFooterViewModel(
hideControls$: constant(!showControls),
showModals$: callModel.showModals$,
asOverlay$: callModel.edgeToEdge$,
buttonSize$: constant(platform === "desktop" ? "md" : "lg"),
buttonSize$: scope.behavior(
isPip$.pipe(map<boolean, "md" | "lg">((pip) => (pip ? "md" : "lg"))),
),
openSettings$: scope.behavior(
combineLatest([
@@ -102,6 +108,7 @@ export function createCallFooterViewModel(
sharingScreen$: callModel.sharingScreen$,
toggleScreenSharing$: constant(callModel.toggleScreenSharing ?? undefined),
screenShareUnavailable$: lowBandwidthMode$,
audioOutputSwitcher$: scope.behavior(
callModel.audioOutputSwitcher$.pipe(
@@ -160,12 +167,13 @@ export function createLobbyFooterViewModel(
hideControls: false,
asOverlay: false,
showModals: true,
buttonSize: platform === "desktop" ? "md" : "lg",
buttonSize: "lg",
openSettings,
hangup,
debugTileLayout: false,
showFooter: true,
toggleScreenSharing: undefined,
screenShareUnavailable: false,
layoutSwitchVm: null,
sharingScreen: false,
audioOutputSwitcher: undefined,
@@ -185,6 +193,7 @@ export function createLobbyFooterViewModel(
constant(false),
backgroundEffectsState$,
camera$,
constant(false),
),
});
}
@@ -0,0 +1,42 @@
/*
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.
*/
.indicator {
position: absolute;
inset-inline: 0;
margin-inline: auto;
/* Where the footer's buttons are, while the footer is hidden */
inset-block-end: calc(env(safe-area-inset-bottom) + var(--cpd-space-10x));
z-index: var(--call-view-header-footer-layer);
box-shadow: 0px 4px 24px 0px rgba(27, 29, 34, 0.1);
}
.indicator.inline {
position: relative;
inset-block-end: auto;
align-self: center;
flex-shrink: 0;
margin-block-start: var(--cpd-space-3x);
max-inline-size: calc(100% - 2 * var(--cpd-space-3x));
}
.cancel {
appearance: none;
background: none;
border: none;
padding: 0;
font: inherit;
color: inherit;
text-decoration: underline;
cursor: pointer;
}
.cancel:focus-visible {
outline: 2px solid currentcolor;
outline-offset: 2px;
border-radius: var(--cpd-space-1x);
}
@@ -0,0 +1,184 @@
/*
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, fn, userEvent, within } from "storybook/test";
import { type JSX, type ReactNode, useRef } from "react";
import type { Meta, StoryObj } from "@storybook/react-vite";
import {
LowBandwidthIndicator,
type LowBandwidthIndicatorSnapshot,
} from "./LowBandwidthIndicator";
import inCallViewStyles from "../room/InCallView.module.css";
import { useStaticViewModel } from "../state/ViewModel";
import { VideoButton } from "../button";
const footerHeight = 136;
/** The indicator at the bottom of a call, over a footer of the usual height. */
function LowBandwidthIndicatorStoryWrapper({
footerShown,
...snapshot
}: LowBandwidthIndicatorSnapshot & { footerShown: boolean }): ReactNode {
const vm = useStaticViewModel(snapshot);
const cameraButtonRef = useRef<HTMLButtonElement>(null);
if (snapshot.inline) {
// Element Web's picture-in-picture window: the tile, then the indicator,
// then the footer, in the call view's column
return (
<div
className={inCallViewStyles.inRoom}
style={{ inlineSize: 340, blockSize: 400 }}
>
<div data-testid="tile" style={{ flexGrow: 1 }} />
<LowBandwidthIndicator vm={vm} footerHeight={null} />
<div data-testid="footer" style={{ flexShrink: 0, blockSize: 96 }} />
</div>
);
}
return (
<div className={inCallViewStyles.inRoom} style={{ position: "relative" }}>
<LowBandwidthIndicator
vm={vm}
footerHeight={footerShown ? footerHeight : null}
focusAfterCancel={cameraButtonRef}
/>
{footerShown && (
<div
data-testid="footer"
style={{
position: "absolute",
insetBlockEnd: 0,
inlineSize: "100%",
blockSize: footerHeight,
display: "flex",
alignItems: "center",
justifyContent: "center",
outline: "1px dashed var(--cpd-color-border-interactive-primary)",
}}
>
<VideoButton ref={cameraButtonRef} enabled={false} />
</div>
)}
</div>
);
}
const meta = {
component: LowBandwidthIndicatorStoryWrapper,
args: { shown: true, inline: false, cancel: fn(), footerShown: true },
argTypes: {
cancel: {
control: { type: "select" },
options: ["MockedCallback", "undefined"],
mapping: { MockedCallback: fn(), undefined: undefined },
},
},
parameters: { layout: "fullscreen" },
decorators: [
(Story): JSX.Element => (
<div style={{ blockSize: "100vh" }}>
<Story />
</div>
),
],
} satisfies Meta<typeof LowBandwidthIndicatorStoryWrapper>;
export default meta;
type Story = StoryObj<typeof meta>;
export const AboveTheFooter: Story = {
play: async ({ args, canvasElement }) => {
const canvas = within(canvasElement);
const indicator = canvas.getByTestId("low-bandwidth-indicator");
await expect(indicator).toHaveTextContent("Low bandwidth mode");
await expect(indicator.getBoundingClientRect().bottom).toBeLessThanOrEqual(
canvas.getByTestId("footer").getBoundingClientRect().top,
);
await userEvent.click(
canvas.getByRole("button", { name: "Cancel Low bandwidth mode" }),
);
await expect(args.cancel).toHaveBeenCalled();
},
};
export const CancelFromTheKeyboard: Story = {
play: async ({ args, canvasElement }) => {
const canvas = within(canvasElement);
canvas.getByRole("button", { name: "Cancel Low bandwidth mode" }).focus();
await userEvent.keyboard("{Enter}");
await expect(args.cancel).toHaveBeenCalled();
// The indicator goes with the mode; focus waits on the camera button
await expect(
canvas.getByRole("switch", { name: "Start video" }),
).toHaveFocus();
},
};
export const FooterHidden: Story = {
args: { footerShown: false },
play: async ({ canvasElement }) => {
const indicator = within(canvasElement).getByTestId(
"low-bandwidth-indicator",
);
await expect(indicator).toBeVisible();
await expect(
canvasElement.getBoundingClientRect().bottom -
indicator.getBoundingClientRect().bottom,
).toBeLessThan(footerHeight);
},
};
export const Narrow: Story = {
globals: { viewport: { value: "mobile2" } },
play: async ({ canvasElement }) => {
await expect(
within(canvasElement).getByRole("button", {
name: "Cancel Low bandwidth mode",
}),
).toBeVisible();
},
};
export const PictureInPicture: Story = {
args: { inline: true },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const indicator = canvas.getByTestId("low-bandwidth-indicator");
const bounds = indicator.getBoundingClientRect();
await expect(bounds.top).toBeGreaterThanOrEqual(
canvas.getByTestId("tile").getBoundingClientRect().bottom,
);
await expect(bounds.bottom).toBeLessThanOrEqual(
canvas.getByTestId("footer").getBoundingClientRect().top,
);
await expect(indicator.scrollWidth).toBeLessThanOrEqual(
indicator.clientWidth,
);
await expect(
canvas.getByRole("button", { name: "Cancel Low bandwidth mode" }),
).toBeVisible();
},
};
export const WithoutControls: Story = {
args: { cancel: undefined },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await expect(canvas.getByTestId("low-bandwidth-indicator")).toBeVisible();
await expect(canvas.queryByRole("button")).toBeNull();
},
};
export const Off: Story = {
args: { shown: false },
play: async ({ canvasElement }) => {
await expect(
within(canvasElement).queryByTestId("low-bandwidth-indicator"),
).toBeNull();
},
};
+83
View File
@@ -0,0 +1,83 @@
/*
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 ReactNode, type Ref, type RefObject } from "react";
import { useTranslation } from "react-i18next";
import classNames from "classnames";
import { Toast } from "@vector-im/compound-web";
import { VideoCallOffIcon } from "@vector-im/compound-design-tokens/assets/web/icons";
import styles from "./LowBandwidthIndicator.module.css";
import { type ViewModel } from "../state/ViewModel";
import { useBehavior } from "../useBehavior";
export interface LowBandwidthIndicatorSnapshot {
/** Whether the call is in Low bandwidth mode, in a window big enough to say so. */
shown: boolean;
/** Whether it takes a row of its own between the tile and the footer. */
inline: boolean;
/** Turns the mode off; undefined where the host hides the call's controls. */
cancel: (() => void) | undefined;
}
interface Props {
vm: ViewModel<LowBandwidthIndicatorSnapshot>;
/** The height of the footer to sit above, or null while the footer is hidden. */
footerHeight: number | null;
/** Where focus goes once Cancel has removed the indicator, and itself. */
focusAfterCancel?: RefObject<HTMLElement | null>;
className?: string;
ref?: Ref<HTMLDivElement>;
}
/** A pill above the call's footer that says the call is in Low bandwidth mode. */
export function LowBandwidthIndicator({
vm,
footerHeight,
focusAfterCancel,
className,
ref,
}: Props): ReactNode {
const { t } = useTranslation();
const shown = useBehavior(vm.shown$);
const inline = useBehavior(vm.inline$);
const cancel = useBehavior(vm.cancel$);
if (!shown) return null;
return (
<Toast
Icon={VideoCallOffIcon}
ref={ref}
className={classNames(
styles.indicator,
{ [styles.inline]: inline },
className,
)}
style={
inline || footerHeight === null
? undefined
: { insetBlockEnd: footerHeight }
}
data-testid="low-bandwidth-indicator"
>
<span>{t("low_bandwidth_mode.indicator")}</span>
{cancel && (
<button
type="button"
className={styles.cancel}
onClick={(): void => {
cancel();
focusAfterCancel?.current?.focus();
}}
aria-label={t("low_bandwidth_mode.indicator_cancel_label")}
>
{t("low_bandwidth_mode.indicator_cancel")}
</button>
)}
</Toast>
);
}
@@ -0,0 +1,81 @@
/*
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, test } from "vitest";
import { createLowBandwidthIndicatorViewModel } from "./LowBandwidthIndicatorViewModel";
import { createLowBandwidthMode } from "../state/LowBandwidthMode";
import { constant } from "../state/Behavior";
import { type Layout } from "../state/layout-types";
import { testScope, withTestScheduler } from "../utils/test";
describe("LowBandwidthIndicatorViewModel", () => {
test("is shown while the mode is on, in the desktop picture-in-picture window too", () => {
withTestScheduler(({ behavior, schedule, expectObservable }) => {
const mode = createLowBandwidthMode(testScope());
const vm = createLowBandwidthIndicatorViewModel(
testScope(),
mode,
behavior("g--p-g", { g: grid, p: pip }),
{ showControls: true, platform: "desktop" },
);
schedule("-yn-y", {
y: () => mode.setEnabled(true),
n: () => mode.setEnabled(false),
});
expectObservable(vm.shown$).toBe("nyn-y", { y: true, n: false });
expectObservable(vm.inline$).toBe("n--y-n", { y: true, n: false });
});
});
test("is not shown in the mobile picture-in-picture window, which has no controls", () => {
withTestScheduler(({ behavior, schedule, expectObservable }) => {
const mode = createLowBandwidthMode(testScope());
const vm = createLowBandwidthIndicatorViewModel(
testScope(),
mode,
behavior("g--p-g", { g: grid, p: pip }),
{ showControls: true, platform: "ios" },
);
schedule("-y", { y: () => mode.setEnabled(true) });
expectObservable(vm.shown$).toBe("ny-n-y", { y: true, n: false });
});
});
test("turns the mode off with Cancel", () => {
const mode = createLowBandwidthMode(testScope());
const vm = createLowBandwidthIndicatorViewModel(
testScope(),
mode,
constant(grid),
{ showControls: true, platform: "desktop" },
);
mode.setEnabled(true);
vm.cancel$.value!();
expect(mode.enabled$.value).toBe(false);
expect(vm.shown$.value).toBe(false);
});
test("has no Cancel where the host hides the call's controls", () => {
const mode = createLowBandwidthMode(testScope());
const vm = createLowBandwidthIndicatorViewModel(
testScope(),
mode,
constant(grid),
{ showControls: false, platform: "desktop" },
);
mode.setEnabled(true);
expect(vm.shown$.value).toBe(true);
expect(vm.cancel$.value).toBeUndefined();
});
});
const grid = { type: "grid" } as Layout;
const pip = { type: "pip" } as Layout;
@@ -0,0 +1,50 @@
/*
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 } from "rxjs";
import { type Behavior, constant } from "../state/Behavior";
import { type Layout } from "../state/layout-types";
import { type LowBandwidthMode } from "../state/LowBandwidthMode";
import { type ObservableScope } from "../state/ObservableScope";
import type { platform as currentPlatform } from "../Platform";
import { type ViewModel } from "../state/ViewModel";
import { type LowBandwidthIndicatorSnapshot } from "./LowBandwidthIndicator";
/**
* Creates the ViewModel for the Low bandwidth mode indicator.
*
* @param scope - ObservableScope that bounds the lifetime of derived behaviors.
* @param lowBandwidthMode - The call's low bandwidth mode, which Cancel turns off.
* @param layout$ - The call's layout.
* @param options - `showControls`: whether the call controls are shown, Cancel
* among them. `platform`: mobile's picture-in-picture window shows no
* controls, so it shows no indicator either.
*/
export function createLowBandwidthIndicatorViewModel(
scope: ObservableScope,
lowBandwidthMode: LowBandwidthMode,
layout$: Behavior<Layout>,
{
showControls,
platform,
}: { showControls: boolean; platform: typeof currentPlatform },
): ViewModel<LowBandwidthIndicatorSnapshot> {
return {
shown$: scope.behavior(
combineLatest(
[lowBandwidthMode.enabled$, layout$],
(enabled, layout) =>
enabled && (layout.type !== "pip" || platform === "desktop"),
),
),
inline$: scope.behavior(layout$.pipe(map((l) => l.type === "pip"))),
cancel$: constant(
showControls ? (): void => lowBandwidthMode.setEnabled(false) : undefined,
),
};
}
+47 -1
View File
@@ -15,6 +15,7 @@ import { useStaticViewModel } from "../state/ViewModel";
import { MediaDevicesContext } from "../MediaDevicesContext";
import { MediaDevices } from "../state/MediaDevices";
import { globalScope } from "../state/ObservableScope";
import { expectExplainsUnavailable } from "../button/expectExplainsUnavailable";
const mediaDevices = new MediaDevices(globalScope, {
controlledAudioDevices: false,
@@ -26,7 +27,7 @@ function MediaMenuButtonStoryWrapper({
...snapshot
}: MediaMenuSnapshot & { kind: "audio" | "video" }): ReactNode {
const vm = useStaticViewModel(snapshot);
return <MediaMenuButton kind={kind} vm={vm} size="md" />;
return <MediaMenuButton kind={kind} vm={vm} size="lg" />;
}
const meta = {
@@ -44,6 +45,7 @@ export default meta;
type Story = StoryObj<typeof meta>;
const empty = {
unavailableReason: undefined,
outputOptions: [],
selectedOutput: undefined,
selectOutput: undefined,
@@ -114,6 +116,50 @@ export const CameraBusy: Story = {
args: { ...Camera.args, busy: true },
};
const lowBandwidthExplanation =
"You can't turn on your camera while Low bandwidth mode is on. To turn it off, select Cancel on the Low bandwidth mode banner, or use Video settings.";
/** Held off, and saying why, with a menu beside it. */
export const CameraUnavailableInLowBandwidthMode: Story = {
args: {
...Camera.args,
enabled: false,
// Undefined in a call; set here to show the button never calls it
toggle: fn(),
unavailableReason: "lowBandwidthMode",
},
play: async ({ args, canvasElement }) => {
await expectExplainsUnavailable(
within(canvasElement).getByRole("switch", { name: "Start video" }),
lowBandwidthExplanation,
args.toggle!,
);
},
};
/** Held off, and saying why, as a plain button. */
export const PlainCameraUnavailableInLowBandwidthMode: Story = {
args: {
...CameraUnavailableInLowBandwidthMode.args,
options: [],
},
play: CameraUnavailableInLowBandwidthMode.play,
};
/** A tap says why, where there is no hover to say it first. */
export const CameraUnavailableInLowBandwidthModeMobile: Story = {
args: CameraUnavailableInLowBandwidthMode.args,
globals: { viewport: { value: "mobile2", isRotated: false } },
play: async ({ args, canvasElement }) => {
await expectExplainsUnavailable(
within(canvasElement).getByRole("switch", { name: "Start video" }),
lowBandwidthExplanation,
args.toggle!,
{ touch: true },
);
},
};
/** Opens the effects, for the stories that check what they say. */
async function openEffects(canvasElement: HTMLElement): Promise<HTMLElement> {
await userEvent.click(
+14 -4
View File
@@ -5,7 +5,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { type FC, useMemo } from "react";
import { type FC, type Ref, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { MicButton, VideoButton } from "../button";
@@ -18,17 +18,20 @@ interface Props {
vm: MediaMenuViewModel;
kind: "audio" | "video";
size: "md" | "lg";
/** The mute button itself. */
buttonRef?: Ref<HTMLButtonElement>;
}
/**
* The microphone's or the camera's mute button: with a menu to pick the
* device while there are devices to offer, a plain mute button otherwise.
*/
export const MediaMenuButton: FC<Props> = ({ vm, kind, size }) => {
export const MediaMenuButton: FC<Props> = ({ vm, kind, size, buttonRef }) => {
const { t } = useTranslation();
const enabled = useBehavior(vm.enabled$);
const busy = useBehavior(vm.busy$);
const toggle = useBehavior(vm.toggle$);
const unavailableReason = useBehavior(vm.unavailableReason$);
const options = useBehavior(vm.options$);
const selected = useBehavior(vm.selected$);
const select = useBehavior(vm.select$);
@@ -72,15 +75,22 @@ export const MediaMenuButton: FC<Props> = ({ vm, kind, size }) => {
}
}, [refusal, t]);
const unavailable =
unavailableReason === "lowBandwidthMode"
? { description: t("low_bandwidth_mode.camera_unavailable") }
: undefined;
if (options.length === 0) {
const PlainButton = kind === "audio" ? MicButton : VideoButton;
return (
<PlainButton
ref={buttonRef}
size={size}
enabled={enabled}
busy={busy}
onClick={toggle}
disabled={busy || toggle === undefined}
unavailable={unavailable}
data-testid={testId}
/>
);
@@ -88,7 +98,6 @@ export const MediaMenuButton: FC<Props> = ({ vm, kind, size }) => {
return kind === "audio" ? (
<MediaMuteAndSwitchButton
size={size}
iconsAndLabels="audio"
enabled={enabled}
busy={busy}
@@ -103,11 +112,12 @@ export const MediaMenuButton: FC<Props> = ({ vm, kind, size }) => {
/>
) : (
<MediaMuteAndSwitchButton
size={size}
iconsAndLabels="video"
muteButtonRef={buttonRef}
enabled={enabled}
busy={busy}
onMuteClick={toggle}
unavailable={unavailable}
options={options}
selectedOption={selected}
onSelect={select}

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