Compare commits

..
5 Commits
  • fix(app,ui): polish handoff links and mobile playback controls
    ## Problem and outcome
    
    The App console could show a launch address that still contained private activation data when copied, while the terminal hyperlink opened a cleaned address. On narrow phones, playback controls could wrap into a second row and cover too much of the video. The handoff now presents the same safe, activation-preserving address everywhere, and the playback bar keeps one compact row with a shorter flexible volume control.
    
    ## Changes
    
    - Sanitize the App activation URL before rendering both copyable console output and terminal hyperlinks, preserving App handoff without exposing credentials.
    - Keep the mobile playback bar on one row; let the volume slider shrink with the available width and hide the nonessential percentage readout at the narrowest sizes.
    - Add bilingual macOS browser/App audio-capture troubleshooting guidance and record the physical-device boundary.
    
    ## Verification
    
    - `npm run check`: TypeScript, 73 test files / 1008 tests, and the Web production build passed.
    - `npm run check:go-core`: Go tests, formatting, vet and supported core target builds passed.
    - `node scripts/check-docs.mjs` and `scripts/check-project-state.ps1` passed.
    - Narrow-layout browser checks covered 320px, 360px, 375px, 390px, 430px, 768px and 1280px widths without wrapping or horizontal overflow.
    - The interaction prototype remains local and uncommitted for later acceptance; it is not part of this PR.
    
    ## Release notes
    
    ### 中文
    
    这是一个维护版本,改善 App 启动链接的安全提示和手机上的播放控制体验。
    
    #### 修复
    
    - 修复 App 控制台复制链接时可能带出私有激活参数的问题。复制、终端链接和手动打开地址现在保持一致,并继续支持自动唤起 App。
    - 修复窄屏手机上的播控挤成两行、遮挡画面的问题。控件保持单行,音量滑条会按可用空间缩短,过窄时隐藏非关键的百分比读数。
    - 补充 macOS 浏览器与 App 采集声音选项的排查说明,明确不同浏览器和系统版本的能力边界。
    
    #### 兼容性
    
    本版本不改变通信协议、配置格式或存储格式。App 公网邀请、本地模式和已部署站点按原方式更新即可;已打开的页面刷新后使用新的播控布局。
    
    ### English
    
    This maintenance release improves App launch links and playback controls on phones.
    
    #### Fixes
    
    - Fixed the App console sometimes exposing private activation parameters in a copied launch address. The copied address, terminal hyperlink and manual URL now match while still supporting App handoff.
    - Fixed narrow phone layouts wrapping playback controls into a second row and covering the video. Controls stay on one row, the volume slider shrinks with the available space, and the nonessential percentage readout hides when space is tight.
    - Added macOS troubleshooting guidance for browser and App audio capture, including the current browser and OS support boundaries.
    
    #### Compatibility
    
    This release changes no wire protocol, configuration format or storage format. Update the App for public invitations or Local mode, or update the deployed site as usual; refresh an open page to use the new playback layout.
  • fix(routing): recover failed connections across route transitions
    ## Problem and outcome / 问题与结果
    
    An active media connection could fail while a replacement was being prepared, but its failure report was suppressed or attributed to the pending route. Separately, a room revision advanced by another Viewer could invalidate a delayed failure report for a connection that was still current, leaving playback stalled after the browser had already reported the failure.
    
    Failure reporting now follows committed connection ownership. P2P and SFU reports carry the existing physical connection identity; the server accepts a delayed active failure only while that connection and its endpoint session still match. Preparation reports retain their exact operation checks, and stale connections, stale sessions and future revisions remain rejected. This adds no wire fields, recovery timers, dependencies or routing policy.
    
    ## Release notes
    
    ### 中文
    
    这是一次连接恢复修复,改善分享过程中断线或画面停滞后的自动恢复。
    
    - 修复自动切换线路期间,当前连接失效后可能未触发正确恢复的问题,覆盖 P2P 和服务器兜底线路。
    - 修复其他观众加入等房间变化恰好发生时,延迟到达的故障反馈可能被忽略,导致画面停滞后无法自动恢复的问题。
    - App 公网邀请或本地模式请房主更新 App 后重新分享,观众刷新页面。使用已部署站点时,请管理员更新 Server,房主和观众刷新页面。
    
    ### English
    
    This patch improves automatic recovery when a connection fails or playback stalls during sharing.
    
    - Fixed failures on the current connection being missed or attributed to the wrong route while Piik prepares a replacement. This covers P2P and server fallback connections.
    - Fixed delayed failure reports being ignored after another Viewer joins or the room changes, which could leave playback stalled without automatic recovery.
    - For App public invitations or Local mode, the Host should update the App and start sharing again; Viewers should reload the page. For a deployed site, update the Server, then refresh the page for the Host and all Viewers.
    
    ## Verification / 验证
    
    - `npm run check`: typecheck, 71 test files / 1,003 tests, and the Web production build passed.
    - `npm run check:go-core`: Go tests, formatting, vet and supported core target builds passed.
    - Browser fault injection passed for delayed reports across room changes, Host and Viewer signaling reconnects, pending-candidate reauthentication, and source replacement during preparation. The previously reproduced stall recovered automatically with one failure report; process, profile and port cleanup passed.
    - The embedded SFU H.264 simulcast gate passed with decoded video and audio, a live 720p to 480p profile change, and publication retirement.
    - Focused regressions cover Host/Viewer and P2P/SFU report ownership, retired connections, wrong identities, stale sessions and future revisions. Documentation and repository hygiene checks passed.
    
    These results do not establish the original reporter's specific cause. Physical Native capture, representative public networks and long-duration recovery remain outside this local acceptance.
    
    ## Impact / 影响
    
    Patch release: **v1.5.3**. No wire, configuration or storage format changes; existing published message handlers remain compatible. The routing contract owns the updated failure-report rule, and TODO retains the outstanding reporter/device evidence boundaries.
  • fix(routing): retain connected candidates during delayed viewer feedback
    When Viewer progress and first-frame confirmations are delayed, an already connected P2P candidate can be discarded at the five-second scheduling boundary if another candidate is available. This can turn a working initial connection into another connection attempt.
    
    Host and relay parents now report transport progress through the existing room router. The router checks the exact participant/session, revision and connection; only the candidate Viewer can confirm first-frame readiness. The total operation deadline and the routing algorithm are unchanged. Browser and Native senders use their existing prepared-child owners, and discarded preparations cannot report progress.
    
    The loopback benchmark now identifies Peer and SFU connections from room signaling, excluding local codec probes and encoding-pool transports from media-edge counts. Its optional old Viewer-only quality canary remains unsuitable for the current sender-owned quality contract and is recorded in TODO.
    
    Validation:
    
    - `npm run check`: type checks, 1,000 tests and production Web build passed.
    - `npm run check:go-core`: formatting, Go tests, vet and supported Windows/Linux builds passed; Darwin capture remains a native-runner check.
    - Documentation and project-state checks passed.
    - Released v1.5.0 versus this candidate, delaying Viewer transport/ready feedback by six seconds: the old candidate connection closed after the scheduling boundary despite 79 decoded frames; the fixed connection stayed intact. Browser Host, Native Host and relay-parent paths were exercised, with another Viewer continuing to play.
    - Three-Viewer loopback topology and relay-departure recovery passed; Host and relay copy limits remained valid.
    - Actual App public-link signaling, with isolated 1/8/20-second packet loss on one Browser Viewer: playback recovered in all three cases and the control Viewer continued. Every test process, port and isolated profile was cleaned up.
    
    The original reporter's browser/network and paired diagnostics are unavailable. These bounded tests establish the repaired mechanism, not the cause of every brief connection or a representative NAT success rate.
    
    ## Release notes
    
    ### 中文
    
    这是一次连接稳定性修复,改善进入房间时的 P2P 连接过程。
    
    - 修复观众的连接确认反馈较慢时,已接通的线路可能被提前拆除,造成重复连接或延迟出画的问题。修复覆盖 App 分享、浏览器分享和观众中继。
    - 使用 App 公网邀请或本地模式时,房主更新 App 后重新分享即可。使用已部署站点时,请管理员更新 Server,并刷新页面。
    
    ### English
    
    This patch improves P2P connection stability when joining a room.
    
    - Fixed an established connection being discarded prematurely when Viewer confirmations arrive late, causing repeated connection attempts or delayed playback. The fix covers App sharing, browser sharing and Viewer relays.
    - For App public invitations or Local mode, the Host should update the App and start sharing again. For a deployed site, update the Server and refresh the page.
  • fix(packaging): make App ZIPs readable in Windows Explorer
    ## Problem and outcome / 问题与结果
    
    The ZIP writer on Windows and macOS archived `.` as a root entry and prefixed members with `./`. Windows File Explorer enumerated zero entries in the published Windows ZIP, although bsdtar could extract it. Archive the source directory's children directly, preserving hidden files and Unix executable modes. Each Windows package now verifies that File Explorer can resolve every source file and directory before publication.
    
    The archive regression checks normalized member paths as well as extraction. This fixes the shared packaging boundary without changing App media or UI behavior.
    
    ## Release notes
    
    ### 中文
    
    v1.5.1 是一次 ZIP 兼容性修复。修复 Windows 文件资源管理器打开 App 下载包时显示为空或无法解压的问题,并在 Windows 打包时逐项检查资源管理器能否读取文件。
    
    遇到该问题,请重新下载 v1.5.1 的 ZIP 并解压。此前已正常解压、运行的 App 不受此问题影响。
    
    ### English
    
    v1.5.1 fixes a ZIP compatibility issue that could make App downloads appear empty or fail to extract in Windows File Explorer. Windows packaging now checks that File Explorer can read every file before release.
    
    If affected, download and extract the v1.5.1 ZIP again. Apps that were already extracted and running are unaffected by this issue.
    
    ## Verification / 验证
    
    - Reproduced with the original v1.5.0 Windows archive: File Explorer listed zero entries; the Linux archive remained readable.
    - Repacked the original Windows package using the corrected entry layout: File Explorer listed all root entries and extracted all seven files; every SHA-256 matched the original.
    - Independent .NET extraction and 7-Zip integrity checks passed.
    - `npm run check`: type checking, 998 tests and Web production build passed.
    - Windows archive tests include hidden files, Unicode names and spaced paths; Unix checks retain executable permissions.
    - Full CI packaging verifies Windows, Linux and macOS before publication.
    
    ## Impact / 影响
    
    Packaging-only patch release v1.5.1. Standard Store/Deflate compression, existing dependencies and product protocols are retained. Existing published archives remain immutable.
  • docs(release): retain two verified Gitee mirror versions
    ## Problem and outcome / 问题与结果
    
    Gitee mirror attachments approached the repository quota as release history accumulated. Keep downloadable packages for the latest stable release and one verified preceding version, with GitHub retaining the full published history. Complete and verify the new mirror before removing older attachments; preserve release descriptions and tags.
    
    This documents the owner's retention decision and the existing API procedure for release postflight. It does not add an automatic deletion mechanism or alter product packages.
    
    ## Verification / 验证
    
    Documentation and repository hygiene checks passed. Both changed paths are excluded from product version selection. The current v1.5.0 publication remains pinned to its accepted source revision.
26 changed files with 646 additions and 84 deletions

No files matched your search

+6
View File
@@ -100,6 +100,12 @@ The wrapper downloads the pinned public-link sidecar, verifies its digest,
builds the target App and available capture process, executes every packaged
runtime from the extracted ZIP, and emits one `.zip` plus its SHA-256 file.
App ZIPs use ordinary Store/Deflate compression and relative entry names without
`.` or `..` path segments; include hidden files and preserve executable modes on
Unix. Windows packaging also checks every entry through Windows Explorer's ZIP
reader. A successful extraction by the writer's own library does not establish
compatibility with the user's default archive tool.
Retain the descriptor and successful deployment output as release metadata. Do
not create a follow-up source commit solely to duplicate their revision, asset,
or hashes.
+23
View File
@@ -10,6 +10,7 @@ collect a diagnostic report if the problem persists.
| What you see | Try this |
| --- | --- |
| Picture but no sound | Unmute the video. The host should choose a source with shareable audio; if sound was disabled, stop and start sharing with it enabled. App window/screen capture keeps that setting when switching sources. |
| No audio option on a Mac | Check whether you are using the browser picker or App capture. See [macOS audio options](#no-audio-option-on-macos). |
| No screen picker | Allow the browser or App to record the screen when the OS asks. Browser capture needs HTTPS or `localhost`; try sharing from a desktop computer. |
| No App windows or screens listed | Check the message in the source picker, then follow [App source troubleshooting](#app-windows-or-screens-are-missing). **Browser** → **Browser picker** also offers browser capture. |
| Yellow outline around the shared window or screen | This is Windows' capture indicator. See [capture borders](#yellow-capture-border-on-windows) for Windows 11 controls and an optional Windows 10 workaround. |
@@ -44,6 +45,28 @@ Local-network permission lets the page contact the App. It is separate from
the WebRTC media settings described below. An unreachable App alone does not
prove that permission was denied.
## No audio option on macOS
**Browser capture:** try an up-to-date Chrome, select a **Chrome tab**, and enable
**Share tab audio**. Window and entire-screen audio need newer platform support:
Google documents **macOS 14.2 or later and Chrome 142 or later** for that feature.
Safari and Firefox currently do not provide screen-share audio through the
browser picker. See [Google's requirements](https://workspaceupdates.googleblog.com/2025/12/share-devices-audio-when-presenting.html)
and [browser audio support](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia#browser_compatibility).
**App capture:** keep Piik App running and open the site through it. Choose an
application/window or screen in Piik's source picker; **Application sound** or
**System sound** appears below a loaded source list. The **Browser** tab instead
leaves audio selection to the browser's own dialog. For an unavailable App or
empty list, follow [App source troubleshooting](#app-windows-or-screens-are-missing).
The Mac App includes native audio capture, but physical Mac testing is still pending.
In **System Settings → Privacy & Security → Screen & System Audio Recording**,
allow the browser or capture app named by the system prompt. Follow any request
to quit and reopen it, then share again. Older macOS versions may call this
**Screen Recording**. [Apple's permission guide](https://support.apple.com/guide/mac-help/mchld6aa7d23/mac)
explains these settings.
## Yellow capture border on Windows
Windows draws this outline to identify the window or display being captured.
+18
View File
@@ -10,6 +10,7 @@
| 你遇到的情况 | 可以先试什么 |
| --- | --- |
| 有画面,没声音 | 先取消视频静音。房主应选择支持分享声音的来源;如果开始时关闭了声音,请停止后重新开始并打开声音。通过 App 采集窗口或屏幕时,切换来源会保留原来的声音设置。 |
| Mac 上没有声音选项 | 先区分浏览器选择器与 App 采集,查看 [macOS 声音选项](#macos-没有声音选项)。 |
| 没有屏幕选择弹窗 | 按系统提示允许浏览器或 App 录制屏幕。浏览器采集需要 HTTPS 或 `localhost`,请在电脑上尝试分享。 |
| App 的窗口或屏幕列表为空 | 先查看选源器中的提示,再按 [App 来源排查](#app-找不到窗口或屏幕) 操作;也可以选 **浏览器** → **浏览器选择器** 使用浏览器采集。 |
| 分享的窗口或屏幕周围出现黄框 | 这是 Windows 的采集提示。查看[采集边框说明](#windows-分享时出现黄框),了解 Windows 11 的开关和 Windows 10 的可选处理方法。 |
@@ -41,6 +42,23 @@
本地网络权限用于让网页连接 App,与下文的 WebRTC 媒体设置不同。
仅凭 App 未连接,不能确定是权限被拒绝。
## macOS 没有声音选项
**浏览器采集:** 可以先用最新版 Chrome 选择 **Chrome 标签页**,并打开 **分享标签页音频**。
窗口和整个屏幕的声音需要较新的平台支持:Google 公布的条件是 **macOS 14.2 及以上、
Chrome 142 及以上**。Safari 和 Firefox 目前不提供浏览器屏幕共享音频。
详见 [Google 的版本要求](https://workspaceupdates.googleblog.com/2025/12/share-devices-audio-when-presenting.html)
和 [浏览器音频支持情况](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia#browser_compatibility)(英文)。
**App 采集:** 保持 Piik App 运行,并通过它打开站点。在 Piik 选源器中选择应用/窗口或屏幕,
来源列表加载后,底部会出现 **应用声音** 或 **系统声音** 开关。选 **浏览器** 分类时,
声音由浏览器自己的弹窗选择。若 App 不可用或列表为空,先按 [App 来源排查](#app-找不到窗口或屏幕) 处理。
Mac App 已有原生音频采集实现,实机测试仍待完成。
在 **系统设置 → 隐私与安全性 → 屏幕与系统音频录制** 中,允许系统提示所指的浏览器或采集程序。
如果系统要求退出并重新打开程序,照提示完成后再分享。旧版 macOS 的选项可能叫 **屏幕录制**。
具体操作见 [Apple 权限说明](https://support.apple.com/zh-cn/guide/mac-help/mchld6aa7d23/mac)。
## Windows 分享时出现黄框
Windows 用黄色边框标出正在采集的窗口或屏幕。在支持的 Windows 版本上,
+9
View File
@@ -114,6 +114,15 @@ publishing. The [release-source policy](../standards/versioning.md#release-sourc
owns provenance, selection and quota limits. The first public release passed
complete matching Server and three-platform App mirror download acceptance.
Release postflight applies the [two-version mirror retention policy](../standards/versioning.md#release-sources).
After verifying the latest mirror and its fallback against GitHub, inventory
older releases with `/releases/{id}/attach_files`, verify their GitHub originals,
then remove only the reviewed attachments through
`DELETE /releases/{id}/attach_files/{attachment_id}`. Recheck both retained
versions and the anonymous `download/latest` links afterward. Keep deletion
inventories and verification results with operator release records, not source
history. The upload script does not itself delete older attachments.
## Platform References
- [Protected branch availability](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches)
+3 -2
View File
@@ -110,8 +110,9 @@ no separate remembered playback intent for source changes or reconnects.
Adding, replacing or removing audio on the same video binding updates only its
audio consumer; it preserves current-frame proof and Viewer-local playback.
The bar spans the screen's lower edge. Narrow screens separate audio controls
from window actions into two rows and retain 44px action targets. Playing video hides the bar
The bar spans the screen's lower edge in one row. Narrow screens shorten the
volume slider and compact horizontal spacing and button widths, retaining 44px
control height and all actions; the percentage readout hides on narrow screens. Playing video hides the bar
after two idle seconds, following [Media Chrome's default](https://github.com/muxinc/media-chrome/blob/main/docs/src/pages/docs/en/components/media-controller.md#autohide).
Pause or unavailable playback keeps it visible. Control hover, keyboard focus,
dragging and an open tooltip hold it open; mouse movement reveals it, and a
+10
View File
@@ -92,6 +92,10 @@ fallback remains. It advances a silent Peer candidate instead of delaying the
next available route; it is not interpreted as terminal ICE failure. The final
or only Peer candidate remains until the unchanged total operation deadline.
Transport-connected progress also retains a candidate through that deadline.
Either exact preparing endpoint can report that progress, so a delayed Viewer
confirmation does not discard a transport already observed by its parent.
This cannot commit the route: first-frame readiness remains Viewer-owned, and
progress never extends the total operation deadline.
Consequently a working SFU route can carry media while its one-candidate direct
convergence uses the full background operation, and peer-only acquisition does
not abandon its only possible route at the foreground boundary.
@@ -123,6 +127,12 @@ perform quality selection or choose another route.
Current-edge P2P signaling remains valid during candidate overlap. Accepting a
replacement from that parent cancels conflicting optional preparation so the
replacement can complete; a retired candidate cannot take its place afterward.
Failure reports belong to the failed physical connection, not another
preparation's phase. A committed connection's identified failure remains valid
across unrelated room revisions only while its endpoint session and connection
identity still match; future revisions and retired connections are rejected.
Preparation reports retain their exact operation fence. Reports without a
connection identity retain their exact room-revision fence.
## SFU Fallback
+10 -2
View File
@@ -271,8 +271,16 @@ an up-to-date result, does not consult the mirror.
Gitee currently documents 100 MB per attachment and 1 GB total repository
attachments for ordinary projects. The mirror rejects files above 100,000,000
bytes before writing. Check aggregate capacity before each release; exhausted
storage leaves a pending preview rather than deleting older downloads.
bytes before writing. GitHub retains published history; Gitee retains package
attachments for the latest stable version and one preceding verified stable
version. Order by semantic version, not update time; a preview cannot displace
the fallback. Verify the new mirror completely before retiring older attachments,
and verify that the fallback's packages remain downloadable and match GitHub.
Delete only older mirror attachments with verified GitHub originals; retain
release descriptions and tags. Unknown files or provenance require review.
Check capacity before upload. Cleanup may reclaim versions outside the two
retained stable versions; never delete either retained version to make an
unverified replacement fit. Exhausted storage leaves a pending preview.
Target authentication, uploads, anonymous metadata/CORS and the complete matching
Server/three-platform App downloads and SHA-256 checks passed for the public release.
Use API metadata in the Browser; ordinary asset-link redirects are not guaranteed
+14 -7
View File
@@ -7,13 +7,18 @@ history. A parked idea is not implementation authority.
## Now
No additional implementation is scheduled. Routine release and postflight
follow the [deployment runbook](./deployment.md); public demo and private service
deployments remain separate. Physical limits are owned by
[verification status](./verification-status.md).
No implementation work is currently scheduled. Reporter/device follow-ups and
evidence-dependent work remain below.
## Awaiting Device Or Reporter Evidence
- [ ] **Brief connection followed by repeated Viewer loss on v1.5.0.** One
Viewer reportedly drops just after connection details appear, while other
Viewers work; App public-link mode is suspected. Check signaling, first-frame
admission and current-edge recovery separately. A delayed-confirmation
reproduction establishes one premature candidate replacement; the affected
environment and paired diagnostics are still unavailable, so the reporting
machine's cause remains unconfirmed.
- [ ] **App source-discovery field acceptance.** Retest the missing-window report
with the current App and page. Obtain OS/browser, version and paired Debug
reports to distinguish discovery, capture capability and enumeration failures.
@@ -62,6 +67,9 @@ not establish better connection success or speed; this note adds no retry policy
when directed, preserving the owner's platform deferrals. Correlate freezes
with publisher/receiver evidence before changing media policy. Run physical
workloads serially from stable executable paths with cleanup between runs.
Before using the optional `viewer-mbb` benchmark canary, align its injected
evidence and capacity assertions with the current sender-owned quality
contract; its old Viewer-only trigger is not a valid quality acceptance gate.
2. **Broader quality work.** Reopen from measured benefit at acceptable complexity.
Preserve chosen profiles, bitrate ceilings, endpoint capacity and P2P-first
routing unless a new accepted decision supports changing them. No weighted
@@ -79,9 +87,8 @@ not establish better connection success or speed; this note adds no retry policy
resource owners, fewer shared writers and a smaller change surface under
[engineering review](./standards/engineering.md#ablation-and-review); file
size alone does not justify a split. The completed audits do not close this
candidate. Reopen C=3 structural-intent retention, SFU failure during unrelated
prepare and multi-child evidence ownership only with current-contract
reproductions.
candidate. Reopen C=3 structural-intent retention and multi-child evidence
ownership only with current-contract reproductions.
When related behavior changes, compare the Browser/Native recovery budget;
preserve Native bridge versus network failure distinctions when sharing code.
No new revision namespace, failure-state mirror or topology queue by default.
+4 -5
View File
@@ -382,13 +382,12 @@ func (model consoleModel) content(styled bool) string {
continue
}
address := consoleAddress(item[1])
if item[0] == "entry" {
address = launchURL(address)
}
style := link
if styled {
target := address
if item[0] == "entry" {
target = launchURL(address)
}
style = style.Hyperlink(target)
style = style.Hyperlink(address)
}
if compactDebug {
fmt.Fprintf(&out, "\n%s\n", style.Render(address))
+32
View File
@@ -190,6 +190,38 @@ func TestBrowserOpenFeedbackBelongsToTheCurrentEntry(t *testing.T) {
}
}
func TestConsoleEntryKeepsAppActivationWithoutExposingCredentials(t *testing.T) {
model := consoleModel{width: 80, language: "en", view: consoleView{
mode: "link", state: "ready",
entry: "http://user:private-secret@localhost:8787/?token=private-secret#client-access=private-secret&piik-client=1",
invite: "https://room.example/?token=private-secret#v=private-secret",
}}
want := []string{"http://localhost:8787/#piik-client=1", "https://room.example/"}
for _, styled := range []bool{false, true} {
content := model.content(styled)
var addresses []string
for _, field := range strings.Fields(ansi.Strip(content)) {
if strings.HasPrefix(field, "http") {
addresses = append(addresses, field)
}
}
if len(addresses) != len(want) {
t.Fatalf("styled=%v: copyable addresses = %q", styled, addresses)
}
for i, address := range want {
if addresses[i] != address {
t.Fatalf("styled=%v: copyable address = %q, want %q", styled, addresses[i], address)
}
if styled && !strings.Contains(content, ansi.SetHyperlink(address)) {
t.Fatalf("terminal hyperlink differs from copyable address %q", address)
}
}
if strings.Contains(content, "private-secret") || strings.Contains(content, "client-access") {
t.Fatal("console exposed an entry or invitation credential")
}
}
}
func TestConsolePresentationAndShutdown(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
+25 -18
View File
@@ -732,10 +732,21 @@ func (r *router) handleRouteReady(participant authenticatedRouteParticipant, mes
r.requestPump(participant.roomID)
}
func (r *router) handleRouteTransportConnected(participant authenticatedRouteParticipant, message protocol.RouteTransportConnectedMessage) {
if participant.role != protocol.RoleViewer {
return
// Either endpoint may report transport progress or local failure. First-frame
// readiness remains owned by the candidate Viewer in handleRouteReady.
func (r *router) ownsCandidateEndpoint(participant authenticatedRouteParticipant, operation *route.OperationSnapshot) bool {
if participant.role == protocol.RoleViewer && participant.peerID == operation.ChildPeerID &&
participant.sessionID == operation.ChildSessionID {
return true
}
if operation.Current.Tuple.Kind == route.UpstreamPeer && participant.peerID == operation.Current.Tuple.ParentPeerID {
peer, ok := r.connectedPeer(participant.roomID, participant.peerID)
return ok && peer.SessionID == participant.sessionID
}
return false
}
func (r *router) handleRouteTransportConnected(participant authenticatedRouteParticipant, message protocol.RouteTransportConnectedMessage) {
rm, _ := r.rooms.Get(participant.roomID)
if rm == nil || rm.controller == nil {
return
@@ -744,17 +755,16 @@ func (r *router) handleRouteTransportConnected(participant authenticatedRoutePar
operation := controller.Operation()
revision := int64(message.Revision)
if operation == nil || operation.Current == nil ||
operation.ChildPeerID != participant.peerID ||
operation.ChildSessionID != participant.sessionID ||
operation.Current.Revision != revision ||
operation.Current.ConnectionID != message.ConnectionID ||
operation.Current.Tuple.Kind != route.UpstreamPeer {
operation.Current.Tuple.Kind != route.UpstreamPeer ||
!r.ownsCandidateEndpoint(participant, operation) {
return
}
before := controller.Revision()
progressed := controller.CandidateTransportConnected(route.CandidateGuard{
ChildPeerID: participant.peerID,
ChildSessionID: participant.sessionID,
ChildPeerID: operation.ChildPeerID,
ChildSessionID: operation.ChildSessionID,
Revision: revision,
ConnectionID: message.ConnectionID,
}, r.now())
@@ -821,21 +831,14 @@ func (r *router) handleRouteFailed(participant authenticatedRouteParticipant, me
return
}
current := operation.Current
ownsChild := participant.role == protocol.RoleViewer &&
participant.peerID == operation.ChildPeerID &&
participant.sessionID == operation.ChildSessionID
ownsParent := false
if current.Tuple.Kind == route.UpstreamPeer && participant.peerID == current.Tuple.ParentPeerID {
peer, ok := r.connectedPeer(participant.roomID, participant.peerID)
ownsParent = ok && peer.SessionID == participant.sessionID
}
ownsEndpoint := r.ownsCandidateEndpoint(participant, operation)
ownsPublication := false
if current.Tuple.Kind == route.UpstreamSfu && participant.role == protocol.RoleHost &&
participant.peerID == rm.hostPeerID {
host, ok := r.store.GetConnectedHost(participant.roomID)
ownsPublication = ok && host.SessionID == participant.sessionID
}
if !ownsChild && !ownsParent && !ownsPublication {
if !ownsEndpoint && !ownsPublication {
return
}
if connectionID != "" && connectionID != current.ConnectionID {
@@ -857,7 +860,11 @@ func (r *router) handleRouteFailed(participant authenticatedRouteParticipant, me
return
}
if snapshot.Revision != revision {
// A room revision can advance for another Viewer while this report is in
// flight. Only an exact still-owned connection may outlive that revision;
// identity-free reports retain their snapshot fence. Endpoint/session and
// connection checks below still reject retired resources.
if revision > snapshot.Revision || (revision != snapshot.Revision && connectionID == "") {
return
}
if participant.role == protocol.RoleHost {
@@ -0,0 +1,132 @@
package signal
import (
"testing"
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
)
func TestRouterFencesDelayedActiveFailureByPhysicalConnection(t *testing.T) {
for _, transport := range []string{"peer", "sfu"} {
for _, role := range []string{"host", "viewer"} {
for _, report := range []string{"exact", "no-identity", "other-connection", "old-session", "future"} {
t.Run(transport+"/"+role+"/"+report, func(t *testing.T) {
h := newRouterHarness(t, routerHarnessOptions{capacity: 2, withSfu: transport == "sfu", fakeTimers: true})
created := h.createRoom()
host := h.connectHost(created, nil, "", "")
viewer := h.connectViewer(created, "delayed-failure")
h.locked(func() { h.doComplete(host); h.doComplete(viewer) })
prepared := h.waitPreparedTransport(viewer.sessionID, "direct")
if transport == "sfu" {
h.routeFailed(viewer, routeFailedMessage(int64(prepared.Revision), "prepare", prepared.Candidate.ConnectionID))
prepared = h.waitPreparedTransport(viewer.sessionID, "sfu")
}
h.routeReady(viewer, int64(prepared.Revision))
var message protocol.RouteFailedMessage
h.locked(func() {
edge := h.doMustEdge(created.RoomID, viewer.peerID)
id := edge.connectionID
if transport == "sfu" && role == "host" {
rm, _ := h.router.rooms.Get(created.RoomID)
id = rm.controller.Snapshot().HostPublication.ConnectionID
}
message = routeFailedMessage(edge.revision, "active", id)
})
other := h.connectViewer(created, "unrelated-join")
h.complete(other)
candidate := h.waitPreparedTransport(other.sessionID, "direct")
h.routeReady(other, int64(candidate.Revision))
h.locked(func() {
rm, _ := h.router.rooms.Get(created.RoomID)
before := rm.controller.Snapshot()
if before.Revision <= int64(message.Revision) {
t.Fatal("another Viewer must advance the room revision")
}
participant := viewer
if role == "host" {
participant = host
}
switch report {
case "no-identity":
message.ConnectionID = nil
case "other-connection":
id := "retired_connection_12345678"
message.ConnectionID = &id
case "old-session":
participant.sessionID = "retired_session_12345678"
case "future":
message.Revision = protocol.Int(before.Revision + 1)
}
h.router.handleRouteFailed(participant, message)
after := rm.controller.Snapshot()
edge, ok := after.UpstreamByViewer.Get(viewer.peerID)
usable := ok && edge.Usable
if transport == "sfu" && role == "host" {
usable = after.HostPublication != nil && after.HostPublication.Usable
}
if usable != (report != "exact") {
t.Fatalf("active usable=%v after %s report", usable, report)
}
unaffected, ok := after.UpstreamByViewer.Get(other.peerID)
if !ok || !unaffected.Usable {
t.Fatal("unrelated direct Viewer must remain usable")
}
})
})
}
}
}
}
func TestRouterActiveFailureDuringPeerPreparationKeepsItsSubject(t *testing.T) {
for _, role := range []string{"host", "viewer"} {
t.Run(role, func(t *testing.T) {
capacity := 2
if role == "viewer" {
capacity = 1
}
h := newRouterHarness(t, routerHarnessOptions{capacity: capacity, withSfu: true, fakeTimers: true})
created := h.createRoom()
host := h.connectHost(created, nil, "", "")
viewer := h.connectViewer(created, "sfu-ingress")
h.locked(func() { h.doComplete(host); h.doComplete(viewer) })
direct := h.waitPreparedTransport(viewer.sessionID, "direct")
h.routeFailed(viewer, routeFailedMessage(int64(direct.Revision), "prepare", direct.Candidate.ConnectionID))
sfu := h.waitPreparedTransport(viewer.sessionID, "sfu")
h.routeReady(viewer, int64(sfu.Revision))
if role == "viewer" {
h.locked(func() { h.doRelay(viewer, 1) })
}
child := h.connectViewer(created, "preparing-child")
h.complete(child)
candidate := h.waitPreparedTransport(child.sessionID, "direct")
h.locked(func() {
rm, _ := h.router.rooms.Get(created.RoomID)
before := rm.controller.Snapshot()
participant := host
id := before.HostPublication.ConnectionID
if role == "viewer" {
participant = viewer
edge, _ := before.UpstreamByViewer.Get(viewer.peerID)
id = edge.ConnectionID
}
if before.Operation.Current.Tuple.ParentPeerID != participant.peerID {
t.Fatal("preparation must belong to the reporting parent")
}
h.router.handleRouteFailed(participant, routeFailedMessage(before.Revision, "active", id))
after := rm.controller.Snapshot()
if role == "host" {
if after.HostPublication != nil && after.HostPublication.Usable {
t.Fatal("failed publication remains usable")
}
if after.Operation == nil || after.Operation.Current == nil || after.Operation.Current.ConnectionID != candidate.Candidate.ConnectionID {
t.Fatal("independent direct candidate was retired")
}
} else if edge, ok := after.UpstreamByViewer.Get(viewer.peerID); ok && edge.Usable {
t.Fatal("failed subscriber remains usable")
}
})
})
}
}
+74
View File
@@ -21,6 +21,7 @@ package signal
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"reflect"
@@ -1149,6 +1150,12 @@ func TestRouterAcceptsActiveFailureForDirectConnectionAdoptedDuringRebuild(t *te
if adopted.revision != active.revision || adopted.connectionID != rebuiltConnectionID {
t.Fatalf("adopted edge = %+v", adopted)
}
h.doFailed(viewer, routeFailedMessage(active.revision, "active", active.connectionID))
rm, _ := h.router.rooms.Get(created.RoomID)
edge, ok := rm.controller.Snapshot().UpstreamByViewer.Get(viewer.peerID)
if !ok || !edge.Usable || edge.ConnectionID != rebuiltConnectionID {
t.Fatal("retired-connection failure affected its replacement")
}
h.doFailed(viewer, routeFailedMessage(active.revision, "active", rebuiltConnectionID))
})
h.waitFailed(viewer.sessionID)
@@ -1515,6 +1522,73 @@ func TestRouterKeepsExactTransportConnectedDirectCandidatePastBoundary(t *testin
})
}
func TestRouterAcceptsExactParentProgressWithoutGrantingReadiness(t *testing.T) {
for _, relayParent := range []bool{false, true} {
t.Run(fmt.Sprintf("relay=%v", relayParent), func(t *testing.T) {
h := newRouterHarness(t, routerHarnessOptions{capacity: 2, withSfu: true, prepareTimeoutMs: 300, fakeTimers: true})
created := h.createRoom()
host := h.connectHost(created, nil, "", "")
h.locked(func() { h.doComplete(host) })
parents := map[string]authenticatedRouteParticipant{host.peerID: host}
if relayParent {
for _, name := range []string{"root-a", "root-b"} {
root := h.connectViewer(created, name)
h.locked(func() { h.doComplete(root) })
prepared := h.waitPreparedTransport(root.sessionID, "direct")
h.routeReady(root, int64(prepared.Revision))
h.locked(func() { h.doRelay(root, 2) })
parents[root.peerID] = root
}
}
viewer := h.connectViewer(created, "delayed-feedback")
h.locked(func() { h.doComplete(viewer) })
direct := h.waitPreparedTransport(viewer.sessionID, "direct")
h.locked(func() {
rm, _ := h.router.rooms.Get(created.RoomID)
before := rm.controller.Operation()
parent := parents[before.Current.Tuple.ParentPeerID]
if (parent.role == protocol.RoleViewer) != relayParent {
t.Fatal("unexpected preparing parent")
}
message := protocol.RouteTransportConnectedMessage{Type: "route-transport-connected", Revision: direct.Revision, ConnectionID: direct.Candidate.ConnectionID}
stale := parent
stale.sessionID = "retired-session"
h.router.handleRouteTransportConnected(stale, message)
foreign := parent
foreign.peerID = "unrelated-peer"
h.router.handleRouteTransportConnected(foreign, message)
wrong := message
wrong.ConnectionID = "retired-connection"
h.router.handleRouteTransportConnected(parent, wrong)
wrong = message
wrong.Revision++
h.router.handleRouteTransportConnected(parent, wrong)
if rm.controller.Operation().WakeAtMs != before.WakeAtMs {
t.Fatal("unrelated progress changed candidate timing")
}
h.router.handleRouteTransportConnected(parent, message)
after := rm.controller.Operation()
if after == nil || after.DeadlineAtMs != before.DeadlineAtMs || after.WakeAtMs != before.DeadlineAtMs {
t.Fatal("parent progress did not retain the original total deadline")
}
h.doReady(parent, int64(direct.Revision))
if rm.controller.Operation() == nil {
t.Fatal("parent committed a route without Viewer readiness")
}
})
h.clock.advance(150)
if prepared, _ := h.preparedFor(viewer.sessionID); !reflect.DeepEqual(prepared, direct) {
t.Fatal("connected candidate was replaced before delayed Viewer readiness")
}
h.routeReady(viewer, int64(direct.Revision))
h.waitFor("the active peer edge", func() bool {
active, ok := h.activeAfter(viewer.sessionID, int64(direct.Revision)-1)
return ok && active.Assignment.Upstream.Kind == "peer"
})
})
}
}
func TestRouterUsesDirectBoundaryToBootstrapSfuWhenEveryHostSlotIsFull(t *testing.T) {
h := newRouterHarness(t, routerHarnessOptions{capacity: 2, withSfu: true, prepareTimeoutMs: 300, fakeTimers: true})
created := h.createRoom()
+22 -2
View File
@@ -1,5 +1,5 @@
import { execFileSync } from "node:child_process";
import { existsSync } from "node:fs";
import { existsSync, readdirSync } from "node:fs";
import { join, resolve } from "node:path";
export function tarExecutable() {
@@ -15,10 +15,30 @@ export function createZip(source, archive) {
if (process.platform === "linux") {
execFileSync("zip", ["-qry", archive, "."], { cwd: source, stdio: "pipe" });
} else {
execFileSync(tarExecutable(), ["--format=zip", "-cf", archive, "."], {
// Archiving "." adds ./ members that Windows Explorer treats as an empty ZIP.
execFileSync(tarExecutable(), ["--format=zip", "-cf", archive, "--", ...readdirSync(source).sort()], {
cwd: source, stdio: "pipe", windowsHide: true,
});
}
if (process.platform === "win32") {
// The writer can read its own incompatible ZIPs. Check Explorer separately,
// including nested helpers and hidden files, before publishing the archive.
execFileSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", `
$ErrorActionPreference = 'Stop'
$shell = New-Object -ComObject Shell.Application
function Check-Folder($folder, [string]$source) {
if ($null -eq $folder) { throw 'Windows Explorer cannot open the ZIP folder' }
foreach ($entry in Get-ChildItem -LiteralPath $source -Force) {
$item = $folder.ParseName($entry.Name)
if ($null -eq $item) { throw "Windows Explorer cannot read ZIP entry: $($entry.Name)" }
if ($entry.PSIsContainer) { Check-Folder $item.GetFolder $entry.FullName }
}
}
Check-Folder $shell.NameSpace($env:PIIK_ZIP_ARCHIVE) $env:PIIK_ZIP_SOURCE
`], { stdio: "pipe", windowsHide: true, timeout: 30_000,
env: { ...process.env, PIIK_ZIP_ARCHIVE: archive, PIIK_ZIP_SOURCE: resolve(source) },
});
}
}
export function extractZip(archive, destination) {
+18 -11
View File
@@ -153,7 +153,7 @@ interface FailurePageEvidence {
connections: Array<{
connectionState: string;
iceConnectionState: string;
identity: "peer" | "unidentified";
identity: "peer" | "sfu" | "unidentified";
hasOutboundVideo: boolean;
hasInboundVideo: boolean;
decoded: boolean;
@@ -788,9 +788,9 @@ function sanitizeFailurePageEvidence(
? connection.iceConnectionState
: "unknown",
identity:
connection.connectionId !== null || connection.remotePeerId !== null
connection.remotePeerId !== null
? "peer"
: "unidentified",
: connection.connectionId !== null ? "sfu" : "unidentified",
hasOutboundVideo: connection.hasOutboundVideo,
hasInboundVideo: connection.hasInboundVideo,
decoded: (connection.receiveTotals?.framesTotal ?? 0) > 0,
@@ -850,7 +850,7 @@ function inspectSfuPublication(pages: readonly PageObservation[]) {
? connection.sendTotals
: connection.receiveTotals;
return (
connection.connectionId === null &&
connection.connectionId !== null &&
connection.remotePeerId === null &&
connection.connectionState === "connected" &&
(direction === "send"
@@ -1170,7 +1170,7 @@ function committedReceiveMetrics(
connection.receive !== null &&
(upstream.kind === "peer"
? connection.remotePeerId === upstream.peerId
: connection.connectionId === null && connection.remotePeerId === null),
: connection.connectionId !== null && connection.remotePeerId === null),
);
return matching.length === 1 ? matching[0]!.receive : null;
}
@@ -1825,7 +1825,7 @@ function buildBenchmarkInitScript(options: {
}
function recordDescription(message, direction) {
const payload = message && message.payload;
const payload = message.type === "sfu-signal" ? message : message.payload;
if (!payload || payload.kind !== "description" || !payload.description) return;
descriptions.push({
peerId: direction === "out" ? message.targetPeerId : message.fromPeerId,
@@ -1833,6 +1833,7 @@ function buildBenchmarkInitScript(options: {
sdpKey: sdpKey(payload.description.sdp),
});
if (descriptions.length > 128) descriptions.shift();
recordActiveOutboundEdges();
}
function sanitizeRouteTimingSamples(value) {
@@ -1912,7 +1913,7 @@ function buildBenchmarkInitScript(options: {
) {
routeTimingSamples = sanitizeRouteTimingSamples(message.snapshot);
}
if (message.type === "signal") recordDescription(message, direction);
if (message.type === "signal" || message.type === "sfu-signal") recordDescription(message, direction);
}
const NativeWebSocket = globalThis.WebSocket;
@@ -1974,7 +1975,7 @@ function buildBenchmarkInitScript(options: {
const NativePeerConnection = globalThis.RTCPeerConnection;
function recordActiveOutboundEdges() {
const active = connections.filter(({ connection }) =>
const active = networkConnections().filter(({ connection }) =>
connection.connectionState !== "closed" &&
connection.connectionState !== "failed" &&
connection.getSenders().some((sender) => sender.track && sender.track.kind === "video")
@@ -2084,6 +2085,12 @@ function buildBenchmarkInitScript(options: {
return { connectionId: null, remotePeerId: null };
}
// Local codec probes and encoding-pool transports never cross room signaling.
// Count actual Peer/SFU media edges, not every RTCPeerConnection in the page.
function networkConnections() {
return connections.filter(({ connection }) => identify(connection).connectionId !== null);
}
function totals(report, type) {
let selected = null;
report.forEach((raw) => {
@@ -2162,13 +2169,13 @@ function buildBenchmarkInitScript(options: {
}
async function sample() {
const sampledConnections = await Promise.all(connections.map(connectionSample));
const sampledConnections = await Promise.all(networkConnections().map(connectionSample));
return { ...baseSnapshot(), connections: sampledConnections };
}
async function progress() {
const values = [];
for (const record of connections) {
for (const record of networkConnections()) {
const connection = record.connection;
const hasOutboundVideo = connection.getSenders().some((sender) => sender.track && sender.track.kind === "video");
const hasInboundVideo = connection.getReceivers().some((receiver) => receiver.track && receiver.track.kind === "video");
@@ -2195,7 +2202,7 @@ function buildBenchmarkInitScript(options: {
function snapshot() {
return {
...baseSnapshot(),
connections: connections.map((record) => ({
connections: networkConnections().map((record) => ({
index: record.index,
...identify(record.connection),
connectionState: record.connection.connectionState,
@@ -27,21 +27,21 @@
.lr-playback .lr-btn:is(:hover, :focus-visible):not(:disabled):not([aria-disabled="true"]) { transform: translateY(-2px); background: var(--wall-2); }
.lr-playback .lr-btn:active:not(:disabled):not([aria-disabled="true"]) { transform: translateY(2px) scale(.95); transition-duration: 80ms; }
.lr-playback .lr-btn[aria-pressed="true"] { background: var(--wall-2); }
.lr-playback-audio { display: flex; align-items: center; gap: 8px; min-width: 0; }
.lr-playback-separator { width: 1px; height: 20px; background: currentColor; opacity: .22; }
.lr-playback-volume { min-width: 0; }
.lr-playback-volume input { width: clamp(64px, 14vw, 144px); min-width: 0; height: 44px; padding: 0; margin: 0; accent-color: var(--action); cursor: pointer; }
.lr-playback-level { width: 4ch; text-align: right; font-size: 13px; font-weight: 700; font-variant-numeric: tabular-nums; }
.lr-playback-audio { display: flex; align-items: center; flex: 1; gap: 8px; min-width: 0; }
.lr-playback-separator { flex: none; width: 1px; height: 20px; background: currentColor; opacity: .22; }
.lr-playback-volume { flex: 0 1 144px; min-width: 32px; }
.lr-playback-volume input { width: 100%; min-width: 0; height: 44px; padding: 0; margin: 0; accent-color: var(--action); cursor: pointer; }
.lr-playback-level { flex: none; width: 4ch; text-align: right; font-size: 13px; font-weight: 700; font-variant-numeric: tabular-nums; }
.lr-playback-level.is-boosted { color: var(--action); }
.lr-playback-view { display: inline-flex; align-items: center; gap: 4px; margin-left: auto; border-left: 1px solid var(--wall-2); padding-left: 8px; }
.lr-playback-view { display: inline-flex; align-items: center; flex: none; gap: 4px; margin-left: auto; border-left: 1px solid var(--wall-2); padding-left: 8px; }
.lr-tv-screen:fullscreen { width: 100%; height: 100%; border: 0; border-radius: 0; }
.lr-tv-screen:has(> .lr-playback) { container-type: inline-size; }
@container (max-width: 440px) {
.lr-playback { flex-wrap: wrap; gap: 2px 6px; padding: 4px 8px max(4px, env(safe-area-inset-bottom)); }
.lr-playback-audio { flex-basis: 100%; gap: 6px; }
.lr-playback-separator { display: none; }
.lr-playback { gap: 6px; padding: 4px 8px max(4px, env(safe-area-inset-bottom)); }
.lr-playback .lr-btn { width: clamp(32px, 11cqw, 44px); }
.lr-playback-audio { gap: 4px; }
.lr-playback-separator, .lr-playback-level { display: none; }
.lr-playback-volume { flex: 1; }
.lr-playback-volume input { width: 100%; }
.lr-playback-view { gap: 2px; border: 0; padding: 0; }
}
@media (prefers-reduced-motion: reduce) {
@@ -47,6 +47,7 @@ interface HostProvisionalChildEvents {
) => void;
onPromotedUpdate?: (peer: HostMediaPeer, snapshot: PeerSnapshot) => void;
onPreparedChildFailed?: (revision: number, connectionId: string) => void;
onPreparedChildConnected?: (revision: number, connectionId: string) => boolean;
}
export type HostPreparedChildActivation =
@@ -58,6 +59,7 @@ interface PreparedHostChild {
candidate: PreparedRouteCandidate;
peer: HostMediaPeer;
failed: boolean;
connectedSent: boolean;
replacesConnectionId: string | null;
}
@@ -119,6 +121,17 @@ export class HostProvisionalChild {
: false,
onUpdate: (snapshot: PeerSnapshot) => {
if (this.prepared?.peer === peer) {
const prepared = this.prepared;
if (
!prepared.failed && !prepared.connectedSent &&
snapshot.connectionState === "connected" &&
snapshot.connectionId === candidate.connectionId &&
snapshot.peerId === candidate.childPeerId
) {
prepared.connectedSent = this.events.onPreparedChildConnected?.(
revision, candidate.connectionId,
) ?? false;
}
if (snapshot.connectionState === "failed") {
this.fail(peer);
}
@@ -150,6 +163,7 @@ export class HostProvisionalChild {
candidate: { ...candidate },
peer,
failed: false,
connectedSent: false,
replacesConnectionId:
this.events.activeConnectionId?.(candidate.childPeerId) ?? null,
};
+16 -4
View File
@@ -659,7 +659,16 @@ export class HostSfuRoute {
return;
}
if (phase === "prepare") {
if (matchesPlannedRoute || wasActive) {
const activeRevision = this.route.getActiveRevision();
if (wasActive) {
if (
activeRevision !== null &&
this.route.getActiveAssignment()?.sfuPublicationGeneration ===
slot.publicationGeneration
) {
this.routeFailed(activeRevision, "active", slot.connectionId);
}
} else if (matchesPlannedRoute) {
this.routeFailed(revision, "prepare", null);
}
return;
@@ -667,7 +676,7 @@ export class HostSfuRoute {
if (!matchesPlannedRoute) {
return;
}
this.requestRecovery(revision);
this.requestRecovery(revision, slot.connectionId);
}
private failPublisherSlot(slot: HostPublisherSlot): void {
@@ -678,7 +687,10 @@ export class HostSfuRoute {
this.handleFailure(slot);
}
private requestRecovery(revision: number): void {
private requestRecovery(
revision: number,
connectionId: string | null = null,
): void {
if (!this.recovery || this.recovery.revision !== revision) {
this.recovery = { revision, refreshed: false };
}
@@ -688,7 +700,7 @@ export class HostSfuRoute {
return;
}
}
this.routeFailed(revision, "active", null);
this.routeFailed(revision, "active", connectionId);
}
private routeFailed(
+9 -2
View File
@@ -42,6 +42,8 @@ export class MediaRouteTransition {
private phase: MediaRoutePhase | null = null;
private plannedAssignment: ParticipantRouteAssignment | null = null;
private activeAssignment: ParticipantRouteAssignment | null = null;
// Preparation advances the operation without replacing committed authority.
private activeRevision: number | null = null;
private mediaAssignment: ParticipantRouteAssignment | null = null;
private preparedCandidate: PreparedRouteCandidate | null = null;
private generation = 0;
@@ -73,6 +75,7 @@ export class MediaRouteTransition {
update.phase === "prepare" ? cloneCandidate(update.candidate) : null;
if (update.phase === "active") {
this.activeAssignment = cloneAssignment(update.assignment);
this.activeRevision = update.revision;
}
this.generation += 1;
return "accepted";
@@ -123,6 +126,10 @@ export class MediaRouteTransition {
return this.activeAssignment ? cloneAssignment(this.activeAssignment) : null;
}
getActiveRevision(): number | null {
return this.activeRevision;
}
getMediaAssignment(): ParticipantRouteAssignment | null {
return this.mediaAssignment ? cloneAssignment(this.mediaAssignment) : null;
}
@@ -138,6 +145,7 @@ export class MediaRouteTransition {
this.phase = null;
this.plannedAssignment = null;
this.activeAssignment = null;
this.activeRevision = null;
this.mediaAssignment = null;
this.preparedCandidate = null;
this.generation += 1;
@@ -169,9 +177,8 @@ export function reportActivePeerRouteFailure(
send: (message: ClientMessage) => boolean,
): boolean {
const assignment = route.getActiveAssignment();
const revision = route.getRevision();
const revision = route.getActiveRevision();
if (
route.getPhase() !== "active" ||
revision === null ||
assignment?.upstream.kind !== "peer" ||
assignment.upstream.peerId !== parentPeerId
+20 -4
View File
@@ -86,6 +86,7 @@ interface ViewerSfuRouteEvents {
framesDecodedDelta: number | null,
revision: number,
mediaIdentity: string,
connectionId: string,
) => void;
onSfuState?: (
state: "connected" | "reconnecting",
@@ -474,6 +475,7 @@ export class ViewerSfuRoute {
framesDecodedDelta,
slot.revision,
slot.mediaIdentity,
slot.connectionId,
);
}
},
@@ -949,7 +951,17 @@ export class ViewerSfuRoute {
return;
}
if (phase === "prepare") {
if (matchesPlannedRoute || wasActive) {
const activeRevision = this.route.getActiveRevision();
const activeAssignment = this.route.getActiveAssignment();
if (wasActive) {
if (
activeRevision !== null &&
activeAssignment?.upstream.kind === "sfu" &&
activeAssignment.sfuPublicationGeneration === slot.publicationGeneration
) {
this.routeFailed(activeRevision, "active", slot.connectionId);
}
} else if (matchesPlannedRoute) {
this.routeFailed(revision, "prepare");
}
return;
@@ -961,7 +973,7 @@ export class ViewerSfuRoute {
this.recovery?.revision === revision &&
this.recovery.refreshed
) {
this.routeFailed(revision, "active");
this.routeFailed(revision, "active", slot.connectionId);
return;
}
this.requestRecovery(revision);
@@ -1007,12 +1019,16 @@ export class ViewerSfuRoute {
: null;
}
private routeFailed(revision: number, phase: MediaRoutePhase): boolean {
private routeFailed(
revision: number,
phase: MediaRoutePhase,
connectionId: string | null = null,
): boolean {
return this.events.send({
type: "route-failed",
revision,
phase,
connectionId: null,
connectionId,
});
}
+3
View File
@@ -1901,6 +1901,9 @@ export function HostPage({
onPreparedChildFailed: (revision, connectionId) => {
reportPreparedHostChildFailure(revision, connectionId, generation);
},
onPreparedChildConnected: (revision, connectionId) =>
isCurrentGeneration(generation) && signalRef.current === signal &&
signal.send({ type: "route-transport-connected", revision, connectionId }),
createPeer:
nativeClient && nativeShareGeneration
? (candidate, input, events) => {
+11 -15
View File
@@ -843,6 +843,8 @@ export function ViewerPage({
}
},
onPreparedChildFailed: reportPreparedChildFailure,
onPreparedChildConnected: (revision, connectionId) =>
active && signal.send({ type: "route-transport-connected", revision, connectionId }),
},
endpointMediaCopyCapacity,
currentRoutePolicy.natPrediction,
@@ -922,7 +924,7 @@ export function ViewerPage({
identity: string,
framesDecodedDelta: number | null,
authorityRevision: number,
connectionId?: string,
connectionId: string,
): void {
if (
currentHostPaused ||
@@ -934,20 +936,12 @@ export function ViewerPage({
decodedFrameStall.allowReportRetry();
return;
}
let sent = false;
if (route === "peer" && connectionId) {
sent = signal.send({
type: "route-failed",
revision: authorityRevision,
phase: "active",
connectionId,
});
} else if (route === "sfu") {
sent = signal.send({
type: "route-media-unavailable",
revision: authorityRevision,
});
}
const sent = signal.send({
type: "route-failed",
revision: authorityRevision,
phase: "active",
connectionId,
});
if (!sent) decodedFrameStall.allowReportRetry();
}
@@ -1125,6 +1119,7 @@ export function ViewerPage({
framesDecodedDelta,
revision,
mediaIdentity,
connectionId,
) => {
if (active && viewerSfuRoute === route) {
observeActiveDecodedFrames(
@@ -1132,6 +1127,7 @@ export function ViewerPage({
mediaIdentity,
framesDecodedDelta,
revision,
connectionId,
);
}
},
+14
View File
@@ -25,6 +25,7 @@ export interface ViewerRelayEvents {
onUpdate?: (snapshot: PeerSnapshot | null) => void;
onSenderUpdate?: (snapshot: PeerSnapshot, revision: number | null) => void;
onPreparedChildFailed?: (revision: number, connectionId: string) => void;
onPreparedChildConnected?: (revision: number, connectionId: string) => boolean;
}
interface PreparedChild {
revision: number;
@@ -32,6 +33,7 @@ interface PreparedChild {
candidate: PreparedRouteCandidate;
peer: HostMediaPeer;
failed: boolean;
connectedSent: boolean;
replacesConnectionId: string | null;
}
@@ -376,6 +378,7 @@ export class ViewerRelay {
candidate: { ...candidate },
peer,
failed: false,
connectedSent: false,
replacesConnectionId:
this.peers.get(candidate.childPeerId)?.connectionId ?? null,
};
@@ -539,6 +542,17 @@ export class ViewerRelay {
: false,
onUpdate: (snapshot) => {
if (this.preparedChild?.peer === peer) {
const prepared = this.preparedChild;
if (
!prepared.failed && !prepared.connectedSent &&
snapshot.connectionState === "connected" &&
snapshot.connectionId === prepared.candidate.connectionId &&
snapshot.peerId === prepared.childPeerId
) {
prepared.connectedSent = this.events.onPreparedChildConnected?.(
prepared.revision, snapshot.connectionId,
) ?? false;
}
if (snapshot.connectionState === "failed") {
this.failPreparedChild(peer);
}
+6 -1
View File
@@ -4,7 +4,7 @@ import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { describe, expect, it } from "vitest";
import { createZip, extractZip } from "../scripts/archive-tool.mjs";
import { createZip, extractZip, tarExecutable } from "../scripts/archive-tool.mjs";
describe("App ZIP distribution", () => {
it("round-trips hidden files, spaced paths and executable permissions", () => {
@@ -28,6 +28,11 @@ describe("App ZIP distribution", () => {
for (const name of executables) chmodSync(join(source, name), 0o755);
createZip(source, archive);
expect(readFileSync(archive).subarray(0, 4)).toEqual(Buffer.from([0x50, 0x4b, 0x03, 0x04]));
const entries = execFileSync(process.platform === "linux" ? "unzip" : tarExecutable(),
process.platform === "linux" ? ["-Z", "-1", archive] : ["-tf", archive],
{ encoding: "utf8", windowsHide: true }).trim().split(/\r?\n/);
expect(entries).toHaveLength(readdirSync(source, { recursive: true }).length);
for (const name of entries) expect(name).not.toMatch(/(^|\/)\.\.?($|\/)/);
mkdirSync(extracted);
extractZip(archive, extracted);
expect(readdirSync(extracted, { recursive: true }).sort()).toEqual(
+52
View File
@@ -1763,6 +1763,30 @@ function hostProvisionalInput(
}
describe("Host provisional child runtime ownership", () => {
it("reports connected preparation once, retries unsent progress and fences replacement", async () => {
const progress = vi.fn().mockReturnValueOnce(false).mockReturnValue(true);
const owner = new HostProvisionalChild({ sendSignal: () => true, onPreparedChildConnected: progress });
const stream = createStream(createTrack("video", "progress-video"), null);
owner.prepare(hostProvisionalInput(7, ["child"], stream));
const first = FakePeerConnection.latest!;
first.connectionState = "connected";
first.dispatchEvent(new Event("connectionstatechange"));
first.dispatchEvent(new Event("connectionstatechange"));
first.dispatchEvent(new Event("connectionstatechange"));
expect(progress).toHaveBeenCalledTimes(2);
expect(progress).toHaveBeenLastCalledWith(7, "candidate-connection-7");
owner.prepare(hostProvisionalInput(8, ["replacement"], stream));
first.dispatchEvent(new Event("connectionstatechange"));
expect(progress).toHaveBeenCalledTimes(2);
const second = FakePeerConnection.latest!;
second.connectionState = "connected";
second.dispatchEvent(new Event("connectionstatechange"));
expect(progress).toHaveBeenLastCalledWith(8, "candidate-connection-8");
owner.discard();
second.dispatchEvent(new Event("connectionstatechange"));
expect(progress).toHaveBeenCalledTimes(3);
});
it("accepts only the exact connection and promotes the same peer", async () => {
const signals: Array<{ peerId: string; connectionId: string }> = [];
const promotedUpdates = vi.fn();
@@ -2313,6 +2337,34 @@ describe("ViewerRelay downstream ownership", () => {
expect(onPreparedChildFailed).toHaveBeenCalledTimes(1);
});
it("reports relay transport progress once and retires its reporting scope", async () => {
const progress = vi.fn().mockReturnValueOnce(false).mockReturnValue(true);
const relay = new ViewerRelay(
{ iceServers: [] }, QUALITY_PROFILES["720p30"],
{ sendSignal: () => true, onPreparedChildConnected: progress },
);
relay.setStream(createStream(createTrack("video", "relay-progress"), null));
relay.prepareChild(7, routeCandidate(7, "child"), ["child"]);
await vi.waitFor(() => expect(FakePeerConnection.latest).not.toBeNull());
const first = FakePeerConnection.latest!;
first.connectionState = "connected";
first.dispatchEvent(new Event("connectionstatechange"));
first.dispatchEvent(new Event("connectionstatechange"));
first.dispatchEvent(new Event("connectionstatechange"));
expect(progress).toHaveBeenCalledTimes(2);
expect(progress).toHaveBeenLastCalledWith(7, "relay-candidate-7");
relay.prepareChild(8, routeCandidate(8, "replacement"), ["replacement"]);
first.dispatchEvent(new Event("connectionstatechange"));
expect(progress).toHaveBeenCalledTimes(2);
const second = FakePeerConnection.latest!;
second.connectionState = "connected";
second.dispatchEvent(new Event("connectionstatechange"));
expect(progress).toHaveBeenLastCalledWith(8, "relay-candidate-8");
relay.dispose();
second.dispatchEvent(new Event("connectionstatechange"));
expect(progress).toHaveBeenCalledTimes(3);
});
it("reports a failed prepared transport once without blaming retained children", async () => {
const onPreparedChildFailed = vi.fn();
const relay = new ViewerRelay(
+91 -1
View File
@@ -367,6 +367,92 @@ describe("minimal route transition contracts", () => {
]);
});
it("reports committed Peer failure during another preparation using active authority", () => {
const route = new MediaRouteTransition();
const send = vi.fn(() => false);
route.accept({ revision: 7, phase: "active", assignment: peerAssignment("parent") });
route.accept({
revision: 8, phase: "prepare",
assignment: peerAssignment("parent", ["child"]), candidate: candidate(8, "child"),
});
expect(reportActivePeerRouteFailure(route, "parent", "active-connection", send)).toBe(false);
expect(send).toHaveBeenLastCalledWith({
type: "route-failed", revision: 7, phase: "active", connectionId: "active-connection",
});
send.mockReturnValue(true);
expect(reportActivePeerRouteFailure(route, "parent", "active-connection", send)).toBe(true);
route.accept({ revision: 9, phase: "active", assignment: peerAssignment("replacement") });
send.mockClear();
expect(reportActivePeerRouteFailure(route, "parent", "active-connection", send)).toBe(true);
route.reset();
expect(reportActivePeerRouteFailure(route, "replacement", "new-connection", send)).toBe(true);
expect(send).not.toHaveBeenCalled();
});
it("reports the committed SFU publisher when a Peer child is preparing", async () => {
const send = vi.fn(() => true);
let fail!: () => void;
const route = new HostSfuRoute({
getStream: () => ({}) as MediaStream,
getProfile: () => QUALITY_PROFILES["720p30"],
getVideoCodec: () => "h264",
reconcileChildren: () => undefined,
send,
createPublisher: (onDisconnected) => {
fail = onDisconnected;
return createFakePublisher([], "active");
},
});
const config = sfuConfig(7);
await route.acceptAndWait({ revision: 7, phase: "active", assignment: hostAssignment(config.publicationGeneration) });
await route.acceptConfig(config);
send.mockClear();
route.accept({
revision: 8, phase: "prepare",
assignment: hostAssignment(config.publicationGeneration, ["child"]), candidate: candidate(8, "child"),
});
fail();
fail();
expect(send.mock.calls).toEqual([[{
type: "route-failed", revision: 7, phase: "active", connectionId: config.connectionId,
}]]);
await route.disconnect();
});
it("reports the committed SFU subscription when a downstream Peer is preparing", async () => {
const send = vi.fn(() => true);
const stream = vi.fn();
let events!: SubscriberEvents;
const route = new ViewerSfuRoute("viewer_12345678", {
activatePeer: () => true,
onSfuStream: stream,
send,
createSubscriber: (callbacks) => {
events = callbacks;
return createFakeSubscriber(callbacks, [], "active");
},
});
const config = sfuConfig(7);
route.accept({ revision: 7, phase: "active", assignment: viewerSfuAssignment() });
await route.acceptConfig(config);
events.onStream({} as MediaStream);
events.onFirstDecodedFrame();
await vi.waitFor(() => expect(stream).toHaveBeenCalledOnce());
send.mockClear();
route.accept({
revision: 8, phase: "prepare",
assignment: viewerSfuAssignment(["child"]), candidate: candidate(8, "child"),
});
events.onDisconnected();
events.onDisconnected();
expect(send.mock.calls).toEqual([[{
type: "route-failed", revision: 7, phase: "active", connectionId: config.connectionId,
}]]);
await route.disconnect();
});
it("publishes SFU media during prepare and promotes before retiring old media", async () => {
const log: string[] = [];
const messages: ClientMessage[] = [];
@@ -970,6 +1056,7 @@ describe("minimal route transition contracts", () => {
framesDecodedDelta: number | null;
revision: number;
mediaIdentity: string;
connectionId: string;
}> = [];
const subscribers: ReturnType<typeof createFakeSubscriber>[] = [];
const route = new ViewerSfuRoute("viewer_12345678", {
@@ -980,7 +1067,8 @@ describe("minimal route transition contracts", () => {
framesDecodedDelta,
revision,
mediaIdentity,
) => decodedSamples.push({ framesDecodedDelta, revision, mediaIdentity }),
connectionId,
) => decodedSamples.push({ framesDecodedDelta, revision, mediaIdentity, connectionId }),
send: (message) => {
messages.push(message);
return true;
@@ -1012,6 +1100,7 @@ describe("minimal route transition contracts", () => {
framesDecodedDelta: 3,
revision: 1,
mediaIdentity: expect.stringContaining("publication_generation_12345678:"),
connectionId: sfuConfig(1).connectionId,
},
]);
@@ -1050,6 +1139,7 @@ describe("minimal route transition contracts", () => {
expect(decodedSamples[1]).toMatchObject({
framesDecodedDelta: null,
revision: 2,
connectionId: sfuConfig(2).connectionId,
});
expect(decodedSamples[1]!.mediaIdentity).not.toBe(
decodedSamples[0]!.mediaIdentity,