fix: keep voice diagnostics scoped to current media

This commit is contained in:
illusia committed 2026-10-01 15:03:58 +08:00
1 parent 5855d0ba67
commit c16d1d4cfb
10 files changed
+532 -220

No files matched your search

+7
View File
@@ -32,6 +32,7 @@ WebSpeak connects browser users to TeamSpeak 3 and TeamSpeak 6 through a self-ho
| `web/src/voice/microphone-meter.ts` | Optional per-peer level sampling, owned analysis nodes and timer, partial-failure cleanup and stale-tick rejection |
| `web/src/voice/webrtc-transport.ts`, `webrtc-playback.ts` | Per-attempt peer negotiation, input/meter ownership, compatibility fallback and independently owned playback elements and retries |
| `web/src/voice/connection.ts`, `commands.ts` | Cancellable ticket acquisition, socket and connection generations, plus per-command acknowledgement deadlines and cleanup |
| `web/src/voice/audio-diagnostics.ts`, `web/src/composables/useWebClientPerformance.ts` | Session-owned diagnostic probes and compatibility counters, browser statistics, comparable sample scopes and cancellable UI polling |
| `web/src/platform/` | Browser mounting and cancellable Android gateway readiness handshake |
| `web/src/services/`, `web/src/i18n/`, `web/src/skins/` | Browser persistence, identity import, skin packages and translations |
| `web/src/services/admin-api.ts`, `admin-requests.ts` | Admin HTTP validation and cancellation, session-bound CSRF and per-feature request ownership, including skin uploads and backup downloads |
@@ -72,6 +73,10 @@ Every acknowledged command owns its original socket, connection generation and d
Audio diagnostic probes retain their cancellation entry and deadline until both gateway and browser statistics finish. Bind the result to the original socket, connection generation and peer; disconnect settles pending consumers immediately, and a late browser getStats result cannot mix with a replacement peer. A probe send failure returns no sample.
Diagnostic samples also include the WebRTC transport generation, so a probe cannot survive a failed attempt that starts and ends without a peer. A browser-local scope ID changes with the source and session resets; compatibility counters reset at session teardown and snapshots stay independent. The scope ID is internal metadata, not part of the gateway protocol. Keep the exported diagnostic types available from the voice composable for existing callers.
The performance panel only subtracts counters from matching scopes, transports and downlink sources (PCM, RTP or gateway frames). Null or rejected probes clear stale activity and restart the baseline. Check the polling generation before starting work as well as after awaiting results; unmount retires callbacks and manual refresh. Preserve the 2-second polling interval. For loss estimates, packetsSent already includes all sent packets, while packetsReceived requires adding lost packets to form the denominator; keep percentages bounded and treat RTCP/local snapshots as estimates.
Accompaniment changes keep the WebRTC sender output alive. Prepare and connect the new source before replacing the old one; a failure preserves the current microphone and accompaniment. The input mixer owns its nodes and output track, never the externally owned capture streams. Release partial allocations and continue cleanup if an individual node fails. Application audio bypasses microphone gain/denoising and retains its source level.
The accompaniment controller owns both active and pending captures. Stop, disconnect and replacement immediately release candidates already returned by the browser, even while optional constraints are pending. Late permissions are stopped on arrival; ended or stale candidates cannot be published. Register ended listeners during preparation and publish activity only after attachment succeeds. Optional content hints and processing constraints may fail without losing capture; distinguish audio attachment errors from permission errors in all five languages.
@@ -137,6 +142,8 @@ npm run verify
`npm run verify` runs unit tests, the backend build and `npm run web:build`. The latter delegates to the frontend build, including `vue-tsc --noEmit`. Use `npm run dev` and `npm run web:dev` for development, or `npm start` after building both applications.
Headless Vue tests use Vite middleware mode with both HMR and the WebSocket listener disabled (`hmr: false`, `ws: false`). Disabling HMR alone still reserves Vite's default socket port and causes parallel test processes to conflict.
CI verifies pushes to `dev` and `master`, pull requests and manual runs. Docker publication on `master` or release tags, and release packaging on tags or manual runs, call the same verification workflow before publishing or packaging. Verification includes the application checks and a Docker HTTP health smoke test; that smoke test does not prove voice or screen-sharing functionality.
Tests requiring a real TeamSpeak server, browser media devices or Android hardware must document their environment and outcome separately. Never substitute a mock codec or an HTTP health response for a successful audio test.
+39 -16
View File
@@ -1,17 +1,17 @@
# WebSpeak 代码待修改清单与修改方向
本文聚焦 `webspeak-webclient`,整理代码结构、待修改问题、大致修改方向、优先级和验收条件。前端 WebRTC 传输与播放、连接控制和命令等待已提取;命令发送异常清理、凭证请求取消与超时等问题已修复,当前通过 300 项测试及前后端构建。
本文聚焦 `webspeak-webclient`,整理代码结构、待修改问题、大致修改方向、优先级和验收条件。前端媒体、连接、命令和诊断采样已分离;统计跨来源混算、旧轮询及失败后残留展示等问题已修复,当前通过 313 项测试及前后端构建。
后续继续整理入口中的诊断与消息状态边界,并拆分页面组件。真实 TeamSpeak、Android 真机与发布包检查独立验收,不能由模拟边界测试或构建通过推定完成。前轮只记录的整理结果保留在文中;本批为其后的实施与验证。
后续继续整理入口中的消息状态边界,并拆分页面组件。真实 TeamSpeak、Android 真机与发布包检查独立验收,不能由模拟边界测试或构建通过推定完成。前轮只记录的整理结果及各批实施记录保留在文中。
## 范围与依据
- 记录日期:2026 年 10 月 1 日。
- 本批起始提交:`dev` 分支,`44f2b7d875034ea77f986bf8ff16a0a1c5319601`;应用版本 `0.2.5-preview`。本批接续已有 WebRTC 工作区改动及只读整理文档。
- 已有的传输、播放与诊断修改纳入当前验证;另新增连接与命令模块,保留原页面调用接口和共享消息契约。
- 本批起始提交:`dev` 分支,`6700466ec95636d33f42aad1adbb0c0312905779`;应用版本 `0.2.5-preview`。诊断批次开始时工作区干净。
- 新增诊断采样模块及实际 Vue 诊断面板状态测试,保留原页面调用接口、类型导出和共享消息契约。
- 依据为源码、回归测试、依赖清单、CI 与发布工作流,以及本地验证输出;本批未连接真实 TeamSpeak、操作媒体设备或运行 Android。
- 根目录测试命令显式列出 34 个测试文件,均存在。接续的 WebRTC 与诊断修改增加 13 项用例,本批连接与命令再增加 13 项;`npm run verify` 通过 300 项测试、后端编译、前端类型检查和生产构建。
- 起始提交 `44f2b7d` 的 [CI 与 Docker 检查](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36823894967) 本批重新查询确认成功;当前新增修改的远端验证按对应提交另行核对。
- 根目录测试命令显式列出 35 个测试文件,均存在。本批新增 13 项用例并增强 1 项已有统计断言;`npm run verify` 通过 313 项测试、后端编译、前端类型检查和生产构建。
- 起始提交 `6700466` 的 [CI 与 Docker 检查](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/actions/runs/36826815347) 本批查询确认成功;当前新增修改的远端验证按对应提交另行核对。
- 下文“代码可确认”指控制流或配置可直接支持的判断;具体故障发生条件仍需回归用例验证。“待验收”表示证据尚缺,不等于已发生故障。P1/P2/P3 表示建议实施顺序,不代表安全漏洞等级。
## 当前代码结构
@@ -24,9 +24,10 @@
| SDK 与媒体 | `ts-client.ts`、`teamspeak-adapter.ts`、`webrtc-audio.ts`、`opus-codec.ts` | SDK 连接及事件适配、WebRTC 混音、平台编解码 |
| 共享契约 | `src/shared/` | 命令、服务端消息、WebRTC、屏幕共享、皮肤和管理请求与响应;后续复用现有模型 |
| 管理与持久化 | `src/admin/`、`src/security/`、`src/persistence/` | 登录、配置、邀请、审计、访问策略与 SQLite |
| 前端语音入口 | `web/src/composables/useVoiceWebSocket.ts` | 1,664 行;保留媒体组装、页面状态及业务动作,已委托 WebRTC、连接和命令资源管理 |
| 浏览器媒体模块 | `web/src/voice/` | 已有屏幕共享、远端播放、麦克风采集、录音测试、输出设备切换、伴奏、输入混音及电平监测;新增 WebRTC 传输 193 行、播放 114 行 |
| 前端语音入口 | `web/src/composables/useVoiceWebSocket.ts` | 1,519 行;保留媒体组装、页面状态及业务动作,已委托 WebRTC、连接、命令与诊断资源管理 |
| 浏览器媒体模块 | `web/src/voice/` | 已有屏幕共享、远端播放、麦克风采集、录音测试、输出设备切换、伴奏、输入混音及电平监测;WebRTC 传输 194 行、播放 114 行 |
| 浏览器连接与命令 | `web/src/voice/connection.ts`、`commands.ts` | 连接模块 132 行,拥有请求取消、期限、socket 与代次;命令模块 59 行,拥有确认等待及统一收尾 |
| 浏览器诊断 | `web/src/voice/audio-diagnostics.ts`、`web/src/composables/useWebClientPerformance.ts` | 采样模块 168 行,拥有等待、来源范围与兼容计数;面板 composable 管理轮询和可比样本的展示 |
| 页面与业务状态 | `web/src/views/`、`web/src/composables/` | 主页面 1,211 行,管理页 400 行;已有业务 composable,模板和部分界面逻辑仍集中 |
| 前端基础服务 | `web/src/services/`、`web/src/i18n/`、`web/src/skins/` | 请求、浏览器存储、身份导入、主题、皮肤及多语言 |
| Android | `web/src/platform/`、`src/mobile/`、`mobile/`、`web/android/` | 本机网关就绪握手、移动打包和原生容器;运行时与设备验收独立 |
@@ -38,16 +39,17 @@
## 事项状态与剩余待办
沿用原清单编号。04-E、04-F、04-G 保留既有验证记录;04-H、04-I 已经实施并通过故障回归。结构拆分和真实环境验收分别跟踪。
沿用原清单编号。04-E 至 04-I 保留既有验证记录;04-J 为本批诊断问题的修复与验证。结构拆分和真实环境验收分别跟踪。
| 编号 | 优先级 | 待办及依据 | 大致修改方向 | 完成条件 |
| --- | --- | --- | --- | --- |
| 04-E | 已修复,本地通过 | 伴奏切换失败曾结束旧发送轨道、丢失旧伴奏及遗留候选节点 | 稳定输出轨道,候选伴奏源接入成功后替换旧源;异常路径释放候选 | 回归已验证旧轨道与采集保留、停止无需分配新输出、部分创建失败释放及关闭容错 |
| 04-F | 已修复,本地通过 | 停止曾等待约束结束才释放候选;准备期间结束的采集仍被激活 | 控制器同时拥有候选与当前流,提前注册结束监听并复核音轨状态 | 停止、断开、替换立即释放候选;已结束和过期采集不会发布活动状态 |
| 04-G | 已修复,本地通过 | 电平监测部分创建失败曾遗留节点,旧计时器会读新分析器,释放异常会中断清理 | 监测实例独立拥有节点、定时器及失效状态;失败仅停止监测 | 分配、连接、读取与释放异常和旧计时器回归通过;语音链保持有效 |
| 04-D | P2,主要传输边界已提取 | WebRTC、连接与命令已独立;入口仍保留诊断和较大的消息状态分支 | 继续核对诊断与状态投影边界,保留页面接口及共享响应式数据 | 旧回调不影响新会话;断开释放资源;投影与展示行为保持一致 |
| 04-D | P2,主要资源边界已提取 | 媒体、连接、命令与诊断已独立;入口仍保留较大的消息状态分支 | 继续核对状态投影边界,保留页面接口及共享响应式数据 | 旧回调不影响新会话;断开释放资源;投影与展示行为保持一致 |
| 04-H | 已修复,本地通过 | 发送抛错曾遗留等待登记与计时器 | 统一命令成功、失败、超时与断开处理,绑定原 socket 和连接代次 | 发送异常立即清理;确认、拒绝、超时、断开和旧回复回归通过 |
| 04-I | 已修复,本地通过 | 凭证请求曾缺少主动取消和期限;socket 关闭异常会中断页面清理 | 连接拥有取消器和 15 秒期限;先使旧操作失效,再独立清理 socket | 请求及响应体挂起、取消、替换、旧期限和关闭异常回归通过;五语提示明确 |
| 04-J | 已修复,本地通过 | 不同来源计数相减产生虚假速率;旧轮询、采样失败和重连可留下错误展示;上行丢包分母重复计入丢失数 | 采样携带本地范围标识,展示只比较同来源数据;失败重建基线,轮询先校验代次;修正上行分母 | 传输与 peer 替换、统计缺失、旧轮询、卸载、重连和丢包率回归通过 |
| 06-C | P2 | 主页面和管理页已有业务模块,模板仍集中 | 先拆稳定界面区域,页面保留连接或认证编排 | 表单、路由、五语、主题、皮肤接口、键盘与窄屏布局保持一致 |
| 03 | P2 | 共享契约已落地,真实收发与旧客户端兼容仍缺验收证据 | 用脱敏的实际消息样本核对字段、默认值、非法输入及兼容范围 | 两端解析一致;非法消息受控处理,不误丢有效事件 |
| 02-C | P2 | 本机与边界替身测试不能证明真实媒体链路 | 建立真实 TeamSpeak 双向语音、WebRTC 回退、伴奏和多用户验收步骤 | 记录版本、浏览器、网络、设备、步骤及实际结果 |
@@ -76,7 +78,17 @@
[webrtc-transport.ts](<USER_HOME>/Desktop/othercode/teamspeakclient4web/webspeak-webclient/web/src/voice/webrtc-transport.ts) 已集中 peer、输入混音、电平监测、ICE 等待、answer 期限和兼容回退;[webrtc-playback.ts](<USER_HOME>/Desktop/othercode/teamspeakclient4web/webspeak-webclient/web/src/voice/webrtc-playback.ts) 已集中播放元素、播放中的 Promise 和用户手势重试监听。原始麦克风和 PCM 由采集层管理,控制 socket 由连接模块管理,入口负责组装。
诊断请求保留等待期限直至网关和浏览器统计均返回,并检查原 socket、连接代次与 peer;断开立即结束消费者等待。清理异常、旧播放重试、旧协商期限、回退信令失败、统计挂起、替换 peer 和诊断发送失败均已纳入 [voice-session.test.mjs](<USER_HOME>/Desktop/othercode/teamspeakclient4web/webspeak-webclient/web/test/voice-session.test.mjs),当前全部通过。此处验证浏览器边界行为,不等同于真实网络媒体验收。
诊断请求现由采样模块管理,保留等待期限直至网关和浏览器统计均返回,并检查原 socket、连接与传输代次和 peer;断开立即结束消费者等待。清理异常、旧播放重试、旧协商期限、回退信令失败、统计挂起、替换 peer 和诊断发送失败均已纳入 [voice-session.test.mjs](<USER_HOME>/Desktop/othercode/teamspeakclient4web/webspeak-webclient/web/test/voice-session.test.mjs),当前全部通过。此处验证浏览器边界行为,不等同于真实网络媒体验收。
### 04-J 诊断采样与展示只比较同一来源
当前实现:[audio-diagnostics.ts](<USER_HOME>/Desktop/othercode/teamspeakclient4web/webspeak-webclient/web/src/voice/audio-diagnostics.ts) 与 [useWebClientPerformance.ts](<USER_HOME>/Desktop/othercode/teamspeakclient4web/webspeak-webclient/web/src/composables/useWebClientPerformance.ts)。原面板直接相减前后样本中的下行计数,来源可能分别为 RTP 包、兼容音频帧或网关发送帧。peer 替换后新计数若大于旧值,也会被误当成同一流的增长。采样失败时保留旧活动状态,已排队的旧轮询会设置运行标志却无法清除;卸载后手动刷新仍能发起请求。
已实施:采样模块拥有等待登记、总期限、兼容计数和浏览器统计。样本携带仅用于浏览器内部的 `scopeId`,不修改网关协议;连接或传输变化以及会话释放会使范围失效。兼容计数随会话重置,旧快照保持独立。面板只比较相同范围、传输和下行计数来源;缺失或拒绝的采样清除旧状态,下一样本重新建立基线。轮询开始前与结果返回后均校验代次,卸载同时禁止旧回调和手动刷新。
[W3C WebRTC 统计定义](https://www.w3.org/TR/webrtc-stats/#dom-rtcsentrtpstreamstats-packetssent) 将 `packetsSent` 定义为已发送包总数。据此,上行丢包估算分母使用发送数,不再重复加上丢失数;下行仍以接收数加丢失数计算。浏览器提供的 `fractionLost` 用于采样中的上行百分比,否则按计数估算。RTCP 反馈和本地计数采样时间可能不同,不能将该估算表述为精确网络测量。
已验证:10 项实际 Vue 状态用例,其中 8 项先失败后通过;语音会话新增 3 项范围与重连用例并增强 1 项丢包率断言,均先失败后通过。保留每 2 秒轮询、采样总期限和已有音频状态提示。并行运行时发现 Vite 即使关闭 HMR 仍监听默认 WebSocket 端口,三个无界面测试入口现同时设置 `ws: false`,无需占用该端口。
## 近期修复的浏览器媒体问题
@@ -121,7 +133,7 @@
### 04-D 前端媒体与连接编排
[useVoiceWebSocket.ts](<USER_HOME>/Desktop/othercode/teamspeakclient4web/webspeak-webclient/web/src/composables/useVoiceWebSocket.ts) 保留为页面调用入口。媒体、连接与命令资源已交由各自模块管理,后续关注诊断和消息投影,避免重复持有响应式数据。
[useVoiceWebSocket.ts](<USER_HOME>/Desktop/othercode/teamspeakclient4web/webspeak-webclient/web/src/composables/useVoiceWebSocket.ts) 保留为页面调用入口。媒体、连接、命令与诊断资源已交由各自模块管理,后续关注消息投影,避免重复持有响应式数据。
| 建议边界 | 应拥有的状态与资源 | 重点约束 |
| --- | --- | --- |
@@ -131,7 +143,8 @@
| WebRTC 传输与播放,已提取 | PeerConnection、offer/answer、ICE 等待、播放元素和协商计时器 | 旧 peer 无法写回;失败恢复兼容 PCM;关闭完整释放 |
| 连接控制,已提取 | WebSocket、加入凭证请求、取消器与连接代次;通过回调更新页面状态 | 旧 socket 消息不写回;取消、超时和失败语义明确 |
| 命令等待,已提取 | 请求标识、待确认登记、期限和结束函数 | 结束幂等;发送失败和断开立即释放 |
| 诊断与状态投影,后续评估 | 统计等待、成员与频道事件、聊天与提示映射 | 先稳定传输边界;只在状态归属清楚时提取,不复制响应式状态 |
| 诊断采样,已提取 | 统计等待、兼容计数、浏览器统计和样本范围 | 只组合当前来源数据;失败与会话释放清除等待;范围不进入网关协议 |
| 状态投影,后续评估 | 成员与频道事件、聊天与提示映射 | 只在状态归属清楚时提取,不复制响应式状态 |
一次提取一个边界,具体文件名在实施时确定。保留 `releaseSessionResources` 作为会话统一释放入口,模块只释放自身拥有的资源,避免多个模块共同修改大型状态对象。
@@ -167,7 +180,7 @@ Android 记录具体设备和系统,验收连接、双向语音、输入输出
| --- | --- |
| 05-A 服务端会话音频 | `SessionAudioTransport` 已接入 PCM、WebRTC 和 TeamSpeak 下行,统一路由、背压与统计 |
| 05-B、05-C WebRTC 关闭 | 已逐项容错释放资源,重复关闭共享完成 Promise,包括失败结果 |
| 02-B 测试入口遗漏 | WebRTC 关闭测试已进入统一命令;当前 34 个列出的测试文件均存在 |
| 02-B 测试入口遗漏 | WebRTC 关闭与诊断面板测试已进入统一命令;当前 35 个列出的测试文件均存在 |
| 05-D SDK 事件与目录 | `SessionEventCoordinator` 已提取;旧 SDK 来源、关闭等待、重连等待及踢出到达顺序已有实现和回归记录 |
| 成员头像 | 下载控制器与 SDK 异步阶段均绑定连接代次;批次、缓存、监听及迟到结果有生命周期限制 |
| 前端基础整理 | 共享消息契约、管理请求与三个状态模块、五语管理文案、头部组件及路由延迟加载已实现 |
@@ -189,8 +202,9 @@ Android 记录具体设备和系统,验收连接、双向语音、输入输出
| --- | --- | --- |
| 已完成,本地通过 | 04-E、04-F:伴奏连续性、失败清理与候选取消 | 12 项断言先失败后通过,统一验证通过;真实媒体另验收 |
| 已完成,本地通过 | 04-G:电平监测异常与旧回调 | 6 项新增用例、274 项全量测试及前后端构建通过 |
| 已完成,本地通过 | WebRTC 与诊断、04-H 和 04-I:连接与命令 | 统一验证通过 300 项测试及前后端构建;对应提交另核对 CI |
| 接下来 | 04-D:诊断与消息投影边界核对 | 保留共享状态与页面接口,继续使用迟到事件和断开生命周期回归 |
| 已完成,本地与 CI 通过 | WebRTC 与诊断、04-H 和 04-I:连接与命令 | 统一验证通过 300 项测试及前后端构建;`6700466` 的 CI 与 Docker 检查已确认成功 |
| 已完成,本地通过 | 04-J:诊断采样与展示 | 统一验证通过 313 项测试及前后端构建;35 个显式测试文件 |
| 接下来 | 04-D:消息投影边界核对 | 保留共享状态与页面接口,继续使用迟到事件和断开生命周期回归 |
| 随后 | 06-C、03:页面组件及契约兼容核对 | 组件行为、草稿、路由、主题、皮肤、五语及真实消息样本验证 |
| 独立安排 | 02-C、07-A:真实 TeamSpeak 与 Android | 环境、版本、设备、网络、操作步骤和实际结果逐项留档,可提前安排 |
| 发布前 | 09-A:各平台干净构建与产物验收 | 从声明输入构建并实际启动;HTTP、真实媒体和平台能力分别记录 |
@@ -399,3 +413,12 @@ Android 记录具体设备和系统,验收连接、双向语音、输入输出
- 增加 13 项测试,其中 7 项故障回归和 1 项新提示缺失检查先失败后通过。另验证命令确认与错误码、旧期限、请求字段及五语超时提示。旧音频事件用例改为执行已捕获的回调,继续覆盖监听解绑后的迟到执行。
- `npm run verify` 通过 300 项测试、后端编译、前端类型检查和生产构建;显式入口仍包含 34 个测试文件。起始提交 `44f2b7d` 的 CI 与 Docker 检查已重新确认成功,本批远端结果按新提交核对。
- 本批未完成真实 TeamSpeak 双向语音、Android 真机或跨平台发布验收;诊断与状态投影、页面组件仍有后续工作,完整目标继续进行。
### 诊断采样与面板状态实施记录
- 起始提交 `6700466` 的 CI、Docker 构建和 HTTP 健康检查已查询确认成功。
- 提取 `audio-diagnostics.ts`,集中统计等待、期限、来源范围和兼容播放计数;原有诊断类型通过语音入口继续导出,入口降至 1,519 行。
- 样本比较增加范围与来源检查,修复跨传输、跨 peer 和浏览器统计缺失时的虚假速率。采样捕获 WebRTC 代次,开始于 peer 分配前的旧探测不能跨越失败回退。
- 面板采样失败清除旧活动状态,下一次成功重新建立基线;旧轮询、卸载后的回调与手动刷新不再开启请求或遗留运行标志。会话恢复重置兼容计数且不修改旧快照。
- 修正上行丢包率分母;新增 13 项测试并增强 1 项已有断言,其中 12 项新增或增强用例先失败后通过。三个 Vue 测试入口禁用 Vite WebSocket 监听,消除并行测试端口竞争。
- 统一入口增加到 35 个测试文件,`npm run verify` 通过 313 项测试、后端编译、前端类型检查和生产构建。真实 TeamSpeak、Android 真机及发布包仍未验收,状态投影和页面组件继续跟踪。
+1 -1
View File
@@ -11,7 +11,7 @@
"scripts": {
"dev": "tsx src/index.ts",
"build": "tsc",
"test": "node --import tsx --test src/admin/skin-registry.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/audio-stats.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/screen-share.test.ts web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-pack.test.ts web/src/services/identity-import.test.ts",
"test": "node --import tsx --test src/admin/skin-registry.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/audio-stats.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-pack.test.ts web/src/services/identity-import.test.ts",
"verify": "npm test && npm run build && npm run web:build",
"start": "node dist/index.js",
"web:dev": "cd web && npx vite --host",
+30 -175
View File
@@ -7,13 +7,15 @@ import { createAccompaniment, type AccompanimentErrorCode } from "../voice/accom
import { createWebRtcTransport } from "../voice/webrtc-transport.js";
import { createVoiceConnection } from "../voice/connection.js";
import { createVoiceCommands } from "../voice/commands.js";
import { createAudioDiagnostics, type AudioPermission, type VoiceAudioStatusSample } from "../voice/audio-diagnostics.js";
export type { AudioPermission, BrowserVoiceAudioStats, VoiceAudioStatusSample } from "../voice/audio-diagnostics.js";
import type { SinkAudioElement } from "../voice/webrtc-playback.js";
import { createScreenShareController } from "../voice/screen-share.js";
export type { ScreenShareOutputSettings, ScreenShareCaptureStats, ScreenSharePeerStats, ScreenShareWebRtcStats } from "../voice/screen-share.js";
import { parseServerMessage } from "../../../src/shared/server-messages.js";
import type { ClientCommandPayloads, ClientCommandType } from "../../../src/shared/client-commands.js";
export type { ScreenShareStreamDescription as ScreenShareStream, ScreenShareViewerDescription as ScreenShareViewer, ScreenSharePeerSignal as ScreenShareSignal } from "../../../src/shared/screen-share.js";
import type { ChannelMember, ChannelInfo, ChatMessage, ServerEvent, VoiceAudioBridgeStats } from "../../../src/shared/voice-models.js";
import type { ChannelMember, ChannelInfo, ChatMessage, ServerEvent } from "../../../src/shared/voice-models.js";
export type { ChannelMember, ChannelInfo, ChatMessage, ServerEvent, VoiceAudioBridgeStats } from "../../../src/shared/voice-models.js";
import { reactive, ref, shallowRef } from "vue";
import { loadLocalPreferences, saveLocalPreferences } from "../services/local-persistence.js";
@@ -51,39 +53,10 @@ export interface AudioOutputDevice {
groupId: string;
}
export type AudioPermission = "unknown" | "granted" | "denied";
type SinkAudioContext = AudioContext & {
setSinkId?: (sinkId: string) => Promise<void>;
};
export interface BrowserVoiceAudioStats {
outboundBytes: number | null;
outboundPackets: number | null;
outboundPacketsLost: number | null;
outboundLossPercent: number | null;
outboundRttMs: number | null;
inboundBytes: number | null;
inboundPackets: number | null;
inboundPacketsLost: number | null;
inboundLossPercent: number | null;
inboundJitterMs: number | null;
concealedSamples: number | null;
}
export interface VoiceAudioStatusSample {
sampledAt: number;
transport: "webrtc" | "websocket" | "negotiating" | "disconnected";
connectionState: string | null;
microphoneMuted: boolean;
microphoneReady: boolean;
microphonePermission: AudioPermission;
playbackState: "playing" | "paused" | "unavailable" | null;
bridge: VoiceAudioBridgeStats;
browser: BrowserVoiceAudioStats | null;
fallbackPlayback: { framesReceived: number; framesDropped: number; decodeErrors: number };
}
const MAX_VISIBLE_ERROR_CODE_LENGTH = 64;
const CLIENT_ERROR_CODE_ALIASES: Record<string, string> = {
PASSWORD_REQUIRED: "SERVER_PASSWORD_REQUIRED",
@@ -245,11 +218,6 @@ export function useVoiceWebSocket() {
});
const commands = createVoiceCommands({ socket: () => ws.value, generation: () => voiceConnection.generation });
let lastConnection: { target: string; channel: string; nickname: string; serverPassword: string; identity?: string; rememberIdentity: boolean; accelerated: boolean; accelerationRelayId: string } | null = null;
let audioStatusProbeSequence = 0;
const pendingAudioStatusProbes = new Map<string, { resolve: (stats: VoiceAudioBridgeStats | null) => void; timer: ReturnType<typeof setTimeout> }>();
let fallbackAudioFramesReceived = 0;
let fallbackAudioFramesDropped = 0;
let fallbackAudioDecodeErrors = 0;
const identityMaterial = ref("");
const storedVolumesByUid = reactive<Record<string, number>>({});
let microphoneStartPromise: Promise<void> | null = null;
@@ -341,8 +309,8 @@ export function useVoiceWebSocket() {
const remotePlayback = createRemotePlayback({
getContext: getAudioCtx,
getVolume: clientId => (volumes[clientId] ?? 1) * effectiveOutputVolume(),
onDecodeError: () => { fallbackAudioDecodeErrors++; },
onDrop: () => { fallbackAudioFramesDropped++; },
onDecodeError: () => audioDiagnostics.count("decodeErrors"),
onDrop: () => audioDiagnostics.count("framesDropped"),
});
const webrtc = createWebRtcTransport({
prepareMicrophone: async () => {
@@ -384,6 +352,26 @@ export function useVoiceWebSocket() {
onPlaying: syncAudioContextNotice,
},
});
const audioDiagnostics = createAudioDiagnostics({
source() {
const socket = ws.value;
if (!socket || socket.readyState !== WebSocket.OPEN || !state.connected) return null;
const peer = webrtc.peer;
return { socket, connection: voiceConnection.generation, transportGeneration: webrtc.generation, peer,
transport: webrtc.active ? "webrtc" : peer ? "negotiating" : "websocket" };
},
presentation({ peer }) {
return {
microphoneMuted: microphoneMuted.value,
microphoneReady: Boolean(micStream?.getAudioTracks().some(track => track.readyState === "live")),
microphonePermission: audioPermission.value,
playbackState: peer
? webrtc.output ? webrtc.output.paused ? "paused" : "playing" : "unavailable"
: audioCtx ? audioCtx.state === "running" ? "playing" : "paused" : null,
};
},
send: (source, sequence) => source.socket.send(JSON.stringify({ type: "audioStatsProbe", payload: { sequence } })),
});
async function saveAudioPreferences(): Promise<void> {
await saveLocalPreferences({
@@ -1021,7 +1009,7 @@ export function useVoiceWebSocket() {
selectedOutputDeviceId.value = committedOutputDeviceId;
noiseSuppressionEnabled.value = committedNoiseSuppressionEnabled;
microphoneTest.dispose();
clearAudioStatusProbes();
audioDiagnostics.reset();
commands.clear(new Error("语音连接已关闭"));
screenShare.stopTransport(sendScreenStop);
webrtc.stop();
@@ -1032,14 +1020,6 @@ export function useVoiceWebSocket() {
whisperActive.value = false;
}
function clearAudioStatusProbes(): void {
for (const [sequence, pending] of pendingAudioStatusProbes) {
clearTimeout(pending.timer);
pendingAudioStatusProbes.delete(sequence);
pending.resolve(null);
}
}
function handleMessage(raw: unknown): void {
const msg = parseServerMessage(raw);
if (!msg || screenShare.handleMessage(msg)) return;
@@ -1161,9 +1141,7 @@ export function useVoiceWebSocket() {
break;
case "audioStats": {
const sequence = typeof msg.sequence === "string" ? msg.sequence : "";
const pending = pendingAudioStatusProbes.get(sequence);
if (!pending) break;
pending.resolve(msg.stats);
audioDiagnostics.receive(sequence, msg.stats);
break;
}
case "disconnected":
@@ -1252,12 +1230,12 @@ export function useVoiceWebSocket() {
// produce duplicate or delayed playback.
if (webrtc.active) return;
if (data.length < 4) {
fallbackAudioFramesDropped++;
audioDiagnostics.count("framesDropped");
return;
}
const clientId = (data[1] << 8) | data[2];
if (clientId === state.tsClientId) return;
fallbackAudioFramesReceived++;
audioDiagnostics.count("framesReceived");
markSpeaking(clientId);
remotePlayback.play(clientId, data.slice(3));
}
@@ -1281,131 +1259,8 @@ export function useVoiceWebSocket() {
return sendCommandAndWait("moveClient", { clientId, channelId, ...(password ? { password } : {}) });
}
async function collectBrowserVoiceAudioStats(): Promise<BrowserVoiceAudioStats | null> {
const peer = webrtc.peer;
if (!peer) return null;
try {
const report = await peer.getStats();
let outbound: Record<string, unknown> | undefined;
let remoteInbound: Record<string, unknown> | undefined;
let inbound: Record<string, unknown> | undefined;
let candidatePair: Record<string, unknown> | undefined;
report.forEach((raw) => {
const stats = raw as unknown as Record<string, unknown>;
const type = typeof stats.type === "string" ? stats.type : "";
const kind = typeof stats.kind === "string" ? stats.kind : typeof stats.mediaType === "string" ? stats.mediaType : "";
if (kind === "audio") {
if (type === "outbound-rtp") outbound = stats;
else if (type === "remote-inbound-rtp") remoteInbound = stats;
else if (type === "inbound-rtp") inbound = stats;
}
if (type === "candidate-pair" && (stats.selected === true || stats.nominated === true) && stats.state === "succeeded") candidatePair = stats;
});
const readNumber = (stats: Record<string, unknown> | undefined, key: string): number | null => {
const value = stats?.[key];
return typeof value === "number" && Number.isFinite(value) ? value : null;
};
const outboundLost = readNumber(remoteInbound, "packetsLost");
const outboundPackets = readNumber(outbound, "packetsSent");
const fractionLost = readNumber(remoteInbound, "fractionLost");
const outboundLossPercent = fractionLost !== null
? Math.min(100, Math.max(0, fractionLost * 100))
: outboundLost !== null && outboundPackets !== null && outboundPackets + Math.max(0, outboundLost) > 0
? (Math.max(0, outboundLost) / (outboundPackets + Math.max(0, outboundLost))) * 100
: null;
const inboundPackets = readNumber(inbound, "packetsReceived");
const inboundPacketsLost = readNumber(inbound, "packetsLost");
const inboundLossTotal = inboundPackets !== null && inboundPacketsLost !== null
? inboundPackets + Math.max(0, inboundPacketsLost)
: null;
const outboundRttSeconds = readNumber(remoteInbound, "roundTripTime") ?? readNumber(candidatePair, "currentRoundTripTime");
const inboundJitterSeconds = readNumber(inbound, "jitter");
return {
outboundBytes: readNumber(outbound, "bytesSent"),
outboundPackets,
outboundPacketsLost: outboundLost,
outboundLossPercent,
outboundRttMs: outboundRttSeconds === null ? null : outboundRttSeconds * 1_000,
inboundBytes: readNumber(inbound, "bytesReceived"),
inboundPackets,
inboundPacketsLost,
inboundLossPercent: inboundLossTotal && inboundLossTotal > 0 && inboundPacketsLost !== null
? (Math.max(0, inboundPacketsLost) / inboundLossTotal) * 100
: null,
inboundJitterMs: inboundJitterSeconds === null ? null : inboundJitterSeconds * 1_000,
concealedSamples: readNumber(inbound, "concealedSamples"),
};
} catch {
return null;
}
}
function measureVoiceAudioStatus(timeoutMs = 1_800): Promise<VoiceAudioStatusSample | null> {
const socket = ws.value;
if (!socket || socket.readyState !== WebSocket.OPEN || !state.connected) return Promise.resolve(null);
const connection = voiceConnection.generation;
const peer = webrtc.peer;
const isCurrent = () => connection === voiceConnection.generation && ws.value === socket
&& socket.readyState === WebSocket.OPEN && state.connected && webrtc.peer === peer;
const sequence = `audio-${Date.now().toString(36)}-${(audioStatusProbeSequence++).toString(36)}`;
const browserStatsPromise = collectBrowserVoiceAudioStats();
return new Promise<VoiceAudioStatusSample | null>((resolve) => {
let settled = false;
let receivedBridge = false;
const finish = (sample: VoiceAudioStatusSample | null): void => {
if (settled) return;
settled = true;
clearTimeout(timer);
pendingAudioStatusProbes.delete(sequence);
resolve(sample);
};
// Keep the deadline and cancellation entry until both sources finish.
// A gateway reply must not leave an unbounded browser getStats wait.
const timer = setTimeout(() => finish(null), timeoutMs);
pendingAudioStatusProbes.set(sequence, {
resolve: (bridge) => {
if (!bridge) {
finish(null);
return;
}
if (settled || receivedBridge) return;
receivedBridge = true;
void browserStatsPromise.then((browser) => {
if (settled) return;
if (!isCurrent()) { finish(null); return; }
const transport = !state.connected
? "disconnected"
: webrtc.active
? "webrtc"
: peer
? "negotiating"
: "websocket";
const playbackState = peer
? webrtc.output ? webrtc.output.paused ? "paused" : "playing" : "unavailable"
: audioCtx ? audioCtx.state === "running" ? "playing" : "paused" : null;
finish({
sampledAt: performance.now(),
transport,
connectionState: peer?.connectionState ?? null,
microphoneMuted: microphoneMuted.value,
microphoneReady: Boolean(micStream?.getAudioTracks().some((track) => track.readyState === "live")),
microphonePermission: audioPermission.value,
playbackState,
bridge,
browser,
fallbackPlayback: {
framesReceived: fallbackAudioFramesReceived,
framesDropped: fallbackAudioFramesDropped,
decodeErrors: fallbackAudioDecodeErrors,
},
});
});
},
timer,
});
try { sendCmd("audioStatsProbe", { sequence }); }
catch { finish(null); }
});
return audioDiagnostics.measure(timeoutMs);
}
function sendTextMessage(message: string, targetId = ""): void {
+28 -26
View File
@@ -1,5 +1,5 @@
import { computed, onUnmounted, ref, watch, type Ref } from "vue";
import type { VoiceAudioStatusSample } from "./useVoiceWebSocket.js";
import type { VoiceAudioStatusSample } from "../voice/audio-diagnostics.js";
const SAMPLE_INTERVAL_MS = 2_000;
@@ -27,13 +27,21 @@ function intervalLossPercent(
currentLost: number | null | undefined,
previousLost: number | null | undefined,
fallback: number | null,
packetsIncludeLost = false,
): number | null {
if (currentReceived == null || previousReceived == null || currentLost == null || previousLost == null) return fallback;
const receivedDelta = counterDelta(currentReceived, previousReceived);
const lostDelta = counterDelta(Math.max(0, currentLost), Math.max(0, previousLost));
if (receivedDelta === null || lostDelta === null) return fallback;
const total = receivedDelta + lostDelta;
return total > 0 ? (lostDelta / total) * 100 : fallback;
const total = receivedDelta + (packetsIncludeLost ? 0 : lostDelta);
return total > 0 ? Math.min(100, (lostDelta / total) * 100) : fallback;
}
function downlinkCounter(sample: VoiceAudioStatusSample | null) {
if (!sample) return null;
if (sample.transport === "websocket") return { source: "pcm", value: sample.fallbackPlayback.framesReceived };
if (sample.transport === "webrtc" && sample.browser?.inboundPackets != null) return { source: "rtp", value: sample.browser.inboundPackets };
return { source: "bridge", value: sample.bridge.egressFrames };
}
export function useWebClientPerformance(
@@ -46,10 +54,12 @@ export function useWebClientPerformance(
const previousSample = ref<VoiceAudioStatusSample | null>(null);
let timer: number | null = null;
let generation = 0;
let disposed = false;
const stats = computed(() => {
const current = latestSample.value;
const previous = previousSample.value;
const prior = previousSample.value;
const previous = current && prior && current.scopeId === prior.scopeId && current.transport === prior.transport ? prior : null;
const elapsedMs = current && previous ? current.sampledAt - previous.sampledAt : 0;
const bridge = current?.bridge;
const previousBridge = previous?.bridge;
@@ -58,25 +68,12 @@ export function useWebClientPerformance(
const uplinkFramesPerSecond = bridge
? ratePerSecond(bridge.tsSendFrames, previousBridge?.tsSendFrames, elapsedMs)
: null;
const downlinkCounter = current
? current.transport === "websocket"
? current.fallbackPlayback.framesReceived
: current.transport === "webrtc" && browser?.inboundPackets !== null && browser?.inboundPackets !== undefined
? browser.inboundPackets
: bridge?.egressFrames ?? null
: null;
const previousDownlinkCounter = previous
? previous.transport === "websocket"
? previous.fallbackPlayback.framesReceived
: previous.transport === "webrtc" && previousBrowser?.inboundPackets !== null && previousBrowser?.inboundPackets !== undefined
? previousBrowser.inboundPackets
: previousBridge?.egressFrames ?? null
: null;
const downlinkFramesPerSecond = downlinkCounter === null
? null
: ratePerSecond(downlinkCounter, previousDownlinkCounter ?? undefined, elapsedMs);
const downlink = downlinkCounter(current);
const priorDownlink = downlinkCounter(previous);
const downlinkFramesPerSecond = downlink && priorDownlink && downlink.source === priorDownlink.source
? ratePerSecond(downlink.value, priorDownlink.value, elapsedMs) : null;
const uplinkLossPercent = browser
? intervalLossPercent(browser.outboundPackets, previousBrowser?.outboundPackets, browser.outboundPacketsLost, previousBrowser?.outboundPacketsLost, browser.outboundLossPercent)
? intervalLossPercent(browser.outboundPackets, previousBrowser?.outboundPackets, browser.outboundPacketsLost, previousBrowser?.outboundPacketsLost, browser.outboundLossPercent, true)
: null;
const downlinkLossPercent = browser
? intervalLossPercent(browser.inboundPackets, previousBrowser?.inboundPackets, browser.inboundPacketsLost, previousBrowser?.inboundPacketsLost, browser.inboundLossPercent)
@@ -138,13 +135,18 @@ export function useWebClientPerformance(
});
async function runProbe(expectedGeneration = generation): Promise<void> {
if (running.value || !connected.value) return;
if (disposed || expectedGeneration !== generation || running.value || !connected.value) return;
running.value = true;
try {
const sample = await measureAudioStatus();
if (expectedGeneration !== generation || !connected.value || !sample) return;
previousSample.value = latestSample.value;
if (expectedGeneration !== generation || !connected.value) return;
previousSample.value = sample ? latestSample.value : null;
latestSample.value = sample;
} catch {
if (expectedGeneration === generation) {
latestSample.value = null;
previousSample.value = null;
}
} finally {
if (expectedGeneration === generation) running.value = false;
}
@@ -181,7 +183,7 @@ export function useWebClientPerformance(
else stop();
}, { immediate: true });
onUnmounted(stop);
onUnmounted(() => { disposed = true; stop(); });
return { panelOpen, running, stats, togglePanel, refresh };
}
+168
View File
@@ -0,0 +1,168 @@
import type { VoiceAudioBridgeStats } from "../../../src/shared/voice-models.js";
export type AudioPermission = "unknown" | "granted" | "denied";
export interface BrowserVoiceAudioStats {
outboundBytes: number | null;
outboundPackets: number | null;
outboundPacketsLost: number | null;
outboundLossPercent: number | null;
outboundRttMs: number | null;
inboundBytes: number | null;
inboundPackets: number | null;
inboundPacketsLost: number | null;
inboundLossPercent: number | null;
inboundJitterMs: number | null;
concealedSamples: number | null;
}
export interface VoiceAudioStatusSample {
/** Browser-local counter scope; changes when the connection or transport does. */
scopeId: number;
sampledAt: number;
transport: "webrtc" | "websocket" | "negotiating" | "disconnected";
connectionState: string | null;
microphoneMuted: boolean;
microphoneReady: boolean;
microphonePermission: AudioPermission;
playbackState: "playing" | "paused" | "unavailable" | null;
bridge: VoiceAudioBridgeStats;
browser: BrowserVoiceAudioStats | null;
fallbackPlayback: { framesReceived: number; framesDropped: number; decodeErrors: number };
}
interface DiagnosticSource {
socket: WebSocket;
connection: number;
transportGeneration: number;
peer: RTCPeerConnection | null;
transport: VoiceAudioStatusSample["transport"];
}
interface DiagnosticOptions {
source(): DiagnosticSource | null;
presentation(source: DiagnosticSource): Pick<VoiceAudioStatusSample,
"microphoneMuted" | "microphoneReady" | "microphonePermission" | "playbackState">;
send(source: DiagnosticSource, sequence: string): void;
}
async function browserStats(peer: RTCPeerConnection | null): Promise<BrowserVoiceAudioStats | null> {
if (!peer) return null;
try {
const report = await peer.getStats();
let outbound: Record<string, unknown> | undefined;
let remoteInbound: Record<string, unknown> | undefined;
let inbound: Record<string, unknown> | undefined;
let candidatePair: Record<string, unknown> | undefined;
report.forEach(raw => {
const stats = raw as unknown as Record<string, unknown>;
const kind = stats.kind ?? stats.mediaType;
if (kind === "audio") {
if (stats.type === "outbound-rtp") outbound = stats;
else if (stats.type === "remote-inbound-rtp") remoteInbound = stats;
else if (stats.type === "inbound-rtp") inbound = stats;
}
if (stats.type === "candidate-pair" && (stats.selected === true || stats.nominated === true) && stats.state === "succeeded") candidatePair = stats;
});
const number = (stats: Record<string, unknown> | undefined, key: string): number | null => {
const value = stats?.[key];
return typeof value === "number" && Number.isFinite(value) ? value : null;
};
const outboundLost = number(remoteInbound, "packetsLost");
const outboundPackets = number(outbound, "packetsSent");
const fractionLost = number(remoteInbound, "fractionLost");
// packetsSent already counts all sent packets; adding lost packets again
// underestimates loss. Prefer the remote RTCP report when supplied.
// https://www.w3.org/TR/webrtc-stats/#dom-rtcsentrtpstreamstats-packetssent
const outboundLossPercent = fractionLost !== null
? Math.min(100, Math.max(0, fractionLost * 100))
: outboundLost !== null && outboundPackets !== null && outboundPackets > 0
? Math.min(100, (Math.max(0, outboundLost) / outboundPackets) * 100)
: null;
const inboundPackets = number(inbound, "packetsReceived");
const inboundPacketsLost = number(inbound, "packetsLost");
const inboundTotal = inboundPackets !== null && inboundPacketsLost !== null
? inboundPackets + Math.max(0, inboundPacketsLost) : null;
const rtt = number(remoteInbound, "roundTripTime") ?? number(candidatePair, "currentRoundTripTime");
const jitter = number(inbound, "jitter");
return {
outboundBytes: number(outbound, "bytesSent"), outboundPackets, outboundPacketsLost: outboundLost,
outboundLossPercent, outboundRttMs: rtt === null ? null : rtt * 1_000,
inboundBytes: number(inbound, "bytesReceived"), inboundPackets, inboundPacketsLost,
inboundLossPercent: inboundTotal && inboundTotal > 0 && inboundPacketsLost !== null
? (Math.max(0, inboundPacketsLost) / inboundTotal) * 100 : null,
inboundJitterMs: jitter === null ? null : jitter * 1_000,
concealedSamples: number(inbound, "concealedSamples"),
};
} catch { return null; }
}
function sameSource(left: DiagnosticSource | null, right: DiagnosticSource | null): boolean {
return Boolean(left && right && left.socket === right.socket && left.connection === right.connection
&& left.transportGeneration === right.transportGeneration && left.peer === right.peer && left.transport === right.transport);
}
export function createAudioDiagnostics(options: DiagnosticOptions) {
const pending = new Map<string, { receive(bridge: VoiceAudioBridgeStats): void; finish(sample: VoiceAudioStatusSample | null): void }>();
const fallback = { framesReceived: 0, framesDropped: 0, decodeErrors: 0 };
let sequence = 0;
let scopeId = 0;
let previousSource: DiagnosticSource | null = null;
function measure(timeoutMs = 1_800): Promise<VoiceAudioStatusSample | null> {
const source = options.source();
if (!source) return Promise.resolve(null);
if (!sameSource(previousSource, source)) {
previousSource = source;
scopeId++;
}
const scope = scopeId;
const requestId = `audio-${Date.now().toString(36)}-${(sequence++).toString(36)}`;
const browser = browserStats(source.peer);
return new Promise(resolve => {
let settled = false;
let receivedBridge = false;
const finish = (sample: VoiceAudioStatusSample | null): void => {
if (settled) return;
settled = true;
clearTimeout(timer);
pending.delete(requestId);
resolve(sample);
};
// Keep cancellation and the deadline until both sources finish.
const timer = setTimeout(() => finish(null), timeoutMs);
pending.set(requestId, {
finish,
receive(bridge) {
if (settled || receivedBridge) return;
receivedBridge = true;
void browser.then(stats => {
if (settled) return;
if (scope !== scopeId || !sameSource(source, options.source())) { finish(null); return; }
finish({
scopeId: scope, sampledAt: performance.now(), transport: source.transport,
connectionState: source.peer?.connectionState ?? null,
...options.presentation(source), bridge, browser: stats, fallbackPlayback: { ...fallback },
});
});
},
});
try { options.send(source, requestId); }
catch { finish(null); }
});
}
return {
measure,
receive(sequence: string, bridge: VoiceAudioBridgeStats): void { pending.get(sequence)?.receive(bridge); },
count(counter: keyof typeof fallback): void { fallback[counter]++; },
reset(): void {
scopeId++;
previousSource = null;
for (const probe of pending.values()) probe.finish(null);
fallback.framesReceived = 0;
fallback.framesDropped = 0;
fallback.decodeErrors = 0;
},
};
}
+1
View File
@@ -182,6 +182,7 @@ export function createWebRtcTransport(options: TransportOptions) {
return {
start, stop, applyAnswer,
get generation(): number { return generation; },
releaseInput(): void { releaseInput(); },
async fallback(reason: string): Promise<void> { if (current) await fail(current, reason); },
get peer(): RTCPeerConnection | null { return current?.peer ?? null; },
+1 -1
View File
@@ -44,7 +44,7 @@ const defaults = path => ({
before(async () => {
vite = await createServer({ configFile: false, root: fileURLToPath(new URL("../", import.meta.url)),
plugins: [vuePlugin()], server: { middlewareMode: true, hmr: false, watch: null },
plugins: [vuePlugin()], server: { middlewareMode: true, hmr: false, ws: false, watch: null },
optimizeDeps: { noDiscovery: true, include: [] }, appType: "custom" });
({ createRenderer, ssrContextKey } = await import("vue"));
({ createRouter, createMemoryHistory } = await import("vue-router"));
+201
View File
@@ -0,0 +1,201 @@
import assert from "node:assert/strict";
import { before, after, beforeEach, afterEach, test } from "node:test";
import { setImmediate as nextTurn } from "node:timers/promises";
import { fileURLToPath } from "node:url";
import { createServer } from "vite";
import { createRenderer, ref, nextTick } from "vue";
let vite, useWebClientPerformance, app, monitor, connected, measure;
const intervals = new Map();
const originalWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
const renderer = createRenderer({
createComment: text => ({ text }), createText: text => ({ text }), createElement: () => ({}),
insert() {}, remove() {}, setText() {}, setElementText() {}, patchProp() {}, parentNode: () => null, nextSibling: () => null,
});
const deferred = () => {
let resolve;
const promise = new Promise(done => { resolve = done; });
return { promise, resolve };
};
function sample(extra = {}, bridge = {}, browser = {}) {
return {
scopeId: 1, sampledAt: 1_000, transport: "webrtc", connectionState: "connected",
microphoneMuted: false, microphoneReady: true, microphonePermission: "granted", playbackState: "playing",
bridge: { transport: "webrtc", tsSendFrames: 0, tsSendErrors: 0, egressFrames: 0,
ingressDroppedFrames: 0, egressDroppedFrames: 0, webrtcIngressDecodeErrors: 0,
webrtcDownlinkDecodeErrors: 0, webrtcQueueDroppedFrames: 0, webrtcQueueUnderrunTicks: 0,
ingressMaxGapMs: 0, egressMaxGapMs: 0, ...bridge },
browser: { outboundBytes: 0, outboundPackets: 0, outboundPacketsLost: 0, outboundLossPercent: 0,
outboundRttMs: 20, inboundBytes: 0, inboundPackets: 0, inboundPacketsLost: 0, inboundLossPercent: 0,
inboundJitterMs: 5, concealedSamples: 0, ...browser },
fallbackPlayback: { framesReceived: 0, framesDropped: 0, decodeErrors: 0 },
...extra,
};
}
before(async () => {
vite = await createServer({ configFile: false, root: fileURLToPath(new URL("../", import.meta.url)),
server: { middlewareMode: true, hmr: false, ws: false, watch: null }, optimizeDeps: { noDiscovery: true, include: [] }, appType: "custom" });
({ useWebClientPerformance } = await vite.ssrLoadModule("/src/composables/useWebClientPerformance.ts"));
});
beforeEach(t => {
intervals.clear();
Object.defineProperty(globalThis, "window", { configurable: true, value: {
setInterval(callback, delay) { assert.equal(delay, 2_000); const timer = {}; intervals.set(timer, callback); return timer; },
} });
const clear = globalThis.clearInterval;
t.mock.method(globalThis, "clearInterval", timer => { if (!intervals.delete(timer)) clear(timer); });
connected = ref(true);
measure = async () => sample();
});
afterEach(() => { app?.unmount(); app = null; });
after(async () => {
await vite?.close();
if (originalWindow) Object.defineProperty(globalThis, "window", originalWindow);
else delete globalThis.window;
});
async function mount() {
app = renderer.createApp({ setup() { monitor = useWebClientPerformance(connected, () => measure()); return () => null; } });
app.mount({});
await nextTurn();
}
async function refresh(value) {
measure = async () => value;
monitor.refresh();
await nextTurn();
}
test("transport changes do not subtract RTP packets from compatibility frames", async () => {
measure = async () => sample({}, {}, { inboundPackets: 20 });
await mount();
await refresh(sample({ transport: "websocket", sampledAt: 3_000,
fallbackPlayback: { framesReceived: 200, framesDropped: 0, decodeErrors: 0 } }));
assert.equal(monitor.stats.value.downlinkFramesPerSecond, null);
assert.equal(monitor.stats.value.health, "quiet");
});
test("replacement peers and reconnects start a fresh counter baseline", async () => {
await mount();
await refresh(sample({ scopeId: 2, sampledAt: 3_000 }, { tsSendFrames: 500, tsSendErrors: 10 },
{ outboundBytes: 50_000, inboundBytes: 40_000, inboundPackets: 200 }));
assert.equal(monitor.stats.value.uplinkFramesPerSecond, null);
assert.equal(monitor.stats.value.uplinkBitrateKbps, null);
assert.equal(monitor.stats.value.downlinkFramesPerSecond, null);
assert.equal(monitor.stats.value.sendErrors, null);
assert.equal(monitor.stats.value.health, "quiet");
await refresh(sample({ scopeId: 2, sampledAt: 5_000 }, { tsSendFrames: 600, tsSendErrors: 10 },
{ outboundBytes: 58_000, inboundBytes: 44_000, inboundPackets: 300 }));
assert.equal(monitor.stats.value.uplinkFramesPerSecond, 50);
assert.equal(monitor.stats.value.downlinkFramesPerSecond, 50);
assert.equal(monitor.stats.value.uplinkBitrateKbps, 32);
assert.equal(monitor.stats.value.health, "active");
});
test("temporarily missing RTP stats do not turn bridge counters into packet deltas", async () => {
measure = async () => sample({}, { egressFrames: 1_000 }, { inboundPackets: 20 });
await mount();
await refresh(sample({ sampledAt: 3_000, browser: null }, { egressFrames: 1_100 }));
assert.equal(monitor.stats.value.downlinkFramesPerSecond, null);
await refresh(sample({ sampledAt: 5_000, browser: null }, { egressFrames: 1_200 }));
assert.equal(monitor.stats.value.downlinkFramesPerSecond, 50);
});
test("a missing sample clears stale activity and a later sample starts a new baseline", async () => {
await mount();
await refresh(sample({ sampledAt: 3_000 }, { tsSendFrames: 100 }));
assert.equal(monitor.stats.value.health, "active");
await refresh(null);
assert.equal(monitor.stats.value.ready, false);
assert.equal(monitor.stats.value.health, "sampling");
assert.equal(monitor.running.value, false);
await refresh(sample({ sampledAt: 7_000 }, { tsSendFrames: 300 }));
assert.equal(monitor.stats.value.uplinkFramesPerSecond, null);
});
test("a rejected probe is contained and the next refresh can recover", async () => {
await mount();
measure = async () => { throw new Error("Stats unavailable"); };
monitor.refresh();
await nextTurn();
assert.equal(monitor.stats.value.ready, false);
assert.equal(monitor.running.value, false);
await refresh(sample());
assert.equal(monitor.stats.value.ready, true);
});
test("a queued old polling callback cannot start work or wedge a replacement connection", async () => {
let calls = 0;
measure = async () => { calls++; return sample(); };
await mount();
const oldTick = [...intervals.values()][0];
connected.value = false;
await nextTick();
assert.equal(intervals.size, 0);
connected.value = true;
await nextTurn();
const callsBefore = calls;
oldTick();
await nextTurn();
assert.equal(calls, callsBefore);
assert.equal(monitor.running.value, false);
monitor.refresh();
await nextTurn();
assert.equal(calls, callsBefore + 1);
});
test("unmount retires pending results, queued timers and manual refresh", async () => {
const pending = deferred();
let calls = 0;
measure = () => { calls++; return pending.promise; };
await mount();
const oldTick = [...intervals.values()][0];
app.unmount();
app = null;
assert.equal(intervals.size, 0);
oldTick();
monitor.refresh();
pending.resolve(sample());
await nextTurn();
assert.equal(calls, 1);
assert.equal(monitor.running.value, false);
assert.equal(monitor.stats.value.ready, false);
});
test("late samples from an old connection cannot replace current diagnostics", async () => {
const pending = deferred();
measure = () => pending.promise;
await mount();
connected.value = false;
await nextTick();
measure = async () => sample({ scopeId: 2, transport: "websocket" });
connected.value = true;
await nextTurn();
pending.resolve(sample({ scopeId: 1, connectionState: "failed" }));
await nextTurn();
assert.equal(monitor.stats.value.transport, "websocket");
assert.equal(monitor.stats.value.health, "quiet");
assert.equal(monitor.running.value, false);
});
test("uplink loss uses sent packets while downlink loss includes missing packets", async () => {
await mount();
await refresh(sample({ sampledAt: 3_000 }, {}, {
outboundPackets: 100, outboundPacketsLost: 20, inboundPackets: 80, inboundPacketsLost: 20,
}));
assert.equal(monitor.stats.value.uplinkLossPercent, 20);
assert.equal(monitor.stats.value.downlinkLossPercent, 20);
});
test("normal counters preserve activity, warning and playback diagnostics", async () => {
await mount();
await refresh(sample({ sampledAt: 3_000, playbackState: "paused" }, { tsSendFrames: 100 }, { inboundPackets: 100 }));
assert.equal(monitor.stats.value.uplinkFramesPerSecond, 50);
assert.equal(monitor.stats.value.downlinkFramesPerSecond, 50);
assert.equal(monitor.stats.value.health, "warning");
assert.equal(monitor.stats.value.uplinkRttMs, 20);
assert.equal(monitor.stats.value.downlinkJitterMs, 5);
connected.value = false;
await nextTick();
assert.equal(monitor.stats.value.health, "disconnected");
assert.equal(monitor.stats.value.ready, false);
});
+56 -1
View File
@@ -166,7 +166,7 @@ before(async () => {
vite = await createServer({
configFile: false,
root: fileURLToPath(new URL("../", import.meta.url)),
server: { middlewareMode: true, hmr: false, watch: null },
server: { middlewareMode: true, hmr: false, ws: false, watch: null },
optimizeDeps: { noDiscovery: true, include: [] },
appType: "custom",
});
@@ -1220,6 +1220,7 @@ test("a current audio probe retains browser metrics and accepts missing browser
assert.equal(sample.browser.outboundPackets, 10);
assert.equal(sample.browser.outboundBytes, 100);
assert.equal(sample.browser.outboundRttMs, 50);
assert.equal(sample.browser.outboundLossPercent, 20);
peer.getStats = async () => { throw new Error("Stats unavailable"); };
const missing = voice.measureVoiceAudioStatus();
const nextRequest = socket.messages.filter(message => message.type === "audioStatsProbe").at(-1);
@@ -1227,6 +1228,60 @@ test("a current audio probe retains browser metrics and accepts missing browser
assert.equal((await missing).browser, null);
});
async function audioSample(socket, bridge = {}) {
const pending = voice.measureVoiceAudioStatus();
const request = socket.messages.filter(message => message.type === "audioStatsProbe").at(-1);
socket.receive({ type: "audioStats", sequence: request.payload.sequence, stats: { transport: "websocket", ...bridge } });
return pending;
}
test("diagnostic sample scopes follow peer replacement and fallback on one socket", async () => {
const { socket } = await connectWebRtc();
const first = await audioSample(socket);
const next = await audioSample(socket);
assert.equal(typeof first.scopeId, "number");
assert.equal(next.scopeId, first.scopeId);
await voice.setInputDevice("replacement");
const replaced = await audioSample(socket);
assert.notEqual(replaced.scopeId, first.scopeId);
socket.receive({ type: "webrtcError", code: "WEBRTC_UNAVAILABLE" });
await nextTurn();
const fallback = await audioSample(socket);
assert.notEqual(fallback.scopeId, replaced.scopeId);
assert.equal(fallback.transport, "websocket");
});
test("session recovery resets compatibility diagnostics without mutating old snapshots", async () => {
const socket = await connect();
socket.receive({ type: "connected", tsClientId: 1 });
await nextTurn();
receiveAudio(socket);
receiveAudio(socket);
socket.onmessage({ data: new Uint8Array([1, 2]).buffer });
const previous = await audioSample(socket);
assert.equal(previous.fallbackPlayback.framesReceived, 2);
assert.equal(previous.fallbackPlayback.framesDropped, 1);
socket.receive({ type: "disconnected", recoverable: true });
socket.receive({ type: "connected", tsClientId: 2 });
await nextTurn();
const current = await audioSample(socket);
assert.notEqual(current.scopeId, previous.scopeId);
assert.deepEqual(current.fallbackPlayback, { framesReceived: 0, framesDropped: 0, decodeErrors: 0 });
assert.equal(previous.fallbackPlayback.framesReceived, 2);
});
test("a probe started before peer allocation cannot survive a failed transport attempt", async t => {
t.mock.method(TestPeer.prototype, "createOffer", async () => { throw new Error("Offer unavailable"); });
const socket = await connect();
socket.receive({ type: "connected", tsClientId: 1, webrtcAvailable: true });
const pending = voice.measureVoiceAudioStatus();
const request = socket.messages.filter(message => message.type === "audioStatsProbe").at(-1);
await nextTurn();
assert.equal(TestPeer.instances.at(-1).connectionState, "closed");
socket.receive({ type: "audioStats", sequence: request.payload.sequence, stats: { transport: "websocket" } });
assert.equal(await pending, null);
});
test("disconnect clears the WebRTC answer deadline immediately", async () => {
await connectWebRtc();
assert.ok(browserTimers.size > 0);