Skip to content

armgit / Piik

Public Imported from GitHub
0

Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。

fix(web): show current connection truth [skip ci]

AAAef36543d6e9a
diff --git a/docs/project-memory.md b/docs/project-memory.md
index e63efcef..4134dc64 100644
--- a/docs/project-memory.md
+++ b/docs/project-memory.md
@@ -32,7 +32,7 @@ Last updated: 2026-08-21
- Flagship media is UDP; HTTPS/WSS stays TLS/TCP; the old release remains rollback-only.
- Treat settings as ceilings and degradation as unclassified. Use correlated Host A+B/Viewer C and one-variable evidence; never force AV1, infer by UA, or create a composite score.
- Web window/system-audio requests are browser hints; tracks use `music`. P2P/relay/SFU senders request 128,000 bit/s and SFU disables DTX; this is a ceiling, not a quality/stereo guarantee. Native Win11 process audio stays source-only; one Viewer got 495 Opus packets.
-- Presence reports exact active upstream and feeds Host topology; it does not prove media. Details may label assigned P2P/SFU before media proof and show TURN only for an actual relay; status stays pending without local/current evidence. Web Host names stay socket/localStorage-only; Native remains outside the boundary.
+- Presence reports exact active upstream and feeds Host topology; it does not prove media. Status and details stay neutral until local/current media evidence, then label P2P/SFU and actual TURN; append its protocol only from local relay stats. Web Host names stay socket/localStorage-only; Native remains outside the boundary.
- Do not add scene detection, dynamic-FPS control, or forced AV1 without negotiation, encode, game, CPU/GPU, and sender evidence.
- ADR-0002 grant/public access, the v3 room-password migration, and Web Host display names are deployed. Names/presence remain session-only without account or roster tables.
@@ -44,7 +44,7 @@ Last updated: 2026-08-21
- The repository is one npm package using Node.js 24, React, TypeScript, Vite, native WebRTC, `ws`, Zod, Vitest, and separate coturn.
- Production is exact `691863e1720ebbee1b5368f29e94f05b3710ccf8`; artifact 605,904 bytes/SHA-256 `7e751c0bf7c97bc7d23edb1e37441fb6c55d90a0cd80647b778fdb5b1ee28bae`; cutover 3,376.021 ms lock/669.678 ms stop-health/604.174 ms switch-health; rollbacks `6634cb9`, `ecc794d`, `16f6eab`.
-- Web keeps one SFU stream, clears unavailable video, shows authoritative pending/P2P/SFU and actual-only TURN, labels paused preview, and drops signals to a grace-retained offline current-edge target. Shared entry/nickname UI is live; Native remains source-only.
+- Web keeps one SFU stream, clears unavailable video, shows evidence-backed P2P/SFU and actual-only TURN, labels paused preview, and drops signals to a grace-retained offline current-edge target. Shared entry/nickname UI is live; Native remains source-only.
- Web relay is cap2 with one upstream; child3 rejects and no UA/visibility split exists.
- Four services are active/running at `NRestarts=0`; local/public health are 200. SQLite v3 has five rooms, SHA-256 `aef724ae52c4107be8ec8791e72f8dcaa11b0ec849fb432d022e2cfb9cfe0974`, owner/mode `screener:screener`/0600.
- Production keeps ordinary ICE STUN-only, SFU roots <=2, selected-edge UDP TTL 120, and one pending/answered `peer-selected` attempt per room excluding Host ingress. This rollout ran no browser/media/SFU/TURN/performance canary; earlier exact-`16f6eab` evidence proves active Host ingress only.
diff --git a/docs/research/webrtc-p2p-screen-sharing.md b/docs/research/webrtc-p2p-screen-sharing.md
index 3b01bc01..b5f7c344 100644
--- a/docs/research/webrtc-p2p-screen-sharing.md
+++ b/docs/research/webrtc-p2p-screen-sharing.md
@@ -318,7 +318,7 @@ WebRTC 媒体本身使用 DTLS-SRTP 加密,但 direct P2P 仍可能让这组
- `qualityLimitationReason` 和各原因累计时长
- jitter buffer delay、decode time 和 total packet send delay
-`RTCIceCandidateStats.protocol` 表示 ICE candidate 的 UDP/TCP;只有本地 relay candidate 的 `relayProtocol` 才表示本端到 TURN 的 UDP/TCP/TLS。规范要求远端 candidate 不暴露 `relayProtocol`,所以本端只能确认远端使用 relay,不能从 `remoteCandidate.protocol` 推断其 TURN 传输。首版分别展示 ICE protocol 与本地 TURN protocol,不为补齐远端字段扩展信令或遥测。
+`RTCIceCandidateStats.protocol` 是内部候选传输字段;只有本地 relay candidate 的 `relayProtocol` 才能确认本端到 TURN 的实际传输。规范不向远端暴露 `relayProtocol`,所以不能从 `remoteCandidate.protocol` 推断远端 TURN 传输。当前详情以 `P2P`/`SFU fallback` 表示媒体方式,直连只显示实际 `protocol`,relay 先显示 `TURN`,仅本地 relay 再附加 `/UDP` 等实际值;candidate type 单列为候选路径,不为补齐远端字段扩展信令或遥测。
WebRTC 标准没有承诺固定毫秒延迟。工程目标必须带网络条件,并使用画面时间码或高速摄像机测量玻璃到玻璃延迟。60 fps 的单帧周期是 16.7 ms,端到端延迟还包含采集等待、编码、单程网络、jitter buffer、解码和显示。
diff --git a/docs/status.md b/docs/status.md
index fc75ac5d..4a4ee00a 100644
--- a/docs/status.md
+++ b/docs/status.md
@@ -7,7 +7,7 @@ Last updated: 2026-08-21
Production at `https://share.bonfire.icu` is exact `691863e1720ebbee1b5368f29e94f05b3710ccf8`; artifact 605,904 bytes, SHA-256 `7e751c0bf7c97bc7d23edb1e37441fb6c55d90a0cd80647b778fdb5b1ee28bae`.
Cutover: 3,376.021 ms lock/669.678 ms stop-health/604.174 ms switch-health. SQLite v3/five rooms has SHA-256 `aef724ae52c4107be8ec8791e72f8dcaa11b0ec849fb432d022e2cfb9cfe0974`, owner/mode `screener:screener`/0600. Four services are active/running at `NRestarts=0`; rollbacks are `6634cb9`, then `ecc794d` and `16f6eab`.
Ordinary ICE is STUN-only; limits are SFU roots <=2, one `peer-selected` attempt excluding Host ingress, and selected UDP TTL 120. This rollout ran no browser/media/SFU/TURN/performance canary; earlier exact-`16f6eab` Host-ingress proof remains separate.
-Stable SFU stream/unavailable state, authoritative pending/P2P/SFU and actual-only TURN are deployed with Host preview notice, entry/nickname UI and Web relay cap2. Native is source-only; Web defaults VP8.
+Stable SFU stream/unavailable state, evidence-backed pending/P2P/SFU and actual-only TURN are in source with Host preview notice, entry/nickname UI and Web relay cap2. Native is source-only; Web defaults VP8.
## Execution Principle
@@ -17,7 +17,7 @@ Flagship; parallel; min run/smoke/rollback; benchmark later. Active UI/config/lo
- Capture precedes room creation; source/quality changes and AV pause preserve peers. Recommended profiles and advanced defaults use `balanced`; clarity/fluid remain explicit. The browser chooses degradation; readback/stats report actual behavior.
- Production access is `screener-v2`: a valid private fragment grant enters directly; every code-only Viewer must first hold site access, after which public-watch accepts the code and private rooms still require their room password. `SITE_ACCESS_PASSWORD`, `/api/site-access`, and the site-access cookie are deployed atomically; raw credentials are never stored.
-- Production UI uses adjacent nickname editing, distinct site/room prompts, and a shared room-code form. Exact upstream may label green P2P/yellow `SFU fallback` before media proof; connected status still needs evidence and TURN stays actual-only.
+- Source UI uses adjacent nickname editing, distinct site/room prompts, and a shared room-code form. Status and details stay neutral before media proof; current evidence labels green P2P/yellow `SFU fallback`, while relay evidence adds `TURN` plus only a locally observed protocol.
- Native v2 is source-only (memory rooms, 300s reclaim); it follows authenticated direct-child assignments up to two and fails unsupported SFU/selected ingress boundedly.
- Production is roots <=2/Web relay <=2; every Web Viewer keeps one upstream and bounded sticky recovery, while child3 is rejected. Room `1` is historical; HTTPS/WSS is TLS/TCP.
- After an answer, a generation-bound 15s initial-connect deadline enters ICE restart; success/replacement/disposal cancels it. It is deployed but not mobile-verified.
diff --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 85d8ef04..28b29978 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"
@@ -100,7 +100,7 @@ rotate、revoke 或从 public-watch 切回 private-link 都是当前 Viewer 的
Web Host 在 `authenticate` 中显式发送 `viewerPresence: true` capability,Viewer 也可显式订阅同一 participant snapshot;Native sender 不发送,因此继续只收到原有 exact server wire。两端可在 `authenticate.displayName` 发送名称,并以 `set-display-name` 更新当前会话。服务端只向已订阅的 Web participant 发送完整 `viewer-presence` snapshot,列表严格来自当前带 sessionId 的在线参与者,不含五秒媒体恢复 grace 成员;条目用 `role` discriminator 区分 Host/Viewer。加入、离线、会话替换、改名和 active route 改变都会重发快照;该只读广播不调用 connect/reconcile,也不建立任何媒体边。Host 的“在线”Viewer 总数只取 Viewer 条目数;最多两条本机媒体快照只补充当前以 Host 为 active upstream 的连接指标。
-每个 presence 条目包含 `role`、`peerId`、`displayName` 和服务端 active assignment 的精确 `upstream`:Host 为 `none`,Viewer 为 `none | peer(peerId) | sfu`。UI 始终展示名称加 peerId 尾部至少六字符短后缀;碰撞时逐字符有界延长至完整 peerId。卡片状态只依据本机连接或当前 Viewer 接收证据显示“已连接”,否则保持中性的“线路分配中”或具体连接状态;active assignment 本身不是连接成功证据。连接详情按 authoritative assignment/controller route 显示媒体徽标,即使媒体仍在连接:`P2P` 为绿色图标,`SFU fallback` 为黄色图标,且仅在本机真实 selected relay 时另附 `TURN`。独立拓扑按钮从同一 snapshot 展示 Host、实际存在的 SFU 节点及精确上下游,不从客户端媒体快照推断。peerId 不因此成为授权身份或路由输入;名称、presence 与拓扑视图不改变授权、媒体或路由状态机。
+每个 presence 条目包含 `role`、`peerId`、`displayName` 和服务端 active assignment 的精确 `upstream`:Host 为 `none`,Viewer 为 `none | peer(peerId) | sfu`。UI 始终展示名称加 peerId 尾部至少六字符短后缀;碰撞时逐字符有界延长至完整 peerId。卡片状态只依据本机连接或当前 Viewer 接收证据显示“已连接”,否则保持中性的“线路分配中”或具体连接状态;active assignment 本身不是连接成功证据。连接详情同样等待当前媒体证据,再显示绿色 `P2P` 或黄色 `SFU fallback`;实际 relay 另附 `TURN`,本地 relay protocol 可见时才显示 `TURN/UDP` 等实际值。独立拓扑按钮可从 authoritative assignment snapshot 展示 Host、实际存在的 SFU 节点及精确上下游,但不把计划线路当作连接成功。peerId 不因此成为授权身份或路由输入;名称、presence 与拓扑视图不改变授权、媒体或路由状态机。
## 信令协议
@@ -313,7 +313,7 @@ hop 按[低服务器成本媒体路由](./research/low-server-media-routes.md)
- `/r/{code}` 观看者:private room 首次解析合法 fragment grant 后立即清理地址栏并直达;仅有 code 时先通过 site access,再按 public/private policy 进入。鉴权后主区域最大化远端视频,标题旁显示可复制的紧凑房间号,顶部保留连接状态,并提供本地音量、静音、全屏和重试控制。
- 移动端:视频保持稳定宽高比,控制与状态移到视频下方,任何文字和按钮不得溢出或遮挡。
-两端后续默认显示紧凑在线 roster;Host 与 Viewer 的本机显示名在界面中统一标为“昵称”,默认只读,铅笔按钮紧贴昵称并只切换当前控件的输入、保存和取消,展示仍为名称加 room-scoped `peerId` 短后缀。一个不持久化的“显示连接详情”复选框按页展开信令、ICE/TURN、浏览器实际暴露的本地/远端候选地址、codec、RTT、RTP 丢包率、编解码耗时及逐边统计;真实连接失败、音频缺失、持续画质受限和需要用户动作的告警始终可见。显示名/roster 不进入 access credential 或 SQLite。
+两端后续默认显示紧凑在线 roster;Host 与 Viewer 的本机显示名在界面中统一标为“昵称”,默认只读,铅笔按钮紧贴昵称并只切换当前控件的输入、保存和取消,展示仍为名称加 room-scoped `peerId` 短后缀。一个不持久化的“显示连接详情”复选框按页展开媒体方式、传输协议、候选路径、浏览器实际暴露的本地/远端候选地址、codec、RTT、RTP 丢包率、编解码耗时及逐边统计;真实连接失败、音频缺失、持续画质受限和需要用户动作的告警始终可见。显示名/roster 不进入 access credential 或 SQLite。
用户可见的非直播状态只使用“已停止分享”(分享端已结束当前发布)、“等待开始分享”(观看端等待发布)、“正在连接”与“正在恢复连接”。`room-closed` 显示“房间已关闭”或“房间已过期”,不得误写成“分享已结束”。房间寿命、媒体代次、换父和恢复等内部状态不得作为额外产品文案暴露。
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 bd21adf5..c78067bc 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"
@@ -32,7 +32,7 @@
- [ ] 路径级质量状态:应用的 `HIGH`/`FALLBACK` 非对称窗口只决定拓扑资格和诊断,不命令正常的媒体层切换,也不计算综合分数。SFU BWE downshift 先进入 `suspect`;多个连续窗口的 sender/viewer 关联证据确认 `FALLBACK` 后,应用不得稳定保留该 parent,并把 downstream capacity 降为 0。计划或显式质量 fallback 仅是内建路径失败后的候选:已有 children 时先在 connection/assignment generation guard 下全部迁走,失败或代次过期则保持原 assignment/quality。Autonomous downshift 无法 packet-level 预先迁移,default-on 前必须验收 descendants 的短暂影响。只有更长的稳定恢复窗口和 cooldown 后才能重新声明 relay capacity。Viewer 请求必须鉴权、限频、去重,并由 sender 的 GCC/Transport-CC、实际码率、RTT、丢包、重传、编码限制、协商 codec/profile/parameters 与 viewer 解码、丢帧、冻结证据交叉验证;不能仅凭自报生效,也不得上传 raw SDP、candidate 地址或原始设备/网络标识。
- [ ] 断线恢复:临时网络变化时按不同层级做一次性恢复,而不是把同一动作机械重复三次。`failed` 边先做一次 ICE restart,再重建一次同 parent 的 `RTCPeerConnection`,随后尝试一个不同的合格 peer parent;只有 peer 路径耗尽才进入 SFU。`connecting`/`checking` 先显示不改变拓扑的慢连接状态,硬超时必须由真实移动网络证据确定,不能为了更快使用服务器而过早放弃最终可成功的 P2P。任一步恢复即停止后续动作;所有异步结果受 session、route revision、assignment/connection generation 约束。active SFU 只允许一次 fresh-token 重试,再失败即有界回到 peer baseline 或明确失败,并向 Host 显示不含 URL、地址、token 或原始错误的失败阶段。
- [ ] 可观测性:按目标 RTP transport 与不透明连接/ICE 代次关联 selected path、`iceGatheringState`/ICE/connection state、事件推导的建立时长、generation-baselined pair-change delta,以及 RTT、RTP 丢包率、抖动、码率、帧率、编码耗时和受限原因。候选与错误的 wire、日志和导出只使用[低服务器成本媒体路由](./research/low-server-media-routes.md)的脱敏字段和 code bucket,禁止 raw SDP、candidate、地址、URL、`errorText` 或网络标识。只有创建该 `RTCPeerConnection` 的本机可在折叠详情中显示浏览器对 selected local/remote candidate 实际暴露的地址与端口;该值不上传、不持久化、不用于地理/NAT 推断,缺失或被隐私保护时显示未知。
-- [ ] 渐进式诊断:分享者和观看者默认只看到房间、画面、核心状态和常用控制;Host 的 Viewer 卡片只把本机连接或当前接收证据称为“已连接”,其余状态保持中性的“线路分配中”或具体连接状态,不把 active assignment 当作连接成功。展开连接详情可按 authoritative assignment/controller route 显示媒体方式,即使媒体仍在连接:`P2P` 使用绿色与直观图标,`SFU` 使用黄色的 `SFU fallback`;实际 selected relay 时才另标 `TURN`。Host/Peer 上下游仍只在独立的权威拓扑视图中展示。候选路径、RTT、视频/音频 RTP 区间丢包率、实际编解码器、音频区间码率/jitter 和视频编码耗时等技术详情由一个明确的“显示连接详情”开关展开。音频 codec MIME、RTP clock、channels 与 fmtp 只能来自当前 RTP 对象引用的 `RTCCodecStats`,缺失即未知;`opus/48000/2` 不得写成 48 kHz 音源或实际立体声。隐藏诊断不能隐藏失败原因、音频缺失、持续画质受限或需要用户操作的告警。
+- [ ] 渐进式诊断:分享者和观看者默认只看到房间、画面、核心状态和常用控制;Host 的 Viewer 卡片只把本机连接或当前接收证据称为“已连接”,其余状态保持中性的“线路分配中”或具体连接状态,不把 active assignment 当作连接成功。展开连接详情也只在当前媒体证据成立后显示媒体方式:`P2P` 使用绿色与直观图标,`SFU` 使用黄色的 `SFU fallback`;实际 relay 时另标 `TURN`,只有本地 relay protocol 可见时才附加 `/UDP` 等实际值。尚未连接时不预告 P2P、SFU 或未知 ICE,只保留中性状态。Host/Peer 上下游仍只在独立的权威拓扑视图中展示。传输协议、候选路径、RTT、视频/音频 RTP 区间丢包率、实际编解码器、音频区间码率/jitter 和视频编码耗时等技术详情由一个明确的“显示连接详情”开关展开。音频 codec MIME、RTP clock、channels 与 fmtp 只能来自当前 RTP 对象引用的 `RTCCodecStats`,缺失即未知;`opus/48000/2` 不得写成 48 kHz 音源或实际立体声。隐藏诊断不能隐藏失败原因、音频缺失、持续画质受限或需要用户操作的告警。
- [ ] 站点访问:生产部署必须配置独立的 `SITE_ACCESS_PASSWORD` 控制建房、Host 信令角色和所有 code-only Viewer 入口;只有本地开发/测试可显式关闭。非空值接受 8 至 128 个可见 ASCII bytes,不能复用 TURN、LiveKit、TLS 或其他部署 secret。`POST /api/site-access` 验证成功签发 12 小时、无服务端会话状态的 HttpOnly、`SameSite=Strict` site-access cookie。有效 room-scoped fragment grant 可绕过站点 gate 直接进入对应房间;其余 `/r/{code}`、`/join` 和 public-watch 必须先持有效站点 cookie,之后才检查房间 public/private policy 和房间密码。失败统一且不得泄露房间是否存在或 policy;建房 HTTP 只认该 cookie。已移除的旧环境变量、endpoint 和 cookie 不保留兼容。不引入账号、JWT、服务端 session Map 或通用 logout。
- [ ] 房间级观看授权:新房间默认生成含 256-bit 随机量、限时且可撤销的 room-scoped Viewer grant;服务端只保存完整 grant 的 SHA-256 摘要。到期阻止以后鉴权/重连,但不为已鉴权 Viewer 设置踢出定时器;即时清退使用 rotate/revoke。浏览器从 URL fragment 严格读取 grant 后,只写该房间的 `sessionStorage` 并立即用 `history.replaceState` 清除 fragment;刷新和页面内重连可继续。私密房间缺失 grant 时必须先通过站点访问,再提供正确房间观看密码;任一缺失都 fail closed。grant 不得进入 `localStorage`、cookie、query、WebSocket URL、Referrer、日志或错误。Host 可 rotate 或 revoke;revoke 只锁定 grant 路径,已配置的房间密码仍是独立的后续进入方式。新 grant 摘要成功提交后必须清除 Viewer grace/路由、终止旧授权代次的信令和媒体并断开全部旧 Viewer,数据库写失败则不得改变连接。public-watch 是显式、可逆的 room policy,只放宽房间级观看,不绕过站点访问。
- [ ] 最小持久化:`ROOM_DATABASE_PATH` 可选且必须与 `SITE_ACCESS_PASSWORD` 同时配置。两者都存在时,SQLite 只持久保存从 `1` 开始自增的房间 ID、Host token 摘要、nullable Viewer grant 摘要,以及 nullable 48-byte Viewer-password material(16-byte salt + 32-byte scrypt verifier);数据库 `CHECK` 约束非空 BLOB 长度,不新增用户、成员或 session 表。明文房间密码只短暂存在于当前页面和鉴权/派生调用内存,不进入 URL、cookie、浏览器持久存储、日志或 SQLite。持久房间停止后仍显示等待状态;私密邀请按期限或 Host rotate 更新。旧 schema 行在原子迁移时必须 fail-closed 为没有可用明文 grant 的锁定私密状态,Host rotate 后才能生成新邀请。
diff --git a/src/client/components/StatsGrid.tsx b/src/client/components/StatsGrid.tsx
index ebee2b0c..2ec40d2c 100644
--- a/src/client/components/StatsGrid.tsx
+++ b/src/client/components/StatsGrid.tsx
@@ -85,7 +85,7 @@ export function StatsGrid({
}
/>
<Metric
- label="ICE 传输"
+ label="传输协议"
value={metrics.iceProtocol?.toUpperCase() ?? "未知"}
/>
{metrics.localCandidateType === "relay" && (
@@ -95,7 +95,7 @@ export function StatsGrid({
/>
)}
<Metric
- label="候选"
+ label="候选路径"
value={`${metrics.localCandidateType ?? "?"} / ${metrics.remoteCandidateType ?? "?"}`}
title="本地 / 远端候选类型"
/>
diff --git a/src/client/components/StatusBadge.tsx b/src/client/components/StatusBadge.tsx
index 72748288..d3e4c20a 100644
--- a/src/client/components/StatusBadge.tsx
+++ b/src/client/components/StatusBadge.tsx
@@ -1,9 +1,13 @@
import { CircleAlert, Network, Radio, Server, Wifi, WifiOff } from "lucide-react";
import type {
- MediaPath,
+ ConnectionMetrics,
SignalConnectionState,
} from "../types";
-import { MEDIA_ROUTE_PRESENTATION, ROUTING_STATUS_PRESENTATION } from "./status-badge-model";
+import {
+ MEDIA_ROUTE_PRESENTATION,
+ mediaTransportPresentation,
+ ROUTING_STATUS_PRESENTATION,
+} from "./status-badge-model";
interface BadgeProps {
tone: "good" | "warning" | "danger" | "neutral";
@@ -56,27 +60,28 @@ export function PeerStatusBadge({
return <Badge {...labels[state]} />;
}
-export function PathBadge({ path }: { path: MediaPath }) {
- if (path === "direct") {
+export function PathBadge({ metrics }: { metrics: ConnectionMetrics }) {
+ const presentation = mediaTransportPresentation(metrics);
+ if (metrics.path === "direct") {
return (
- <span className="path-badge path-direct" title="ICE 直连成功">
+ <span className="path-badge path-direct" title={presentation.title}>
<Wifi size={14} aria-hidden="true" />
- ICE 直连
+ {presentation.label}
</span>
);
}
- if (path === "relay") {
+ if (metrics.path === "relay") {
return (
- <span className="path-badge path-relay" title="此连接正在使用 TURN 中继">
+ <span className="path-badge path-relay" title={presentation.title}>
<Radio size={14} aria-hidden="true" />
- TURN 传输
+ {presentation.label}
</span>
);
}
return (
- <span className="path-badge path-unknown" title="尚未选出可用的 ICE 路径">
+ <span className="path-badge path-unknown" title={presentation.title}>
<WifiOff size={14} aria-hidden="true" />
- ICE 未知
+ {presentation.label}
</span>
);
}
diff --git a/src/client/components/status-badge-model.ts b/src/client/components/status-badge-model.ts
index 25748b4d..46df396c 100644
--- a/src/client/components/status-badge-model.ts
+++ b/src/client/components/status-badge-model.ts
@@ -9,6 +9,43 @@ export const ROUTING_STATUS_PRESENTATION = { tone: "neutral", label: "线路分
export type PresentedMediaRoute = keyof typeof MEDIA_ROUTE_PRESENTATION;
+export function mediaTransportPresentation(
+ metrics: Pick<
+ ConnectionMetrics,
+ "path" | "iceProtocol" | "localCandidateType" | "localRelayProtocol"
+ >,
+): { label: string; title: string } {
+ if (metrics.path === "direct") {
+ const protocol = metrics.iceProtocol?.toUpperCase() ?? null;
+ return {
+ label: protocol ?? "直连",
+ title: protocol ? `此连接使用直连 ${protocol}` : "此连接使用直连传输",
+ };
+ }
+ if (metrics.path === "relay") {
+ const protocol =
+ metrics.localCandidateType === "relay"
+ ? (metrics.localRelayProtocol?.toUpperCase() ?? null)
+ : null;
+ return {
+ label: protocol ? `TURN/${protocol}` : "TURN",
+ title: protocol
+ ? `此连接正在使用 TURN/${protocol} 中继`
+ : "此连接正在使用 TURN 中继;远端中继协议不可见",
+ };
+ }
+ return { label: "传输未确定", title: "尚未选出可用的传输路径" };
+}
+
+export function hasPeerRouteEvidence(
+ peer: PeerSnapshot | null | undefined,
+): boolean {
+ return Boolean(
+ peer &&
+ (peer.connectionState === "connected" || peer.metrics.path !== "unknown"),
+ );
+}
+
export function viewerRouteEvidence(
upstream: ParticipantRouteAssignment["upstream"] | null,
peer: PeerSnapshot | null,
@@ -26,17 +63,21 @@ export function viewerRouteEvidence(
if (!upstream) {
return sfu
? { route: "sfu", evidence: sfu }
- : peer
+ : hasPeerRouteEvidence(peer)
? { route: "p2p", evidence: peer }
: { route: null, evidence: null };
}
if (upstream.kind === "sfu") {
- return { route: "sfu", evidence: sfu };
+ return sfu
+ ? { route: "sfu", evidence: sfu }
+ : { route: null, evidence: null };
}
if (upstream.kind === "peer") {
+ const matchingPeer = peer?.peerId === upstream.peerId ? peer : null;
+ const hasMatchingPeerEvidence = hasPeerRouteEvidence(matchingPeer);
return {
- route: "p2p",
- evidence: peer?.peerId === upstream.peerId ? peer : null,
+ route: hasMatchingPeerEvidence ? "p2p" : null,
+ evidence: hasMatchingPeerEvidence ? matchingPeer : null,
};
}
return { route: null, evidence: null };
diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsx
index 6364336f..66cde1a8 100644
--- a/src/client/pages/HostPage.tsx
+++ b/src/client/pages/HostPage.tsx
@@ -45,6 +45,7 @@ import {
} from "../components/StatusBadge";
import { StatsGrid } from "../components/StatsGrid";
import { TopologyView } from "../components/TopologyView";
+import { hasPeerRouteEvidence } from "../components/status-badge-model";
import { ApiError, createRoom } from "../lib/api";
import { createOpaqueId } from "../lib/opaque-id";
import {
@@ -2095,12 +2096,16 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
? peerSnapshots.get(viewer.peerId)
: undefined;
const qualityEvidence = viewerQualityEvidence.get(viewer.peerId);
- const hasCurrentMediaEvidence =
+ const hasCurrentQualityEvidence =
+ viewer.upstream.kind === "peer" &&
+ qualityEvidence?.parentPeerId === viewer.upstream.peerId;
+ const hasCurrentRouteEvidence =
+ hasPeerRouteEvidence(snapshot) || hasCurrentQualityEvidence;
+ const hasCurrentConnectionEvidence =
snapshot?.connectionState === "connected" ||
- (viewer.upstream.kind === "peer" &&
- qualityEvidence?.parentPeerId === viewer.upstream.peerId);
+ hasCurrentQualityEvidence;
const viewerState =
- hasCurrentMediaEvidence
+ hasCurrentConnectionEvidence
? "connected"
: (snapshot?.connectionState ?? "routing");
return (
@@ -2111,26 +2116,30 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
<PeerStatusBadge state={viewerState} />
</div>
</div>
- {showConnectionDetails && viewer.upstream.kind !== "none" && (
+ {showConnectionDetails &&
+ hasCurrentRouteEvidence &&
+ viewer.upstream.kind !== "none" && (
<div className="viewer-transport-heading">
<MediaRouteBadge
route={viewer.upstream.kind === "peer" ? "p2p" : "sfu"}
/>
{snapshot?.metrics.path === "relay" && (
- <PathBadge path="relay" />
+ <PathBadge metrics={snapshot.metrics} />
)}
</div>
)}
- {showConnectionDetails && snapshot && (
- <>
+ {showConnectionDetails &&
+ snapshot &&
+ hasPeerRouteEvidence(snapshot) && (
<StatsGrid
metrics={snapshot.metrics}
direction="send"
senderParameters={snapshot.senderParameters}
/>
- </>
- )}
- {showConnectionDetails && qualityEvidence && (
+ )}
+ {showConnectionDetails &&
+ qualityEvidence &&
+ hasCurrentQualityEvidence && (
<>
<p className="section-meta">观看端接收</p>
<StatsGrid
diff --git a/src/client/pages/ViewerPage.tsx b/src/client/pages/ViewerPage.tsx
index 689f1328..9300be7c 100644
--- a/src/client/pages/ViewerPage.tsx
+++ b/src/client/pages/ViewerPage.tsx
@@ -1176,7 +1176,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
<>
<MediaRouteBadge route={routePresentation.route} />
{routeMetrics?.path === "relay" && (
- <PathBadge path="relay" />
+ <PathBadge metrics={routeMetrics} />
)}
</>
)}
@@ -1362,7 +1362,7 @@ export function ViewerPage({ roomId, viewerGrant }: ViewerPageProps) {
<div className="viewer-transport-heading">
<MediaRouteBadge route={routePresentation.route} />
{routeMetrics?.path === "relay" && (
- <PathBadge path="relay" />
+ <PathBadge metrics={routeMetrics} />
)}
</div>
{routeMetrics && (
diff --git a/src/client/webrtc/host-peer.ts b/src/client/webrtc/host-peer.ts
index d52f90da..91be489c 100644
--- a/src/client/webrtc/host-peer.ts
+++ b/src/client/webrtc/host-peer.ts
@@ -264,7 +264,7 @@ export class HostPeer {
iceServers: iceConfig.iceServers,
});
} catch (error) {
- this.setError(error, "更新 ICE 配置失败");
+ this.setError(error, "更新网络配置失败");
}
}
diff --git a/src/client/webrtc/viewer-peer.ts b/src/client/webrtc/viewer-peer.ts
index b387d2a0..abae1608 100644
--- a/src/client/webrtc/viewer-peer.ts
+++ b/src/client/webrtc/viewer-peer.ts
@@ -182,7 +182,7 @@ export class ViewerPeer {
iceServers: iceConfig.iceServers,
});
} catch (error) {
- this.setError(error, "更新 ICE 配置失败");
+ this.setError(error, "更新网络配置失败");
}
}
diff --git a/tests/status-badge.test.ts b/tests/status-badge.test.ts
index e00e9dd5..50ddf264 100644
--- a/tests/status-badge.test.ts
+++ b/tests/status-badge.test.ts
@@ -1,7 +1,9 @@
import { describe, expect, it } from "vitest";
import {
+ hasPeerRouteEvidence,
MEDIA_ROUTE_PRESENTATION,
+ mediaTransportPresentation,
ROUTING_STATUS_PRESENTATION,
viewerRouteEvidence,
} from "../src/client/components/status-badge-model.ts";
@@ -26,19 +28,19 @@ describe("route status badges", () => {
});
});
- it("shows an assigned route before current media evidence", () => {
+ it("keeps an assigned route neutral before current media evidence", () => {
expect(ROUTING_STATUS_PRESENTATION).toEqual({
tone: "neutral", label: "线路分配中",
});
expect(viewerRouteEvidence({ kind: "sfu" }, null, null)).toEqual({
- route: "sfu",
+ route: null,
evidence: null,
});
});
it("uses evidence only when it matches the authoritative upstream", () => {
expect(viewerRouteEvidence({ kind: "sfu" }, peerSnapshot, null)).toEqual({
- route: "sfu",
+ route: null,
evidence: null,
});
expect(
@@ -47,7 +49,37 @@ describe("route status badges", () => {
peerSnapshot,
null,
),
- ).toEqual({ route: "p2p", evidence: null });
+ ).toEqual({ route: null, evidence: null });
+
+ const sfu = { connectionState: "connected" as const, metrics: null };
+ expect(viewerRouteEvidence({ kind: "sfu" }, null, sfu)).toEqual({
+ route: "sfu",
+ evidence: sfu,
+ });
+ });
+
+ it("requires a connected peer or an observed selected path", () => {
+ const connecting = {
+ ...peerSnapshot,
+ connectionState: "connecting" as const,
+ metrics: { ...EMPTY_METRICS, path: "unknown" as const },
+ };
+ expect(hasPeerRouteEvidence(connecting)).toBe(false);
+ expect(
+ viewerRouteEvidence(
+ { kind: "peer", peerId: "host-peer" },
+ connecting,
+ null,
+ ),
+ ).toEqual({ route: null, evidence: null });
+
+ expect(
+ viewerRouteEvidence(
+ { kind: "peer", peerId: "host-peer" },
+ { ...connecting, metrics: { ...EMPTY_METRICS, path: "direct" } },
+ null,
+ ).route,
+ ).toBe("p2p");
});
it("exposes TURN only from current assigned-edge evidence", () => {
@@ -63,4 +95,37 @@ describe("route status badges", () => {
).evidence?.metrics?.path,
).toBe("relay");
});
+
+ it("states a TURN protocol only from local relay evidence", () => {
+ expect(
+ mediaTransportPresentation({
+ ...EMPTY_METRICS,
+ path: "relay",
+ localCandidateType: "relay",
+ localRelayProtocol: "udp",
+ }).label,
+ ).toBe("TURN/UDP");
+ expect(
+ mediaTransportPresentation({
+ ...EMPTY_METRICS,
+ path: "relay",
+ localCandidateType: "relay",
+ localRelayProtocol: "tls",
+ }).label,
+ ).toBe("TURN/TLS");
+ expect(
+ mediaTransportPresentation({
+ ...EMPTY_METRICS,
+ path: "relay",
+ localCandidateType: "host",
+ }).label,
+ ).toBe("TURN");
+ expect(
+ mediaTransportPresentation({
+ ...EMPTY_METRICS,
+ path: "direct",
+ iceProtocol: "udp",
+ }).label,
+ ).toBe("UDP");
+ });
});