Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。
fix(route): fix audited routing and lifecycle invariants (#313)
AAA76531641924e
diff --git a/.github/workflows/native-sender-package.yml b/.github/workflows/native-sender-package.ymldeleted file mode 100644index 0fed7a31..00000000--- a/.github/workflows/native-sender-package.yml+++ /dev/null@@ -1,38 +0,0 @@-name: Native sender release package (manual)--on:- workflow_dispatch:--permissions:- contents: read--jobs:- package:- name: Package native release candidate- runs-on: windows-latest- steps:- - name: Check out repository- uses: actions/checkout@v6- with:- fetch-depth: 0- - name: Set up Go- uses: actions/setup-go@v6- with:- go-version: 1.26.6- cache-dependency-path: native/sender/go.sum- - name: Build and verify package- shell: pwsh- run: |- ./scripts/package-native-sender.ps1 `- -OutputDirectory (Join-Path $env:RUNNER_TEMP 'screener-native-package') `- -Revision '${{ github.sha }}'- - name: Upload evaluation artifact- uses: actions/upload-artifact@v7- with:- name: screener-native-windows-x64-${{ github.sha }}- path: |- ${{ runner.temp }}/screener-native-package/*.zip- ${{ runner.temp }}/screener-native-package/*.zip.sha256- if-no-files-found: error- retention-days: 7- compression-level: 0diff --git a/docs/adr/0005-automatic-hybrid-media-routing.md b/docs/adr/0005-automatic-hybrid-media-routing.mdindex 03425103..07734f51 100644--- a/docs/adr/0005-automatic-hybrid-media-routing.md+++ b/docs/adr/0005-automatic-hybrid-media-routing.md@@ -1,6 +1,6 @@# ADR-0005: Automatic Hybrid Media Routing-- Status: accepted and deployed; native-edge convergence defaults on per share+- Status: Accepted- Date: 2026-08-20- Last updated: 2026-08-28@@ -62,11 +62,13 @@ itself reparented while its descendants remain attached.### Deterministic Candidates-Each child operation owns one candidate list and cursor, one current candidate-and reservations, one route-demand owner, one fact version, and one total-deadline. Candidate creation first rejects stale sessions, unreachable sources,-cycles, insufficient steady/overlap capacity, tuples already consumed by that-operation, and unavailable SFU resources.+Each child operation owns one immutable purpose, one candidate list and cursor,+one current candidate and reservations, one route-demand owner, one fact version,+and one total deadline. Availability work preempts a background operation by+aborting it and creating the required operation; the old operation is never+relabelled. Candidate creation first rejects stale sessions, unreachable+sources, cycles, insufficient steady/overlap capacity, tuples already consumed+by that operation, and unavailable SFU resources.Eligible Peer parents are ordered by:@@ -87,8 +89,12 @@ root. A fresh healthy candidate sender proof is required before make-before-breacommit. Success moves one branch toward even fanout; failure consumes that one-shot intent. No timer,continuous rebalance or general load score is introduced.-A failed exact tuple is consumed only for its current operation. A later external-fact may make it eligible again; there is no persistent parent blacklist.+A failed tuple is consumed for its exact candidate opportunity: tuple, relevant+endpoint sessions or publication generation, and endpoint-transition strength.+Only a new session or generation, or a strictly better transition, makes that+opportunity new. Candidate removal, worsening, reordering, and unrelated facts+do not retry it. An external SFU-resource wake may reopen SFU opportunities but+never Peer opportunities. There is no persistent parent blacklist.### Prepare, Commit, And Rollback@@ -156,6 +162,12 @@ space times the per-room Viewer limit; neither has an independent tuning key.Exact publication and subscription handles remain charged while reserved,committed, or draining. Reactivating the same handle does not double-charge it.+Grant revocation, Viewer leave, and SFU-to-P2P replacement remove the exact+LiveKit Viewer participant and confirm its absence. This control-plane drain is+not token revocation or ledger release: an already issued self-hosted LiveKit+token remains usable until expiry, so that subscription's egress stays charged+until the whole publication generation is deleted and confirmed absent.+The application explicitly creates a managed LiveKit room before issuing mediatokens. Replacement, abort, timeout, confirmed media-participant loss, sharerollover, stop, and room deletion transfer the resources they own into the same typed drain path.@@ -225,9 +237,13 @@ candidate receive windows. A P2P candidate commits only after first decodedframe and three consecutive windows with no freeze/pause, no lower pixel area orrounded FPS, and a strict improvement in at least one of those dimensions.Bitrate does not rank P2P candidates because codec and content phase make it-non-monotonic. Old-edge recovery, missing/incomparable evidence, authority-change, or deadline aborts the experiment. A successful commit clears and-rebaselines the affected subtree.+non-monotonic. Three consecutive comparable non-improving windows reject the+candidate and advance the existing cursor without resetting the deadline. A+persistently limited exact candidate sender is also vetoed even when receiver+comparison approves it. Unknown or incomparable evidence waits only within the+existing deadline; none of these outcomes creates a score. Old-edge recovery,+authority change, or deadline aborts the experiment. A successful commit clears+and rebaselines the affected subtree.The same rule supplies both active parent change and relay abdication. A badrelay ingress reparents that relay while retaining its subtree. A bad exactdiff --git a/docs/adr/0007-path-isolated-representation-quality.md b/docs/adr/0007-path-isolated-representation-quality.mdindex 7eaeac82..2d7be934 100644--- a/docs/adr/0007-path-isolated-representation-quality.md+++ b/docs/adr/0007-path-isolated-representation-quality.md@@ -1,8 +1,8 @@# ADR-0007: Framework-Owned Media Quality Adaptation-- Status: Accepted; adaptive gate and local selector deployed+- Status: Accepted- Date: 2026-08-19-- Last reviewed: 2026-08-26+- Last reviewed: 2026-08-28## Context@@ -61,11 +61,11 @@ it does not need a second bitrate, resolution, FPS, or layer-control system.remains disabled because a Viewer may relay its received track to peerchildren; local DOM size or visibility cannot represent that downstreamdemand.-8. Quality measurements are diagnostic. Bitrate, resolution, FPS, RTT, jitter,- loss, freeze counters, codec, and limitation reason do not trigger parent- selection, relay abdication, periodic rebalancing, or route changes. Only- hard connection failure, the existing non-paused decoded-frame stall, parent- departure, or capacity invalidation can make an active edge unusable.+8. WebRTC and LiveKit remain the media-adaptation owners. ADR-0005's deployed+ native-edge convergence may consume only a persistent categorical limitation+ from the exact sender and comparative delivery proof from the same Viewer over+ a real prepared candidate. It does not set bitrate, resolution, FPS, or layer,+ infer a physical bottleneck, or combine quality measurements into a score.9. A healthy decoded route remains sticky. Manual media reconnect rebuilds thecurrent exact P2P parent or current SFU subscription; it does not search fora better parent. If current-route recovery genuinely exhausts, ADR-0005's@@ -109,8 +109,9 @@ LiveKit HIGH+LOW publication without backup codec.- A Host may need to lower its explicit share profile when encoder or uplinkcapacity is insufficient; Screener does not silently remove constrainedViewer support.-- ADR-0005's native-edge local convergence remains unimplemented. Weighted or- global topology optimization still requires another route-model decision.+- ADR-0005's native-edge local convergence is deployed and performs bounded+ real-candidate comparisons without owning media adaptation. Weighted or global+ topology optimization still requires another route-model decision.## Stop Linesdiff --git a/docs/deployment.md b/docs/deployment.mdindex e85e7adc..685fc519 100644--- a/docs/deployment.md+++ b/docs/deployment.md@@ -33,12 +33,11 @@ Start from a clean exact revision with Node.js 24 and npm 11:```shnpm cinpm run check-npm run buildnode scripts/package-app-release.mjs <output-directory-outside-repository>```-The packager refuses a dirty tree, records the full revision, emits a runtime-archive plus path/size/SHA-256 manifest and release descriptor, and+The packager refuses a dirty tree, builds from that exact revision, records the+full revision, emits a runtime archive plus path/size/SHA-256 manifest and release descriptor, andextracts its own artifact to verify it. Upload the archive, manifest, anddescriptor together to `/opt/screener/uploads`.diff --git a/docs/product/media-quality.md b/docs/product/media-quality.mdindex 7a42f3f8..c2068c5e 100644--- a/docs/product/media-quality.md+++ b/docs/product/media-quality.md@@ -94,10 +94,10 @@ are the observable result. Connection detail may show actual path, codec,resolution, FPS, bitrate, loss, jitter, RTT, and encode/decode behavior when theBrowser exposes them; missing or reset counters remain unknown.-The current quality shadow accepts only current foreground presentation evidence-and never changes routes or media settings. ADR-0005 accepts native-edge local-topology convergence that is not implemented or deployed; weighted/global-optimization remains parked in [TODO](../todo.md).+WebRTC and LiveKit remain the media-adaptation owners. ADR-0005's deployed+native-edge convergence consumes only a persistent categorical sender limitation+and proof from the same Viewer over a real prepared candidate; it does not turn+quality metrics into media settings or a weighted/global route score.Web pages cannot guarantee Host background capture, mobile background playback,or relay execution after Browser/OS suspension. Those remain physical lifecyclediff --git a/docs/product/rooms-access.md b/docs/product/rooms-access.mdindex 76d052f0..527c2174 100644--- a/docs/product/rooms-access.md+++ b/docs/product/rooms-access.md@@ -57,7 +57,10 @@ remain separate.Rotating or revoking the Viewer grant is a strong authorization change. The newgeneration is committed before old Viewers, signaling grace, routes, and sender-edges are closed. Changing code-entry policy or password affects later+edges are closed. An affected SFU Viewer is removed by its exact LiveKit+identity and confirmed absent. This does not revoke an already issued+self-hosted LiveKit token: its subscription stays charged until that publication+generation drains. Changing code-entry policy or password affects latercode-only attempts and does not silently revoke invitations.## Persistence Modesdiff --git a/docs/product/routing-transport.md b/docs/product/routing-transport.mdindex 8460ba69..5eed20f5 100644--- a/docs/product/routing-transport.md+++ b/docs/product/routing-transport.md@@ -59,7 +59,8 @@ route stays active until the exact candidate child decodes a first new frame;ICE connected alone is not commit proof. Availability repair may instead use theexplicit bounded-gap plan defined by ADR-0005 when no overlap slot exists.Failure or stale authority releases the candidate and preserves unaffected-branches.+branches. An operation's purpose is immutable; availability work preempts a+background operation by replacing it rather than changing its meaning.Direct peers receive the first bounded opportunity, with SFU used foravailability when direct paths cannot provide media. Remaining direct paths may@@ -97,7 +98,10 @@ configures no TURN, ICE/TCP, media TCP, or TLS-relayed media path. HTTPS/WSS isseparate control transport and remains TLS/TCP.SFU resources remain bounded throughout reservation, use, and cleanup; stale-credentials cannot recreate off-ledger media. ADR-0005 owns that lifecycle.+credentials cannot recreate off-ledger media. Grant revocation, Viewer leave,+and SFU-to-P2P replacement remove the exact LiveKit Viewer and confirm absence,+but the subscription remains charged until its publication generation drains.+ADR-0005 owns that lifecycle.## Quality And Privacy Boundaries@@ -107,8 +111,9 @@ per-share convergence gate is enabled, Screener uses an exact persistent nativesender limitation only to trigger one measured experiment through the existingserial operation. The same Viewer must then prove a P2P candidate strictlyimproves delivered pixel area or rounded FPS without regressing either dimension-or producing a freeze/pause across three fresh paired windows. Ordinary quality-moves remain Peer-to-Peer. SFU may+or producing a freeze/pause across three fresh paired windows. A persistently+limited exact candidate sender cannot commit. Ordinary quality moves remain+Peer-to-Peer. SFU mayjoin quality work only as Host fanout relief when every current Host-origin Peeredge, with at least two such edges, is persistently degraded; one Viewer movesbefore the controller observes the new topology again. During that overlap, thediff --git a/docs/status.md b/docs/status.mdindex 77edcb67..4befbc4a 100644--- a/docs/status.md+++ b/docs/status.md@@ -74,6 +74,19 @@ This is the current execution index. Git history owns completed timelines;pagehide no longer triggers LiveKit's automatic disconnect. Native Viewercontrols still own playback, and manual reconnect stays on the current route.+## Source/Production Delta++- Current source replaces aggregate route-fact retries with exact session,+ publication and transition opportunities; advances proved non-improving+ candidates; binds stall and recovery reports to physical media identities;+ and removes exact retired LiveKit Viewers while retaining generation-owned+ resource charges.+- Current source also keeps lease authority in `RoomStore`, batches stable-room+ expiry persistence, serializes share start with room replacement, binds Web+ release artifacts to their source revision, and retains Native sender code as+ research rather than a distribution surface. These corrections are not+ deployed; production remains exact release `24cb780` above.+## Current MilestoneMeasured route convergence, generation-owned Viewer presentation and@@ -97,5 +110,6 @@ subscribers back to P2P, and retired the Host SFU publication.## Current Hold-No source or deployment P0/P1 is open. Sanitized route logging remains enabled-for the pre-release canary.+No source P0/P1 is known. Production does not contain the current source+corrections until an explicitly authorized deployment. Sanitized route logging+remains enabled for the pre-release canary.diff --git a/docs/todo.md b/docs/todo.mdindex 8799f94b..56658040 100644--- a/docs/todo.md+++ b/docs/todo.md@@ -1,23 +1,32 @@# Current TODO Ledger-Last reviewed: 2026-08-27+Last reviewed: 2026-08-28Only **Now** is executable. Observations, old branches, experiments, and parkedtopics are not implementation authority.## Now-No implementation task is currently authorized. Continue bounded production-observation of the deployed route canary; new code requires new evidence.+No implementation task is currently authorized. The audit root-cause+corrections are integrated and verified in current source but remain undeployed;+deployment requires explicit authority.## Parked Repository Work1. **Bounded mechanism simplification.** Remove only the proved zero-consumer orduplicate owners: coarse `mediaAssignment` wire residue, legacy SFU room-nameacceptance, orphan `scripts/browser-codec-preflight.ts`, and the access gate's- test-title scan. Keep the production+ test-title scan. The same bounded pass may remove the unused SFU publisher+ snapshot callback, test-only production helpers, unused SFU token allowlist+ input, debug ordinals after participant retirement, and share-unowned sender+ evidence caches. Keep the production`src/client/webrtc/video-codec-preflight.ts`, live internal media-assignmenthelpers, and destructive-path safety gates.+2. **Tooling ownership correction.** Give every CDP call a deadline, move shared+ Browser harness code out of the Native owner, type-check the access/privacy+ gate, run repository hygiene under the pinned Node version, ignore untracked+ drafts in canonical-document gates, and scope rejected Native checks to+ Native changes or explicit research runs.## Parked Product Work@@ -25,27 +34,42 @@ observation of the deployed route canary; new code requires new evidence.parent-wide prediction, startup-limited inference, and alternative SFUpolicies remain unaccepted. Reopen only from exact path evidence; do not adda score, all-pairs probe, periodic rebalancer, or ordinary SFU preference.-2. **Mobile Viewer lifecycle.** Run Android Chrome and iOS Safari matrices for+2. **Startup codec budget.** Reconcile the bounded Auto codec probe with the+ first-frame target from measured Browser evidence; do not silently weaken+ Auto or move an unproved result into the availability path.+3. **Control-plane resource fairness.** Calibrate one deployment-wide LiveKit+ control queue and simple HTTP/WebSocket ingress budgets before implementation;+ prove a self-hosted stale-token revocation boundary before independently+ releasing subscription egress; do not introduce accounts, polling, risk+ scoring, or an independent policy framework.+4. **Client ownership and diagnostic rendering.** Batch Host-only diagnostic+ snapshots when a 20-Viewer measurement proves rendering cost, and extract+ media-session owners from the Host/Viewer pages only alongside reachable+ behavior work. File length alone does not authorize a page rewrite.+5. **C=3 structural intent retention.** Revisit multiple simultaneous one-shot+ Host-root convergence intents only with an exact C=3 reproduction; do not add+ periodic balancing or another topology queue for the default path.+6. **Mobile Viewer lifecycle.** Run Android Chrome and iOS Safari matrices forautoplay, background audio, foreground recovery, lock/page reclamation,rotation, network migration, and relay survival.-3. **Representative network acceptance.** Complete public-network direct,+7. **Representative network acceptance.** Complete public-network direct,Browser relay, SFU, recovery, Pause/Resume, screen-audio, real-game A/V,two-room SFU, 20-Viewer endurance, and all-UDP-blocked bounded failure.-4. **Whole-product UI and bilingual decision.** Review copy, responsive+8. **Whole-product UI and bilingual decision.** Review copy, responsivehierarchy, visual consistency, restrained motion, rendering cost, terminalnavigation, and Chinese/English scope once media behavior stabilizes.-5. **Client-input security review.** Audit HTTP/WebSocket schema, auth,+9. **Client-input security review.** Audit HTTP/WebSocket schema, auth,authorization, rate/body/resource bounds, errors, logs, and secrets withoutadding a parallel security framework.-6. **Public-server package.** Package the exact Web/signaling, STUN/SFU, proxy,+10. **Public-server package.** Package the exact Web/signaling, STUN/SFU, proxy,secrets, health, and recovery contract for a user-owned server.-7. **Fully local package.** Package Host capture, application server, and local+11. **Fully local package.** Package Host capture, application server, and localstate for Windows/macOS/Linux with honest TLS, gateway, NAT, and firewalllimits.-8. **Native Host and shared encode.** Revisit Windows first only after capture,+12. **Native Host and shared encode.** Revisit Windows first only after capture,hardware encode, audio, RTP feedback, resources, packaging, licensing, andBrowser interoperability are proved.-9. **Platform output.** Revisit AirPlay/Cast only when a target Browser and+13. **Platform output.** Revisit AirPlay/Cast only when a target Browser andphysical receiver prove the live `MediaStream` contract.## Decision Neededdiff --git a/native/sender/README.md b/native/sender/README.mdindex ef59d8d8..33bd3b46 100644--- a/native/sender/README.md+++ b/native/sender/README.md@@ -1,43 +1,16 @@-# Screener Native Sender for Windows x64+# Screener Native Sender Research-This evaluation package contains the current Native sender and its Windows 11-window-capture helper. It has no installer, updater, code signature, or bundled-server.+This directory retains Native sender and shared-encode evidence. It is not a+current product or distribution surface and its private wire is not compatible+with the current Browser/server contract. Do not package or distribute it.-## Run+[ADR-0006](../../docs/adr/0006-fixed-high-native-sender-canary.md) owns the stop+line; [Native sender research](../../docs/research/native-sender.md) owns the+retained evidence and the gates required before this work can resume.-1. Keep `screener-sender.exe` and `screener-window-capture.exe` in the same- directory.-2. Run `screener-sender.exe`. It opens a loopback-only UI in the default- browser; current Chrome or Edge is required.-3. Enter the Screener server and site access password. Browser VP8 remains the- default; browser H.264 and Native window H.264 are explicit opt-ins.-4. For a browser video source, choose the browser screen/window and optionally- select the same window target for process-tree audio. Native window H.264- requires one target and captures its video and process-tree audio together.-5. Close the console window to stop the sender.+The retained Go checks remain available from `native/sender`:-Native capture requires Windows 11 build 22000 or newer. It binds the selected-window to its process identity, never falls back to the system mix, and never-falls back from the hardware-only Media Foundation H.264 encoder to software.-Browser H.264 still requests browser hardware preference without proving which-physical encoder Chrome or Edge selected. Viewers use the normal Web client.--Verify the downloaded ZIP against its adjacent `.sha256` file, then verify the-files inside it with `SHA256SUMS.txt`. The package is unsigned, so Windows may-show an unknown-publisher warning.--The project distribution license is not yet selected. This short-lived Actions-artifact is for evaluation and does not grant redistribution rights. Exact-third-party license texts for the linked Go runtime and modules are under-`licenses/`.--## Build--From a clean Git checkout on Windows with Go 1.26.6 and Visual Studio C++ Build-Tools installed:--```powershell-$output = Join-Path ([IO.Path]::GetTempPath()) "screener-native-package-$([Guid]::NewGuid())"-./scripts/package-native-sender.ps1 -OutputDirectory $output+```sh+go test ./...+go vet ./...```diff --git a/scripts/package-app-release.mjs b/scripts/package-app-release.mjsindex a49faf29..1f5d3e2a 100644--- a/scripts/package-app-release.mjs+++ b/scripts/package-app-release.mjs@@ -36,6 +36,30 @@ function run(command, args, cwd) {return result.stdout.trim();}+function buildRuntime(cwd) {+ if (process.platform === "win32") {+ run(+ process.env.ComSpec || "cmd.exe",+ ["/d", "/s", "/c", "npm run build"],+ cwd,+ );+ return;+ }+ run("npm", ["run", "build"], cwd);+}++function assertCleanRevision(repositoryRoot, expectedRevision) {+ const revision = run("git", ["rev-parse", "HEAD"], repositoryRoot).toLowerCase();+ if (!/^[0-9a-f]{40}$/.test(revision)) fail("Git did not return a full revision");+ if (expectedRevision && revision !== expectedRevision) {+ fail("Repository revision changed during release packaging");+ }+ if (run("git", ["status", "--porcelain"], repositoryRoot) !== "") {+ fail("Application releases require a clean Git checkout");+ }+ return revision;+}+function sha256(path) {return createHash("sha256").update(readFileSync(path)).digest("hex");}@@ -155,13 +179,14 @@ if (relativeOutput === "" || (!relativeOutput.startsWith("..") && !isAbsolute(re}if (existsSync(outputRoot)) fail("Output directory must not already exist");-const revision = run("git", ["rev-parse", "HEAD"], repositoryRoot).toLowerCase();-if (!/^[0-9a-f]{40}$/.test(revision)) fail("Git did not return a full revision");-if (run("git", ["status", "--porcelain"], repositoryRoot) !== "") {- fail("Application releases require a clean Git checkout");-}+const revision = assertCleanRevision(repositoryRoot);-for (const required of ["package.json", "package-lock.json", "dist/client", "dist/server"]) {+for (const required of ["package.json", "package-lock.json"]) {+ if (!existsSync(join(repositoryRoot, required))) fail(`Missing release input: ${required}`);+}+buildRuntime(repositoryRoot);+assertCleanRevision(repositoryRoot, revision);+for (const required of ["dist/client", "dist/server"]) {if (!existsSync(join(repositoryRoot, required))) fail(`Missing built runtime path: ${required}`);}@@ -179,6 +204,7 @@ try {]) {copyRuntimeFile(repositoryRoot, runtimeRoot, source);}+ assertCleanRevision(repositoryRoot, revision);writeFileSync(join(runtimeRoot, "REVISION"), `${revision}\n`, "ascii");const records = recordsFor(runtimeRoot);diff --git a/scripts/package-native-sender.ps1 b/scripts/package-native-sender.ps1deleted file mode 100644index 551d5b21..00000000--- a/scripts/package-native-sender.ps1+++ /dev/null@@ -1,124 +0,0 @@-[CmdletBinding()]-param(- [Parameter(Mandatory = $true)]- [string]$OutputDirectory,-- [string]$Revision-)--Set-StrictMode -Version Latest-$ErrorActionPreference = 'Stop'--$scriptDirectory = Split-Path -Parent $MyInvocation.MyCommand.Path-$repositoryRoot = [IO.Path]::GetFullPath((Join-Path $scriptDirectory '..'))-$outputRoot = [IO.Path]::GetFullPath($OutputDirectory)-$repositoryPrefix = $repositoryRoot.TrimEnd([IO.Path]::DirectorySeparatorChar) + [IO.Path]::DirectorySeparatorChar-if ($outputRoot.Equals($repositoryRoot, [StringComparison]::OrdinalIgnoreCase) -or- $outputRoot.StartsWith($repositoryPrefix, [StringComparison]::OrdinalIgnoreCase)) {- throw 'OutputDirectory must be outside the repository.'-}-if (Test-Path -LiteralPath $outputRoot) {- throw 'OutputDirectory must not already exist.'-}--$headRevision = (& git -C $repositoryRoot rev-parse HEAD).Trim()-if ($LASTEXITCODE -ne 0) { throw 'Unable to resolve the Git revision.' }-if ([string]::IsNullOrWhiteSpace($Revision)) { $Revision = $headRevision }-$Revision = $Revision.Trim().ToLowerInvariant()-if ($Revision -notmatch '^[0-9a-f]{40}$' -or $Revision -ne $headRevision) {- throw 'Revision must be the full SHA-1 of the checked-out commit.'-}-$dirty = @(git -C $repositoryRoot status --porcelain)-if ($LASTEXITCODE -ne 0 -or $dirty.Count -ne 0) {- throw 'Native packages must be built from a clean Git checkout.'-}--$go = Get-Command go.exe -ErrorAction Stop-$senderDirectory = Join-Path $repositoryRoot 'native\sender'-$packageName = "screener-native-windows-x64-$($Revision.Substring(0, 12))"-$packageDirectory = Join-Path $outputRoot $packageName-$licenseDirectory = Join-Path $packageDirectory 'licenses'-$senderExecutable = Join-Path $packageDirectory 'screener-sender.exe'-$zipPath = Join-Path $outputRoot "$packageName.zip"-New-Item -ItemType Directory -Path $licenseDirectory -Force | Out-Null--$previousGoOS = $env:GOOS-$previousGoArch = $env:GOARCH-$previousCGO = $env:CGO_ENABLED-Push-Location $senderDirectory-try {- $env:GOOS = 'windows'- $env:GOARCH = 'amd64'- $env:CGO_ENABLED = '0'- $linkerFlags = "-X main.buildRevision=$Revision"- & $go.Source build -mod=readonly -trimpath -buildvcs=true -ldflags $linkerFlags -o $senderExecutable ./cmd/screener-sender- if ($LASTEXITCODE -ne 0) { throw 'Native sender build failed.' }-- $moduleLines = @(& $go.Source list -deps -f '{{with .Module}}{{if not .Main}}{{.Path}}|{{.Version}}|{{.Dir}}{{end}}{{end}}' ./cmd/screener-sender |- Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | Sort-Object -Unique)- if ($LASTEXITCODE -ne 0 -or $moduleLines.Count -eq 0) {- throw 'Unable to enumerate linked Go modules.'- }- $goVersion = (& $go.Source version).Trim()- $goRoot = (& $go.Source env GOROOT).Trim()-} finally {- Pop-Location- $env:GOOS = $previousGoOS- $env:GOARCH = $previousGoArch- $env:CGO_ENABLED = $previousCGO-}--& (Join-Path $repositoryRoot 'native\window-capture-helper\build.ps1') -OutputDirectory $packageDirectory | Out-Null-@('window-capture.obj', 'process-audio.obj') | ForEach-Object {- $helperObject = Join-Path $packageDirectory $_- if (Test-Path -LiteralPath $helperObject) { Remove-Item -LiteralPath $helperObject -Force }-}--$moduleManifest = @()-foreach ($line in $moduleLines) {- $modulePath, $moduleVersion, $moduleDirectory = $line -split '\|', 3- if ([string]::IsNullOrWhiteSpace($moduleDirectory) -or -not (Test-Path -LiteralPath $moduleDirectory -PathType Container)) {- throw "Linked module source is unavailable: $modulePath@$moduleVersion"- }- $licenseFiles = @(Get-ChildItem -LiteralPath $moduleDirectory -File | Where-Object {- $_.Name -match '^(LICENSE|LICENCE|COPYING|NOTICE)(\.|$)'- })- if ($licenseFiles.Count -eq 0) { throw "Linked module has no recognized license file: $modulePath@$moduleVersion" }- $moduleLicenseDirectory = Join-Path $licenseDirectory (($modulePath + '@' + $moduleVersion) -replace '[^A-Za-z0-9._@+-]', '_')- New-Item -ItemType Directory -Path $moduleLicenseDirectory | Out-Null- $licenseFiles | Copy-Item -Destination $moduleLicenseDirectory- $moduleManifest += "$modulePath $moduleVersion"-}--$goLicense = Join-Path $goRoot 'LICENSE'-if (-not (Test-Path -LiteralPath $goLicense -PathType Leaf)) { throw 'Go toolchain license was not found.' }-$goLicenseDirectory = Join-Path $licenseDirectory 'go-toolchain'-New-Item -ItemType Directory -Path $goLicenseDirectory | Out-Null-Copy-Item -LiteralPath $goLicense -Destination (Join-Path $goLicenseDirectory 'LICENSE')-$moduleManifest | Set-Content -LiteralPath (Join-Path $licenseDirectory 'MODULES.txt') -Encoding ascii-Copy-Item -LiteralPath (Join-Path $senderDirectory 'README.md') -Destination (Join-Path $packageDirectory 'README.md')-@(- "revision=$Revision"- 'platform=windows/amd64'- "toolchain=$goVersion"-) | Set-Content -LiteralPath (Join-Path $packageDirectory 'REVISION.txt') -Encoding ascii--$versionOutput = (& $senderExecutable --version).Trim()-if ($LASTEXITCODE -ne 0 -or $versionOutput -ne "Screener sender $Revision") {- throw 'Packaged sender revision smoke failed.'-}--$packagePrefix = $packageDirectory.TrimEnd([IO.Path]::DirectorySeparatorChar) + [IO.Path]::DirectorySeparatorChar-$checksums = Get-ChildItem -LiteralPath $packageDirectory -File -Recurse | Sort-Object FullName | ForEach-Object {- $relativePath = $_.FullName.Substring($packagePrefix.Length).Replace('\', '/')- "$((Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256).Hash.ToLowerInvariant()) $relativePath"-}-$checksums | Set-Content -LiteralPath (Join-Path $packageDirectory 'SHA256SUMS.txt') -Encoding ascii--Compress-Archive -LiteralPath $packageDirectory -DestinationPath $zipPath -CompressionLevel Optimal-$zipHash = (Get-FileHash -LiteralPath $zipPath -Algorithm SHA256).Hash.ToLowerInvariant()-"$zipHash $([IO.Path]::GetFileName($zipPath))" |- Set-Content -LiteralPath "$zipPath.sha256" -Encoding ascii--Write-Output $zipPath-Write-Output "$zipPath.sha256"diff --git a/scripts/required-project-paths.txt b/scripts/required-project-paths.txtindex 4fb35fa3..0d89c8c3 100644--- a/scripts/required-project-paths.txt+++ b/scripts/required-project-paths.txt@@ -15,7 +15,6 @@ tsconfig.json.githooks/pre-commit.github/pull_request_template.md.github/workflows/repository-hygiene.yml-.github/workflows/native-sender-package.ymldocs/README.mddocs/project-memory.mddocs/status.md@@ -44,7 +43,6 @@ scripts/required-project-paths.txtscripts/check-project-state.shscripts/check-project-state.ps1scripts/check-docs.mjs-scripts/package-native-sender.ps1scripts/install-hooks.shscripts/install-hooks.ps1deploy/coturn/turnserver.conf.examplediff --git a/src/client/components/StageEntryActions.tsx b/src/client/components/StageEntryActions.tsxindex a1c58b41..112a7c03 100644--- a/src/client/components/StageEntryActions.tsx+++ b/src/client/components/StageEntryActions.tsx@@ -4,12 +4,14 @@ import { RoomCodeEntry } from "./RoomCodeEntry";interface StageEntryActionsProps {joiningRoom: boolean;+ startSharingDisabled?: boolean;onJoinToggle: () => void;onStartSharing: () => void;}export function StageEntryActions({joiningRoom,+ startSharingDisabled = false,onJoinToggle,onStartSharing,}: StageEntryActionsProps) {@@ -19,6 +21,7 @@ export function StageEntryActions({<buttonclassName="entry-action"type="button"+ disabled={startSharingDisabled}title="开始分享屏幕"onClick={onStartSharing}>diff --git a/src/client/media/candidate-quality-probe.ts b/src/client/media/candidate-quality-probe.tsindex 3a7f9611..108d725f 100644--- a/src/client/media/candidate-quality-probe.ts+++ b/src/client/media/candidate-quality-probe.ts@@ -125,6 +125,7 @@ class ConsecutiveCandidateQualityProbe {private lastCandidateTimestampMs: number | null = null;private lastCurrentTimestampMs: number | null = null;private consecutiveApprovedWindows = 0;+ private consecutiveRejectedWindows = 0;constructor(private readonly compare: (@@ -136,12 +137,12 @@ class ConsecutiveCandidateQualityProbe {observe(current: ConnectionMetrics | null,candidate: ConnectionMetrics,- ): boolean {+ ): CandidateQualityProbeResult {if (candidate.sampleTimestampMs === null ||candidate.sampleTimestampMs === this.lastCandidateTimestampMs) {- return false;+ return "pending";}this.lastCandidateTimestampMs = candidate.sampleTimestampMs;if (@@ -150,27 +151,48 @@ class ConsecutiveCandidateQualityProbe {(this.lastCurrentTimestampMs !== null &¤t.sampleTimestampMs <= this.lastCurrentTimestampMs)) {- this.consecutiveApprovedWindows = 0;- return false;+ this.resetRuns();+ return "pending";}this.lastCurrentTimestampMs = current.sampleTimestampMs;const approved = this.compare(current, candidate);- this.consecutiveApprovedWindows = approved- ? this.consecutiveApprovedWindows + 1- : 0;- return (- this.consecutiveApprovedWindows >=+ if (approved === null) {+ this.resetRuns();+ return "pending";+ }+ if (approved) {+ this.consecutiveApprovedWindows += 1;+ this.consecutiveRejectedWindows = 0;+ return this.consecutiveApprovedWindows >=+ PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS+ ? "approved"+ : "pending";+ }+ this.consecutiveApprovedWindows = 0;+ this.consecutiveRejectedWindows += 1;+ return this.consecutiveRejectedWindows >=PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS- );+ ? "rejected"+ : "pending";}reset(): void {this.lastCandidateTimestampMs = null;this.lastCurrentTimestampMs = null;+ this.resetRuns();+ }++ private resetRuns(): void {this.consecutiveApprovedWindows = 0;+ this.consecutiveRejectedWindows = 0;}}+export type CandidateQualityProbeResult =+ | "pending"+ | "approved"+ | "rejected";+export class SfuQualityProbe extends ConsecutiveCandidateQualityProbe {constructor() {super(sfuCandidateDoesNotRegress);diff --git a/src/client/media/decoded-frame-stall.ts b/src/client/media/decoded-frame-stall.tsindex 96dc3275..cb313782 100644--- a/src/client/media/decoded-frame-stall.ts+++ b/src/client/media/decoded-frame-stall.ts@@ -37,7 +37,12 @@ export class DecodedFrameStallDetector {this.reported = false;return false;}- if ((framesDecodedDelta ?? 0) > 0) {+ if (framesDecodedDelta === null) {+ this.lastDecodedAt = nowMs;+ this.reported = false;+ return false;+ }+ if (framesDecodedDelta > 0) {this.lastDecodedAt = nowMs;this.reported = false;return false;diff --git a/src/client/media/viewer-sfu-route.ts b/src/client/media/viewer-sfu-route.tsindex d1578fd2..3476e11f 100644--- a/src/client/media/viewer-sfu-route.ts+++ b/src/client/media/viewer-sfu-route.ts@@ -8,7 +8,10 @@ import type {import { SfuSubscriber } from "../sfu/subscriber";import type { ConnectionMetrics } from "../types";import type { SfuConnectionConfig } from "../sfu/publisher";-import { SfuQualityProbe } from "./candidate-quality-probe";+import {+ SfuQualityProbe,+ type CandidateQualityProbeResult,+} from "./candidate-quality-probe";import {MediaRouteTransition,reportActivePeerRouteFailure,@@ -27,6 +30,7 @@ interface ViewerSubscriberTransport {}interface ViewerSubscriberSlot {+ mediaIdentity: string;revision: number;phase: MediaRoutePhase;publicationGeneration: string;@@ -38,7 +42,7 @@ interface ViewerSubscriberSlot {decodedFrame: boolean;readySent: boolean;qualityProbe: SfuQualityProbe | null;- qualityApproved: boolean;+ qualityResult: CandidateQualityProbeResult;failed: boolean;activationToken: RouteOperationToken | null;}@@ -77,6 +81,7 @@ interface ViewerSfuRouteEvents {onSfuDecodedFrameSample?: (framesDecodedDelta: number | null,revision: number,+ mediaIdentity: string,) => void;onSfuState?: (state: "connected" | "reconnecting",@@ -106,6 +111,7 @@ export class ViewerSfuRoute {private resyncGeneration = 0;private resyncing = false;private manualReconnectRevision: number | null = null;+ private subscriberGeneration = 0;private paused = false;private closed = false;@@ -260,7 +266,7 @@ export class ViewerSfuRoute {if (paused) {this.pending?.qualityProbe?.reset();if (this.pending) {- this.pending.qualityApproved = false;+ this.pending.qualityResult = "pending";}}if (paused) {@@ -271,7 +277,7 @@ export class ViewerSfuRoute {resetQualityProbe(): void {this.pending?.qualityProbe?.reset();if (this.pending) {- this.pending.qualityApproved = false;+ this.pending.qualityResult = "pending";}}@@ -464,15 +470,20 @@ export class ViewerSfuRoute {) {if (this.events.qualityProbeEligible?.() === false) {slot.qualityProbe.reset();- slot.qualityApproved = false;- } else if (- slot.qualityProbe.observe(+ slot.qualityResult = "pending";+ } else {+ slot.qualityResult = slot.qualityProbe.observe(this.events.currentPeerMetrics?.() ?? null,metrics,- )- ) {- slot.qualityApproved = true;- this.sendPendingReady(slot);+ );+ if (slot.qualityResult === "approved") {+ this.sendPendingReady(slot);+ } else if (+ slot.qualityResult === "rejected" &&+ this.routeFailed(slot.revision, "prepare")+ ) {+ this.clearPending();+ }}}},@@ -481,6 +492,7 @@ export class ViewerSfuRoute {this.events.onSfuDecodedFrameSample?.(framesDecodedDelta,slot.revision,+ slot.mediaIdentity,);}},@@ -497,6 +509,7 @@ export class ViewerSfuRoute {new SfuSubscriber(subscriberEvents);const preparedCandidate = this.route.getPreparedCandidate();slot = {+ mediaIdentity: `${publicationGeneration}:${++this.subscriberGeneration}`,revision: message.revision,phase,publicationGeneration,@@ -512,7 +525,7 @@ export class ViewerSfuRoute {preparedCandidate.qualityProbe? new SfuQualityProbe(): null,- qualityApproved: false,+ qualityResult: "pending",failed: false,activationToken: null,};@@ -778,7 +791,7 @@ export class ViewerSfuRoute {slot.failed ||slot.readySent ||!slot.decodedFrame ||- (slot.qualityProbe !== null && !slot.qualityApproved) ||+ (slot.qualityProbe !== null && slot.qualityResult !== "approved") ||(slot.qualityProbe !== null &&this.events.qualityProbeEligible?.() === false) ||this.route.getPhase() !== "prepare" ||@@ -999,8 +1012,8 @@ export class ViewerSfuRoute {: null;}- private routeFailed(revision: number, phase: MediaRoutePhase): void {- this.events.send({+ private routeFailed(revision: number, phase: MediaRoutePhase): boolean {+ return this.events.send({type: "route-failed",revision,phase,diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsxindex 115e9b09..bddb6a64 100644--- a/src/client/pages/HostPage.tsx+++ b/src/client/pages/HostPage.tsx@@ -288,7 +288,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {useState<HostCreationProfile>(readCreationProfile);const creationProfileRef = useRef(creationProfile);const [roomMutation, setRoomMutation] = useState<- "access" | "replacement" | null+ "access" | "replacement" | "sharing" | null>(null);const roomMutating = roomMutation !== null;const [viewerPasswordEnabled, setViewerPasswordEnabled] = useState(@@ -332,7 +332,6 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {const hostClientIdRef = useRef<string | null>(null);const iceConfigRef = useRef<IceConfig | null>(null);const peersRef = useRef(new Map<string, HostPeer>());- const retiredConnectionsRef = useRef(new Map<string, string>());const hostProvisionalChildRef = useRef<HostProvisionalChild | null>(null);const activeHostChildPeerIdsRef = useRef<string[]>([]);const endpointMediaCopyCapacityRef = useRef(MAX_ENDPOINT_MEDIA_CHILDREN);@@ -458,7 +457,6 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {signalRef.current?.stop();peersRef.current.forEach((peer) => peer.dispose());peersRef.current.clear();- retiredConnectionsRef.current.clear();hostProvisionalChildRef.current?.discard();hostProvisionalChildRef.current = null;activeHostChildPeerIdsRef.current = [];@@ -488,6 +486,16 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {);}+ function isCurrentShare(+ generation: number,+ shareGeneration: string,+ ): boolean {+ return (+ isCurrentGeneration(generation) &&+ shareGenerationRef.current === shareGeneration+ );+ }+async function resolveStreamVideoCodec(stream: MediaStream,): Promise<BrowserVideoCodecPreference> {@@ -615,7 +623,6 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {shareGenerationRef.current = null;peersRef.current.forEach((peer) => peer.dispose());peersRef.current.clear();- retiredConnectionsRef.current.clear();hostProvisionalChildRef.current?.discard();hostProvisionalChildRef.current = null;activeHostChildPeerIdsRef.current = [];@@ -671,7 +678,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {}function beginRoomMutation(- kind: "access" | "replacement",+ kind: "access" | "replacement" | "sharing",): object | null {if (roomMutationRef.current) {return null;@@ -1087,7 +1094,6 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {clearViewerQualityEvidence(peerId);const peer = peersRef.current.get(peerId);if (peer) {- retiredConnectionsRef.current.set(peerId, peer.connectionId);peer.dispose();}peersRef.current.delete(peerId);@@ -1265,6 +1271,8 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {started = await peer.start();} catch (error) {if (peersRef.current.get(peerId) === peer) {+ const connectionId = peer.connectionId;+ reportHostChildFailure(peerId, connectionId, generation);removePeer(peerId);}throw error;@@ -1273,10 +1281,13 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {return;}- removePeer(peerId);+ const connectionId = peer.connectionId;if (peerAssistedRef.current || attempt >= 1) {+ reportHostChildFailure(peerId, connectionId, generation);+ removePeer(peerId);return;}+ removePeer(peerId);window.setTimeout(() => {if (isCurrentGeneration(generation) &&@@ -1360,6 +1371,24 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {);}+ function reportHostChildFailure(+ peerId: string,+ connectionId: string,+ generation: number,+ ): boolean {+ return Boolean(+ isCurrentGeneration(generation) &&+ peerAssistedRef.current &&+ hostChildIsAssigned(peerId) &&+ signalRef.current?.send({+ type: "route-failed",+ revision: activeRouteRevisionRef.current,+ phase: "active",+ connectionId,+ }),+ );+ }+function handleSignalMessage(message: ServerMessage,generation: number,@@ -1607,10 +1636,16 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {if (phase === "starting" ||phase === "live" ||- activeGenerationRef.current !== null+ activeGenerationRef.current !== null ||+ roomMutationRef.current !== null) {return;}+ const mutation = beginRoomMutation("sharing");+ if (!mutation) {+ return;+ }+ try {const generation = generationRef.current + 1;const shareGeneration = createOpaqueId();generationRef.current = generation;@@ -1625,7 +1660,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {// This must remain the first awaited operation in the button gesture.captured = await captureDisplay(qualitySettingsRef.current);} catch (error) {- if (!isCurrentGeneration(generation)) {+ if (!isCurrentShare(generation, shareGeneration)) {return;}activeGenerationRef.current = null;@@ -1635,7 +1670,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {return;}- if (!isCurrentGeneration(generation)) {+ if (!isCurrentShare(generation, shareGeneration)) {captured.getTracks().forEach((track) => track.stop());return;}@@ -1647,7 +1682,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {videoCodecRef.current = await resolveStreamVideoCodec(captured);setResolvedVideoCodec(videoCodecRef.current.primary);- if (!isCurrentGeneration(generation)) {+ if (!isCurrentShare(generation, shareGeneration)) {captured.getTracks().forEach((track) => track.stop());return;}@@ -1655,7 +1690,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {let createdRoom: HostRoomState | null = null;let claimedRoom = false;try {- let reusableRoom = room;+ const reusableRoom = roomRef.current;createdRoom = reusableRoom ?? hostRoomFromStored(readHostRoom());if (!createdRoom) {const response = await createRoom(@@ -1664,15 +1699,17 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {readPreferredRoomId(),);createdRoom = hostRoomFromCreated(response);- if (!isCurrentGeneration(generation)) {+ if (!isCurrentShare(generation, shareGeneration)) {captured.getTracks().forEach((track) => track.stop());closeAbandonedRoom(createdRoom);return;}writeHostRoom(createdRoom);+ roomRef.current = createdRoom;setRoom(createdRoom);claimedRoom = true;} else {+ roomRef.current = createdRoom;setRoom(createdRoom);claimedRoom = true;}@@ -1703,7 +1740,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {{onStatus: (status) => {if (- isCurrentGeneration(generation) &&+ isCurrentShare(generation, shareGeneration) &&signalRef.current === signal) {setSignalStatus(status);@@ -1711,7 +1748,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {},onTerminated: (reason) => {if (- isCurrentGeneration(generation) &&+ isCurrentShare(generation, shareGeneration) &&signalRef.current === signal) {endSharing(hostTerminationMessage(reason), false);@@ -1719,7 +1756,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {},onAccessRequired: () => {if (- isCurrentGeneration(generation) &&+ isCurrentShare(generation, shareGeneration) &&signalRef.current === signal) {endSharing("站点访问已失效,请重新验证", false);@@ -1728,7 +1765,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {},onMessage: (message) => {if (- !isCurrentGeneration(generation) ||+ !isCurrentShare(generation, shareGeneration) ||signalRef.current !== signal) {return;@@ -1787,18 +1824,19 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {readPreferredRoomId(),);const replacement = hostRoomFromCreated(response);- if (!isCurrentGeneration(generation)) {+ if (!isCurrentShare(generation, shareGeneration)) {captured.getTracks().forEach((track) => track.stop());closeAbandonedRoom(replacement);return;}writeHostRoom(replacement);+ roomRef.current = replacement;setRoom(replacement);const replacementSignal = connectSignal(replacement);signalRef.current = replacementSignal;replacementSignal.start();} catch (error) {- if (!isCurrentGeneration(generation)) {+ if (!isCurrentShare(generation, shareGeneration)) {return;}activeGenerationRef.current = null;@@ -1819,7 +1857,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {signalRef.current = signal;signal.start();} catch (error) {- if (!isCurrentGeneration(generation)) {+ if (!isCurrentShare(generation, shareGeneration)) {captured.getTracks().forEach((track) => track.stop());if (createdRoom && !claimedRoom) {closeAbandonedRoom(createdRoom);@@ -1839,6 +1877,9 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {setNotice(readableError(error, "room"));setPhase("error");}+ } finally {+ finishRoomMutation(mutation);+ }}async function switchSource(): Promise<void> {@@ -2392,6 +2433,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {)}<StageEntryActionsjoiningRoom={joiningRoom}+ startSharingDisabled={roomMutating}onStartSharing={() => {setJoiningRoom(false);void startSharing();diff --git a/src/client/pages/ViewerPage.tsx b/src/client/pages/ViewerPage.tsxindex 27408b87..9aae9940 100644--- a/src/client/pages/ViewerPage.tsx+++ b/src/client/pages/ViewerPage.tsx@@ -45,7 +45,10 @@ import { readDisplayName, saveDisplayName } from "../lib/display-name";import { clearViewerGrant, getStableClientId } from "../lib/session";import { SignalingClient } from "../lib/signaling";import { labelParticipantSnapshot } from "../lib/viewer-presence";-import { P2pQualityProbe } from "../media/candidate-quality-probe";+import {+ P2pQualityProbe,+ type CandidateQualityProbeResult,+} from "../media/candidate-quality-probe";import { DecodedFrameStallDetector } from "../media/decoded-frame-stall";import type { QualitySettings } from "../media/quality";import { relayCapacityMessageForBrowser } from "../media/relay-capability";@@ -117,7 +120,7 @@ interface PendingPeerRoute {stream: MediaStream | null;snapshot: PeerSnapshot | null;qualityProbe: P2pQualityProbe | null;- qualityApproved: boolean;+ qualityResult: CandidateQualityProbeResult;}interface RemoteMediaBinding {@@ -447,7 +450,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {pageSuspended = true;viewerSfuRoute?.resetQualityProbe();pendingPeer?.qualityProbe?.reset();- if (pendingPeer) pendingPeer.qualityApproved = false;+ if (pendingPeer) pendingPeer.qualityResult = "pending";syncDecodedFrameStallPause();if (newlySuspended) {invalidateSenderQualityEvidence();@@ -753,34 +756,58 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {probe?.peer?.dispose();}+ function reportActivePeerFailure(+ parentPeerId: string,+ connectionId: string,+ peer: ViewerPeer,+ ): boolean {+ if (+ currentRouteAssignment?.upstream.kind !== "peer" ||+ currentRouteAssignment.upstream.peerId !== parentPeerId ||+ peerRef.current !== peer ||+ peer.getConnectionIdentity()?.parentPeerId !== parentPeerId ||+ !peer.hasConnectionId(connectionId)+ ) {+ return true;+ }+ return (+ viewerSfuRoute?.reportPeerFailure(+ parentPeerId,+ connectionId,+ ) ?? true+ );+ }+function observeActiveDecodedFrames(route: "peer" | "sfu",identity: string,framesDecodedDelta: number | null,+ authorityRevision: number,connectionId?: string,): void {if (!peerAssisted ||currentHostPaused ||- !decodedFrameStall.observe(- `${route}:${currentRouteRevision}:${identity}`,- framesDecodedDelta,- )+ !decodedFrameStall.observe(`${route}:${identity}`, framesDecodedDelta)) {return;}+ if (authorityRevision !== currentRouteRevision) {+ decodedFrameStall.allowReportRetry();+ return;+ }let sent = false;if (route === "peer" && connectionId) {sent = signal.send({type: "route-failed",- revision: currentRouteRevision,+ revision: authorityRevision,phase: "active",connectionId,});} else if (route === "sfu") {sent = signal.send({type: "route-media-unavailable",- revision: currentRouteRevision,+ revision: authorityRevision,});}if (!sent) decodedFrameStall.allowReportRetry();@@ -817,7 +844,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {if (!pendingPeerHasDecodedFrame(probe)) {return false;}- if (probe.qualityProbe && !probe.qualityApproved) {+ if (probe.qualityProbe && probe.qualityResult !== "approved") {return false;}probe.readySent = signal.send({@@ -909,7 +936,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {qualityProbe: candidate.qualityProbe? new P2pQualityProbe(): null,- qualityApproved: false,+ qualityResult: "pending",};}prepareParent(@@ -952,12 +979,17 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {);reconcileRelayChildren(previousChildPeerIds, revision);},- onSfuDecodedFrameSample: (framesDecodedDelta, revision) => {+ onSfuDecodedFrameSample: (+ framesDecodedDelta,+ revision,+ mediaIdentity,+ ) => {if (active && viewerSfuRoute === route) {observeActiveDecodedFrames("sfu",- String(revision),+ mediaIdentity,framesDecodedDelta,+ revision,);}},@@ -1171,11 +1203,24 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {)) {probe.qualityProbe.reset();- probe.qualityApproved = false;- } else if (- probe.qualityProbe.observe(activePeerMetrics, snapshot.metrics)- ) {- probe.qualityApproved = true;+ probe.qualityResult = "pending";+ } else {+ probe.qualityResult = probe.qualityProbe.observe(+ activePeerMetrics,+ snapshot.metrics,+ );+ if (+ probe.qualityResult === "rejected" &&+ signal.send({+ type: "route-failed",+ revision: probe.revision,+ phase: "prepare",+ connectionId: probe.candidateConnectionId,+ })+ ) {+ discardPendingPeer();+ return;+ }}}provePendingPeer();@@ -1185,6 +1230,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {"peer",`${probe.parentPeerId}:${snapshot.connectionId}`,snapshot.metrics.intervalFramesDecoded,+ currentRouteRevision,snapshot.connectionId,);offerPeerQualityEvidence(snapshot, peer);@@ -1224,8 +1270,8 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {peer.dispose();return true;}- return peerRef.current === peer && viewerSfuRoute- ? viewerSfuRoute.reportPeerFailure(parentPeerId, connectionId)+ return peerRef.current === peer+ ? reportActivePeerFailure(parentPeerId, connectionId, peer): true;},},@@ -1241,7 +1287,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {if (!currentIceConfig) {return null;}- const peer = new ViewerPeer(+ const peer: ViewerPeer = new ViewerPeer(currentIceConfig,{sendSignal: (targetPeerId, payload) =>@@ -1272,6 +1318,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {"peer",`${snapshot.peerId}:${snapshot.connectionId}`,snapshot.metrics.intervalFramesDecoded,+ currentRouteRevision,snapshot.connectionId,);offerPeerQualityEvidence(snapshot, peer);@@ -1297,9 +1344,16 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {});}},- onRecoveryExhausted: (parentPeerId, connectionId) => {+ onRecoveryExhausted: (+ parentPeerId,+ connectionId,+ ): boolean => {if (viewerSfuRoute) {- return viewerSfuRoute.reportPeerFailure(parentPeerId, connectionId);+ return reportActivePeerFailure(+ parentPeerId,+ connectionId,+ peer,+ );}invalidateQualityPresentation();dispatchPresentation({@@ -1326,6 +1380,11 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {clearRelayChildEvidence();currentPeerId = message.peerId;endpointMediaCopyCapacity = message.endpointMediaCopyCapacity;+ currentAssignment = limitMediaAssignment(+ currentAssignment,+ endpointMediaCopyCapacity,+ );+ viewerRelay?.updateCapacity(endpointMediaCopyCapacity);viewerAuthorizationGeneration =message.viewerAuthorizationGeneration;setSfuStandbyUrl(diff --git a/src/client/webrtc/viewer-relay.ts b/src/client/webrtc/viewer-relay.tsindex bebef755..e772013e 100644--- a/src/client/webrtc/viewer-relay.ts+++ b/src/client/webrtc/viewer-relay.ts@@ -49,7 +49,7 @@ export class ViewerRelay {private iceConfig: IceConfig,private desiredProfile: QualityProfile,private readonly events: ViewerRelayEvents,- private readonly maxMediaEdges = MAX_ENDPOINT_MEDIA_CHILDREN,+ private maxMediaEdges = MAX_ENDPOINT_MEDIA_CHILDREN,) {}getSnapshot(childPeerId?: string): PeerSnapshot | null {@@ -158,6 +158,17 @@ export class ViewerRelay {this.reconcileChildren(childPeerIds, null);}+ updateCapacity(maxMediaEdges: number): void {+ if (this.disposed || this.maxMediaEdges === maxMediaEdges) {+ return;+ }+ this.maxMediaEdges = maxMediaEdges;+ if (this.plannedChildPeerIds.length > maxMediaEdges) {+ this.discardPreparedChild();+ }+ this.reconcileChildren(this.childPeerIds, null);+ }+private reconcileChildren(childPeerIds: readonly string[],promotedPeerId: string | null,diff --git a/src/server/hybrid-media-router.ts b/src/server/hybrid-media-router.tsindex e58d5c6b..d55237aa 100644--- a/src/server/hybrid-media-router.ts+++ b/src/server/hybrid-media-router.ts@@ -66,11 +66,14 @@ type RouteResource =| SfuPublicationRouteResource| OverlapRouteResource;-interface SfuDrainTask {- fence: SfuResourceFence;+type SfuDrainTarget =+ | { kind: "publication"; fence: SfuResourceFence }+ | { kind: "subscription"; fence: SfuSubscriptionFence };++type SfuDrainTask = SfuDrainTarget & {operation?: Promise<void>;retryTimer?: NodeJS.Timeout;-}+};interface HostOfflineCheck {hostPeerId: string;@@ -178,7 +181,9 @@ export class HybridMediaRouter {this.hostOfflineChecks.clear();const fallback = this.options.sfuFallback;if (!fallback) return;- for (const fence of fallback.admission.beginDrainAll()) this.scheduleSfuDrain(fence);+ for (const fence of fallback.admission.beginDrainAll()) {+ this.scheduleSfuPublicationDrain(fence);+ }for (const [key, task] of [...this.sfuDrainTasks]) {if (task.retryTimer) clearTimeout(task.retryTimer);if (task.operation) await task.operation;@@ -820,6 +825,21 @@ export class HybridMediaRouter {if (snapshot.revision !== message.revision) return;if (participant.role === "host") {+ if (+ message.connectionId &&+ controller.invalidateDirectEdgeFromParent(+ {+ parentPeerId: participant.peerId,+ parentSessionId: participant.sessionId,+ routeRevision: snapshot.revision,+ connectionId: message.connectionId,+ },+ this.now(),+ )+ ) {+ this.requestPump(participant.roomId);+ return;+ }const publication = snapshot.hostPublication;if (!publication ||@@ -1219,7 +1239,7 @@ export class HybridMediaRouter {...publication.resource.fence,viewerPeerId: operation.childPeerId,};- if (!fallback.admission.reserveSubscription(fence)) {+ if (!(await this.reserveSfuSubscription(fence))) {return { kind: "denied", rejectionBucket: "sfu-admission" };}const currentEdge = snapshot.upstreamByViewer.get(operation.childPeerId);@@ -1300,7 +1320,7 @@ export class HybridMediaRouter {}if (!fallback.admission.reserveSubscription(subscriptionFence)) {fallback.admission.beginDrain(publicationFence);- this.scheduleSfuDrain(publicationFence);+ this.scheduleSfuPublicationDrain(publicationFence);return { kind: "denied", rejectionBucket: "sfu-admission" };}const subscription = subscriptionResource(subscriptionFence);@@ -1617,7 +1637,7 @@ export class HybridMediaRouter {reservation.publication.fence,);if (!draining) return false;- for (const fence of draining) this.scheduleSfuDrain(fence);+ for (const fence of draining) this.scheduleSfuPublicationDrain(fence);return true;}@@ -1626,7 +1646,7 @@ export class HybridMediaRouter {}private releaseResources(resources: readonly RouteResource[]): void {- // Generation drain owns physical release; its child handles stay charged until absence.+ // Publication drains own accounting; subscription drains only remove exact participants.for (const resource of resources) {if (resource.kind === "sfu-publication") this.releaseResource(resource);}@@ -1644,21 +1664,41 @@ export class HybridMediaRouter {return;}if (this.options.sfuFallback?.admission.beginDrain(resource.fence)) {- this.scheduleSfuDrain(resource.fence);+ this.scheduleSfuPublicationDrain(resource.fence);}}private releaseSubscription(fence: SfuSubscriptionFence): boolean {const admission = this.options.sfuFallback?.admission;if (!admission) return false;- const beforeEgress = admission.usage().egress;- const accepted = admission.releaseSubscription(fence);- if (accepted && admission.usage().egress < beforeEgress) {- this.wakeResourceWaiters();- }+ const accepted = admission.beginSubscriptionDrain(fence);+ if (accepted) this.scheduleSfuSubscriptionDrain(fence);return accepted;}+ private async reserveSfuSubscription(+ fence: SfuSubscriptionFence,+ ): Promise<boolean> {+ const fallback = this.options.sfuFallback;+ if (!fallback) return false;+ const key = sfuDrainKey({ kind: "subscription", fence });+ const pending = this.sfuDrainTasks.get(key);+ if (pending?.operation) {+ try {+ await pending.operation;+ } catch {+ return false;+ }+ if (this.sfuDrainTasks.get(key) === pending) return false;+ }+ const task = this.sfuDrainTasks.get(key);+ if (task?.kind === "subscription") {+ if (task.retryTimer) clearTimeout(task.retryTimer);+ this.sfuDrainTasks.delete(key);+ }+ return fallback.admission.reserveSubscription(fence);+ }+private wakeResourceWaiters(): void {const roomIds = [...this.resourceWaiters];this.resourceWaiters.clear();@@ -1827,12 +1867,34 @@ export class HybridMediaRouter {this.hostOfflineChecks.delete(roomId);}- private scheduleSfuDrain(fence: SfuResourceFence): void {+ private scheduleSfuPublicationDrain(fence: SfuResourceFence): void {+ const roomName = managedSfuRoomName(fence);+ for (const [key, task] of this.sfuDrainTasks) {+ if (+ task.kind === "subscription" &&+ managedSfuRoomName(task.fence) === roomName+ ) {+ if (task.retryTimer) clearTimeout(task.retryTimer);+ this.sfuDrainTasks.delete(key);+ }+ }+ this.scheduleSfuDrain({ kind: "publication", fence });+ }++ private scheduleSfuSubscriptionDrain(fence: SfuSubscriptionFence): void {+ if (this.sfuDrainTasks.has(managedSfuRoomName(fence))) return;+ this.scheduleSfuDrain({ kind: "subscription", fence });+ }++ private scheduleSfuDrain(target: SfuDrainTarget): void {if (!this.options.sfuFallback) return;- const key = managedSfuRoomName(fence);+ const key = sfuDrainKey(target);let task = this.sfuDrainTasks.get(key);if (!task) {- task = { fence: { ...fence } };+ task =+ target.kind === "publication"+ ? { kind: "publication", fence: { ...target.fence } }+ : { kind: "subscription", fence: { ...target.fence } };this.sfuDrainTasks.set(key, task);}if (!task.operation && !task.retryTimer) {@@ -1847,13 +1909,24 @@ export class HybridMediaRouter {let tracked!: Promise<void>;tracked = (async () => {try {- await fallback.roomControl.deleteRoom(task.fence);+ if (task.kind === "publication") {+ await fallback.roomControl.deleteRoom(task.fence);+ } else {+ await fallback.roomControl.drainSubscription(task.fence);+ }if (this.sfuDrainTasks.get(key) !== task) return;- if (!fallback.admission.completeDrain(task.fence)) {+ if (+ task.kind === "publication" &&+ !fallback.admission.completeDrain(task.fence)+ ) {throw new Error("LiveKit drain has no matching resource generation");}this.sfuDrainTasks.delete(key);- this.wakeResourceWaiters();+ if (task.kind === "publication") {+ this.wakeResourceWaiters();+ } else {+ this.requestPump(task.fence.roomId);+ }} catch (error) {if (this.sfuDrainTasks.get(key) !== task) return;if (this.closing) throw error;@@ -1882,7 +1955,7 @@ export class HybridMediaRouter {this.rooms.delete(roomId);this.resourceWaiters.delete(roomId);for (const fence of this.options.sfuFallback?.admission.beginDrainRoom(roomId) ?? []) {- this.scheduleSfuDrain(fence);+ this.scheduleSfuPublicationDrain(fence);}}@@ -1990,6 +2063,13 @@ function opaqueId(): string {return randomBytes(16).toString("base64url");}+function sfuDrainKey(target: SfuDrainTarget): string {+ const roomName = managedSfuRoomName(target.fence);+ return target.kind === "publication"+ ? roomName+ : `${roomName}\u0000viewer:${target.fence.viewerPeerId}`;+}+function overlapResource(endpointPeerId: string): OverlapRouteResource {return { kind: "overlap", endpointPeerId, released: false };}diff --git a/src/server/room-database.ts b/src/server/room-database.tsindex 2125c657..94e5a591 100644--- a/src/server/room-database.ts+++ b/src/server/room-database.ts@@ -216,14 +216,28 @@ export class RoomDatabase {}deleteRoom(roomId: string, hostTokenDigest: Buffer): void {- assertRoomIdentity(roomId, hostTokenDigest);+ this.deleteRooms([{ roomId, hostTokenDigest }]);+ }++ deleteRooms(+ rooms: readonly { roomId: string; hostTokenDigest: Buffer }[],+ ): void {+ for (const room of rooms) {+ assertRoomIdentity(room.roomId, room.hostTokenDigest);+ }+ if (rooms.length === 0) {+ return;+ }this.transaction((database) => {- const changes = database- .prepare(- "DELETE FROM rooms WHERE room_id = ? AND host_token_digest = ?",- )- .run(roomId, hostTokenDigest).changes;- assertSingleChange(changes, "delete");+ const statement = database.prepare(+ "DELETE FROM rooms WHERE room_id = ? AND host_token_digest = ?",+ );+ for (const room of rooms) {+ assertSingleChange(+ statement.run(room.roomId, room.hostTokenDigest).changes,+ "delete",+ );+ }});}diff --git a/src/server/room-route-controller.ts b/src/server/room-route-controller.tsindex 3ab08107..d8f4e690 100644--- a/src/server/room-route-controller.ts+++ b/src/server/room-route-controller.ts@@ -107,10 +107,10 @@ interface Participant {departureConfirmed: boolean;joinOrder: number;effectiveDownstreamCapacity: number;- blockedAtFactVersion?: number;- bootstrapFailureAtFactVersion?: number;+ availabilityExhausted: boolean;+ consumedCandidateOpportunities: Map<string, number>;+ bootstrapFailureReported?: boolean;sfuFirstAtNextRoute?: boolean;- failedTuple?: { key: string; factVersion: number };}interface Attempt<Resource> {@@ -129,6 +129,7 @@ interface Attempt<Resource> {senderQualityState?: "healthy" | "degraded";senderQualityAcceptedAtMs?: number;senderQualityConsecutiveHealthyWindows?: number;+ senderQualityConsecutiveDegradedWindows?: number;senderQualitySampleTimestampMs?: number;senderQualityIdentity?: string;}@@ -138,7 +139,7 @@ interface ChildOperation<Resource> {childSessionId: string;demandPeerId: string;demandSessionId: string;- reason: RouteDemandReason;+ readonly reason: RouteDemandReason;baseRevision: number;candidates: CandidatePlan[];cursor: number;@@ -158,8 +159,6 @@ interface DirectContinuation {interface SfuBootstrapIntent {demandPeerId: string;demandSessionId: string;- factVersion: number;- triedCarrierPeerIds: Set<string>;}interface SfuBootstrapCarrier {@@ -356,7 +355,10 @@ export class RoomRouteController<Resource = unknown> {private readonly qualityBaselinesPending = new Set<string>();private readonly directContinuations = new Map<string, DirectContinuation>();private sfuBootstrapIntent?: SfuBootstrapIntent;- private sfuBootstrapExhaustedAtFactVersion?: number;+ private readonly consumedSfuBootstrapOpportunities = new Map<+ string,+ number+ >();private rootConvergenceRootPeerId?: string;constructor(private readonly options: ControllerOptions) {@@ -477,6 +479,7 @@ export class RoomRouteController<Resource = unknown> {let changed = false;const previousSessionId = current.sessionId;if (previousSessionId !== input.sessionId) {+ this.clearOpportunitiesForSessionChange(input.peerId, input.role);this.clearQualityForParticipant(input.peerId);const revisionBefore = this.revision;if (this.operationUsesParticipantSession(input.peerId)) {@@ -500,9 +503,6 @@ export class RoomRouteController<Resource = unknown> {current.effectiveDownstreamCapacity = capacity;changed = true;}- if (changed && current.blockedAtFactVersion !== undefined) {- current.blockedAtFactVersion = undefined;- }if (changed) {this.touchFacts();this.debug("participant-updated", {@@ -525,6 +525,8 @@ export class RoomRouteController<Resource = unknown> {effectiveDownstreamCapacity: capacity,departureConfirmed: false,joinOrder: this.nextJoinOrder++,+ availabilityExhausted: false,+ consumedCandidateOpportunities: new Map(),});this.debug("participant-joined", {participant: this.debugPeer(input.peerId),@@ -542,6 +544,7 @@ export class RoomRouteController<Resource = unknown> {disconnectSession(peerId: string, sessionId: string): boolean {const participant = this.participants.get(peerId);if (!participant || participant.sessionId !== sessionId) return false;+ this.clearOpportunitiesForSessionChange(peerId, participant.role);participant.sessionId = null;this.clearQualityForParticipant(peerId);this.directContinuations.delete(peerId);@@ -559,6 +562,7 @@ export class RoomRouteController<Resource = unknown> {this.routeTimings.delete(peerId);if (participant.departureConfirmed && participant.sessionId === null &&participant.effectiveDownstreamCapacity === 0) return true;+ this.clearOpportunitiesForSessionChange(peerId, participant.role);participant.sessionId = null;this.clearQualityForParticipant(peerId);participant.departureConfirmed = true;@@ -589,7 +593,6 @@ export class RoomRouteController<Resource = unknown> {const changed = participant.effectiveDownstreamCapacity !== capacity;if (!changed) return true;participant.effectiveDownstreamCapacity = capacity;- participant.blockedAtFactVersion = undefined;if (nowMs !== undefined) {for (const childPeerId of this.overflowPeerChildren(peerId)) {this.recordDemand(childPeerId, nowMs, "capacity-reduction");@@ -604,6 +607,8 @@ export class RoomRouteController<Resource = unknown> {}touchExternalFacts(): void {+ this.clearSfuCandidateOpportunities();+ this.sfuBootstrapIntent = undefined;this.touchFacts();}@@ -654,15 +659,13 @@ export class RoomRouteController<Resource = unknown> {return false;}if (edge.usable) {+ this.consumeActiveEdgeOpportunity(child, edge);this.clearQualityForParticipant(guard.childPeerId);edge.usable = false;this.directContinuations.delete(guard.childPeerId);- child.blockedAtFactVersion = undefined;+ child.availabilityExhausted = false;+ child.bootstrapFailureReported = undefined;this.touchFacts();- child.failedTuple = {- key: edgeTupleKey(edge),- factVersion: this.factVersion,- };if (nowMs !== undefined) {this.recordDemand(guard.childPeerId, nowMs, "edge-unavailable");}@@ -670,6 +673,36 @@ export class RoomRouteController<Resource = unknown> {return true;}+ invalidateDirectEdgeFromParent(+ input: {+ parentPeerId: string;+ parentSessionId: string;+ routeRevision: number;+ connectionId: string;+ },+ nowMs?: number,+ ): boolean {+ const match = [...this.upstreamByViewer].find(+ ([, edge]) =>+ edge.kind === "peer" &&+ edge.parentPeerId === input.parentPeerId &&+ edge.parentSessionId === input.parentSessionId &&+ edge.connectionId === input.connectionId,+ );+ if (!match) return false;+ const [childPeerId, edge] = match;+ return this.invalidateEdge(+ {+ childPeerId,+ childSessionId: edge.childSessionId,+ parentSessionId: input.parentSessionId,+ routeRevision: input.routeRevision,+ connectionId: input.connectionId,+ },+ nowMs,+ );+ }+invalidateHostPublication(guard: {hostSessionId: string;routeRevision: number;@@ -686,7 +719,6 @@ export class RoomRouteController<Resource = unknown> {publication.usable = false;this.directContinuations.clear();this.sfuBootstrapIntent = undefined;- this.sfuBootstrapExhaustedAtFactVersion = undefined;if (nowMs !== undefined) {for (const [childPeerId, edge] of this.upstreamByViewer) {if (edge.kind === "sfu") {@@ -720,10 +752,7 @@ export class RoomRouteController<Resource = unknown> {this.clearQualityForParticipant(input.childPeerId);edge.connectionId = input.newConnectionId;const child = this.participants.get(input.childPeerId);- if (child) {- child.blockedAtFactVersion = undefined;- child.failedTuple = undefined;- }+ if (child) child.availabilityExhausted = false;this.touchFacts();return true;}@@ -740,7 +769,7 @@ export class RoomRouteController<Resource = unknown> {edge.physicalActive = false;edge.usable = false;this.clearQualityForParticipant(guard.childPeerId);- child.blockedAtFactVersion = undefined;+ child.availabilityExhausted = false;this.revision = this.allocateRevision();if (this.operation) this.operation.baseRevision = this.revision;this.touchFacts();@@ -944,7 +973,8 @@ export class RoomRouteController<Resource = unknown> {const operation = this.operation;const attempt = operation?.current;if (- operation?.reason === "root-convergence" &&+ (operation?.reason === "root-convergence" ||+ operation?.reason === "quality-convergence") &&attempt?.tuple.kind === "peer" &&operation.childPeerId === input.childPeerId &&operation.childSessionId === child.sessionId &&@@ -1292,6 +1322,7 @@ export class RoomRouteController<Resource = unknown> {attempt.senderQualityState = undefined;attempt.senderQualityAcceptedAtMs = undefined;attempt.senderQualityConsecutiveHealthyWindows = undefined;+ attempt.senderQualityConsecutiveDegradedWindows = undefined;attempt.senderQualitySampleTimestampMs = undefined;return {accepted: true,@@ -1343,13 +1374,15 @@ export class RoomRouteController<Resource = unknown> {released: [],};}+ const sameFreshState =+ attempt.senderQualityAcceptedAtMs !== undefined &&+ acceptedAtMs <+ attempt.senderQualityAcceptedAtMs ++ VIEWER_QUALITY_EVIDENCE_EXPIRY_MS;const consecutiveHealthyWindows =attempt.tuple.kind === "sfu" && state === "healthy"? attempt.senderQualityState === "healthy" &&- attempt.senderQualityAcceptedAtMs !== undefined &&- acceptedAtMs <- attempt.senderQualityAcceptedAtMs +- VIEWER_QUALITY_EVIDENCE_EXPIRY_MS+ sameFreshState? safeAdd(attempt.senderQualityConsecutiveHealthyWindows ?? 0,1,@@ -1358,10 +1391,21 @@ export class RoomRouteController<Resource = unknown> {: state === "healthy"? 1: 0;+ const consecutiveDegradedWindows =+ state === "degraded"+ ? attempt.senderQualityState === "degraded" && sameFreshState+ ? safeAdd(+ attempt.senderQualityConsecutiveDegradedWindows ?? 0,+ 1,+ )+ : 1+ : 0;attempt.senderQualityState = state;attempt.senderQualityAcceptedAtMs = acceptedAtMs;attempt.senderQualityConsecutiveHealthyWindows =consecutiveHealthyWindows;+ attempt.senderQualityConsecutiveDegradedWindows =+ consecutiveDegradedWindows;attempt.senderQualitySampleTimestampMs = sampleTimestampMs;attempt.senderQualityIdentity = senderIdentity;const guard = {@@ -1370,8 +1414,15 @@ export class RoomRouteController<Resource = unknown> {revision: attempt.revision,connectionId: attempt.connectionId,};+ const persistentQualityPeerDegradation =+ operation.reason === "quality-convergence" &&+ attempt.tuple.kind === "peer" &&+ consecutiveDegradedWindows >= PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS;const settled =- state === "degraded"+ state === "degraded" &&+ (attempt.tuple.kind !== "peer" ||+ operation.reason !== "quality-convergence" ||+ persistentQualityPeerDegradation)? this.candidateFailed(guard, acceptedAtMs): attempt.mediaReady &&(attempt.tuple.kind !== "sfu" ||@@ -1412,12 +1463,14 @@ export class RoomRouteController<Resource = unknown> {const operation = this.operation;const attempt = operation?.current;const ownsCandidate =- this.operationRequiresNativeCandidateProof(operation) &&attempt &&(attempt.tuple.kind === "peer"- ? attempt.tuple.parentPeerId === parentPeerId &&+ ? (operation?.reason === "root-convergence" ||+ operation?.reason === "quality-convergence") &&+ attempt.tuple.parentPeerId === parentPeerId &&attempt.parentSessionId === parentSessionId- : parentPeerId === this.options.hostPeerId &&+ : this.operationRequiresNativeCandidateProof(operation) &&+ parentPeerId === this.options.hostPeerId &&attempt.hostSessionId === parentSessionId);return ownsCandidate ? this.abortOperation(nowMs, "aborted") : [];}@@ -1541,7 +1594,7 @@ export class RoomRouteController<Resource = unknown> {this.revision = this.allocateRevision();this.touchFacts();}- child.blockedAtFactVersion = this.factVersion;+ child.availabilityExhausted = true;this.finishTiming(demandPeerId,nowMs,@@ -1609,7 +1662,7 @@ export class RoomRouteController<Resource = unknown> {};}const plan = operation.candidates[operation.cursor];- if (!plan || !this.candidateValid(operation.childPeerId, plan)) {+ if (!plan || !this.operationCandidateValid(operation, plan)) {return {accepted: false,released: [...validation.released, ...reservationResources(input.reservation)],@@ -1714,6 +1767,12 @@ export class RoomRouteController<Resource = unknown> {};}if (bucket === "candidate-failed") {+ if (this.isAvailabilityOperation(operation.reason)) {+ this.consumeCandidateOpportunity(+ operation.childPeerId,+ operation.candidates[operation.cursor]!,+ );+ }this.promoteNextDirectWithinHeadStart(operation, nowMs);}this.consumeDirectContinuationCandidate(operation);@@ -1847,6 +1906,12 @@ export class RoomRouteController<Resource = unknown> {operation.reason === "quality-convergence" &&attempt.tuple.kind === "peer" &&!relativeP2pApproved;+ if (+ relativeP2pApproved &&+ this.candidateSenderPersistentlyDegraded(attempt, nowMs)+ ) {+ return this.candidateFailed(guard, nowMs);+ }const nativeCandidateProof =this.operationRequiresNativeCandidateProof(operation);if (relativeP2pApproved || relativeP2pPending || nativeCandidateProof) {@@ -1922,6 +1987,12 @@ export class RoomRouteController<Resource = unknown> {}}if (!commitReservation(attempt.reservation)) {+ if (this.isAvailabilityOperation(operation.reason)) {+ this.consumeCandidateOpportunity(+ operation.childPeerId,+ operation.candidates[operation.cursor]!,+ );+ }this.debug("candidate-commit-rejected", {child: this.debugPeer(operation.childPeerId),candidate: this.debugTuple(attempt.tuple),@@ -2013,6 +2084,12 @@ export class RoomRouteController<Resource = unknown> {operation?.current &&this.guardMatches(guard, operation, operation.current)) {+ if (this.isAvailabilityOperation(operation.reason)) {+ this.consumeCandidateOpportunity(+ operation.childPeerId,+ operation.candidates[operation.cursor]!,+ );+ }this.debug("candidate-failed", {child: this.debugPeer(operation.childPeerId),candidate: this.debugTuple(operation.current.tuple),@@ -2086,7 +2163,7 @@ export class RoomRouteController<Resource = unknown> {this.routeTimings.clear();this.directContinuations.clear();this.sfuBootstrapIntent = undefined;- this.sfuBootstrapExhaustedAtFactVersion = undefined;+ this.consumedSfuBootstrapOpportunities.clear();this.rootConvergenceRootPeerId = undefined;this.paused = true;return [...resources];@@ -2157,17 +2234,23 @@ export class RoomRouteController<Resource = unknown> {operation.childPeerId,nowMs,factsChanged ? "stale" : "operation-deadline",+ operation.candidates[+ Math.min(operation.cursor, operation.candidates.length - 1)+ ],): undefined;const bootstrapAvailable =!backgroundConvergence &&!sfuBootstrap &&- !factsChanged &&this.bootstrapCandidateAvailable(operation.demandPeerId);+ if (bootstrapAvailable) {+ this.consumeCurrentAvailabilityOpportunity(operation);+ } else {+ this.consumeAvailabilityOperation(operation);+ }const exhausted = sfuBootstrap? failedBootstrapDemand !== undefined: !backgroundConvergence &&- !factsChanged &&!bootstrapAvailable;if (bootstrapAvailable) this.stageSfuBootstrap(operation);if (!sfuBootstrap) {@@ -2193,8 +2276,7 @@ export class RoomRouteController<Resource = unknown> {this.blockAndClear(operation,!backgroundConvergence &&- !sfuBootstrap &&- !factsChanged,+ !sfuBootstrap,released,revisionAdvanced,);@@ -2247,7 +2329,7 @@ export class RoomRouteController<Resource = unknown> {!guardFailed &&!peerNoProgressExpired &&plan &&- this.candidateValid(operation.childPeerId, plan, attempt)+ this.operationCandidateValid(operation, plan, attempt)) {return result;}@@ -2272,7 +2354,7 @@ export class RoomRouteController<Resource = unknown> {this.replanRemaining(operation);}while (operation.cursor < operation.candidates.length &&- !this.candidateValid(operation.childPeerId, operation.candidates[operation.cursor]!)) {+ !this.operationCandidateValid(operation, operation.candidates[operation.cursor]!)) {this.noteRejection(operation.demandPeerId, "stale");if (operation.reason === "direct-convergence") {this.consumeDirectContinuationCandidate(operation);@@ -2299,17 +2381,19 @@ export class RoomRouteController<Resource = unknown> {operation.childPeerId,nowMs,rejectionBucket,+ operation.candidates[+ Math.min(operation.cursor, operation.candidates.length - 1)+ ],): undefined;const bootstrapAvailable =!backgroundConvergence &&!sfuBootstrap &&- !factsChanged &&this.bootstrapCandidateAvailable(operation.demandPeerId);+ if (!bootstrapAvailable) this.consumeAvailabilityOperation(operation);const exhausted = sfuBootstrap? failedBootstrapDemand !== undefined: !backgroundConvergence &&- !factsChanged &&!bootstrapAvailable;if (bootstrapAvailable) this.stageSfuBootstrap(operation);if (!sfuBootstrap) {@@ -2335,8 +2419,7 @@ export class RoomRouteController<Resource = unknown> {this.blockAndClear(operation,!backgroundConvergence &&- !sfuBootstrap &&- !factsChanged,+ !sfuBootstrap,released,this.revision !== activeRevisionAtStart,);@@ -2454,10 +2537,11 @@ export class RoomRouteController<Resource = unknown> {}const participant = this.participants.get(operation.childPeerId);if (participant) {- participant.blockedAtFactVersion = undefined;- participant.failedTuple = undefined;+ participant.availabilityExhausted = false;+ participant.bootstrapFailureReported = undefined;}if (old?.kind === "sfu" && !this.hasSfuSubscribers() && this.hostPublication) {+ this.clearSfuCandidateOpportunities();this.hostPublication = null;}if (@@ -2469,7 +2553,7 @@ export class RoomRouteController<Resource = unknown> {demand.sfuFirstAtNextRoute = true;}this.sfuBootstrapIntent = undefined;- this.sfuBootstrapExhaustedAtFactVersion = undefined;+ this.consumedSfuBootstrapOpportunities.clear();} else if (this.usableRoute(operation.demandPeerId)) {this.clearSfuBootstrapForDemand(operation.demandPeerId);}@@ -2491,10 +2575,16 @@ export class RoomRouteController<Resource = unknown> {childPeerId: string,sfuOnly: boolean,): CandidatePlan[] {- const child = this.participants.get(childPeerId)!;- const failedKey = child.failedTuple?.factVersion === this.factVersion- ? child.failedTuple.key- : undefined;+ return this.buildCandidatePlans(childPeerId, sfuOnly).filter(+ (candidate) =>+ this.candidateOpportunityAvailable(childPeerId, candidate),+ );+ }++ private buildCandidatePlans(+ childPeerId: string,+ sfuOnly: boolean,+ ): CandidatePlan[] {const descendants = this.descendantsOf(childPeerId);const parents = [...this.participants.values()].filter((parent) => parent.sessionId && !parent.departureConfirmed && parent.peerId !== childPeerId &&@@ -2526,13 +2616,95 @@ export class RoomRouteController<Resource = unknown> {? [directCandidates[0]!, sfuCandidate, ...directCandidates.slice(1)]: [sfuCandidate]: [...directCandidates, ...(sfuCandidate ? [sfuCandidate] : [])];- return candidates.filter((candidate, index, all) => tupleKey(candidate) !== failedKey &&+ return candidates.filter((candidate, index, all) =>all.findIndex((other) => tupleKey(other) === tupleKey(candidate)) === index).map((candidate) => this.planCandidate(childPeerId, candidate)).filter((candidate): candidate is CandidatePlan => candidate !== null &&this.candidateValid(childPeerId, candidate));}+ private candidateOpportunityAvailable(+ childPeerId: string,+ plan: CandidatePlan,+ ): boolean {+ const consumed = this.participants+ .get(childPeerId)+ ?.consumedCandidateOpportunities.get(+ this.candidateOpportunityBase(childPeerId, plan),+ );+ return (+ consumed === undefined ||+ endpointTransitionRank(plan.endpointTransition) < consumed+ );+ }++ private candidateOpportunityBase(+ childPeerId: string,+ plan: CandidatePlan,+ ): string {+ const childSessionId =+ this.participants.get(childPeerId)?.sessionId ?? "";+ if (plan.tuple.kind === "peer") {+ return `${tupleKey(plan.tuple)}\0${childSessionId}\0${+ this.participants.get(plan.tuple.parentPeerId)?.sessionId ?? ""+ }`;+ }+ const publicationGeneration =+ plan.tuple.publication === "create"+ ? ""+ : (this.hostPublication?.generation ?? "");+ return `${tupleKey(plan.tuple)}\0${childSessionId}\0${+ this.participants.get(this.options.hostPeerId)?.sessionId ?? ""+ }\0${publicationGeneration}`;+ }++ private consumeCandidateOpportunity(+ childPeerId: string,+ plan: CandidatePlan,+ ): void {+ const consumed = this.participants.get(+ childPeerId,+ )?.consumedCandidateOpportunities;+ if (!consumed) return;+ consumeOpportunity(+ consumed,+ this.candidateOpportunityBase(childPeerId, plan),+ endpointTransitionRank(plan.endpointTransition),+ );+ }++ private consumeActiveEdgeOpportunity(+ child: Participant,+ edge: CommittedEdge<Resource>,+ ): void {+ const base =+ edge.kind === "peer"+ ? `peer:${edge.parentPeerId}\0${child.sessionId ?? ""}\0${+ edge.parentSessionId+ }`+ : `sfu:reuse\0${child.sessionId ?? ""}\0${+ this.hostPublication?.hostSessionId ?? ""+ }\0${edge.publicationGeneration}`;+ consumeOpportunity(child.consumedCandidateOpportunities, base, 0);+ }++ private consumeAvailabilityOperation(+ operation: ChildOperation<Resource>,+ ): void {+ if (!this.isAvailabilityOperation(operation.reason)) return;+ for (const plan of operation.candidates) {+ this.consumeCandidateOpportunity(operation.childPeerId, plan);+ }+ }++ private consumeCurrentAvailabilityOpportunity(+ operation: ChildOperation<Resource>,+ ): void {+ if (!this.isAvailabilityOperation(operation.reason)) return;+ const plan = operation.candidates[operation.cursor];+ if (plan) this.consumeCandidateOpportunity(operation.childPeerId, plan);+ }+private senderQualityState(childPeerId: string,edge: CommittedEdge<Resource>,@@ -2555,6 +2727,21 @@ export class RoomRouteController<Resource = unknown> {: "unknown";}+ private candidateSenderPersistentlyDegraded(+ attempt: Attempt<Resource>,+ nowMs: number,+ ): boolean {+ return Boolean(+ attempt.senderQualityState === "degraded" &&+ attempt.senderQualityAcceptedAtMs !== undefined &&+ nowMs <+ attempt.senderQualityAcceptedAtMs ++ VIEWER_QUALITY_EVIDENCE_EXPIRY_MS &&+ (attempt.senderQualityConsecutiveDegradedWindows ?? 0) >=+ PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS,+ );+ }+private sfuPublisherQualityState(publicationGeneration: string,nowMs: number,@@ -2634,7 +2821,7 @@ export class RoomRouteController<Resource = unknown> {return [];}const currentKey = edgeTupleKey(current);- const candidates = this.buildCandidates(childPeerId, false).filter(+ const candidates = this.buildCandidatePlans(childPeerId, false).filter((candidate) =>candidate.endpointTransition.kind !== "bounded-gap" &&tupleKey(candidate.tuple) !== currentKey &&@@ -2943,6 +3130,10 @@ export class RoomRouteController<Resource = unknown> {);}+ private isAvailabilityOperation(reason: RouteDemandReason): boolean {+ return reason !== "sfu-bootstrap" && !this.isBackgroundConvergence(reason);+ }+private operationRequiresNativeCandidateProof(operation: ChildOperation<Resource> | undefined,): operation is ChildOperation<Resource> {@@ -2983,7 +3174,6 @@ export class RoomRouteController<Resource = unknown> {if (!intent) return undefined;const carrierPeerId = this.safeSfuBootstrapCarriers(intent.demandPeerId,- intent.triedCarrierPeerIds,)[0];return carrierPeerId? {@@ -2995,71 +3185,51 @@ export class RoomRouteController<Resource = unknown> {}private hasSfuBootstrapWork(): boolean {- if (- this.sfuBootstrapExhaustedAtFactVersion === this.factVersion- ) {- return this.availableViewers(true).some(- (viewer) =>- viewer.blockedAtFactVersion === this.factVersion &&- viewer.bootstrapFailureAtFactVersion !== this.factVersion,- );- }- return this.currentSfuBootstrapIntent() !== undefined;+ if (this.currentSfuBootstrapIntent()) return true;+ return this.availableViewers(true).some(+ (viewer) =>+ viewer.availabilityExhausted &&+ this.sfuBootstrapNeeded(viewer.peerId) &&+ (this.safeSfuBootstrapCarriers(viewer.peerId).length > 0 ||+ viewer.bootstrapFailureReported !== true),+ );}private takeSfuBootstrapCarrier(nowMs: number,failedPeerIds: string[],): SfuBootstrapCarrier | undefined {- if (- this.sfuBootstrapExhaustedAtFactVersion === this.factVersion &&- this.sfuBootstrapGloballyNeeded()- ) {- this.reportSfuBootstrapFailures(nowMs, failedPeerIds);- return undefined;- }+ if (!this.sfuBootstrapGloballyNeeded()) return undefined;const carrier = this.peekSfuBootstrapCarrier();if (carrier) return carrier;- if (!this.currentSfuBootstrapIntent()) return undefined;this.sfuBootstrapIntent = undefined;- this.sfuBootstrapExhaustedAtFactVersion = this.factVersion;this.reportSfuBootstrapFailures(nowMs, failedPeerIds);return undefined;}private currentSfuBootstrapIntent(): SfuBootstrapIntent | undefined {- if (- this.sfuBootstrapExhaustedAtFactVersion !== undefined &&- this.sfuBootstrapExhaustedAtFactVersion !== this.factVersion- ) {- this.sfuBootstrapExhaustedAtFactVersion = undefined;- }- if (this.sfuBootstrapExhaustedAtFactVersion === this.factVersion) {- return undefined;- }const current = this.sfuBootstrapIntent;if (current) {const demand = this.participants.get(current.demandPeerId);if (this.sfuBootstrapNeeded(current.demandPeerId) &&- demand?.sessionId === current.demandSessionId+ demand?.sessionId === current.demandSessionId &&+ this.safeSfuBootstrapCarriers(current.demandPeerId).length > 0) {- current.factVersion = this.factVersion;return current;}this.sfuBootstrapIntent = undefined;}const demand = this.availableViewers(true).find((viewer) =>- viewer.blockedAtFactVersion === this.factVersion &&- this.sfuBootstrapNeeded(viewer.peerId),+ viewer.availabilityExhausted &&+ this.sfuBootstrapNeeded(viewer.peerId) &&+ this.safeSfuBootstrapCarriers(viewer.peerId).length > 0,);if (!demand?.sessionId) return undefined;const created: SfuBootstrapIntent = {demandPeerId: demand.peerId,demandSessionId: demand.sessionId,- factVersion: this.factVersion,- triedCarrierPeerIds: new Set(),};this.sfuBootstrapIntent = created;return created;@@ -3078,13 +3248,9 @@ export class RoomRouteController<Resource = unknown> {) {return false;}- if (intent.factVersion !== this.factVersion) {- intent.factVersion = this.factVersion;- }- return this.safeSfuBootstrapCarriers(- operation.demandPeerId,- intent.triedCarrierPeerIds,- ).includes(operation.childPeerId);+ return this.safeSfuBootstrapCarriers(operation.demandPeerId).includes(+ operation.childPeerId,+ );}private sfuBootstrapNeeded(demandPeerId: string): boolean {@@ -3105,16 +3271,18 @@ export class RoomRouteController<Resource = unknown> {private safeSfuBootstrapCarriers(demandPeerId: string,- triedCarrierPeerIds?: ReadonlySet<string>,): string[] {if (!this.sfuBootstrapNeeded(demandPeerId)) return [];+ return this.sfuBootstrapCarriers();+ }++ private sfuBootstrapCarriers(): string[] {const tuple: Extract<CandidateTuple, { kind: "sfu" }> = {kind: "sfu",publication: "create",};return this.childrenOf(this.options.hostPeerId).filter((peerId) => {- if (triedCarrierPeerIds?.has(peerId)) return false;const participant = this.participants.get(peerId);const edge = this.upstreamByViewer.get(peerId);const plan = this.planCandidate(peerId, tuple);@@ -3125,7 +3293,11 @@ export class RoomRouteController<Resource = unknown> {edge.usable &&edge.physicalActive &&plan &&- plan.endpointTransition.kind !== "bounded-gap",+ plan.endpointTransition.kind !== "bounded-gap" &&+ this.sfuBootstrapOpportunityAvailable(+ peerId,+ plan,+ ),);}).sort((left, right) =>@@ -3136,33 +3308,67 @@ export class RoomRouteController<Resource = unknown> {);}+ private sfuBootstrapOpportunityAvailable(+ carrierPeerId: string,+ plan: CandidatePlan,+ ): boolean {+ const consumed = this.consumedSfuBootstrapOpportunities.get(+ this.sfuBootstrapOpportunityBase(carrierPeerId, plan),+ );+ return (+ consumed === undefined ||+ endpointTransitionRank(plan.endpointTransition) < consumed+ );+ }++ private sfuBootstrapOpportunityBase(+ carrierPeerId: string,+ plan: CandidatePlan,+ ): string {+ return `${carrierPeerId}\0${this.candidateOpportunityBase(+ carrierPeerId,+ plan,+ )}`;+ }++ private consumeSfuBootstrapOpportunity(+ carrierPeerId: string,+ plan: CandidatePlan,+ ): void {+ consumeOpportunity(+ this.consumedSfuBootstrapOpportunities,+ this.sfuBootstrapOpportunityBase(carrierPeerId, plan),+ endpointTransitionRank(plan.endpointTransition),+ );+ }+private completeSfuBootstrapCarrier(carrierPeerId: string,nowMs: number,bucket: RouteDiagnosticRejectionBucket,+ attemptedPlan?: CandidatePlan,): string | undefined {const intent = this.sfuBootstrapIntent;- if (- !intent ||- intent.factVersion !== this.factVersion- ) {- return undefined;+ if (!intent) return undefined;+ const plan = attemptedPlan ?? this.planCandidate(carrierPeerId, {+ kind: "sfu",+ publication: "create",+ });+ if (plan) {+ this.consumeSfuBootstrapOpportunity(+ carrierPeerId,+ plan,+ );+ this.consumeCandidateOpportunity(carrierPeerId, plan);}- intent.triedCarrierPeerIds.add(carrierPeerId);- if (- this.safeSfuBootstrapCarriers(- intent.demandPeerId,- intent.triedCarrierPeerIds,- ).length > 0- ) {+ if (this.safeSfuBootstrapCarriers(intent.demandPeerId).length > 0) {return undefined;}const demand = this.participants.get(intent.demandPeerId);- if (demand) demand.blockedAtFactVersion = this.factVersion;+ if (demand) demand.availabilityExhausted = true;this.finishTiming(intent.demandPeerId, nowMs, "failed", bucket);- if (demand) demand.bootstrapFailureAtFactVersion = this.factVersion;+ if (demand) demand.bootstrapFailureReported = true;this.sfuBootstrapIntent = undefined;- this.sfuBootstrapExhaustedAtFactVersion = this.factVersion;return intent.demandPeerId;}@@ -3172,13 +3378,14 @@ export class RoomRouteController<Resource = unknown> {): void {for (const demand of this.availableViewers(true)) {if (- demand.blockedAtFactVersion !== this.factVersion ||+ !demand.availabilityExhausted ||+ !this.sfuBootstrapNeeded(demand.peerId) ||this.usableRoute(demand.peerId) ||- demand.bootstrapFailureAtFactVersion === this.factVersion+ demand.bootstrapFailureReported === true) {continue;}- demand.bootstrapFailureAtFactVersion = this.factVersion;+ demand.bootstrapFailureReported = true;this.finishTiming(demand.peerId, nowMs, "failed", "candidate-failed");failedPeerIds.push(demand.peerId);}@@ -3188,15 +3395,8 @@ export class RoomRouteController<Resource = unknown> {if (!this.sfuBootstrapNeeded(demandPeerId)) return;const demand = this.participants.get(demandPeerId);if (!demand?.sessionId) return;- if (- this.sfuBootstrapExhaustedAtFactVersion === this.factVersion- ) {- demand.bootstrapFailureAtFactVersion = this.factVersion;- return;- }- demand.bootstrapFailureAtFactVersion = this.factVersion;+ demand.bootstrapFailureReported = true;this.sfuBootstrapIntent = undefined;- this.sfuBootstrapExhaustedAtFactVersion = this.factVersion;}private stageSfuBootstrap(@@ -3204,20 +3404,17 @@ export class RoomRouteController<Resource = unknown> {): void {const demand = this.participants.get(operation.demandPeerId);if (!demand?.sessionId || !this.sfuBootstrapNeeded(demand.peerId)) return;- if (this.sfuBootstrapExhaustedAtFactVersion === this.factVersion) return;+ if (this.safeSfuBootstrapCarriers(demand.peerId).length === 0) return;const current = this.sfuBootstrapIntent;if (current?.demandPeerId === demand.peerId &&- current.demandSessionId === demand.sessionId &&- current.factVersion === this.factVersion+ current.demandSessionId === demand.sessionId) {return;}this.sfuBootstrapIntent = {demandPeerId: demand.peerId,demandSessionId: demand.sessionId,- factVersion: this.factVersion,- triedCarrierPeerIds: new Set(),};}@@ -3229,10 +3426,17 @@ export class RoomRouteController<Resource = unknown> {}}+ private participantBlocked(participant: Participant): boolean {+ return Boolean(+ participant.availabilityExhausted &&+ this.buildCandidates(participant.peerId, false).length === 0,+ );+ }+private availableViewers(includeBlocked = false): Participant[] {return [...this.participants.values()].filter((participant) => participant.role === "viewer" &&participant.sessionId && !participant.departureConfirmed &&- (includeBlocked || participant.blockedAtFactVersion !== this.factVersion))+ (includeBlocked || !this.participantBlocked(participant))).sort(compareParticipant);}@@ -3241,7 +3445,8 @@ export class RoomRouteController<Resource = unknown> {for (const parent of this.participants.values()) {const overflow = this.overflowPeerChildren(parent.peerId).filter((id) => {const child = this.participants.get(id);- return child?.sessionId && !child.departureConfirmed && child.blockedAtFactVersion !== this.factVersion;+ return child?.sessionId && !child.departureConfirmed &&+ !this.participantBlocked(child);});result.push(...overflow.reverse());}@@ -3293,6 +3498,18 @@ export class RoomRouteController<Resource = unknown> {return Boolean(currentPlan && endpointTransitionEquals(currentPlan.endpointTransition, plan.endpointTransition));}+ private operationCandidateValid(+ operation: ChildOperation<Resource>,+ plan: CandidatePlan,+ attempt?: Attempt<Resource>,+ ): boolean {+ return (+ this.candidateValid(operation.childPeerId, plan, attempt) &&+ (!this.isAvailabilityOperation(operation.reason) ||+ this.candidateOpportunityAvailable(operation.childPeerId, plan))+ );+ }+private planCandidate(childPeerId: string, tuple: CandidateTuple): CandidatePlan | null {if (tuple.kind === "sfu" && tuple.publication === "reuse") {return { tuple, endpointTransition: { kind: "none" } };@@ -3381,6 +3598,7 @@ export class RoomRouteController<Resource = unknown> {if (!this.hasSfuSubscribers() && this.hostPublication) {this.clearSfuQuality();if (this.hostPublication.physicalActive) released.push(this.hostPublication.resource);+ this.clearSfuCandidateOpportunities();this.hostPublication = null;}this.revision = this.allocateRevision();@@ -3460,7 +3678,7 @@ export class RoomRouteController<Resource = unknown> {this.touchFacts();}if (!block || !child) return;- child.blockedAtFactVersion = this.factVersion;+ child.availabilityExhausted = true;}private retireInvalidOperationEdge(childPeerId: string, released: Resource[]): boolean {@@ -3506,7 +3724,10 @@ export class RoomRouteController<Resource = unknown> {}const replanned = tuples.map((tuple) => this.planCandidate(operation.childPeerId, tuple))- .filter((plan): plan is CandidatePlan => plan !== null);+ .filter(+ (plan): plan is CandidatePlan =>+ plan !== null && this.operationCandidateValid(operation, plan),+ );operation.candidates = [...prefix, ...replanned];operation.builtAtFactVersion = this.factVersion;}@@ -3549,6 +3770,12 @@ export class RoomRouteController<Resource = unknown> {: null;if (operation.current) {this.noteRejection(operation.demandPeerId, "first-frame-timeout");+ if (this.isAvailabilityOperation(operation.reason)) {+ this.consumeCandidateOpportunity(+ operation.childPeerId,+ operation.candidates[operation.cursor]!,+ );+ }released.push(...reservationResources(operation.current.reservation));this.advanceActiveRevision(operation);operation.current = undefined;@@ -3641,11 +3868,6 @@ export class RoomRouteController<Resource = unknown> {}private bootstrapCandidateAvailable(demandPeerId: string): boolean {- if (- this.sfuBootstrapExhaustedAtFactVersion === this.factVersion- ) {- return false;- }return this.safeSfuBootstrapCarriers(demandPeerId).length > 0;}@@ -3871,6 +4093,51 @@ export class RoomRouteController<Resource = unknown> {});}+ private clearOpportunitiesForSessionChange(+ peerId: string,+ role: Participant["role"],+ ): void {+ const participant = this.participants.get(peerId);+ if (participant) {+ participant.consumedCandidateOpportunities.clear();+ participant.availabilityExhausted = false;+ participant.bootstrapFailureReported = undefined;+ }+ const parentPrefix = `peer:${peerId}\0`;+ for (const child of this.participants.values()) {+ for (const key of child.consumedCandidateOpportunities.keys()) {+ if (+ key.startsWith(parentPrefix) ||+ (role === "host" && key.startsWith("sfu:"))+ ) {+ child.consumedCandidateOpportunities.delete(key);+ }+ }+ }+ if (role === "host") {+ this.consumedSfuBootstrapOpportunities.clear();+ } else {+ const carrierPrefix = `${peerId}\0`;+ for (const key of this.consumedSfuBootstrapOpportunities.keys()) {+ if (key.startsWith(carrierPrefix)) {+ this.consumedSfuBootstrapOpportunities.delete(key);+ }+ }+ }+ }++ private clearSfuCandidateOpportunities(): void {+ for (const participant of this.participants.values()) {+ for (const key of participant.consumedCandidateOpportunities.keys()) {+ if (key.startsWith("sfu:")) {+ participant.consumedCandidateOpportunities.delete(key);+ }+ }+ participant.bootstrapFailureReported = undefined;+ }+ this.consumedSfuBootstrapOpportunities.clear();+ }+private requireSenderQualityBaseline(peerId: string,suppressFact = false,@@ -3906,10 +4173,6 @@ export class RoomRouteController<Resource = unknown> {finalRoute: "waiting",rejectionBucket: "none",};- if (this.operation?.demandPeerId === childPeerId) {- this.operation.reason = reason;- record.operationStartedAtMs = nowMs;- }this.routeTimings.set(childPeerId, record);}@@ -4044,6 +4307,7 @@ export class RoomRouteController<Resource = unknown> {if (this.hostPublication.physicalActive) released.push(this.hostPublication.resource);this.hostPublication = null;}+ this.clearSfuCandidateOpportunities();return released;}@@ -4164,6 +4428,23 @@ function edgeTupleKey<Resource>(edge: CommittedEdge<Resource>): string {return edge.kind === "peer" ? `peer:${edge.parentPeerId}` : "sfu:reuse";}+function endpointTransitionRank(transition: EndpointTransition): number {+ return transition.kind === "none"+ ? 0+ : transition.kind === "overlap"+ ? 1+ : 2;+}++function consumeOpportunity(+ consumed: Map<string, number>,+ base: string,+ rank: number,+): void {+ const previous = consumed.get(base);+ if (previous === undefined || rank < previous) consumed.set(base, rank);+}+function cloneCandidatePlan(plan: CandidatePlan): CandidatePlan {return {tuple: { ...plan.tuple },diff --git a/src/server/room-store.ts b/src/server/room-store.tsindex 81f35ea3..1ad73016 100644--- a/src/server/room-store.ts+++ b/src/server/room-store.ts@@ -651,13 +651,20 @@ export class RoomStore {expireRooms(nowMs = this.now()): ClosedRoom[] {this.ensureInitialized();- const expired: ClosedRoom[] = [];- for (const [roomId, room] of this.rooms) {- if (!roomIsExpired(room, nowMs)) {- continue;- }- this.options.database?.deleteRoom(roomId, room.hostTokenDigest);- expired.push({ roomId, sessionIds: connectedSessionIds(room) });+ const expiredRooms = [...this.rooms].filter(([, room]) =>+ roomIsExpired(room, nowMs),+ );+ this.options.database?.deleteRooms(+ expiredRooms.map(([roomId, room]) => ({+ roomId,+ hostTokenDigest: room.hostTokenDigest,+ })),+ );+ const expired = expiredRooms.map(([roomId, room]) => ({+ roomId,+ sessionIds: connectedSessionIds(room),+ }));+ for (const [roomId] of expiredRooms) {this.rooms.delete(roomId);this.releaseRoomCode(roomId);}diff --git a/src/server/sfu-resource-admission.ts b/src/server/sfu-resource-admission.tsindex c77bf1d7..e80fa03a 100644--- a/src/server/sfu-resource-admission.ts+++ b/src/server/sfu-resource-admission.ts@@ -147,7 +147,7 @@ export class SfuResourceAdmission {return true;}- releaseSubscription(fence: SfuSubscriptionFence): boolean {+ beginSubscriptionDrain(fence: SfuSubscriptionFence): boolean {assertSubscriptionFence(fence);const publication = this.publication(fence);const subscription = publication?.subscriptions.get(fence.viewerPeerId);@@ -158,11 +158,7 @@ export class SfuResourceAdmission {) {return false;}- if (subscription.state === "reserved") {- subscription.state = "draining";- return true;- }- if (subscription.state === "committed") {+ if (subscription.state !== "draining") {subscription.state = "draining";}return true;diff --git a/src/server/sfu-room-control.ts b/src/server/sfu-room-control.tsindex e3281dac..fd4f345d 100644--- a/src/server/sfu-room-control.ts+++ b/src/server/sfu-room-control.ts@@ -1,7 +1,10 @@import { RoomServiceClient, ServerError } from "livekit-server-sdk";import { MAX_VIEWERS_PER_ROOM_LIMIT } from "../shared/protocol.js";-import type { SfuResourceFence } from "./sfu-resource-admission.js";+import type {+ SfuResourceFence,+ SfuSubscriptionFence,+} from "./sfu-resource-admission.js";const MANAGED_ROOM_PREFIX = "screener-v1.";const ROOM_ID_PATTERN = /^[1-9]\d{0,11}$/;@@ -25,12 +28,14 @@ export interface LiveKitRoomService {listRooms(names?: string[]): Promise<LiveKitRoomRecord[]>;deleteRoom(room: string): Promise<void>;listParticipants(room: string): Promise<LiveKitParticipantRecord[]>;+ removeParticipant(room: string, identity: string): Promise<void>;}export interface SfuRoomControl {initialize(): Promise<void>;createRoom(fence: SfuResourceFence): Promise<void>;deleteRoom(fence: SfuResourceFence): Promise<void>;+ drainSubscription(fence: SfuSubscriptionFence): Promise<void>;hostParticipantExists(fence: SfuResourceFence): Promise<boolean>;}@@ -112,22 +117,30 @@ export class LiveKitSfuRoomControl implements SfuRoomControl {});}- hostParticipantExists(fence: SfuResourceFence): Promise<boolean> {+ drainSubscription(fence: SfuSubscriptionFence): Promise<void> {const roomName = managedSfuRoomName(fence);+ const identity = managedSfuViewerIdentity(fence.viewerPeerId);return this.serialize(roomName, async () => {try {- return (await this.roomService.listParticipants(roomName)).some(- (participant) => participant.identity === "host",- );+ await this.roomService.removeParticipant(roomName, identity);} catch (error) {- if (isNotFound(error)) {- return false;+ if (!isNotFound(error)) {+ throw error;}- throw error;+ }+ if (await this.participantExists(roomName, identity)) {+ throw new Error("Managed LiveKit participant removal was not confirmed");}});}+ hostParticipantExists(fence: SfuResourceFence): Promise<boolean> {+ const roomName = managedSfuRoomName(fence);+ return this.serialize(roomName, () =>+ this.participantExists(roomName, "host"),+ );+ }+private async deleteRoomByName(roomName: string): Promise<void> {try {await this.roomService.deleteRoom(roomName);@@ -138,6 +151,22 @@ export class LiveKitSfuRoomControl implements SfuRoomControl {}}+ private async participantExists(+ roomName: string,+ identity: string,+ ): Promise<boolean> {+ try {+ return (await this.roomService.listParticipants(roomName)).some(+ (participant) => participant.identity === identity,+ );+ } catch (error) {+ if (isNotFound(error)) {+ return false;+ }+ throw error;+ }+ }+private serialize<Result>(roomName: string,operation: () => Promise<Result>,@@ -169,6 +198,13 @@ export function managedSfuRoomName(fence: SfuResourceFence): string {return `${MANAGED_ROOM_PREFIX}${fence.roomId}.${fence.shareGeneration}.${fence.publicationGeneration}`;}+function managedSfuViewerIdentity(peerId: string): string {+ if (!OPAQUE_ID_PATTERN.test(peerId)) {+ throw new Error("Managed LiveKit Viewer identity is invalid");+ }+ return `viewer:${peerId}`;+}+export function isManagedSfuRoomName(roomName: string): boolean {if (LEGACY_MANAGED_ROOM_PATTERN.test(roomName)) {return true;diff --git a/src/server/signaling.ts b/src/server/signaling.tsindex 636825ef..c93369af 100644--- a/src/server/signaling.ts+++ b/src/server/signaling.ts@@ -52,7 +52,6 @@ interface AuthenticatedSession {roomId: string;role: Role;peerId: string;- roomExpiresAtMs: number | null;shareGeneration: string | null;displayName: string | null;viewerPresence: boolean;@@ -428,13 +427,6 @@ export class SignalingServer {return;}- if (- state.authenticated.roomExpiresAtMs !== null &&- this.now() >= state.authenticated.roomExpiresAtMs- ) {- this.expireRooms();- return;- }if (!this.isCurrentSession(state)) {socket.close(SIGNAL_CLOSE_CODES.sessionReplaced, "Session replaced");return;@@ -616,10 +608,6 @@ export class SignalingServer {roomId: participant.roomId,role: participant.role,peerId: participant.peerId,- roomExpiresAtMs:- participant.expiresAt === null- ? null- : Date.parse(participant.expiresAt),shareGeneration,displayName:message.role === "host"diff --git a/tests/candidate-quality-probe.test.ts b/tests/candidate-quality-probe.test.tsindex f7b8d47b..7fe167c4 100644--- a/tests/candidate-quality-probe.test.ts+++ b/tests/candidate-quality-probe.test.ts@@ -130,42 +130,62 @@ describe("SFU quality probe", () => {frameHeight: 720,framesPerSecond: 30,});- expect(probe.observe(current(1_000), candidate(1_100))).toBe(false);- expect(probe.observe(current(3_000), candidate(3_100))).toBe(false);- expect(probe.observe(current(5_000), candidate(5_100))).toBe(true);+ expect(probe.observe(current(1_000), candidate(1_100))).toBe("pending");+ expect(probe.observe(current(3_000), candidate(3_100))).toBe("pending");+ expect(probe.observe(current(5_000), candidate(5_100))).toBe("approved");probe.reset();- expect(probe.observe(current(7_000), candidate(7_100))).toBe(false);+ expect(probe.observe(current(7_000), candidate(7_100))).toBe("pending");+ });++ it("rejects after three comparable non-improving P2P windows", () => {+ const probe = new P2pQualityProbe();+ expect(probe.observe(metrics(1_000), metrics(1_100))).toBe("pending");+ expect(probe.observe(metrics(3_000), metrics(3_100))).toBe("pending");+ expect(probe.observe(metrics(5_000), metrics(5_100))).toBe("rejected");+ });++ it("keeps unknown evidence pending instead of counting it as rejection", () => {+ const probe = new P2pQualityProbe();+ expect(probe.observe(metrics(1_000), metrics(1_100))).toBe("pending");+ expect(probe.observe(metrics(3_000), metrics(3_100))).toBe("pending");+ expect(+ probe.observe(+ metrics(5_000),+ metrics(5_100, { intervalFreezeCount: null }),+ ),+ ).toBe("pending");+ expect(probe.observe(metrics(7_000), metrics(7_100))).toBe("pending");});it("requires three consecutive windows and resets after a regression", () => {const probe = new SfuQualityProbe();- expect(probe.observe(metrics(1_000), metrics(1_100))).toBe(false);- expect(probe.observe(metrics(3_000), metrics(3_100))).toBe(false);+ expect(probe.observe(metrics(1_000), metrics(1_100))).toBe("pending");+ expect(probe.observe(metrics(3_000), metrics(3_100))).toBe("pending");expect(probe.observe(metrics(5_000), metrics(5_100, { framesPerSecond: 30 })),- ).toBe(false);- expect(probe.observe(metrics(7_000), metrics(7_100))).toBe(false);- expect(probe.observe(metrics(9_000), metrics(9_100))).toBe(false);- expect(probe.observe(metrics(11_000), metrics(11_100))).toBe(true);+ ).toBe("pending");+ expect(probe.observe(metrics(7_000), metrics(7_100))).toBe("pending");+ expect(probe.observe(metrics(9_000), metrics(9_100))).toBe("pending");+ expect(probe.observe(metrics(11_000), metrics(11_100))).toBe("approved");});it("resets when either side lacks a new comparable window", () => {const probe = new SfuQualityProbe();- expect(probe.observe(metrics(1_000), metrics(1_100))).toBe(false);- expect(probe.observe(metrics(3_000), metrics(3_100))).toBe(false);- expect(probe.observe(metrics(3_000), metrics(5_100))).toBe(false);- expect(probe.observe(metrics(7_000), metrics(7_100))).toBe(false);- expect(probe.observe(metrics(9_000), metrics(9_100))).toBe(false);- expect(probe.observe(metrics(11_000), metrics(11_100))).toBe(true);+ expect(probe.observe(metrics(1_000), metrics(1_100))).toBe("pending");+ expect(probe.observe(metrics(3_000), metrics(3_100))).toBe("pending");+ expect(probe.observe(metrics(3_000), metrics(5_100))).toBe("pending");+ expect(probe.observe(metrics(7_000), metrics(7_100))).toBe("pending");+ expect(probe.observe(metrics(9_000), metrics(9_100))).toBe("pending");+ expect(probe.observe(metrics(11_000), metrics(11_100))).toBe("approved");probe.reset();- expect(probe.observe(metrics(13_000), metrics(13_100))).toBe(false);+ expect(probe.observe(metrics(13_000), metrics(13_100))).toBe("pending");expect(probe.observe(metrics(15_000),metrics(15_100, { intervalFreezeDurationMs: null }),),- ).toBe(false);- expect(probe.observe(metrics(17_000), metrics(17_100))).toBe(false);+ ).toBe("pending");+ expect(probe.observe(metrics(17_000), metrics(17_100))).toBe("pending");});});diff --git a/tests/decoded-frame-stall.test.ts b/tests/decoded-frame-stall.test.tsindex 4a0f4e77..92d48e27 100644--- a/tests/decoded-frame-stall.test.ts+++ b/tests/decoded-frame-stall.test.ts@@ -8,24 +8,42 @@ import {describe("DecodedFrameStallDetector", () => {it("reports one exact active stall and resets on progress or identity change", () => {const detector = new DecodedFrameStallDetector();- expect(detector.observe("peer:1:a", null, 0)).toBe(false);+ expect(detector.observe("peer:a", 0, 0)).toBe(false);expect(- detector.observe("peer:1:a", 0, ROUTE_DECODED_FRAME_STALL_MS),+ detector.observe("peer:a", 0, ROUTE_DECODED_FRAME_STALL_MS),).toBe(true);expect(- detector.observe("peer:1:a", 0, ROUTE_DECODED_FRAME_STALL_MS + 1),+ detector.observe("peer:a", 0, ROUTE_DECODED_FRAME_STALL_MS + 1),).toBe(false);- expect(detector.observe("peer:1:a", 1, ROUTE_DECODED_FRAME_STALL_MS + 2)).toBe(+ expect(detector.observe("peer:a", 1, ROUTE_DECODED_FRAME_STALL_MS + 2)).toBe(false,);expect(- detector.observe("peer:1:a", 0, ROUTE_DECODED_FRAME_STALL_MS * 2 + 2),+ detector.observe("peer:a", 0, ROUTE_DECODED_FRAME_STALL_MS * 2 + 2),).toBe(true);- expect(detector.observe("sfu:2:b", 0, ROUTE_DECODED_FRAME_STALL_MS * 3)).toBe(+ expect(detector.observe("sfu:b", 0, ROUTE_DECODED_FRAME_STALL_MS * 3)).toBe(false,);});+ it("does not turn unknown samples into elapsed stall evidence", () => {+ const detector = new DecodedFrameStallDetector();+ expect(detector.observe("peer:a", 0, 0)).toBe(false);+ expect(+ detector.observe("peer:a", null, ROUTE_DECODED_FRAME_STALL_MS),+ ).toBe(false);+ expect(+ detector.observe(+ "peer:a",+ 0,+ ROUTE_DECODED_FRAME_STALL_MS * 2 - 1,+ ),+ ).toBe(false);+ expect(+ detector.observe("peer:a", 0, ROUTE_DECODED_FRAME_STALL_MS * 2),+ ).toBe(true);+ });+it("suppresses and rebases progress while paused", () => {const detector = new DecodedFrameStallDetector();detector.observe("peer:1:a", 0, 0);@@ -60,6 +78,13 @@ describe("DecodedFrameStallDetector", () => {0,ROUTE_DECODED_FRAME_STALL_MS * 5,),+ ).toBe(false);+ expect(+ detector.observe(+ "peer:1:a",+ 0,+ ROUTE_DECODED_FRAME_STALL_MS * 6 - 1,+ ),).toBe(true);});diff --git a/tests/fake-sfu-room-control.ts b/tests/fake-sfu-room-control.tsindex d89d0312..2470ac63 100644--- a/tests/fake-sfu-room-control.ts+++ b/tests/fake-sfu-room-control.ts@@ -1,4 +1,7 @@-import type { SfuResourceFence } from "../src/server/sfu-resource-admission.ts";+import type {+ SfuResourceFence,+ SfuSubscriptionFence,+} from "../src/server/sfu-resource-admission.ts";import {managedSfuRoomName,type SfuRoomControl,@@ -8,12 +11,15 @@ export class FakeSfuRoomControl implements SfuRoomControl {readonly rooms = new Map<string, Set<string>>();readonly created: SfuResourceFence[] = [];readonly deleted: SfuResourceFence[] = [];+ readonly subscriptionDrainAttempts: SfuSubscriptionFence[] = [];+ readonly drainedSubscriptions: SfuSubscriptionFence[] = [];readonly startupDeletedRoomNames: string[] = [];initializeCalls = 0;initializeBarrier?: Promise<void>;initializeError?: Error;createBarrier?: Promise<void>;deleteBarrier?: Promise<void>;+ subscriptionDrainBarrier?: Promise<void>;failDelete = false;failHostCheck = false;@@ -46,6 +52,15 @@ export class FakeSfuRoomControl implements SfuRoomControl {this.deleted.push({ ...fence });}+ async drainSubscription(fence: SfuSubscriptionFence): Promise<void> {+ this.subscriptionDrainAttempts.push({ ...fence });+ await this.subscriptionDrainBarrier;+ this.rooms+ .get(managedSfuRoomName(fence))+ ?.delete(`viewer:${fence.viewerPeerId}`);+ this.drainedSubscriptions.push({ ...fence });+ }+async hostParticipantExists(fence: SfuResourceFence): Promise<boolean> {if (this.failHostCheck) {throw new Error("host check failed");diff --git a/tests/host-peer-tracks.test.ts b/tests/host-peer-tracks.test.tsindex 42d116ba..89a6dd04 100644--- a/tests/host-peer-tracks.test.ts+++ b/tests/host-peer-tracks.test.ts@@ -1849,6 +1849,30 @@ describe("ViewerRelay downstream ownership", () => {relay.dispose();});+ it("reconciles a reauthenticated endpoint cap without rebuilding retained children", async () => {+ const relay = new ViewerRelay(+ { iceServers: [] },+ QUALITY_PROFILES["720p30"],+ { sendSignal: () => true },+ 3,+ );+ relay.setStream(createStream(createTrack("video", "cap-update-video"), null));+ relay.setChildren(["child-0", "child-1", "child-2"]);+ await vi.waitFor(() => expect(FakePeerConnection.instances).toHaveLength(3));+ const retained = FakePeerConnection.instances.slice(0, 2);+ const removed = FakePeerConnection.instances[2]!;+ retained.forEach((connection) => {+ connection.connectionState = "connected";+ });++ relay.updateCapacity(2);++ expect(FakePeerConnection.instances.slice(0, 2)).toEqual(retained);+ expect(removed.connectionState).toBe("closed");+ expect(FakePeerConnection.activeCount).toBe(2);+ relay.dispose();+ });+it("exposes a defensive snapshot of current downstream send metrics", async () => {const relay = new ViewerRelay({ iceServers: [] },diff --git a/tests/hybrid-media-router.test.ts b/tests/hybrid-media-router.test.tsindex e0b1737b..3ee74092 100644--- a/tests/hybrid-media-router.test.ts+++ b/tests/hybrid-media-router.test.ts@@ -106,11 +106,26 @@ function activeAfter();}+function deferred(): {+ promise: Promise<void>;+ resolve: () => void;+ reject: (reason?: unknown) => void;+} {+ let resolve!: () => void;+ let reject!: (reason?: unknown) => void;+ const promise = new Promise<void>((settle, fail) => {+ resolve = settle;+ reject = fail;+ });+ return { promise, resolve, reject };+}+function harness(endpointMediaCopyCapacity: 1 | 2 | 3,withSfu = false,prepareTimeoutMs?: number,sfuIngressCapacity = 2,+ drainRetryMs?: number,) {const store = createStore();const sent = new Map<string, ServerMessage[]>();@@ -134,6 +149,7 @@ function harness(admission,roomControl,...(prepareTimeoutMs ? { prepareTimeoutMs } : {}),+ ...(drainRetryMs ? { drainRetryMs } : {}),tokenIssuer: {async issueToken({ peerId }) {if (nextTokenIssueError) {@@ -218,6 +234,113 @@ async function establishSfuRoom(}describe("HybridMediaRouter v9 runtime", () => {+ it("maps an exact Host active failure to its committed direct edge", async () => {+ const { store, sent, router } = harness(2);+ try {+ const room = await store.createRoom();+ const host = connectHost(store, room);+ complete(router, host);+ const viewer = connectViewer(store, room, "host-edge-failure");+ complete(router, viewer);+ await vi.waitFor(() =>+ expect(preparedFor(sent, viewer.sessionId)).toBeDefined(),+ );+ const prepared = preparedFor(sent, viewer.sessionId)!;+ router.handleRouteReady(viewer, {+ type: "route-ready",+ revision: prepared.revision,+ phase: "prepare",+ });+ const active = router.resolveActiveViewerMediaEdge(+ room.roomId,+ viewer.peerId,+ )!;++ router.handleRouteFailed(host, {+ type: "route-failed",+ revision: active.revision,+ phase: "active",+ connectionId: active.connectionId,+ });++ await vi.waitFor(() =>+ expect(+ sent+ .get(viewer.sessionId)+ ?.findLast((message) => message.type === "route-status"),+ ).toMatchObject({+ state: "failed",+ reason: "route-exhausted",+ }),+ );+ } finally {+ await router.close();+ }+ });++ it("accepts active failure for a direct connection adopted during rebuild", async () => {+ const { store, sent, router } = harness(2);+ try {+ const room = await store.createRoom();+ const host = connectHost(store, room);+ complete(router, host);+ const viewer = connectViewer(store, room, "rebuilt-edge-failure");+ complete(router, viewer);+ await vi.waitFor(() =>+ expect(preparedFor(sent, viewer.sessionId)).toBeDefined(),+ );+ const prepared = preparedFor(sent, viewer.sessionId)!;+ router.handleRouteReady(viewer, {+ type: "route-ready",+ revision: prepared.revision,+ phase: "prepare",+ });+ const active = router.resolveActiveViewerMediaEdge(+ room.roomId,+ viewer.peerId,+ )!;+ const rebuiltConnectionId = "rebuilt_connection_12345678";+ expect(+ router.peerSignalAuthorization({+ roomId: room.roomId,+ sourcePeerId: host.peerId,+ sourceSessionId: host.sessionId,+ targetPeerId: viewer.peerId,+ targetSessionId: viewer.sessionId,+ connectionId: rebuiltConnectionId,+ signalKind: "description",+ descriptionType: "offer",+ }),+ ).toBe(true);+ expect(+ router.resolveActiveViewerMediaEdge(room.roomId, viewer.peerId),+ ).toMatchObject({+ revision: active.revision,+ connectionId: rebuiltConnectionId,+ });++ router.handleRouteFailed(viewer, {+ type: "route-failed",+ revision: active.revision,+ phase: "active",+ connectionId: rebuiltConnectionId,+ });++ await vi.waitFor(() =>+ expect(+ sent+ .get(viewer.sessionId)+ ?.findLast((message) => message.type === "route-status"),+ ).toMatchObject({+ state: "failed",+ reason: "route-exhausted",+ }),+ );+ } finally {+ await router.close();+ }+ });+it("commits P2P quality convergence after client relative approval", async () => {const { store, sent, router } = harness(2);try {@@ -912,8 +1035,14 @@ describe("HybridMediaRouter v9 runtime", () => {}});- it("does not wake admission waiters when a subscription remains charged for drain", async () => {- const { store, sent, admission, router } = harness(1, true, undefined, 2);+ it("physically removes an exact subscription without releasing its generation charge", async () => {+ const { store, sent, admission, roomControl, router } = harness(+ 1,+ true,+ undefined,+ 2,+ );+ let closed = false;try {const activeRoom = await store.createRoom();const active = await establishSfuRoom(@@ -957,6 +1086,8 @@ describe("HybridMediaRouter v9 runtime", () => {).toMatchObject({ state: "waiting", reason: "sfu-admission" }),);const attemptsBeforeRelease = reservePublication.mock.calls.length;+ const drainGate = deferred();+ roomControl!.subscriptionDrainBarrier = drainGate.promise;store.disconnectParticipant(activeRoom.roomId,@@ -972,12 +1103,27 @@ describe("HybridMediaRouter v9 runtime", () => {await vi.waitFor(() =>expect(router.routeDiagnosticSnapshot(activeRoom.roomId).children).toHaveLength(1),);- await Promise.resolve();+ await vi.waitFor(() =>+ expect(roomControl?.subscriptionDrainAttempts).toContainEqual(+ expect.objectContaining({ viewerPeerId: active.first.peerId }),+ ),+ );+ expect(admission?.usage()).toEqual({ ingress: 2, egress: 2 });+ drainGate.resolve();+ await vi.waitFor(() =>+ expect(roomControl?.drainedSubscriptions).toContainEqual(+ expect.objectContaining({ viewerPeerId: active.first.peerId }),+ ),+ );expect(admission?.usage()).toEqual({ ingress: 2, egress: 2 });expect(reservePublication).toHaveBeenCalledTimes(attemptsBeforeRelease);- } finally {+await router.close();+ closed = true;+ expect(admission?.usage()).toEqual({ ingress: 0, egress: 0 });+ } finally {+ if (!closed) await router.close();}});@@ -1150,8 +1296,14 @@ describe("HybridMediaRouter v9 runtime", () => {}});- it("keeps SFU Viewer and downstream Peer evidence identities separate", async () => {- const { store, sent, router } = harness(1, true, 1_000);+ it("retries a failed physical drain before reusing the exact SFU identity", async () => {+ const { store, sent, admission, roomControl, router } = harness(+ 1,+ true,+ 1_000,+ 2,+ 10,+ );try {const room = await store.createRoom();const { first } = await establishSfuRoom(store, sent, router, room);@@ -1194,6 +1346,10 @@ describe("HybridMediaRouter v9 runtime", () => {),);const directPrepare = preparedFor(sent, child.sessionId)!;+ const drainGate = deferred();+ const drainSubscription = vi+ .spyOn(roomControl!, "drainSubscription")+ .mockImplementationOnce(() => drainGate.promise);router.handleRouteReady(child, {type: "route-ready",revision: directPrepare.revision,@@ -1205,6 +1361,49 @@ describe("HybridMediaRouter v9 runtime", () => {?.upstream,).toEqual({ kind: "peer", peerId: first.peerId }),);+ await vi.waitFor(() =>+ expect(drainSubscription).toHaveBeenCalledWith(+ expect.objectContaining({ viewerPeerId: child.peerId }),+ ),+ );+ expect(admission?.usage()).toEqual({ ingress: 1, egress: 3 });++ router.handleRouteFailed(child, {+ type: "route-failed",+ revision: directPrepare.revision,+ phase: "active",+ connectionId: directPrepare.candidate.connectionId,+ });+ await vi.waitFor(() =>+ expect(router.routeDiagnosticSnapshot(room.roomId).operation).not.toBeNull(),+ );+ expect(preparedFor(sent, child.sessionId)?.revision).toBe(+ directPrepare.revision,+ );++ drainGate.reject(new Error("transient participant drain failure"));+ await vi.waitFor(() => expect(drainSubscription).toHaveBeenCalledTimes(2));+ const reusedSfu = await vi.waitFor(() => {+ const prepared = preparedFor(sent, child.sessionId);+ expect(prepared?.revision).toBeGreaterThan(directPrepare.revision);+ expect(prepared?.candidate.transport).toBe("sfu");+ return prepared!;+ });+ router.handleRouteReady(child, {+ type: "route-ready",+ revision: reusedSfu.revision,+ phase: "prepare",+ });+ await vi.waitFor(() =>+ expect(+ router.resolveActiveViewerMediaEdge(room.roomId, child.peerId)+ ?.upstream,+ ).toEqual({ kind: "sfu" }),+ );+ expect(roomControl!.drainedSubscriptions).toContainEqual(+ expect.objectContaining({ viewerPeerId: child.peerId }),+ );+ expect(admission?.usage()).toEqual({ ingress: 1, egress: 3 });expect(router.resolveActiveViewerMediaEdge(room.roomId, first.peerId)?.upstream,diff --git a/tests/room-database.test.ts b/tests/room-database.test.tsindex cf7bb36e..3d5aa09f 100644--- a/tests/room-database.test.ts+++ b/tests/room-database.test.ts@@ -292,6 +292,35 @@ describe("SQLite stable room authority", () => {expect(replacement.viewerGrant).not.toBe(room.viewerGrant);});+ it("rolls back a batch expiry when any exact room authority is stale", async () => {+ const path = databasePath();+ const clock = { nowMs: 10 };+ const first = stableStore(path, clock);+ await first.createRoom("open", null, "4321");+ await first.createRoom("open", null, "5678");+ closeStore(first);++ const database = new RoomDatabase(path);+ const restored = database.initialize(clock.nowMs, 1_010);+ expect(restored).toHaveLength(2);+ expect(() =>+ database.deleteRooms([+ {+ roomId: restored[0]!.roomId,+ hostTokenDigest: restored[0]!.hostTokenDigest,+ },+ {+ roomId: restored[1]!.roomId,+ hostTokenDigest: Buffer.alloc(32),+ },+ ]),+ ).toThrow("Room database delete did not match current authority");+ database.close();++ const second = stableStore(path, clock);+ expect(second.size).toBe(2);+ });+it("persists room replacement as one authority transition", async () => {const path = databasePath();const clock = { nowMs: 10 };diff --git a/tests/room-route-controller.test.ts b/tests/room-route-controller.test.tsindex 3c5a1385..da678993 100644--- a/tests/room-route-controller.test.ts+++ b/tests/room-route-controller.test.ts@@ -581,7 +581,7 @@ describe("RoomRouteController", () => {expect(routes.routeDiagnosticSnapshot(7_301).children[0]?.quality).toBeNull();});- it("does not require a P2P candidate sender category after client approval", () => {+ it("does not let one candidate limitation window override relative proof", () => {const routes = controller(2, { qualityConvergenceEnabled: true });addViewer(routes, A, 2);addViewer(routes, B, 2);@@ -626,7 +626,7 @@ describe("RoomRouteController", () => {state: "degraded",acceptedAtMs: 105,}).accepted,- ).toBe(false);+ ).toBe(true);expect(routes.candidateReady({@@ -642,7 +642,7 @@ describe("RoomRouteController", () => {).toBe(true);});- it("leaves P2P candidate sender identity out of relative approval", () => {+ it("does not let unknown candidate sender evidence veto relative proof", () => {const routes = controller(2, { qualityConvergenceEnabled: true });addViewer(routes, A, 2);addViewer(routes, B, 2);@@ -662,24 +662,19 @@ describe("RoomRouteController", () => {reservation: { kind: "direct" },});const current = begin.operation!.current!;- const candidateEvidence = (senderIdentity: string, sampleTimestampMs: number) =>+ expect(routes.observeSenderQualityEvidence({parentPeerId: B,parentSessionId: `${B}_session`,childPeerId: A,routeRevision: current.revision,connectionId: "a_from_b",- senderIdentity,- sampleTimestampMs,- state: "healthy",- acceptedAtMs: sampleTimestampMs,- });- expect(candidateEvidence("candidate-rtp-1\u0000track", 105).accepted).toBe(- false,- );- expect(candidateEvidence("candidate-rtp-2\u0000track", 106).accepted).toBe(- false,- );+ senderIdentity: null,+ sampleTimestampMs: null,+ state: "unknown",+ acceptedAtMs: 105,+ }).accepted,+ ).toBe(true);expect(routes.candidateReady({@@ -688,7 +683,7 @@ describe("RoomRouteController", () => {revision: current.revision,connectionId: "a_from_b",},- 107,+ 106,undefined,{ relativeQualityApproved: true },).committed,@@ -700,6 +695,113 @@ describe("RoomRouteController", () => {});});+ it("advances past a persistently limited quality candidate", () => {+ const routes = controller(3, { qualityConvergenceEnabled: true });+ for (const [peerId, connectionId] of [+ [A, "a_from_host"],+ [B, "b_from_host"],+ [C, "c_from_host"],+ ] as const) {+ addViewer(routes, peerId, 3);+ routes.hydrateEdge(peerId, peerEdge(HOST, connectionId));+ }+ observeSenderState(routes, {+ childPeerId: B,+ connectionId: "b_from_host",+ state: "healthy",+ acceptedAtMs: 99,+ });+ observeSenderState(routes, {+ childPeerId: C,+ connectionId: "c_from_host",+ state: "healthy",+ acceptedAtMs: 99,+ });+ observePersistentDegraded(routes, A, "a_from_host", 99);++ const operation = routes.reconcile(103).operation!;+ const deadlineAtMs = operation.deadlineAtMs;+ const firstParent = (+ operation.candidates[0]!.tuple as Extract<+ (typeof operation.candidates)[number]["tuple"],+ { kind: "peer" }+ >+ ).parentPeerId;+ const first = beginCandidate(routes, {+ nowMs: 104,+ connectionId: "first_quality_candidate",+ reservation: { kind: "direct" },+ }).operation!;+ let lastResult;+ for (const acceptedAtMs of [105, 106, 107]) {+ lastResult = routes.observeSenderQualityEvidence({+ parentPeerId: firstParent,+ parentSessionId: `${firstParent}_session`,+ childPeerId: A,+ routeRevision: first.current!.revision,+ connectionId: "first_quality_candidate",+ senderIdentity: "first-quality-rtp\u0000track",+ sampleTimestampMs: acceptedAtMs,+ state: "degraded",+ acceptedAtMs,+ });+ expect(lastResult.accepted).toBe(true);+ }+ expect(lastResult?.committed).toBe(false);+ expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({+ parentPeerId: HOST,+ connectionId: "a_from_host",+ });+ expect(routes.snapshot().operation).toMatchObject({+ cursor: 1,+ deadlineAtMs,+ current: undefined,+ });++ const secondParent = (+ routes.snapshot().operation!.candidates[1]!.tuple as Extract<+ (typeof operation.candidates)[number]["tuple"],+ { kind: "peer" }+ >+ ).parentPeerId;+ expect(secondParent).not.toBe(firstParent);+ const second = beginCandidate(routes, {+ nowMs: 108,+ connectionId: "second_quality_candidate",+ reservation: { kind: "direct" },+ }).operation!;+ expect(+ routes.observeSenderQualityEvidence({+ parentPeerId: secondParent,+ parentSessionId: `${secondParent}_session`,+ childPeerId: A,+ routeRevision: second.current!.revision,+ connectionId: "second_quality_candidate",+ senderIdentity: null,+ sampleTimestampMs: null,+ state: "unknown",+ acceptedAtMs: 109,+ }).accepted,+ ).toBe(true);+ expect(+ routes.candidateReady(+ {+ childPeerId: A,+ childSessionId: `${A}_session`,+ revision: second.current!.revision,+ connectionId: "second_quality_candidate",+ },+ 110,+ undefined,+ { relativeQualityApproved: true },+ ).committed,+ ).toBe(true);+ expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({+ parentPeerId: secondParent,+ connectionId: "second_quality_candidate",+ });+ });+it("preempts quality work for a Viewer without media", () => {const routes = controller(2, { qualityConvergenceEnabled: true });addViewer(routes, A, 2);@@ -738,6 +840,131 @@ describe("RoomRouteController", () => {});});+ it("keeps a quality operation reason immutable until availability preempts it", () => {+ const routes = controller(2, { qualityConvergenceEnabled: true });+ addViewer(routes, A, 2);+ addViewer(routes, B, 2);+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));+ observeSenderState(routes, {+ childPeerId: B,+ connectionId: "b_from_host",+ state: "healthy",+ acceptedAtMs: 99,+ });+ observePersistentDegraded(routes, A, "a_from_host", 99);+ expect(routes.reconcile(103).operation?.reason).toBe(+ "quality-convergence",+ );++ expect(+ routes.invalidateEdge(+ {+ childPeerId: A,+ childSessionId: `${A}_session`,+ parentSessionId: "host_session",+ routeRevision: routes.snapshot().revision,+ connectionId: "a_from_host",+ },+ 104,+ ),+ ).toBe(true);+ expect(routes.snapshot().operation?.reason).toBe("quality-convergence");+ expect(routes.reconcile(105).operation).toMatchObject({+ childPeerId: A,+ reason: "edge-unavailable",+ });+ });++ it("keeps a direct convergence reason immutable until availability preempts it", () => {+ const routes = controller(2, { sfuEnabled: true });+ addViewer(routes, B, 2);+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));+ routes.hydrateHostPublication("publication", "publication_resource");+ addViewer(routes, A, 0, 0);+ const acquisition = routes.reconcile(0).operation!;+ beginCandidate(routes, {+ nowMs: 1,+ connectionId: "a_head_start",+ reservation: { kind: "direct" },+ });+ routes.operationExpired(acquisition.wakeAtMs);+ const sfu = beginCandidate(routes, {+ nowMs: acquisition.wakeAtMs + 1,+ connectionId: "a_sfu",+ reservation: { kind: "sfu-reuse", edge: "a_subscription" },+ }).operation!;+ expect(+ routes.candidateReady(+ {+ childPeerId: A,+ childSessionId: `${A}_session`,+ revision: sfu.current!.revision,+ connectionId: "a_sfu",+ },+ acquisition.wakeAtMs + 2,+ ).committed,+ ).toBe(true);+ expect(routes.reconcile(acquisition.wakeAtMs + 3).operation?.reason).toBe(+ "direct-convergence",+ );++ expect(+ routes.invalidateEdge(+ {+ childPeerId: A,+ childSessionId: `${A}_session`,+ routeRevision: routes.snapshot().revision,+ connectionId: "a_sfu",+ },+ acquisition.wakeAtMs + 4,+ ),+ ).toBe(true);+ expect(routes.snapshot().operation?.reason).toBe("direct-convergence");+ expect(routes.reconcile(acquisition.wakeAtMs + 5).operation).toMatchObject({+ childPeerId: A,+ reason: "edge-unavailable",+ });+ });++ it("keeps a root convergence reason immutable until availability preempts it", () => {+ const routes = controller(2, { qualityConvergenceEnabled: true });+ addViewer(routes, B, 2);+ addViewer(routes, C, 0);+ addViewer(routes, D, 0);+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));+ routes.hydrateEdge(C, peerEdge(B, "c_from_b"));+ routes.hydrateEdge(D, peerEdge(B, "d_from_b"));+ addViewer(routes, A, 2, 10);+ routes.reconcile(10);+ commitCurrent(routes, 11, "a_from_host");+ const convergence = routes.reconcile(13).operation!;+ expect(convergence.reason).toBe("root-convergence");+ const oldEdge = routes.snapshot().upstreamByViewer.get(+ convergence.childPeerId,+ );+ expect(oldEdge?.kind).toBe("peer");+ if (oldEdge?.kind !== "peer") throw new Error("Expected Peer edge");++ expect(+ routes.invalidateEdge(+ {+ childPeerId: convergence.childPeerId,+ childSessionId: convergence.childSessionId,+ parentSessionId: oldEdge.parentSessionId,+ routeRevision: routes.snapshot().revision,+ connectionId: oldEdge.connectionId,+ },+ 14,+ ),+ ).toBe(true);+ expect(routes.snapshot().operation?.reason).toBe("root-convergence");+ expect(routes.reconcile(15).operation).toMatchObject({+ childPeerId: convergence.childPeerId,+ reason: "edge-unavailable",+ });+ });+it("keeps a usable parent eligible before native state becomes clear", () => {const routes = controller(2, { qualityConvergenceEnabled: true });addViewer(routes, A, 2);@@ -756,7 +983,7 @@ describe("RoomRouteController", () => {});});- it("uses client relative proof even when candidate native state is limited", () => {+ it("uses relative proof after candidate native state expires", () => {const routes = controller(2, { qualityConvergenceEnabled: true });addViewer(routes, A, 2);addViewer(routes, B, 2);@@ -824,7 +1051,7 @@ describe("RoomRouteController", () => {state: "healthy",acceptedAtMs: 104,}).accepted,- ).toBe(false);+ ).toBe(true);for (const acceptedAtMs of [5_101, 5_102, 5_103]) {expect(observeCurrent(A, "a_from_host", "degraded", acceptedAtMs).accepted,@@ -1669,6 +1896,48 @@ describe("RoomRouteController", () => {});});+ it("invalidates one exact active Peer edge from its parent idempotently", () => {+ const routes = controller(2);+ addViewer(routes, A, 0);+ addViewer(routes, B, 1);+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));+ const report = {+ parentPeerId: HOST,+ parentSessionId: "host_session",+ routeRevision: routes.snapshot().revision,+ connectionId: "a_from_host",+ };++ expect(routes.invalidateDirectEdgeFromParent(report, 10)).toBe(true);+ const afterFirst = routes.snapshot();+ expect(afterFirst.upstreamByViewer.get(A)).toMatchObject({+ usable: false,+ connectionId: "a_from_host",+ });+ expect(afterFirst.upstreamByViewer.get(B)).toMatchObject({+ usable: true,+ connectionId: "b_from_host",+ });+ expect(routes.invalidateDirectEdgeFromParent(report, 11)).toBe(true);+ expect(routes.snapshot().factVersion).toBe(afterFirst.factVersion);+ expect(+ routes.invalidateDirectEdgeFromParent({+ ...report,+ connectionId: "unknown_connection",+ }),+ ).toBe(false);+ expect(routes.reconcile(12).operation).toMatchObject({+ childPeerId: A,+ reason: "edge-unavailable",+ candidates: [+ {+ tuple: { kind: "peer", parentPeerId: B, transport: "direct" },+ },+ ],+ });+ });+it("advances one candidate cursor without resetting the operation deadline", () => {const routes = controller(2, { sfuEnabled: true });addViewer(routes, A, 2);@@ -2776,7 +3045,14 @@ describe("RoomRouteController", () => {});expect(staleReserve).toMatchObject({ accepted: false });expect(staleReserve.released).toEqual(["stale_reservation"]);- expect(reserve.snapshot().operation).toMatchObject({ cursor: 1 });+ expect(reserve.snapshot().operation).toMatchObject({+ cursor: 0,+ candidates: [+ {+ tuple: { kind: "peer", parentPeerId: A, transport: "direct" },+ },+ ],+ });expect(reserve.snapshot().operation?.current).toBeUndefined();const skip = controller(2);@@ -2786,8 +3062,8 @@ describe("RoomRouteController", () => {const staleCursor = skip.reconcile(0).operation!;skip.setEffectiveCapacity(HOST, "host_session", 0);expect(skip.skipCurrentCandidate(cursorGuard(staleCursor), 1).accepted).toBe(false);- expect(skip.snapshot().operation).toMatchObject({ cursor: 1 });- expect(skip.snapshot().operation?.candidates[1]?.tuple).toMatchObject({+ expect(skip.snapshot().operation).toMatchObject({ cursor: 0 });+ expect(skip.snapshot().operation?.candidates[0]?.tuple).toMatchObject({kind: "peer",parentPeerId: A,});@@ -2933,7 +3209,7 @@ describe("RoomRouteController", () => {});});- it("does not reopen an exhausted bootstrap without a new fact", () => {+ it("retries a bootstrap carrier only when its transition improves", () => {const routes = controller(1, { sfuEnabled: true });addViewer(routes, A, 0);routes.hydrateEdge(A, peerEdge(HOST, "failed_direct"));@@ -2963,11 +3239,33 @@ describe("RoomRouteController", () => {revision: prepared.current!.revision,connectionId: "failed_sfu",}, 2)).toMatchObject({ accepted: true, failedPeerIds: [A] });+ const improved = routes.reconcile(3).operation!;+ expect(improved.candidates[0]).toMatchObject({+ tuple: { kind: "sfu", publication: "create" },+ endpointTransition: { kind: "none", producerPeerId: HOST },+ });+ const improvedAttempt = beginCandidate(routes, {+ nowMs: 4,+ connectionId: "improved_sfu",+ publicationGeneration: "improved_publication",+ publicationConnectionId: "improved_publication_connection",+ reservation: {+ kind: "sfu-create",+ edge: "improved_subscription_resource",+ publication: "improved_publication_resource",+ },+ }).operation!;+ expect(routes.candidateFailed({+ childPeerId: improved.childPeerId,+ childSessionId: improved.childSessionId,+ revision: improvedAttempt.current!.revision,+ connectionId: "improved_sfu",+ }, 5)).toMatchObject({ accepted: true, failedPeerIds: [A] });const factVersion = routes.snapshot().factVersion;- expect(routes.reconcile(3).operation).toBeUndefined();+ expect(routes.reconcile(6).operation).toBeUndefined();expect(routes.setEffectiveCapacity(A, `${A}_session`, 0)).toBe(true);expect(routes.snapshot().factVersion).toBe(factVersion);- expect(routes.reconcile(4).operation).toBeUndefined();+ expect(routes.reconcile(7).operation).toBeUndefined();expect(routes.invalidateEdge({childPeerId: A,childSessionId: `${A}_session`,@@ -2976,7 +3274,12 @@ describe("RoomRouteController", () => {connectionId: "failed_direct",})).toBe(true);expect(routes.snapshot().factVersion).toBe(factVersion);- expect(routes.reconcile(5).operation).toBeUndefined();+ expect(routes.reconcile(8).operation).toBeUndefined();++ addViewer(routes, B, 0, 9);+ expect(routes.reconcile(9).operation?.childPeerId).toBe(B);+ while (routes.snapshot().operation) skipCandidate(routes, 10);+ expect(routes.reconcile(11).operation).toBeUndefined();});it.each([1, 2] as const)(@@ -3071,31 +3374,280 @@ describe("RoomRouteController", () => {expect(routes.snapshot().hostPublication).toBeNull();});- it("retries an exact failed tuple only after a new external fact", () => {+ it("does not reopen a consumed none transition when it worsens to overlap", () => {+ const routes = controller(2, { sfuEnabled: true });+ addViewer(routes, A, 0);+ routes.hydrateHostPublication("publication", "publication_resource");+ routes.hydrateEdge(A, {+ kind: "sfu",+ publicationGeneration: "publication",+ transport: "sfu",+ connectionId: "a_from_sfu",+ usable: true,+ physicalActive: true,+ resource: "a_subscription",+ });+ expect(routes.invalidateEdge({+ childPeerId: A,+ childSessionId: `${A}_session`,+ routeRevision: 0,+ connectionId: "a_from_sfu",+ })).toBe(true);+ const operation = routes.reconcile(0).operation!;+ expect(operation.candidates[0]).toMatchObject({+ tuple: { kind: "peer", parentPeerId: HOST, transport: "direct" },+ endpointTransition: { kind: "none", producerPeerId: HOST },+ });++ expect(routes.setEffectiveCapacity(HOST, "host_session", 1)).toBe(true);+ expect(routes.operationExpired(operation.deadlineAtMs).failedPeerIds).toEqual([+ A,+ ]);+ const retry = routes.reconcile(operation.deadlineAtMs + 1).operation!;+ expect(retry.candidates).toEqual([+ {+ tuple: { kind: "sfu", publication: "replace" },+ endpointTransition: { kind: "none", producerPeerId: HOST },+ },+ ]);+ expect(+ retry.candidates.some(+ (candidate) =>+ candidate.tuple.kind === "peer" &&+ candidate.tuple.parentPeerId === HOST,+ ),+ ).toBe(false);+ });++ it("does not unblock an exhausted demand for an unrelated join", () => {+ const routes = controller(1);+ addViewer(routes, B, 0);+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));+ addViewer(routes, A, 0, 0);+ expect(routes.reconcile(0).failedPeerIds).toEqual([A]);++ expect(routes.setEffectiveCapacity(A, `${A}_session`, 1)).toBe(true);+ expect(routes.reconcile(1).operation).toBeUndefined();++ addViewer(routes, C, 0, 2);+ expect(routes.reconcile(2).failedPeerIds).toEqual([C]);+ expect(routes.snapshot().operation).toBeUndefined();++ expect(routes.setEffectiveCapacity(B, `${B}_session`, 1)).toBe(true);+ expect(routes.reconcile(3).operation).toMatchObject({+ childPeerId: A,+ candidates: [+ {+ tuple: { kind: "peer", parentPeerId: B, transport: "direct" },+ },+ ],+ });+ });++ it("does not revive an exact failed Host tuple when a new parent joins", () => {const routes = controller(1);addViewer(routes, A, 0);routes.hydrateEdge(A, peerEdge(HOST, "failed_direct"));+ expect(+ routes.invalidateEdge({+ childPeerId: A,+ childSessionId: `${A}_session`,+ parentSessionId: "host_session",+ routeRevision: 0,+ connectionId: "failed_direct",+ }),+ ).toBe(true);+ expect(routes.reconcile(0).operation).toBeUndefined();++ addViewer(routes, B, 1, 1);+ expect(routes.reconcile(2).operation).toMatchObject({+ childPeerId: B,+ reason: "join",+ });+ commitCurrent(routes, 2, "b_from_host");+ const retry = routes.reconcile(4).operation!;+ expect(retry).toMatchObject({+ childPeerId: A,+ candidates: [+ {+ tuple: { kind: "peer", parentPeerId: B, transport: "direct" },+ },+ ],+ });+ expect(+ retry.candidates.some(+ (candidate) =>+ candidate.tuple.kind === "peer" &&+ candidate.tuple.parentPeerId === HOST,+ ),+ ).toBe(false);+ });++ it("does not unblock an exhausted Viewer when its candidate set shrinks", () => {+ const routes = controller(1);+ addViewer(routes, A, 0);+ routes.hydrateEdge(A, peerEdge(HOST, "failed_host"));expect(routes.invalidateEdge({childPeerId: A,childSessionId: `${A}_session`,parentSessionId: "host_session",routeRevision: 0,- connectionId: "failed_direct",+ connectionId: "failed_host",})).toBe(true);expect(routes.reconcile(0).operation).toBeUndefined();- expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({- usable: false,- physicalActive: false,++ addViewer(routes, B, 1, 1);+ routes.reconcile(1);+ commitCurrent(routes, 2, "b_from_host");+ const candidate = routes.reconcile(3).operation!;+ const attempt = beginCandidate(routes, {+ nowMs: 4,+ connectionId: "a_from_b",+ reservation: { kind: "direct" },+ }).operation!;+ expect(routes.candidateFailed({+ childPeerId: A,+ childSessionId: `${A}_session`,+ revision: attempt.current!.revision,+ connectionId: "a_from_b",+ }, 5).failedPeerIds).toEqual([A]);+ expect(candidate.candidates).toHaveLength(1);++ expect(routes.disconnectSession(B, `${B}_session`)).toBe(true);+ expect(routes.reconcile(6).operation).toBeUndefined();+ });++ it("treats a replacement child session as a new exact opportunity", () => {+ const routes = controller(1);+ addViewer(routes, A, 0);+ routes.hydrateEdge(A, peerEdge(HOST, "failed_host"));+ expect(routes.invalidateEdge({+ childPeerId: A,+ childSessionId: `${A}_session`,+ parentSessionId: "host_session",+ routeRevision: 0,+ connectionId: "failed_host",+ })).toBe(true);+ expect(routes.reconcile(0).operation).toBeUndefined();++ routes.upsertParticipant({+ peerId: A,+ role: "viewer",+ sessionId: "replacement_session",+ effectiveDownstreamCapacity: 0,});+ expect(routes.reconcile(1).operation).toMatchObject({+ childPeerId: A,+ childSessionId: "replacement_session",+ candidates: [+ {+ tuple: { kind: "peer", parentPeerId: HOST, transport: "direct" },+ },+ ],+ });+ });- routes.touchExternalFacts();- expect(routes.reconcile(1).operation?.candidates[0]?.tuple).toEqual({- kind: "peer",- parentPeerId: HOST,- transport: "direct",+ it("does not retry a failed bootstrap carrier when another carrier leaves", () => {+ const routes = controller(2, { sfuEnabled: true });+ for (const [peerId, connectionId] of [+ [B, "b_from_host"],+ [C, "c_from_host"],+ ] as const) {+ addViewer(routes, peerId, 1);+ routes.hydrateEdge(peerId, peerEdge(HOST, connectionId));+ }+ addViewer(routes, A, 0, 0);+ const acquisition = routes.reconcile(0).operation!;+ beginCandidate(routes, {+ nowMs: 1,+ connectionId: "a_head_start",+ reservation: { kind: "direct" },+ });+ routes.operationExpired(acquisition.wakeAtMs);++ const bootstrap = routes.reconcile(acquisition.wakeAtMs + 1).operation!;+ expect(bootstrap.reason).toBe("sfu-bootstrap");+ const failedCarrier = bootstrap.childPeerId;+ const otherCarrier = failedCarrier === B ? C : B;+ const attempt = beginCandidate(routes, {+ nowMs: acquisition.wakeAtMs + 2,+ connectionId: "failed_bootstrap",+ publicationGeneration: "failed_publication",+ publicationConnectionId: "failed_publication_connection",+ reservation: {+ kind: "sfu-create",+ edge: "failed_subscription",+ publication: "failed_publication_resource",+ overlap: "failed_overlap",+ },+ }).operation!;+ expect(routes.candidateFailed({+ childPeerId: failedCarrier,+ childSessionId: `${failedCarrier}_session`,+ revision: attempt.current!.revision,+ connectionId: "failed_bootstrap",+ }, acquisition.wakeAtMs + 3).accepted).toBe(true);++ expect(+ routes.disconnectSession(otherCarrier, `${otherCarrier}_session`),+ ).toBe(true);+ const next = routes.reconcile(acquisition.wakeAtMs + 4).operation;+ expect(next).not.toMatchObject({+ reason: "sfu-bootstrap",+ childPeerId: failedCarrier,});});+ it("reopens only SFU opportunities for a new external fact", () => {+ const routes = controller(1, { sfuEnabled: true });+ addViewer(routes, A, 0, 0);+ routes.reconcile(0);+ const directAttempt = beginCandidate(routes, {+ nowMs: 1,+ connectionId: "failed_direct",+ reservation: { kind: "direct" },+ }).operation!;+ expect(routes.candidateFailed({+ childPeerId: A,+ childSessionId: `${A}_session`,+ revision: directAttempt.current!.revision,+ connectionId: "failed_direct",+ }, 2).accepted).toBe(true);+ const sfuAttempt = beginCandidate(routes, {+ nowMs: 3,+ connectionId: "failed_sfu",+ publicationGeneration: "failed_publication",+ publicationConnectionId: "failed_publication_connection",+ reservation: {+ kind: "sfu-create",+ edge: "failed_subscription",+ publication: "failed_publication_resource",+ },+ }).operation!;+ expect(routes.candidateFailed({+ childPeerId: A,+ childSessionId: `${A}_session`,+ revision: sfuAttempt.current!.revision,+ connectionId: "failed_sfu",+ }, 4).accepted).toBe(true);+ expect(routes.snapshot().operation).toBeUndefined();+ expect(routes.reconcile(5).operation).toBeUndefined();++ routes.touchExternalFacts();+ const retried = routes.reconcile(6).operation!;+ expect(retried.candidates).toEqual([+ {+ tuple: { kind: "sfu", publication: "create" },+ endpointTransition: { kind: "none", producerPeerId: HOST },+ },+ ]);+ expect(+ retried.candidates.some(+ (candidate) => candidate.tuple.kind === "peer",+ ),+ ).toBe(false);+ });+it("fails all waiting demands without cutting capacity-three Host children", () => {const routes = controller(3, { sfuEnabled: true });for (const [peerId, connectionId] of [diff --git a/tests/route-transition.test.ts b/tests/route-transition.test.tsindex 50fe5adf..765569aa 100644--- a/tests/route-transition.test.ts+++ b/tests/route-transition.test.ts@@ -518,14 +518,18 @@ describe("minimal route transition contracts", () => {const decodedSamples: Array<{framesDecodedDelta: number | null;revision: number;+ mediaIdentity: string;}> = [];const subscribers: ReturnType<typeof createFakeSubscriber>[] = [];const route = new ViewerSfuRoute("viewer_12345678", {activatePeer: () => true,reconcileSfuChildren: () => undefined,onSfuStream: (stream) => streams.push(stream),- onSfuDecodedFrameSample: (framesDecodedDelta, revision) =>- decodedSamples.push({ framesDecodedDelta, revision }),+ onSfuDecodedFrameSample: (+ framesDecodedDelta,+ revision,+ mediaIdentity,+ ) => decodedSamples.push({ framesDecodedDelta, revision, mediaIdentity }),send: (message) => {messages.push(message);return true;@@ -552,7 +556,13 @@ describe("minimal route transition contracts", () => {subscribers[0]?.events.onFirstDecodedFrame();await vi.waitFor(() => expect(streams).toEqual([firstStream]));subscribers[0]?.events.onDecodedFrameSample(3);- expect(decodedSamples).toEqual([{ framesDecodedDelta: 3, revision: 1 }]);+ expect(decodedSamples).toEqual([+ {+ framesDecodedDelta: 3,+ revision: 1,+ mediaIdentity: expect.stringContaining("publication_generation_12345678:"),+ },+ ]);route.accept({revision: 2,@@ -568,7 +578,7 @@ describe("minimal route transition contracts", () => {} as ConnectionMetrics);subscribers[1]?.events.onDecodedFrameSample(null);expect(messages.filter((message) => message.type === "route-ready")).toEqual([]);- expect(decodedSamples).toEqual([{ framesDecodedDelta: 3, revision: 1 }]);+ expect(decodedSamples).toHaveLength(1);subscribers[1]?.events.onFirstDecodedFrame();subscribers[1]?.events.onFirstDecodedFrame();@@ -585,10 +595,14 @@ describe("minimal route transition contracts", () => {await vi.waitFor(() => expect(streams).toEqual([firstStream, pendingStream]));subscribers[1]?.events.onDecodedFrameSample(null);subscribers[0]?.events.onDecodedFrameSample(9);- expect(decodedSamples).toEqual([- { framesDecodedDelta: 3, revision: 1 },- { framesDecodedDelta: null, revision: 2 },- ]);+ expect(decodedSamples).toHaveLength(2);+ expect(decodedSamples[1]).toMatchObject({+ framesDecodedDelta: null,+ revision: 2,+ });+ expect(decodedSamples[1]!.mediaIdentity).not.toBe(+ decodedSamples[0]!.mediaIdentity,+ );expect(subscribers[0]?.deactivate).toHaveBeenCalledOnce();expect(subscribers[0]?.disconnect).toHaveBeenCalledOnce();});@@ -665,6 +679,68 @@ describe("minimal route transition contracts", () => {]);});+ it("rejects a quality SFU candidate after three comparable regressions", async () => {+ const messages: ClientMessage[] = [];+ const subscribers: ReturnType<typeof createFakeSubscriber>[] = [];+ let currentMetrics = receiveMetrics(1_000);+ const route = new ViewerSfuRoute("viewer_12345678", {+ activatePeer: () => true,+ reconcileSfuChildren: () => undefined,+ onSfuStream: () => undefined,+ currentPeerMetrics: () => currentMetrics,+ qualityProbeEligible: () => true,+ send: (message) => {+ messages.push(message);+ return true;+ },+ createSubscriber: (events) => {+ const subscriber = createFakeSubscriber(events, [], "candidate");+ subscribers.push(subscriber);+ return subscriber;+ },+ });++ route.accept({+ revision: 1,+ phase: "active",+ assignment: peerAssignment("parent_12345678"),+ });+ route.accept({+ revision: 2,+ phase: "prepare",+ assignment: viewerSfuAssignment(),+ candidate: candidate(+ 2,+ "viewer_12345678",+ "sfu",+ "candidate_2_12345678",+ true,+ ),+ });+ await route.acceptConfig(sfuConfig(2));+ const subscriber = subscribers[0]!;+ subscriber.events.onStream({} as MediaStream);+ subscriber.events.onFirstDecodedFrame();++ for (const timestampMs of [1_100, 3_100, 5_100]) {+ currentMetrics = receiveMetrics(timestampMs - 100);+ subscriber.events.onStats(+ receiveMetrics(timestampMs, { framesPerSecond: 30 }),+ );+ }++ expect(messages.at(-1)).toEqual({+ type: "route-failed",+ revision: 2,+ phase: "prepare",+ connectionId: null,+ });+ expect(subscriber.disconnect).toHaveBeenCalledOnce();+ expect(+ messages.filter((message) => message.type === "route-ready"),+ ).toEqual([]);+ });+it("reconnects only the active SFU subscriber on the current route", async () => {const messages: ClientMessage[] = [];const streams: MediaStream[] = [];diff --git a/tests/server-signal.test.ts b/tests/server-signal.test.tsindex b198f018..1a9cbbde 100644--- a/tests/server-signal.test.ts+++ b/tests/server-signal.test.ts@@ -1819,6 +1819,47 @@ describe("WebSocket signaling", () => {expect(authenticated.role).toBe("host");});+ it("keeps a pre-Host Viewer session current after the Host clears the room lease", async () => {+ let now = Date.UTC(2026, 7, 20, 12);+ const harness = await startHarness({ now: () => now });+ const viewer = await openClient(harness.webSocketUrl);+ await authenticate(+ viewer,+ harness.room,+ "viewer",+ "pre-host-lease-viewer",+ 1,+ undefined,+ { displayName: "Before" },+ );+ const host = await openClient(harness.webSocketUrl);+ await authenticate(+ host,+ harness.room,+ "host",+ "pre-host-lease-host",+ 1,+ undefined,+ { viewerPresence: true },+ );+ await nextViewerPresenceMatching(host, (message) =>+ viewerPresenceEntries(message).some(+ (participant) => participant.displayName === "Before",+ ),+ );++ now += 86_400_001;+ viewer.socket.send(+ JSON.stringify({ type: "set-display-name", displayName: "After" }),+ );+ const updated = await nextViewerPresenceMatching(host, (message) =>+ viewerPresenceEntries(message).some(+ (participant) => participant.displayName === "After",+ ),+ );+ expect(viewerPresenceEntries(updated)).toHaveLength(1);+ });+it("leaves established authorization and media untouched when a grant update fails", async () => {const harness = await startHarness();const host = await openClient(harness.webSocketUrl);diff --git a/tests/sfu-resource-admission.test.ts b/tests/sfu-resource-admission.test.tsindex 6cff73b6..3107ffa1 100644--- a/tests/sfu-resource-admission.test.ts+++ b/tests/sfu-resource-admission.test.ts@@ -80,9 +80,9 @@ describe("SfuResourceAdmission", () => {expect(admission.commitSubscription(subscription(active, "viewer_b"))).toBe(false,);- expect(admission.releaseSubscription(subscription(active, "viewer_b"))).toBe(- false,- );+ expect(+ admission.beginSubscriptionDrain(subscription(active, "viewer_b")),+ ).toBe(false);expect(admission.beginDrain(stale)).toBe(false);});@@ -145,8 +145,8 @@ describe("SfuResourceAdmission", () => {expect(admission.reserveSubscription(candidate)).toBe(true);expect(admission.usage()).toEqual({ ingress: 1, egress: 2 });- expect(admission.releaseSubscription(candidate)).toBe(true);- expect(admission.releaseSubscription(candidate)).toBe(true);+ expect(admission.beginSubscriptionDrain(candidate)).toBe(true);+ expect(admission.beginSubscriptionDrain(candidate)).toBe(true);expect(admission.commitSubscription(candidate)).toBe(false);expect(admission.usage()).toEqual({ ingress: 1, egress: 2 });expect(@@ -157,7 +157,7 @@ describe("SfuResourceAdmission", () => {expect(admission.usage()).toEqual({ ingress: 0, egress: 0 });});- it("reactivates a draining subscription in the current generation without double charging", () => {+ it("reactivates an exact draining subscription without double charging", () => {const admission = new SfuResourceAdmission({ingressCapacity: 1,egressCapacity: 1,@@ -167,13 +167,13 @@ describe("SfuResourceAdmission", () => {expect(admission.reservePublication(active)).toBe(true);expect(admission.reserveSubscription(viewer)).toBe(true);expect(admission.commitPublication(active)).toEqual([]);- expect(admission.releaseSubscription(viewer)).toBe(true);+ expect(admission.beginSubscriptionDrain(viewer)).toBe(true);expect(admission.usage()).toEqual({ ingress: 1, egress: 1 });expect(admission.reserveSubscription(viewer)).toBe(true);expect(admission.reserveSubscription(viewer)).toBe(true);expect(admission.usage()).toEqual({ ingress: 1, egress: 1 });- expect(admission.releaseSubscription(viewer)).toBe(true);+ expect(admission.beginSubscriptionDrain(viewer)).toBe(true);expect(admission.reserveSubscription(subscription(active, "viewer_b")),).toBe(false);@@ -192,7 +192,7 @@ describe("SfuResourceAdmission", () => {expect(admission.reservePublication(active)).toBe(true);expect(admission.reserveSubscription(viewer)).toBe(true);expect(admission.commitPublication(active)).toEqual([]);- expect(admission.releaseSubscription(viewer)).toBe(true);+ expect(admission.beginSubscriptionDrain(viewer)).toBe(true);expect(admission.reserveSubscription(subscription(active, "viewer_b")),).toBe(false);diff --git a/tests/sfu-room-control.test.ts b/tests/sfu-room-control.test.tsindex 15d4b88b..6a0078ab 100644--- a/tests/sfu-room-control.test.ts+++ b/tests/sfu-room-control.test.ts@@ -17,6 +17,7 @@ class FakeRoomService implements LiveKitRoomService {readonly createOptions: Array<{ name: string; maxParticipants: number }> = [];createBarrier?: Promise<void>;retainDeletedRoom = false;+ retainRemovedParticipant = false;async createRoom(options: { name: string; maxParticipants: number }) {this.operations.push(`create:${options.name}`);@@ -54,6 +55,17 @@ class FakeRoomService implements LiveKitRoomService {return [...participants].map((identity) => ({ identity }));}+ async removeParticipant(room: string, identity: string): Promise<void> {+ this.operations.push(`remove:${room}:${identity}`);+ const participants = this.rooms.get(room);+ if (!participants?.has(identity)) {+ throw new ServerError("Not Found", "missing", 404, "not_found");+ }+ if (!this.retainRemovedParticipant) {+ participants.delete(identity);+ }+ }+join(room: string, identity: string): boolean {const participants = this.rooms.get(room);if (!participants) {@@ -178,6 +190,44 @@ describe("LiveKitSfuRoomControl", () => {).resolves.toBe(false);});+ it("removes and confirms only the exact Viewer subscription", async () => {+ const roomService = new FakeRoomService();+ const roomControl = control(roomService);+ const resourceFence = fence();+ await roomControl.createRoom(resourceFence);+ const roomName = managedSfuRoomName(resourceFence);+ const viewerPeerId = "viewer_peer_12345678";+ expect(roomService.join(roomName, "host")).toBe(true);+ expect(roomService.join(roomName, `viewer:${viewerPeerId}`)).toBe(true);+ expect(roomService.join(roomName, "viewer:other_peer_12345678")).toBe(true);++ const subscriptionFence = { ...resourceFence, viewerPeerId };+ await expect(+ roomControl.drainSubscription(subscriptionFence),+ ).resolves.toBeUndefined();+ expect(roomService.rooms.get(roomName)).toEqual(+ new Set(["host", "viewer:other_peer_12345678"]),+ );+ await expect(+ roomControl.drainSubscription(subscriptionFence),+ ).resolves.toBeUndefined();+ });++ it("rejects an unconfirmed Viewer participant drain", async () => {+ const roomService = new FakeRoomService();+ const roomControl = control(roomService);+ const resourceFence = fence();+ await roomControl.createRoom(resourceFence);+ const roomName = managedSfuRoomName(resourceFence);+ const viewerPeerId = "viewer_peer_12345678";+ roomService.join(roomName, `viewer:${viewerPeerId}`);+ roomService.retainRemovedParticipant = true;++ await expect(+ roomControl.drainSubscription({ ...resourceFence, viewerPeerId }),+ ).rejects.toThrow("removal was not confirmed");+ });+it("keeps the tracked deployment unable to auto-create rooms", () => {const configuration = readFileSync(new URL("../deploy/livekit/livekit.yaml.example", import.meta.url),diff --git a/tests/stage-entry-actions.test.ts b/tests/stage-entry-actions.test.tsindex 5e64fa6e..4909237b 100644--- a/tests/stage-entry-actions.test.ts+++ b/tests/stage-entry-actions.test.ts@@ -57,4 +57,17 @@ describe("Host stage entry layout", () => {/\.room-code-entry\.is-inline\s*\{[\s\S]*?width:\s*min\(520px, calc\(100% - 20px\)\);[\s\S]*?grid-template-columns:\s*minmax\(0, 1fr\) 44px;/,);});++ it("disables share start while room authority is mutating", () => {+ const markup = renderToStaticMarkup(+ createElement(StageEntryActions, {+ joiningRoom: false,+ startSharingDisabled: true,+ onJoinToggle: () => undefined,+ onStartSharing: () => undefined,+ }),+ );++ expect(markup).toMatch(/<button[^>]*disabled=""[^>]*>/);+ });});