Compare commits

..
1 Commits
  • fix: repair media startup and retire shared session resources (#483)
    Early video retransmissions could be rejected before an SFU publication admitted its primary stream. The shared RTP reader now restores the associated primary identity before admission. A repository audit also found ownership omissions in Viewer input retirement, queued route work, partially constructed connections and sender-evidence cleanup; each is corrected at its existing owner without changing routing or adaptation policy.
    
    The same phase fixes bounded Linux diagnostic encoding, picker/tooltip keyboard and touch behavior, and stale-language notices. Documentation now reflects current App, room and media lifecycles. Theme-role consolidation remains deferred.
    
    Validation: complete Web check (1,685 tests, type-check and build); Windows Go core tests/vet/cross-builds; Linux CI race/vulnerability checks and all seven package targets; native Linux diagnostic fixtures on both architectures; actual Chromium/Pion SFU decode, live settings, reload/recovery and resource-retirement gate; documentation and website builds. Confirmed defects were compared against their baseline and independently reviewed. No protocol, configuration or persistence migration is required. Physical device limits and unmatched field reports remain open.
    
    ## Release notes
    
    ### 中文
    
    这是一次分享稳定性与交互细节维护更新,兼容现有 2.x 客户端和站点。
    
    - 修复部分服务器中转开播失败:较早到达的视频重传包不再被误判,导致媒体发布提前结束。
    - 修复停播后快速重新分享时,旧任务可能拖延新线路准备的问题。
    - 撤销邀请或替换观众会话时,同步清理对应的远控输入身份,保留其他观众的正常使用。
    - 改善连接失败、观众反复加入退出后的资源回收;避免 Linux 单路输出的错误信息意外中断整个分享。
    - 修正选源、互动和线路提示的键盘/触屏操作;切换语言后,当前校验与错误提示会同步更新。
    
    ### English
    
    This maintenance update improves sharing reliability and interaction details. It remains compatible with existing 2.x Apps and Sites.
    
    - Fix an SFU startup failure caused by video retransmissions arriving before the primary stream was admitted.
    - Prevent retired sharing tasks from delaying route preparation after a quick stop and restart.
    - Retire remote-input identities when invitations are revoked or Viewer sessions are replaced, while preserving other participants.
    - Release resources correctly after connection failures and repeated Viewer churn; prevent Linux output diagnostics from unexpectedly ending the whole share.
    - Improve keyboard and touch behavior in source selection, interactions and route help. Active validation and error messages now follow language changes.
48 changed files with 700 additions and 247 deletions

No files matched your search

+3 -4
View File
@@ -51,10 +51,9 @@ STUN_URLS=
# Local App modes never create these listeners, even with public discovery.
STUN_LISTEN_HOST=0.0.0.0
# Optional bounded NAT traversal support. The per-share switch stays visible;
# it is locked off when disabled, and defaults on when enabled after all three
# local STUN listeners bind. Browser
# P2P derives UDP 3479/3480 from the first STUN_URLS endpoint on UDP 3478.
# Optional bounded NAT traversal support. Current pages use it automatically
# on P2P-first sites after all three local STUN listeners bind. Auxiliary
# discovery uses UDP 3479/3480 at the first STUN_URLS endpoint on UDP 3478.
# Cloud security-group and host firewall rules must also allow these UDP ports.
NAT_PREDICTION_ENABLED=false
@@ -25,7 +25,7 @@ Every room owns:
- one random free code from `1000` through `9999`;
- a SHA-256 Host-token digest and Viewer-grant digest;
- a monotonically increasing Viewer authorization generation;
- an opaque random Viewer authorization generation;
- `open | private` code entry and optional salted scrypt password material.
Room authority has no time limit by default. Explicit replacement or deletion
@@ -57,9 +57,11 @@ It never stores raw tokens, grants, or passwords.
The schema is one exact current version on an embedded SQLite driver, one
connection, one writer, and transactional room mutations. An unknown schema,
wrong application identity, corrupt row, inaccessible path, or second owner
fails startup before signaling or LiveKit mutation. This private pre-release
contract has no legacy reader or migration chain. A schema cutover must preserve
existing authority through an explicit offline operation on a verified copy,
fails startup before signaling or SFU resource mutation. There is no automatic
legacy reader or migration chain; published upgrades follow the
[public compatibility promise](../standards/versioning.md#public-compatibility-promise).
A schema cutover must preserve existing authority through an explicit offline
operation on a verified copy,
with the previous database and application retained for rollback. Removing the
lease column never deletes rooms or rotates credentials.
@@ -68,18 +70,20 @@ media route is considered online until fresh sessions establish it again.
Participants, display names, client/peer/session IDs, share generation, pause,
quality settings, codec decisions, route graph, pending operations, first-frame
proof, SFU tokens/resources/rooms, RTCStats, diagnostics, and logs remain
proof, SFU publications/subscriptions, RTCStats, diagnostics, and logs remain
process-only. Every restart creates fresh session and route authority and media
must reconnect and recommit on a newly decoded frame. SQLite does not make a
LiveKit restart seamless or remove the browser gesture required after capture
must reconnect and recommit on a newly decoded frame. SQLite does not make media
recovery seamless or remove the browser gesture required after capture
itself ends.
### Host Ownership And Preferred Code
The Host browser keeps the raw Host token and creation profile in same-origin
local storage. The server keeps only the token digest. Clearing browser data or
changing device loses ownership; IP, UA, hardware and browser fingerprints are
never identity.
Each Host tab keeps its current room and raw Host token in session storage;
same-origin local storage keeps the resume hint and independent creation profile.
The [Host-tab lifecycle](../standards/rooms-access.md#room-authority) owns
cross-tab claims and resume behavior. The server keeps only the token digest.
Clearing browser data or changing device loses ownership; IP, UA, hardware and
browser fingerprints are never identity.
The browser also remembers one non-secret preferred room code with no local
expiry or renewal timer. It is only a future allocation hint. The server remains
+2 -2
View File
@@ -29,8 +29,8 @@ platform probe and physical gate report it.
[media quality](../standards/media-quality.md). Audio scope adds no second
representation or independent clock; Host commentary uses the existing mixer.
4. Browser source switching replaces the current screen-audio track in the same
persistent media stream. Local Viewer play, mute, and volume stay inside the
native media element.
persistent media stream. Viewer play, mute, and volume remain local playback
controls, owned by the Viewer audio path rather than capture or routing.
5. Do not describe generic Browser system audio as application-isolated. UI and
documentation must leave source scope to the Browser's actual result.
6. Windows process-tree audio for a selected window, and default render-device
+5 -3
View File
@@ -75,9 +75,11 @@ the same Browser build.
- The App is one process. Room authority, the loopback capability service, and
native media share it, so a panic in the server ends the Local session exactly
as a crashed Node child did, and the capability service no longer survives a
failed room authority. Hosted exits non-zero and systemd restarts it; nothing
restarts a vanished authority in place.
as a crashed Node child did. An ordinary Local/public room startup failure
leaves the resident App and capability service available under
[ADR-0010](./0010-cross-platform-client-runtime.md); a process crash does not.
Hosted exits non-zero and systemd restarts it; nothing restarts a vanished
authority in place.
- Package and runtime cost falls in three places: the App package loses its
bundled runtime and dependency tree, the application release becomes the server
binary with its notices and revision, and a production host installs no
@@ -21,8 +21,9 @@
- Browser relay can keep screen audio in the same persistent `MediaStream` while
source tracks are added, removed, or replaced. It does not need a Web Audio
mix/resample graph or second clock.
- Viewer play, mute, volume, and autoplay recovery belong to the native media
element and do not change sender or room state.
- Viewer play, mute, volume, and autoplay recovery remain local under the
[playback owner](../standards/presentation-lifecycle.md#playback-ownership)
and do not change sender or room state.
## RED Tradeoff
@@ -27,8 +27,8 @@ consumer and a distinct responsibility.
The App binds IPv4 loopback on a bounded range (`39721`-`39730`). `/health`
returns the protocol version, service identity, selected port, and an
`instanceToken`. `/control` admits one WebSocket session whose subprotocol
contains that same value. The first frame must be `hello`; subsequent requests
`instanceToken`. `/control` admits up to two WebSocket sessions whose subprotocols
contain that same value. The first frame must be `hello`; subsequent requests
are limited to capability discovery, source preview, and one generation-fenced
share's media controls.
@@ -37,9 +37,10 @@ unrelated listener. It is visible through health and stdout and is not an
authentication secret. Host and Origin checks plus Chromium's Local Network
Access permission form the Browser boundary.
The current protocol advertises only the native capabilities and
generation-fenced media commands that have consumers. It carries no room
credentials or route policy; those stay in the Browser/server protocol.
The current protocol advertises native capabilities and generation-fenced media
commands that have consumers. The Browser also delivers authenticated remote-input
peer identities and their scoped secrets to the native input owner. Room access
credentials and route policy stay in the Browser/server protocol.
## App Composition
+7 -6
View File
@@ -8,7 +8,7 @@
SQLite has one cohesive current consumer: the room authorization aggregate. It
is justified when application releases should retain not only a preferred code,
but the exact Host ownership, existing Viewer invitation, revocation high-water,
but the exact Host ownership, existing Viewer invitation, authorization generation,
code-entry policy and password verifier. It is not a generic
store for future features.
@@ -53,16 +53,17 @@ receive fresh session/peer/connection/route generations, and recommit media on a
newly decoded frame. A surviving Host capture track may therefore recover with a
bounded interruption; a page/browser restart still requires a new capture gesture.
The application continues to clear and rebuild LiveKit rooms and the process
resource ledger. SQLite does not make a LiveKit process restart seamless. True
LiveKit failover remains its separate Redis/distributed/draining architecture.
The application rebuilds embedded SFU publications, subscriptions and the process
resource ledger. SQLite does not make a media-process restart seamless.
LiveKit's separate Redis/distributed/draining architecture is not part of this
embedded composition.
## Why Not A Signed Recovery Capsule
A signed Host capsule is smaller only when recovery may issue a new invitation.
It cannot prove that an older capsule is not replaying a Viewer grant revoked by
a newer one. Stable old invitations plus strong rotate/revoke therefore require
a durable latest-authorization-generation high-water mark. Once that durable
a durable current authorization generation. Once that durable
owner exists, keeping the code, credential digests, policy and verifier in
the same SQLite row is simpler than a client capsule, signing key and second
truth path.
@@ -73,7 +74,7 @@ The accepted implementation uses one embedded SQLite driver, one exact schema,
one process connection and transactional low-frequency room writes. No ORM,
event table, stats writer, compatibility reader or migration chain is added.
Unknown schema, wrong application identity, corrupt row, inaccessible file or a
second owner fails before signaling or LiveKit mutation.
second owner fails before signaling or SFU resource mutation.
Production activation is not an app-only cutover. It requires an access-restricted
writable directory, configuration backup, database backup/restore procedure and
+1 -1
View File
@@ -71,7 +71,7 @@ runtime change for either is claimed here.
- Native Pion candidate input is syntax-checked with the existing ICE parser,
bounded before queuing, and discarded when malformed, stale, or over capacity.
Repeated answers for an edge are idempotent. Profile updates remain fenced to
that same share session in the current loopback v9 wire.
that same share session in the current loopback v10 wire.
- An unexpected Browser control-socket close now notifies the active Host owner;
intentional user cleanup remains silent and uses the existing share fence.
+5
View File
@@ -11,6 +11,11 @@ not define route selection, wire messages, UI, or current deployment state.
## Conclusion
These conclusions describe ordinary track forwarding and the alternatives checked
on 2026-08-22. The later independent producer/carrier composition in
[ADR-0014](../adr/0014-browser-node-local-encoding-pool.md) owns optional Browser
encoding reuse; it does not remove relay decoding or per-child transport work.
A normal Browser can receive a remote WebRTC video track and add it to another
`RTCPeerConnection`. This is the compatibility-first peer relay path and can
distribute Host upload across participating Viewers.
+2 -1
View File
@@ -98,7 +98,8 @@ that every popup should acquire.
| Read a brief explanation | Shared `Tooltip`; no settings or required actions hidden in a hint |
| Adjust a few contextual settings | Attached native popover with `useAnchoredPopover`; dismiss after use, no dragging or detaching |
| Work through related settings | Inline disclosure or tabs, as in `SharingSettings`; expand into page flow rather than cover the picture |
| Complete a bounded task before continuing | Existing modal dialog, such as source selection; contain focus and return it on close |
| Complete a task that blocks the page | Existing native modal dialog, such as share-failure help; contain focus and return it on close |
| Choose a source inside the television | TV-local nonmodal dialog; keep its own Tab loop, inner guidance before Escape cancellation, and return focus to the current share action on close. Surrounding room controls remain available to the pointer |
| Keep a room tool available while watching or working | `FloatingPanel`, as used for interactions and Host remote permissions; retain its position without reflowing the room |
| Use a tool outside the page | Optional `usePanelWindow` on capable browsers; reuse the same content/session, as with interactions, remote permissions and the docked remote keyboard |
+8 -9
View File
@@ -56,15 +56,14 @@ Release artifacts and operator deployment records own delivery completion;
## Current Work
Current source retains the existing 2.x protocol and route owners. This phase
combines attended keyboard/mouse control, Viewer playback settings and the
interaction window, with shared forwarding recovery repairs. Native input is
included in App builds and remains off until the Host enables it; its
[prototype boundary](./research/room-interactions.md#attended-remote-control-prototype)
owns platform evidence. The owner authorized release after final automated and
local acceptance on 2026-10-19. [TODO](./todo.md) owns upstream follow-up,
device acceptance and deferred work. Release artifacts and operator records own
delivery results.
The published v2.2.0 includes attended keyboard/mouse control, Viewer playback
settings and the interaction window. Current maintenance retains the existing
2.x protocol and route owners and audits the repository alongside scoped media,
interaction and lifecycle repairs. On 2026-10-19 the owner authorized publishing
v2.2.1 once this audit and acceptance are complete. The promotional film remains
a local draft pending review. [TODO](./todo.md) owns upstream follow-up, device
acceptance and deferred work. Release artifacts and operator records own delivery
results.
2.0 separates numeric media requests from presets and bounded runtime admission,
retains successfully applied quality settings, and lets App serve an approved
+22 -16
View File
@@ -17,7 +17,7 @@ platform deferrals or establish a diagnosis for unmatched reports.
- [ ] **macOS bundle startup acceptance (#479).** The package now contains the
actual Mach-O entry and helpers inside `.app`, replacing the shell launcher's
dependency on an external sibling executable. A moved-bundle assembly check
passes, and candidate CI has built and packaged both Mac architectures.
passes, and release CI has built and packaged both Mac architectures.
Verify Finder launch on macOS, including a downloaded/quarantined bundle and
capture permissions. The packaging defect
is established; its correction has not yet been matched to the reporter's Mac.
@@ -30,10 +30,13 @@ platform deferrals or establish a diagnosis for unmatched reports.
own that boundary; this local repair does not diagnose the unmatched field
reports below.
- [ ] **Audio-exclusion explanation (#480).** At release, point the reporter to
the [source-audio scopes](./guide/getting-started.md#exclude-a-voice-app-from-screen-audio).
The missing window/camera exclusion control is intentional; investigate a
specific unwanted recording only if a matching source/input report establishes it.
- [ ] **Early repaired-media startup.** Release postflight reproduced an SFU
publication failure before the subscriber offer. A deterministic Pion trial
established that repair can queue before primary RID admission, retaining a
zero SSRC. The shared RTP reader now restores the admitted primary identity;
focused forwarding and Browser SFU lifecycle checks pass. Complete this repository
audit and acceptance, publish v2.2.1, and repeat the affected deployment check. The
production logs match this failure boundary but do not identify the packet fields.
- [ ] **SFU recovery rollout.** Shared forwarding now gives DownTrack one
owner for video sender reports and RR/RTT accounting, with Pion scheduling.
@@ -44,20 +47,23 @@ platform deferrals or establish a diagnosis for unmatched reports.
the affected upstream clock. This does not diagnose every unmatched
sustained-quality report below.
- [ ] **Release issue follow-up.** After owner acceptance and publication, link
confirmed fixes to the release PR and notes, then reply with the shipped
version on relevant open and previously closed issues. Close only established
resolutions or explicitly declined requests; retain unmatched reports as
awaiting evidence.
- [ ] **New promotional film.** Begin after publication. Explain Piik's screen
sharing directly, then show sharing/invitation, interaction and single-controller
keyboard/mouse use with explicit Host consent. Its visual direction may differ
from the existing film. Local key visuals and the motion study are exploratory,
not a finished film.
- [ ] **New promotional film.** Review the local 54-second Chinese/English
motion draft, which introduces screen sharing, invitation, interaction and
single-controller keyboard/mouse use with explicit Host consent. Confirm the
pacing and soundtrack before replacing the existing online film. The current
draft uses product components and staged scenes, not a recorded live session.
## Held By Owner
- [ ] **Theme-role consistency.** Deferred to the next minor update by
the owner on 2026-10-19. Keep this release's accepted palette. Sliding
segments should reuse the theme's selected-control colour pair rather than
inverse text/paper colours; review related App, Web and website choices at
their shared owners. Define primary, secondary, selection and status roles
once; preserve primary-action and semantic-status identities. Bridge the
same-origin website/docs appearance preference through their existing theme
adapters rather than keeping independent explicit choices.
- [ ] **Remote-control latency and responsiveness.** Scheduled after this release.
Compare input-to-visible-response timing on the same endpoints, source and
network against a mature remote-control implementation. Separate input
+4 -2
View File
@@ -93,6 +93,10 @@ func (engine *Engine) BeginPunch(connectionID string, source *Source, servers []
if err != nil || len(key) != 32 || connectionID == "" || len(connectionID) > 256 {
return nil, errors.New("invalid connection preparation")
}
// Publication registration takes the engine before its source. Keep the
// same order so preparing a peer cannot deadlock an SFU publication.
engine.mu.Lock()
defer engine.mu.Unlock()
if source != nil {
source.mu.Lock()
defer source.mu.Unlock()
@@ -100,8 +104,6 @@ func (engine *Engine) BeginPunch(connectionID string, source *Source, servers []
return nil, errors.New("media source is unavailable")
}
}
engine.mu.Lock()
defer engine.mu.Unlock()
if engine.closed || engine.punch != nil {
return nil, errors.New("connection preparation is unavailable")
}
+20
View File
@@ -151,6 +151,26 @@ func TestSourceAuthorizationPolicy(t *testing.T) {
if second.requested || m.active != nil {
t.Fatal("replacement source accepted input without opt-in")
}
if err := setTestPolicy(s, "room", ""); err != nil {
t.Fatal(err)
}
request(first, "")
revokedGrant := first.grant
if err := s.SetPeers(peers[1:]); err != nil {
t.Fatal(err)
}
if m.active != nil || first.grant != "" || m.connections[endpointKey{s, first.id}] != nil {
t.Fatal("room membership removal retained the active input grant")
}
m.receive(first, webrtc.DataChannelMessage{IsString: true, Data: []byte(`{"type":"key","code":"KeyA","down":true,"grant":"` + revokedGrant + `"}`)}, first.epoch)
request(first, "")
if m.active != nil || first.requested || len(sink.events) != 0 {
t.Fatal("removed endpoint regained input with its old grant or key")
}
request(second, "")
if m.active != second {
t.Fatal("membership removal interrupted the remaining authenticated endpoint")
}
}
func TestRouteReplacementRequiresApprovalAndIgnoresOldClosure(t *testing.T) {
+4 -4
View File
@@ -26,14 +26,14 @@ func registerVideoCodec(media *webrtc.MediaEngine, codec webrtc.RTPCodecParamete
}, webrtc.RTPCodecTypeVideo)
}
// ReadRTP restores repaired packets using the negotiated codec. Pion v4.2.23
// can queue RTX before a RID track's first primary read initializes PayloadType,
// even though Codec is already known. Do not rewrite ordinary packets: their
// payload type still has to match the source's negotiated identity.
// ReadRTP restores repaired packets to the admitted primary track. Pion can
// queue RTX before RID admission initializes SSRC or the first primary read
// initializes PayloadType. Ordinary packets retain their wire identity checks.
func ReadRTP(track *webrtc.TrackRemote) (*rtp.Packet, interceptor.Attributes, error) {
packet, attributes, err := track.ReadRTP()
if err == nil && attributes.Get(webrtc.AttributeRtxPayloadType) != nil {
packet.PayloadType = uint8(track.Codec().PayloadType)
packet.SSRC = uint32(track.SSRC())
}
return packet, attributes, err
}
+95 -15
View File
@@ -19,8 +19,12 @@ import (
// This fences the startup race without sleeping or accessing library internals.
type queuedRepair struct {
interceptor.NoOp
queued chan struct{}
once sync.Once
queued chan struct{}
once sync.Once
primary chan struct{}
primaryOnce sync.Once
inject chan func(*rtp.Packet) error
localOnce sync.Once
}
func (observer *queuedRepair) NewInterceptor(string) (interceptor.Interceptor, error) {
@@ -29,7 +33,7 @@ func (observer *queuedRepair) NewInterceptor(string) (interceptor.Interceptor, e
// Raw Pion tracks leave simulcast extensions to their sender. Mirror a Browser's
// repaired RID so the receiver binds the retransmission to the original layer.
func (*queuedRepair) BindLocalStream(info *interceptor.StreamInfo, writer interceptor.RTPWriter) interceptor.RTPWriter {
func (observer *queuedRepair) BindLocalStream(info *interceptor.StreamInfo, writer interceptor.RTPWriter) interceptor.RTPWriter {
var rid, repaired uint8
for _, extension := range info.RTPHeaderExtensions {
if extension.URI == publicationRIDExtension {
@@ -38,6 +42,22 @@ func (*queuedRepair) BindLocalStream(info *interceptor.StreamInfo, writer interc
repaired = uint8(extension.ID)
}
}
// A valid repair can arrive while the primary SSRC probe still awaits RID.
// Inject it through the real negotiated SRTP writer to control that ordering.
observer.localOnce.Do(func() {
observer.inject <- func(packet *rtp.Packet) error {
header := packet.Header.Clone()
header.SSRC, header.PayloadType = info.SSRCRetransmission, info.PayloadTypeRetransmission
if err := header.DelExtension(rid); err != nil {
return err
}
if err := header.SetExtension(repaired, []byte("q")); err != nil {
return err
}
_, err := writer.Write(&header, append([]byte{0, 1}, packet.Payload...), nil)
return err
}
})
return interceptor.RTPWriterFunc(func(header *rtp.Header, payload []byte, attributes interceptor.Attributes) (int, error) {
if header.SSRC == info.SSRCRetransmission && rid != 0 && repaired != 0 {
repairedHeader := header.Clone()
@@ -56,7 +76,13 @@ func (*queuedRepair) BindLocalStream(info *interceptor.StreamInfo, writer interc
func (observer *queuedRepair) BindRemoteStream(info *interceptor.StreamInfo, reader interceptor.RTPReader) interceptor.RTPReader {
if !strings.EqualFold(info.MimeType, webrtc.MimeTypeRTX) {
return reader
return interceptor.RTPReaderFunc(func(data []byte, attributes interceptor.Attributes) (int, interceptor.Attributes, error) {
n, attr, err := reader.Read(data, attributes)
if err == nil {
observer.primaryOnce.Do(func() { close(observer.primary) })
}
return n, attr, err
})
}
read := false
return interceptor.RTPReaderFunc(func(data []byte, attributes interceptor.Attributes) (int, interceptor.Attributes, error) {
@@ -69,6 +95,16 @@ func (observer *queuedRepair) BindRemoteStream(info *interceptor.StreamInfo, rea
}
func TestReadRTPEarlySimulcastRepairRetainsNegotiatedIdentity(t *testing.T) {
for _, beforePrimary := range []bool{false, true} {
name := "before-first-read"
if beforePrimary {
name = "before-primary-admission"
}
t.Run(name, func(t *testing.T) { testEarlySimulcastRepair(t, beforePrimary) })
}
}
func testEarlySimulcastRepair(t *testing.T, beforePrimary bool) {
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
check := func(err error) {
@@ -77,7 +113,7 @@ func TestReadRTPEarlySimulcastRepairRetainsNegotiatedIdentity(t *testing.T) {
t.Fatal(err)
}
}
observer := &queuedRepair{queued: make(chan struct{})}
observer := &queuedRepair{queued: make(chan struct{}), primary: make(chan struct{}), inject: make(chan func(*rtp.Packet) error, 1)}
newPeer := func() *webrtc.PeerConnection {
engine := &webrtc.MediaEngine{}
check(engine.RegisterDefaultCodecs())
@@ -111,7 +147,11 @@ func TestReadRTPEarlySimulcastRepairRetainsNegotiatedIdentity(t *testing.T) {
}
}()
tracks := make(chan *webrtc.TrackRemote, 1)
subscriber.OnTrack(func(track *webrtc.TrackRemote, _ *webrtc.RTPReceiver) { tracks <- track })
var remoteReceiver *webrtc.RTPReceiver
subscriber.OnTrack(func(track *webrtc.TrackRemote, receiver *webrtc.RTPReceiver) {
remoteReceiver = receiver
tracks <- track
})
negotiate := func(from, to *webrtc.PeerConnection, description webrtc.SessionDescription) {
gathered := webrtc.GatheringCompletePromise(from)
check(from.SetLocalDescription(description))
@@ -140,6 +180,35 @@ func TestReadRTPEarlySimulcastRepairRetainsNegotiatedIdentity(t *testing.T) {
ticker := time.NewTicker(10 * time.Millisecond)
defer ticker.Stop()
var remote *webrtc.TrackRemote
if beforePrimary {
// Hold primary admission after reading a packet without RID. Repair already
// carries repaired RID, so Pion queues it before primary SSRC is initialized.
initial := packet.Clone()
for _, extension := range sender.GetParameters().HeaderExtensions {
if extension.URI == publicationRIDExtension {
check(initial.DelExtension(uint8(extension.ID)))
}
}
waiting := true
for waiting {
select {
case <-observer.primary:
waiting = false
case <-ticker.C:
check(low.WriteRTP(initial))
case <-ctx.Done():
t.Fatal("primary probe did not read:", ctx.Err())
}
}
inject := <-observer.inject
check(inject(packet))
select {
case <-observer.queued:
case <-ctx.Done():
t.Fatal("early repair was not queued:", ctx.Err())
}
packet.SequenceNumber = 2
}
for remote == nil {
select {
case remote = <-tracks:
@@ -149,22 +218,33 @@ func TestReadRTPEarlySimulcastRepairRetainsNegotiatedIdentity(t *testing.T) {
t.Fatal(ctx.Err())
}
}
check(subscriber.WriteRTCP([]rtcp.Packet{&rtcp.TransportLayerNack{
MediaSSRC: uint32(remote.SSRC()), Nacks: []rtcp.NackPair{{PacketID: 1}},
}}))
select {
case <-observer.queued:
case <-ctx.Done():
t.Fatal("early repair was not queued:", ctx.Err())
if !beforePrimary {
check(subscriber.WriteRTCP([]rtcp.Packet{&rtcp.TransportLayerNack{
MediaSSRC: uint32(remote.SSRC()), Nacks: []rtcp.NackPair{{PacketID: 1}},
}}))
select {
case <-observer.queued:
case <-ctx.Done():
t.Fatal("early repair was not queued:", ctx.Err())
}
}
source, err := NewSource(SourceOptions{
ID: "repair-test", StreamID: "repair-test", Codec: remote.Codec(),
Formats: []LayerFormat{{Width: 8, Height: 8, Bitrate: 100_000}},
HeaderExtensions: remoteReceiver.GetParameters().HeaderExtensions,
})
check(err)
defer source.Close()
check(source.BindLayer(0, uint32(remote.SSRC()), remoteReceiver.GetParameters()))
check(remote.SetReadDeadline(time.Now().Add(time.Second)))
for {
received, attributes, err := ReadRTP(remote)
check(err)
if received.PayloadType != uint8(remote.Codec().PayloadType) || received.SSRC != uint32(remote.SSRC()) ||
received.SequenceNumber != packet.SequenceNumber || !bytes.Equal(received.Payload, packet.Payload) {
t.Fatalf("repaired packet lost its negotiated identity: payload type=%d, codec=%d", received.PayloadType, remote.Codec().PayloadType)
(received.SequenceNumber != 1 && (!beforePrimary || received.SequenceNumber != 2)) || !bytes.Equal(received.Payload, packet.Payload) {
t.Fatalf("repaired packet lost its negotiated identity: SSRC=%d, primary SSRC=%d, payload type=%d, codec=%d", received.SSRC, remote.SSRC(), received.PayloadType, remote.Codec().PayloadType)
}
check(source.WriteRTP(0, received))
if attributes.Get(webrtc.AttributeRtxPayloadType) != nil {
break
}
+3
View File
@@ -232,6 +232,9 @@ func (s *Server) revokeGrantViewers(roomID string, update room.ViewerGrantUpdate
if len(update.RevokedViewers) == 0 {
return
}
// The store has already removed their admission. Retire input identity as
// well; a shared relay's media connection may survive this Viewer leaving.
s.sendRemoteInputPeers(roomID)
s.deferredViewerPresenceRooms[roomID] = struct{}{}
func() {
defer delete(s.deferredViewerPresenceRooms, roomID)
@@ -42,3 +42,53 @@ func TestInputKeysBelongToAuthenticatedRoomEndpoints(t *testing.T) {
t.Fatal("departure retained input authority")
}
}
func TestInvitationRevocationRemovesOnlyGrantAdmittedInputKeys(t *testing.T) {
for name, request := range map[string]protocol.RoomAccessUpdateRequest{
"rotate": protocol.RotateViewerGrantRequest{Action: "rotate-viewer-grant"},
"revoke": protocol.RevokeViewerGrantRequest{Action: "revoke-viewer-grant"},
} {
t.Run(name, func(t *testing.T) {
h := startHarness(t, harnessOptions{})
host, invited, codeViewer := openClient(t, h), openClient(t, h), openClient(t, h)
authenticate(t, host, h.room, protocol.RoleHost, "host_input_revoke", -1, "", presenceOptions{})
authenticate(t, invited, h.room, protocol.RoleViewer, "invited_input_revoke", -1, "", presenceOptions{})
remaining := authenticate(t, codeViewer, h.room, protocol.RoleViewer, "code_input_revoke", -1, "", presenceOptions{codeOnly: true})
host.sendJSON(map[string]any{"type": "subscribe-remote-input"})
host.next("remote-input-peers")
invited.sendJSON(map[string]any{"type": "subscribe-remote-input", "endpointId": strings.Repeat("1", 32), "secret": strings.Repeat("2", 64)})
host.next("remote-input-peers")
codeViewer.sendJSON(map[string]any{"type": "subscribe-remote-input", "endpointId": strings.Repeat("3", 32), "secret": strings.Repeat("4", 64)})
host.next("remote-input-peers")
h.updateRoomAccess(request)
invited.next("viewer-grant-revoked")
event, err := protocol.DecodeServerMessage(host.next("remote-input-peers").raw)
if err != nil {
t.Fatal(err)
}
peers := event.(protocol.RemoteInputPeersMessage).Peers
if len(peers) != 1 || peers[0].PeerID != remaining.PeerID || peers[0].Secret != strings.Repeat("4", 64) {
t.Fatalf("input keys did not follow current room authority: %+v", peers)
}
})
}
}
func TestReplacedViewerCannotRetainInputKeysWithoutSubscribing(t *testing.T) {
h := startHarness(t, harnessOptions{})
host, oldViewer := openClient(t, h), openClient(t, h)
authenticate(t, host, h.room, protocol.RoleHost, "host_input_replace", -1, "", presenceOptions{})
authenticate(t, oldViewer, h.room, protocol.RoleViewer, "viewer_input_replace", -1, "", presenceOptions{})
host.sendJSON(map[string]any{"type": "subscribe-remote-input"})
host.next("remote-input-peers")
oldViewer.sendJSON(map[string]any{"type": "subscribe-remote-input", "endpointId": strings.Repeat("1", 32), "secret": strings.Repeat("2", 64)})
host.next("remote-input-peers")
replacement := openClient(t, h)
authenticate(t, replacement, h.room, protocol.RoleViewer, "viewer_input_replace", -1, "", presenceOptions{})
event, err := protocol.DecodeServerMessage(host.next("remote-input-peers").raw)
if err != nil || len(event.(protocol.RemoteInputPeersMessage).Peers) != 0 {
t.Fatal("replaced session retained input authority")
}
}
+9
View File
@@ -90,6 +90,15 @@ func (r *router) drivePump(roomID string, rm *roomRuntime, controller *route.Con
r.mu.Lock()
defer r.mu.Unlock()
defer func() { r.inflight-- }()
if current, _ := r.rooms.Get(roomID); current != rm || rm.controller != controller {
// Preparation yielded before this share retired. Its remainder owns only
// the reservation, never the replacement room's waiters or deadline.
rm.pumping = false
if pending != nil && !pending.result.denied {
r.releaseReservation(pending.result.prepared.reservation)
}
return
}
if !failed {
failed = r.recoverPump(func() {
if pending != nil {
+87 -20
View File
@@ -1373,39 +1373,60 @@ func TestRouterKeepsPeerOnlySharesOutOfConfiguredSfuFallback(t *testing.T) {
}
func TestRouterSilentlyKeepsWorkingMediaWhenQualityOnlySfuAdmissionIsDenied(t *testing.T) {
h := newRouterHarness(t, routerHarnessOptions{capacity: 1, withSfu: true, sfuIngressCapacity: 1})
debug := captureRouteDebug(t)
h := newRouterHarness(t, routerHarnessOptions{capacity: 2, withSfu: true, sfuIngressCapacity: 1})
occupied := sfu.ResourceFence{RoomID: "9001", ShareGeneration: "occupied_share_12345678", PublicationGeneration: "occupied_publication_12345678"}
created := h.createRoom()
host := h.connectHost(created, qualityPolicy, "", "")
viewer := h.connectViewer(created, "quality-sfu-denied")
h.locked(func() {
if !h.admission.ReservePublication(occupied) {
t.Fatal("the occupying publication must be reserved")
}
h.doComplete(host)
h.doComplete(viewer)
})
prepared := h.waitPrepared(viewer.sessionID)
var active activeViewerMediaEdge
h.locked(func() {
h.doReady(viewer, int64(prepared.Revision))
active = h.doMustEdge(created.RoomID, viewer.peerID)
for index, state := range []string{"healthy", "degraded"} {
if !h.router.observeSenderQualityEvidence(host, senderEvidenceMessage(viewer.peerID, active.connectionID, "viewer-rtp", "track", float64(100+index), active.revision, state)) {
t.Fatalf("%s evidence must be accepted", state)
viewers := []authenticatedRouteParticipant{
h.connectViewer(created, "quality-sfu-denied-first"),
h.connectViewer(created, "quality-sfu-denied-second"),
}
active := make([]activeViewerMediaEdge, len(viewers))
for index, viewer := range viewers {
h.complete(viewer)
prepared := h.waitPrepared(viewer.sessionID)
h.routeReady(viewer, int64(prepared.Revision))
active[index] = h.mustActiveEdge(created.RoomID, viewer.peerID)
}
degrade := func(viewer authenticatedRouteParticipant) {
h.locked(func() {
edge := h.doMustEdge(created.RoomID, viewer.peerID)
for index, state := range []string{"healthy", "degraded", "degraded", "degraded"} {
if !h.router.observeSenderQualityEvidence(host, senderEvidenceMessage(viewer.peerID, edge.connectionID, "viewer-rtp", "track", float64(100+index), edge.revision, state)) {
t.Fatalf("%s evidence must be accepted", state)
}
}
})
}
// SFU relief requires every Host root to be persistently degraded. Exhaust
// the second root's regeneration before the first makes SFU eligible.
degrade(viewers[1])
regeneration := h.waitPreparedAbove(viewers[1].sessionID, active[1].revision)
h.routeFailed(viewers[1], routeFailedMessage(int64(regeneration.Revision), "prepare", regeneration.Candidate.ConnectionID))
h.settle()
degrade(viewers[0])
h.waitFor("the quality-only SFU admission rejection", func() bool {
return debug.calledWith(created.RoomID, "candidate-preparation-denied", map[string]any{"rejectionBucket": "sfu-admission"})
})
h.settle()
for index, viewer := range viewers {
for _, message := range h.messages(viewer.sessionID) {
if _, ok := message.(protocol.RouteStatusMessage); ok {
t.Fatal("a denied quality-only candidate must stay silent")
}
}
})
h.waitFor("the quality operation to settle", func() bool { return h.diagnostic(created.RoomID).Operation == nil })
for _, message := range h.messages(viewer.sessionID) {
if _, ok := message.(protocol.RouteStatusMessage); ok {
t.Fatal("a denied quality-only candidate must stay silent")
if edge := h.mustActiveEdge(created.RoomID, viewer.peerID); edge.connectionID != active[index].connectionID ||
edge.upstream != protocol.PeerUpstream(host.peerID) {
t.Fatalf("working media changed: %+v", edge)
}
}
if edge := h.mustActiveEdge(created.RoomID, viewer.peerID); edge.connectionID != active.connectionID ||
edge.upstream != protocol.PeerUpstream(host.peerID) {
t.Fatalf("working media changed: %+v", edge)
}
h.locked(func() {
h.admission.BeginDrain(occupied)
h.admission.CompleteDrain(occupied)
@@ -1970,6 +1991,52 @@ func TestRouterOrdersExactPrepareCommitsOnlyChildProofAndRollsBackAboveP(t *test
}
}
func TestRetiredPumpPreservesReplacementShareResourceWaiter(t *testing.T) {
h := newRouterHarness(t, routerHarnessOptions{capacity: 1, withSfu: true, sfuIngressCapacity: 1})
created := h.createRoom()
host := h.connectHost(created, nil, "", "")
viewer := h.connectViewer(created, "replacement-waiter")
occupied := sfu.ResourceFence{RoomID: "9001", ShareGeneration: "occupied-share", PublicationGeneration: "occupied-publication"}
h.locked(func() {
h.router.sfuOnly = true
if !h.admission.ReservePublication(occupied) {
t.Fatal("reserve occupied publication")
}
h.router.connectParticipant(host)
h.router.connectParticipant(viewer)
old, _ := h.router.rooms.Get(created.RoomID)
old.pumping = true
controller := old.controller
revision := controller.Revision()
// Suspend the same queued remainder as requestPump, allowing the new
// share to acquire the authority mutex before the old driver resumes.
pending := h.router.pumpRoom(created.RoomID, old, controller, &revision, nil, true)
if pending == nil || !pending.result.denied {
t.Fatal("expected queued denied candidate")
}
h.router.stopRoom(created.RoomID)
h.router.connectParticipant(host)
replacement, _ := h.router.rooms.Get(created.RoomID)
replacementRevision := replacement.controller.Revision()
h.router.pumpRoom(created.RoomID, replacement, replacement.controller, &replacementRevision, nil, false)
if !h.router.resourceWaiters.Has(created.RoomID) {
t.Fatal("replacement did not wait")
}
h.router.inflight++
go h.router.drivePump(created.RoomID, old, controller, revision, pending, false)
})
h.settle()
h.locked(func() {
if !h.router.resourceWaiters.Has(created.RoomID) {
t.Fatal("retired pump erased the replacement share's SFU waiter")
}
h.admission.BeginDrain(occupied)
h.admission.CompleteDrain(occupied)
h.router.wakeResourceWaiters()
})
h.waitPreparedTransport(viewer.sessionID, "sfu")
}
func TestRouterCreatesOneHostPublicationAndReusesExactViewerSubscriptions(t *testing.T) {
h := newRouterHarness(t, routerHarnessOptions{capacity: 1, withSfu: true})
created := h.createRoom()
+3
View File
@@ -1016,6 +1016,9 @@ func (s *Server) completeAuthentication(sess *session, request authRequest, part
if replaced := s.sessionsByID[participant.ReplacedSessionID]; replaced != nil && replaced != sess {
replaced.close(websocket.StatusCode(protocol.SignalCloseSessionReplaced), "Session replaced")
}
if participant.Role == protocol.RoleViewer {
s.sendRemoteInputPeers(roomID)
}
}
if participant.Role == protocol.RoleHost && mediaActive {
+5 -1
View File
@@ -941,10 +941,14 @@ static gboolean bus_message(GstBus *bus, GstMessage *message, gpointer data) {
} else if (!failed->failed) {
failed->failed = TRUE;
set_output_active(failed, FALSE);
// A byte limit can split a localized diagnostic's final UTF-8 character.
// Keep this optional error valid so the Go reader retains healthy outputs.
char *detail = g_utf8_make_valid(cause, MIN(strlen(cause), 512));
if (!write_frame(6, 0, (guint8)failed->layer, 0, 0, 0, 0,
(const guint8 *)cause, MIN(strlen(cause), 512))) {
(const guint8 *)detail, strlen(detail))) {
fail_run(run, "native media output closed");
}
g_free(detail);
}
g_clear_error(&error);
g_free(debug);
+14 -5
View File
@@ -470,7 +470,7 @@ static gboolean verify_sibling_survives(gpointer data) {
return G_SOURCE_REMOVE;
}
static void check_output_failure_isolation(gboolean post_error) {
static void check_output_failure_isolation(gboolean post_error, const char *error_detail) {
FailureFixture fixture = {.run = {.output_count = 2}, .frames_at_failure = -1};
CaptureRun *run = &fixture.run;
g_mutex_init(&run->lock);
@@ -484,7 +484,7 @@ static void check_output_failure_isolation(gboolean post_error) {
"frames. ! valve name=gate1 drop=true ! ( queue max-size-buffers=1 "
"max-size-bytes=0 max-size-time=0 leaky=downstream ! "
"identity name=encoder1 ! fakesink name=good signal-handoffs=true sync=false async=false )",
post_error ? 3 : -1);
post_error && error_detail == NULL ? 3 : -1);
GError *error = NULL;
run->pipeline = gst_parse_launch(description, &error);
g_free(description);
@@ -525,6 +525,7 @@ static void check_output_failure_isolation(gboolean post_error) {
g_assert_cmpint(gst_element_set_state(run->pipeline, GST_STATE_PLAYING), !=, GST_STATE_CHANGE_FAILURE);
g_assert_true(set_output_active(&run->outputs[0], TRUE));
g_assert_true(set_output_active(&run->outputs[1], TRUE));
if (error_detail != NULL) fail_output(&run->outputs[0], error_detail);
g_timeout_add(10, verify_sibling_survives, &fixture);
g_main_loop_run(run->loop);
g_assert_cmpstr(run->failure, ==, "shared source fixture failure");
@@ -543,7 +544,10 @@ static void check_output_failure_isolation(gboolean post_error) {
g_assert_cmpint(bytes[5], ==, 6);
g_assert_cmpint(bytes[7], ==, 0);
g_assert_cmpuint(size, ==, 32 + read_be((guint8 *)bytes + 28, 4));
if (post_error) g_assert_nonnull(strstr(bytes + 32, "Failed after iterations as requested"));
g_assert_true(g_utf8_validate(bytes + 32, size - 32, NULL));
if (error_detail != NULL) {
g_assert_cmpuint(size, <=, 32 + 512 + 2); // A partial final byte becomes U+FFFD.
} else if (post_error) g_assert_nonnull(strstr(bytes + 32, "Failed after iterations as requested"));
g_free(bytes);
unlink(frame_path);
g_free(frame_path);
@@ -599,7 +603,12 @@ int main(int argc, char **argv) {
check_encoder_timestamp_segment(1000ULL * 60 * 60 * GST_SECOND);
check_encoder_timestamp_segment(0);
check_slot_retirement();
check_output_failure_isolation(TRUE);
check_output_failure_isolation(FALSE);
check_output_failure_isolation(TRUE, NULL);
check_output_failure_isolation(FALSE, NULL);
char *prefix = g_strnfill(511, 'x');
char *localized_error = g_strconcat(prefix, "\xe4\xb8\xad\xe6\x96\x87", NULL);
check_output_failure_isolation(TRUE, localized_error);
g_free(localized_error);
g_free(prefix);
return 0;
}
@@ -187,6 +187,17 @@ export function CaptureSourcePicker({
className={`lr-tv-overlay lr-source-picker${vis ? " is-visual" : ""}`}
role="dialog"
aria-label={t("host.sourcePicker.title")}
onKeyDown={event => {
if (event.key !== "Tab" || event.defaultPrevented || event.nativeEvent.isComposing) return;
// This TV-local task keeps its keyboard loop without making the room
// modal; pointer users can still reach the surrounding room controls.
const controls = [...event.currentTarget.querySelectorAll<HTMLElement>(
'button, input, select, textarea, a[href], summary, [tabindex]',
)].filter(element => element.tabIndex >= 0 && !element.matches(":disabled") && element.getClientRects().length);
const next = event.shiftKey && event.target === controls[0] ? controls.at(-1)
: !event.shiftKey && event.target === controls.at(-1) ? controls[0] : undefined;
if (next) { event.preventDefault(); next.focus(); }
}}
>
<div className="lr-source-picker-panel">
<header className="lr-source-picker-head">
+8 -14
View File
@@ -9,14 +9,16 @@ import { useCopy } from "../../ui/copy";
import { resolveMediaFailure, type MediaFailure } from "../../ui/media-failure";
import type { ConnectionMetrics } from "../../types";
import { MetricCells } from "./Metrics";
import { Pill } from "./primitives";
export function RouteGlyph({ route }: { route: "p2p" | "sfu" }) {
const { t, vis } = useCopy();
const cell = (
<span
<button
type="button"
className="lr-meter-cell"
// The route hint is available to keyboard users in every language.
tabIndex={0}
aria-label={t(route === "sfu" ? "state.route.sfu" : "state.route.p2p")}
style={{ border: 0, color: "inherit", font: "inherit", textAlign: "start" }}
>
{route === "sfu" ? (
<svg width="36" height="16" viewBox="0 0 36 16" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
@@ -39,10 +41,11 @@ export function RouteGlyph({ route }: { route: "p2p" | "sfu" }) {
) : (
<b>{route === "sfu" ? "SFU" : "P2P"}</b>
)}
</span>
</button>
);
return (
<Tooltip
toggleOnClick
kind={route === "sfu" ? "hint-route-sfu" : "hint-route-p2p"}
text={vis ? undefined : t(route === "sfu" ? "state.route.sfu" : "state.route.p2p")}
>
@@ -90,16 +93,7 @@ export function PawnDetail({
</span>
) : null}
{errorText ? (
<Tooltip kind="route-failed" text={vis ? undefined : errorText}>
<span
className="lr-pill is-bad"
role="alert"
tabIndex={0}
>
<Glyph name="alert" size={16} />
{vis ? <span className="visually-hidden">{errorText}</span> : <span>{errorText}</span>}
</span>
</Tooltip>
<Pill icon="alert" tone="bad" label={errorText} comic="route-failed" alert />
) : null}
{route ? <RouteGlyph route={route} /> : null}
{metrics ? (
@@ -4,7 +4,7 @@ import { ViewerAudio, type ViewerAudioSnapshot } from "../../media/viewer-audio"
import { useCopy } from "../../ui/copy";
import { Glyph } from "../../ui/icons";
import { debugError } from "../../lib/debug";
import { Btn, Cap } from "./primitives";
import { Btn } from "./primitives";
import { ViewerPlaybackSettings, type ViewerPlaybackSettingsProps } from "./ViewerPlaybackSettings";
import { Tooltip } from "./Tooltip";
import { useAnchoredPopover } from "./use-anchored-popover";
@@ -243,7 +243,7 @@ function PlaybackMore({ panel, children, settings, overlaySettings, onReconnect,
overlaySettings?: ReactNode;
onReconnect: () => void; reconnectAvailable: boolean;
}) {
const { t } = useCopy();
const { t, vis } = useCopy();
const id = useId();
const [open, setOpen] = useState(false);
const reconnect = <Btn icon="refresh" title="viewer.reconnect" hint="hint-reconnect" draw="playback-reconnect"
@@ -262,7 +262,7 @@ function PlaybackMore({ panel, children, settings, overlaySettings, onReconnect,
{settings ? <ViewerPlaybackSettings {...settings} displayActions={display} reconnect={reconnect} />
: <div className="lr-playback-menu-actions">{display}{reconnect}</div>}
{overlaySettings && <section className="lr-playback-overlay-settings" aria-label={t("playback.overlay")}>
<h3><Glyph name="danmaku" size={17} /><Cap k="playback.overlay" /></h3>
<h3><Glyph name="danmaku" size={17} /><span className={vis ? "visually-hidden" : undefined}>{t("playback.overlay")}</span></h3>
{overlaySettings}
</section>}
</div>
@@ -49,6 +49,7 @@ function InteractionPanel({ session, state, ...couch }: ConnectedProps & {
const panelArea = useRef<HTMLDivElement>(null);
const anchor = useRef<HTMLButtonElement | null>(null);
const panelAnchor = useRef<HTMLElement | null>(null);
const enterPanelPicker = useRef(false);
const log = useRef<HTMLDivElement>(null);
const readingPosition = useRef(0);
const id = useId();
@@ -85,7 +86,8 @@ function InteractionPanel({ session, state, ...couch }: ConnectedProps & {
const selected = panelArea.current?.querySelector<HTMLButtonElement>('[aria-pressed="true"]');
selected?.scrollIntoView({ block: "nearest", inline: "nearest" });
// Enter the tray on opening, without stealing focus when retargeting.
if (selected?.ownerDocument.activeElement === panelAnchor.current) selected.focus({ preventScroll: true });
if (enterPanelPicker.current) selected?.focus({ preventScroll: true });
enterPanelPicker.current = false;
}, [panelTarget, chatDocument]);
useLayoutEffect(() => {
const popup = document.getElementById(menuId);
@@ -104,6 +106,7 @@ function InteractionPanel({ session, state, ...couch }: ConnectedProps & {
session.send({ kind: "reaction", reaction, ...(targetPeerId ? { targetPeerId } : {}) });
}
function openPanelReactions(key: string, trigger: HTMLElement | null) {
enterPanelPicker.current = !panelPerson;
panelAnchor.current = trigger;
setPanelTarget(key);
}
+5 -6
View File
@@ -112,15 +112,13 @@ export function Tooltip({
title?: string;
}>(children) ? children : null;
const disabledTrigger = trigger?.props.disabled === true;
const rawDisabledTriggerLabel = disabledTrigger && trigger
const rawTriggerLabel = trigger
? trigger.props["aria-label"] ??
trigger.props.label ??
trigger.props.title
: undefined;
const disabledTriggerLabel =
rawDisabledTriggerLabel && isCopyKey(rawDisabledTriggerLabel)
? say(rawDisabledTriggerLabel)
: rawDisabledTriggerLabel;
const triggerLabel = rawTriggerLabel && isCopyKey(rawTriggerLabel) ? say(rawTriggerLabel) : rawTriggerLabel;
const disabledTriggerLabel = disabledTrigger ? triggerLabel : undefined;
const focusableWrap = disabledTrigger || (overflowing && !kind && trigger?.type !== "button");
useLayoutEffect(() => {
@@ -579,7 +577,8 @@ export function Tooltip({
<span ref={tipRef} id={tooltipId} popover="manual"
data-tone={resolvedTone}
style={{ ...comicStyle(resolvedTone), left: position.left, top: position.top, "--tooltip-caret": `${position.caret}px` } as CSSProperties}
className={`lr-comic-tip${kind ? " has-comic" : ""}${caption !== undefined ? " is-text" : ""}${placeClass}`} role="tooltip" aria-hidden={!interactionOpen}>
className={`lr-comic-tip${kind ? " has-comic" : ""}${caption !== undefined ? " is-text" : ""}${placeClass}`}
role="tooltip" aria-label={caption ? undefined : triggerLabel} aria-hidden={!interactionOpen || (!caption && !triggerLabel)}>
{panelMounted ? <span className="lr-comic-tip-content">
{kind ? isHintKind(kind)
? <HintComic kind={kind} size={200} tone={resolvedTone} motion={resolvedMotion} />
@@ -3,7 +3,7 @@ import type { ViewerRoutePreference } from "../../../shared/protocol";
import type { VideoFit } from "../../media/video-geometry";
import { useCopy } from "../../ui/copy";
import { Glyph } from "../../ui/icons";
import { Cap, Chip, RowGroup } from "./primitives";
import { Cap, Chip, Pill, RowGroup } from "./primitives";
export interface ViewerPlaybackSettingsProps {
pictureFit: VideoFit;
@@ -29,7 +29,7 @@ export function ViewerPlaybackSettings({ pictureFit, setPictureFit, route, displ
: `playback.routeHint.${route.preference}` as const;
return <div className="lr-viewer-settings">
<section aria-label={t("playback.pictureFit")}>
<div className="lr-viewer-settings-heading"><h3><Glyph name="tv" size={17} /><Cap k="playback.pictureFit" /></h3></div>
<div className="lr-viewer-settings-heading"><h3><Glyph name="tv" size={17} /><span className={vis ? "visually-hidden" : undefined}>{t("playback.pictureFit")}</span></h3></div>
<RowGroup>{(["contain", "cover", "fill"] as const).map(fit => <Chip key={fit}
selected={pictureFit === fit} title={t(`playback.fit.${fit}`)} hint={`hint-fit-${fit}`} onClick={() => setPictureFit(fit)}>
{vis && <Glyph name={fit === "contain" ? "fitContain" : fit === "cover" ? "fitCover" : "fitStretch"} size={20} />}
@@ -40,19 +40,26 @@ export function ViewerPlaybackSettings({ pictureFit, setPictureFit, route, displ
</section>
<section aria-label={t("playback.connection")}>
<div className="lr-viewer-settings-heading">
<h3><Glyph name="branch" size={17} /><Cap k="playback.connection" /></h3>
<h3><Glyph name="branch" size={17} /><span className={vis ? "visually-hidden" : undefined}>{t("playback.connection")}</span></h3>
{reconnect}
</div>
{route && <>
<RowGroup>{(["auto", "p2p", "sfu"] as const).map(preference => <Chip key={preference}
selected={route.preference === preference} title={t(`playback.route.${preference}`)}
disabled={route.disabled || (preference === "p2p" && route.sfuOnly) || (preference === "sfu" && !route.sfuAvailable)}
hint={preference === "auto" ? undefined : preference === "p2p" ? "hint-route-p2p" : "hint-route-sfu"}
onClick={() => { if (route.preference !== preference) route.onChange(preference); }}>
{vis && <Glyph name={preference === "auto" ? "branch" : preference === "p2p" ? "link" : "server"} size={17} />}
<Cap k={`playback.route.${preference}`} />
</Chip>)}</RowGroup>
<RowGroup>{(["auto", "p2p", "sfu"] as const).map(preference => {
const locked = preference === "p2p" && route.sfuOnly ? "playback.routeSfuOnly"
: preference === "sfu" && !route.sfuAvailable ? route.peerOnly ? "playback.routePeerOnly" : "playback.routeNoSfu" : undefined;
return <Chip key={preference}
selected={route.preference === preference} title={t(`playback.route.${preference}`)}
disabled={route.disabled || Boolean(locked)}
hint={locked ? preference === "p2p" ? "hint-route-sfu-required" : "hint-route-p2p-required"
: preference === "auto" ? undefined : preference === "p2p" ? "hint-route-p2p" : "hint-route-sfu"}
hintText={locked ? t(locked) : undefined}
onClick={() => { if (route.preference !== preference) route.onChange(preference); }}>
{vis && <Glyph name={preference === "auto" ? "branch" : preference === "p2p" ? "link" : "server"} size={17} />}
<Cap k={`playback.route.${preference}`} />
</Chip>;
})}</RowGroup>
{!vis && <p className={route.rejected ? "is-error" : undefined} role={route.rejected ? "status" : undefined}>{t(routeHint)}</p>}
{vis && route.rejected && <Pill icon="alert" tone="bad" label={t(routeHint)} comic="settings-failed" />}
</>}
</section>
</div>;
@@ -66,6 +66,7 @@ const PRESENTATIONS: Partial<Record<ComicKind | HintKind, ComicPresentation>> =
"hint-admission-password": { tone: "off", motion: "still" },
"hint-admission-invite": { tone: "off", motion: "still" },
"hint-route-p2p-required": LIMITED,
"hint-route-sfu-required": LIMITED,
"hint-volume-basic": LIMITED,
"hint-no-audio": LIMITED,
"hint-pip-unavailable": LIMITED,
+1 -1
View File
@@ -26,7 +26,6 @@ export const HINT_KINDS: readonly HintKind[] = [
"hint-fit-contain",
"hint-fit-cover",
"hint-fit-fill",
"hint-reaction-picker",
"hint-share-start",
"hint-share-stop",
"hint-microphone-on",
@@ -84,6 +83,7 @@ export const HINT_KINDS: readonly HintKind[] = [
"hint-theater-exit",
"hint-route-p2p",
"hint-route-p2p-required",
"hint-route-sfu-required",
"hint-route-sfu",
"hint-client-local",
"hint-app-ready",
@@ -391,6 +391,13 @@ ${rmBlock(
</>
);
// A site requiring server forwarding excludes the direct peer path.
const HintRouteSfuRequired: HintScene = ({ theme }) => <>
<HintRouteSfu theme={theme} />
<path d="M58 58h44" fill="none" stroke={FAINT} strokeWidth={2} strokeDasharray="3 3" />
<RedX cx={80} cy={58} arm={7} />
</>;
// The home mark distinguishes local sharing from a public direct route.
const HintClientLocal: HintScene = ({ theme }) => (
<>
@@ -440,6 +447,7 @@ export const SET4_SCENES: Record<Set4Kind, HintScene> = {
"hint-route-p2p": HintRouteP2p,
"hint-route-p2p-required": HintRouteP2pRequired,
"hint-route-sfu": HintRouteSfu,
"hint-route-sfu-required": HintRouteSfuRequired,
"hint-client-local": HintClientLocal,
"hint-app-ready": () => <g transform="translate(112 0)" color={INK}><BrandMark size={96} motion="loop" /></g>,
"hint-client-site": HintClientSite,
+4 -2
View File
@@ -130,6 +130,7 @@ export function Chip({
onClick,
title,
hint,
hintText,
name,
value,
children,
@@ -140,6 +141,7 @@ export function Chip({
title: string;
/** Shared hint comic; text modes add the localized caption. */
hint?: HintKind;
hintText?: string;
name?: string;
value?: string;
children: ReactNode;
@@ -157,7 +159,7 @@ export function Chip({
disabled={disabled && !softDisabled}
aria-disabled={softDisabled || undefined}
style={softDisabled ? SOFT_DISABLED_STYLE : undefined}
aria-label={title}
aria-label={disabled && hintText ? `${title} · ${hintText}` : title}
onClick={
softDisabled
? blockSoftDisabledClick
@@ -173,7 +175,7 @@ export function Chip({
</button>
);
return hint ? (
<Tooltip kind={hint} text={vis ? undefined : title}>{chip}</Tooltip>
<Tooltip kind={hint} text={vis ? undefined : hintText ?? title}>{chip}</Tooltip>
) : (
chip
);
+1 -1
View File
@@ -597,7 +597,7 @@ export const en: Record<CopyKey, string> = {
"viewer.msg.waitingHost": "Waiting for the host to share",
"viewer.msg.preparingP2p": "Establishing P2P",
"viewer.msg.connectionRetry": "Retrying ({current}/{total})",
"viewer.msg.preparingSfu": "Connecting backup route",
"viewer.msg.preparingSfu": "Connecting server relay",
"viewer.msg.allocating": "Allocating a route",
"viewer.msg.receiving": "Receiving video",
"viewer.msg.playing": "Playing",
+1 -1
View File
@@ -597,7 +597,7 @@ export const zh = {
"viewer.msg.waitingHost": "等待开始分享",
"viewer.msg.preparingP2p": "正在建立 P2P",
"viewer.msg.connectionRetry": "正在重试({current}/{total})",
"viewer.msg.preparingSfu": "正在连接备用线路",
"viewer.msg.preparingSfu": "正在连接服务器中转",
"viewer.msg.allocating": "正在分配线路",
"viewer.msg.receiving": "正在接收画面",
"viewer.msg.playing": "正在播放",
+32 -21
View File
@@ -1,3 +1,4 @@
import { retireSfuPublisherQualityEvidence } from "./sender-quality-evidence";
import type { CopyKey } from "../ui/copy";
import type { MediaFailure } from "../ui/media-failure";
import type {
@@ -256,7 +257,7 @@ export class HostSfuRoute {
}
slot.failed = true;
}
await disconnectPublisher(publisher);
await this.disconnectPublisher(slot);
return;
}
if (this.pending !== slot || !this.route.owns(token)) {
@@ -264,7 +265,7 @@ export class HostSfuRoute {
this.pending = null;
}
slot.failed = true;
await disconnectPublisher(publisher);
await this.disconnectPublisher(slot);
return;
}
slot.connected = true;
@@ -275,7 +276,7 @@ export class HostSfuRoute {
this.pending = null;
}
slot.failed = true;
await disconnectPublisher(publisher);
await this.disconnectPublisher(slot);
return;
}
prepared = await this.preparePublisher(slot);
@@ -288,7 +289,7 @@ export class HostSfuRoute {
}
} catch {
this.failPublisherSlot(slot);
await disconnectPublisher(publisher);
await this.disconnectPublisher(slot);
}
}
@@ -361,7 +362,7 @@ export class HostSfuRoute {
for (const [index, slot] of slots.entries()) {
if (results[index] === false) {
this.failPublisherSlot(slot);
await disconnectPublisher(slot.publisher);
await this.disconnectPublisher(slot);
}
}
});
@@ -398,7 +399,7 @@ export class HostSfuRoute {
// Cancel before joining the transition queue: its current operation may
// itself be waiting for one of these publishers to finish preparation.
await Promise.all([
pending ? disconnectPublisher(pending.publisher) : undefined,
pending ? this.disconnectPublisher(pending) : undefined,
active && active !== pending ? this.disconnectRetiredPublisher(active) : undefined,
]);
}
@@ -486,7 +487,7 @@ export class HostSfuRoute {
if (!this.route.markMediaActive(token)) {
this.active = previous;
pending.failed = true;
await disconnectPublisher(pending.publisher);
await this.disconnectPublisher(pending);
return;
}
this.lastFailureStage = null;
@@ -496,7 +497,7 @@ export class HostSfuRoute {
if (previous.active) {
await previous.publisher.deactivate().catch(() => false);
}
await disconnectPublisher(previous.publisher);
await this.disconnectPublisher(previous);
}
}
@@ -511,12 +512,12 @@ export class HostSfuRoute {
try {
if (!(await slot.publisher.activate(stream, profile, videoCodec))) {
this.failPublisherSlot(slot);
await disconnectPublisher(slot.publisher);
await this.disconnectPublisher(slot);
return false;
}
slot.publisher.setPaused(this.paused);
if (this.pending !== slot || !this.ownsPublisherSlot(slot)) {
await disconnectPublisher(slot.publisher);
await this.disconnectPublisher(slot);
return false;
}
slot.active = true;
@@ -527,7 +528,7 @@ export class HostSfuRoute {
!(await slot.publisher.replaceStream(latestStream))
) {
this.failPublisherSlot(slot);
await disconnectPublisher(slot.publisher);
await this.disconnectPublisher(slot);
return false;
}
const latestProfile = this.events.getProfile();
@@ -536,13 +537,13 @@ export class HostSfuRoute {
!(await slot.publisher.updateProfile(latestProfile))
) {
this.failPublisherSlot(slot);
await disconnectPublisher(slot.publisher);
await this.disconnectPublisher(slot);
return false;
}
return this.pending === slot && this.ownsPublisherSlot(slot);
} catch {
this.failPublisherSlot(slot);
await disconnectPublisher(slot.publisher);
await this.disconnectPublisher(slot);
return false;
}
}
@@ -570,7 +571,7 @@ export class HostSfuRoute {
const pending = this.pending;
this.pending = null;
pending.failed = true;
const closing = disconnectPublisher(pending.publisher);
const closing = this.disconnectPublisher(pending);
void this.queueTransition(() => closing);
}
@@ -605,7 +606,7 @@ export class HostSfuRoute {
if (active.active) {
await active.publisher.deactivate().catch(() => false);
}
await disconnectPublisher(active.publisher);
await this.disconnectPublisher(active);
}
private handleFailure(slot: HostPublisherSlot): void {
@@ -632,6 +633,7 @@ export class HostSfuRoute {
if (wasActive) {
this.active = null;
}
this.retirePublisherEvidence(slot);
if (revision === null || phase === null) {
return;
@@ -694,6 +696,21 @@ export class HostSfuRoute {
});
}
private async disconnectPublisher(slot: HostPublisherSlot): Promise<void> {
this.retirePublisherEvidence(slot);
await slot.publisher.disconnect().catch(() => undefined);
}
private retirePublisherEvidence(slot: HostPublisherSlot): void {
const generation = slot.publicationGeneration;
if (![this.active, this.pending].some((current) =>
current && current !== slot && !current.failed &&
current.publicationGeneration === generation,
)) {
retireSfuPublisherQualityEvidence(generation);
}
}
private handlePublisherStats(
slot: HostPublisherSlot,
metrics: ConnectionMetrics | null,
@@ -715,12 +732,6 @@ export class HostSfuRoute {
}
}
async function disconnectPublisher(
publisher: HostPublisherTransport,
): Promise<void> {
await publisher.disconnect().catch(() => undefined);
}
function sfuFailureWarning(stage: SfuPublisherFailureStage): MediaFailure {
const stageKey: Record<SfuPublisherFailureStage, CopyKey> = {
connect: "host.warn.sfuStage.connect",
@@ -15,6 +15,18 @@ const unknownPublications = new Set<string>();
const connectionSampleTimestamps = new Map<string, number>();
const publicationSampleTimestamps = new Map<string, number>();
export function retireSenderQualityEvidence(connectionId: string): void {
connectionGenerations.delete(connectionId);
unknownConnections.delete(connectionId);
connectionSampleTimestamps.delete(connectionId);
}
export function retireSfuPublisherQualityEvidence(publicationGeneration: string): void {
publicationGenerations.delete(publicationGeneration);
unknownPublications.delete(publicationGeneration);
publicationSampleTimestamps.delete(publicationGeneration);
}
export function invalidateSenderQualityEvidence(): void {
senderEvidenceGeneration += 1;
connectionGenerations.clear();
@@ -87,6 +99,10 @@ export function senderQualityEvidenceFromSnapshot(
snapshot: PeerSnapshot,
routeRevision: number,
): Extract<ClientMessage, { type: "sender-quality-evidence" }> | null {
if (snapshot.connectionState === "failed" || snapshot.connectionState === "closed") {
retireSenderQualityEvidence(snapshot.connectionId);
return null;
}
const evidence = nativeQualityState(snapshot.metrics);
const rawSampleTimestampMs = snapshot.metrics.sampleTimestampMs;
const hasIdentity =
+2
View File
@@ -5,6 +5,7 @@ import type {
SignalPayload,
} from "../../shared/protocol";
import { EMPTY_METRICS, type PeerSnapshot } from "../types";
import { retireSenderQualityEvidence } from "../media/sender-quality-evidence";
import type { HostMediaPeer } from "../webrtc/host-peer";
import { NativeSenderEdge, type NativeEdgeControl } from "./native-sender-edge";
import type { NativeVideoCodec } from "./wire";
@@ -223,6 +224,7 @@ export class NativeSenderPeer implements HostMediaPeer {
dispose(): void {
if (this.disposed) return;
this.disposed = true;
retireSenderQualityEvidence(this.connectionId);
this.edge.dispose();
}
}
+18 -16
View File
@@ -197,8 +197,8 @@ import {
} from "../webrtc/video-codec";
import { preferredVideoCodecForTrack } from "../webrtc/video-codec-preflight";
import {
hostActionErrorNotice,
hostServerErrorNotice,
hostActionErrorKey,
hostServerErrorKey,
shouldPauseLocalPreview,
sourceSwitchNotice,
isCapturePermissionFailure,
@@ -250,10 +250,10 @@ function captureDetails(stream: MediaStream, native = false, sourceAudio?: boole
};
}
function readableError(error: unknown, action: HostAction): string {
function readableError(error: unknown, action: HostAction): StatusNoticeMessage {
return error instanceof ApiError
? error.message
: hostActionErrorNotice(error, action);
: { key: hostActionErrorKey(error, action) };
}
function closeAbandonedRoom(room: HostRoomIdentity): void {
@@ -485,7 +485,7 @@ export function HostPage({
readDisplayName(defaultHostDisplayName(vis)),
);
const [displayNameDraft, setDisplayNameDraft] = useState(displayName);
const [displayNameError, setDisplayNameError] = useState<string | null>(null);
const [displayNameError, setDisplayNameError] = useState(false);
const [editingDisplayName, setEditingDisplayName] = useState(false);
const [viewerQualityEvidence, setViewerQualityEvidence] = useState<
ReadonlyMap<string, ViewerQualityEvidencePresentation>
@@ -522,7 +522,9 @@ export function HostPage({
if (error instanceof NativeMediaBridgeError || (error instanceof NativeRequestError &&
(["unavailable", "disconnected", "send-failed"].includes(error.reason) || error.operation === "prepare-edge"))) action = "connection";
const permissionMissing = isCapturePermissionFailure(error, action);
setNoticeValue({ kind: "text", text: readableError(error, action), target, tone: permissionMissing ? "warn" : "bad",
const message = readableError(error, action);
setNoticeValue({ ...(typeof message === "string" ? { kind: "text", text: message } : { kind: "key", ...message }),
target, tone: permissionMissing ? "warn" : "bad",
failureCode: error instanceof ApiError ? `site/http-${error.status}` : hostFailureCode(error, action),
comic: permissionMissing ? "hint-capture-browser" : action === "connection" ? "route-failed" : action === "capture" || action === "source"
? "source-failed" : action === "quality" || action === "sourceAudio" ? "settings-failed" : "warning" });
@@ -2547,7 +2549,7 @@ export function HostPage({
displayNameRef.current = initialDisplayName;
setDisplayName(initialDisplayName);
setDisplayNameDraft(initialDisplayName);
setDisplayNameError(null);
setDisplayNameError(false);
const signal = new SignalingClient(
{
roomId: activeRoom.roomId,
@@ -2627,7 +2629,7 @@ export function HostPage({
return;
}
if (message.type === "error" && message.code === "HOST_ALREADY_CONNECTED") {
endRoomSession(hostServerErrorNotice(message.code), "signal-failed");
endRoomSession({ key: hostServerErrorKey(message.code) }, "signal-failed");
return;
}
const reauthenticated =
@@ -2669,7 +2671,7 @@ export function HostPage({
}
if (message.type === "sharing-start-failed") {
if (localShareActive && message.shareGeneration === currentShareGeneration) {
endSharing(hostServerErrorNotice(message.code), false, "signal-failed", "bad");
endSharing({ key: hostServerErrorKey(message.code) }, false, "signal-failed", "bad");
}
return;
}
@@ -2679,7 +2681,7 @@ export function HostPage({
return;
}
if (message.type === "error") {
setNotice(hostServerErrorNotice(message.code), "signal-failed", "bad");
setNoticeKey(hostServerErrorKey(message.code), "signal-failed", "bad");
return;
}
const mediaActive =
@@ -3487,13 +3489,13 @@ export function HostPage({
const hostFallback = defaultHostDisplayName(vis);
const saved = saveDisplayName(displayNameDraft, hostFallback);
if (!saved) {
setDisplayNameError(say("host.nameError"));
setDisplayNameError(true);
return;
}
displayNameRef.current = saved;
setDisplayName(saved);
setDisplayNameDraft(saved);
setDisplayNameError(null);
setDisplayNameError(false);
setEditingDisplayName(false);
setHasCustomDisplayName(readStoredDisplayName() !== null);
if (signalRef.current && !signalRef.current.setDisplayName(saved)) {
@@ -4068,7 +4070,7 @@ export function HostPage({
aria-invalid={displayNameError ? "true" : undefined}
onChange={(event) => {
setDisplayNameDraft(event.target.value);
setDisplayNameError(null);
setDisplayNameError(false);
}}
/>
</span>
@@ -4085,7 +4087,7 @@ export function HostPage({
hint="hint-close"
onClick={() => {
setDisplayNameDraft(displayName);
setDisplayNameError(null);
setDisplayNameError(false);
setEditingDisplayName(false);
}}
/>
@@ -4103,7 +4105,7 @@ export function HostPage({
hint="hint-rename"
onClick={() => {
setDisplayNameDraft(displayName);
setDisplayNameError(null);
setDisplayNameError(false);
setEditingDisplayName(true);
}}
/>
@@ -4113,7 +4115,7 @@ export function HostPage({
<Pill
icon="alert"
tone="bad"
label={displayNameError}
label={t("host.nameError")}
alert
comic="name-invalid"
/>
+18 -18
View File
@@ -43,44 +43,44 @@ export function isCapturePermissionFailure(error: unknown, action: HostAction):
error instanceof DOMException && error.name === "NotAllowedError";
}
export function hostActionErrorNotice(
export function hostActionErrorKey(
error: unknown,
action: HostAction,
): string {
): CopyKey {
if (error instanceof NativeRequestError) {
switch (error.reason) {
case "unavailable":
case "disconnected":
case "send-failed": return say("native.fail.controlDisconnected");
case "timeout": return say("native.fail.requestTimeout");
case "invalid-response": return say("native.fail.invalidResponse");
case "send-failed": return "native.fail.controlDisconnected";
case "timeout": return "native.fail.requestTimeout";
case "invalid-response": return "native.fail.invalidResponse";
case "rejected":
if (error.operation === "start-share") return say("native.fail.captureStart");
if (error.operation === "prepare-edge") return say("native.fail.edgePrepare");
if (error.operation === "start-share") return "native.fail.captureStart";
if (error.operation === "prepare-edge") return "native.fail.edgePrepare";
break;
}
}
if (error instanceof NativeMediaBridgeInitializationError) return say("native.fail.browserMedia");
if (error instanceof NativeMediaBridgeError) return say("native.fail.edge");
if (isCapturePermissionFailure(error, action)) return say("host.capture.cancelled");
if (error instanceof NativeMediaBridgeInitializationError) return "native.fail.browserMedia";
if (error instanceof NativeMediaBridgeError) return "native.fail.edge";
if (isCapturePermissionFailure(error, action)) return "host.capture.cancelled";
if (
error instanceof DOMException &&
(action === "capture" || action === "source")
) {
switch (error.name) {
case "NotFoundError":
return say("host.capture.noSource");
return "host.capture.noSource";
case "NotReadableError":
return say("host.capture.readFailed");
return "host.capture.readFailed";
case "SecurityError":
return say("host.capture.unavailable");
return "host.capture.unavailable";
case "InvalidStateError":
return say("host.capture.inactive");
return "host.capture.inactive";
case "OverconstrainedError":
return say("host.capture.constraints");
return "host.capture.constraints";
}
}
return say(HOST_ACTION_FALLBACK[action]);
return HOST_ACTION_FALLBACK[action];
}
/** Safe support context: never copy arbitrary exception text or request fields. */
@@ -113,8 +113,8 @@ export function hostFailureChecks(code: string): CopyKey[] {
return [];
}
export function hostServerErrorNotice(code: ServerErrorCode): string {
return say(HOST_SERVER_ERROR_NOTICE[code]);
export function hostServerErrorKey(code: ServerErrorCode): CopyKey {
return HOST_SERVER_ERROR_NOTICE[code];
}
export function sourceSwitchNotice({
+1
View File
@@ -99,6 +99,7 @@ export type Set4Kind =
| "hint-theater-exit"
| "hint-route-p2p"
| "hint-route-p2p-required"
| "hint-route-sfu-required"
| "hint-route-sfu"
| "hint-client-local"
| "hint-app-ready"
+5 -1
View File
@@ -22,6 +22,7 @@ import {
type QualityProfile,
} from "../media/quality";
import { cloneSenderVideoTrack, stopSenderVideoTrack } from "../media/sender-video-track";
import { retireSenderQualityEvidence } from "../media/sender-quality-evidence";
import { EMPTY_METRICS, type PeerSnapshot } from "../types";
import {
captureMetrics,
@@ -137,8 +138,9 @@ export class HostPeer {
: null;
this.startupVideoProfilePending = needsStartupVideoProfile(desiredProfile);
this.encodedStreamsEnabled = !!videoPool && supportsBrowserEncoding();
let allocatedConnection: RTCPeerConnection | null = null;
try {
this.connection = new RTCPeerConnection({
this.connection = allocatedConnection = new RTCPeerConnection({
...(this.encodedStreamsEnabled ? { encodedInsertableStreams: true } : {}),
iceServers: iceServersWithNatPrediction(
iceConfig.iceServers,
@@ -148,6 +150,7 @@ export class HostPeer {
});
if (events.onInputChannel) events.onInputChannel(this.connection.createDataChannel(INPUT_CHANNEL), this.connection);
} catch (error) {
allocatedConnection?.close();
stopSenderVideoTrack(this.senderVideoTrack);
throw error;
}
@@ -517,6 +520,7 @@ export class HostPeer {
return;
}
this.lifetime.abort();
retireSenderQualityEvidence(this.connectionId);
this.nextNegotiationEpoch();
this.ordinaryAnswerEpoch = null;
this.pendingNegotiation = false;
+35 -34
View File
@@ -1,13 +1,13 @@
import { describe, expect, it } from "vitest";
import { setCopy } from "../src/client/ui/copy.ts";
import { say, setCopy } from "../src/client/ui/copy.ts";
import { NativeMediaBridgeError, NativeMediaBridgeInitializationError } from "../src/client/native/media-bridge";
import { NativeRequestError } from "../src/client/native/client";
import {
hostActionErrorNotice,
hostActionErrorKey,
hostFailureCode,
hostFailureChecks,
hostServerErrorNotice,
hostServerErrorKey,
shouldPauseLocalPreview,
sourceSwitchNotice,
} from "../src/client/pages/host-page-notices.ts";
@@ -19,9 +19,9 @@ describe("host error notices", () => {
const rejected = new NativeRequestError("rejected", "start-share", { cause: "private source title" });
const timeout = new NativeRequestError("timeout", "start-share");
const disconnected = new NativeRequestError("disconnected", "start-share");
expect(hostActionErrorNotice(rejected, "capture")).toContain("未能采集所选来源");
expect(hostActionErrorNotice(timeout, "capture")).toContain("响应超时");
expect(hostActionErrorNotice(disconnected, "capture")).toContain("连接已断开");
expect(hostActionErrorKey(rejected, "capture")).toBe("native.fail.captureStart");
expect(hostActionErrorKey(timeout, "capture")).toBe("native.fail.requestTimeout");
expect(hostActionErrorKey(disconnected, "capture")).toBe("native.fail.controlDisconnected");
expect(hostFailureCode(rejected, "capture")).toBe("app/start-share/rejected");
expect(hostFailureCode(new Error("secret invitation and source"), "capture")).toBe("capture/unknown");
expect(hostFailureCode(new DOMException("secret", "UnrecognizedError"), "capture")).toBe("capture/unknown");
@@ -57,34 +57,35 @@ describe("host error notices", () => {
const failure = new NativeMediaBridgeInitializationError("private detail", {
cause: new DOMException("private cause", "NotAllowedError"),
});
expect(hostActionErrorNotice(failure, "capture")).toBe(notice);
expect(hostActionErrorKey(failure, "capture")).toBe("native.fail.browserMedia");
expect(say(hostActionErrorKey(failure, "capture"))).toBe(notice);
} finally {
setCopy({ lang: "zh" });
}
});
it("classifies the native preview bridge as a connection failure", () => {
expect(hostActionErrorNotice(new NativeMediaBridgeError("private detail"), "capture"))
.toBe("Piik App 媒体连接失败");
expect(hostActionErrorKey(new NativeMediaBridgeError("private detail"), "capture"))
.toBe("native.fail.edge");
});
it("maps every server error code without exposing server text", () => {
const notices = {
AUTH_REQUIRED: "站点访问已失效,请重新验证",
INVALID_MESSAGE: "页面版本已更新,请刷新后重试",
INVALID_TOKEN: "分享凭证已失效,请重新创建房间",
ROOM_NOT_FOUND: "房间不存在",
ROOM_ACCESS_DENIED: "当前操作没有权限",
ROOM_FULL: "房间已满",
HOST_ALREADY_CONNECTED: "此房间已在另一个页面中分享",
PEER_NOT_FOUND: "对应的观看连接已经离开",
FORBIDDEN: "当前操作不可用",
SERVER_ERROR: "服务暂时不可用,请稍后重试",
AUTH_REQUIRED: "gate.expired",
INVALID_MESSAGE: "host.terminated.stale",
INVALID_TOKEN: "host.err.invalidToken",
ROOM_NOT_FOUND: "viewer.msg.notFound",
ROOM_ACCESS_DENIED: "host.err.accessDenied",
ROOM_FULL: "join.full",
HOST_ALREADY_CONNECTED: "host.err.alreadyConnected",
PEER_NOT_FOUND: "host.err.peerGone",
FORBIDDEN: "host.err.forbidden",
SERVER_ERROR: "host.err.serverError",
} as const;
for (const [code, notice] of Object.entries(notices)) {
expect(
hostServerErrorNotice(code as keyof typeof notices),
hostServerErrorKey(code as keyof typeof notices),
).toBe(notice);
expect(notice).not.toContain("server-internal-sentinel");
}
@@ -92,27 +93,27 @@ describe("host error notices", () => {
it("uses stable action messages instead of arbitrary exception text", () => {
const sentinel = new Error("browser-internal-sentinel");
expect(hostActionErrorNotice(sentinel, "quality")).toBe(
"应用画质设置失败",
expect(hostActionErrorKey(sentinel, "quality")).toBe(
"host.fail.quality",
);
expect(hostActionErrorNotice(sentinel, "connection")).toBe(
"观看连接处理失败",
expect(hostActionErrorKey(sentinel, "connection")).toBe(
"host.fail.connection",
);
expect(hostActionErrorNotice(sentinel, "room")).toBe("房间操作失败");
expect(hostActionErrorNotice(sentinel, "source")).toBe("切换分享来源失败");
expect(hostActionErrorNotice(sentinel, "sourceAudio")).toBe("未能更新来源声音,请重试");
expect(hostActionErrorKey(sentinel, "room")).toBe("host.fail.room");
expect(hostActionErrorKey(sentinel, "source")).toBe("host.fail.source");
expect(hostActionErrorKey(sentinel, "sourceAudio")).toBe("host.fail.sourceAudio");
});
it.each([
["NotAllowedError", "屏幕选择已取消或没有共享权限"],
["NotFoundError", "没有可用的屏幕分享来源"],
["NotReadableError", "无法读取所选分享来源,请重新选源"],
["SecurityError", "当前页面无法启动屏幕分享"],
["InvalidStateError", "请回到当前页面,再点击分享并选择来源。"],
["OverconstrainedError", "所选来源无法满足当前画面设置。请降低设置或换一个来源。"],
["NotAllowedError", "host.capture.cancelled"],
["NotFoundError", "host.capture.noSource"],
["NotReadableError", "host.capture.readFailed"],
["SecurityError", "host.capture.unavailable"],
["InvalidStateError", "host.capture.inactive"],
["OverconstrainedError", "host.capture.constraints"],
])("maps capture DOMException %s", (name, notice) => {
expect(
hostActionErrorNotice(new DOMException("raw-browser-text", name), "capture"),
hostActionErrorKey(new DOMException("raw-browser-text", name), "capture"),
).toBe(notice);
});
});
+42
View File
@@ -5,6 +5,7 @@ import {
type QualityProfile,
} from "../src/client/media/quality.ts";
import { HostProvisionalChild } from "../src/client/media/host-provisional-child.ts";
import { senderQualityEvidenceFromSnapshot } from "../src/client/media/sender-quality-evidence.ts";
import { EMPTY_METRICS, type PeerSnapshot } from "../src/client/types.ts";
import { HostPeer, RENEGOTIATION_ANSWER_TIMEOUT_MS, type HostMediaPeer } from "../src/client/webrtc/host-peer.ts";
import {
@@ -560,6 +561,47 @@ function encodedPeerFixture() {
}
describe("HostPeer sender-frame lifetime", () => {
it("retires sender evidence with its connection", () => {
const peer = createPeer(createStream(createTrack("video", "source"), null));
const snapshot = peer.getSnapshot();
expect(senderQualityEvidenceFromSnapshot(snapshot, 1)?.state).toBe("unknown");
expect(senderQualityEvidenceFromSnapshot(snapshot, 1)).toBeNull();
peer.dispose();
expect(senderQualityEvidenceFromSnapshot(snapshot, 1)?.state).toBe("unknown");
});
// Channel setup can fail before the peer reaches its disposal owner.
it.each(["allocation", "binding"] as const)(
"closes the allocated connection when input channel %s fails",
(failure) => {
const video = createTrack("video", "input-setup");
const error = new DOMException("Input setup failed", "OperationError");
class InputConnection extends FakePeerConnection {
createDataChannel(): RTCDataChannel {
if (failure === "allocation") throw error;
return {} as RTCDataChannel;
}
}
vi.stubGlobal("RTCPeerConnection", InputConnection);
expect(() => new HostPeer(
"viewer-peer",
{ iceServers: [] },
createStream(video, null),
QUALITY_PROFILES["720p30"],
{
sendSignal: () => true,
onUpdate: () => {},
onInputChannel: () => { throw error; },
},
)).toThrow(error);
expect(FakePeerConnection.latest?.connectionState).toBe("closed");
expect(FakePeerConnection.activeCount).toBe(0);
const clone = vi.mocked(video.clone).mock.results[0]!.value;
expect(clone.stop).toHaveBeenCalledOnce();
expect(video.stop).not.toHaveBeenCalled();
},
);
it.each(["current", "replaced", "pending"])("handles a %s frame input ending in its owning operation", async (phase) => {
const endings: Array<{ track: MediaStreamTrack; end: () => void }> = [];
vi.spyOn(senderTracks, "cloneSenderVideoTrack").mockImplementation((source, onEnded) => {
+33 -10
View File
@@ -15,7 +15,8 @@ import { InputRoute } from "../src/client/remote-control/input-route";
import { reconcileBoundedMediaChildren } from "../src/client/webrtc/media-assignment";
import { debugError, debugEvent, debugOperation } from "../src/client/lib/debug";
import { ApiError } from "../src/client/lib/api";
import { hostActionErrorNotice, hostFailureCode, isCapturePermissionFailure } from "../src/client/pages/host-page-notices";
import { hostActionErrorKey, hostServerErrorKey, hostFailureCode, isCapturePermissionFailure } from "../src/client/pages/host-page-notices";
import { say, setCopy } from "../src/client/ui/copy";
// Exercise the actual page owners without mounting capture hardware or a Browser.
const source = ts.createSourceFile("HostPage.tsx", readFileSync(
@@ -28,18 +29,22 @@ const owners = new Set(["changeQuality", "commitQuality", "rememberQuality", "lo
"openCaptureSourcePicker", "startBrowserShareFromPicker", "startNativeShareFromPicker",
"startSharing", "connectRoomSignal", "createReplacementRoom", "beginRoomMutation", "finishRoomMutation", "setCaptureError", "changeMicrophone", "toggleSharingPause",
"startPeer", "reconcileHostChildren", "setNotice", "setNoticeKey", "setStatusNotice", "setNoticeError", "setNoticeErrorKey", "endSharing", "disposeResources", "hostTerminationKey", "copyRoomLink", "isCurrentRoomAuthority",
"handleRoomAccessFailure", "replaceCurrentRoom", "forgetRoom", "endRoomSession"]);
"handleRoomAccessFailure", "replaceCurrentRoom", "forgetRoom", "endRoomSession", "readableError"]);
const functions: string[] = [];
let noticeRendering = "";
function collect(node: ts.Node): void {
if (ts.isFunctionDeclaration(node) && node.name && owners.has(node.name.text)) {
functions.push(node.getText(source));
owners.delete(node.name.text);
}
if (ts.isVariableDeclaration(node) && node.name.getText(source) === "noticeText") {
noticeRendering = node.initializer!.getText(source);
}
ts.forEachChild(node, collect);
}
collect(source);
if (owners.size) throw new Error(`Missing Host owner: ${[...owners].join(", ")}`);
if (owners.size || !noticeRendering) throw new Error(`Missing Host owner: ${[...owners].join(", ")}`);
const executable = ts.transpileModule(functions.join("\n"), {
compilerOptions: { target: ts.ScriptTarget.ES2022 },
}).outputText;
@@ -73,7 +78,7 @@ function fixture(launchedByClient = true) {
stopReceive: vi.fn(async () => undefined), stopShare: vi.fn(async () => undefined) };
const route = { updateProfile: vi.fn(async () => true), resyncAuthoritative: vi.fn(async (): Promise<void> => undefined) };
const state = {
debugError, debugEvent, debugOperation, NativeCompatibilityError, NativeRequestError, NativeMediaBridgeError, isCapturePermissionFailure, hostFailureCode, DOMException, AbortController,
debugError, debugEvent, debugOperation, NativeCompatibilityError, NativeRequestError, NativeMediaBridgeError, isCapturePermissionFailure, hostFailureCode, hostActionErrorKey, hostServerErrorKey, DOMException, AbortController,
launchedByClient, isClientActivated: vi.fn(() => launchedByClient), hostRoomSessionAvailable: false,
NativeClient: { connect: vi.fn(async (_options?: { signal: AbortSignal }): Promise<typeof client | null> => null) },
nativeClientConnectRef: ref<{ promise: Promise<typeof client | null>; controller: AbortController } | null>(null),
@@ -108,7 +113,7 @@ function fixture(launchedByClient = true) {
peersRef: ref(new Map([["viewer", peer]])), hostProvisionalChildRef: ref(null), hostSfuRouteRef: ref(route),
signalRef: ref({ setHostQualitySettings: vi.fn(), setAudioAvailable: vi.fn(), send: vi.fn() }),
setQualitySettings: vi.fn(), setAdvancedQuality: vi.fn(), setChangingQuality: vi.fn(), savePreferredQuality: vi.fn(),
setNoticeValue: vi.fn(), setNoticeError: vi.fn(), readableError: hostActionErrorNotice,
setNoticeValue: vi.fn(), setNoticeError: vi.fn(),
setDetails: vi.fn(), setNativeActive: vi.fn(), setRemoteControlState: vi.fn(),
remoteInputPeersRef: ref([]), getRuntimeCapabilities: vi.fn(async () => ({ remoteInput: false })),
applyCaptureProfile: vi.fn(async (_stream: unknown, profile: QualitySettings) => { physical = profile; }),
@@ -151,6 +156,7 @@ function fixture(launchedByClient = true) {
start: () => start( { kind: "native", client, target: {}, audio: false, path: {} }) as Promise<void>,
startBrowser: () => start({ kind: "browser" }) as Promise<void>,
writeNoticeError,
renderNotice: (noticeValue: unknown) => runInContext(noticeRendering, createContext({ noticeValue, t: say })),
discover: context.acquireNativeClient as () => Promise<typeof client | null>,
requestShare: context.requestSharing as () => void,
startNative: () => context.startNativeShare(1, "share", { client, target: {}, audio: false, path: {} }) as Promise<unknown>,
@@ -257,7 +263,6 @@ describe("Host room ownership", () => {
setDisplayName: vi.fn(), setDisplayNameDraft: vi.fn(), setDisplayNameError: vi.fn(),
setInteractionSession: vi.fn(), setSignalStatus: vi.fn(), forgetRoom,
onAuthorizationRequired: vi.fn(), clearHostRoom: vi.fn(), writePreferredRoom: vi.fn(),
hostServerErrorNotice: (code: string) => code,
});
return { ...current, room, signals, forgetRoom, connect: (value = room) => current.context.connectRoomSignal(value) as Signal };
}
@@ -841,7 +846,6 @@ describe("Host quality ownership", () => {
const setNoticeValue = vi.fn();
Object.assign(current.context, {
phase: "idle", setNoticeValue, setNoticeError: current.writeNoticeError,
readableError: hostActionErrorNotice,
captureBrowserSource: vi.fn(async () => { throw denied; }),
});
current.activeGenerationRef.current = null;
@@ -849,7 +853,7 @@ describe("Host quality ownership", () => {
current.client.startShare.mockRejectedValue(denied);
await (entry === "native" ? current.start() : current.startBrowser());
expect(setNoticeValue).toHaveBeenLastCalledWith({
kind: "text", text: hostActionErrorNotice(denied, "capture"),
kind: "key", key: "host.capture.cancelled",
target: "television", comic: "hint-capture-browser", tone: "warn",
failureCode: "browser/NotAllowedError",
});
@@ -1014,12 +1018,11 @@ describe("Host quality ownership", () => {
const setNoticeValue = vi.fn();
Object.assign(current.context, {
setNoticeValue, setNoticeError: current.writeNoticeError,
readableError: hostActionErrorNotice,
});
current.client.replaceShareSource.mockRejectedValue(denied);
await current.switchSource();
expect(setNoticeValue).toHaveBeenLastCalledWith({
kind: "text", text: hostActionErrorNotice(denied, "source"),
kind: "key", key: "host.capture.cancelled",
target: "operation", comic: "hint-capture-browser", tone: "warn",
failureCode: "browser/NotAllowedError",
});
@@ -1027,6 +1030,26 @@ describe("Host quality ownership", () => {
expect(current.track.stop).not.toHaveBeenCalled();
});
it("keeps error keys until the actual page rendering uses the current language", () => {
const current = fixture();
const denied = new DOMException("private capture detail", "NotAllowedError");
current.writeNoticeError(denied, "capture", "television");
const notice = current.setNoticeValue.mock.lastCall![0];
expect(notice).toMatchObject({ kind: "key", key: "host.capture.cancelled" });
try {
setCopy({ lang: "en" });
expect(current.renderNotice(notice)).toBe("Screen selection cancelled or not permitted");
setCopy({ lang: "zh" });
expect(current.renderNotice(notice)).toBe("屏幕选择已取消或没有共享权限");
current.context.setNoticeKey(hostServerErrorKey("ROOM_FULL"), "signal-failed", "bad");
expect(current.renderNotice(current.setNoticeValue.mock.lastCall![0])).toBe("房间已满");
current.writeNoticeError(new ApiError("HTTP failure with specific context", 403), "room");
expect(current.renderNotice(current.setNoticeValue.mock.lastCall![0])).toBe("HTTP failure with specific context");
} finally {
setCopy({ lang: "zh" });
}
});
it.each([
{ key: "host.stopNotice", comic: "share-ended", tone: "off" },
{ key: "host.shareEnded", comic: "source-failed", tone: "bad" },
+3
View File
@@ -115,6 +115,9 @@ describe("native Host peer quality", () => {
},
});
peer.dispose();
expect(senderQualityEvidenceFromSnapshot(snapshots.at(-1)!, 7)).toMatchObject({
state: "unknown",
});
});
it("applies the latest relay ceiling before preparing a child", async () => {
+18
View File
@@ -7,6 +7,10 @@ import type {
} from "../src/shared/protocol.ts";
import { HostSfuRoute } from "../src/client/media/host-sfu-route.ts";
import { QUALITY_PROFILES } from "../src/client/media/quality.ts";
import {
invalidateSenderQualityEvidence,
sfuPublisherQualityEvidenceFromMetrics,
} from "../src/client/media/sender-quality-evidence.ts";
import {
exactPeerSignalOwner,
MediaRouteTransition,
@@ -665,6 +669,13 @@ describe("minimal route transition contracts", () => {
});
it("replaces a Host physical connection within one publication and fences stale signaling", async () => {
invalidateSenderQualityEvidence();
const metrics = {
...EMPTY_METRICS, sampleTimestampMs: 1_000, sampleWindowMs: 2_000,
intervalFramesEncoded: 30, nativeEdgeQualityState: "healthy" as const,
qualityLimitationReason: "none",
};
const evidence = () => sfuPublisherQualityEvidenceFromMetrics(metrics, 1, "publication");
const publishers: ReturnType<typeof createFakePublisher>[] = [];
const route = new HostSfuRoute({
getStream: () => ({}) as MediaStream,
@@ -681,16 +692,23 @@ describe("minimal route transition contracts", () => {
await route.acceptAndWait({ revision: 1, phase: "active", assignment: hostAssignment("publication") });
const first = sfuConfig(1, "publication");
await route.acceptConfig(first);
expect(evidence()?.state).toBe("unknown");
metrics.sampleTimestampMs += 2_000;
expect(evidence()?.state).toBe("healthy");
const replacement = { ...first, connectionId: "replacement_connection" };
await route.acceptConfig(replacement);
expect(publishers).toHaveLength(2);
expect(publishers[0]!.disconnect).toHaveBeenCalledOnce();
expect(publishers[1]!.disconnect).not.toHaveBeenCalled();
metrics.sampleTimestampMs += 2_000;
expect(evidence()?.state).toBe("healthy");
await route.acceptSignal({ ...first, type: "sfu-signal", kind: "candidate", candidate: { candidate: "old" } });
expect(publishers[0]!.acceptSignal).not.toHaveBeenCalled();
await route.acceptSignal({ ...replacement, type: "sfu-signal", kind: "candidate", candidate: { candidate: "current" } });
expect(publishers[1]!.acceptSignal).toHaveBeenCalledOnce();
await route.disconnect();
metrics.sampleTimestampMs += 2_000;
expect(evidence()?.state).toBe("unknown");
});
it("reports and retires an exact active SFU source replacement failure", async () => {
+39
View File
@@ -2,6 +2,8 @@ import { describe, expect, it } from "vitest";
import {
invalidateSenderQualityEvidence,
retireSenderQualityEvidence,
retireSfuPublisherQualityEvidence,
senderQualityEvidenceFromSnapshot,
sfuPublisherQualityEvidenceFromMetrics,
} from "../src/client/media/sender-quality-evidence.ts";
@@ -38,6 +40,43 @@ function report(
}
describe("native sender quality evidence", () => {
it.each(["failed", "closed"] as const)("does not retain a retired %s snapshot", (connectionState) => {
invalidateSenderQualityEvidence();
const snapshot: PeerSnapshot = {
peerId: "viewer_12345678", connectionId: "connection_12345678",
connectionState: "connected", iceConnectionState: "connected", error: null,
metrics: { ...EMPTY_METRICS },
};
expect(senderQualityEvidenceFromSnapshot(snapshot, 2)?.state).toBe("unknown");
expect(senderQualityEvidenceFromSnapshot({ ...snapshot, connectionState }, 2)).toBeNull();
expect(senderQualityEvidenceFromSnapshot(snapshot, 2)?.state).toBe("unknown");
});
it.each(["direct", "publication"])("retires only the released %s identity", (path) => {
invalidateSenderQualityEvidence();
const metrics = {
...EMPTY_METRICS, sampleTimestampMs: 1_000, sampleWindowMs: 2_000,
rtpStatsId: "outbound-1", trackIdentifier: "track-1", intervalFramesEncoded: 30,
nativeEdgeQualityState: "healthy" as const, qualityLimitationReason: "none",
};
const emit = (identity: string) => path === "direct"
? senderQualityEvidenceFromSnapshot({
peerId: "viewer_12345678", connectionId: identity,
connectionState: "connected", iceConnectionState: "connected", error: null, metrics,
}, 2)
: sfuPublisherQualityEvidenceFromMetrics(metrics, 2, identity);
const retired = "retired_12345678";
const live = "live_12345678";
expect(emit(retired)?.state).toBe("unknown");
expect(emit(live)?.state).toBe("unknown");
if (path === "direct") retireSenderQualityEvidence(retired);
else retireSfuPublisherQualityEvidence(retired);
expect(emit(retired)?.state).toBe("unknown");
expect(emit(live)).toBeNull();
metrics.sampleTimestampMs += 2_000;
expect(emit(live)?.state).toBe("healthy");
});
it.each(["direct", "publication"])("preserves %s observations independently of control evidence", (path) => {
invalidateSenderQualityEvidence();
const metrics = {