Compare commits

..
Author SHA1 Message Date
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
64 changed files with 1726 additions and 1522 deletions
@@ -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
+1 -1
View File
@@ -41,7 +41,7 @@
},
"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:01b0026b7f8760c511d15bea7199873d1dd33cbdb43ba4b2e39b74f508583ca4
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:01b0026b7f8760c511d15bea7199873d1dd33cbdb43ba4b2e39b74f508583ca4
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.
+4
View File
@@ -172,6 +172,10 @@
"login_auth_links_prompt": "Not registered yet?",
"login_subheading": "To continue to Element",
"login_title": "Login",
"low_bandwidth_mode": {
"switch_description": "Stop all video for this call, so that audio keeps flowing on a slow network. Lasts until the call ends.",
"switch_label": "Low bandwidth mode"
},
"microphone_level": {
"label": "Microphone level",
"no_device": "No microphone found. Connect one, then try again.",
+2 -3
View File
@@ -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",
@@ -111,7 +110,7 @@
"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",
+106
View File
@@ -0,0 +1,106 @@
/*
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 {
expectInboundVideo,
expectNoInboundVideo,
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("receives no video, and receives it again when turned off", async ({
browser,
}) => {
const { alice, bob } = await twoInACall(browser);
await expectInboundVideo(alice);
await setLowBandwidthMode(alice, true);
// 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);
// Bob's screen share keeps its place on Alice's stage, blank
await bob.getByRole("switch", { name: "Share screen" }).click();
await expect(alice.getByRole("radio", { name: "Spotlight" })).toBeChecked();
await expectNoInboundVideo(alice);
await setLowBandwidthMode(alice, false);
const firstFrameMs = await expectInboundVideo(alice);
test.info().annotations.push({
type: "video back after turning the mode off",
description: `${firstFrameMs} ms`,
});
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();
}
+2 -2
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());
@@ -62,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());
+16 -66
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"],
},
];
@@ -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({ reducedMotion: "reduce" });
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,
@@ -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) {
@@ -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);
+107
View File
@@ -0,0 +1,107 @@
/*
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);
}
/** 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;
}
/**
* Turns Low bandwidth mode on or off from the call's developer options,
* turning developer mode on first if needed.
*/
export async function setLowBandwidthMode(
target: Page | FrameLocator,
on: boolean,
): Promise<void> {
await target
.getByRole("button", { name: "Settings" })
.filter({ visible: true })
.first()
.click();
await target.getByRole("tab", { name: "Preferences" }).click();
await target.getByText("Developer mode", { exact: true }).check();
await target.getByRole("tab", { name: "Developer" }).click();
// 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();
}
+117 -175
View File
@@ -24,12 +24,9 @@ importers:
.:
devDependencies:
'@base-ui/react':
specifier: ^1.9.0
version: 1.9.0(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
'@codecov/vite-plugin':
specifier: ^2.0.0
version: 2.0.1(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
version: 2.0.1(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@fontsource/inconsolata':
specifier: ^5.1.0
version: 5.3.0
@@ -44,7 +41,7 @@ importers:
version: 11.7.12
'@livekit/components-core':
specifier: ^0.12.0
version: 0.12.17(livekit-client@2.23.0(@types/dom-mediacapture-record@1.0.22))(tslib@2.9.1)
version: 0.12.16(livekit-client@2.23.0(@types/dom-mediacapture-record@1.0.22))(tslib@2.9.1)
'@livekit/track-processors':
specifier: ^0.8.0
version: 0.8.3(@types/dom-mediacapture-transform@0.1.11)(livekit-client@2.23.0(@types/dom-mediacapture-record@1.0.22))
@@ -68,7 +65,7 @@ importers:
version: 10.1.2(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
'@rolldown/plugin-babel':
specifier: ^0.3.0
version: 0.3.1(@babel/core@7.29.13(supports-color@7.2.0))(@babel/runtime@8.0.8)(rolldown@1.2.19)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
version: 0.3.1(@babel/core@7.29.13(supports-color@7.2.0))(@babel/runtime@8.0.8)(rolldown@1.2.19)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@sentry/react':
specifier: ^8.0.0
version: 8.55.2(react@19.3.1)
@@ -83,7 +80,7 @@ importers:
version: 10.6.8(@vitest/browser-playwright@4.1.12)(@vitest/browser@4.1.12)(react@19.3.1)(storybook@10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1))(vitest@4.1.12)
'@storybook/react-vite':
specifier: ^10.3.6
version: 10.6.8(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rollup@4.60.1)(storybook@10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1))(supports-color@7.2.0)(typescript@5.9.3)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
version: 10.6.8(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rollup@4.60.1)(storybook@10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1))(supports-color@7.2.0)(typescript@5.9.3)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@testing-library/dom':
specifier: ^10.1.0
version: 10.4.2
@@ -109,8 +106,8 @@ importers:
specifier: ^4.17.12
version: 4.17.12
'@types/node':
specifier: ^26.6.11
version: 26.6.11
specifier: ^24.0.0
version: 24.19.2
'@types/qrcode':
specifier: ^1.5.5
version: 1.5.6
@@ -137,10 +134,10 @@ importers:
version: 10.6.0(@fontsource/inconsolata@5.3.0)(@fontsource/inter@5.3.0)(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(@vector-im/compound-design-tokens@11.3.1(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
'@vitejs/plugin-react':
specifier: ^6.0.2
version: 6.3.0(@rolldown/plugin-babel@0.3.1(@babel/core@7.29.13(supports-color@7.2.0))(@babel/runtime@8.0.8)(rolldown@1.2.19)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)))(babel-plugin-react-compiler@1.0.0)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
version: 6.3.0(@rolldown/plugin-babel@0.3.1(@babel/core@7.29.13(supports-color@7.2.0))(@babel/runtime@8.0.8)(rolldown@1.2.19)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)))(babel-plugin-react-compiler@1.0.0)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@vitest/browser-playwright':
specifier: ^4.1.5
version: 4.1.12(playwright@1.65.1)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)
version: 4.1.12(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)
'@vitest/coverage-v8':
specifier: ^4.0.18
version: 4.1.12(@vitest/browser@4.1.12)(vitest@4.1.12)
@@ -176,13 +173,13 @@ importers:
version: 8.3.1
i18next-cli:
specifier: ^1.61.0
version: 1.91.3(@types/node@26.6.11)(@types/react@19.3.0)(react@19.3.1)(typescript@5.9.3)
version: 1.91.3(@types/node@24.19.2)(@types/react@19.3.0)(react@19.3.1)(typescript@5.9.3)
jsdom:
specifier: ^26.0.0
version: 26.1.0(supports-color@7.2.0)
knip:
specifier: ^5.86.0
version: 5.88.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@26.6.11)(typescript@5.9.3)
version: 5.88.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@24.19.2)(typescript@5.9.3)
livekit-client:
specifier: ^2.18.1
version: 2.23.0(@types/dom-mediacapture-record@1.0.22)
@@ -193,8 +190,8 @@ importers:
specifier: ^1.9.1
version: 1.9.2
matrix-js-sdk:
specifier: github:matrix-org/matrix-js-sdk#aa1a8db0689465a8549546aea4c6cf1e696d6e44
version: https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/aa1a8db0689465a8549546aea4c6cf1e696d6e44
specifier: github:matrix-org/matrix-js-sdk#6c8b1b418189919bc69fd9df5e57354e7b3c39cb
version: https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/6c8b1b418189919bc69fd9df5e57354e7b3c39cb
matrix-widget-api:
specifier: ^1.18.0
version: 1.20.0
@@ -269,25 +266,25 @@ importers:
version: 1.1.2(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
vite:
specifier: ^8.0.0
version: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
version: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite-plugin-html:
specifier: ^3.2.2
version: 3.2.2(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
version: 3.2.2(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
vite-plugin-node-polyfills:
specifier: ^0.28.0
version: 0.28.0(rollup@4.60.1)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
version: 0.28.0(rollup@4.60.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
vite-plugin-node-stdlib-browser:
specifier: ^0.2.1
version: 0.2.1(node-stdlib-browser@1.3.1)(rollup@4.60.1)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
version: 0.2.1(node-stdlib-browser@1.3.1)(rollup@4.60.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
vite-plugin-svgr:
specifier: ^4.0.0
version: 4.5.0(rollup@4.60.1)(supports-color@7.2.0)(typescript@5.9.3)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
version: 4.5.0(rollup@4.60.1)(supports-color@7.2.0)(typescript@5.9.3)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
vite-plugin-wasm:
specifier: ^3.6.0
version: 3.6.0(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
version: 3.6.0(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
vitest:
specifier: ^4.1.5
version: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@26.6.11)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
version: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
vitest-axe:
specifier: ^1.0.0-pre.3
version: 1.0.0-pre.5(vitest@4.1.12)
@@ -435,33 +432,6 @@ packages:
resolution: {integrity: sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==}
engines: {node: '>=6.9.0'}
'@base-ui/react@1.9.0':
resolution: {integrity: sha512-S8CSYosASBKtpL8SWUfS78rFElfLijiCgA7oHOK22jCJ95FULsYyKwBNFOgudt0RA+/7yNc7F81bOvQnRgbBiQ==}
engines: {node: '>=14.0.0'}
peerDependencies:
'@date-fns/tz': ^1.2.0
'@types/react': ^17 || ^18 || ^19
date-fns: ^4.0.0
react: ^17 || ^18 || ^19
react-dom: ^17 || ^18 || ^19
peerDependenciesMeta:
'@date-fns/tz':
optional: true
'@types/react':
optional: true
date-fns:
optional: true
'@base-ui/utils@0.5.0':
resolution: {integrity: sha512-dYGGcEttjkYiMoa5nHm8vLaJ2UcuTWxo3BFAwOYXeRg/q7UVVvA6cacEIXEs3FgBfK1CGtW1ptElqs7wsx+t9A==}
peerDependencies:
'@types/react': ^17 || ^18 || ^19
react: ^17 || ^18 || ^19
react-dom: ^17 || ^18 || ^19
peerDependenciesMeta:
'@types/react':
optional: true
'@bcoe/v8-coverage@1.0.2':
resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==}
engines: {node: '>=18'}
@@ -1171,8 +1141,8 @@ packages:
'@jridgewell/trace-mapping@0.3.31':
resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
'@livekit/components-core@0.12.17':
resolution: {integrity: sha512-DhpVOojgl9eC+jVnnuPGGq/ijlqi5XgpZqCj/G+ijujc44UyZEprSUStjDG0ai6ymBlJics3XKLDLLtihCxssg==}
'@livekit/components-core@0.12.16':
resolution: {integrity: sha512-jcXuNeHKGkXgRiT4wniWRpg+TKUSoTL9da01tMxxKGmjp98zB2DVgPmk1fBZfgDVjPBF+jsZe/WkeFAbvJu4Gw==}
engines: {node: '>=18'}
peerDependencies:
livekit-client: ^2.20.1
@@ -1190,8 +1160,8 @@ packages:
'@types/dom-mediacapture-transform': ^0.1.9
livekit-client: ^1.12.0 || ^2.1.0
'@matrix-org/matrix-sdk-crypto-wasm@19.0.1':
resolution: {integrity: sha512-8KtzFk8xGxUGVVCAK4FWB1poOQoKLzy2Z98iudD7cbaciZ6UIkxivYgMA4/f2z3L0nVSAPiWaBp4mwWv2BBocQ==}
'@matrix-org/matrix-sdk-crypto-wasm@18.9.2':
resolution: {integrity: sha512-GHeuSeb5Fj6Wg2+NE/WoLJJs9U3nOzttO+2sj7lOaS5gNBpGIksc48N/Q/kK/Z+Lxh7YMhopB7M8b6HyASXnGQ==}
engines: {node: '>= 18'}
'@mdx-js/react@3.1.1':
@@ -3141,8 +3111,8 @@ packages:
'@types/mdx@2.0.14':
resolution: {integrity: sha512-T48PeuJtvLosNTPVhfnIp3i/n3a4g4Bad7YCq5k64D4u7NwDrAotikQ+5+sjtUvBmxCMlbo3dVL+C2dP0rWHzg==}
'@types/node@26.6.11':
resolution: {integrity: sha512-uUyQ2XLEz+EXh34lmS3GhKrkqn/8FU7KUiKRpk347At2bmnMVWss45yz8b4FG/tUtmV1tV/+TVkITItPROyeeQ==}
'@types/node@24.19.2':
resolution: {integrity: sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==}
'@types/qrcode@1.5.6':
resolution: {integrity: sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw==}
@@ -4645,9 +4615,9 @@ packages:
matrix-events-sdk@0.0.1:
resolution: {integrity: sha512-1QEOsXO+bhyCroIe2/A5OwaxHvBm7EsSQ46DEDn8RBIfQwN5HWBpFvyWWR4QY0KHPPnnJdI99wgRiAl7Ad5qaA==}
matrix-js-sdk@https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/aa1a8db0689465a8549546aea4c6cf1e696d6e44:
resolution: {gitHosted: true, integrity: sha512-+KmFg7V9NwrP+fnmbJDVr/iCbulKipj71d4upw2IPH0F/sGWu0ovggBeidn2UHkGq6ziWnAymCgxbBiCWVo+Jw==, tarball: https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/aa1a8db0689465a8549546aea4c6cf1e696d6e44}
version: 45.2.0
matrix-js-sdk@https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/6c8b1b418189919bc69fd9df5e57354e7b3c39cb:
resolution: {gitHosted: true, integrity: sha512-wKP5LDUeHlussA80SizNnzqU2ZspXJlq6TmDbDEUJPcjF9MbydYXqMy5LsquK8XtuNJTKyvGRxkL6GEEYmo+qQ==, tarball: https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/6c8b1b418189919bc69fd9df5e57354e7b3c39cb}
version: 45.1.0
engines: {node: '>=22.0.0'}
matrix-widget-api@1.20.0:
@@ -5349,9 +5319,6 @@ packages:
require-main-filename@2.0.0:
resolution: {integrity: sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==}
reselect@5.3.0:
resolution: {integrity: sha512-XGoLeRAVzUTcJ1qkxPQhDJyIZ5d6zzZD9nT7AEZOaaU9UbWclhycElmhO+VD5bFeLuzhPBaOV2oXC8uG35ZSpg==}
resolve-from@4.0.0:
resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==}
engines: {node: '>=4'}
@@ -5739,8 +5706,8 @@ packages:
resolution: {integrity: sha512-X2wH19RAPZE3+ldGicOkoj/SIA83OIxcJ6Cuaw23hf8Xc6fQpvZXY0SftE2JgS0QhYLUG4uwodSI3R53keyh7w==}
engines: {node: '>=14'}
undici-types@8.9.0:
resolution: {integrity: sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==}
undici-types@7.24.6:
resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==}
undici@6.29.1:
resolution: {integrity: sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA==}
@@ -6326,29 +6293,6 @@ snapshots:
'@babel/helper-string-parser': 7.29.7
'@babel/helper-validator-identifier': 7.29.7
'@base-ui/react@1.9.0(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)':
dependencies:
'@babel/runtime': 8.0.8
'@base-ui/utils': 0.5.0(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
'@floating-ui/react-dom': 2.1.9(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
'@floating-ui/utils': 0.2.12
react: 19.3.1
react-dom: 19.3.1(react@19.3.1)
use-sync-external-store: 1.7.0(react@19.3.1)
optionalDependencies:
'@types/react': 19.3.0
'@base-ui/utils@0.5.0(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)':
dependencies:
'@babel/runtime': 8.0.8
'@floating-ui/utils': 0.2.12
react: 19.3.1
react-dom: 19.3.1(react@19.3.1)
reselect: 5.3.0
use-sync-external-store: 1.7.0(react@19.3.1)
optionalDependencies:
'@types/react': 19.3.0
'@bcoe/v8-coverage@1.0.2': {}
'@blazediff/core@1.9.1': {}
@@ -6364,11 +6308,11 @@ snapshots:
unplugin: 1.16.1
zod: 3.25.76
'@codecov/vite-plugin@2.0.1(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
'@codecov/vite-plugin@2.0.1(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
dependencies:
'@codecov/bundler-plugin-core': 2.0.1
unplugin: 1.16.1
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
'@croct/json5-parser@0.2.2':
dependencies:
@@ -6928,59 +6872,59 @@ snapshots:
'@inquirer/ansi@2.1.1': {}
'@inquirer/confirm@6.4.0(@types/node@26.6.11)':
'@inquirer/confirm@6.4.0(@types/node@24.19.2)':
dependencies:
'@inquirer/core': 12.1.1(@types/node@26.6.11)
'@inquirer/type': 4.3.0(@types/node@26.6.11)
'@inquirer/core': 12.1.1(@types/node@24.19.2)
'@inquirer/type': 4.3.0(@types/node@24.19.2)
optionalDependencies:
'@types/node': 26.6.11
'@types/node': 24.19.2
'@inquirer/core@12.1.1(@types/node@26.6.11)':
'@inquirer/core@12.1.1(@types/node@24.19.2)':
dependencies:
'@inquirer/ansi': 2.1.1
'@inquirer/figures': 2.1.1
'@inquirer/type': 4.3.1(@types/node@26.6.11)
'@inquirer/type': 4.3.1(@types/node@24.19.2)
cli-width: 4.1.0
fast-string-width: 3.0.2
fast-wrap-ansi: 0.2.2
mute-stream: 3.0.0
signal-exit: 4.1.0
optionalDependencies:
'@types/node': 26.6.11
'@types/node': 24.19.2
'@inquirer/figures@2.1.1': {}
'@inquirer/input@5.2.0(@types/node@26.6.11)':
'@inquirer/input@5.2.0(@types/node@24.19.2)':
dependencies:
'@inquirer/core': 12.1.1(@types/node@26.6.11)
'@inquirer/type': 4.3.0(@types/node@26.6.11)
'@inquirer/core': 12.1.1(@types/node@24.19.2)
'@inquirer/type': 4.3.0(@types/node@24.19.2)
optionalDependencies:
'@types/node': 26.6.11
'@types/node': 24.19.2
'@inquirer/password@5.3.0(@types/node@26.6.11)':
'@inquirer/password@5.3.0(@types/node@24.19.2)':
dependencies:
'@inquirer/ansi': 2.1.1
'@inquirer/core': 12.1.1(@types/node@26.6.11)
'@inquirer/type': 4.3.0(@types/node@26.6.11)
'@inquirer/core': 12.1.1(@types/node@24.19.2)
'@inquirer/type': 4.3.0(@types/node@24.19.2)
optionalDependencies:
'@types/node': 26.6.11
'@types/node': 24.19.2
'@inquirer/select@5.3.0(@types/node@26.6.11)':
'@inquirer/select@5.3.0(@types/node@24.19.2)':
dependencies:
'@inquirer/ansi': 2.1.1
'@inquirer/core': 12.1.1(@types/node@26.6.11)
'@inquirer/core': 12.1.1(@types/node@24.19.2)
'@inquirer/figures': 2.1.1
'@inquirer/type': 4.3.0(@types/node@26.6.11)
'@inquirer/type': 4.3.0(@types/node@24.19.2)
optionalDependencies:
'@types/node': 26.6.11
'@types/node': 24.19.2
'@inquirer/type@4.3.0(@types/node@26.6.11)':
'@inquirer/type@4.3.0(@types/node@24.19.2)':
optionalDependencies:
'@types/node': 26.6.11
'@types/node': 24.19.2
'@inquirer/type@4.3.1(@types/node@26.6.11)':
'@inquirer/type@4.3.1(@types/node@24.19.2)':
optionalDependencies:
'@types/node': 26.6.11
'@types/node': 24.19.2
'@isaacs/cliui@8.0.2':
dependencies:
@@ -6993,11 +6937,11 @@ snapshots:
'@isaacs/nonrecursive-glob-match@1.1.0': {}
'@joshwooding/vite-plugin-react-docgen-typescript@0.7.0(typescript@5.9.3)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
'@joshwooding/vite-plugin-react-docgen-typescript@0.7.0(typescript@5.9.3)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
dependencies:
glob: 10.5.0
react-docgen-typescript: 2.4.0(typescript@5.9.3)
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
optionalDependencies:
typescript: 5.9.3
@@ -7025,7 +6969,7 @@ snapshots:
'@jridgewell/resolve-uri': 3.1.2
'@jridgewell/sourcemap-codec': 1.6.0
'@livekit/components-core@0.12.17(livekit-client@2.23.0(@types/dom-mediacapture-record@1.0.22))(tslib@2.9.1)':
'@livekit/components-core@0.12.16(livekit-client@2.23.0(@types/dom-mediacapture-record@1.0.22))(tslib@2.9.1)':
dependencies:
'@floating-ui/dom': 1.8.0
livekit-client: 2.23.0(@types/dom-mediacapture-record@1.0.22)
@@ -7045,7 +6989,7 @@ snapshots:
'@types/dom-mediacapture-transform': 0.1.11
livekit-client: 2.23.0(@types/dom-mediacapture-record@1.0.22)
'@matrix-org/matrix-sdk-crypto-wasm@19.0.1': {}
'@matrix-org/matrix-sdk-crypto-wasm@18.9.2': {}
'@mdx-js/react@3.1.1(@types/react@19.3.0)(react@19.3.1)':
dependencies:
@@ -7994,7 +7938,7 @@ snapshots:
'@rolldown/binding-win32-x64-msvc@1.2.19':
optional: true
'@rolldown/plugin-babel@0.3.1(@babel/core@7.29.13(supports-color@7.2.0))(@babel/runtime@8.0.8)(rolldown@1.2.19)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
'@rolldown/plugin-babel@0.3.1(@babel/core@7.29.13(supports-color@7.2.0))(@babel/runtime@8.0.8)(rolldown@1.2.19)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
dependencies:
'@babel/core': 7.29.13(supports-color@7.2.0)
artichokie: 0.4.5
@@ -8002,7 +7946,7 @@ snapshots:
rolldown: 1.2.19
optionalDependencies:
'@babel/runtime': 8.0.8
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
'@rolldown/pluginutils@1.1.1': {}
@@ -8236,17 +8180,17 @@ snapshots:
'@storybook/icons': 2.2.0(react@19.3.1)
storybook: 10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1)
optionalDependencies:
'@vitest/browser': 4.1.12(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)
'@vitest/browser-playwright': 4.1.12(playwright@1.65.1)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)
vitest: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@26.6.11)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@vitest/browser': 4.1.12(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)
'@vitest/browser-playwright': 4.1.12(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)
vitest: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
transitivePeerDependencies:
- react
'@storybook/builder-vite@10.6.8(storybook@10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1))(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
'@storybook/builder-vite@10.6.8(storybook@10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
dependencies:
storybook: 10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1)
ts-dedent: 2.3.0
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
'@storybook/global@5.0.0': {}
@@ -8263,11 +8207,11 @@ snapshots:
'@types/react': 19.3.0
'@types/react-dom': 19.3.0(@types/react@19.3.0)
'@storybook/react-vite@10.6.8(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rollup@4.60.1)(storybook@10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1))(supports-color@7.2.0)(typescript@5.9.3)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
'@storybook/react-vite@10.6.8(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rollup@4.60.1)(storybook@10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1))(supports-color@7.2.0)(typescript@5.9.3)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
dependencies:
'@joshwooding/vite-plugin-react-docgen-typescript': 0.7.0(typescript@5.9.3)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@joshwooding/vite-plugin-react-docgen-typescript': 0.7.0(typescript@5.9.3)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@rollup/pluginutils': 5.5.1(rollup@4.60.1)
'@storybook/builder-vite': 10.6.8(storybook@10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1))(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@storybook/builder-vite': 10.6.8(storybook@10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@storybook/react': 10.6.8(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(storybook@10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1))(supports-color@7.2.0)(typescript@5.9.3)
empathic: 2.1.0
magic-string: 1.4.5
@@ -8277,7 +8221,7 @@ snapshots:
resolve: 1.22.14
storybook: 10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1)
tsconfig-paths: 4.2.0
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
optionalDependencies:
typescript: 5.9.3
transitivePeerDependencies:
@@ -8535,7 +8479,7 @@ snapshots:
'@types/jsdom@21.1.7':
dependencies:
'@types/node': 26.6.11
'@types/node': 24.19.2
'@types/tough-cookie': 4.0.5
parse5: 7.3.0
@@ -8549,13 +8493,13 @@ snapshots:
'@types/mdx@2.0.14': {}
'@types/node@26.6.11':
'@types/node@24.19.2':
dependencies:
undici-types: 8.9.0
undici-types: 7.24.6
'@types/qrcode@1.5.6':
dependencies:
'@types/node': 26.6.11
'@types/node': 24.19.2
'@types/react-dom@19.3.0(@types/react@19.3.0)':
dependencies:
@@ -8714,37 +8658,37 @@ snapshots:
- '@types/react-dom'
- react-dom
'@vitejs/plugin-react@6.3.0(@rolldown/plugin-babel@0.3.1(@babel/core@7.29.13(supports-color@7.2.0))(@babel/runtime@8.0.8)(rolldown@1.2.19)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)))(babel-plugin-react-compiler@1.0.0)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
'@vitejs/plugin-react@6.3.0(@rolldown/plugin-babel@0.3.1(@babel/core@7.29.13(supports-color@7.2.0))(@babel/runtime@8.0.8)(rolldown@1.2.19)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)))(babel-plugin-react-compiler@1.0.0)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
dependencies:
'@rolldown/pluginutils': 1.1.1
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
optionalDependencies:
'@rolldown/plugin-babel': 0.3.1(@babel/core@7.29.13(supports-color@7.2.0))(@babel/runtime@8.0.8)(rolldown@1.2.19)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@rolldown/plugin-babel': 0.3.1(@babel/core@7.29.13(supports-color@7.2.0))(@babel/runtime@8.0.8)(rolldown@1.2.19)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
babel-plugin-react-compiler: 1.0.0
'@vitest/browser-playwright@4.1.12(playwright@1.65.1)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)':
'@vitest/browser-playwright@4.1.12(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)':
dependencies:
'@vitest/browser': 4.1.12(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)
'@vitest/mocker': 4.1.12(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@vitest/browser': 4.1.12(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)
'@vitest/mocker': 4.1.12(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
playwright: 1.65.1
tinyrainbow: 3.2.0
vitest: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@26.6.11)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
vitest: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
transitivePeerDependencies:
- bufferutil
- msw
- utf-8-validate
- vite
'@vitest/browser@4.1.12(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)':
'@vitest/browser@4.1.12(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)':
dependencies:
'@blazediff/core': 1.9.1
'@vitest/mocker': 4.1.12(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@vitest/mocker': 4.1.12(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@vitest/utils': 4.1.12
magic-string: 0.30.21
pngjs: 7.0.0
sirv: 3.0.2
tinyrainbow: 3.2.0
vitest: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@26.6.11)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
vitest: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
ws: 8.23.0
transitivePeerDependencies:
- bufferutil
@@ -8764,9 +8708,9 @@ snapshots:
obug: 2.2.1
std-env: 4.3.0
tinyrainbow: 3.2.0
vitest: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@26.6.11)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
vitest: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
optionalDependencies:
'@vitest/browser': 4.1.12(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)
'@vitest/browser': 4.1.12(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)
'@vitest/expect@3.2.4':
dependencies:
@@ -8785,13 +8729,13 @@ snapshots:
chai: 6.3.0
tinyrainbow: 3.2.0
'@vitest/mocker@4.1.12(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
'@vitest/mocker@4.1.12(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
dependencies:
'@vitest/spy': 4.1.12
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
'@vitest/pretty-format@3.2.4':
dependencies:
@@ -8828,7 +8772,7 @@ snapshots:
sirv: 3.0.2
tinyglobby: 0.2.17
tinyrainbow: 3.1.1
vitest: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@26.6.11)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
vitest: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@vitest/utils@3.2.4':
dependencies:
@@ -9803,14 +9747,14 @@ snapshots:
dependencies:
'@babel/runtime': 7.29.15
i18next-cli@1.91.3(@types/node@26.6.11)(@types/react@19.3.0)(react@19.3.1)(typescript@5.9.3):
i18next-cli@1.91.3(@types/node@24.19.2)(@types/react@19.3.0)(react@19.3.1)(typescript@5.9.3):
dependencies:
'@croct/json5-parser': 0.2.2
'@formatjs/icu-messageformat-parser': 3.5.23
'@inquirer/confirm': 6.4.0(@types/node@26.6.11)
'@inquirer/input': 5.2.0(@types/node@26.6.11)
'@inquirer/password': 5.3.0(@types/node@26.6.11)
'@inquirer/select': 5.3.0(@types/node@26.6.11)
'@inquirer/confirm': 6.4.0(@types/node@24.19.2)
'@inquirer/input': 5.2.0(@types/node@24.19.2)
'@inquirer/password': 5.3.0(@types/node@24.19.2)
'@inquirer/select': 5.3.0(@types/node@24.19.2)
'@swc/core': 1.16.22
chokidar: 5.0.0
commander: 15.1.0
@@ -10041,10 +9985,10 @@ snapshots:
dependencies:
json-buffer: 3.0.1
knip@5.88.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@26.6.11)(typescript@5.9.3):
knip@5.88.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@24.19.2)(typescript@5.9.3):
dependencies:
'@nodelib/fs.walk': 1.2.8
'@types/node': 26.6.11
'@types/node': 24.19.2
fast-glob: 3.3.3
formatly: 0.3.0
jiti: 2.6.1
@@ -10188,10 +10132,10 @@ snapshots:
matrix-events-sdk@0.0.1: {}
matrix-js-sdk@https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/aa1a8db0689465a8549546aea4c6cf1e696d6e44:
matrix-js-sdk@https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/6c8b1b418189919bc69fd9df5e57354e7b3c39cb:
dependencies:
'@babel/runtime': 8.0.8
'@matrix-org/matrix-sdk-crypto-wasm': 19.0.1
'@matrix-org/matrix-sdk-crypto-wasm': 18.9.2
another-json: 0.2.0
bs58: 6.0.0
content-type: 3.1.1
@@ -11044,8 +10988,6 @@ snapshots:
require-main-filename@2.0.0: {}
reselect@5.3.0: {}
resolve-from@4.0.0: {}
resolve@1.22.13:
@@ -11457,7 +11399,7 @@ snapshots:
unbash@2.2.0: {}
undici-types@8.9.0: {}
undici-types@7.24.6: {}
undici@6.29.1: {}
@@ -11547,7 +11489,7 @@ snapshots:
- '@types/react'
- '@types/react-dom'
vite-plugin-html@3.2.2(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)):
vite-plugin-html@3.2.2(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)):
dependencies:
'@rollup/pluginutils': 4.2.1
colorette: 2.0.20
@@ -11561,40 +11503,40 @@ snapshots:
html-minifier-terser: 6.1.0
node-html-parser: 5.4.2
pathe: 0.2.0
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite-plugin-node-polyfills@0.28.0(rollup@4.60.1)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)):
vite-plugin-node-polyfills@0.28.0(rollup@4.60.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)):
dependencies:
'@rollup/plugin-inject': 5.0.5(rollup@4.60.1)
node-stdlib-browser: 1.3.1
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
transitivePeerDependencies:
- rollup
vite-plugin-node-stdlib-browser@0.2.1(node-stdlib-browser@1.3.1)(rollup@4.60.1)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)):
vite-plugin-node-stdlib-browser@0.2.1(node-stdlib-browser@1.3.1)(rollup@4.60.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)):
dependencies:
'@rollup/plugin-inject': 5.0.5(rollup@4.60.1)
node-stdlib-browser: 1.3.1
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
transitivePeerDependencies:
- rollup
vite-plugin-svgr@4.5.0(rollup@4.60.1)(supports-color@7.2.0)(typescript@5.9.3)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)):
vite-plugin-svgr@4.5.0(rollup@4.60.1)(supports-color@7.2.0)(typescript@5.9.3)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)):
dependencies:
'@rollup/pluginutils': 5.3.0(rollup@4.60.1)
'@svgr/core': 8.1.0(supports-color@7.2.0)(typescript@5.9.3)
'@svgr/plugin-jsx': 8.1.0(@svgr/core@8.1.0(supports-color@7.2.0)(typescript@5.9.3))(supports-color@7.2.0)
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
transitivePeerDependencies:
- rollup
- supports-color
- typescript
vite-plugin-wasm@3.6.0(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)):
vite-plugin-wasm@3.6.0(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)):
dependencies:
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1):
vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1):
dependencies:
lightningcss: 1.33.0
picomatch: 4.0.7
@@ -11602,7 +11544,7 @@ snapshots:
rolldown: 1.2.19
tinyglobby: 0.2.17
optionalDependencies:
'@types/node': 26.6.11
'@types/node': 24.19.2
esbuild: 0.28.2
fsevents: 2.3.3
jiti: 2.7.0
@@ -11616,12 +11558,12 @@ snapshots:
axe-core: 4.11.3
chalk: 5.6.2
lodash-es: 4.18.1
vitest: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@26.6.11)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
vitest: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
vitest@4.1.12(@opentelemetry/api@1.9.1)(@types/node@26.6.11)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)):
vitest@4.1.12(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)):
dependencies:
'@vitest/expect': 4.1.12
'@vitest/mocker': 4.1.12(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@vitest/mocker': 4.1.12(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@vitest/pretty-format': 4.1.12
'@vitest/runner': 4.1.12
'@vitest/snapshot': 4.1.12
@@ -11638,12 +11580,12 @@ snapshots:
tinyexec: 1.3.1
tinyglobby: 0.2.17
tinyrainbow: 3.2.0
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
why-is-node-running: 2.3.0
optionalDependencies:
'@opentelemetry/api': 1.9.1
'@types/node': 26.6.11
'@vitest/browser-playwright': 4.1.12(playwright@1.65.1)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)
'@types/node': 24.19.2
'@vitest/browser-playwright': 4.1.12(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)
'@vitest/coverage-v8': 4.1.12(@vitest/browser@4.1.12)(vitest@4.1.12)
'@vitest/ui': 4.1.12(vitest@4.1.12)
jsdom: 26.1.0(supports-color@7.2.0)
+33 -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,13 @@ export interface MatrixRTCClient {
*/
setAudioOutputDeviceId(deviceId: string): Promise<void>;
/**
* Whether remote video is received. While false no remote video track is
* subscribed on any 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 +597,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,
};
+12
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,13 @@ export interface RTCParticipation {
*/
setAudioOutputDeviceId(deviceId: string): Promise<void>;
/**
* Whether remote video is received. While false no remote video track is
* subscribed on any 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;
+7
View File
@@ -159,6 +159,13 @@ export interface MediaBackend {
*/
setAudioOutputDeviceId(deviceId: string): Promise<void>;
/**
* Whether remote video is subscribed. 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.
+173 -65
View File
@@ -28,6 +28,7 @@ import {
} 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 +43,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 +53,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 +65,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 +81,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 +376,6 @@ describe("Start connection states", () => {
...connectionOpts(),
role: "publisher",
transport: { type: "livekit", livekit_service_url: serviceUrl },
flow: { kind: "openID", serviceUrl },
},
logger,
);
@@ -388,65 +387,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 +621,169 @@ 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("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: false,
screenShareAudio: true,
};
const VIDEO_ON = {
microphone: true,
camera: true,
screenShare: true,
screenShareAudio: true,
};
type MockPublication = RemoteTrackPublication & {
setSubscribed: ReturnType<typeof vi.fn>;
};
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, subscribed),
camera: mockPublication(Track.Kind.Video, subscribed),
screenShare: mockPublication(Track.Kind.Video, subscribed),
screenShareAudio: mockPublication(Track.Kind.Audio, 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,
subscribed: boolean | undefined,
): MockPublication {
const publication = {
kind,
subscribed,
get isDesired(): boolean {
return this.subscribed !== false;
},
setSubscribed: vi.fn((value: boolean) => {
publication.subscribed = 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();
+67 -45
View File
@@ -19,20 +19,20 @@ import {
type RemoteParticipant,
type RemoteTrackPublication,
type Room as LivekitRoom,
type RoomConnectOptions,
RoomEvent,
type SubscriptionError,
type Track,
Track,
type TrackPublication,
} 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 +43,6 @@ import {
MatrixRTCError,
InsufficientCapacityError,
LivekitConnectionError,
NoMatrix2AuthorizationService,
PeerConnectionTimeoutError,
SFURoomCreationRestrictedError,
UnknownRTCError,
@@ -60,19 +59,17 @@ 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 video is subscribed. Read at connect and followed for the
* connection's lifetime; audio is always subscribed.
*/
receiveVideo$: Behavior<boolean>;
/** Optional factory to create the LiveKit room, mainly for testing purposes. */
livekitRoomFactory: () => LivekitRoom;
@@ -115,9 +112,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 +140,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 +168,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 +183,45 @@ export class Connection {
});
}
/**
* Keeps every remote publication subscribed or not as `receiveVideo$` asks.
* 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 wanted =
publication.kind !== Track.Kind.Video || this.receiveVideo$.value;
// Every call sends a subscription update, wanted or not
if (publication.isDesired !== wanted) publication.setSubscribed(wanted);
};
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 +433,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 +444,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 video is not received never asks the SFU for it. */
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 };
}
+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>
);
};
-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>
`;
@@ -537,9 +537,7 @@ export const RemovingWithLiveSelection: Story = {
const cross = tile.parentElement!.querySelector<HTMLElement>(
"[aria-hidden]:last-child",
)!;
// The menu slides in over 180ms from transparent. On a fast machine the
// hover lands before its first frame, so wait it out.
await waitFor(async () => expect(cross).toBeVisible());
await expect(cross).toBeVisible();
await userEvent.click(cross);
await waitFor(async () =>
@@ -909,10 +907,7 @@ export const SelectionSettling: Story = {
await menu.findByRole("menuitemradio", { name: "Microphone 2" }),
);
// The menu slides in over 180ms from transparent. On a fast machine the
// hover lands before its first frame, so wait it out.
const spinner = await menu.findByLabelText("Activating…");
await waitFor(async () => expect(spinner).toBeVisible());
await expect(await menu.findByLabelText("Activating…")).toBeVisible();
for (const item of menu.getAllByRole("menuitemradio"))
await expect(item).toHaveAttribute("aria-disabled", "true");
},
+14 -24
View File
@@ -25,25 +25,19 @@ describe("useGroupCallRooms", () => {
expect(listedRoomIds([room])).toEqual([room.roomId]);
});
test.each([EventType.RTCMembershipStable, EventType.RTCMembership])(
"lists a joined room with a sticky %s membership",
(type) => {
const room = mockCallRoom({
stickyEvents: [new MatrixEvent({ type })],
});
expect(listedRoomIds([room])).toEqual([room.roomId]);
},
);
test("lists a joined room with a sticky RTC membership", () => {
const room = mockCallRoom({
stickyEvents: [new MatrixEvent({ type: EventType.RTCMembership })],
});
expect(listedRoomIds([room])).toEqual([room.roomId]);
});
test.each([EventType.RTCMembershipStable, EventType.RTCMembership])(
"lists a joined room with a %s membership in its timeline",
(type) => {
const room = mockCallRoom({
timelineEvents: [new MatrixEvent({ type })],
});
expect(listedRoomIds([room])).toEqual([room.roomId]);
},
);
test("lists a joined room with an RTC membership in its timeline", () => {
const room = mockCallRoom({
timelineEvents: [new MatrixEvent({ type: EventType.RTCMembership })],
});
expect(listedRoomIds([room])).toEqual([room.roomId]);
});
test("lists a knocked room without any call events", () => {
const room = mockCallRoom({
@@ -67,12 +61,8 @@ describe("useGroupCallRooms", () => {
const room = mockCallRoom({
membership,
legacyMemberState: true,
stickyEvents: [
new MatrixEvent({ type: EventType.RTCMembershipStable }),
],
timelineEvents: [
new MatrixEvent({ type: EventType.RTCMembershipStable }),
],
stickyEvents: [new MatrixEvent({ type: EventType.RTCMembership })],
timelineEvents: [new MatrixEvent({ type: EventType.RTCMembership })],
});
expect(listedRoomIds([room])).toEqual([]);
},
+4 -11
View File
@@ -7,7 +7,6 @@ Please see LICENSE in the repository root for full details.
import {
type MatrixClient,
type MatrixEvent,
type RoomMember,
type Room,
RoomEvent,
@@ -144,25 +143,19 @@ const roomHasCallMembershipEvents = (room: Room): boolean => {
// Check for recent calls using sticky events.
for (const sticky of room._unstable_getStickyEvents()) {
if (isRtcMembershipEvent(sticky)) {
if (sticky.getType() === EventType.RTCMembership) {
return true;
}
}
// Otherwise, check recent event history to see if anyone had
// sent a call membership in here.
return timeline.getEvents().some(isRtcMembershipEvent);
return timeline
.getEvents()
.some((e) => e.getType() === EventType.RTCMembership);
// Otherwise, it's *unlikely* this room was ever a call.
};
// Memberships sent before the event type was stabilised still mark a call room.
function isRtcMembershipEvent(event: MatrixEvent): boolean {
const type = event.getType();
return (
type === EventType.RTCMembershipStable || type === EventType.RTCMembership
);
}
export function useGroupCallRooms(client: MatrixClient): GroupCallRoom[] {
const [rooms, setRooms] = useState<GroupCallRoom[]>([]);
+15 -1
View File
@@ -73,6 +73,10 @@ import { useMuteStates } from "../state/useMuteStates.ts";
import { useLeaveToHome } from "../LeaveToHomeContext.ts";
import { useLocalMedia } from "../useLocalMedia.ts";
import { ObservableScope } from "../state/ObservableScope.ts";
import {
createLowBandwidthMode,
type LowBandwidthMode,
} from "../state/LowBandwidthMode.ts";
import { type CallNotificationWrapper } from "../state/CallViewModel/CallNotificationLifecycle.ts";
import { type CallMatrixBackend } from "../CallMatrixBackend.ts";
@@ -146,6 +150,9 @@ export const CallView: FC<Props> = ({
// rebuilt.
const [joined, setJoined] = useState(false);
const muteStates = useMuteStates();
// Held here too, so that it survives the call failing and being
// reconnected. The lobby starts every new call with it off
const [lowBandwidthMode] = useState(createLowBandwidthMode);
const e2eeSystem = useRoomEncryptionSystem(backend.roomId);
// One slot for every join of this call: leaving and joining again, to
@@ -180,6 +187,7 @@ export const CallView: FC<Props> = ({
joined={joined}
setJoined={setJoined}
muteStates={muteStates}
lowBandwidthMode={lowBandwidthMode}
/>
);
};
@@ -249,6 +257,7 @@ interface LoadedProps extends Omit<Props, "rtcSession" | "backend"> {
joined: boolean;
setJoined: (value: boolean) => void;
muteStates: MuteStates;
lowBandwidthMode: LowBandwidthMode;
}
/**
@@ -281,6 +290,7 @@ const LoadedCallView: FC<LoadedProps> = ({
joined,
setJoined,
muteStates,
lowBandwidthMode,
}) => {
// Used to thread through any errors that occur outside the error boundary
const [externalError, setExternalError] = useState<ElementCallError | null>(
@@ -587,7 +597,10 @@ const LoadedCallView: FC<LoadedProps> = ({
matrixInfo={matrixInfo}
media={media}
muteStates={muteStates}
onEnter={() => setJoined(true)}
onEnter={() => {
lowBandwidthMode.reset();
setJoined(true);
}}
confineToRoom={confineToRoom}
hideHeader={header !== HeaderStyle.Standard}
participantCount={participantCount}
@@ -618,6 +631,7 @@ const LoadedCallView: FC<LoadedProps> = ({
onLeft={onLeft}
media={media}
muteStates={muteStates}
lowBandwidthMode={lowBandwidthMode}
e2eeSystem={e2eeSystem}
//otelGroupCallMembership={otelGroupCallMembership}
onShareClick={onShareClick}
+3
View File
@@ -21,6 +21,7 @@ import { TooltipProvider } from "@vector-im/compound-web";
import userEvent from "@testing-library/user-event";
import { ActiveCall, InCallView } from "./InCallView";
import { createLowBandwidthMode } from "../state/LowBandwidthMode";
import {
mockMediaDevices,
mockMuteStates,
@@ -242,6 +243,7 @@ function renderActiveCall(slot: RTCSlot): RenderResult {
sentCallNotification$={NEVER}
matrixRoom={matrixRoom}
muteStates={mockMuteStates()}
lowBandwidthMode={createLowBandwidthMode()}
matrixInfo={matrixInfo}
onShareClick={null}
e2eeSystem={{ kind: E2eeType.NONE }}
@@ -311,6 +313,7 @@ describe("ActiveCall", () => {
sentCallNotification$={NEVER}
matrixRoom={matrixRoom}
muteStates={mockMuteStates()}
lowBandwidthMode={createLowBandwidthMode()}
matrixInfo={matrixInfo}
onShareClick={null}
e2eeSystem={{ kind: E2eeType.NONE }}
+9 -1
View File
@@ -41,6 +41,7 @@ import { RageshakeRequestModal } from "./RageshakeRequestModal";
import { useWakeLock } from "../useWakeLock";
import { useMergedRefs } from "../useMergedRefs";
import { type MuteStates } from "../state/MuteStates";
import { type LowBandwidthMode } from "../state/LowBandwidthMode";
import { type MatrixInfo } from "./VideoPreview";
import { InviteButton } from "../button/InviteButton";
import {
@@ -194,6 +195,7 @@ export interface ActiveCallProps extends Omit<
e2eeSystem: EncryptionSystem;
/** The tracks the lobby opened, for the join to publish. */
media: LocalMedia;
lowBandwidthMode: LowBandwidthMode;
// TODO refactor those reasons into an enum
onLeft: (
reason: "user" | "timeout" | "decline" | "allOthersLeft" | "error",
@@ -230,6 +232,7 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
const capture = captureSettings();
const rtcParticipation = props.slot.join({
...rtcParticipationOptions(urlParams),
receiveVideo: !props.lowBandwidthMode.enabled$.value,
// Without a lobby nothing was captured and the join captures itself
publish:
props.media.requests.length > 0
@@ -250,6 +253,7 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
client: props.client,
mediaDevices,
muteStates: props.muteStates,
lowBandwidthMode: props.lowBandwidthMode,
encryptionSystem: props.e2eeSystem,
viewSize$: scope.behavior(observeElementSize$(rootElement)),
handsRaisedSubject$: reactionsReader.raisedHands$,
@@ -282,6 +286,7 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
props.sentCallNotification$,
props.matrixRoom,
props.muteStates,
props.lowBandwidthMode,
props.e2eeSystem,
props.onLeft,
urlParams,
@@ -307,7 +312,9 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
{ showControls: urlParams.showControls, header: urlParams.header },
);
setFooterVm(footerVm);
setDeveloperSettingsVm(createDeveloperSettingsTabViewModel(scope, vm));
setDeveloperSettingsVm(
createDeveloperSettingsTabViewModel(scope, vm, props.lowBandwidthMode),
);
return (): void => {
scope.end();
@@ -315,6 +322,7 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
}, [
props.matrixRoom,
props.muteStates,
props.lowBandwidthMode,
props.e2eeSystem,
props.onLeft,
urlParams,
@@ -429,6 +429,7 @@ describe("DeveloperSettingsTab", () => {
const client = createMockMatrixClient();
const vm = createStaticViewModel<DeveloperSettingsSnapshot>({
keyRotation: { suppressed: false, participantCount: 5 },
lowBandwidthMode: null,
});
render(
@@ -452,6 +453,7 @@ describe("DeveloperSettingsTab", () => {
const client = createMockMatrixClient();
const vm = createStaticViewModel<DeveloperSettingsSnapshot>({
keyRotation: { suppressed: true, participantCount: 50 },
lowBandwidthMode: null,
});
render(
@@ -493,4 +495,48 @@ describe("DeveloperSettingsTab", () => {
);
});
});
describe("Low bandwidth mode", () => {
it("is a switch for the call, while in one", async () => {
const user = userEvent.setup();
const setEnabled = vi.fn();
render(
<TooltipProvider>
<DeveloperSettingsTab
client={createMockMatrixClient()}
env={{} as unknown as ImportMetaEnv}
vm={createStaticViewModel<DeveloperSettingsSnapshot>({
keyRotation: null,
lowBandwidthMode: { enabled: false, setEnabled },
})}
/>
</TooltipProvider>,
);
const toggle = screen.getByRole("checkbox", {
name: "Low bandwidth mode",
});
expect(toggle).not.toBeChecked();
expect(toggle).toHaveAccessibleDescription(
"Stop all video for this call, so that audio keeps flowing on a slow network. Lasts until the call ends.",
);
await user.click(toggle);
expect(setEnabled).toHaveBeenCalledWith(true);
});
it("is not offered outside a call", () => {
render(
<TooltipProvider>
<DeveloperSettingsTab
client={createMockMatrixClient()}
env={{} as unknown as ImportMetaEnv}
vm={outOfCallDeveloperSettingsTabViewModel}
/>
</TooltipProvider>,
);
expect(
screen.queryByRole("checkbox", { name: "Low bandwidth mode" }),
).toBeNull();
});
});
});
+21
View File
@@ -97,6 +97,11 @@ export interface KeyRotationInfo {
export interface DeveloperSettingsSnapshot {
/** The media key rotation state, or `null` when we are not in a call. */
keyRotation: KeyRotationInfo | null;
/** The call's low bandwidth mode, or `null` when we are not in a call. */
lowBandwidthMode: {
enabled: boolean;
setEnabled: (enabled: boolean) => void;
} | null;
}
/**
@@ -141,6 +146,7 @@ export const DeveloperSettingsTab: FC<Props> = ({
}) => {
const { t } = useTranslation();
const keyRotation = useBehavior(vm.keyRotation$);
const lowBandwidthMode = useBehavior(vm.lowBandwidthMode$);
const [duplicateTiles, setDuplicateTiles] = useSetting(duplicateTilesSetting);
const [debugTileLayout, setDebugTileLayout] = useSetting(
debugTileLayoutSetting,
@@ -410,6 +416,21 @@ export const DeveloperSettingsTab: FC<Props> = ({
</p>
{keyRotation !== null && <KeyRotationStatus info={keyRotation} />}
<Separator />
{/* Null outside a call (the lobby, the user menu): the mode belongs to a call */}
{lowBandwidthMode !== null && (
<FieldRow>
<InputField
id="lowBandwidthMode"
type="checkbox"
label={t("low_bandwidth_mode.switch_label")}
description={t("low_bandwidth_mode.switch_description")}
checked={lowBandwidthMode.enabled}
onChange={(event: ChangeEvent<HTMLInputElement>): void =>
lowBandwidthMode.setEnabled(event.target.checked)
}
/>
</FieldRow>
)}
<FieldRow>
<InputField
id="duplicateTiles"
@@ -9,6 +9,7 @@ import { describe, expect, it } from "vitest";
import { BehaviorSubject } from "rxjs";
import { testScope } from "../utils/test";
import { createLowBandwidthMode } from "../state/LowBandwidthMode";
import { type CallViewModel } from "../state/CallViewModel/CallViewModel";
import {
createDeveloperSettingsTabViewModel,
@@ -19,10 +20,11 @@ describe("createDeveloperSettingsTabViewModel", () => {
it("projects the key rotation state of the call", () => {
const keyRotationSuppressed$ = new BehaviorSubject(false);
const participantCount$ = new BehaviorSubject(5);
const vm = createDeveloperSettingsTabViewModel(testScope(), {
keyRotationSuppressed$,
participantCount$,
} as unknown as CallViewModel);
const vm = createDeveloperSettingsTabViewModel(
testScope(),
{ keyRotationSuppressed$, participantCount$ } as unknown as CallViewModel,
createLowBandwidthMode(),
);
expect(vm.keyRotation$.value).toEqual({
suppressed: false,
@@ -37,9 +39,35 @@ describe("createDeveloperSettingsTabViewModel", () => {
participantCount: 50,
});
});
it("has a switch reflecting the call's low bandwidth mode", () => {
const mode = createLowBandwidthMode();
const vm = createDeveloperSettingsTabViewModel(
testScope(),
{
keyRotationSuppressed$: new BehaviorSubject(false),
participantCount$: new BehaviorSubject(1),
} as unknown as CallViewModel,
mode,
);
expect(vm.lowBandwidthMode$.value?.enabled).toBe(false);
vm.lowBandwidthMode$.value!.setEnabled(true);
expect(mode.enabled$.value).toBe(true);
expect(vm.lowBandwidthMode$.value?.enabled).toBe(true);
mode.setEnabled(false);
expect(vm.lowBandwidthMode$.value?.enabled).toBe(false);
});
});
describe("outOfCallDeveloperSettingsTabViewModel", () => {
it("has no low bandwidth mode switch", () => {
expect(outOfCallDeveloperSettingsTabViewModel.lowBandwidthMode$.value).toBe(
null,
);
});
it("has no key rotation state", () => {
expect(outOfCallDeveloperSettingsTabViewModel.keyRotation$.value).toBe(
null,
+16 -2
View File
@@ -5,9 +5,10 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { combineLatest } from "rxjs";
import { combineLatest, map } from "rxjs";
import { type CallViewModel } from "../state/CallViewModel/CallViewModel.ts";
import { type LowBandwidthMode } from "../state/LowBandwidthMode.ts";
import { type ObservableScope } from "../state/ObservableScope.ts";
import { createStaticViewModel, type ViewModel } from "../state/ViewModel.ts";
import { type DeveloperSettingsSnapshot } from "./DeveloperSettingsTab.tsx";
@@ -20,12 +21,22 @@ import { type DeveloperSettingsSnapshot } from "./DeveloperSettingsTab.tsx";
*
* @param scope - ObservableScope that bounds the lifetime of derived behaviors.
* @param callModel - The root CallViewModel; provides the key rotation state.
* @param lowBandwidthMode - The call's low bandwidth mode, for its switch.
*/
export function createDeveloperSettingsTabViewModel(
scope: ObservableScope,
callModel: CallViewModel,
lowBandwidthMode: LowBandwidthMode,
): ViewModel<DeveloperSettingsSnapshot> {
return {
lowBandwidthMode$: scope.behavior(
lowBandwidthMode.enabled$.pipe(
map((enabled) => ({
enabled,
setEnabled: lowBandwidthMode.setEnabled,
})),
),
),
keyRotation$: scope.behavior(
combineLatest(
[callModel.keyRotationSuppressed$, callModel.participantCount$],
@@ -40,4 +51,7 @@ export function createDeveloperSettingsTabViewModel(
* menu), where no call state exists. All call specific fields are `null`.
*/
export const outOfCallDeveloperSettingsTabViewModel: ViewModel<DeveloperSettingsSnapshot> =
createStaticViewModel<DeveloperSettingsSnapshot>({ keyRotation: null });
createStaticViewModel<DeveloperSettingsSnapshot>({
keyRotation: null,
lowBandwidthMode: null,
});
@@ -75,6 +75,10 @@ import {
type VideoProcessor,
} from "@element-hq/matrixrtc-sdk";
import { type BackgroundEffectsState } from "../BackgroundEffects";
import { createLowBandwidthMode } from "../LowBandwidthMode.ts";
import { type MediaViewModel } from "../media/MediaViewModel.ts";
import { type RemoteScreenShareViewModel } from "../media/RemoteScreenShareViewModel.ts";
import { type UserMediaViewModel } from "../media/UserMediaViewModel.ts";
initializeWidget();
@@ -1897,3 +1901,154 @@ describe("a camera with a video processor", () => {
expect(participation!.publish).not.toHaveBeenCalled();
});
});
describe("low bandwidth mode", () => {
const withCallViewModel = withCallViewModelInMode(MatrixRTCMode.Matrix_2_0);
const onOff = { y: true, n: false };
test("stops and resumes receiving video as the mode is turned on and off", () => {
const lowBandwidthMode = createLowBandwidthMode();
withCallViewModel(
{ lowBandwidthMode },
(_vm, _session, { rtcParticipation }) => {
expect(rtcParticipation.setReceiveVideo).toHaveBeenLastCalledWith(true);
lowBandwidthMode.setEnabled(true);
expect(rtcParticipation.setReceiveVideo).toHaveBeenLastCalledWith(
false,
);
lowBandwidthMode.setEnabled(false);
expect(rtcParticipation.setReceiveVideo).toHaveBeenLastCalledWith(true);
},
);
});
test("shows a camera that is still sending as off while on", () => {
withTestScheduler(({ schedule, expectObservable }) => {
const lowBandwidthMode = createLowBandwidthMode();
withCallViewModel(
{
lowBandwidthMode,
// Three, for the grid
remoteParticipants$: constant([aliceParticipant, bobParticipant]),
rtcMembers$: constant([localRtcMember, aliceRtcMember, bobRtcMember]),
videoEnabled: new Map([[aliceParticipant, constant(true)]]),
},
(vm) => {
schedule("-yn", {
y: () => lowBandwidthMode.setEnabled(true),
n: () => lowBandwidthMode.setEnabled(false),
});
expectObservable(
gridMedia$(vm.layout$, `${aliceId}:0`).pipe(
switchMap((media) => media?.videoEnabled$ ?? NEVER),
distinctUntilChanged(),
),
).toBe("yny", onOff);
},
);
});
});
test("keeps a remote screen share on the stage, without its picture, while on", () => {
withTestScheduler(({ schedule, expectObservable }) => {
const lowBandwidthMode = createLowBandwidthMode();
withCallViewModel(
{
lowBandwidthMode,
remoteParticipants$: constant([aliceParticipant]),
rtcMembers$: constant([localRtcMember, aliceRtcMember]),
sharingScreen: new Map([[aliceParticipant, constant(true)]]),
},
(vm) => {
schedule("-yn", {
y: () => lowBandwidthMode.setEnabled(true),
n: () => lowBandwidthMode.setEnabled(false),
});
const share$ = spotlightMedia$(
vm.layout$,
`${aliceId}:0:screen-share`,
);
expectObservable(
share$.pipe(
map((share) => share !== undefined),
distinctUntilChanged(),
),
).toBe("y", onOff);
expectObservable(
share$.pipe(
switchMap(
(share) =>
(share as RemoteScreenShareViewModel | undefined)
?.videoEnabled$ ?? NEVER,
),
distinctUntilChanged(),
),
).toBe("yny", onOff);
},
);
});
});
test("leaves a blank share out of the picture-in-picture window while on", () => {
withTestScheduler(({ schedule, expectObservable }) => {
const lowBandwidthMode = createLowBandwidthMode();
withCallViewModel(
{
lowBandwidthMode,
remoteParticipants$: constant([aliceParticipant]),
rtcMembers$: constant([localRtcMember, aliceRtcMember]),
sharingScreen: new Map([[aliceParticipant, constant(true)]]),
},
(vm) => {
schedule("-pyn", {
p: () => window.controls.enablePip(),
y: () => lowBandwidthMode.setEnabled(true),
n: () => lowBandwidthMode.setEnabled(false),
});
onTestFinished(() => window.controls.disablePip());
expectObservable(summarizeLayout$(vm.layout$)).toBe("abcb", {
a: {
type: "spotlight-landscape",
spotlight: [`${aliceId}:0:screen-share`],
grid: [`${localId}:0`, `${aliceId}:0`],
},
b: { type: "pip", spotlight: [`${aliceId}:0:screen-share`] },
c: { type: "pip", spotlight: [`${aliceId}:0`] },
});
},
);
});
});
function gridMedia$(
layout$: Observable<Layout>,
id: string,
): Observable<UserMediaViewModel | undefined> {
return layout$.pipe(
switchMap((layout) =>
"grid" in layout && layout.grid.length > 0
? combineLatest(layout.grid.map((tile) => tile.media$))
: NEVER,
),
map((media) =>
media.find(
(m): m is UserMediaViewModel => m.id === id && m.type === "user",
),
),
);
}
function spotlightMedia$(
layout$: Observable<Layout>,
id: string,
): Observable<MediaViewModel | undefined> {
return layout$.pipe(
switchMap((layout) =>
layout.type === "spotlight-landscape"
? layout.spotlight.vm.media$
: NEVER,
),
map((media) => media.find((m) => m.id === id)),
);
}
});
+52 -28
View File
@@ -82,6 +82,7 @@ import {
import { type BackgroundEffectsState } from "../BackgroundEffects";
import { shallowEquals as arrayShallowEquals } from "../../utils/array";
import { type MediaDevices } from "../MediaDevices";
import { type LowBandwidthMode } from "../LowBandwidthMode";
import { type MuteStates } from "../MuteStates";
import {
followDevice,
@@ -207,6 +208,8 @@ export interface CallViewModelProps {
client: Pick<MatrixClient, "getUserId" | "getDeviceId">;
mediaDevices: MediaDevices;
muteStates: MuteStates;
/** The call's low bandwidth mode, which outlives this view model. */
lowBandwidthMode: LowBandwidthMode;
encryptionSystem: EncryptionSystem;
/**
* The size of the space the call is drawn in: the page when Element Call
@@ -506,6 +509,7 @@ export function createCallViewModel$(
client,
mediaDevices,
muteStates,
lowBandwidthMode,
encryptionSystem,
viewSize$,
handsRaisedSubject$,
@@ -653,6 +657,10 @@ export function createCallViewModel$(
});
});
lowBandwidthMode.enabled$
.pipe(scope.bind())
.subscribe((enabled) => rtcParticipation.setReceiveVideo(!enabled));
const members$ = scope.behavior<(LocalRTCMember | RemoteRTCMember)[]>(
combineLatest(
[rtcParticipation.localMember$, rtcParticipation.remoteMembers$],
@@ -750,6 +758,7 @@ export function createCallViewModel$(
),
mediaDevices,
pretendToBeDisconnected$: reconnecting$,
videoPaused$: lowBandwidthMode.enabled$,
displayName$: member.displayName$,
mxcAvatarUrl$: member.avatarUrl$,
handRaised$: scope.behavior(
@@ -925,34 +934,6 @@ export function createCallViewModel$(
),
);
const spotlightAndPip$ = scope.behavior(
combineLatest(
[ringingMedia$, screenShares$, spotlightSpeaker$, localUserMediaForPip$],
(ringing, screenShares, speaker, localPip) =>
computeSpotlight({ ringing, screenShares, speaker, localPip }),
).pipe(
distinctUntilChanged(
(a, b) =>
arrayShallowEquals(a.spotlight, b.spotlight) && a.pip === b.pip,
),
),
);
const spotlight$ = scope.behavior<MediaViewModel[]>(
spotlightAndPip$.pipe(
map(({ spotlight }) => spotlight),
distinctUntilChanged<MediaViewModel[]>(arrayShallowEquals),
),
);
const hasRemoteScreenShares$ = scope.behavior<boolean>(
spotlight$.pipe(
map((spotlight) =>
spotlight.some((vm) => vm.type === "screen share" && !vm.local),
),
),
);
const pipEnabled$ = scope.behavior(setPipEnabled$, false);
// A guess at what the window's mode should be based on the size and shape of
@@ -980,6 +961,49 @@ export function createCallViewModel$(
),
);
// A share received without its picture is a blank tile: one is no use
// in a window this small
const spotlightScreenShares$ = scope.behavior(
combineLatest(
[screenShares$, lowBandwidthMode.enabled$, windowMode$],
(screenShares, lowBandwidth, windowMode) =>
lowBandwidth && windowMode === "pip" ? [] : screenShares,
),
);
const spotlightAndPip$ = scope.behavior(
combineLatest(
[
ringingMedia$,
spotlightScreenShares$,
spotlightSpeaker$,
localUserMediaForPip$,
],
(ringing, screenShares, speaker, localPip) =>
computeSpotlight({ ringing, screenShares, speaker, localPip }),
).pipe(
distinctUntilChanged(
(a, b) =>
arrayShallowEquals(a.spotlight, b.spotlight) && a.pip === b.pip,
),
),
);
const spotlight$ = scope.behavior<MediaViewModel[]>(
spotlightAndPip$.pipe(
map(({ spotlight }) => spotlight),
distinctUntilChanged<MediaViewModel[]>(arrayShallowEquals),
),
);
const hasRemoteScreenShares$ = scope.behavior<boolean>(
spotlight$.pipe(
map((spotlight) =>
spotlight.some((vm) => vm.type === "screen share" && !vm.local),
),
),
);
const spotlightExpandedToggle$ = new Subject<void>();
const spotlightExpanded$ = createToggle$(
scope,
@@ -6,6 +6,10 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import {
createLowBandwidthMode,
type LowBandwidthMode,
} from "../LowBandwidthMode";
import {
type Behavior,
constant,
@@ -95,6 +99,7 @@ export interface CallViewModelInputs {
mediaDevices: MediaDevices;
initialSyncState: SyncState;
viewSize$: Behavior<{ width: number; height: number }>;
lowBandwidthMode: LowBandwidthMode;
}
export const localParticipant: Participant = { identity: "" };
@@ -121,6 +126,7 @@ export function withCallViewModel(mode: MatrixRTCMode) {
mediaDevices = mockMediaDevices({}),
initialSyncState = SyncState.Syncing,
viewSize$ = constant({ width: 1000, height: 800 }),
lowBandwidthMode = createLowBandwidthMode(),
}: Partial<CallViewModelInputs> = {},
continuation: (
vm: CallViewModel,
@@ -290,6 +296,7 @@ export function withCallViewModel(mode: MatrixRTCMode) {
client: room.client,
mediaDevices,
muteStates,
lowBandwidthMode,
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
viewSize$,
handsRaisedSubject$: raisedHands$,
+25
View File
@@ -0,0 +1,25 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { describe, test } from "vitest";
import { withTestScheduler } from "../utils/test";
import { createLowBandwidthMode } from "./LowBandwidthMode";
describe("LowBandwidthMode", () => {
test("starts off, and is turned on and off and reset without developer mode", () => {
withTestScheduler(({ schedule, expectObservable }) => {
const mode = createLowBandwidthMode();
schedule("-ab-ar", {
a: () => mode.setEnabled(true),
b: () => mode.setEnabled(false),
r: () => mode.reset(),
});
expectObservable(mode.enabled$).toBe("nyn-yn", { y: true, n: false });
});
});
});
+31
View File
@@ -0,0 +1,31 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { BehaviorSubject } from "rxjs";
import { type Behavior } from "./Behavior";
/**
* Whether the call has given up video to keep audio flowing on a slow
* network. Lasts for one call: never stored.
*/
export interface LowBandwidthMode {
enabled$: Behavior<boolean>;
/** The one way in and out. Not gated on developer mode: only the switch is. */
setEnabled(enabled: boolean): void;
/** Back to off, for a new call. */
reset(): void;
}
export function createLowBandwidthMode(): LowBandwidthMode {
const enabled$ = new BehaviorSubject(false);
return {
enabled$,
setEnabled: (enabled): void => enabled$.next(enabled),
reset: (): void => enabled$.next(false),
};
}
+17 -3
View File
@@ -11,7 +11,7 @@ import {
type ObservableScope,
trackBySource$,
} from "@element-hq/matrixrtc-sdk";
import { map } from "rxjs";
import { combineLatest, map } from "rxjs";
import {
type BaseScreenShareInputs,
@@ -27,6 +27,11 @@ export interface RemoteScreenShareViewModel
* Whether this screen share's video should be displayed.
*/
videoEnabled$: Behavior<boolean>;
/**
* Whether the call has stopped receiving video: the share is shown
* without its picture, and nothing in its place.
*/
videoPaused$: Behavior<boolean>;
/**
* Whether this screen share should be considered to have an audio track.
*/
@@ -35,11 +40,16 @@ export interface RemoteScreenShareViewModel
export interface RemoteScreenShareInputs extends BaseScreenShareInputs {
pretendToBeDisconnected$: Behavior<boolean>;
videoPaused$: Behavior<boolean>;
}
export function createRemoteScreenShare(
scope: ObservableScope,
{ pretendToBeDisconnected$, ...inputs }: RemoteScreenShareInputs,
{
pretendToBeDisconnected$,
videoPaused$,
...inputs
}: RemoteScreenShareInputs,
): RemoteScreenShareViewModel {
const audio$ = trackBySource$(
scope,
@@ -58,8 +68,12 @@ export function createRemoteScreenShare(
}),
local: false,
videoEnabled$: scope.behavior(
pretendToBeDisconnected$.pipe(map((disconnected) => !disconnected)),
combineLatest(
[pretendToBeDisconnected$, videoPaused$],
(disconnected, paused) => !disconnected && !paused,
),
),
videoPaused$,
audioEnabled$: scope.behavior(
audio$.pipe(map((track) => track !== undefined)),
),
+6 -4
View File
@@ -33,11 +33,13 @@ export interface RemoteUserMediaViewModel
export interface RemoteUserMediaInputs extends BaseUserMediaInputs {
pretendToBeDisconnected$: Behavior<boolean>;
/** Whether the call has stopped receiving video, while the sender may still be sending it. */
videoPaused$: Behavior<boolean>;
}
export function createRemoteUserMedia(
scope: ObservableScope,
{ pretendToBeDisconnected$, ...inputs }: RemoteUserMediaInputs,
{ pretendToBeDisconnected$, videoPaused$, ...inputs }: RemoteUserMediaInputs,
): RemoteUserMediaViewModel {
const baseUserMedia = createBaseUserMedia(scope, inputs);
@@ -73,9 +75,9 @@ export function createRemoteUserMedia(
),
),
videoEnabled$: scope.behavior(
pretendToBeDisconnected$.pipe(
switchMap((disconnected) =>
disconnected ? of(false) : baseUserMedia.videoEnabled$,
combineLatest([pretendToBeDisconnected$, videoPaused$]).pipe(
switchMap(([disconnected, paused]) =>
disconnected || paused ? of(false) : baseUserMedia.videoEnabled$,
),
),
),
@@ -90,6 +90,7 @@ export function createWrappedUserMedia(
member,
mediaDevices,
pretendToBeDisconnected$,
videoPaused$,
...inputs
}: WrappedUserMediaInputs,
): WrappedUserMediaViewModel {
@@ -98,6 +99,7 @@ export function createWrappedUserMedia(
: createRemoteUserMedia(scope, {
member,
pretendToBeDisconnected$,
videoPaused$,
...inputs,
});
@@ -122,6 +124,7 @@ export function createWrappedUserMedia(
id,
member,
pretendToBeDisconnected$,
videoPaused$,
});
},
),
+21
View File
@@ -46,6 +46,27 @@ describe("MediaView", () => {
});
});
describe("with no placeholder", () => {
it("draws nothing in place of a video that is off", () => {
render(
<MediaView
{...baseProps}
video={mockVideoTrack({ source: "screenShare" })}
videoEnabled={false}
placeholder="none"
/>,
);
expect(
screen.queryByRole("img", { name: "@alice:example.com" }),
).toBeNull();
expect(screen.getByTestId("videoTile")).toHaveAttribute(
"data-video-enabled",
"false",
);
expect(screen.getByTestId("name_tag")).toHaveTextContent("some name");
});
});
describe("with video", () => {
it("labels the video element with the track source", () => {
render(
+14 -9
View File
@@ -58,6 +58,8 @@ interface Props extends ComponentProps<typeof animated.div> {
displayName: string;
mxcAvatarUrl: string | undefined;
avatarStyle?: "solid" | "translucent";
/** What is drawn while there is no video: the avatar, or nothing. */
placeholder?: "avatar" | "none";
background?: "solid" | "transparent";
focusable: boolean;
primaryButton?: ReactNode;
@@ -97,6 +99,7 @@ export const MediaView: FC<Props> = ({
displayName,
mxcAvatarUrl,
avatarStyle = "solid",
placeholder = "avatar",
background = "solid",
focusable,
primaryButton,
@@ -188,15 +191,17 @@ export const MediaView: FC<Props> = ({
<div className={styles.speakingBorder} />
</div>
)}
<Avatar
id={userId}
name={displayName}
size={avatarSize}
src={mxcAvatarUrl}
data-style={avatarStyle}
className={styles.avatar}
style={{ display: video && videoEnabled ? "none" : "initial" }}
/>
{placeholder === "avatar" && (
<Avatar
id={userId}
name={displayName}
size={avatarSize}
src={mxcAvatarUrl}
data-style={avatarStyle}
className={styles.avatar}
style={{ display: video && videoEnabled ? "none" : "initial" }}
/>
)}
{video !== undefined && (
// A live camera has no captions to offer
// eslint-disable-next-line jsx-a11y/media-has-caption
+8 -1
View File
@@ -146,6 +146,7 @@ SpotlightUserMediaItem.displayName = "SpotlightUserMediaItem";
interface SpotlightScreenShareItemProps extends SpotlightMemberMediaItemBaseProps {
vm: ScreenShareViewModel;
videoEnabled: boolean;
placeholder?: "avatar" | "none";
}
const SpotlightScreenShareItem: FC<SpotlightScreenShareItemProps> = ({
@@ -163,8 +164,14 @@ const SpotlightRemoteScreenShareItem: FC<
SpotlightRemoteScreenShareItemProps
> = ({ vm, ...props }) => {
const videoEnabled = useBehavior(vm.videoEnabled$);
const videoPaused = useBehavior(vm.videoPaused$);
return (
<SpotlightScreenShareItem vm={vm} videoEnabled={videoEnabled} {...props} />
<SpotlightScreenShareItem
vm={vm}
videoEnabled={videoEnabled}
placeholder={videoPaused ? "none" : "avatar"}
{...props}
/>
);
};
+8 -1
View File
@@ -5,6 +5,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { createLowBandwidthMode } from "../state/LowBandwidthMode";
import { type CallMembership } from "matrix-js-sdk/lib/matrixrtc";
import { BehaviorSubject } from "rxjs";
import { vitest } from "vitest";
@@ -221,6 +222,7 @@ export function getBasicCallViewModelEnvironment(
),
),
});
const lowBandwidthMode = createLowBandwidthMode();
const vm = createCallViewModel$(
scope,
{
@@ -229,6 +231,7 @@ export function getBasicCallViewModelEnvironment(
client,
mediaDevices,
muteStates,
lowBandwidthMode,
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
viewSize$: constant({ width: 1000, height: 800 }),
handsRaisedSubject$: handRaisedSubject$,
@@ -254,7 +257,11 @@ export function getBasicCallViewModelEnvironment(
return {
vm,
footerVm,
developerSettingsVm: createDeveloperSettingsTabViewModel(testScope(), vm),
developerSettingsVm: createDeveloperSettingsTabViewModel(
testScope(),
vm,
lowBandwidthMode,
),
rtcMemberships$,
rtcSession,
matrixRoom,
+10 -1
View File
@@ -406,7 +406,12 @@ export function mockRemoteMedia(
roomMember: Partial<RoomMember>,
/** The tracks, or a behavior of them for a test that has them arrive. */
tracks: MockTracks | Behavior<MockTracks>,
{ transport }: { transport?: Transport } = { transport: exampleTransport },
{
transport,
videoPaused$ = constant(false),
}: { transport?: Transport; videoPaused$?: Behavior<boolean> } = {
transport: exampleTransport,
},
): RemoteUserMediaViewModel {
const member = mockMatrixRoomMember(rtcMember, roomMember);
return createRemoteUserMedia(testScope(), {
@@ -422,6 +427,7 @@ export function mockRemoteMedia(
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
transport$: constant(transport),
pretendToBeDisconnected$: constant(false),
videoPaused$,
displayName$: constant(member.rawDisplayName ?? "nodisplayname"),
mxcAvatarUrl$: constant(member.getMxcAvatarUrl()),
handRaised$: constant(null),
@@ -433,6 +439,7 @@ export function mockRemoteScreenShare(
rtcMember: CallMembership,
roomMember: Partial<RoomMember>,
tracks: MockTracks,
videoPaused$: Behavior<boolean> = constant(false),
): RemoteScreenShareViewModel {
const member = mockMatrixRoomMember(rtcMember, roomMember);
return createRemoteScreenShare(testScope(), {
@@ -446,6 +453,7 @@ export function mockRemoteScreenShare(
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
transport$: constant(exampleTransport),
pretendToBeDisconnected$: constant(false),
videoPaused$,
displayName$: constant(member.rawDisplayName ?? "nodisplayname"),
mxcAvatarUrl$: constant(member.getMxcAvatarUrl()),
});
@@ -574,6 +582,7 @@ function mockSlotWithParticipation(
keyRotationSuppressed$,
connectedTransports$,
setAudioOutputDeviceId: vi.fn(async () => Promise.resolve()),
setReceiveVideo: vi.fn(),
sendData: vi.fn(async () => Promise.resolve()),
data$: NEVER,
};
+50
View File
@@ -75,3 +75,53 @@ for (const [property, value] of [
get: () => value,
configurable: true,
});
const storage: Record<string, string> = {};
const localStoragePolyfill = {
getItem(key: string) {
return Object.prototype.hasOwnProperty.call(storage, key)
? storage[key]
: null;
},
setItem(key: string, value: string) {
storage[key] = String(value);
},
removeItem(key: string) {
delete storage[key];
},
clear() {
for (const key in storage) {
delete storage[key];
}
},
key(index: number) {
const keys = Object.keys(storage);
return keys[index] ?? null;
},
get length() {
return Object.keys(storage).length;
},
} as unknown as Storage;
if (
typeof globalThis.localStorage === "undefined" ||
typeof globalThis.localStorage.clear !== "function"
) {
Object.defineProperty(globalThis, "localStorage", {
value: localStoragePolyfill,
writable: true,
configurable: true,
});
}
if (
typeof window !== "undefined" &&
(typeof window.localStorage === "undefined" ||
typeof window.localStorage.clear !== "function")
) {
Object.defineProperty(window, "localStorage", {
value: localStoragePolyfill,
writable: true,
configurable: true,
});
}
-4
View File
@@ -21,10 +21,6 @@ export default defineConfig((configEnv) =>
css: { include: /.+/ },
setupFiles: ["src/vitest.setup.ts"],
environment: "jsdom",
// Node's own localStorage (on by default since Node 25) is
// unusable without a file to back it and shadows jsdom's.
// We should be able to remove this once we switch to Vitest 5.
execArgv: ["--no-experimental-webstorage"],
include: [
"src/**/*.test.ts",
"src/**/*.test.tsx",