Compare commits

..
Author SHA1 Message Date
Timo K. 80ca4d7e0f Add basic tests for refactored files 2026-11-12 17:47:27 +01:00
Timo K. a2e3a2c13f review 2026-11-12 13:25:45 +01:00
Timo K. 8d5d482771 Remove the derived hooks from ClientContext
Those were hooks just used in one place. We move them directly into
their component.
This is acceptable because the disconnect banner needs a new appraoch
when not having a syncing clinet but just a matrixBackend.
2026-11-12 13:25:45 +01:00
Timo K.andClaude Fable 5.1 87f2726dd8 Hand the client provider a session
ClientProvider had a `client` prop and a `loadClient` prop and ran the
session in an effect: restoring, exposing setClient, changePassword and
logout, and holding the "load" broadcast. It takes one `ClientSession`
now and only renders what the session says, so the context carries the
session itself rather than a parallel `ClientState` shape.

- main.tsx builds a `StandaloneClientSession` for the SPA and a
  `pendingHostClientSession` for the widget; App.tsx no longer waits for
  the widget client itself. The component wraps the host's client in a
  `hostClientSession`.
- The login and registration pages call `session.login` and
  `session.register`, and sign a registration in with `setSignedIn` once
  they are done with the account, in place of `setClient`. The two
  wrapper hooks and `utils/spa` go; their logic lives in the holder.
- `useClient` and `useClientLegacy` keep their shapes minus `setClient`;
  `useClientSession` and `useClientSessionState` are the new way in.
  Logging out leaves for home and resets analytics from `useClientLegacy`,
  as before, around the session's own logout.
- `useClientDisconnected` reads the session state directly.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-12 13:25:45 +01:00
Timo K.andClaude Fable 5.1 5fb9d6a81e Add a client session holder for the standalone app
Where the client comes from, and what may be done with the session
behind it, is state that outlives any React tree: main.tsx, the widget
and the component each need to construct a different one and hand it
down. `ClientSession` names that: a Behavior of the session state plus
the actions a session offers, which are absent when the session is not
Element Call's to manage. `hostClientSession` wraps a client a host
already has, `pendingHostClientSession` one still arriving over the
widget API.

`StandaloneClientSession` is the one for the SPA. Nothing in it is new
logic: `restore` is `initSPA` from `utils/spa`; `login`, `register` and
`createClient` are the tails of `useInteractiveLogin` and
`useInteractiveRegistration` after the auth split; `changePassword`,
`logout` and the "load" broadcast that shuts other instances down are
lifted out of `ClientProvider`. Registering and signing in are separate
steps, as a caller may have more to do with the account before the
session changes hands. `StoredSession` is `Session` from the context,
which goes once the provider takes a session.

Nothing consumes the holder yet; the next commit switches the provider
over. Both are tested through every state here, while the code they
replace is still around to compare against.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-12 13:25:45 +01:00
Timo K.andClaude Fable 5.1 ba6bcdc4eb Separate interactive auth from client creation
The login and registration hooks each did three things: talk the
user-interactive auth flow through with the homeserver, start a client
on the credentials it handed out, and, for registration, fetch the terms
and recaptcha key. Only the first is auth.

`interactiveAuth.ts` keeps that part as two plain functions, with the UIA
bodies moved verbatim, so they can be unit tested without React or a
client store: `loginWithPassword` and `registerWithPassword` resolve to
the credentials the homeserver issued and nothing else. Fetching the
terms is `useRegistrationTerms` now. The two hooks are left as thin
wrappers that compose the pieces, with the same signatures, so their
callers do not change in this commit.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-12 13:25:45 +01:00
Timo K.andClaude Fable 5.1 56d73d1dfc Track the client's connection in a hook of its own
Whether the client is disconnected is a fact about the client's sync, not
about the session, yet the provider owned the sync listener and put the
flag on the context state, so the banner had to reach through the whole
`ClientState` to read it. `useClientDisconnected` listens on whichever
client is signed in, tagging its verdict with that client so a swapped
client does not inherit the old one's before its first sync.

The avatar, which only needs the client, takes it from `useClient` in the
same spirit: consumers read the narrowest hook that answers them.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-12 13:25:45 +01:00
Timo K.andClaude Fable 5.1 89ad1ec936 Read reaction support from the host bridge
The client context copied `hostBridge.supportsReactions` into a
`supportedFeatures` field, and the one consumer, the reactions sender,
read it from there. It reads the host bridge itself now, which is where
the fact comes from; the context carries one thing less that has nothing
to do with the client.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-12 13:25:45 +01:00
Timo K.andClaude Fable 5.1 b9a3cc6678 Reword the store worker comments
Shorter notes on why `initClient` has a module of its own and why
`utils/matrix` must not import a client store; the reasoning is the same.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-12 13:25:45 +01:00
101 changed files with 3700 additions and 3057 deletions
-35
View File
@@ -1,35 +0,0 @@
---
name: handoff
description: Implement the first cut of a task and stop for a direction check before the quality pass.
argument-hint: <the task>
disable-model-invocation: true
---
Task: $ARGUMENTS
Stop after the first implementation and hand it back before the quality pass.
## Before the hand-off
- Run the narrowest check that rules out an obviously broken hand-off: the test
file for the touched code, `tsc` on its own, a single story. Not the full
`pnpm lint`, not the whole suite.
- If a wider check is needed before feedback can be useful, keep it to the touched
code and say why it was needed.
- Leave wider refactors, extra tests and documentation polish out. They are
follow-up work, not part of the first hand-off.
## The hand-off
Stop and ask whether the direction is right. The message says:
- what was built and where, in a few lines,
- which check ran and what it returned, verbatim if it failed,
- what was left out on purpose,
- the decisions that could have gone another way.
Do not continue past this point on your own.
## After the user confirms
The skill ends here. Continue with the quality pass as usual.
-3
View File
@@ -105,9 +105,6 @@
- name: "Claude-Review"
description: "Request code review from Claude"
color: "e57157"
- name: "Claude-Analyse-Failures"
description: "Request an analysis of failing tests from Claude"
color: "4ADEC0"
- name: "customer-retainer"
color: "F44A5F"
- name: "dependencies"
@@ -1,106 +0,0 @@
name: Claude failure analysis
on:
pull_request:
types: [labeled]
permissions:
# The action exchanges the GitHub OIDC token for a short-lived Anthropic
# access token. GitHub API access goes through CLAUDE_GH_TOKEN instead.
id-token: write
actions: read
jobs:
analysis:
name: Analyse failures
# Only run on labelling and skip forks.
if: github.event.label.name == 'Claude-Analyse-Failures' && github.event.pull_request.head.repo.full_name == github.repository
runs-on: ubuntu-24.04
# The turn limit below is generous, so bound the job by time instead.
timeout-minutes: 30
steps:
- name: Checkout code
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
# We may need commit history.
fetch-depth: 0
persist-credentials: false
# Pre-download job logs and artifacts of failed runs so that Claude doesn't spend cycles on it.
- name: Download logs and artifacts of failed workflow runs
env:
GH_TOKEN: ${{ github.token }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
run: |
set -eu
dir=agent-workspace/ci-artifacts
mkdir -p "$dir"
for run in $(gh run list --commit "$HEAD_SHA" --status failure --json databaseId --jq '.[].databaseId'); do
mkdir -p "$dir/$run"
# Fetch run summary, logs of failed jobs and artifacts.
gh run view "$run" > "$dir/$run/run.txt"
gh run view "$run" --log-failed > "$dir/$run/failed-jobs.log"
gh run download "$run" --dir "$dir/$run" || echo "No artifacts for run $run"
done
# Unpack any (nested) zip archives.
while zips=$(find "$dir" -name '*.zip') && [ -n "$zips" ]; do
echo "$zips" | while IFS= read -r zip; do
unzip -oq "$zip" -d "${zip%.zip}" && rm "$zip"
done
done
find "$dir" -maxdepth 3 -type d
- name: Analyse
uses: anthropics/claude-code-action@6fed3ca145920b639991cb756090506e1bcaf515 # v1.0.245
with:
anthropic_federation_rule_id: fdrl_01XQmWo4nka1ZTqZdsdeScyr
anthropic_organization_id: dfbc9a23-d636-4653-8970-035204ef60fa
anthropic_service_account_id: svac_018Ay5qaA7ZW8X7XsbdekqUM
anthropic_workspace_id: wrkspc_01Aw8LHjBS6fZysu9yqzYifW
# The token used here must grant read access to code, issues, and metadata as well as
# read and write access to pull requests.
github_token: ${{ secrets.CLAUDE_GH_TOKEN }}
use_sticky_comment: true
track_progress: true
additional_permissions: |
actions: read
prompt: |
One or more test jobs failed on this pull request. Find out why and
what would need to change to make them pass.
The details, logs and artifacts of every failed workflow run have
already been downloaded into `agent-workspace/ci-artifacts/<run id>/`:
- `run.txt`: Textual run summary with jobs, steps and failure annotations
- `failed-jobs.log`: Logs of the failed jobs
- Any other file: Unpacked run artifacts.
If `agent-workspace/ci-artifacts` is empty, no workflow failed. Say so
and stop in this case.
Read the commits on this branch with `git log` and `git diff` against
the base branch of the PR.
For each failed workflow run , find out what failed and search the
root cause(s). Stop investigating once direct evidence confirms a root
cause. Devise at least one possible resolution for each root cause.
Report your findings as PR comment. Start your message with "# Automated
CI failure analysis". Then add one section per root cause with:
- The affected workflows
- Evidence from the logs
- The fix proposal(s)
Be brief and concise in all your communication. Do not mention things
workflows that did not fail.
Use Markdown links for anything that can be navigated to on GitHub
such as files, commits, issues, pull requests, workflow runs and
jobs.
# Set a generous turn limit. It's bounded by timeout-minutes above.
claude_args: |
--model claude-fable-5-1
--allowedTools "mcp__github_ci__get_ci_status,mcp__github_ci__get_workflow_run_details,mcp__github_ci__download_job_log,mcp__github__list_commits,mcp__github__get_commit,mcp__github__get_file_contents,mcp__github__search_code,mcp__github__list_workflow_runs,mcp__github__get_workflow_run,mcp__github__list_pull_requests,mcp__github__get_pull_request,mcp__github__get_pull_request_files,mcp__github__list_tags,Bash(git log:*),Bash(git diff:*),Bash(git show:*),Bash(gh run list:*),Bash(gh run view:*),Bash(gh run download:*),Bash(gh pr view:*),Bash(gh pr diff:*),Bash(gh api:*),Bash(docker:*)"
--max-turns 150
@@ -1,4 +1,4 @@
name: Claude review
name: Claude
on:
pull_request:
types: [labeled]
-4
View File
@@ -44,7 +44,3 @@ storybook-static
# Nested checkout made by scripts/layered.sh
/matrix-js-sdk/
# Claude
/.claude/*
!/.claude/skills/
+4 -25
View File
@@ -16,35 +16,19 @@ host's page. It is the MatrixRTC reference implementation.
`@media`, global `i18next` or the `widget` global — take it from a provider.
- The change works standalone, as a widget and as a component. Say what you checked.
- Every gate below is green before you push.
- Hand off after the first implementation, before the quality pass. Then commit on
the user's word where the setup allows it, or hand them the message.
## Read before you
| … | … |
| -------------------------------- | ---------------------------------------------------------- |
| start a task of any size | [docs/agents/workflow.md](docs/agents/workflow.md) |
| touch call logic or a view model | [docs/agents/architecture.md](docs/agents/architecture.md) |
| write any code | [docs/agents/code-style.md](docs/agents/code-style.md) |
| write a test, story or e2e spec | [docs/agents/testing.md](docs/agents/testing.md) |
| open a PR | [CONTRIBUTING.md](CONTRIBUTING.md) |
## Scratch files live in `agent-workspace/`
Git-ignored. One kebab-case subfolder per task, matching the branch topic:
`agent-workspace/<slug>/`.
| File | Purpose |
| --------------------------- | -------------------------------------------------------------------------------- |
| `plan.md` | The concrete approach — files, symbols, edit order — once direction is confirmed |
| `commit-msg.txt` | `git commit -F agent-workspace/<slug>/commit-msg.txt` |
| `pr-body.md` | `gh pr create --body-file agent-workspace/<slug>/pr-body.md` |
| `implementation-summary.md` | What was built, decisions, trade-offs |
| `NN-prompt.md` | Raw prompt text, numbered, when worth keeping |
- Nothing here is durable. The folder is ignored, so anything worth keeping is
promoted into the PR body or a doc before the task ends.
- Never write scratch files to the repo root. Stray `load_test_summary.md` and
`config.json_` files are what this folder prevents.
- Start `pr-body.md` from `.github/PULL_REQUEST_TEMPLATE.md` and fill every
section.
| implement from a feature spec | [FEATURES_SPEC/AGENTS.md](FEATURES_SPEC/AGENTS.md) |
## Gates
@@ -58,11 +42,6 @@ pnpm i18n:check
`knip` fails on dead code; a file deliberately inert ahead of its consumer goes in
`knip.ts` `ignoreFiles` with a reason.
Ready means every gate is green and the change is covered at the layers
[testing.md](docs/agents/testing.md) asks for. Read the diff against
[code-style.md](docs/agents/code-style.md) first. Re-run the whole checklist after
any fix.
## A good PR
- One slice, under ~400 changed lines, green on its own, linked to its issue.
+13 -7
View File
@@ -73,6 +73,7 @@ import {
} from "../src/UrlParams";
import { MediaDevicesContext } from "../src/MediaDevicesContext";
import { AppViewModel } from "../src/state/AppViewModel";
import { hostClientSession } from "../src/state/ClientSession";
import { ObservableScope } from "../src/state/ObservableScope";
import { BackgroundEffectsProvider } from "../src/tracks/BackgroundEffectsContext";
import { Config } from "../src/config/Config";
@@ -189,20 +190,25 @@ export const ElementCall: FC<ElementCallProps> = ({
[roomId, intent, stableConfig],
);
// Created in an effect so that the scope it lives in ends when the component
// is unmounted (or these options change), rather than keeping its device
// observers running for the rest of the page's life. Null until then, which
// is one render.
const { controlledAudioDevices, callIntent } = params;
const [vm, setVm] = useState<AppViewModel | null>(null);
useEffect(() => {
const scope = new ObservableScope();
setVm(new AppViewModel(scope, { controlledAudioDevices, callIntent }));
setVm(
new AppViewModel(
scope,
{ controlledAudioDevices, callIntent },
// The host owns the client. We create a clientSession wrapping the host client.
hostClientSession(client),
// The host owns the session too, so there is nothing to manage here
null,
),
);
return (): void => {
setVm(null);
scope.end();
};
}, [controlledAudioDevices, callIntent]);
}, [controlledAudioDevices, callIntent, client]);
const room = client.getRoom(roomId);
const rtcSession = useMemo(
@@ -250,7 +256,7 @@ export const ElementCall: FC<ElementCallProps> = ({
>
<Decoration>
<TooltipProvider>
<ClientProvider client={client}>
<ClientProvider session={vm.clientSession}>
<MediaDevicesContext value={vm.mediaDevices}>
<BackgroundEffectsProvider
effects={vm.backgroundEffects}
+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:f85350f2b31a7521a800d9050e9f5c0676d04cfb60675242ccc0c6e25cad7d04
image: ghcr.io/element-hq/element-web:develop@sha256:72791f0b2541208f8f7edd9c6b5a7eaf88accd8ed1f0c4db1bc62bfe18eb90fe
element-web-1:
# Pin to a SHA so that upstream cannot break our tests. Renovate handles regular updates.
image: ghcr.io/element-hq/element-web:develop@sha256:f85350f2b31a7521a800d9050e9f5c0676d04cfb60675242ccc0c6e25cad7d04
image: ghcr.io/element-hq/element-web:develop@sha256:72791f0b2541208f8f7edd9c6b5a7eaf88accd8ed1f0c4db1bc62bfe18eb90fe
volumes:
# The other site opens the embedded package under test in place of the
# copy its image bundles (the first site opens the dev server's app.
+1 -5
View File
@@ -14,11 +14,7 @@ This folder contains documentation for setup, usage, and development of Element
Entry point: [AGENTS.md](../AGENTS.md).
- [Agent workflow](./agents/workflow.md)
- [Architecture](./agents/architecture.md)
- [Code style](./agents/code-style.md)
- [Testing](./agents/testing.md)
Opt-in skills in [`.claude/skills/`](../.claude/skills/):
- `/handoff <task>` — get the first implementation back for a direction check
before lint, the full suite and polish.
+9 -16
View File
@@ -10,13 +10,6 @@
- Owning a resource: a class taking the scope in its constructor — `MediaDevices`,
`MuteStates`, `TileStore`, `Publisher`, `Connection`. Both styles are current;
don't convert one to the other in passing.
- A factory's required parameters are what the thing is made of: no sensible
default. Several of them go in a props interface, so each can carry a doc
comment. Its trailing `options` bag is how the host wants it to behave: every
field optional, each defaulting to standalone behaviour, so `{}` works. A
value with no default is never an option; a test seam is never an option
either — mock the dependency it comes from. See `createCallViewModel$`, with
`CallViewModelProps` and `CallViewModelOptions`.
- `foo$` is an observable. `Behavior<T>`, an observable with a current value, is
the default for anything a view reads.
@@ -43,15 +36,15 @@ Element Call can be mounted several times inside a host's React tree, so it owns
neither window, URL, document nor router. Each seam defaults to the old standalone
and widget behaviour.
| Never | Use |
| --------------------------------------------- | ----------------------------------------------------------- |
| the `widget` global | `useHostBridge()` — `src/HostBridge.ts` |
| `getUrlParams()`, `window.location` | `useUrlParams()` |
| `useNavigate("/")`, `<Link to="/">` | `useLeaveToHome()`, `LeaveToHomeLink` |
| `document.body` | `useRootElement()` |
| `window.innerWidth/Height`, `useMediaQuery` | `useRootSizeMatches()` in views, `viewSize$` in view models |
| global `i18next` | the instance in `src/utils/i18n.ts` |
| config or analytics reading their environment | `Config.initWith()`, `PosthogAnalytics.configure()` |
| Never | Use |
| --------------------------------------------- | ------------------------------------------------------------- |
| the `widget` global | `useHostBridge()` — `src/HostBridge.ts` |
| `getUrlParams()`, `window.location` | `useUrlParams()` |
| `useNavigate("/")`, `<Link to="/">` | `useLeaveToHome()`, `LeaveToHomeLink` |
| `document.body` | `useRootElement()` |
| `window.innerWidth/Height`, `useMediaQuery` | `useRootSizeMatches()` in views, `windowSize$` in view models |
| global `i18next` | the instance in `src/utils/i18n.ts` |
| config or analytics reading their environment | `Config.initWith()`, `PosthogAnalytics.configure()` |
- View models take values as options, never `getUrlParams()`
(`callViewModelOptionsFromParams`, `CallViewModelOptions.hostBridge`).
+50
View File
@@ -0,0 +1,50 @@
# Agent workflow
## Scratch files live in `agent-workspace/`
Git-ignored. One kebab-case subfolder per task, matching the branch topic:
`agent-workspace/<slug>/`.
| File | Purpose |
| --------------------------- | -------------------------------------------------------------------------------- |
| `plan.md` | The concrete approach — files, symbols, edit order — once direction is confirmed |
| `commit-msg.txt` | `git commit -F agent-workspace/<slug>/commit-msg.txt` |
| `pr-body.md` | `gh pr create --body-file agent-workspace/<slug>/pr-body.md` |
| `implementation-summary.md` | What was built, decisions, trade-offs |
| `NN-prompt.md` | Raw prompt text, numbered, when worth keeping |
- Nothing here is durable. The folder is ignored, so anything worth keeping is
promoted into the PR body, a doc, or a feature spec before the task ends.
- Never write scratch files to the repo root. Stray `load_test_summary.md` and
`config.json_` files are what this folder prevents.
- Start `pr-body.md` from `.github/PULL_REQUEST_TEMPLATE.md` and fill every
section.
- Commit subjects are plain imperative English. No conventional-commits prefixes.
- A `plan.md` and a feature spec sit at different altitudes; neither replaces the
other. A spec in `FEATURES_SPEC/` is durable and deliberately abstract —
behaviour, decisions, acceptance criteria — so the feature can be rebuilt against
a `main` nobody has seen yet. A plan is one slice of it landing on today's
`main`: the paths, symbols and edit order the spec's decisions and criteria must
not name. `FEATURES_SPEC/AGENTS.md` wins wherever the two genuinely overlap.
## Hand off before the quality pass
- Implement the change, run the narrowest check that rules out an obviously broken
handoff, then stop and ask whether the direction is right.
- Full `pnpm lint`, the whole suite, coverage and benchmarks come after the
direction is confirmed.
- Wider refactors, extra tests and documentation polish are follow-up work, not
part of the first handoff.
- If a check is needed before feedback, keep it to the touched code and say why.
## Commit and PR readiness
- Commit once the user confirms direction, or asks for one. Not before. Where the
setup has no git identity, a sandbox included, write the message to
`commit-msg.txt` and hand it over instead.
- Ready means every gate in [AGENTS.md](../../AGENTS.md#gates) is green and the
change is covered at the layers [testing.md](./testing.md) asks for. Read the diff
against [code-style.md](./code-style.md) first.
- Re-run the whole checklist after any fix. Only on green, either way.
- Once a human has started reviewing, fix forward — never force-push a
regeneration over a review in progress.
+2 -2
View File
@@ -107,11 +107,11 @@
"livekit-client": "^2.18.1",
"lodash-es": "^4.17.21",
"loglevel": "^1.9.1",
"matrix-js-sdk": "github:matrix-org/matrix-js-sdk#6c8b1b418189919bc69fd9df5e57354e7b3c39cb",
"matrix-js-sdk": "github:matrix-org/matrix-js-sdk#dc8610e796c92553c658300a4882dde961a0678a",
"matrix-widget-api": "^1.18.0",
"node-stdlib-browser": "^1.3.1",
"normalize.css": "^8.0.1",
"oxfmt": "^0.79.0",
"oxfmt": "^0.66.0",
"oxlint": "^1.70.0",
"oxlint-tsgolint": "^0.25.0",
"pako": "^2.0.4",
+122 -111
View File
@@ -16,7 +16,7 @@ overrides:
undici: ^6.27.0
flatted: ^3.4.2
ws: ^8.21.0
dompurify: ^3.4.17
dompurify: ^3.4.11
importers:
@@ -39,7 +39,7 @@ importers:
version: 11.7.12
'@livekit/components-core':
specifier: ^0.12.0
version: 0.12.16(livekit-client@2.23.0(@types/dom-mediacapture-record@1.0.22))(tslib@2.8.1)
version: 0.12.15(livekit-client@2.23.0(@types/dom-mediacapture-record@1.0.22))(tslib@2.8.1)
'@livekit/track-processors':
specifier: ^0.7.1
version: 0.7.2(@types/dom-mediacapture-transform@0.1.11)(livekit-client@2.23.0(@types/dom-mediacapture-record@1.0.22))
@@ -191,8 +191,8 @@ importers:
specifier: ^1.9.1
version: 1.9.2
matrix-js-sdk:
specifier: github:matrix-org/matrix-js-sdk#6c8b1b418189919bc69fd9df5e57354e7b3c39cb
version: https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/6c8b1b418189919bc69fd9df5e57354e7b3c39cb
specifier: github:matrix-org/matrix-js-sdk#dc8610e796c92553c658300a4882dde961a0678a
version: https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/dc8610e796c92553c658300a4882dde961a0678a
matrix-widget-api:
specifier: ^1.18.0
version: 1.20.0
@@ -203,8 +203,8 @@ importers:
specifier: ^8.0.1
version: 8.0.1
oxfmt:
specifier: ^0.79.0
version: 0.79.0
specifier: ^0.66.0
version: 0.66.0
oxlint:
specifier: ^1.70.0
version: 1.81.0(oxlint-tsgolint@0.25.0)
@@ -943,6 +943,9 @@ packages:
'@floating-ui/core@1.8.0':
resolution: {integrity: sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==}
'@floating-ui/dom@1.7.6':
resolution: {integrity: sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ==}
'@floating-ui/dom@1.8.0':
resolution: {integrity: sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==}
@@ -1173,8 +1176,8 @@ packages:
'@jridgewell/trace-mapping@0.3.31':
resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
'@livekit/components-core@0.12.16':
resolution: {integrity: sha512-jcXuNeHKGkXgRiT4wniWRpg+TKUSoTL9da01tMxxKGmjp98zB2DVgPmk1fBZfgDVjPBF+jsZe/WkeFAbvJu4Gw==}
'@livekit/components-core@0.12.15':
resolution: {integrity: sha512-bDkK+jkPMgyT4a5lZmdcuc/hZ8fZUrXW+qQPNHVeSpXCBMzk5q9QWzx+HPtTsPJ8hnncWGfoT81RnXHBsy+Z8g==}
engines: {node: '>=18'}
peerDependencies:
livekit-client: ^2.20.1
@@ -1192,8 +1195,8 @@ packages:
'@types/dom-mediacapture-transform': ^0.1.9
livekit-client: ^1.12.0 || ^2.1.0
'@matrix-org/matrix-sdk-crypto-wasm@18.9.2':
resolution: {integrity: sha512-GHeuSeb5Fj6Wg2+NE/WoLJJs9U3nOzttO+2sj7lOaS5gNBpGIksc48N/Q/kK/Z+Lxh7YMhopB7M8b6HyASXnGQ==}
'@matrix-org/matrix-sdk-crypto-wasm@18.9.0':
resolution: {integrity: sha512-NtLzNDTEfNASBjNCTGZHuk7N0jrQhS6Zx2CM857rCHZYYh/rpbKGQNrJ7azktm4S1P5Jy3WU3nwJTGohGw26qQ==}
engines: {node: '>= 18'}
'@mdx-js/react@3.1.1':
@@ -1626,124 +1629,124 @@ packages:
cpu: [x64]
os: [win32]
'@oxfmt/binding-android-arm-eabi@0.79.0':
resolution: {integrity: sha512-xOCQ/rvokUXs8SxOQY5Wy2ukPaZJZ0PmdJovN0ryB1c8DVEtbcvliLdYtINUYh8QOTpmBOctIisSJk9tvh+J6w==}
'@oxfmt/binding-android-arm-eabi@0.66.0':
resolution: {integrity: sha512-2Me9eoptv6ERdEuI2P8AOlYdHHraXebJaM6SC0kc2Dfb+mLrep2db+fedBPKaYn673h/vBgvP4tkOdAbaudX6w==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm]
os: [android]
'@oxfmt/binding-android-arm64@0.79.0':
resolution: {integrity: sha512-WMLDvCjjchUYtI6zXKOdzTDGm72BaYZiz1/VhB1rrxdakUZRlJh1aMr3CT6ui51uHcWVBycULIXSZHpw6u2pTQ==}
'@oxfmt/binding-android-arm64@0.66.0':
resolution: {integrity: sha512-u7O+bSSF0HGsDKkQQxBqvLGVepu93RA+JKu+ONqvfh4sCnCEbj31wZj4iG5gk3XfRwrmYj0/8catkO2LcblQKQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [android]
'@oxfmt/binding-darwin-arm64@0.79.0':
resolution: {integrity: sha512-+LzSN7w7tULz96ntS1Uqe5oI00XZ0o/m/t3+eSfiQp3aTPnj2eGUafqEWryMLk84j7x9NiF+GEP2YT4/BfClgA==}
'@oxfmt/binding-darwin-arm64@0.66.0':
resolution: {integrity: sha512-/ikyMIVjX/sdo7KtjxoEsSUosfPzveVhT9RWMx9yGqFDKFJ89JAEKuEeLBmurDjrkb4w8tOnAdSO3SBaplY3bw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [darwin]
'@oxfmt/binding-darwin-x64@0.79.0':
resolution: {integrity: sha512-KFiMRhKeiiooaS1dKc4r8AZgOrfOhwVe1yf/aRef+8BajJwtVjMtlsQl/BNRxtkFbq13GjEo/4Q+9YhFGU4o6g==}
'@oxfmt/binding-darwin-x64@0.66.0':
resolution: {integrity: sha512-q5xUsKeFqawa9NXa6ZGXWimFV19m8MogKPdTaSVDAAk2EQKBmBZRDeluwcl1p8ty/OFc9s9888OKEh3xfPVH0g==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [darwin]
'@oxfmt/binding-freebsd-x64@0.79.0':
resolution: {integrity: sha512-lHVIp0g8ZOFKiqVscvttp+3HJkkRH6XkGgfAA0lVexIlE1mMFVp4V7RBdxz/P9p7T8pSNsYdapFWvdT21Mib9w==}
'@oxfmt/binding-freebsd-x64@0.66.0':
resolution: {integrity: sha512-CR+x4VzMY0pRXLK/xFQ/RzsSFkP5t2Z2mef0QY6OP/rTRcMUoMLCOM62/3Fp/t0K+UDoBKxvMyeb6D0zPMjleA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [freebsd]
'@oxfmt/binding-linux-arm-gnueabihf@0.79.0':
resolution: {integrity: sha512-Pt35GoxiMUfnr+23cuzk07XQVvISDFxxPcp/aFVB87+RQvJoQaBo/XN7Re9XxgElvbELdyxTLnV9XM2aTfJeUA==}
'@oxfmt/binding-linux-arm-gnueabihf@0.66.0':
resolution: {integrity: sha512-ZEYmO/LbH9tTQCADILHGZE4GeOXOAj2VzedHkASNwjmwlwtutJCLpCJbIs37wRGTFgWRoEcD72jpMX+IBJUGjQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm]
os: [linux]
'@oxfmt/binding-linux-arm-musleabihf@0.79.0':
resolution: {integrity: sha512-zPi9Dni58VKp3r1QUcFvnbJNfBr49qyecq0vlM4SaX/MSjmguq77VngirghDua5tyhIDfqdUMTCK2KRlnZFp/g==}
'@oxfmt/binding-linux-arm-musleabihf@0.66.0':
resolution: {integrity: sha512-hNtR9/oU0CeTkq7JnRkmBQwqe17v2ZaAMLC4VcN7IIOWeRyWDk0knSPWS9iiLmtbZ2RRBBtsG01jQgkZmKCJeQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm]
os: [linux]
'@oxfmt/binding-linux-arm64-gnu@0.79.0':
resolution: {integrity: sha512-XhRehATEWjwX7VVEgDUD+7pfHYncQIJaEU0qsHvEKtu9XX0QYzcKvXhU9+URfiGX9WRh3wy2Ow+YCc3EeHtImg==}
'@oxfmt/binding-linux-arm64-gnu@0.66.0':
resolution: {integrity: sha512-uwOVQ8i6I1LT/+eDzfsgrrcZp8Fn6NPVUPn8fF5gdFGekFf0PddF+LEuwsD0/pbNUcKZhDj2rQ5UpITh9gF4iQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@oxfmt/binding-linux-arm64-musl@0.79.0':
resolution: {integrity: sha512-gbVjFZYug0MEyqvuTAzXGNxFJmBqBO32o1Fud1lG8bGs6oVz48ZtNQyEcAzqrOwaaG+Sxtv4gVzcsfht9aqmkg==}
'@oxfmt/binding-linux-arm64-musl@0.66.0':
resolution: {integrity: sha512-tTkF2Dmx4nGAjmBlZb+UtTGqR/EK4ZrW9qBfzte07a9XWqzoGGKzpFFlyNDhQe+Uwql94+ReCTeNbhOXscw1Dg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [musl]
'@oxfmt/binding-linux-ppc64-gnu@0.79.0':
resolution: {integrity: sha512-0N0sD3vnllyuiNh1r6zKvNXWE/CakcPKJAespg7XE2+sfvxpz5Q1iFah8sF5aedsOmVvbZaOPZcSHVmMosT1fA==}
'@oxfmt/binding-linux-ppc64-gnu@0.66.0':
resolution: {integrity: sha512-F3cKHUav4yXOHn6GFnwpBhSYsJOYKKf9eqO/9jlEuqPxNw9zb98E9ZFct79gcg8pibUGkbveEu9WDlmXJpDzKw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@oxfmt/binding-linux-riscv64-gnu@0.79.0':
resolution: {integrity: sha512-YtjqUHolcX6cv0ZMZuKQCM4H0ae/okcowy0wGcPHJk4O+8zjy3TvNhzDQ1/KGCkMJO8Fwulm1JcPJsraVJ3p+w==}
'@oxfmt/binding-linux-riscv64-gnu@0.66.0':
resolution: {integrity: sha512-K5fDaNZfDyQMYA/3qL21bqyN0X9T15LLwwbFPt2aHc94+ZG7bh0vZEsy2y7NlRnjjHFSwN+Hzg6ldJtbOriH4Q==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@oxfmt/binding-linux-riscv64-musl@0.79.0':
resolution: {integrity: sha512-H2gb9bEBr5tcdP5FU8JYTfgOavXDorWcAAlwci/zEKF2jzgh/oEr/SAw6aHB9n3FLEvnKvOh0A1fjku+vgYoUA==}
'@oxfmt/binding-linux-riscv64-musl@0.66.0':
resolution: {integrity: sha512-44Yc+I+qOmTElRcEhm5hUKIUJEQIOugymz4ua4tB0Wox7tGAfIbjzmXz/HDAtw1Ij6gmBwZlzh4hc9679RhWeA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
libc: [musl]
'@oxfmt/binding-linux-s390x-gnu@0.79.0':
resolution: {integrity: sha512-aZUbyWW5dSOxT/u6suWc4S9GVDt7YPPNMKQon+z79M8dpXmosadcFHAb7jBhpU7Hdsd2GN6/y3nd0JFTsGddZw==}
'@oxfmt/binding-linux-s390x-gnu@0.66.0':
resolution: {integrity: sha512-1e29Eg9hEj2kRBB19M0seIehPbbXHCk35GvImjDvb79rjjYjXCRmtbUNHJcgoktZAMIzXrTbxDBKmTc1V4bg3A==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@oxfmt/binding-linux-x64-gnu@0.79.0':
resolution: {integrity: sha512-5pW/ZHYfjjQ71gQR+EKzDz8ZzWIDHlTUtWtxVFNgZbKxVZnRxiSXVrllbjpJtx1q8VtSPZ+Lyg9BLny3yw+PTA==}
'@oxfmt/binding-linux-x64-gnu@0.66.0':
resolution: {integrity: sha512-vODY1UQo10gngn0+D4xHKU84F1Twm1LqrzV4SqPXvmQKSd87paehvZ6jqA5wKs6XQrlWul9clYMDVHcoW9CPMA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [glibc]
'@oxfmt/binding-linux-x64-musl@0.79.0':
resolution: {integrity: sha512-3IVUerTDB7Dvd90c1EurAzlVnlE9Azl7Wn8e33qX3wL/IqnslF+P7HvwkD+VeMbHxRtuw0EEBGSArZFXpUAZrQ==}
'@oxfmt/binding-linux-x64-musl@0.66.0':
resolution: {integrity: sha512-YDzXx2JsT4+HL4MdkVrYjO55NS5lUKNm8rLC4ZPou8+seu0v0jhecSh+ufoO6+xEa8gccEezMlI2WHJi4ApUgw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [musl]
'@oxfmt/binding-openharmony-arm64@0.79.0':
resolution: {integrity: sha512-C5QDgJBtu9+/2BQScoP7ynv54PLOqfoSqhRWwI0D0RPOwYD4tYj0TUdJbXMO1fNegL/5zJiSOxkq6II2xvttWg==}
'@oxfmt/binding-openharmony-arm64@0.66.0':
resolution: {integrity: sha512-mJjUYd8lj0+j4JkYyEM+5qKBf1Rnrpgjn/SVYKJhicVDqLz566ooa7Fs8zflPqt+dnZDV7X054rVIQX6ZcQNlQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [openharmony]
'@oxfmt/binding-win32-arm64-msvc@0.79.0':
resolution: {integrity: sha512-zlW1m8M49vNGgqQF/ze80KW8pZMicnW2XDZGBHuYtXTRYn4ewvgpqN9wwoqb6uLZZfb1R1zaQWKEB8cs7KYjwA==}
'@oxfmt/binding-win32-arm64-msvc@0.66.0':
resolution: {integrity: sha512-soV+0vESv7e5ntCHWC61x4gg8OSak6IHHnWsZmHrJFlvMj2AK+kmldErCNkVkrvc1Ts2/++rJXn+IuAb2WMXhw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [win32]
'@oxfmt/binding-win32-ia32-msvc@0.79.0':
resolution: {integrity: sha512-wbb7hFv2wK3SCTfu8dl1ydNsXM5dmH+PJMU3sojCkfKcG29VDpITL5/AtouCzXjkOc90QRkcAZcg36gP0KqoHA==}
'@oxfmt/binding-win32-ia32-msvc@0.66.0':
resolution: {integrity: sha512-YCPi23uRIEYuIKTZohAkKbPFpujQ5QBuUM5iDv+UqbCmTPAkaFsxjsSuB8xlBpRT0G7eP/4HMF+cPDSqHtOD9A==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ia32]
os: [win32]
'@oxfmt/binding-win32-x64-msvc@0.79.0':
resolution: {integrity: sha512-JLaeaQ+4LkQiVXY06JIV1dBFEDJzssvDieK/3Poi6CsY+c4UxghZVrrsfcKGJ5R/0F2Sw3C5Lf5Hu0sM5qJfPw==}
'@oxfmt/binding-win32-x64-msvc@0.66.0':
resolution: {integrity: sha512-bwTQcv/JVRPkOqQtMF0X7vpvpncDQiBcXHxZ9S2hR12Hlo8bvBdUR5x5XnxzDZ3kM0qoZw1rv7KaD66Ly+pFWA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [win32]
@@ -3895,8 +3898,8 @@ packages:
resolution: {integrity: sha512-GrwoxYN+uWlzO8uhUXRl0P+kHE4GtVPfYzVLcUxPL7KNdHKj66vvlhiweIHqYYXWlw+T8iLMp42Lm67ghw4WMQ==}
engines: {node: '>= 4'}
dompurify@3.4.18:
resolution: {integrity: sha512-ofe3wI/uNm68HInABYFJYqQxRw1EaKAjNdrFVKqjUY+UZurvNd2L/HuQe097s/4RivWiZyP6tT7aoT8atjfhwg==}
dompurify@3.4.12:
resolution: {integrity: sha512-zQvGet8Z2sWbQhCmfFz/T5QWH2oBmjnqK3qvOjaqaNLrLEF912WamU+ohnTp0TCep/MFVHpdJuCZEdFOdTnEFg==}
domutils@2.8.0:
resolution: {integrity: sha512-w96Cjofp72M5IIhpjgobBimYEfoPjx1Vx0BSX9P30WBdZW2WIKU0T1Bd0kz2eNZ9ikjKgHbEyKx8BB6H1L3h3A==}
@@ -4676,6 +4679,10 @@ packages:
resolution: {integrity: sha512-ja1E3yCr9i/0hmBVaM0bfwDjnGy8I/s6PP4DFp+yP+a+mrHO4Rm7DtmnqROTUkHIkqffC84YY7AeqX6oFk0WFg==}
engines: {node: '>=18'}
loglevel@1.9.1:
resolution: {integrity: sha512-hP3I3kCrDIMuRwAwHltphhDM1r8i55H33GgqjXbrisuJhF4kRhW1dNuxsRklp4bXl8DSdLaNLuiL4A/LWRfxvg==}
engines: {node: '>= 0.6.0'}
loglevel@1.9.2:
resolution: {integrity: sha512-HgMmCqIJSAKqo68l0rS2AanEWfkxaZ5wNiEFb5ggm08lDs9Xl2KxBlX3PTcaD2chBM1gXAYf491/M2Rv8Jwayg==}
engines: {node: '>= 0.6.0'}
@@ -4727,9 +4734,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/6c8b1b418189919bc69fd9df5e57354e7b3c39cb:
resolution: {gitHosted: true, tarball: https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/6c8b1b418189919bc69fd9df5e57354e7b3c39cb}
version: 45.1.0
matrix-js-sdk@https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/dc8610e796c92553c658300a4882dde961a0678a:
resolution: {gitHosted: true, integrity: sha512-Ldt/VkCzBtre6m1cn0FqgrzRV0GrgWIoARgQUQO58ef2Edu2ERFCINPzp/psFS5RwoN3RIy9Rm4oPVc1ATkEWA==, tarball: https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/dc8610e796c92553c658300a4882dde961a0678a}
version: 45.0.0
engines: {node: '>=22.0.0'}
matrix-widget-api@1.20.0:
@@ -4893,17 +4900,14 @@ packages:
oxc-resolver@11.21.2:
resolution: {integrity: sha512-w5tLwYN3Zo24w5EeWJjJWZOwhYqTtC8PS2B1tIt7BZUuqTIcU07sQValbDw+rq7+AuAGzOHklgK+ifsy4lpXfw==}
oxfmt@0.79.0:
resolution: {integrity: sha512-92iLHGxAgtYk6jLp/1ZBnEeABveNduHZgMDQj7tyqO9iafuJG3q+YHJq0R5Aa4YT+E6xswMQXdmPZYMwynS8ig==}
oxfmt@0.66.0:
resolution: {integrity: sha512-FfvqR8RFtV6JJpRrpkfqyVCQ7HDvZ/VriWFx7veftCgL1B5ZO9qNr+1rvPieycMQnNfVG0PWyJQiy7p0hq1I5w==}
engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true
peerDependencies:
'@astrojs/compiler-rs': ^0.5.0
svelte: ^5.0.0
vite-plus: '*'
peerDependenciesMeta:
'@astrojs/compiler-rs':
optional: true
svelte:
optional: true
vite-plus:
@@ -5787,8 +5791,8 @@ packages:
resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}
engines: {node: '>=12.0.0'}
tinypool@2.2.0:
resolution: {integrity: sha512-jBrmx4lYmaC9k/mgPbylxs7kBUxHtD8256up+HjLaDFfXScKJQyil+SWXSvhAtT7XHo+yTVlpB81PGmHP8oLSQ==}
tinypool@2.1.0:
resolution: {integrity: sha512-Pugqs6M0m7Lv1I7FtxN4aoyToKg1C4tu+/381vH35y8oENM/Ai7f7C4StcoK4/+BSw9ebcS8jRiVrORFKCALLw==}
engines: {node: ^20.0.0 || >=22.0.0}
tinyrainbow@2.0.0:
@@ -6916,6 +6920,11 @@ snapshots:
dependencies:
'@floating-ui/utils': 0.2.12
'@floating-ui/dom@1.7.6':
dependencies:
'@floating-ui/core': 1.8.0
'@floating-ui/utils': 0.2.12
'@floating-ui/dom@1.8.0':
dependencies:
'@floating-ui/core': 1.8.0
@@ -7149,11 +7158,11 @@ snapshots:
'@jridgewell/resolve-uri': 3.1.2
'@jridgewell/sourcemap-codec': 1.6.0
'@livekit/components-core@0.12.16(livekit-client@2.23.0(@types/dom-mediacapture-record@1.0.22))(tslib@2.8.1)':
'@livekit/components-core@0.12.15(livekit-client@2.23.0(@types/dom-mediacapture-record@1.0.22))(tslib@2.8.1)':
dependencies:
'@floating-ui/dom': 1.8.0
'@floating-ui/dom': 1.7.6
livekit-client: 2.23.0(@types/dom-mediacapture-record@1.0.22)
loglevel: 1.9.2
loglevel: 1.9.1
rxjs: 7.8.2
tslib: 2.8.1
@@ -7169,7 +7178,7 @@ snapshots:
'@types/dom-mediacapture-transform': 0.1.11
livekit-client: 2.23.0(@types/dom-mediacapture-record@1.0.22)
'@matrix-org/matrix-sdk-crypto-wasm@18.9.2': {}
'@matrix-org/matrix-sdk-crypto-wasm@18.9.0': {}
'@mdx-js/react@3.1.1(@types/react@19.2.18)(react@19.3.1)':
dependencies:
@@ -7467,61 +7476,61 @@ snapshots:
'@oxc-resolver/binding-win32-x64-msvc@11.21.2':
optional: true
'@oxfmt/binding-android-arm-eabi@0.79.0':
'@oxfmt/binding-android-arm-eabi@0.66.0':
optional: true
'@oxfmt/binding-android-arm64@0.79.0':
'@oxfmt/binding-android-arm64@0.66.0':
optional: true
'@oxfmt/binding-darwin-arm64@0.79.0':
'@oxfmt/binding-darwin-arm64@0.66.0':
optional: true
'@oxfmt/binding-darwin-x64@0.79.0':
'@oxfmt/binding-darwin-x64@0.66.0':
optional: true
'@oxfmt/binding-freebsd-x64@0.79.0':
'@oxfmt/binding-freebsd-x64@0.66.0':
optional: true
'@oxfmt/binding-linux-arm-gnueabihf@0.79.0':
'@oxfmt/binding-linux-arm-gnueabihf@0.66.0':
optional: true
'@oxfmt/binding-linux-arm-musleabihf@0.79.0':
'@oxfmt/binding-linux-arm-musleabihf@0.66.0':
optional: true
'@oxfmt/binding-linux-arm64-gnu@0.79.0':
'@oxfmt/binding-linux-arm64-gnu@0.66.0':
optional: true
'@oxfmt/binding-linux-arm64-musl@0.79.0':
'@oxfmt/binding-linux-arm64-musl@0.66.0':
optional: true
'@oxfmt/binding-linux-ppc64-gnu@0.79.0':
'@oxfmt/binding-linux-ppc64-gnu@0.66.0':
optional: true
'@oxfmt/binding-linux-riscv64-gnu@0.79.0':
'@oxfmt/binding-linux-riscv64-gnu@0.66.0':
optional: true
'@oxfmt/binding-linux-riscv64-musl@0.79.0':
'@oxfmt/binding-linux-riscv64-musl@0.66.0':
optional: true
'@oxfmt/binding-linux-s390x-gnu@0.79.0':
'@oxfmt/binding-linux-s390x-gnu@0.66.0':
optional: true
'@oxfmt/binding-linux-x64-gnu@0.79.0':
'@oxfmt/binding-linux-x64-gnu@0.66.0':
optional: true
'@oxfmt/binding-linux-x64-musl@0.79.0':
'@oxfmt/binding-linux-x64-musl@0.66.0':
optional: true
'@oxfmt/binding-openharmony-arm64@0.79.0':
'@oxfmt/binding-openharmony-arm64@0.66.0':
optional: true
'@oxfmt/binding-win32-arm64-msvc@0.79.0':
'@oxfmt/binding-win32-arm64-msvc@0.66.0':
optional: true
'@oxfmt/binding-win32-ia32-msvc@0.79.0':
'@oxfmt/binding-win32-ia32-msvc@0.66.0':
optional: true
'@oxfmt/binding-win32-x64-msvc@0.79.0':
'@oxfmt/binding-win32-x64-msvc@0.66.0':
optional: true
'@oxlint-tsgolint/darwin-arm64@0.25.0':
@@ -9506,7 +9515,7 @@ snapshots:
dependencies:
domelementtype: 2.3.0
dompurify@3.4.18:
dompurify@3.4.12:
optionalDependencies:
'@types/trusted-types': 2.0.7
@@ -10020,7 +10029,7 @@ snapshots:
i18next-resources-for-ts@2.1.0:
dependencies:
'@babel/runtime': 7.29.10
'@babel/runtime': 7.29.7
'@swc/core': 1.16.2
chokidar: 5.0.0
yaml: 2.9.0
@@ -10354,6 +10363,8 @@ snapshots:
is-unicode-supported: 2.1.0
yoctocolors: 2.2.0
loglevel@1.9.1: {}
loglevel@1.9.2: {}
loupe@3.2.1: {}
@@ -10402,10 +10413,10 @@ snapshots:
matrix-events-sdk@0.0.1: {}
matrix-js-sdk@https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/6c8b1b418189919bc69fd9df5e57354e7b3c39cb:
matrix-js-sdk@https://codeload.github.com/matrix-org/matrix-js-sdk/tar.gz/dc8610e796c92553c658300a4882dde961a0678a:
dependencies:
'@babel/runtime': 8.0.8
'@matrix-org/matrix-sdk-crypto-wasm': 18.9.2
'@matrix-org/matrix-sdk-crypto-wasm': 18.9.0
another-json: 0.2.0
bs58: 6.0.0
content-type: 3.1.1
@@ -10663,29 +10674,29 @@ snapshots:
'@oxc-resolver/binding-win32-arm64-msvc': 11.21.2
'@oxc-resolver/binding-win32-x64-msvc': 11.21.2
oxfmt@0.79.0:
oxfmt@0.66.0:
dependencies:
tinypool: 2.2.0
tinypool: 2.1.0
optionalDependencies:
'@oxfmt/binding-android-arm-eabi': 0.79.0
'@oxfmt/binding-android-arm64': 0.79.0
'@oxfmt/binding-darwin-arm64': 0.79.0
'@oxfmt/binding-darwin-x64': 0.79.0
'@oxfmt/binding-freebsd-x64': 0.79.0
'@oxfmt/binding-linux-arm-gnueabihf': 0.79.0
'@oxfmt/binding-linux-arm-musleabihf': 0.79.0
'@oxfmt/binding-linux-arm64-gnu': 0.79.0
'@oxfmt/binding-linux-arm64-musl': 0.79.0
'@oxfmt/binding-linux-ppc64-gnu': 0.79.0
'@oxfmt/binding-linux-riscv64-gnu': 0.79.0
'@oxfmt/binding-linux-riscv64-musl': 0.79.0
'@oxfmt/binding-linux-s390x-gnu': 0.79.0
'@oxfmt/binding-linux-x64-gnu': 0.79.0
'@oxfmt/binding-linux-x64-musl': 0.79.0
'@oxfmt/binding-openharmony-arm64': 0.79.0
'@oxfmt/binding-win32-arm64-msvc': 0.79.0
'@oxfmt/binding-win32-ia32-msvc': 0.79.0
'@oxfmt/binding-win32-x64-msvc': 0.79.0
'@oxfmt/binding-android-arm-eabi': 0.66.0
'@oxfmt/binding-android-arm64': 0.66.0
'@oxfmt/binding-darwin-arm64': 0.66.0
'@oxfmt/binding-darwin-x64': 0.66.0
'@oxfmt/binding-freebsd-x64': 0.66.0
'@oxfmt/binding-linux-arm-gnueabihf': 0.66.0
'@oxfmt/binding-linux-arm-musleabihf': 0.66.0
'@oxfmt/binding-linux-arm64-gnu': 0.66.0
'@oxfmt/binding-linux-arm64-musl': 0.66.0
'@oxfmt/binding-linux-ppc64-gnu': 0.66.0
'@oxfmt/binding-linux-riscv64-gnu': 0.66.0
'@oxfmt/binding-linux-riscv64-musl': 0.66.0
'@oxfmt/binding-linux-s390x-gnu': 0.66.0
'@oxfmt/binding-linux-x64-gnu': 0.66.0
'@oxfmt/binding-linux-x64-musl': 0.66.0
'@oxfmt/binding-openharmony-arm64': 0.66.0
'@oxfmt/binding-win32-arm64-msvc': 0.66.0
'@oxfmt/binding-win32-ia32-msvc': 0.66.0
'@oxfmt/binding-win32-x64-msvc': 0.66.0
oxlint-tsgolint@0.25.0:
optionalDependencies:
@@ -11087,7 +11098,7 @@ snapshots:
'@posthog/core': 1.46.4
'@posthog/types': 1.400.0
core-js: 3.49.0
dompurify: 3.4.18
dompurify: 3.4.12
fflate: 0.4.8
preact: 10.29.8
query-selector-shadow-dom: 1.0.1
@@ -11203,7 +11214,7 @@ snapshots:
react-i18next@17.0.13(i18next@26.4.1(typescript@5.9.3))(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(typescript@5.9.3):
dependencies:
'@babel/runtime': 7.29.10
'@babel/runtime': 7.29.7
html-parse-stringify: 4.0.1
i18next: 26.4.1(typescript@5.9.3)
react: 19.2.8
@@ -11660,7 +11671,7 @@ snapshots:
fdir: 6.5.0(picomatch@4.0.5)
picomatch: 4.0.5
tinypool@2.2.0: {}
tinypool@2.1.0: {}
tinyrainbow@2.0.0: {}
+1 -4
View File
@@ -59,7 +59,4 @@ overrides:
# - https://github.com/element-hq/element-call/security/dependabot/196
# - https://github.com/element-hq/element-call/security/dependabot/195
# - https://github.com/element-hq/element-call/security/dependabot/193
# - https://github.com/advisories/GHSA-cg2g-xh64-v4q7
# - https://github.com/advisories/GHSA-mrv2-3pqr-j5jr
# - https://github.com/advisories/GHSA-c6gr-qvv4-5v3f
"dompurify": "^3.4.17"
"dompurify": "^3.4.11"
+3 -5
View File
@@ -5,7 +5,7 @@
"schedule:monthly",
":enableVulnerabilityAlertsWithLabel(security)"
],
"labels": ["dependencies"],
"addLabels": ["dependencies"],
"minimumReleaseAge": "5 days",
"packageRules": [
{
@@ -16,8 +16,7 @@
{
"groupName": "GitHub Actions",
"matchDepTypes": ["action"],
"pinDigests": true,
"labels": ["PR-Task"]
"pinDigests": true
},
{
"description": "Disable Renovate for packages we want to monitor ourselves",
@@ -70,8 +69,7 @@
"matchUpdateTypes": ["digest"],
"schedule": ["* 0-3 * * *"],
"minimumReleaseAge": null,
"automerge": true,
"labels": ["PR-Task"]
"automerge": true
}
],
"semanticCommits": "disabled",
+9 -11
View File
@@ -128,22 +128,20 @@ export async function createMatrixRTCSdk(
});
vm = createCallViewModel$(
scope,
{
rtcParticipation: participation,
matrixRoom: room,
mediaDevices,
muteStates,
encryptionSystem,
// The bundle owns its page, so the body is the space it has
viewSize$: scope.behavior(observeElementSize$(document.body)),
handsRaisedSubject$: of({}),
reactionsSubject$: of({}),
},
participation,
room,
mediaDevices,
muteStates,
{
...callViewModelOptionsFromParams(urlParams),
encryptionSystem,
capture,
hostBridge,
// The bundle owns its page, so the body is the space it has
windowSize$: scope.behavior(observeElementSize$(document.body)),
},
of({}),
of({}),
);
// Once the hang-up has gone through, unstick and ask the host to close us
vm.leave$
+1 -3
View File
@@ -634,9 +634,7 @@ export type MediaSource =
| "unknown";
export type MediaStreamStats =
| RTCInboundRtpStreamStats
| RTCOutboundRtpStreamStats
| undefined;
RTCInboundRtpStreamStats | RTCOutboundRtpStreamStats | undefined;
/** One published track of a member. */
export interface MediaTrack {
-10
View File
@@ -152,15 +152,6 @@ describe("createLocalMedia", () => {
});
});
// As the built-in camera of a Mac
it("takes a camera that doesn't say which way it faces to face the user", async () => {
const media = createLocalMedia(fakeGetUserMedia());
const [camera] = (await media.capture([{ source: "camera" }])) as [
LocalVideoMediaTrack,
];
expect(camera.facingMode$.value).toBe("user");
});
it("releases one device and stops the rest", async () => {
const media = createLocalMedia(fakeGetUserMedia());
const [microphone, camera] = await media.capture([
@@ -207,7 +198,6 @@ function fakeTrack(
const track = {
kind,
id: `${kind}-${nextId++}`,
label: "",
enabled: true,
stop: vi.fn(),
getSettings: () => settings,
+15 -4
View File
@@ -19,7 +19,6 @@ import {
type VideoProcessor,
} from "./media-api";
import { constant } from "./reactive/Behavior";
import { facingModeOf } from "./utils/facingMode";
import { inTurn } from "./utils/processorTurns";
type Source = "microphone" | "camera";
@@ -162,7 +161,9 @@ function trackConstraints(request: Request): MediaTrackConstraints {
class CapturedTrack {
public readonly mediaTrack: LocalAudioMediaTrack | LocalVideoMediaTrack;
private readonly muted$ = new BehaviorSubject(false);
private readonly facingMode$: BehaviorSubject<"user" | "environment">;
private readonly facingMode$: BehaviorSubject<
"user" | "environment" | undefined
>;
private readonly elements = new Set<HTMLMediaElement>();
private processor: HandedOverTrack["processor"];
/** What the processor reads frames from; a processor needs a playing element. */
@@ -305,9 +306,10 @@ class CapturedTrack {
kind: "video",
facingMode$: this.facingMode$,
switchFacingMode: async () => {
const facingMode = this.facingMode$.value;
if (facingMode === undefined) return;
await this.reacquire({
facingMode:
this.facingMode$.value === "user" ? "environment" : "user",
facingMode: facingMode === "user" ? "environment" : "user",
});
return this.track.getSettings().deviceId;
},
@@ -323,3 +325,12 @@ function play(element: HTMLMediaElement, track: MediaStreamTrack): void {
const playing = element.play() as Promise<void> | undefined;
playing?.catch(() => undefined);
}
function facingModeOf(
track: MediaStreamTrack,
): "user" | "environment" | undefined {
const { facingMode } = track.getSettings();
return facingMode === "user" || facingMode === "environment"
? facingMode
: undefined;
}
+2 -2
View File
@@ -140,8 +140,8 @@ function setup(
getDeviceId: () => deviceId,
getDomain: () => "example.org",
getSyncState: () => SyncState.Syncing,
getRTCTransports: vi.fn().mockResolvedValue(homeserverTransports),
getLivekitToken: vi.fn().mockResolvedValue({ jwt: publisherJWT }),
_unstable_getRTCTransports: vi.fn().mockResolvedValue(homeserverTransports),
_unstable_getLivekitToken: vi.fn().mockResolvedValue({ jwt: publisherJWT }),
} as unknown as MatrixClient;
const members$ = new BehaviorSubject<RTCMember[]>([]);
+2 -2
View File
@@ -31,7 +31,7 @@ function client(
): Parameters<typeof discoverLocalTransport>[0] {
return {
getDomain: () => "example.org",
getRTCTransports: vi.fn().mockResolvedValue(advertised),
_unstable_getRTCTransports: vi.fn().mockResolvedValue(advertised),
};
}
@@ -54,7 +54,7 @@ describe("discoverLocalTransport", () => {
logger,
),
).resolves.toBe(hostTransport);
expect(c.getRTCTransports).not.toHaveBeenCalled();
expect(c._unstable_getRTCTransports).not.toHaveBeenCalled();
});
it("prefers the homeserver's transport over the host's fallback", async () => {
+1 -1
View File
@@ -22,7 +22,7 @@ import { TransportAutoDiscovery } from "./TransportAutoDiscovery";
* @throws {MatrixRTCTransportMissingError} where none of these exists.
*/
export async function discoverLocalTransport(
client: Pick<MatrixClient, "getDomain" | "getRTCTransports">,
client: Pick<MatrixClient, "getDomain" | "_unstable_getRTCTransports">,
transportTypes: readonly string[],
{
transport: override,
@@ -36,7 +36,11 @@ const configTransport: Transport = {
function makeClient(): MockedObject<DiscoveryClient> {
return {
getRTCTransports: vi.fn().mockResolvedValue([]),
getDomain: vi.fn().mockReturnValue("example.org"),
baseUrl: "https://matrix.example.org",
_unstable_getRTCTransports: vi.fn().mockResolvedValue([]),
getOpenIdToken: vi.fn(),
getDeviceId: vi.fn(),
} as unknown as MockedObject<DiscoveryClient>;
}
@@ -53,7 +57,7 @@ describe("TransportAutoDiscovery", () => {
"prefers backend transport other app config $transports",
async ({ transports }) => {
const client = makeClient();
client.getRTCTransports.mockResolvedValue(transports);
client._unstable_getRTCTransports.mockResolvedValue(transports);
const discovery = new TransportAutoDiscovery({
client,
@@ -67,7 +71,7 @@ describe("TransportAutoDiscovery", () => {
expect(discoveredTransport).toStrictEqual(backendTransport);
expect(discoveredTransport).not.toStrictEqual(configTransport);
expect(client.getRTCTransports).toHaveBeenCalledTimes(1);
expect(client._unstable_getRTCTransports).toHaveBeenCalledTimes(1);
},
);
@@ -77,7 +81,10 @@ describe("TransportAutoDiscovery", () => {
url: "wss://sfu.example.org",
};
const client = makeClient();
client.getRTCTransports.mockResolvedValue([backendTransport, mLivekit]);
client._unstable_getRTCTransports.mockResolvedValue([
backendTransport,
mLivekit,
]);
const discovery = new TransportAutoDiscovery({
client,
@@ -93,7 +100,7 @@ describe("TransportAutoDiscovery", () => {
it("Retries limit_exceeded backend transport", async () => {
const client = makeClient();
client.getRTCTransports
client._unstable_getRTCTransports
.mockRejectedValueOnce(
new MatrixError(
{
@@ -117,7 +124,7 @@ describe("TransportAutoDiscovery", () => {
backendTransport,
);
expect(client.getRTCTransports).toHaveBeenCalledTimes(2);
expect(client._unstable_getRTCTransports).toHaveBeenCalledTimes(2);
});
const INVALID_TEST_CASES: Array<{ transports: Transport[] }> = [
@@ -128,7 +135,7 @@ describe("TransportAutoDiscovery", () => {
"falls back to config when backend has no (valid) livekit transports $transports",
async ({ transports }) => {
const client = makeClient();
client.getRTCTransports.mockResolvedValue(transports);
client._unstable_getRTCTransports.mockResolvedValue(transports);
const discovery = new TransportAutoDiscovery({
client,
@@ -145,7 +152,7 @@ describe("TransportAutoDiscovery", () => {
it("returns null when backend and config are all unavailable", async () => {
const client = makeClient();
client.getRTCTransports.mockResolvedValue([]);
client._unstable_getRTCTransports.mockResolvedValue([]);
const discovery = new TransportAutoDiscovery({
client,
+5 -2
View File
@@ -10,7 +10,10 @@ import { type Logger } from "matrix-js-sdk/lib/logger";
import { doNetworkOperationWithRetry } from "../utils/network";
type TransportDiscoveryClient = Pick<MatrixClient, "getRTCTransports">;
type TransportDiscoveryClient = Pick<
MatrixClient,
"getDomain" | "_unstable_getRTCTransports"
>;
export interface TransportAutoDiscoveryProps {
client: TransportDiscoveryClient;
@@ -71,7 +74,7 @@ export class TransportAutoDiscovery {
this.logger.info("First try to use getRTCTransports end point ...");
try {
const transportList = await doNetworkOperationWithRetry(async () =>
client.getRTCTransports(),
client._unstable_getRTCTransports(),
);
for (const type of this.transportTypes) {
const first = transportList.find(
+2 -6
View File
@@ -151,16 +151,12 @@ export interface LocalAudioMediaTrack
extends AudioMediaTrack, LocalMediaTrack {}
export interface LocalVideoMediaTrack extends VideoMediaTrack, LocalMediaTrack {
/**
* For mirroring. A camera that does not say which way it faces is taken to
* face the user, unless it is known to film the room, as a phone used as a
* webcam. Undefined while there is no camera track.
*/
/** For mirroring; undefined where the camera does not say which way it faces. */
facingMode$: Behavior<"user" | "environment" | undefined>;
/**
* Restarts the camera facing the other way, on devices with a front and a
* back camera, and resolves with the id of the device now in use. Does
* nothing while there is no camera track.
* nothing where the facing mode is unknown.
*/
switchFacingMode(): Promise<string | undefined>;
/** Background blur and the like; undefined removes the processor. */
@@ -92,7 +92,7 @@ function setupTest(): void {
matrix_server_name: "example.org",
expires_in: 3600,
}),
getLivekitToken: vi.fn().mockResolvedValue({ jwt: testJWTToken }),
_unstable_getLivekitToken: vi.fn().mockResolvedValue({ jwt: testJWTToken }),
});
localParticipantEventEmiter = new EventEmitter();
@@ -191,7 +191,7 @@ describe("Start connection states", () => {
const deferred = Promise.withResolvers<LivekitGetTokenResponse>();
client.getLivekitToken.mockImplementation(
client._unstable_getLivekitToken.mockImplementation(
async (): Promise<LivekitGetTokenResponse> => {
return await deferred.promise;
},
@@ -235,7 +235,7 @@ describe("Start connection states", () => {
onTestFinished(() => s.unsubscribe());
const deferredSFU = Promise.withResolvers<void>();
client.getLivekitToken.mockImplementation(async () => {
client._unstable_getLivekitToken.mockImplementation(async () => {
await deferredSFU.promise;
throw new MatrixError(
{
@@ -378,7 +378,7 @@ describe("Start connection states", () => {
await connection.start();
expect(client.getLivekitToken).not.toHaveBeenCalled();
expect(client._unstable_getLivekitToken).not.toHaveBeenCalled();
expect(fetchMock.called(`${serviceUrl}/sfu/get`)).toBe(true);
expect(fakeLivekitRoom.connect).toHaveBeenCalledWith(
"wss://sfu",
@@ -33,7 +33,7 @@ const urlTransport: UnstableLivekitTransport = {
function client(): ClientGetTokenParts & ClientOpenIDParts {
return {
getOpenIdToken: vi.fn(),
getLivekitToken: vi.fn().mockResolvedValue({ jwt: testJWTToken }),
_unstable_getLivekitToken: vi.fn().mockResolvedValue({ jwt: testJWTToken }),
};
}
@@ -160,8 +160,8 @@ describe("createLivekitBackend", () => {
const client = {
baseUrl: homeserver,
getOpenIdToken: vi.fn(),
getLivekitToken: vi.fn(),
delegateDelayedLeave: vi.fn(),
_unstable_getLivekitToken: vi.fn(),
_unstable_delegateDelayedLeave: vi.fn(),
};
/** The connections the stubbed factory handed out, with their participants to drive. */
let connections: {
@@ -73,7 +73,10 @@ export interface LivekitBackendOptions {
*/
client: Pick<
MatrixClient,
"getOpenIdToken" | "getLivekitToken" | "delegateDelayedLeave" | "baseUrl"
| "getOpenIdToken"
| "_unstable_getLivekitToken"
| "_unstable_delegateDelayedLeave"
| "baseUrl"
>;
mediaQuality?: MediaQuality;
}
@@ -18,7 +18,15 @@ import {
TrackEvent,
type TrackPublication,
} from "livekit-client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
afterEach,
beforeEach,
describe,
expect,
it,
onTestFinished,
vi,
} from "vitest";
import { ObservableScope } from "../../reactive/ObservableScope";
import {
@@ -225,6 +233,10 @@ describe("createLivekitMediaTrack", () => {
])(
"leaves a processed camera alone unless its device changes: $deviceId",
async ({ deviceId, switches }) => {
vi.stubGlobal("MediaStreamTrack", class {});
onTestFinished(() => {
vi.unstubAllGlobals();
});
const camera = Object.assign(Object.create(LocalVideoTrack.prototype), {
source: Track.Source.Camera,
_mediaStreamTrack: {
@@ -258,41 +270,6 @@ describe("createLivekitMediaTrack", () => {
},
);
it("takes the facing mode of a processed camera from the camera", async () => {
const source = {
readyState: "live",
label: "Back Camera",
getSettings: () => ({ facingMode: "environment" }),
};
const camera = Object.assign(Object.create(LocalVideoTrack.prototype), {
source: Track.Source.Camera,
_mediaStreamTrack: source,
mediaStream: { getVideoTracks: () => [source] },
processor: {
processedTrack: { label: "", getSettings: () => ({}) },
},
restartTrack: vi.fn().mockResolvedValue(undefined),
}) as LocalVideoTrack;
const { participant, publication, room } = fakes({
track: camera as unknown as FakeTrack,
});
const track = createLocalLivekitMediaTrack(
scope,
Object.assign(participant, {
isLocal: true,
}) as unknown as LocalParticipant,
publication as unknown as TrackPublication,
room,
vi.fn(),
) as LocalVideoMediaTrack;
expect(track.facingMode$.value).toBe("environment");
await track.switchFacingMode();
expect(camera.restartTrack).toHaveBeenCalledExactlyOnceWith({
facingMode: "user",
});
});
// LiveKit stops a camera that is turned off; the processor is built when it
// is turned on again
it.each([
@@ -302,6 +279,10 @@ describe("createLivekitMediaTrack", () => {
"gives a processor to a camera that $state: $takes",
async ({ isMuted, takes }) => {
// jsdom has none; LiveKit's facing mode checks against it
vi.stubGlobal("MediaStreamTrack", class {});
onTestFinished(() => {
vi.unstubAllGlobals();
});
const camera = Object.assign(Object.create(LocalVideoTrack.prototype), {
isMuted,
_mediaStreamTrack: {
@@ -11,6 +11,7 @@ import {
roomEventSelector,
} from "@livekit/components-core";
import {
facingModeFromLocalTrack,
type LocalParticipant,
LocalTrack,
LocalVideoTrack,
@@ -49,7 +50,6 @@ import {
type VideoMediaTrack,
} from "../../media-api";
import { MatrixRTCError } from "../../errors";
import { facingModeOf } from "../../utils/facingMode";
import { toLivekitProcessor, type LivekitProcessor } from "./videoProcessor";
export const mediaSources: Record<Track.Source, MediaSource> = {
@@ -231,9 +231,10 @@ export function createLocalLivekitMediaTrack(
switchFacingMode: async () => {
const track = videoTrack();
if (!track) return;
const { facingMode } = facingModeFromLocalTrack(track);
if (facingMode !== "user" && facingMode !== "environment") return;
await track.restartTrack({
facingMode:
facingModeOf(sourceTrack(track)) === "user" ? "environment" : "user",
facingMode: facingMode === "user" ? "environment" : "user",
});
return track.mediaStreamTrack.getSettings().deviceId;
},
@@ -287,14 +288,6 @@ async function rtpStreamStats(
return undefined;
}
/**
* The camera's own track. While a processor runs LiveKit's media stream track
* is the processed one, which says nothing of the camera.
*/
function sourceTrack(track: LocalVideoTrack): MediaStreamTrack {
return track.mediaStream?.getVideoTracks()[0] ?? track.mediaStreamTrack;
}
function facingMode$(
scope: ObservableScope,
track$: Behavior<Track | undefined>,
@@ -305,7 +298,12 @@ function facingMode$(
if (!(track instanceof LocalVideoTrack)) return of(undefined);
return fromEvent(track, TrackEvent.Restarted).pipe(
startWith(null),
map(() => facingModeOf(sourceTrack(track))),
map(() => {
const { facingMode } = facingModeFromLocalTrack(track);
return facingMode === "user" || facingMode === "environment"
? facingMode
: undefined;
}),
);
}),
),
@@ -84,7 +84,7 @@ describe("findRemotePublishLivekitTransport", () => {
beforeEach(() => {
client = {
getLivekitToken: vi
_unstable_getLivekitToken: vi
.fn()
.mockResolvedValue({ jwt: jwtWithPublishGrant(true) }),
};
@@ -92,8 +92,8 @@ describe("findRemotePublishLivekitTransport", () => {
it("publishes on the oldest member's SFU with its server_name", async () => {
await expect(find([carol, bob])).resolves.toEqual(bobsTransport);
expect(client.getLivekitToken).toHaveBeenCalledTimes(1);
expect(client.getLivekitToken).toHaveBeenCalledWith({
expect(client._unstable_getLivekitToken).toHaveBeenCalledTimes(1);
expect(client._unstable_getLivekitToken).toHaveBeenCalledWith({
url: "wss://sfu.bob.com",
server_name: "bob.com",
room_id: "!room:example.org",
@@ -103,68 +103,70 @@ describe("findRemotePublishLivekitTransport", () => {
});
it("asks about an SFU once however many members are on it", async () => {
client.getLivekitToken.mockResolvedValue({
client._unstable_getLivekitToken.mockResolvedValue({
jwt: jwtWithPublishGrant(false),
});
await expect(find([dave, bobsLaptop, bob])).resolves.toBeNull();
expect(client.getLivekitToken).toHaveBeenCalledTimes(1);
expect(client._unstable_getLivekitToken).toHaveBeenCalledTimes(1);
});
it("skips our own membership", async () => {
await expect(find([ourselves, bob])).resolves.toEqual(bobsTransport);
expect(client.getLivekitToken).toHaveBeenCalledTimes(1);
expect(client._unstable_getLivekitToken).toHaveBeenCalledTimes(1);
});
it("ignores members publishing through a legacy JWT service", async () => {
await expect(find([legacyErin, bob])).resolves.toEqual(bobsTransport);
expect(client.getLivekitToken).toHaveBeenCalledTimes(1);
expect(client._unstable_getLivekitToken).toHaveBeenCalledTimes(1);
});
it("moves on when a homeserver does not let us publish", async () => {
client.getLivekitToken.mockImplementation(async ({ server_name }) =>
Promise.resolve({
jwt: jwtWithPublishGrant(server_name === "carol.com"),
}),
client._unstable_getLivekitToken.mockImplementation(
async ({ server_name }) =>
Promise.resolve({
jwt: jwtWithPublishGrant(server_name === "carol.com"),
}),
);
await expect(find([bob, carol])).resolves.toEqual(carolsTransport);
expect(client.getLivekitToken).toHaveBeenCalledTimes(2);
expect(client._unstable_getLivekitToken).toHaveBeenCalledTimes(2);
});
it("moves on when a homeserver refuses to issue a token", async () => {
client.getLivekitToken.mockImplementation(async ({ server_name }) =>
server_name === "bob.com"
? Promise.reject(
new MatrixError(
{ errcode: "M_FORBIDDEN", error: "Not joined" },
403,
),
)
: Promise.resolve({ jwt: jwtWithPublishGrant(true) }),
client._unstable_getLivekitToken.mockImplementation(
async ({ server_name }) =>
server_name === "bob.com"
? Promise.reject(
new MatrixError(
{ errcode: "M_FORBIDDEN", error: "Not joined" },
403,
),
)
: Promise.resolve({ jwt: jwtWithPublishGrant(true) }),
);
await expect(find([bob, carol])).resolves.toEqual(carolsTransport);
});
it("finds nothing once all candidates are exhausted", async () => {
client.getLivekitToken.mockResolvedValue({
client._unstable_getLivekitToken.mockResolvedValue({
jwt: jwtWithPublishGrant(false),
});
await expect(find([bob, carol])).resolves.toBeNull();
expect(client.getLivekitToken).toHaveBeenCalledTimes(2);
expect(client._unstable_getLivekitToken).toHaveBeenCalledTimes(2);
});
it("gives up immediately if our homeserver lacks the CS API", async () => {
client.getLivekitToken.mockRejectedValue(csApiMissing);
client._unstable_getLivekitToken.mockRejectedValue(csApiMissing);
await expect(find([bob, carol])).resolves.toBeNull();
expect(client.getLivekitToken).toHaveBeenCalledTimes(1);
expect(client._unstable_getLivekitToken).toHaveBeenCalledTimes(1);
});
it("finds nothing where there are no other members", async () => {
await expect(find([ourselves])).resolves.toBeNull();
expect(client.getLivekitToken).not.toHaveBeenCalled();
expect(client._unstable_getLivekitToken).not.toHaveBeenCalled();
});
});
+7 -4
View File
@@ -20,7 +20,10 @@ function isNetworkError(e: unknown): boolean {
return e instanceof HTTPError || e instanceof ConnectionError;
}
export type ClientGetTokenParts = Pick<MatrixClient, "getLivekitToken">;
export type ClientGetTokenParts = Pick<
MatrixClient,
"_unstable_getLivekitToken"
>;
export interface GetSFUConfigParams {
client: ClientGetTokenParts;
@@ -45,7 +48,7 @@ export async function getSFUConfig({
}: GetSFUConfigParams): Promise<SFUConfig> {
const res = await doNetworkOperationWithRetry(
async () =>
client.getLivekitToken({
client._unstable_getLivekitToken({
url,
server_name: serverName,
room_id: roomId,
@@ -59,7 +62,7 @@ export async function getSFUConfig({
export type ClientDelegationParts = Pick<
MatrixClient,
"delegateDelayedLeave" | "baseUrl"
"_unstable_delegateDelayedLeave" | "baseUrl"
>;
export interface DelegateDelayedLeaveParams {
@@ -87,7 +90,7 @@ export async function delegateDelayedLeave({
}: DelegateDelayedLeaveParams): Promise<void> {
await doNetworkOperationWithRetry(
async () =>
client.delegateDelayedLeave({
client._unstable_delegateDelayedLeave({
url,
room_id: roomId,
slot_id: slotId,
@@ -33,8 +33,8 @@ const client: Mocked<
openID.ClientOpenIDParts
> = {
baseUrl: "https://matrix.example.org",
getLivekitToken: vi.fn().mockResolvedValue({ jwt: csApiJWTToken }),
delegateDelayedLeave: vi.fn().mockResolvedValue({}),
_unstable_getLivekitToken: vi.fn().mockResolvedValue({ jwt: csApiJWTToken }),
_unstable_delegateDelayedLeave: vi.fn().mockResolvedValue({}),
getOpenIdToken: vi
.fn()
.mockResolvedValue({ access_token: "mock-openID-token" }),
@@ -110,7 +110,7 @@ describe("getSFUConfig", () => {
livekitAlias: "via CS API",
}),
);
expect(client.getLivekitToken).toHaveBeenCalledWith({
expect(client._unstable_getLivekitToken).toHaveBeenCalledWith({
url: urlTransport.url,
server_name: "example.org",
room_id: roomId,
@@ -122,11 +122,11 @@ describe("getSFUConfig", () => {
it("does not fall back to OpenID with url transport", async () => {
mockJWTService();
client.getLivekitToken.mockRejectedValueOnce(unsupportedError);
client._unstable_getLivekitToken.mockRejectedValueOnce(unsupportedError);
await expect(
getSFUConfig({ ...defaultParams, transport: urlTransport }),
).rejects.toThrow(expect.any(NoMatrix2AuthorizationService));
expect(client.getLivekitToken).toHaveBeenCalled();
expect(client._unstable_getLivekitToken).toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual([]);
});
@@ -140,7 +140,7 @@ describe("getSFUConfig", () => {
livekitAlias: "via default endpoint",
}),
);
expect(client.getLivekitToken).not.toHaveBeenCalled();
expect(client._unstable_getLivekitToken).not.toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual(["/get_token"]);
});
@@ -157,7 +157,7 @@ describe("getSFUConfig", () => {
livekitAlias: "via default endpoint",
}),
);
expect(client.getLivekitToken).not.toHaveBeenCalled();
expect(client._unstable_getLivekitToken).not.toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual(["/get_token"]);
});
@@ -166,7 +166,7 @@ describe("getSFUConfig", () => {
const error = new Error(
"The rtc_livekit_get_token action is not supported by the client.",
);
client.getLivekitToken.mockRejectedValueOnce(error);
client._unstable_getLivekitToken.mockRejectedValueOnce(error);
await expect(
getSFUConfig({ ...defaultParams, transport: urlTransport }),
).rejects.toThrow(error);
@@ -182,13 +182,13 @@ describe("getSFUConfig", () => {
role: "publisher",
}),
).toEqual(expect.objectContaining({ jwt: csApiJWTToken }));
expect(client.getLivekitToken).toHaveBeenCalled();
expect(client._unstable_getLivekitToken).toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual([]);
});
it("does not fall back to OpenID when publishing with url transport", async () => {
mockJWTService();
client.getLivekitToken.mockRejectedValueOnce(unsupportedError);
client._unstable_getLivekitToken.mockRejectedValueOnce(unsupportedError);
await expect(
getSFUConfig({
...defaultParams,
@@ -196,7 +196,7 @@ describe("getSFUConfig", () => {
role: "publisher",
}),
).rejects.toThrow(expect.any(NoMatrix2AuthorizationService));
expect(client.getLivekitToken).toHaveBeenCalled();
expect(client._unstable_getLivekitToken).toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual([]);
});
@@ -216,7 +216,7 @@ describe("getSFUConfig", () => {
livekitAlias: "via legacy endpoint",
}),
);
expect(client.getLivekitToken).not.toHaveBeenCalled();
expect(client._unstable_getLivekitToken).not.toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual(["/sfu/get"]);
});
});
@@ -245,7 +245,7 @@ describe("delegateDelayedLeave", () => {
it("uses CS API with url transport", async () => {
mockJWTService();
await delegateDelayedLeave({ ...defaultParams, transport: urlTransport });
expect(client.delegateDelayedLeave).toHaveBeenCalledWith({
expect(client._unstable_delegateDelayedLeave).toHaveBeenCalledWith({
url: urlTransport.url,
room_id: roomId,
slot_id: slotId,
@@ -257,11 +257,13 @@ describe("delegateDelayedLeave", () => {
it("does not fall back to OpenID with url transport", async () => {
mockJWTService();
client.delegateDelayedLeave.mockRejectedValueOnce(unsupportedError);
client._unstable_delegateDelayedLeave.mockRejectedValueOnce(
unsupportedError,
);
await expect(
delegateDelayedLeave({ ...defaultParams, transport: urlTransport }),
).rejects.toThrow();
expect(client.delegateDelayedLeave).toHaveBeenCalled();
expect(client._unstable_delegateDelayedLeave).toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual([]);
});
@@ -271,7 +273,7 @@ describe("delegateDelayedLeave", () => {
...defaultParams,
transport: serviceUrlTransport,
});
expect(client.delegateDelayedLeave).not.toHaveBeenCalled();
expect(client._unstable_delegateDelayedLeave).not.toHaveBeenCalled();
expect(delegationViaJWTService()).toEqual({
delay_id: "delay123",
delay_timeout: 3_600_000,
@@ -286,7 +288,7 @@ describe("delegateDelayedLeave", () => {
...defaultParams,
transport: urlAndServiceUrlTransport,
});
expect(client.delegateDelayedLeave).not.toHaveBeenCalled();
expect(client._unstable_delegateDelayedLeave).not.toHaveBeenCalled();
expect(delegationViaJWTService()).toEqual({
delay_id: "delay123",
delay_timeout: 3_600_000,
-43
View File
@@ -1,43 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { describe, expect, it } from "vitest";
import { facingModeOf } from "./facingMode";
function camera(label: string, facingMode?: string): MediaStreamTrack {
return {
label,
getSettings: () => (facingMode === undefined ? {} : { facingMode }),
} as MediaStreamTrack;
}
describe("facingModeOf", () => {
it.each([
{ label: "Back Camera", facingMode: "environment", faces: "environment" },
{ label: "iPhone Camera", facingMode: "user", faces: "user" },
{ label: "FaceTime HD Camera", facingMode: undefined, faces: "user" },
{ label: "", facingMode: undefined, faces: "user" },
{
label: "Alice's iPhone Camera",
facingMode: undefined,
faces: "environment",
},
{ label: "iPad Camera", facingMode: undefined, faces: "environment" },
{
label: " OBS Virtual Camera ",
facingMode: undefined,
faces: "environment",
},
{ label: "Integrated Camera", facingMode: "left", faces: "user" },
])(
"takes $label ($facingMode) to face $faces",
({ label, facingMode, faces }) => {
expect(facingModeOf(camera(label, facingMode))).toBe(faces);
},
);
});
-23
View File
@@ -1,23 +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.
*/
/**
* Which way a camera faces. Laptop and desktop cameras don't say and face the
* user; of those, a phone used as a webcam (Continuity Camera) films with its
* rear camera and OBS shows a scene, so neither is taken to face the user.
* LiveKit makes the same guess.
*/
export function facingModeOf(track: MediaStreamTrack): "user" | "environment" {
const { facingMode } = track.getSettings();
if (facingMode === "user" || facingMode === "environment") return facingMode;
const label = track.label.trim().toLowerCase();
return label === "obs virtual camera" ||
label.includes("iphone") ||
label.includes("ipad")
? "environment"
: "user";
}
+9 -32
View File
@@ -23,14 +23,13 @@ import {
import * as Sentry from "@sentry/react";
import { TooltipProvider } from "@vector-im/compound-web";
import { logger } from "matrix-js-sdk/lib/logger";
import { type MatrixClient } from "matrix-js-sdk";
import { I18nextProvider } from "react-i18next";
import { HomePage } from "./home/HomePage";
import { LoginPage } from "./auth/LoginPage";
import { RegisterPage } from "./auth/RegisterPage";
import { RoomPage } from "./room/RoomPage";
import { type ClientLoader, ClientProvider } from "./ClientContext";
import { ClientManagerProvider, ClientProvider } from "./ClientContext";
import { ErrorPage, LoadingPage } from "./FullScreenView";
import { Initializer } from "./initializer";
import { type WidgetHelpers } from "./widget";
@@ -57,16 +56,6 @@ import { LeaveToHomeProvider } from "./LeaveToHomeContext";
const SentryRoute = Sentry.withSentryReactRouterV7Routing(Route);
// Element Call's own session, for when no host supplies a client.
// - Passed in here, not imported by ClientProvider: this module is only in the
// app builds, so the client setup and the store worker behind it stay out of
// the component package (see the `loadClient` prop).
// - Imported on demand, as it was before, so that a widget, which gets its
// client from the host, never downloads it.
// - Module-level, so that the provider's effect sees one stable loader.
const loadStandaloneClient: ClientLoader = async (...args) =>
(await import("./utils/spa")).initSPA(...args);
interface SimpleProviderProps {
children: JSX.Element;
}
@@ -141,22 +130,9 @@ export const App: FC<Props> = ({ vm, widget }) => {
.catch(logger.error);
});
// As a widget, the client comes from the host over the widget API. Standalone,
// Element Call finds one itself, so there is nothing to wait for here.
const [widgetClient, setWidgetClient] = useState<MatrixClient | undefined>(
undefined,
);
useEffect(() => {
if (widget === null) return;
widget.client
.then(setWidgetClient)
.catch((e) => logger.error("Failed to obtain the host's client", e));
}, [widget]);
const clientReady = widget === null || widgetClient !== undefined;
const content =
loaded && clientReady ? (
<ClientProvider client={widgetClient} loadClient={loadStandaloneClient}>
const content = loaded ? (
<ClientProvider session={vm.clientSession}>
<ClientManagerProvider value={vm.clientManager}>
<MediaDevicesContext value={vm.mediaDevices}>
<BackgroundEffectsProvider effects={vm.backgroundEffects}>
<Sentry.ErrorBoundary
@@ -171,10 +147,11 @@ export const App: FC<Props> = ({ vm, widget }) => {
</Sentry.ErrorBoundary>
</BackgroundEffectsProvider>
</MediaDevicesContext>
</ClientProvider>
) : (
<LoadingPage />
);
</ClientManagerProvider>
</ClientProvider>
) : (
<LoadingPage />
);
return (
<I18nextProvider i18n={i18n}>
+2 -16
View File
@@ -12,6 +12,7 @@ import { type FC, type PropsWithChildren } from "react";
import { ClientContextProvider } from "./ClientContext";
import { Avatar } from "./Avatar";
import { hostClientSession } from "./state/ClientSession";
import { mockMatrixRoomMember, mockRtcMembership } from "./utils/test";
import {
type HostBridge,
@@ -26,22 +27,7 @@ const TestComponent: FC<
}>
> = ({ client, hostBridge = nullHostBridge, children }) => {
return (
<ClientContextProvider
value={{
state: "valid",
disconnected: false,
supportedFeatures: {
reactions: true,
},
setClient: vi.fn(),
authenticated: {
client,
isPasswordlessUser: true,
changePassword: vi.fn(),
logout: vi.fn(),
},
}}
>
<ClientContextProvider value={hostClientSession(client)}>
<HostBridgeProvider value={hostBridge}>{children}</HostBridgeProvider>
</ClientContextProvider>
);
+6 -10
View File
@@ -15,7 +15,7 @@ import {
import { Avatar as CompoundAvatar } from "@vector-im/compound-web";
import { type MatrixClient } from "matrix-js-sdk";
import { useClientState } from "./ClientContext";
import { useClient } from "./ClientContext";
import { useHostBridge } from "./HostBridge";
export enum Size {
@@ -74,7 +74,7 @@ export const Avatar: FC<Props> = ({
style,
...props
}) => {
const clientState = useClientState();
const { client } = useClient();
const hostBridge = useHostBridge();
const sizePx = useMemo(
@@ -87,7 +87,7 @@ export const Avatar: FC<Props> = ({
const [avatarUrl, setAvatarUrl] = useState<string | undefined>(undefined);
// In theory, a change in `clientState` or `sizePx` could run extra media
// In theory, a change in `client` or `sizePx` could run extra media
// downloads, but in practice they should be stable long before this code runs.
useEffect(() => {
if (!src) {
@@ -99,12 +99,8 @@ export const Avatar: FC<Props> = ({
if (hostBridge.downloadMedia) {
blob = hostBridge.downloadMedia(src);
} else if (
clientState?.state === "valid" &&
clientState.authenticated?.client &&
sizePx
) {
blob = getAvatarFromServer(clientState.authenticated.client, src, sizePx);
} else if (client && sizePx) {
blob = getAvatarFromServer(client, src, sizePx);
} else {
setAvatarUrl(undefined);
return;
@@ -133,7 +129,7 @@ export const Avatar: FC<Props> = ({
URL.revokeObjectURL(objectUrl);
}
};
}, [clientState, hostBridge, src, sizePx]);
}, [client, hostBridge, src, sizePx]);
return (
<CompoundAvatar
+86 -72
View File
@@ -6,16 +6,25 @@ Please see LICENSE in the repository root for full details.
*/
import { expect, test, vi } from "vitest";
import { render, waitFor } from "@testing-library/react";
import { act, render, renderHook } from "@testing-library/react";
import { BrowserRouter } from "react-router-dom";
import { type MatrixClient } from "matrix-js-sdk";
import { type FC } from "react";
import { BehaviorSubject } from "rxjs";
import {
type ClientLoader,
ClientManagerProvider,
ClientProvider,
useClientState,
useClientManager,
useClientManagerIfAny,
useClientSessionState,
} from "./ClientContext";
import {
type ClientManager,
type ClientSession,
type ClientSessionState,
hostClientSession,
} from "./state/ClientSession";
const mockClient = (userId = "@alice:example.org"): MatrixClient =>
({
@@ -28,67 +37,47 @@ const mockClient = (userId = "@alice:example.org"): MatrixClient =>
/** Reports what the context says, so a test can assert on it. */
const ShowClientState: FC = () => {
const state = useClientState();
if (state === undefined) return <span>loading</span>;
if (state.state === "error") return <span>error</span>;
return (
<span>{state.authenticated?.client.getUserId() ?? "unauthenticated"}</span>
);
const state = useClientSessionState();
switch (state.state) {
case "signedIn":
return <span>{state.client.getUserId()}</span>;
case "signedOut":
return <span>unauthenticated</span>;
default:
return <span>{state.state}</span>;
}
};
test("uses a client supplied by the host without waiting", () => {
const client = mockClient();
const { container } = render(
const renderProvider = (
session: ClientSession,
children = <ShowClientState />,
): ReturnType<typeof render> =>
render(
<BrowserRouter>
<ClientProvider client={client}>
<ShowClientState />
</ClientProvider>
<ClientProvider session={session}>{children}</ClientProvider>
</BrowserRouter>,
);
test("uses a client supplied by the host without waiting", () => {
const { container } = renderProvider(hostClientSession(mockClient()));
// Available on the very first render: a supplied client needs no session
// restoring, so there is no loading state to pass through.
expect(container.textContent).toBe("@alice:example.org");
});
test("does not claim exclusive use of storage when given a client", () => {
// The channel is created when the module loads, so spy on the prototype
// rather than trying to replace the global.
const postMessage = vi.spyOn(BroadcastChannel.prototype, "postMessage");
render(
<BrowserRouter>
<ClientProvider client={mockClient()}>
<ShowClientState />
</ClientProvider>
</BrowserRouter>,
);
// The broadcast shuts down other instances to protect Element Call's own
// stores. A host's client brings its own, so there is nothing to protect.
expect(postMessage).not.toHaveBeenCalled();
postMessage.mockRestore();
});
test("follows the client when the host swaps it", () => {
const first = mockClient();
const second = mockClient("@bob:example.org");
const { container, rerender } = render(
<BrowserRouter>
<ClientProvider client={first}>
<ShowClientState />
</ClientProvider>
</BrowserRouter>,
const { container, rerender } = renderProvider(
hostClientSession(mockClient()),
);
expect(container.textContent).toBe("@alice:example.org");
// A host that re-authenticates hands us a new client on a mounted component
rerender(
<BrowserRouter>
<ClientProvider client={second}>
<ClientProvider
session={hostClientSession(mockClient("@bob:example.org"))}
>
<ShowClientState />
</ClientProvider>
</BrowserRouter>,
@@ -97,38 +86,63 @@ test("follows the client when the host swaps it", () => {
expect(container.textContent).toBe("@bob:example.org");
});
test("finds a client of its own when the host supplies none", async () => {
const client = mockClient();
const loadClient = vi
.fn<ClientLoader>()
.mockResolvedValue({ client, passwordlessUser: true });
const { container } = render(
<BrowserRouter>
<ClientProvider loadClient={loadClient}>
<ShowClientState />
</ClientProvider>
</BrowserRouter>,
);
test("follows a session of its own as it is restored", () => {
const state$ = new BehaviorSubject<ClientSessionState>({ state: "loading" });
const { container } = renderProvider({ state$ });
// Nothing to show until a session has been restored or created
expect(container.textContent).toBe("loading");
await waitFor(() => expect(container.textContent).toBe("@alice:example.org"));
// Given the session store to restore from and to clear on a stale session
expect(loadClient).toHaveBeenCalledWith(
expect.any(Function),
expect.any(Function),
act(() =>
state$.next({
state: "signedIn",
client: mockClient(),
passwordlessUser: true,
}),
);
expect(container.textContent).toBe("@alice:example.org");
});
test("has no one signed in when given neither a client nor a way to load one", async () => {
const { container } = render(
<BrowserRouter>
<ClientProvider>
<ShowClientState />
</ClientProvider>
</BrowserRouter>,
test("has no one signed in when the session says so", () => {
const { container } = renderProvider({
state$: new BehaviorSubject<ClientSessionState>({ state: "signedOut" }),
});
expect(container.textContent).toBe("unauthenticated");
});
test("shows the session's error in place of its children", () => {
const { container } = renderProvider({
state$: new BehaviorSubject<ClientSessionState>({
state: "error",
error: new Error("Opened elsewhere"),
}),
});
// The error page, not the children
expect(container.textContent).not.toContain("error");
expect(container.textContent).toContain("Something went wrong");
});
test("hands the session's manager to views that need one", () => {
const manager: ClientManager = {
login: vi.fn(),
register: vi.fn(),
logout: vi.fn(),
};
const { result } = renderHook(
() => [useClientManager(), useClientManagerIfAny()],
{
wrapper: ({ children }) => (
<ClientManagerProvider value={manager}>
<>{children}</>
</ClientManagerProvider>
),
},
);
expect(result.current).toEqual([manager, manager]);
});
await waitFor(() => expect(container.textContent).toBe("unauthenticated"));
test("has no manager for a host's session", () => {
// The component and the widget provide none; a view that insists on one is
// in the wrong build
expect(renderHook(() => useClientManagerIfAny()).result.current).toBeNull();
expect(() => renderHook(() => useClientManager())).toThrow();
});
+52 -374
View File
@@ -5,30 +5,18 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import {
type FC,
useCallback,
useEffect,
useState,
createContext,
use,
useRef,
useMemo,
type JSX,
} from "react";
import { logger } from "matrix-js-sdk/lib/logger";
import { type ISyncStateData, type SyncState } from "matrix-js-sdk/lib/sync";
import { ClientEvent, type MatrixClient } from "matrix-js-sdk";
import { type FC, useEffect, createContext, use, type JSX } from "react";
import { type MatrixClient } from "matrix-js-sdk";
import { ErrorPage } from "./FullScreenView";
import { useHostBridge } from "./HostBridge";
import { useLeaveToHome } from "./LeaveToHomeContext";
import { PosthogAnalytics } from "./analytics/PosthogAnalytics";
import { useBehavior } from "./useBehavior";
import { constant } from "./state/Behavior";
import {
PosthogAnalytics,
RegistrationType,
} from "./analytics/PosthogAnalytics";
import { useEventTarget } from "./useEvents";
import { OpenElsewhereError } from "./RichError";
type ClientManager,
type ClientSession,
type ClientSessionState,
} from "./state/ClientSession";
declare global {
interface Window {
@@ -37,380 +25,70 @@ declare global {
}
}
export type ClientState = ValidClientState | ErrorState;
export type ValidClientState = {
state: "valid";
authenticated?: AuthenticatedClient;
// 'Disconnected' rather than 'connected' because it tracks specifically
// whether the client is supposed to be connected but is not
disconnected: boolean;
supportedFeatures: {
reactions: boolean;
};
setClient: (client: MatrixClient, session: Session) => void;
// Without a provider, no one is signed in and there is no session to act on
const noClientSession: ClientSession = {
state$: constant({ state: "signedOut" }),
};
export type AuthenticatedClient = {
client: MatrixClient;
isPasswordlessUser: boolean;
changePassword: (password: string) => Promise<void>;
logout: () => void;
};
export type ErrorState = {
state: "error";
error: Error;
};
const ClientContext = createContext<ClientState | undefined>(undefined);
const ClientContext = createContext<ClientSession>(noClientSession);
export const ClientContextProvider = ClientContext.Provider;
export const useClientState = (): ClientState | undefined => use(ClientContext);
export const useClientSessionState = (): ClientSessionState =>
useBehavior(use(ClientContext).state$);
export function useClient(): {
client?: MatrixClient;
setClient?: (client: MatrixClient, session: Session) => void;
} {
let client;
let setClient;
const clientState = useClientState();
if (clientState?.state === "valid") {
client = clientState.authenticated?.client;
setClient = clientState.setClient;
}
return { client, setClient };
export function useClient(): { client?: MatrixClient } {
const state = useClientSessionState();
return { client: state.state === "signedIn" ? state.client : undefined };
}
// Plain representation of the `ClientContext` as a helper for old components that expected an object with multiple fields.
export function useClientLegacy(): {
client?: MatrixClient;
setClient?: (client: MatrixClient, session: Session) => void;
passwordlessUser: boolean;
loading: boolean;
authenticated: boolean;
logout?: () => void;
error?: Error;
} {
const clientState = useClientState();
// Null where the session is a host's: the component, and the widget
const ClientManagerContext = createContext<ClientManager | null>(null);
let client;
let setClient;
let passwordlessUser = false;
let loading = true;
let error;
let authenticated = false;
let logout;
export const ClientManagerProvider = ClientManagerContext.Provider;
if (clientState?.state === "valid") {
client = clientState.authenticated?.client;
setClient = clientState.setClient;
passwordlessUser = clientState.authenticated?.isPasswordlessUser ?? false;
loading = false;
authenticated = client !== undefined;
logout = clientState.authenticated?.logout;
} else if (clientState?.state === "error") {
error = clientState.error;
loading = false;
}
return {
client,
setClient,
passwordlessUser,
loading,
authenticated,
logout,
error,
};
}
const loadChannel =
"BroadcastChannel" in window ? new BroadcastChannel("load") : null;
interface Props {
children: JSX.Element;
/**
* The client Element Call should use.
*
* An application hosting Element Call as a component already has a client,
* and owns the user's session; supplying it here means Element Call neither
* authenticates anyone nor manages their session. Left out, Element Call finds a client
* itself — from the widget API, or by restoring or creating a session of its
* own.
*/
client?: MatrixClient;
/**
* How Element Call finds a client when none is supplied: the standalone app
* restores or creates a session of its own. Stable, as a hook dependency.
* Left out along with the client, no one is signed in.
*
* A prop, rather than this module importing `utils/spa` itself, because:
* - This module is in the component build, and so is everything it imports,
* dynamically or not: a dynamic import becomes a chunk in the package,
* not a module left out of it.
* - Behind `utils/spa` sits `utils/initClient` and the client store worker,
* which the bundler emits as soon as it loads the import (see there).
* - `App.tsx`, which the component never imports, is where the standalone
* app passes the loader in; the component passes nothing, having the
* host's client.
*/
loadClient?: ClientLoader;
/**
* The manager of a session that is Element Call's own, for views that only
* the standalone app mounts: the login and registration pages. Throws
* elsewhere, as those views have no business being there.
*/
export function useClientManager(): ClientManager {
const manager = use(ClientManagerContext);
if (manager === null)
throw new Error("This view needs a session of Element Call's own");
return manager;
}
/**
* Restores or creates a session of Element Call's own, kept where the given
* functions keep it. Resolves to null when no one is signed in.
* The session's manager, or null where the session is a host's. For views
* shared with the widget, which can offer to sign out only when that is ours
* to do.
*/
export type ClientLoader = (
loadSession: () => Session | undefined,
clearSession: () => void,
) => Promise<InitResult | null>;
export const useClientManagerIfAny = (): ClientManager | null =>
use(ClientManagerContext);
export const ClientProvider: FC<Props> = ({ children, client, loadClient }) => {
const leaveToHome = useLeaveToHome();
const hostBridge = useHostBridge();
interface Props {
children: JSX.Element;
/** a session from Element Call SPA, from a widget or the host (EW) */
session: ClientSession;
}
// null = signed out, undefined = loading
const [initClientState, setInitClientState] = useState<
InitResult | null | undefined
>(
client === undefined
? undefined
: // A supplied client belongs to the host, so there is no session of ours
// to restore and nothing to wait for.
{ client, passwordlessUser: false },
);
const initializing = useRef(false);
useEffect(() => {
if (client !== undefined) {
// Nothing to load, but a host may hand us a different client later — on
// re-authenticating, say — so follow whichever one it has given us.
setInitClientState((current) =>
current?.client === client
? current
: { client, passwordlessUser: false },
);
// Analytics still need to follow the user's choices.
if (PosthogAnalytics.instance.isEnabled())
PosthogAnalytics.instance.startListeningToSettingsChanges();
return;
}
// In case the component is mounted, unmounted, and remounted quickly (as
// React does in strict mode), we need to make sure not to doubly initialize
// the client.
if (initializing.current) return;
if (loadClient === undefined) {
setInitClientState(null);
return;
}
initializing.current = true;
loadClient(loadSession, clearSession)
.then((initResult) => {
setInitClientState(initResult);
if (PosthogAnalytics.instance.isEnabled())
PosthogAnalytics.instance.startListeningToSettingsChanges();
})
.catch((err) => logger.error(err))
.finally(() => (initializing.current = false));
}, [client, loadClient]);
const changePassword = useCallback(
async (password: string) => {
const session = loadSession();
if (!initClientState?.client || !session) {
return;
}
await initClientState.client.setPassword(
{
type: "m.login.password",
identifier: {
type: "m.id.user",
user: session.user_id,
},
user: session.user_id,
password: session.tempPassword,
},
password,
);
saveSession({ ...session, passwordlessUser: false });
setInitClientState({
...initClientState,
passwordlessUser: false,
});
},
[initClientState],
);
const setClient = useCallback(
(client: MatrixClient, session: Session) => {
const oldClient = initClientState?.client;
if (oldClient && oldClient !== client) {
oldClient.stopClient();
}
saveSession(session);
setInitClientState({
client,
passwordlessUser: session.passwordlessUser,
});
if (PosthogAnalytics.instance.isEnabled())
PosthogAnalytics.instance.startListeningToSettingsChanges();
},
[initClientState?.client],
);
const logout = useCallback(async () => {
const client = initClientState?.client;
if (!client) {
return;
}
await client.logout(true);
await client.clearStores();
clearSession();
setInitClientState(null);
leaveToHome?.();
PosthogAnalytics.instance.logout();
PosthogAnalytics.instance.setRegistrationType(RegistrationType.Guest);
}, [leaveToHome, initClientState?.client]);
// To protect against multiple sessions writing to the same storage
// simultaneously, we send a broadcast message that shuts down all other
// running instances of the app. Element Call only has storage of its own to
// protect when it created the session itself; given a client — by a host, or
// over the widget API — it is mostly stateless.
const ownsSession = client === undefined;
useEffect(() => {
if (ownsSession) loadChannel?.postMessage({});
}, [ownsSession]);
const [alreadyOpenedErr, setAlreadyOpenedErr] = useState<Error | undefined>(
undefined,
);
useEventTarget(
loadChannel,
"message",
useCallback(() => {
initClientState?.client.stopClient();
setAlreadyOpenedErr(new OpenElsewhereError());
}, [initClientState?.client, setAlreadyOpenedErr]),
);
const [isDisconnected, setIsDisconnected] = useState(false);
const [supportsReactions, setSupportsReactions] = useState(false);
const state: ClientState | undefined = useMemo(() => {
if (alreadyOpenedErr) {
return { state: "error", error: alreadyOpenedErr };
}
if (initClientState === undefined) return undefined;
const authenticated =
initClientState === null
? undefined
: {
client: initClientState.client,
isPasswordlessUser: initClientState.passwordlessUser,
changePassword,
logout,
};
return {
state: "valid",
authenticated,
setClient,
disconnected: isDisconnected,
supportedFeatures: {
reactions: supportsReactions,
},
};
}, [
alreadyOpenedErr,
changePassword,
initClientState,
logout,
setClient,
isDisconnected,
supportsReactions,
]);
const onSync = useCallback(
(state: SyncState, _old: SyncState | null, data?: ISyncStateData) => {
setIsDisconnected(clientIsDisconnected(state, data));
},
[],
);
export const ClientProvider: FC<Props> = ({ children, session }) => {
const state = useBehavior(session.state$);
useEffect(() => {
if (!initClientState) {
return;
}
window.matrixclient = initClientState.client;
window.passwordlessUser = initClientState.passwordlessUser;
if (state.state !== "signedIn") return;
window.matrixclient = state.client;
window.passwordlessUser = state.passwordlessUser;
if (PosthogAnalytics.hasInstance())
PosthogAnalytics.instance.onLoginStatusChanged();
// Analytics follow the user's choices whoever the client belongs to
if (PosthogAnalytics.instance.isEnabled())
PosthogAnalytics.instance.startListeningToSettingsChanges();
}, [state]);
if (initClientState.client) {
initClientState.client.on(ClientEvent.Sync, onSync);
}
if (state.state === "error") return <ErrorPage error={state.error} />;
if (!hostBridge.supportsReactions)
logger.warn("The host does not permit reactions");
setSupportsReactions(hostBridge.supportsReactions);
return (): void => {
if (initClientState.client) {
initClientState.client.removeListener(ClientEvent.Sync, onSync);
}
};
}, [initClientState, onSync, hostBridge]);
if (alreadyOpenedErr) {
return <ErrorPage error={alreadyOpenedErr} />;
}
return <ClientContext value={state}>{children}</ClientContext>;
return <ClientContext value={session}>{children}</ClientContext>;
};
export type InitResult = {
client: MatrixClient;
passwordlessUser: boolean;
};
export interface Session {
user_id: string;
device_id: string;
access_token: string;
passwordlessUser: boolean;
tempPassword?: string;
}
const clearSession = (): void => localStorage.removeItem("matrix-auth-store");
const saveSession = (s: Session): void =>
localStorage.setItem("matrix-auth-store", JSON.stringify(s));
const loadSession = (): Session | undefined => {
const data = localStorage.getItem("matrix-auth-store");
if (!data) {
return undefined;
}
return JSON.parse(data);
};
const clientIsDisconnected = (
syncState: SyncState,
syncData?: ISyncStateData,
): boolean =>
syncState === "ERROR" && syncData?.error?.name === "ConnectionError";
+43
View File
@@ -0,0 +1,43 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { expect, test, vi } from "vitest";
import { act, render } from "@testing-library/react";
import { type MatrixClient } from "matrix-js-sdk";
import { ClientProvider } from "./ClientContext";
import { DisconnectedBanner } from "./DisconnectedBanner";
import { hostClientSession } from "./state/ClientSession";
test("shows while the client's sync fails to connect", () => {
const client = {
on: vi.fn(),
removeListener: vi.fn(),
getUserId: () => "@alice:example.org",
} as Partial<MatrixClient> as MatrixClient;
const { container } = render(
<ClientProvider session={hostClientSession(client)}>
<DisconnectedBanner />
</ClientProvider>,
);
expect(container.textContent).toBe("");
const [, onSync] = vi.mocked(client.on).mock.calls[0] as [
unknown,
(state: string, old: null, data?: { error?: Error }) => void,
];
const connectionError = Object.assign(new Error("offline"), {
name: "ConnectionError",
});
act(() => onSync("ERROR", null, { error: connectionError }));
expect(container.textContent).not.toBe("");
// Any other failure is not a connection problem
act(() => onSync("ERROR", null, { error: new Error("rate limited") }));
expect(container.textContent).toBe("");
act(() => onSync("SYNCING", null));
expect(container.textContent).toBe("");
});
+38 -8
View File
@@ -6,30 +6,60 @@ Please see LICENSE in the repository root for full details.
*/
import classNames from "classnames";
import { type FC, type HTMLAttributes, type ReactNode } from "react";
import {
type FC,
type HTMLAttributes,
type ReactNode,
useEffect,
useState,
} from "react";
import { useTranslation } from "react-i18next";
import { ClientEvent, type MatrixClient } from "matrix-js-sdk";
import { type ISyncStateData, type SyncState } from "matrix-js-sdk/lib/sync";
import styles from "./DisconnectedBanner.module.css";
import { type ValidClientState, useClientState } from "./ClientContext";
import { useClient } from "./ClientContext";
interface Props extends HTMLAttributes<HTMLElement> {
children?: ReactNode;
className?: string;
}
/**
* Shown while the signed-in client is supposed to be connected but is not.
*/
export const DisconnectedBanner: FC<Props> = ({
children,
className,
...rest
}) => {
const { t } = useTranslation();
const clientState = useClientState();
let shouldShowBanner = false;
const { client } = useClient();
// Tagged with the client it describes, so that a swapped client does not
// inherit the old one's verdict before its first sync
const [disconnected, setDisconnected] = useState<
[MatrixClient, boolean] | null
>(null);
if (clientState?.state === "valid") {
const validClientState = clientState as ValidClientState;
shouldShowBanner = validClientState.disconnected;
}
useEffect(() => {
if (client === undefined) return;
const onSync = (
syncState: SyncState,
_old: SyncState | null,
data?: ISyncStateData,
): void => {
const clientIsDisconnected =
syncState === "ERROR" && data?.error?.name === "ConnectionError";
setDisconnected([client, clientIsDisconnected]);
};
client.on(ClientEvent.Sync, onSync);
return (): void => {
client.removeListener(ClientEvent.Sync, onSync);
};
}, [client]);
const shouldShowBanner =
disconnected !== null && disconnected[0] === client && disconnected[1];
return (
<>
+96
View File
@@ -0,0 +1,96 @@
/*
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, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { BrowserRouter } from "react-router-dom";
import { type MatrixClient } from "matrix-js-sdk";
import { TooltipProvider } from "@vector-im/compound-web";
import { BehaviorSubject } from "rxjs";
import { ClientManagerProvider, ClientProvider } from "./ClientContext";
import { LeaveToHomeProvider } from "./LeaveToHomeContext";
import {
type ClientManager,
type ClientSession,
type ClientSessionState,
hostClientSession,
} from "./state/ClientSession";
import { UserMenuContainer } from "./UserMenuContainer";
import { flushPromises } from "./utils/test";
vi.mock("./settings/SettingsModal", () => ({
defaultSettingsTab: "audio",
SettingsModal: (): null => null,
}));
const mockClient = (): MatrixClient =>
({
on: vi.fn(),
removeListener: vi.fn(),
getUserId: () => "@alice:example.org",
getUserIdLocalpart: () => "alice",
getDeviceId: () => "AAAA",
getUser: () => null,
stopClient: vi.fn(),
}) as Partial<MatrixClient> as MatrixClient;
test("leaves for home after logging out of the session", async () => {
const logout = vi.fn().mockResolvedValue(undefined);
const leaveToHome = vi.fn();
renderMenu(
{
state$: new BehaviorSubject<ClientSessionState>({
state: "signedIn",
client: mockClient(),
passwordlessUser: false,
}),
},
{ login: vi.fn(), register: vi.fn(), logout },
leaveToHome,
);
await selectSignOut();
expect(logout).toHaveBeenCalled();
expect(leaveToHome).toHaveBeenCalled();
});
test("cannot end a session that is not ours", async () => {
const leaveToHome = vi.fn();
renderMenu(hostClientSession(mockClient()), null, leaveToHome);
await selectSignOut();
expect(leaveToHome).not.toHaveBeenCalled();
});
async function selectSignOut(): Promise<void> {
const user = userEvent.setup();
await user.click(screen.getByTestId("usermenu_open"));
await user.click(await screen.findByTestId("usermenu_logout"));
await flushPromises();
}
function renderMenu(
session: ClientSession,
manager: ClientManager | null,
leaveToHome: (() => void) | null = null,
): void {
render(
<BrowserRouter>
<TooltipProvider>
<LeaveToHomeProvider value={leaveToHome}>
<ClientProvider session={session}>
<ClientManagerProvider value={manager}>
<UserMenuContainer />
</ClientManagerProvider>
</ClientProvider>
</LeaveToHomeProvider>
</TooltipProvider>
</BrowserRouter>,
);
}
+18 -5
View File
@@ -9,7 +9,12 @@ import { type FC, useCallback, useState } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { logger } from "matrix-js-sdk/lib/logger";
import { useClientLegacy } from "./ClientContext";
import {
useClient,
useClientManagerIfAny,
useClientSessionState,
} from "./ClientContext";
import { useLeaveToHome } from "./LeaveToHomeContext";
import { useProfile } from "./profile/useProfile";
import { defaultSettingsTab, SettingsModal } from "./settings/SettingsModal";
import { UserMenu } from "./UserMenu";
@@ -21,7 +26,13 @@ interface Props {
export const UserMenuContainer: FC<Props> = ({ preventNavigation = false }) => {
const location = useLocation();
const navigate = useNavigate();
const { client, logout, authenticated, passwordlessUser } = useClientLegacy();
const { client } = useClient();
const session = useClientSessionState();
const passwordlessUser =
session.state === "signedIn" && session.passwordlessUser;
// Absent when the session is a host's, which Element Call cannot end
const logout = useClientManagerIfAny()?.logout;
const leaveToHome = useLeaveToHome();
const { displayName, avatarUrl } = useProfile(client);
const [settingsModalOpen, setSettingsModalOpen] = useState(false);
const onDismissSettingsModal = useCallback(
@@ -43,7 +54,9 @@ export const UserMenuContainer: FC<Props> = ({ preventNavigation = false }) => {
setSettingsModalOpen(true);
break;
case "logout":
logout?.();
logout?.()
.then(() => leaveToHome?.())
.catch((e) => logger.error("Failed to log out", e));
break;
case "login":
navigate("/login", { state: { from: location } })?.catch((error) =>
@@ -52,7 +65,7 @@ export const UserMenuContainer: FC<Props> = ({ preventNavigation = false }) => {
break;
}
},
[navigate, location, logout, setSettingsModalOpen],
[navigate, location, logout, leaveToHome, setSettingsModalOpen],
);
const userName = client?.getUserIdLocalpart() ?? "";
@@ -60,7 +73,7 @@ export const UserMenuContainer: FC<Props> = ({ preventNavigation = false }) => {
<>
<UserMenu
preventNavigation={preventNavigation}
isAuthenticated={authenticated}
isAuthenticated={client !== undefined}
isPasswordlessUser={passwordlessUser}
avatarUrl={avatarUrl}
onAction={onAction}
+78
View File
@@ -0,0 +1,78 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { afterEach, beforeEach, expect, test, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { type FC } from "react";
import { MemoryRouter, useLocation } from "react-router-dom";
import { type MatrixClient } from "matrix-js-sdk";
import { LoginPage } from "./LoginPage";
import { ClientManagerProvider } from "../ClientContext";
import { type ClientManager } from "../state/ClientSession";
import { Config } from "../config/Config";
beforeEach(() => {
vi.spyOn(Config, "defaultHomeserverUrl").mockReturnValue(
"https://hs.example.org",
);
});
afterEach(() => {
vi.restoreAllMocks();
vi.clearAllMocks();
});
test("signs in with the session's manager and goes home", async () => {
const manager = mockManager();
vi.mocked(manager.login).mockResolvedValue({} as MatrixClient);
renderLogin(manager);
await submit("alice", "hunter2");
expect(manager.login).toHaveBeenCalledWith(
"https://hs.example.org",
"alice",
"hunter2",
);
expect(await screen.findByText("at /")).toBeVisible();
});
test("shows why signing in failed", async () => {
const manager = mockManager();
vi.mocked(manager.login).mockRejectedValue(new Error("Wrong password"));
renderLogin(manager);
await submit("alice", "hunter2");
expect(await screen.findByText("Wrong password")).toBeVisible();
expect(screen.getByText("at /login")).toBeVisible();
});
async function submit(username: string, password: string): Promise<void> {
const user = userEvent.setup();
await user.type(screen.getByTestId("login_username"), username);
await user.type(screen.getByTestId("login_password"), password);
await user.click(screen.getByTestId("login_login"));
}
function mockManager(): ClientManager {
return { login: vi.fn(), register: vi.fn(), logout: vi.fn() };
}
const WhereAmI: FC = () => <span>at {useLocation().pathname}</span>;
function renderLogin(manager: ClientManager): void {
render(
<MemoryRouter initialEntries={["/login"]}>
<ClientManagerProvider value={manager}>
<LoginPage />
<WhereAmI />
</ClientManagerProvider>
</MemoryRouter>,
);
}
+4 -13
View File
@@ -11,10 +11,9 @@ import { Trans, useTranslation } from "react-i18next";
import { Button } from "@vector-im/compound-web";
import Logo from "../icons/LogoLarge.svg?react";
import { useClient } from "../ClientContext";
import { useClientManager } from "../ClientContext";
import { FieldRow, InputField, ErrorMessage } from "../input/Input";
import styles from "./LoginPage.module.css";
import { useInteractiveLogin } from "./useInteractiveLogin";
import { usePageTitle } from "../usePageTitle";
import { PosthogAnalytics } from "../analytics/PosthogAnalytics";
import { Config } from "../config/Config";
@@ -24,8 +23,7 @@ export const LoginPage: FC = () => {
const { t } = useTranslation();
usePageTitle(t("login_title"));
const { client, setClient } = useClient();
const login = useInteractiveLogin(client);
const { login } = useClientManager();
const homeserver = Config.defaultHomeserverUrl(); // TODO: Make this configurable
const usernameRef = useRef<HTMLInputElement>(null);
const passwordRef = useRef<HTMLInputElement>(null);
@@ -46,15 +44,8 @@ export const LoginPage: FC = () => {
setLoading(false);
return;
}
login(homeserver, usernameRef.current.value, passwordRef.current.value)
.then(async ([client, session]) => {
if (!setClient) {
return;
}
setClient(client, session);
.then(async () => {
const locationState = location.state;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
@@ -72,7 +63,7 @@ export const LoginPage: FC = () => {
setLoading(false);
});
},
[login, location, navigate, homeserver, setClient],
[login, location, navigate, homeserver],
);
// we need to limit the length of the homserver name to not cover the whole loginview input with the string.
let shortendHomeserverName = Config.defaultServerName()?.slice(0, 25);
+133
View File
@@ -0,0 +1,133 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { afterEach, expect, test, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { type FC } from "react";
import { MemoryRouter, useLocation } from "react-router-dom";
import { type MatrixClient } from "matrix-js-sdk";
import { BehaviorSubject } from "rxjs";
import { RegisterPage } from "./RegisterPage";
import { ClientContextProvider, ClientManagerProvider } from "../ClientContext";
import {
type ClientManager,
type ClientSessionState,
} from "../state/ClientSession";
vi.mock("./useRecaptcha", () => ({
useRecaptcha: () => ({
execute: vi.fn().mockResolvedValue("captcha-response"),
reset,
recaptchaId: "recaptcha",
}),
}));
vi.mock("./useRegistrationTerms", () => ({
useRegistrationTerms: () => ({ recaptchaKey: "site-key" }),
}));
const reset = vi.fn();
afterEach(() => vi.clearAllMocks());
test("waits for the session to be restored", () => {
renderRegister({ state: "loading" }, mockManager());
expect(screen.getByRole("heading", { name: "Loading…" })).toBeVisible();
});
test("registers an account, signs in and goes home", async () => {
const manager = mockManager();
const setSignedIn = vi.fn();
vi.mocked(manager.register).mockResolvedValue({
client: {} as MatrixClient,
setSignedIn,
});
renderRegister({ state: "signedOut" }, manager);
await submit("alice", "hunter2");
expect(manager.register).toHaveBeenCalledWith(
"alice",
"hunter2",
"alice",
"captcha-response",
false,
);
expect(setSignedIn).toHaveBeenCalled();
expect(await screen.findByText("at /")).toBeVisible();
});
test("upgrades a passwordless user to a full account", async () => {
const manager = mockManager();
vi.mocked(manager.register).mockResolvedValue({
client: {} as MatrixClient,
setSignedIn: vi.fn(),
});
renderRegister(
{
state: "signedIn",
client: { getUserId: () => "@guest:example.org" } as MatrixClient,
passwordlessUser: true,
},
manager,
);
await submit("alice", "hunter2");
expect(manager.register).toHaveBeenCalledWith(
"alice",
"hunter2",
"alice",
"captcha-response",
true,
);
});
test("shows why registering failed and resets the captcha", async () => {
const manager = mockManager();
vi.mocked(manager.register).mockRejectedValue(new Error("Name taken"));
renderRegister({ state: "signedOut" }, manager);
await submit("alice", "hunter2");
expect(await screen.findByText("Name taken")).toBeVisible();
expect(reset).toHaveBeenCalled();
expect(screen.getByText("at /register")).toBeVisible();
});
async function submit(username: string, password: string): Promise<void> {
const user = userEvent.setup();
await user.type(screen.getByTestId("register_username"), username);
await user.type(screen.getByTestId("register_password"), password);
await user.type(screen.getByTestId("register_confirm_password"), password);
await user.click(screen.getByTestId("register_register"));
}
function mockManager(): ClientManager {
return { login: vi.fn(), register: vi.fn(), logout: vi.fn() };
}
const WhereAmI: FC = () => <span>at {useLocation().pathname}</span>;
function renderRegister(
state: ClientSessionState,
manager: ClientManager,
): void {
render(
<MemoryRouter initialEntries={["/register"]}>
<ClientContextProvider
value={{ state$: new BehaviorSubject<ClientSessionState>(state) }}
>
<ClientManagerProvider value={manager}>
<RegisterPage />
<WhereAmI />
</ClientManagerProvider>
</ClientContextProvider>
</MemoryRouter>,
);
}
+17 -17
View File
@@ -22,8 +22,12 @@ import { logger } from "matrix-js-sdk/lib/logger";
import { Button, Text } from "@vector-im/compound-web";
import { FieldRow, InputField, ErrorMessage } from "../input/Input";
import { useClientLegacy } from "../ClientContext";
import { useInteractiveRegistration } from "./useInteractiveRegistration";
import {
useClient,
useClientManager,
useClientSessionState,
} from "../ClientContext";
import { useRegistrationTerms } from "./useRegistrationTerms";
import styles from "./LoginPage.module.css";
import Logo from "../icons/LogoLarge.svg?react";
import { LoadingPage } from "../FullScreenView";
@@ -37,8 +41,13 @@ export const RegisterPage: FC = () => {
const { t } = useTranslation();
usePageTitle(t("action.register"));
const { loading, authenticated, passwordlessUser, client, setClient } =
useClientLegacy();
const session = useClientSessionState();
const loading = session.state === "loading";
const passwordlessUser =
session.state === "signedIn" && session.passwordlessUser;
const { client } = useClient();
const authenticated = client !== undefined;
const { register } = useClientManager();
const confirmPasswordRef = useRef<HTMLInputElement>(null);
const navigate = useNavigate();
@@ -47,7 +56,7 @@ export const RegisterPage: FC = () => {
const [error, setError] = useState<Error>();
const [password, setPassword] = useState("");
const [passwordConfirmation, setPasswordConfirmation] = useState("");
const { recaptchaKey, register } = useInteractiveRegistration(client);
const { recaptchaKey } = useRegistrationTerms();
const { execute, reset, recaptchaId } = useRecaptcha(recaptchaKey);
const onSubmitRegisterForm = useCallback(
@@ -64,7 +73,7 @@ export const RegisterPage: FC = () => {
setRegistering(true);
const recaptchaResponse = await execute();
const [newClient, session] = await register(
const { client: newClient, setSignedIn } = await register(
userName,
password,
userName,
@@ -95,7 +104,7 @@ export const RegisterPage: FC = () => {
}
}
setClient?.(newClient, session);
setSignedIn();
PosthogAnalytics.instance.eventSignup.cacheSignupEnd(new Date());
};
@@ -117,16 +126,7 @@ export const RegisterPage: FC = () => {
reset();
});
},
[
register,
location,
navigate,
passwordlessUser,
reset,
execute,
client,
setClient,
],
[register, location, navigate, passwordlessUser, reset, execute, client],
);
useEffect(() => {
+104
View File
@@ -0,0 +1,104 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { afterEach, expect, test, vi } from "vitest";
import { createClient, type MatrixClient, MatrixError } from "matrix-js-sdk";
import type * as MatrixJsSdk from "matrix-js-sdk";
import { loginWithPassword, registerWithPassword } from "./interactiveAuth";
vi.mock("matrix-js-sdk", async (importOriginal) => ({
...(await importOriginal<typeof MatrixJsSdk>()),
createClient: vi.fn(),
}));
const credentials = {
user_id: "@alice:example.org",
device_id: "AAAA",
access_token: "secret",
};
// What interactive auth asks of the client besides the request itself
const authClient = { generateClientSecret: () => "client-secret" };
afterEach(() => {
vi.clearAllMocks();
});
test("logs in with a password", async () => {
const login = vi.fn().mockResolvedValue({ ...credentials, extra: "ignored" });
vi.mocked(createClient).mockReturnValue({
...authClient,
login,
} as Partial<MatrixClient> as MatrixClient);
await expect(
loginWithPassword("https://hs.example.org", "alice", "hunter2"),
).resolves.toEqual(credentials);
expect(createClient).toHaveBeenCalledWith({
baseUrl: "https://hs.example.org",
});
expect(login).toHaveBeenCalledWith("m.login.password", {
identifier: { type: "m.id.user", user: "alice" },
password: "hunter2",
});
});
test("registers, agreeing to the terms and answering the recaptcha", async () => {
// The homeserver turns the first request away with the stages to complete
// No error in it: that is the shape of a challenge rather than a refusal
const challenge = new MatrixError(
{
session: "session",
flows: [{ stages: ["m.login.terms", "m.login.recaptcha"] }],
params: {},
completed: [],
},
401,
);
const registerRequest = vi
.fn()
.mockImplementation(({ auth }: { auth?: { type: string } }) => {
if (auth === undefined) throw challenge;
challenge.data.completed = [
...(challenge.data.completed as string[]),
auth.type,
];
if (challenge.data.completed.length < 2) throw challenge;
return credentials;
});
vi.mocked(createClient).mockReturnValue({
...authClient,
registerRequest,
} as Partial<MatrixClient> as MatrixClient);
await expect(
registerWithPassword(
"https://hs.example.org",
"alice",
"hunter2",
"captcha",
),
).resolves.toEqual(credentials);
expect(registerRequest).toHaveBeenCalledWith(
expect.objectContaining({
username: "alice",
password: "hunter2",
auth: expect.objectContaining({ type: "m.login.terms" }),
}),
);
expect(registerRequest).toHaveBeenCalledWith(
expect.objectContaining({
auth: expect.objectContaining({
type: "m.login.recaptcha",
response: "captcha",
}),
}),
);
});
+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 {
createClient,
InteractiveAuth,
type LoginResponse,
type RegisterResponse,
} from "matrix-js-sdk";
import { logger } from "matrix-js-sdk/lib/logger";
import { type StoredSession } from "../state/ClientSession";
/** What the homeserver hands out for a new session. */
export type Credentials = Pick<
StoredSession,
"user_id" | "device_id" | "access_token"
>;
/**
* Logs in to the given homeserver with a password.
*/
export async function loginWithPassword(
homeserver: string,
username: string,
password: string,
): Promise<Credentials> {
const authClient = createClient({ baseUrl: homeserver });
const interactiveAuth = new InteractiveAuth({
matrixClient: authClient,
doRequest: async (): Promise<LoginResponse> =>
authClient.login("m.login.password", {
identifier: {
type: "m.id.user",
user: username,
},
password,
}),
stateUpdated: (): void => {},
requestEmailToken: async (): Promise<{ sid: string }> =>
Promise.resolve({ sid: "" }),
});
return credentials(await interactiveAuth.attemptAuth());
}
/**
* Registers an account on the given homeserver, accepting its terms and
* answering its recaptcha challenge.
*/
export async function registerWithPassword(
homeserver: string,
username: string,
password: string,
recaptchaResponse: string,
): Promise<Credentials> {
const authClient = createClient({ baseUrl: homeserver });
const interactiveAuth = new InteractiveAuth({
matrixClient: authClient,
doRequest: async (auth): Promise<RegisterResponse> =>
authClient.registerRequest({
username,
password,
auth: auth || undefined,
}),
stateUpdated: (nextStage, status): void => {
if (status.error) {
throw new Error(status.error);
}
if (nextStage === "m.login.terms") {
interactiveAuth
.submitAuthDict({
type: "m.login.terms",
})
.catch((e) => {
logger.error(e);
});
} else if (nextStage === "m.login.recaptcha") {
interactiveAuth
.submitAuthDict({
type: "m.login.recaptcha",
response: recaptchaResponse,
})
.catch((e) => {
logger.error(e);
});
}
},
requestEmailToken: async (): Promise<{ sid: string }> =>
Promise.resolve({ sid: "dummy" }),
});
return credentials(await interactiveAuth.attemptAuth());
}
// XXX: attemptAuth claims to return an IAuthData which contains none of these
// things - the js-sdk types may be wrong?
function credentials(authData: unknown): Credentials {
/* eslint-disable camelcase */
const { user_id, access_token, device_id } = authData as Credentials;
return { user_id, access_token, device_id };
/* eslint-enable camelcase */
}
-84
View File
@@ -1,84 +0,0 @@
/*
Copyright 2022-2024 New Vector Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { useCallback } from "react";
import { InteractiveAuth } from "matrix-js-sdk";
import {
createClient,
type LoginResponse,
type MatrixClient,
} from "matrix-js-sdk";
import { initClient } from "../utils/initClient";
import { type Session } from "../ClientContext";
/**
* This provides the login method to login using user credentials.
* @param oldClient If there is an already authenticated client it should be passed to this hook
* this allows the interactive login to sign out the client before logging in.
* @returns A async method that can be called/awaited to log in with the provided credentials.
*/
export function useInteractiveLogin(
oldClient?: MatrixClient,
): (
homeserver: string,
username: string,
password: string,
) => Promise<[MatrixClient, Session]> {
return useCallback<
(
homeserver: string,
username: string,
password: string,
) => Promise<[MatrixClient, Session]>
>(
async (homeserver: string, username: string, password: string) => {
const authClient = createClient({ baseUrl: homeserver });
const interactiveAuth = new InteractiveAuth({
matrixClient: authClient,
doRequest: async (): Promise<LoginResponse> =>
authClient.login("m.login.password", {
identifier: {
type: "m.id.user",
user: username,
},
password,
}),
stateUpdated: (): void => {},
requestEmailToken: async (): Promise<{ sid: string }> =>
Promise.resolve({ sid: "" }),
});
// XXX: This claims to return an IAuthData which contains none of these
// things - the js-sdk types may be wrong?
/* eslint-disable camelcase,@typescript-eslint/no-explicit-any */
const { user_id, access_token, device_id } =
(await interactiveAuth.attemptAuth()) as any;
const session = {
user_id,
access_token,
device_id,
passwordlessUser: false,
};
// To not confuse the rust crypto sessions we need to logout the old client before initializing the new one.
await oldClient?.logout(true);
const client = await initClient(
{
baseUrl: homeserver,
accessToken: access_token,
userId: user_id,
deviceId: device_id,
},
false,
);
/* eslint-enable camelcase */
return [client, session];
},
[oldClient],
);
}
-145
View File
@@ -1,145 +0,0 @@
/*
Copyright 2022-2024 New Vector Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { useState, useEffect, useCallback, useRef } from "react";
import { InteractiveAuth } from "matrix-js-sdk";
import {
createClient,
type MatrixClient,
type RegisterResponse,
} from "matrix-js-sdk";
import { logger } from "matrix-js-sdk/lib/logger";
import { initClient } from "../utils/initClient";
import { type Session } from "../ClientContext";
import { Config } from "../config/Config";
import { useUrlParams } from "../UrlParams";
export const useInteractiveRegistration = (
oldClient?: MatrixClient,
): {
privacyPolicyUrl?: string;
recaptchaKey?: string;
register: (
username: string,
password: string,
displayName: string,
recaptchaResponse: string,
passwordlessUser: boolean,
) => Promise<[MatrixClient, Session]>;
} => {
const { isWidget } = useUrlParams();
const [privacyPolicyUrl, setPrivacyPolicyUrl] = useState<string | undefined>(
undefined,
);
const [recaptchaKey, setRecaptchaKey] = useState<string | undefined>(
undefined,
);
const authClient = useRef<MatrixClient | undefined>(undefined);
if (!authClient.current) {
authClient.current = createClient({
baseUrl: Config.defaultHomeserverUrl()!,
});
}
useEffect(() => {
if (isWidget) return;
// An empty registerRequest is used to get the privacy policy and recaptcha key.
authClient.current!.registerRequest({}).catch((error) => {
setPrivacyPolicyUrl(
error.data?.params["m.login.terms"]?.policies?.privacy_policy?.en?.url,
);
setRecaptchaKey(error.data?.params["m.login.recaptcha"]?.public_key);
});
}, [isWidget]);
const register = useCallback(
async (
username: string,
password: string,
displayName: string,
recaptchaResponse: string,
passwordlessUser: boolean,
): Promise<[MatrixClient, Session]> => {
const interactiveAuth = new InteractiveAuth({
matrixClient: authClient.current!,
doRequest: async (auth): Promise<RegisterResponse> =>
authClient.current!.registerRequest({
username,
password,
auth: auth || undefined,
}),
stateUpdated: (nextStage, status): void => {
if (status.error) {
throw new Error(status.error);
}
if (nextStage === "m.login.terms") {
interactiveAuth
.submitAuthDict({
type: "m.login.terms",
})
.catch((e) => {
logger.error(e);
});
} else if (nextStage === "m.login.recaptcha") {
interactiveAuth
.submitAuthDict({
type: "m.login.recaptcha",
response: recaptchaResponse,
})
.catch((e) => {
logger.error(e);
});
}
},
requestEmailToken: async (): Promise<{ sid: string }> =>
Promise.resolve({ sid: "dummy" }),
});
// XXX: This claims to return an IAuthData which contains none of these
// things - the js-sdk types may be wrong?
/* eslint-disable camelcase,@typescript-eslint/no-explicit-any */
const { user_id, access_token, device_id } =
(await interactiveAuth.attemptAuth()) as any;
await oldClient?.logout(true);
const client = await initClient(
{
baseUrl: Config.defaultHomeserverUrl()!,
accessToken: access_token,
userId: user_id,
deviceId: device_id,
},
false,
);
await client.setDisplayName(displayName);
const session: Session = {
user_id,
device_id,
access_token,
passwordlessUser,
};
/* eslint-enable camelcase */
if (passwordlessUser) {
session.tempPassword = password;
}
const user = client.getUser(client.getUserId()!)!;
user.setRawDisplayName(displayName);
user.setDisplayName(displayName);
return [client, session];
},
[oldClient],
);
return { privacyPolicyUrl, recaptchaKey, register };
};
@@ -0,0 +1,116 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { afterEach, expect, test, vi } from "vitest";
import { renderHook } from "@testing-library/react";
import { type FC, type PropsWithChildren } from "react";
import { type MatrixClient } from "matrix-js-sdk";
import { useRegisterPasswordlessUser } from "./useRegisterPasswordlessUser";
import { ClientManagerProvider } from "../ClientContext";
import { type ClientManager } from "../state/ClientSession";
import { computeUrlParams, UrlParamsProvider } from "../UrlParams";
vi.mock("./useRecaptcha", () => ({
useRecaptcha: () => ({
execute: vi.fn().mockResolvedValue("captcha-response"),
reset,
recaptchaId: "recaptcha",
}),
}));
vi.mock("./useRegistrationTerms", () => ({
useRegistrationTerms: () => ({
privacyPolicyUrl: "https://hs.example.org/privacy",
recaptchaKey: "site-key",
}),
}));
vi.mock("./generateRandomName", () => ({
generateRandomName: () => "Random Name",
}));
const reset = vi.fn();
afterEach(() => vi.clearAllMocks());
test("registers a user under a random name and signs them in", async () => {
const setSignedIn = vi.fn();
const manager = mockManager();
vi.mocked(manager.register).mockResolvedValue({
client: {} as MatrixClient,
setSignedIn,
});
const { result } = renderHook(() => useRegisterPasswordlessUser(), {
wrapper: wrapper(manager, false),
});
await result.current.registerPasswordlessUser("Alice");
expect(manager.register).toHaveBeenCalledWith(
"Random Name",
expect.stringMatching(/^.{16}$/),
"Alice",
"captcha-response",
true,
);
expect(setSignedIn).toHaveBeenCalled();
expect(result.current.privacyPolicyUrl).toBe(
"https://hs.example.org/privacy",
);
expect(result.current.recaptchaId).toBe("recaptcha");
});
test("resets the captcha when registration fails", async () => {
const manager = mockManager();
vi.mocked(manager.register).mockRejectedValue(new Error("Nope"));
const { result } = renderHook(() => useRegisterPasswordlessUser(), {
wrapper: wrapper(manager, false),
});
await expect(
result.current.registerPasswordlessUser("Alice"),
).rejects.toThrow("Nope");
expect(reset).toHaveBeenCalled();
});
test("cannot register on a session that is not ours", async () => {
const { result } = renderHook(() => useRegisterPasswordlessUser(), {
wrapper: wrapper(null, false),
});
await expect(
result.current.registerPasswordlessUser("Alice"),
).rejects.toThrow("This session cannot register");
});
test("never registers as a widget", async () => {
const manager = mockManager();
const { result } = renderHook(() => useRegisterPasswordlessUser(), {
wrapper: wrapper(manager, true),
});
await expect(
result.current.registerPasswordlessUser("Alice"),
).rejects.toThrow(/embedded mode/);
expect(manager.register).not.toHaveBeenCalled();
});
function mockManager(): ClientManager {
return { login: vi.fn(), register: vi.fn(), logout: vi.fn() };
}
function wrapper(
manager: ClientManager | null,
isWidget: boolean,
): FC<PropsWithChildren> {
const params = { ...computeUrlParams(), isWidget };
return ({ children }) => (
<UrlParamsProvider value={params}>
<ClientManagerProvider value={manager}>{children}</ClientManagerProvider>
</UrlParamsProvider>
);
}
+10 -10
View File
@@ -8,8 +8,8 @@ Please see LICENSE in the repository root for full details.
import { useCallback } from "react";
import { secureRandomString } from "matrix-js-sdk/lib/randomstring";
import { useClient } from "../ClientContext";
import { useInteractiveRegistration } from "../auth/useInteractiveRegistration";
import { useClientManagerIfAny } from "../ClientContext";
import { useRegistrationTerms } from "../auth/useRegistrationTerms";
import { generateRandomName } from "../auth/generateRandomName";
import { useRecaptcha } from "../auth/useRecaptcha";
import { useUrlParams } from "../UrlParams";
@@ -21,16 +21,16 @@ interface UseRegisterPasswordlessUserType {
}
export function useRegisterPasswordlessUser(): UseRegisterPasswordlessUserType {
const { setClient } = useClient();
// Null in the widget, which never registers anyone
const register = useClientManagerIfAny()?.register;
const { isWidget } = useUrlParams();
const { privacyPolicyUrl, recaptchaKey, register } =
useInteractiveRegistration();
const { privacyPolicyUrl, recaptchaKey } = useRegistrationTerms();
const { execute, reset, recaptchaId } = useRecaptcha(recaptchaKey);
const registerPasswordlessUser = useCallback(
async (displayName: string) => {
if (!setClient) {
throw new Error("No client context");
if (!register) {
throw new Error("This session cannot register");
}
if (isWidget) {
throw new Error(
@@ -41,20 +41,20 @@ export function useRegisterPasswordlessUser(): UseRegisterPasswordlessUserType {
try {
const recaptchaResponse = await execute();
const userName = generateRandomName();
const [client, session] = await register(
const { setSignedIn } = await register(
userName,
secureRandomString(16),
displayName,
recaptchaResponse,
true,
);
setClient(client, session);
setSignedIn();
} catch (e) {
reset();
throw e;
}
},
[execute, reset, register, setClient, isWidget],
[execute, reset, register, isWidget],
);
return { privacyPolicyUrl, registerPasswordlessUser, recaptchaId };
+98
View File
@@ -0,0 +1,98 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { afterEach, beforeEach, expect, test, vi } from "vitest";
import { renderHook, waitFor } from "@testing-library/react";
import type * as MatrixJsSdk from "matrix-js-sdk";
import { createClient, type MatrixClient } from "matrix-js-sdk";
import { type FC, type PropsWithChildren } from "react";
import { useRegistrationTerms } from "./useRegistrationTerms";
import { computeUrlParams, UrlParamsProvider } from "../UrlParams";
import { Config } from "../config/Config";
vi.mock("matrix-js-sdk", async (importOriginal) => ({
...(await importOriginal<typeof MatrixJsSdk>()),
createClient: vi.fn(),
}));
const registerRequest = vi.fn();
beforeEach(() => {
vi.spyOn(Config, "defaultHomeserverUrl").mockReturnValue(
"https://hs.example.org",
);
vi.mocked(createClient).mockReturnValue({
registerRequest,
} as Partial<MatrixClient> as MatrixClient);
});
afterEach(() => {
vi.restoreAllMocks();
vi.clearAllMocks();
});
test("reads the terms the homeserver asks for from a registration attempt", async () => {
registerRequest.mockRejectedValue({
data: {
params: {
"m.login.terms": {
policies: {
privacy_policy: { en: { url: "https://hs.example.org/privacy" } },
},
},
"m.login.recaptcha": { public_key: "site-key" },
},
},
});
const { result } = renderHook(() => useRegistrationTerms(), {
wrapper: wrapper(false),
});
expect(createClient).toHaveBeenCalledWith({
baseUrl: "https://hs.example.org",
});
await waitFor(() =>
expect(result.current).toEqual({
privacyPolicyUrl: "https://hs.example.org/privacy",
recaptchaKey: "site-key",
}),
);
});
test("has nothing to agree to where the homeserver asks for nothing", async () => {
registerRequest.mockRejectedValue({ data: { params: {} } });
const { result } = renderHook(() => useRegistrationTerms(), {
wrapper: wrapper(false),
});
await waitFor(() => expect(registerRequest).toHaveBeenCalled());
expect(result.current).toEqual({
privacyPolicyUrl: undefined,
recaptchaKey: undefined,
});
});
test("asks the homeserver nothing as a widget", () => {
const { result } = renderHook(() => useRegistrationTerms(), {
wrapper: wrapper(true),
});
expect(createClient).not.toHaveBeenCalled();
expect(result.current).toEqual({
privacyPolicyUrl: undefined,
recaptchaKey: undefined,
});
});
function wrapper(isWidget: boolean): FC<PropsWithChildren> {
const params = { ...computeUrlParams(), isWidget };
return ({ children }) => (
<UrlParamsProvider value={params}>{children}</UrlParamsProvider>
);
}
+46
View File
@@ -0,0 +1,46 @@
/*
Copyright 2022-2024 New Vector Ltd.
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 { useEffect, useState } from "react";
import { createClient } from "matrix-js-sdk";
import { Config } from "../config/Config";
import { useUrlParams } from "../UrlParams";
/**
* What the homeserver asks of a registration: its privacy policy to agree to
* and the recaptcha key to answer a challenge with.
*/
export function useRegistrationTerms(): {
privacyPolicyUrl?: string;
recaptchaKey?: string;
} {
const { isWidget } = useUrlParams();
const [privacyPolicyUrl, setPrivacyPolicyUrl] = useState<string | undefined>(
undefined,
);
const [recaptchaKey, setRecaptchaKey] = useState<string | undefined>(
undefined,
);
useEffect(() => {
if (isWidget) return;
// An empty registerRequest is used to get the privacy policy and recaptcha key.
createClient({ baseUrl: Config.defaultHomeserverUrl()! })
.registerRequest({})
.catch((error) => {
setPrivacyPolicyUrl(
error.data?.params["m.login.terms"]?.policies?.privacy_policy?.en
?.url,
);
setRecaptchaKey(error.data?.params["m.login.recaptcha"]?.public_key);
});
}, [isWidget]);
return { privacyPolicyUrl, recaptchaKey };
}
+1 -1
View File
@@ -45,7 +45,7 @@ interface Props {
/** Offers to add a background of one's own. Omit to leave that tile out. */
onAdd?: () => void;
addLabel?: string;
/** Removes a removable one, unless it is the selected one. Omit to offer none. */
/** Removes a removable one, never the one in force. Omit to offer none. */
onRemove?: (id: string) => void;
removeLabel?: string;
}
+193 -68
View File
@@ -22,7 +22,7 @@ import { MediaDevices } from "../state/MediaDevices";
import { globalScope } from "../state/ObservableScope";
import { constant } from "../state/Behavior";
import { type LayoutMode } from "../state/LayoutSwitchViewModel";
import { type MediaMenuSnapshot } from "./MediaMenuViewModel";
import { shippedBackgrounds } from "../tracks/backgroundEffectCatalog";
// consts for tests
const reactionIdentifier = "@user:example.com:DEVICE";
@@ -35,57 +35,10 @@ const mediaDevices = new MediaDevices(globalScope, {
controlledAudioDevices: false,
});
function menu(
kind: "audio" | "video",
withDevices: boolean,
): MediaMenuSnapshot {
const device = kind === "audio" ? "Microphone" : "Camera";
return {
enabled: true,
busy: false,
toggle: fn(),
options: withDevices
? [
{ id: "1", label: { type: "name", name: `${device} 1` } },
{ id: "2", label: { type: "name", name: `${device} 2` } },
]
: [],
selected: "1",
select: fn(),
outputOptions:
withDevices && kind === "audio"
? [
{
id: "default",
label: { type: "default", name: "Built-in Output" },
},
]
: [],
selectedOutput: "default",
selectOutput: fn(),
backgroundEffect: "none",
backgroundEffects:
kind === "video"
? [
{ id: "none", kind: "none" },
{ id: "blur", kind: "blur" },
]
: [],
backgroundEffectNotice: undefined,
backgroundEffectSettling: false,
backgroundImageRefusal: undefined,
selectBackgroundEffect: fn(),
addBackgroundImage: undefined,
removeBackgroundEffect: undefined,
cameraTrack: null,
};
}
/**
* A wrapper component that is used for:
* - exposing the snapshot via props so the storybook documents the snapshot properties (basically unpack them form the vm)
* - constructing the layout switch and the menus' view models; the menus'
* own states are in the MediaMenuButton stories
* - constructing the layout switch view model
* - Add additional react context
* The paraeters are all params from the FooterSnapshot,
* the Snapshot of the vm, the wrapper will create a mocked vm from it and pass it to the CallFooter.
@@ -96,22 +49,15 @@ function CallFooterStoryWrapper({
children,
layout,
setLayout,
withDevices,
...vmSnapshot
}: Omit<FooterSnapshot, "layoutSwitchVm" | "audioMenuVm" | "cameraMenuVm"> & {
}: Omit<FooterSnapshot, "layoutSwitchVm"> & {
children?: false | JSX.Element | JSX.Element[] | undefined;
layout: LayoutMode | null;
setLayout: (value: LayoutMode) => void;
/** Whether the menus have devices to pick, or are plain mute buttons. */
withDevices: boolean;
}): ReactNode {
const audioMenuVm = useStaticViewModel(menu("audio", withDevices));
const cameraMenuVm = useStaticViewModel(menu("video", withDevices));
const vm = useStaticViewModel({
...vmSnapshot,
layoutSwitchVm: layout && { layout$: constant(layout), setLayout },
audioMenuVm,
cameraMenuVm,
});
return (
<MediaDevicesContext value={mediaDevices}>
@@ -156,6 +102,8 @@ const meta = {
},
toggleScreenSharing: fnArgType,
openSettings: fnArgType,
toggleAudio: fnArgType,
toggleVideo: fnArgType,
hangup: fnArgType,
},
} satisfies Meta<typeof CallFooterStoryWrapper>;
@@ -168,9 +116,32 @@ export const Default: Story = {
showLogo: false,
layout: "grid",
setLayout: fn(),
withDevices: false,
audioEnabled: true,
audioBusy: false,
videoEnabled: true,
videoBusy: false,
openSettings: fn(),
toggleAudio: fn(),
toggleVideo: fn(),
toggleScreenSharing: fn(),
selectBackgroundEffect: fn(),
backgroundEffect: "blur",
backgroundEffects: [
{ id: "none", kind: "none", removable: false },
{ id: "blur", kind: "blur", removable: false },
...shippedBackgrounds.map((background) => ({
id: `image:${background.id}`,
kind: "image" as const,
imageUrl: background.imagePath,
removable: false,
})),
],
backgroundEffectNotice: undefined,
backgroundEffectSettling: false,
backgroundImageRefusal: undefined,
addBackgroundImage: fn(),
removeBackgroundEffect: fn(),
cameraTrack: null,
hangup: fn(),
buttonSize: "lg",
showFooter: true,
@@ -183,17 +154,49 @@ export const Default: Story = {
reactionData: undefined,
debugTileLayout: false,
tileStoreGeneration: undefined,
audioOptions: [],
audioOutputOptions: [],
videoOptions: [],
selectedAudio: undefined,
selectedAudioOutput: undefined,
selectedVideo: undefined,
selectAudioButtonOption: undefined,
selectAudioOutputOption: undefined,
selectVideoButtonOption: undefined,
},
parameters: {
layout: "fullscreen",
},
};
export const StaysWhileAMenuIsOpen: Story = {
export const WithAudioAndVideoOptions: Story = {
...Default,
args: {
...Default.args,
withDevices: true,
audioEnabled: false,
videoEnabled: true,
audioOptions: [
{ label: { type: "name", name: "Microphone 1" }, id: "1" },
{ label: { type: "name", name: "Microphone 2" }, id: "2" },
],
audioOutputOptions: [
{ label: { type: "default", name: "Built-in Output" }, id: "default" },
{ label: { type: "name", name: "Headset" }, id: "2" },
],
videoOptions: [
{ label: { type: "name", name: "Camera 1" }, id: "1" },
{ label: { type: "name", name: "Camera 2" }, id: "2" },
],
selectedAudio: "2",
selectedAudioOutput: "default",
selectedVideo: "1",
},
};
export const StaysWhileAMenuIsOpen: Story = {
...Default,
args: {
...WithAudioAndVideoOptions.args,
// In a short window the footer overlays the call and hides itself.
asOverlay: true,
showFooter: true,
@@ -216,6 +219,25 @@ export const StaysWhileAMenuIsOpen: Story = {
},
};
export const AudioBusy: Story = {
...Default,
args: {
...Default.args,
audioEnabled: true,
audioBusy: true,
videoEnabled: true,
},
};
export const VideoBusy: Story = {
...Default,
args: {
...Default.args,
audioEnabled: true,
videoEnabled: true,
videoBusy: true,
},
};
export const WithLogo: Story = {
...Default,
args: {
@@ -224,7 +246,45 @@ export const WithLogo: Story = {
},
};
/** Switching to grid, and the footer's own buttons, act. */
export const AudioVideoEnabled: Story = {
...Default,
args: {
...Default.args,
audioEnabled: true,
videoEnabled: true,
},
play: async ({ args, canvasElement }) => {
const canvas = within(canvasElement);
const spotlightRadio = canvas.getByRole("radio", { name: "Spotlight" });
await userEvent.click(spotlightRadio);
await expect(args.setLayout).toHaveBeenCalledWith("spotlight");
const micButtonMute = canvas.getByRole("switch", {
name: "Mute microphone",
});
await userEvent.click(micButtonMute);
await expect(args.toggleAudio).toHaveBeenCalled();
const videoMuteButton = canvas.getByRole("switch", {
name: "Stop video",
});
await userEvent.click(videoMuteButton);
await expect(args.toggleVideo).toHaveBeenCalled();
const screenShare = canvas.getByRole("switch", {
name: "Share screen",
});
await userEvent.click(screenShare);
await expect(args.toggleScreenSharing).toHaveBeenCalled();
const endCall = canvas.getByRole("button", {
name: "End call",
});
await userEvent.click(endCall);
await expect(args.hangup).toHaveBeenCalled();
},
};
/** used to test switching to grid mode */
export const SpotlightMode: Story = {
...Default,
args: {
@@ -233,12 +293,10 @@ export const SpotlightMode: Story = {
},
play: async ({ args, canvasElement }) => {
const canvas = within(canvasElement);
await userEvent.click(canvas.getByRole("radio", { name: "Grid" }));
const spotlightRadio = canvas.getByRole("radio", { name: "Grid" });
await userEvent.click(spotlightRadio);
await expect(args.setLayout).toHaveBeenCalledWith("grid");
await userEvent.click(canvas.getByRole("switch", { name: "Share screen" }));
await expect(args.toggleScreenSharing).toHaveBeenCalled();
await userEvent.click(canvas.getByRole("button", { name: "End call" }));
await expect(args.hangup).toHaveBeenCalled();
},
};
@@ -272,10 +330,34 @@ export const Pip: Story = {
buttonSize: "md",
layout: null,
},
play: async ({ canvasElement }) => {
play: async ({ args, canvasElement }) => {
const canvas = within(canvasElement);
await expect(
within(canvasElement).queryByRole("radio", { name: "Spotlight" }),
canvas.queryByRole("radio", { name: "Spotlight" }),
).not.toBeInTheDocument();
const micButtonMute = canvas.getByRole("switch", {
name: "Mute microphone",
});
await userEvent.click(micButtonMute);
await expect(args.toggleAudio).toHaveBeenCalled();
const videoMuteButton = canvas.getByRole("switch", {
name: "Stop video",
});
await userEvent.click(videoMuteButton);
await expect(args.toggleVideo).toHaveBeenCalled();
const screenShare = canvas.getByRole("switch", {
name: "Share screen",
});
await userEvent.click(screenShare);
await expect(args.toggleScreenSharing).toHaveBeenCalled();
const endCall = canvas.getByRole("button", {
name: "End call",
});
await userEvent.click(endCall);
await expect(args.hangup).toHaveBeenCalled();
},
};
export const NoControlsWithLogo: Story = {
@@ -296,6 +378,18 @@ export const DebugData: Story = {
},
};
export const UnavailableMediaDevices: Story = {
...Default,
args: {
...Default.args,
audioEnabled: false,
videoEnabled: false,
toggleAudio: undefined,
toggleVideo: undefined,
audioOutputSwitcher: undefined,
},
};
export const MobileLayout: Story = {
...Default,
args: {
@@ -326,6 +420,37 @@ export const Lobby: Story = {
},
};
export const LobbyMobile: Story = {
...Default,
args: {
...Default.args,
showLogo: false,
layout: null,
toggleScreenSharing: undefined,
},
globals: {
viewport: { value: "mobile2", isRotated: false },
},
parameters: {
...Default.parameters,
},
};
export const LobbyRecentButton: Story = {
...Default,
args: {
...Default.args,
children: <Link>Back To Recents</Link>,
showLogo: false,
layout: null,
toggleScreenSharing: undefined,
},
parameters: {
...Default.parameters,
},
};
export const LobbyRecentButtonMobile: Story = {
...Default,
args: {
+165 -20
View File
@@ -7,11 +7,14 @@ Please see LICENSE in the repository root for full details.
import { type FC, type JSX, type Ref, useMemo } from "react";
import classNames from "classnames";
import { useTranslation } from "react-i18next";
import LogoMark from "../icons/LogoMark.svg?react";
import LogoType from "../icons/LogoType.svg?react";
import {
EndCallButton,
MicButton,
VideoButton,
ShareScreenButton,
SettingsButton,
ReactionToggleButton,
@@ -20,13 +23,23 @@ import {
type ReactionData,
} from "../button";
import styles from "./CallFooter.module.css";
import {
MediaMuteAndSwitchButton,
type MenuOptions,
} from "./MediaMuteAndSwitchButton";
import { type Behavior } from "../state/Behavior";
import { type ViewModel } from "../state/ViewModel";
import { useBehavior } from "../useBehavior";
import { type LayoutSwitchViewModel } from "../state/LayoutSwitchViewModel";
import { LayoutSwitch } from "../room/LayoutSwitch";
import { type MediaMenuViewModel } from "./MediaMenuViewModel";
import { MediaMenuButton } from "./MediaMenuButton";
import { type BackgroundEffectGridItem } from "./BackgroundEffectGrid";
import { SelfPreview } from "./SelfPreview";
import { type UnusableReason } from "../tracks/backgroundImages";
import { type LocalVideoMediaTrack } from "@element-hq/matrixrtc-sdk";
export interface BackgroundImageRefusal {
reason: UnusableReason | "not-kept";
}
export interface AudioOutputSwitcher {
targetOutput: string;
@@ -48,6 +61,16 @@ export interface AudioOutputSwitcher {
*/
export type FooterSnapshot = FooterActions & FooterState;
export interface FooterActions {
/** Also controls if the audioMute button is disabled */
toggleAudio: (() => void) | undefined;
/** Also controls if the videoMute button is disabled */
toggleVideo: (() => void) | undefined;
/** Undefined where background effects can't be chosen. */
selectBackgroundEffect: ((id: string) => void) | undefined;
/** Undefined where no background can be added. */
addBackgroundImage: ((file: File) => void) | undefined;
/** Removes an added background by its option id; never the one in force. */
removeBackgroundEffect: ((id: string) => void) | undefined;
toggleScreenSharing: (() => void) | undefined;
/** Also controls if the settings button is visible */
openSettings: (() => void) | undefined;
@@ -57,8 +80,22 @@ export interface FooterActions {
// we do not use any ? optional properties so that the vm type is including all fields.
export interface FooterState {
audioMenuVm: MediaMenuViewModel;
cameraMenuVm: MediaMenuViewModel;
audioEnabled: boolean;
audioBusy: boolean;
videoEnabled: boolean;
videoBusy: boolean;
/** The background effect in force, as its option id. */
backgroundEffect: string;
/** Every effect on offer, in the order they are shown. */
backgroundEffects: BackgroundEffectGridItem[];
/** What the user is told about effects here, if anything. */
backgroundEffectNotice: "unavailable" | "slow" | undefined;
/** Whether the first effect chosen is still being prepared. */
backgroundEffectSettling: boolean;
/** Why the last file offered couldn't be kept, if it couldn't. */
backgroundImageRefusal: BackgroundImageRefusal | undefined;
/** The camera to preview, with the effect in force; null while it is off. */
cameraTrack: LocalVideoMediaTrack | null;
showFooter: boolean;
/* This is needed for WindowMode = "flat" */
@@ -85,6 +122,19 @@ export interface FooterState {
// debug stuff
debugTileLayout: boolean;
tileStoreGeneration: number | undefined;
/** Providing no options `[]` or `undefined` will imply that we dont have a audio fast switcher */
audioOptions: MenuOptions[];
/** Output (speaker) devices. */
audioOutputOptions: MenuOptions[];
/** Providing no options `[]` or `undefined` will imply that we dont have a audio fast switcher */
videoOptions: MenuOptions[];
selectedAudio: string | undefined;
selectedAudioOutput: string | undefined;
selectedVideo: string | undefined;
selectAudioButtonOption: ((deviceId: string) => void) | undefined;
selectAudioOutputOption: ((deviceId: string) => void) | undefined;
selectVideoButtonOption: ((option: string) => void) | undefined;
}
export interface FooterProps {
@@ -100,14 +150,19 @@ export const CallFooter: FC<FooterProps> = ({
children,
vm,
}) => {
const { t } = useTranslation();
const asOverlay = useBehavior(vm.asOverlay$);
const showFooter = useBehavior(vm.showFooter$);
const hideControls = useBehavior(vm.hideControls$);
const showModals = useBehavior(vm.showModals$);
const layoutSwitchVm = useBehavior(vm.layoutSwitchVm$);
const audioMenuVm = useBehavior(vm.audioMenuVm$);
const cameraMenuVm = useBehavior(vm.cameraMenuVm$);
const openSettings = useBehavior(vm.openSettings$);
const audioEnabled = useBehavior(vm.audioEnabled$);
const audioBusy = useBehavior(vm.audioBusy$);
const videoEnabled = useBehavior(vm.videoEnabled$);
const videoBusy = useBehavior(vm.videoBusy$);
const toggleAudio = useBehavior(vm.toggleAudio$);
const toggleVideo = useBehavior(vm.toggleVideo$);
const sharingScreen = useBehavior(vm.sharingScreen$);
const toggleScreenSharing = useBehavior(vm.toggleScreenSharing$);
const reactionIdentifier = useBehavior(vm.reactionIdentifier$);
@@ -115,6 +170,38 @@ export const CallFooter: FC<FooterProps> = ({
const audioOutputSwitcher = useBehavior(vm.audioOutputSwitcher$);
const hangup = useBehavior(vm.hangup$);
const debugTileLayout = useBehavior(vm.debugTileLayout$);
const videoOptions = useBehavior(vm.videoOptions$);
const selectedVideo = useBehavior(vm.selectedVideo$);
const audioOptions = useBehavior(vm.audioOptions$);
const selectedAudio = useBehavior(vm.selectedAudio$);
const selectAudioButtonOption = useBehavior(vm.selectAudioButtonOption$);
const audioOutputOptions = useBehavior(vm.audioOutputOptions$);
const selectedAudioOutput = useBehavior(vm.selectedAudioOutput$);
const selectAudioOutputOption = useBehavior(vm.selectAudioOutputOption$);
const selectVideoButtonOption = useBehavior(vm.selectVideoButtonOption$);
const backgroundEffect = useBehavior(vm.backgroundEffect$);
const selectBackgroundEffect = useBehavior(vm.selectBackgroundEffect$);
const backgroundEffectNotice = useBehavior(vm.backgroundEffectNotice$);
const backgroundEffectSettling = useBehavior(vm.backgroundEffectSettling$);
const addBackgroundImage = useBehavior(vm.addBackgroundImage$);
const removeBackgroundEffect = useBehavior(vm.removeBackgroundEffect$);
const cameraTrack = useBehavior(vm.cameraTrack$);
const refusal = useBehavior(vm.backgroundImageRefusal$);
const refusalMessage = useMemo(() => {
switch (refusal?.reason) {
case undefined:
return undefined;
case "not-an-image":
return { text: t("error.background_not_an_image") };
case "animated":
return { text: t("error.background_animated") };
case "undecodable":
return { text: t("error.background_undecodable") };
case "not-kept":
return { text: t("error.background_not_kept") };
}
}, [refusal, t]);
const backgroundEffects = useBehavior(vm.backgroundEffects$);
const buttonSize = useBehavior(vm.buttonSize$);
const showLogo = useBehavior(vm.showLogo$);
@@ -134,20 +221,78 @@ export const CallFooter: FC<FooterProps> = ({
);
}
buttons.push(
<MediaMenuButton
key="audio"
kind="audio"
vm={audioMenuVm}
size={buttonSize}
/>,
<MediaMenuButton
key="video"
kind="video"
vm={cameraMenuVm}
size={buttonSize}
/>,
);
if ((audioOptions?.length ?? 0) > 0) {
buttons.push(
<MediaMuteAndSwitchButton
key="audio"
iconsAndLabels="audio"
enabled={audioEnabled ?? false}
busy={audioBusy ?? false}
onMuteClick={toggleAudio}
data-testid="incall_mute"
options={audioOptions}
selectedOption={selectedAudio}
onSelect={selectAudioButtonOption}
outputOptions={audioOutputOptions}
selectedOutputOption={selectedAudioOutput}
onSelectOutput={selectAudioOutputOption}
/>,
);
} else {
buttons.push(
<MicButton
size={buttonSize}
key="audio"
enabled={audioEnabled ?? false}
busy={audioBusy ?? false}
onClick={toggleAudio}
disabled={(audioBusy ?? false) || toggleAudio === undefined}
data-testid="incall_mute"
/>,
);
}
if ((videoOptions?.length ?? 0) > 0) {
buttons.push(
<MediaMuteAndSwitchButton
key="video"
iconsAndLabels="video"
enabled={videoEnabled ?? false}
busy={videoBusy ?? false}
onMuteClick={toggleVideo}
options={videoOptions}
selectedOption={selectedVideo}
onSelect={selectVideoButtonOption}
backgroundEffects={backgroundEffects}
selectedBackgroundEffect={backgroundEffect}
onSelectBackgroundEffect={selectBackgroundEffect}
backgroundEffectSettling={backgroundEffectSettling}
onAddBackgroundImage={addBackgroundImage}
onRemoveBackgroundEffect={removeBackgroundEffect}
selfPreview={<SelfPreview track={cameraTrack} />}
backgroundImageRefusal={refusalMessage}
backgroundEffectNotice={
backgroundEffectNotice === "unavailable"
? t("background_effects.unavailable")
: backgroundEffectNotice === "slow"
? t("background_effects.slow")
: undefined
}
/>,
);
} else {
buttons.push(
<VideoButton
size={buttonSize}
key="video"
enabled={videoEnabled ?? false}
busy={videoBusy ?? false}
onClick={toggleVideo}
disabled={(videoBusy ?? false) || toggleVideo === undefined}
data-testid="incall_videomute"
/>,
);
}
if (toggleScreenSharing !== undefined) {
buttons.push(
+446 -63
View File
@@ -5,15 +5,18 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { describe, expect, it, vi } from "vitest";
import { afterEach, describe, expect, it, vi } from "vitest";
import { BehaviorSubject } from "rxjs";
import { type LocalVideoMediaTrack } from "@element-hq/matrixrtc-sdk";
import {
flushPromises,
testScope,
mockMuteStates,
mockMediaDevices,
mockVideoTrack,
} from "../utils/test";
import { constant } from "../state/Behavior";
import { type Behavior, constant } from "../state/Behavior";
import { type BackgroundEffectsState } from "../state/BackgroundEffects";
import type { CallViewModel } from "../state/CallViewModel/CallViewModel";
import type { Layout } from "../state/layout-types";
@@ -24,6 +27,15 @@ import {
createLobbyFooterViewModel,
} from "./CallFooterViewModel";
import { HeaderStyle } from "../UrlParams";
import { backgroundEffect as backgroundEffectSetting } from "../settings/settings";
import { shippedBackgrounds } from "../tracks/backgroundEffectCatalog";
import type * as BackgroundImages from "../tracks/backgroundImages";
import {
type AddedBackground,
addedBackgrounds,
maxAddedBackgrounds,
UnusableImage,
} from "../tracks/backgroundImages";
const platformMock = vi.hoisted(() => vi.fn(() => "desktop"));
vi.mock("../Platform", () => ({
@@ -32,6 +44,35 @@ vi.mock("../Platform", () => ({
},
}));
// The SDK's own check needs WebGL and canvas APIs jsdom does not have.
const sdkSupportMock = vi.hoisted(() => vi.fn(() => false));
const modernRouteMock = vi.hoisted(() => vi.fn(() => true));
vi.mock("@livekit/track-processors", () => ({
supportsBackgroundProcessors: (): boolean => sdkSupportMock(),
supportsModernBackgroundProcessors: (): boolean => modernRouteMock(),
}));
const store = vi.hoisted(() => ({
add: vi.fn<(file: Blob) => Promise<string>>(),
remove: vi.fn<(id: string) => Promise<void>>(),
}));
vi.mock("../tracks/backgroundImages", async (original) => {
const { BehaviorSubject } = await import("rxjs");
return {
...(await original<typeof BackgroundImages>()),
addedBackgrounds: {
added$: new BehaviorSubject<AddedBackground[] | undefined>([]),
add: store.add,
remove: store.remove,
},
};
});
const outputSelectionMock = vi.hoisted(() => vi.fn(() => true));
vi.mock("livekit-client", () => ({
supportsAudioOutputSelection: (): boolean => outputSelectionMock(),
}));
/**
* Returns the minimum set of CallViewModel fields required by
* createCallFooterViewModel, with all other properties stubbed to
@@ -72,82 +113,424 @@ const pipLayout: Layout = {
spotlight: {} as SpotlightTileViewModel,
};
const pipeline = constant<BackgroundEffectsState>({
supported: true,
const noPipeline = constant<BackgroundEffectsState>({
supported: false,
processor: undefined,
});
const oneOfEach = {
available$: constant(
new Map<string, DeviceLabel>([["1", { type: "number", number: 1 }]]),
),
selected$: constant(undefined),
select: vi.fn(),
};
const devices = mockMediaDevices({
audioInput: oneOfEach,
videoInput: oneOfEach,
/** The provider's verdict, which the SDK's check stands for here. */
function pipelineAsTheSdkSays(): Behavior<BackgroundEffectsState> {
return constant({ supported: sdkSupportMock(), processor: undefined });
}
const twoMicsAndOneCamMediaDevices = mockMediaDevices({
audioInput: {
available$: constant(
new Map<string, DeviceLabel>([
["mic1", { type: "number", number: 1 }],
["mic2", { type: "name", name: "Microphone 2" }],
]),
),
selected$: constant(undefined),
select: vi.fn(),
},
videoInput: {
available$: constant(
new Map<string, DeviceLabel>([
["cam1", { type: "name", name: "Camera 1" }],
]),
),
selected$: constant(undefined),
select: vi.fn(),
},
});
describe("createCallFooterViewModel", () => {
it.each([
["desktop", "grid", true, gridLayout],
["ios", "grid", false, gridLayout],
["desktop", "pip", false, pipLayout],
] as const)(
"on %s in a %s layout, offers the device menus: %s",
(platform, _, offered, layout) => {
describe("selectAudioOutputOption", () => {
function buildFooterVm(): ReturnType<typeof createCallFooterViewModel> {
platformMock.mockReturnValue("desktop");
return createCallFooterViewModel(
testScope(),
buildMinimalCallViewModel(gridLayout),
mockMuteStates(),
twoMicsAndOneCamMediaDevices,
noPipeline,
/* reactionIdentifier */ undefined,
{ showControls: true, header: HeaderStyle.Standard },
);
}
it("is withheld where the platform cannot route audio to a chosen device", () => {
outputSelectionMock.mockReturnValue(false);
expect(buildFooterVm().selectAudioOutputOption$.value).toBeUndefined();
});
it("is offered where the platform can route audio to a chosen device", () => {
outputSelectionMock.mockReturnValue(true);
expect(buildFooterVm().selectAudioOutputOption$.value).toBeDefined();
});
});
describe("audioOutputOptions", () => {
it("is an empty list, not absent, where the platform enumerates no outputs", () => {
platformMock.mockReturnValue("desktop");
outputSelectionMock.mockReturnValue(true);
const vm = createCallFooterViewModel(
testScope(),
buildMinimalCallViewModel(gridLayout),
mockMuteStates(),
mockMediaDevices({
audioInput: {
available$: constant(
new Map<string, DeviceLabel>([
["mic1", { type: "name", name: "Microphone 1" }],
]),
),
selected$: constant(undefined),
select: vi.fn(),
},
// As Safari: no outputs listed.
audioOutput: {
available$: constant(new Map<string, DeviceLabel>()),
selected$: constant(undefined),
select: vi.fn(),
},
}),
noPipeline,
/* reactionIdentifier */ undefined,
{ showControls: true, header: HeaderStyle.Standard },
);
// Empty, not undefined: undefined would hide the section.
expect(vm.audioOutputOptions$.value).toEqual([]);
});
});
describe("audioOptions and videoOptions", () => {
function checkEmptyFor(platform: string, layout: Layout): void {
platformMock.mockReturnValue(platform);
const vm = createCallFooterViewModel(
testScope(),
buildMinimalCallViewModel(layout),
mockMuteStates(),
devices,
pipeline,
twoMicsAndOneCamMediaDevices,
noPipeline,
/* reactionIdentifier */ undefined,
{ showControls: true, header: HeaderStyle.Standard },
);
const audio = vm.audioMenuVm$.value;
const camera = vm.cameraMenuVm$.value;
expect(audio.options$.value.length > 0).toBe(offered);
expect(camera.options$.value.length > 0).toBe(offered);
expect(camera.selectBackgroundEffect$.value !== undefined).toBe(offered);
},
);
it("previews the call's camera", () => {
const track = mockVideoTrack({});
const vm = createCallFooterViewModel(
testScope(),
{ ...buildMinimalCallViewModel(gridLayout), camera$: constant(track) },
mockMuteStates(),
devices,
pipeline,
/* reactionIdentifier */ undefined,
{ showControls: true, header: HeaderStyle.Standard },
);
expect(vm.cameraMenuVm$.value.cameraTrack$.value).toBe(track);
expect(vm.audioOptions$.value).toEqual([]);
expect(vm.videoOptions$.value).toEqual([]);
}
it("are both empty when the platform is iOS", () => {
checkEmptyFor("ios", gridLayout);
});
it("are both empty when the layout is pip", () => {
checkEmptyFor("desktop", pipLayout);
});
it("are populated when the platform is desktop and the layout is not PiP", () => {
platformMock.mockReturnValue("desktop");
const vm = createCallFooterViewModel(
testScope(),
buildMinimalCallViewModel(gridLayout),
mockMuteStates(),
twoMicsAndOneCamMediaDevices,
noPipeline,
/* reactionIdentifier */ undefined,
{ showControls: true, header: HeaderStyle.Standard },
);
expect(vm.audioOptions$?.value).toEqual([
{
id: "mic1",
label: {
number: 1,
type: "number",
},
},
{
id: "mic2",
label: {
name: "Microphone 2",
type: "name",
},
},
]);
expect(vm.videoOptions$?.value).toEqual([
{
id: "cam1",
label: {
name: "Camera 1",
type: "name",
},
},
]);
});
});
});
describe("createLobbyFooterViewModel", () => {
it("offers the device menus even on a phone, previewing the lobby's camera", () => {
platformMock.mockReturnValue("ios");
const track = mockVideoTrack({});
const vm = createLobbyFooterViewModel(
testScope(),
mockMuteStates(),
devices,
pipeline,
constant(track),
/* openSettings */ undefined,
/* hangup */ undefined,
/* showLogo */ false,
);
const camera = vm.cameraMenuVm$.value;
expect(vm.audioMenuVm$.value.options$.value).not.toEqual([]);
expect(camera.options$.value).not.toEqual([]);
expect(camera.selectBackgroundEffect$.value).toBeDefined();
expect(camera.cameraTrack$.value).toBe(track);
describe("background effects", () => {
afterEach(() => backgroundEffectSetting.setValue("none"));
// The lobby, because in a call the whole device switcher is already
// withheld on a phone, whatever the verdict says.
function lobbyOn(
platform: string,
): ReturnType<typeof createLobbyFooterViewModel> {
platformMock.mockReturnValue(platform);
return createLobbyFooterViewModel(
testScope(),
mockMuteStates(),
twoMicsAndOneCamMediaDevices,
pipelineAsTheSdkSays(),
/* camera$ */ constant(null),
/* openSettings */ undefined,
/* hangup */ undefined,
/* showLogo */ false,
);
}
it("offers them on a phone whose browser can run them", () => {
sdkSupportMock.mockReturnValue(true);
expect(lobbyOn("ios").selectBackgroundEffect$.value).toBeDefined();
});
it("offers them on a desktop whose browser can run them", () => {
sdkSupportMock.mockReturnValue(true);
expect(lobbyOn("desktop").selectBackgroundEffect$.value).toBeDefined();
});
it("offers nothing where the browser itself cannot run them", () => {
sdkSupportMock.mockReturnValue(false);
expect(lobbyOn("desktop").selectBackgroundEffect$.value).toBeUndefined();
expect(lobbyOn("desktop").addBackgroundImage$.value).toBeUndefined();
});
it("puts no effect in force where the browser cannot run them", () => {
backgroundEffectSetting.setValue("blur");
sdkSupportMock.mockReturnValue(false);
expect(lobbyOn("desktop").backgroundEffect$.value).toBe("none");
sdkSupportMock.mockReturnValue(true);
expect(lobbyOn("desktop").backgroundEffect$.value).toBe("blur");
});
it("stores the effect chosen", () => {
sdkSupportMock.mockReturnValue(true);
const vm = lobbyOn("desktop");
vm.selectBackgroundEffect$.value?.("image:arc");
expect(vm.backgroundEffect$.value).toBe("image:arc");
// What isn't an effect on offer is stored as none.
vm.selectBackgroundEffect$.value?.("image:gone");
expect(backgroundEffectSetting.getValue()).toBe("none");
});
it("says they run slowly where only the slower route exists", () => {
sdkSupportMock.mockReturnValue(true);
modernRouteMock.mockReturnValue(false);
const slow = lobbyOn("desktop");
expect(slow.backgroundEffectNotice$.value).toBe("slow");
expect(slow.selectBackgroundEffect$.value).toBeDefined();
modernRouteMock.mockReturnValue(true);
expect(lobbyOn("desktop").backgroundEffectNotice$.value).toBeUndefined();
});
it("offers every effect in order, the added ones removable", () => {
sdkSupportMock.mockReturnValue(true);
const added$ = addedBackgrounds.added$ as BehaviorSubject<
AddedBackground[] | undefined
>;
added$.next([{ id: "mine", url: "blob:mine" }]);
expect(lobbyOn("desktop").backgroundEffects$.value).toEqual([
{ id: "none", kind: "none", removable: false },
{ id: "blur", kind: "blur", removable: false },
...shippedBackgrounds.map((background) => ({
id: `image:${background.id}`,
kind: "image",
imageUrl: background.imagePath,
removable: false,
})),
{
id: "added:mine",
kind: "image",
imageUrl: "blob:mine",
removable: true,
},
]);
added$.next([]);
});
it("says they are unavailable where they cannot be chosen", () => {
sdkSupportMock.mockReturnValue(false);
expect(lobbyOn("desktop").backgroundEffectNotice$.value).toBe(
"unavailable",
);
});
it("passes on the wait for the first effect", () => {
platformMock.mockReturnValue("desktop");
const pipeline$ = new BehaviorSubject<BackgroundEffectsState>({
supported: true,
processor: undefined,
wait: "settling",
});
const vm = createLobbyFooterViewModel(
testScope(),
mockMuteStates(),
twoMicsAndOneCamMediaDevices,
pipeline$,
/* camera$ */ constant(null),
/* openSettings */ undefined,
/* hangup */ undefined,
/* showLogo */ false,
);
expect(vm.backgroundEffectSettling$.value).toBe(true);
pipeline$.next({ ...pipeline$.value, wait: undefined });
expect(vm.backgroundEffectSettling$.value).toBe(false);
});
it("offers nothing once the pipeline fails to build, keeping the choice", () => {
platformMock.mockReturnValue("desktop");
backgroundEffectSetting.setValue("blur");
const pipeline$ = new BehaviorSubject<BackgroundEffectsState>({
supported: true,
processor: undefined,
});
const vm = createLobbyFooterViewModel(
testScope(),
mockMuteStates(),
twoMicsAndOneCamMediaDevices,
pipeline$,
/* camera$ */ constant(null),
/* openSettings */ undefined,
/* hangup */ undefined,
/* showLogo */ false,
);
expect(vm.backgroundEffect$.value).toBe("blur");
pipeline$.next({ supported: false, processor: undefined });
expect(vm.selectBackgroundEffect$.value).toBeUndefined();
expect(vm.addBackgroundImage$.value).toBeUndefined();
expect(vm.backgroundEffect$.value).toBe("none");
expect(backgroundEffectSetting.getValue()).toBe("blur");
});
it("adding is unavailable at the limit", () => {
sdkSupportMock.mockReturnValue(true);
const added$ = addedBackgrounds.added$ as BehaviorSubject<
AddedBackground[] | undefined
>;
const vm = lobbyOn("desktop");
expect(vm.addBackgroundImage$.value).toBeDefined();
added$.next(
Array.from({ length: maxAddedBackgrounds }, (_, i) => ({
id: `${i}`,
url: `blob:${i}`,
})),
);
expect(vm.addBackgroundImage$.value).toBeUndefined();
added$.next(added$.value!.slice(1));
expect(vm.addBackgroundImage$.value).toBeDefined();
added$.next([]);
});
it("says why each refused file was refused", async () => {
sdkSupportMock.mockReturnValue(true);
const vm = lobbyOn("desktop");
store.add.mockRejectedValue(new UnusableImage("animated"));
vm.addBackgroundImage$.value!(new File(["x"], "a.gif"));
await flushPromises();
const first = vm.backgroundImageRefusal$.value;
expect(first).toEqual({ reason: "animated" });
// The same again is a refusal of its own, so it is shown again.
vm.addBackgroundImage$.value!(new File(["x"], "a.gif"));
await flushPromises();
expect(vm.backgroundImageRefusal$.value).toEqual({ reason: "animated" });
expect(vm.backgroundImageRefusal$.value).not.toBe(first);
store.add.mockRejectedValue(new Error("quota"));
vm.addBackgroundImage$.value!(new File(["x"], "b.png"));
await flushPromises();
expect(vm.backgroundImageRefusal$.value).toEqual({ reason: "not-kept" });
store.add.mockResolvedValue("kept");
vm.addBackgroundImage$.value!(new File(["x"], "c.png"));
await flushPromises();
expect(vm.backgroundImageRefusal$.value).toBeUndefined();
});
it("never removes the background in force", () => {
sdkSupportMock.mockReturnValue(true);
store.remove.mockResolvedValue();
const vm = lobbyOn("desktop");
backgroundEffectSetting.setValue("added:worn");
vm.removeBackgroundEffect$.value!("added:worn");
expect(store.remove).not.toHaveBeenCalled();
vm.removeBackgroundEffect$.value!("added:spare");
expect(store.remove).toHaveBeenCalledWith("spare");
});
it("previews the lobby's camera while there is one", () => {
const track = mockVideoTrack({});
const camera$ = new BehaviorSubject<LocalVideoMediaTrack | null>(track);
const vm = createLobbyFooterViewModel(
testScope(),
mockMuteStates(),
twoMicsAndOneCamMediaDevices,
noPipeline,
camera$,
/* openSettings */ undefined,
/* hangup */ undefined,
/* showLogo */ false,
);
expect(vm.cameraTrack$.value).toBe(track);
// The lobby releases the camera when it is turned off
camera$.next(null);
expect(vm.cameraTrack$.value).toBeNull();
});
it("previews the call's camera only while it is not muted", () => {
const muted$ = new BehaviorSubject(false);
const track = mockVideoTrack({ muted$ });
const vm = createCallFooterViewModel(
testScope(),
{ ...buildMinimalCallViewModel(gridLayout), camera$: constant(track) },
mockMuteStates(),
twoMicsAndOneCamMediaDevices,
noPipeline,
/* reactionIdentifier */ undefined,
{ showControls: true, header: HeaderStyle.Standard },
);
expect(vm.cameraTrack$.value).toBe(track);
muted$.next(true);
expect(vm.cameraTrack$.value).toBeNull();
muted$.next(false);
expect(vm.cameraTrack$.value).toBe(track);
});
it("availability is the same before and during a call", () => {
for (const supported of [true, false]) {
sdkSupportMock.mockReturnValue(supported);
const lobby = lobbyOn("desktop");
const inCall = createCallFooterViewModel(
testScope(),
buildMinimalCallViewModel(gridLayout),
mockMuteStates(),
twoMicsAndOneCamMediaDevices,
pipelineAsTheSdkSays(),
/* reactionIdentifier */ undefined,
{ showControls: true, header: HeaderStyle.Standard },
);
const offeredInLobby =
lobby.selectBackgroundEffect$.value !== undefined;
expect(inCall.selectBackgroundEffect$.value !== undefined).toBe(
offeredInLobby,
);
expect(offeredInLobby).toBe(supported);
}
});
});
});
+305 -54
View File
@@ -5,24 +5,253 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { combineLatest, map, type Observable } from "rxjs";
import {
BehaviorSubject,
combineLatest,
distinctUntilChanged,
map,
type Observable,
of,
switchMap,
} from "rxjs";
import { supportsAudioOutputSelection } from "livekit-client";
import { type LocalVideoMediaTrack } from "@element-hq/matrixrtc-sdk";
import { supportsModernBackgroundProcessors } from "@livekit/track-processors";
import { logger } from "matrix-js-sdk/lib/logger";
import {
parseEffect,
serializeEffect,
shippedBackgrounds,
} from "../tracks/backgroundEffectCatalog";
import {
type AddedBackground,
addedBackgrounds,
maxAddedBackgrounds,
UnusableImage,
} from "../tracks/backgroundImages";
import { type CallViewModel } from "../state/CallViewModel/CallViewModel";
import { type BackgroundEffectsState } from "../state/BackgroundEffects";
import { type MenuOptions } from "./MediaMuteAndSwitchButton";
import { type MediaDevices } from "../state/MediaDevices";
import { debugTileLayout as debugTileLayoutSetting } from "../settings/settings";
import {
backgroundEffect as backgroundEffectSetting,
debugTileLayout as debugTileLayoutSetting,
} from "../settings/settings";
import { type Behavior, constant } from "../state/Behavior";
import type { ObservableScope } from "../state/ObservableScope";
import { type MuteStates } from "../state/MuteStates";
import { createStaticViewModel, type ViewModel } from "../state/ViewModel";
import { HeaderStyle } from "../UrlParams";
import { platform } from "../Platform";
import { type FooterSnapshot } from "./CallFooter";
import {
createAudioMenuViewModel,
createCameraMenuViewModel,
} from "./MediaMenuViewModel";
import { type BackgroundImageRefusal, type FooterSnapshot } from "./CallFooter";
import { type BackgroundEffectGridItem } from "./BackgroundEffectGrid";
/**
* Shared helper: maps MuteStates into the audio/video enabled + toggle behaviors
* needed by FooterSnapshot.
*/
function buildMuteBehaviors(
scope: ObservableScope,
muteStates: MuteStates,
): Pick<
ViewModel<FooterSnapshot>,
| "audioEnabled$"
| "audioBusy$"
| "toggleAudio$"
| "videoEnabled$"
| "videoBusy$"
| "toggleVideo$"
> {
return {
audioEnabled$: muteStates.audio.enabled$,
audioBusy$: muteStates.audio.syncing$,
toggleAudio$: scope.behavior(
muteStates.audio.toggle$.pipe(map((t) => t ?? undefined)),
),
videoEnabled$: muteStates.video.enabled$,
videoBusy$: muteStates.video.syncing$,
toggleVideo$: scope.behavior(
muteStates.video.toggle$.pipe(map((t) => t ?? undefined)),
),
};
}
/**
* Shared helper: maps MediaDevices into the audio/video device-list behaviors
* needed by FooterSnapshot (options, selection, callbacks, background effect).
*/
function buildDeviceBehaviors(
scope: ObservableScope,
mediaDevices: MediaDevices,
/** return empty arrays for audioOptions and videoOptions*/
disableSwitcher$: Behavior<boolean>,
backgroundEffectsState$: Observable<BackgroundEffectsState>,
/** The camera as the pipeline has it, for the menu's preview. */
camera$: Observable<LocalVideoMediaTrack | null | undefined>,
): Pick<
ViewModel<FooterSnapshot>,
| "audioOptions$"
| "selectedAudio$"
| "selectAudioButtonOption$"
| "audioOutputOptions$"
| "selectedAudioOutput$"
| "selectAudioOutputOption$"
| "videoOptions$"
| "selectedVideo$"
| "selectVideoButtonOption$"
| "backgroundEffect$"
| "selectBackgroundEffect$"
| "backgroundEffects$"
| "backgroundEffectNotice$"
| "backgroundEffectSettling$"
| "addBackgroundImage$"
| "backgroundImageRefusal$"
| "removeBackgroundEffect$"
| "cameraTrack$"
> {
const options$ = (
available$: Behavior<Map<string, MenuOptions["label"]>>,
): Observable<MenuOptions[]> =>
disableSwitcher$.pipe(
switchMap((disable) =>
disable
? constant([] as MenuOptions[])
: available$.pipe(
map((available) =>
[...available.entries()].map(([id, label]) => ({ id, label })),
),
),
),
);
// Also false once the pipeline has failed to build this session.
const supported$ = backgroundEffectsState$.pipe(
map(({ supported }) => supported === true),
distinctUntilChanged(),
);
const slow = !supportsModernBackgroundProcessors();
const offered$ = combineLatest([disableSwitcher$, supported$]).pipe(
map(([switcherDisabled, supported]) => !switcherDisabled && supported),
);
// A new object for each refusal, so the same one twice is shown twice.
const refusal$ = new BehaviorSubject<BackgroundImageRefusal | undefined>(
undefined,
);
return {
audioOptions$: scope.behavior(options$(mediaDevices.audioInput.available$)),
selectedAudio$: scope.behavior(
mediaDevices.audioInput.selected$.pipe(map((s) => s?.id)),
),
selectAudioButtonOption$: constant(mediaDevices.audioInput.select),
audioOutputOptions$: scope.behavior(
options$(mediaDevices.audioOutput.available$),
),
selectedAudioOutput$: scope.behavior(
mediaDevices.audioOutput.selected$.pipe(map((s) => s?.id)),
),
// Withheld where the platform can't route audio to a chosen device, which
// disables the speaker section.
selectAudioOutputOption$: constant(
supportsAudioOutputSelection()
? mediaDevices.audioOutput.select
: undefined,
),
videoOptions$: scope.behavior(options$(mediaDevices.videoInput.available$)),
selectedVideo$: scope.behavior(
mediaDevices.videoInput.selected$.pipe(map((s) => s?.id)),
),
selectVideoButtonOption$: constant(mediaDevices.videoInput.select),
backgroundEffect$: scope.behavior(
combineLatest([backgroundEffectSetting.value$, supported$]).pipe(
map(([raw, supported]) =>
supported ? serializeEffect(parseEffect(raw)) : "none",
),
),
),
selectBackgroundEffect$: scope.behavior(
offered$.pipe(
map((offered) =>
offered
? (id: string): void =>
backgroundEffectSetting.setValue(
serializeEffect(parseEffect(id)),
)
: undefined,
),
),
),
backgroundEffects$: scope.behavior(
addedBackgrounds.added$.pipe(
map((added) => backgroundEffectChoices(added ?? [])),
),
),
backgroundEffectNotice$: scope.behavior(
offered$.pipe(
map((offered) =>
!offered ? "unavailable" : slow ? "slow" : undefined,
),
),
),
backgroundEffectSettling$: scope.behavior(
backgroundEffectsState$.pipe(
map(({ wait }) => wait !== undefined),
distinctUntilChanged(),
),
false,
),
// Kept and offered, not put on: that waits for the user to choose it.
addBackgroundImage$: scope.behavior(
combineLatest([offered$, addedBackgrounds.added$]).pipe(
map(([offered, added]) =>
offered && (added?.length ?? 0) < maxAddedBackgrounds
? (file: File): void => {
refusal$.next(undefined);
addedBackgrounds.add(file).catch((e) => {
logger.warn("Could not keep that background", e);
refusal$.next({
reason: e instanceof UnusableImage ? e.reason : "not-kept",
});
});
}
: undefined,
),
),
),
backgroundImageRefusal$: refusal$,
// None while muted: the call mutes its track rather than releasing it.
cameraTrack$: scope.behavior(
camera$.pipe(
switchMap((camera) =>
camera
? camera.muted$.pipe(map((muted) => (muted ? null : camera)))
: of(null),
),
),
null,
),
// Never the one in force: taking it away would leave nothing chosen.
removeBackgroundEffect$: scope.behavior(
offered$.pipe(
map((offered) =>
offered
? (optionId: string): void => {
const effect = parseEffect(optionId);
if (effect.kind !== "added") return;
if (backgroundEffectSetting.getValue() === optionId) return;
addedBackgrounds
.remove(effect.id)
.catch((e) =>
logger.warn("Could not remove that background", e),
);
}
: undefined,
),
),
),
};
}
/**
* Creates the ViewModel for the CallFooter.
@@ -57,23 +286,13 @@ export function createCallFooterViewModel(
isPip$.pipe(map((isPip) => isPip || platform !== "desktop")),
);
return {
audioMenuVm$: constant(
createAudioMenuViewModel(
scope,
muteStates,
mediaDevices,
disableDeviceSwitcher$,
),
),
cameraMenuVm$: constant(
createCameraMenuViewModel(
scope,
muteStates,
mediaDevices,
disableDeviceSwitcher$,
backgroundEffectsState$,
callModel.camera$,
),
...buildMuteBehaviors(scope, muteStates),
...buildDeviceBehaviors(
scope,
mediaDevices,
disableDeviceSwitcher$,
backgroundEffectsState$,
callModel.camera$,
),
// candidat to move into the FooterViewModel
showFooter$: callModel.showFooter$,
@@ -153,40 +372,72 @@ export function createLobbyFooterViewModel(
hangup: (() => void) | undefined,
showLogo: boolean,
): ViewModel<FooterSnapshot> {
return createStaticViewModel({
// we can safly skip any props that we do not need.
// The view model will then have less keys.
// But as soon as we call `useViewModel` and convert back to a snapshot the missing props will
// be correcty matching the snapshot type.
showLogo,
hideControls: false,
asOverlay: false,
showModals: true,
buttonSize: "lg",
openSettings,
hangup,
debugTileLayout: false,
showFooter: true,
toggleScreenSharing: undefined,
layoutSwitchVm: null,
sharingScreen: false,
audioOutputSwitcher: undefined,
reactionIdentifier: undefined,
reactionData: undefined,
tileStoreGeneration: undefined,
audioMenuVm: createAudioMenuViewModel(
return {
...createStaticViewModel({
// we can safly skip any props that we do not need.
// The view model will then have less keys.
// But as soon as we call `useViewModel` and convert back to a snapshot the missing props will
// be correcty matching the snapshot type.
showLogo,
hideControls: false,
asOverlay: false,
showModals: true,
buttonSize: "lg",
openSettings,
hangup,
debugTileLayout: false,
showFooter: true,
toggleAudio: undefined,
toggleVideo: undefined,
toggleScreenSharing: undefined,
audioEnabled: undefined,
audioBusy: false,
videoEnabled: undefined,
videoBusy: false,
layoutSwitchVm: null,
sharingScreen: false,
audioOutputSwitcher: undefined,
reactionIdentifier: undefined,
reactionData: undefined,
tileStoreGeneration: undefined,
audioOptions: undefined,
audioOutputOptions: undefined,
videoOptions: undefined,
selectedAudio: undefined,
selectedAudioOutput: undefined,
selectedVideo: undefined,
selectAudioButtonOption: undefined,
selectAudioOutputOption: undefined,
selectVideoButtonOption: undefined,
}),
...buildMuteBehaviors(scope, muteStates),
...buildDeviceBehaviors(
scope,
muteStates,
mediaDevices,
constant(false),
),
cameraMenuVm: createCameraMenuViewModel(
scope,
muteStates,
mediaDevices,
constant(false),
backgroundEffectsState$,
camera$,
),
});
};
}
function backgroundEffectChoices(
added: AddedBackground[],
): BackgroundEffectGridItem[] {
return [
{ id: serializeEffect({ kind: "none" }), kind: "none", removable: false },
{ id: serializeEffect({ kind: "blur" }), kind: "blur", removable: false },
...shippedBackgrounds.map((background) => ({
id: serializeEffect({ kind: "shipped", id: background.id }),
kind: "image" as const,
imageUrl: background.imagePath,
removable: false,
})),
...added.map((background) => ({
id: serializeEffect({ kind: "added", id: background.id }),
kind: "image" as const,
imageUrl: background.url,
removable: true,
})),
];
}
-193
View File
@@ -1,193 +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, fn, userEvent, within } from "storybook/test";
import { type JSX, type ReactNode } from "react";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { MediaMenuButton } from "./MediaMenuButton";
import { type MediaMenuSnapshot } from "./MediaMenuViewModel";
import { useStaticViewModel } from "../state/ViewModel";
import { MediaDevicesContext } from "../MediaDevicesContext";
import { MediaDevices } from "../state/MediaDevices";
import { globalScope } from "../state/ObservableScope";
const mediaDevices = new MediaDevices(globalScope, {
controlledAudioDevices: false,
});
/** Builds the view model from the story's args, so each field is a control. */
function MediaMenuButtonStoryWrapper({
kind,
...snapshot
}: MediaMenuSnapshot & { kind: "audio" | "video" }): ReactNode {
const vm = useStaticViewModel(snapshot);
return <MediaMenuButton kind={kind} vm={vm} size="lg" />;
}
const meta = {
component: MediaMenuButtonStoryWrapper,
decorators: [
(Story): JSX.Element => (
<MediaDevicesContext value={mediaDevices}>
<Story />
</MediaDevicesContext>
),
],
} satisfies Meta<typeof MediaMenuButtonStoryWrapper>;
export default meta;
type Story = StoryObj<typeof meta>;
const empty = {
outputOptions: [],
selectedOutput: undefined,
selectOutput: undefined,
backgroundEffect: undefined,
backgroundEffects: [],
backgroundEffectNotice: undefined,
backgroundEffectSettling: false,
backgroundImageRefusal: undefined,
selectBackgroundEffect: undefined,
addBackgroundImage: undefined,
removeBackgroundEffect: undefined,
cameraTrack: null,
} satisfies Partial<MediaMenuSnapshot>;
export const Microphone: Story = {
args: {
...empty,
kind: "audio",
enabled: true,
busy: false,
toggle: fn(),
options: [
{ id: "mic1", label: { type: "name", name: "Microphone 1" } },
{ id: "mic2", label: { type: "name", name: "Microphone 2" } },
],
selected: "mic1",
select: fn(),
outputOptions: [
{ id: "default", label: { type: "default", name: "Built-in Output" } },
],
selectedOutput: "default",
selectOutput: fn(),
},
play: async ({ args, canvasElement }) => {
await userEvent.click(
within(canvasElement).getByRole("switch", { name: "Mute microphone" }),
);
await expect(args.toggle).toHaveBeenCalled();
},
};
export const Camera: Story = {
args: {
...empty,
kind: "video",
enabled: true,
busy: false,
toggle: fn(),
options: [{ id: "cam1", label: { type: "name", name: "Camera 1" } }],
selected: "cam1",
select: fn(),
backgroundEffect: "none",
backgroundEffects: [
{ id: "none", kind: "none" },
{ id: "blur", kind: "blur" },
],
selectBackgroundEffect: fn(),
},
play: async ({ args, canvasElement }) => {
await userEvent.click(
within(canvasElement).getByRole("switch", { name: "Stop video" }),
);
await expect(args.toggle).toHaveBeenCalled();
},
};
export const CameraBusy: Story = {
args: { ...Camera.args, busy: true },
};
/** Opens the effects, for the stories that check what they say. */
async function openEffects(canvasElement: HTMLElement): Promise<HTMLElement> {
await userEvent.click(
within(canvasElement).getByRole("button", { name: "Camera" }),
);
return within(document.body).findByRole("group", {
name: "Background effects",
});
}
/** The view model says why; the view says it in words. */
export const CameraEffectsUnavailable: Story = {
args: {
...Camera.args,
selectBackgroundEffect: undefined,
backgroundEffectNotice: "unavailable",
},
play: async ({ canvasElement }) => {
const section = await openEffects(canvasElement);
await expect(
within(section).getByRole("group"),
).toHaveAccessibleDescription(
"Background effects are not supported on this platform.",
);
},
};
export const CameraEffectsSlow: Story = {
args: {
...Camera.args,
backgroundEffectNotice: "slow",
},
play: async ({ canvasElement }) => {
const section = await openEffects(canvasElement);
await expect(
within(section).getByRole("group"),
).toHaveAccessibleDescription(
"Background effects run slowly on this platform, which may cause your video to stutter.",
);
},
};
export const CameraFileRefused: Story = {
args: {
...Camera.args,
addBackgroundImage: fn(),
backgroundImageRefusal: { reason: "not-an-image", dismiss: fn() },
},
play: async ({ canvasElement }) => {
await openEffects(canvasElement);
await expect(
await within(document.body).findByText(
"That file is not a supported image",
),
).toBeInTheDocument();
},
};
/** No devices to pick and none to mute: a plain, disabled mute button. */
export const WithoutDevices: Story = {
args: {
...Camera.args,
enabled: false,
toggle: undefined,
options: [],
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await expect(
canvas.queryByRole("button", { name: "Camera" }),
).not.toBeInTheDocument();
await expect(canvas.getByTestId("incall_videomute")).toHaveAttribute(
"aria-disabled",
"true",
);
},
};
-124
View File
@@ -1,124 +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, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { MicButton, VideoButton } from "../button";
import { MediaMuteAndSwitchButton } from "./MediaMuteAndSwitchButton";
import { type MediaMenuViewModel } from "./MediaMenuViewModel";
import { SelfPreview } from "./SelfPreview";
import { useBehavior } from "../useBehavior";
interface Props {
vm: MediaMenuViewModel;
kind: "audio" | "video";
size: "md" | "lg";
}
/**
* The microphone's or the camera's mute button: with a menu to pick the
* device while there are devices to offer, a plain mute button otherwise.
*/
export const MediaMenuButton: FC<Props> = ({ vm, kind, size }) => {
const { t } = useTranslation();
const enabled = useBehavior(vm.enabled$);
const busy = useBehavior(vm.busy$);
const toggle = useBehavior(vm.toggle$);
const options = useBehavior(vm.options$);
const selected = useBehavior(vm.selected$);
const select = useBehavior(vm.select$);
const outputOptions = useBehavior(vm.outputOptions$);
const selectedOutput = useBehavior(vm.selectedOutput$);
const selectOutput = useBehavior(vm.selectOutput$);
const backgroundEffect = useBehavior(vm.backgroundEffect$);
const backgroundEffects = useBehavior(vm.backgroundEffects$);
const notice = useBehavior(vm.backgroundEffectNotice$);
const settling = useBehavior(vm.backgroundEffectSettling$);
const refusal = useBehavior(vm.backgroundImageRefusal$);
const selectBackgroundEffect = useBehavior(vm.selectBackgroundEffect$);
const addBackgroundImage = useBehavior(vm.addBackgroundImage$);
const removeBackgroundEffect = useBehavior(vm.removeBackgroundEffect$);
const cameraTrack = useBehavior(vm.cameraTrack$);
const testId = kind === "audio" ? "incall_mute" : "incall_videomute";
const noticeText = useMemo(() => {
switch (notice) {
case undefined:
return undefined;
case "unavailable":
return t("background_effects.unavailable");
case "slow":
return t("background_effects.slow");
}
}, [notice, t]);
const refusalText = useMemo(() => {
switch (refusal?.reason) {
case undefined:
return undefined;
case "not-an-image":
return t("error.background_not_an_image");
case "animated":
return t("error.background_animated");
case "undecodable":
return t("error.background_undecodable");
case "not-kept":
return t("error.background_not_kept");
}
}, [refusal, t]);
if (options.length === 0) {
const PlainButton = kind === "audio" ? MicButton : VideoButton;
return (
<PlainButton
size={size}
enabled={enabled}
busy={busy}
onClick={toggle}
disabled={busy || toggle === undefined}
data-testid={testId}
/>
);
}
return kind === "audio" ? (
<MediaMuteAndSwitchButton
iconsAndLabels="audio"
enabled={enabled}
busy={busy}
onMuteClick={toggle}
data-testid={testId}
options={options}
selectedOption={selected}
onSelect={select}
outputOptions={outputOptions}
selectedOutputOption={selectedOutput}
onSelectOutput={selectOutput}
/>
) : (
<MediaMuteAndSwitchButton
iconsAndLabels="video"
enabled={enabled}
busy={busy}
onMuteClick={toggle}
options={options}
selectedOption={selected}
onSelect={select}
backgroundEffects={backgroundEffects}
selectedBackgroundEffect={backgroundEffect}
onSelectBackgroundEffect={selectBackgroundEffect}
backgroundEffectSettling={settling}
onAddBackgroundImage={addBackgroundImage}
onRemoveBackgroundEffect={removeBackgroundEffect}
selfPreview={<SelfPreview track={cameraTrack} />}
backgroundImageRefusal={refusalText}
onDismissBackgroundImageRefusal={refusal?.dismiss}
backgroundEffectNotice={noticeText}
/>
);
};
-294
View File
@@ -1,294 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { afterEach, describe, expect, it, vi } from "vitest";
import { BehaviorSubject, type Observable } from "rxjs";
import { type LocalVideoMediaTrack } from "@element-hq/matrixrtc-sdk";
import {
flushPromises,
testScope,
mockMuteStates,
mockMediaDevices,
mockVideoTrack,
} from "../utils/test";
import { constant } from "../state/Behavior";
import { type BackgroundEffectsState } from "../state/BackgroundEffects";
import type { DeviceLabel } from "../state/MediaDevices";
import {
createAudioMenuViewModel,
createCameraMenuViewModel,
type MediaMenuViewModel,
} from "./MediaMenuViewModel";
import { backgroundEffect as backgroundEffectSetting } from "../settings/settings";
import { shippedBackgrounds } from "../tracks/backgroundEffectCatalog";
import type * as BackgroundImages from "../tracks/backgroundImages";
import {
type AddedBackground,
addedBackgrounds,
maxAddedBackgrounds,
UnusableImage,
} from "../tracks/backgroundImages";
const modernRouteMock = vi.hoisted(() => vi.fn(() => true));
vi.mock("@livekit/track-processors", () => ({
supportsModernBackgroundProcessors: (): boolean => modernRouteMock(),
}));
const outputSelectionMock = vi.hoisted(() => vi.fn(() => true));
vi.mock("livekit-client", () => ({
supportsAudioOutputSelection: (): boolean => outputSelectionMock(),
}));
const store = vi.hoisted(() => ({
add: vi.fn<(file: Blob) => Promise<string>>(),
remove: vi.fn<(id: string) => Promise<void>>(),
}));
vi.mock("../tracks/backgroundImages", async (original) => {
const { BehaviorSubject } = await import("rxjs");
return {
...(await original<typeof BackgroundImages>()),
addedBackgrounds: {
added$: new BehaviorSubject<AddedBackground[] | undefined>([]),
add: store.add,
remove: store.remove,
},
};
});
const added$ = addedBackgrounds.added$ as BehaviorSubject<
AddedBackground[] | undefined
>;
const devices = mockMediaDevices({
audioInput: {
available$: constant(
new Map<string, DeviceLabel>([
["mic1", { type: "number", number: 1 }],
["mic2", { type: "name", name: "Microphone 2" }],
]),
),
selected$: constant(undefined),
select: vi.fn(),
},
// As Safari: no outputs listed.
audioOutput: {
available$: constant(new Map<string, DeviceLabel>()),
selected$: constant(undefined),
select: vi.fn(),
},
});
function audioMenu(disableSwitcher = false): MediaMenuViewModel {
return createAudioMenuViewModel(
testScope(),
mockMuteStates(),
devices,
constant(disableSwitcher),
);
}
function cameraMenu({
supported = true,
disableSwitcher = false,
pipeline$ = constant({ supported, processor: undefined }),
camera$ = constant(null),
}: {
supported?: boolean;
disableSwitcher?: boolean;
pipeline$?: Observable<BackgroundEffectsState>;
camera$?: Observable<LocalVideoMediaTrack | null>;
} = {}): MediaMenuViewModel {
return createCameraMenuViewModel(
testScope(),
mockMuteStates(),
devices,
constant(disableSwitcher),
pipeline$,
camera$,
);
}
describe("createAudioMenuViewModel", () => {
it("lists the devices, unless the switcher is withheld", () => {
expect(audioMenu().options$.value).toEqual([
{ id: "mic1", label: { type: "number", number: 1 } },
{ id: "mic2", label: { type: "name", name: "Microphone 2" } },
]);
expect(audioMenu(true).options$.value).toEqual([]);
});
it("lists no outputs as an empty list, which keeps the section", () => {
expect(audioMenu().outputOptions$.value).toEqual([]);
});
it.each([true, false])(
"offers to pick an output only where the platform can route to it (%s)",
(canRoute) => {
outputSelectionMock.mockReturnValue(canRoute);
expect(audioMenu().selectOutput$.value !== undefined).toBe(canRoute);
},
);
});
describe("createCameraMenuViewModel", () => {
afterEach(() => {
backgroundEffectSetting.setValue("none");
added$.next([]);
});
it("offers effects where they run, saying where they run slowly", () => {
modernRouteMock.mockReturnValue(true);
const vm = cameraMenu();
expect(vm.selectBackgroundEffect$.value).toBeDefined();
expect(vm.addBackgroundImage$.value).toBeDefined();
expect(vm.backgroundEffectNotice$.value).toBeUndefined();
modernRouteMock.mockReturnValue(false);
const slow = cameraMenu();
expect(slow.selectBackgroundEffect$.value).toBeDefined();
expect(slow.backgroundEffectNotice$.value).toBe("slow");
modernRouteMock.mockReturnValue(true);
});
it("offers nothing while the switcher is withheld", () => {
const vm = cameraMenu({ disableSwitcher: true });
expect(vm.options$.value).toEqual([]);
expect(vm.selectBackgroundEffect$.value).toBeUndefined();
expect(vm.backgroundEffectNotice$.value).toBe("unavailable");
});
it("offers nothing once the pipeline fails to build, keeping the choice", () => {
backgroundEffectSetting.setValue("blur");
const pipeline$ = new BehaviorSubject<BackgroundEffectsState>({
supported: true,
processor: undefined,
});
const vm = cameraMenu({ pipeline$ });
expect(vm.backgroundEffect$.value).toBe("blur");
pipeline$.next({ supported: false, processor: undefined });
expect(vm.selectBackgroundEffect$.value).toBeUndefined();
expect(vm.addBackgroundImage$.value).toBeUndefined();
expect(vm.removeBackgroundEffect$.value).toBeUndefined();
expect(vm.backgroundEffectNotice$.value).toBe("unavailable");
expect(vm.backgroundEffect$.value).toBe("none");
expect(backgroundEffectSetting.getValue()).toBe("blur");
});
it("saves the effect chosen, and none for one not on offer", () => {
const vm = cameraMenu();
vm.selectBackgroundEffect$.value!("image:arc");
expect(vm.backgroundEffect$.value).toBe("image:arc");
vm.selectBackgroundEffect$.value!("image:gone");
expect(backgroundEffectSetting.getValue()).toBe("none");
});
it("offers every effect in order, the added ones removable", () => {
added$.next([{ id: "mine", url: "blob:mine" }]);
expect(cameraMenu().backgroundEffects$.value).toEqual([
{ id: "none", kind: "none", removable: false },
{ id: "blur", kind: "blur", removable: false },
...shippedBackgrounds.map((background) => ({
id: `image:${background.id}`,
kind: "image",
imageUrl: background.imagePath,
removable: false,
})),
{
id: "added:mine",
kind: "image",
imageUrl: "blob:mine",
removable: true,
},
]);
});
it("passes on the wait for the first effect", () => {
const pipeline$ = new BehaviorSubject<BackgroundEffectsState>({
supported: true,
processor: undefined,
wait: "settling",
});
const vm = cameraMenu({ pipeline$ });
expect(vm.backgroundEffectSettling$.value).toBe(true);
pipeline$.next({ ...pipeline$.value, wait: undefined });
expect(vm.backgroundEffectSettling$.value).toBe(false);
});
it("offers adding only below the limit", () => {
const vm = cameraMenu();
added$.next(
Array.from({ length: maxAddedBackgrounds }, (_, i) => ({
id: `${i}`,
url: `blob:${i}`,
})),
);
expect(vm.addBackgroundImage$.value).toBeUndefined();
added$.next(added$.value!.slice(1));
expect(vm.addBackgroundImage$.value).toBeDefined();
});
it("says why each refused file was refused", async () => {
const vm = cameraMenu();
store.add.mockRejectedValue(new UnusableImage("animated"));
vm.addBackgroundImage$.value!(new File(["x"], "a.gif"));
await flushPromises();
expect(vm.backgroundImageRefusal$.value?.reason).toBe("animated");
store.add.mockRejectedValue(new Error("quota"));
vm.addBackgroundImage$.value!(new File(["x"], "b.png"));
await flushPromises();
expect(vm.backgroundImageRefusal$.value?.reason).toBe("not-kept");
store.add.mockResolvedValue("kept");
vm.addBackgroundImage$.value!(new File(["x"], "c.png"));
await flushPromises();
expect(vm.backgroundImageRefusal$.value).toBeUndefined();
});
it("drops a refusal once dismissed, and only that one", async () => {
const vm = cameraMenu();
store.add.mockRejectedValue(new UnusableImage("animated"));
vm.addBackgroundImage$.value!(new File(["x"], "a.gif"));
await flushPromises();
const first = vm.backgroundImageRefusal$.value!;
first.dismiss();
expect(vm.backgroundImageRefusal$.value).toBeUndefined();
// The same again is a refusal of its own, which the first can't dismiss.
vm.addBackgroundImage$.value!(new File(["x"], "a.gif"));
await flushPromises();
expect(vm.backgroundImageRefusal$.value?.reason).toBe("animated");
first.dismiss();
expect(vm.backgroundImageRefusal$.value?.reason).toBe("animated");
});
it("never removes the selected background", () => {
store.remove.mockResolvedValue();
const vm = cameraMenu();
backgroundEffectSetting.setValue("added:worn");
vm.removeBackgroundEffect$.value!("added:worn");
expect(store.remove).not.toHaveBeenCalled();
vm.removeBackgroundEffect$.value!("added:spare");
expect(store.remove).toHaveBeenCalledWith("spare");
});
it("previews the camera only while there is one and it is not muted", () => {
const muted$ = new BehaviorSubject(false);
const track = mockVideoTrack({ muted$ });
const camera$ = new BehaviorSubject<LocalVideoMediaTrack | null>(track);
const vm = cameraMenu({ camera$ });
expect(vm.cameraTrack$.value).toBe(track);
muted$.next(true);
expect(vm.cameraTrack$.value).toBeNull();
muted$.next(false);
expect(vm.cameraTrack$.value).toBe(track);
camera$.next(null);
expect(vm.cameraTrack$.value).toBeNull();
});
});
-324
View File
@@ -1,324 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import {
BehaviorSubject,
combineLatest,
distinctUntilChanged,
map,
type Observable,
of,
switchMap,
} from "rxjs";
import { supportsAudioOutputSelection } from "livekit-client";
import { type LocalVideoMediaTrack } from "@element-hq/matrixrtc-sdk";
import { supportsModernBackgroundProcessors } from "@livekit/track-processors";
import { logger } from "matrix-js-sdk/lib/logger";
import {
parseEffect,
serializeEffect,
shippedBackgrounds,
} from "../tracks/backgroundEffectCatalog";
import {
type AddedBackground,
addedBackgrounds,
maxAddedBackgrounds,
type UnusableReason,
UnusableImage,
} from "../tracks/backgroundImages";
import { type BackgroundEffectsState } from "../state/BackgroundEffects";
import { type MenuOptions } from "./MediaMuteAndSwitchButton";
import { type MediaDevices } from "../state/MediaDevices";
import { backgroundEffect as backgroundEffectSetting } from "../settings/settings";
import { type Behavior, constant } from "../state/Behavior";
import type { ObservableScope } from "../state/ObservableScope";
import { type MuteStates } from "../state/MuteStates";
import { createStaticViewModel, type ViewModel } from "../state/ViewModel";
import { type BackgroundEffectGridItem } from "./BackgroundEffectGrid";
export interface BackgroundImageRefusal {
reason: UnusableReason | "not-kept";
/** Done with it: once read, or once the menu showing it closes. */
dismiss: () => void;
}
/**
* A mute button with a menu to pick the device, shared by the microphone and
* the camera. Fields that belong to the other device are left empty.
*/
export interface MediaMenuSnapshot {
/** Whether the device is on. (muted/unmuted state) */
enabled: boolean;
busy: boolean;
/** Turns the device on or off. Undefined while it can't be toggled. (disable interaction state) */
toggle: (() => void) | undefined;
options: MenuOptions[];
selected: string | undefined;
select: ((id: string) => void) | undefined;
/** Output (speaker) devices. Microphone only. */
outputOptions: MenuOptions[];
selectedOutput: string | undefined;
/** Undefined if the output device is not configurable. */
selectOutput: ((id: string) => void) | undefined;
/** The selected background effect, as its option id. Camera only. */
backgroundEffect: string | undefined;
/** Every effect on offer, in the order they are shown. */
backgroundEffects: BackgroundEffectGridItem[];
/** What the user is told about effects here, if anything. */
backgroundEffectNotice: "unavailable" | "slow" | undefined;
/** Whether the first effect chosen is still being prepared. */
backgroundEffectSettling: boolean;
/** Why the last file offered couldn't be kept, if it couldn't. */
backgroundImageRefusal: BackgroundImageRefusal | undefined;
/** Undefined where background effects can't be chosen. */
selectBackgroundEffect: ((id: string) => void) | undefined;
/** Undefined where no background can be added. */
addBackgroundImage: ((file: File) => void) | undefined;
/** Removes an added background by its option id, unless it is the selected one. */
removeBackgroundEffect: ((id: string) => void) | undefined;
/** The camera to preview, with the selected effect; null while it is off. */
cameraTrack: LocalVideoMediaTrack | null;
}
export type MediaMenuViewModel = ViewModel<MediaMenuSnapshot>;
const noBackgroundEffects = {
backgroundEffect: undefined,
backgroundEffects: [],
backgroundEffectNotice: undefined,
backgroundEffectSettling: false,
backgroundImageRefusal: undefined,
selectBackgroundEffect: undefined,
addBackgroundImage: undefined,
removeBackgroundEffect: undefined,
cameraTrack: null,
} satisfies Partial<MediaMenuSnapshot>;
function options$(
disableSwitcher$: Behavior<boolean>,
available$: Behavior<Map<string, MenuOptions["label"]>>,
): Observable<MenuOptions[]> {
return disableSwitcher$.pipe(
switchMap((disable) =>
disable
? constant([] as MenuOptions[])
: available$.pipe(
map((available) =>
[...available.entries()].map(([id, label]) => ({ id, label })),
),
),
),
);
}
/**
* The microphone's mute button and menu, with the speaker choice.
*
* @param disableSwitcher$ - True to leave out the menu.
*/
export function createAudioMenuViewModel(
scope: ObservableScope,
muteStates: MuteStates,
mediaDevices: MediaDevices,
disableSwitcher$: Behavior<boolean>,
): MediaMenuViewModel {
const { audio } = muteStates;
return {
...createStaticViewModel(noBackgroundEffects),
enabled$: audio.enabled$,
busy$: audio.syncing$,
toggle$: scope.behavior(audio.toggle$.pipe(map((t) => t ?? undefined))),
options$: scope.behavior(
options$(disableSwitcher$, mediaDevices.audioInput.available$),
),
selected$: scope.behavior(
mediaDevices.audioInput.selected$.pipe(map((s) => s?.id)),
),
select$: constant(mediaDevices.audioInput.select),
outputOptions$: scope.behavior(
options$(disableSwitcher$, mediaDevices.audioOutput.available$),
),
selectedOutput$: scope.behavior(
mediaDevices.audioOutput.selected$.pipe(map((s) => s?.id)),
),
selectOutput$: constant(
supportsAudioOutputSelection()
? mediaDevices.audioOutput.select
: undefined,
),
};
}
/**
* The camera's mute button and menu, with the background effects and a
* preview of the camera.
*
* @param disableSwitcher$ - True to leave out the menu.
* @param backgroundEffectsState$ - The background pipeline's state: whether
* effects run here, and the wait for the first.
* @param camera$ - The camera as the pipeline has it, for the preview.
*/
export function createCameraMenuViewModel(
scope: ObservableScope,
muteStates: MuteStates,
mediaDevices: MediaDevices,
disableSwitcher$: Behavior<boolean>,
backgroundEffectsState$: Observable<BackgroundEffectsState>,
camera$: Observable<LocalVideoMediaTrack | null | undefined>,
): MediaMenuViewModel {
const { video } = muteStates;
// Also false once the pipeline has failed to build this session.
const supported$ = backgroundEffectsState$.pipe(
map(({ supported }) => supported === true),
distinctUntilChanged(),
);
const slow = !supportsModernBackgroundProcessors();
const offered$ = combineLatest([disableSwitcher$, supported$]).pipe(
map(([switcherDisabled, supported]) => !switcherDisabled && supported),
);
const refusal$ = new BehaviorSubject<BackgroundImageRefusal | undefined>(
undefined,
);
const refuse = (reason: BackgroundImageRefusal["reason"]): void => {
const refusal: BackgroundImageRefusal = {
reason,
// A later refusal is not this one's to dismiss.
dismiss: () => {
if (refusal$.value === refusal) refusal$.next(undefined);
},
};
refusal$.next(refusal);
};
return {
...createStaticViewModel({
outputOptions: [],
selectedOutput: undefined,
selectOutput: undefined,
}),
enabled$: video.enabled$,
busy$: video.syncing$,
toggle$: scope.behavior(video.toggle$.pipe(map((t) => t ?? undefined))),
options$: scope.behavior(
options$(disableSwitcher$, mediaDevices.videoInput.available$),
),
selected$: scope.behavior(
mediaDevices.videoInput.selected$.pipe(map((s) => s?.id)),
),
select$: constant(mediaDevices.videoInput.select),
backgroundEffect$: scope.behavior(
combineLatest([backgroundEffectSetting.value$, supported$]).pipe(
map(([raw, supported]) =>
supported ? serializeEffect(parseEffect(raw)) : "none",
),
),
),
selectBackgroundEffect$: scope.behavior(
offered$.pipe(
map((offered) =>
offered
? (id: string): void =>
backgroundEffectSetting.setValue(
serializeEffect(parseEffect(id)),
)
: undefined,
),
),
),
backgroundEffects$: scope.behavior(
addedBackgrounds.added$.pipe(
map((added) => backgroundEffectChoices(added ?? [])),
),
),
backgroundEffectNotice$: scope.behavior(
offered$.pipe(
map((offered) =>
!offered ? "unavailable" : slow ? "slow" : undefined,
),
),
),
backgroundEffectSettling$: scope.behavior(
backgroundEffectsState$.pipe(
map(({ wait }) => wait !== undefined),
distinctUntilChanged(),
),
false,
),
// Kept and offered, not put on: that waits for the user to choose it.
addBackgroundImage$: scope.behavior(
combineLatest([offered$, addedBackgrounds.added$]).pipe(
map(([offered, added]) =>
offered && (added?.length ?? 0) < maxAddedBackgrounds
? (file: File): void => {
refusal$.next(undefined);
addedBackgrounds.add(file).catch((e) => {
logger.warn("Could not keep that background", e);
refuse(e instanceof UnusableImage ? e.reason : "not-kept");
});
}
: undefined,
),
),
),
backgroundImageRefusal$: refusal$,
// Muting stops the camera, and so its light.
// The track outlives the mute, so its mute state is checked.
cameraTrack$: scope.behavior(
camera$.pipe(
switchMap((camera) =>
camera
? camera.muted$.pipe(map((muted) => (muted ? null : camera)))
: of(null),
),
),
null,
),
removeBackgroundEffect$: scope.behavior(
offered$.pipe(
map((offered) =>
offered
? (optionId: string): void => {
const effect = parseEffect(optionId);
if (effect.kind !== "added") return;
// The selected effect can't be removed: that would leave no
// effect selected.
if (backgroundEffectSetting.getValue() === optionId) return;
addedBackgrounds
.remove(effect.id)
.catch((e) =>
logger.warn("Could not remove that background", e),
);
}
: undefined,
),
),
),
};
}
function backgroundEffectChoices(
added: AddedBackground[],
): BackgroundEffectGridItem[] {
return [
{ id: serializeEffect({ kind: "none" }), kind: "none", removable: false },
{ id: serializeEffect({ kind: "blur" }), kind: "blur", removable: false },
...shippedBackgrounds.map((background) => ({
id: serializeEffect({ kind: "shipped", id: background.id }),
kind: "image" as const,
imageUrl: background.imagePath,
removable: false,
})),
...added.map((background) => ({
id: serializeEffect({ kind: "added", id: background.id }),
kind: "image" as const,
imageUrl: background.url,
removable: true,
})),
];
}
@@ -404,7 +404,7 @@ export const BackgroundImageRefused: Story = {
selectedBackgroundEffect: "blur",
backgroundEffectNotice:
"Background effects run slowly on this platform, which may cause your video to stutter.",
backgroundImageRefusal: "That file is not a supported image",
backgroundImageRefusal: { text: "That file is not a supported image" },
},
decorators: [
(Story): JSX.Element => (
@@ -440,7 +440,7 @@ function swatch(colour: string): string {
)}`;
}
/** One's own backgrounds are removable, unless one is the selected one. */
/** One's own backgrounds are removable, never the one in force. */
export const AddedBackgroundsCanBeRemoved: Story = {
args: {
...VideoUnmute.args,
@@ -437,7 +437,7 @@ describe("MediaMuteAndSwitchButton", () => {
}
});
test("a refusal is dismissed when closed, or with the menu", async () => {
test("a refusal can be dismissed and does not outlive the menu", async () => {
const user = userEvent.setup();
// jsdom lays nothing out, so has nothing to scroll.
const scroll = Element.prototype.scrollIntoView;
@@ -445,8 +445,7 @@ describe("MediaMuteAndSwitchButton", () => {
onTestFinished(() => {
Element.prototype.scrollIntoView = scroll;
});
const onDismiss = vi.fn();
const menu = (refusal?: string): JSX.Element =>
const menu = (refusal?: { text: string }): JSX.Element =>
withProviders(
<MediaMuteAndSwitchButton
iconsAndLabels="video"
@@ -458,22 +457,28 @@ describe("MediaMuteAndSwitchButton", () => {
onSelectBackgroundEffect={vi.fn()}
onAddBackgroundImage={vi.fn()}
backgroundImageRefusal={refusal}
onDismissBackgroundImageRefusal={onDismiss}
/>,
);
const { rerender, getByRole } = render(menu());
await user.click(getByRole("button", { name: "Camera" }));
rerender(menu("That file is not a supported image"));
rerender(menu({ text: "That file is not a supported image" }));
expect(
screen.getByText("That file is not a supported image"),
).toBeVisible();
screen.getByRole("menuitemradio", { name: "Blur", checked: true });
await user.click(screen.getByRole("button", { name: "Close" }));
expect(onDismiss).toHaveBeenCalledTimes(1);
expect(screen.queryByText("That file is not a supported image")).toBeNull();
// The next refusal is shown, even if it says the same.
rerender(menu({ text: "That file is not a supported image" }));
expect(
screen.getByText("That file is not a supported image"),
).toBeVisible();
await user.keyboard("{Escape}");
expect(onDismiss).toHaveBeenCalledTimes(2);
await user.click(getByRole("button", { name: "Camera" }));
expect(screen.queryByText("That file is not a supported image")).toBeNull();
});
test("offers the background effects in a phone's drawer", async () => {
+16 -17
View File
@@ -85,12 +85,10 @@ export interface MediaMuteAndSwitchButtonProps {
backgroundEffectSettling?: boolean;
/** Called with the file chosen from the add tile. Omit to leave it out. */
onAddBackgroundImage?: (file: File) => void;
/** Removes a removable effect, unless it is the selected one. */
/** Removes a removable effect, never the one in force. */
onRemoveBackgroundEffect?: (id: string) => void;
/** Why the last file offered couldn't be used, if it couldn't. */
backgroundImageRefusal?: string;
/** Called as the refusal is closed, or the menu showing it. */
onDismissBackgroundImageRefusal?: () => void;
/** Why the last file offered couldn't be used; a new object each time. */
backgroundImageRefusal?: { text: string };
/** The user's own camera, shown at the top of the camera menu. */
selfPreview?: ReactNode;
/**
@@ -137,7 +135,6 @@ export const MediaMuteAndSwitchButton: FC<MediaMuteAndSwitchButtonProps> = ({
onAddBackgroundImage,
onRemoveBackgroundEffect,
backgroundImageRefusal,
onDismissBackgroundImageRefusal,
selfPreview,
onSelect,
}) => {
@@ -152,18 +149,20 @@ export const MediaMuteAndSwitchButton: FC<MediaMuteAndSwitchButtonProps> = ({
// elsewhere; it is held open until the picker is done.
const choosingFile = useRef(false);
const fileInput = useRef<HTMLInputElement | null>(null);
// A refusal is about the attempt that caused it: shown until dismissed or
// until the menu closes, and again for the next one.
const [seenRefusal, setSeenRefusal] = useState<object>();
const refusal =
backgroundImageRefusal !== seenRefusal ? backgroundImageRefusal : undefined;
const onOpenChange = useCallback(
(open: boolean): void => {
if (!open && choosingFile.current) return;
setMenuOpen(open);
if (!open) {
// Drop a request that never arrived.
setPlannedSelection(null);
// A refusal is about the attempt that caused it.
onDismissBackgroundImageRefusal?.();
}
// Drop a request that never arrived.
if (!open) setPlannedSelection(null);
if (!open) setSeenRefusal(backgroundImageRefusal);
},
[onDismissBackgroundImageRefusal],
[backgroundImageRefusal],
);
// Scrolled to as it appears, as the list may be scrolled away from it.
const scrollIntoView = useCallback((element: HTMLElement | null): void => {
@@ -513,7 +512,7 @@ export const MediaMuteAndSwitchButton: FC<MediaMuteAndSwitchButtonProps> = ({
removeLabel={t("action.remove")}
/>
{/* In the list, so the menu grows no taller for it. */}
{backgroundImageRefusal !== undefined && (
{refusal !== undefined && (
<div
ref={scrollIntoView}
role="none"
@@ -521,12 +520,12 @@ export const MediaMuteAndSwitchButton: FC<MediaMuteAndSwitchButtonProps> = ({
>
<Alert
type="critical"
title={backgroundImageRefusal}
onClose={onDismissBackgroundImageRefusal}
title={refusal.text}
onClose={(): void => setSeenRefusal(refusal)}
/>
</div>
)}
{backgroundImageRefusal === undefined &&
{refusal === undefined &&
backgroundEffectNotice !== undefined && (
<div id={noticeId} role="none" className={styles.notice}>
<InfoIcon width={20} height={20} />
+62
View File
@@ -0,0 +1,62 @@
/*
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, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import { BrowserRouter } from "react-router-dom";
import { type MatrixClient } from "matrix-js-sdk";
import { BehaviorSubject } from "rxjs";
import { HomePage } from "./HomePage";
import { ClientContextProvider } from "../ClientContext";
import { type ClientSessionState } from "../state/ClientSession";
vi.mock("./RegisteredView", () => ({
RegisteredView: ({ client }: { client: MatrixClient }) => (
<span>registered as {client.getUserId()}</span>
),
}));
vi.mock("./UnauthenticatedView", () => ({
UnauthenticatedView: () => <span>unauthenticated</span>,
}));
test("waits for the session to be restored", () => {
renderHome({ state: "loading" });
expect(screen.getByRole("heading", { name: "Loading…" })).toBeVisible();
});
test("shows the session's error", () => {
vi.spyOn(console, "error").mockImplementation(() => {});
renderHome({ state: "error", error: new Error("Opened elsewhere") });
expect(screen.getByText("Something went wrong")).toBeVisible();
});
test("welcomes a signed-in user", () => {
renderHome({
state: "signedIn",
client: { getUserId: () => "@alice:example.org" } as MatrixClient,
passwordlessUser: false,
});
expect(screen.getByText("registered as @alice:example.org")).toBeVisible();
});
test("invites a signed-out user to start a call", () => {
renderHome({ state: "signedOut" });
expect(screen.getByText("unauthenticated")).toBeVisible();
});
function renderHome(state: ClientSessionState): void {
render(
<BrowserRouter>
<ClientContextProvider
value={{ state$: new BehaviorSubject<ClientSessionState>(state) }}
>
<HomePage />
</ClientContextProvider>
</BrowserRouter>,
);
}
+11 -12
View File
@@ -8,7 +8,7 @@ Please see LICENSE in the repository root for full details.
import { useTranslation } from "react-i18next";
import { type FC } from "react";
import { useClientState } from "../ClientContext";
import { useClientSessionState } from "../ClientContext";
import { ErrorPage, LoadingPage } from "../FullScreenView";
import { UnauthenticatedView } from "./UnauthenticatedView";
import { RegisteredView } from "./RegisteredView";
@@ -18,17 +18,16 @@ export const HomePage: FC = () => {
const { t } = useTranslation();
usePageTitle(t("common.home"));
const clientState = useClientState();
const session = useClientSessionState();
if (!clientState) {
return <LoadingPage />;
} else if (clientState.state === "error") {
return <ErrorPage error={clientState.error} />;
} else {
return clientState.authenticated ? (
<RegisteredView client={clientState.authenticated.client} />
) : (
<UnauthenticatedView />
);
switch (session.state) {
case "loading":
return <LoadingPage />;
case "error":
return <ErrorPage error={session.error} />;
case "signedIn":
return <RegisteredView client={session.client} />;
case "signedOut":
return <UnauthenticatedView />;
}
};
+136
View File
@@ -0,0 +1,136 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { afterEach, expect, test, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { type FC } from "react";
import { MemoryRouter, useLocation } from "react-router-dom";
import { type MatrixClient } from "matrix-js-sdk";
import { UnauthenticatedView } from "./UnauthenticatedView";
import { ClientManagerProvider } from "../ClientContext";
import { type ClientManager } from "../state/ClientSession";
import { computeUrlParams, UrlParamsProvider } from "../UrlParams";
import type * as matrixUtils from "../utils/matrix";
import { createRoom, getRelativeRoomUrl } from "../utils/matrix";
import { E2eeType } from "../e2ee/e2eeType";
vi.mock("../auth/useRecaptcha", () => ({
useRecaptcha: () => ({
execute: vi.fn().mockResolvedValue("captcha-response"),
reset,
recaptchaId: "recaptcha",
}),
}));
vi.mock("../auth/useRegistrationTerms", () => ({
useRegistrationTerms: () => ({ recaptchaKey: "site-key" }),
}));
vi.mock("../auth/generateRandomName", () => ({
generateRandomName: () => "Random Name",
}));
vi.mock("../utils/matrix", async (importOriginal) => ({
...(await importOriginal<typeof matrixUtils>()),
createRoom: vi.fn(),
}));
vi.mock("../UserMenuContainer", () => ({ UserMenuContainer: () => null }));
const reset = vi.fn();
const client = {} as MatrixClient;
afterEach(() => vi.clearAllMocks());
test("registers a guest, creates their call and signs them in", async () => {
const manager = mockManager();
const setSignedIn = vi.fn();
vi.mocked(manager.register).mockResolvedValue({ client, setSignedIn });
vi.mocked(createRoom).mockResolvedValue({
roomId: "!call:example.org",
alias: "#my-call:example.org",
password: "secret",
});
renderView(manager);
await submit("My Call", "Alice");
expect(manager.register).toHaveBeenCalledWith(
"Random Name",
expect.stringMatching(/^.{16}$/),
"Alice",
"captcha-response",
true,
);
expect(createRoom).toHaveBeenCalledWith(
client,
"My Call",
E2eeType.SHARED_KEY,
);
expect(setSignedIn).toHaveBeenCalled();
const url = getRelativeRoomUrl(
"!call:example.org",
{ kind: E2eeType.SHARED_KEY, secret: "secret" },
"My Call",
);
expect(await screen.findByText(`at ${url}`)).toBeVisible();
});
test("signs in only once the user chooses to join a call that exists", async () => {
const manager = mockManager();
const setSignedIn = vi.fn();
vi.mocked(manager.register).mockResolvedValue({ client, setSignedIn });
vi.mocked(createRoom).mockRejectedValue({ errcode: "M_ROOM_IN_USE" });
renderView(manager);
await submit("My Call", "Alice");
const join = await screen.findByRole("button", { name: "Yes, join call" });
expect(setSignedIn).not.toHaveBeenCalled();
await userEvent.click(join);
expect(setSignedIn).toHaveBeenCalled();
expect(await screen.findByText("at /my-call")).toBeVisible();
});
test("shows why registering failed and resets the captcha", async () => {
const manager = mockManager();
vi.mocked(manager.register).mockRejectedValue(new Error("Rate limited"));
renderView(manager);
await submit("My Call", "Alice");
expect(await screen.findByText("Rate limited")).toBeVisible();
expect(reset).toHaveBeenCalled();
expect(createRoom).not.toHaveBeenCalled();
});
async function submit(callName: string, displayName: string): Promise<void> {
const user = userEvent.setup();
await user.type(screen.getByTestId("home_callName"), callName);
await user.type(screen.getByTestId("home_displayName"), displayName);
await user.click(screen.getByTestId("home_go"));
}
function mockManager(): ClientManager {
return { login: vi.fn(), register: vi.fn(), logout: vi.fn() };
}
const WhereAmI: FC = () => {
const { pathname, search, hash } = useLocation();
return <span>{`at ${pathname}${search}${hash}`}</span>;
};
function renderView(manager: ClientManager): void {
render(
<MemoryRouter initialEntries={["/"]}>
<UrlParamsProvider value={computeUrlParams()}>
<ClientManagerProvider value={manager}>
<UnauthenticatedView />
<WhereAmI />
</ClientManagerProvider>
</UrlParamsProvider>
</MemoryRouter>,
);
}
+12 -24
View File
@@ -12,7 +12,7 @@ import { Button, Heading, Text } from "@vector-im/compound-web";
import { logger } from "matrix-js-sdk/lib/logger";
import { useNavigate } from "react-router-dom";
import { useClient } from "../ClientContext";
import { useClientManager } from "../ClientContext";
import { Header, HeaderLogo, LeftNav, RightNav } from "../Header";
import { UserMenuContainer } from "../UserMenuContainer";
import { FieldRow, InputField, ErrorMessage } from "../input/Input";
@@ -22,7 +22,7 @@ import {
roomAliasLocalpartFromRoomName,
sanitiseRoomNameInput,
} from "../utils/matrix";
import { useInteractiveRegistration } from "../auth/useInteractiveRegistration";
import { useRegistrationTerms } from "../auth/useRegistrationTerms";
import { JoinExistingCallModal } from "./JoinExistingCallModal";
import { useRecaptcha } from "../auth/useRecaptcha";
import { Form } from "../form/Form";
@@ -37,12 +37,12 @@ import { ExternalLink, Link } from "../button/Link";
import { useUrlParams } from "../UrlParams";
export const UnauthenticatedView: FC = () => {
const { setClient } = useClient();
const { register } = useClientManager();
const { header } = useUrlParams();
const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error>();
const [optInAnalytics] = useOptInAnalytics();
const { recaptchaKey, register } = useInteractiveRegistration();
const { recaptchaKey } = useRegistrationTerms();
const { execute, reset, recaptchaId } = useRecaptcha(recaptchaKey);
const [joinExistingCallModalOpen, setJoinExistingCallModalOpen] =
@@ -67,7 +67,9 @@ export const UnauthenticatedView: FC = () => {
setLoading(true);
const recaptchaResponse = await execute();
const userName = generateRandomName();
const [client, session] = await register(
// Signed in only once the call exists too: this view is replaced the
// moment the session has a user, and the call is what they came for
const { client, setSignedIn } = await register(
userName,
secureRandomString(16),
displayName,
@@ -83,15 +85,12 @@ export const UnauthenticatedView: FC = () => {
E2eeType.SHARED_KEY,
);
} catch (error) {
if (!setClient) {
throw error;
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (error.errcode === "M_ROOM_IN_USE") {
setOnFinished(() => {
setClient(client, session);
// Wrapped once more, as a bare function would be taken for an updater
setOnFinished(() => () => {
setSignedIn();
const aliasLocalpart = roomAliasLocalpartFromRoomName(roomName);
navigate(`/${aliasLocalpart}`)?.catch((error) => {
logger.error("Failed to navigate to alias localpart", error);
@@ -106,14 +105,10 @@ export const UnauthenticatedView: FC = () => {
}
}
// Only consider the registration successful if we managed to create the room, too
if (!setClient) {
throw new Error("setClient is undefined");
}
if (!createRoomResult.password)
throw new Error("Failed to create room with shared secret");
setClient(client, session);
setSignedIn();
await navigate(
getRelativeRoomUrl(
createRoomResult.roomId,
@@ -130,14 +125,7 @@ export const UnauthenticatedView: FC = () => {
reset();
});
},
[
register,
reset,
execute,
navigate,
setJoinExistingCallModalOpen,
setClient,
],
[register, reset, execute, navigate, setJoinExistingCallModalOpen],
);
return (
-122
View File
@@ -1,122 +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 { renderHook } from "@testing-library/react";
import {
EventType,
JoinRule,
KnownMembership,
type MatrixClient,
MatrixEvent,
type Room,
} from "matrix-js-sdk";
import { describe, expect, test } from "vitest";
import { useGroupCallRooms } from "./useGroupCallRooms";
import { mockMatrixRoom } from "../utils/test";
describe("useGroupCallRooms", () => {
test("lists a joined room with legacy call member state", () => {
const room = mockCallRoom({ legacyMemberState: true });
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("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({
membership: KnownMembership.Knock,
joinRule: JoinRule.Knock,
});
expect(listedRoomIds([room])).toEqual([room.roomId]);
});
test("omits a joined room without any call events", () => {
const room = mockCallRoom({
stickyEvents: [new MatrixEvent({ type: EventType.RoomMessage })],
timelineEvents: [new MatrixEvent({ type: EventType.RoomMessage })],
});
expect(listedRoomIds([room])).toEqual([]);
});
test.each([KnownMembership.Invite, KnownMembership.Leave])(
"omits a room with %s membership despite call events",
(membership) => {
const room = mockCallRoom({
membership,
legacyMemberState: true,
stickyEvents: [new MatrixEvent({ type: EventType.RTCMembership })],
timelineEvents: [new MatrixEvent({ type: EventType.RTCMembership })],
});
expect(listedRoomIds([room])).toEqual([]);
},
);
});
function listedRoomIds(rooms: Room[]): string[] {
const client = {
getRooms: () => rooms,
getUserId: () => "@alice:example.org",
on: () => {},
off: () => {},
matrixRTC: {
getRoomSession: () => ({ memberships: [] }),
on: () => {},
off: () => {},
},
} as unknown as MatrixClient;
const { result } = renderHook(() => useGroupCallRooms(client));
return result.current.map(({ room }) => room.roomId);
}
let nextRoomId = 0;
function mockCallRoom({
membership = KnownMembership.Join,
joinRule = JoinRule.Public,
legacyMemberState = false,
stickyEvents = [],
timelineEvents = [],
}: {
membership?: KnownMembership;
joinRule?: JoinRule;
legacyMemberState?: boolean;
stickyEvents?: MatrixEvent[];
timelineEvents?: MatrixEvent[];
}): Room {
const stateEvents = new Map(
legacyMemberState ? [[EventType.GroupCallMemberPrefix, new Map()]] : [],
);
return mockMatrixRoom({
roomId: `!room${nextRoomId++}:example.org`,
name: "Call room",
getMyMembership: () => membership,
getJoinRule: () => joinRule,
hasEncryptionStateEvent: () => true,
getCanonicalAlias: () => null,
getMxcAvatarUrl: () => null,
getLiveTimeline: () =>
({
getState: () => ({ events: stateEvents }),
getEvents: () => timelineEvents,
}) as unknown as ReturnType<Room["getLiveTimeline"]>,
_unstable_getStickyEvents: () =>
stickyEvents as unknown as ReturnType<Room["_unstable_getStickyEvents"]>,
});
}
+6 -4
View File
@@ -141,7 +141,7 @@ const roomHasCallMembershipEvents = (room: Room): boolean => {
return true;
}
// Check for recent calls using sticky events.
// Check for *active* calls using sticky events.
for (const sticky of room._unstable_getStickyEvents()) {
if (sticky.getType() === EventType.RTCMembership) {
return true;
@@ -150,9 +150,11 @@ const roomHasCallMembershipEvents = (room: Room): boolean => {
// Otherwise, check recent event history to see if anyone had
// sent a call membership in here.
return timeline
.getEvents()
.some((e) => e.getType() === EventType.RTCMembership);
return timeline.getEvents().some(
(e) =>
// Membership events only count if both of these are true
e.unstableStickyInfo && e.getType() === EventType.GroupCallMemberPrefix,
);
// Otherwise, it's *unlikely* this room was ever a call.
};
+1 -2
View File
@@ -22,8 +22,7 @@ and their fonts, where a host embedding the component supplies its own. The
@import url("@fontsource/inconsolata/400.css");
@import url("@fontsource/inconsolata/700.css");
@import url("@vector-im/compound-design-tokens/assets/web/css/compound-design-tokens.css")
layer(compound);
@import url("@vector-im/compound-design-tokens/assets/web/css/compound-design-tokens.css") layer(compound);
@import url("@vector-im/compound-web/dist/style.css") layer(compound.components);
body {
+19 -9
View File
@@ -20,7 +20,9 @@ import { App } from "./App";
import { init as initRageshake } from "./settings/rageshake";
import { Initializer } from "./initializer";
import { AppViewModel } from "./state/AppViewModel";
import { pendingHostClientSession } from "./state/ClientSession";
import { globalScope } from "./state/ObservableScope";
import { StandaloneClientSession } from "./state/StandaloneClientSession";
import { getUrlParams } from "./UrlParams";
initRageshake().catch((e) => {
@@ -51,17 +53,25 @@ if (fatalError !== null) {
Initializer.initBeforeReact()
.then((widget) => {
const { controlledAudioDevices, callIntent } = getUrlParams();
// As a widget, the client comes from the host over the widget API, and
// the session is the host's. Standalone, Element Call restores or creates
// a session of its own, which it also manages.
const options = { controlledAudioDevices, callIntent };
let vm: AppViewModel;
if (widget === null) {
const session = new StandaloneClientSession(globalScope);
vm = new AppViewModel(globalScope, options, session, session);
} else {
vm = new AppViewModel(
globalScope,
options,
pendingHostClientSession(globalScope, widget.client),
null,
);
}
root.render(
<StrictMode>
<App
vm={
new AppViewModel(globalScope, {
controlledAudioDevices,
callIntent,
})
}
widget={widget}
/>
<App vm={vm} widget={widget} />
</StrictMode>,
);
})
+2 -4
View File
@@ -18,7 +18,7 @@ import { type MatrixRTCSession } from "matrix-js-sdk/lib/matrixrtc";
import { logger } from "matrix-js-sdk/lib/logger";
import { useMatrixRTCSessionMemberships } from "../useMatrixRTCSessionMemberships";
import { useClientState } from "../ClientContext";
import { useHostBridge } from "../HostBridge";
import { ElementCallReactionEventType, type ReactionOption } from ".";
import { type CallViewModel } from "../state/CallViewModel/CallViewModel";
import { useBehavior } from "../useBehavior";
@@ -54,9 +54,7 @@ export const ReactionsSenderProvider = ({
vm: CallViewModel;
}): JSX.Element => {
const memberships = useMatrixRTCSessionMemberships(rtcSession);
const clientState = useClientState();
const supportsReactions =
clientState?.state === "valid" && clientState.supportedFeatures.reactions;
const { supportsReactions } = useHostBridge();
const room = rtcSession.room;
const myUserId = room.client.getUserId();
const myDeviceId = room.client.getDeviceId();
+8 -10
View File
@@ -186,18 +186,13 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
const vm = createCallViewModel$(
scope,
{
rtcParticipation,
matrixRoom: props.matrixRoom,
mediaDevices,
muteStates: props.muteStates,
encryptionSystem: props.e2eeSystem,
viewSize$: scope.behavior(observeElementSize$(rootElement)),
handsRaisedSubject$: reactionsReader.raisedHands$,
reactionsSubject$: reactionsReader.reactions$,
},
rtcParticipation,
props.matrixRoom,
mediaDevices,
props.muteStates,
{
...callViewModelOptionsFromParams(urlParams),
encryptionSystem: props.e2eeSystem,
capture,
backgroundEffectsState$,
hostBridge,
@@ -207,7 +202,10 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
scope,
props.rtcSession,
),
windowSize$: scope.behavior(observeElementSize$(rootElement)),
},
reactionsReader.raisedHands$,
reactionsReader.reactions$,
);
setVm(vm);
+101
View File
@@ -0,0 +1,101 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { afterEach, expect, test, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { type MatrixClient } from "matrix-js-sdk";
import { BehaviorSubject } from "rxjs";
import { RoomPage } from "./RoomPage";
import { ClientContextProvider } from "../ClientContext";
import { type ClientSessionState } from "../state/ClientSession";
import { computeUrlParams, UrlParamsProvider } from "../UrlParams";
import { useLoadGroupCall } from "./useLoadGroupCall";
vi.mock("./useLoadGroupCall", () => ({
useLoadGroupCall: vi.fn(() => ({ kind: "loading" })),
CallTerminatedMessage: class extends Error {},
}));
vi.mock("./useRoomName", () => ({ useRoomName: () => null }));
vi.mock("../profile/useProfile", () => ({ useProfile: () => ({}) }));
vi.mock("../auth/useRegisterPasswordlessUser", () => ({
useRegisterPasswordlessUser: () => ({ registerPasswordlessUser }),
}));
vi.mock("./RoomAuthView", () => ({
RoomAuthView: () => <span>room auth view</span>,
}));
vi.mock("../home/HomePage", () => ({
HomePage: () => <span>home page</span>,
}));
vi.mock("./CallView", () => ({
CallView: ({ isPasswordlessUser }: { isPasswordlessUser: boolean }) => (
<span>call view, passwordless: {String(isPasswordlessUser)}</span>
),
}));
vi.mock("./KnockLobbyView", () => ({ KnockLobbyView: () => null }));
const registerPasswordlessUser = vi.fn().mockResolvedValue(undefined);
afterEach(() => vi.clearAllMocks());
test("waits for the session to be restored", () => {
renderRoom({ state: "loading" }, "/call");
expect(screen.getByRole("heading", { name: "Loading…" })).toBeVisible();
});
test("asks a signed-out user to join as a guest", () => {
renderRoom({ state: "signedOut" }, "/call");
expect(screen.getByText("room auth view")).toBeVisible();
expect(registerPasswordlessUser).not.toHaveBeenCalled();
});
test("registers a passwordless user when the URL names one", () => {
renderRoom({ state: "signedOut" }, "/call", "Alice");
expect(registerPasswordlessUser).toHaveBeenCalledWith("Alice");
});
test("falls back to the home page without a room", () => {
renderRoom(signedIn(false), "/");
expect(screen.getByText("home page")).toBeVisible();
});
test("tells the call whether its user is passwordless", () => {
vi.mocked(useLoadGroupCall).mockReturnValue({
kind: "loaded",
rtcSession: { room: {} },
} as unknown as ReturnType<typeof useLoadGroupCall>);
renderRoom(signedIn(true), "/call");
expect(screen.getByText("call view, passwordless: true")).toBeVisible();
});
function signedIn(passwordlessUser: boolean): ClientSessionState {
return {
state: "signedIn",
client: { getUserId: () => "@alice:example.org" } as MatrixClient,
passwordlessUser,
};
}
function renderRoom(
state: ClientSessionState,
path: string,
displayName: string | null = null,
): void {
render(
<MemoryRouter initialEntries={[path]}>
<UrlParamsProvider value={{ ...computeUrlParams(), displayName }}>
<ClientContextProvider
value={{ state$: new BehaviorSubject<ClientSessionState>(state) }}
>
<RoomPage />
</ClientContextProvider>
</UrlParamsProvider>
</MemoryRouter>,
);
}
+7 -4
View File
@@ -12,7 +12,7 @@ import { logger } from "matrix-js-sdk/lib/logger";
import { Trans, useTranslation } from "react-i18next";
import { UnknownSolidIcon } from "@vector-im/compound-design-tokens/assets/web/icons";
import { useClientLegacy } from "../ClientContext";
import { useClient, useClientSessionState } from "../ClientContext";
import { ErrorPage, FullScreenView, LoadingPage } from "../FullScreenView";
import { RoomAuthView } from "./RoomAuthView";
import { CallView } from "./CallView";
@@ -42,8 +42,12 @@ export const RoomPage: FC = (): ReactNode => {
const { registerPasswordlessUser } = useRegisterPasswordlessUser();
const [isRegistering, setIsRegistering] = useState(false);
const { loading, authenticated, client, error, passwordlessUser } =
useClientLegacy();
const { client } = useClient();
const session = useClientSessionState();
const loading = session.state === "loading";
const passwordlessUser =
session.state === "signedIn" && session.passwordlessUser;
const authenticated = client !== undefined;
const { avatarUrl, displayName: userDisplayName } = useProfile(client);
const groupCallState = useLoadGroupCall(client, roomIdOrAlias, viaServers);
@@ -184,7 +188,6 @@ export const RoomPage: FC = (): ReactNode => {
};
if (loading || isRegistering) return <LoadingPage />;
if (error) return <ErrorPage error={error} />;
if (!client) return <RoomAuthView />;
// TODO: This doesn't belong here, the app routes need to be reworked
if (!roomIdOrAlias) return <HomePage />;
+2 -16
View File
@@ -20,6 +20,7 @@ import { type MatrixClient } from "matrix-js-sdk/lib/client";
import { useSubmitRageshake, getRageshakeSubmitUrl } from "./submit-rageshake";
import { ClientContextProvider } from "../ClientContext";
import { hostClientSession } from "../state/ClientSession";
import { getUrlParams } from "../UrlParams";
import { mockConfig } from "../utils/test";
import { DEFAULT_CONFIG } from "../config/ConfigOptions";
@@ -74,22 +75,7 @@ function renderWithMockClient(
} as unknown as MatrixClient);
render(
<ClientContextProvider
value={{
state: "valid",
disconnected: false,
supportedFeatures: {
reactions: true,
},
setClient: vi.fn(),
authenticated: {
client,
isPasswordlessUser: true,
changePassword: vi.fn(),
logout: vi.fn(),
},
}}
>
<ClientContextProvider value={hostClientSession(client)}>
<TestComponent
sendLogs={sendLogs}
getRageshakeSubmitUrl={getRageshakeSubmitUrl}
+7
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 { type ClientManager, type ClientSession } from "./ClientSession";
import { type AudioOutputOptions, MediaDevices } from "./MediaDevices";
import { type ObservableScope } from "./ObservableScope";
import { createAppBackgroundEffects } from "../tracks/BackgroundEffectsContext";
@@ -22,8 +23,14 @@ export class AppViewModel {
// TODO: Move more application logic here. The CallViewModel, at the very
// least, ought to be accessible from this object.
/**
* @param clientSession Where the client comes from. SPA js-sdk, EW host, widget
*/
public constructor(
private readonly scope: ObservableScope,
private readonly audioOutputOptions: AudioOutputOptions,
public readonly clientSession: ClientSession,
/** Null where the session is a host's and not ours to manage. */
public readonly clientManager: ClientManager | null,
) {}
}
+4 -4
View File
@@ -75,7 +75,7 @@ describe("the pipeline's state", () => {
const effects = createBackgroundEffects(testScope(), {
supported: true,
effect$: behavior(effect, { n: "none", b: "blur" }),
clearEffect: vi.fn(),
setEffect: vi.fn(),
added$: new BehaviorSubject<AddedBackground[] | undefined>([]),
canSegment: () => cold(answer, { y: true, n: false }),
pipeline: fakePipeline().pipeline,
@@ -110,7 +110,7 @@ describe("the pipeline's state", () => {
describe("background effects", () => {
let effect$: BehaviorSubject<string>;
let added$: BehaviorSubject<AddedBackground[] | undefined>;
let clearEffect: () => void;
let setEffect: (raw: string) => void;
let fake: ReturnType<typeof fakePipeline>;
function build(
@@ -119,7 +119,7 @@ describe("background effects", () => {
return createBackgroundEffects(testScope(), {
supported: true,
effect$,
clearEffect,
setEffect,
added$,
canSegment: () => of(true),
pipeline: fake.pipeline,
@@ -135,7 +135,7 @@ describe("background effects", () => {
beforeEach(() => {
effect$ = new BehaviorSubject("none");
added$ = new BehaviorSubject<AddedBackground[] | undefined>(undefined);
clearEffect = vi.fn(() => effect$.next("none"));
setEffect = vi.fn((raw: string) => effect$.next(raw));
fake = fakePipeline();
});
+5 -4
View File
@@ -33,6 +33,7 @@ import { type Behavior } from "./Behavior";
import { type ObservableScope } from "./ObservableScope";
import {
type BackgroundEffect,
type EffectId,
imagePathFor,
parseEffect,
} from "../tracks/backgroundEffectCatalog";
@@ -56,8 +57,8 @@ export interface BackgroundEffectsOptions {
supported: boolean;
/** The effect chosen, as the setting stores it. */
effect$: Behavior<string>;
/** Resets the choice to no effect, for when the chosen one can't run here. */
clearEffect: () => void;
/** Stores a choice, to forget one that can't be honoured. */
setEffect: (id: EffectId) => void;
/** The backgrounds the device keeps, undefined until it has said. */
added$: Behavior<AddedBackground[] | undefined>;
/** Builds a segmenter on trial, and answers whether it could. */
@@ -79,7 +80,7 @@ export function createBackgroundEffects(
{
supported,
effect$,
clearEffect,
setEffect,
added$,
canSegment,
pipeline,
@@ -106,7 +107,7 @@ export function createBackgroundEffects(
added !== undefined &&
!added.some(({ id }) => id === effect.id))
)
clearEffect();
setEffect("none");
});
// Asked once an effect is first wanted. A browser update may fix what
@@ -5,14 +5,12 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import EventEmitter from "events";
import { expect, test } from "vitest";
import { test } from "vitest";
import {
EventType,
type IRoomTimelineData,
MatrixEvent,
type Room,
RoomEvent,
RoomStickyEventsEvent,
} from "matrix-js-sdk";
import {
RTC_CALL_INTENT_AUDIO,
@@ -31,7 +29,6 @@ import {
import {
type CallNotificationWrapper,
createCallNotificationLifecycle$,
createReceivedDecline$,
type RingAttempt,
} from "./CallNotificationLifecycle";
import { constant } from "../Behavior";
@@ -208,16 +205,22 @@ test("ring attempt can be declined", () => {
a: mockRingEvent("$notif1", 30),
}),
receivedDecline$: hot("--d", {
d: new MatrixEvent({
type: EventType.RTCDecline,
sender: alice.userId,
content: {
"m.relates_to": {
rel_type: "m.reference",
event_id: "$notif1",
d: [
new MatrixEvent({
type: EventType.RTCDecline,
sender: alice.userId,
content: {
"m.relates_to": {
rel_type: "m.reference",
event_id: "$notif1",
},
},
},
}),
}),
{} as Room,
undefined,
false,
{} as IRoomTimelineData,
],
}),
});
@@ -237,16 +240,22 @@ test("ring attempt times out if recipient declines too late", () => {
a: mockRingEvent("$notif1", 30),
}),
receivedDecline$: hot("100ms d", {
d: new MatrixEvent({
type: EventType.RTCDecline,
sender: alice.userId,
content: {
"m.relates_to": {
rel_type: "m.reference",
event_id: "$notif1",
d: [
new MatrixEvent({
type: EventType.RTCDecline,
sender: alice.userId,
content: {
"m.relates_to": {
rel_type: "m.reference",
event_id: "$notif1",
},
},
},
}),
}),
{} as Room,
undefined,
false,
{} as IRoomTimelineData,
],
}),
});
@@ -266,16 +275,22 @@ test("decline event relating to wrong event is ignored (times out)", () => {
a: mockRingEvent("$notif1", 30),
}),
receivedDecline$: hot("--d", {
d: new MatrixEvent({
type: EventType.RTCDecline,
sender: alice.userId,
content: {
"m.relates_to": {
rel_type: "m.reference",
event_id: "$other", // <---- WRONG
d: [
new MatrixEvent({
type: EventType.RTCDecline,
sender: alice.userId,
content: {
"m.relates_to": {
rel_type: "m.reference",
event_id: "$other", // <---- WRONG
},
},
},
}),
}),
{} as Room,
undefined,
false,
{} as IRoomTimelineData,
],
}),
});
@@ -295,16 +310,22 @@ test("decline event from wrong sender is ignored (times out)", () => {
a: mockRingEvent("$notif1", 30),
}),
receivedDecline$: hot("--d", {
d: new MatrixEvent({
type: EventType.RTCDecline,
sender: local.userId, // <---- WRONG
content: {
"m.relates_to": {
rel_type: "m.reference",
event_id: "$notif1",
d: [
new MatrixEvent({
type: EventType.RTCDecline,
sender: local.userId, // <---- WRONG
content: {
"m.relates_to": {
rel_type: "m.reference",
event_id: "$notif1",
},
},
},
}),
}),
{} as Room,
undefined,
false,
{} as IRoomTimelineData,
],
}),
});
@@ -314,42 +335,3 @@ test("decline event from wrong sender is ignored (times out)", () => {
});
});
});
test("declines are received from the timeline and the sticky section", () => {
const event = (eventId: string, type = EventType.RTCDecline): MatrixEvent =>
new MatrixEvent({ event_id: eventId, type, sender: alice.userId });
const room = Object.assign(new EventEmitter(), {
_unstable_getStickyEvents: () => [
event("$existing"),
event("$existingMembership", EventType.RTCMembership),
],
});
const received: string[] = [];
const subscription = createReceivedDecline$(
room as unknown as Room,
).subscribe((event) => received.push(event.getId()!));
const timelineArgs = [room, false, false, {}];
room.emit(RoomEvent.Timeline, event("$timeline"), ...timelineArgs);
room.emit(
RoomEvent.Timeline,
event("$message", EventType.RoomMessage),
...timelineArgs,
);
// A gappy sync delivers the decline only in the sticky section
room.emit(RoomStickyEventsEvent.Update, [event("$sticky")], [], []);
room.emit(
RoomStickyEventsEvent.Update,
[],
[{ previous: event("$old"), current: event("$replacement") }],
[event("$removed")],
);
subscription.unsubscribe();
expect(received).toEqual([
"$existing",
"$timeline",
"$sticky",
"$replacement",
]);
});
@@ -14,9 +14,7 @@ import {
toStableCallIntent,
} from "matrix-js-sdk/lib/matrixrtc";
import {
defer,
filter,
from,
fromEvent,
map,
merge,
@@ -29,17 +27,13 @@ import {
EMPTY,
race,
take,
mergeMap,
} from "rxjs";
import {
type EventTimelineSetHandlerMap,
EventType,
type MatrixEvent,
type Room as MatrixRoom,
RoomEvent,
RoomStickyEventsEvent,
} from "matrix-js-sdk";
import { type RoomStickyEventsMap } from "matrix-js-sdk/lib/models/room-sticky-events";
import { logger as rootLogger } from "matrix-js-sdk/lib/logger";
import { type Behavior, type ObservableScope } from "@element-hq/matrixrtc-sdk";
@@ -76,34 +70,12 @@ export function createSentCallNotification$(
export function createReceivedDecline$(
matrixRoom: MatrixRoom,
): Observable<MatrixEvent> {
// A decline is sticky, so after a gappy sync it arrives only in the sticky
// section, which never reaches the timeline. Racing for the first outcome
// makes a decline seen in both places harmless.
const timeline$ = (
): Observable<Parameters<EventTimelineSetHandlerMap[RoomEvent.Timeline]>> {
return (
fromEvent(matrixRoom, RoomEvent.Timeline) as Observable<
Parameters<EventTimelineSetHandlerMap[RoomEvent.Timeline]>
>
).pipe(map(([event]) => event));
// The decline can arrive via sync before the send of our notification
// resolves, which is when we start listening. To guard against this, we
// include what is already in the sticky section.
const currentSticky$ = defer(() =>
from(matrixRoom._unstable_getStickyEvents()),
);
const sticky$ = (
fromEvent(matrixRoom, RoomStickyEventsEvent.Update) as Observable<
Parameters<RoomStickyEventsMap[RoomStickyEventsEvent.Update]>
>
).pipe(
mergeMap(([added, updated]) => [
...added,
...updated.map(({ current }) => current),
]),
);
return merge(currentSticky$, sticky$, timeline$).pipe(
filter((event) => event.getType() === EventType.RTCDecline),
);
).pipe(filter(([event]) => event.getType() === EventType.RTCDecline));
}
export interface Props {
@@ -113,7 +85,9 @@ export interface Props {
/** The user ids of the room's members, ours included. */
roomMemberUserIds$: Behavior<string[]>;
sentCallNotification$: Observable<CallNotificationWrapper | null>;
receivedDecline$: Observable<MatrixEvent>;
receivedDecline$: Observable<
Parameters<EventTimelineSetHandlerMap[RoomEvent.Timeline]>
>;
options: { waitForCallPickup?: boolean; autoLeaveWhenOthersLeft?: boolean };
localUser: { deviceId: string; userId: string };
}
@@ -174,7 +148,7 @@ export function createCallNotificationLifecycle$({
// Call is declined when we receive a decline event
const decline$ = receivedDecline$.pipe(
filter(
(event) =>
([event]) =>
event.getRelation()?.rel_type === "m.reference" &&
event.getRelation()?.event_id === notificationEvent.event_id &&
event.getSender() === recipient,
+10 -5
View File
@@ -36,6 +36,7 @@ import {
mockRtcMembership,
testScope,
} from "../../utils/test.ts";
import { E2eeType } from "../../e2ee/e2eeType.ts";
import {
alice,
aliceId,
@@ -505,7 +506,7 @@ describe.each(modes)("CallViewModel (%s mode)", (mode) => {
videoEnabled: new Map([
[localParticipant, behavior(videoInputMarbles, yesNo)],
]),
viewSize$: constant({ width: 380, height: 700 }), // Mobile phone in portrait
windowSize$: constant({ width: 380, height: 700 }), // Mobile phone in portrait
},
(vm) => {
schedule(tapScreenInputMarbles, { a: () => vm.tapScreen() });
@@ -547,7 +548,7 @@ describe.each(modes)("CallViewModel (%s mode)", (mode) => {
// Both Alice and Bob are with us in the room
roomMembers: [local, alice, bob],
rtcMembers$: constant([localRtcMember, aliceRtcMember]),
viewSize$: constant({ width: 380, height: 700 }), // Mobile phone
windowSize$: constant({ width: 380, height: 700 }), // Mobile phone
},
(vm) => {
// Uses one-on-one mobile layout
@@ -594,7 +595,7 @@ describe.each(modes)("CallViewModel (%s mode)", (mode) => {
sharingScreen: new Map([
[aliceParticipant, behavior(aliceSharingInputMarbles, yesNo)],
]),
viewSize$: constant({ width: 700, height: 380 }), // Mobile phone in landscape
windowSize$: constant({ width: 700, height: 380 }), // Mobile phone in landscape
},
(vm) => {
expectObservable(summarizeLayout$(vm.layout$)).toBe(
@@ -782,13 +783,13 @@ describe.each(modes)("CallViewModel (%s mode)", (mode) => {
test("layout reacts to window size", () => {
withTestScheduler(({ behavior, expectObservable }) => {
const viewSizeInputMarbles = "abc";
const windowSizeInputMarbles = "abc";
const expectedLayoutMarbles = " abc";
withCallViewModel(
{
remoteParticipants$: constant([aliceParticipant]),
rtcMembers$: constant([localRtcMember, aliceRtcMember]),
viewSize$: behavior(viewSizeInputMarbles, {
windowSize$: behavior(windowSizeInputMarbles, {
a: { width: 380, height: 700 }, // Start very narrow, like a phone
b: { width: 1000, height: 800 }, // Go to normal desktop window size
c: { width: 200, height: 180 }, // Go to PiP size
@@ -1465,6 +1466,7 @@ describe.each(modes)("CallViewModel (%s mode)", (mode) => {
},
{
autoLeaveWhenOthersLeft: true,
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
},
);
});
@@ -1482,6 +1484,7 @@ describe.each(modes)("CallViewModel (%s mode)", (mode) => {
},
{
autoLeaveWhenOthersLeft: true,
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
},
);
});
@@ -1499,6 +1502,7 @@ describe.each(modes)("CallViewModel (%s mode)", (mode) => {
},
{
autoLeaveWhenOthersLeft: false,
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
},
);
});
@@ -1528,6 +1532,7 @@ describe.each(modes)("CallViewModel (%s mode)", (mode) => {
},
{
autoLeaveWhenOthersLeft: true,
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
},
);
});
+25 -47
View File
@@ -185,39 +185,8 @@ export function initialPublishRequests(
return requests;
}
/**
* What the call is made of: the room, the participation, the devices, the
* things with no sensible default. How the host wants it to behave is in
* {@link CallViewModelOptions} instead.
*/
export interface CallViewModelProps {
rtcParticipation: RTCParticipation;
/** A call is permanently tied to a single Matrix room. */
matrixRoom: MatrixRoom;
mediaDevices: MediaDevices;
muteStates: MuteStates;
encryptionSystem: EncryptionSystem;
/**
* The size of the space the call is drawn in: the page when Element Call
* owns it, or the container a host mounted it in when it is a component.
* The layout — whether the call is shown full size, flat, narrow or as a
* picture-in-picture — follows this rather than the size of the window, so
* that a component shrunk by its host adapts even though the window has not
* changed.
*/
viewSize$: Behavior<{ width: number; height: number }>;
handsRaisedSubject$: Observable<Record<string, RaisedHandInfo>>;
reactionsSubject$: Observable<Record<string, ReactionInfo>>;
}
/**
* How the host wants the call to behave. Every field is optional and defaults
* to what standalone Element Call does, so `{}` is a working standalone call.
* What the call is made of is in {@link CallViewModelProps} instead. A test
* that wants to replace behaviour mocks the dependency it comes from rather
* than adding an option here.
*/
export interface CallViewModelOptions {
encryptionSystem: EncryptionSystem;
/**
* How our tracks are captured and encoded; the browser's and LiveKit's
* defaults otherwise.
@@ -253,6 +222,17 @@ export interface CallViewModelOptions {
* Defaults to none sent.
*/
sentCallNotification$?: Observable<CallNotificationWrapper | null>;
/**
* The size of the space the call is drawn in: the page when Element Call
* owns it, or the container a host mounted it in when it is a component.
* The layout — whether the call is shown full size, flat, narrow or as a
* picture-in-picture — follows this rather than the size of the window, so
* that a component shrunk by its host adapts even though the window has not
* changed.
*/
windowSize$: Behavior<{ width: number; height: number }>;
/** Optional behavior overriding for the screensharing, for testing */
toggleScreensharing?: () => void;
}
/**
@@ -489,17 +469,14 @@ export interface CallViewModel {
*/
export function createCallViewModel$(
scope: ObservableScope,
{
rtcParticipation,
matrixRoom,
mediaDevices,
muteStates,
encryptionSystem,
viewSize$,
handsRaisedSubject$,
reactionsSubject$,
}: CallViewModelProps,
options: CallViewModelOptions = {},
rtcParticipation: RTCParticipation,
// A call is permanently tied to a single Matrix room
matrixRoom: MatrixRoom,
mediaDevices: MediaDevices,
muteStates: MuteStates,
options: CallViewModelOptions,
handsRaisedSubject$: Observable<Record<string, RaisedHandInfo>>,
reactionsSubject$: Observable<Record<string, ReactionInfo>>,
): CallViewModel {
const logger = rootLogger.getChild("[CallViewModel]");
const client = matrixRoom.client;
@@ -725,7 +702,7 @@ export function createCallViewModel$(
userId: member.userId,
rtcBackendIdentity: member.rtcBackendIdentity,
member,
encryptionSystem,
encryptionSystem: options.encryptionSystem,
transport$: scope.behavior(
member.transport$.pipe(map((transport) => transport?.raw)),
),
@@ -939,7 +916,7 @@ export function createCallViewModel$(
// A guess at what the window's mode should be based on the size and shape of
// the space we have to draw in.
const naturalWindowMode$ = scope.behavior<WindowMode>(
viewSize$.pipe(
options.windowSize$.pipe(
map(({ width, height }) => {
if (height <= 400 && width <= 340) return "pip";
// Our layouts for flat windows are better at adapting to a small width
@@ -1523,7 +1500,8 @@ export function createCallViewModel$(
* the platform cannot capture a screen, or the host hides the button.
*/
const toggleScreenSharing =
hideScreensharing || !("getDisplayMedia" in (navigator.mediaDevices ?? {}))
options.toggleScreensharing ??
(hideScreensharing || !("getDisplayMedia" in (navigator.mediaDevices ?? {}))
? null
: (): void => {
const track = screenShare$.value;
@@ -1544,7 +1522,7 @@ export function createCallViewModel$(
e instanceof Error ? e : new Error(String(e)),
);
});
};
});
// Tell the host and the analytics about the user's joins and leaves. The
// participation is joined by the time the view model is built on it
@@ -81,7 +81,7 @@ export interface CallViewModelInputs {
sharingScreen: Map<Participant, Behavior<boolean>>;
mediaDevices: MediaDevices;
initialSyncState: SyncState;
viewSize$: Behavior<{ width: number; height: number }>;
windowSize$: Behavior<{ width: number; height: number }>;
}
export const localParticipant: Participant = { identity: "" };
@@ -106,7 +106,7 @@ export function withCallViewModel(mode: MatrixRTCMode) {
sharingScreen = new Map(),
mediaDevices = mockMediaDevices({}),
initialSyncState = SyncState.Syncing,
viewSize$ = constant({ width: 1000, height: 800 }),
windowSize$ = constant({ width: 1000, height: 800 }),
}: Partial<CallViewModelInputs> = {},
continuation: (
vm: CallViewModel,
@@ -146,7 +146,6 @@ export function withCallViewModel(mode: MatrixRTCMode) {
})() as Partial<MatrixClient> as MatrixClient,
getMembers: () => roomMembers,
getMembersWithMembership: () => roomMembers,
_unstable_getStickyEvents: () => [],
});
const rtcSession = new MockRTCSession(room, []).withMemberships(
rtcMembers$,
@@ -262,24 +261,22 @@ export function withCallViewModel(mode: MatrixRTCMode) {
const vm = createCallViewModel$(
scope,
rtcParticipation,
room,
mediaDevices,
muteStates,
{
rtcParticipation,
matrixRoom: room,
mediaDevices,
muteStates,
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
viewSize$,
handsRaisedSubject$: raisedHands$,
reactionsSubject$: reactions$,
},
{
autoLeaveWhenOthersLeft: false,
sentCallNotification$: createSentCallNotification$(
scope,
rtcSession.asMockedSession(),
),
windowSize$,
...options,
},
raisedHands$,
reactions$,
);
void mode;
+2
View File
@@ -17,6 +17,7 @@ import {
type HostRequest,
nullHostBridge,
} from "../HostBridge.ts";
import { E2eeType } from "../e2ee/e2eeType.ts";
import { MatrixRTCMode } from "../config/ConfigOptions.ts";
it.each([[MatrixRTCMode.Compatibility], [MatrixRTCMode.Matrix_2_0]])(
@@ -40,6 +41,7 @@ it.each([[MatrixRTCMode.Compatibility], [MatrixRTCMode.Matrix_2_0]])(
hangUp$.next({ data: {}, reply });
},
{
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
hostBridge,
},
);
+45
View File
@@ -0,0 +1,45 @@
/*
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 { type MatrixClient } from "matrix-js-sdk";
import { hostClientSession, pendingHostClientSession } from "./ClientSession";
import { flushPromises, testScope } from "../utils/test";
const client = {} as MatrixClient;
test("a host's client is signed in from the start", () => {
const session = hostClientSession(client);
expect(session.state$.value).toEqual({
state: "signedIn",
client,
passwordlessUser: false,
});
});
test("a pending host client is loading until it arrives", async () => {
const session = pendingHostClientSession(
testScope(),
Promise.resolve(client),
);
expect(session.state$.value).toEqual({ state: "loading" });
await flushPromises();
expect(session.state$.value).toEqual({
state: "signedIn",
client,
passwordlessUser: false,
});
});
test("a pending host client that never arrives is an error", async () => {
const error = new Error("no widget API");
const session = pendingHostClientSession(testScope(), Promise.reject(error));
await flushPromises();
// An error page rather than a spinner that never ends
expect(session.state$.value).toEqual({ state: "error", error });
});
+104
View File
@@ -0,0 +1,104 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { type MatrixClient } from "matrix-js-sdk";
import { logger } from "matrix-js-sdk/lib/logger";
import { catchError, from, map, of } from "rxjs";
import { type Behavior, constant } from "./Behavior";
import { type ObservableScope } from "./ObservableScope";
/**
* A session of Element Call's own, as the standalone app stores it.
*/
export interface StoredSession {
user_id: string;
device_id: string;
access_token: string;
passwordlessUser: boolean;
}
export type ClientSessionState =
| { state: "loading" }
| { state: "signedOut" }
| { state: "signedIn"; client: MatrixClient; passwordlessUser: boolean }
| { state: "error"; error: Error };
/**
* A newly registered account, with its client started. Registering and signing
* in are separate steps, as a caller may have more to do with the account
* before the session changes hands — creating the call it was registered for,
* say.
*/
export interface Registration {
client: MatrixClient;
setSignedIn: () => void;
}
/**
* Where Element Call's client comes from. Every build has one: a session of
* Element Call's own, or one a host has supplied.
*/
export interface ClientSession {
state$: Behavior<ClientSessionState>;
}
/**
* What can be done with a client created in EC (SPA). Widget and host client
* wont have this, see useClientManager and useClientManagerIfAny
*/
export interface ClientManager {
/** Signs in to the homeserver with a password, ending any current session. */
login: (
homeserver: string,
username: string,
password: string,
) => Promise<MatrixClient>;
/** Registers an account on the default homeserver. */
register: (
username: string,
password: string,
displayName: string,
recaptchaResponse: string,
passwordlessUser: boolean,
) => Promise<Registration>;
logout: () => Promise<void>;
}
/**
* A client supplied by the host, which owns the user's session: signed in from
* the start, nothing to restore. Used for the component target.
*/
export function hostClientSession(client: MatrixClient): ClientSession {
return { state$: constant(signedIn(client)) };
}
/**
* A client the host is still handing over.
* Used for the embedded target, widget API.
*/
export function pendingHostClientSession(
scope: ObservableScope,
client: Promise<MatrixClient>,
): ClientSession {
return {
state$: scope.behavior<ClientSessionState>(
from(client).pipe(
map(signedIn),
catchError((e) => {
logger.error("Failed to obtain the host's client", e);
return of<ClientSessionState>({ state: "error", error: e });
}),
),
{ state: "loading" },
),
};
}
function signedIn(client: MatrixClient): ClientSessionState {
return { state: "signedIn", client, passwordlessUser: false };
}
+265
View File
@@ -0,0 +1,265 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { afterEach, beforeEach, expect, test, vi } from "vitest";
import { type MatrixClient, MatrixError, type User } from "matrix-js-sdk";
import { StandaloneClientSession } from "./StandaloneClientSession";
import { type StoredSession } from "./ClientSession";
import { initClient } from "../utils/initClient";
import {
loginWithPassword,
registerWithPassword,
} from "../auth/interactiveAuth";
import { PosthogAnalytics } from "../analytics/PosthogAnalytics";
import { Config } from "../config/Config";
import { OpenElsewhereError } from "../RichError";
import { flushPromises, testScope } from "../utils/test";
vi.mock("../utils/initClient", () => ({ initClient: vi.fn() }));
vi.mock("../auth/interactiveAuth", () => ({
loginWithPassword: vi.fn(),
registerWithPassword: vi.fn(),
}));
const SESSION_KEY = "matrix-auth-store";
const session: StoredSession = {
user_id: "@alice:example.org",
device_id: "AAAA",
access_token: "secret",
passwordlessUser: true,
};
const user = { setRawDisplayName: vi.fn(), setDisplayName: vi.fn() };
const mockClient = (): MatrixClient =>
({
stopClient: vi.fn(),
logout: vi.fn().mockResolvedValue(undefined),
clearStores: vi.fn().mockResolvedValue(undefined),
setDisplayName: vi.fn().mockResolvedValue(undefined),
getUserId: () => session.user_id,
getUser: () => user as unknown as User,
}) as Partial<MatrixClient> as MatrixClient;
const credentials = {
user_id: "@bob:example.org",
device_id: "BBBB",
access_token: "fresh",
};
const storeSession = (): void =>
localStorage.setItem(SESSION_KEY, JSON.stringify(session));
const storedSession = (): StoredSession | null =>
JSON.parse(localStorage.getItem(SESSION_KEY) ?? "null");
beforeEach(() => {
vi.spyOn(Config, "init").mockResolvedValue(undefined);
vi.spyOn(Config, "defaultHomeserverUrl").mockReturnValue(
"https://hs.example.org",
);
localStorage.clear();
});
afterEach(() => {
vi.restoreAllMocks();
vi.clearAllMocks();
});
test("restores the stored session once the config is loaded", async () => {
storeSession();
const client = mockClient();
vi.mocked(initClient).mockResolvedValue(client);
const clientSession = new StandaloneClientSession(testScope());
expect(clientSession.state$.value).toEqual({ state: "loading" });
await flushPromises();
expect(Config.init).toHaveBeenCalled();
expect(initClient).toHaveBeenCalledWith(
expect.objectContaining({
baseUrl: "https://hs.example.org",
accessToken: "secret",
userId: "@alice:example.org",
deviceId: "AAAA",
}),
// Restoring: the crypto store is the session's, not to be wiped
true,
);
expect(clientSession.state$.value).toEqual({
state: "signedIn",
client,
passwordlessUser: true,
});
});
test("has no one signed in when there is no session to restore", async () => {
const clientSession = new StandaloneClientSession(testScope());
await flushPromises();
expect(initClient).not.toHaveBeenCalled();
expect(clientSession.state$.value).toEqual({ state: "signedOut" });
});
test("drops a session the homeserver no longer knows", async () => {
storeSession();
vi.mocked(initClient).mockRejectedValue(
new MatrixError({ errcode: "M_UNKNOWN_TOKEN", error: "Unknown token" }),
);
const clientSession = new StandaloneClientSession(testScope());
await flushPromises();
expect(storedSession()).toBeNull();
expect(clientSession.state$.value).toEqual({ state: "signedOut" });
});
test("drops the session and reports any other error", async () => {
storeSession();
const error = new Error("offline");
vi.mocked(initClient).mockRejectedValue(error);
const clientSession = new StandaloneClientSession(testScope());
await flushPromises();
expect(storedSession()).toBeNull();
// An error page rather than a spinner that never ends
expect(clientSession.state$.value).toEqual({ state: "error", error });
});
test("logs in with a password, ending the session it had", async () => {
storeSession();
const restored = mockClient();
vi.mocked(initClient).mockResolvedValueOnce(restored);
const clientSession = new StandaloneClientSession(testScope());
await flushPromises();
const client = mockClient();
vi.mocked(loginWithPassword).mockResolvedValue(credentials);
vi.mocked(initClient).mockResolvedValueOnce(client);
await expect(
clientSession.login("https://other.example.org", "bob", "hunter2"),
).resolves.toBe(client);
expect(loginWithPassword).toHaveBeenCalledWith(
"https://other.example.org",
"bob",
"hunter2",
);
// The old session is logged out before the new client starts, so that the
// crypto stores are not shared between the two
expect(restored.logout).toHaveBeenCalledWith(true);
expect(initClient).toHaveBeenLastCalledWith(
{
baseUrl: "https://other.example.org",
accessToken: "fresh",
userId: "@bob:example.org",
deviceId: "BBBB",
},
false,
);
expect(clientSession.state$.value).toEqual({
state: "signedIn",
client,
passwordlessUser: false,
});
expect(storedSession()).toEqual({ ...credentials, passwordlessUser: false });
});
test("registers a passwordless account, signing in only when asked", async () => {
const clientSession = new StandaloneClientSession(testScope());
await flushPromises();
const client = mockClient();
vi.mocked(registerWithPassword).mockResolvedValue(credentials);
vi.mocked(initClient).mockResolvedValue(client);
const registration = await clientSession.register(
"bob",
"temporary",
"Bob",
"captcha",
true,
);
expect(registerWithPassword).toHaveBeenCalledWith(
"https://hs.example.org",
"bob",
"temporary",
"captcha",
);
expect(registration.client).toBe(client);
expect(client.setDisplayName).toHaveBeenCalledWith("Bob");
expect(user.setDisplayName).toHaveBeenCalledWith("Bob");
// Registered, but not yet signed in: the caller may still be setting up
expect(clientSession.state$.value).toEqual({ state: "signedOut" });
expect(storedSession()).toBeNull();
registration.setSignedIn();
expect(clientSession.state$.value).toEqual({
state: "signedIn",
client,
passwordlessUser: true,
});
expect(storedSession()).toEqual({ ...credentials, passwordlessUser: true });
});
test("registers an account with a password of its own", async () => {
const clientSession = new StandaloneClientSession(testScope());
await flushPromises();
vi.mocked(registerWithPassword).mockResolvedValue(credentials);
vi.mocked(initClient).mockResolvedValue(mockClient());
const { setSignedIn } = await clientSession.register(
"bob",
"hunter2",
"Bob",
"captcha",
false,
);
setSignedIn();
expect(storedSession()).toEqual({ ...credentials, passwordlessUser: false });
});
test("logs out, clearing the client's stores and the stored session", async () => {
storeSession();
const client = mockClient();
vi.mocked(initClient).mockResolvedValue(client);
const clientSession = new StandaloneClientSession(testScope());
await flushPromises();
const analyticsLogout = vi.spyOn(PosthogAnalytics.instance, "logout");
await clientSession.logout();
expect(client.logout).toHaveBeenCalledWith(true);
expect(client.clearStores).toHaveBeenCalled();
expect(storedSession()).toBeNull();
expect(clientSession.state$.value).toEqual({ state: "signedOut" });
// Analytics forget the user along with the session
expect(analyticsLogout).toHaveBeenCalled();
});
test("claims exclusive use of storage from other instances of the app", () => {
// The channel is created with the session, so spy on the prototype rather
// than trying to replace the global.
const postMessage = vi.spyOn(BroadcastChannel.prototype, "postMessage");
new StandaloneClientSession(testScope());
expect(postMessage).toHaveBeenCalled();
});
test("stops when another instance of the app claims storage", async () => {
storeSession();
const client = mockClient();
vi.mocked(initClient).mockResolvedValue(client);
const clientSession = new StandaloneClientSession(testScope());
await flushPromises();
new BroadcastChannel("load").postMessage({});
await vi.waitFor(() =>
expect(clientSession.state$.value).toMatchObject({ state: "error" }),
);
expect(client.stopClient).toHaveBeenCalled();
const { value } = clientSession.state$;
expect(value.state === "error" && value.error).toBeInstanceOf(
OpenElsewhereError,
);
});
+222
View File
@@ -0,0 +1,222 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { type MatrixClient, MatrixError } from "matrix-js-sdk";
import { logger } from "matrix-js-sdk/lib/logger";
import { BehaviorSubject } from "rxjs";
import {
PosthogAnalytics,
RegistrationType,
} from "../analytics/PosthogAnalytics";
import { Config } from "../config/Config";
import { OpenElsewhereError } from "../RichError";
import {
loginWithPassword,
registerWithPassword,
} from "../auth/interactiveAuth";
import { initClient } from "../utils/initClient";
import { fallbackICEServerAllowed } from "../utils/matrix";
import { type Behavior } from "./Behavior";
import {
type ClientManager,
type ClientSession,
type ClientSessionState,
type Registration,
type StoredSession,
} from "./ClientSession";
import { type ObservableScope } from "./ObservableScope";
const SESSION_KEY = "matrix-auth-store";
/**
* A client session for the SPA: restored from storage on construction, and
* signed in to, out of, or re-authenticated by the login, registration and
* account flows.
*
* This class is responsible for restoring from store and logout and change Pwd.
*
* To make sure we do not load/bundle the client store worker it is important
* that this is a separate file: only this module reaches `utils/initClient`,
* and therefore the client store worker, so it may only be imported by the
* standalone app's entry point.
*/
export class StandaloneClientSession implements ClientSession, ClientManager {
private readonly state = new BehaviorSubject<ClientSessionState>({
state: "loading",
});
public readonly state$: Behavior<ClientSessionState> = this.scope.behavior(
this.state,
);
// To protect against multiple sessions writing to the same storage
// simultaneously, we send a broadcast message that shuts down all other
// running instances of the app.
private readonly loadChannel =
"BroadcastChannel" in window ? new BroadcastChannel("load") : null;
public constructor(private readonly scope: ObservableScope) {
this.loadChannel?.postMessage({});
const onOpenedElsewhere = (): void => {
this.client?.stopClient();
this.state.next({ state: "error", error: new OpenElsewhereError() });
};
this.loadChannel?.addEventListener("message", onOpenedElsewhere);
scope.onEnd(() =>
this.loadChannel?.removeEventListener("message", onOpenedElsewhere),
);
this.restore().catch((e) => {
logger.error("Failed to restore the session", e);
this.state.next({ state: "error", error: e });
});
}
private get client(): MatrixClient | undefined {
const { value } = this.state;
return value.state === "signedIn" ? value.client : undefined;
}
private async restore(): Promise<void> {
// The homeserver to restore against is in the config, which is loaded
// concurrently with this
await Config.init();
try {
const session = loadSession();
if (session === undefined) {
logger.log("No session stored; continuing without a client");
this.state.next({ state: "signedOut" });
return;
}
logger.log("Using a standalone client");
const client = await initClient(
{
baseUrl: Config.defaultHomeserverUrl()!,
accessToken: session.access_token,
userId: session.user_id,
deviceId: session.device_id,
fallbackICEServerAllowed,
livekitServiceURL: Config.get().livekit?.livekit_service_url,
},
true,
);
this.state.next({
state: "signedIn",
client,
passwordlessUser: session.passwordlessUser,
});
} catch (e) {
// Whatever went wrong, the stored session is not to be tried again
clearSession();
if (e instanceof MatrixError && e.errcode === "M_UNKNOWN_TOKEN") {
logger.log(
"The session from local store is invalid; continuing without a client",
);
this.state.next({ state: "signedOut" });
return;
}
throw e;
}
}
public readonly login = async (
homeserver: string,
username: string,
password: string,
): Promise<MatrixClient> => {
const session: StoredSession = {
...(await loginWithPassword(homeserver, username, password)),
passwordlessUser: false,
};
const client = await this.createClient(homeserver, session);
this.signIn(client, session);
return client;
};
public readonly register = async (
username: string,
password: string,
displayName: string,
recaptchaResponse: string,
passwordlessUser: boolean,
): Promise<Registration> => {
const homeserver = Config.defaultHomeserverUrl()!;
const session: StoredSession = {
...(await registerWithPassword(
homeserver,
username,
password,
recaptchaResponse,
)),
passwordlessUser,
};
const client = await this.createClient(homeserver, session);
await client.setDisplayName(displayName);
const user = client.getUser(client.getUserId()!)!;
user.setRawDisplayName(displayName);
user.setDisplayName(displayName);
return { client, setSignedIn: (): void => this.signIn(client, session) };
};
/**
* Starts a client for a new session, ending the current one first.
*/
private async createClient(
homeserver: string,
session: StoredSession,
): Promise<MatrixClient> {
// To not confuse the rust crypto sessions we need to log out the old
// client before initializing the new one
await this.client?.logout(true);
return initClient(
{
baseUrl: homeserver,
accessToken: session.access_token,
userId: session.user_id,
deviceId: session.device_id,
},
false,
);
}
private signIn(client: MatrixClient, session: StoredSession): void {
saveSession(session);
this.state.next({
state: "signedIn",
client,
passwordlessUser: session.passwordlessUser,
});
}
public readonly logout = async (): Promise<void> => {
const client = this.client;
if (!client) return;
await client.logout(true);
await client.clearStores();
clearSession();
this.state.next({ state: "signedOut" });
PosthogAnalytics.instance.logout();
PosthogAnalytics.instance.setRegistrationType(RegistrationType.Guest);
};
}
function loadSession(): StoredSession | undefined {
const data = localStorage.getItem(SESSION_KEY);
return data ? JSON.parse(data) : undefined;
}
function saveSession(session: StoredSession): void {
localStorage.setItem(SESSION_KEY, JSON.stringify(session));
}
function clearSession(): void {
localStorage.removeItem(SESSION_KEY);
}
+1 -1
View File
@@ -57,7 +57,7 @@ export function createAppBackgroundEffects(
return createBackgroundEffects(scope, {
supported: supportsBackgroundProcessors(),
effect$: backgroundEffectSetting.value$,
clearEffect: () => backgroundEffectSetting.setValue("none"),
setEffect: backgroundEffectSetting.setValue,
added$: addedBackgrounds.added$,
canSegment,
pipeline: new BackgroundProcessorWrapper(transformer, "background-effect"),
+2 -7
View File
@@ -17,13 +17,8 @@ import {
import { type ISyncStateData, type SyncState } from "matrix-js-sdk/lib/sync";
import { logger } from "matrix-js-sdk/lib/logger";
// This import is why `initClient` has a module of its own:
// - The bundler emits the worker file (11 MB: the Matrix SDK and its crypto
// wasm) the moment it loads this import — whether or not anything ever calls
// `new IndexedDBWorker()`. Tree shaking drops the call, not the file.
// - So it may only sit in a module the component build never loads. It used
// to be in `./matrix`, which the component reaches for the room URL helpers,
// and the worker shipped in the package, unused and unusable by any host.
// This import pulls in many MBs of SDK code and crypto WASM which should only
// be included in full SPA builds, which is why `initClient` gets its own module.
import IndexedDBWorker from "../IndexedDBWorker?worker";
import { getUrlParams } from "../UrlParams";
import { Config } from "../config/Config";
+2 -5
View File
@@ -5,6 +5,8 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
// *Do not* import any client stores in this module, to keep the component
// build lean.
import { ClientEvent, Preset, Visibility } from "matrix-js-sdk";
import { logger } from "matrix-js-sdk/lib/logger";
import { secureRandomBase64Url } from "matrix-js-sdk/lib/randomstring";
@@ -18,11 +20,6 @@ import {
saveKeyForRoom,
} from "../e2ee/sharedKeyManagement";
// Shared with the component, which reaches this module for the room URLs. So
// nothing in here may import the client store worker: the bundler emits the
// worker file on loading the import, used or not. The one function that needs
// it, `initClient`, lives in `./initClient` for that reason.
export const fallbackICEServerAllowed =
import.meta.env.VITE_FALLBACK_STUN_ALLOWED === "true";
-83
View File
@@ -1,83 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { type MatrixClient, MatrixError } from "matrix-js-sdk";
import { initClient } from "./initClient";
import { initSPA } from "./spa";
import { Config } from "../config/Config";
import { type Session } from "../ClientContext";
vi.mock("./initClient", () => ({ initClient: vi.fn() }));
const session: Session = {
user_id: "@alice:example.org",
device_id: "AAAA",
access_token: "secret",
passwordlessUser: true,
};
const client = {} as MatrixClient;
describe("initSPA", () => {
const clearSession = vi.fn();
beforeEach(() => {
vi.spyOn(Config, "defaultHomeserverUrl").mockReturnValue(
"https://hs.example.org",
);
});
afterEach(() => {
vi.restoreAllMocks();
vi.clearAllMocks();
});
it("continues without a client when no session is stored", async () => {
await expect(initSPA(() => undefined, clearSession)).resolves.toBeNull();
expect(initClient).not.toHaveBeenCalled();
expect(clearSession).not.toHaveBeenCalled();
});
it("restores the stored session into a client", async () => {
vi.mocked(initClient).mockResolvedValue(client);
await expect(initSPA(() => session, clearSession)).resolves.toEqual({
client,
passwordlessUser: true,
});
expect(initClient).toHaveBeenCalledWith(
expect.objectContaining({
baseUrl: "https://hs.example.org",
accessToken: "secret",
userId: "@alice:example.org",
deviceId: "AAAA",
}),
// Restoring: the crypto store is the session's, not to be wiped
true,
);
});
it("drops a session the homeserver no longer knows", async () => {
vi.mocked(initClient).mockRejectedValue(
new MatrixError({ errcode: "M_UNKNOWN_TOKEN", error: "Unknown token" }),
);
await expect(initSPA(() => session, clearSession)).resolves.toBeNull();
expect(clearSession).toHaveBeenCalled();
});
it("drops the session and fails on any other error", async () => {
vi.mocked(initClient).mockRejectedValue(new Error("offline"));
await expect(initSPA(() => session, clearSession)).rejects.toThrow(
"offline",
);
expect(clearSession).toHaveBeenCalled();
});
});
-63
View File
@@ -1,63 +0,0 @@
/*
Copyright 2024 New Vector Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { type ICreateClientOpts, MatrixError } from "matrix-js-sdk";
import { logger } from "matrix-js-sdk/lib/logger";
import { Config } from "../config/Config";
import { fallbackICEServerAllowed } from "./matrix";
import { initClient } from "./initClient";
import type { InitResult, Session } from "../ClientContext";
export async function initSPA(
loadSession: () => Session | undefined,
clearSession: () => void,
): Promise<InitResult | null> {
// We're running as a standalone application
try {
const session = loadSession();
if (!session) {
logger.log("No session stored; continuing without a client");
return null;
}
logger.log("Using a standalone client");
/* eslint-disable camelcase */
const { user_id, device_id, access_token, passwordlessUser } = session;
const initClientParams: ICreateClientOpts = {
baseUrl: Config.defaultHomeserverUrl()!,
accessToken: access_token,
userId: user_id,
deviceId: device_id,
fallbackICEServerAllowed,
livekitServiceURL: Config.get().livekit?.livekit_service_url,
};
try {
const client = await initClient(initClientParams, true);
return {
client,
passwordlessUser,
};
} catch (err) {
if (err instanceof MatrixError && err.errcode === "M_UNKNOWN_TOKEN") {
// We can't use this session anymore, so let's log it out
logger.log(
"The session from local store is invalid; continuing without a client",
);
clearSession();
// returning null = "no client` pls register" (undefined = "loading" which is the current value when reaching this line)
return null;
}
throw err;
}
} catch (err) {
clearSession();
throw err;
}
}

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