Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。
fix(route): converge direct paths without disrupting media
AAA00c205edbe01
diff --git a/AGENTS.md b/AGENTS.mdindex 4815a0ac..07f20367 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -24,7 +24,7 @@- Keep media distributed and automatic. Central services own rooms, authentication, signaling, STUN, observability, and bounded fallback resources; do not silently make the product always-SFU.- Ordinary peer ICE remains STUN-only and direct/peer UDP remains first; the only application fallback is the dedicated LiveKit SFU over UDP. Browser SFU publisher and subscriber PCs retain LiveKit-signaled UDP candidates but do not inherit external STUN/TURN ICE servers; deployment STUN remains available to ordinary peers and LiveKit server-side public-IP discovery. Screener configures no TURN, ICE/TCP, media TCP, or TLS-relayed media path. Every accepted path ends in bounded success or clear failure, and HTTPS/WSS transport is independent of media transport.- Every non-server endpoint uses one server-authoritative steady outbound media-copy cap: default `2`, configurable as `1`, `2`, or `3`. A peer child or the Host's single SFU publication consumes one slot; upstream receive is free, and SFU subscriber egress is accounted at the server. Browser role, UA, visibility, and client advertisement do not create another tier.-- The accepted route model is one committed graph, one event-driven reconciliation loop, and at most one room-serial child operation. That operation owns one deterministic candidate list/cursor, one current candidate with its reservations, and one total deadline; its exact child commits on the first newly decoded frame. Join/waiting, child reparent, relay ingress repair with subtree retention, confirmed departure, and effective-capacity reduction all use this operation. A failed exact candidate is already tried for that operation, so other direct parents come first and SFU is the bounded suffix; no persistent parent blacklist is created.+- The accepted route model is one committed graph, one event-driven reconciliation loop, and at most one room-serial child operation. That operation owns one deterministic candidate list/cursor, one current candidate with its reservations, one route-demand owner, and one total deadline; its exact media child commits on the first newly decoded frame. Exact direct transport-connected progress may keep the current candidate until that total deadline but cannot commit or change the graph. Join/waiting, child reparent, relay ingress repair with subtree retention, confirmed departure, and effective-capacity reduction all use this operation. Initial acquisition gives direct candidates one bounded foreground window, then uses SFU for availability while any remaining direct candidates converge behind working media; a failed exact candidate is tried only for that operation and creates no persistent parent blacklist.- WebRTC and LiveKit own ICE/DTLS/consent, congestion control, transient reconnect, and SFU stream state. Screener does not add all-pairs endpoint probing, parent-wide quality inference, a weighted route score, periodic rebalancing, or an independent depth cap. SFU is one Host publication with per-Viewer subscriptions, and endpoint overlap plus SFU resources remain independently admitted and bounded. Any future strict-firewall transport must be accepted as a LiveKit-internal capability from real evidence, not added as another application route candidate.- WebRTC and LiveKit also own media-quality adaptation, bandwidth estimation, representation/layer selection, and recovery. Screener may express standard content intent, user-selected ceilings, codec choice, and documented component options, but it does not invent or maintain an application resolution/FPS/bitrate ladder, representation formula, quality score, hysteresis loop, periodic media controller, or manual SFU selector. Browser game-screen video uses the standard `contentHint = "motion"`; do not silently unset it or replace native adaptation unless the owner explicitly accepts a primary-source-supported mature alternative. Prefer pinned component defaults over hand-built SFU layers.diff --git a/docs/adr/0005-automatic-hybrid-media-routing.md b/docs/adr/0005-automatic-hybrid-media-routing.mdindex 76639cfa..4ea42e7e 100644--- a/docs/adr/0005-automatic-hybrid-media-routing.md+++ b/docs/adr/0005-automatic-hybrid-media-routing.md@@ -92,8 +92,9 @@ capacity, sender reservations, candidate tuples already tried by the currentoperation, and server admission.It thenorders eligible parents lexicographically by the shallowest resulting depth,-the greatest remaining steady sender capacity, stable join order, and peer-identity. It prepares one candidate at a time. The candidate's standard ICE+the greatest remaining steady sender capacity, a stable child-parent hash,+join order, and peer identity. The pairwise hash distributes otherwise equal+first choices without weakening capacity authority. It prepares one candidate at a time. The candidate's standard ICEchecklist proves transport connectivity; the exact candidate child's first newdecoded video frame is the application media-ready event. Raw addresses, aclaimed NAT class, geography, user agent, or a@@ -120,14 +121,18 @@ parent cannot immediately repeat. A new external fact may make the oldcandidate eligible again; failure does not globally exclude that parent.Foreground availability and direct convergence have separate priorities but-use the same controller and candidate transaction. Without a current Host-publication, route acquisition first tries the best eligible direct parent,-then SFU, then retains the remaining direct suffix. Once the room has a healthy Host publication, another-joining Viewer first commits an SFU subscription so an earlier slow direct-candidate cannot serialize every waiting Viewer. A Viewer that committed SFU-from foreground acquisition retains that healthy route while the controller later tries its-remaining direct parents, one exact candidate at a time. Newly unrouted or-repairing Viewers always preempt this background direct work. The first direct+use the same controller and candidate transaction. Route acquisition gives the+best eligible direct parent one five-second head start before SFU. An exact hard+failure may advance another direct candidate inside that same window, but the+window never resets. If that exact direct candidate reports standard WebRTC+transport `connected`, the controller keeps it until the operation deadline;+this is progress only and cannot commit a route. Reaching the foreground+boundary without that progress defers the unresolved direct candidate rather+than declaring it failed, then starts SFU. A Viewer that+committed SFU retains that healthy route while the controller later tries its+remaining direct parents, one exact candidate at a time and round-robin across+SFU Viewers after each consumed candidate. Newly unrouted or repairing Viewers+always preempt this background direct work. The first directcandidate that proves a decoded frame replaces SFU make-before-break; exhaustingthe finite parent list simply keeps SFU. A candidate that would require abounded-gap cutover is skipped because background convergence may not interrupt@@ -135,14 +140,18 @@ current media. This is event-driven route convergence, not periodic rebalancingor quality-based switching.If an SFU subscription is needed while the Host has no publication and all Host-slots are occupied, reconciliation uses the same child operation to convert one-deterministic current Host direct child into the first SFU subscriber. It uses-the affected child when that child is already a Host direct child; otherwise it-uses the newest connected Host direct child in stable join order. The candidate-creates the single Host publication, preserves that child's subtree, and commits-on its first newly decoded frame. The publication then replaces the released-Host peer slot, and the next reconciliation handles the original waiting or-failed child. This creates no bootstrap state or second graph.+slots are occupied, the controller retains one bounded bootstrap intent: the+original demand and session, plus the finite Host direct children already tried+as carriers. Each carrier uses the ordinary child+operation and must fit in the existing overlap allowance; a transition that+would first cut a healthy carrier is ineligible. Carrier failure leaves that+carrier's committed route intact and advances the intent. Exhausting all safe+carriers fails the waiting demands for that fact, never the healthy carriers.+On success, the original demand tries the new publication before its eligible+direct candidates; after its first decoded SFU frame those direct candidates+resume as background convergence. A new external fact may rebuild the finite carrier+list. This intent is part of the same controller and owns no second graph,+concurrent route operation, or independent timer.### Authorization and transition@@ -151,19 +160,23 @@ authenticated room and endpoint sessions, current share generation, base routerevision, and unique pending revision. Connection identity fences the candidatePeerConnection, and publication generation remains owned by the SFU resourcelifecycle.-A single pending child-operation object aggregates these bindings, the-deterministic candidate list and cursor, its current candidate and reservations,-and one deadline. Candidate failure advances only that exact cursor entry.+A single pending child-operation object aggregates these bindings, its exact+media child and route-demand owner, the deterministic candidate list and cursor,+its current candidate and reservations, and one deadline. Candidate failure+advances only that exact cursor entry.Initial availability keeps one bounded direct window before SFU. Background-direct convergence uses the same bounded window for each remaining exact parent;-its finite tried set survives between attempts, and a higher-priority route-demand aborts the current attempt without marking the parent failed. These+direct convergence uses the operation's full deadline for each remaining exact parent;+its finite tried set survives between attempts, rotates to the next SFU Viewer+after a consumed candidate, and a higher-priority route demand aborts the+current attempt without marking the parent failed. Thesefields do not create another graph, concurrent pending route revision, periodictimer, assignment generation, or all-pairs probe.A `prepare` route update names that operation's exact child, route kind, andserver-issued candidate connection identity. Parent and child thereforeprepare the same connection; neither endpoint infers candidate authority from-an assignment-list difference.+an assignment-list difference. The candidate child may report one exact+transport-connected progress event fenced by the same revision and connection;+only its later decoded-frame ready event can commit.The current Browser runtime contract uses the single `screener-v12` wire. On each WebSocket, theserver sends the exact prepare before its SFU configuration; the candidate childis queued before a peer parent is allowed to start its offer. WebSocket orderingdiff --git a/docs/research/advanced-peer-distribution.md b/docs/research/advanced-peer-distribution.mdindex 82a30d4a..95f8c11d 100644--- a/docs/research/advanced-peer-distribution.md+++ b/docs/research/advanced-peer-distribution.md@@ -242,9 +242,9 @@ and a four-second state reconciliation that requires three consecutivemismatches before a full reconnect. Jitsi Videobridge similarly defaults to a15-second first-transfer timeout and an eight-second inactivity limit. These arereference boundaries, not universal prescriptions. Screener's separately owned-15-second initial deadline is a deployed implementation value, not an accepted-experience target; mobile-network evidence may justify revisiting the one total-deadline only through ADR-0005.+15-second ViewerPeer connection watchdog and the controller's 20-second route+deadline are implementation values, not accepted experience targets;+mobile-network evidence may justify revisiting them only through ADR-0005.WebRTC/LiveKit first owns transient reconnect. A hard failure or non-pauseddecoded-frame stall wakes ADR-0005 once and seeds the exact failed@@ -277,6 +277,16 @@ capacity, and the untried P2P-fed parent were all present. A room-wide serialcandidate therefore amplified one slow parent into queue delay for every laterViewer.+The same trace contained four exact P2P first-frame successes at 0.488, 0.584,+0.593, and 2.901 seconds. The current five-second foreground head start covers+that observed maximum while halving the failed-candidate queue delay. It is a+measured product budget, not a browser or ICE standard; SFU-backed background+convergence preserves slower candidates for the full route deadline.+Standard `RTCPeerConnection.connectionState = connected` proves that the exact+ICE/DTLS transport is established but not that RTP video decoded. Screener may+therefore use it only to retain that candidate through the total route deadline;+the first newly decoded frame remains the sole graph-commit proof.+Browser ICE already races and paces address, interface, and NAT candidate pairsinside one exact `RTCPeerConnection`. There is no mature Web API that racesmultiple remote peers as one connection; each additional peer requires another@@ -289,7 +299,8 @@ interchangeable; that model does not apply to one live RTP `MediaStream`.The retained Browser design consequently keeps one current candidate and oneauthoritative graph. Initial acquisition gives one best direct parent a bounded-head start before SFU; once SFU has a current decoded frame, the remaining exact+head start before SFU and uses a stable pairwise hash to distribute otherwise+equal parent choices; once SFU has a current decoded frame, the remaining exactdirect parents are attempted one at a time behind that media. A new unrouted orrepairing Viewer preempts this low-priority convergence. Direct success commitsmake-before-break on its first decoded frame; exhaustion leaves healthy SFUdiff --git "a/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md" "b/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"index 7d587165..6cb55acc 100644--- "a/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"+++ "b/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"@@ -374,15 +374,15 @@ Token-free SFU standby prewarm 保持可选且不创建 participant、publicatio服务端维护每个房间唯一的版本化 route owner,它独占 committed graph、一个 pending child operation 和 transition lifecycle。运行时只在该 owner 外保存一个串行 pump、一个 operation deadline timer 和资源生命周期任务;拓扑 helper 不持有第二份 graph。operation 内聚 tuple list/cursor、一个 current candidate/预留、当前 fact version 和一个总 deadline。committed media graph 必须无环且 source-reachable;Host 没有 upstream,每名 Viewer 同时只有零或一个 active upstream。加入、容量变化、节点离开、当前 edge `failed/closed`,以及非暂停时的 decoded-frame stall 都只唤醒同一个 `reconcileRoom(roomId)`;未受影响分支保持 sticky。-`reconcileRoom` 在没有 pending operation 时先删除 disconnected childless participant,再找一个 waiting Viewer,或 parent offline/effective-capacity 不足、exact edge 已失效的 child。Candidate planning 拒绝 stale session、不可 source-reachable、成环或没有稳态/overlap/bounded-gap producer slot 的 candidate;server resource admission 在执行当前 cursor 时单独检查。由 failed edge 启动时只为当前 fact version 把 exact candidate 记为已尝试;新的外部事实允许重新评估。对剩余 upstream 依次比较结果深度、剩余 sender slots、稳定加入顺序与 peer identity,先建立其他 direct/STUN,再复用或建立 SFU。Host root退出后新释放的Host槽位因此优先于另一root的更深槽位;健康旧边保持sticky,不做周期性整树平衡。每次只 reserve/prepare cursor 指向的 candidate。WebRTC 负责 ICE/DTLS/consent;exact candidate child 解码出第一帧新画面后发送一次 ready,controller 先同步 commit typed admission,再原子提交 graph。失败释放 candidate、广播严格更新的 rollback revision 并推进 cursor,operation 总 deadline 不重置。耗尽时 hard-invalid、confirmed-departed 或 deterministic overflow edge 被退休并进入明确 waiting;healthy bootstrap edge 保留。无环和房间 admission 已约束最大深度,不增加独立 depth hard cap。+`reconcileRoom` 在没有 pending operation 时先处理 foreground route demand,再处理低优先级 direct convergence。Candidate planning 拒绝 stale session、不可 source-reachable、成环或没有稳态/overlap producer slot 的 candidate;排序依次使用结果深度、剩余 sender slots、稳定 child-parent hash、加入顺序与 peer identity。每次只 reserve/prepare 一个 exact candidate;WebRTC 负责 ICE/DTLS/consent,candidate child 解码出第一帧新画面后才同步提交资源和 graph。失败只消费该 exact tuple,健康旧边保持 sticky,不做周期性整树平衡或独立 depth hard cap。完整 cursor、bootstrap 与终态所有权由 ADR-0005 定义。Pending candidate 的 receive-transport owner 只在当前 exact generation 下运行一个短生命周期 `framesDecoded` 观察器。全新 peer/SFU activation 以正累计值证明首帧;暂停期间仍保留的 prepared SFU 在 Resume 时先取 baseline,再要求后续增长。观察器在 proof、promotion、pause、换代或 teardown 时停止,不增加另一 success/failure deadline,也不参与 candidate 选择。Active route 仍由既有两秒 stats sampler维护诊断和 decoded stall,两者不得互相替代。SFU subscriber 的同一 sampler 从 active 开始持续到 deactivate/teardown;没有 video track、合并 report 为空或读取异常时只向 decoded-stall owner 交付一次 `null` progress sample,真实 metrics 仍只在有效 report 存在时交付。Track 换代同时换代 accumulator,旧异步结果不得驱动当前 route。-一个 operation 仍只有一个 timer 和一个总 deadline,但 timer 的下一次 wake 从当前 candidate list 派生。Controller 提取实际存在的 direct 与 SFU 阶段并等分总窗口;显式失败可以在阶段内继续尝试其他 candidate,silent candidate 到达 direct wake boundary 后释放 reservation、广播 rollback 并跳到 SFU。只有 direct 时仍使用完整 deadline;direct+SFU 时各用一半。这样不引入每-candidate magic milliseconds,也不允许一条 silent direct 把 SFU suffix 饿死。+一个 operation 只有一个 timer 和一个总 deadline。Initial acquisition 给 direct 一个由生产首帧数据标定的固定 foreground window;显式硬失败可在该绝对窗口内推进其他 direct,silent candidate 到达边界后释放 reservation并转入SFU。Exact direct若在边界前报告标准WebRTC transport connected,就保留到总deadline继续等待第一解码帧;该进度不提交graph。SFU取得首帧后,剩余direct tuple才作为background逐Viewer轮转;没有SFU时仍使用完整deadline。不存在逐candidate timer或随人数切分的预算。-首次需要 SFU 但 Host 已满时不建立另一条 rescue 流程。若 affected child 已是 Host direct child,就用它;否则用稳定加入顺序中最新的 connected Host direct child。`reconcileRoom` 为该 child 建立普通 SFU candidate,创建唯一 publication,保持其 subtree,并在该 child 首帧后提交。Host publication 取代释放的 peer slot,随后同一 fixed-point scan 再处理原 waiting/failed child。若旧 Host peer sender 在首帧前仍保留,candidate 必须持有同一 `TransitionOverlapSlot`。没有 overlap 时先 preflight server resource,再退休 exact producer;operation 保持原总 deadline、按新 graph 重算未尝试 suffix,并为被切断的 healthy direct edge追加一个最后 restore tuple。Forward candidate 与 restore 都失败才进入 waiting,不得产生第四份 endpoint copy或另一套恢复状态。+首次需要 SFU 但 Host 已满时,controller保存原始demand/session和本fact已试carrier集合,依稳定顺序让一个健康Host-direct child用普通SFU candidate建立publication。该candidate必须持有既有`TransitionOverlapSlot`;需要先切断健康carrier的bounded-gap计划不具资格。失败保持carrier及其subtree并尝试下一carrier;全部耗尽时终态归原始demand,同一fact不为后续demand重复整套carrier。成功后原demand下一次先尝试SFU,失败仍可继续direct suffix;carrier自身也进入低优先级direct convergence,待容量允许时恢复原Host直连。-所有非服务器端点共享一个 server-authoritative steady outbound media-copy cap `C`:唯一配置 `ENDPOINT_MEDIA_COPY_CAPACITY` 默认 `2`,只接受 `1`、`2` 或 `3`,不兼容旧键。服务端将 endpoint 当前广告的 `0..C` 可用值 clamp 为唯一 `effectiveDownstreamCapacity`;该值只表示当前可用 sender slots,不建立角色、浏览器、UA、设备或页面可见性 tier。peer child 或 Host publication 各占一份,upstream receive 免费;SFU subscriber egress 使用独立 server admission。Browser `screener-v12` 的 `authenticated.endpointMediaCopyCapacity` 把部署 `C` 交给 Host 与 Viewer;两端用该值校验稳态 assignment,并让 active+pending 的物理 copy 只在 controller 已授权 overlap 时达到 `min(C + 1, 3)`。代码通过一个 shared accounting guard 执行,不重复 magic number;其他 wire 与 Native executable 在 authority 前拒绝,不保留兼容路径。`C=3` 满载时先收到 active bounded-gap retirement再收到 prepare;任何会产生第四份 endpoint media copy 的 token都不得签发。+所有非服务器端点共享一个 server-authoritative steady outbound media-copy cap `C`:唯一配置 `ENDPOINT_MEDIA_COPY_CAPACITY` 默认 `2`,只接受 `1`、`2` 或 `3`,不兼容旧键。服务端将 endpoint 当前广告的 `0..C` 可用值 clamp 为唯一 `effectiveDownstreamCapacity`;该值只表示当前可用 sender slots,不建立角色、浏览器、UA、设备或页面可见性 tier。peer child 或 Host publication 各占一份,upstream receive 免费;SFU subscriber egress 使用独立 server admission。Browser `screener-v12` 的 `authenticated.endpointMediaCopyCapacity` 把部署 `C` 交给 Host 与 Viewer;两端用该值校验稳态 assignment,并让 active+pending 的物理 copy 只在 controller 已授权 overlap 时达到 `min(C + 1, 3)`。代码通过一个 shared accounting guard 执行,不重复 magic number;其他 wire 与 Native executable 在 authority 前拒绝,不保留兼容路径。任何会产生第四份 endpoint media copy 的 token都不得签发;`C=3`满载bootstrap保持健康树并明确失败。SFU admission 在应用单进程中只有一个注入实例。LiveKit credential tuple 完整时必须显式配置私有 `LIVEKIT_API_URL`;固定四位房号池给出 9000 个 publication ingress,上界 `9000 * MAX_VIEWERS_PER_ROOM` 给出 subscription egress,不存在独立 SFU 容量配置。专用 LiveKit 实例设置 `room.auto_create: false`。账本只保存全局已用计数,以及 exact room/share/publication generation 下的一份 publication handle 和按 Viewer identity 索引的 subscription handle。Publication 的 `reserved | committed | draining` 占 ingress `1`,每份 subscription 的同类状态占 egress `1`;离开 route 的 subscription 在该 generation 删除并确认 absent 前保持 draining,同一 Viewer handle 再次启用不重复计数。首个 SFU child 先 reserve publication 与自己的 subscription,再通过 `RoomService.CreateRoom` 创建 exact-generation room,成功后才 prepare 和签发 token;后续 child 只在同 generation reserve subscription 并复用 Host publication。exact candidate child 的 first decoded frame 后 commit 自己的资源;publication replacement 将旧 generation 及其全部 subscription 一起转入 draining,失败、超时、失联、分享换代、停止或删房按资源所有权进入同一生命周期。只有 `RoomService.DeleteRoom` 成功且 follow-up lookup 证明 room 不存在,账本才扣除该 generation 的 ingress/egress;auto-create 关闭后,旧 token 不能重建已删除 room。进程启动在接受流量前拒绝任何非 Screener room,删除全部遗留 Screener room并确认 namespace 为空;关闭时先 drain 再遗忘计数。Host 信令离线期间若 exact room 中的 Host participant 仍存在就继续计费并保留健康媒体,participant 消失后在一个有界轮询周期内回收。稳态 reserve/commit/drain bookkeeping 仍是 Map lookup 与整数加减;只有 generation 创建、删除、启动清场和 Host 离线检查访问 LiveKit control plane。多应用进程部署必须先增加共享原子 admission/lifecycle owner。diff --git "a/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md" "b/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"index ce05b0cd..4f8372c2 100644--- "a/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"+++ "b/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"@@ -25,13 +25,13 @@ SFU 的 publication、subscription、server-resource accounting、临时 overlap- 本地昵称与房间成员:用户可设置一个只保存在当前浏览器同源 `localStorage` 的显示名,界面统一称为“昵称”;默认以只读文本显示,铅笔编辑按钮紧贴昵称,点击后才进入编辑。Viewer 顶部标题直接显示“{Host 名称} 的屏幕”,不得在下方重复一行 Host 名称。信令只在当前在线 socket 会话内保存和广播 NFC 规范化、最多 24 个 Unicode code points、拒绝控制/换行/双向覆盖符与孤立 surrogate 的纯文本标签,不写服务端持久存储或日志。空值使用通用角色 fallback。Web Host 与 Viewer 都必须看到全部当前在线 Viewer 的权威总数与 roster,不能拿最多两条 Host 媒体直连数冒充在线人数;presence 更新也不得创建媒体连接。展示身份默认只显示名称;仅当房内出现同名时追加当前房间 `peerId` 的至少六字符短后缀,并只在同名项后缀碰撞时有界延长。显示名、后缀和 `clientId` 都不是账号、授权身份或全局 UUID,重复名称允许且不得参与授权、路由或质量决策。Web Host 与 Viewer 通过同一 opt-in participant roster 看到 Host 名称;Native/executable sender 不在当前发布面,也不接收 Web roster。- 一对多观看:每个房间允许一名 Host 和最多 `20` 名 authenticated Viewer;房间 admission 与端点下游容量、SFU admission 分别配置,超额加入必须明确拒绝。观看人数不从 endpoint cap 推导,20-Viewer smoke 只证明控制面与资源上界,不是任意网络质量声明。- 端点发送容量:所有非服务器端点使用同一个服务端权威稳态 outbound media-copy capacity,由唯一部署项 `ENDPOINT_MEDIA_COPY_CAPACITY` 配置,默认 `2` 且只接受 `1`、`2` 或 `3`;不读取旧键或保留第二套 tier。peer child 或 Host 的唯一 SFU publication 各消耗一份,上游接收不消耗该预算。客户端只能声明不高于部署值的可用容量,角色、浏览器、UA、设备类型和页面可见性不产生不同上限。服务端在每次 `authenticated` 权威快照中返回最终 `endpointMediaCopyCapacity`;普通非 peer-assisted 模式也只授权稳定加入顺序中的至多 `C` 个 Host child,超额 Viewer 保持入房等待并在槽位释放后提升,信令不能绕过该集合。Browser Host 与 Viewer 严格校验该值并用它约束稳态 assignment;并行产生媒体的 candidate 必须持有唯一 `TransitionOverlapSlot`,active+pending 物理 copy 只可达到 `min(C + 1, 3)` 并在 commit/abort 后释放。`C=3` 满载时必须先收到 active bounded-gap retirement 再 prepare,绝不产生第四份 copy。SFU subscriber egress 由独立 server admission 记账。当前不兼容房间合同以单一 release 原子升级;缺失/非法 cap、旧 wire 与 executable sender都在取得room/route authority前fail closed。-- P2P 优先:每条普通逻辑媒体边先尝试 direct/peer UDP,服务器不得默认中转可直连媒体。更多观看者优先沿满足统一端点容量的无环 peer 图分布;每名 Viewer 同时至多一个 active upstream,失败时只影响需要重选的 child。任何 source-reachable endpoint 在 effective capacity 有空位时都可作为 parent candidate;Peer-fed 与 SFU-fed endpoint 使用同一个 provisional-child transaction,并在 candidate child 解码出第一帧新画面后独立提交该 edge。Host 已满且首次需要 SFU 时,同一 reconcile 将 affected Host direct child(若无则稳定顺序中最新的 connected Host direct child)作为本次 child operation,创建唯一 Host publication 并把该 child 变为首个 SFU subscriber,subtree 不动;publication 取代释放的 Host peer slot,下一次扫描再处理原受限 Viewer,不建立 bootstrap 状态机。+- P2P 优先:每条普通逻辑媒体边先尝试 direct/peer UDP,服务器不得默认中转可直连媒体。更多观看者优先沿满足统一端点容量的无环 peer 图分布;每名 Viewer 同时至多一个 active upstream,失败时只影响需要重选的 child。任何 source-reachable endpoint 在 effective capacity 有空位时都可作为 parent candidate;Peer-fed 与 SFU-fed endpoint 使用同一个 provisional-child transaction,并在 candidate child 解码出第一帧新画面后独立提交该 edge。Host 已满且首次需要 SFU 时,同一 controller 用有限 carrier cursor 建立唯一 publication;carrier 必须能在既有 overlap 上限内完成,不能先切断健康分支。终态归原始等待需求,publication 成功后该需求先取得 SFU 画面,剩余 direct candidate 再在后台收敛;完整事务由 ADR-0005 定义。- NAT 与传输边界:STUN 必须可用,所有 ordinary peer `RTCPeerConnection` 只接收 STUN ICE servers。Browser LiveKit publisher/subscriber PC 必须显式使用空 `iceServers`,保留 LiveKit signaling 交付的授权 SFU UDP candidates,并由标准 ICE 选择 nominated non-relay pair;不得把 ordinary-peer STUN、LiveKit join response 中的 STUN 或默认公共 STUN混入该 PC,也不得把某一种 candidate type 或数量写成成功条件。部署 STUN 仍供 ordinary peers 和 LiveKit server-side 公网地址发现使用。浏览器 ICE connectivity checks 是 direct UDP 可达性的权威;Screener 不合成 remote candidate、不预测端口、不分类 NAT,也不使用 TCP 探测推断 UDP 媒体可达性。所有恢复和候选授权必须绑定 authenticated room/endpoint session、share generation、base/pending route revision 与 candidate connection identity;成功即停止,失败、超时或绑定失效即撤销,direct 阶段耗尽后在同一 operation deadline 内进入 SFU/UDP,全部可用路径耗尽后明确等待或失败。已接受的完整顺序只有保持或尝试 direct/STUN peers,再复用或建立 direct-ingress Host publication/SFU subscription。Screener 不配置 TURN、ICE/TCP、media TCP 或 TLS-relayed media;当前 LiveKit 也保持 UDP-only。未来若真实严格防火墙矩阵证明需要另一种传输,必须把它作为 LiveKit 内部能力重新决策,不能增加第三种应用 route candidate。LiveKit join JWT 仅按协议进入不得记录的 WebSocket request target;HTTPS/WSS 继续独立使用 TLS/TCP。- 质量控制:推荐档位始终只有 720p30(3 Mbps)、1080p30(5 Mbps)、1080p60(8 Mbps)三档,默认选择中档 `1080p30`。高级设置的分辨率选项增加 `480p`(854x480),其 FPS 与码率仍由高级控件独立选择;不增加 `480p` 推荐档、preset ID 或固定的 480p FPS/码率组合。三档与高级设置初始值统一采用中档 `balanced`(均衡),`maintain-resolution`(清晰)、`maintain-framerate`(流畅)保留为显式选择。Browser 视频固定使用 VP8;界面、质量状态和 wire 不提供 codec 选择或切换。分享期间可直接换视频档位和 64/128/192 kbps 音频 sender ceiling,音频默认选择中档 128 kbps,不重新选择来源或重建健康连接。Peer-assisted relay 与已配置的 SFU 必须接收同一个严格校验的房间级权威设置,覆盖当前和以后建立的 sender;普通 P2P 信令结构保持不变。任何设置都只是浏览器上限和偏好,具体降级由 WebRTC/LiveKit 决定;必须读回实际 sender 参数并通过 stats 观测结果、显示参数拒绝、改写和持续受限原因。Host 资源不足时由 Host 主动选择较低的现有档位。Screener 不设置自定义 SFU layer list、动态 FPS、综合评分或周期性全房间调档。- 路径隔离表示:direct/peer 继续使用每条 PeerConnection 独立的 stock WebRTC GCC,不把 Viewer 反馈合成全房目标。Browser Host 的唯一 SFU publication 不设置 `screenShareSimulcastLayers`,由锁定的 LiveKit client 默认行为拥有 VP8 screen-share representations、source replacement 与 republish;LiveKit Dynacast 和启用 send-side BWE 的 server stream allocator 负责需求聚合与每个 subscriber 的实际下行层。Screener 不实现质量评分、带宽估计、周期调档或应用媒体层 selector。所有当前 Viewer 都可能承担 peer children,因此 subscriber 保持 `adaptiveStream: false`,不得让本地元素尺寸或可见性控制 relay ingress。表示选择不改变拓扑、端点容量或路由失效权威。-- 路由失效输入:应用不推断 parent-wide 质量,也不计算综合分数。当前 authenticated child 只在 PeerConnection `failed/closed`,或非权威暂停时现有 periodic stats 在统一 deadline 内没有新 decoded frame 时,使自己的 exact edge 失效并唤醒同一个 reconcile。decoded progress 只保存 route-keyed `lastDecodedAt`,route/connection变化或新帧重置、暂停抑制,同一 edge只报告一次,不增加轮询器。Active SFU route 暂时没有 video track、stats report 为空或 stats 读取失败时,现有采样 cadence 仍把该次作为无 decoded progress 推进 deadline;它不得停表、伪造连接指标或立即判定 edge 失效,只有 route 停用或 teardown 才停止该 cadence。该 operation 把失败的 exact direct parent 在当前 fact version 直接视为已尝试,先选择其他 direct parent,再进入有界 SFU suffix;新的外部事实才允许原 direct tuple 重新进入。Track availability、低码率、低 FPS、模糊、sender/viewer stats 与 SFU layer只用于stock WebRTC/LiveKit恢复和诊断。relay自身ingress失效时,它作为child换父并保留subtree;disconnect或effective downstream capacity降低只让direct/overflow children逐个走同一事务。+- 路由失效输入:应用不推断 parent-wide 质量,也不计算综合分数。当前 authenticated child 只在 PeerConnection `failed/closed`,或非权威暂停时现有 periodic stats 在统一 deadline 内没有新 decoded frame 时,使自己的 exact edge 失效并唤醒同一个 reconcile。decoded progress 只保存 route-keyed `lastDecodedAt`,route/connection变化或新帧重置、暂停抑制,同一 edge只报告一次,不增加轮询器。Active SFU route 暂时没有 video track、stats report 为空或 stats 读取失败时,现有采样 cadence 仍把该次作为无 decoded progress 推进 deadline;它不得停表、伪造连接指标或立即判定 edge 失效,只有 route 停用或 teardown 才停止该 cadence。该 operation 把失败的 exact direct parent 在当前 fact version 视为已尝试;foreground direct window结束后用SFU取得可用画面,剩余direct candidate只在画面后方收敛,新的外部事实才允许本轮失败tuple重新进入。Track availability、低码率、低 FPS、模糊、sender/viewer stats 与 SFU layer只用于stock WebRTC/LiveKit恢复和诊断。relay自身ingress失效时,它作为child换父并保留subtree;disconnect或effective downstream capacity降低只让direct/overflow children逐个走同一事务。- 断线恢复:临时网络变化先交给 WebRTC/LiveKit 的 ICE、consent、重连和流状态。Direct edge 可在 exact current parent/child sessions 内采用 framework rebuild 的新 connection ID而不改变topology。应用只在上述exact edge失效后运行一次有界reconcile;任一步成功即停止。候选耗尽时hard-invalid、confirmed-departed或overflow edge被退休并进入明确waiting,healthy bootstrap edge保留。所有异步结果受authenticated session、share generation、base/pending route revision与candidate connection identity约束,未受影响分支保持sticky。权威暂停abort未提交candidate、保留active graph、抑制stall,并在resume后重新reconcile。-- 同一 operation 的一个总 deadline 只按实际存在的 `direct | sfu` 语义阶段等分,不配置每个 candidate 的 magic timeout。阶段内的硬失败继续推进 cursor;silent ICE 到达 direct 阶段边界时跳过剩余 direct tuple,必须把派生份额留给 SFU。20 名 Viewer 同时加入时,每名 child 的 operation deadline 不会被人数除分,但单一 room-serial operation 可能形成线性排队尾延迟;在接受另一种并发模型前,只测量 queue wait、candidate start、first decoded frame 与 final route 的 p50/p95/max,不用 NAT 猜测、TCP probe 或 magic timeout 绕过排队。+- 每名 child 只有一个有界 operation deadline;foreground direct 预算、SFU 可用性优先和后台 direct 收敛由 ADR-0005 的同一 cursor 模型定义,不配置逐 candidate timeout。Exact direct 的标准WebRTC transport-connected只把当前wake延长到该总deadline,不提交graph;第一解码帧仍是唯一commit证据。20 名 Viewer 同时加入时,单一 room-serial operation 仍可能形成线性排队尾延迟;在接受另一种并发模型前,只测量 queue wait、candidate start、first decoded frame 与 final route 的 p50/p95/max,不用 NAT 猜测、TCP probe 或 magic timeout 绕过排队。- 可观测性:按目标 RTP transport 与不透明连接/ICE 代次关联 selected path、`iceGatheringState`/ICE/connection state、事件推导的建立时长、generation-baselined pair-change delta,以及 RTT、RTP 丢包率、抖动、码率、帧率、编码耗时和受限原因。候选、route decision、队列时序与错误的 wire 和日志使用封闭 schema 和 code bucket,禁止 raw SDP、candidate、地址、URL、`errorText`、真实 peer/parent/session/connection identity 或网络标识。Host 与 Viewer 产品 UI 不提供连接诊断文件下载;本地折叠详情只显示当前页面直接观测到的连接事实。现有 Host-only bounded route snapshot 保留给自动验收,不连续推送、不进入产品 UI、也不形成 route authority。只有创建该 `RTCPeerConnection` 的本机可显示浏览器对 selected local/remote candidate 实际暴露的地址与端口;该值不上传、不持久化、不用于地理/NAT 推断,缺失或被隐私保护时显示未知。- 渐进式诊断:分享者和观看者默认只看到房间、画面、核心状态和常用控制;Host 对每名 Viewer 使用同一种卡片,不按 direct、Peer 转发或 SFU 分组。卡片只把本机连接或当前 Viewer 接收证据称为“已连接”,其余状态保持中性的“线路分配中”或具体连接状态,不把 active assignment 当作连接成功。展开连接详情也只在当前媒体证据成立后显示绿色 `P2P` 或黄色 `SFU fallback`;一级只保留分辨率、帧率、码率和丢包等一眼可读的实际画面结果,二级只显示当前确有值且能解释网络、编解码或播放质量的指标。固定的 VP8/Opus 不常驻展示,只在实际协商偏离产品合同时提示;候选地址、候选对 ID、STUN 计数、RID、fmtp 和其他浏览器内部标识不进入产品 UI。Host/Peer/SFU 的精确上下游与分支结构只由独立权威拓扑视图表达,不在卡片内重复。远端 Viewer evidence 的详情 shell 在同一 viewer/upstream/connection/route identity 内保持稳定并保留每个字段最后一次真实非空观测;五秒 freshness 只决定 evidence 能否继续证明“已连接”,`connecting`/`disconnected` 立即降为非 fresh,`failed`/`closed`、identity/session/share/route 变化或非单调 sequence 则清空/换代。隐藏诊断不能隐藏失败原因、音频缺失、持续画质受限、编码合同偏离或需要用户操作的告警。- 站点访问:生产部署必须配置独立的 `SITE_ACCESS_PASSWORD` 控制建房、Host 信令角色和所有 code-only Viewer 入口;只有本地开发/测试可显式关闭。非空值接受 8 至 128 个可见 ASCII bytes,不能复用 LiveKit、TLS 或其他部署 secret。`POST /api/site-access` 验证成功签发 12 小时、无服务端会话状态的 HttpOnly、`SameSite=Strict` site-access cookie。有效 room-scoped fragment grant 可绕过站点 gate 直接进入对应房间;其余 `/r/{code}` 和 `/join` 必须先持有效 site-access cookie,之后才检查房间是否存在与 `open | private` code-only policy。未分配、已回收或已过期的 code 返回 `ROOM_NOT_FOUND`;现存私密房间的无密码、缺失或错误密码及容量拒绝继续使用 `ROOM_ACCESS_DENIED`。建房 HTTP 只认该 cookie。已移除的旧环境变量、endpoint 和 cookie 不保留兼容。不引入账号、JWT、服务端 session Map 或通用 logout。@@ -44,8 +44,8 @@ SFU 的 publication、subscription、server-resource accounting、临时 overlap- 本地自包含一键包:提供 Windows、macOS 和 Linux 可分发的桌面包,在分享者电脑上同时运行 Host、当前 Web/信令应用服务器和本地状态,朋友继续通过普通浏览器邀请观看。安装后启动不要求源码 checkout、Node 或任何外部 Screener、STUN、SFU、隧道或 relay 服务;它尽力使用本机可达入口和 direct P2P,但必须明确报告公网入口、可信 HTTPS/WSS、网关映射或 NAT 路径缺失,不能承诺任意 CGNAT/严格防火墙必通。两种分发包都排在当前功能、路由、NAT 和真实网络 TODO 完成之后。- 独立房间入口:合法 `/r/{code}#v={grant}` 邀请直接进入对应房间;没有 grant 的 `/join` 或 `/r/{code}` 先显示明确标为“站点访问”的整站验证,再提交 code-only 尝试。`open` 且可准入时直接进入;未分配、已回收或已过期的 code 明确显示“房间不存在或已过期”且不提供密码输入;现存房间的其他预期拒绝使用 `ROOM_ACCESS_DENIED`,不披露具体 policy。有效 site-access cookie 只跳过第一步,两类密码不得复用或互相替代。Host 可设置、轮换或移除房间观看密码;密码接受 1 至 64 个可见 ASCII 字符,异步 scrypt 全局最多执行 2 个、等待 16 个派生。Host 可把房间密码保存在同源本地创建偏好中;它不得进入 URL、cookie、日志或服务端持久存储。-- 统一自动路由:旗舰部署开启 `PEER_ASSISTED_MEDIA` 后,每个房间使用一个服务端 route controller,独占 committed graph、一个 pending child operation 和 event-driven reconcile。运行时只增加一个串行pump、一个operation deadline timer与typed resource lifecycle task,不维护另一份graph。operation持有candidate list/cursor、一个current candidate/资源预留、fact version和一个总deadline。committed graph必须无环、source-reachable,且每名Viewer同时至多一个active upstream。加入、容量变化、节点离开、exact edge `failed/closed`,以及非暂停decoded-frame stall都只唤醒同一个reconcile;其余健康分支保持sticky。候选按当前身份、source reachability、无环、effective capacity与sender transition硬过滤,再按结果深度、剩余sender slots、稳定加入顺序和peer identity排序;因此 Host root退出后新释放的Host槽位比已有root的更深槽位优先,但健康旧边不因周期性平衡而迁移。server admission在执行当前cursor时独立reserve。candidate child首帧ready触发`settleReady(commitAdmissionSync)`,成功prepare `P`提交active `P`;失败释放资源并用同一monotonic allocator广播`R>P` rollback,cursor推进但总deadline不重置。bounded-gap先preflight server resource,再retire producer、按新graph重算未尝试suffix,并在切断healthy edge时追加一个普通restore candidate。relay自身ingress失效时作为child换父并保留subtree;relay disconnect/cap降低让overflow children逐个走同一事务,childless后删除。房间admission和无环约束最大深度,不设独立hard cap。普通peer始终STUN-only,SFU使用独立admission。-- 观看端连接反馈:Viewer 舞台从鉴权到首帧使用一个由现有权威状态推导的稳定阶段反馈,至少区分等待分享、分配线路、建立 P2P、连接 SFU、等待首帧、浏览器阻止自动播放、恢复连接和有界失败。阶段不是进度百分比,也不产生 route authority;只有当前 video element 实际提交首帧后才显示正在播放。Autoplay rejection 通过原生媒体 controls 恢复;连接中不显示虚假的播放动作。手动“重新连接媒体”只恢复当前 exact route:P2P 直接重建到同一 parent 的连接,SFU 只断开并重连当前 publication 的 subscriber;两者都保留 Screener WebSocket、房间会话和 route revision,不触发主动换父、质量选优或 P2P/SFU 重选。真实恢复耗尽后才进入既有 route-failure operation。仍有已证明旧帧时保留为背景并显示恢复状态,不为显示反馈主动清空健康 media element。页面从冻结/隐藏恢复时先重置 decoded-stall wall-clock baseline 并重新证明当前代画面,冻结时间本身不得成为立即换路依据。Host 离线本身不使仍健康的媒体失效;exact upstream 硬失败或 route terminal failure 必须使 current frame proof 失效,已证明画面至多降为 retained background,不能遮蔽离线或有界失败。已接受的 `screener-v12` 服务端补充消息是 strict、current-revision-fenced `route-status` union,且只允许 `waiting/sfu-admission` 与 `failed/route-exhausted` 两种配对;它不携带 raw text、身份、candidate 或 retry hint,prepare/active、access、Host、signal、media 与 autoplay 继续由各自权威输入派生。+- 统一自动路由:旗舰部署开启 `PEER_ASSISTED_MEDIA` 后,每个房间只有一个服务端 route controller、一个 committed graph、一个 pending child operation、一个串行 pump 和一个 operation deadline timer。Graph 必须无环、source-reachable,且每名 Viewer 同时至多一个 active upstream;加入、容量变化、离开、exact edge 失败与非暂停 decoded-frame stall 都只唤醒同一个 reconcile,其余健康分支保持 sticky。候选先按身份、source reachability、无环、effective capacity 与 sender transition 过滤,再按深度、剩余容量、稳定 child-parent hash 和稳定身份排序;server admission、exact transport progress、首帧 commit、Host-full bootstrap、后台 round-robin 与终态所有权统一由 ADR-0005 定义。普通 peer 始终 STUN-only,SFU 使用独立 admission;不建立第二 graph、周期性重平衡、质量评分或独立 depth cap。+- 观看端连接反馈:Viewer 舞台从鉴权到首帧使用一个由现有权威状态推导的稳定阶段反馈,至少区分等待分享、分配线路、建立 P2P、连接 SFU、等待首帧、浏览器阻止自动播放、恢复连接和有界失败。阶段不是进度百分比,也不产生 route authority;只有当前 video element 实际提交首帧后才显示正在播放。Autoplay rejection 通过原生媒体 controls 恢复;连接中不显示虚假的播放动作。手动“重新连接媒体”只恢复当前 exact route:P2P 直接重建到同一 parent 的连接,SFU 只断开并重连当前 publication 的 subscriber;两者都保留 Screener WebSocket、房间会话和 route revision,不触发主动换父、质量选优或 P2P/SFU 重选。真实恢复耗尽后才进入既有 route-failure operation。仍有已证明旧帧时保留为背景并显示恢复状态,不为显示反馈主动清空健康 media element。页面从冻结/隐藏恢复时先重置 decoded-stall wall-clock baseline 并重新证明当前代画面,冻结时间本身不得成为立即换路依据。Host 离线本身不使仍健康的媒体失效;exact upstream 硬失败或 route terminal failure 必须使 current frame proof 失效,已证明画面至多降为 retained background,不能遮蔽离线或有界失败。已接受的 `screener-v12` 补充消息只有 strict、current-candidate-fenced 的 transport-connected 进度,以及仅允许 `waiting/sfu-admission` 与 `failed/route-exhausted` 两种配对的 `route-status` union;两者都不携带 raw text、额外身份或 retry hint,且都不产生 route authority。- 质量控制扩展:推荐档位仍是默认入口且只保留 720p30/1080p30/1080p60 三档,当前页面初始 desired state 选择均衡的 1080p30 且不写 `localStorage`;“分享高级设置”允许 480p(854x480)/720p/1080p/1440p 分辨率 ceiling、15 至 60 的整数 FPS ceiling、2 至 12 Mbps 视频码率 ceiling、清晰/均衡/流畅三种偏好,以及离散的 `64 kbps 普通 | 128 kbps 音乐默认 | 192 kbps 保真` 屏幕音频 sender ceiling;480p 不形成推荐档或固定 FPS/码率组合,音频初始值为 128 kbps。视频档位和音频档位可在直播中显式应用。所有当前及以后建立的 Web Host、Browser relay 与 SFU sender 都读取最新 desired 档位,并各自在 fresh sender parameters 上应用和读回 endpoint-local applied 值;实际码率仍由浏览器拥塞控制和 stats 决定。Peer 只在唯一明确的 active Opus audio 上做结构化、幂等的 Viewer answer `stereo=1;maxaveragebitrate=192000` 变换,使同一接收上限覆盖三档;非目标形态或 parser/writer 异常必须原样保留浏览器 answer,不得阻断可继续的 mono/video edge。不得用宽泛字符串/正则改 SDP,也不得改写浏览器协商的 FEC。SFU 将 64/128 kbps 映射到 pinned SDK stereo music preset,192 kbps 使用显式 ceiling,统一设置 `forceStereo = true`、`dtx = false` 与 `red = false`。不得暴露任意码率、声道、采样率、audio codec、stereo、DTX、RED 或 FEC 控件;192 kbps 只是显式较高上限,不是无损、高保真或最低码率保证。实际质量持续低于所选上限时必须显示可解释的限制原因;在真实拥塞、编码器和接收端证据完成前,不把任一组合称为“完美平衡”。未来 microphone voice 若进入范围,必须是独立 track/处理链,不能把 AEC/降噪/DTX 套到电影或游戏音频。- SFU 质量设置生命周期:直播中修改档位时,浏览器 sender 的 applied readback、LiveKit `LocalVideoTrack` 保存的 degradation preference、track restart options 与 `LocalTrackPublication` 的 republish options 必须作为同一次串行操作更新;任一步失败恢复旧 sender 与旧 SDK 保存态,旧 publication generation 不得回写当前状态。LiveKit full reconnect/republish 不得恢复初次发布的旧偏好。该修复不改变 codec、码率上限、层数或路由,也不能单独解释即时低帧。- 本地预览性能候选:在相同动态场景中 A/B 测量 Host 动态预览开/关的 CPU、GPU、encode time 和实际 FPS。只有稳定收益且捕获、编码和远端画面不受影响时,才允许直播开始后默认显示静止缩略图或隐藏动态预览并提供按需展开;未测前不宣称收益。diff --git a/src/client/pages/ViewerPage.tsx b/src/client/pages/ViewerPage.tsxindex d316cdf5..6b32cdf4 100644--- a/src/client/pages/ViewerPage.tsx+++ b/src/client/pages/ViewerPage.tsx@@ -1,11 +1,15 @@import {+ CirclePlay,KeyRound,LoaderCircle,Network,+ Pause,Pencil,RefreshCw,Save,+ TriangleAlert,VideoOff,+ WifiOff,X,} from "lucide-react";import { useEffect, useMemo, useReducer, useRef, useState } from "react";@@ -60,6 +64,7 @@ import {reduceViewerPresentation,type ViewerFailureCode,type ViewerRouteKind,+ type ViewerStage,} from "../media/viewer-presentation";import {isAutoplayPolicyRejection,@@ -98,6 +103,7 @@ interface PendingPeerRoute {parentPeerId: string;peer: ViewerPeer | null;decodedFrame: boolean;+ connectedSent: boolean;readySent: boolean;candidateConnectionId: string;stream: MediaStream | null;@@ -111,6 +117,43 @@ interface RemoteMediaBinding {videoTrackKey: string;}+function StageOverlayIcon({ stage }: { stage: ViewerStage }) {+ if (stage === "needs-play") {+ return <CirclePlay size={36} strokeWidth={1.5} aria-hidden="true" />;+ }+ if (stage === "host-paused") {+ return <Pause size={36} strokeWidth={1.5} aria-hidden="true" />;+ }+ if (stage === "host-offline") {+ return <WifiOff size={36} strokeWidth={1.5} aria-hidden="true" />;+ }+ if (+ stage === "route-failed" ||+ stage === "playback-failed" ||+ stage === "server-error"+ ) {+ return <TriangleAlert size={36} strokeWidth={1.5} aria-hidden="true" />;+ }+ if (+ stage === "recovering" ||+ stage === "waiting-sfu" ||+ stage === "preparing-p2p" ||+ stage === "preparing-sfu" ||+ stage === "receiving" ||+ stage === "allocating"+ ) {+ return (+ <LoaderCircle+ size={36}+ strokeWidth={1.5}+ className="spin"+ aria-hidden="true"+ />+ );+ }+ return <VideoOff size={36} strokeWidth={1.5} aria-hidden="true" />;+}+export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {const [presentationState, dispatchPresentation] = useReducer(reduceViewerPresentation,@@ -619,6 +662,17 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {if (!probe || probe.readySent) {return true;}+ if (+ !probe.connectedSent &&+ probe.snapshot?.connectionState === "connected" &&+ probe.snapshot.connectionId === probe.candidateConnectionId+ ) {+ probe.connectedSent = signal.send({+ type: "route-transport-connected",+ revision: probe.revision,+ connectionId: probe.candidateConnectionId,+ });+ }if (!pendingPeerHasDecodedFrame(probe)) {return false;}@@ -702,6 +756,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {parentPeerId: assignment.upstream.peerId,peer: null,decodedFrame: false,+ connectedSent: false,readySent: false,candidateConnectionId: candidate.connectionId,stream: null,@@ -980,6 +1035,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {probe.stream = null;probe.snapshot = null;probe.decodedFrame = false;+ probe.connectedSent = false;probe.readySent = false;peer.dispose();return true;@@ -1549,12 +1605,17 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {}return;}- video.srcObject = remoteMedia.stream;+ const streamChanged = video.srcObject !== remoteMedia.stream;+ if (streamChanged) {+ video.srcObject = remoteMedia.stream;+ }if (presentationState.host === "paused") {video.pause();return;}- attemptPlayback(video, remoteMedia);+ if (streamChanged) {+ attemptPlayback(video, remoteMedia);+ }}, [remoteMedia]);useEffect(() => {@@ -1890,13 +1951,30 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {/>{presentation.overlay === "blocking" && (<div className="stage-placeholder" role="status">- <VideoOff size={36} strokeWidth={1.5} aria-hidden="true" />+ <StageOverlayIcon stage={presentation.stage} /><span>{presentation.message}</span></div>)}- {presentation.overlay === "status" && (+ {presentation.overlay === "status" &&+ presentation.stage === "needs-play" && (+ <button+ className="stage-overlay is-interactive"+ type="button"+ onClick={() => {+ const video = videoRef.current;+ const binding = remoteMediaRef.current;+ if (video && binding) attemptPlayback(video, binding);+ }}+ >+ <StageOverlayIcon stage={presentation.stage} />+ <span>{presentation.message}</span>+ </button>+ )}+ {presentation.overlay === "status" &&+ presentation.stage !== "needs-play" && (<div className="stage-overlay" role="status">- {presentation.message}+ <StageOverlayIcon stage={presentation.stage} />+ <span>{presentation.message}</span></div>)}</section>diff --git a/src/client/styles.css b/src/client/styles.cssindex 748df582..6021709c 100644--- a/src/client/styles.css+++ b/src/client/styles.css@@ -327,11 +327,30 @@ h3 {}.stage-overlay {+ width: 100%;+ padding: 0;+ border: 0;color: var(--text);background: rgba(5, 7, 6, 0.72);+ font: inherit;+ text-align: center;pointer-events: none;}+.stage-overlay.is-interactive {+ cursor: pointer;+ pointer-events: auto;+}++.stage-overlay.is-interactive:hover {+ background: rgba(5, 7, 6, 0.8);+}++.stage-overlay.is-interactive:focus-visible {+ outline: 2px solid var(--green);+ outline-offset: -3px;+}+.stage-entry {grid-template-columns: minmax(0, 1fr);grid-template-rows: minmax(0, 1fr) 44px minmax(0, 1fr);diff --git a/src/server/hybrid-media-router.ts b/src/server/hybrid-media-router.tsindex 0a6fcc38..31119ad5 100644--- a/src/server/hybrid-media-router.ts+++ b/src/server/hybrid-media-router.ts@@ -509,6 +509,56 @@ export class HybridMediaRouter {this.requestPump(participant.roomId);}+ handleRouteTransportConnected(+ participant: AuthenticatedRouteParticipant,+ message: Extract<ClientMessage, { type: "route-transport-connected" }>,+ ): void {+ if (participant.role !== "viewer") return;+ const room = this.rooms.get(participant.roomId);+ const controller = room?.controller;+ const operation = controller?.snapshot().operation;+ const current = operation?.current;+ if (+ !room ||+ !controller ||+ !operation ||+ !current ||+ operation.childPeerId !== participant.peerId ||+ operation.childSessionId !== participant.sessionId ||+ current.revision !== message.revision ||+ current.connectionId !== message.connectionId ||+ current.tuple.kind !== "peer"+ ) {+ return;+ }+ const before = controller.snapshot().revision;+ const progressed = controller.candidateTransportConnected(+ {+ childPeerId: participant.peerId,+ childSessionId: participant.sessionId,+ revision: message.revision,+ connectionId: message.connectionId,+ },+ this.now(),+ );+ this.releaseResources(progressed.released);+ if (controller.snapshot().revision !== before) {+ this.broadcastActive(participant.roomId, room);+ }+ if (progressed.exhausted) {+ this.sendViewerRouteStatus(participant.roomId, operation.demandPeerId, {+ type: "route-status",+ revision: controller.snapshot().revision,+ state: "failed",+ reason: "route-exhausted",+ });+ }+ const after = controller.snapshot().operation;+ if (!progressed.accepted || after?.wakeAtMs !== operation.wakeAtMs) {+ this.requestPump(participant.roomId);+ }+ }+handleRouteMediaUnavailable(participant: AuthenticatedRouteParticipant,message: Extract<ClientMessage, { type: "route-media-unavailable" }>,@@ -593,7 +643,7 @@ export class HybridMediaRouter {if (settled.exhausted) {this.sendViewerRouteStatus(participant.roomId,- operation.childPeerId,+ operation.demandPeerId,{type: "route-status",revision: controller.snapshot().revision,@@ -790,11 +840,7 @@ export class HybridMediaRouter {return;}const guard = cursorGuard(operation, plan);- if (plan.tuple.kind === "sfu") {- this.resourceWaiters.add(roomId);- } else {- this.resourceWaiters.delete(roomId);- }+ this.resourceWaiters.delete(roomId);const preparation = await this.prepareCandidate(roomId,room,@@ -823,7 +869,7 @@ export class HybridMediaRouter {continue;}this.resourceWaiters.add(roomId);- this.sendViewerRouteStatus(roomId, operation.childPeerId, {+ this.sendViewerRouteStatus(roomId, operation.demandPeerId, {type: "route-status",revision: operation.baseRevision,state: "waiting",@@ -839,7 +885,7 @@ export class HybridMediaRouter {);this.releaseResources(skipped.released);if (skipped.exhausted) {- this.sendViewerRouteStatus(roomId, operation.childPeerId, {+ this.sendViewerRouteStatus(roomId, operation.demandPeerId, {type: "route-status",revision: controller.snapshot().revision,state: "failed",@@ -860,7 +906,7 @@ export class HybridMediaRouter {const gap = controller.retireCurrentCandidateProducer(guard, this.now());this.releaseResources(gap.released);if (gap.exhausted) {- this.sendViewerRouteStatus(roomId, operation.childPeerId, {+ this.sendViewerRouteStatus(roomId, operation.demandPeerId, {type: "route-status",revision: controller.snapshot().revision,state: "failed",@@ -897,12 +943,12 @@ export class HybridMediaRouter {this.releaseResources(begun.released);if (!begun.accepted || !begun.operation?.current) {if (begun.exhausted) {- this.sendViewerRouteStatus(roomId, operation.childPeerId, {- type: "route-status",- revision: controller.snapshot().revision,- state: "failed",- reason: "route-exhausted",- });+ this.sendViewerRouteStatus(roomId, operation.demandPeerId, {+ type: "route-status",+ revision: controller.snapshot().revision,+ state: "failed",+ reason: "route-exhausted",+ });}continue;}@@ -1467,7 +1513,7 @@ export class HybridMediaRouter {this.releaseResources(expired.released);if (room.controller.snapshot().revision !== before) this.broadcastActive(roomId, room);if (expired.exhausted) {- this.sendViewerRouteStatus(roomId, operation.childPeerId, {+ this.sendViewerRouteStatus(roomId, operation.demandPeerId, {type: "route-status",revision: room.controller.snapshot().revision,state: "failed",diff --git a/src/server/room-route-controller.ts b/src/server/room-route-controller.tsindex b7897f0d..52658483 100644--- a/src/server/room-route-controller.ts+++ b/src/server/room-route-controller.ts@@ -1,3 +1,4 @@+import { createHash } from "node:crypto";import { debuglog } from "node:util";import {@@ -93,6 +94,7 @@ export interface ControllerOptions {}const routeDebug = debuglog("screener-route");+const MAX_DIRECT_HEAD_START_MS = 5_000;interface Participant {peerId: string;@@ -102,6 +104,8 @@ interface Participant {joinOrder: number;effectiveDownstreamCapacity: number;blockedAtFactVersion?: number;+ bootstrapFailureAtFactVersion?: number;+ sfuFirstAtNextRoute?: boolean;failedTuple?: { key: string; factVersion: number };}@@ -115,17 +119,21 @@ interface Attempt<Resource> {publicationGeneration?: string;publicationConnectionId?: string;reservation: CandidateReservation<Resource>;+ transportConnected: boolean;}interface ChildOperation<Resource> {childPeerId: string;childSessionId: string;+ demandPeerId: string;+ demandSessionId: string;reason: RouteDemandReason;baseRevision: number;candidates: CandidatePlan[];cursor: number;deadlineAtMs: number;builtAtFactVersion: number;+ deferredParentPeerIds: string[];current?: Attempt<Resource>;}@@ -136,9 +144,23 @@ interface DirectContinuation {parentPeerIds: string[];}+interface SfuBootstrapIntent {+ demandPeerId: string;+ demandSessionId: string;+ factVersion: number;+ triedCarrierPeerIds: Set<string>;+}++interface SfuBootstrapCarrier {+ demandPeerId: string;+ demandSessionId: string;+ carrierPeerId: string;+}+export interface OperationSnapshot {childPeerId: string;childSessionId: string;+ demandPeerId: string;reason: RouteDemandReason;baseRevision: number;factVersion: number;@@ -211,6 +233,8 @@ export class RoomRouteController<Resource = unknown> {private paused = false;private readonly routeTimings = new Map<string, RouteTimingRecord>();private readonly directContinuations = new Map<string, DirectContinuation>();+ private sfuBootstrapIntent?: SfuBootstrapIntent;+ private sfuBootstrapExhaustedAtFactVersion?: number;constructor(private readonly options: ControllerOptions) {assertEndpointMediaCopyCapacity(options.endpointMediaCopyCapacity);@@ -292,7 +316,7 @@ export class RoomRouteController<Resource = unknown> {);const operation = this.operation;const childOrdinal = operation- ? ordinals.get(operation.childPeerId)+ ? ordinals.get(operation.demandPeerId): undefined;return {children,@@ -319,21 +343,17 @@ export class RoomRouteController<Resource = unknown> {const capacity = this.effectiveCapacity(input.effectiveDownstreamCapacity);const current = this.participants.get(input.peerId);const released: Resource[] = [];- if (- !current &&- input.role === "viewer" &&- this.operation?.reason === "direct-convergence"- ) {- released.push(...this.abortOperation(nowMs, "aborted"));- }if (current && current.role !== input.role) throw new Error("Route role cannot change");if (current) {let changed = false;const previousSessionId = current.sessionId;if (previousSessionId !== input.sessionId) {const revisionBefore = this.revision;- released.push(...this.abortOperation(nowMs, "stale"));+ if (this.operationUsesParticipantSession(input.peerId)) {+ released.push(...this.abortOperation(nowMs, "stale"));+ }this.directContinuations.delete(input.peerId);+ this.clearSfuBootstrapForDemand(input.peerId);current.sessionId = input.sessionId;const rebound = this.rebindCommittedSession(input.peerId, input.sessionId);released.push(...rebound.released);@@ -394,6 +414,7 @@ export class RoomRouteController<Resource = unknown> {if (!participant || participant.sessionId !== sessionId) return false;participant.sessionId = null;this.directContinuations.delete(peerId);+ this.clearSfuBootstrapForDemand(peerId);this.touchFacts();this.debug("participant-disconnected", {participant: this.debugPeer(peerId),@@ -411,6 +432,7 @@ export class RoomRouteController<Resource = unknown> {participant.departureConfirmed = true;participant.effectiveDownstreamCapacity = 0;this.directContinuations.delete(peerId);+ this.clearSfuBootstrapForDemand(peerId);if (nowMs !== undefined) {for (const childPeerId of this.childrenOf(peerId)) {this.recordDemand(childPeerId, nowMs, "parent-departed");@@ -528,6 +550,8 @@ export class RoomRouteController<Resource = unknown> {if (publication.usable) {publication.usable = false;this.directContinuations.clear();+ this.sfuBootstrapIntent = undefined;+ this.sfuBootstrapExhaustedAtFactVersion = undefined;if (nowMs !== undefined) {for (const [childPeerId, edge] of this.upstreamByViewer) {if (edge.kind === "sfu") {@@ -620,6 +644,15 @@ export class RoomRouteController<Resource = unknown> {const failedPeerIds = validation.exhaustedChildPeerId? [validation.exhaustedChildPeerId]: [];+ if (+ this.operation?.reason === "direct-convergence" &&+ (this.hasSfuBootstrapWork() || this.selectNextChild())+ ) {+ this.debug("direct-convergence-preempted", {+ child: this.debugPeer(this.operation.childPeerId),+ });+ released.push(...this.abortOperation(nowMs, "aborted"));+ }if (this.paused || this.operation) {return {operation: this.operationSnapshot(),@@ -631,12 +664,15 @@ export class RoomRouteController<Resource = unknown> {const removedPeerIds = this.pruneDepartedLeaves(released);for (let remaining = this.participants.size; remaining > 0; remaining -= 1) {- const bootstrap = this.bootstrapForBlockedDemand();- const routeChildPeerId = bootstrap ?? this.selectNextChild();+ const bootstrap = this.takeSfuBootstrapCarrier(nowMs, failedPeerIds);+ const routeChildPeerId = bootstrap ? undefined : this.selectNextChild();const continuation = routeChildPeerId? undefined+ : bootstrap+ ? undefined: this.selectDirectContinuation();- const childPeerId = routeChildPeerId ?? continuation?.childPeerId;+ const childPeerId =+ routeChildPeerId ?? bootstrap?.carrierPeerId ?? continuation?.childPeerId;if (!childPeerId) return { removedPeerIds, failedPeerIds, released };const child = this.participants.get(childPeerId)!;const reason: RouteDemandReason = continuation@@ -645,14 +681,26 @@ export class RoomRouteController<Resource = unknown> {? "sfu-bootstrap": (this.routeTimings.get(childPeerId)?.reason ??this.routeDemandReason(childPeerId));- this.ensureDemand(childPeerId, nowMs, reason);- const candidates = continuation+ const demandPeerId = bootstrap?.demandPeerId ?? childPeerId;+ const demand = this.participants.get(demandPeerId)!;+ this.ensureDemand(demandPeerId, nowMs, reason);+ let candidates = continuation? [continuation.plan]- : this.buildCandidates(- childPeerId,- bootstrap !== undefined,- reason,- );+ : this.buildCandidates(childPeerId, bootstrap !== undefined);+ if (!bootstrap && !continuation && demand.sfuFirstAtNextRoute) {+ const sfuIndex = candidates.findIndex(+ (candidate) => candidate.tuple.kind === "sfu",+ );+ if (sfuIndex > 0) {+ const [sfu] = candidates.splice(sfuIndex, 1);+ candidates = [sfu!, ...candidates];+ }+ }+ if (reason === "sfu-bootstrap") {+ candidates = candidates.filter(+ (candidate) => candidate.endpointTransition.kind !== "bounded-gap",+ );+ }if (candidates.length === 0) {this.debug("operation-unavailable", {child: this.debugPeer(childPeerId),@@ -662,36 +710,48 @@ export class RoomRouteController<Resource = unknown> {this.directContinuations.delete(childPeerId);continue;}+ if (reason === "sfu-bootstrap") {+ const failedDemandPeerId = this.completeSfuBootstrapCarrier(+ childPeerId,+ nowMs,+ "candidate-failed",+ );+ if (failedDemandPeerId) failedPeerIds.push(failedDemandPeerId);+ continue;+ }if (this.retireInvalidOperationEdge(childPeerId, released)) {this.revision = this.allocateRevision();this.touchFacts();}child.blockedAtFactVersion = this.factVersion;this.finishTiming(- childPeerId,+ demandPeerId,nowMs,"failed",reason === "capacity-reduction"? "endpoint-capacity": "candidate-failed",);- if (bootstrap === undefined) failedPeerIds.push(childPeerId);+ if (this.bootstrapCandidateAvailable(demandPeerId)) {+ continue;+ }+ this.rememberUnavailableSfuBootstrap(demandPeerId);+ failedPeerIds.push(demandPeerId);continue;}- this.startOperationTiming(childPeerId, nowMs);+ this.startOperationTiming(demandPeerId, nowMs);this.operation = {childPeerId,childSessionId: child.sessionId!,+ demandPeerId,+ demandSessionId: demand.sessionId!,reason,baseRevision: this.revision,candidates,cursor: 0,- deadlineAtMs:- nowMs +- (reason === "direct-convergence"- ? this.directHeadStartMs()- : this.options.operationTimeoutMs),+ deadlineAtMs: nowMs + this.options.operationTimeoutMs,builtAtFactVersion: this.factVersion,+ deferredParentPeerIds: [],};this.debug("operation-started", {child: this.debugPeer(childPeerId),@@ -784,6 +844,7 @@ export class RoomRouteController<Resource = unknown> {publicationGeneration,publicationConnectionId: input.publicationConnectionId,reservation: input.reservation,+ transportConnected: false,};this.debug("candidate-started", {child: this.debugPeer(operation.childPeerId),@@ -791,7 +852,7 @@ export class RoomRouteController<Resource = unknown> {revision: operation.current.revision,cursor: operation.cursor,});- this.startCandidateTiming(operation.childPeerId, input.nowMs);+ this.startCandidateTiming(operation.demandPeerId, input.nowMs);return { accepted: true, operation: this.operationSnapshot(), released: validation.released };}@@ -807,7 +868,7 @@ export class RoomRouteController<Resource = unknown> {) {return false;}- this.noteRejection(operation.childPeerId, bucket);+ this.noteRejection(operation.demandPeerId, bucket);return true;}@@ -821,8 +882,11 @@ export class RoomRouteController<Resource = unknown> {if (!operation || operation.current || !this.cursorGuardMatches(guard, operation)) {return { accepted: false, released: validation.released, exhausted: validation.exhausted };}+ if (bucket === "candidate-failed") {+ this.promoteNextDirectWithinHeadStart(operation, nowMs);+ }this.consumeDirectContinuationCandidate(operation);- this.noteRejection(operation.childPeerId, bucket);+ this.noteRejection(operation.demandPeerId, bucket);this.debug("candidate-rejected", {child: this.debugPeer(operation.childPeerId),candidate: this.debugTuple(operation.candidates[operation.cursor]!.tuple),@@ -830,7 +894,7 @@ export class RoomRouteController<Resource = unknown> {cursor: operation.cursor,});operation.cursor += 1;- this.clearCandidateTiming(operation.childPeerId);+ this.clearCandidateTiming(operation.demandPeerId);const advanced = this.validateOrAdvance(nowMs);return {operation: this.operationSnapshot(),@@ -920,7 +984,8 @@ export class RoomRouteController<Resource = unknown> {candidate: this.debugTuple(attempt.tuple),revision: attempt.revision,});- this.noteRejection(operation.childPeerId, "candidate-failed");+ this.promoteNextDirectWithinHeadStart(operation, nowMs);+ this.noteRejection(operation.demandPeerId, "candidate-failed");const failed = this.validateOrAdvance(nowMs, guard);return {accepted: false,@@ -929,13 +994,15 @@ export class RoomRouteController<Resource = unknown> {released: [...validation.released, ...failed.released],};}- this.finishTiming(- operation.childPeerId,- nowMs,- attempt.tuple.kind === "peer" ? "direct" : "sfu",- "none",- true,- );+ if (operation.reason !== "sfu-bootstrap") {+ this.finishTiming(+ operation.demandPeerId,+ nowMs,+ attempt.tuple.kind === "peer" ? "direct" : "sfu",+ "none",+ true,+ );+ }this.debug("candidate-ready", {child: this.debugPeer(operation.childPeerId),candidate: this.debugTuple(attempt.tuple),@@ -957,6 +1024,39 @@ export class RoomRouteController<Resource = unknown> {return { accepted: true, activeRevision: this.revision, released };}+ candidateTransportConnected(+ guard: CandidateGuard,+ nowMs: number,+ ): SettleResult<Resource> {+ const validation = this.validateOrAdvance(nowMs);+ const operation = this.operation;+ const attempt = operation?.current;+ if (+ !operation ||+ !attempt ||+ attempt.tuple.kind !== "peer" ||+ !this.guardMatches(guard, operation, attempt)+ ) {+ return {+ accepted: false,+ exhausted: validation.exhausted,+ activeRevision: this.revision,+ released: validation.released,+ };+ }+ attempt.transportConnected = true;+ this.debug("candidate-transport-connected", {+ child: this.debugPeer(operation.childPeerId),+ candidate: this.debugTuple(attempt.tuple),+ revision: attempt.revision,+ });+ return {+ accepted: true,+ activeRevision: this.revision,+ released: validation.released,+ };+ }+candidateFailed(guard: CandidateGuard, nowMs: number): SettleResult<Resource> {const operation = this.operation;if (@@ -968,8 +1068,9 @@ export class RoomRouteController<Resource = unknown> {candidate: this.debugTuple(operation.current.tuple),revision: operation.current.revision,});+ this.promoteNextDirectWithinHeadStart(operation, nowMs);this.consumeDirectContinuationCandidate(operation);- this.noteRejection(operation.childPeerId, "candidate-failed");+ this.noteRejection(operation.demandPeerId, "candidate-failed");}const validation = this.validateOrAdvance(nowMs, guard);if (validation.consumedGuard) {@@ -1008,6 +1109,8 @@ export class RoomRouteController<Resource = unknown> {this.participants.clear();this.routeTimings.clear();this.directContinuations.clear();+ this.sfuBootstrapIntent = undefined;+ this.sfuBootstrapExhaustedAtFactVersion = undefined;this.paused = true;return [...resources];}@@ -1030,8 +1133,23 @@ export class RoomRouteController<Resource = unknown> {} = { released, expired: false, consumedGuard: false };let operation = this.operation;if (!operation) return result;+ if (!this.bootstrapOperationOwned(operation)) {+ if (operation.current) {+ released.push(...reservationResources(operation.current.reservation));+ this.advanceActiveRevision(operation);+ }+ this.finishTiming(+ operation.demandPeerId,+ nowMs,+ this.currentFinalRoute(operation.demandPeerId),+ "stale",+ );+ this.operation = undefined;+ return result;+ }if (nowMs >= operation.deadlineAtMs) {const directConvergence = operation.reason === "direct-convergence";+ const sfuBootstrap = operation.reason === "sfu-bootstrap";if (directConvergence) {this.consumeDirectContinuationCandidate(operation);}@@ -1039,42 +1157,66 @@ export class RoomRouteController<Resource = unknown> {const revisionAdvanced = Boolean(operation.current);if (operation.current) this.advanceActiveRevision(operation);const factsChanged = operation.builtAtFactVersion !== this.factVersion;- this.finishTiming(- operation.childPeerId,- nowMs,- directConvergence- ? this.currentFinalRoute(operation.childPeerId)- : factsChanged- ? "waiting"- : "failed",- factsChanged ? "stale" : "operation-deadline",- );+ const failedBootstrapDemand = sfuBootstrap+ ? this.completeSfuBootstrapCarrier(+ operation.childPeerId,+ nowMs,+ factsChanged ? "stale" : "operation-deadline",+ )+ : undefined;+ const bootstrapAvailable =+ !directConvergence &&+ !sfuBootstrap &&+ !factsChanged &&+ this.bootstrapCandidateAvailable(operation.demandPeerId);+ const exhausted = sfuBootstrap+ ? failedBootstrapDemand !== undefined+ : !directConvergence && !factsChanged && !bootstrapAvailable;+ if (bootstrapAvailable) this.stageSfuBootstrap(operation);+ if (!sfuBootstrap) {+ this.finishTiming(+ operation.demandPeerId,+ nowMs,+ directConvergence+ ? this.currentFinalRoute(operation.demandPeerId)+ : exhausted+ ? "failed"+ : "waiting",+ factsChanged ? "stale" : "operation-deadline",+ );+ }this.blockAndClear(operation,- !directConvergence && !factsChanged,+ !directConvergence && !sfuBootstrap && !factsChanged,released,revisionAdvanced,);+ if (exhausted && !sfuBootstrap) {+ this.rememberUnavailableSfuBootstrap(operation.demandPeerId);+ }return {...result,- exhausted: directConvergence ? undefined : !factsChanged,- exhaustedChildPeerId:- directConvergence || factsChanged- ? undefined- : operation.childPeerId,+ exhausted: directConvergence ? undefined : exhausted,+ exhaustedChildPeerId: failedBootstrapDemand ??+ (exhausted ? operation.demandPeerId : undefined),expired: true,};}if (this.advanceExpiredDirectHeadStart(operation, nowMs, released)) {result.expired = true;}- if (this.participants.get(operation.childPeerId)?.sessionId !== operation.childSessionId) {+ if (+ this.participants.get(operation.childPeerId)?.sessionId !==+ operation.childSessionId ||+ this.participants.get(operation.demandPeerId)?.sessionId !==+ operation.demandSessionId+ ) {if (operation.current) released.push(...reservationResources(operation.current.reservation));if (operation.current) this.advanceActiveRevision(operation);this.finishTiming(- operation.childPeerId,+ operation.demandPeerId,nowMs,- this.currentFinalRoute(operation.childPeerId),+ this.currentFinalRoute(operation.demandPeerId),"aborted",);this.operation = undefined;@@ -1091,7 +1233,7 @@ export class RoomRouteController<Resource = unknown> {const plan = operation.candidates[operation.cursor];if (!guardFailed && plan && this.candidateValid(operation.childPeerId, plan, attempt)) return result;if (!guardFailed) {- this.noteRejection(operation.childPeerId, "stale");+ this.noteRejection(operation.demandPeerId, "stale");}if (operation.reason === "direct-convergence") {this.consumeDirectContinuationCandidate(operation);@@ -1100,48 +1242,70 @@ export class RoomRouteController<Resource = unknown> {this.advanceActiveRevision(operation);operation.current = undefined;operation.cursor += 1;- this.clearCandidateTiming(operation.childPeerId);+ this.clearCandidateTiming(operation.demandPeerId);result.consumedGuard = Boolean(guardFailed);this.replanRemaining(operation);}while (operation.cursor < operation.candidates.length &&!this.candidateValid(operation.childPeerId, operation.candidates[operation.cursor]!)) {- this.noteRejection(operation.childPeerId, "stale");+ this.noteRejection(operation.demandPeerId, "stale");if (operation.reason === "direct-convergence") {this.consumeDirectContinuationCandidate(operation);}operation.cursor += 1;- this.clearCandidateTiming(operation.childPeerId);+ this.clearCandidateTiming(operation.demandPeerId);}if (operation.cursor < operation.candidates.length) return result;const directConvergence = operation.reason === "direct-convergence";+ const sfuBootstrap = operation.reason === "sfu-bootstrap";const factsChanged = operation.builtAtFactVersion !== this.factVersion;- this.finishTiming(- operation.childPeerId,- nowMs,- directConvergence- ? this.currentFinalRoute(operation.childPeerId)- : factsChanged- ? "waiting"- : "failed",- factsChanged- ? "stale"- : this.routeTimings.get(operation.childPeerId)?.rejectionBucket ===- "none"- ? "candidate-failed"- : this.routeTimings.get(operation.childPeerId)!.rejectionBucket,- );+ const rejectionBucket = factsChanged+ ? "stale"+ : this.routeTimings.get(operation.demandPeerId)?.rejectionBucket ===+ "none"+ ? "candidate-failed"+ : (this.routeTimings.get(operation.demandPeerId)?.rejectionBucket ??+ "candidate-failed");+ const failedBootstrapDemand = sfuBootstrap+ ? this.completeSfuBootstrapCarrier(+ operation.childPeerId,+ nowMs,+ rejectionBucket,+ )+ : undefined;+ const bootstrapAvailable =+ !directConvergence &&+ !sfuBootstrap &&+ !factsChanged &&+ this.bootstrapCandidateAvailable(operation.demandPeerId);+ const exhausted = sfuBootstrap+ ? failedBootstrapDemand !== undefined+ : !directConvergence && !factsChanged && !bootstrapAvailable;+ if (bootstrapAvailable) this.stageSfuBootstrap(operation);+ if (!sfuBootstrap) {+ this.finishTiming(+ operation.demandPeerId,+ nowMs,+ directConvergence+ ? this.currentFinalRoute(operation.demandPeerId)+ : exhausted+ ? "failed"+ : "waiting",+ rejectionBucket,+ );+ }this.blockAndClear(operation,- !directConvergence && !factsChanged,+ !directConvergence && !sfuBootstrap && !factsChanged,released,this.revision !== activeRevisionAtStart,);- result.exhausted = directConvergence- ? undefined- : !factsChanged && !this.bootstrapForBlockedDemand();- if (result.exhausted) {- result.exhaustedChildPeerId = operation.childPeerId;+ result.exhausted = directConvergence ? undefined : exhausted;+ if (failedBootstrapDemand) {+ result.exhaustedChildPeerId = failedBootstrapDemand;+ } else if (exhausted) {+ result.exhaustedChildPeerId = operation.demandPeerId;+ this.rememberUnavailableSfuBootstrap(operation.demandPeerId);}}return result;@@ -1191,15 +1355,22 @@ export class RoomRouteController<Resource = unknown> {connectionId: attempt.connectionId, usable: true, physicalActive: true, resource: edge,});const remainingParentPeerIds =- operation.reason !== "sfu-bootstrap" &&- operation.reason !== "direct-convergence"- ? operation.candidates- .slice(operation.cursor + 1)- .flatMap((candidate) =>- candidate.tuple.kind === "peer"- ? [candidate.tuple.parentPeerId]- : [],- )+ operation.reason === "sfu-bootstrap" &&+ old?.kind === "peer" &&+ old.usable &&+ old.physicalActive+ ? [old.parentPeerId]+ : operation.reason !== "direct-convergence"+ ? [+ ...operation.candidates+ .slice(operation.cursor + 1)+ .flatMap((candidate) =>+ candidate.tuple.kind === "peer"+ ? [candidate.tuple.parentPeerId]+ : [],+ ),+ ...operation.deferredParentPeerIds,+ ]: [];if (remainingParentPeerIds.length > 0) {this.directContinuations.set(operation.childPeerId, {@@ -1223,6 +1394,19 @@ export class RoomRouteController<Resource = unknown> {if (old?.kind === "sfu" && !this.hasSfuSubscribers() && this.hostPublication) {this.hostPublication = null;}+ if (+ operation.reason === "sfu-bootstrap" &&+ attempt.tuple.kind === "sfu"+ ) {+ const demand = this.participants.get(operation.demandPeerId);+ if (demand?.sessionId === operation.demandSessionId) {+ demand.sfuFirstAtNextRoute = true;+ }+ this.sfuBootstrapIntent = undefined;+ this.sfuBootstrapExhaustedAtFactVersion = undefined;+ } else if (this.usableRoute(operation.demandPeerId)) {+ this.clearSfuBootstrapForDemand(operation.demandPeerId);+ }this.assertGraph();this.debug("route-committed", {child: this.debugPeer(operation.childPeerId),@@ -1240,7 +1424,6 @@ export class RoomRouteController<Resource = unknown> {private buildCandidates(childPeerId: string,sfuOnly: boolean,- reason: RouteDemandReason,): CandidatePlan[] {const child = this.participants.get(childPeerId)!;const failedKey = child.failedTuple?.factVersion === this.factVersion@@ -1252,6 +1435,7 @@ export class RoomRouteController<Resource = unknown> {!descendants.has(parent.peerId) && this.sourceUsable(parent.peerId) && this.targetFits(parent.peerId, childPeerId)).sort((left, right) => this.depth(left.peerId) - this.depth(right.peerId) ||this.remaining(right.peerId, childPeerId) - this.remaining(left.peerId, childPeerId) ||+ stablePairRank(childPeerId, left.peerId) - stablePairRank(childPeerId, right.peerId) ||compareParticipant(left, right));const directCandidates: CandidateTuple[] = parents.map((parent) => ({kind: "peer",@@ -1272,9 +1456,7 @@ export class RoomRouteController<Resource = unknown> {? [sfuCandidate]: []: sfuCandidate- ? reason === "join" && sfuCandidate.publication === "reuse"- ? [sfuCandidate, ...directCandidates]- : directCandidates.length > 0+ ? directCandidates.length > 0? [directCandidates[0]!, sfuCandidate, ...directCandidates.slice(1)]: [sfuCandidate]: [...directCandidates, ...(sfuCandidate ? [sfuCandidate] : [])];@@ -1307,7 +1489,9 @@ export class RoomRouteController<Resource = unknown> {childPeerId: string;plan: CandidatePlan;} | undefined {- for (const [childPeerId, continuation] of this.directContinuations) {+ for (const [childPeerId, continuation] of [+ ...this.directContinuations,+ ]) {const child = this.participants.get(childPeerId);const edge = this.upstreamByViewer.get(childPeerId);if (@@ -1326,8 +1510,7 @@ export class RoomRouteController<Resource = unknown> {this.directContinuations.delete(childPeerId);continue;}- while (continuation.parentPeerIds.length > 0) {- const parentPeerId = continuation.parentPeerIds[0]!;+ for (const parentPeerId of continuation.parentPeerIds) {const tuple: CandidateTuple = {kind: "peer",parentPeerId,@@ -1341,19 +1524,23 @@ export class RoomRouteController<Resource = unknown> {) {return { childPeerId, plan };}- continuation.parentPeerIds.shift();}- this.directContinuations.delete(childPeerId);- this.debug("direct-convergence-complete", {- child: this.debugPeer(childPeerId),- route: "sfu",- });+ if (continuation.parentPeerIds.length === 0) {+ this.directContinuations.delete(childPeerId);+ this.debug("direct-convergence-complete", {+ child: this.debugPeer(childPeerId),+ route: "sfu",+ });+ }}return undefined;}private directHeadStartMs(): number {- return Math.max(1, Math.floor(this.options.operationTimeoutMs / 2));+ return Math.min(+ MAX_DIRECT_HEAD_START_MS,+ Math.max(1, Math.floor(this.options.operationTimeoutMs / 2)),+ );}private consumeDirectContinuationCandidate(@@ -1366,7 +1553,8 @@ export class RoomRouteController<Resource = unknown> {const continuation = this.directContinuations.get(operation.childPeerId);if (!continuation) return;const index = continuation.parentPeerIds.indexOf(tuple.parentPeerId);- if (index >= 0) continuation.parentPeerIds.splice(index, 1);+ if (index < 0) return;+ continuation.parentPeerIds.splice(index, 1);this.debug("direct-convergence-advanced", {child: this.debugPeer(operation.childPeerId),parent: this.debugPeer(tuple.parentPeerId),@@ -1374,21 +1562,261 @@ export class RoomRouteController<Resource = unknown> {});if (continuation.parentPeerIds.length === 0) {this.directContinuations.delete(operation.childPeerId);+ } else {+ this.directContinuations.delete(operation.childPeerId);+ this.directContinuations.set(operation.childPeerId, continuation);+ }+ }++ private peekSfuBootstrapCarrier(): SfuBootstrapCarrier | undefined {+ const intent = this.currentSfuBootstrapIntent();+ if (!intent) return undefined;+ const carrierPeerId = this.safeSfuBootstrapCarriers(+ intent.demandPeerId,+ intent.triedCarrierPeerIds,+ )[0];+ return carrierPeerId+ ? {+ demandPeerId: intent.demandPeerId,+ demandSessionId: intent.demandSessionId,+ carrierPeerId,+ }+ : undefined;+ }++ private hasSfuBootstrapWork(): boolean {+ if (+ this.sfuBootstrapExhaustedAtFactVersion === this.factVersion+ ) {+ return this.availableViewers(true).some(+ (viewer) =>+ viewer.blockedAtFactVersion === this.factVersion &&+ viewer.bootstrapFailureAtFactVersion !== this.factVersion,+ );}+ return this.currentSfuBootstrapIntent() !== undefined;}- private bootstrapForBlockedDemand(): string | undefined {- if (!this.options.sfuEnabled || this.hostPublication || this.hostHasPublicationSlot()) return undefined;- const demand = this.availableViewers(true).find((viewer) => viewer.blockedAtFactVersion === this.factVersion);- if (!demand) return undefined;+ private takeSfuBootstrapCarrier(+ nowMs: number,+ failedPeerIds: string[],+ ): SfuBootstrapCarrier | undefined {+ if (+ this.sfuBootstrapExhaustedAtFactVersion === this.factVersion &&+ this.sfuBootstrapGloballyNeeded()+ ) {+ this.reportSfuBootstrapFailures(nowMs, failedPeerIds);+ return undefined;+ }+ const carrier = this.peekSfuBootstrapCarrier();+ if (carrier) return carrier;+ if (!this.currentSfuBootstrapIntent()) return undefined;+ this.sfuBootstrapIntent = undefined;+ this.sfuBootstrapExhaustedAtFactVersion = this.factVersion;+ this.reportSfuBootstrapFailures(nowMs, failedPeerIds);+ return undefined;+ }++ private currentSfuBootstrapIntent(): SfuBootstrapIntent | undefined {+ if (+ this.sfuBootstrapExhaustedAtFactVersion !== undefined &&+ this.sfuBootstrapExhaustedAtFactVersion !== this.factVersion+ ) {+ this.sfuBootstrapExhaustedAtFactVersion = undefined;+ }+ if (this.sfuBootstrapExhaustedAtFactVersion === this.factVersion) {+ return undefined;+ }+ const current = this.sfuBootstrapIntent;+ if (current) {+ const demand = this.participants.get(current.demandPeerId);+ if (+ this.sfuBootstrapNeeded(current.demandPeerId) &&+ demand?.sessionId === current.demandSessionId+ ) {+ current.factVersion = this.factVersion;+ return current;+ }+ this.sfuBootstrapIntent = undefined;+ }+ const demand = this.availableViewers(true).find(+ (viewer) =>+ viewer.blockedAtFactVersion === this.factVersion &&+ this.sfuBootstrapNeeded(viewer.peerId),+ );+ if (!demand?.sessionId) return undefined;+ const created: SfuBootstrapIntent = {+ demandPeerId: demand.peerId,+ demandSessionId: demand.sessionId,+ factVersion: this.factVersion,+ triedCarrierPeerIds: new Set(),+ };+ this.sfuBootstrapIntent = created;+ return created;+ }++ private bootstrapOperationOwned(+ operation: ChildOperation<Resource>,+ ): boolean {+ if (operation.reason !== "sfu-bootstrap") return true;+ const intent = this.sfuBootstrapIntent;+ if (+ !intent ||+ intent.demandPeerId !== operation.demandPeerId ||+ intent.demandSessionId !== operation.demandSessionId ||+ !this.sfuBootstrapNeeded(operation.demandPeerId)+ ) {+ return false;+ }+ if (intent.factVersion !== this.factVersion) {+ intent.factVersion = this.factVersion;+ }+ return this.safeSfuBootstrapCarriers(+ operation.demandPeerId,+ intent.triedCarrierPeerIds,+ ).includes(operation.childPeerId);+ }++ private sfuBootstrapNeeded(demandPeerId: string): boolean {+ return Boolean(+ this.sfuBootstrapGloballyNeeded() &&+ this.participants.get(demandPeerId)?.sessionId &&+ !this.usableRoute(demandPeerId),+ );+ }++ private sfuBootstrapGloballyNeeded(): boolean {+ return Boolean(+ this.options.sfuEnabled &&+ !this.hostPublication &&+ !this.hostHasPublicationSlot(),+ );+ }++ private safeSfuBootstrapCarriers(+ demandPeerId: string,+ triedCarrierPeerIds?: ReadonlySet<string>,+ ): string[] {+ if (!this.sfuBootstrapNeeded(demandPeerId)) return [];+ const tuple: Extract<CandidateTuple, { kind: "sfu" }> = {+ kind: "sfu",+ publication: "create",+ };return this.childrenOf(this.options.hostPeerId)- .filter((id) => {- const participant = this.participants.get(id);- const edge = this.upstreamByViewer.get(id);- return participant?.sessionId && participant.blockedAtFactVersion !== this.factVersion &&- edge?.kind === "peer" && edge.transport === "direct" && edge.usable && edge.physicalActive;+ .filter((peerId) => {+ if (triedCarrierPeerIds?.has(peerId)) return false;+ const participant = this.participants.get(peerId);+ const edge = this.upstreamByViewer.get(peerId);+ const plan = this.planCandidate(peerId, tuple);+ return Boolean(+ participant?.sessionId &&+ edge?.kind === "peer" &&+ edge.transport === "direct" &&+ edge.usable &&+ edge.physicalActive &&+ plan &&+ plan.endpointTransition.kind !== "bounded-gap",+ );})- .sort((left, right) => compareParticipant(this.participants.get(right)!, this.participants.get(left)!))[0];+ .sort((left, right) =>+ compareParticipant(+ this.participants.get(right)!,+ this.participants.get(left)!,+ ),+ );+ }++ private completeSfuBootstrapCarrier(+ carrierPeerId: string,+ nowMs: number,+ bucket: RouteDiagnosticRejectionBucket,+ ): string | undefined {+ const intent = this.sfuBootstrapIntent;+ if (+ !intent ||+ intent.factVersion !== this.factVersion+ ) {+ return undefined;+ }+ intent.triedCarrierPeerIds.add(carrierPeerId);+ if (+ this.safeSfuBootstrapCarriers(+ intent.demandPeerId,+ intent.triedCarrierPeerIds,+ ).length > 0+ ) {+ return undefined;+ }+ const demand = this.participants.get(intent.demandPeerId);+ if (demand) demand.blockedAtFactVersion = this.factVersion;+ this.finishTiming(intent.demandPeerId, nowMs, "failed", bucket);+ if (demand) demand.bootstrapFailureAtFactVersion = this.factVersion;+ this.sfuBootstrapIntent = undefined;+ this.sfuBootstrapExhaustedAtFactVersion = this.factVersion;+ return intent.demandPeerId;+ }++ private reportSfuBootstrapFailures(+ nowMs: number,+ failedPeerIds: string[],+ ): void {+ for (const demand of this.availableViewers(true)) {+ if (+ demand.blockedAtFactVersion !== this.factVersion ||+ this.usableRoute(demand.peerId) ||+ demand.bootstrapFailureAtFactVersion === this.factVersion+ ) {+ continue;+ }+ demand.bootstrapFailureAtFactVersion = this.factVersion;+ this.finishTiming(demand.peerId, nowMs, "failed", "candidate-failed");+ failedPeerIds.push(demand.peerId);+ }+ }++ private rememberUnavailableSfuBootstrap(demandPeerId: string): void {+ if (!this.sfuBootstrapNeeded(demandPeerId)) return;+ const demand = this.participants.get(demandPeerId);+ if (!demand?.sessionId) return;+ if (+ this.sfuBootstrapExhaustedAtFactVersion === this.factVersion+ ) {+ demand.bootstrapFailureAtFactVersion = this.factVersion;+ return;+ }+ demand.bootstrapFailureAtFactVersion = this.factVersion;+ this.sfuBootstrapIntent = undefined;+ this.sfuBootstrapExhaustedAtFactVersion = this.factVersion;+ }++ private stageSfuBootstrap(+ operation: ChildOperation<Resource>,+ ): void {+ const demand = this.participants.get(operation.demandPeerId);+ if (!demand?.sessionId || !this.sfuBootstrapNeeded(demand.peerId)) return;+ if (this.sfuBootstrapExhaustedAtFactVersion === this.factVersion) return;+ const current = this.sfuBootstrapIntent;+ if (+ current?.demandPeerId === demand.peerId &&+ current.demandSessionId === demand.sessionId &&+ current.factVersion === this.factVersion+ ) {+ return;+ }+ this.sfuBootstrapIntent = {+ demandPeerId: demand.peerId,+ demandSessionId: demand.sessionId,+ factVersion: this.factVersion,+ triedCarrierPeerIds: new Set(),+ };+ }++ private clearSfuBootstrapForDemand(demandPeerId: string): void {+ const demand = this.participants.get(demandPeerId);+ if (demand) demand.sfuFirstAtNextRoute = undefined;+ if (this.sfuBootstrapIntent?.demandPeerId === demandPeerId) {+ this.sfuBootstrapIntent = undefined;+ }}private availableViewers(includeBlocked = false): Participant[] {@@ -1533,6 +1961,7 @@ export class RoomRouteController<Resource = unknown> {this.participants.delete(participant.peerId);this.routeTimings.delete(participant.peerId);this.directContinuations.delete(participant.peerId);+ this.clearSfuBootstrapForDemand(participant.peerId);removed.push(participant.peerId);changed = true;}@@ -1555,9 +1984,9 @@ export class RoomRouteController<Resource = unknown> {if (!this.operation) return [];if (nowMs !== undefined) {this.finishTiming(- this.operation.childPeerId,+ this.operation.demandPeerId,nowMs,- this.currentFinalRoute(this.operation.childPeerId),+ this.currentFinalRoute(this.operation.demandPeerId),bucket,);}@@ -1570,6 +1999,22 @@ export class RoomRouteController<Resource = unknown> {return released;}+ private operationUsesParticipantSession(peerId: string): boolean {+ const operation = this.operation;+ if (!operation) return false;+ if (+ operation.childPeerId === peerId ||+ operation.demandPeerId === peerId+ ) {+ return true;+ }+ const tuple =+ operation.current?.tuple ?? operation.candidates[operation.cursor]?.tuple;+ return tuple?.kind === "peer"+ ? tuple.parentPeerId === peerId+ : peerId === this.options.hostPeerId;+ }+private advanceActiveRevision(operation: ChildOperation<Resource>): void {this.revision = this.allocateRevision();operation.baseRevision = this.revision;@@ -1648,6 +2093,7 @@ export class RoomRouteController<Resource = unknown> {const operation = this.operation;if (!operation) return undefined;return { childPeerId: operation.childPeerId, childSessionId: operation.childSessionId,+ demandPeerId: operation.demandPeerId,reason: operation.reason,baseRevision: operation.baseRevision, factVersion: operation.builtAtFactVersion,candidates: operation.candidates.map(cloneCandidatePlan),@@ -1664,18 +2110,15 @@ export class RoomRouteController<Resource = unknown> {): boolean {const currentTuple =operation.current?.tuple ?? operation.candidates[operation.cursor]?.tuple;- const fallbackTuple = operation.candidates[operation.cursor + 1]?.tuple;+ const sfuIndex = this.foregroundSfuIndex(operation);if (- operation.reason === "direct-convergence" ||- operation.cursor !== 0 ||currentTuple?.kind !== "peer" ||- (fallbackTuple?.kind !== "sfu" && !this.bootstrapCandidateAvailable())+ operation.current?.transportConnected ||+ sfuIndex <= operation.cursor) {return false;}- const headStartDeadlineAtMs =- operation.deadlineAtMs - this.options.operationTimeoutMs +- this.directHeadStartMs();+ const headStartDeadlineAtMs = this.directHeadStartDeadlineAt(operation);if (nowMs < headStartDeadlineAtMs) {return false;}@@ -1683,13 +2126,22 @@ export class RoomRouteController<Resource = unknown> {? this.debugTuple(operation.current.tuple): null;if (operation.current) {- this.noteRejection(operation.childPeerId, "first-frame-timeout");+ this.noteRejection(operation.demandPeerId, "first-frame-timeout");released.push(...reservationResources(operation.current.reservation));this.advanceActiveRevision(operation);operation.current = undefined;- operation.cursor += 1;- this.clearCandidateTiming(operation.childPeerId);- }+ this.clearCandidateTiming(operation.demandPeerId);+ }+ operation.deferredParentPeerIds.push(+ ...operation.candidates+ .slice(operation.cursor, sfuIndex)+ .flatMap((candidate) =>+ candidate.tuple.kind === "peer"+ ? [candidate.tuple.parentPeerId]+ : [],+ ),+ );+ operation.cursor = sfuIndex;this.debug("direct-head-start-expired", {child: this.debugPeer(operation.childPeerId),activeCandidate,@@ -1703,39 +2155,65 @@ export class RoomRouteController<Resource = unknown> {private operationWakeAt(operation: ChildOperation<Resource>): number {const currentTuple =operation.current?.tuple ?? operation.candidates[operation.cursor]?.tuple;- const fallbackTuple = operation.candidates[operation.cursor + 1]?.tuple;if (- operation.reason !== "direct-convergence" &&- operation.cursor === 0 &¤tTuple?.kind === "peer" &&- (fallbackTuple?.kind === "sfu" || this.bootstrapCandidateAvailable())+ !operation.current?.transportConnected &&+ this.foregroundSfuIndex(operation) > operation.cursor) {- return (- operation.deadlineAtMs - this.options.operationTimeoutMs +- this.directHeadStartMs()- );+ return this.directHeadStartDeadlineAt(operation);}return operation.deadlineAtMs;}- private bootstrapCandidateAvailable(): boolean {+ private directHeadStartDeadlineAt(+ operation: ChildOperation<Resource>,+ ): number {+ return (+ operation.deadlineAtMs - this.options.operationTimeoutMs ++ this.directHeadStartMs()+ );+ }++ private foregroundSfuIndex(operation: ChildOperation<Resource>): number {+ if (operation.reason === "direct-convergence") return -1;+ const index = operation.candidates.findIndex(+ (candidate, candidateIndex) =>+ candidateIndex >= operation.cursor && candidate.tuple.kind === "sfu",+ );+ return index >= 0+ ? index+ : this.bootstrapCandidateAvailable(operation.demandPeerId)+ ? operation.candidates.length+ : -1;+ }++ private promoteNextDirectWithinHeadStart(+ operation: ChildOperation<Resource>,+ nowMs: number,+ ): void {+ const sfuIndex = this.foregroundSfuIndex(operation);if (- !this.options.sfuEnabled ||- this.hostPublication ||- this.hostHasPublicationSlot()+ sfuIndex !== operation.cursor + 1 ||+ nowMs >= this.directHeadStartDeadlineAt(operation)+ ) {+ return;+ }+ const nextDirectIndex = operation.candidates.findIndex(+ (candidate, candidateIndex) =>+ candidateIndex > sfuIndex && candidate.tuple.kind === "peer",+ );+ if (nextDirectIndex < 0) return;+ const [nextDirect] = operation.candidates.splice(nextDirectIndex, 1);+ operation.candidates.splice(sfuIndex, 0, nextDirect!);+ }++ private bootstrapCandidateAvailable(demandPeerId: string): boolean {+ if (+ this.sfuBootstrapExhaustedAtFactVersion === this.factVersion) {return false;}- return this.childrenOf(this.options.hostPeerId).some((id) => {- const participant = this.participants.get(id);- const edge = this.upstreamByViewer.get(id);- return Boolean(- participant?.sessionId &&- edge?.kind === "peer" &&- edge.usable &&- edge.physicalActive,- );- });+ return this.safeSfuBootstrapCarriers(demandPeerId).length > 0;}private guardMatches(guard: CandidateGuard, operation: ChildOperation<Resource>, attempt: Attempt<Resource>): boolean {@@ -1882,7 +2360,7 @@ export class RoomRouteController<Resource = unknown> {finalRoute: "waiting",rejectionBucket: "none",};- if (this.operation?.childPeerId === childPeerId) {+ if (this.operation?.demandPeerId === childPeerId) {this.operation.reason = reason;record.operationStartedAtMs = nowMs;}@@ -2095,6 +2573,15 @@ function compareParticipant(left: Participant, right: Participant): number {return left.joinOrder - right.joinOrder || left.peerId.localeCompare(right.peerId);}+function stablePairRank(childPeerId: string, parentPeerId: string): number {+ return createHash("sha256")+ .update(childPeerId)+ .update("\0")+ .update(parentPeerId)+ .digest()+ .readUIntBE(0, 6);+}+function elapsedMs(startedAtMs: number, endedAtMs: number): number | null {const elapsed = Math.floor(endedAtMs - startedAtMs);return Number.isSafeInteger(elapsed) && elapsed >= 0 ? elapsed : null;diff --git a/src/server/signaling.ts b/src/server/signaling.tsindex ff4ff38a..9545fbf0 100644--- a/src/server/signaling.ts+++ b/src/server/signaling.ts@@ -886,6 +886,19 @@ export class SignalingServer {message,);return;+ case "route-transport-connected":+ if (!this.isHybridMediaEnabled()) {+ this.sendError(socket, "FORBIDDEN", "Media routes are not enabled");+ return;+ }+ this.hybridMediaRouter!.handleRouteTransportConnected(+ {+ ...authenticated,+ sessionId: this.socketStates.get(socket)!.sessionId,+ },+ message,+ );+ return;case "route-media-unavailable":if (!this.isHybridMediaEnabled()) {this.sendError(socket, "FORBIDDEN", "Media routes are not enabled");diff --git a/src/shared/protocol.ts b/src/shared/protocol.tsindex bf453330..c5e83ec9 100644--- a/src/shared/protocol.ts+++ b/src/shared/protocol.ts@@ -695,6 +695,13 @@ export const clientMessageSchema = z.union([phase: mediaRoutePhaseSchema,}).strict(),+ z+ .object({+ type: z.literal("route-transport-connected"),+ revision: mediaRouteRevisionSchema,+ connectionId: opaqueIdSchema,+ })+ .strict(),z.object({type: z.literal("route-media-unavailable"),diff --git a/tests/hybrid-media-router.test.ts b/tests/hybrid-media-router.test.tsindex ea290a16..204bb0a2 100644--- a/tests/hybrid-media-router.test.ts+++ b/tests/hybrid-media-router.test.ts@@ -231,6 +231,45 @@ describe("HybridMediaRouter v9 runtime", () => {}});+ it("keeps an exact transport-connected direct candidate past the boundary", async () => {+ vi.useFakeTimers();+ vi.setSystemTime(0);+ const { store, sent, router } = harness(2, true, 300);+ try {+ const room = await store.createRoom();+ const host = connectHost(store, room);+ complete(router, host);+ const viewer = connectViewer(store, room, "transport-connected");+ complete(router, viewer);+ await vi.waitFor(() =>+ expect(preparedFor(sent, viewer.sessionId)?.candidate.transport).toBe(+ "direct",+ ),+ );+ const direct = preparedFor(sent, viewer.sessionId)!;+ router.handleRouteTransportConnected(viewer, {+ type: "route-transport-connected",+ revision: direct.revision,+ connectionId: direct.candidate.connectionId,+ });+ await vi.advanceTimersByTimeAsync(150);+ expect(preparedFor(sent, viewer.sessionId)).toEqual(direct);+ router.handleRouteReady(viewer, {+ type: "route-ready",+ revision: direct.revision,+ phase: "prepare",+ });+ await vi.waitFor(() =>+ expect(activeAfter(sent, viewer.sessionId, direct.revision - 1)).toMatchObject({+ assignment: { upstream: { kind: "peer" } },+ }),+ );+ } finally {+ await router.close();+ vi.useRealTimers();+ }+ });+it("uses the direct boundary to bootstrap SFU when every Host slot is full", async () => {vi.useFakeTimers();vi.setSystemTime(0);@@ -283,14 +322,61 @@ describe("HybridMediaRouter v9 runtime", () => {"sfu",),);+ const secondBootstrap = preparedFor(sent, secondRoot.sessionId)!;+ router.handleRouteFailed(secondRoot, {+ type: "route-failed",+ revision: secondBootstrap.revision,+ phase: "prepare",+ connectionId: secondBootstrap.candidate.connectionId,+ });+ await vi.waitFor(() =>+ expect(preparedFor(sent, firstRoot.sessionId)?.candidate.transport).toBe(+ "sfu",+ ),+ );expect(sent- .get(waiting.sessionId)+ .get(secondRoot.sessionId)?.some((message) =>message.type === "route-status" && message.state === "failed",),).toBe(false);+ const firstBootstrap = preparedFor(sent, firstRoot.sessionId)!;+ router.handleRouteFailed(firstRoot, {+ type: "route-failed",+ revision: firstBootstrap.revision,+ phase: "prepare",+ connectionId: firstBootstrap.candidate.connectionId,+ });+ await vi.waitFor(() =>+ expect(+ sent+ .get(waiting.sessionId)+ ?.findLast((message) => message.type === "route-status"),+ ).toMatchObject({+ state: "failed",+ reason: "route-exhausted",+ }),+ );+ for (const root of [firstRoot, secondRoot]) {+ expect(+ sent+ .get(root.sessionId)+ ?.some(+ (message) =>+ message.type === "route-status" && message.state === "failed",+ ),+ ).toBe(false);+ }+ expect(+ sent+ .get(waiting.sessionId)+ ?.some(+ (message) =>+ message.type === "route-status" && message.state === "failed",+ ),+ ).toBe(true);} finally {await router.close();vi.useRealTimers();@@ -709,7 +795,7 @@ describe("HybridMediaRouter v9 runtime", () => {});it("keeps SFU Viewer and downstream Peer evidence identities separate", async () => {- const { store, sent, router } = harness(1, true);+ const { store, sent, router } = harness(1, true, 1_000);try {const room = await store.createRoom();const { first } = await establishSfuRoom(store, sent, router, room);@@ -723,6 +809,12 @@ describe("HybridMediaRouter v9 runtime", () => {router.setViewerRelayCapacity(first, 1);const child = connectViewer(store, room, "sfu-peer-child");complete(router, child);+ await vi.waitFor(() =>+ expect(preparedFor(sent, child.sessionId)?.candidate.transport).toBe(+ "direct",+ ),+ );+ await new Promise((resolve) => setTimeout(resolve, 510));await vi.waitFor(() =>expect(preparedFor(sent, child.sessionId)?.candidate.transport).toBe("sfu",diff --git a/tests/protocol.test.ts b/tests/protocol.test.tsindex 34817161..f0767560 100644--- a/tests/protocol.test.ts+++ b/tests/protocol.test.ts@@ -822,6 +822,13 @@ describe("client signaling protocol", () => {phase: "prepare",}).success,).toBe(true);+ expect(+ clientMessageSchema.safeParse({+ type: "route-transport-connected",+ revision: 7,+ connectionId: "connection_12345678",+ }).success,+ ).toBe(true);expect(clientMessageSchema.safeParse({type: "route-media-unavailable",@@ -850,6 +857,12 @@ describe("client signaling protocol", () => {phase: "prepare",}).success,).toBe(false);+ expect(+ clientMessageSchema.safeParse({+ type: "route-transport-connected",+ revision: 7,+ }).success,+ ).toBe(false);expect(clientMessageSchema.safeParse({type: "route-media-unavailable",diff --git a/tests/room-route-controller.test.ts b/tests/room-route-controller.test.tsindex 896ea4c4..dde49f7e 100644--- a/tests/room-route-controller.test.ts+++ b/tests/room-route-controller.test.ts@@ -437,14 +437,22 @@ describe("RoomRouteController", () => {let nowMs = 0;waiting.forEach((peerId, index) => {- const sfuOperation = routes.reconcile(nowMs).operation!;- expect(sfuOperation.childPeerId).toBe(peerId);+ const directOperation = routes.reconcile(nowMs).operation!;+ expect(directOperation.childPeerId).toBe(peerId);+ expect(directOperation.candidates[0]?.tuple.kind).toBe("peer");+ beginCandidate(routes, {+ nowMs: nowMs + 1,+ connectionId: `${peerId}_direct`,+ reservation: { kind: "direct" },+ });+ routes.operationExpired(directOperation.wakeAtMs);+ const sfuOperation = routes.snapshot().operation!;expect(sfuOperation.candidates[sfuOperation.cursor]!.tuple).toEqual({kind: "sfu",publication: "reuse",});const prepared = beginCandidate(routes, {- nowMs: nowMs + 1,+ nowMs: directOperation.wakeAtMs + 1,connectionId: `${peerId}_sfu`,reservation: {kind: "sfu-reuse",@@ -459,10 +467,10 @@ describe("RoomRouteController", () => {revision: prepared.current!.revision,connectionId: `${peerId}_sfu`,},- nowMs + 2,+ directOperation.wakeAtMs + 2,).accepted,).toBe(true);- nowMs += 3;+ nowMs = directOperation.wakeAtMs + 3;expect(routes.snapshot().upstreamByViewer.get(B)).toMatchObject({kind: "sfu",@@ -691,6 +699,108 @@ describe("RoomRouteController", () => {});});+ it("uses the same direct head-start after an early hard failure", () => {+ const routes = controller(2, { sfuEnabled: true });+ addViewer(routes, D, 0);+ routes.hydrateEdge(D, peerEdge(HOST, "host_full"));+ routes.hydrateHostPublication("publication_1", "publication_resource");+ for (const peerId of [B, C]) {+ addViewer(routes, peerId, 1);+ routes.hydrateEdge(peerId, {+ kind: "sfu",+ publicationGeneration: "publication_1",+ transport: "sfu",+ connectionId: `${peerId}_sfu`,+ usable: true,+ physicalActive: true,+ resource: `${peerId}_subscription`,+ });+ }+ addViewer(routes, A, 0);++ const operation = routes.reconcile(0).operation!;+ expect(operation.candidates.map((candidate) => candidate.tuple.kind)).toEqual([+ "peer",+ "sfu",+ "peer",+ ]);+ const first = beginCandidate(routes, {+ nowMs: 1,+ connectionId: "first_direct",+ reservation: { kind: "direct" },+ }).operation!;+ expect(routes.candidateFailed({+ childPeerId: A,+ childSessionId: `${A}_session`,+ revision: first.current!.revision,+ connectionId: "first_direct",+ }, 2).accepted).toBe(true);+ expect(routes.snapshot().operation).toMatchObject({+ cursor: 1,+ wakeAtMs: operation.wakeAtMs,+ });+ expect(+ routes.snapshot().operation!.candidates[1]!.tuple.kind,+ ).toBe("peer");+ });++ it("keeps a transport-connected direct candidate until the total deadline", () => {+ const routes = controller(2, { sfuEnabled: true });+ addViewer(routes, D, 0);+ routes.hydrateEdge(D, peerEdge(HOST, "host_full"));+ routes.hydrateHostPublication("publication", "publication_resource");+ addViewer(routes, B, 1);+ routes.hydrateEdge(B, {+ kind: "sfu",+ publicationGeneration: "publication",+ transport: "sfu",+ connectionId: "b_sfu",+ usable: true,+ physicalActive: true,+ resource: "b_subscription",+ });+ addViewer(routes, A, 0);++ const operation = routes.reconcile(0).operation!;+ const direct = beginCandidate(routes, {+ nowMs: 1,+ connectionId: "a_direct",+ reservation: { kind: "direct" },+ }).operation!;+ expect(routes.candidateTransportConnected({+ childPeerId: A,+ childSessionId: `${A}_session`,+ revision: direct.current!.revision,+ connectionId: "a_direct",+ }, 1_000).accepted).toBe(true);+ expect(routes.candidateTransportConnected({+ childPeerId: A,+ childSessionId: `${A}_session`,+ revision: direct.current!.revision,+ connectionId: "a_direct",+ }, 1_001).accepted).toBe(true);+ expect(routes.candidateTransportConnected({+ childPeerId: A,+ childSessionId: `${A}_session`,+ revision: direct.current!.revision,+ connectionId: "stale_direct",+ }, 1_002).accepted).toBe(false);+ expect(routes.snapshot().revision).toBe(direct.current!.revision - 1);+ expect(routes.snapshot().operation?.wakeAtMs).toBe(operation.deadlineAtMs);+ expect(routes.operationExpired(operation.wakeAtMs).accepted).toBe(false);+ expect(routes.snapshot().operation?.current?.connectionId).toBe("a_direct");+ expect(routes.candidateReady({+ childPeerId: A,+ childSessionId: `${A}_session`,+ revision: direct.current!.revision,+ connectionId: "a_direct",+ }, operation.wakeAtMs + 1).accepted).toBe(true);+ expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({+ kind: "peer",+ connectionId: "a_direct",+ });+ });+it("keeps SFU active while converging through an SFU-fed parent", () => {const routes = controller(2, { sfuEnabled: true });addViewer(routes, B, 2);@@ -711,12 +821,20 @@ describe("RoomRouteController", () => {routes.hydrateEdge(C, peerEdge(HOST, "c_from_host"));addViewer(routes, A, 0);- expect(routes.reconcile(0).operation?.candidates[0]?.tuple).toEqual({- kind: "sfu",- publication: "reuse",+ const acquisition = routes.reconcile(0).operation!;+ expect(acquisition.candidates[0]?.tuple).toEqual({+ kind: "peer",+ parentPeerId: B,+ transport: "direct",});- const prepared = beginCandidate(routes, {+ beginCandidate(routes, {nowMs: 1,+ connectionId: "a_direct_head_start",+ reservation: { kind: "direct" },+ });+ routes.operationExpired(acquisition.wakeAtMs);+ const prepared = beginCandidate(routes, {+ nowMs: acquisition.wakeAtMs + 1,connectionId: "a_sfu_reuse",reservation: { kind: "sfu-reuse", edge: "a_subscription" },}).operation!;@@ -728,7 +846,7 @@ describe("RoomRouteController", () => {revision: prepared.current!.revision,connectionId: "a_sfu_reuse",},- 2,+ acquisition.wakeAtMs + 2,).accepted,).toBe(true);expect(routes.snapshot().hostPublication).toMatchObject({@@ -740,7 +858,7 @@ describe("RoomRouteController", () => {publicationGeneration: "publication_generation",usable: true,});- const convergence = routes.reconcile(3).operation!;+ const convergence = routes.reconcile(acquisition.wakeAtMs + 3).operation!;expect(convergence).toMatchObject({childPeerId: A,reason: "direct-convergence",@@ -751,7 +869,7 @@ describe("RoomRouteController", () => {transport: "direct",});const direct = beginCandidate(routes, {- nowMs: 4,+ nowMs: acquisition.wakeAtMs + 4,connectionId: "a_from_b",reservation: { kind: "direct" },}).operation!;@@ -764,7 +882,7 @@ describe("RoomRouteController", () => {childSessionId: `${A}_session`,revision: direct.current!.revision,connectionId: "a_from_b",- }, 5).accepted).toBe(true);+ }, acquisition.wakeAtMs + 5).accepted).toBe(true);expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({kind: "peer",parentPeerId: B,@@ -790,9 +908,21 @@ describe("RoomRouteController", () => {});}addViewer(routes, A, 0, 0);- routes.reconcile(0);- const sfu = beginCandidate(routes, {+ const acquisition = routes.reconcile(0).operation!;+ const headStartTuple = acquisition.candidates[0]!.tuple;+ expect(headStartTuple.kind).toBe("peer");+ const headStartParent = headStartTuple.kind === "peer"+ ? headStartTuple.parentPeerId+ : "";+ const otherParent = headStartParent === B ? C : B;+ beginCandidate(routes, {nowMs: 1,+ connectionId: "a_direct_head_start",+ reservation: { kind: "direct" },+ });+ routes.operationExpired(acquisition.wakeAtMs);+ const sfu = beginCandidate(routes, {+ nowMs: acquisition.wakeAtMs + 1,connectionId: "a_sfu",reservation: { kind: "sfu-reuse", edge: "a_subscription" },}).operation!;@@ -801,31 +931,98 @@ describe("RoomRouteController", () => {childSessionId: `${A}_session`,revision: sfu.current!.revision,connectionId: "a_sfu",- }, 2).accepted).toBe(true);+ }, acquisition.wakeAtMs + 2).accepted).toBe(true);- const first = routes.reconcile(3).operation!;+ const first = routes.reconcile(acquisition.wakeAtMs + 3).operation!;expect(first.candidates[0]?.tuple).toMatchObject({kind: "peer",- parentPeerId: B,+ parentPeerId: otherParent,});const failed = beginCandidate(routes, {- nowMs: 4,- connectionId: "a_from_b",+ nowMs: acquisition.wakeAtMs + 4,+ connectionId: "a_direct_followup",reservation: { kind: "direct" },}).operation!;expect(routes.candidateFailed({childPeerId: A,childSessionId: `${A}_session`,revision: failed.current!.revision,- connectionId: "a_from_b",- }, 5).exhausted).toBeUndefined();+ connectionId: "a_direct_followup",+ }, acquisition.wakeAtMs + 5).exhausted).toBeUndefined();expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({kind: "sfu",connectionId: "a_sfu",});- expect(routes.reconcile(6).operation?.candidates[0]?.tuple).toMatchObject({+ expect(+ routes.reconcile(acquisition.wakeAtMs + 6).operation?.candidates[0]?.tuple,+ ).toMatchObject({kind: "peer",- parentPeerId: C,+ parentPeerId: headStartParent,+ });+ });++ it("round-robins background direct convergence between SFU Viewers", () => {+ const routes = controller(2, { sfuEnabled: true });+ routes.hydrateHostPublication("publication", "publication_resource");+ for (const peerId of [B, C]) {+ addViewer(routes, peerId, 2);+ routes.hydrateEdge(peerId, {+ kind: "sfu",+ publicationGeneration: "publication",+ transport: "sfu",+ connectionId: `${peerId}_sfu`,+ usable: true,+ physicalActive: true,+ resource: `${peerId}_subscription`,+ });+ }++ let nowMs = 0;+ for (const peerId of [A, D]) {+ addViewer(routes, peerId, 0, nowMs);+ const acquisition = routes.reconcile(nowMs).operation!;+ beginCandidate(routes, {+ nowMs: nowMs + 1,+ connectionId: `${peerId}_head_start`,+ reservation: { kind: "direct" },+ });+ routes.operationExpired(acquisition.wakeAtMs);+ const sfu = beginCandidate(routes, {+ nowMs: acquisition.wakeAtMs + 1,+ connectionId: `${peerId}_sfu`,+ reservation: {+ kind: "sfu-reuse",+ edge: `${peerId}_subscription`,+ },+ }).operation!;+ expect(routes.candidateReady({+ childPeerId: peerId,+ childSessionId: `${peerId}_session`,+ revision: sfu.current!.revision,+ connectionId: `${peerId}_sfu`,+ }, acquisition.wakeAtMs + 2).accepted).toBe(true);+ nowMs = acquisition.wakeAtMs + 3;+ }++ const first = routes.reconcile(nowMs).operation!;+ expect(first).toMatchObject({+ childPeerId: A,+ reason: "direct-convergence",+ });+ const firstAttempt = beginCandidate(routes, {+ nowMs: nowMs + 1,+ connectionId: "a_background_direct",+ reservation: { kind: "direct" },+ }).operation!;+ expect(routes.candidateFailed({+ childPeerId: A,+ childSessionId: `${A}_session`,+ revision: firstAttempt.current!.revision,+ connectionId: "a_background_direct",+ }, nowMs + 2).accepted).toBe(true);+ expect(routes.reconcile(nowMs + 3).operation).toMatchObject({+ childPeerId: D,+ reason: "direct-convergence",});});@@ -842,10 +1039,18 @@ describe("RoomRouteController", () => {physicalActive: true,resource: "b_subscription",});+ addViewer(routes, C, 0);+ routes.hydrateEdge(C, peerEdge(HOST, "c_from_host"));addViewer(routes, A, 0, 0);- routes.reconcile(0);- const sfu = beginCandidate(routes, {+ const acquisition = routes.reconcile(0).operation!;+ beginCandidate(routes, {nowMs: 1,+ connectionId: "a_direct_head_start",+ reservation: { kind: "direct" },+ });+ routes.operationExpired(acquisition.wakeAtMs);+ const sfu = beginCandidate(routes, {+ nowMs: acquisition.wakeAtMs + 1,connectionId: "a_sfu",reservation: { kind: "sfu-reuse", edge: "a_subscription" },}).operation!;@@ -854,39 +1059,44 @@ describe("RoomRouteController", () => {childSessionId: `${A}_session`,revision: sfu.current!.revision,connectionId: "a_sfu",- }, 2);- expect(routes.reconcile(3).operation?.reason).toBe("direct-convergence");+ }, acquisition.wakeAtMs + 2);+ expect(+ routes.reconcile(acquisition.wakeAtMs + 3).operation?.reason,+ ).toBe("direct-convergence");beginCandidate(routes, {- nowMs: 4,+ nowMs: acquisition.wakeAtMs + 4,connectionId: "a_direct_pending",reservation: { kind: "direct", overlap: "a_overlap" },});- const released = routes.upsertParticipant({- peerId: C,- role: "viewer",- sessionId: `${C}_session`,- effectiveDownstreamCapacity: 0,- }, 5);- expect(released).toEqual(["a_overlap"]);- expect(routes.snapshot().operation).toBeUndefined();+ const activeRevision = routes.snapshot().revision;+ expect(routes.invalidateEdge({+ childPeerId: C,+ childSessionId: `${C}_session`,+ parentSessionId: "host_session",+ routeRevision: activeRevision,+ connectionId: "c_from_host",+ }, acquisition.wakeAtMs + 5)).toBe(true);+ const reconciled = routes.reconcile(acquisition.wakeAtMs + 6);+ expect(reconciled.released).toEqual(["a_overlap"]);expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({kind: "sfu",connectionId: "a_sfu",});- expect(routes.reconcile(6).operation).toMatchObject({+ expect(reconciled.operation).toMatchObject({childPeerId: C,- reason: "join",+ reason: "edge-unavailable",});});- it("reserves a stage for Host-full SFU bootstrap before it is a tuple", () => {+ it("owns Host-full SFU bootstrap failure by the waiting demand", () => {const routes = controller(2, { sfuEnabled: true });addViewer(routes, B, 2);routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));addViewer(routes, C, 0);routes.hydrateEdge(C, peerEdge(HOST, "c_from_host"));addViewer(routes, A, 0);+ addViewer(routes, D, 0);const operation = routes.reconcile(0).operation!;expect(operation.candidates.some((candidate) => candidate.tuple.kind === "sfu"))@@ -905,13 +1115,221 @@ describe("RoomRouteController", () => {const bootstrap = routes.reconcile(operation.wakeAtMs + 1).operation!;expect(bootstrap.childPeerId).toBe(C);+ expect(bootstrap.demandPeerId).toBe(A);expect(bootstrap.candidates[0]!.tuple).toMatchObject({kind: "sfu",publication: "create",});+ expect(bootstrap.candidates[0]!.endpointTransition.kind).toBe("overlap");+ const firstCarrier = beginCandidate(routes, {+ nowMs: operation.wakeAtMs + 2,+ connectionId: "c_bootstrap_sfu",+ publicationGeneration: "c_bootstrap_publication",+ publicationConnectionId: "c_bootstrap_ingress",+ reservation: {+ kind: "sfu-create",+ edge: "c_bootstrap_subscription",+ publication: "c_bootstrap_publication_resource",+ overlap: "c_bootstrap_overlap",+ },+ }).operation!;+ expect(routes.candidateFailed({+ childPeerId: C,+ childSessionId: `${C}_session`,+ revision: firstCarrier.current!.revision,+ connectionId: "c_bootstrap_sfu",+ }, operation.wakeAtMs + 3).exhausted).toBe(false);+ expect(routes.snapshot().upstreamByViewer.get(C)).toMatchObject({+ connectionId: "c_from_host",+ usable: true,+ physicalActive: true,+ });++ const secondBootstrap = routes.reconcile(operation.wakeAtMs + 4).operation!;+ expect(secondBootstrap).toMatchObject({+ childPeerId: B,+ demandPeerId: A,+ reason: "sfu-bootstrap",+ });+ const secondCarrier = beginCandidate(routes, {+ nowMs: operation.wakeAtMs + 5,+ connectionId: "b_bootstrap_sfu",+ publicationGeneration: "b_bootstrap_publication",+ publicationConnectionId: "b_bootstrap_ingress",+ reservation: {+ kind: "sfu-create",+ edge: "b_bootstrap_subscription",+ publication: "b_bootstrap_publication_resource",+ overlap: "b_bootstrap_overlap",+ },+ }).operation!;+ expect(routes.candidateFailed({+ childPeerId: B,+ childSessionId: `${B}_session`,+ revision: secondCarrier.current!.revision,+ connectionId: "b_bootstrap_sfu",+ }, operation.wakeAtMs + 6).exhausted).toBe(true);+ for (const [peerId, connectionId] of [+ [B, "b_from_host"],+ [C, "c_from_host"],+ ] as const) {+ expect(routes.snapshot().upstreamByViewer.get(peerId)).toMatchObject({+ connectionId,+ usable: true,+ physicalActive: true,+ });+ }+ const nextDemand = routes.reconcile(operation.wakeAtMs + 7).operation!;+ expect(nextDemand).toMatchObject({ childPeerId: D, reason: "join" });+ beginCandidate(routes, {+ nowMs: operation.wakeAtMs + 8,+ connectionId: "d_direct",+ reservation: { kind: "direct" },+ });+ expect(routes.operationExpired(nextDemand.deadlineAtMs).exhausted).toBe(true);+ expect(routes.reconcile(nextDemand.deadlineAtMs + 1).operation).toBeUndefined();+ });++ it("abandons bootstrap when a Host slot becomes available", () => {+ const routes = controller(2, { sfuEnabled: true });+ expect(routes.setEffectiveCapacity(HOST, "host_session", 1)).toBe(true);+ addViewer(routes, B, 0);+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));+ addViewer(routes, A, 0);++ const bootstrap = routes.reconcile(0).operation!;+ expect(bootstrap).toMatchObject({+ childPeerId: B,+ demandPeerId: A,+ reason: "sfu-bootstrap",+ });+ const prepared = beginCandidate(routes, {+ nowMs: 1,+ connectionId: "stale_bootstrap",+ publicationGeneration: "stale_publication",+ publicationConnectionId: "stale_ingress",+ reservation: {+ kind: "sfu-create",+ edge: "stale_subscription",+ publication: "stale_publication_resource",+ overlap: "stale_overlap",+ },+ }).operation!;++ expect(routes.setEffectiveCapacity(HOST, "host_session", 2)).toBe(true);+ const stale = routes.candidateReady({+ childPeerId: B,+ childSessionId: `${B}_session`,+ revision: prepared.current!.revision,+ connectionId: "stale_bootstrap",+ }, 2);+ expect(stale.accepted).toBe(false);+ expect(stale.released).toEqual(expect.arrayContaining([+ "stale_subscription",+ "stale_publication_resource",+ "stale_overlap",+ ]));+ expect(routes.snapshot().upstreamByViewer.get(B)).toMatchObject({+ connectionId: "b_from_host",+ usable: true,+ physicalActive: true,+ });+ expect(routes.reconcile(3).operation).toMatchObject({+ childPeerId: A,+ demandPeerId: A,+ reason: "join",+ });+ });++ it("tries SFU first after bootstrap and retains the direct suffix", () => {+ const routes = controller(2, { sfuEnabled: true });+ for (const [peerId, connectionId] of [+ [B, "b_from_host"],+ [C, "c_from_host"],+ ] as const) {+ addViewer(routes, peerId, 1);+ routes.hydrateEdge(peerId, peerEdge(HOST, connectionId));+ }+ addViewer(routes, A, 0);++ const acquisition = routes.reconcile(0).operation!;+ beginCandidate(routes, {+ nowMs: 1,+ connectionId: "a_direct_head_start",+ reservation: { kind: "direct" },+ });+ routes.operationExpired(acquisition.wakeAtMs);+ const bootstrap = routes.reconcile(acquisition.wakeAtMs + 1).operation!;+ const carrier = beginCandidate(routes, {+ nowMs: acquisition.wakeAtMs + 2,+ connectionId: "bootstrap_sfu",+ publicationGeneration: "bootstrap_publication",+ publicationConnectionId: "bootstrap_ingress",+ reservation: {+ kind: "sfu-create",+ edge: "carrier_subscription",+ publication: "bootstrap_publication_resource",+ overlap: "bootstrap_overlap",+ },+ }).operation!;+ expect(routes.candidateReady({+ childPeerId: bootstrap.childPeerId,+ childSessionId: bootstrap.childSessionId,+ revision: carrier.current!.revision,+ connectionId: "bootstrap_sfu",+ }, acquisition.wakeAtMs + 3).accepted).toBe(true);++ const demand = routes.reconcile(acquisition.wakeAtMs + 4).operation!;+ expect(demand).toMatchObject({+ childPeerId: A,+ demandPeerId: A,+ reason: "join",+ });+ expect(demand.candidates[0]?.tuple).toEqual({+ kind: "sfu",+ publication: "reuse",+ });+ expect(+ demand.candidates.slice(1).every((candidate) => candidate.tuple.kind === "peer"),+ ).toBe(true);+ const subscription = beginCandidate(routes, {+ nowMs: acquisition.wakeAtMs + 5,+ connectionId: "a_sfu",+ reservation: { kind: "sfu-reuse", edge: "a_subscription" },+ }).operation!;+ expect(routes.candidateFailed({+ childPeerId: A,+ childSessionId: `${A}_session`,+ revision: subscription.current!.revision,+ connectionId: "a_sfu",+ }, acquisition.wakeAtMs + 6).accepted).toBe(true);+ expect(+ routes.snapshot().operation?.candidates[+ routes.snapshot().operation!.cursor+ ]?.tuple.kind,+ ).toBe("peer");+ const direct = beginCandidate(routes, {+ nowMs: acquisition.wakeAtMs + 7,+ connectionId: "a_deferred_direct",+ reservation: { kind: "direct" },+ }).operation!;+ expect(routes.candidateReady({+ childPeerId: A,+ childSessionId: `${A}_session`,+ revision: direct.current!.revision,+ connectionId: "a_deferred_direct",+ }, acquisition.wakeAtMs + 8).accepted).toBe(true);+ expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({+ kind: "peer",+ connectionId: "a_deferred_direct",+ });+ expect(routes.reconcile(acquisition.wakeAtMs + 9).operation).toMatchObject({+ childPeerId: bootstrap.childPeerId,+ reason: "direct-convergence",+ });});- it("retains another exact failed edge while one child operation is busy", () => {+ it("replans when the current candidate parent fails", () => {const routes = controller(3);addViewer(routes, A, 1);addViewer(routes, B, 1);@@ -935,13 +1353,21 @@ describe("RoomRouteController", () => {connectionId: "a_new",reservation: { kind: "direct" },}).operation!;+ const currentTuple = current.current!.tuple;+ expect(currentTuple.kind).toBe("peer");+ const failedParentPeerId = currentTuple.kind === "peer"+ ? currentTuple.parentPeerId+ : B;+ const failedParentConnectionId = failedParentPeerId === B+ ? "b_old"+ : "c_old";expect(routes.invalidateEdge({- childPeerId: B,- childSessionId: `${B}_session`,+ childPeerId: failedParentPeerId,+ childSessionId: `${failedParentPeerId}_session`,parentSessionId: "host_session",routeRevision: revision,- connectionId: "b_old",+ connectionId: failedParentConnectionId,}),).toBe(true);expect(@@ -965,7 +1391,43 @@ describe("RoomRouteController", () => {connectionId: "a_new_2",}, 3).accepted,).toBe(true);- expect(routes.reconcile(3).operation?.childPeerId).toBe(B);+ expect(routes.reconcile(3).operation?.childPeerId).toBe(+ failedParentPeerId,+ );+ });++ it("keeps an active candidate when an unrelated session is replaced", () => {+ const routes = controller(2);+ for (const [peerId, connectionId] of [+ [B, "b_from_host"],+ [C, "c_from_host"],+ ] as const) {+ addViewer(routes, peerId, 1);+ routes.hydrateEdge(peerId, peerEdge(HOST, connectionId));+ }+ addViewer(routes, A, 0);+ const operation = routes.reconcile(0).operation!;+ const active = beginCandidate(routes, {+ nowMs: 1,+ connectionId: "a_active_candidate",+ reservation: { kind: "direct" },+ }).operation!;+ const tuple = active.current!.tuple;+ expect(tuple.kind).toBe("peer");+ const unrelatedPeerId = tuple.kind === "peer" && tuple.parentPeerId === B+ ? C+ : B;++ expect(routes.upsertParticipant({+ peerId: unrelatedPeerId,+ role: "viewer",+ sessionId: `${unrelatedPeerId}_replacement`,+ effectiveDownstreamCapacity: 1,+ }, 2)).toEqual([]);+ expect(routes.snapshot().operation?.current).toMatchObject({+ revision: operation.baseRevision + 1,+ connectionId: "a_active_candidate",+ });});it("uses a freed Host slot for new demand without moving healthy descendants", () => {@@ -1079,11 +1541,18 @@ describe("RoomRouteController", () => {});const operation = routes.reconcile(0).operation!;expect(operation.candidates[0]?.tuple).toEqual({- kind: "sfu",- publication: "reuse",+ kind: "peer",+ parentPeerId: A,+ transport: "direct",});beginCandidate(routes, {nowMs: 1,+ connectionId: "b_direct_head_start",+ reservation: { kind: "direct" },+ });+ routes.operationExpired(operation.wakeAtMs);+ beginCandidate(routes, {+ nowMs: operation.wakeAtMs + 1,connectionId: "b_candidate",reservation: { kind: "sfu-reuse", edge: "b_subscription" },});@@ -1533,7 +2002,7 @@ describe("RoomRouteController", () => {});});- it("appends one ordinary restore candidate after a healthy bounded gap", () => {+ it("fails all waiting demands without cutting capacity-three Host children", () => {const routes = controller(3, { sfuEnabled: true });for (const [peerId, connectionId] of [[A, "a_direct"],@@ -1544,17 +2013,21 @@ describe("RoomRouteController", () => {routes.hydrateEdge(peerId, peerEdge(HOST, connectionId));}addViewer(routes, D, 0);- const operation = routes.reconcile(0).operation!;- expect(operation.childPeerId).toBe(C);- expect(operation.candidates[0]?.endpointTransition.kind).toBe("bounded-gap");- const gap = routes.retireCurrentCandidateProducer(cursorGuard(operation), 1);- expect(gap.accepted).toBe(true);- const tuples = routes.snapshot().operation?.candidates.map((plan) => plan.tuple);- expect(tuples?.at(-1)).toEqual({- kind: "peer",- parentPeerId: HOST,- transport: "direct",- });+ addViewer(routes, E, 0);+ const reconciled = routes.reconcile(0);+ expect(reconciled.operation).toBeUndefined();+ expect(reconciled.failedPeerIds).toEqual([D, E]);+ for (const [peerId, connectionId] of [+ [A, "a_direct"],+ [B, "b_direct"],+ [C, "c_direct"],+ ] as const) {+ expect(routes.snapshot().upstreamByViewer.get(peerId)).toMatchObject({+ connectionId,+ usable: true,+ physicalActive: true,+ });+ }});it("does not promote when synchronous admission commit fails", () => {diff --git a/tests/server-signal.test.ts b/tests/server-signal.test.tsindex 12350f66..455a0a3b 100644--- a/tests/server-signal.test.ts+++ b/tests/server-signal.test.ts@@ -704,6 +704,13 @@ describe("WebSocket signaling", () => {throw new Error(`route error: ${error.message}`);}),]);+ viewer.socket.send(+ JSON.stringify({+ type: "route-transport-connected",+ revision: prepared.revision,+ connectionId: prepared.candidate.connectionId,+ }),+ );viewer.socket.send(JSON.stringify({type: "route-ready",