Files
piik/internal/app/portmapping/mapping_test.go
T
AAA e3ada873fd feat(app): improve sharing controls, recovery and troubleshooting
Sharing failures were often reduced to a generic message, and changing Windows audio exclusion required reopening source selection. This phase keeps actionable failure context at the TV status indicator, adds live source-audio controls, and integrates independent capture, codec and ICE-lifetime repairs against the published contract.

The audio controls reuse source replacement and the existing mixer; audio-only changes preserve video capture, encoded sources and connections. Source enumeration is bounded by the serialized control response. Codec preflight and H.264 decoder input enforce the existing native format. Gateway mappings are revalidated only for actual ICE gatherings. Website scripts and styles now share content-addressed build output.

Browser/server v23, Native control v9, capture v7 and the 1440p ceiling stay unchanged. The held 4K/capability candidate and Magicsock transport are excluded. Documentation changes belong to the existing guides, standards and evidence owners.

## Validation

- `npm run check`: type checking, 81 test files / 1,370 tests and the production Web build passed.
- `npm run check:go`: Go tests, formatting, vet, cross-builds and Windows native capture regressions passed. A first run hit Windows temporary-directory cleanup after an unchanged SQLite test; five focused repetitions and the full rerun passed.
- Native Host gates passed separately with H.264 and VP8: live/paused quality changes, minimized-window recovery, source replacement, Viewer decoding and complete process/port cleanup. The App Local entry/authentication/invitation gate passed.
- Website/documentation build, documentation links and repository hygiene passed. Browser review covered Chinese/English, dark/light controls, 320px/360px and desktop layouts, audio selection/off state, troubleshooting dialog/ESC focus return, matching GitHub/Gitee architecture links and the embedded film.
- macOS/Linux physical capture, Windows 10 exclusion and representative network/device coverage remain explicit evidence limits. CI must pass Linux race checks and native packaging before publication.

## Release notes

### 中文

这是一次分享体验与兼容性更新。Windows App 支持在开播后调整排除的应用声音;遇到分享失败时,也有更清楚的提示和排查入口。

#### 使用改进

- 在「分享设置 → 声音」中调整系统声音和排除的应用,无需停止分享。支持的 Windows 10 系统也会按实际能力显示排除选项。
- 分享失败提示保留具体原因。点击电视下方状态,可查看处理建议、诊断入口及对应的故障排查文档。
- 补全中英文常见问题说明,涵盖 App 连接、选源与编码、站点地址配置、严格网络和浏览器 HDR 限制。

#### 修复

- 修复窗口较多或名称较长时选源列表可能加载失败,以及部分独立窗口未列出的情况。
- 改善 Windows 窗口最小化、恢复后的采集衔接。
- 修复部分 Firefox 编码属性影响连接的问题,并使原生接收的格式预判与实际支持范围一致。
- 重连时刷新网关端口映射,避免沿用已失效的映射结果;加强原生 H.264 输入校验。
- 官网下载架构切换增加统一动效,脚本与样式使用带内容标识的地址,减少更新后的缓存混用。

更新 App 并刷新页面即可使用相应改进,无需迁移配置或房间数据。Windows 10 音频排除是否可用取决于系统能力。

### English

This update improves sharing controls and compatibility. Windows App users can change audio exclusion during a share, and sharing failures now provide clearer guidance and a direct troubleshooting entry.

#### Improvements

- Change system sound and the excluded application under **Sharing settings → Sound** without stopping the share. Supported Windows 10 installations can also expose exclusion after the capability check.
- Sharing failures retain their specific cause. Select the status below the TV for recovery suggestions, diagnostics and the relevant troubleshooting guide.
- Updated English and Chinese guides cover App connectivity, source selection and encoding, site-address configuration, restricted networks and Browser HDR limitations.

#### Fixes

- Fixed source lists failing with many windows or long titles, and certain independent application windows being omitted.
- Improved Windows capture transitions when a window is minimized and restored.
- Fixed stale Firefox codec attributes disrupting connections and aligned native receiver preflight with its supported formats.
- Refresh gateway port mappings for new ICE gatherings instead of reusing stale results, and validate H.264 input before native decoding.
- Added consistent motion to website architecture selection and content-hashed script/style URLs to prevent mixed cached versions.

Update the App and reload the page to use the relevant improvements. No configuration or room-data migration is required. Windows 10 audio exclusion depends on actual system capability.
2026-10-06 02:24:15 +08:00

276 lines
7.4 KiB
Go

package portmapping
import (
"context"
"errors"
"sync"
"testing"
"time"
)
type fakeGateway struct {
mu sync.Mutex
added []int
deleted []int
addErr error
block chan struct{}
externalPort int
}
func (gateway *fakeGateway) AddPortMapping(
_ context.Context,
_ string,
port int,
_ string,
_ time.Duration,
) (int, error) {
gateway.mu.Lock()
gateway.added = append(gateway.added, port)
block := gateway.block
addErr := gateway.addErr
externalPort := gateway.externalPort
gateway.mu.Unlock()
if block != nil {
// Exercise the caller's bound even if a gateway fails to observe context.
<-block
}
if addErr != nil {
return 0, addErr
}
if externalPort != 0 {
return externalPort, nil
}
return port + 1, nil
}
func (gateway *fakeGateway) DeletePortMapping(
_ context.Context,
_ string,
port int,
) error {
gateway.mu.Lock()
defer gateway.mu.Unlock()
gateway.deleted = append(gateway.deleted, port)
return nil
}
func TestMappingRefreshesForEachGatheringAndReleasesOnce(t *testing.T) {
original := discoverGateway
t.Cleanup(func() { discoverGateway = original })
fake := &fakeGateway{}
discoverGateway = func(context.Context) (gateway, error) {
return fake, nil
}
mapping := Start(43210)
if port := mapping.Prepare(); port != 43211 {
t.Fatalf("mapped port = %d, want 43211", port)
}
if port := mapping.Prepare(); port != 43211 {
t.Fatalf("refreshed mapped port = %d, want 43211", port)
}
mapping.Close()
mapping.Close()
fake.mu.Lock()
defer fake.mu.Unlock()
if len(fake.added) != 2 || fake.added[0] != 43210 || fake.added[1] != 43210 {
t.Fatalf("added ports = %v, want [43210 43210]", fake.added)
}
if len(fake.deleted) != 1 || fake.deleted[0] != 43210 {
t.Fatalf("deleted ports = %v, want [43210]", fake.deleted)
}
}
func TestMappingAbsenceLeavesICEAvailable(t *testing.T) {
original := discoverGateway
t.Cleanup(func() { discoverGateway = original })
discoverGateway = func(context.Context) (gateway, error) {
return nil, errors.New("no mapping service")
}
mapping := Start(43210)
mapping.Prepare()
mapping.Close()
}
func TestMappingGatheringAfterGatewayStateLossUsesNewAllocation(t *testing.T) {
original := discoverGateway
t.Cleanup(func() { discoverGateway = original })
fake := &fakeGateway{externalPort: 43211}
discoverGateway = func(context.Context) (gateway, error) { return fake, nil }
mapping := Start(43210)
t.Cleanup(mapping.Close)
if port := mapping.Prepare(); port != 43211 {
t.Fatalf("initial mapped port = %d", port)
}
// A gateway reset can discard a mapping before its requested lease expires.
// An ICE restart retains this connection/socket and starts a fresh gathering.
fake.mu.Lock()
fake.externalPort = 43212
fake.mu.Unlock()
if port := mapping.Prepare(); port != 43212 {
t.Fatalf("new gathering advertised stale mapped port %d, want 43212", port)
}
}
func TestMappingFailureIsNotRetriedWithinTheConnection(t *testing.T) {
original := discoverGateway
t.Cleanup(func() { discoverGateway = original })
fake := &fakeGateway{addErr: errors.New("mapping rejected")}
discoverGateway = func(context.Context) (gateway, error) {
return fake, nil
}
mapping := Start(43210)
mapping.Prepare()
mapping.Prepare()
mapping.Close()
fake.mu.Lock()
defer fake.mu.Unlock()
if len(fake.added) != 1 || len(fake.deleted) != 1 {
t.Fatalf("mapping calls = add %v delete %v", fake.added, fake.deleted)
}
}
func TestMappingAttemptStaysBoundedWhenTheClientIgnoresContext(t *testing.T) {
original := discoverGateway
t.Cleanup(func() { discoverGateway = original })
fake := &fakeGateway{block: make(chan struct{})}
discoverGateway = func(context.Context) (gateway, error) {
return fake, nil
}
t.Cleanup(func() { close(fake.block) })
mapping := Start(43210)
started := time.Now()
if port := mapping.Prepare(); port != 0 {
t.Fatalf("mapped port = %d, want 0 for an unanswered attempt", port)
}
if elapsed := time.Since(started); elapsed > attemptTimeout+2*time.Second {
t.Fatalf("Prepare blocked %v, want within the attempt bound", elapsed)
}
mapping.Close()
}
func TestCloseSkipsDeleteWhileAnAttemptIsStillAbandoned(t *testing.T) {
original := discoverGateway
t.Cleanup(func() { discoverGateway = original })
fake := &fakeGateway{}
discoverGateway = func(context.Context) (gateway, error) {
return fake, nil
}
mapping := Start(43210)
if port := mapping.Prepare(); port != 43211 {
t.Fatalf("mapped port = %d, want 43211", port)
}
fake.mu.Lock()
fake.block = make(chan struct{})
fake.mu.Unlock()
t.Cleanup(func() { close(fake.block) })
// The renewal attempt is abandoned after attemptTimeout while the fake
// keeps ignoring the context. Close must stay bounded and must not race
// the dependency's still-running call with a Delete.
mapping.Prepare()
started := time.Now()
mapping.Close()
if elapsed := time.Since(started); elapsed > 2*deleteTimeout+time.Second {
t.Fatalf("Close blocked %v, want a brief bounded wait", elapsed)
}
fake.mu.Lock()
defer fake.mu.Unlock()
if len(fake.added) != 2 || len(fake.deleted) != 0 {
t.Fatalf("mapping calls = add %v delete %v, want the Delete skipped",
fake.added, fake.deleted)
}
}
func TestRenewalFailureKeepsTheOriginalMappingOwnedUntilClose(t *testing.T) {
original := discoverGateway
t.Cleanup(func() { discoverGateway = original })
fake := &fakeGateway{}
discoverGateway = func(context.Context) (gateway, error) {
return fake, nil
}
mapping := Start(43210)
mapping.Prepare()
fake.mu.Lock()
fake.addErr = errors.New("renewal rejected")
fake.mu.Unlock()
if port := mapping.Prepare(); port != 0 {
t.Fatalf("failed renewal advertised stale port %d", port)
}
mapping.Close()
fake.mu.Lock()
defer fake.mu.Unlock()
if len(fake.added) != 2 || len(fake.deleted) != 1 || fake.deleted[0] != 43210 {
t.Fatalf("mapping calls = add %v delete %v", fake.added, fake.deleted)
}
}
type cancelableGateway struct {
*fakeGateway
started chan struct{}
}
func (gateway *cancelableGateway) AddPortMapping(ctx context.Context, _ string, _ int, _ string, _ time.Duration) (int, error) {
close(gateway.started)
<-ctx.Done()
return 0, ctx.Err()
}
func TestMappingCloseCancelsPendingCreation(t *testing.T) {
original := discoverGateway
t.Cleanup(func() { discoverGateway = original })
fake := &cancelableGateway{fakeGateway: &fakeGateway{}, started: make(chan struct{})}
discoverGateway = func(context.Context) (gateway, error) { return fake, nil }
mapping := Start(43210)
prepared := make(chan int, 1)
go func() { prepared <- mapping.Prepare() }()
<-fake.started
done := make(chan struct{})
go func() {
mapping.Close()
close(done)
}()
t.Cleanup(func() { <-done })
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("mapping close did not cancel creation")
}
if port := <-prepared; port != 0 {
t.Fatalf("retired mapping returned port %d", port)
}
fake.mu.Lock()
defer fake.mu.Unlock()
if len(fake.deleted) != 1 {
t.Fatalf("cleanup calls = %v, want the canceled attempt released", fake.deleted)
}
}
func TestMappingDiscoveryStopsWithTheConnection(t *testing.T) {
original := discoverGateway
t.Cleanup(func() { discoverGateway = original })
discoverGateway = func(ctx context.Context) (gateway, error) {
<-ctx.Done()
return nil, ctx.Err()
}
mapping := Start(43210)
done := make(chan struct{})
go func() {
mapping.Close()
close(done)
}()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("mapping close did not cancel discovery")
}
}