mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-01 02:52:49 +08:00
Compare commits
7
Commits
dev
..
9a12e2ee7b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9a12e2ee7b | ||
|
|
3e4be94ae7 | ||
|
|
3339d09936 | ||
|
|
462bab57d2 | ||
|
|
6bbc292056 | ||
|
|
e3c71f07b1 | ||
|
|
cf1cc9fb94 |
No files matched your search
@@ -9,7 +9,7 @@ on:
|
||||
version:
|
||||
description: Release version without the v prefix
|
||||
required: true
|
||||
default: 0.3.2
|
||||
default: 0.3.3
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
@@ -214,7 +214,38 @@ jobs:
|
||||
grep -q '"status":"ok"' <<<"$health"
|
||||
grep -q "\"version\":\"$release_version\"" <<<"$health"
|
||||
)
|
||||
tar -czf "$GITHUB_WORKSPACE/${package_name}.tar.gz" -C "$RUNNER_TEMP" "$package_name"
|
||||
# Native rebuilds can leave hard-linked objects and Python/toolchain
|
||||
# symlinks in scratch directories. Ship independent files and keep
|
||||
# build-only scratch paths out of the portable runtime archive.
|
||||
tar --hard-dereference \
|
||||
--exclude='*/@discordjs/opus/build-tmp-*' \
|
||||
--exclude='*/node_gyp_bins' \
|
||||
-czf "$GITHUB_WORKSPACE/${package_name}.tar.gz" -C "$RUNNER_TEMP" "$package_name"
|
||||
# Verify the shipped tarball is accepted by the same extractor and
|
||||
# package validator used by console updates, including .bin links.
|
||||
node --input-type=module - "$GITHUB_WORKSPACE/${package_name}.tar.gz" "$RUNNER_TEMP/${package_name}-updater-check" "$release_version" <<'NODE'
|
||||
import path from 'node:path';
|
||||
import { rm } from 'node:fs/promises';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { extractReleaseArchive } from './dist/updater/archive.js';
|
||||
import { locatePackageRoot } from './dist/updater/code-swap.js';
|
||||
const [archive, destination, version] = process.argv.slice(2);
|
||||
try {
|
||||
await extractReleaseArchive(archive, destination, path.basename(archive));
|
||||
const root = locatePackageRoot(destination, version, 'linux');
|
||||
const nativeSmoke = spawnSync(path.join(root, 'runtime', 'node'), ['--input-type=commonjs', '-e', `
|
||||
const { OpusEncoder } = require('@discordjs/opus');
|
||||
const encoder = new OpusEncoder(48000, 2);
|
||||
const packet = encoder.encode(Buffer.alloc(3840));
|
||||
if (encoder.decode(packet).length !== 3840) throw new Error('Packaged Opus codec failed');
|
||||
`], { cwd: root, encoding: 'utf8', timeout: 15000 });
|
||||
if (nativeSmoke.error) throw nativeSmoke.error;
|
||||
if (nativeSmoke.status !== 0) throw new Error(nativeSmoke.stderr || 'Packaged Opus runtime failed');
|
||||
console.log(`Console updater accepts ${path.basename(archive)}`);
|
||||
} finally {
|
||||
await rm(destination, { recursive: true, force: true });
|
||||
}
|
||||
NODE
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: linux-${{ matrix.arch }}
|
||||
|
||||
@@ -19,9 +19,7 @@
|
||||
</p>
|
||||
</div>
|
||||
|
||||
当前版本 / Current version: **[v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2)** · [更新内容 / Release notes](./docs/README.zh-CN.md#latest-release-notes)
|
||||
|
||||
dev 实验功能 / dev experiment: [锁屏通话 / Lock-screen calls](./docs/EXPERIMENTAL_BACKGROUND_CALLS.md)(默认关闭,尚未通过真机锁屏验收 / off by default; physical-device validation pending)。
|
||||
当前版本 / Current version: **[v0.3.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.3)** · [更新内容 / Release notes](./docs/README.zh-CN.md#latest-release-notes)
|
||||
|
||||
## 关于 WebSpeak · Overview
|
||||
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
# 锁屏通话实验 / Experimental lock-screen calls
|
||||
|
||||
此功能目前只用于 dev 分支实验,默认关闭。它改善浏览器的音频路径,不能保证浏览器或操作系统允许锁屏后一直录音、联网或播放。尚未完成 Android/iOS 真机锁屏验收。
|
||||
|
||||
## 使用
|
||||
|
||||
在音频配置中开启“锁屏通话(实验性)”,然后断开并重新进入语音房间。设置只在下次连接生效,通话中修改不会突然更换麦克风路径。需要网关及浏览器支持 WebRTC。没有 WebRTC 或协商失败时,回退到原有兼容传输,音频配置中的原生模式提示会消失。
|
||||
|
||||
原生模式直接发送系统麦克风音轨,并用浏览器原生 `<audio srcObject>` 接收。浏览器的回声消除、标准降噪仍可使用;RNNoise 强降噪、软件输入增益、客户端音量计、语音阈值和伴奏不参与这条路径。非零输入增益不会缩放声音,0% 仍禁止发送。此模式持续发送未静音的麦克风,请在不需要说话时静音。静音同时控制音轨与网关的麦克风状态。关闭实验选项并重新连接可恢复普通处理。
|
||||
|
||||
支持的浏览器会显示系统媒体控制。Pause 同时静音麦克风及接收声音;Play 只恢复接收,不解除麦克风静音。麦克风切换需要明确操作,Stop/Hang up 会结束连接并释放采集。在支持 Audio Session API 的平台上声明 `play-and-record`,离开时恢复之前的类型。系统暂停或结束音轨时,音频配置会显示中断提示。
|
||||
|
||||
## 实现与边界
|
||||
|
||||
- 普通模式保留现有 Web Audio、WebRTC 与 PCM 回退。原生模式不创建麦克风的 AudioContext、AudioWorklet、分析器或混音节点。
|
||||
- 远端原生音频的 `play()` 不再等待采集 AudioContext 的 `resume()`;未完成的恢复请求不会连带阻塞收听。
|
||||
- 返回前台和系统 Play 只重试当前会话的播放。它们不会重新申请麦克风、取消静音或重新建立已结束的通话。
|
||||
- Media Session 是系统控制接口,不是后台保活权限。PWA、Service Worker、屏幕常亮都不能绕过系统限制;不播放静音文件或伪造音乐来保活。
|
||||
- WebSocket 兼容模式仍依赖 JavaScript 解码与 Web Audio,不作锁屏持续通话保证。真实语音需要持续网络连接,不能像音乐文件那样提前缓冲。
|
||||
- Android APK 目前仍为 WebView 与嵌入式网关。这次未添加原生前台音频服务,也未完成 APK 后台双向语音验收。
|
||||
|
||||
## 验证
|
||||
|
||||
自动化测试覆盖原始音轨发送、静音、权限请求取消、WebRTC 失败/缺失后的回退、系统 API 缺失/部分支持、旧系统动作隔离、采集恢复不阻塞播放,以及前台恢复不自动开麦。
|
||||
|
||||
2026-11-24 本地验证:`npm run verify` 的 1023 项测试全部通过,前后端构建成功。Windows Edge 使用模拟麦克风、两个真实浏览器 RTCPeerConnection 做回环,确认原生轨道收发 RTP、播放不等待采集恢复、静音切换及资源释放;1440px 与 390px 视口检查了全部五种语言的设置界面。该回环未连接 TeamSpeak,移动视口也不是手机系统锁屏测试。
|
||||
|
||||
真机验收应连接真实 TeamSpeak 房间,用第二个独立客户端双向监听,并分别记录:
|
||||
|
||||
1. Android Chrome、iPhone Safari、已安装 PWA 和 APK 的版本、系统版本、网络与省电设置。
|
||||
2. 普通模式与实验模式下,前台、切应用、锁屏各 1/5/15 分钟的收听和发送;每次恢复说话前后都检查第二端实际听感及媒体收发计数。
|
||||
3. 开麦/静音/输入音量 0%、系统 Play/Pause/麦克风控制、蓝牙切换、电话打断、网络切换和网关重连。
|
||||
4. 断开或撤销权限后系统录音指示消失;旧权限请求或系统按钮不能重新启动采集。关闭实验并重连后强降噪、伴奏和普通音量控制恢复。
|
||||
|
||||
桌面模拟移动视口、无头浏览器和单元测试不代表通过真机锁屏验收。
|
||||
|
||||
## References
|
||||
|
||||
- HollyMusic [`useAudioPlayer.ts`](https://github.com/redcatH/HollyMusic/blob/abbae61d4ee7a7ac53a417c4da6802ff70b10717/hooks/useAudioPlayer.ts) and [`audio-analysis.ts`](https://github.com/redcatH/HollyMusic/blob/abbae61d4ee7a7ac53a417c4da6802ff70b10717/lib/client/audio-analysis.ts): native playback separated from optional Web Audio processing. This implementation uses the same architectural idea; no HollyMusic source was copied.
|
||||
- [Media Session API](https://web.dev/articles/media-session) and [Audio Session draft](https://www.w3.org/TR/audio-session/).
|
||||
- [Android foreground service types](https://developer.android.com/develop/background-work/services/fgs/service-types).
|
||||
|
||||
The experiment is off by default and applies on the next connection. It uses native WebRTC microphone tracks and native remote playback, while keeping mute, hangup and compatibility fallback. Optional Web Audio processing and accompaniment are unavailable in the native route. OS playback controls never unmute the microphone implicitly. Browser/OS restrictions still apply; physical-device background calling and native Android foreground audio services remain unverified/unimplemented respectively.
|
||||
+15
-1
@@ -13,7 +13,7 @@
|
||||
|
||||
WebSpeak ist ein selbst gehosteter Browserclient und ein Sprach-Gateway für TeamSpeak 3 und TeamSpeak 6. Nutzer verwenden Sprache, Chat und Bildschirmfreigabe im Browser; Betreiber verwalten Zielserver, Zugriff und Daten über die Webkonsole.
|
||||
|
||||
Stabile Version: [Hinweise zu v0.3.2](#latest-release-notes) · [Pakete herunterladen](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Skin-Wiederherstellung, App-Bibliothek und Plugin-Formulare.
|
||||
Stabile Version: [Hinweise zu v0.3.3](#latest-release-notes) · [Pakete herunterladen](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Konsolen-Updates, Wiederherstellung und bessere Skin-Kompatibilität.
|
||||
|
||||
|
||||
|
||||
@@ -341,6 +341,20 @@ Funktionale Plugins sind unabhängige Anwendungen mit Browserfunktionen und opti
|
||||
|
||||
<a id="latest-release-notes"></a>
|
||||
|
||||
### [v0.3.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.3) · 2026-11-26
|
||||
|
||||
**Schwerpunkt: stabile Versionen prüfen und Updates direkt in der Verwaltung installieren.**
|
||||
|
||||
- Die Konsole prüft offizielle GitHub Releases; Administratoren wählen eine Version und bestätigen die Installation nach SHA-256-Prüfung. Die Installation unterstützt zunächst offizielle Linux-x64-Pakete im Vordergrund. Windows, Linux arm64, Docker, Quellinstallationen und von systemd, PM2 oder Supervisor verwaltete Instanzen können Versionen und Versionshinweise prüfen; die Installation bleibt manuell.
|
||||
- Nur Programmdateien werden ersetzt. `data/`, `config.json`, `certs/`, installierte Skins und Plugins bleiben erhalten. Der Prozessneustart trennt Sprachsitzungen und Konsole kurzzeitig. SHA256SUMS.txt ist eine Integritätsprüfsumme, keine digitale Signatur.
|
||||
- Gesundheitsprüfung, Rollback und Startwiederherstellung nach Unterbrechungen wurden gehärtet. Wiederherstellung und Update verwenden dieselbe Sperre. Größenlimits, Schreibfehler und Abbruch beenden Anfragen, geben Leser frei und bereinigen parallele Downloads.
|
||||
- Skins können Wiederherstellungsbedienelemente über deklarierte Slots platzieren und Host-Bedienelemente über geschützte Variablen gestalten. Bei unbrauchbaren Werten greifen Standardlayout und -farben. Verbesserte Vermeidung verdeckter Elemente, Toast-Hit-Tests sowie Kompatibilität mit verzögertem Skin-Laden und Animationen; Wiederherstellungskürzel bleiben verfügbar.
|
||||
- Enthält #60, #61, #62 und nachfolgende Korrekturen sowie aktualisierte Skin-Anleitungen und Beispiele. Danke an OddTurtleHead.
|
||||
|
||||
**Upgrade:** v0.3.2 und ältere Versionen zuerst manuell auf v0.3.3 aktualisieren. Danach sind Konsolen-Updates für künftige stabile Versionen auf unterstützten Installationen verfügbar. Daten vorher sichern. Docker: `docker compose pull && docker compose up -d` unter Beibehaltung des Datenvolumes. Verwaltete Dienste vor dem Dateiaustausch stoppen und anschließend neu starten.
|
||||
|
||||
Prüfung: 1102 automatisierte Tests, Frontend-/Backend-Builds und Docker-Startprüfung bestanden.
|
||||
|
||||
### [v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2) · 2026-11-14
|
||||
|
||||
- Drittanbieter-Skins können Host-Dekorationen gestalten. Der Host verwaltet Wiederherstellung und Freigabe, damit Nutzer zu einem integrierten Skin zurückkehren können. Danke an ph1gros für die TS3-Erkennung und Kompatibilitätshinweise (#46) und an OddTurtleHead für Host-Design und Skin-Wiederherstellung (#57).
|
||||
|
||||
+15
-1
@@ -13,7 +13,7 @@
|
||||
|
||||
WebSpeak is a self-hosted browser client and voice gateway for TeamSpeak 3 and TeamSpeak 6. Visitors join voice, chat and screen sharing in a browser; operators manage target servers, access policy and data through the administration console.
|
||||
|
||||
Stable release: [v0.3.2 notes](#latest-release-notes) · [Download packages](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Skin recovery, app library layouts, and plugin settings forms.
|
||||
Stable release: [v0.3.3 notes](#latest-release-notes) · [Download packages](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Console updates, reliable recovery, and skin compatibility improvements.
|
||||
|
||||
|
||||
|
||||
@@ -347,6 +347,20 @@ Functional plugins are independent applications using standard browser capabilit
|
||||
|
||||
<a id="latest-release-notes"></a>
|
||||
|
||||
### [v0.3.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.3) · 2026-11-26
|
||||
|
||||
**Highlight: stable-release checks and one-click updates in the administration console.**
|
||||
|
||||
- Administrators can check official GitHub Releases, select a version and confirm installation. Packages must pass SHA-256 verification. Installation initially supports official Linux x64 packages running in the foreground. Windows, Linux arm64, Docker, source installs and instances managed by systemd, PM2 or Supervisor retain version checks and release-note links; installation follows their manual deployment procedure.
|
||||
- Updates replace application files while preserving `data/`, `config.json`, `certs/`, installed skins and plugins. Installation restarts the process and briefly disconnects voice sessions and the console. SHA256SUMS.txt is an integrity checksum, not a digital signature.
|
||||
- Hardened health checks, rollback and startup recovery after interrupted updates. Recovery shares the update lock, preventing a duplicate launch from rolling back a live update. Size-limit errors, disk-write failures and cancellation abort requests, release response readers and clean up sibling downloads.
|
||||
- Skins can place recovery controls in declared slots and style host controls through protected tokens, with default placement and colours when unusable. Improved floating-control avoidance, hit-testing through toasts, late skin loading and animation compatibility; recovery shortcuts remain available.
|
||||
- Includes #60, #61, #62 and follow-up maintenance fixes, plus updated skin development documentation and examples. Thanks to OddTurtleHead.
|
||||
|
||||
**Upgrading:** manually upgrade v0.3.2 or earlier to v0.3.3 first. Supported installs can then use the console for future stable releases. Back up data before upgrading. Docker uses `docker compose pull && docker compose up -d` with the data volume preserved. Stop managed services before replacing application files, then start them again.
|
||||
|
||||
Validation: 1,102 automated tests, frontend/backend builds and the Docker startup health check passed.
|
||||
|
||||
### [v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2) · 2026-11-14
|
||||
|
||||
- Third-party skins can style host decorations. The host manages recovery and authorization so users can switch back to a built-in skin. Thanks to ph1gros for the TS3 detection and compatibility work (#46), and OddTurtleHead for host theming and skin recovery (#57).
|
||||
|
||||
+15
-1
@@ -13,7 +13,7 @@
|
||||
|
||||
WebSpeak はセルフホスト型の TeamSpeak 3 / TeamSpeak 6 ブラウザークライアント兼音声ゲートウェイです。ユーザーはブラウザーで音声、チャット、画面共有に参加でき、運営者は管理コンソールで接続先、アクセス方針、データを管理できます。
|
||||
|
||||
安定版:[v0.3.2 更新内容](#latest-release-notes) · [ダウンロード](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · スキンの復元、アプリライブラリの配置、プラグイン設定フォーム。
|
||||
安定版:[v0.3.3 更新内容](#latest-release-notes) · [ダウンロード](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · コンソール更新、復元処理、スキン互換性の改善。
|
||||
|
||||
|
||||
|
||||
@@ -276,6 +276,20 @@ relay.example.com {
|
||||
|
||||
<a id="latest-release-notes"></a>
|
||||
|
||||
### [v0.3.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.3) · 2026-11-26
|
||||
|
||||
**主な変更:管理コンソールから安定版の確認とワンクリック更新が可能になりました。**
|
||||
|
||||
- 公式 GitHub Releases を確認し、管理者がバージョンを選んでインストールを承認します。パッケージは SHA-256 検証が必須です。自動インストールの対象は、フォアグラウンドで実行する公式 Linux x64 パッケージです。Windows、Linux arm64、Docker、ソース実行、systemd・PM2・Supervisor 管理の環境では、バージョン確認とリリースノートの閲覧ができ、インストールは手動です。
|
||||
- 置き換えるのはプログラムファイルのみです。`data/`、`config.json`、`certs/`、インストール済みのスキンとプラグインは保持します。プロセスの再起動により、音声セッションと管理画面が一時的に切断されます。SHA256SUMS.txt は整合性のチェックサムであり、デジタル署名ではありません。
|
||||
- ヘルスチェック、ロールバック、中断後の起動復元を強化しました。復元処理は更新処理とロックを共有し、重複起動による実行中の更新の巻き戻しを防ぎます。サイズ超過、書き込み失敗、キャンセル時にはリクエストと並列ダウンロードを中止し、読み取りストリームを解放します。
|
||||
- 宣言したスロットと保護されたスタイル変数で、スキン内の復元入口とホスト操作部を調整できます。利用できない配置や色は標準に戻ります。浮動ボタンの重なり回避、通知の下にある要素の判定、スキンの遅延読み込みとアニメーションの互換性を改善し、復元ショートカットを維持しました。
|
||||
- #60、#61、#62 と追加修正を収録し、スキン開発ガイドとサンプルを更新しました。OddTurtleHead の貢献に感謝します。
|
||||
|
||||
**更新方法:** v0.3.2 以前は、最初に v0.3.3 へ手動で更新してください。その後、対応する環境ではコンソールから今後の安定版をインストールできます。事前にデータをバックアップしてください。Docker はデータボリュームを保持して `docker compose pull && docker compose up -d` を実行します。サービス管理下では、停止してからプログラムファイルを置き換え、再起動してください。
|
||||
|
||||
検証:1102 件の自動テスト、フロントエンド・バックエンドのビルド、Docker 起動ヘルスチェックを通過。
|
||||
|
||||
### [v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2) · 2026-11-14
|
||||
|
||||
- サードパーティースキンでホストの装飾を変更できます。復元と許可の操作は WebSpeak が管理し、組み込みスキンに戻せます。TS3 判定と互換性情報の ph1gros(#46)、ホスト装飾と復元機能の OddTurtleHead(#57)に感謝します。
|
||||
|
||||
+15
-1
@@ -13,7 +13,7 @@
|
||||
|
||||
WebSpeak — самостоятельно размещаемый браузерный клиент и голосовой шлюз для TeamSpeak 3 и TeamSpeak 6. Пользователи подключаются к голосу, чату и демонстрации экрана через браузер, а оператор управляет серверами, доступом и данными в веб-консоли.
|
||||
|
||||
Стабильный выпуск: [изменения v0.3.2](#latest-release-notes) · [Скачать](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Восстановление темы, библиотека приложений и формы настройки плагинов.
|
||||
Стабильный выпуск: [изменения v0.3.3](#latest-release-notes) · [Скачать](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · Обновление из консоли, восстановление и улучшенная совместимость скинов.
|
||||
|
||||
|
||||
|
||||
@@ -276,6 +276,20 @@ relay.example.com {
|
||||
|
||||
<a id="latest-release-notes"></a>
|
||||
|
||||
### [v0.3.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.3) · 2026-11-26
|
||||
|
||||
**Главное: проверка стабильных версий и установка обновлений из консоли администратора.**
|
||||
|
||||
- Консоль проверяет официальные GitHub Releases; администратор выбирает версию и подтверждает установку после проверки SHA-256. Установка пока поддерживается для официальных пакетов Linux x64, запущенных в переднем плане. Windows, Linux arm64, Docker, исходники и экземпляры под управлением systemd, PM2 или Supervisor могут проверять версии и открывать примечания; установка остаётся ручной.
|
||||
- Заменяются только файлы программы. `data/`, `config.json`, `certs/`, установленные скины и плагины сохраняются. Перезапуск ненадолго отключает голосовые сеансы и консоль. SHA256SUMS.txt — контрольная сумма целостности, а не цифровая подпись.
|
||||
- Усилены проверка работоспособности, откат и восстановление запуска после прерванного обновления. Восстановление использует общую блокировку с обновлением, чтобы повторный запуск не откатывал активную установку. При превышении лимита, ошибке записи или отмене запросы прерываются, потоки освобождаются, параллельная загрузка отменяется.
|
||||
- Скины могут размещать элементы восстановления в объявленных слотах и оформлять элементы хоста через защищённые переменные. При непригодном оформлении используются стандартные расположение и цвета. Улучшены обход перекрытий, проверка элементов под уведомлениями, поздняя загрузка скинов и совместимость анимаций; сочетания клавиш восстановления сохранены.
|
||||
- Включены #60, #61, #62 и последующие исправления, обновлены руководство и примеры скинов. Спасибо OddTurtleHead.
|
||||
|
||||
**Переход:** v0.3.2 и более ранние версии сначала обновляются до v0.3.3 вручную. После этого поддерживаемые установки могут получать следующие стабильные версии через консоль. Сделайте резервную копию. Docker: `docker compose pull && docker compose up -d` с сохранением тома данных. Управляемую службу остановите перед заменой файлов, затем запустите снова.
|
||||
|
||||
Проверено: 1102 автоматических теста, сборки фронтенда и бэкенда, проверка запуска Docker.
|
||||
|
||||
### [v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2) · 2026-11-14
|
||||
|
||||
- Сторонние темы могут оформлять декоративные элементы. WebSpeak управляет восстановлением и разрешениями, чтобы пользователи могли вернуться к встроенной теме. Спасибо ph1gros за определение TS3 и сведения о совместимости (#46), а OddTurtleHead за оформление интерфейса и восстановление темы (#57).
|
||||
|
||||
+17
-3
@@ -13,7 +13,7 @@
|
||||
|
||||
WebSpeak 是可自行部署的 TeamSpeak 3 / TeamSpeak 6 网页客户端与语音网关。用户通过浏览器加入语音、聊天和屏幕共享;部署者通过管理员控制台管理目标服务器、访问策略和数据。
|
||||
|
||||
稳定版:[v0.3.2 更新日志](#latest-release-notes) · [下载发布包](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · 皮肤恢复入口、应用库布局和插件配置表单。
|
||||
稳定版:[v0.3.3 更新日志](#latest-release-notes) · [下载发布包](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) · 控制台一键更新、升级恢复与皮肤兼容性改进。
|
||||
|
||||
|
||||
|
||||
@@ -366,12 +366,26 @@ relay.example.com {
|
||||
|
||||
## 更新日志
|
||||
|
||||
<a id="live-update-2026-11-13"></a>
|
||||
|
||||
<a id="latest-release-notes"></a>
|
||||
|
||||
### [v0.3.3](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.3) · 2026-11-26
|
||||
|
||||
**本次重点:管理员控制台新增正式版本检查与一键更新。**
|
||||
|
||||
- 管理员可检查官方 GitHub Releases,选择版本并确认安装;下载包必须通过 SHA-256 校验。首期自动安装支持前台运行的 Linux x64 官方发布包。Windows、Linux arm64、Docker、源码,以及 systemd、PM2、Supervisor 托管实例均保留版本检查和发行说明入口,安装仍按各部署方式手动完成。
|
||||
- 更新仅替换程序文件,保留 `data/`、`config.json`、`certs/` 及已安装的皮肤和插件。安装会重启进程,语音会话和管理页面会短暂断开。SHA256SUMS.txt 是完整性校验和,不是数字签名。
|
||||
- 加固升级健康检查、失败回滚和断电/进程中断后的启动恢复;恢复流程与更新进程共享锁,防止正常更新被重复启动误回滚。下载超限、写盘失败或取消时会中止请求、释放响应流,并清理并行下载。
|
||||
- 皮肤可通过声明的布局槽位和受保护样式变量调整恢复入口与宿主控件的外观;不可读或不可用时回退到默认布局和样式。改进浮动入口的遮挡避让、提示消息穿透判断、皮肤延迟加载和动画兼容性,保留恢复快捷键。
|
||||
- 纳入 #60、#61、#62 及后续维护修复,更新皮肤开发文档和示例。感谢 OddTurtleHead 的贡献。
|
||||
|
||||
**升级说明:** v0.3.2 及更早版本请先手动升级到 v0.3.3;之后可在支持的部署中使用控制台安装后续正式版。升级前请备份数据。Docker 使用 `docker compose pull && docker compose up -d` 并保留数据卷;服务托管实例请停止服务、替换程序文件后再启动。
|
||||
|
||||
验证:1102 项自动化测试通过,前后端构建及 Docker 启动健康检查通过。
|
||||
|
||||
### [v0.3.2](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.3.2) · 2026-11-14
|
||||
|
||||
<a id="live-update-2026-11-13"></a>
|
||||
|
||||
- 第三方皮肤可以为宿主装饰添加样式。恢复入口和授权弹窗由宿主管理,应用皮肤后仍能切回内置皮肤。感谢 ph1gros 对 TS3 版本识别及兼容性文档的贡献(#46),以及 OddTurtleHead 对宿主装饰和皮肤恢复的贡献(#57)。
|
||||
- 日间、夜间和 ILLUSIA 的应用库在顶部工具栏展开。KAAK 3.1.134 将应用库放入最左侧图标栏,按钮与相邻控件对齐。固定应用排在列表前面。
|
||||
- 插件后台提供字段编辑器,以及 P2P 文件传输、视频同看和 TSMusicBot 的配置表单。插件页面可以打开对应仓库。
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "webspeak-android-gateway",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.3",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "webspeak-android-gateway",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.3",
|
||||
"dependencies": {
|
||||
"@honeybbq/teamspeak": "1.0.0-beta.23",
|
||||
"express": "^4.21.2",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "webspeak-android-gateway",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.3",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "index.cjs",
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.3",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.3",
|
||||
"license": "AGPL-3.0-only",
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.3",
|
||||
"private": true,
|
||||
"license": "AGPL-3.0-only",
|
||||
"type": "module",
|
||||
@@ -11,7 +11,7 @@
|
||||
"scripts": {
|
||||
"dev": "tsx src/index.ts",
|
||||
"build": "tsc",
|
||||
"test": "node --import tsx --test src/admin/security-boundaries.test.ts src/admin/update-routes.test.ts src/updater/version.test.ts src/updater/deployment.test.ts src/updater/archive.test.ts src/updater/code-swap.test.ts src/updater/update-state.test.ts src/updater/update-service.test.ts src/updater/restart-runner.test.ts src/updater/swap-recovery.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.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 scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.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/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.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/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.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/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/src/services/host-floating-placement.test.ts web/test/host-chrome-recovery.test.mjs web/src/services/call-media-session.test.ts",
|
||||
"test": "node --import tsx --test src/admin/security-boundaries.test.ts src/admin/update-routes.test.ts src/updater/version.test.ts src/updater/deployment.test.ts src/updater/archive.test.ts src/updater/code-swap.test.ts src/updater/update-state.test.ts src/updater/update-service.test.ts src/updater/restart-runner.test.ts src/updater/swap-recovery.test.ts src/domain/teamspeak-target.test.ts web/src/voice/member-volume-preferences.test.ts web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/skin-store.test.ts src/admin/ts-admin-service.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 scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-gateway-auth.test.ts src/server/voice-gateway.test.ts src/server/relay-delegation.integration.test.ts src/persistence/database.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/teamspeak-adapter.test.ts src/server/teamspeak-sdk.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/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.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/skin-layout.test.ts src/shared/skin-css.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.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/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-workspace.test.mjs web/test/skin-workspace.test.ts web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-content.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts src/plugins/plugins.test.ts web/test/plugins.integration.test.ts web/src/services/plugin-app-client.test.ts web/src/services/instance-authorization.test.ts web/src/services/host-chrome-visibility.test.ts web/src/services/host-control-tokens.test.ts web/src/services/host-recovery-helpers.test.ts web/src/services/host-slot-placement.test.ts web/src/services/host-floating-placement.test.ts web/test/host-chrome-recovery.test.mjs",
|
||||
"verify": "npm test && npm run build && npm run web:build",
|
||||
"skin:harbor:build": "node web/scripts/build-harbor-voice-skin.mjs",
|
||||
"skin:open-voice:build": "node web/scripts/build-open-voice-surface-skin.mjs",
|
||||
|
||||
+100
-23
@@ -28,8 +28,8 @@ code_missing() {
|
||||
return 1
|
||||
}
|
||||
|
||||
# A backup can only repair an install if it recorded a swap and still holds
|
||||
# every entry needed to boot. Partial/legacy backups must be skipped.
|
||||
# A backup can only repair a missing-code install if it is complete. Partial
|
||||
# backups are still resumable when they belong to the active task.
|
||||
backup_is_complete() {
|
||||
[ -f "$1/.webspeak-swap.json" ] || return 1
|
||||
for entry in $required_entries; do
|
||||
@@ -52,6 +52,86 @@ task_backup_can_repair() {
|
||||
return 0
|
||||
}
|
||||
|
||||
state_file="$data_dir/updates/state.json"
|
||||
lock_file="$data_dir/updates/update.lock"
|
||||
read_update_task() {
|
||||
task_id=""
|
||||
task_status=""
|
||||
if [ -f "$state_file" ]; then
|
||||
task_id=$(sed -n 's/.*"id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$state_file" | head -n 1)
|
||||
task_status=$(sed -n 's/.*"status"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$state_file" | head -n 1)
|
||||
fi
|
||||
case "$task_id" in
|
||||
""|*[!A-Za-z0-9_-]*) task_id="" ;;
|
||||
esac
|
||||
}
|
||||
read_update_task
|
||||
|
||||
process_start() {
|
||||
# After the last ')' field 3 is first; starttime (field 22) is twentieth.
|
||||
if [ -r "/proc/$1/stat" ]; then
|
||||
sed 's/.*) //' "/proc/$1/stat" 2>/dev/null | awk '{print $20}'
|
||||
fi
|
||||
}
|
||||
|
||||
release_recovery_lock() {
|
||||
if [ "${lock_owned:-0}" = 1 ] && [ "$(cat "$lock_file" 2>/dev/null)" = "$lock_payload" ]; then
|
||||
rm -f -- "$lock_file"
|
||||
fi
|
||||
lock_owned=0
|
||||
}
|
||||
|
||||
acquire_recovery_lock() {
|
||||
# Share the updater's exclusive-create JSON lock. A distinct task id stops
|
||||
# a delayed restart runner from taking this recovery lock over. Keep it for
|
||||
# the entire restore, and only reclaim a proven-dead, unchanged owner.
|
||||
mkdir -p "$data_dir/updates"
|
||||
lock_owned=0
|
||||
start=$(process_start "$$")
|
||||
lock_payload="{\"pid\":$$,\"taskId\":\"recovery_$$\",\"createdAt\":\"\",\"processStart\":\"$start\"}"
|
||||
for attempt in 1 2 3 4; do
|
||||
if (umask 077; set -C; printf '%s\n' "$lock_payload" > "$lock_file") 2>/dev/null; then
|
||||
lock_owned=1
|
||||
trap 'release_recovery_lock' 0
|
||||
trap 'exit 1' HUP INT TERM
|
||||
return 0
|
||||
fi
|
||||
observed=$(cat "$lock_file" 2>/dev/null) || return 1
|
||||
owner=$(printf '%s\n' "$observed" | sed -n 's/.*"pid"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\)[[:space:]]*[,}].*/\1/p' | head -n 1)
|
||||
owner_task=$(printf '%s\n' "$observed" | sed -n 's/.*"taskId"[[:space:]]*:[[:space:]]*"\([^"]\{1,\}\)".*/\1/p' | head -n 1)
|
||||
case "$owner" in ""|*[!0-9]*) return 1 ;; esac
|
||||
[ -n "$owner_task" ] || return 1
|
||||
if [ "$owner" != 0 ]; then
|
||||
if kill -0 "$owner" 2>/dev/null || [ -d "/proc/$owner" ]; then
|
||||
saved_start=$(printf '%s\n' "$observed" | sed -n 's/.*"processStart"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n 1)
|
||||
current_start=$(process_start "$owner")
|
||||
# Unknown markers and inaccessible processes are conservatively live.
|
||||
if [ -z "$saved_start" ] || [ -z "$current_start" ] || [ "$saved_start" = "$current_start" ]; then
|
||||
return 1
|
||||
fi
|
||||
elif [ ! -d /proc ]; then
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
[ "$(cat "$lock_file" 2>/dev/null)" = "$observed" ] || continue
|
||||
rm -f -- "$lock_file" || return 1
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
recovery_needed() {
|
||||
if code_missing; then
|
||||
return 0
|
||||
fi
|
||||
case "$task_status" in
|
||||
downloading|verifying|extracting|staging|restarting)
|
||||
[ -n "$task_id" ] && [ -d "$backups/$task_id" ] && [ -f "$backups/$task_id/.webspeak-swap.json" ]
|
||||
return $?
|
||||
;;
|
||||
esac
|
||||
return 1
|
||||
}
|
||||
|
||||
restore_from_backup() {
|
||||
backup="$1"
|
||||
# Move whatever partial new code the interrupted swap left in the install
|
||||
@@ -80,33 +160,29 @@ restore_from_backup() {
|
||||
done
|
||||
}
|
||||
|
||||
if code_missing; then
|
||||
if recovery_needed; then
|
||||
if ! acquire_recovery_lock; then
|
||||
echo "WebSpeak update or recovery is already running, or its lock cannot be verified; refusing to change application files." >&2
|
||||
exit 75
|
||||
fi
|
||||
# The runner may have completed between the first state read and the lock.
|
||||
read_update_task
|
||||
fi
|
||||
|
||||
if [ "${lock_owned:-0}" = 1 ] && recovery_needed; then
|
||||
restore_backup=""
|
||||
|
||||
# The interrupted task is the source of truth: backups/<task.id> holds the
|
||||
# exact version that was running before the swap. A successful earlier
|
||||
# update leaves its backup behind (M1 does not clean it up), so picking the
|
||||
# first or alphabetically smallest backup can resurrect a much older build.
|
||||
state_file="$data_dir/updates/state.json"
|
||||
task_id=""
|
||||
if [ -f "$state_file" ]; then
|
||||
task_id=$(sed -n 's/.*"id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$state_file" | head -n 1)
|
||||
fi
|
||||
# Task ids are generated as upd_<base36>_<hex>. Reject anything else so a
|
||||
# tampered state.json cannot become a path traversal or a glob pattern.
|
||||
case "$task_id" in
|
||||
""|*[!A-Za-z0-9_-]*) task_id="" ;;
|
||||
esac
|
||||
if [ -n "$task_id" ]; then
|
||||
# The interrupted task is the source of truth. Its backup may be partial
|
||||
# while the old tree is being saved or while a previous recovery is still
|
||||
# consuming it, but it must never be replaced by an older complete backup.
|
||||
if [ -n "$task_id" ] && [ -d "$backups/$task_id" ]; then
|
||||
candidate="$backups/$task_id"
|
||||
if task_backup_can_repair "$candidate"; then
|
||||
restore_backup="$candidate"
|
||||
fi
|
||||
fi
|
||||
|
||||
# No usable task backup (e.g. state.json was lost): use the most recently
|
||||
# modified complete backup rather than whichever name happens to sort first.
|
||||
if [ -z "$restore_backup" ]; then
|
||||
else
|
||||
# No current task backup (e.g. state.json was lost): use the most recently
|
||||
# modified complete backup rather than whichever name happens to sort first.
|
||||
for manifest in "$backups"/*/.webspeak-swap.json; do
|
||||
[ -f "$manifest" ] || continue
|
||||
backup="${manifest%/.webspeak-swap.json}"
|
||||
@@ -129,4 +205,5 @@ if code_missing; then
|
||||
fi
|
||||
fi
|
||||
|
||||
release_recovery_lock
|
||||
exec "$PWD/runtime/node" "$PWD/dist/index.js"
|
||||
@@ -37,6 +37,11 @@ test("staged packages must be complete, regular files and version-matched", t =>
|
||||
rmSync(path.join(missing, "runtime", "node"));
|
||||
assert.throws(() => validateStagedPackage(missing, { version: "0.4.0", platform: "linux" }), packageInvalid);
|
||||
|
||||
const missingLauncher = workspace(t);
|
||||
createPackageFiles(missingLauncher, "0.4.0");
|
||||
rmSync(path.join(missingLauncher, "start-webspeak.sh"));
|
||||
assert.throws(() => validateStagedPackage(missingLauncher, { version: "0.4.0", platform: "linux" }), packageInvalid);
|
||||
|
||||
const linked = workspace(t);
|
||||
createPackageFiles(linked, "0.4.0");
|
||||
rmSync(path.join(linked, "runtime", "node"));
|
||||
|
||||
@@ -56,6 +56,7 @@ export function validateStagedPackage(root: string, options: StagedPackageOption
|
||||
requireEntry(root, "node_modules", "directory");
|
||||
requireEntry(root, "package.json", "file");
|
||||
requireEntry(root, options.platform === "win32" ? "runtime/node.exe" : "runtime/node", "file");
|
||||
requireEntry(root, options.platform === "win32" ? "start-webspeak.cmd" : "start-webspeak.sh", "file");
|
||||
let manifest: unknown;
|
||||
try { manifest = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")); }
|
||||
catch { throw new CodeSwapError("UPDATE_PACKAGE_INVALID", "Release package manifest is not valid JSON."); }
|
||||
@@ -145,10 +146,10 @@ function moveIfPresent(from: string, to: string): void {
|
||||
}
|
||||
|
||||
/**
|
||||
* Backups written by this version contain only atomically moved entries.
|
||||
* The manifest records which entries were moved completely, so a backup that
|
||||
* was partially written by an older implementation (or tampered with) can be
|
||||
* rejected instead of overwriting an intact install tree.
|
||||
* Backups written by this version journal each entry before moving it. The
|
||||
* journal may therefore contain an entry whose move never started, but it can
|
||||
* never omit an entry that reached the backup. Recovery acts only on entries
|
||||
* that actually exist in the backup, so a kill between journal and move is safe.
|
||||
*/
|
||||
const SWAP_MANIFEST = ".webspeak-swap.json";
|
||||
|
||||
@@ -203,10 +204,10 @@ export function swapCode(rootDir: string, stagedRoot: string, backupDir: string)
|
||||
writeSwapManifest(backupDir, []);
|
||||
for (const entry of CODE_ENTRIES) {
|
||||
if (!existsSync(path.join(rootDir, entry))) continue;
|
||||
moveIfPresent(path.join(rootDir, entry), path.join(backupDir, entry));
|
||||
movedToBackup.push(entry);
|
||||
swapWindowBarrier(entry);
|
||||
writeSwapManifest(backupDir, movedToBackup);
|
||||
moveIfPresent(path.join(rootDir, entry), path.join(backupDir, entry));
|
||||
swapWindowBarrier(entry);
|
||||
}
|
||||
swapWindowBarrier();
|
||||
for (const entry of CODE_ENTRIES) {
|
||||
@@ -216,7 +217,12 @@ export function swapCode(rootDir: string, stagedRoot: string, backupDir: string)
|
||||
}
|
||||
} catch (error) {
|
||||
try { restoreMovedEntries(rootDir, backupDir, movedToBackup, movedToRoot); }
|
||||
catch { /* Report the original swap error; rollback failure is handled by the caller. */ }
|
||||
catch (rollbackError) {
|
||||
throw new CodeSwapError(
|
||||
"UPDATE_ROLLBACK_FAILED",
|
||||
`${error instanceof Error ? error.message : "Release package swap failed."} Code rollback also failed: ${rollbackError instanceof Error ? rollbackError.message : "unknown error"}`,
|
||||
);
|
||||
}
|
||||
if (error instanceof CodeSwapError) throw error;
|
||||
throw new CodeSwapError("UPDATE_SWAP_FAILED", error instanceof Error ? error.message : "Release package swap failed.");
|
||||
}
|
||||
|
||||
@@ -2,9 +2,12 @@ import assert from "node:assert/strict";
|
||||
import test, { type TestContext } from "node:test";
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import fs from "node:fs";
|
||||
import { syncBuiltinESMExports } from "node:module";
|
||||
import { createServer } from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { setCodeSwapCopyForTests } from "./code-swap.js";
|
||||
import { runRestartPlan } from "./restart-runner.js";
|
||||
|
||||
const sleep = (milliseconds: number) => new Promise<void>((resolve) => setTimeout(resolve, milliseconds));
|
||||
@@ -27,13 +30,13 @@ async function waitFor(check: () => boolean, timeoutMs = 5_000): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
function appScript(version: string, port: number, pidFile: string): string {
|
||||
function appScript(version: string, port: number, pidFile: string, status = "ok"): string {
|
||||
return `const http = require("node:http");
|
||||
const { writeFileSync } = require("node:fs");
|
||||
const server = http.createServer((request, response) => {
|
||||
if (request.url === "/api/health") {
|
||||
response.setHeader("content-type", "application/json");
|
||||
response.end(JSON.stringify({ status: "ok", version: ${JSON.stringify(version)} }));
|
||||
response.end(JSON.stringify({ status: ${JSON.stringify(status)}, version: ${JSON.stringify(version)} }));
|
||||
return;
|
||||
}
|
||||
response.statusCode = 404;
|
||||
@@ -85,10 +88,10 @@ function runnerFixture(t: TestContext): RunnerFixture {
|
||||
};
|
||||
}
|
||||
|
||||
function writePlan(fixture: RunnerFixture, port: number, pidFile: string, options: { targetVersion: string; reportedVersion: string; healthTimeoutMs?: number }) {
|
||||
function writePlan(fixture: RunnerFixture, port: number, pidFile: string, options: { targetVersion: string; reportedVersion: string; reportedStatus?: string; healthTimeoutMs?: number }) {
|
||||
mkdirSync(path.dirname(fixture.statePath), { recursive: true });
|
||||
writeFileSync(fixture.lockPath, JSON.stringify({ pid: process.pid, taskId: fixture.taskId, createdAt: new Date().toISOString() }));
|
||||
writeFileSync(path.join(fixture.stagedRoot, "dist", "index.js"), appScript(options.reportedVersion, port, pidFile));
|
||||
writeFileSync(path.join(fixture.stagedRoot, "dist", "index.js"), appScript(options.reportedVersion, port, pidFile, options.reportedStatus));
|
||||
writeFileSync(fixture.planPath, JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
taskId: fixture.taskId,
|
||||
@@ -123,6 +126,21 @@ async function stopPidFile(pidFile: string): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
test("a runner refused by another lock owner leaves its files and state untouched", async t => {
|
||||
const fixture = runnerFixture(t);
|
||||
writePlan(fixture, await availablePort(), fixture.pidFile, { targetVersion: "2.0.0", reportedVersion: "2.0.0" });
|
||||
const owner = JSON.stringify({ pid: process.pid, taskId: "recovery_owner", createdAt: new Date().toISOString() });
|
||||
writeFileSync(fixture.lockPath, owner);
|
||||
writeFileSync(fixture.statePath, JSON.stringify({ schemaVersion: 1, task: null }));
|
||||
const before = readFileSync(fixture.statePath, "utf8");
|
||||
assert.equal(await runRestartPlan(fixture.planPath), 1);
|
||||
assert.equal(readFileSync(fixture.statePath, "utf8"), before);
|
||||
assert.equal(readFileSync(fixture.lockPath, "utf8"), owner);
|
||||
assert.equal(existsSync(fixture.backupDir), false);
|
||||
assert.equal(existsSync(fixture.pidFile), false);
|
||||
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "1.0.0");
|
||||
});
|
||||
|
||||
test("a healthy target version completes the swap and leaves persistent state alone", { timeout: 20_000 }, async t => {
|
||||
const fixture = runnerFixture(t);
|
||||
const port = await availablePort();
|
||||
@@ -148,6 +166,57 @@ test("a healthy target version completes the swap and leaves persistent state al
|
||||
await waitFor(() => existsSync(fixture.pidFile));
|
||||
});
|
||||
|
||||
test("a failed in-process rollback is persisted as a rollback failure", { timeout: 20_000 }, async t => {
|
||||
const fixture = runnerFixture(t);
|
||||
const port = await availablePort();
|
||||
writePlan(fixture, port, fixture.pidFile, { targetVersion: "2.0.0", reportedVersion: "2.0.0" });
|
||||
const originalRename = fs.renameSync;
|
||||
t.after(() => {
|
||||
fs.renameSync = originalRename;
|
||||
syncBuiltinESMExports();
|
||||
setCodeSwapCopyForTests(null);
|
||||
});
|
||||
const exdev = () => Object.assign(new Error("cross-device link"), { code: "EXDEV" });
|
||||
fs.renameSync = ((from, to) => {
|
||||
if (from === path.join(fixture.rootDir, "dist") && to === path.join(fixture.backupDir, "dist")) throw exdev();
|
||||
if (from === path.join(fixture.stagedRoot, "dist") && to === path.join(fixture.rootDir, "dist")) throw new Error("simulated staging failure");
|
||||
if (from === path.join(fixture.backupDir, "dist") && to === path.join(fixture.rootDir, "dist")) throw exdev();
|
||||
return originalRename(from, to);
|
||||
}) as typeof fs.renameSync;
|
||||
syncBuiltinESMExports();
|
||||
let copies = 0;
|
||||
setCodeSwapCopyForTests((from, to) => {
|
||||
copies += 1;
|
||||
if (copies === 2) throw new Error("simulated rollback copy failure");
|
||||
fs.cpSync(from, to, { recursive: true });
|
||||
});
|
||||
|
||||
assert.equal(await runRestartPlan(fixture.planPath), 1);
|
||||
const state = JSON.parse(readFileSync(fixture.statePath, "utf8"));
|
||||
assert.equal(state.task.status, "failed");
|
||||
assert.equal(state.task.rolledBack, false);
|
||||
assert.equal(state.task.errorCode, "UPDATE_ROLLBACK_FAILED");
|
||||
assert.equal(existsSync(path.join(fixture.rootDir, "dist", "index.js")), false);
|
||||
assert.equal(existsSync(path.join(fixture.backupDir, "dist", "index.js")), true);
|
||||
});
|
||||
|
||||
test("a target reporting the expected version with an error status is not accepted as healthy", { timeout: 20_000 }, async t => {
|
||||
const fixture = runnerFixture(t);
|
||||
const port = await availablePort();
|
||||
writePlan(fixture, port, fixture.pidFile, {
|
||||
targetVersion: "2.0.0", reportedVersion: "2.0.0", reportedStatus: "error", healthTimeoutMs: 500,
|
||||
});
|
||||
writeFileSync(path.join(fixture.rootDir, "dist", "index.js"), appScript("1.0.0", port, fixture.pidFile));
|
||||
t.after(() => stopPidFile(fixture.pidFile));
|
||||
|
||||
assert.equal(await runRestartPlan(fixture.planPath), 1);
|
||||
const state = JSON.parse(readFileSync(fixture.statePath, "utf8"));
|
||||
assert.equal(state.task.status, "failed");
|
||||
assert.equal(state.task.rolledBack, true);
|
||||
assert.equal(state.task.errorCode, "UPDATE_HEALTH_CHECK_FAILED");
|
||||
assert.match(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), /version: "1\.0\.0"/);
|
||||
});
|
||||
|
||||
test("a failed health check rolls back to the previous code and reports the failure", { timeout: 20_000 }, async t => {
|
||||
const fixture = runnerFixture(t);
|
||||
const port = await availablePort();
|
||||
|
||||
@@ -217,7 +217,7 @@ async function waitForVersion(plan: RestartPlan, version: string, timeoutMs: num
|
||||
if (last?.status === "ok" && last.version === version) return last;
|
||||
await sleep(plan.pollIntervalMs);
|
||||
}
|
||||
return last?.version === version ? last : null;
|
||||
return null;
|
||||
}
|
||||
|
||||
function startApp(plan: RestartPlan): ChildProcess {
|
||||
@@ -273,8 +273,6 @@ export async function runRestartPlan(planPath: string): Promise<number> {
|
||||
const state = new StateWriter(plan);
|
||||
let swapped = false;
|
||||
let newApp: ChildProcess | undefined;
|
||||
state.status("restarting");
|
||||
state.step("restart", "running");
|
||||
// Take over the update lock before doing anything else. The parent process
|
||||
// is about to exit and its lock would otherwise have a dead pid, letting a
|
||||
// second instance starting in this window roll the healthy code back.
|
||||
@@ -285,6 +283,8 @@ export async function runRestartPlan(planPath: string): Promise<number> {
|
||||
} catch (error) {
|
||||
throw new RunnerError("UPDATE_LOCK_FAILED", error instanceof Error ? error.message : "The update lock could not be taken over.");
|
||||
}
|
||||
state.status("restarting");
|
||||
state.step("restart", "running");
|
||||
await waitForParent(plan.waitForPid, plan.parentTimeoutMs);
|
||||
state.step("swap", "running");
|
||||
swapCode(plan.rootDir, plan.stagedRoot, plan.backupDir);
|
||||
@@ -303,12 +303,21 @@ export async function runRestartPlan(planPath: string): Promise<number> {
|
||||
try { rmSync(plan.stagedRoot, { recursive: true, force: true }); } catch { /* Best effort. */ }
|
||||
return 0;
|
||||
} catch (error) {
|
||||
// A recovery process or another update owns the tree. Without ownership
|
||||
// this runner must not rewrite its state or start an app during recovery.
|
||||
if (!releaseLock) return 1;
|
||||
await stopApp(newApp);
|
||||
const code = error instanceof RunnerError || error instanceof CodeSwapError
|
||||
? error.code
|
||||
: "UPDATE_RESTART_FAILED";
|
||||
const message = error instanceof Error ? error.message : "The update could not be completed.";
|
||||
state.step("restart", "failed", message);
|
||||
if (!swapped && code === "UPDATE_ROLLBACK_FAILED") {
|
||||
state.rolledBack(false);
|
||||
state.status("failed", { code, message });
|
||||
releaseLock?.();
|
||||
return 1;
|
||||
}
|
||||
let rolledBack = !swapped;
|
||||
if (swapped) {
|
||||
state.step("rollback", "running");
|
||||
|
||||
@@ -2,12 +2,13 @@ import assert from "node:assert/strict";
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { createServer } from "node:net";
|
||||
import test, { type TestContext } from "node:test";
|
||||
import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { UpdateService } from "./update-service.js";
|
||||
import { CODE_ENTRIES } from "./code-swap.js";
|
||||
import { CODE_ENTRIES, swapCode } from "./code-swap.js";
|
||||
import { acquireUpdateLock, updateLockIsHeld } from "./update-state.js";
|
||||
|
||||
const SOURCE_DIR = path.dirname(fileURLToPath(import.meta.url));
|
||||
const REPO_ROOT = path.resolve(SOURCE_DIR, "..", "..");
|
||||
@@ -17,6 +18,71 @@ const TASK_ID = "upd_sigkill_window";
|
||||
|
||||
const logger = { debug() {}, info() {}, warn() {}, error() {}, child() { return this; } };
|
||||
|
||||
for (const lockKind of ["live", "unreadable"] as const) {
|
||||
test(`launcher preserves a target while the update lock is ${lockKind}`, { timeout: 15_000, skip: process.platform !== "linux" }, async t => {
|
||||
const fixture = buildFixture(t, await availablePort());
|
||||
swapCode(fixture.rootDir, fixture.stagedRoot, fixture.backupDir);
|
||||
const lockPath = path.join(fixture.dataDir, "updates", "update.lock");
|
||||
if (lockKind === "live") {
|
||||
const release = acquireUpdateLock(lockPath, TASK_ID);
|
||||
t.after(release);
|
||||
assert.equal(updateLockIsHeld(lockPath, TASK_ID), true);
|
||||
} else {
|
||||
writeFileSync(lockPath, "{invalid");
|
||||
}
|
||||
const before = readFileSync(lockPath, "utf8");
|
||||
const app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], {
|
||||
cwd: fixture.rootDir, env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir }, stdio: "ignore",
|
||||
});
|
||||
t.after(() => stop(app));
|
||||
await waitFor(() => app.exitCode !== null, "launcher did not refuse the held update lock", 5_000);
|
||||
assert.equal(app.exitCode, 75);
|
||||
assert.equal(readFileSync(lockPath, "utf8"), before);
|
||||
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.4.0");
|
||||
assert.equal(JSON.parse(readFileSync(path.join(fixture.backupDir, "package.json"), "utf8")).version, "0.3.2");
|
||||
});
|
||||
}
|
||||
|
||||
test("concurrent launchers cannot restore the same interrupted tree together", { timeout: 20_000, skip: process.platform !== "linux" }, async t => {
|
||||
const port = await availablePort();
|
||||
const fixture = buildFixture(t, port);
|
||||
swapCode(fixture.rootDir, fixture.stagedRoot, fixture.backupDir);
|
||||
const bin = path.join(fixture.directory, "bin");
|
||||
mkdirSync(bin);
|
||||
// Pause the first real restore at mv, without adding a production test hook.
|
||||
writeFileSync(path.join(bin, "mv"), `#!/bin/sh
|
||||
printf '%s' "$$" > "$RECOVERY_TEST_BARRIER/entered"
|
||||
attempt=0
|
||||
while [ ! -f "$RECOVERY_TEST_BARRIER/resume" ] && [ "$attempt" -lt 200 ]; do
|
||||
sleep 0.05
|
||||
attempt=$((attempt + 1))
|
||||
done
|
||||
exec /bin/mv "$@"
|
||||
`, { mode: 0o755 });
|
||||
const env = { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir,
|
||||
PATH: `${bin}${path.delimiter}${process.env.PATH}`, RECOVERY_TEST_BARRIER: fixture.barrierDir };
|
||||
const first = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], { cwd: fixture.rootDir, env, stdio: "ignore" });
|
||||
let second: ChildProcess | undefined;
|
||||
try {
|
||||
await waitFor(() => existsSync(path.join(fixture.barrierDir, "entered")), "first launcher did not start restoring");
|
||||
const lockPath = path.join(fixture.dataDir, "updates", "update.lock");
|
||||
assert.equal(updateLockIsHeld(lockPath), true);
|
||||
const owner = readFileSync(lockPath, "utf8");
|
||||
second = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], { cwd: fixture.rootDir, env, stdio: "ignore" });
|
||||
await waitFor(() => second!.exitCode !== null, "second launcher did not refuse concurrent recovery", 5_000);
|
||||
assert.equal(second.exitCode, 75);
|
||||
assert.equal(readFileSync(lockPath, "utf8"), owner);
|
||||
writeFileSync(path.join(fixture.barrierDir, "resume"), "");
|
||||
await waitFor(() => healthVersion(port).then(version => version === "0.3.2"), "first launcher did not finish recovery");
|
||||
assert.equal(existsSync(lockPath), false);
|
||||
} finally {
|
||||
// Stop children before buildFixture's after hook removes their files.
|
||||
writeFileSync(path.join(fixture.barrierDir, "resume"), "");
|
||||
stop(first); stop(second);
|
||||
await waitFor(() => !processAlive(first.pid) && !processAlive(second?.pid), "recovery processes did not stop", 5_000);
|
||||
}
|
||||
});
|
||||
|
||||
// Exercise a kill after every old entry's rename, before the manifest is
|
||||
// updated. In particular the backup is still partial for the first entries.
|
||||
for (const entry of CODE_ENTRIES) {
|
||||
@@ -81,6 +147,11 @@ async function healthVersion(port: number): Promise<string | null> {
|
||||
}
|
||||
}
|
||||
|
||||
function startedVersion(fixture: Fixture): string | null {
|
||||
const { startedFile } = JSON.parse(readFileSync(fixture.markerFiles.config, "utf8")) as { startedFile: string };
|
||||
return existsSync(startedFile) ? readFileSync(startedFile, "utf8") : null;
|
||||
}
|
||||
|
||||
function processAlive(pid: number | undefined): boolean {
|
||||
if (!pid || pid <= 0) return false;
|
||||
try { process.kill(pid, 0); return true; }
|
||||
@@ -309,6 +380,83 @@ test(
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
"launcher resumes a partial current backup instead of installing a stale complete backup",
|
||||
{ timeout: 20_000 },
|
||||
async t => {
|
||||
const port = await availablePort();
|
||||
const fixture = buildFixture(t, port, true);
|
||||
const staleDir = path.join(fixture.dataDir, "updates", "backups", "aaa_stale_backup");
|
||||
mkdirSync(fixture.backupDir, { recursive: true });
|
||||
renameSync(path.join(fixture.rootDir, "dist"), path.join(fixture.backupDir, "dist"));
|
||||
writeFileSync(path.join(fixture.backupDir, ".webspeak-swap.json"), JSON.stringify({ schemaVersion: 1, entries: ["dist"] }));
|
||||
let app: ChildProcess | undefined;
|
||||
t.after(() => stop(app));
|
||||
|
||||
app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], {
|
||||
cwd: fixture.rootDir,
|
||||
env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir },
|
||||
stdio: "ignore",
|
||||
});
|
||||
await waitFor(() => startedVersion(fixture) !== null, "launcher did not resume the partial current backup");
|
||||
assert.equal(startedVersion(fixture), "0.3.2");
|
||||
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.3.2");
|
||||
assert.equal(JSON.parse(readFileSync(path.join(staleDir, "package.json"), "utf8")).version, "0.1.0");
|
||||
assert.equal(existsSync(path.join(staleDir, "dist", "index.js")), true);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
"launcher resumes a rollback that already consumed part of the current backup",
|
||||
{ timeout: 20_000 },
|
||||
async t => {
|
||||
const port = await availablePort();
|
||||
const fixture = buildFixture(t, port);
|
||||
swapCode(fixture.rootDir, fixture.stagedRoot, fixture.backupDir);
|
||||
for (const entry of ["runtime", "package.json"]) {
|
||||
rmSync(path.join(fixture.rootDir, entry), { recursive: true, force: true });
|
||||
renameSync(path.join(fixture.backupDir, entry), path.join(fixture.rootDir, entry));
|
||||
}
|
||||
mkdirSync(path.join(fixture.backupDir, "rejected"), { recursive: true });
|
||||
renameSync(path.join(fixture.rootDir, "dist"), path.join(fixture.backupDir, "rejected", "dist"));
|
||||
let app: ChildProcess | undefined;
|
||||
t.after(() => stop(app));
|
||||
|
||||
app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], {
|
||||
cwd: fixture.rootDir,
|
||||
env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir },
|
||||
stdio: "ignore",
|
||||
});
|
||||
await waitFor(() => startedVersion(fixture) !== null, "launcher did not resume the interrupted rollback");
|
||||
assert.equal(startedVersion(fixture), "0.3.2");
|
||||
assert.equal(existsSync(path.join(fixture.rootDir, "dist", "index.js")), true);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
"launcher rolls back an active fully swapped tree before starting the target",
|
||||
{ timeout: 20_000 },
|
||||
async t => {
|
||||
const port = await availablePort();
|
||||
const fixture = buildFixture(t, port);
|
||||
writeFileSync(path.join(fixture.stagedRoot, "dist", "index.js"), appScript());
|
||||
copyFileSync(process.execPath, path.join(fixture.stagedRoot, "runtime", "node"));
|
||||
chmodSync(path.join(fixture.stagedRoot, "runtime", "node"), 0o755);
|
||||
swapCode(fixture.rootDir, fixture.stagedRoot, fixture.backupDir);
|
||||
let app: ChildProcess | undefined;
|
||||
t.after(() => stop(app));
|
||||
|
||||
app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], {
|
||||
cwd: fixture.rootDir,
|
||||
env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir },
|
||||
stdio: "ignore",
|
||||
});
|
||||
await waitFor(() => startedVersion(fixture) !== null, "launcher did not resolve the active swapped tree");
|
||||
assert.equal(startedVersion(fixture), "0.3.2");
|
||||
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.3.2");
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
"recovery prefers the in-progress task backup over an older lexicographically-first backup",
|
||||
{ timeout: 40_000 },
|
||||
|
||||
@@ -143,6 +143,7 @@ export function createPackageFiles(root: string, version: string, extra: Record<
|
||||
writeFileSync(path.join(root, "dist", "index.js"), "// package entry\n", "utf8");
|
||||
writeFileSync(path.join(root, "web", "dist", "index.html"), "<!doctype html>\n", "utf8");
|
||||
writeFileSync(path.join(root, "runtime", "node"), "#!/bin/sh\nexit 0\n", { encoding: "utf8", mode: 0o755 });
|
||||
writeFileSync(path.join(root, "start-webspeak.sh"), "#!/bin/sh\nexit 0\n", { encoding: "utf8", mode: 0o755 });
|
||||
for (const [relative, contents] of Object.entries(extra)) {
|
||||
const target = path.join(root, relative);
|
||||
mkdirSync(path.dirname(target), { recursive: true });
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn } from "node:child_process";
|
||||
import { once } from "node:events";
|
||||
import fs from "node:fs";
|
||||
import { syncBuiltinESMExports } from "node:module";
|
||||
import { Writable } from "node:stream";
|
||||
import test, { type TestContext } from "node:test";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
@@ -8,6 +11,7 @@ import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { CHECKSUM_ASSET_NAME, OFFICIAL_REPOSITORY } from "./releases.js";
|
||||
import { swapCode } from "./code-swap.js";
|
||||
import { UpdateError, UpdateService, type UpdateErrorCode, type UpdateServiceOptions } from "./update-service.js";
|
||||
import { createPackageFiles, createTarGz, sha256Hex, type TarFixtureEntry } from "./test-support.js";
|
||||
import { acquireUpdateLock, readUpdateState, writeUpdateState } from "./update-state.js";
|
||||
@@ -67,6 +71,7 @@ function packageArchive(version: string, extra: TarFixtureEntry[] = []): Buffer
|
||||
{ name: "webspeak/web/dist/index.html", data: "<!doctype html>\n" },
|
||||
{ name: "webspeak/node_modules/.keep", data: "" },
|
||||
{ name: "webspeak/runtime/node", data: "#!/bin/sh\nexit 0\n", mode: 0o755 },
|
||||
{ name: "webspeak/start-webspeak.sh", data: "#!/bin/sh\nexit 0\n", mode: 0o755 },
|
||||
...extra,
|
||||
]);
|
||||
}
|
||||
@@ -269,6 +274,142 @@ test("unsafe archives are refused before any code is staged", async t => {
|
||||
assert.equal(state.task?.errorCode, "UPDATE_ARCHIVE_UNSAFE");
|
||||
});
|
||||
|
||||
test("an asynchronous download write failure rejects the update without crashing the process", async t => {
|
||||
const archive = packageArchive("0.4.0");
|
||||
const checksums = Buffer.from(checksumText(ASSET_NAME, archive));
|
||||
const release = releaseJson({
|
||||
version: "0.4.0",
|
||||
assets: [
|
||||
{ name: ASSET_NAME, data: archive },
|
||||
{ name: CHECKSUM_ASSET_NAME, data: checksums },
|
||||
],
|
||||
});
|
||||
const originalCreateWriteStream = fs.createWriteStream;
|
||||
t.after(() => {
|
||||
fs.createWriteStream = originalCreateWriteStream;
|
||||
syncBuiltinESMExports();
|
||||
});
|
||||
fs.createWriteStream = (() => new Writable({
|
||||
write(_chunk, _encoding, callback) {
|
||||
setImmediate(() => callback(new Error("simulated ENOSPC")));
|
||||
},
|
||||
})) as unknown as typeof fs.createWriteStream;
|
||||
syncBuiltinESMExports();
|
||||
const cancelled = new Set<string>();
|
||||
const responses: Response[] = [];
|
||||
const signals: AbortSignal[] = [];
|
||||
const stalledBody = (url: string) => new ReadableStream({
|
||||
start(controller) { controller.enqueue(new Uint8Array([1, 2, 3])); },
|
||||
pull() { return new Promise(() => {}); },
|
||||
cancel() { cancelled.add(url); },
|
||||
});
|
||||
const fetch = (async (input: string | URL | Request, init?: RequestInit) => {
|
||||
if (String(input) === RELEASE_LIST_URL) return new Response(JSON.stringify([release]), { status: 200 });
|
||||
signals.push(init!.signal!);
|
||||
const response = new Response(stalledBody(String(input)), { status: 200 });
|
||||
responses.push(response);
|
||||
return response;
|
||||
}) as typeof globalThis.fetch;
|
||||
const { service, launched } = createService(t, [], new Map(), { fetch });
|
||||
|
||||
await assert.rejects(service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_DOWNLOAD_FAILED"));
|
||||
assert.equal(launched.length, 0);
|
||||
assert.equal(cancelled.size, 2);
|
||||
assert.ok(signals.every(signal => signal.aborted));
|
||||
assert.ok(responses.every(response => !response.body!.locked));
|
||||
});
|
||||
|
||||
test("a rejected asset aborts its stalled sibling before update cleanup returns", { timeout: 5_000 }, async t => {
|
||||
const archive = packageArchive("0.4.0");
|
||||
const checksums = Buffer.from(checksumText(ASSET_NAME, archive));
|
||||
const release = releaseJson({ version: "0.4.0", assets: [{ name: ASSET_NAME, data: archive }, { name: CHECKSUM_ASSET_NAME, data: checksums }] });
|
||||
const responses: Response[] = [], signals: AbortSignal[] = [];
|
||||
let cancelled = 0;
|
||||
const { service, dataDir } = createService(t, [], new Map(), { fetch: (async (input, init) => {
|
||||
const url = String(input);
|
||||
if (url === RELEASE_LIST_URL) return new Response(JSON.stringify([release]));
|
||||
signals.push(init!.signal!);
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
start(controller) { controller.enqueue(new Uint8Array([1])); },
|
||||
pull() { return new Promise(() => {}); },
|
||||
cancel() { cancelled++; },
|
||||
});
|
||||
const response = new Response(body, { headers: url.endsWith(ASSET_NAME) ? { "content-length": String(513 * 1024 * 1024) } : {} });
|
||||
responses.push(response);
|
||||
return response;
|
||||
}) as typeof fetch });
|
||||
await assert.rejects(service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_DOWNLOAD_TOO_LARGE"));
|
||||
assert.equal(cancelled, 2);
|
||||
assert.ok(signals.every(signal => signal.aborted));
|
||||
assert.ok(responses.every(response => !response.body!.locked));
|
||||
assert.equal(existsSync(path.join(dataDir, "updates", "update.lock")), false);
|
||||
});
|
||||
|
||||
test("download rejection cancels its body and releases the reader, including unread responses", async t => {
|
||||
for (const declaredSize of [false, true]) {
|
||||
let cancelled = false;
|
||||
let signal: AbortSignal | null | undefined;
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
start(controller) { controller.enqueue(new Uint8Array([1, 2, 3])); },
|
||||
cancel() { cancelled = true; },
|
||||
});
|
||||
const { service } = createService(t, [], new Map(), { fetch: (async (_input, init) => {
|
||||
signal = init?.signal;
|
||||
return new Response(body, { headers: declaredSize ? { "content-length": "3" } : {} });
|
||||
}) as typeof fetch });
|
||||
const target = path.join(workspace(t), "asset");
|
||||
// A small injected byte limit exercises the production rejection path
|
||||
// without allocating or writing a 512 MiB package in a regression test.
|
||||
const download = service as unknown as { downloadAsset(asset: { name: string; url: string; size: number; digest: null }, destination: string, limit: number): Promise<unknown> };
|
||||
await assert.rejects(download.downloadAsset({ name: ASSET_NAME,
|
||||
url: `https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${ASSET_NAME}`, size: 3, digest: null }, target, 1),
|
||||
updateErrorCode("UPDATE_DOWNLOAD_TOO_LARGE"));
|
||||
assert.equal(cancelled, true);
|
||||
assert.equal(body.locked, false);
|
||||
assert.equal(signal?.aborted, true);
|
||||
assert.equal(existsSync(target), false);
|
||||
assert.equal(existsSync(`${target}.${process.pid}.tmp`), false);
|
||||
}
|
||||
});
|
||||
|
||||
test("a successful download releases its reader without aborting the request", async t => {
|
||||
let signal: AbortSignal | null | undefined;
|
||||
const response = new Response(new Uint8Array([1, 2, 3]));
|
||||
const { service } = createService(t, [], new Map(), { fetch: (async (_input, init) => {
|
||||
signal = init?.signal; return response;
|
||||
}) as typeof fetch });
|
||||
const target = path.join(workspace(t), "asset");
|
||||
const download = service as unknown as { downloadAsset(asset: { name: string; url: string; size: number; digest: null }, destination: string, limit: number): Promise<unknown> };
|
||||
await download.downloadAsset({ name: ASSET_NAME,
|
||||
url: `https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${ASSET_NAME}`, size: 3, digest: null }, target, 4);
|
||||
assert.deepEqual(readFileSync(target), Buffer.from([1, 2, 3]));
|
||||
assert.equal(response.body!.locked, false);
|
||||
assert.equal(signal?.aborted, false);
|
||||
});
|
||||
|
||||
test("a download redirected outside GitHub is refused before it is written", async t => {
|
||||
const archive = packageArchive("0.4.0");
|
||||
const checksums = Buffer.from(checksumText(ASSET_NAME, archive));
|
||||
const release = releaseJson({
|
||||
version: "0.4.0",
|
||||
assets: [
|
||||
{ name: ASSET_NAME, data: archive },
|
||||
{ name: CHECKSUM_ASSET_NAME, data: checksums },
|
||||
],
|
||||
});
|
||||
const fetch = (async (input: string | URL | Request) => {
|
||||
const url = String(input);
|
||||
if (url === RELEASE_LIST_URL) return new Response(JSON.stringify([release]), { status: 200 });
|
||||
const response = new Response(url.endsWith(ASSET_NAME) ? new Uint8Array(archive) : new Uint8Array(checksums), { status: 200 });
|
||||
if (url.endsWith(ASSET_NAME)) Object.defineProperty(response, "url", { value: "https://example.invalid/package.tar.gz" });
|
||||
return response;
|
||||
}) as typeof globalThis.fetch;
|
||||
const { service, launched } = createService(t, [], new Map(), { fetch });
|
||||
|
||||
await assert.rejects(service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_RELEASE_UNAVAILABLE"));
|
||||
assert.equal(launched.length, 0);
|
||||
});
|
||||
|
||||
test("a verified package is staged, persisted and handed to the restart runner", async t => {
|
||||
const archive = packageArchive("0.4.0");
|
||||
const checksums = Buffer.from(checksumText(ASSET_NAME, archive));
|
||||
@@ -400,7 +541,7 @@ test("initialization restores the previous code from an interrupted swap backup"
|
||||
writeFileSync(lockPath, JSON.stringify({ pid: 0, taskId, createdAt: "2026-01-01T00:00:00.000Z" }));
|
||||
|
||||
const restarted = new UpdateService({
|
||||
rootDir: fixture.rootDir, dataDir: fixture.dataDir, currentVersion: "0.4.0", logger,
|
||||
rootDir: fixture.rootDir, dataDir: fixture.dataDir, currentVersion: "0.3.2", logger,
|
||||
platform: "linux", architecture: "x64", env: {}, isDocker: false, fetch: fakeFetch([], new Map()),
|
||||
now: () => new Date("2026-01-01T00:10:00.000Z"),
|
||||
});
|
||||
@@ -415,6 +556,39 @@ test("initialization restores the previous code from an interrupted swap backup"
|
||||
assert.equal(existsSync(lockPath), false);
|
||||
});
|
||||
|
||||
test("initialization keeps a complete target tree consistent with the running target version", t => {
|
||||
const fixture = createService(t, [], new Map());
|
||||
const taskId = "upd_complete_target";
|
||||
const statePath = path.join(fixture.dataDir, "updates", "state.json");
|
||||
const lockPath = path.join(fixture.dataDir, "updates", "update.lock");
|
||||
const backupDir = path.join(fixture.dataDir, "updates", "backups", taskId);
|
||||
const stagedRoot = path.join(fixture.dataDir, "updates", "tasks", taskId, "staged");
|
||||
createPackageFiles(stagedRoot, "0.4.0", { "dist/index.js": "// complete target code\n" });
|
||||
swapCode(fixture.rootDir, stagedRoot, backupDir);
|
||||
writeUpdateState(statePath, {
|
||||
schemaVersion: 1,
|
||||
task: {
|
||||
id: taskId, status: "restarting", fromVersion: "0.3.2", targetVersion: "0.4.0",
|
||||
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
|
||||
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
|
||||
},
|
||||
});
|
||||
writeFileSync(lockPath, JSON.stringify({ pid: 0, taskId, createdAt: "2026-01-01T00:00:00.000Z" }));
|
||||
|
||||
const restarted = new UpdateService({
|
||||
rootDir: fixture.rootDir, dataDir: fixture.dataDir, currentVersion: "0.4.0", logger,
|
||||
platform: "linux", architecture: "x64", env: {}, isDocker: false, fetch: fakeFetch([], new Map()),
|
||||
now: () => new Date("2026-01-01T00:10:00.000Z"),
|
||||
});
|
||||
restarted.initialize();
|
||||
|
||||
assert.equal(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), "// complete target code\n");
|
||||
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.4.0");
|
||||
assert.equal(restarted.getStatus().task?.status, "succeeded");
|
||||
assert.equal(restarted.getStatus().task?.rolledBack, false);
|
||||
assert.equal(existsSync(lockPath), false);
|
||||
});
|
||||
|
||||
test("initialization keeps a live task but reconciles it once its process is gone", async t => {
|
||||
const fixture = createService(t, [], new Map());
|
||||
const running = {
|
||||
@@ -444,6 +618,30 @@ test("initialization keeps a live task but reconciles it once its process is gon
|
||||
assert.equal(restarted.getStatus().task?.errorCode, "UPDATE_INTERRUPTED");
|
||||
});
|
||||
|
||||
test("initialization preserves an interrupted tree while a launcher recovery owns the lock", t => {
|
||||
const fixture = createService(t, [], new Map());
|
||||
const taskId = "upd_launcher_recovery";
|
||||
const updates = path.join(fixture.dataDir, "updates");
|
||||
const staged = path.join(updates, "tasks", taskId, "staged");
|
||||
createPackageFiles(staged, "0.4.0");
|
||||
const backup = path.join(updates, "backups", taskId);
|
||||
swapCode(fixture.rootDir, staged, backup);
|
||||
writeUpdateState(path.join(updates, "state.json"), { schemaVersion: 1, task: {
|
||||
id: taskId, status: "restarting", fromVersion: "0.3.2", targetVersion: "0.4.0",
|
||||
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
|
||||
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
|
||||
} });
|
||||
const lockPath = path.join(updates, "update.lock");
|
||||
const release = acquireUpdateLock(lockPath, "recovery_other_launcher");
|
||||
t.after(release);
|
||||
const owner = readFileSync(lockPath, "utf8");
|
||||
fixture.service.initialize();
|
||||
assert.equal(readFileSync(lockPath, "utf8"), owner);
|
||||
assert.equal(fixture.service.getStatus().task?.status, "restarting");
|
||||
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.4.0");
|
||||
assert.equal(JSON.parse(readFileSync(path.join(backup, "package.json"), "utf8")).version, "0.3.2");
|
||||
});
|
||||
|
||||
test("a replacement app can update again after the runner finishes its cached task", async t => {
|
||||
const fixture = createService(t, [], new Map());
|
||||
const statePath = path.join(fixture.dataDir, "updates", "state.json");
|
||||
|
||||
@@ -9,7 +9,7 @@ import { fileURLToPath } from "node:url";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { UpdateCheckView, UpdateReleaseView, UpdateStatusView, UpdateTaskStatus, UpdateTaskView } from "../shared/update.js";
|
||||
import { ArchiveError, extractReleaseArchive } from "./archive.js";
|
||||
import { CodeSwapError, locatePackageRoot, restoreCode } from "./code-swap.js";
|
||||
import { CodeSwapError, locatePackageRoot, restoreCode, validateStagedPackage } from "./code-swap.js";
|
||||
import { detectDeployment, releaseAssetName, type DeploymentInfo } from "./deployment.js";
|
||||
import {
|
||||
assertOfficialDownloadUrl, CHECKSUM_ASSET_NAME, GitHubReleaseSource, ReleaseSourceError,
|
||||
@@ -162,7 +162,7 @@ export class UpdateService {
|
||||
const task = this.state.task;
|
||||
// A live lock owner (for example a second process starting by mistake)
|
||||
// must not have its in-flight task reconciled as interrupted.
|
||||
if (!task || !isActiveTaskStatus(task.status) || !updateLockIsHeld(this.lockPath, task.id)) {
|
||||
if (!task || !isActiveTaskStatus(task.status) || !updateLockIsHeld(this.lockPath)) {
|
||||
const recovered = task && isActiveTaskStatus(task.status) ? this.recoverInterruptedSwap(task) : null;
|
||||
const changed = recovered !== null || reconcileInterruptedState(this.state, this.options.currentVersion, this.now().toISOString());
|
||||
if (changed) writeUpdateState(this.statePath, this.state);
|
||||
@@ -184,6 +184,15 @@ export class UpdateService {
|
||||
private recoverInterruptedSwap(task: NonNullable<PersistedUpdateState["task"]>): boolean | null {
|
||||
const backupDir = path.join(this.backupsDir, task.id);
|
||||
if (!existsSync(backupDir)) return null;
|
||||
if (this.options.currentVersion === task.targetVersion) {
|
||||
try {
|
||||
validateStagedPackage(this.options.rootDir, { version: task.targetVersion, platform: this.options.platform });
|
||||
return null;
|
||||
} catch {
|
||||
// A process can read the target version before every target entry is in
|
||||
// place. Fall through to recovery when the on-disk tree is incomplete.
|
||||
}
|
||||
}
|
||||
const now = this.now().toISOString();
|
||||
let restored = false;
|
||||
try {
|
||||
@@ -321,10 +330,22 @@ export class UpdateService {
|
||||
const archivePath = path.join(downloadDirectory, assetName);
|
||||
const checksumPath = path.join(downloadDirectory, CHECKSUM_ASSET_NAME);
|
||||
this.startStep(task, "download");
|
||||
const [archive, checksumFile] = await Promise.all([
|
||||
this.downloadAsset(asset, archivePath, DOWNLOAD_LIMIT),
|
||||
this.downloadAsset(checksumAsset, checksumPath, CHECKSUM_LIMIT),
|
||||
]);
|
||||
const downloadsController = new AbortController();
|
||||
const downloads = [
|
||||
this.downloadAsset(asset, archivePath, DOWNLOAD_LIMIT, downloadsController.signal),
|
||||
this.downloadAsset(checksumAsset, checksumPath, CHECKSUM_LIMIT, downloadsController.signal),
|
||||
];
|
||||
let archive: DownloadResult;
|
||||
let checksumFile: DownloadResult;
|
||||
try {
|
||||
[archive, checksumFile] = await Promise.all(downloads);
|
||||
} catch (error) {
|
||||
downloadsController.abort();
|
||||
// No sibling may still hold a response reader or write into the task
|
||||
// directory when applyUpdate's failure cleanup removes that directory.
|
||||
await Promise.allSettled(downloads);
|
||||
throw error;
|
||||
}
|
||||
this.finishStep(task, "download", "succeeded");
|
||||
this.updateTaskStatus(task, "verifying");
|
||||
this.startStep(task, "checksum");
|
||||
@@ -467,50 +488,76 @@ export class UpdateService {
|
||||
if (value.toLowerCase() !== actual) throw new UpdateError("UPDATE_DIGEST_MISMATCH", "The package does not match the GitHub asset digest.", 422);
|
||||
}
|
||||
|
||||
private async downloadAsset(asset: ReleaseAsset, destination: string, limit: number): Promise<DownloadResult> {
|
||||
private async downloadAsset(asset: ReleaseAsset, destination: string, limit: number, cancelSignal?: AbortSignal): Promise<DownloadResult> {
|
||||
try { assertOfficialDownloadUrl(asset.url, ...repositoryParts(this.options.repository)); }
|
||||
catch (error) { throw mapError(error); }
|
||||
let response: Response;
|
||||
const controller = new AbortController();
|
||||
const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(this.options.downloadTimeoutMs ?? 300_000), ...(cancelSignal ? [cancelSignal] : [])]);
|
||||
try {
|
||||
response = await this.fetcher(asset.url, {
|
||||
headers: { "user-agent": "WebSpeak-Console-Updater", accept: "application/octet-stream" },
|
||||
signal: AbortSignal.timeout(this.options.downloadTimeoutMs ?? 300_000),
|
||||
signal,
|
||||
});
|
||||
} catch (error) {
|
||||
controller.abort();
|
||||
throw new UpdateError("UPDATE_DOWNLOAD_FAILED", error instanceof Error ? error.message : "The release asset could not be downloaded.", 502);
|
||||
}
|
||||
if (response.url) {
|
||||
try { assertOfficialDownloadUrl(response.url, ...repositoryParts(this.options.repository)); }
|
||||
catch (error) { throw mapError(error); }
|
||||
}
|
||||
if (!response.ok || !response.body) throw new UpdateError("UPDATE_DOWNLOAD_FAILED", `The release asset returned HTTP ${response.status}.`, 502);
|
||||
const declared = Number(response.headers.get("content-length") ?? "");
|
||||
if (Number.isFinite(declared) && declared > limit) throw new UpdateError("UPDATE_DOWNLOAD_TOO_LARGE", "The release asset exceeds the download limit.", 422);
|
||||
const temporary = `${destination}.${process.pid}.tmp`;
|
||||
const hash = createHash("sha256");
|
||||
const stream = createWriteStream(temporary, { mode: 0o600, flags: "wx" });
|
||||
let bytes = 0;
|
||||
let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
|
||||
let stream: ReturnType<typeof createWriteStream> | undefined;
|
||||
let temporary: string | undefined;
|
||||
let onAbort: (() => void) | undefined;
|
||||
try {
|
||||
for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {
|
||||
const buffer = Buffer.from(chunk);
|
||||
if (response.url) {
|
||||
try { assertOfficialDownloadUrl(response.url, ...repositoryParts(this.options.repository)); }
|
||||
catch (error) { throw mapError(error); }
|
||||
}
|
||||
if (!response.ok || !response.body) throw new UpdateError("UPDATE_DOWNLOAD_FAILED", `The release asset returned HTTP ${response.status}.`, 502);
|
||||
const declared = Number(response.headers.get("content-length") ?? "");
|
||||
if (Number.isFinite(declared) && declared > limit) throw new UpdateError("UPDATE_DOWNLOAD_TOO_LARGE", "The release asset exceeds the download limit.", 422);
|
||||
temporary = `${destination}.${process.pid}.tmp`;
|
||||
const hash = createHash("sha256");
|
||||
signal.throwIfAborted();
|
||||
reader = response.body.getReader();
|
||||
stream = createWriteStream(temporary, { mode: 0o600, flags: "wx" });
|
||||
let bytes = 0;
|
||||
let failStream!: (error: Error) => void;
|
||||
const streamFailure = new Promise<Error>((resolve) => { failStream = resolve; });
|
||||
stream.on("error", failStream);
|
||||
onAbort = () => failStream(signal.reason instanceof Error ? signal.reason : new Error("Download aborted."));
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
if (signal.aborted) onAbort();
|
||||
const writer = stream;
|
||||
const finished = new Promise<void>((resolve) => { writer.once("finish", resolve); });
|
||||
while (true) {
|
||||
const next = await Promise.race([reader.read(), streamFailure]);
|
||||
if (next instanceof Error) throw next;
|
||||
if (next.done) break;
|
||||
const buffer = Buffer.from(next.value);
|
||||
bytes += buffer.length;
|
||||
if (bytes > limit) throw new UpdateError("UPDATE_DOWNLOAD_TOO_LARGE", "The release asset exceeds the download limit.", 422);
|
||||
hash.update(buffer);
|
||||
if (!stream.write(buffer)) await new Promise<void>((resolve) => stream.once("drain", resolve));
|
||||
if (!stream.write(buffer)) {
|
||||
const drained = await Promise.race([streamFailure, new Promise<void>((resolve) => { writer.once("drain", resolve); })]);
|
||||
if (drained instanceof Error) throw drained;
|
||||
}
|
||||
}
|
||||
stream.end();
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
stream.once("finish", resolve);
|
||||
stream.once("error", reject);
|
||||
});
|
||||
const streamError = await Promise.race([finished.then(() => null), streamFailure]);
|
||||
if (streamError) throw streamError;
|
||||
await rename(temporary, destination);
|
||||
return { sha256: hash.digest("hex"), bytes };
|
||||
} catch (error) {
|
||||
stream.destroy();
|
||||
await rm(temporary, { force: true }).catch(() => undefined);
|
||||
controller.abort();
|
||||
await (reader ? reader.cancel() : response.body?.cancel())?.catch(() => undefined);
|
||||
stream?.destroy();
|
||||
if (temporary) await rm(temporary, { force: true }).catch(() => undefined);
|
||||
if (error instanceof UpdateError) throw error;
|
||||
throw new UpdateError("UPDATE_DOWNLOAD_FAILED", error instanceof Error ? error.message : "The release asset could not be saved.", 502);
|
||||
} finally {
|
||||
if (onAbort) signal.removeEventListener("abort", onAbort);
|
||||
reader?.releaseLock();
|
||||
}
|
||||
return { sha256: hash.digest("hex"), bytes };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
apply plugin: 'com.android.application'
|
||||
|
||||
def appVersion = project.hasProperty('appVersion') ? project.property('appVersion').toString() : '0.3.2'
|
||||
def appVersionCode = project.hasProperty('appVersionCode') ? project.property('appVersionCode').toString().toInteger() : 302
|
||||
def appVersion = project.hasProperty('appVersion') ? project.property('appVersion').toString() : '0.3.3'
|
||||
def appVersionCode = project.hasProperty('appVersionCode') ? project.property('appVersionCode').toString().toInteger() : 303
|
||||
|
||||
android {
|
||||
namespace = "io.webspeak.client"
|
||||
|
||||
Generated
+2
-2
@@ -25,7 +25,7 @@
|
||||
"vite": "^6.4.3",
|
||||
"vue-tsc": "^2.2.8"
|
||||
},
|
||||
"version": "0.3.2"
|
||||
"version": "0.3.3"
|
||||
},
|
||||
"node_modules/@babel/helper-string-parser": {
|
||||
"version": "7.27.1",
|
||||
@@ -2952,5 +2952,5 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"version": "0.3.2"
|
||||
"version": "0.3.3"
|
||||
}
|
||||
+1
-1
@@ -27,5 +27,5 @@
|
||||
"vite": "^6.4.3",
|
||||
"vue-tsc": "^2.2.8"
|
||||
},
|
||||
"version": "0.3.2"
|
||||
"version": "0.3.3"
|
||||
}
|
||||
@@ -47,16 +47,15 @@
|
||||
:value="inputVolume * 100"
|
||||
:style="rangeStyle(inputVolume, 1)"
|
||||
:aria-label="t('inputVolume')"
|
||||
:disabled="backgroundCallActive"
|
||||
@input="onInputVolume"
|
||||
/>
|
||||
<div class="dock-panel-divider"></div>
|
||||
<label class="dock-switch-row">
|
||||
<span><strong>{{ t("noiseSuppression") }}</strong></span>
|
||||
<select class="noise-suppression-level" :value="backgroundCallActive && noiseSuppressionLevel === 'strong' ? 'standard' : noiseSuppressionLevel" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
|
||||
<select class="noise-suppression-level" :value="noiseSuppressionLevel" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
|
||||
<option value="off">{{ t("noiseSuppressionOff") }}</option>
|
||||
<option value="standard">{{ t("noiseSuppressionStandard") }}</option>
|
||||
<option value="strong" :disabled="backgroundCallActive">{{ t("noiseSuppressionStrong") }}</option>
|
||||
<option value="strong">{{ t("noiseSuppressionStrong") }}</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
@@ -132,12 +131,12 @@ import type { useVoiceWebSocket } from "../../composables/useVoiceWebSocket.js";
|
||||
import type { useWebClientAudioControls } from "../../composables/useWebClientAudioControls.js";
|
||||
|
||||
const props = defineProps<{
|
||||
model: Pick<ReturnType<typeof useVoiceWebSocket>, "microphoneMuted" | "inputVolume" | "outputVolume" | "outputMuted" | "noiseSuppressionLevel" | "accompanimentActive" | "backgroundCallActive">;
|
||||
model: Pick<ReturnType<typeof useVoiceWebSocket>, "microphoneMuted" | "inputVolume" | "outputVolume" | "outputMuted" | "noiseSuppressionLevel" | "accompanimentActive">;
|
||||
controls: Pick<ReturnType<typeof useWebClientAudioControls>, "toggleMicrophone" | "toggleNoiseSuppression" | "onInputVolume" | "onOutputVolume" | "onNoiseSuppressionChange" | "toggleAccompaniment">;
|
||||
t: (key: string) => string;
|
||||
rangeStyle: (value: number, max: number) => Record<string, string>;
|
||||
}>();
|
||||
const { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionLevel, accompanimentActive, backgroundCallActive } = props.model;
|
||||
const { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionLevel, accompanimentActive } = props.model;
|
||||
const { toggleMicrophone, onInputVolume, onOutputVolume, onNoiseSuppressionChange, toggleAccompaniment } = props.controls;
|
||||
const emit = defineEmits<{ settings: []; outputMute: [] }>();
|
||||
</script>
|
||||
@@ -25,15 +25,6 @@
|
||||
:size="19" /></button></header
|
||||
><div class="settings-content">
|
||||
<div class="settings-audio-card">
|
||||
<section class="settings-section">
|
||||
<label class="settings-form-row background-call-setting">
|
||||
<span><strong>{{ t("backgroundCallTitle") }}</strong><small>{{ t("backgroundCallHint") }}</small></span>
|
||||
<input type="checkbox" :checked="backgroundCallEnabled" @change="onBackgroundCallChange" />
|
||||
</label>
|
||||
<p v-if="backgroundCallActive" class="settings-hint background-call-note">{{ t("backgroundCallProcessingHint") }}</p>
|
||||
<p v-if="backgroundCallActive && backgroundCallInterrupted" class="settings-error background-call-note">{{ t("backgroundCallInterrupted") }}</p>
|
||||
<p v-else-if="!backgroundCallActive && backgroundCallEnabled" class="settings-hint background-call-note">{{ t("backgroundCallPending") }}</p>
|
||||
</section>
|
||||
<section class="settings-section"
|
||||
><h3
|
||||
><Icon
|
||||
@@ -87,10 +78,10 @@
|
||||
></div
|
||||
><label class="settings-form-row">
|
||||
<span><strong>{{ t("noiseSuppression") }}</strong><small>{{ t("noiseSuppressionHint") }}</small></span>
|
||||
<select class="noise-suppression-level" :value="backgroundCallActive && noiseSuppressionLevel === 'strong' ? 'standard' : noiseSuppressionLevel" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
|
||||
<select class="noise-suppression-level" :value="noiseSuppressionLevel" :aria-label="t('noiseSuppression')" @change="onNoiseSuppressionChange">
|
||||
<option value="off">{{ t("noiseSuppressionOff") }}</option>
|
||||
<option value="standard">{{ t("noiseSuppressionStandard") }}</option>
|
||||
<option value="strong" :disabled="backgroundCallActive">{{ t("noiseSuppressionStrong") }}</option>
|
||||
<option value="strong">{{ t("noiseSuppressionStrong") }}</option>
|
||||
</select>
|
||||
</label
|
||||
><div class="settings-form-row settings-range-form-row"
|
||||
@@ -106,7 +97,6 @@
|
||||
:value="inputVolume * 100"
|
||||
:style="rangeStyle(inputVolume, 1)"
|
||||
:aria-label="t('inputVolume')"
|
||||
:disabled="backgroundCallActive"
|
||||
@input="onInputVolume"
|
||||
/></div
|
||||
></div
|
||||
@@ -123,13 +113,12 @@
|
||||
:value="voxThreshold * 1000"
|
||||
:style="rangeStyle(voxThreshold, 0.08)"
|
||||
:aria-label="t('voxThreshold')"
|
||||
:disabled="backgroundCallActive"
|
||||
@input="onVoxThreshold"
|
||||
/></div
|
||||
></div
|
||||
><div class="audio-level-row"
|
||||
><span>{{ t("micLevel") }}</span
|
||||
><strong>{{ backgroundCallActive ? t('backgroundCallNative') : `${Math.round(micLevel * 100)}%` }}</strong></div
|
||||
><strong>{{ Math.round(micLevel * 100) }}%</strong></div
|
||||
><div class="audio-level-track"
|
||||
><i :style="{ width: `${Math.round(micLevel * 100)}%` }"></i></div
|
||||
><div class="mic-test"
|
||||
@@ -225,9 +214,7 @@
|
||||
><div class="audio-diagnostic"
|
||||
><span>{{ t("audioStatus") }}</span
|
||||
><strong>{{
|
||||
backgroundCallActive && backgroundCallInterrupted
|
||||
? t("audioSuspended")
|
||||
: backgroundCallActive || audioContextState === "running"
|
||||
audioContextState === "running"
|
||||
? microphoneError
|
||||
? t("audioUnavailable")
|
||||
: t("audioReady")
|
||||
@@ -268,10 +255,6 @@ import type { useVoiceWebSocket } from "../../composables/useVoiceWebSocket.js";
|
||||
import type { useWebClientAudioControls } from "../../composables/useWebClientAudioControls.js";
|
||||
|
||||
type AudioSettingsState = Pick<ReturnType<typeof useVoiceWebSocket>,
|
||||
| "backgroundCallEnabled"
|
||||
| "backgroundCallActive"
|
||||
| "backgroundCallInterrupted"
|
||||
| "setBackgroundCallEnabled"
|
||||
| "inputDevices"
|
||||
| "outputDevices"
|
||||
| "selectedInputDeviceId"
|
||||
@@ -317,10 +300,6 @@ const { onDialogKeydown } = useDialogFocus(dialog, () => emit("close"));
|
||||
|
||||
// The page owns the stable voice refs and audio controller; this dialog only presents them.
|
||||
const {
|
||||
backgroundCallEnabled,
|
||||
backgroundCallActive,
|
||||
backgroundCallInterrupted,
|
||||
setBackgroundCallEnabled,
|
||||
inputDevices,
|
||||
outputDevices,
|
||||
selectedInputDeviceId,
|
||||
@@ -353,10 +332,6 @@ const {
|
||||
toggleMicrophone,
|
||||
} = props.controls;
|
||||
|
||||
function onBackgroundCallChange(event: Event): void {
|
||||
setBackgroundCallEnabled((event.target as HTMLInputElement).checked);
|
||||
}
|
||||
|
||||
const inputDeviceOptions = computed(() => [
|
||||
{ value: "", label: props.t("defaultMicrophone") },
|
||||
...inputDevices.map((device, index) => ({
|
||||
@@ -372,12 +347,3 @@ const outputDeviceOptions = computed(() => [
|
||||
})),
|
||||
]);
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.background-call-setting { display: flex; align-items: flex-start; gap: 16px; }
|
||||
.background-call-setting span { flex: 1; min-width: 0; }
|
||||
.background-call-setting strong, .background-call-setting small { display: block; }
|
||||
.background-call-setting small { margin-top: 6px; font-size: 12px; line-height: 1.65; color: var(--text-muted); }
|
||||
.background-call-setting input { flex: none; width: 18px; height: 18px; margin: 2px 0 0; accent-color: var(--accent); }
|
||||
.background-call-note { font-size: 12px; line-height: 1.65; }
|
||||
</style>
|
||||
@@ -5,8 +5,6 @@ export type { MicrophoneProcessingSettings } from "../voice/microphone-capture.j
|
||||
import { createAudioSinkRouter } from "../voice/audio-sink.js";
|
||||
import { createAccompaniment, type AccompanimentErrorCode } from "../voice/accompaniment.js";
|
||||
import { createWebRtcTransport } from "../voice/webrtc-transport.js";
|
||||
import { createNativeMicrophoneCapture } from "../voice/native-microphone.js";
|
||||
import { createCallMediaSession } from "../services/call-media-session.js";
|
||||
import { createVoiceConnection } from "../voice/connection.js";
|
||||
import { createVoiceCommands } from "../voice/commands.js";
|
||||
import { createVoiceSessionState } from "../voice/session-state.js";
|
||||
@@ -23,7 +21,7 @@ import type { ChatMessage } from "../../../src/shared/voice-models.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";
|
||||
export type { ChannelMember, ChannelInfo, ChatMessage, ServerEvent, VoiceAudioBridgeStats } from "../../../src/shared/voice-models.js";
|
||||
import { computed, onScopeDispose, reactive, ref, shallowRef, watch } from "vue";
|
||||
import { computed, onBeforeUnmount, reactive, ref, shallowRef } from "vue";
|
||||
import { loadLocalPreferences, saveLocalPreferences } from "../services/local-persistence.js";
|
||||
|
||||
export interface VoiceState {
|
||||
@@ -259,11 +257,6 @@ export function useVoiceWebSocket() {
|
||||
let micStream: MediaStream | null = null;
|
||||
const microphoneCaptureFactory = createMicrophoneCaptureFactory();
|
||||
let microphoneCapture: MicrophoneCapture | null = null;
|
||||
let microphoneNative = false;
|
||||
const backgroundCallEnabled = ref(false);
|
||||
const backgroundCallActive = ref(false);
|
||||
const backgroundCallInterrupted = ref(false);
|
||||
let backgroundCallTouched = false;
|
||||
let pendingMicrophoneCapture: AbortController | null = null;
|
||||
const accompanimentActive = ref(false);
|
||||
const accompanimentSupported = ref(typeof navigator !== "undefined" && Boolean(navigator.mediaDevices?.getDisplayMedia));
|
||||
@@ -352,7 +345,7 @@ export function useVoiceWebSocket() {
|
||||
stunServer: () => webRtcStunServer,
|
||||
prepareMicrophone: async () => {
|
||||
await ensureMicrophone();
|
||||
return micStream ? { context: microphoneNative ? null : getAudioCtx(), stream: micStream,
|
||||
return micStream ? { context: getAudioCtx(), stream: micStream,
|
||||
processedStream: microphoneCapture?.processedStream ?? micStream } : null;
|
||||
},
|
||||
stopPcm: stopCaptureGraph,
|
||||
@@ -373,7 +366,6 @@ export function useVoiceWebSocket() {
|
||||
async onFallback(reason, isCurrent) {
|
||||
if (!isCurrent()) return;
|
||||
sessionTrace.record("webrtc.fallback", { code: safeClientErrorCode(reason) || "WEBRTC_UNAVAILABLE" });
|
||||
backgroundCallActive.value = false;
|
||||
setAudioNotice("WEBRTC_FALLBACK", `实时语音(WebRTC)不可用(错误代码:${safeClientErrorCode(reason) || "WEBRTC_UNAVAILABLE"}),已切换为兼容传输:延迟与音质可能下降`);
|
||||
try { await startMicrophone(); }
|
||||
catch (error) { if (isCurrent()) setMicrophoneError(error); }
|
||||
@@ -395,38 +387,6 @@ export function useVoiceWebSocket() {
|
||||
onPlaying: syncAudioContextNotice,
|
||||
},
|
||||
});
|
||||
const callMediaSession = createCallMediaSession({
|
||||
resume() {
|
||||
// A media Play command resumes listening only. Unmuting needs an explicit
|
||||
// microphone action, never a page visibility or system playback event.
|
||||
outputMuted.value = false;
|
||||
applyOutputVolume();
|
||||
webrtc.resumePlayback();
|
||||
},
|
||||
pause() {
|
||||
setMicrophoneMuted(true);
|
||||
outputMuted.value = true;
|
||||
applyOutputVolume();
|
||||
},
|
||||
toggleMicrophone: () => setMicrophoneMuted(!microphoneMuted.value),
|
||||
hangup: () => disconnect(),
|
||||
});
|
||||
function syncCallMediaSession(): void {
|
||||
callMediaSession.sync({ active: state.connected && backgroundCallActive.value,
|
||||
muted: microphoneMuted.value, outputMuted: outputMuted.value, title: serverInfo.value?.name || "WebSpeak" });
|
||||
}
|
||||
watch([() => state.connected, backgroundCallActive, microphoneMuted, outputMuted, serverInfo], syncCallMediaSession);
|
||||
const resumeVisibleCall = () => {
|
||||
if (!state.connected || !backgroundCallActive.value || document.visibilityState !== "visible") return;
|
||||
webrtc.resumePlayback();
|
||||
};
|
||||
document.addEventListener("visibilitychange", resumeVisibleCall);
|
||||
window.addEventListener("pageshow", resumeVisibleCall);
|
||||
onScopeDispose(() => {
|
||||
callMediaSession.dispose();
|
||||
document.removeEventListener("visibilitychange", resumeVisibleCall);
|
||||
window.removeEventListener("pageshow", resumeVisibleCall);
|
||||
});
|
||||
const audioDiagnostics = createAudioDiagnostics({
|
||||
source() {
|
||||
const socket = ws.value;
|
||||
@@ -438,7 +398,7 @@ export function useVoiceWebSocket() {
|
||||
presentation({ peer }) {
|
||||
return {
|
||||
microphoneMuted: microphoneMuted.value,
|
||||
microphoneReady: Boolean(micStream?.getAudioTracks().some(track => track.readyState === "live" && !track.muted)),
|
||||
microphoneReady: Boolean(micStream?.getAudioTracks().some(track => track.readyState === "live")),
|
||||
microphonePermission: audioPermission.value,
|
||||
playbackState: peer
|
||||
? webrtc.output ? webrtc.output.paused ? "paused" : "playing" : "unavailable"
|
||||
@@ -454,7 +414,6 @@ export function useVoiceWebSocket() {
|
||||
preferredInputDeviceId: committedInputDeviceId,
|
||||
inputDeviceId: committedInputDeviceId,
|
||||
microphoneMuted: microphoneMuted.value,
|
||||
backgroundCallEnabled: backgroundCallEnabled.value,
|
||||
noiseSuppressionEnabled: committedNoiseSuppressionLevel !== "off",
|
||||
noiseSuppressionLevel: committedNoiseSuppressionLevel,
|
||||
voxThreshold: voxThreshold.value,
|
||||
@@ -474,7 +433,6 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
|
||||
const audioPreferencesReady = loadLocalPreferences().then((preferences) => {
|
||||
if (!backgroundCallTouched) backgroundCallEnabled.value = preferences.backgroundCallEnabled === true;
|
||||
if (!inputDeviceTouched) {
|
||||
if (!selectedInputDeviceId.value) selectedInputDeviceId.value = preferences.preferredInputDeviceId ?? preferences.inputDeviceId ?? "";
|
||||
committedInputDeviceId = selectedInputDeviceId.value;
|
||||
@@ -591,7 +549,7 @@ export function useVoiceWebSocket() {
|
||||
|
||||
/** A suspended AudioContext silently swallows capture: say so instead of pretending. */
|
||||
function syncAudioContextNotice(): void {
|
||||
if (!microphoneNative && audioCtx && audioCtx.state === "suspended") {
|
||||
if (audioCtx && audioCtx.state === "suspended") {
|
||||
setAudioNotice("AUDIO_CONTEXT_SUSPENDED", "浏览器的音频处理被暂停(需要一次页面交互),麦克风与扬声器可能无声:请点击页面任意位置后重试");
|
||||
} else {
|
||||
clearAudioNotice("AUDIO_CONTEXT_SUSPENDED");
|
||||
@@ -744,10 +702,9 @@ export function useVoiceWebSocket() {
|
||||
pendingMicrophoneCapture?.abort();
|
||||
const controller = new AbortController();
|
||||
pendingMicrophoneCapture = controller;
|
||||
const native = backgroundCallActive.value;
|
||||
const ctx = native ? null : getAudioCtx();
|
||||
const ctx = getAudioCtx();
|
||||
const assertCurrent = (): void => {
|
||||
if (generation !== microphoneGeneration || (ctx && audioCtx !== ctx) || controller.signal.aborted) throw new CancelledMediaOperation();
|
||||
if (generation !== microphoneGeneration || audioCtx !== ctx || controller.signal.aborted) throw new CancelledMediaOperation();
|
||||
};
|
||||
let nextStream: MediaStream | null = null;
|
||||
let nextCapture: MicrophoneCapture | null = null;
|
||||
@@ -755,35 +712,24 @@ export function useVoiceWebSocket() {
|
||||
try {
|
||||
nextStream = await requestMediaBeforeAudioResume(
|
||||
() => navigator.mediaDevices.getUserMedia({ audio: microphoneConstraints() }),
|
||||
() => ctx?.state === "suspended" ? ctx.resume() : Promise.resolve(),
|
||||
() => ctx.state === "suspended" ? ctx.resume() : Promise.resolve(),
|
||||
);
|
||||
assertCurrent();
|
||||
audioPermission.value = "granted";
|
||||
if (native) {
|
||||
nextCapture = createNativeMicrophoneCapture(nextStream);
|
||||
factoryOwnsStream = true;
|
||||
} else {
|
||||
factoryOwnsStream = true;
|
||||
nextCapture = await microphoneCaptureFactory.prepare({
|
||||
context: ctx!, stream: nextStream, signal: controller.signal, assertCurrent,
|
||||
rnnoiseEnabled: noiseSuppressionLevel.value === "strong", volume: inputVolume.value, onSamples: handleCaptureChunk,
|
||||
});
|
||||
}
|
||||
factoryOwnsStream = true;
|
||||
nextCapture = await microphoneCaptureFactory.prepare({
|
||||
context: ctx, stream: nextStream, signal: controller.signal, assertCurrent,
|
||||
rnnoiseEnabled: noiseSuppressionLevel.value === "strong", volume: inputVolume.value, onSamples: handleCaptureChunk,
|
||||
});
|
||||
assertCurrent();
|
||||
// Commit only a complete graph. Permission and node failures leave the
|
||||
// previous stream, PCM route and WebRTC peer untouched.
|
||||
stopMicrophone(false);
|
||||
micStream = nextStream;
|
||||
microphoneCapture = nextCapture;
|
||||
microphoneNative = native;
|
||||
backgroundCallInterrupted.value = false;
|
||||
sessionTrace.record("microphone.route", { native });
|
||||
const microphoneTrack = nextStream.getAudioTracks()[0];
|
||||
if (microphoneTrack) {
|
||||
const recordTrack = (stateName: string) => {
|
||||
sessionTrace.record("microphone.track", { state: stateName, muted: microphoneTrack.muted });
|
||||
if (micStream === nextStream && native) backgroundCallInterrupted.value = microphoneTrack.muted || microphoneTrack.readyState !== "live";
|
||||
};
|
||||
const recordTrack = (stateName: string) => sessionTrace.record("microphone.track", { state: stateName, muted: microphoneTrack.muted });
|
||||
recordTrack(microphoneTrack.readyState);
|
||||
microphoneTrack.addEventListener("mute", () => recordTrack("mute"));
|
||||
microphoneTrack.addEventListener("unmute", () => recordTrack("unmute"));
|
||||
@@ -813,8 +759,8 @@ export function useVoiceWebSocket() {
|
||||
|
||||
// 导出给 WebClient:开麦前先 await 此函数完成真实采集,避免出现“假成功”
|
||||
async function ensureMicrophone(): Promise<void> {
|
||||
if (microphoneStartPromise) await microphoneStartPromise;
|
||||
if (micStream && microphoneNative === backgroundCallActive.value) return;
|
||||
if (microphoneStartPromise) return microphoneStartPromise;
|
||||
if (micStream) return;
|
||||
if (!microphoneStartPromise) {
|
||||
const generation = microphoneGeneration + 1;
|
||||
const pending = startMicrophone().then(async () => {
|
||||
@@ -847,10 +793,6 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
|
||||
async function startAccompaniment(): Promise<void> {
|
||||
if (backgroundCallActive.value) {
|
||||
accompanimentErrorCode.value = "backgroundMode";
|
||||
throw new DOMException("Accompaniment is unavailable in native call mode", "NotSupportedError");
|
||||
}
|
||||
await accompaniment.start();
|
||||
}
|
||||
|
||||
@@ -885,8 +827,6 @@ export function useVoiceWebSocket() {
|
||||
if (micStream) sessionTrace.record("microphone.track", { state: "released" });
|
||||
microphoneCapture?.dispose();
|
||||
microphoneCapture = null;
|
||||
microphoneNative = false;
|
||||
backgroundCallInterrupted.value = false;
|
||||
webrtc.releaseInput();
|
||||
micStream = null;
|
||||
if (closeContext) {
|
||||
@@ -1127,8 +1067,6 @@ export function useVoiceWebSocket() {
|
||||
commands.clear(new Error("语音连接已关闭"));
|
||||
screenShare.stopTransport(sendScreenStop);
|
||||
webrtc.stop();
|
||||
backgroundCallActive.value = false;
|
||||
callMediaSession.dispose();
|
||||
remotePlayback.clearAll();
|
||||
stopMicrophone();
|
||||
clearSpeakingState();
|
||||
@@ -1168,9 +1106,6 @@ export function useVoiceWebSocket() {
|
||||
sendCmd("setMicrophoneMuted", { muted: microphoneMuted.value });
|
||||
screenShare.setIceServers(msg.screenShareIceServers);
|
||||
webRtcStunServer = msg.webRtcStunServer ?? "";
|
||||
backgroundCallActive.value = backgroundCallEnabled.value && msg.webrtcAvailable === true && typeof RTCPeerConnection !== "undefined";
|
||||
sessionTrace.record("call.background", { requested: backgroundCallEnabled.value, native: backgroundCallActive.value });
|
||||
syncCallMediaSession();
|
||||
sessionState.connected(msg);
|
||||
applyWhisperState(msg.whisperTargetIds, msg.whisperActive);
|
||||
if (typeof msg.identity === "string" && msg.identity.length <= 8192) {
|
||||
@@ -1506,12 +1441,6 @@ export function useVoiceWebSocket() {
|
||||
void saveAudioPreferences();
|
||||
}
|
||||
|
||||
function setBackgroundCallEnabled(enabled: boolean): void {
|
||||
backgroundCallTouched = true;
|
||||
backgroundCallEnabled.value = enabled;
|
||||
void saveAudioPreferences();
|
||||
}
|
||||
|
||||
async function setNoiseSuppressionLevel(level: "off" | "standard" | "strong"): Promise<void> {
|
||||
if (noiseSuppressionLevel.value === level) return;
|
||||
noiseSuppressionTouched = true;
|
||||
@@ -1550,7 +1479,7 @@ export function useVoiceWebSocket() {
|
||||
void saveAudioPreferences();
|
||||
}
|
||||
|
||||
onScopeDispose(() => { disconnect(); sessionTrace.dispose(); });
|
||||
onBeforeUnmount(() => sessionTrace.dispose());
|
||||
|
||||
return {
|
||||
pluginSession,
|
||||
@@ -1566,10 +1495,6 @@ export function useVoiceWebSocket() {
|
||||
serverEvents,
|
||||
pokeNotifications,
|
||||
microphoneMuted,
|
||||
backgroundCallEnabled,
|
||||
backgroundCallActive,
|
||||
backgroundCallInterrupted,
|
||||
setBackgroundCallEnabled,
|
||||
noiseSuppressionEnabled,
|
||||
noiseSuppressionLevel,
|
||||
inputVolume,
|
||||
|
||||
@@ -166,9 +166,7 @@ export function useWebClientAudioControls({
|
||||
await startAccompaniment();
|
||||
if (accompanimentActive.value) showToast(t("accompanimentStarted"));
|
||||
} catch {
|
||||
const messageKey = accompanimentErrorCode.value === "backgroundMode"
|
||||
? "backgroundCallProcessingHint"
|
||||
: accompanimentErrorCode.value === "needsWebRtc"
|
||||
const messageKey = accompanimentErrorCode.value === "needsWebRtc"
|
||||
? "accompanimentNeedsWebRtc"
|
||||
: accompanimentErrorCode.value === "noAudio"
|
||||
? "accompanimentNoAudio"
|
||||
|
||||
@@ -347,12 +347,6 @@ export const webClientTranslations: Record<string, Record<string, string>> = {
|
||||
exportAudioTrace: "导出最近两分钟的音频诊断",
|
||||
audioTraceHint: "可导出不含语音内容、昵称或服务器地址的本地诊断记录。",
|
||||
backgroundVoiceHint: "浏览器后台麦克风受浏览器和系统策略限制;锁屏或切后台后可能暂停。",
|
||||
backgroundCallTitle: "锁屏通话(实验性)",
|
||||
backgroundCallHint: "默认关闭,下次连接生效。尝试使用系统原生语音链路;锁屏或后台通话仍受浏览器与系统限制。",
|
||||
backgroundCallProcessingHint: "本次通话使用系统麦克风处理并持续开麦(可手动静音)。强降噪、输入增益、音量计、语音阈值和伴奏不可用;关闭此选项后重新连接可恢复。",
|
||||
backgroundCallPending: "等待下次连接启用;需要网关与浏览器支持 WebRTC,不可用时仍使用兼容传输。",
|
||||
backgroundCallNative: "系统原生语音",
|
||||
backgroundCallInterrupted: "系统已暂停或结束麦克风采集。返回页面后检查权限,必要时重新连接;不会自动取消静音。",
|
||||
rnnoise: "RNNoise 降噪",
|
||||
echoCancellation: "回声消除",
|
||||
autoGainControl: "自动增益",
|
||||
@@ -785,12 +779,6 @@ export const webClientTranslations: Record<string, Record<string, string>> = {
|
||||
exportAudioTrace: "Export the last two minutes of audio diagnostics",
|
||||
audioTraceHint: "The local trace excludes audio content, nicknames, and server addresses.",
|
||||
backgroundVoiceHint: "Background microphone capture depends on browser and OS policy and may pause when hidden or locked.",
|
||||
backgroundCallTitle: "Lock-screen calls (experimental)",
|
||||
backgroundCallHint: "Off by default; applies on the next connection. Tries the native audio path. Browser and OS background restrictions still apply.",
|
||||
backgroundCallProcessingHint: "This call uses system microphone processing with continuous transmission unless muted. Strong denoising, input gain, level meters, voice threshold and accompaniment are unavailable. Disable this option and reconnect to restore them.",
|
||||
backgroundCallPending: "Waiting for the next connection. Requires browser and gateway WebRTC support; otherwise compatibility transport is used.",
|
||||
backgroundCallNative: "Native system audio",
|
||||
backgroundCallInterrupted: "The system paused or ended microphone capture. Return to the page, check permission and reconnect if needed. Your microphone will not be unmuted automatically.",
|
||||
rnnoise: "RNNoise suppression",
|
||||
echoCancellation: "Echo cancellation",
|
||||
autoGainControl: "Automatic gain control",
|
||||
@@ -1216,12 +1204,6 @@ webClientTranslations.de = {
|
||||
exportAudioTrace: "Letzte zwei Minuten der Audiodiagnose exportieren",
|
||||
audioTraceHint: "Der lokale Verlauf enthält keine Audioinhalte, Namen oder Serveradressen.",
|
||||
backgroundVoiceHint: "Die Mikrofonaufnahme im Hintergrund hängt von Browser und Betriebssystem ab und kann pausieren.",
|
||||
backgroundCallTitle: "Telefonieren bei gesperrtem Bildschirm (experimentell)",
|
||||
backgroundCallHint: "Standardmäßig aus; gilt ab der nächsten Verbindung. Verwendet nach Möglichkeit den nativen Audiopfad. Browser- und Systembeschränkungen gelten weiterhin.",
|
||||
backgroundCallProcessingHint: "Dieser Anruf nutzt die Mikrofonverarbeitung des Systems und sendet dauerhaft, sofern nicht stummgeschaltet. Starke Rauschunterdrückung, Eingangsverstärkung, Pegelanzeige, Sprachschwelle und Begleitung sind nicht verfügbar. Zum Wiederherstellen deaktivieren und neu verbinden.",
|
||||
backgroundCallPending: "Wartet auf die nächste Verbindung. Erfordert WebRTC im Browser und Gateway; andernfalls wird der Kompatibilitätsmodus verwendet.",
|
||||
backgroundCallNative: "Natives Systemaudio",
|
||||
backgroundCallInterrupted: "Das System hat die Mikrofonaufnahme unterbrochen oder beendet. Zur Seite zurückkehren, Berechtigung prüfen und bei Bedarf neu verbinden. Das Mikrofon wird nicht automatisch eingeschaltet.",
|
||||
rnnoise: "RNNoise-Geräuschunterdrückung",
|
||||
echoCancellation: "Echounterdrückung",
|
||||
autoGainControl: "Automatische Verstärkungsregelung",
|
||||
@@ -1397,12 +1379,6 @@ webClientTranslations.ru = {
|
||||
exportAudioTrace: "Экспортировать диагностику звука за последние две минуты",
|
||||
audioTraceHint: "Локальная запись не содержит аудио, имён или адресов серверов.",
|
||||
backgroundVoiceHint: "Фоновая запись с микрофона зависит от браузера и ОС и может приостанавливаться.",
|
||||
backgroundCallTitle: "Звонки при блокировке экрана (эксперимент)",
|
||||
backgroundCallHint: "По умолчанию выключено; применяется при следующем подключении. Использует системный аудиотракт, когда возможно. Ограничения браузера и ОС сохраняются.",
|
||||
backgroundCallProcessingHint: "Используется системная обработка микрофона с непрерывной передачей, пока микрофон не выключен. Сильное шумоподавление, усиление входа, индикаторы уровня, порог голоса и аккомпанемент недоступны. Для восстановления выключите опцию и подключитесь заново.",
|
||||
backgroundCallPending: "Ожидание следующего подключения. Нужна поддержка WebRTC браузером и шлюзом; иначе используется совместимый режим.",
|
||||
backgroundCallNative: "Системный аудиотракт",
|
||||
backgroundCallInterrupted: "Система приостановила или завершила запись. Вернитесь на страницу, проверьте разрешение и при необходимости подключитесь заново. Микрофон не включается автоматически.",
|
||||
highQuality: "Качественный звук",
|
||||
opusAudio: "Передача Opus с низкой задержкой",
|
||||
secureJoin: "Безопасное подключение",
|
||||
@@ -1622,12 +1598,6 @@ webClientTranslations.ja = {
|
||||
exportAudioTrace: "直近 2 分間の音声診断をエクスポート",
|
||||
audioTraceHint: "音声、ニックネーム、サーバーアドレスを含まないローカル診断です。",
|
||||
backgroundVoiceHint: "バックグラウンドでのマイク利用はブラウザーと OS の制御を受け、停止する場合があります。",
|
||||
backgroundCallTitle: "ロック画面で通話(試験機能)",
|
||||
backgroundCallHint: "初期設定はオフ。次回接続時に適用されます。システムの音声経路を試しますが、ブラウザーと OS のバックグラウンド制限は適用されます。",
|
||||
backgroundCallProcessingHint: "システムのマイク処理を使い、ミュートするまで連続送信します。強いノイズ抑制、入力ゲイン、レベル表示、音声しきい値、伴奏は使えません。元に戻すにはオフにして再接続してください。",
|
||||
backgroundCallPending: "次回接続を待っています。ブラウザーとゲートウェイの WebRTC 対応が必要です。非対応の場合は互換モードになります。",
|
||||
backgroundCallNative: "システム音声",
|
||||
backgroundCallInterrupted: "システムがマイク収録を一時停止または終了しました。ページに戻り権限を確認し、必要なら再接続してください。ミュートは自動解除されません。",
|
||||
highQuality: "高品質な音声",
|
||||
opusAudio: "低遅延 Opus 転送",
|
||||
secureJoin: "安全に参加",
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test, { type TestContext } from "node:test";
|
||||
import { createCallMediaSession } from "./call-media-session.js";
|
||||
|
||||
function fixture(t: TestContext, unsupported = false) {
|
||||
const original = Object.getOwnPropertyDescriptor(globalThis, "MediaMetadata");
|
||||
Object.defineProperty(globalThis, "MediaMetadata", { configurable: true, value: class {
|
||||
title: string;
|
||||
constructor(init: { title: string }) { this.title = init.title; }
|
||||
} });
|
||||
t.after(() => {
|
||||
if (original) Object.defineProperty(globalThis, "MediaMetadata", original);
|
||||
else Reflect.deleteProperty(globalThis, "MediaMetadata");
|
||||
});
|
||||
const handlers = new Map<string, (() => void) | null>();
|
||||
const events: string[] = [];
|
||||
const session = {
|
||||
metadata: null as MediaMetadata | null, playbackState: "none" as MediaSessionPlaybackState,
|
||||
setActionHandler(action: string, callback: (() => void) | null) {
|
||||
if (unsupported && action === "togglemicrophone") throw new Error("Not supported");
|
||||
handlers.set(action, callback);
|
||||
},
|
||||
setMicrophoneActive(active: boolean) { events.push(`mic:${active}`); },
|
||||
};
|
||||
const audioSession = { type: "auto" };
|
||||
const controller = createCallMediaSession({ resume: () => events.push("play"), pause: () => events.push("pause"),
|
||||
toggleMicrophone: () => events.push("toggle"), hangup: () => events.push("hangup") }, { mediaSession: session as unknown as MediaSession, audioSession });
|
||||
t.after(() => controller.dispose());
|
||||
const sync = (active = true, muted = false) => controller.sync({ active, muted, outputMuted: false, title: "Test room" });
|
||||
return { controller, handlers, events, session, audioSession, sync };
|
||||
}
|
||||
|
||||
test("call media controls are opt-in, reflect mute, and restore OS state on release", t => {
|
||||
const f = fixture(t);
|
||||
f.sync(false);
|
||||
assert.equal(f.handlers.size, 0);
|
||||
f.sync();
|
||||
assert.equal(f.audioSession.type, "play-and-record");
|
||||
assert.equal(f.session.metadata?.title, "Test room");
|
||||
f.handlers.get("play")!();
|
||||
f.handlers.get("pause")!();
|
||||
f.handlers.get("togglemicrophone")!();
|
||||
f.sync(true, true);
|
||||
assert.ok(f.events.includes("mic:false"));
|
||||
f.sync(false);
|
||||
assert.equal(f.audioSession.type, "auto");
|
||||
assert.equal(f.session.metadata, null);
|
||||
assert.equal(f.session.playbackState, "none");
|
||||
assert.ok([...f.handlers.values()].every(value => value === null));
|
||||
});
|
||||
|
||||
test("a queued OS action cannot affect a disconnected or replacement call", t => {
|
||||
const f = fixture(t);
|
||||
f.sync();
|
||||
const stale = f.handlers.get("togglemicrophone")!;
|
||||
f.sync(false);
|
||||
f.sync();
|
||||
stale();
|
||||
assert.ok(!f.events.includes("toggle"));
|
||||
f.handlers.get("togglemicrophone")!();
|
||||
assert.equal(f.events.filter(e => e === "toggle").length, 1);
|
||||
});
|
||||
|
||||
test("partial API support leaves the other call controls functional", t => {
|
||||
const f = fixture(t, true);
|
||||
assert.doesNotThrow(() => f.sync());
|
||||
f.handlers.get("hangup")!();
|
||||
assert.ok(f.events.includes("hangup"));
|
||||
assert.equal(f.handlers.has("togglemicrophone"), false);
|
||||
assert.doesNotThrow(() => f.controller.dispose());
|
||||
});
|
||||
|
||||
test("missing system APIs never prevent calling", () => {
|
||||
const controller = createCallMediaSession({ resume() {}, pause() {}, toggleMicrophone() {}, hangup() {} }, {});
|
||||
assert.doesNotThrow(() => controller.sync({ active: true, muted: false, outputMuted: false, title: "Room" }));
|
||||
assert.doesNotThrow(() => controller.dispose());
|
||||
});
|
||||
@@ -1,75 +0,0 @@
|
||||
interface CallSnapshot { active: boolean; muted: boolean; outputMuted: boolean; title: string }
|
||||
interface AudioSession { type: string }
|
||||
type CallAction = MediaSessionAction | "hangup" | "togglemicrophone";
|
||||
type CallNavigator = Pick<Navigator, "mediaSession"> & { audioSession?: AudioSession };
|
||||
interface CallActions {
|
||||
resume(): void;
|
||||
pause(): void;
|
||||
toggleMicrophone(): void;
|
||||
hangup(): void;
|
||||
}
|
||||
|
||||
/** Optional OS integration, never a keepalive or permission to restart capture. */
|
||||
export function createCallMediaSession(actions: CallActions, target: Partial<CallNavigator> = navigator) {
|
||||
let active = false;
|
||||
let generation = 0;
|
||||
let metadata: MediaMetadata | null = null;
|
||||
let oldMetadata: MediaMetadata | null = null;
|
||||
let oldPlayback: MediaSessionPlaybackState = "none";
|
||||
let oldAudioType: string | undefined;
|
||||
const installed: CallAction[] = [];
|
||||
const safely = (operation: () => void) => { try { operation(); } catch { /* platform may only implement part of the API */ } };
|
||||
|
||||
function stop(): void {
|
||||
if (!active) return;
|
||||
active = false;
|
||||
generation++;
|
||||
const session = target.mediaSession;
|
||||
safely(() => (session as (MediaSession & { setMicrophoneActive?: (active: boolean) => void }) | undefined)?.setMicrophoneActive?.(false));
|
||||
for (const action of installed.splice(0)) safely(() => session?.setActionHandler(action as MediaSessionAction, null));
|
||||
if (session && session.metadata === metadata) {
|
||||
safely(() => { session.metadata = oldMetadata; session.playbackState = oldPlayback; });
|
||||
}
|
||||
safely(() => {
|
||||
if (target.audioSession?.type === "play-and-record" && oldAudioType !== undefined) target.audioSession.type = oldAudioType;
|
||||
});
|
||||
metadata = null;
|
||||
}
|
||||
|
||||
return {
|
||||
sync(snapshot: CallSnapshot): void {
|
||||
if (!snapshot.active) { stop(); return; }
|
||||
const session = target.mediaSession;
|
||||
if (!active) {
|
||||
active = true;
|
||||
const currentGeneration = ++generation;
|
||||
oldMetadata = session?.metadata ?? null;
|
||||
oldPlayback = session?.playbackState ?? "none";
|
||||
safely(() => {
|
||||
oldAudioType = target.audioSession?.type;
|
||||
if (target.audioSession) target.audioSession.type = "play-and-record";
|
||||
});
|
||||
if (session) {
|
||||
const handlers: Partial<Record<CallAction, () => void>> = {
|
||||
play: actions.resume, pause: actions.pause,
|
||||
stop: actions.hangup, hangup: actions.hangup, togglemicrophone: actions.toggleMicrophone,
|
||||
};
|
||||
for (const [action, handler] of Object.entries(handlers)) safely(() => {
|
||||
session.setActionHandler(action as MediaSessionAction, () => { if (active && generation === currentGeneration) handler(); });
|
||||
installed.push(action as CallAction);
|
||||
});
|
||||
}
|
||||
}
|
||||
if (!session) return;
|
||||
safely(() => {
|
||||
if (!metadata || metadata.title !== snapshot.title) {
|
||||
metadata = new MediaMetadata({ title: snapshot.title, artist: "WebSpeak" });
|
||||
session.metadata = metadata;
|
||||
}
|
||||
session.playbackState = snapshot.outputMuted ? "paused" : "playing";
|
||||
});
|
||||
safely(() => (session as MediaSession & { setMicrophoneActive?: (active: boolean) => void }).setMicrophoneActive?.(!snapshot.muted));
|
||||
},
|
||||
dispose: stop,
|
||||
};
|
||||
}
|
||||
@@ -145,7 +145,6 @@ export interface LocalPreferences {
|
||||
theme?: "system" | "light" | "dark";
|
||||
skinId?: string;
|
||||
microphoneMuted?: boolean;
|
||||
backgroundCallEnabled?: boolean;
|
||||
noiseSuppressionEnabled?: boolean;
|
||||
noiseSuppressionLevel?: "off" | "standard" | "strong";
|
||||
voxThreshold?: number;
|
||||
|
||||
@@ -1048,10 +1048,6 @@ const {
|
||||
serverEvents,
|
||||
pokeNotifications,
|
||||
microphoneMuted,
|
||||
backgroundCallEnabled,
|
||||
backgroundCallActive,
|
||||
backgroundCallInterrupted,
|
||||
setBackgroundCallEnabled,
|
||||
noiseSuppressionEnabled,
|
||||
noiseSuppressionLevel,
|
||||
inputVolume,
|
||||
@@ -1306,12 +1302,8 @@ function reconnectMobile(): void {
|
||||
reconnectNow();
|
||||
}
|
||||
const { toggleMicrophone, stopWhisperTalk } = audioControls;
|
||||
const audioDockState = { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionLevel, accompanimentActive, backgroundCallActive };
|
||||
const audioDockState = { microphoneMuted, inputVolume, outputVolume, outputMuted, noiseSuppressionLevel, accompanimentActive };
|
||||
const audioSettingsState = {
|
||||
backgroundCallEnabled,
|
||||
backgroundCallActive,
|
||||
backgroundCallInterrupted,
|
||||
setBackgroundCallEnabled,
|
||||
inputDevices,
|
||||
outputDevices,
|
||||
selectedInputDeviceId,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export type AccompanimentErrorCode = "" | "unsupported" | "needsWebRtc" | "noAudio" | "permission" | "audio" | "backgroundMode";
|
||||
export type AccompanimentErrorCode = "" | "unsupported" | "needsWebRtc" | "noAudio" | "permission" | "audio";
|
||||
|
||||
interface AccompanimentTarget {
|
||||
setAccompaniment(stream: MediaStream | null): void;
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import type { MicrophoneCapture } from "./microphone-capture.js";
|
||||
|
||||
/** Native browser processing only: no RNNoise, PCM worklet, analyser or gain graph. */
|
||||
export function createNativeMicrophoneCapture(stream: MediaStream): MicrophoneCapture {
|
||||
const track = stream.getAudioTracks()[0];
|
||||
if (!track || track.readyState !== "live") throw new DOMException("No live microphone", "NotReadableError");
|
||||
const settings = track.getSettings();
|
||||
let disposed = false;
|
||||
return {
|
||||
processedStream: stream,
|
||||
processing: {
|
||||
echoCancellation: typeof settings.echoCancellation === "boolean" ? settings.echoCancellation : null,
|
||||
noiseSuppression: typeof settings.noiseSuppression === "boolean" ? settings.noiseSuppression : null,
|
||||
autoGainControl: typeof settings.autoGainControl === "boolean" ? settings.autoGainControl : null,
|
||||
rnnoise: false,
|
||||
},
|
||||
activate() {},
|
||||
setVolume() {},
|
||||
stopCapture() {},
|
||||
dispose() {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
for (const item of stream.getTracks()) {
|
||||
try { item.stop(); } catch { /* release the other tracks too */ }
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -5,23 +5,6 @@ export interface WebRtcInput {
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
/** The capture owner releases this stream; no Web Audio graph or clone owns it. */
|
||||
export function createNativeWebRtcInput(stream: MediaStream, volume: number): WebRtcInput {
|
||||
const track = stream.getAudioTracks()[0];
|
||||
if (!track || track.readyState !== "live") throw new Error("No live native microphone track");
|
||||
let disposed = false;
|
||||
const setVolume = (value: number) => { if (!disposed) track.enabled = value > 0; };
|
||||
setVolume(volume);
|
||||
return {
|
||||
stream,
|
||||
setVolume,
|
||||
setAccompaniment(source) {
|
||||
if (source) throw new DOMException("Native call input does not mix accompaniment", "NotSupportedError");
|
||||
},
|
||||
dispose() { disposed = true; },
|
||||
};
|
||||
}
|
||||
|
||||
// Own only the mixing nodes and their output. Capture controllers own the input
|
||||
// streams. Keep the sender track alive when accompaniment starts/stops/changes.
|
||||
export function createWebRtcInput(context: AudioContext, microphone: MediaStream, volume: number): WebRtcInput {
|
||||
|
||||
@@ -58,9 +58,7 @@ export function createWebRtcPlayback(options: WebRtcPlaybackOptions) {
|
||||
const task = (async () => {
|
||||
const context = options.context();
|
||||
if (context?.state === "suspended") {
|
||||
// Capture may never resume while locked. Native remote playback must
|
||||
// not wait on that independent graph, including on a retry gesture.
|
||||
try { void context.resume().catch(() => undefined); } catch { /* retry on a user gesture */ }
|
||||
try { await context.resume(); } catch { /* a real user gesture may still be required */ }
|
||||
}
|
||||
if (!isCurrent(record)) return;
|
||||
try {
|
||||
@@ -110,7 +108,6 @@ export function createWebRtcPlayback(options: WebRtcPlaybackOptions) {
|
||||
|
||||
return {
|
||||
attach, stop,
|
||||
resume(): void { if (current) void play(current); },
|
||||
get output(): SinkAudioElement | null { return current?.output ?? null; },
|
||||
setVolume(value: number): void { if (current) current.output.volume = value; },
|
||||
};
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { isSessionDescription, type WebRtcClientMessage } from "../../../src/shared/webrtc.js";
|
||||
import { createNativeWebRtcInput, createWebRtcInput, type WebRtcInput } from "./webrtc-input.js";
|
||||
import { createWebRtcInput, type WebRtcInput } from "./webrtc-input.js";
|
||||
import { createMicrophoneMeter, type MicrophoneMeter } from "./microphone-meter.js";
|
||||
import { createWebRtcPlayback, type WebRtcPlaybackOptions } from "./webrtc-playback.js";
|
||||
import { addOpusFmtpParameters } from "../../../src/shared/opus-sdp.js";
|
||||
|
||||
interface Microphone {
|
||||
context: AudioContext | null;
|
||||
context: AudioContext;
|
||||
stream: MediaStream;
|
||||
processedStream: MediaStream;
|
||||
}
|
||||
@@ -134,8 +134,7 @@ export function createWebRtcTransport(options: TransportOptions) {
|
||||
const peer = new RTCPeerConnection({ iceServers: stunServer ? [{ urls: stunServer }] : [] });
|
||||
record.peer = peer;
|
||||
track.enabled = !options.muted();
|
||||
const volume = options.muted() ? 0 : options.inputVolume();
|
||||
const input = context ? createWebRtcInput(context, processedStream, volume) : createNativeWebRtcInput(stream, volume);
|
||||
const input = createWebRtcInput(context, processedStream, options.muted() ? 0 : options.inputVolume());
|
||||
record.input = input;
|
||||
peer.addTrack(input.stream.getAudioTracks()[0]!, input.stream);
|
||||
peer.ontrack = event => {
|
||||
@@ -143,7 +142,7 @@ export function createWebRtcTransport(options: TransportOptions) {
|
||||
try { playback.attach(event.streams[0] ?? new MediaStream([event.track])); }
|
||||
catch { void fail(record, "WEBRTC_PLAYBACK_FAILED"); }
|
||||
};
|
||||
if (context) record.meter = createMicrophoneMeter(context, stream, rms => options.onLevel(rms, track));
|
||||
record.meter = createMicrophoneMeter(context, stream, rms => options.onLevel(rms, track));
|
||||
peer.onconnectionstatechange = () => {
|
||||
options.onConnectionState?.(peer.connectionState);
|
||||
if (isCurrent(record) && peer.connectionState === "failed") void fail(record, "WEBRTC_CONNECTION_FAILED");
|
||||
@@ -197,6 +196,5 @@ export function createWebRtcTransport(options: TransportOptions) {
|
||||
get active(): boolean { return current?.active ?? false; },
|
||||
get output() { return playback.output; },
|
||||
setOutputVolume: playback.setVolume,
|
||||
resumePlayback: playback.resume,
|
||||
};
|
||||
}
|
||||
@@ -156,7 +156,6 @@ let useWebClientChat;
|
||||
let useWebClientChannels;
|
||||
let webClientTranslations;
|
||||
let voice;
|
||||
let voiceScope;
|
||||
const savedGlobals = new Map();
|
||||
function replaceGlobal(name, value) {
|
||||
if (!savedGlobals.has(name)) savedGlobals.set(name, Object.getOwnPropertyDescriptor(globalThis, name));
|
||||
@@ -225,14 +224,12 @@ beforeEach(() => {
|
||||
getUserMedia: async () => microphoneStream(),
|
||||
enumerateDevices: async () => [],
|
||||
} });
|
||||
voiceScope = effectScope();
|
||||
voice = voiceScope.run(() => useVoiceWebSocket());
|
||||
voice = useVoiceWebSocket();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
voice?.stopMicrophoneTest();
|
||||
voice?.disconnect();
|
||||
voiceScope?.stop();
|
||||
for (const timer of browserTimers) clearTimeout(timer);
|
||||
browserTimers.clear();
|
||||
});
|
||||
@@ -736,165 +733,6 @@ async function connectWebRtc() {
|
||||
return { socket, peer: TestPeer.instances.at(-1) };
|
||||
}
|
||||
|
||||
test("experimental calls send the native mic without creating a Web Audio graph and preserve mute", async () => {
|
||||
const stream = microphoneStream();
|
||||
navigator.mediaDevices.getUserMedia = async () => stream;
|
||||
assert.equal(voice.backgroundCallEnabled.value, false);
|
||||
voice.setBackgroundCallEnabled(true);
|
||||
const { peer, socket } = await connectWebRtc();
|
||||
assert.equal(voice.backgroundCallActive.value, true);
|
||||
assert.equal(peer.sender.track, stream.track);
|
||||
assert.equal(AudioContextStub.instances.length, 0);
|
||||
assert.equal(voice.microphoneProcessing.rnnoise, false);
|
||||
voice.setMicrophoneMuted(true);
|
||||
assert.equal(stream.track.enabled, false);
|
||||
assert.ok(socket.messages.some(m => m.type === "setMicrophoneMuted" && m.payload.muted));
|
||||
voice.setMicrophoneMuted(false);
|
||||
assert.equal(stream.track.enabled, true);
|
||||
await assert.rejects(voice.startAccompaniment(), /unavailable/);
|
||||
assert.equal(voice.accompanimentErrorCode.value, "backgroundMode");
|
||||
voice.disconnect();
|
||||
assert.equal(stream.track.readyState, "ended");
|
||||
assert.equal(peer.connectionState, "closed");
|
||||
assert.equal(voice.backgroundCallActive.value, false);
|
||||
});
|
||||
|
||||
test("changing the experiment applies only to the next connection", async () => {
|
||||
await connectWebRtc();
|
||||
voice.setBackgroundCallEnabled(true);
|
||||
assert.equal(voice.backgroundCallActive.value, false);
|
||||
const { peer } = await connectWebRtc();
|
||||
const track = peer.sender.track;
|
||||
voice.setBackgroundCallEnabled(false);
|
||||
assert.equal(voice.backgroundCallActive.value, true);
|
||||
assert.equal(track.readyState, "live");
|
||||
await connectWebRtc();
|
||||
assert.equal(voice.backgroundCallActive.value, false);
|
||||
});
|
||||
|
||||
test("native input at zero gain stays silent and scope disposal releases the microphone", async () => {
|
||||
voice.setBackgroundCallEnabled(true);
|
||||
voice.setInputVolume(0);
|
||||
const { peer } = await connectWebRtc();
|
||||
assert.equal(peer.sender.track.enabled, false);
|
||||
voice.setMicrophoneMuted(true);
|
||||
voice.setMicrophoneMuted(false);
|
||||
assert.equal(peer.sender.track.enabled, false, "unmute must preserve a zero input level");
|
||||
voiceScope.stop();
|
||||
assert.equal(peer.sender.track.readyState, "ended");
|
||||
assert.equal(peer.connectionState, "closed");
|
||||
});
|
||||
|
||||
test("native system microphone interruption is reported without changing user mute", async () => {
|
||||
voice.setBackgroundCallEnabled(true);
|
||||
const { peer } = await connectWebRtc();
|
||||
const track = peer.sender.track;
|
||||
track.muted = true;
|
||||
track.dispatchEvent(new Event("mute"));
|
||||
assert.equal(voice.backgroundCallInterrupted.value, true);
|
||||
voice.setMicrophoneMuted(true);
|
||||
track.muted = false;
|
||||
track.dispatchEvent(new Event("unmute"));
|
||||
assert.equal(voice.backgroundCallInterrupted.value, false);
|
||||
assert.equal(voice.microphoneMuted.value, true);
|
||||
assert.equal(track.enabled, false);
|
||||
});
|
||||
|
||||
test("an experimental connection replaces a processing preview still waiting on permission", async () => {
|
||||
const permission = deferred();
|
||||
const preview = microphoneStream();
|
||||
const native = microphoneStream();
|
||||
let requests = 0;
|
||||
navigator.mediaDevices.getUserMedia = () => ++requests === 1 ? permission.promise : Promise.resolve(native);
|
||||
const preparation = voice.prepareInputDevices();
|
||||
voice.setBackgroundCallEnabled(true);
|
||||
const socket = await connect();
|
||||
socket.receive({ type: "connected", tsClientId: 1, webrtcAvailable: true });
|
||||
permission.resolve(preview);
|
||||
await preparation.catch(() => {});
|
||||
await nextTurn();
|
||||
assert.equal(preview.track.readyState, "ended");
|
||||
assert.equal(TestPeer.instances.at(-1).sender.track, native.track);
|
||||
assert.equal(voice.backgroundCallActive.value, true);
|
||||
});
|
||||
|
||||
test("native mode falls back to processed PCM after WebRTC failure", async () => {
|
||||
const streams = [];
|
||||
navigator.mediaDevices.getUserMedia = async () => { const stream = microphoneStream(); streams.push(stream); return stream; };
|
||||
voice.setBackgroundCallEnabled(true);
|
||||
const { peer } = await connectWebRtc();
|
||||
peer.connectionState = "failed";
|
||||
peer.onconnectionstatechange();
|
||||
await nextTurn();
|
||||
assert.equal(voice.backgroundCallActive.value, false);
|
||||
assert.equal(streams[0].track.readyState, "ended");
|
||||
assert.equal(streams.at(-1).track.readyState, "live");
|
||||
assert.ok(AudioContextStub.processors.length > 0);
|
||||
assert.equal(voice.state.audioNoticeCode, "WEBRTC_FALLBACK");
|
||||
});
|
||||
|
||||
test("a gateway without WebRTC keeps compatibility capture with the experiment enabled", async () => {
|
||||
voice.setBackgroundCallEnabled(true);
|
||||
const socket = await connect();
|
||||
socket.receive({ type: "connected", tsClientId: 1 });
|
||||
await nextTurn();
|
||||
assert.equal(voice.backgroundCallActive.value, false);
|
||||
assert.ok(AudioContextStub.processors.length > 0);
|
||||
assert.equal(TestPeer.instances.length, 0);
|
||||
});
|
||||
|
||||
test("disconnect retires a pending native microphone permission request", async () => {
|
||||
const pending = deferred();
|
||||
navigator.mediaDevices.getUserMedia = () => pending.promise;
|
||||
voice.setBackgroundCallEnabled(true);
|
||||
const socket = await connect();
|
||||
socket.receive({ type: "connected", tsClientId: 1, webrtcAvailable: true });
|
||||
await nextTurn();
|
||||
voice.disconnect();
|
||||
const stream = microphoneStream();
|
||||
pending.resolve(stream);
|
||||
await nextTurn();
|
||||
assert.equal(stream.track.readyState, "ended");
|
||||
assert.equal(TestPeer.instances.length, 0);
|
||||
assert.equal(voice.backgroundCallActive.value, false);
|
||||
});
|
||||
|
||||
test("native remote playback does not wait for a suspended capture context to resume", async () => {
|
||||
const { peer } = await connectWebRtc();
|
||||
const context = AudioContextStub.instances.at(-1);
|
||||
context.state = "suspended";
|
||||
context.resume = () => new Promise(() => {});
|
||||
let plays = 0;
|
||||
const output = new TestAudioElement();
|
||||
output.play = async () => { plays++; };
|
||||
document.createElement = () => output;
|
||||
peer.ontrack({ streams: [microphoneStream()] });
|
||||
await nextTurn();
|
||||
assert.equal(plays, 1);
|
||||
});
|
||||
|
||||
test("OS playback resume and page restoration never unmute a native call", async () => {
|
||||
const handlers = new Map();
|
||||
navigator.mediaSession = { metadata: null, playbackState: "none", setActionHandler: (action, handler) => handlers.set(action, handler) };
|
||||
navigator.audioSession = { type: "auto" };
|
||||
voice.setBackgroundCallEnabled(true);
|
||||
const { peer } = await connectWebRtc();
|
||||
handlers.get("pause")();
|
||||
await nextTurn();
|
||||
assert.equal(peer.sender.track.enabled, false);
|
||||
handlers.get("play")();
|
||||
document.visibilityState = "visible";
|
||||
document.dispatchEvent(new Event("visibilitychange"));
|
||||
await nextTurn();
|
||||
assert.equal(voice.microphoneMuted.value, true);
|
||||
assert.equal(peer.sender.track.enabled, false);
|
||||
handlers.get("togglemicrophone")();
|
||||
assert.equal(peer.sender.track.enabled, true);
|
||||
handlers.get("hangup")();
|
||||
assert.equal(peer.connectionState, "closed");
|
||||
assert.equal(navigator.audioSession.type, "auto");
|
||||
});
|
||||
|
||||
function enableMicrophoneMeter(t) {
|
||||
const analysers = [];
|
||||
const intervals = [];
|
||||
|
||||
Reference in new issue
Block a user