diff --git a/cmd/piik-server/release.go b/cmd/piik-server/release.go index 79e03972c..cfe2e2bf8 100644 --- a/cmd/piik-server/release.go +++ b/cmd/piik-server/release.go @@ -19,7 +19,7 @@ import ( // The Browser notice and operator checker read the same published release. const defaultReleaseAPIURL = "https://api.github.com/repos/TNTcraftHIM/Piik/releases/latest" -const mirrorReleaseAPIURL = "https://gitee.com/api/v5/repos/TNTcraftHIM/Piik/releases" +const mirrorReleaseAPIURL = "https://api.atomgit.com/api/v5/repos/TNTcraftHIM/Piik/releases" // deploy/check-release.sh forwards these codes without installing anything. const ( @@ -29,7 +29,7 @@ const ( releaseTimeout = 5 * time.Second releaseURLPrefix = "https://github.com/TNTcraftHIM/Piik/releases/tag/" releaseAPIHost = "api.github.com" - mirrorReleasePrefix = "https://gitee.com/TNTcraftHIM/Piik/releases/tag/" + mirrorReleaseURL = "https://atomgit.com/TNTcraftHIM/Piik/releases" ) var fullRevisionPattern = regexp.MustCompile(`^[0-9a-f]{40}$`) @@ -288,5 +288,5 @@ func parseMirrorReleaseMetadata(payload []byte) (version, revision, releaseURL s if !ok { return "", "", "", false } - return version, revision, mirrorReleasePrefix + version, true + return version, revision, mirrorReleaseURL, true } diff --git a/cmd/piik-server/release_test.go b/cmd/piik-server/release_test.go index fb5e03920..02692b7a6 100644 --- a/cmd/piik-server/release_test.go +++ b/cmd/piik-server/release_test.go @@ -309,7 +309,7 @@ func TestMirrorFallbackUsesOriginalSourceAndCompleteStablePagination(t *testing. })) defer mirror.Close() result := checkRelease(t.Context(), deployedVersion, deployedRevision, primary.URL, "operator-secret", mirror.URL) - assertResult(t, result, statusUpdateAvailable, deployedVersion, latestVersion, deployedRevision, latestRevision, mirrorReleasePrefix+latestVersion) + assertResult(t, result, statusUpdateAvailable, deployedVersion, latestVersion, deployedRevision, latestRevision, mirrorReleaseURL) if mirrorCalls != 2 { t.Fatalf("mirror calls = %d", mirrorCalls) } diff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.md index 69c3aba6a..fd8835de0 100644 --- a/docs/guide/troubleshooting.md +++ b/docs/guide/troubleshooting.md @@ -57,8 +57,12 @@ over the existing official App. ### macOS blocks first launch -Current Mac builds are unsigned and unnotarized. To open one, verify the -download and allow this App through macOS's first-launch check: +Current Mac builds are not Developer ID-signed or notarized by Apple. For +first-launch warnings, verify the download and allow this App through macOS: + +If macOS reports malware, says the App will damage your computer, or moves it +to Trash automatically, [report the exact alert and download link](#reporting-a-problem). +Do not use the quarantine command below for those alerts. 1. Download the matching Mac ZIP from the project's Releases and compare its SHA-256 with the checksum published for that release. In Terminal, run diff --git a/docs/guide/troubleshooting.zh-CN.md b/docs/guide/troubleshooting.zh-CN.md index ef75ac153..2490686b2 100644 --- a/docs/guide/troubleshooting.zh-CN.md +++ b/docs/guide/troubleshooting.zh-CN.md @@ -52,6 +52,9 @@ outline: 2 当前 Mac 版本未进行 Developer ID 签名和 Apple 公证。首次打开时,先校验下载文件,再为这个 App 放行: +若 macOS 提示恶意软件、「会损坏你的电脑」,或自动将 App 移到废纸篓, +请[保留完整提示和下载链接反馈](#反馈问题),不要使用下方的隔离标记命令。 + 1. 从项目 Releases 下载对应的 Mac ZIP,核对同一版本公布的 SHA-256。 在终端运行 `shasum -a256 ~/Downloads/piik-app-darwin-arm64.zip`; Intel Mac 将文件名中的 `arm64` 换为 `amd64`。校验不一致时应重新下载,不要绕过警告。 diff --git a/docs/research/native-client-media.md b/docs/research/native-client-media.md index f36ce7497..6e6251d03 100644 --- a/docs/research/native-client-media.md +++ b/docs/research/native-client-media.md @@ -513,6 +513,10 @@ an absent optional property or readback no longer rejects an otherwise usable encoder. Required CBR, bitrate and GOP checks, Constrained Baseline bitstream admission, actual H.264 output and Auto's measured frame cadence retain their owners. +The [H264 burst and recovery assessment](./webrtc-encoder-pool.md#h264-burst-and-recovery) +records the measured scene-change queue delay and the rejected one-frame HRD +override. Average bitrate and optional low-latency mode do not bound each AU. + Issue [#432](https://github.com/TNTcraftHIM/Piik/issues/432) reports more visible blocking with native H.264 than VP8 on v1.6.7. Review of its attached Browser report confirms 720p30 in both comparison windows, roughly 11 Mbps received, diff --git a/docs/research/node-local-media-design.md b/docs/research/node-local-media-design.md index 47d310c09..f26d7aec6 100644 --- a/docs/research/node-local-media-design.md +++ b/docs/research/node-local-media-design.md @@ -426,6 +426,12 @@ Pion's existing 1.5 pacing headroom. This follows the Both queue controls must pass; correcting old-packet delay alone does not establish healthy Native sending. +A 2026-11-03 2.x headroom-only comparison retained that same healthy-link gate +and diagnostic observation code. Raising headroom to 2.5 downgraded the high +output after 4.27 seconds. The matching 1.5 control completed 12.19 seconds, +retained the high output without congestion and received about 4.8–5.02 Mbps. +The larger headroom was rejected; the existing 1.5 setting remains. + Allocation also distinguishes source measurements from changed capacity. A stable 1 Mbps connection must not drop its output merely because that source's measurement changes from 900 kbps to 1.05 Mbps, or because a lower output's diff --git a/docs/research/room-interactions.md b/docs/research/room-interactions.md index 3d3dc79f0..092a3946f 100644 --- a/docs/research/room-interactions.md +++ b/docs/research/room-interactions.md @@ -916,8 +916,9 @@ For 200 samples, Browser input dispatch and AES-GCM-to-send each had a 0.1 ms at the 95th percentile, matching the short timer rather than a rendering-frame wait. Encrypted Pion delivery through Host authorization to a recorded input sink was 0.13 ms at the 95th percentile. No slow point appeared in these local -components. End-to-end timing still needs target execution, Native capture and -encoding, remote transport and physical display response in the same trial. +components. The later [Native H264 end-to-end control](./webrtc-encoder-pool.md#h264-burst-and-recovery) +includes real OS input, capture, encoding and Browser compositor presentation; +its remaining scene-change delay is traced to the send queue. The reviewed implementation uses WGC capture and the documented Windows input API, without game-memory access, injected game code or an input driver. diff --git a/docs/research/webrtc-encoder-pool.md b/docs/research/webrtc-encoder-pool.md index 54fc5343e..878a72d1f 100644 --- a/docs/research/webrtc-encoder-pool.md +++ b/docs/research/webrtc-encoder-pool.md @@ -469,6 +469,36 @@ path remains. The four-second decision budget is unchanged. Current grouping at that point still folded multiple weak consumers into one low budget; the following integration addresses that independent requirement. +#### H264 Burst And Recovery + +A 2026-11-03 Windows 2.x control traced Native H264 scene-change delay through +normal Host approval, real clicks on an owned window, capture and Browser +presentation. At a 5 Mbps / 30 fps ceiling, the actual 826×612 output supplied +six AUs of 170–181 KB, each marked `Recovery=false`. +Matching source packets and received frame timestamps placed 154–168 ms in the +send queue before dequeue; the segmented writer control observed no synchronous +write over 5 ms. The five-click input-to-compositor median was 235.1 ms. + +A follow-up with the original settings parsed all six 172–182 KB AUs through +Pion's H264 reader with SEI included. Each contained one type-1 non-IDR VCL NAL; +AUD, prefix NAL and Annex-B start codes accounted for only 19 bytes. There was +no SEI or trailing zero padding. All 139 observed wire markers matched their +source AU uniquely, and the six large AUs spent 155–170 ms in the send queue. +The burst is coded picture data, not removable filler. `Recovery=false` remains +an independent encoder flag; a type-1 NAL does not identify its slice type. + +A candidate applied optional H264 +[HRD buffer size](https://learn.microsoft.com/en-us/windows/win32/directshow/avenccommonbuffersize-property) +in bytes, using one frame of the current rate at initialization and live updates. +In the same control it reduced the largest AU to 38 KB and the median to +54.5 ms, with matching sampled colours. The existing 76-second +`TestAdaptiveOutputFixture` then rejected it: after 2 Mbps → 100 kbps → 2 Mbps, +output remained 320×180 at about 120–124 kbps through the end, with no restored +full-size frames. Optional setters did not avoid the earlier recovery failure. +The candidate was removed and was not applied to the Rust MF owner. Its latency +gain does not justify restoring the one-frame HRD override; the existing +encoding and pacing settings remain. + ### Budget Restoration Transport allocation and encoder resolution recover separately. Replaying the diff --git a/docs/standards/engineering.md b/docs/standards/engineering.md index c4d455f5a..0f132b080 100644 --- a/docs/standards/engineering.md +++ b/docs/standards/engineering.md @@ -215,8 +215,10 @@ in [introduction design](./public-introduction.md) and the [website runbook](../ Queued events retain physical-owner validity until the final serialized write; readiness commits also require the resource's current state. Reused logical IDs do not identify a replacement instance. A child's attachment failure does - not retire its shared producer. New subscriptions follow the old owner's - retirement, including repeated cleanup callers. + not retire its shared producer. Replacing an exclusive subscription waits for + the current owner's retirement; repeated cleanup callers await that same work. + For shared leases, the owning controller confirms the replacement before + releasing a healthy lease. Closing a Browser connection may leave its API promises pending. Its owner cancels the corresponding waits so a serialized successor never depends on completion from a retired connection; late results still need identity checks. diff --git a/docs/standards/routing-transport.md b/docs/standards/routing-transport.md index 853932cec..95aea8735 100644 --- a/docs/standards/routing-transport.md +++ b/docs/standards/routing-transport.md @@ -159,6 +159,9 @@ voice readiness never becomes evidence that a video frame has arrived. ## Reconciliation One room controller owns the committed graph and one bounded child transition. +Committed child membership applies immediately, independently of asynchronous +upstream activation. A later child preparation does not retire an already +committed upstream that is still being promoted locally. Healthy current edges remain sticky. When admitted overlap exists, a usable old route stays active until the exact candidate child decodes a first new frame; the candidate must still be connected when that proof is accepted and when it @@ -224,6 +227,8 @@ Committed P2P recovery first requests an ICE restart, then requests a rebuild if necessary, within the existing two-request budget. A sender without restart support, including the current Native sender, replaces its connection on that first request. +Restart authority follows the exact retained edge and its endpoint sessions; +an ancestor repairing its own ingress does not revoke that edge's recovery. The budget belongs to the current parent and survives physical connection or Browser/Native backend replacement. Only a connected transport or a new parent resets it; replacing an unconnected backend cannot renew recovery indefinitely. diff --git a/docs/standards/versioning.md b/docs/standards/versioning.md index 47bad5e5a..82fe88211 100644 --- a/docs/standards/versioning.md +++ b/docs/standards/versioning.md @@ -156,6 +156,12 @@ notice. Unknown SHA is not inferred from a branch name in GitHub metadata. The publisher records a full SHA in `target_commitish` and verifies actual tag identity separately. Stable update notices ignore prereleases. +Mode entry and the Site's App control share the check against the App's compiled +identity. A newer stable release marks that App control; its panel groups the +installed version, manual download and App management. This also covers starred +Site startup, which bypasses mode entry. Approved health supplies build identity; +older Apps without that metadata retain their ordinary connection and management. + ### Major-Upgrade Guidance The App update notice keeps direct download as its primary action, with a small diff --git a/docs/todo.md b/docs/todo.md index 8dc4537d5..b8248513e 100644 --- a/docs/todo.md +++ b/docs/todo.md @@ -1,48 +1,46 @@ # Current TODO Ledger -Last reviewed: 2026-11-01 +Last reviewed: 2026-11-03 This ledger contains unfinished work and explicit owner holds. Product modules own behavior; research and Git/PRs own evidence and completed history. ## Now +- [ ] **Public-invitation candidate retirement.** Capture the parent and server + reason when a candidate is retired before its first SDP offer. Keep this + separate from candidates that actually enter ICE and fail. - [ ] **Browser sharing falls to low source FPS during motion.** Trace raw capture, sender-owned track input and encoding on Windows Chrome with mixed direct/SFU delivery. The observed source fell to roughly 2 fps during video or game playback; reproduce with real window/display capture. Keep the separate SFU packet-loss stage distinct from source-frame production. -- [ ] **Windows App sharing ends unexpectedly.** Identify WGC/source, device or - encoder termination in the supplied release feedback using the native stage - and HRESULT, and reproduce the unexpected termination. -- [ ] **Native screen sound recaptures room voice.** Exclude Piik voice while - retaining intended source audio. Verify Browser own-document exclusion and - Native process exclusion; keep acoustic echo and duplicate commentary with - their separate microphone owners. +- [ ] **Unclassified capture termination in older Windows feedback.** Identify + the Native failure stage and HRESULT in the original v2.4.1/v2.5.1 attempts. + Their Browser reports show Native failure before page cleanup but do not + identify its trigger. +- [ ] **Room voice in Native display sound.** Resolve the remaining case where + system loopback recaptures Browser voice, while excluding the Browser process + also removes its other audio. Browser own-document exclusion and Native + process-tree exclusion are already implemented; acoustic echo and duplicate + commentary retain their separate microphone owners. - [ ] **Virtual-LAN page loading.** Investigate the UU report where only the tab title appears and the page never loads. Static compression reduces transfer size; capture the stalled document/script response to locate this failure. -- [ ] **Remote-control end-to-end latency.** Measure input-to-visible-response - on an attended target, covering OS execution, Native capture/encoding, remote - transport and display in the same trial. The - [input assessment](./research/room-interactions.md#window-capture-and-game-input) - owns completed local component measurements. +- [ ] **Native H264 scene-change latency.** Reduce large-AU send-queue delay + while preserving bitrate restoration. The + [end-to-end control](./research/webrtc-encoder-pool.md#h264-burst-and-recovery) + locates the delay and rejects the one-frame HRD override that prevents recovery. - [ ] **Linux capture ends after selection (#499).** Follow [#499](https://github.com/TNTcraftHIM/Piik/issues/499) on niri/Wayland with GStreamer NVENC. The Browser report records capture ending before connection cleanup; obtain the native capture failure to distinguish the encoder and Portal. -- [ ] **macOS source-picker thumbnails (#500).** The reporter confirmed normal - sharing on 2026-10-28; the remaining [#500](https://github.com/TNTcraftHIM/Piik/issues/500) - report concerns missing screen thumbnails in the source picker. The macOS - helper now implements the existing preview command; verify its build and - display/window thumbnails on a physical Mac before closing the issue. - [ ] **Mouse input stops when Host Chrome is minimized (#502).** Follow [#502](https://github.com/TNTcraftHIM/Piik/issues/502) on the original Windows - host: the v2.5.1 follow-up retains the grant, but mouse movement and left/right - clicks stop until Chrome is restored. The diagnostic candidate adds aggregate - input-stage and sink-API counts without recording input values. Obtain App ZIPs - during the minimized failure and after restoration; the local controlled - Chrome trial did not reproduce the original machine's trigger. + host. The supplied v2.5.2 reports retain the grant and receive authorized mouse + events, but Windows `SendInput` rejects a button event and subsequent release + attempts. Identify that OS refusal trigger and verify held-button recovery; + the local controlled Chrome trial did not reproduce it. - [ ] **Return LiveKit to an upstream pin.** Follow [upstream #5016](https://github.com/livekit/livekit/pull/5016). Once upstream supplies the allocator input Piik needs, verify recovery and remove the @@ -56,6 +54,10 @@ own behavior; research and Git/PRs own evidence and completed history. ## Next +- [ ] **Stronger microphone noise suppression (#518).** Assess the + [requested speech-processing option](https://github.com/TNTcraftHIM/Piik/issues/518) + through the shared microphone input. Browser voice processing is already the + default; keep screen and system audio unprocessed. - [ ] **3.0 semantic reconstruction.** Continue the isolated `feat/channel-prototype` from the accepted domain/room/participant model. Map existing behavior and ownership, remove accidental constraints, then implement cohesive Rust runtimes diff --git a/internal/app/buildinfo/buildinfo.go b/internal/app/buildinfo/buildinfo.go index 2ca2c3468..e94129592 100644 --- a/internal/app/buildinfo/buildinfo.go +++ b/internal/app/buildinfo/buildinfo.go @@ -2,6 +2,7 @@ package buildinfo import ( + "runtime" "strings" "golang.org/x/mod/semver" @@ -11,6 +12,13 @@ import ( var Release = "development" var Revision = "development" +func PackageTarget() string { + if runtime.GOOS == "android" { + return "android-universal" + } + return runtime.GOOS + "-" + runtime.GOARCH +} + func Version() string { version := strings.TrimSpace(Release) if version != "" && semver.Canonical(version) == version && semver.Prerelease(version) == "" { diff --git a/internal/app/launcher/server.go b/internal/app/launcher/server.go index a73dcc55b..926932a87 100644 --- a/internal/app/launcher/server.go +++ b/internal/app/launcher/server.go @@ -12,12 +12,12 @@ import ( "net" "net/http" "net/url" - "runtime" "slices" "strings" "sync" "time" + "github.com/TNTcraftHIM/Piik/internal/app/buildinfo" appconfig "github.com/TNTcraftHIM/Piik/internal/app/config" "github.com/TNTcraftHIM/Piik/internal/app/failure" "github.com/TNTcraftHIM/Piik/internal/app/lan" @@ -298,17 +298,13 @@ func (server *Server) handleState(response http.ResponseWriter, request *http.Re target, resultErr = attempt.target, attempt.err starting = !attempt.completed } - packageTarget := runtime.GOOS + "-" + runtime.GOARCH - if runtime.GOOS == "android" { - packageTarget = "android-universal" - } state := map[string]any{ "sites": slices.Clone(server.sites), "startupSite": server.startupSite, "localAccessPassword": server.localAccessPassword, "version": server.version, "revision": server.revision, - "packageTarget": packageTarget, + "packageTarget": buildinfo.PackageTarget(), "controlPort": server.controlPort, "target": target, "starting": starting, diff --git a/internal/app/loopback/server.go b/internal/app/loopback/server.go index 70e3ae4ba..d4dc9a8ad 100644 --- a/internal/app/loopback/server.go +++ b/internal/app/loopback/server.go @@ -16,6 +16,7 @@ import ( "sync" "time" + "github.com/TNTcraftHIM/Piik/internal/app/buildinfo" appconfig "github.com/TNTcraftHIM/Piik/internal/app/config" "github.com/TNTcraftHIM/Piik/internal/server/protocol" "github.com/coder/websocket" @@ -70,6 +71,9 @@ type Endpoint struct { } type Health struct { + Version string `json:"version"` + Revision string `json:"revision"` + PackageTarget string `json:"packageTarget"` Protocol int `json:"protocol"` Service string `json:"service"` Port int `json:"port"` @@ -417,6 +421,9 @@ func (server *Server) handleHealth(response http.ResponseWriter, request *http.R } response.Header().Set("Cache-Control", "no-store") writeJSON(response, http.StatusOK, Health{ + Version: buildinfo.Version(), + Revision: buildinfo.Revision, + PackageTarget: buildinfo.PackageTarget(), Protocol: ProtocolVersion, Service: ServiceName, Port: server.endpoint.Port, diff --git a/internal/app/loopback/server_test.go b/internal/app/loopback/server_test.go index c395a1e73..7b9214813 100644 --- a/internal/app/loopback/server_test.go +++ b/internal/app/loopback/server_test.go @@ -13,6 +13,7 @@ import ( "testing" "time" + "github.com/TNTcraftHIM/Piik/internal/app/buildinfo" "github.com/coder/websocket" "github.com/coder/websocket/wsjson" ) @@ -52,6 +53,9 @@ func TestHealthActivationURLIsOptionalAndOriginBound(t *testing.T) { } func TestStartServesHealthAndStrictControlHandshake(t *testing.T) { + release, revision := buildinfo.Release, buildinfo.Revision + buildinfo.Release, buildinfo.Revision = "v2.5.2", strings.Repeat("a", 40) + t.Cleanup(func() { buildinfo.Release, buildinfo.Revision = release, revision }) expectedMedia := NativeMediaCapabilities{ Video: true, ProcessAudio: false, SystemAudio: true, HardwareH264: true, MaxRelayChildren: 20, } @@ -71,6 +75,7 @@ func TestStartServesHealthAndStrictControlHandshake(t *testing.T) { } response.Body.Close() if health.Protocol != ProtocolVersion || health.Service != ServiceName || + health.Version != buildinfo.Version() || health.Revision != buildinfo.Revision || health.PackageTarget != buildinfo.PackageTarget() || health.Port != endpoint.Port || health.InstanceToken != endpoint.InstanceToken || health.NativeMedia != expectedMedia { t.Fatalf("health = %+v", health) diff --git a/internal/app/mediaedge/ice_socket.go b/internal/app/mediaedge/ice_socket.go index e11826cae..0b1b628ba 100644 --- a/internal/app/mediaedge/ice_socket.go +++ b/internal/app/mediaedge/ice_socket.go @@ -48,17 +48,20 @@ func (engine *Engine) newICESocket(servers []webrtc.ICEServer, mapping bool) (*i // Adoption happens before the one PeerConnection is constructed. Discovery and // media then keep this exact socket, including any authenticated punched tuple. func (engine *Engine) adoptICESocket(connection net.PacketConn, servers []webrtc.ICEServer, mapping bool) (*iceSocket, error) { + var punchedPeer *net.UDPAddr + if prepared, ok := connection.(*PunchedSocket); ok { + punchedPeer = prepared.remote + connection = prepared.PacketConn + } ctx, cancel := context.WithCancel(engine.ctx) socket := &iceSocket{ engine: engine, ctx: ctx, cancel: cancel, - localPort: connection.LocalAddr().(*net.UDPAddr).Port, + localPort: connection.LocalAddr().(*net.UDPAddr).Port, + punchedPeer: punchedPeer, mux: forwarding.NewUDPMux(ice.UDPMuxParams{ Logger: diagnostics.PionLoggerFactory().NewLogger("piik-ice"), UDPConn: connection, }), } - if prepared, ok := connection.(*PunchedSocket); ok { - socket.punchedPeer = prepared.remote - } if engine.portMapping && mapping && len(stunServers(servers)) > 0 { socket.portMapping = portmapping.Start(socket.localPort) } diff --git a/internal/media/forwarding/ice.go b/internal/media/forwarding/ice.go index 281d6cced..3a4dfc482 100644 --- a/internal/media/forwarding/ice.go +++ b/internal/media/forwarding/ice.go @@ -42,6 +42,11 @@ func AddICECandidate(connection *webrtc.PeerConnection, candidate webrtc.ICECand // addresses at each gathering. Its default stdnet snapshot otherwise survives // ICE restart (and every new SFU connection sharing that mux). func NewUDPMux(params ice.UDPMuxParams) *ice.UDPMuxDefault { + // Size the actual media socket before Pion starts reading. Preparation's + // unused candidate sockets keep their ordinary OS buffers. + if connection, ok := params.UDPConn.(interface{ SetReadBuffer(int) error }); ok { + _ = connection.SetReadBuffer(2 * 1024 * 1024) + } if params.Net == nil { params.Net = &muxNetwork{} } diff --git a/internal/media/forwarding/transport.go b/internal/media/forwarding/transport.go index 55fd536f6..76d1b4ba1 100644 --- a/internal/media/forwarding/transport.go +++ b/internal/media/forwarding/transport.go @@ -488,6 +488,8 @@ type EgressStats struct { Packets, RTPBytes, DroppedPackets uint64 } +const pacingHeadroom = 1.5 + // The SDK owns packet timing; bounded tickets keep original packet ownership // here until a ticket sends or Stop retires it. SFU's unpaced writer assumes // already-paced input, which does not hold for locally encoded whole frames. @@ -512,7 +514,7 @@ func newPacedQueue(log logger.Logger, limit, bitrate int) *boundedPacer { // prevents a stale low estimate from trapping already encoded frames for // seconds; this is not a network latency promise. queue := newBoundedPacer(packetpacer.NewPacerLeakyBucket(3*time.Millisecond, - int(float64(bitrate)*1.5), 200*time.Millisecond, log), log, limit) + int(float64(bitrate)*pacingHeadroom), 200*time.Millisecond, log), log, limit) queue.bitrate.Store(int64(bitrate)) return queue } @@ -525,7 +527,7 @@ func newBoundedPacer(packetPacer packetpacer.Pacer, log logger.Logger, limit int func (queue *boundedPacer) SetBitrate(bitrate int) { queue.bitrate.Store(int64(bitrate)) - queue.Pacer.SetBitrate(int(float64(bitrate) * 1.5)) + queue.Pacer.SetBitrate(int(float64(bitrate) * pacingHeadroom)) } func (queue *boundedPacer) Enqueue(packet *pacer.Packet) { @@ -582,11 +584,11 @@ func (queue *boundedPacer) SetPacerProbeObserverListener(listener pacer.PacerPro func (queue *boundedPacer) StartProbeCluster(info ccutils.ProbeClusterInfo) { queue.sender.StartProbeCluster(info) - queue.Pacer.SetBitrate(int(float64(info.Goal.DesiredBps) * 1.5)) + queue.Pacer.SetBitrate(int(float64(info.Goal.DesiredBps) * pacingHeadroom)) } func (queue *boundedPacer) EndProbeCluster(id ccutils.ProbeClusterId) ccutils.ProbeClusterInfo { - queue.Pacer.SetBitrate(int(float64(queue.bitrate.Load()) * 1.5)) + queue.Pacer.SetBitrate(int(float64(queue.bitrate.Load()) * pacingHeadroom)) return queue.sender.EndProbeCluster(id) } diff --git a/internal/server/signal/router.go b/internal/server/signal/router.go index 58b04445c..8dd89d8a4 100644 --- a/internal/server/signal/router.go +++ b/internal/server/signal/router.go @@ -557,6 +557,19 @@ func (r *router) isActivePeerParentOf(roomID, parentPeerID, childPeerID string) return ok && activeParent == parentPeerID } +// A retained child connection can restart while its parent repairs its own +// ingress. The full source path need not be ready, but this inbound edge must +// still own the exact endpoint sessions and connection. +func (r *router) peerRestartAuthorized(input peerSignalInput) bool { + rm, _ := r.rooms.Get(input.roomID) + if rm == nil || rm.controller == nil { + return false + } + edge, ok := rm.controller.Snapshot().UpstreamByViewer.Get(input.sourcePeerID) + return ok && edge.Kind == route.UpstreamPeer && edge.ParentPeerID == input.targetPeerID && + r.peerSignalAuthorization(input) == signalAuthorizationAllowed +} + // resolveActivePeerEdge returns false when the child has no active Peer edge. func (r *router) resolveActivePeerEdge(roomID, childPeerID string) (revision int64, parentPeerID string, ok bool) { edge, found := r.resolveActiveViewerMediaEdge(roomID, childPeerID) diff --git a/internal/server/signal/server.go b/internal/server/signal/server.go index 2641acbc6..46633eb67 100644 --- a/internal/server/signal/server.go +++ b/internal/server/signal/server.go @@ -1779,15 +1779,18 @@ func (s *Server) routePeerAssistedSignal(sess *session, source *authenticatedSes func (s *Server) routePeerAssistedRestart(sess *session, source *authenticatedSession, message protocol.ClientRestartRequestMessage) { targetPeerID := message.TargetPeerID - if targetPeerID == "" || !s.router.isActivePeerParentOf(source.roomID, targetPeerID, source.peerID) { - s.sendError(sess, "FORBIDDEN", "Restart target is not the assigned media parent") - return - } parent, hasParent := s.connectedPeer(source.roomID, targetPeerID) if !hasParent { s.sendError(sess, "PEER_NOT_FOUND", "Media parent is not connected") return } + if !s.router.peerRestartAuthorized(peerSignalInput{ + roomID: source.roomID, sourcePeerID: source.peerID, sourceSessionID: sess.sessionID, + targetPeerID: targetPeerID, targetSessionID: parent.SessionID, connectionID: message.ConnectionID, + }) { + s.sendError(sess, "FORBIDDEN", "Restart target is not the assigned media parent") + return + } s.sendToSession(parent.SessionID, protocol.ServerRestartRequestMessage{ Type: "restart-request", FromPeerID: source.peerID, diff --git a/internal/server/signal/server_test.go b/internal/server/signal/server_test.go index 00c0c2392..11c10accf 100644 --- a/internal/server/signal/server_test.go +++ b/internal/server/signal/server_test.go @@ -2780,6 +2780,77 @@ func TestSignalKeepsMediaIdentityThroughGraceWhilePresenceReturnsOnce(t *testing `{"fromPeerId":%q,"connectionId":"connection-during-grace","rebuild":false}`, firstViewerAuth.PeerID)) } +func TestSignalAllowsRetainedChildRestartWhileRelayRepairsIngress(t *testing.T) { + h := startHarness(t, harnessOptions{endpointMediaCopyCapacity: 1}) + host := openClient(t, h) + hostAuth := authenticate(t, host, h.room, protocol.RoleHost, "restart-host-client", 0, "", presenceOptions{}) + relay := openClient(t, h) + relayAuth := authenticate(t, relay, h.room, protocol.RoleViewer, "restart-relay-client", 1, "", presenceOptions{}) + commitPreparedRoute(t, relay) + child := openClient(t, h) + childAuth := authenticate(t, child, h.room, protocol.RoleViewer, "restart-child-client", 0, "", presenceOptions{}) + active := commitPreparedRoute(t, child) + if active.Assignment.Upstream != protocol.PeerUpstream(relayAuth.PeerID) { + t.Fatalf("child upstream = %v, want the relay", active.Assignment.Upstream) + } + var relayEdge, childEdge activeViewerMediaEdge + h.locked(func() { + var ok bool + relayEdge, ok = h.server.router.resolveActiveViewerMediaEdge(h.room.RoomID, relayAuth.PeerID) + if !ok { + t.Fatal("relay ingress must be active") + } + childEdge, ok = h.server.router.resolveActiveViewerMediaEdge(h.room.RoomID, childAuth.PeerID) + if !ok { + t.Fatal("child ingress must be active") + } + }) + relay.sendJSON(map[string]any{ + "type": "route-failed", "phase": "active", "revision": relayEdge.revision, + "connectionId": relayEdge.connectionID, + }) + repair := nextPreparedRoute(t, relay) + h.locked(func() { + rm, _ := h.server.router.rooms.Get(h.room.RoomID) + snapshot := rm.controller.Snapshot() + edge, ok := snapshot.UpstreamByViewer.Get(childAuth.PeerID) + if !ok || !edge.PhysicalActive || !edge.Usable || videoConnectionID(snapshot, edge) != childEdge.connectionID { + t.Fatal("relay repair must retain its child's physical connection") + } + if _, ok := h.server.router.resolveActiveViewerMediaEdge(h.room.RoomID, childAuth.PeerID); ok { + t.Fatal("a retained subtree must not claim the repairing source path is ready") + } + }) + child.sendJSON(map[string]any{ + "type": "restart-request", "targetPeerId": relayAuth.PeerID, + "connectionId": childEdge.connectionID, "rebuild": false, + }) + forwarded, ok := relay.tryNext("restart-request", defaultWait) + if !ok { + denial, _ := child.tryNext("error", 0) + t.Fatalf("retained child restart was not forwarded: %s", denial.raw) + } + expectMatch(t, forwarded.raw, fmt.Sprintf( + `{"fromPeerId":%q,"connectionId":%q,"rebuild":false}`, childAuth.PeerID, childEdge.connectionID)) + for _, request := range []map[string]any{ + {"type": "restart-request", "targetPeerId": hostAuth.PeerID, "connectionId": childEdge.connectionID, "rebuild": true}, + {"type": "restart-request", "targetPeerId": relayAuth.PeerID, "connectionId": "retired_connection_12345678", "rebuild": true}, + } { + child.sendJSON(request) + expectMatch(t, child.next("error").raw, `{"code":"FORBIDDEN"}`) + } + relay.sendJSON(map[string]any{ + "type": "restart-request", "targetPeerId": childAuth.PeerID, + "connectionId": childEdge.connectionID, "rebuild": true, + }) + expectMatch(t, relay.next("error").raw, `{"code":"FORBIDDEN"}`) + relay.sendJSON(map[string]any{ + "type": "restart-request", "targetPeerId": repair.Assignment.Upstream.PeerID, + "connectionId": repair.Candidate.ConnectionID, "rebuild": true, + }) + expectMatch(t, relay.next("error").raw, `{"code":"FORBIDDEN"}`) +} + // --------------------------------------------------------------------------- // capacity and abandonment // --------------------------------------------------------------------------- diff --git a/native/capture/windows/h264_encoder.cpp b/native/capture/windows/h264_encoder.cpp index aad9e30dc..3d143293d 100644 --- a/native/capture/windows/h264_encoder.cpp +++ b/native/capture/windows/h264_encoder.cpp @@ -506,6 +506,19 @@ std::vector ReadSample(IMFSample* sample) { } std::copy(raw, raw + current, bytes.begin()); Check(buffer->Unlock(), "output-buffer-unlock"); + // Some local MFTs encode Baseline Level 1b using level_idc 9. RFC 6184 + // represents it as level_idc 11 with constraint_set3 for this profile. + for (auto start = FindStartCode(bytes, 0); start;) { + const size_t nal = start->first + start->second; + const auto next = FindStartCode(bytes, nal); + const size_t end = next ? next->first : bytes.size(); + if (end - nal >= 4 && (bytes[nal] & 0x1f) == 7 && + bytes[nal + 1] == 0x42 && bytes[nal + 3] == 9) { + bytes[nal + 2] |= 0x10; + bytes[nal + 3] = 11; + } + start = next; + } return bytes; } diff --git a/native/capture/windows/main.cpp b/native/capture/windows/main.cpp index ecd1357a0..9b40576f2 100644 --- a/native/capture/windows/main.cpp +++ b/native/capture/windows/main.cpp @@ -1541,11 +1541,18 @@ struct CaptureInput final { UINT64 capture_timestamp = 0; }; -std::shared_ptr RefreshCaptureInput(const CaptureInput& latest) { +UINT64 NextPresentationTimestamp(UINT64 candidate, UINT64 previous) { + constexpr UINT64 rtp_tick_100ns = (10'000'000 + 90'000 - 1) / 90'000; + return std::max(candidate, previous + rtp_tick_100ns); +} + +std::shared_ptr RefreshCaptureInput( + const CaptureInput& latest, UINT64 previous_presentation) { auto input = std::make_shared(latest); // WGC SystemRelativeTime and MFGetSystemTime share the 100 ns QPC clock. - // A requested still frame is presented now, including after a quiet gap. - input->timestamp = static_cast(MFGetSystemTime()); + // Delayed capture can already have advanced presentation beyond the clock. + input->timestamp = NextPresentationTimestamp( + static_cast(MFGetSystemTime()), previous_presentation); return input; } @@ -1555,8 +1562,7 @@ std::optional CapturePresentationTimestamp( if (captured <= previous_capture || captured < minimum_capture) return std::nullopt; // A real frame can have been captured before a requested still was presented. // Retain its new pixels and keep separate access units at least one RTP tick apart. - constexpr UINT64 rtp_tick_100ns = (10'000'000 + 90'000 - 1) / 90'000; - return std::max(captured, previous_presentation + rtp_tick_100ns); + return NextPresentationTimestamp(captured, previous_presentation); } class OutputWorker final { @@ -2196,7 +2202,7 @@ void RunVideoCapture(ProductArguments arguments) { if (wait == WAIT_TIMEOUT) { // An explicit output/control request may reuse a quiet source; silence is not EOF. if (refresh_input && latest_input) { - submit(RefreshCaptureInput(*latest_input)); + submit(RefreshCaptureInput(*latest_input, previous_timestamp)); } continue; } diff --git a/native/capture/windows/output_worker.test.cpp b/native/capture/windows/output_worker.test.cpp index 4741fb774..06bb43f1c 100644 --- a/native/capture/windows/output_worker.test.cpp +++ b/native/capture/windows/output_worker.test.cpp @@ -71,7 +71,7 @@ void CheckQuietCaptureRefresh() { latest.capture_timestamp = latest.timestamp; const auto previous = latest.timestamp; const auto before = static_cast(MFGetSystemTime()); - const auto refreshed = RefreshCaptureInput(latest); + const auto refreshed = RefreshCaptureInput(latest, previous); const auto after = static_cast(MFGetSystemTime()); assert(refreshed->timestamp >= before && refreshed->timestamp <= after); assert(refreshed->timestamp - previous >= 50'000'000); @@ -81,6 +81,17 @@ void CheckQuietCaptureRefresh() { refreshed->presentation.cx == latest.presentation.cx && refreshed->presentation.cy == latest.presentation.cy && refreshed->color_space == latest.color_space && refreshed->texture.Get() == latest.texture.Get()); + // A delayed real frame can advance presentation beyond the current QPC time. + CaptureInput ahead = latest; + ahead.timestamp = after + 10'000'000; + const auto after_ahead = RefreshCaptureInput(latest, ahead.timestamp); + assert(after_ahead->timestamp > ahead.timestamp); + assert((after_ahead->timestamp - ahead.timestamp) * 90'000 >= 10'000'000); + const auto repeated = RefreshCaptureInput(latest, after_ahead->timestamp); + assert(repeated->timestamp > after_ahead->timestamp); + assert((repeated->timestamp - after_ahead->timestamp) * 90'000 >= 10'000'000); + assert(repeated->capture_timestamp == latest.capture_timestamp); + assert(latest.timestamp == previous); // The compositor changed the picture just before the refresh, but its frame // callback arrives afterwards. It is new capture input, not a stale still. const auto delayed_capture = before - 1; @@ -150,14 +161,16 @@ void CheckRetainedContentAtAdaptedCadence(ID3D11Device* device) { input->presentation = {64, 64}; input->timestamp = static_cast(MFGetSystemTime()); input->capture_timestamp = input->timestamp; + UINT64 previous_timestamp = 0; auto submit = [&](std::shared_ptr next) { for (auto& worker : workers) worker->Submit(next); + previous_timestamp = next->timestamp; }; const auto deadline = EncoderClock::now() + std::chrono::seconds(3); auto wait = [&](auto done) { while (!done()) { assert(EncoderClock::now() < deadline); - if (refresh.exchange(false)) submit(RefreshCaptureInput(*input)); + if (refresh.exchange(false)) submit(RefreshCaptureInput(*input, previous_timestamp)); std::this_thread::sleep_for(std::chrono::milliseconds(34)); } }; @@ -172,20 +185,20 @@ void CheckRetainedContentAtAdaptedCadence(ID3D11Device* device) { submit(input); wait([&] { return changed[0] > 0 && changed[1] > 0; }); // One rendition's drop must not reopen the other rendition's delivered content. - if (refresh.exchange(false)) submit(RefreshCaptureInput(*input)); + if (refresh.exchange(false)) submit(RefreshCaptureInput(*input, previous_timestamp)); std::this_thread::sleep_for(std::chrono::milliseconds(100)); assert(!refresh.load()); const auto before = keys[0].load(); workers[0]->RequestKeyFrame(); - submit(RefreshCaptureInput(*input)); + submit(RefreshCaptureInput(*input, previous_timestamp)); wait([&] { return keys[0] > before; }); - if (refresh.exchange(false)) submit(RefreshCaptureInput(*input)); + if (refresh.exchange(false)) submit(RefreshCaptureInput(*input, previous_timestamp)); std::this_thread::sleep_for(std::chrono::milliseconds(100)); assert(!refresh.load()); workers[0]->SetBitrate(profile.bit_rate); - submit(RefreshCaptureInput(*input)); + submit(RefreshCaptureInput(*input, previous_timestamp)); wait([&] { return published_bitrate[0] == profile.bit_rate; }); - if (refresh.exchange(false)) submit(RefreshCaptureInput(*input)); + if (refresh.exchange(false)) submit(RefreshCaptureInput(*input, previous_timestamp)); std::this_thread::sleep_for(std::chrono::milliseconds(100)); assert(!refresh.load()); for (auto& worker : workers) worker->Stop(); @@ -371,6 +384,37 @@ void CheckH264ProfileCompatibility() { CloseHandle(read); } +void CheckLocalH264Level1b() { + Runtime runtime; + // Include both start-code lengths, ordinary Baseline, a different profile, + // non-SPS data and a truncated SPS: only the local Baseline 1b bytes change. + const std::vector input{ + 0, 0, 0, 1, 0x67, 0x42, 0xc0, 9, 0x80, + 0, 0, 1, 0x67, 0x42, 0xe0, 9, 0x80, + 0, 0, 1, 0x67, 0x42, 0xc0, 31, 0x80, + 0, 0, 1, 0x67, 0x64, 0, 9, 0x80, + 0, 0, 1, 0x65, 0x42, 0xc0, 9, + 0, 0, 1, 0x67, 0x42, 0xc0}; + auto expected = input; + expected[6] = 0xd0; + expected[7] = 11; + expected[14] = 0xf0; + expected[15] = 11; + ComPtr sample; + Check(MFCreateSample(&sample), "fixture-sample"); + ComPtr buffer; + Check(MFCreateMemoryBuffer(static_cast(input.size()), &buffer), "fixture-buffer"); + BYTE* raw = nullptr; + Check(buffer->Lock(&raw, nullptr, nullptr), "fixture-lock"); + std::copy(input.begin(), input.end(), raw); + Check(buffer->Unlock(), "fixture-unlock"); + Check(buffer->SetCurrentLength(static_cast(input.size())), "fixture-length"); + Check(sample->AddBuffer(buffer.Get()), "fixture-add-buffer"); + assert(ReadSample(sample.Get()) == expected); + assert(SupportsH264ProfileLevelId("42d00b")); + assert(!SupportsH264ProfileLevelId("42c009")); +} + void CheckEncoderCandidates() { const std::vector candidates{{0, 0}, {1, 0}, {1, 1}, {2, 0}}; const EncoderCandidate preferred{1, 0}; @@ -747,6 +791,7 @@ int main() { CheckEncoderCandidates(); CheckQuietCaptureRefresh(); CheckH264ProfileCompatibility(); + CheckLocalH264Level1b(); CheckPrimaryFailureDetails(); CheckAudioCapabilityIsolation(); CheckOutputSampleAlignment(); diff --git a/scripts/app-browser-fanout-gate.ts b/scripts/app-browser-fanout-gate.ts index 280cb22f7..9f3ef1128 100644 --- a/scripts/app-browser-fanout-gate.ts +++ b/scripts/app-browser-fanout-gate.ts @@ -24,6 +24,7 @@ const probe = String.raw`(() => { localStorage.setItem('piik:ui-lang', 'en'); localStorage.setItem('piik:ui-mode', 'text'); const pcs = [], requests = [], sockets = [], errors = []; + let sourceAudioAvailable = null; window.addEventListener('unhandledrejection', (e) => errors.push(String(e.reason))); const codecPreferences = RTCRtpTransceiver.prototype.setCodecPreferences; RTCRtpTransceiver.prototype.setCodecPreferences = function(value) { @@ -36,6 +37,11 @@ const probe = String.raw`(() => { window.WebSocket = class extends WS { constructor(...args) { super(...args); if (String(args[0]).includes('/control')) { sockets.push(this); + } else if (new URL(String(args[0]), location.href).pathname === '/signal') { + this.addEventListener('message', ({data}) => { + const message = JSON.parse(data); + if (message.type === 'audio-presence') sourceAudioAvailable = message.available; + }); } } send(raw) { if (this.url.includes('/control')) { @@ -108,7 +114,7 @@ const probe = String.raw`(() => { edgeRequests: requests.filter((r) => r === 'prepare-edge').length, controlOpen: sockets.some((s) => s.readyState === WS.OPEN), codecSelected: [...document.querySelectorAll('button.lr-chip.is-selected')].map((b) => b.textContent), - audio: video?.srcObject?.getAudioTracks().length || 0, + audio: video?.srcObject?.getAudioTracks().length || 0, sourceAudioAvailable, buttons: [...document.querySelectorAll('.lr-host-share-slot button')].map((b) => b.getAttribute('aria-label')) }; } }; @@ -314,9 +320,10 @@ async function main(): Promise { await click(host, 'button[aria-label="Switch source"]'); await click(host, 'button[data-source-tab="browser"]'); await click(host, 'button.lr-source-option[aria-label="Choose what to share"]'); - await waitForSample(() => read(host), (s) => s.receiveRequests === 2 && s.captures === 2 && s.sharing, 15000); + await waitForSample(() => read(host), (s) => s.receiveRequests === 1 && s.captures === 2 && s.sharing, 15000); const beforeSource = await read(viewers[1]!); - await waitForSample(() => read(viewers[1]!), (s) => s.width > 0 && s.frames >= beforeSource.frames+20 && s.audio===Number(!initialAudio), 25000); + // Source sound changes independently of the stable mixed transport track. + await waitForSample(() => read(viewers[1]!), (s) => s.width > 0 && s.frames >= beforeSource.frames+20 && s.sourceAudioAvailable === !initialAudio, 25000); checks.sourceAudioChange = true; stage = "app-exit"; app.stdin.write("\n"); diff --git a/scripts/peer-assisted-benchmark.ts b/scripts/peer-assisted-benchmark.ts index 7d51d9c10..4a85d2786 100644 --- a/scripts/peer-assisted-benchmark.ts +++ b/scripts/peer-assisted-benchmark.ts @@ -2579,9 +2579,16 @@ async function startHost( return true; })()`, ); - await waitForPage(cdp, page, `document.querySelector('button.lr-source-option[aria-label="Choose what to share"]')`, - 5_000, "Browser capture choice", signal); - await evaluate(cdp, page, `document.querySelector('button.lr-source-option[aria-label="Choose what to share"]').click()`); + await waitForPage(cdp, page, `(() => { + const tab = document.querySelector('button[data-source-tab="browser"]'); + return tab instanceof HTMLButtonElement && !tab.disabled && tab.getClientRects().length > 0; + })()`, 5_000, "Browser capture tab", signal); + await evaluate(cdp, page, `document.querySelector('button[data-source-tab="browser"]').click()`); + await waitForPage(cdp, page, `(() => { + const choice = document.querySelector('[role="tabpanel"] button.lr-source-option'); + return choice instanceof HTMLButtonElement && !choice.disabled && choice.getClientRects().length > 0; + })()`, 5_000, "Browser capture choice", signal); + await evaluate(cdp, page, `document.querySelector('[role="tabpanel"] button.lr-source-option').click()`); await waitForPage( cdp, page, diff --git a/src/client/components/connection-details.ts b/src/client/components/connection-details.ts index 5d1522e98..3163cd8b6 100644 --- a/src/client/components/connection-details.ts +++ b/src/client/components/connection-details.ts @@ -27,6 +27,7 @@ export function summarizeConnectionMetrics(samples: readonly ConnectionMetricSam jitterMs: mean(numbers(metrics.map(metric => metric.jitterMs))), packetLossPercent: metrics.length === 1 ? metrics[0]!.packetLossPercent : direction === "send" ? mean(numbers(metrics.map(metric => metric.packetLossPercent))) + : packetSamples.length !== metrics.length ? null : packetLossPercentFromDeltas(sum(packetSamples.map(metric => metric.intervalPacketsReceived!)), sum(packetSamples.map(metric => metric.intervalPacketsLost!))), resolution: resolutions.length ? [resolutions[0]!, resolutions.at(-1)!] as const : null, framesPerSecond: frames.length ? [Math.min(...frames), Math.max(...frames)] as const : null, diff --git a/src/client/components/living/AppConnectionButton.tsx b/src/client/components/living/AppConnectionButton.tsx index d4fde8599..53a877190 100644 --- a/src/client/components/living/AppConnectionButton.tsx +++ b/src/client/components/living/AppConnectionButton.tsx @@ -9,6 +9,9 @@ import { HintComic } from "./hints"; import { LoadingStatus } from "./WaitingStatus"; import { useAnchoredPopover } from "./use-anchored-popover"; import { androidAppIntent } from "../../native/activation"; +import type { AppReleaseIdentity } from "../../lib/release-update"; +import { useReleaseUpdate } from "../../lib/use-release-update"; +import { AppReleaseNotice } from "./AppReleaseNotice"; interface AppConnectionProps { onConnected?: () => void; @@ -33,6 +36,12 @@ export function AppConnectionButton({ onConnected }: AppConnectionProps) { useAnchoredPopover(trigger, help); const pending = useRef(null); const healthCheck = useRef(null); + const [build, setBuild] = useState(); + const { update: release, refresh: checkRelease } = useReleaseUpdate(build); + function rememberBuild(health: Partial | null) { + setBuild(health?.version && health.revision + ? { version: health.version, revision: health.revision, packageTarget: health.packageTarget } : undefined); + } useEffect(() => { const refresh = async () => { if (pending.current || help.current?.matches(":popover-open") || !isClientActivated()) return; @@ -42,9 +51,13 @@ export function AppConnectionButton({ onConnected }: AppConnectionProps) { if (current.signal.aborted) return; try { const health = await native.discoverNativeHealth({ signal: current.signal, waitForPermission: false }); - if (!current.signal.aborted && !pending.current) setState(health ? "ready" : "idle"); + if (!current.signal.aborted && !pending.current) { + rememberBuild(health); + setState(health ? "ready" : "idle"); + } } catch (error) { if (!current.signal.aborted && !pending.current) { + rememberBuild(null); setState(error instanceof native.NativeCompatibilityError ? "incompatible" : "idle"); } } @@ -79,10 +92,16 @@ export function AppConnectionButton({ onConnected }: AppConnectionProps) { const verifyApproval = async (reported = false) => { if (approving || signal.aborted) return; approving = true; - const health = await native?.discoverNativeHealth({ signal }).catch(() => null); + const health = await native?.discoverNativeHealth({ signal, ...(manage ? { waitForPermission: false } : {}) }).catch(() => null); if (signal.aborted) return; approving = false; + if (manage) { + rememberBuild(health ?? null); + if (!health) finish("idle"); + return; + } if (health) { + rememberBuild(health); finish("ready"); activateClient(); onConnected?.(); @@ -112,7 +131,7 @@ export function AppConnectionButton({ onConnected }: AppConnectionProps) { attempt.cancel = () => finish(manage ? "ready" : "idle"); const onFocus = () => { if (waking) { attempt.open?.(); return; } - if (attempt.popup) void verifyApproval(); + if (attempt.popup || manage) void verifyApproval(); }; const onVisible = () => { if (document.visibilityState === "visible") onFocus(); }; window.addEventListener("message", onMessage); @@ -133,6 +152,7 @@ export function AppConnectionButton({ onConnected }: AppConnectionProps) { if (!url) { finish("unavailable"); return; } const health = await native.discoverNativeHealth({ signal, waitForPermission: false }); if (signal.aborted) return; + rememberBuild(health); manage = manage && health !== null; if (health && !manage) { finish("ready"); @@ -174,19 +194,23 @@ export function AppConnectionButton({ onConnected }: AppConnectionProps) { state === "waking" ? "client.connect.returnToBrowser" : state === "ready" ? "client.connect.manage" : state === "incompatible" ? "native.incompatible" : state === "unavailable" ? "client.connect.unavailable" : "client.connect.action"); const failed = state === "unavailable" || state === "incompatible"; - return <> @@ -208,6 +232,11 @@ export function AppConnectionButton({ onConnected }: AppConnectionProps) {

{state === "busy" ? t("client.connect.permissionHint") : label}

+ {state === "ready" && build &&

+ {t("client.launch.version", { version: build.version })} + {vis && } +

} + {update && }
{state !== "busy" &&
-

{t("client.connect.browserHint")}

+ {state !== "ready" &&

{t("client.connect.browserHint")}

} ; } diff --git a/src/client/components/living/AppReleaseNotice.tsx b/src/client/components/living/AppReleaseNotice.tsx index d3ac8c1bd..6a0c55110 100644 --- a/src/client/components/living/AppReleaseNotice.tsx +++ b/src/client/components/living/AppReleaseNotice.tsx @@ -15,21 +15,20 @@ export function AppReleaseNotice({ update }: { update: ReleaseUpdateNotice }) { const { vis, t } = useCopy(); const warningId = useId(); const major = update.kind === "major-update"; - const label = `${t(labels[update.kind])} · ${update.version}${update.extractAPK ? " (ZIP)" : ""}`; - const updateHint = major ? t("client.update.majorHint") : vis ? update.version : label; - const hint = update.extractAPK ? `${updateHint} ${t("client.update.extractAPK")}` : updateHint; + const label = `${t(labels[update.kind])} ${update.version}`; + const caption = major || update.kind === "update-available" ? t("client.update.download", { version: update.version }) : label; return ; +} diff --git a/src/client/lib/release-update.ts b/src/client/lib/release-update.ts index 3d5e15341..0061b7a28 100644 --- a/src/client/lib/release-update.ts +++ b/src/client/lib/release-update.ts @@ -2,21 +2,23 @@ import { compare, major, valid } from "semver"; export const DEFAULT_RELEASE_API_URL = "https://api.github.com/repos/TNTcraftHIM/Piik/releases/latest"; -export const MIRROR_RELEASE_API_URL = "https://gitee.com/api/v5/repos/TNTcraftHIM/Piik/releases"; +export const MIRROR_RELEASE_API_URL = "https://api.atomgit.com/api/v5/repos/TNTcraftHIM/Piik/releases"; const RELEASE_PAGE = "https://github.com/TNTcraftHIM/Piik/releases/tag/"; -const MIRROR_RELEASE_PAGE = "https://gitee.com/TNTcraftHIM/Piik/releases/tag/"; +const MIRROR_RELEASE_PAGE = "https://atomgit.com/TNTcraftHIM/Piik/releases"; export interface ReleaseIdentity { version: string; revision: string; } +export interface AppReleaseIdentity extends ReleaseIdentity { + packageTarget?: string; +} interface PublishedRelease { version: string; revision: string | null; url: string; releaseURL: string; publishedAt?: string; - extractAPK?: boolean; } export interface ReleaseUpdateNotice extends PublishedRelease { kind: "update-available" | "major-update" | "different-build" | "official-release"; @@ -32,25 +34,23 @@ function normalizeVersion(value: unknown): string | null { return version ? `v${version}` : null; } -function packageDownload(release: PublishedRelease, assets: unknown, target?: string): Pick { - if (!target || !/^[a-z0-9]+-[a-z0-9]+$/.test(target) || !Array.isArray(assets)) return { url: release.url }; - const android = target === "android-universal"; - const mirror = release.url.startsWith(MIRROR_RELEASE_PAGE); - const extension = android && !mirror ? "apk" : "zip"; +function packageDownloadURL(release: PublishedRelease, assets: unknown, target?: string): string { + if (!target || !/^[a-z0-9]+-[a-z0-9]+$/.test(target) || !Array.isArray(assets)) return release.url; + const extension = target === "android-universal" ? "apk" : "zip"; + const mirror = release.releaseURL === MIRROR_RELEASE_PAGE; const names = [`piik-app-${target}.${extension}`]; - if (release.revision && !android) names.push(`piik-app-${target}-${release.revision.slice(0, 7)}.zip`); + if (release.revision && extension === "zip") names.push(`piik-app-${target}-${release.revision.slice(0, 7)}.zip`); for (const name of names) { const matches = assets.filter(asset => asset?.name === name); if (!matches.length) continue; const asset = matches[0]; - const expectedURL = `${release.url.replace("/releases/tag/", "/releases/download/")}/${name}`; - return matches.length === 1 && (mirror || + const expectedURL = mirror ? `${MIRROR_RELEASE_PAGE}/download/${release.version}/${name}` + : `${release.releaseURL.replace("/releases/tag/", "/releases/download/")}/${name}`; + return matches.length === 1 && (mirror ? asset.type === "attach" : (Number.isSafeInteger(asset.size) && asset.size > 0 && asset.state === "uploaded")) && - asset.browser_download_url === expectedURL - ? { url: asset.browser_download_url, ...(android && mirror ? { extractAPK: true } : {}) } - : { url: release.url }; + asset.browser_download_url === expectedURL ? asset.browser_download_url : release.url; } - return { url: release.url }; + return release.url; } export function parseReleaseMetadata(value: unknown, packageTarget?: string): PublishedRelease | null { @@ -71,7 +71,7 @@ export function parseReleaseMetadata(value: unknown, packageTarget?: string): Pu releaseURL: RELEASE_PAGE + version, ...(Number.isFinite(publishedTime) ? { publishedAt: new Date(publishedTime).toISOString() } : {}), }; - return { ...normalized, ...packageDownload(normalized, release.assets, packageTarget) }; + return { ...normalized, url: packageDownloadURL(normalized, release.assets, packageTarget) }; } export function parseMirrorReleaseMetadata(value: unknown, packageTarget?: string): PublishedRelease | null { @@ -86,9 +86,9 @@ export function parseMirrorReleaseMetadata(value: unknown, packageTarget?: strin target_commitish: sources[0][1], }); if (!normalized) return null; - const mirror = { ...normalized, url: MIRROR_RELEASE_PAGE + normalized.version, - releaseURL: MIRROR_RELEASE_PAGE + normalized.version }; - return { ...mirror, ...packageDownload(mirror, release.assets, packageTarget) }; + const mirror = { ...normalized, url: MIRROR_RELEASE_PAGE, + releaseURL: MIRROR_RELEASE_PAGE }; + return { ...mirror, url: packageDownloadURL(mirror, release.assets, packageTarget) }; } export function releaseUpdateNotice( diff --git a/src/client/lib/use-release-update.ts b/src/client/lib/use-release-update.ts new file mode 100644 index 000000000..3f912701e --- /dev/null +++ b/src/client/lib/use-release-update.ts @@ -0,0 +1,20 @@ +import { useEffect, useState } from "react"; +import { checkReleaseUpdate, type AppReleaseIdentity, type ReleaseUpdateNotice } from "./release-update"; + +/** Each surface checks the connected App build, independently of the Site build. */ +export function useReleaseUpdate(identity?: AppReleaseIdentity) { + const version = identity?.version, revision = identity?.revision, packageTarget = identity?.packageTarget; + const key = JSON.stringify([version, revision, packageTarget]); + const [result, setResult] = useState<{ key: string; notice: ReleaseUpdateNotice | null }>(); + const [check, setCheck] = useState(0); + useEffect(() => { + if (!version || !revision) return; + let current = true; + void checkReleaseUpdate({ version, revision }, { packageTarget }).then(notice => { + if (current) setResult({ key, notice }); + }).catch(() => undefined); + return () => { current = false; }; + }, [version, revision, packageTarget, key, check]); + return { update: result?.key === key ? result.notice : null, + refresh: () => setCheck(value => value + 1) }; +} diff --git a/src/client/locales/en.ts b/src/client/locales/en.ts index d10956af9..fae37444f 100644 --- a/src/client/locales/en.ts +++ b/src/client/locales/en.ts @@ -251,6 +251,7 @@ export const en: Record = { "client.connect.remove": "Revoke this Site's App access", "client.connect.openOnStart": "Open this site when App starts", "client.connect.manage": "App is ready. Manage App.", + "client.connect.update": "App {current}. Update to {version}.", "client.connect.approveTitle": "Allow this Site to use Piik App?", "client.connect.approveHint": "This Site will be able to use this device's screens, windows and microphone. Check that you trust this address.", "client.connect.approve": "Allow access", @@ -296,8 +297,8 @@ export const en: Record = { "client.update.available": "A newer Piik release is available", "client.update.major": "New major Piik release", "client.update.majorHint": "This update includes breaking changes. Read the release notes before upgrading.", - "client.update.downloads": "Gitee mirror", - "client.update.extractAPK": "Extract the ZIP, then install the APK.", + "client.update.downloads": "AtomGit mirror", + "client.update.download": "Download {version}", "client.update.differentBuild": "This build differs from the official release", "client.update.official": "An official Piik release is available", @@ -311,6 +312,8 @@ export const en: Record = { "gate.malformed": "Invalid room code format", "gate.malformedHint": "Enter a four-digit room code between 1000 and 9999", "gate.unavailableRoute": "Unavailable", + "startup.failed": "Page couldn’t load", + "startup.retry": "Refresh the page to try again.", "join.title": "Join a room", "join.hint": "Enter a room code for {site}", diff --git a/src/client/locales/zh.ts b/src/client/locales/zh.ts index 04c1dd7c1..4ca84e47f 100644 --- a/src/client/locales/zh.ts +++ b/src/client/locales/zh.ts @@ -251,6 +251,7 @@ export const zh = { "client.connect.remove": "取消此站点的 App 授权", "client.connect.openOnStart": "启动 App 时打开此站点", "client.connect.manage": "App 已就绪,点击管理。", + "client.connect.update": "App {current},可更新至 {version}。", "client.connect.approveTitle": "允许使用 Piik App?", "client.connect.approveHint": "此站点将可以使用本机的屏幕、窗口和麦克风。请确认你信任这个网址。", "client.connect.approve": "允许使用", @@ -296,8 +297,8 @@ export const zh = { "client.update.available": "发现新的 Piik 版本", "client.update.major": "发现新的 Piik 大版本", "client.update.majorHint": "此更新含不兼容改动。升级前请查看版本说明。", - "client.update.downloads": "Gitee 备用下载", - "client.update.extractAPK": "解压 ZIP 后安装 APK。", + "client.update.downloads": "AtomGit 备用下载", + "client.update.download": "下载 {version}", "client.update.differentBuild": "当前构建与官方发行版不同", "client.update.official": "可获取 Piik 正式发行版", @@ -311,6 +312,8 @@ export const zh = { "gate.malformed": "房间号格式不正确", "gate.malformedHint": "请输入 1000 至 9999 的四位房间号", "gate.unavailableRoute": "无法访问", + "startup.failed": "页面未能加载", + "startup.retry": "请刷新页面后重试。", "join.title": "加入房间", "join.hint": "输入 {site} 的房间号", diff --git a/src/client/main.tsx b/src/client/main.tsx index a596555e7..c153fc909 100644 --- a/src/client/main.tsx +++ b/src/client/main.tsx @@ -1,12 +1,19 @@ import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; import { App } from "./App"; +import { StartupFailure } from "./components/living/StartupFailure"; import "./styles.css"; async function main() { + let app = ; // Room controls share the Popover API; install it before any component mounts. if (!("popover" in HTMLElement.prototype)) { - await import("./ui/popover-polyfill"); + try { + await import("./ui/popover-polyfill"); + } catch (error) { + console.error("Could not initialize page controls", error); + app = ; + } } const root = document.getElementById("root"); @@ -16,7 +23,7 @@ async function main() { createRoot(root).render( - + {app} , ); } diff --git a/src/client/media/browser-encoding-pool.ts b/src/client/media/browser-encoding-pool.ts index 2551d98b7..b50c55730 100644 --- a/src/client/media/browser-encoding-pool.ts +++ b/src/client/media/browser-encoding-pool.ts @@ -2,6 +2,7 @@ import { createOpaqueId } from "../lib/opaque-id"; import { browserDebugEnabled, debugError, debugEvent } from "../lib/debug"; import { EMPTY_METRICS, type ConnectionMetrics } from "../types"; import { captureMetrics, collectConnectionMetricsFromReport, createStatsAccumulator } from "../webrtc/stats"; +import { waitForConnectionOperation } from "../webrtc/connection-operation"; import { BrowserEncodingProducer } from "./browser-encoding-producer"; import { BROWSER_CARRIER_SIZE, type BrowserEncodingOutput } from "./browser-encoding-output"; import { codecIdentity, fits, nativeVideoBudget, negotiatedCodec, noRegression, observeVideo, @@ -28,7 +29,7 @@ type Member = { profile: QualityProfile; encoded: BrowserEncodingOutput; configureCarrier: () => Promise; requestKey: () => Promise; onFatal: () => void; - paused: boolean; disabled: boolean; disposed: boolean; mixed: boolean; carrier: boolean; + paused: boolean; disabled: boolean; readonly disposed: boolean; abort: AbortController; mixed: boolean; carrier: boolean; codec?: RTCRtpCodec; codecKey?: string; budget?: number; raw?: RTCOutboundRtpStreamStats; encoderStats: ReturnType; current?: Group; pending?: { group: Group; selecting?: boolean }; @@ -53,7 +54,8 @@ export class BrowserEncodingPool { onFatal: () => void): BrowserPooledSender | null { if (this.disposed || this.failedSources.has(source) || source.kind !== "video" || source.readyState !== "live") return null; const member: Member = { id: createOpaqueId(), source, sender, connection, profile: { ...profile }, encoded, configureCarrier, requestKey, onFatal, - paused: !source.enabled, disabled: false, disposed: false, mixed: false, carrier: encoded.snapshot().frames === 0, + paused: !source.enabled, disabled: false, abort: new AbortController(), + get disposed() { return this.abort.signal.aborted; }, mixed: false, carrier: encoded.snapshot().frames === 0, encoderStats: createStatsAccumulator() }; this.members.add(member); // A fresh connection has no useful raw output to preserve. Start its @@ -153,7 +155,7 @@ export class BrowserEncodingPool { await Promise.allSettled([ ...[...this.members].map(async (member) => { if (member.disposed || member.disabled || member.connection.connectionState !== "connected") { member.budget = undefined; return; } - const report = await member.connection.getStats().catch(() => null); + const report = await waitForConnectionOperation(member.abort.signal, () => member.connection.getStats()).catch(() => null); if (member.disposed) return; if (!report) { member.budget = undefined; return; } const codec = negotiatedCodec(report); @@ -409,7 +411,7 @@ export class BrowserEncodingPool { private remove(member: Member): void { if (member.disposed) return; - member.disposed = true; + member.abort.abort(); this.members.delete(member); member.encoded.passthrough(member.requestKey); member.carrier = false; diff --git a/src/client/media/browser-encoding-producer.ts b/src/client/media/browser-encoding-producer.ts index a7e57c9e8..5439b5e4e 100644 --- a/src/client/media/browser-encoding-producer.ts +++ b/src/client/media/browser-encoding-producer.ts @@ -11,6 +11,7 @@ import { videoQualitySettingsEqual, type QualityProfile, } from "./quality"; import { cloneSenderVideoTrack, stopSenderVideoTrack } from "./sender-video-track"; +import { waitForConnectionOperation } from "../webrtc/connection-operation"; // Leave time for ordinary encoding before the outer Viewer/route deadline. // Bound local transport setup, not frame production from a quiet source. @@ -163,7 +164,10 @@ export class BrowserEncodingProducer { async report(): Promise { this.requireSender(); const connection = this.send!; - const report = await connection.getStats().catch((error) => { debugRtcFailure(connection, error); throw error; }); + const report = await waitForConnectionOperation(this.streamAbort.signal, () => connection.getStats()).catch((error) => { + if (!this.disposed) debugRtcFailure(connection, error); + throw error; + }); debugRtcStats(connection, report); if (!this.disposed && this.startupPending && (this.startupFrames ?? 0) >= STARTUP_VIDEO_ENCODED_FRAMES) { diff --git a/src/client/media/candidate-quality-probe.ts b/src/client/media/candidate-quality-probe.ts index ff515a4f5..3726c4cbf 100644 --- a/src/client/media/candidate-quality-probe.ts +++ b/src/client/media/candidate-quality-probe.ts @@ -5,7 +5,7 @@ interface DeliveredVideoSample { timestampMs: number; windowMs: number; pixels: number; - framesPerSecond: number; + framesDecoded: number; bitrateKbps: number | null; } @@ -28,7 +28,7 @@ function deliveredNothingSample( timestampMs: sampleTimestampMs, windowMs: sampleWindowMs, pixels: 0, - framesPerSecond: 0, + framesDecoded: 0, bitrateKbps: 0, }; } @@ -67,8 +67,7 @@ function deliveredVideoSample( timestampMs: sampleTimestampMs, windowMs: sampleWindowMs, pixels: frameWidth * frameHeight, - // Native framesPerSecond covers the last second, not this comparison window. - framesPerSecond: Math.round((intervalFramesDecoded * 1_000) / sampleWindowMs), + framesDecoded: intervalFramesDecoded, bitrateKbps: typeof bitrateKbps === "number" && Number.isFinite(bitrateKbps) && @@ -103,6 +102,24 @@ function comparableSamples( return [currentVideo, candidateVideo]; } +function frameRateDoesNotRegress( + current: DeliveredVideoSample, + candidate: DeliveredVideoSample, +): boolean { + return frameCountDeficit( + current.framesDecoded, current.windowMs, + candidate.framesDecoded, candidate.windowMs, + ) <= 1; +} + +function frameCountDeficit( + currentFrames: number, currentWindowMs: number, + candidateFrames: number, candidateWindowMs: number, +): number { + // Normalize discrete counters to one window; a boundary frame is not a rate change. + return Math.round(currentFrames * candidateWindowMs / currentWindowMs) - candidateFrames; +} + export function sfuCandidateDoesNotRegress( current: ConnectionMetrics, candidate: ConnectionMetrics, @@ -122,7 +139,7 @@ export function sfuCandidateDoesNotRegress( candidate.intervalPauseCount === 0 && candidate.intervalPauseDurationMs === 0 && candidateVideo.pixels >= currentVideo.pixels && - candidateVideo.framesPerSecond >= currentVideo.framesPerSecond && + frameRateDoesNotRegress(currentVideo, candidateVideo) && candidateVideo.bitrateKbps >= currentVideo.bitrateKbps ); } @@ -140,7 +157,7 @@ export function p2pCandidateDoesNotRegress( candidate.intervalPauseCount === 0 && candidate.intervalPauseDurationMs === 0 && candidateVideo.pixels >= currentVideo.pixels && - candidateVideo.framesPerSecond >= currentVideo.framesPerSecond + frameRateDoesNotRegress(currentVideo, candidateVideo) ); } @@ -149,6 +166,7 @@ class ConsecutiveCandidateQualityProbe { private lastCurrentTimestampMs: number | null = null; private consecutiveApprovedWindows = 0; private consecutiveRejectedWindows = 0; + private consecutiveFrameDeficit = 0; constructor( private readonly compare: ( @@ -197,14 +215,23 @@ class ConsecutiveCandidateQualityProbe { return "pending"; } if (approved) { + // The whole proof run shares one frame of resolution, not one per window. + this.consecutiveFrameDeficit += frameCountDeficit( + current.intervalFramesDecoded!, current.sampleWindowMs!, + candidate.intervalFramesDecoded!, candidate.sampleWindowMs!, + ); + if (this.consecutiveFrameDeficit > 1) { + this.resetRuns(); + return "pending"; + } this.consecutiveApprovedWindows += 1; this.consecutiveRejectedWindows = 0; - return this.consecutiveApprovedWindows >= - PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS + return this.consecutiveApprovedWindows >= PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS ? "approved" : "pending"; } this.consecutiveApprovedWindows = 0; + this.consecutiveFrameDeficit = 0; this.consecutiveRejectedWindows += 1; return this.consecutiveRejectedWindows >= PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS @@ -221,6 +248,7 @@ class ConsecutiveCandidateQualityProbe { private resetRuns(): void { this.consecutiveApprovedWindows = 0; this.consecutiveRejectedWindows = 0; + this.consecutiveFrameDeficit = 0; } } diff --git a/src/client/media/host-sfu-route.ts b/src/client/media/host-sfu-route.ts index e7944c374..c7b3ed2c4 100644 --- a/src/client/media/host-sfu-route.ts +++ b/src/client/media/host-sfu-route.ts @@ -44,6 +44,7 @@ export interface HostPublisherTransport { interface HostPublisherSlot { revision: number; + activationToken: RouteOperationToken | null; connectionId: string; publicationGeneration: string; publisher: HostPublisherTransport; @@ -56,7 +57,7 @@ interface HostSfuRouteEvents { getStream: () => MediaStream | null; getProfile: () => QualityProfile; getVideoCodec: () => BrowserVideoCodec; - reconcileChildren: (childPeerIds: string[]) => void; + reconcileChildren: (assignment: ParticipantRouteAssignment, revision: number) => void; send: (message: ClientMessage) => boolean; onSenderUpdate?: ( metrics: ConnectionMetrics, @@ -102,8 +103,8 @@ export class HostSfuRoute { update.assignment.sfuPublicationGeneration, ) : null; - if (pausedActiveReconciliation) { - this.events.reconcileChildren(update.assignment.childPeerIds); + if (update.phase === "active" && result !== "duplicate") { + this.events.reconcileChildren(update.assignment, update.revision); } if (this.paused && update.phase === "prepare") { this.clearPending(); @@ -113,10 +114,19 @@ export class HostSfuRoute { this.recovery = null; this.lastFailureStage = null; } + if ( + update.phase === "active" && this.pending && + this.pending.publicationGeneration === update.assignment.sfuPublicationGeneration && + (this.pending.revision === update.revision || this.pending.activationToken) + ) { + this.pending.activationToken = this.route.getActiveToken(); + this.pending.revision = update.revision; + this.pending.publisher.updateConfig(this.pending); + } if (update.phase === "prepare") { if ( this.pending && - (this.pending.revision !== update.revision || + ((!this.pending.activationToken && this.pending.revision !== update.revision) || this.pending.publicationGeneration !== update.assignment.sfuPublicationGeneration) ) { @@ -128,7 +138,7 @@ export class HostSfuRoute { return result; } - const token = this.route.token(); + const token = this.route.getActiveToken(); if (retiredActive) { void this.queueTransition(() => this.disconnectRetiredPublisher(retiredActive), @@ -163,8 +173,12 @@ export class HostSfuRoute { this.route.reset(); this.recovery = null; const closing = this.retirePublishers(); - const accepted = this.route.accept(update); - this.events.reconcileChildren([]); + this.events.reconcileChildren({ + upstream: { kind: "none" }, + childPeerIds: [], + sfuPublicationGeneration: null, + }, update.revision); + const accepted = this.accept(update); await this.queueTransition(() => closing); @@ -172,8 +186,8 @@ export class HostSfuRoute { return "stale"; } this.resyncing = false; - const token = this.route.token(); - if (token && this.route.getPhase() === "active") { + const token = this.route.getActiveToken(); + if (token) { await this.queueActivation(token); } return accepted; @@ -215,7 +229,8 @@ export class HostSfuRoute { return; } if ( - this.pending?.revision === message.revision && + this.pending && + (this.pending.revision === message.revision || this.pending.activationToken) && this.pending.publicationGeneration === publicationGeneration && this.pending.connectionId === message.connectionId && !this.pending.failed @@ -238,6 +253,7 @@ export class HostSfuRoute { }); slot = { revision: message.revision, + activationToken: phase === "active" ? this.route.getActiveToken() : null, connectionId: message.connectionId, publicationGeneration, publisher, @@ -249,7 +265,7 @@ export class HostSfuRoute { try { const connected = await publisher.connect(message); if (!connected) { - if (this.pending === slot && this.route.owns(token)) { + if (this.pending === slot && this.ownsPublisherSlot(slot)) { this.handleFailure(slot); } else { if (this.pending === slot) { @@ -260,7 +276,7 @@ export class HostSfuRoute { await this.disconnectPublisher(slot); return; } - if (this.pending !== slot || !this.route.owns(token)) { + if (this.pending !== slot || !this.ownsPublisherSlot(slot)) { if (this.pending === slot) { this.pending = null; } @@ -271,7 +287,7 @@ export class HostSfuRoute { slot.connected = true; let prepared = false; await this.queueTransition(async () => { - if (this.pending !== slot || !this.route.owns(token)) { + if (this.pending !== slot || !this.ownsPublisherSlot(slot)) { if (this.pending === slot) { this.pending = null; } @@ -284,8 +300,8 @@ export class HostSfuRoute { if (!prepared) { return; } - if (phase === "active" && !this.resyncing) { - await this.queueActivation(token); + if (slot.activationToken && !this.resyncing) { + await this.queueActivation(slot.activationToken); } } catch { this.failPublisherSlot(slot); @@ -308,7 +324,7 @@ export class HostSfuRoute { slot && !slot.failed && slot.connectionId === message.connectionId && slot.publicationGeneration === message.publicationGeneration, ); - if (slot === this.pending && slot?.revision !== message.revision) return; + if (slot === this.pending && !slot?.activationToken && slot?.revision !== message.revision) return; await slot?.publisher.acceptSignal(message); } @@ -417,8 +433,12 @@ export class HostSfuRoute { token: RouteOperationToken, retireUnreferenced = false, ): Promise { + const pending = this.pending; return this.queueTransition(async () => { - if (this.closed || this.resyncing || !this.route.owns(token, "active")) { + if ( + this.closed || this.resyncing || !this.route.ownsActive(token) || + (pending?.activationToken && this.pending !== pending && this.active !== pending) + ) { return; } const assignment = this.route.getActiveAssignment(); @@ -429,11 +449,11 @@ export class HostSfuRoute { assignment.sfuPublicationGeneration ) { await this.retireActive(); - if (!this.route.owns(token, "active")) { + if (!this.route.ownsActive(token)) { return; } } - await this.activate(assignment, token); + await this.activate(assignment, token, pending); } }); } @@ -447,20 +467,19 @@ export class HostSfuRoute { private async activate( assignment: ParticipantRouteAssignment, token: RouteOperationToken, + pendingAtQueue: HostPublisherSlot | null, ): Promise { const publicationGeneration = assignment.sfuPublicationGeneration; if (publicationGeneration === null) { - this.clearPending(); + if (this.pending === pendingAtQueue) this.clearPending(); await this.retireActive(); - if (!this.route.owns(token, "active")) { + if (!this.route.ownsActive(token)) { return; } - this.events.reconcileChildren(assignment.childPeerIds); this.commitMedia(token); return; } - this.events.reconcileChildren(assignment.childPeerIds); if ( this.active && !this.active.failed && @@ -468,8 +487,9 @@ export class HostSfuRoute { this.pending?.publicationGeneration !== publicationGeneration ) { this.active.revision = token.revision; + this.active.activationToken = token; this.active.publisher.updateConfig(this.active); - this.clearPending(); + if (this.pending === pendingAtQueue) this.clearPending(); if (this.active.active) { this.commitMedia(token); } @@ -484,7 +504,7 @@ export class HostSfuRoute { !pending.connected || !pending.active ) { - if (this.route.owns(token, "active")) { + if (this.route.ownsActive(token)) { this.requestRecovery(token.revision); } return; @@ -558,6 +578,7 @@ export class HostSfuRoute { } private ownsPublisherSlot(slot: HostPublisherSlot): boolean { + if (slot.activationToken) return this.route.ownsActive(slot.activationToken); return ( this.route.getRevision() === slot.revision && this.route.getPlannedAssignment()?.sfuPublicationGeneration === @@ -624,6 +645,8 @@ export class HostSfuRoute { } const wasActive = this.active === slot; const wasPending = this.pending === slot; + const wasCommitted = slot.activationToken !== null && + this.route.ownsActive(slot.activationToken); if (!wasActive && !wasPending) { slot.failed = true; return; @@ -649,7 +672,7 @@ export class HostSfuRoute { } if (phase === "prepare") { const activeRevision = this.route.getActiveRevision(); - if (wasActive) { + if (wasActive || wasCommitted) { if ( activeRevision !== null && this.route.getActiveAssignment()?.sfuPublicationGeneration === diff --git a/src/client/media/route-transition.ts b/src/client/media/route-transition.ts index 1303c6634..8c1efdc9a 100644 --- a/src/client/media/route-transition.ts +++ b/src/client/media/route-transition.ts @@ -43,7 +43,7 @@ export class MediaRouteTransition { private plannedAssignment: ParticipantRouteAssignment | null = null; private activeAssignment: ParticipantRouteAssignment | null = null; // Preparation advances the operation without replacing committed authority. - private activeRevision: number | null = null; + private activeToken: RouteOperationToken | null = null; private mediaAssignment: ParticipantRouteAssignment | null = null; private preparedCandidate: PreparedRouteCandidate | null = null; private generation = 0; @@ -73,11 +73,11 @@ export class MediaRouteTransition { this.plannedAssignment = cloneAssignment(update.assignment); this.preparedCandidate = update.phase === "prepare" ? cloneCandidate(update.candidate) : null; + this.generation += 1; if (update.phase === "active") { this.activeAssignment = cloneAssignment(update.assignment); - this.activeRevision = update.revision; + this.activeToken = { revision: update.revision, generation: this.generation }; } - this.generation += 1; return "accepted"; } @@ -101,7 +101,7 @@ export class MediaRouteTransition { } markMediaActive(token: RouteOperationToken): boolean { - if (!this.owns(token, "active") || !this.activeAssignment) { + if (!this.ownsActive(token) || !this.activeAssignment) { return false; } this.mediaAssignment = cloneAssignment(this.activeAssignment); @@ -127,7 +127,16 @@ export class MediaRouteTransition { } getActiveRevision(): number | null { - return this.activeRevision; + return this.activeToken?.revision ?? null; + } + + getActiveToken(): RouteOperationToken | null { + return this.activeToken ? { ...this.activeToken } : null; + } + + ownsActive(token: RouteOperationToken): boolean { + return token.revision === this.activeToken?.revision && + token.generation === this.activeToken.generation; } getMediaAssignment(): ParticipantRouteAssignment | null { @@ -145,7 +154,7 @@ export class MediaRouteTransition { this.phase = null; this.plannedAssignment = null; this.activeAssignment = null; - this.activeRevision = null; + this.activeToken = null; this.mediaAssignment = null; this.preparedCandidate = null; this.generation += 1; diff --git a/src/client/media/viewer-presentation.ts b/src/client/media/viewer-presentation.ts index 535770944..dc7c629dc 100644 --- a/src/client/media/viewer-presentation.ts +++ b/src/client/media/viewer-presentation.ts @@ -219,7 +219,9 @@ export function reduceViewerPresentation( }, routeStatus: action.authoritative ? null - : !committedRoute && state.routeStatus?.revision === action.revision + : !committedRoute && + (state.routeStatus?.revision === action.revision || + (action.kind === "none" && state.routeStatus?.state === "failed")) ? state.routeStatus : null, connection: action.authoritative && state.media === null diff --git a/src/client/media/viewer-sfu-route.ts b/src/client/media/viewer-sfu-route.ts index 7f84f8528..f99718212 100644 --- a/src/client/media/viewer-sfu-route.ts +++ b/src/client/media/viewer-sfu-route.ts @@ -107,7 +107,11 @@ export class ViewerSfuRoute { private readonly route = new MediaRouteTransition(); private pending: ViewerSubscriberSlot | null = null; private active: ViewerSubscriberSlot | null = null; - private pendingPeer: { revision: number; connectionId: string } | null = null; + private pendingPeer: { + revision: number; + connectionId: string; + activationToken: RouteOperationToken | null; + } | null = null; private transitionTail: Promise = Promise.resolve(); private resyncGeneration = 0; private resyncing = false; @@ -123,12 +127,7 @@ export class ViewerSfuRoute { if (this.closed) { return "stale"; } - const previousRevision = this.route.getRevision(); - const previousMediaAssignment = this.route.getMediaAssignment(); - const sameCommittedMedia = sameUpstream( - previousMediaAssignment, - update.assignment, - ); + const previousActiveAssignment = this.route.getActiveAssignment(); const result = this.route.accept(update); if (result === "stale") { return result; @@ -141,7 +140,8 @@ export class ViewerSfuRoute { const retiredActive = pausedActiveReconciliation ? this.detachUnreferencedActive(update.assignment) : null; - if (pausedActiveReconciliation) { + // Committed child permissions cannot wait for unrelated upstream SDP. + if (update.phase === "active" && result !== "duplicate") { this.activateChildren(update.assignment.childPeerIds, update.revision); } if (this.paused && update.phase === "prepare") { @@ -156,13 +156,28 @@ export class ViewerSfuRoute { this.disconnectRetiredSubscriber(retiredActive), ); } - if (previousRevision !== update.revision && !sameCommittedMedia) { - if ( - update.phase !== "prepare" && - this.pendingPeer !== null - ) { - this.events.preparePeer?.(null); - this.pendingPeer = null; + if (update.phase === "active") { + const token = this.route.getActiveToken()!; + if (this.pendingPeer) { + if (update.assignment.upstream.kind === "peer" && + (this.pendingPeer.revision === update.revision || + (this.pendingPeer.activationToken && sameUpstream(previousActiveAssignment, update.assignment)))) { + this.pendingPeer.activationToken = token; + } else { + this.pendingPeer = null; + this.events.preparePeer?.(null); + } + } + if (this.pending) { + if (update.assignment.upstream.kind === "sfu" && + this.pending.publicationGeneration === update.assignment.sfuPublicationGeneration && + (this.pending.revision === update.revision || this.pending.activationToken)) { + this.pending.activationToken = token; + this.pending.revision = update.revision; + this.pending.subscriber.updateConfig(this.pending); + } else { + this.clearPending(); + } } } if (update.phase === "prepare") { @@ -176,33 +191,39 @@ export class ViewerSfuRoute { ownsChildCandidate ? update.assignment.childPeerIds : undefined, ownsChildCandidate ? update.revision : undefined, ); + if (!ownsUpstreamCandidate) { + // A child operation cannot retire an incoming resource already committed + // by the server, even while its local activation is still queued. + if (this.pendingPeer && !this.pendingPeer.activationToken) { + this.pendingPeer = null; + this.events.preparePeer?.(null); + } + if (this.pending && !this.pending.activationToken) this.clearPending(); + return result; + } + const replacedPeerCandidate = this.pendingPeer !== null; + if (replacedPeerCandidate) { + this.events.preparePeer?.(null); + this.pendingPeer = null; + } const needsPeerCandidate = - ownsUpstreamCandidate && candidate.transport !== "sfu" && update.assignment.upstream.kind === "peer" && candidate.connectionId.length > 0; - const replacedPeerCandidate = this.pendingPeer !== null; - if (replacedPeerCandidate) { - this.pendingPeer = null; - this.events.preparePeer?.(null); - } if (needsPeerCandidate && update.assignment.upstream.kind === "peer") { this.pendingPeer = { revision: update.revision, connectionId: candidate.connectionId, + activationToken: null, }; this.events.preparePeer?.(update.assignment, update.revision, candidate); - } else if ( - update.assignment.upstream.kind !== "peer" && - !replacedPeerCandidate - ) { + } else if (update.assignment.upstream.kind !== "peer" && !replacedPeerCandidate) { this.events.preparePeer?.(null); } if (this.pending?.revision !== update.revision) { this.clearPending(); } if ( - !ownsUpstreamCandidate || candidate.transport !== "sfu" || update.assignment.upstream.kind !== "sfu" ) { @@ -211,11 +232,11 @@ export class ViewerSfuRoute { return result; } - const token = this.route.token(); + const token = this.route.getActiveToken(); if (!token) { return result; } - if (this.pendingPeer?.revision !== update.revision) { + if (!this.pendingPeer) { this.preparePeer(update.assignment); } if (this.resyncing) { @@ -293,7 +314,6 @@ export class ViewerSfuRoute { if (identityChanged) { this.viewerPeerId = viewerPeerId; } - this.pendingPeer = null; const currentMediaAssignment = this.route.getMediaAssignment(); const preservesActiveMedia = Boolean( !identityChanged && @@ -327,6 +347,7 @@ export class ViewerSfuRoute { const resyncGeneration = ++this.resyncGeneration; this.resyncing = true; + this.pendingPeer = null; this.route.reset(); this.events.prepareChild?.(null); const pending = this.pending; @@ -342,6 +363,9 @@ export class ViewerSfuRoute { const accepted = this.route.accept(update); this.preparePeer(update.assignment); this.events.resetMedia?.(); + if (update.phase === "active") { + this.activateChildren(update.assignment.childPeerIds, update.revision); + } await this.queueTransition(async () => { if (active?.activated) { @@ -363,8 +387,8 @@ export class ViewerSfuRoute { return "stale"; } this.resyncing = false; - const token = this.route.token(); - if (token && this.route.getPhase() === "active") { + const token = this.route.getActiveToken(); + if (token) { await this.queueActiveRoute(token, false); } return accepted; @@ -461,11 +485,6 @@ export class ViewerSfuRoute { ); if (slot.qualityResult === "approved") { this.sendPendingReady(slot); - } else if ( - slot.qualityResult === "rejected" && - this.routeFailed(slot.revision, "prepare") - ) { - this.clearPending(); } } } @@ -558,9 +577,9 @@ export class ViewerSfuRoute { } retryPeerActivation(connectionId: string): boolean { - const token = this.route.token(); - if (this.closed || this.resyncing || !token || !this.route.owns(token, "active") || - this.pendingPeer?.revision !== token.revision || this.pendingPeer.connectionId !== connectionId) return false; + const token = this.pendingPeer?.activationToken; + if (this.closed || this.resyncing || !token || !this.route.ownsActive(token) || + this.pendingPeer?.connectionId !== connectionId) return false; void this.queueActiveRoute(token, false); return true; } @@ -570,7 +589,7 @@ export class ViewerSfuRoute { slot && !slot.failed && slot.connectionId === message.connectionId && slot.publicationGeneration === message.publicationGeneration, ); - if (slot === this.pending && slot?.revision !== message.revision) return; + if (slot === this.pending && !slot?.activationToken && slot?.revision !== message.revision) return; await slot?.subscriber.acceptSignal(message); } @@ -627,8 +646,12 @@ export class ViewerSfuRoute { acknowledge: boolean, retireUnreferenced = false, ): Promise { + const pendingPeer = this.pendingPeer; + const pendingSfu = this.pending; return this.queueTransition(async () => { - if (this.closed || this.resyncing || !this.route.owns(token, "active")) { + if (this.closed || this.resyncing || !this.route.ownsActive(token) || + (pendingPeer?.activationToken && this.pendingPeer !== pendingPeer) || + (pendingSfu?.activationToken && this.pending !== pendingSfu && this.active !== pendingSfu)) { return; } const assignment = this.route.getActiveAssignment(); @@ -644,12 +667,11 @@ export class ViewerSfuRoute { this.active?.publicationGeneration !== assignedPublicationGeneration ) { await this.retireActive(); - if (!this.route.owns(token, "active")) { + if (!this.route.ownsActive(token)) { return; } } if (assignment.upstream.kind === "sfu") { - this.activateChildren(assignment.childPeerIds, token.revision); const mediaAssignment = this.route.getMediaAssignment(); if ( mediaAssignment?.upstream.kind === "sfu" && @@ -659,7 +681,7 @@ export class ViewerSfuRoute { !this.active.failed && this.pending?.publicationGeneration !== assignment.sfuPublicationGeneration ) { - this.clearPending(); + if (this.pending === pendingSfu) this.clearPending(); this.active.revision = token.revision; this.active.subscriber.updateConfig(this.active); this.commitMedia(token); @@ -669,36 +691,38 @@ export class ViewerSfuRoute { return; } - const pendingPeer = this.pendingPeer; const promoted = - pendingPeer?.revision === token.revision - ? await this.events.activatePeer(assignment, token.revision) + pendingPeer?.activationToken && this.route.ownsActive(pendingPeer.activationToken) + ? await this.events.activatePeer(assignment, pendingPeer.revision) : false; - if (!this.route.owns(token, "active")) { + if (pendingPeer) { + if (this.pendingPeer !== pendingPeer) return; + if (pendingPeer.activationToken) token = pendingPeer.activationToken; + } + if (!this.route.ownsActive(token)) { return; } if (promoted === "waiting") return; - if (pendingPeer?.revision === token.revision && promoted !== true) { + if (pendingPeer?.activationToken && promoted !== true) { // Readiness may reach the server before a candidate's local failure. // Once committed, report against the exact active connection for recovery. this.routeFailed(token.revision, "active", pendingPeer.connectionId); return; } - this.pendingPeer = null; - this.clearPending(); + if (this.pendingPeer === pendingPeer) this.pendingPeer = null; + if (this.pending === pendingSfu) this.clearPending(); if (this.active) { await this.retireActive(); } - if (!this.route.owns(token, "active")) { + if (!this.route.ownsActive(token)) { return; } if (!promoted) { await this.events.activatePeer(assignment); } - if (!this.route.owns(token, "active")) { + if (!this.route.ownsActive(token)) { return; } - this.activateChildren(assignment.childPeerIds, token.revision); this.commitMedia(token); }); } @@ -743,14 +767,13 @@ export class ViewerSfuRoute { ) { if ( acknowledge && - this.route.owns(token, "active") && + this.route.ownsActive(token) && pending === null ) { this.events.send({ type: "refresh-sfu", revision: token.revision }); } return; } - pending.activationToken = token; await this.promotePendingSfu(pending); } @@ -776,10 +799,12 @@ export class ViewerSfuRoute { if (this.paused || !slot.activated) { return false; } - const assignment = this.route.getPlannedAssignment(); - const phase = this.route.getPhase(); + const committed = slot.activationToken && this.route.ownsActive(slot.activationToken); + const assignment = committed ? this.route.getActiveAssignment() : this.route.getPlannedAssignment(); + const phase = committed ? "active" : this.route.getPhase(); + const revision = committed ? this.route.getActiveRevision() : this.route.getRevision(); if ( - this.route.getRevision() !== slot.revision || + revision !== slot.revision || assignment?.upstream.kind !== "sfu" || assignment.sfuPublicationGeneration !== slot.publicationGeneration || phase === null @@ -826,7 +851,7 @@ export class ViewerSfuRoute { !slot.stream || !slot.decodedFrame || !token || - !this.route.owns(token, "active") || + !this.route.ownsActive(token) || assignment?.upstream.kind !== "sfu" ) { return; @@ -959,7 +984,7 @@ export class ViewerSfuRoute { if (revision === null || phase === null) { return; } - if (wasActive) { + if (wasActive || (slot.activationToken && this.route.ownsActive(slot.activationToken))) { const activeRevision = this.route.getActiveRevision(); const activeAssignment = this.route.getActiveAssignment(); if ( diff --git a/src/client/native/client.ts b/src/client/native/client.ts index b60dc07d4..426269c69 100644 --- a/src/client/native/client.ts +++ b/src/client/native/client.ts @@ -60,14 +60,13 @@ export function isLoopbackPage(): boolean { return ["localhost", "127.0.0.1", "[::1]"].includes(window.location.hostname); } -async function ungrantedLocalPermission(): Promise { +async function localPermission(): Promise { // App Local already runs on loopback. Its permission can say "prompt" even // though loopback-to-loopback requests do not need consent. if (isLoopbackPage()) return null; for (const name of ["loopback-network", "local-network-access"]) { try { - const { state } = await navigator.permissions.query({ name: name as PermissionName }); - return state === "granted" ? null : state; + return await navigator.permissions.query({ name: name as PermissionName }); } catch { // Older Chromium uses the combined name; other browsers may expose neither. } @@ -149,21 +148,23 @@ async function discoverNative( { waitForPermission = true, signal }: NativeDiscoveryOptions, ): Promise { if (signal?.aborted) return null; - if (!waitForPermission) { - const permission = await ungrantedLocalPermission(); - if (permission) { - debugEvent("native", "unavailable", { stage: "permission", permission }); - return null; - } + const permission = await localPermission(); + if (!waitForPermission && permission && permission.state !== "granted") { + debugEvent("native", "unavailable", { stage: "permission", permission: permission.state }); + return null; } if (signal?.aborted) return null; const controller = new AbortController(); const abort = () => controller.abort(signal?.reason); signal?.addEventListener("abort", abort, { once: true }); - // The first request may wait for browser permission. One shared deadline - // bounds the scan; a silent port must not hide an App on another port. - const timer = window.setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS); + // Permission waiting is user-owned; the parallel scan has one network deadline. + let timer: number | undefined; + const startDeadline = () => { timer ??= window.setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS); }; + const permissionChanged = () => { if (permission?.state !== "prompt") startDeadline(); }; + const awaitingPermission = permission?.state === "prompt"; try { + if (awaitingPermission) permission.addEventListener("change", permissionChanged); + permissionChanged(); // An explicit launch stays with its App even when another approved App is faster. const selectedPort = clientRuntimePort(); const ports = selectedPort === null ? Array.from({ @@ -175,6 +176,7 @@ async function discoverNative( signal: controller.signal, ...(isLoopbackPage() ? {} : { targetAddressSpace: "loopback" }), } as RequestInit); + startDeadline(); if (!response.ok) throw new Error("Piik App discovery was not accepted"); const body: unknown = await response.json(); const identity = nativeDiscoveryIdentitySchema.safeParse(body); @@ -201,6 +203,7 @@ async function discoverNative( debugEvent("native", "unavailable", { stage: "discovery", timedOut: controller.signal.aborted }); return null; } finally { + if (awaitingPermission) permission.removeEventListener("change", permissionChanged); signal?.removeEventListener("abort", abort); window.clearTimeout(timer); controller.abort(); diff --git a/src/client/native/wire.ts b/src/client/native/wire.ts index d9030d662..2bab3e493 100644 --- a/src/client/native/wire.ts +++ b/src/client/native/wire.ts @@ -27,6 +27,9 @@ export const nativeDiscoveryIdentitySchema = z.object({ export const nativeHealthSchema = nativeDiscoveryIdentitySchema.extend({ protocol: z.literal(NATIVE_CLIENT_PROTOCOL), + version: z.string().optional(), + revision: z.string().optional(), + packageTarget: z.string().optional(), qualityPreference: z.boolean().optional(), activationURL: z.literal("piik://media").optional(), instanceToken: z diff --git a/src/client/pages/AppLauncherPage.tsx b/src/client/pages/AppLauncherPage.tsx index ab7504093..6aa9e560b 100644 --- a/src/client/pages/AppLauncherPage.tsx +++ b/src/client/pages/AppLauncherPage.tsx @@ -13,10 +13,8 @@ import { consoleLanguage } from "../locales"; import { Glyph } from "../ui/icons"; import { currentThemePreference, subscribeTheme } from "../ui/theme"; import { clientLaunchURL, type ClientLaunchPresentation } from "../lib/session"; -import { - checkReleaseUpdate, - type ReleaseUpdateNotice, -} from "../lib/release-update"; +import type { AppReleaseIdentity } from "../lib/release-update"; +import { useReleaseUpdate } from "../lib/use-release-update"; const launcherStateSchema = z.object({ sites: z.array(z.string()), @@ -60,7 +58,8 @@ export function AppLauncherPage() { const [debugError, setDebugError] = useState(false); const [reload, setReload] = useState(0); const [lan, setLan] = useState["lan"]>(); - const [update, setUpdate] = useState(null); + const [build, setBuild] = useState(); + const { update } = useReleaseUpdate(build); const [version, setVersion] = useState(); const [target, setTarget] = useState(); const [controlPort, setControlPort] = useState(); @@ -92,7 +91,6 @@ export function AppLauncherPage() { useEffect(() => { let current = true; let timer: ReturnType | undefined; - let checkedRelease = false; let restoredSettings = false; let reading = false; const readState = () => { @@ -132,16 +130,7 @@ export function AppLauncherPage() { : previous?.kind === "load" ? null : previous); setLoading(false); if (state.starting) timer = setTimeout(() => void readState(), 750); - if (checkedRelease) return; - checkedRelease = true; - void checkReleaseUpdate({ - version: state.version, - revision: state.revision, - }, { packageTarget: state.packageTarget }) - .then((notice) => { - if (current && notice) setUpdate(notice); - }) - .catch(() => undefined); + setBuild({ version: state.version, revision: state.revision, packageTarget: state.packageTarget }); }) .catch(() => { if (!fresh()) return; diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsx index 0fdd3d697..03669f7ac 100644 --- a/src/client/pages/HostPage.tsx +++ b/src/client/pages/HostPage.tsx @@ -861,12 +861,13 @@ export function HostPage({ } return new SfuPublisher(events); }, - reconcileChildren: (childPeerIds) => { + reconcileChildren: (assignment, revision) => { if ( isCurrentGeneration(generation) && hostSfuRouteRef.current === route ) { - reconcileHostChildren(childPeerIds, generation); + activatePreparedHostChild(revision, assignment); + reconcileHostChildren(assignment.childPeerIds, generation); } }, send: (message) => @@ -2571,8 +2572,6 @@ export function HostPage({ } else { discardPreparedHostChild(); } - } else { - activatePreparedHostChild(message.revision, message.assignment); } if ( message.phase === "active" && diff --git a/src/client/pages/StatusPreviewPage.tsx b/src/client/pages/StatusPreviewPage.tsx index 8ad510150..885fcc119 100644 --- a/src/client/pages/StatusPreviewPage.tsx +++ b/src/client/pages/StatusPreviewPage.tsx @@ -7,6 +7,7 @@ import { StatusIndicator } from "../components/living/StatusIndicator"; import { ShareFailureHelp } from "../components/living/ShareFailureHelp"; import { hostFailureChecks } from "./host-page-notices"; import { LoadingStatus } from "../components/living/WaitingStatus"; +import { StartupFailure } from "../components/living/StartupFailure"; import { Pill } from "../components/living/primitives"; import { deriveViewerPresentation } from "../media/viewer-presentation"; import { @@ -44,6 +45,11 @@ function StatusMark({ status }: { status: StatusDescriptor }) { } export function StatusPreviewPage() { + return new URLSearchParams(location.search).has("startup-failure") + ? : ; +} + +function StatusCatalog() { usePreviewAnchor(); const { lang, vis, t, titleFrames } = useCopy(); const [selected, setSelected] = useState("playing"); @@ -203,6 +209,7 @@ export function StatusPreviewPage() {

加载与等待

页面加载与站点检查只显示真实状态。App 启动与媒体等待保留一句次要短句,每 15 秒轮换,隐藏时暂停;连续等待中的状态变化不会重新抽句。

+

{t("startup.failed")}